@le-space/orbitdb-identity-provider-webauthn-did 0.12.1 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,71 @@
1
1
  # Changes
2
2
 
3
+ ## 0.13.0
4
+
5
+ An application can now say, before each passkey prompt, what it is for — and `./elements` brings a
6
+ dialog that does it.
7
+
8
+ ### Added
9
+
10
+ - **Before each passkey prompt, a word on what it is for.** Creating a passkey-backed identity asks
11
+ the authenticator three times in a row, and restoring one does too. Without a word in between
12
+ that looks like a loop, and people cancel it. Le-Space/belege put a dialog between its prompts
13
+ (#429), but only this package knows when it is about to ask and why. Every WebAuthn call here now
14
+ first awaits `beforePasskeyCeremony(purpose)`. An application registers a handler with
15
+ `setPasskeyStepHandler` and numbers an action's prompts with `withPasskeySteps(of, run)`. Every
16
+ prompt after the first is then announced, with its purpose, and starts from the click that
17
+ answers it. A cancel (`PasskeyStepCancelled`) stops before the authenticator is asked and reaches
18
+ the caller unchanged, also through `sign()` and the signing key's PRF read, which turn other
19
+ failures into errors or fallbacks of their own. Without a handler, or outside a plan, nothing
20
+ changes. Exported from the root and from `./standalone`.
21
+ - **`./elements` with `<passkey-step-dialog>`:** that handler without a framework, after belege's
22
+ `PasskeyStepDialog.svelte`. It shows "Passkey prompt n of m", a title and a reason per purpose,
23
+ and **Continue** / **Cancel**. Its wording is in English and German and can be replaced per
24
+ language; its colours come from custom properties. `connectPasskeyStepDialog(element)` makes it
25
+ the handler. Le-Space/simple-todo's escrow01 is the first application to use it.
26
+
27
+ Tested in `tests/passkey-steps.test.js` (Node, through `createCredential`, the signing key's PRF
28
+ read, `sign()` and the restore against the mock authenticator) and
29
+ `tests/passkey-step-dialog.test.js` (Chromium, with its own `playwright.elements.config.js`, run in
30
+ CI once the browsers are installed).
31
+
32
+ ### Repository
33
+
34
+ - **No `@libp2p/crypto` below 5.1.22 in this repository's own install** (#102). Up to 5.1.21 it is
35
+ affected by GHSA-rvfr-cqwq-rc4j: its ASN.1 DER decoder can be driven into a long synchronous
36
+ loop by a remote peer before authentication. The override applies to this repository's lockfile
37
+ only. The package's own range, `^5.1.20`, already admits 5.1.22, so an application resolving it
38
+ fresh gets the fixed version; one with an older lockfile should update it.
39
+
40
+ ## 0.12.2
41
+
42
+ A request that names a passkey asks that passkey. Until now this entry stood under 0.12.1, but
43
+ 0.12.1 was tagged before it merged and does not have it.
44
+
45
+ ### Fixed
46
+
47
+ - **A PRF output came from whichever passkey answered.** With discoverable credentials on (the
48
+ default), `buildCredentialRequestOptions` dropped the credential id it was given, so the browser
49
+ let any passkey of the relying party answer: two passkeys of one site in one keychain, or two
50
+ security keys plugged in. Every request that names a credential now carries it in
51
+ `allowCredentials`; discoverable credentials decide only what a request without one does.
52
+ `readPrfOutput` also checks which credential answered and refuses another one
53
+ (`WebAuthnAuthenticationError`), and the provider's own read for the signing key derives nothing
54
+ from it. Found in simple-todo's invoice01: a second passkey's vault slot was sealed under the
55
+ first one's PRF output, and the second passkey could not open it. Le-Space/belege has asked with
56
+ `discoverableCredentials: false` since its #429 for this reason. simple-todo's archived01 asked
57
+ through `readPrfOutput` without it, and is fixed by updating to 0.12.2.
58
+ - **`extractPrfSeedFromCredential` named the credential all along, by accident.** From 0.2.8 on it
59
+ passes `discoverableCredentials` on from its own options, and a key that is there but `undefined`
60
+ counted as off; only a caller passing `true` was affected. It still does not check which
61
+ credential answered: `readPrfOutput` does. Le-Space/invoice reads through it, so its requests
62
+ named the passkey; it took any answer, and now reads through `readPrfOutput`
63
+ (Le-Space/invoice#64). This entry first counted Le-Space/invoice among the applications that
64
+ asked without a credential.
65
+
66
+ Tested in `tests/prf-keys.test.js` with discoverable credentials on: a request names the credential
67
+ it asks, and another credential's answer is refused.
68
+
3
69
  ## 0.12.1
4
70
 
5
71
  A peer loads another peer's varsig identity from IPFS again, with Helia 7.
package/README.md CHANGED
@@ -74,9 +74,14 @@ Behavior:
74
74
 
75
75
  - `discoverableCredentials: true`
76
76
  - registration requests resident/discoverable credentials
77
- - assertion requests omit `allowCredentials`
77
+ - an assertion that names no credential omits `allowCredentials`, and the
78
+ browser offers the passkeys it has
78
79
  - `discoverableCredentials: false`
79
- - assertion requests target a specific credential ID via `allowCredentials`
80
+ - every assertion names its credential
81
+ - Either way, an assertion that names a credential asks that one, in
82
+ `allowCredentials` (since 0.12.2). Before, discoverable mode dropped the
83
+ name, and another passkey of the site could answer — with its own PRF
84
+ output, which looks as random as the right one.
80
85
 
81
86
  ## Memory Keystore Quick Start
82
87
 
@@ -135,6 +140,38 @@ Two ways past that, and the first keeps nothing:
135
140
  1. `restoreIdentityFromAuthenticator()` — two discoverable assertions, from which `recoverPublicKey()` returns the credential's public key and with it the DID (0.6.0)
136
141
  2. metadata written at registration — `largeBlob` where it comes back, otherwise browser storage — which the demos still do, because a stored copy spares both touches
137
142
 
143
+ ### Saying what each passkey prompt is for
144
+
145
+ Creating a passkey-backed identity asks the authenticator three times in a row, and restoring one does too. Without a word in between, that looks like a loop. Every WebAuthn call in this package first awaits a step hook, so an application can show what the next prompt is for and start it from a click:
146
+
147
+ ```js
148
+ import {
149
+ WebAuthnDIDProvider,
150
+ OrbitDBWebAuthnIdentityProviderFunction,
151
+ withPasskeySteps,
152
+ } from '@le-space/orbitdb-identity-provider-webauthn-did';
153
+ import { connectPasskeyStepDialog } from '@le-space/orbitdb-identity-provider-webauthn-did/elements';
154
+
155
+ // <passkey-step-dialog></passkey-step-dialog> somewhere in the page
156
+ connectPasskeyStepDialog(document.querySelector('passkey-step-dialog'));
157
+
158
+ const identity = await withPasskeySteps(3, async () => {
159
+ // 1 of 3: the passkey, from the click that started this
160
+ const credential = await WebAuthnDIDProvider.createCredential({
161
+ userId,
162
+ displayName,
163
+ });
164
+ // 2 and 3 of 3, each announced: the signing key's PRF output, the identity signature
165
+ return identities.createIdentity({
166
+ provider: OrbitDBWebAuthnIdentityProviderFunction({
167
+ webauthnCredential: credential,
168
+ }),
169
+ });
170
+ });
171
+ ```
172
+
173
+ Between two prompts, `<passkey-step-dialog>` shows "Passkey prompt 2 of 3", what the prompt is for and why, then **Continue**, which starts it, or **Cancel**, which rejects with `PasskeyStepCancelled` before the authenticator is asked. It has no framework, its wording is built in for English and German and can be replaced per language, and it takes its colours from custom properties. Without a handler, or outside `withPasskeySteps`, nothing changes. See [Passkey Steps](docs/API.md#passkey-steps).
174
+
138
175
  ### Hardware-Secured Varsig Quick Start
139
176
 
140
177
  ```javascript
package/docs/API.md CHANGED
@@ -263,6 +263,51 @@ used in [the recovery example](https://github.com/NiKrause/orbitdb-storage-bridg
263
263
  the database half of the same problem is in
264
264
  [orbitdb-storage-bridge](https://github.com/NiKrause/orbitdb-storage-bridge/blob/main/docs/RECOVERY-ON-A-SECOND-DEVICE.md).
265
265
 
266
+ ### Passkey Steps
267
+
268
+ Before each passkey prompt, a word on what it is for, when an application asks for one. Every WebAuthn call in this package first awaits `beforePasskeyCeremony(purpose)`. Inside a plan, every prompt after the first goes to the registered handler. The first prompt comes from the click that started the action, so it is not announced. The handler resolves to let the prompt start (from its click, which Safari wants for each WebAuthn call) or throws to stop it.
269
+
270
+ ```js
271
+ import {
272
+ setPasskeyStepHandler,
273
+ withPasskeySteps,
274
+ PasskeyStepCancelled,
275
+ } from '@le-space/orbitdb-identity-provider-webauthn-did';
276
+
277
+ const stop = setPasskeyStepHandler(async ({ purpose, n, of, kind }) => {
278
+ // show "prompt n of of", what `purpose` is for; resolve on Continue,
279
+ // throw new PasskeyStepCancelled() on Cancel
280
+ });
281
+ await withPasskeySteps(3, () => createPasskeyAndIdentity());
282
+ ```
283
+
284
+ #### `setPasskeyStepHandler(handler | null)`
285
+
286
+ Registers what runs before each announced prompt and returns a function that unregisters it, if it is still the one. A handler sees `{ purpose, n, of, kind }`: `of` is `null` when the plan gave no count, and `kind` is `'create'` or `'get'`.
287
+
288
+ #### `withPasskeySteps(of | { of, askFirst }, run)`
289
+
290
+ Runs `run` with its prompts numbered. `of` is how many the action takes, as the application counts them: a number that is too small makes the dialog say "4 of 3" and does nothing worse. `askFirst` announces the first prompt too, for an action that does not start from a click of its own. Plans do not nest: an inner plan numbers its own prompts and the outer one resumes afterwards.
291
+
292
+ #### `beforePasskeyCeremony(purpose, kind = 'get')`
293
+
294
+ What the package calls before each WebAuthn call. An application calls it around its own calls, so they are counted in the same plan. Call it outside any `try` that turns a failed ceremony into a fallback: a cancel has to reach the action, not be read as "this authenticator cannot".
295
+
296
+ #### `PASSKEY_PURPOSES`, `PasskeyStepCancelled`
297
+
298
+ The purposes are `create`, `signing-key` (the PRF output the signing key comes from), `identity` (the identity signature), `restore` and `restore-confirm` (the two touches of `restoreIdentityFromAuthenticator`), `keystore` (sealing or opening the keystore's key), `prf` (`readPrfOutput`, `extractPrfSeedFromCredential`), `metadata` (largeBlob metadata), `wallet` (the P-256 wallet's signatures) and `sign-entry` (varsig). `PasskeyStepCancelled` is what a cancel throws. It reaches the caller as it is, also through `sign()`, which wraps WebAuthn errors in its own.
299
+
300
+ #### `./elements`: `<passkey-step-dialog>`
301
+
302
+ ```js
303
+ import { connectPasskeyStepDialog } from '@le-space/orbitdb-identity-provider-webauthn-did/elements';
304
+ const dialog = document.querySelector('passkey-step-dialog');
305
+ connectPasskeyStepDialog(dialog); // returns a function that disconnects it
306
+ dialog.strings = { de: { purposes: { prf: { title: '…', why: '…' } } } }; // optional
307
+ ```
308
+
309
+ A framework-free handler: "Passkey prompt n of m", a title and a reason per purpose, a line that this is not a loop, **Continue** (focused) and **Cancel**. Escape counts as Cancel. The language is the element's `lang`, then the document's. English and German are built in (`PASSKEY_STEP_STRINGS`), and `strings` replaces any of them per language or adds a language. Its colours come from `--passkey-step-background`, `-color`, `-muted`, `-border`, `-accent`, `-on-accent`, `-radius` and `-backdrop`; the defaults follow `prefers-color-scheme`. `element.ask(step)` is the handler itself, for an application that wants to call it directly.
310
+
266
311
  ### PRF Keys and Vaults
267
312
 
268
313
  Since 0.9.0. Applications that keep data under keys from the passkey used to
@@ -283,9 +328,14 @@ bytes that never come back.
283
328
  - `prfInput` — overrides the credential's. Leave it out when the output also
284
329
  goes to the identity provider, which asks with the credential's.
285
330
 
331
+ It asks this credential only (`allowCredentials`), and checks that this
332
+ credential answered: another passkey of the same site would answer with its own
333
+ PRF output, and every key derived from it would quietly be the wrong one.
334
+
286
335
  Throws `PrfUnavailableError` when the authenticator answers without a PRF
287
- output. A refused prompt stays the browser's `NotAllowedError`, so "the user
288
- said no" and "this authenticator has no PRF" can be told apart.
336
+ output, and `WebAuthnAuthenticationError` when another credential answers. A
337
+ refused prompt stays the browser's `NotAllowedError`, so "the user said no" and
338
+ "this authenticator has no PRF" can be told apart.
289
339
 
290
340
  #### `deriveSubkey(prfOutput, info, { length = 32 })`
291
341
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@le-space/orbitdb-identity-provider-webauthn-did",
3
- "version": "0.12.1",
3
+ "version": "0.13.0",
4
4
  "description": "WebAuthn-based DID identity provider for OrbitDB for hardware-secured wallets and biometric Passkey authentication",
5
5
  "main": "src/index.js",
6
6
  "types": "types/index.d.ts",
@@ -25,6 +25,10 @@
25
25
  "./vault": {
26
26
  "types": "./types/vault.d.ts",
27
27
  "import": "./src/vault/index.js"
28
+ },
29
+ "./elements": {
30
+ "types": "./types/elements.d.ts",
31
+ "import": "./src/elements/index.js"
28
32
  }
29
33
  },
30
34
  "scripts": {
@@ -151,7 +155,8 @@
151
155
  "iso-web": "^3.1.2",
152
156
  "iso-webauthn-varsig": "npm:@le-space/iso-webauthn-varsig@^0.3.0",
153
157
  "conf>ajv": "^8.18.0",
154
- "ajv>fast-uri": "^3.1.9"
158
+ "ajv>fast-uri": "^3.1.9",
159
+ "@libp2p/crypto@<5.1.22": "5.1.22"
155
160
  },
156
161
  "onlyBuiltDependencies": [
157
162
  "@ipshipyard/node-datachannel",
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Custom elements, for an application whatever its framework.
3
+ *
4
+ * `<passkey-step-dialog>` says, between two passkey prompts, what the next one
5
+ * is for. {@link connectPasskeyStepDialog} makes an element on the page the
6
+ * handler for every prompt this package announces.
7
+ */
8
+ import { setPasskeyStepHandler } from '../passkey-steps.js';
9
+ import {
10
+ PasskeyStepDialogElement,
11
+ PASSKEY_STEP_STRINGS,
12
+ } from './passkey-step-dialog.js';
13
+
14
+ if (
15
+ globalThis.customElements &&
16
+ !globalThis.customElements.get('passkey-step-dialog')
17
+ ) {
18
+ globalThis.customElements.define(
19
+ 'passkey-step-dialog',
20
+ PasskeyStepDialogElement
21
+ );
22
+ }
23
+
24
+ /**
25
+ * Let this element answer every announced passkey prompt.
26
+ *
27
+ * @param {PasskeyStepDialogElement} element
28
+ * @returns {() => void} disconnects it again (if it is still the handler)
29
+ */
30
+ export function connectPasskeyStepDialog(element) {
31
+ return setPasskeyStepHandler((step) => element.ask(step));
32
+ }
33
+
34
+ export { PasskeyStepDialogElement, PASSKEY_STEP_STRINGS };
35
+ export {
36
+ setPasskeyStepHandler,
37
+ withPasskeySteps,
38
+ PasskeyStepCancelled,
39
+ PASSKEY_PURPOSES,
40
+ } from '../passkey-steps.js';
@@ -0,0 +1,332 @@
1
+ /**
2
+ * `<passkey-step-dialog>`: between two passkey prompts, what the next one is
3
+ * for, and "Continue" to start it.
4
+ *
5
+ * A handler for {@link setPasskeyStepHandler} that needs no framework. It was
6
+ * Le-Space/belege's `PasskeyStepDialog.svelte` (#429) first; this is the same
7
+ * dialog for every application that uses this package.
8
+ *
9
+ * ```html
10
+ * <passkey-step-dialog></passkey-step-dialog>
11
+ * <script type="module">
12
+ * import { connectPasskeyStepDialog } from '@le-space/orbitdb-identity-provider-webauthn-did/elements'
13
+ * connectPasskeyStepDialog(document.querySelector('passkey-step-dialog'))
14
+ * </script>
15
+ * ```
16
+ *
17
+ * The language follows the element's `lang`, then the document's; German and
18
+ * English are built in. `strings` replaces any of them, per language — an
19
+ * application's own words for a purpose, or a language of its own.
20
+ *
21
+ * Its colours come from custom properties, so it sits in an application's
22
+ * theme instead of next to it: `--passkey-step-background`, `-color`,
23
+ * `-muted`, `-border`, `-accent`, `-on-accent`, `-radius`, `-backdrop`.
24
+ */
25
+ import { PasskeyStepCancelled } from '../passkey-steps.js';
26
+
27
+ /**
28
+ * @typedef {{ title: string, why: string }} PurposeText
29
+ * @typedef {{ count: string, countOpen: string, notALoop: string,
30
+ * continue: string, cancel: string,
31
+ * purposes: Record<string, PurposeText> }} PasskeyStepStrings
32
+ */
33
+
34
+ /** @type {Record<'en' | 'de', PasskeyStepStrings>} */
35
+ export const PASSKEY_STEP_STRINGS = {
36
+ en: {
37
+ count: 'Passkey prompt {n} of {of}',
38
+ countOpen: 'Passkey prompt {n}',
39
+ notALoop:
40
+ 'Each prompt has its own purpose; it is not a repeat. With a security key: touch it and, if asked, enter its PIN.',
41
+ continue: 'Continue',
42
+ cancel: 'Cancel',
43
+ purposes: {
44
+ create: {
45
+ title: 'Now create your passkey',
46
+ why: 'Your device creates a passkey for this app, with Touch ID or your PIN for example.',
47
+ },
48
+ 'signing-key': {
49
+ title: 'Now the key that signs your entries',
50
+ why: 'Your passkey gives the app a secret. The key that signs what you write comes from it, so the same passkey signs as you on every device.',
51
+ },
52
+ identity: {
53
+ title: 'Now confirm your identity',
54
+ why: 'The passkey signs your identity, so other devices can check that your entries come from you.',
55
+ },
56
+ restore: {
57
+ title: 'Now find your passkey',
58
+ why: 'This device has nothing stored for it. Your device or password manager offers the passkey, and the app recovers your identity from its answer.',
59
+ },
60
+ 'restore-confirm': {
61
+ title: 'Once more, the same passkey',
62
+ why: 'A passkey’s public key is recovered from two signatures. The second one confirms which key is yours.',
63
+ },
64
+ keystore: {
65
+ title: 'Now your sealed keys',
66
+ why: 'The keys this app keeps on this device are sealed with your passkey: it seals them, or opens them for this visit.',
67
+ },
68
+ prf: {
69
+ title: 'Now the key for your data',
70
+ why: 'Your passkey gives the app a secret, and the key for your data comes from it.',
71
+ },
72
+ metadata: {
73
+ title: 'Now the details your passkey carries',
74
+ why: 'The passkey keeps a few details for this app, so another device can find your identity.',
75
+ },
76
+ wallet: {
77
+ title: 'Now confirm with your passkey',
78
+ why: 'The passkey signs a request for your account. Without it, nothing is moved.',
79
+ },
80
+ 'sign-entry': {
81
+ title: 'Now sign this entry',
82
+ why: 'Here the passkey signs each entry itself.',
83
+ },
84
+ },
85
+ },
86
+ de: {
87
+ count: 'Passkey-Abfrage {n} von {of}',
88
+ countOpen: 'Passkey-Abfrage {n}',
89
+ notALoop:
90
+ 'Jede Abfrage hat ihren eigenen Zweck, es ist keine Wiederholung. Mit einem Sicherheitsschlüssel: berühren und, falls gefragt, die PIN eingeben.',
91
+ continue: 'Weiter',
92
+ cancel: 'Abbrechen',
93
+ purposes: {
94
+ create: {
95
+ title: 'Jetzt Ihren Passkey anlegen',
96
+ why: 'Ihr Gerät legt einen Passkey für diese App an, zum Beispiel mit Touch ID oder Ihrer PIN.',
97
+ },
98
+ 'signing-key': {
99
+ title: 'Jetzt der Schlüssel, der Ihre Einträge unterschreibt',
100
+ why: 'Ihr Passkey gibt der App ein Geheimnis. Daraus entsteht der Schlüssel, der unterschreibt, was Sie schreiben – so unterschreibt derselbe Passkey auf jedem Gerät als Sie.',
101
+ },
102
+ identity: {
103
+ title: 'Jetzt Ihre Identität bestätigen',
104
+ why: 'Der Passkey unterschreibt Ihre Identität. So können andere Geräte prüfen, dass Ihre Einträge von Ihnen stammen.',
105
+ },
106
+ restore: {
107
+ title: 'Jetzt Ihren Passkey finden',
108
+ why: 'Auf diesem Gerät ist dafür nichts gespeichert. Ihr Gerät oder Passwortmanager bietet den Passkey an, und aus seiner Antwort stellt die App Ihre Identität wieder her.',
109
+ },
110
+ 'restore-confirm': {
111
+ title: 'Noch einmal derselbe Passkey',
112
+ why: 'Der öffentliche Schlüssel eines Passkeys ergibt sich aus zwei Unterschriften. Die zweite bestätigt, welcher Schlüssel Ihrer ist.',
113
+ },
114
+ keystore: {
115
+ title: 'Jetzt Ihre versiegelten Schlüssel',
116
+ why: 'Die Schlüssel, die diese App auf diesem Gerät aufbewahrt, sind mit Ihrem Passkey versiegelt: Er versiegelt sie oder öffnet sie für diesen Besuch.',
117
+ },
118
+ prf: {
119
+ title: 'Jetzt der Schlüssel für Ihre Daten',
120
+ why: 'Ihr Passkey gibt der App ein Geheimnis, und daraus entsteht der Schlüssel für Ihre Daten.',
121
+ },
122
+ metadata: {
123
+ title: 'Jetzt die Angaben, die Ihr Passkey mitführt',
124
+ why: 'Der Passkey bewahrt ein paar Angaben für diese App auf, damit ein anderes Gerät Ihre Identität findet.',
125
+ },
126
+ wallet: {
127
+ title: 'Jetzt mit dem Passkey bestätigen',
128
+ why: 'Der Passkey unterschreibt eine Anfrage für Ihr Konto. Ohne ihn wird nichts bewegt.',
129
+ },
130
+ 'sign-entry': {
131
+ title: 'Jetzt diesen Eintrag unterschreiben',
132
+ why: 'Hier unterschreibt der Passkey jeden Eintrag selbst.',
133
+ },
134
+ },
135
+ },
136
+ };
137
+
138
+ const STYLE = `
139
+ :host {
140
+ --_bg: var(--passkey-step-background, #ffffff);
141
+ --_fg: var(--passkey-step-color, #1b2230);
142
+ --_muted: var(--passkey-step-muted, #5b6577);
143
+ --_border: var(--passkey-step-border, #d6dce6);
144
+ --_accent: var(--passkey-step-accent, #cf3f30);
145
+ --_on-accent: var(--passkey-step-on-accent, #ffffff);
146
+ --_radius: var(--passkey-step-radius, 14px);
147
+ }
148
+ @media (prefers-color-scheme: dark) {
149
+ :host {
150
+ --_bg: var(--passkey-step-background, #12161f);
151
+ --_fg: var(--passkey-step-color, #e8ecf3);
152
+ --_muted: var(--passkey-step-muted, #97a1b3);
153
+ --_border: var(--passkey-step-border, rgba(255, 255, 255, 0.14));
154
+ }
155
+ }
156
+ dialog {
157
+ box-sizing: border-box;
158
+ width: calc(100vw - 2rem);
159
+ max-width: 28rem;
160
+ max-height: calc(100dvh - 2rem);
161
+ overflow: auto;
162
+ margin: auto;
163
+ padding: 1.25rem;
164
+ border: 1px solid var(--_border);
165
+ border-radius: var(--_radius);
166
+ background: var(--_bg);
167
+ color: var(--_fg);
168
+ font: inherit;
169
+ }
170
+ dialog::backdrop { background: var(--passkey-step-backdrop, rgba(0, 0, 0, 0.55)); }
171
+ .count {
172
+ margin: 0; font-size: 0.75rem; font-weight: 600;
173
+ letter-spacing: 0.04em; text-transform: uppercase; color: var(--_muted);
174
+ }
175
+ h2 { margin: 0.25rem 0 0; font-size: 1.125rem; line-height: 1.35; }
176
+ p.why { margin: 0.5rem 0 0; line-height: 1.5; font-size: 0.95rem; }
177
+ p.loop { margin: 0.5rem 0 0; line-height: 1.5; font-size: 0.875rem; color: var(--_muted); }
178
+ .actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 0.5rem; margin-top: 1rem; }
179
+ button {
180
+ min-height: 2.75rem; padding: 0 1rem; border-radius: 0.375rem;
181
+ font: inherit; font-size: 0.9rem; cursor: pointer;
182
+ }
183
+ button[part="cancel"] { background: transparent; color: var(--_fg); border: 1px solid var(--_border); }
184
+ button[part="continue"] { background: var(--_accent); color: var(--_on-accent); border: 1px solid transparent; font-weight: 600; }
185
+ button:focus-visible { outline: 2px solid var(--_accent); outline-offset: 2px; }
186
+ `;
187
+
188
+ /**
189
+ * @param {string} template
190
+ * @param {Record<string, string | number>} values
191
+ */
192
+ const fill = (template, values) =>
193
+ template.replace(/\{(\w+)\}/g, (whole, key) =>
194
+ key in values ? String(values[key]) : whole
195
+ );
196
+
197
+ export class PasskeyStepDialogElement extends HTMLElement {
198
+ /** @type {Partial<Record<string, Partial<PasskeyStepStrings>>>} */
199
+ #overrides = {};
200
+ /** @type {{ resolve: () => void, reject: (error: Error) => void } | null} */
201
+ #pending = null;
202
+
203
+ constructor() {
204
+ super();
205
+ const root = this.attachShadow({ mode: 'open' });
206
+ root.innerHTML = `<style>${STYLE}</style>
207
+ <dialog part="dialog" aria-labelledby="title" aria-describedby="why">
208
+ <p class="count" part="count"></p>
209
+ <h2 id="title" part="title"></h2>
210
+ <p id="why" class="why" part="why"></p>
211
+ <p class="loop" part="loop"></p>
212
+ <div class="actions">
213
+ <button type="button" part="cancel"></button>
214
+ <button type="button" part="continue" autofocus></button>
215
+ </div>
216
+ </dialog>`;
217
+ this.dialog = /** @type {HTMLDialogElement} */ (
218
+ root.querySelector('dialog')
219
+ );
220
+ root
221
+ .querySelector('[part=continue]')
222
+ .addEventListener('click', () => this.#settle(null));
223
+ root
224
+ .querySelector('[part=cancel]')
225
+ .addEventListener('click', () =>
226
+ this.#settle(new PasskeyStepCancelled())
227
+ );
228
+ // Escape is "Cancel", not a silent close that leaves the action waiting.
229
+ this.dialog.addEventListener('cancel', (event) => {
230
+ event.preventDefault();
231
+ this.#settle(new PasskeyStepCancelled());
232
+ });
233
+ }
234
+
235
+ /**
236
+ * Replace built-in wording, per language: `{ de: { purposes: { prf: { title,
237
+ * why } } } }`, or a language of its own with every key.
238
+ *
239
+ * @param {Partial<Record<string, Partial<PasskeyStepStrings>>>} value
240
+ */
241
+ set strings(value) {
242
+ this.#overrides = value ?? {};
243
+ }
244
+
245
+ get strings() {
246
+ return this.#overrides;
247
+ }
248
+
249
+ /** The language on screen: this element's `lang`, then the document's. */
250
+ get language() {
251
+ const declared = (
252
+ this.getAttribute('lang') ||
253
+ this.closest('[lang]')?.getAttribute('lang') ||
254
+ document.documentElement.lang ||
255
+ 'en'
256
+ )
257
+ .slice(0, 2)
258
+ .toLowerCase();
259
+ return declared;
260
+ }
261
+
262
+ /** @returns {PasskeyStepStrings} */
263
+ #text() {
264
+ const language = this.language;
265
+ const base = PASSKEY_STEP_STRINGS[language] ?? PASSKEY_STEP_STRINGS.en;
266
+ const own = this.#overrides[language] ?? {};
267
+ return {
268
+ ...base,
269
+ ...own,
270
+ purposes: { ...base.purposes, ...(own.purposes ?? {}) },
271
+ };
272
+ }
273
+
274
+ /**
275
+ * Show the step and wait. Resolves on "Continue"; rejects with
276
+ * {@link PasskeyStepCancelled} on "Cancel" or Escape.
277
+ *
278
+ * @param {import('../passkey-steps.js').PasskeyStep} step
279
+ * @returns {Promise<void>}
280
+ */
281
+ ask(step) {
282
+ // A step that is still open is answered "cancel" first: two prompts at
283
+ // once are not possible, so an older one is a leftover.
284
+ this.#settle(new PasskeyStepCancelled());
285
+
286
+ const text = this.#text();
287
+ const purpose = text.purposes[step.purpose] ?? {
288
+ title: step.purpose,
289
+ why: '',
290
+ };
291
+ const root = /** @type {ShadowRoot} */ (this.shadowRoot);
292
+ root.querySelector('[part=count]').textContent =
293
+ typeof step.of === 'number'
294
+ ? fill(text.count, { n: step.n, of: step.of })
295
+ : fill(text.countOpen, { n: step.n });
296
+ root.querySelector('[part=title]').textContent = purpose.title;
297
+ root.querySelector('[part=why]').textContent = purpose.why;
298
+ root.querySelector('[part=loop]').textContent = text.notALoop;
299
+ root.querySelector('[part=continue]').textContent = text.continue;
300
+ root.querySelector('[part=cancel]').textContent = text.cancel;
301
+ this.setAttribute('data-purpose', step.purpose);
302
+
303
+ return new Promise((resolve, reject) => {
304
+ this.#pending = { resolve, reject };
305
+ if (!this.dialog.open) this.dialog.showModal();
306
+ /** @type {HTMLElement} */ (
307
+ root.querySelector('[part=continue]')
308
+ ).focus();
309
+ });
310
+ }
311
+
312
+ /** Whether a step is showing. */
313
+ get isOpen() {
314
+ return this.dialog.open;
315
+ }
316
+
317
+ /** @param {Error | null} error */
318
+ #settle(error) {
319
+ const pending = this.#pending;
320
+ if (!pending) return;
321
+ this.#pending = null;
322
+ this.removeAttribute('data-purpose');
323
+ if (this.dialog.open) this.dialog.close();
324
+ if (error) pending.reject(error);
325
+ else pending.resolve();
326
+ }
327
+
328
+ disconnectedCallback() {
329
+ // Taken off the page while it waits: nothing can answer it any more.
330
+ this.#settle(new PasskeyStepCancelled());
331
+ }
332
+ }
package/src/index.js CHANGED
@@ -308,6 +308,16 @@ export {
308
308
  recoverPublicKeyCandidates,
309
309
  } from './webauthn/recovery.js';
310
310
  export { restoreIdentityFromAuthenticator } from './webauthn/restore.js';
311
+ // Before each passkey prompt, a word on what it is for — when an application
312
+ // registers a handler (src/passkey-steps.js; `<passkey-step-dialog>` in
313
+ // ./elements is one).
314
+ export {
315
+ setPasskeyStepHandler,
316
+ withPasskeySteps,
317
+ beforePasskeyCeremony,
318
+ PasskeyStepCancelled,
319
+ PASSKEY_PURPOSES,
320
+ } from './passkey-steps.js';
311
321
  // OrbitDB's identity cache refuses another session of the same passkey
312
322
  // (orbitdb/orbitdb#1258); this is the provider's answer until it is fixed there.
313
323
  export {
@@ -36,7 +36,8 @@ import {
36
36
  import { CRYPTO_ALGORITHMS, KEY_TYPES } from '../constants.js';
37
37
  import { buildCredentialRequestOptions } from '../webauthn/config.js';
38
38
  import { prfInputForRelyingParty } from '../webauthn/prf-input.js';
39
- import { hkdfSha256 } from './prf-keys.js';
39
+ import { hkdfSha256, sameBytes } from './prf-keys.js';
40
+ import { beforePasskeyCeremony } from '../passkey-steps.js';
40
41
 
41
42
  const log = logger('orbitdb-identity-provider-webauthn-did:derived-key');
42
43
 
@@ -131,6 +132,7 @@ export async function getPrfOutput(credential, { rpId } = {}) {
131
132
  ? credential.rawCredentialId
132
133
  : new Uint8Array(credential.rawCredentialId ?? []);
133
134
 
135
+ await beforePasskeyCeremony('signing-key');
134
136
  try {
135
137
  const assertion = await navigator.credentials.get(
136
138
  buildCredentialRequestOptions({
@@ -145,6 +147,13 @@ export async function getPrfOutput(credential, { rpId } = {}) {
145
147
  })
146
148
  );
147
149
 
150
+ // Another passkey's PRF output would derive another passkey's key, under
151
+ // this DID: refused like an answer without PRF.
152
+ const answered = assertion?.rawId ? new Uint8Array(assertion.rawId) : null;
153
+ if (answered && !sameBytes(answered, rawCredentialId)) {
154
+ log('another credential answered; no key derived from it');
155
+ return null;
156
+ }
148
157
  const results = assertion?.getClientExtensionResults?.()?.prf?.results;
149
158
  if (!results?.first) {
150
159
  log('authenticator returned no PRF output');
@@ -12,6 +12,7 @@ import {
12
12
  KEYSTORE_ENCRYPTION_METHODS,
13
13
  } from '../constants.js';
14
14
  import { KeystoreEncryptionError, PrfUnavailableError } from '../errors.js';
15
+ import { beforePasskeyCeremony } from '../passkey-steps.js';
15
16
 
16
17
  const log = logger(
17
18
  'orbitdb-identity-provider-webauthn-did:keystore-encryption'
@@ -257,6 +258,7 @@ export async function writeSKToLargeBlob(credentialId, sk, rpId) {
257
258
  log('Writing secret key to largeBlob');
258
259
 
259
260
  let assertion;
261
+ await beforePasskeyCeremony('keystore');
260
262
  try {
261
263
  assertion = await navigator.credentials.get(
262
264
  buildCredentialRequestOptions({
@@ -306,6 +308,7 @@ export async function writeSKToLargeBlob(credentialId, sk, rpId) {
306
308
  export async function retrieveSKFromLargeBlob(credentialId, rpId) {
307
309
  log('Retrieving secret key from largeBlob');
308
310
 
311
+ await beforePasskeyCeremony('keystore');
309
312
  try {
310
313
  const assertion = await navigator.credentials.get(
311
314
  buildCredentialRequestOptions({
@@ -374,6 +377,7 @@ export async function wrapSKWithHmacSecret(credentialId, sk, rpId) {
374
377
 
375
378
  const salt = crypto.getRandomValues(new Uint8Array(32));
376
379
 
380
+ await beforePasskeyCeremony('keystore');
377
381
  try {
378
382
  const assertion = await navigator.credentials.get(
379
383
  buildCredentialRequestOptions({
@@ -431,6 +435,7 @@ export async function wrapSKWithPRF(credentialId, sk, rpId, prfInput) {
431
435
 
432
436
  const prfEval = prfInput || crypto.getRandomValues(new Uint8Array(32));
433
437
 
438
+ await beforePasskeyCeremony('keystore');
434
439
  try {
435
440
  const assertion = await navigator.credentials.get(
436
441
  buildCredentialRequestOptions({
@@ -486,6 +491,7 @@ export async function unwrapSKWithHmacSecret(
486
491
  ) {
487
492
  log('Unwrapping secret key with hmac-secret');
488
493
 
494
+ await beforePasskeyCeremony('keystore');
489
495
  try {
490
496
  const assertion = await navigator.credentials.get(
491
497
  buildCredentialRequestOptions({
@@ -553,6 +559,7 @@ export async function unwrapSKWithPRF(
553
559
 
554
560
  const prfEval = salt || crypto.getRandomValues(new Uint8Array(32));
555
561
 
562
+ await beforePasskeyCeremony('keystore');
556
563
  try {
557
564
  const assertion = await navigator.credentials.get(
558
565
  buildCredentialRequestOptions({
@@ -20,9 +20,10 @@
20
20
  * the identity asks the passkey once.
21
21
  */
22
22
  import { CRYPTO_ALGORITHMS } from '../constants.js';
23
- import { PrfUnavailableError } from '../errors.js';
23
+ import { PrfUnavailableError, WebAuthnAuthenticationError } from '../errors.js';
24
24
  import { buildCredentialRequestOptions } from '../webauthn/config.js';
25
25
  import { prfInputForRelyingParty } from '../webauthn/prf-input.js';
26
+ import { beforePasskeyCeremony } from '../passkey-steps.js';
26
27
 
27
28
  const MIN_PRF_BYTES = 32;
28
29
  const HKDF_MAX_BYTES = 255 * 32;
@@ -39,6 +40,11 @@ function toBytes(value) {
39
40
  return undefined;
40
41
  }
41
42
 
43
+ /** @param {Uint8Array} a @param {Uint8Array} b */
44
+ export function sameBytes(a, b) {
45
+ return a.length === b.length && a.every((byte, i) => byte === b[i]);
46
+ }
47
+
42
48
  /**
43
49
  * HKDF-SHA-256 with an empty salt.
44
50
  *
@@ -113,8 +119,13 @@ function assertInfo(info, caller) {
113
119
  * @param {string} [options.rpId] - Relying party id; defaults to this page's
114
120
  * hostname.
115
121
  * @param {Uint8Array} [options.prfInput] - Overrides the credential's input.
122
+ * The request names the credential, and the answer is checked against it:
123
+ * another passkey of the same relying party would answer with its own PRF
124
+ * output, and every key derived from that would belong to the wrong one.
125
+ *
116
126
  * @returns {Promise<Uint8Array>} The PRF output, 32 bytes.
117
127
  * @throws {PrfUnavailableError} When the authenticator answers without one.
128
+ * @throws {WebAuthnAuthenticationError} When another credential answers.
118
129
  */
119
130
  export async function readPrfOutput(credential, { rpId, prfInput } = {}) {
120
131
  if (!credential || typeof credential !== 'object') {
@@ -130,6 +141,7 @@ export async function readPrfOutput(credential, { rpId, prfInput } = {}) {
130
141
  toBytes(credential.prfInput) ??
131
142
  (await prfInputForRelyingParty(relyingParty));
132
143
 
144
+ await beforePasskeyCeremony('prf');
133
145
  const assertion = await navigator.credentials.get(
134
146
  buildCredentialRequestOptions({
135
147
  challenge: crypto.getRandomValues(new Uint8Array(32)),
@@ -140,6 +152,12 @@ export async function readPrfOutput(credential, { rpId, prfInput } = {}) {
140
152
  })
141
153
  );
142
154
 
155
+ const answered = toBytes(assertion?.rawId);
156
+ if (answered && !sameBytes(answered, rawCredentialId)) {
157
+ throw new WebAuthnAuthenticationError(
158
+ 'Another passkey answered than the one asked for its PRF output'
159
+ );
160
+ }
143
161
  const first = assertion?.getClientExtensionResults?.()?.prf?.results?.first;
144
162
  if (!first) {
145
163
  throw new PrfUnavailableError(
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Before a passkey prompt, a word on what it is for — when an application asks
3
+ * for one.
4
+ *
5
+ * Creating a passkey-backed identity asks the authenticator three times in a
6
+ * row: the passkey itself, the PRF output the signing key comes from, and the
7
+ * signature on the identity. Restoring one from the authenticator asks three
8
+ * times as well. Without a word in between, that looks like a loop, and people
9
+ * cancel it. Le-Space/belege put a dialog between its prompts (#429); every
10
+ * other application would have had to rebuild it, and only this package knows
11
+ * when it is about to ask and why.
12
+ *
13
+ * So every WebAuthn call in this package first awaits
14
+ * {@link beforePasskeyCeremony} with its purpose. An application that wants
15
+ * the word in between registers a handler and declares how many prompts an
16
+ * action takes:
17
+ *
18
+ * ```js
19
+ * setPasskeyStepHandler((step) => dialog.ask(step)) // resolve = go on, throw = stop
20
+ * await withPasskeySteps(3, async () => {
21
+ * const credential = await WebAuthnDIDProvider.createCredential(...) // 1 of 3
22
+ * await startOrbitDB(credential) // 2 and 3 of 3
23
+ * })
24
+ * ```
25
+ *
26
+ * The first prompt of a plan is not announced: it comes from the click that
27
+ * started the action. Every later one is, and it starts from the click that
28
+ * answers the handler — which is also what Safari wants, a user gesture for
29
+ * each WebAuthn call.
30
+ *
31
+ * Without a handler, or outside a plan, nothing changes: every call goes
32
+ * straight to the authenticator, as before.
33
+ *
34
+ * `<passkey-step-dialog>` in `./elements` is a handler that needs no
35
+ * framework.
36
+ */
37
+
38
+ /**
39
+ * Why the authenticator is being asked. The dialog's wording is keyed on it.
40
+ *
41
+ * - `create` — a new passkey
42
+ * - `signing-key` — the PRF output the signing key is derived from
43
+ * - `identity` — the passkey signs the identity once
44
+ * - `restore` — find a passkey this device has nothing stored for
45
+ * - `restore-confirm` — the same passkey again: two signatures recover its key
46
+ * - `keystore` — seal or open the keystore's key with the passkey
47
+ * - `prf` — a secret from the passkey, for the application's own key
48
+ * - `metadata` — details the passkey carries for this application
49
+ * - `wallet` — the passkey signs for the account
50
+ * - `sign-entry` — the passkey signs an entry itself (varsig)
51
+ *
52
+ * @typedef {'create' | 'signing-key' | 'identity' | 'restore' | 'restore-confirm'
53
+ * | 'keystore' | 'prf' | 'metadata' | 'wallet' | 'sign-entry'} PasskeyPurpose
54
+ */
55
+
56
+ /** @type {ReadonlyArray<PasskeyPurpose>} */
57
+ export const PASSKEY_PURPOSES = Object.freeze([
58
+ 'create',
59
+ 'signing-key',
60
+ 'identity',
61
+ 'restore',
62
+ 'restore-confirm',
63
+ 'keystore',
64
+ 'prf',
65
+ 'metadata',
66
+ 'wallet',
67
+ 'sign-entry',
68
+ ]);
69
+
70
+ /**
71
+ * What a handler is told: which prompt comes next, and why. `of` is null when
72
+ * the plan did not say how many there are.
73
+ *
74
+ * @typedef {{ purpose: PasskeyPurpose, n: number, of: number | null,
75
+ * kind: 'create' | 'get' }} PasskeyStep
76
+ */
77
+
78
+ /** Thrown when somebody stops between two prompts. Nothing has been asked yet. */
79
+ export class PasskeyStepCancelled extends Error {
80
+ constructor(message = 'The passkey prompt was cancelled before it started.') {
81
+ super(message);
82
+ this.name = 'PasskeyStepCancelled';
83
+ }
84
+ }
85
+
86
+ /** @type {((step: PasskeyStep) => unknown) | null} */
87
+ let handler = null;
88
+
89
+ /** @type {{ of: number | null, n: number, askFirst: boolean } | null} */
90
+ let plan = null;
91
+
92
+ /**
93
+ * Register what runs before each announced prompt, or `null` to stop.
94
+ *
95
+ * The handler resolves to let the prompt go ahead and throws to stop it — a
96
+ * {@link PasskeyStepCancelled}, ideally, which then reaches the caller of the
97
+ * action unchanged.
98
+ *
99
+ * @param {((step: PasskeyStep) => unknown) | null} next
100
+ * @returns {() => void} unregisters this handler, if it is still the one
101
+ */
102
+ export function setPasskeyStepHandler(next) {
103
+ const mine = typeof next === 'function' ? next : null;
104
+ handler = mine;
105
+ return () => {
106
+ if (handler === mine) handler = null;
107
+ };
108
+ }
109
+
110
+ /**
111
+ * Run an action whose passkey prompts are numbered.
112
+ *
113
+ * `of` is how many prompts the action takes, as the application counts them
114
+ * (escrow01: 3 to create a passkey, 3 to restore one, 1 to come back with a
115
+ * stored one). A number that turns out too small does no harm beyond the
116
+ * dialog saying "4 of 3": the count is the application's promise, and its
117
+ * tests are where it is kept.
118
+ *
119
+ * `askFirst` announces the first prompt too, for an action that does not start
120
+ * from a click of its own.
121
+ *
122
+ * Plans do not nest: the inner one numbers its own prompts and the outer one
123
+ * resumes afterwards. WebAuthn allows one ceremony at a time, so there is
124
+ * never more than one plan running.
125
+ *
126
+ * @template T
127
+ * @param {number | null | { of?: number | null, askFirst?: boolean }} options
128
+ * @param {() => Promise<T> | T} run
129
+ * @returns {Promise<T>}
130
+ */
131
+ export async function withPasskeySteps(options, run) {
132
+ const { of = null, askFirst = false } =
133
+ typeof options === 'number' || options === null
134
+ ? { of: options }
135
+ : (options ?? {});
136
+ const outer = plan;
137
+ plan = { of: typeof of === 'number' && of > 0 ? of : null, n: 0, askFirst };
138
+ try {
139
+ return await run();
140
+ } finally {
141
+ plan = outer;
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Called by this package — and by an application, around its own WebAuthn
147
+ * calls — right before the authenticator is asked.
148
+ *
149
+ * Outside a plan, or without a handler, it returns at once. Inside one it
150
+ * counts the prompt and, from the second on (or from the first, with
151
+ * `askFirst`), waits for the handler.
152
+ *
153
+ * Call it outside any `try` that turns a failed ceremony into a fallback: a
154
+ * cancel has to reach the person's action, not be read as "this
155
+ * authenticator cannot".
156
+ *
157
+ * @param {PasskeyPurpose} purpose
158
+ * @param {'create' | 'get'} [kind]
159
+ * @returns {Promise<void>}
160
+ */
161
+ export async function beforePasskeyCeremony(purpose, kind = 'get') {
162
+ if (!plan) return;
163
+ plan.n += 1;
164
+ if (!handler) return;
165
+ if (plan.n === 1 && !plan.askFirst) return;
166
+ await handler({ purpose, n: plan.n, of: plan.of, kind });
167
+ }
@@ -71,3 +71,13 @@ export {
71
71
  encryptArchive,
72
72
  decryptArchive,
73
73
  } from './worker/client.js';
74
+
75
+ // The standalone wallet asks the passkey too; an application that uses only
76
+ // this entry announces those prompts with the same handler.
77
+ export {
78
+ setPasskeyStepHandler,
79
+ withPasskeySteps,
80
+ beforePasskeyCeremony,
81
+ PasskeyStepCancelled,
82
+ PASSKEY_PURPOSES,
83
+ } from '../passkey-steps.js';
@@ -1,5 +1,6 @@
1
1
  import { buildCredentialRequestOptions } from '../../webauthn/config.js';
2
2
  import { STORAGE_KEYS } from '../../constants.js';
3
+ import { beforePasskeyCeremony } from '../../passkey-steps.js';
3
4
 
4
5
  function ensureUint8Array(value, fieldName) {
5
6
  if (value instanceof Uint8Array) return value;
@@ -123,6 +124,7 @@ export async function extractPrfSeedFromCredential(credential, options = {}) {
123
124
  prfInput = crypto.getRandomValues(new Uint8Array(32));
124
125
  }
125
126
 
127
+ await beforePasskeyCeremony('prf');
126
128
  const assertion = await navigator.credentials.get(
127
129
  buildCredentialRequestOptions({
128
130
  challenge: crypto.getRandomValues(new Uint8Array(32)),
@@ -21,6 +21,7 @@ import {
21
21
  } from '../../errors.js';
22
22
  import { buildCredentialRequestOptions } from '../../webauthn/config.js';
23
23
  import { MULTICODEC, decodeDidKey } from '../../webauthn/proof-verification.js';
24
+ import { beforePasskeyCeremony } from '../../passkey-steps.js';
24
25
 
25
26
  // secp256r1 (NIST P-256), SEC 2 §2.4.2: y² = x³ − 3x + b over GF(p), order n.
26
27
  const P256_P =
@@ -468,6 +469,7 @@ export async function signP256Challenge(descriptor, challenge) {
468
469
  }
469
470
 
470
471
  let assertion;
472
+ await beforePasskeyCeremony('wallet');
471
473
  try {
472
474
  assertion = await navigator.credentials.get(
473
475
  buildCredentialRequestOptions({
@@ -24,6 +24,7 @@ import {
24
24
  WebAuthnAuthenticationError,
25
25
  } from '../errors.js';
26
26
  import { logWebAuthnResponse } from '../webauthn/debug-log.js';
27
+ import { beforePasskeyCeremony } from '../passkey-steps.js';
27
28
 
28
29
  /**
29
30
  * Run a WebAuthn assertion for a payload.
@@ -50,6 +51,7 @@ async function runWebAuthnAssertionForPayload(
50
51
  const signedBytes = bindContext(domainLabel, payloadBytes);
51
52
  const challengeBytes = await buildChallengeBytes(signedBytes);
52
53
 
54
+ await beforePasskeyCeremony('sign-entry');
53
55
  const assertion = await navigator.credentials.get(
54
56
  buildCredentialRequestOptions({
55
57
  rpId,
@@ -9,6 +9,7 @@ import {
9
9
  resolveAuthenticatorAttachment,
10
10
  } from '../webauthn/config.js';
11
11
  import { logWebAuthnResponse } from '../webauthn/debug-log.js';
12
+ import { beforePasskeyCeremony } from '../passkey-steps.js';
12
13
 
13
14
  /**
14
15
  * Extract public key info from a WebAuthn attestation object.
@@ -127,6 +128,7 @@ async function createWebAuthnVarsigCredential(options = {}) {
127
128
  extensions: { largeBlob: { support: 'preferred' } },
128
129
  };
129
130
 
131
+ await beforePasskeyCeremony('create', 'create');
130
132
  const credential = await navigator.credentials.create({ publicKey });
131
133
  if (!credential) {
132
134
  throw new Error('Passkey registration failed.');
@@ -138,7 +138,14 @@ export function buildCredentialRequestOptions(options = {}) {
138
138
  ...(rpId ? { rpId } : {}),
139
139
  userVerification,
140
140
  ...(extensions ? { extensions } : {}),
141
- ...(!discoverableCredentials && credentialId
141
+ // A request that names a credential asks that credential. Discoverable
142
+ // credentials decide only what a request without one does: the browser
143
+ // offers the passkeys it has. Left to the browser, a request that named
144
+ // one was answered by whichever passkey the person picked or the
145
+ // authenticator chose — with that passkey's PRF output, which nothing can
146
+ // tell from the right one: a vault slot sealed under another key, a
147
+ // signing key derived from another passkey.
148
+ ...(credentialId
142
149
  ? {
143
150
  allowCredentials: [
144
151
  {
@@ -1,4 +1,5 @@
1
1
  import { buildCredentialRequestOptions } from './config.js';
2
+ import { beforePasskeyCeremony } from '../passkey-steps.js';
2
3
 
3
4
  const encoder = new TextEncoder();
4
5
  const decoder = new TextDecoder();
@@ -110,6 +111,7 @@ export async function writeLargeBlobMetadata({
110
111
  discoverableCredentials = false,
111
112
  userVerification = 'required',
112
113
  }) {
114
+ await beforePasskeyCeremony('metadata');
113
115
  const assertion = await navigator.credentials.get(
114
116
  buildCredentialRequestOptions({
115
117
  challenge: crypto.getRandomValues(new Uint8Array(32)),
@@ -137,6 +139,7 @@ export async function readLargeBlobMetadata({
137
139
  discoverableCredentials = true,
138
140
  userVerification = 'required',
139
141
  }) {
142
+ await beforePasskeyCeremony('metadata');
140
143
  const assertion = await navigator.credentials.get(
141
144
  buildCredentialRequestOptions({
142
145
  challenge: crypto.getRandomValues(new Uint8Array(32)),
@@ -33,6 +33,7 @@ import {
33
33
  p256PublicKeyBytes,
34
34
  verifyWebAuthnProof,
35
35
  } from './proof-verification.js';
36
+ import { beforePasskeyCeremony } from '../passkey-steps.js';
36
37
 
37
38
  const webauthnLog = logger('orbitdb-identity-provider-webauthn-did:webauthn');
38
39
 
@@ -254,6 +255,7 @@ export class WebAuthnDIDProvider {
254
255
  prfInput = prfConfig.prfInput;
255
256
  }
256
257
 
258
+ await beforePasskeyCeremony('create', 'create');
257
259
  try {
258
260
  const credential = await navigator.credentials.create(credentialOptions);
259
261
 
@@ -654,6 +656,7 @@ export class WebAuthnDIDProvider {
654
656
  throw new WebAuthnNotSupportedError();
655
657
  }
656
658
 
659
+ await beforePasskeyCeremony('identity');
657
660
  try {
658
661
  webauthnLog('Signer context: %o', {
659
662
  signer: 'webauthn',
@@ -31,6 +31,7 @@ import { buildCredentialRequestOptions } from './config.js';
31
31
  import { prfInputForRelyingParty } from './prf-input.js';
32
32
  import { WebAuthnDIDProvider } from './provider.js';
33
33
  import { recoverPublicKey } from './recovery.js';
34
+ import { beforePasskeyCeremony } from '../passkey-steps.js';
34
35
 
35
36
  const log = logger('orbitdb-identity-provider-webauthn-did:restore');
36
37
 
@@ -69,6 +70,7 @@ export async function restoreIdentityFromAuthenticator({
69
70
  // Touch one: discoverable, so the device does not have to know which
70
71
  // credential to ask for — it has nothing stored, that is the premise.
71
72
  onTouch?.({ touch: 1, of: 2 });
73
+ await beforePasskeyCeremony('restore');
72
74
  const first = await navigator.credentials.get(
73
75
  buildCredentialRequestOptions({
74
76
  rpId: party,
@@ -95,6 +97,7 @@ export async function restoreIdentityFromAuthenticator({
95
97
  // Touch two: the same credential, another challenge. Only the signature
96
98
  // matters, so this asks for no more verification than the key insists on.
97
99
  onTouch?.({ touch: 2, of: 2 });
100
+ await beforePasskeyCeremony('restore-confirm');
98
101
  const second = await navigator.credentials.get(
99
102
  buildCredentialRequestOptions({
100
103
  rpId: party,
@@ -0,0 +1,49 @@
1
+ import type { PasskeyStep } from './passkey-steps';
2
+
3
+ export interface PasskeyPurposeText {
4
+ title: string;
5
+ why: string;
6
+ }
7
+
8
+ export interface PasskeyStepStrings {
9
+ count: string;
10
+ countOpen: string;
11
+ notALoop: string;
12
+ continue: string;
13
+ cancel: string;
14
+ purposes: Record<string, PasskeyPurposeText>;
15
+ }
16
+
17
+ /** Built-in wording, German and English. */
18
+ export const PASSKEY_STEP_STRINGS: Record<'en' | 'de', PasskeyStepStrings>;
19
+
20
+ /** `<passkey-step-dialog>`: between two passkey prompts, what the next one is for. */
21
+ export class PasskeyStepDialogElement extends HTMLElement {
22
+ /** Replace built-in wording per language, or add a language. */
23
+ strings: Partial<Record<string, Partial<PasskeyStepStrings>>>;
24
+ /** This element's `lang`, then the document's. */
25
+ readonly language: string;
26
+ /** Whether a step is showing. */
27
+ readonly isOpen: boolean;
28
+ /** Show the step; resolves on "Continue", rejects with PasskeyStepCancelled otherwise. */
29
+ ask(step: PasskeyStep): Promise<void>;
30
+ }
31
+
32
+ /** Make this element the handler for every announced passkey prompt. */
33
+ export function connectPasskeyStepDialog(
34
+ element: PasskeyStepDialogElement
35
+ ): () => void;
36
+
37
+ export {
38
+ setPasskeyStepHandler,
39
+ withPasskeySteps,
40
+ PasskeyStepCancelled,
41
+ PASSKEY_PURPOSES,
42
+ } from './passkey-steps';
43
+ export type { PasskeyStep, PasskeyPurpose } from './passkey-steps';
44
+
45
+ declare global {
46
+ interface HTMLElementTagNameMap {
47
+ 'passkey-step-dialog': PasskeyStepDialogElement;
48
+ }
49
+ }
package/types/index.d.ts CHANGED
@@ -785,3 +785,5 @@ export function withoutStaleIdentityCache<
785
785
  export function createIdentities(
786
786
  options?: Record<string, unknown>
787
787
  ): Promise<unknown>;
788
+
789
+ export * from './passkey-steps';
@@ -0,0 +1,51 @@
1
+ /** Why the authenticator is being asked; the dialog's wording is keyed on it. */
2
+ export type PasskeyPurpose =
3
+ | 'create'
4
+ | 'signing-key'
5
+ | 'identity'
6
+ | 'restore'
7
+ | 'restore-confirm'
8
+ | 'keystore'
9
+ | 'prf'
10
+ | 'metadata'
11
+ | 'wallet'
12
+ | 'sign-entry';
13
+
14
+ export const PASSKEY_PURPOSES: ReadonlyArray<PasskeyPurpose>;
15
+
16
+ /** Which prompt comes next, and why. `of` is null when the plan did not say. */
17
+ export interface PasskeyStep {
18
+ purpose: PasskeyPurpose;
19
+ n: number;
20
+ of: number | null;
21
+ kind: 'create' | 'get';
22
+ }
23
+
24
+ /** Thrown when somebody stops between two prompts. Nothing has been asked yet. */
25
+ export class PasskeyStepCancelled extends Error {
26
+ constructor(message?: string);
27
+ }
28
+
29
+ /**
30
+ * Register what runs before each announced prompt, or `null` to stop.
31
+ * Resolve to let the prompt go ahead, throw to stop it.
32
+ * Returns a function that unregisters this handler, if it is still the one.
33
+ */
34
+ export function setPasskeyStepHandler(
35
+ handler: ((step: PasskeyStep) => unknown) | null
36
+ ): () => void;
37
+
38
+ /**
39
+ * Run an action whose passkey prompts are numbered. `of` is how many prompts
40
+ * it takes; the first one is not announced unless `askFirst` is set.
41
+ */
42
+ export function withPasskeySteps<T>(
43
+ options: number | null | { of?: number | null; askFirst?: boolean },
44
+ run: () => Promise<T> | T
45
+ ): Promise<T>;
46
+
47
+ /** Called right before the authenticator is asked; awaits the handler inside a plan. */
48
+ export function beforePasskeyCeremony(
49
+ purpose: PasskeyPurpose,
50
+ kind?: 'create' | 'get'
51
+ ): Promise<void>;
@@ -532,3 +532,5 @@ export class PrfUnavailableError extends Error {
532
532
  export class VaultError extends Error {
533
533
  code: VaultErrorCode;
534
534
  }
535
+
536
+ export * from './passkey-steps';