-
Notifications
You must be signed in to change notification settings - Fork 684
Expand file tree
/
Copy pathautofill.service.ts
More file actions
364 lines (312 loc) · 16.3 KB
/
autofill.service.ts
File metadata and controls
364 lines (312 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
import { DropdownAction, NotificationAction } from 'proton-pass-extension/app/content/constants.runtime';
import { withContext } from 'proton-pass-extension/app/content/context/context';
import type { ContentScriptContextFactoryOptions } from 'proton-pass-extension/app/content/context/factory';
import { autofillCCFields } from 'proton-pass-extension/app/content/services/autofill/autofill.cc';
import type { FrameMessageHandler } from 'proton-pass-extension/app/content/services/client/client.channel';
import type { FieldHandle } from 'proton-pass-extension/app/content/services/form/field';
import type { FormHandle } from 'proton-pass-extension/app/content/services/form/form';
import { sendContentScriptTelemetry } from 'proton-pass-extension/app/content/utils/telemetry';
import { contentScriptMessage, sendMessage } from 'proton-pass-extension/lib/message/send-message';
import type { AutofillRequest, AutofillResult } from 'proton-pass-extension/types/autofill';
import { WorkerMessageType } from 'proton-pass-extension/types/messages';
import { CCFieldType, FieldType } from '@proton/pass/fathom/labels';
import { passwordSave } from '@proton/pass/store/actions/creators/password';
import type { ItemContent } from '@proton/pass/types/data/items';
import { TelemetryEventName } from '@proton/pass/types/data/telemetry';
import type { AsyncCallback, MaybeNull } from '@proton/pass/types/utils/index';
import type { FormCredentials } from '@proton/pass/types/worker/form';
import { first } from '@proton/pass/utils/array/first';
import { truthy } from '@proton/pass/utils/fp/predicates';
import { asyncLock } from '@proton/pass/utils/fp/promises';
import { serialize } from '@proton/pass/utils/object/serialize';
import { uniqueId } from '@proton/pass/utils/string/unique-id';
import { getEpoch } from '@proton/pass/utils/time/epoch';
import { nextTick, onNextTick } from '@proton/pass/utils/time/next-tick';
import { resolveSubdomain } from '@proton/pass/utils/url/utils';
import { omit } from '@proton/shared/lib/helpers/object';
import { autofillIdentityFields } from './autofill.identity';
type AutofillCounters = {
/** Number of autofillable login credentials for the current
* tab's URL. Null if not yet calculated or invalidated */
credentials: MaybeNull<number>;
/** Number of identity items available for autofill */
identities: MaybeNull<number>;
/** Number of CC items available for autofill */
creditCards: MaybeNull<number>;
};
type AutofillState = {
/** Ongoing autofill request potentially across multiple frames.
* This allows trapping interactions during an autofill sequence
* for UX purposes (field switching during autofill) and allowing
* proper refocusing behaviour when sequence finishes. */
processing: boolean;
};
/** Retrieves and caches the count of an autofill's state key.
* Uses a cached value if available, otherwise queries the worker. */
const autofillCounter = (key: keyof AutofillCounters, state: AutofillCounters) =>
asyncLock(
async (): Promise<number> =>
(state[key] =
state[key] ??
(await sendMessage.on(
contentScriptMessage({
type: (
{
credentials: WorkerMessageType.AUTOFILL_LOGIN_QUERY,
identities: WorkerMessageType.AUTOFILL_IDENTITY_QUERY,
creditCards: WorkerMessageType.AUTOFILL_CC_QUERY,
} as const
)[key],
payload: {},
}),
(res) => (res.type === 'success' ? res.items.length : 0)
)))
);
/** Duration in milliseconds to lock field interactivity after autofill completion.
* Safari requires 250ms (vs 50ms default) to accommodate websites that apply custom
* focus management patches specifically for Safari (e.g., Adyen payment provider),
* preventing race conditions where focus-to-next-field logic interferes with autofill. */
const AUTOFILL_LOCK_TIME = BUILD_TARGET === 'safari' ? 250 : 50;
export const createAutofillService = ({ controller }: ContentScriptContextFactoryOptions) => {
const state: AutofillState = { processing: false };
const counters: AutofillCounters = {
credentials: null,
identities: null,
creditCards: null,
};
const getCredentialsCount = autofillCounter('credentials', counters);
const getIdentitiesCount = autofillCounter('identities', counters);
const getCreditCardsCount = autofillCounter('creditCards', counters);
/** Synchronizes login form fields with current credential count.
* Resets credential and identity counts if forced or user logged out */
const sync = withContext<(options?: { forceSync: boolean }) => Promise<void>>(async (ctx, options) => {
if (!ctx) return;
const authorized = ctx.getState().authorized;
if (options?.forceSync || !authorized) {
counters.credentials = null;
counters.identities = null;
counters.creditCards = null;
}
let logins = false;
let identities = false;
let ccs = false;
const fields = ctx.service.formManager.getFields();
for (const field of fields) {
if (field.action?.type === DropdownAction.AUTOFILL_LOGIN) logins = true;
if (field.action?.type === DropdownAction.AUTOFILL_IDENTITY) identities = true;
if (field.action?.type === DropdownAction.AUTOFILL_CC) ccs = true;
}
if (authorized) {
if (logins) await getCredentialsCount();
if (identities) await getIdentitiesCount();
if (ccs) await getCreditCardsCount();
}
fields.forEach((field) => field.icon?.sync());
});
/** Locks field interactivity during autofill to prevent "focus-to-next"
* interference. Fields unlock themselves before filling (see field.ts). */
const autofillSequence = <T extends AsyncCallback>(fn: T) =>
withContext<(...args: Parameters<T>) => Promise<ReturnType<T>>>(async (ctx, ...args) => {
const formManager = ctx?.service.formManager;
const fields = formManager?.getFields();
fields?.forEach((field) => field.interactivity.lock());
state.processing = true;
const res = await fn(...args);
return new Promise(
onNextTick((resolve) => {
state.processing = false;
fields?.forEach((field) => field.interactivity.unlock());
resolve(res);
})
);
}) as T;
const autofillLogin = autofillSequence(async (form: FormHandle, data: FormCredentials) => {
await first(form.getFieldsFor(FieldType.USERNAME) ?? [])?.autofill(data.userIdentifier);
await first(form.getFieldsFor(FieldType.EMAIL) ?? [])?.autofill(data.userIdentifier);
for (const field of form.getFieldsFor(FieldType.PASSWORD_CURRENT)) await field.autofill(data.password);
sendContentScriptTelemetry(TelemetryEventName.AutofillTriggered, {}, { location: 'source' });
});
const autofillPassword = autofillSequence(
withContext<(form: FormHandle, password: string) => Promise<void>>(async (ctx, form, password) => {
const url = ctx?.getExtensionContext()?.url;
if (url) {
for (const field of form.getFieldsFor(FieldType.PASSWORD_NEW)) await field.autofill(password);
void sendMessage(
contentScriptMessage({
type: WorkerMessageType.STORE_DISPATCH,
payload: {
action: serialize(
passwordSave({
id: uniqueId(),
value: password,
origin: resolveSubdomain(url),
createTime: getEpoch(),
})
),
},
})
);
}
})
);
const autofillEmail = autofillSequence((field: FieldHandle, data: string) => field.autofill(data));
/** Autofills OTP fields in a form. Uses paste method for multiple fields,
* individual autofill for single field. Includes fallback logic for paste
* failures in multi-field scenarios. */
const autofillOTP = autofillSequence(async (form: FormHandle, code: string) => {
const fields = form.getFieldsFor(FieldType.OTP);
if (fields.length === 0) return;
if (fields.length === 1) await fields[0].autofill(code, { paste: false });
if (fields.length > 1) {
/* for FF : sanity check in case the paste failed */
await fields[0].autofill(code, { paste: true });
/** Map individual field handles to the corresponding char */
const otpFields = fields.map((field, idx) => [field, code?.[idx] ?? ''] as const);
for (const [field, value] of otpFields) {
if (!field.element.value || field.element.value !== value) {
await field.autofill(value ?? '');
}
}
}
sendContentScriptTelemetry(TelemetryEventName.TwoFAAutofill, {}, {});
});
/** Clears previously autofilled identity fields when called with a new identity item */
const autofillIdentity = autofillSequence(async (selectedField: FieldHandle, data: ItemContent<'identity'>) => {
const fields = selectedField.getFormHandle().getFields();
for (const field of fields) {
if (
field.autofilled &&
field.fieldType === FieldType.IDENTITY &&
field.sectionIndex === selectedField.sectionIndex
) {
/** If an identity field in the same section was
* previously autofilled, clear the previous value. */
await field.autofill('');
field.autofilled = null;
field.autofilledItemKey = null;
}
}
await autofillIdentityFields(fields, selectedField, data);
});
/** Checks for OTP fields in tracked forms and prompts for autofill if eligible.
* Queries the service worker for matching items and opens an `AutofillOTP`
* notification if appropriate. Returns true if a prompt was shown, false otherwise. */
const evaluateOTP = withContext<(forms: FormHandle[]) => Promise<boolean>>(async (ctx, forms) => {
const enabled = Boolean(ctx?.getFeatures().Autofill2FA);
const hasOTP = enabled && forms.some((form) => form.otp);
return (
hasOTP &&
sendMessage.on(contentScriptMessage({ type: WorkerMessageType.AUTOFILL_OTP_CHECK }), (res) => {
if (res.type === 'success' && res.shouldPrompt) {
ctx?.service.inline.notification.open({
action: NotificationAction.OTP,
item: omit(res, ['type', 'shouldPrompt']),
});
return true;
}
return false;
})
);
});
const executeAutofill = withContext<(payload: AutofillRequest<'fill'>) => Promise<AutofillResult>>(
(ctx, payload) => {
switch (payload.type) {
case 'creditCard':
/** `formIds` are resolved via service worker's clustering phase.
* Origin validation is enforced service-worker side. */
const ccFields = payload.fields.map((field) =>
ctx?.service.formManager
.getFormById(field.formId)
?.getFieldById<FieldType.CREDIT_CARD>(field.fieldId)
);
return autofillCCFields(ccFields.filter(truthy), payload)
.then((autofilled) => ({ type: 'creditCard' as const, autofilled: autofilled.flat() }))
.catch(() => ({ type: 'creditCard' as const, autofilled: [] }));
}
}
);
/** Cross-frame autofill orchestration with interactivity management :
* 1. 'start': Lock all fields to prevent focus stealing during async fill operations
* 2. 'fill': Execute autofill (async, may span multiple frames)
* 3. 'completed': Unlock target field for user interaction, re-lock others briefly */
const onAutofillRequest: FrameMessageHandler<WorkerMessageType.AUTOFILL_SEQUENCE> = withContext(
(ctx, { payload }, sendResponse) => {
const formManager = ctx?.service.formManager;
const fields = formManager?.getFields();
switch (payload.status) {
case 'start':
/** cross-frame autofill sequence starting:
* lock all tracked fields temporarily. */
fields?.forEach((field) => field.interactivity.lock());
state.processing = true;
break;
case 'fill':
/** fill step: each field will unlock itself
* as part of its autofill call */
void executeAutofill(payload).then(sendResponse);
return true;
case 'completed':
const { formId, fieldId } = payload.refocus;
const refocusable = formManager?.getFormById(formId)?.getFieldById(fieldId);
/** Re-lock tracked fields to prevent race conditions where cross-frame
* "focus next field" requests arrive after autofill completes (common on
* payment forms with address/card fields across iframes). */
fields?.forEach((field) => field.interactivity.lock(AUTOFILL_LOCK_TIME));
refocusable?.interactivity.unlock();
refocusable?.focus({ preventAction: true });
nextTick(() => {
state.processing = false;
if (refocusable) {
const { fieldSubType } = refocusable;
if (fieldSubType === CCFieldType.NUMBER || fieldSubType === CCFieldType.CSC) {
/** Some payment forms (e.g., Verizon) clear field values on focus.
* If the refocused field is a card number or CSC, verify it wasn't
* cleared and re-autofill without acquiring focus if necessary. */
const { value, element, autofilled } = refocusable;
const wasResetOnRefocus = autofilled && !element.value && value;
if (wasResetOnRefocus) void refocusable.autofill(value, { noFocus: true });
}
}
});
break;
}
}
);
const onAutofillTrigger = withContext((ctx) => {
const fields = ctx?.service.formManager.getFields();
const loginField = fields?.find(
(field) => field.action?.type === DropdownAction.AUTOFILL_LOGIN
);
if (loginField) {
ctx?.service.inline.dropdown.toggle({
type: 'field',
action: DropdownAction.AUTOFILL_LOGIN,
autofocused: false,
autofilled: loginField.autofilled !== null,
field: loginField,
});
}
});
controller.channel.register(WorkerMessageType.AUTOFILL_SEQUENCE, onAutofillRequest);
controller.channel.register(WorkerMessageType.AUTOFILL_TRIGGER, onAutofillTrigger);
return {
get processing() {
return state.processing;
},
autofillEmail,
autofillIdentity,
autofillLogin,
autofillOTP,
autofillPassword,
evaluateOTP,
getCredentialsCount,
getCreditCardsCount,
getIdentitiesCount,
sync,
destroy: () => {
controller.channel.unregister(WorkerMessageType.AUTOFILL_SEQUENCE, onAutofillRequest);
controller.channel.unregister(WorkerMessageType.AUTOFILL_TRIGGER, onAutofillTrigger);
},
};
};
export type AutofillService = ReturnType<typeof createAutofillService>;