axiam-sdk 1.0.0-beta14 → 1.0.0-beta15

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.
Files changed (42) hide show
  1. package/README.md +46 -6
  2. package/dist/browser/index.d.cts +24 -5
  3. package/dist/browser/index.d.ts +24 -5
  4. package/dist/browser/index.js +7 -0
  5. package/dist/browser/index.js.map +1 -1
  6. package/dist/browser/index.mjs +7 -1
  7. package/dist/browser/index.mjs.map +1 -1
  8. package/dist/{client-JWANinYZ.d.cts → client-CzVEJTC5.d.cts} +45 -2
  9. package/dist/{client-BXXwSvBI.d.ts → client-DLapMy-5.d.ts} +45 -2
  10. package/dist/{cookieJar-DZSc_d8H.d.ts → cookieJar-DIpQK-11.d.ts} +14 -4
  11. package/dist/{cookieJar-DXyJgm8n.d.cts → cookieJar-DoJeU4IN.d.cts} +14 -4
  12. package/dist/grpc/index.d.cts +5 -5
  13. package/dist/grpc/index.d.ts +5 -5
  14. package/dist/grpc/index.js +135 -9
  15. package/dist/grpc/index.js.map +1 -1
  16. package/dist/grpc/index.mjs +135 -9
  17. package/dist/grpc/index.mjs.map +1 -1
  18. package/dist/index.d.cts +2 -2
  19. package/dist/index.d.ts +2 -2
  20. package/dist/index.js +103 -6
  21. package/dist/index.js.map +1 -1
  22. package/dist/index.mjs +103 -6
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/middleware/index.d.cts +3 -3
  25. package/dist/middleware/index.d.ts +3 -3
  26. package/dist/node/index.d.cts +5 -5
  27. package/dist/node/index.d.ts +5 -5
  28. package/dist/node/index.js +135 -9
  29. package/dist/node/index.js.map +1 -1
  30. package/dist/node/index.mjs +135 -9
  31. package/dist/node/index.mjs.map +1 -1
  32. package/dist/{oidcState-C_9FRWTp.d.cts → oidcState-CSi4DY8h.d.cts} +1 -1
  33. package/dist/{oidcState-YzbbVX-C.d.ts → oidcState-CffZ6PkC.d.ts} +1 -1
  34. package/dist/rest/index.d.cts +3 -3
  35. package/dist/rest/index.d.ts +3 -3
  36. package/dist/rest/index.js +103 -6
  37. package/dist/rest/index.js.map +1 -1
  38. package/dist/rest/index.mjs +103 -6
  39. package/dist/rest/index.mjs.map +1 -1
  40. package/dist/{session-B0Lkz0X9.d.cts → session-oiuBA1ZA.d.cts} +17 -1
  41. package/dist/{session-fJCGq5jw.d.ts → session-ymrHvMuJ.d.ts} +17 -1
  42. package/package.json +1 -1
package/README.md CHANGED
@@ -32,7 +32,7 @@ browser bundle pulls in no Node-only code. §12.2 forbids splitting them across
32
32
  the four operations contract 1.38 adds are on `OidcClient` too, with the nine that preceded
33
33
  them, even though three of them need no Node-only code at all.
34
34
 
35
- §27 is implemented **in full**, both halves: the 158-operation imperative surface *and*
35
+ §27 is implemented **in full**, both halves: the 160-operation imperative surface *and*
36
36
  the §27.6 declarative manifest with its §27.7 `defineManifest` and decorator forms. The
37
37
  contract asks an SDK that ships only one half to say which; this one ships both.
38
38
 
@@ -120,7 +120,7 @@ never contains `@grpc/grpc-js` or `amqplib`):
120
120
  | Entry point | Persona | Contents |
121
121
  |-------------------------|-----------------------------|---------------------------------------------------------------------------|
122
122
  | `axiam-sdk` / `axiam-sdk/rest` | Browser + Node, REST-only | `AxiamClient`: `login`/`verifyMfa`/`refresh`/`logout`, `can`/`batchCheck` over the FND-04 REST authz endpoint |
123
- | `axiam-sdk/browser` | Browser only | The WebAuthn **platform ceremony** — `webauthnRegister`/`webauthnLogin`/`webauthnDiscoverableLogin` over `navigator.credentials` (CONTRACT.md §24.6b). The relying-party operations themselves are on `AxiamClient` in `/rest` and work in Node too. |
123
+ | `axiam-sdk/browser` | Browser only | The WebAuthn **platform ceremony** — `webauthnRegister`/`webauthnSetupRegister`/`webauthnLogin`/`webauthnDiscoverableLogin` over `navigator.credentials` (CONTRACT.md §24.6b). The relying-party operations themselves are on `AxiamClient` in `/rest` and work in Node too. |
124
124
  | `axiam-sdk/grpc` | Node only | Everything in `/rest` plus `AuthzGrpcClient.checkAccess`/`batchCheck` and `UserInfoGrpcClient.getUserInfo` over gRPC, the Node persona (`createNodeSession`), and the local-JWKS verifier |
125
125
  | `axiam-sdk/amqp` | Node only | `consume()` — HMAC-verified AMQP audit/authz event consumer (CONTRACT.md §8) |
126
126
  | `axiam-sdk/node` | Node only | The Node persona (`createNodeSession`/`createNodeClient`, cookie jar + local-JWKS verifier) plus the **OIDC/SSO relying-party helpers** — `OidcClient`, `MemoryOidcStateStore`, PKCE primitives (CONTRACT.md §12) |
@@ -1046,9 +1046,16 @@ you which half you get.
1046
1046
 
1047
1047
  | | Where | Runs in |
1048
1048
  |---|---|---|
1049
- | The six relying-party operations | `AxiamClient`, from `axiam-sdk` / `axiam-sdk/rest` | **Browser and Node** |
1049
+ | The eight relying-party operations | `AxiamClient`, from `axiam-sdk` / `axiam-sdk/rest` | **Browser and Node** |
1050
1050
  | The ceremony (`navigator.credentials`) | `axiam-sdk/browser` | Browser only |
1051
1051
 
1052
+ Six of the eight enrol or authenticate an existing account and are covered
1053
+ below. The other two, `webauthnSetupRegisterStart`/`webauthnSetupRegisterFinish`
1054
+ (contract 1.45), enrol a passkey as an account's **first** factor during forced
1055
+ login setup and take no session at all — see
1056
+ ["A passkey or security key as the first factor"](#a-passkey-or-security-key-as-the-first-factor-contract-145)
1057
+ in the account-lifecycle section, next to their TOTP twin.
1058
+
1052
1059
  The Node half is not a consolation prize. A service completing a ceremony that
1053
1060
  ran on a handset — an Android app, an iOS app, a hardware client — is the
1054
1061
  relying party, exactly as a browser is, and it never touches
@@ -1226,6 +1233,39 @@ If you match `LoginResult` exhaustively, this is the edit you need. A genuine
1226
1233
  authorization refusal is still an `AuthzError`: the SDK matches on the body's own
1227
1234
  discriminant, not on the `403` alone.
1228
1235
 
1236
+ ### A passkey or security key as the first factor (contract 1.45)
1237
+
1238
+ `mfaSetupEnroll`/`mfaSetupConfirm` above are the TOTP path through
1239
+ `mfa_setup_required`. `webauthnSetupRegisterStart`/`webauthnSetupRegisterFinish`
1240
+ are the WebAuthn twin, for a user who would rather enrol a passkey or security
1241
+ key as their first factor:
1242
+
1243
+ ```ts
1244
+ case 'mfa_setup_required': {
1245
+ const { challenge, stateToken } = await client.webauthnSetupRegisterStart(result.setupToken);
1246
+ const credential = await createTheAuthenticatorResponse(challenge); // e.g. axiam-sdk/browser
1247
+ await client.webauthnSetupRegisterFinish(
1248
+ result.setupToken,
1249
+ stateToken,
1250
+ 'Alice’s security key',
1251
+ credential,
1252
+ );
1253
+ break; // this completes the login, exactly as mfaSetupConfirm does
1254
+ }
1255
+ ```
1256
+
1257
+ In the browser, `webauthnSetupRegister(client, result.setupToken, name)` from
1258
+ `axiam-sdk/browser` (§24.6b) runs all three steps, mirroring `webauthnRegister`.
1259
+
1260
+ **They take no session, and never will.** The setup token in the body is the
1261
+ only credential either endpoint accepts — unlike `webauthnRegisterStart`/
1262
+ `webauthnRegisterFinish`, which enrol a passkey for an *already signed-in*
1263
+ user and require one. Calling them on a client that happens to be
1264
+ authenticated elsewhere does not attach that session: a setup token adds an
1265
+ account's first factor, never a second, and the SDK never lets the two
1266
+ credentials mix. `webauthnSetupRegisterFinish` adopts the resulting session
1267
+ exactly as `mfaSetupConfirm` does, because it *is* the same completed login.
1268
+
1229
1269
  ### Email verification and password reset
1230
1270
 
1231
1271
  ```ts
@@ -1762,7 +1802,7 @@ entries are keyed by subject rather than by session.
1762
1802
  Everything above assumes a populated tenant. `login` signs a user in,
1763
1803
  `checkAccess` asks about a resource, `verifyWebhook` checks a delivery signature — and
1764
1804
  none of them can create the user, declare the resource or register the webhook. The
1765
- management surface is the part that can: **158 operations across 24 namespaces**,
1805
+ management surface is the part that can: **160 operations across 24 namespaces**,
1766
1806
  generated from `management-registry.json`, which is the whole server API minus what other
1767
1807
  contract sections own and minus organization creation and deletion (§27.0 keeps those out
1768
1808
  of reach of a client library on purpose).
@@ -1873,7 +1913,7 @@ back.
1873
1913
 
1874
1914
  ### Declarative manifests (§27.6, §27.7)
1875
1915
 
1876
- Calling 158 operations one at a time is rarely what an application wants. What it does at
1916
+ Calling 160 operations one at a time is rarely what an application wants. What it does at
1877
1917
  start-up, in a migration, or in a test fixture is assert a shape:
1878
1918
 
1879
1919
  ```ts
@@ -1911,7 +1951,7 @@ actions that would reconcile the tenant.
1911
1951
  a tenant that also holds hand-made state.
1912
1952
  - **Applying twice converges**: the second plan is all `no-change`. That is what makes
1913
1953
  re-running after a failure safe.
1914
- - **There is no transaction** across 158 independent HTTP endpoints, and `ApplyReport` does
1954
+ - **There is no transaction** across 160 independent HTTP endpoints, and `ApplyReport` does
1915
1955
  not pretend there is. If step 12 of 30 fails, steps 1–11 have happened; the report says
1916
1956
  which, execution stops rather than continuing blindly, and there is no `rollback` —
1917
1957
  because this SDK could not honour one.
@@ -1,10 +1,10 @@
1
- import { A as AxiamClient, W as WebauthnWorkspace, a as WebauthnLoginResult, b as WebauthnCredential } from '../client-JWANinYZ.cjs';
1
+ import { A as AxiamClient, W as WebauthnWorkspace, a as WebauthnLoginResult, b as WebauthnCredential } from '../client-CzVEJTC5.cjs';
2
+ import { S as Sensitive } from '../sensitive-BC_s7Rrd.cjs';
3
+ import { L as LoginResult } from '../types-zXSpiQM-.cjs';
2
4
  export { W as WebauthnFailure, c as classifyWebauthnError, w as webauthnErrorMessage } from '../webauthnErrors-fLgfOflO.cjs';
3
- import '../sensitive-BC_s7Rrd.cjs';
4
- import '../session-B0Lkz0X9.cjs';
5
+ import '../session-oiuBA1ZA.cjs';
5
6
  import 'axios';
6
7
  import '../telemetry-DrGqL4kb.cjs';
7
- import '../types-zXSpiQM-.cjs';
8
8
 
9
9
  /**
10
10
  * Whether this runtime can perform a WebAuthn ceremony at all.
@@ -59,6 +59,25 @@ interface WebauthnCeremonyOptions {
59
59
  * not passed — the SDK never infers it and never defaults it.
60
60
  */
61
61
  declare function webauthnRegister(client: AxiamClient, credentialName: string, kind?: AuthenticatorKind, options?: WebauthnCeremonyOptions): Promise<WebauthnCredential>;
62
+ /**
63
+ * Enrol a passkey or security key as the account's **first** factor, during
64
+ * forced login setup (§24.6, contract 1.45) — the setup-token twin of
65
+ * {@link webauthnRegister}, reached where `mfaSetupEnroll`/`mfaSetupConfirm`'s
66
+ * TOTP path is reached: `login()` answered `mfa_setup_required` because the
67
+ * tenant requires MFA and this account has none.
68
+ *
69
+ * Runs the full ceremony: `setup/register/start`, the authenticator, then
70
+ * `setup/register/finish` — which, unlike `webauthnRegisterFinish`,
71
+ * adopts credentials and completes the interrupted login (§25.2 rule 2,
72
+ * mirrored). The pair stays individually callable on `AxiamClient` for the
73
+ * same reason {@link webauthnRegister} is additive rather than the only way
74
+ * in (§24.6 rule 1).
75
+ *
76
+ * @param setupToken the token from `login()`'s `mfa_setup_required` outcome.
77
+ * @param kind optional `authenticatorAttachment` hint. Omitted entirely when
78
+ * not passed — the SDK never infers it and never defaults it.
79
+ */
80
+ declare function webauthnSetupRegister(client: AxiamClient, setupToken: Sensitive<string> | string, credentialName: string, kind?: AuthenticatorKind, options?: WebauthnCeremonyOptions): Promise<LoginResult>;
62
81
  /**
63
82
  * Sign in with a passkey as a **second factor** (§24.6).
64
83
  *
@@ -87,4 +106,4 @@ declare function base64UrlToBytes(value: string): Uint8Array<ArrayBuffer>;
87
106
  /** Encode bytes as unpadded base64url. */
88
107
  declare function bytesToBase64Url(buffer: ArrayBuffer | Uint8Array): string;
89
108
 
90
- export { type AuthenticatorKind, type WebauthnCeremonyOptions, base64UrlToBytes, bytesToBase64Url, isConditionalMediationAvailable, isWebauthnSupported, webauthnDiscoverableLogin, webauthnLogin, webauthnRegister };
109
+ export { type AuthenticatorKind, type WebauthnCeremonyOptions, base64UrlToBytes, bytesToBase64Url, isConditionalMediationAvailable, isWebauthnSupported, webauthnDiscoverableLogin, webauthnLogin, webauthnRegister, webauthnSetupRegister };
@@ -1,10 +1,10 @@
1
- import { A as AxiamClient, W as WebauthnWorkspace, a as WebauthnLoginResult, b as WebauthnCredential } from '../client-BXXwSvBI.js';
1
+ import { A as AxiamClient, W as WebauthnWorkspace, a as WebauthnLoginResult, b as WebauthnCredential } from '../client-DLapMy-5.js';
2
+ import { S as Sensitive } from '../sensitive-BC_s7Rrd.js';
3
+ import { L as LoginResult } from '../types-BOX-6Srv.js';
2
4
  export { W as WebauthnFailure, c as classifyWebauthnError, w as webauthnErrorMessage } from '../webauthnErrors-fLgfOflO.js';
3
- import '../sensitive-BC_s7Rrd.js';
4
- import '../session-fJCGq5jw.js';
5
+ import '../session-ymrHvMuJ.js';
5
6
  import 'axios';
6
7
  import '../telemetry-DrGqL4kb.js';
7
- import '../types-BOX-6Srv.js';
8
8
 
9
9
  /**
10
10
  * Whether this runtime can perform a WebAuthn ceremony at all.
@@ -59,6 +59,25 @@ interface WebauthnCeremonyOptions {
59
59
  * not passed — the SDK never infers it and never defaults it.
60
60
  */
61
61
  declare function webauthnRegister(client: AxiamClient, credentialName: string, kind?: AuthenticatorKind, options?: WebauthnCeremonyOptions): Promise<WebauthnCredential>;
62
+ /**
63
+ * Enrol a passkey or security key as the account's **first** factor, during
64
+ * forced login setup (§24.6, contract 1.45) — the setup-token twin of
65
+ * {@link webauthnRegister}, reached where `mfaSetupEnroll`/`mfaSetupConfirm`'s
66
+ * TOTP path is reached: `login()` answered `mfa_setup_required` because the
67
+ * tenant requires MFA and this account has none.
68
+ *
69
+ * Runs the full ceremony: `setup/register/start`, the authenticator, then
70
+ * `setup/register/finish` — which, unlike `webauthnRegisterFinish`,
71
+ * adopts credentials and completes the interrupted login (§25.2 rule 2,
72
+ * mirrored). The pair stays individually callable on `AxiamClient` for the
73
+ * same reason {@link webauthnRegister} is additive rather than the only way
74
+ * in (§24.6 rule 1).
75
+ *
76
+ * @param setupToken the token from `login()`'s `mfa_setup_required` outcome.
77
+ * @param kind optional `authenticatorAttachment` hint. Omitted entirely when
78
+ * not passed — the SDK never infers it and never defaults it.
79
+ */
80
+ declare function webauthnSetupRegister(client: AxiamClient, setupToken: Sensitive<string> | string, credentialName: string, kind?: AuthenticatorKind, options?: WebauthnCeremonyOptions): Promise<LoginResult>;
62
81
  /**
63
82
  * Sign in with a passkey as a **second factor** (§24.6).
64
83
  *
@@ -87,4 +106,4 @@ declare function base64UrlToBytes(value: string): Uint8Array<ArrayBuffer>;
87
106
  /** Encode bytes as unpadded base64url. */
88
107
  declare function bytesToBase64Url(buffer: ArrayBuffer | Uint8Array): string;
89
108
 
90
- export { type AuthenticatorKind, type WebauthnCeremonyOptions, base64UrlToBytes, bytesToBase64Url, isConditionalMediationAvailable, isWebauthnSupported, webauthnDiscoverableLogin, webauthnLogin, webauthnRegister };
109
+ export { type AuthenticatorKind, type WebauthnCeremonyOptions, base64UrlToBytes, bytesToBase64Url, isConditionalMediationAvailable, isWebauthnSupported, webauthnDiscoverableLogin, webauthnLogin, webauthnRegister, webauthnSetupRegister };
@@ -92,6 +92,12 @@ async function webauthnRegister(client, credentialName, kind, options) {
92
92
  const credential = await createCredential(challenge, kind, options?.signal);
93
93
  return client.webauthnRegisterFinish(stateToken, credentialName, credential);
94
94
  }
95
+ async function webauthnSetupRegister(client, setupToken, credentialName, kind, options) {
96
+ requireSupport("webauthnSetupRegister");
97
+ const { challenge, stateToken } = await client.webauthnSetupRegisterStart(setupToken);
98
+ const credential = await createCredential(challenge, kind, options?.signal);
99
+ return client.webauthnSetupRegisterFinish(setupToken, stateToken, credentialName, credential);
100
+ }
95
101
  async function webauthnLogin(client, challengeToken, options) {
96
102
  requireSupport("webauthnLogin");
97
103
  const { challenge, stateToken } = await client.webauthnAuthenticateStart(challengeToken);
@@ -209,5 +215,6 @@ exports.webauthnDiscoverableLogin = webauthnDiscoverableLogin;
209
215
  exports.webauthnErrorMessage = webauthnErrorMessage;
210
216
  exports.webauthnLogin = webauthnLogin;
211
217
  exports.webauthnRegister = webauthnRegister;
218
+ exports.webauthnSetupRegister = webauthnSetupRegister;
212
219
  //# sourceMappingURL=index.js.map
213
220
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/browser/base64url.ts","../../src/rest/webauthnErrors.ts","../../src/brow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AE,GAChE,EAAC;AAAA,IACL,GAAI,sBAAA,GAAyB,EAAE,sBAAA,KAA2B,EAAC;AAAA,IAC3D,GAAI,KAAK,WAAA,GACL,EAAE,aAAa,IAAA,CAAK,WAAA,KACpB,EAAC;AAAA,IACL,GAAI,KAAK,UAAA,GACL,EAAE,YAAY,IAAA,CAAK,UAAA,KACnB;AAAC,GACP;AACF;AAGA,SAAS,iBAAiB,IAAA,EAAqE;AAC7F,EAAA,OAAO;AAAA,IACL,SAAA,EAAW,gBAAA,CAAiB,IAAA,CAAK,SAAS,CAAA;AAAA,IAC1C,GAAI,KAAK,OAAA,KAAY,MAAA,GAAY,EAAE,OAAA,EAAS,IAAA,CAAK,OAAA,EAAQ,GAAI,EAAC;AAAA,IAC9D,GAAI,KAAK,IAAA,GAAO,EAAE,MAAM,IAAA,CAAK,IAAA,KAAS,EAAC;AAAA,IACvC,GAAI,IAAA,CAAK,gBAAA,GACL,EAAE,gBAAA,EAAkB,IAAA,CAAK,gBAAA,CAAiB,GAAA,CAAI,YAAY,CAAA,EAAE,GAC5D,EAAC;AAAA,IACL,GAAI,KAAK,gBAAA,GACL,EAAE,kBAAkB,IAAA,CAAK,gBAAA,KACzB,EAAC;AAAA,IACL,GAAI,KAAK,UAAA,GACL,EAAE,YAAY,IAAA,CAAK,UAAA,KACnB;AAAC,GACP;AACF;AAEA,SAAS,aAAa,CAAA,EAAoE;AACxF,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,gBAAA,CAAiB,CAAA,CAAE,EAAE,CAAA;AAAA,IACzB,MAAM,CAAA,CAAE,IAAA;AAAA,IACR,GAAI,EAAE,UAAA,GAAa,EAAE,YAAY,CAAA,CAAE,UAAA,KAA2C;AAAC,GACjF;AACF","file":"index.js","sourcesContent":["// base64url ⇄ ArrayBuffer, for the WebAuthn JSON form (CONTRACT.md §24.6).\n//\n// Hand-rolled rather than pulled from `@simplewebauthn/browser`, which is what\n// the AXIAM admin UI uses. The conversion is thirty lines and fully specified\n// by RFC 4648 §5; a runtime dependency on every consumer's bundle to avoid\n// writing them, in a package whose whole job is to add as little as possible\n// to a browser bundle, is the wrong trade. The test file pins both directions\n// against fixed vectors, including the padding cases that are the only part\n// anyone gets wrong.\n//\n// Every buffer in a WebAuthn JSON message is base64url, **unpadded**. We\n// accept padding on the way in, because a server or a library that emits it is\n// not wrong, and never emit it on the way out.\n\n/**\n * Decode an unpadded (or padded) base64url string to bytes.\n *\n * Typed `Uint8Array<ArrayBuffer>` rather than the bare `Uint8Array`, whose\n * default parameter is `ArrayBufferLike` and therefore admits\n * `SharedArrayBuffer` — which `BufferSource`, and so every WebAuthn DOM\n * option, does not. The buffer is freshly allocated here and is never shared.\n */\nexport function base64UrlToBytes(value: string): Uint8Array<ArrayBuffer> {\n const padded = value.replace(/-/g, '+').replace(/_/g, '/');\n const binary = atob(padded.padEnd(Math.ceil(padded.length / 4) * 4, '='));\n const bytes = new Uint8Array(new ArrayBuffer(binary.length));\n for (let i = 0; i < binary.length; i += 1) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\n/** Encode bytes as unpadded base64url. */\nexport function bytesToBase64Url(buffer: ArrayBuffer | Uint8Array): string {\n const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);\n let binary = '';\n // Chunked: `String.fromCharCode(...bytes)` blows the argument limit on an\n // attestation object, which is routinely a few kilobytes.\n const CHUNK = 0x8000;\n for (let i = 0; i < bytes.length; i += CHUNK) {\n binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n","// Ceremony failure classification (CONTRACT.md §24.6b rule 5).\n//\n// Isomorphic on purpose. §24.6b rule 5's closing paragraph puts this in the\n// core rather than beside the linked-API helper: an Android app catching a\n// `CreateCredentialException`, or a Node service handed an error string by the\n// handset that ran the ceremony, has the same five outcomes and the same reason\n// to want one vocabulary for them. Nothing here touches the DOM — it reads the\n// error's `name`, which is the only machine-readable part any platform gives.\n\n/**\n * A ceremony failure a caller can say something useful about.\n *\n * Five outcomes, and the interesting ones are the first two.\n */\nexport type WebauthnFailure =\n | 'cancelled'\n | 'already_registered'\n | 'timeout'\n | 'unsupported'\n | 'unknown';\n\n/**\n * Map a platform ceremony error to its canonical classification (§24.6b rule 5).\n *\n * Accepts anything: a browser `DOMException`, an Android\n * `CreateCredentialException` name relayed as a string, an\n * `ASAuthorizationError` code relayed by name. Everything unrecognized is\n * `unknown` rather than a throw — a classifier that can fail is one more thing\n * for an error handler to handle.\n */\nexport function classifyWebauthnError(err: unknown): WebauthnFailure {\n const name = errorName(err);\n switch (name) {\n // NotAllowedError covers BOTH an explicit refusal and a silent timeout.\n // The spec deliberately refuses to distinguish them, because telling a\n // website which one happened leaks whether an authenticator was present.\n // \"cancelled\" is therefore the honest label for both — and it must not be\n // recovered by timing the call.\n case 'NotAllowedError':\n case 'canceled':\n case 'cancelled':\n return 'cancelled';\n // The authenticator already holds a credential for this account: the\n // server sent it in `excludeCredentials` and the authenticator refused to\n // silently mint a second. That is the exclusion list working, not a\n // failure — and it is the only classification whose remedy is \"use a\n // different device\" rather than \"try again\".\n case 'InvalidStateError':\n return 'already_registered';\n case 'AbortError':\n case 'timeout':\n return 'timeout';\n case 'NotSupportedError':\n case 'SecurityError':\n return 'unsupported';\n default:\n return 'unknown';\n }\n}\n\n/**\n * Copy for each failure, safe to show a user.\n *\n * The `cancelled` string deliberately does not accuse anyone of cancelling: the\n * same classification covers a silent timeout, and the spec will not say which\n * happened.\n */\nexport function webauthnErrorMessage(failure: WebauthnFailure): string {\n switch (failure) {\n case 'cancelled':\n return 'The request was cancelled or timed out. You can try again.';\n case 'already_registered':\n return 'This device is already registered on your account. Try a different device, or remove the existing one first.';\n case 'timeout':\n return 'The request timed out before it completed. Please try again.';\n case 'unsupported':\n return 'This browser or device cannot be used for passkeys. Try a different browser, or use another sign-in method.';\n case 'unknown':\n return 'Something went wrong. Please try again.';\n }\n}\n\n/** The platform's own error name, however it arrived. */\nfunction errorName(err: unknown): string | undefined {\n if (typeof err === 'string') return err;\n if (typeof err !== 'object' || err === null) return undefined;\n const name = (err as { name?: unknown }).name;\n return typeof name === 'string' ? name : undefined;\n}\n","// The WebAuthn platform ceremony (CONTRACT.md §24.6).\n//\n// This is the half of a passkey ceremony that talks to an *authenticator*, and\n// the only half that needs a browser. It lives on its own subpath so the\n// isomorphic `/rest` core stays free of DOM code: a Node consumer gets the\n// §24.1 relying-party layer and nothing here, which is §24.7's posture for the\n// Node build stated as a module boundary rather than as a runtime throw.\n//\n// ## What this module is allowed to change, which is almost nothing\n//\n// §24.0: the server picks every option and verifies every response, so the\n// options reach `navigator.credentials` as the server sent them and the\n// authenticator's answer goes back untouched. The two things that happen here\n// look like exceptions and are not:\n//\n// 1. **base64url → ArrayBuffer.** The DOM API takes `BufferSource` where the\n// JSON form carries a base64url string. Those are the same bytes in the\n// representation each side demands, which is a transcription, not an\n// adjustment. Nothing is defaulted, dropped, reordered or re-derived —\n// the round-trip test asserts exactly that.\n// 2. **`authenticatorAttachment`.** §24.6 rule 4's single permitted\n// addition, and only from an explicit caller argument. It selects which\n// authenticator the user is prompted for; it cannot weaken what the\n// server will accept. Without it, a user who asked for a security key is\n// prompted for the platform biometric instead.\n\nimport type {\n AxiamClient,\n WebauthnAuthenticationResponse,\n WebauthnCreationChallenge,\n WebauthnCreationOptionsJson,\n WebauthnCredential,\n WebauthnCredentialDescriptorJson,\n WebauthnLoginResult,\n WebauthnRegistrationResponse,\n WebauthnRequestChallenge,\n WebauthnRequestOptionsJson,\n WebauthnWorkspace,\n} from '../rest/index.js';\nimport { base64UrlToBytes, bytesToBase64Url } from './base64url.js';\n\n// §24.6b rule 5's classification lives in the isomorphic core, not here: an\n// Android app catching a `CreateCredentialException` wants the same vocabulary,\n// and it never loads this module. Re-exported so a browser consumer still finds\n// it on the subpath it is already importing from.\nexport { classifyWebauthnError, webauthnErrorMessage } from '../rest/index.js';\nexport type { WebauthnFailure } from '../rest/index.js';\n\n// ---------------------------------------------------------------------------\n// Feature detection (§24.6 rule 6)\n// ---------------------------------------------------------------------------\n\n/**\n * Whether this runtime can perform a WebAuthn ceremony at all.\n *\n * A query, not an exception (§24.6 rule 6) — a caller hides the enrolment\n * button rather than offering one that throws. Answers `false` in Node, where\n * the §24.1 relying-party layer still works fine.\n */\nexport function isWebauthnSupported(): boolean {\n return (\n typeof globalThis !== 'undefined' &&\n typeof (globalThis as { PublicKeyCredential?: unknown }).PublicKeyCredential !== 'undefined' &&\n typeof navigator !== 'undefined' &&\n typeof navigator.credentials?.get === 'function'\n );\n}\n\n/**\n * Whether this browser supports **conditional mediation** — passkey autofill,\n * where saved passkeys are offered from inside the username field rather than\n * behind a button.\n *\n * Returns `false` rather than throwing where the probe itself is missing\n * (§24.6 rule 3): conditional UI is a progressive enhancement, and its absence\n * must degrade to the explicit prompt, never to a broken sign-in page.\n */\nexport async function isConditionalMediationAvailable(): Promise<boolean> {\n if (!isWebauthnSupported()) return false;\n const ctor = (globalThis as { PublicKeyCredential?: { isConditionalMediationAvailable?: unknown } })\n .PublicKeyCredential;\n const probe = ctor?.isConditionalMediationAvailable;\n if (typeof probe !== 'function') return false;\n try {\n return await (probe as () => Promise<boolean>).call(ctor);\n } catch {\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Composed helpers (§24.6 rule 1 — additive; the six wire ops stay public)\n// ---------------------------------------------------------------------------\n\n/**\n * Which kind of authenticator the user reached for.\n *\n * A hint only (§24.6 rule 4). `platform` is a passkey built into the device\n * (Touch ID, Windows Hello, a phone); `cross-platform` is a removable security\n * key.\n */\nexport type AuthenticatorKind = 'platform' | 'cross-platform';\n\n/** Options shared by the two sign-in helpers. */\nexport interface WebauthnCeremonyOptions {\n /**\n * Use conditional mediation (passkey autofill) instead of a modal prompt.\n *\n * The returned promise may never settle — the user simply may not pick a\n * passkey — so a caller using this must be prepared to abandon it, and MUST\n * NOT surface an abandoned ceremony as an authentication failure (§24.6\n * rule 3). The browser aborts it when the page navigates.\n */\n conditional?: boolean;\n /** Abort the ceremony. Also how a conditional ceremony is abandoned. */\n signal?: AbortSignal;\n}\n\n/**\n * Enrol a passkey or security key for the signed-in user (§24.6).\n *\n * Runs the full ceremony: `register/start`, the authenticator, then\n * `register/finish`. The three steps stay individually callable on\n * `AxiamClient` — a caller driving a virtual authenticator in a test needs the\n * pair directly, which is why this helper is additive rather than the only way\n * in (§24.6 rule 1).\n *\n * @param kind optional `authenticatorAttachment` hint. Omitted entirely when\n * not passed — the SDK never infers it and never defaults it.\n */\nexport async function webauthnRegister(\n client: AxiamClient,\n credentialName: string,\n kind?: AuthenticatorKind,\n options?: WebauthnCeremonyOptions,\n): Promise<WebauthnCredential> {\n requireSupport('webauthnRegister');\n\n const { challenge, stateToken } = await client.webauthnRegisterStart();\n const credential = await createCredential(challenge, kind, options?.signal);\n return client.webauthnRegisterFinish(stateToken, credentialName, credential);\n}\n\n/**\n * Sign in with a passkey as a **second factor** (§24.6).\n *\n * `challengeToken` is the `mfaToken` from a `login()` that answered\n * `mfa_required` with `\"webauthn\"` among its methods.\n */\nexport async function webauthnLogin(\n client: AxiamClient,\n challengeToken: string,\n options?: WebauthnCeremonyOptions,\n): Promise<WebauthnLoginResult> {\n requireSupport('webauthnLogin');\n\n const { challenge, stateToken } = await client.webauthnAuthenticateStart(challengeToken);\n const assertion = await getAssertion(challenge, options);\n return client.webauthnAuthenticateFinish(stateToken, assertion);\n}\n\n/**\n * Sign in with a passkey **without typing a username first** (§24.6).\n *\n * The workspace still has to be named — a discoverable credential is resolved\n * inside one tenant — but it comes from the client's own configuration unless\n * overridden, and slugs are accepted.\n */\nexport async function webauthnDiscoverableLogin(\n client: AxiamClient,\n workspace?: WebauthnWorkspace,\n options?: WebauthnCeremonyOptions,\n): Promise<WebauthnLoginResult> {\n requireSupport('webauthnDiscoverableLogin');\n\n const { challenge, stateToken } = await client.webauthnDiscoverableStart(workspace);\n const assertion = await getAssertion(challenge, options);\n return client.webauthnDiscoverableFinish(stateToken, assertion);\n}\n\n// ---------------------------------------------------------------------------\n// Ceremony internals\n// ---------------------------------------------------------------------------\n\nfunction requireSupport(operation: string): void {\n if (!isWebauthnSupported()) {\n throw new Error(\n `${operation}: this runtime has no WebAuthn authenticator. Check isWebauthnSupported() first, ` +\n 'or use the relying-party operations on AxiamClient with a response produced elsewhere ' +\n '(CONTRACT.md §24.6).',\n );\n }\n}\n\n/** Run `navigator.credentials.create()` and return the JSON form of its answer. */\nasync function createCredential(\n challenge: WebauthnCreationChallenge,\n kind: AuthenticatorKind | undefined,\n signal: AbortSignal | undefined,\n): Promise<WebauthnRegistrationResponse> {\n const credential = (await navigator.credentials.create({\n publicKey: toCreationOptions(challenge.publicKey, kind),\n ...(signal ? { signal } : {}),\n })) as PublicKeyCredential | null;\n\n if (!credential) {\n // Spec-wise unreachable — a rejection is how failure is reported — but a\n // `null` here would otherwise become a confusing property access.\n throw new Error('webauthnRegister: the authenticator returned no credential.');\n }\n\n const response = credential.response as AuthenticatorAttestationResponse;\n const transports =\n typeof response.getTransports === 'function' ? response.getTransports() : undefined;\n\n return {\n id: credential.id,\n rawId: bytesToBase64Url(credential.rawId),\n response: {\n clientDataJSON: bytesToBase64Url(response.clientDataJSON),\n attestationObject: bytesToBase64Url(response.attestationObject),\n ...(transports && transports.length > 0 ? { transports } : {}),\n },\n type: credential.type,\n ...(credential.authenticatorAttachment\n ? { authenticatorAttachment: credential.authenticatorAttachment }\n : {}),\n clientExtensionResults: credential.getClientExtensionResults() as Record<string, unknown>,\n };\n}\n\n/** Run `navigator.credentials.get()` and return the JSON form of its answer. */\nasync function getAssertion(\n challenge: WebauthnRequestChallenge,\n options: WebauthnCeremonyOptions | undefined,\n): Promise<WebauthnAuthenticationResponse> {\n const credential = (await navigator.credentials.get({\n publicKey: toRequestOptions(challenge.publicKey),\n ...(options?.conditional ? { mediation: 'conditional' as CredentialMediationRequirement } : {}),\n ...(options?.signal ? { signal: options.signal } : {}),\n })) as PublicKeyCredential | null;\n\n if (!credential) {\n throw new Error('webauthnLogin: the authenticator returned no assertion.');\n }\n\n const response = credential.response as AuthenticatorAssertionResponse;\n return {\n id: credential.id,\n rawId: bytesToBase64Url(credential.rawId),\n response: {\n clientDataJSON: bytesToBase64Url(response.clientDataJSON),\n authenticatorData: bytesToBase64Url(response.authenticatorData),\n signature: bytesToBase64Url(response.signature),\n ...(response.userHandle ? { userHandle: bytesToBase64Url(response.userHandle) } : {}),\n },\n type: credential.type,\n ...(credential.authenticatorAttachment\n ? { authenticatorAttachment: credential.authenticatorAttachment }\n : {}),\n clientExtensionResults: credential.getClientExtensionResults() as Record<string, unknown>,\n };\n}\n\n/**\n * Transcribe the server's creation options into what the DOM API takes.\n *\n * Every optional field is forwarded **only if the server sent it** — §24.0\n * rule 1 forbids expanding an absent `authenticatorSelection` into an empty\n * object or supplying a `timeout` the server did not choose. The string enums\n * (`residentKey`, `userVerification`, `attestation`) are cast rather than\n * validated: §24.0 rule 2 says an SDK may fail to parse but must not refuse\n * options it parsed, and a client-side allow-list of acceptable values is a\n * second policy engine.\n */\nfunction toCreationOptions(\n json: WebauthnCreationOptionsJson,\n kind: AuthenticatorKind | undefined,\n): PublicKeyCredentialCreationOptions {\n const selection = json.authenticatorSelection;\n // The only place this module adds anything (§24.6 rule 4). When the caller\n // passed no kind and the server sent no selection, the key stays absent.\n const authenticatorSelection =\n selection || kind\n ? ({\n ...(selection?.residentKey ? { residentKey: selection.residentKey } : {}),\n ...(selection?.requireResidentKey !== undefined\n ? { requireResidentKey: selection.requireResidentKey }\n : {}),\n ...(selection?.userVerification\n ? { userVerification: selection.userVerification }\n : {}),\n ...(kind\n ? { authenticatorAttachment: kind }\n : selection?.authenticatorAttachment\n ? { authenticatorAttachment: selection.authenticatorAttachment }\n : {}),\n } as AuthenticatorSelectionCriteria)\n : undefined;\n\n return {\n challenge: base64UrlToBytes(json.challenge),\n rp: json.rp,\n user: {\n id: base64UrlToBytes(json.user.id),\n name: json.user.name,\n displayName: json.user.displayName,\n },\n pubKeyCredParams: json.pubKeyCredParams as PublicKeyCredentialParameters[],\n ...(json.timeout !== undefined ? { timeout: json.timeout } : {}),\n ...(json.excludeCredentials\n ? { excludeCredentials: json.excludeCredentials.map(toDescriptor) }\n : {}),\n ...(authenticatorSelection ? { authenticatorSelection } : {}),\n ...(json.attestation\n ? { attestation: json.attestation as AttestationConveyancePreference }\n : {}),\n ...(json.extensions\n ? { extensions: json.extensions as AuthenticationExtensionsClientInputs }\n : {}),\n };\n}\n\n/** The same transcription for an assertion challenge. */\nfunction toRequestOptions(json: WebauthnRequestOptionsJson): PublicKeyCredentialRequestOptions {\n return {\n challenge: base64UrlToBytes(json.challenge),\n ...(json.timeout !== undefined ? { timeout: json.timeout } : {}),\n ...(json.rpId ? { rpId: json.rpId } : {}),\n ...(json.allowCredentials\n ? { allowCredentials: json.allowCredentials.map(toDescriptor) }\n : {}),\n ...(json.userVerification\n ? { userVerification: json.userVerification as UserVerificationRequirement }\n : {}),\n ...(json.extensions\n ? { extensions: json.extensions as AuthenticationExtensionsClientInputs }\n : {}),\n };\n}\n\nfunction toDescriptor(d: WebauthnCredentialDescriptorJson): PublicKeyCredentialDescriptor {\n return {\n id: base64UrlToBytes(d.id),\n type: d.type as PublicKeyCredentialType,\n ...(d.transports ? { transports: d.transports as AuthenticatorTransport[] } : {}),\n };\n}\n"]}
1
+ {"version":3,"sources":["../../src/browser/base64url.ts","../../src/rest/webauthnErrors.ts","../../src/browser/webauthn.ts"],"names":[],"mappings":";;;AAsBO,SAAS,iBAAiB,KAAA,EAAwC;AACvE,EAAA,MAAM,MAAA,GAAS,MAAM,OAAA,CAAQ,IAAA,EAAM,GAAG,CAAA,CAAE,OAAA,CAAQ,MAAM,GAAG,CAAA;AACzD,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,MAAA,CAAO,MAAA,CAAO,IAAA,CAAK,IAAA,CAAK,MAAA,CAAO,MAAA,GAAS,CAAC,CAAA,GAAI,CAAA,EAAG,GAAG,CAAC,CAAA;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AA,CAAK,kBAAA,CAAmB,GAAA,CAAI,YAAY,CAAA,EAAE,GAChE,EAAC;AAAA,IACL,GAAI,sBAAA,GAAyB,EAAE,sBAAA,KAA2B,EAAC;AAAA,IAC3D,GAAI,KAAK,WAAA,GACL,EAAE,aAAa,IAAA,CAAK,WAAA,KACpB,EAAC;AAAA,IACL,GAAI,KAAK,UAAA,GACL,EAAE,YAAY,IAAA,CAAK,UAAA,KACnB;AAAC,GACP;AACF;AAGA,SAAS,iBAAiB,IAAA,EAAqE;AAC7F,EAAA,OAAO;AAAA,IACL,SAAA,EAAW,gBAAA,CAAiB,IAAA,CAAK,SAAS,CAAA;AAAA,IAC1C,GAAI,KAAK,OAAA,KAAY,MAAA,GAAY,EAAE,OAAA,EAAS,IAAA,CAAK,OAAA,EAAQ,GAAI,EAAC;AAAA,IAC9D,GAAI,KAAK,IAAA,GAAO,EAAE,MAAM,IAAA,CAAK,IAAA,KAAS,EAAC;AAAA,IACvC,GAAI,IAAA,CAAK,gBAAA,GACL,EAAE,gBAAA,EAAkB,IAAA,CAAK,gBAAA,CAAiB,GAAA,CAAI,YAAY,CAAA,EAAE,GAC5D,EAAC;AAAA,IACL,GAAI,KAAK,gBAAA,GACL,EAAE,kBAAkB,IAAA,CAAK,gBAAA,KACzB,EAAC;AAAA,IACL,GAAI,KAAK,UAAA,GACL,EAAE,YAAY,IAAA,CAAK,UAAA,KACnB;AAAC,GACP;AACF;AAEA,SAAS,aAAa,CAAA,EAAoE;AACxF,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,gBAAA,CAAiB,CAAA,CAAE,EAAE,CAAA;AAAA,IACzB,MAAM,CAAA,CAAE,IAAA;AAAA,IACR,GAAI,EAAE,UAAA,GAAa,EAAE,YAAY,CAAA,CAAE,UAAA,KAA2C;AAAC,GACjF;AACF","file":"index.js","sourcesContent":["// base64url ⇄ ArrayBuffer, for the WebAuthn JSON form (CONTRACT.md §24.6).\n//\n// Hand-rolled rather than pulled from `@simplewebauthn/browser`, which is what\n// the AXIAM admin UI uses. The conversion is thirty lines and fully specified\n// by RFC 4648 §5; a runtime dependency on every consumer's bundle to avoid\n// writing them, in a package whose whole job is to add as little as possible\n// to a browser bundle, is the wrong trade. The test file pins both directions\n// against fixed vectors, including the padding cases that are the only part\n// anyone gets wrong.\n//\n// Every buffer in a WebAuthn JSON message is base64url, **unpadded**. We\n// accept padding on the way in, because a server or a library that emits it is\n// not wrong, and never emit it on the way out.\n\n/**\n * Decode an unpadded (or padded) base64url string to bytes.\n *\n * Typed `Uint8Array<ArrayBuffer>` rather than the bare `Uint8Array`, whose\n * default parameter is `ArrayBufferLike` and therefore admits\n * `SharedArrayBuffer` — which `BufferSource`, and so every WebAuthn DOM\n * option, does not. The buffer is freshly allocated here and is never shared.\n */\nexport function base64UrlToBytes(value: string): Uint8Array<ArrayBuffer> {\n const padded = value.replace(/-/g, '+').replace(/_/g, '/');\n const binary = atob(padded.padEnd(Math.ceil(padded.length / 4) * 4, '='));\n const bytes = new Uint8Array(new ArrayBuffer(binary.length));\n for (let i = 0; i < binary.length; i += 1) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\n/** Encode bytes as unpadded base64url. */\nexport function bytesToBase64Url(buffer: ArrayBuffer | Uint8Array): string {\n const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);\n let binary = '';\n // Chunked: `String.fromCharCode(...bytes)` blows the argument limit on an\n // attestation object, which is routinely a few kilobytes.\n const CHUNK = 0x8000;\n for (let i = 0; i < bytes.length; i += CHUNK) {\n binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n","// Ceremony failure classification (CONTRACT.md §24.6b rule 5).\n//\n// Isomorphic on purpose. §24.6b rule 5's closing paragraph puts this in the\n// core rather than beside the linked-API helper: an Android app catching a\n// `CreateCredentialException`, or a Node service handed an error string by the\n// handset that ran the ceremony, has the same five outcomes and the same reason\n// to want one vocabulary for them. Nothing here touches the DOM — it reads the\n// error's `name`, which is the only machine-readable part any platform gives.\n\n/**\n * A ceremony failure a caller can say something useful about.\n *\n * Five outcomes, and the interesting ones are the first two.\n */\nexport type WebauthnFailure =\n | 'cancelled'\n | 'already_registered'\n | 'timeout'\n | 'unsupported'\n | 'unknown';\n\n/**\n * Map a platform ceremony error to its canonical classification (§24.6b rule 5).\n *\n * Accepts anything: a browser `DOMException`, an Android\n * `CreateCredentialException` name relayed as a string, an\n * `ASAuthorizationError` code relayed by name. Everything unrecognized is\n * `unknown` rather than a throw — a classifier that can fail is one more thing\n * for an error handler to handle.\n */\nexport function classifyWebauthnError(err: unknown): WebauthnFailure {\n const name = errorName(err);\n switch (name) {\n // NotAllowedError covers BOTH an explicit refusal and a silent timeout.\n // The spec deliberately refuses to distinguish them, because telling a\n // website which one happened leaks whether an authenticator was present.\n // \"cancelled\" is therefore the honest label for both — and it must not be\n // recovered by timing the call.\n case 'NotAllowedError':\n case 'canceled':\n case 'cancelled':\n return 'cancelled';\n // The authenticator already holds a credential for this account: the\n // server sent it in `excludeCredentials` and the authenticator refused to\n // silently mint a second. That is the exclusion list working, not a\n // failure — and it is the only classification whose remedy is \"use a\n // different device\" rather than \"try again\".\n case 'InvalidStateError':\n return 'already_registered';\n case 'AbortError':\n case 'timeout':\n return 'timeout';\n case 'NotSupportedError':\n case 'SecurityError':\n return 'unsupported';\n default:\n return 'unknown';\n }\n}\n\n/**\n * Copy for each failure, safe to show a user.\n *\n * The `cancelled` string deliberately does not accuse anyone of cancelling: the\n * same classification covers a silent timeout, and the spec will not say which\n * happened.\n */\nexport function webauthnErrorMessage(failure: WebauthnFailure): string {\n switch (failure) {\n case 'cancelled':\n return 'The request was cancelled or timed out. You can try again.';\n case 'already_registered':\n return 'This device is already registered on your account. Try a different device, or remove the existing one first.';\n case 'timeout':\n return 'The request timed out before it completed. Please try again.';\n case 'unsupported':\n return 'This browser or device cannot be used for passkeys. Try a different browser, or use another sign-in method.';\n case 'unknown':\n return 'Something went wrong. Please try again.';\n }\n}\n\n/** The platform's own error name, however it arrived. */\nfunction errorName(err: unknown): string | undefined {\n if (typeof err === 'string') return err;\n if (typeof err !== 'object' || err === null) return undefined;\n const name = (err as { name?: unknown }).name;\n return typeof name === 'string' ? name : undefined;\n}\n","// The WebAuthn platform ceremony (CONTRACT.md §24.6).\n//\n// This is the half of a passkey ceremony that talks to an *authenticator*, and\n// the only half that needs a browser. It lives on its own subpath so the\n// isomorphic `/rest` core stays free of DOM code: a Node consumer gets the\n// §24.1 relying-party layer and nothing here, which is §24.7's posture for the\n// Node build stated as a module boundary rather than as a runtime throw.\n//\n// ## What this module is allowed to change, which is almost nothing\n//\n// §24.0: the server picks every option and verifies every response, so the\n// options reach `navigator.credentials` as the server sent them and the\n// authenticator's answer goes back untouched. The two things that happen here\n// look like exceptions and are not:\n//\n// 1. **base64url → ArrayBuffer.** The DOM API takes `BufferSource` where the\n// JSON form carries a base64url string. Those are the same bytes in the\n// representation each side demands, which is a transcription, not an\n// adjustment. Nothing is defaulted, dropped, reordered or re-derived —\n// the round-trip test asserts exactly that.\n// 2. **`authenticatorAttachment`.** §24.6 rule 4's single permitted\n// addition, and only from an explicit caller argument. It selects which\n// authenticator the user is prompted for; it cannot weaken what the\n// server will accept. Without it, a user who asked for a security key is\n// prompted for the platform biometric instead.\n\nimport type {\n AxiamClient,\n LoginResult,\n Sensitive,\n WebauthnAuthenticationResponse,\n WebauthnCreationChallenge,\n WebauthnCreationOptionsJson,\n WebauthnCredential,\n WebauthnCredentialDescriptorJson,\n WebauthnLoginResult,\n WebauthnRegistrationResponse,\n WebauthnRequestChallenge,\n WebauthnRequestOptionsJson,\n WebauthnWorkspace,\n} from '../rest/index.js';\nimport { base64UrlToBytes, bytesToBase64Url } from './base64url.js';\n\n// §24.6b rule 5's classification lives in the isomorphic core, not here: an\n// Android app catching a `CreateCredentialException` wants the same vocabulary,\n// and it never loads this module. Re-exported so a browser consumer still finds\n// it on the subpath it is already importing from.\nexport { classifyWebauthnError, webauthnErrorMessage } from '../rest/index.js';\nexport type { WebauthnFailure } from '../rest/index.js';\n\n// ---------------------------------------------------------------------------\n// Feature detection (§24.6 rule 6)\n// ---------------------------------------------------------------------------\n\n/**\n * Whether this runtime can perform a WebAuthn ceremony at all.\n *\n * A query, not an exception (§24.6 rule 6) — a caller hides the enrolment\n * button rather than offering one that throws. Answers `false` in Node, where\n * the §24.1 relying-party layer still works fine.\n */\nexport function isWebauthnSupported(): boolean {\n return (\n typeof globalThis !== 'undefined' &&\n typeof (globalThis as { PublicKeyCredential?: unknown }).PublicKeyCredential !== 'undefined' &&\n typeof navigator !== 'undefined' &&\n typeof navigator.credentials?.get === 'function'\n );\n}\n\n/**\n * Whether this browser supports **conditional mediation** — passkey autofill,\n * where saved passkeys are offered from inside the username field rather than\n * behind a button.\n *\n * Returns `false` rather than throwing where the probe itself is missing\n * (§24.6 rule 3): conditional UI is a progressive enhancement, and its absence\n * must degrade to the explicit prompt, never to a broken sign-in page.\n */\nexport async function isConditionalMediationAvailable(): Promise<boolean> {\n if (!isWebauthnSupported()) return false;\n const ctor = (globalThis as { PublicKeyCredential?: { isConditionalMediationAvailable?: unknown } })\n .PublicKeyCredential;\n const probe = ctor?.isConditionalMediationAvailable;\n if (typeof probe !== 'function') return false;\n try {\n return await (probe as () => Promise<boolean>).call(ctor);\n } catch {\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Composed helpers (§24.6 rule 1 — additive; the six wire ops stay public)\n// ---------------------------------------------------------------------------\n\n/**\n * Which kind of authenticator the user reached for.\n *\n * A hint only (§24.6 rule 4). `platform` is a passkey built into the device\n * (Touch ID, Windows Hello, a phone); `cross-platform` is a removable security\n * key.\n */\nexport type AuthenticatorKind = 'platform' | 'cross-platform';\n\n/** Options shared by the two sign-in helpers. */\nexport interface WebauthnCeremonyOptions {\n /**\n * Use conditional mediation (passkey autofill) instead of a modal prompt.\n *\n * The returned promise may never settle — the user simply may not pick a\n * passkey — so a caller using this must be prepared to abandon it, and MUST\n * NOT surface an abandoned ceremony as an authentication failure (§24.6\n * rule 3). The browser aborts it when the page navigates.\n */\n conditional?: boolean;\n /** Abort the ceremony. Also how a conditional ceremony is abandoned. */\n signal?: AbortSignal;\n}\n\n/**\n * Enrol a passkey or security key for the signed-in user (§24.6).\n *\n * Runs the full ceremony: `register/start`, the authenticator, then\n * `register/finish`. The three steps stay individually callable on\n * `AxiamClient` — a caller driving a virtual authenticator in a test needs the\n * pair directly, which is why this helper is additive rather than the only way\n * in (§24.6 rule 1).\n *\n * @param kind optional `authenticatorAttachment` hint. Omitted entirely when\n * not passed — the SDK never infers it and never defaults it.\n */\nexport async function webauthnRegister(\n client: AxiamClient,\n credentialName: string,\n kind?: AuthenticatorKind,\n options?: WebauthnCeremonyOptions,\n): Promise<WebauthnCredential> {\n requireSupport('webauthnRegister');\n\n const { challenge, stateToken } = await client.webauthnRegisterStart();\n const credential = await createCredential(challenge, kind, options?.signal);\n return client.webauthnRegisterFinish(stateToken, credentialName, credential);\n}\n\n/**\n * Enrol a passkey or security key as the account's **first** factor, during\n * forced login setup (§24.6, contract 1.45) — the setup-token twin of\n * {@link webauthnRegister}, reached where `mfaSetupEnroll`/`mfaSetupConfirm`'s\n * TOTP path is reached: `login()` answered `mfa_setup_required` because the\n * tenant requires MFA and this account has none.\n *\n * Runs the full ceremony: `setup/register/start`, the authenticator, then\n * `setup/register/finish` — which, unlike `webauthnRegisterFinish`,\n * adopts credentials and completes the interrupted login (§25.2 rule 2,\n * mirrored). The pair stays individually callable on `AxiamClient` for the\n * same reason {@link webauthnRegister} is additive rather than the only way\n * in (§24.6 rule 1).\n *\n * @param setupToken the token from `login()`'s `mfa_setup_required` outcome.\n * @param kind optional `authenticatorAttachment` hint. Omitted entirely when\n * not passed — the SDK never infers it and never defaults it.\n */\nexport async function webauthnSetupRegister(\n client: AxiamClient,\n setupToken: Sensitive<string> | string,\n credentialName: string,\n kind?: AuthenticatorKind,\n options?: WebauthnCeremonyOptions,\n): Promise<LoginResult> {\n requireSupport('webauthnSetupRegister');\n\n const { challenge, stateToken } = await client.webauthnSetupRegisterStart(setupToken);\n const credential = await createCredential(challenge, kind, options?.signal);\n return client.webauthnSetupRegisterFinish(setupToken, stateToken, credentialName, credential);\n}\n\n/**\n * Sign in with a passkey as a **second factor** (§24.6).\n *\n * `challengeToken` is the `mfaToken` from a `login()` that answered\n * `mfa_required` with `\"webauthn\"` among its methods.\n */\nexport async function webauthnLogin(\n client: AxiamClient,\n challengeToken: string,\n options?: WebauthnCeremonyOptions,\n): Promise<WebauthnLoginResult> {\n requireSupport('webauthnLogin');\n\n const { challenge, stateToken } = await client.webauthnAuthenticateStart(challengeToken);\n const assertion = await getAssertion(challenge, options);\n return client.webauthnAuthenticateFinish(stateToken, assertion);\n}\n\n/**\n * Sign in with a passkey **without typing a username first** (§24.6).\n *\n * The workspace still has to be named — a discoverable credential is resolved\n * inside one tenant — but it comes from the client's own configuration unless\n * overridden, and slugs are accepted.\n */\nexport async function webauthnDiscoverableLogin(\n client: AxiamClient,\n workspace?: WebauthnWorkspace,\n options?: WebauthnCeremonyOptions,\n): Promise<WebauthnLoginResult> {\n requireSupport('webauthnDiscoverableLogin');\n\n const { challenge, stateToken } = await client.webauthnDiscoverableStart(workspace);\n const assertion = await getAssertion(challenge, options);\n return client.webauthnDiscoverableFinish(stateToken, assertion);\n}\n\n// ---------------------------------------------------------------------------\n// Ceremony internals\n// ---------------------------------------------------------------------------\n\nfunction requireSupport(operation: string): void {\n if (!isWebauthnSupported()) {\n throw new Error(\n `${operation}: this runtime has no WebAuthn authenticator. Check isWebauthnSupported() first, ` +\n 'or use the relying-party operations on AxiamClient with a response produced elsewhere ' +\n '(CONTRACT.md §24.6).',\n );\n }\n}\n\n/** Run `navigator.credentials.create()` and return the JSON form of its answer. */\nasync function createCredential(\n challenge: WebauthnCreationChallenge,\n kind: AuthenticatorKind | undefined,\n signal: AbortSignal | undefined,\n): Promise<WebauthnRegistrationResponse> {\n const credential = (await navigator.credentials.create({\n publicKey: toCreationOptions(challenge.publicKey, kind),\n ...(signal ? { signal } : {}),\n })) as PublicKeyCredential | null;\n\n if (!credential) {\n // Spec-wise unreachable — a rejection is how failure is reported — but a\n // `null` here would otherwise become a confusing property access.\n throw new Error('webauthnRegister: the authenticator returned no credential.');\n }\n\n const response = credential.response as AuthenticatorAttestationResponse;\n const transports =\n typeof response.getTransports === 'function' ? response.getTransports() : undefined;\n\n return {\n id: credential.id,\n rawId: bytesToBase64Url(credential.rawId),\n response: {\n clientDataJSON: bytesToBase64Url(response.clientDataJSON),\n attestationObject: bytesToBase64Url(response.attestationObject),\n ...(transports && transports.length > 0 ? { transports } : {}),\n },\n type: credential.type,\n ...(credential.authenticatorAttachment\n ? { authenticatorAttachment: credential.authenticatorAttachment }\n : {}),\n clientExtensionResults: credential.getClientExtensionResults() as Record<string, unknown>,\n };\n}\n\n/** Run `navigator.credentials.get()` and return the JSON form of its answer. */\nasync function getAssertion(\n challenge: WebauthnRequestChallenge,\n options: WebauthnCeremonyOptions | undefined,\n): Promise<WebauthnAuthenticationResponse> {\n const credential = (await navigator.credentials.get({\n publicKey: toRequestOptions(challenge.publicKey),\n ...(options?.conditional ? { mediation: 'conditional' as CredentialMediationRequirement } : {}),\n ...(options?.signal ? { signal: options.signal } : {}),\n })) as PublicKeyCredential | null;\n\n if (!credential) {\n throw new Error('webauthnLogin: the authenticator returned no assertion.');\n }\n\n const response = credential.response as AuthenticatorAssertionResponse;\n return {\n id: credential.id,\n rawId: bytesToBase64Url(credential.rawId),\n response: {\n clientDataJSON: bytesToBase64Url(response.clientDataJSON),\n authenticatorData: bytesToBase64Url(response.authenticatorData),\n signature: bytesToBase64Url(response.signature),\n ...(response.userHandle ? { userHandle: bytesToBase64Url(response.userHandle) } : {}),\n },\n type: credential.type,\n ...(credential.authenticatorAttachment\n ? { authenticatorAttachment: credential.authenticatorAttachment }\n : {}),\n clientExtensionResults: credential.getClientExtensionResults() as Record<string, unknown>,\n };\n}\n\n/**\n * Transcribe the server's creation options into what the DOM API takes.\n *\n * Every optional field is forwarded **only if the server sent it** — §24.0\n * rule 1 forbids expanding an absent `authenticatorSelection` into an empty\n * object or supplying a `timeout` the server did not choose. The string enums\n * (`residentKey`, `userVerification`, `attestation`) are cast rather than\n * validated: §24.0 rule 2 says an SDK may fail to parse but must not refuse\n * options it parsed, and a client-side allow-list of acceptable values is a\n * second policy engine.\n */\nfunction toCreationOptions(\n json: WebauthnCreationOptionsJson,\n kind: AuthenticatorKind | undefined,\n): PublicKeyCredentialCreationOptions {\n const selection = json.authenticatorSelection;\n // The only place this module adds anything (§24.6 rule 4). When the caller\n // passed no kind and the server sent no selection, the key stays absent.\n const authenticatorSelection =\n selection || kind\n ? ({\n ...(selection?.residentKey ? { residentKey: selection.residentKey } : {}),\n ...(selection?.requireResidentKey !== undefined\n ? { requireResidentKey: selection.requireResidentKey }\n : {}),\n ...(selection?.userVerification\n ? { userVerification: selection.userVerification }\n : {}),\n ...(kind\n ? { authenticatorAttachment: kind }\n : selection?.authenticatorAttachment\n ? { authenticatorAttachment: selection.authenticatorAttachment }\n : {}),\n } as AuthenticatorSelectionCriteria)\n : undefined;\n\n return {\n challenge: base64UrlToBytes(json.challenge),\n rp: json.rp,\n user: {\n id: base64UrlToBytes(json.user.id),\n name: json.user.name,\n displayName: json.user.displayName,\n },\n pubKeyCredParams: json.pubKeyCredParams as PublicKeyCredentialParameters[],\n ...(json.timeout !== undefined ? { timeout: json.timeout } : {}),\n ...(json.excludeCredentials\n ? { excludeCredentials: json.excludeCredentials.map(toDescriptor) }\n : {}),\n ...(authenticatorSelection ? { authenticatorSelection } : {}),\n ...(json.attestation\n ? { attestation: json.attestation as AttestationConveyancePreference }\n : {}),\n ...(json.extensions\n ? { extensions: json.extensions as AuthenticationExtensionsClientInputs }\n : {}),\n };\n}\n\n/** The same transcription for an assertion challenge. */\nfunction toRequestOptions(json: WebauthnRequestOptionsJson): PublicKeyCredentialRequestOptions {\n return {\n challenge: base64UrlToBytes(json.challenge),\n ...(json.timeout !== undefined ? { timeout: json.timeout } : {}),\n ...(json.rpId ? { rpId: json.rpId } : {}),\n ...(json.allowCredentials\n ? { allowCredentials: json.allowCredentials.map(toDescriptor) }\n : {}),\n ...(json.userVerification\n ? { userVerification: json.userVerification as UserVerificationRequirement }\n : {}),\n ...(json.extensions\n ? { extensions: json.extensions as AuthenticationExtensionsClientInputs }\n : {}),\n };\n}\n\nfunction toDescriptor(d: WebauthnCredentialDescriptorJson): PublicKeyCredentialDescriptor {\n return {\n id: base64UrlToBytes(d.id),\n type: d.type as PublicKeyCredentialType,\n ...(d.transports ? { transports: d.transports as AuthenticatorTransport[] } : {}),\n };\n}\n"]}
@@ -90,6 +90,12 @@ async function webauthnRegister(client, credentialName, kind, options) {
90
90
  const credential = await createCredential(challenge, kind, options?.signal);
91
91
  return client.webauthnRegisterFinish(stateToken, credentialName, credential);
92
92
  }
93
+ async function webauthnSetupRegister(client, setupToken, credentialName, kind, options) {
94
+ requireSupport("webauthnSetupRegister");
95
+ const { challenge, stateToken } = await client.webauthnSetupRegisterStart(setupToken);
96
+ const credential = await createCredential(challenge, kind, options?.signal);
97
+ return client.webauthnSetupRegisterFinish(setupToken, stateToken, credentialName, credential);
98
+ }
93
99
  async function webauthnLogin(client, challengeToken, options) {
94
100
  requireSupport("webauthnLogin");
95
101
  const { challenge, stateToken } = await client.webauthnAuthenticateStart(challengeToken);
@@ -198,6 +204,6 @@ function toDescriptor(d) {
198
204
  };
199
205
  }
200
206
 
201
- export { base64UrlToBytes, bytesToBase64Url, classifyWebauthnError, isConditionalMediationAvailable, isWebauthnSupported, webauthnDiscoverableLogin, webauthnErrorMessage, webauthnLogin, webauthnRegister };
207
+ export { base64UrlToBytes, bytesToBase64Url, classifyWebauthnError, isConditionalMediationAvailable, isWebauthnSupported, webauthnDiscoverableLogin, webauthnErrorMessage, webauthnLogin, webauthnRegister, webauthnSetupRegister };
202
208
  //# sourceMappingURL=index.mjs.map
203
209
  //# sourceMapp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n//\n// Hand-rolled rather than pulled from `@simplewebauthn/browser`, which is what\n// the AXIAM admin UI uses. The conversion is thirty lines and fully specified\n// by RFC 4648 §5; a runtime dependency on every consumer's bundle to avoid\n// writing them, in a package whose whole job is to add as little as possible\n// to a browser bundle, is the wrong trade. The test file pins both directions\n// against fixed vectors, including the padding cases that are the only part\n// anyone gets wrong.\n//\n// Every buffer in a WebAuthn JSON message is base64url, **unpadded**. We\n// accept padding on the way in, because a server or a library that emits it is\n// not wrong, and never emit it on the way out.\n\n/**\n * Decode an unpadded (or padded) base64url string to bytes.\n *\n * Typed `Uint8Array<ArrayBuffer>` rather than the bare `Uint8Array`, whose\n * default parameter is `ArrayBufferLike` and therefore admits\n * `SharedArrayBuffer` — which `BufferSource`, and so every WebAuthn DOM\n * option, does not. The buffer is freshly allocated here and is never shared.\n */\nexport function base64UrlToBytes(value: string): Uint8Array<ArrayBuffer> {\n const padded = value.replace(/-/g, '+').replace(/_/g, '/');\n const binary = atob(padded.padEnd(Math.ceil(padded.length / 4) * 4, '='));\n const bytes = new Uint8Array(new ArrayBuffer(binary.length));\n for (let i = 0; i < binary.length; i += 1) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\n/** Encode bytes as unpadded base64url. */\nexport function bytesToBase64Url(buffer: ArrayBuffer | Uint8Array): string {\n const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);\n let binary = '';\n // Chunked: `String.fromCharCode(...bytes)` blows the argument limit on an\n // attestation object, which is routinely a few kilobytes.\n const CHUNK = 0x8000;\n for (let i = 0; i < bytes.length; i += CHUNK) {\n binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n","// Ceremony failure classification (CONTRACT.md §24.6b rule 5).\n//\n// Isomorphic on purpose. §24.6b rule 5's closing paragraph puts this in the\n// core rather than beside the linked-API helper: an Android app catching a\n// `CreateCredentialException`, or a Node service handed an error string by the\n// handset that ran the ceremony, has the same five outcomes and the same reason\n// to want one vocabulary for them. Nothing here touches the DOM — it reads the\n// error's `name`, which is the only machine-readable part any platform gives.\n\n/**\n * A ceremony failure a caller can say something useful about.\n *\n * Five outcomes, and the interesting ones are the first two.\n */\nexport type WebauthnFailure =\n | 'cancelled'\n | 'already_registered'\n | 'timeout'\n | 'unsupported'\n | 'unknown';\n\n/**\n * Map a platform ceremony error to its canonical classification (§24.6b rule 5).\n *\n * Accepts anything: a browser `DOMException`, an Android\n * `CreateCredentialException` name relayed as a string, an\n * `ASAuthorizationError` code relayed by name. Everything unrecognized is\n * `unknown` rather than a throw — a classifier that can fail is one more thing\n * for an error handler to handle.\n */\nexport function classifyWebauthnError(err: unknown): WebauthnFailure {\n const name = errorName(err);\n switch (name) {\n // NotAllowedError covers BOTH an explicit refusal and a silent timeout.\n // The spec deliberately refuses to distinguish them, because telling a\n // website which one happened leaks whether an authenticator was present.\n // \"cancelled\" is therefore the honest label for both — and it must not be\n // recovered by timing the call.\n case 'NotAllowedError':\n case 'canceled':\n case 'cancelled':\n return 'cancelled';\n // The authenticator already holds a credential for this account: the\n // server sent it in `excludeCredentials` and the authenticator refused to\n // silently mint a second. That is the exclusion list working, not a\n // failure — and it is the only classification whose remedy is \"use a\n // different device\" rather than \"try again\".\n case 'InvalidStateError':\n return 'already_registered';\n case 'AbortError':\n case 'timeout':\n return 'timeout';\n case 'NotSupportedError':\n case 'SecurityError':\n return 'unsupported';\n default:\n return 'unknown';\n }\n}\n\n/**\n * Copy for each failure, safe to show a user.\n *\n * The `cancelled` string deliberately does not accuse anyone of cancelling: the\n * same classification covers a silent timeout, and the spec will not say which\n * happened.\n */\nexport function webauthnErrorMessage(failure: WebauthnFailure): string {\n switch (failure) {\n case 'cancelled':\n return 'The request was cancelled or timed out. You can try again.';\n case 'already_registered':\n return 'This device is already registered on your account. Try a different device, or remove the existing one first.';\n case 'timeout':\n return 'The request timed out before it completed. Please try again.';\n case 'unsupported':\n return 'This browser or device cannot be used for passkeys. Try a different browser, or use another sign-in method.';\n case 'unknown':\n return 'Something went wrong. Please try again.';\n }\n}\n\n/** The platform's own error name, however it arrived. */\nfunction errorName(err: unknown): string | undefined {\n if (typeof err === 'string') return err;\n if (typeof err !== 'object' || err === null) return undefined;\n const name = (err as { name?: unknown }).name;\n return typeof name === 'string' ? name : undefined;\n}\n","// The WebAuthn platform ceremony (CONTRACT.md §24.6).\n//\n// This is the half of a passkey ceremony that talks to an *authenticator*, and\n// the only half that needs a browser. It lives on its own subpath so the\n// isomorphic `/rest` core stays free of DOM code: a Node consumer gets the\n// §24.1 relying-party layer and nothing here, which is §24.7's posture for the\n// Node build stated as a module boundary rather than as a runtime throw.\n//\n// ## What this module is allowed to change, which is almost nothing\n//\n// §24.0: the server picks every option and verifies every response, so the\n// options reach `navigator.credentials` as the server sent them and the\n// authenticator's answer goes back untouched. The two things that happen here\n// look like exceptions and are not:\n//\n// 1. **base64url → ArrayBuffer.** The DOM API takes `BufferSource` where the\n// JSON form carries a base64url string. Those are the same bytes in the\n// representation each side demands, which is a transcription, not an\n// adjustment. Nothing is defaulted, dropped, reordered or re-derived —\n// the round-trip test asserts exactly that.\n// 2. **`authenticatorAttachment`.** §24.6 rule 4's single permitted\n// addition, and only from an explicit caller argument. It selects which\n// authenticator the user is prompted for; it cannot weaken what the\n// server will accept. Without it, a user who asked for a security key is\n// prompted for the platform biometric instead.\n\nimport type {\n AxiamClient,\n WebauthnAuthenticationResponse,\n WebauthnCreationChallenge,\n WebauthnCreationOptionsJson,\n WebauthnCredential,\n WebauthnCredentialDescriptorJson,\n WebauthnLoginResult,\n WebauthnRegistrationResponse,\n WebauthnRequestChallenge,\n WebauthnRequestOptionsJson,\n WebauthnWorkspace,\n} from '../rest/index.js';\nimport { base64UrlToBytes, bytesToBase64Url } from './base64url.js';\n\n// §24.6b rule 5's classification lives in the isomorphic core, not here: an\n// Android app catching a `CreateCredentialException` wants the same vocabulary,\n// and it never loads this module. Re-exported so a browser consumer still finds\n// it on the subpath it is already importing from.\nexport { classifyWebauthnError, webauthnErrorMessage } from '../rest/index.js';\nexport type { WebauthnFailure } from '../rest/index.js';\n\n// ---------------------------------------------------------------------------\n// Feature detection (§24.6 rule 6)\n// ---------------------------------------------------------------------------\n\n/**\n * Whether this runtime can perform a WebAuthn ceremony at all.\n *\n * A query, not an exception (§24.6 rule 6) — a caller hides the enrolment\n * button rather than offering one that throws. Answers `false` in Node, where\n * the §24.1 relying-party layer still works fine.\n */\nexport function isWebauthnSupported(): boolean {\n return (\n typeof globalThis !== 'undefined' &&\n typeof (globalThis as { PublicKeyCredential?: unknown }).PublicKeyCredential !== 'undefined' &&\n typeof navigator !== 'undefined' &&\n typeof navigator.credentials?.get === 'function'\n );\n}\n\n/**\n * Whether this browser supports **conditional mediation** — passkey autofill,\n * where saved passkeys are offered from inside the username field rather than\n * behind a button.\n *\n * Returns `false` rather than throwing where the probe itself is missing\n * (§24.6 rule 3): conditional UI is a progressive enhancement, and its absence\n * must degrade to the explicit prompt, never to a broken sign-in page.\n */\nexport async function isConditionalMediationAvailable(): Promise<boolean> {\n if (!isWebauthnSupported()) return false;\n const ctor = (globalThis as { PublicKeyCredential?: { isConditionalMediationAvailable?: unknown } })\n .PublicKeyCredential;\n const probe = ctor?.isConditionalMediationAvailable;\n if (typeof probe !== 'function') return false;\n try {\n return await (probe as () => Promise<boolean>).call(ctor);\n } catch {\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Composed helpers (§24.6 rule 1 — additive; the six wire ops stay public)\n// ---------------------------------------------------------------------------\n\n/**\n * Which kind of authenticator the user reached for.\n *\n * A hint only (§24.6 rule 4). `platform` is a passkey built into the device\n * (Touch ID, Windows Hello, a phone); `cross-platform` is a removable security\n * key.\n */\nexport type AuthenticatorKind = 'platform' | 'cross-platform';\n\n/** Options shared by the two sign-in helpers. */\nexport interface WebauthnCeremonyOptions {\n /**\n * Use conditional mediation (passkey autofill) instead of a modal prompt.\n *\n * The returned promise may never settle — the user simply may not pick a\n * passkey — so a caller using this must be prepared to abandon it, and MUST\n * NOT surface an abandoned ceremony as an authentication failure (§24.6\n * rule 3). The browser aborts it when the page navigates.\n */\n conditional?: boolean;\n /** Abort the ceremony. Also how a conditional ceremony is abandoned. */\n signal?: AbortSignal;\n}\n\n/**\n * Enrol a passkey or security key for the signed-in user (§24.6).\n *\n * Runs the full ceremony: `register/start`, the authenticator, then\n * `register/finish`. The three steps stay individually callable on\n * `AxiamClient` — a caller driving a virtual authenticator in a test needs the\n * pair directly, which is why this helper is additive rather than the only way\n * in (§24.6 rule 1).\n *\n * @param kind optional `authenticatorAttachment` hint. Omitted entirely when\n * not passed — the SDK never infers it and never defaults it.\n */\nexport async function webauthnRegister(\n client: AxiamClient,\n credentialName: string,\n kind?: AuthenticatorKind,\n options?: WebauthnCeremonyOptions,\n): Promise<WebauthnCredential> {\n requireSupport('webauthnRegister');\n\n const { challenge, stateToken } = await client.webauthnRegisterStart();\n const credential = await createCredential(challenge, kind, options?.signal);\n return client.webauthnRegisterFinish(stateToken, credentialName, credential);\n}\n\n/**\n * Sign in with a passkey as a **second factor** (§24.6).\n *\n * `challengeToken` is the `mfaToken` from a `login()` that answered\n * `mfa_required` with `\"webauthn\"` among its methods.\n */\nexport async function webauthnLogin(\n client: AxiamClient,\n challengeToken: string,\n options?: WebauthnCeremonyOptions,\n): Promise<WebauthnLoginResult> {\n requireSupport('webauthnLogin');\n\n const { challenge, stateToken } = await client.webauthnAuthenticateStart(challengeToken);\n const assertion = await getAssertion(challenge, options);\n return client.webauthnAuthenticateFinish(stateToken, assertion);\n}\n\n/**\n * Sign in with a passkey **without typing a username first** (§24.6).\n *\n * The workspace still has to be named — a discoverable credential is resolved\n * inside one tenant — but it comes from the client's own configuration unless\n * overridden, and slugs are accepted.\n */\nexport async function webauthnDiscoverableLogin(\n client: AxiamClient,\n workspace?: WebauthnWorkspace,\n options?: WebauthnCeremonyOptions,\n): Promise<WebauthnLoginResult> {\n requireSupport('webauthnDiscoverableLogin');\n\n const { challenge, stateToken } = await client.webauthnDiscoverableStart(workspace);\n const assertion = await getAssertion(challenge, options);\n return client.webauthnDiscoverableFinish(stateToken, assertion);\n}\n\n// ---------------------------------------------------------------------------\n// Ceremony internals\n// ---------------------------------------------------------------------------\n\nfunction requireSupport(operation: string): void {\n if (!isWebauthnSupported()) {\n throw new Error(\n `${operation}: this runtime has no WebAuthn authenticator. Check isWebauthnSupported() first, ` +\n 'or use the relying-party operations on AxiamClient with a response produced elsewhere ' +\n '(CONTRACT.md §24.6).',\n );\n }\n}\n\n/** Run `navigator.credentials.create()` and return the JSON form of its answer. */\nasync function createCredential(\n challenge: WebauthnCreationChallenge,\n kind: AuthenticatorKind | undefined,\n signal: AbortSignal | undefined,\n): Promise<WebauthnRegistrationResponse> {\n const credential = (await navigator.credentials.create({\n publicKey: toCreationOptions(challenge.publicKey, kind),\n ...(signal ? { signal } : {}),\n })) as PublicKeyCredential | null;\n\n if (!credential) {\n // Spec-wise unreachable — a rejection is how failure is reported — but a\n // `null` here would otherwise become a confusing property access.\n throw new Error('webauthnRegister: the authenticator returned no credential.');\n }\n\n const response = credential.response as AuthenticatorAttestationResponse;\n const transports =\n typeof response.getTransports === 'function' ? response.getTransports() : undefined;\n\n return {\n id: credential.id,\n rawId: bytesToBase64Url(credential.rawId),\n response: {\n clientDataJSON: bytesToBase64Url(response.clientDataJSON),\n attestationObject: bytesToBase64Url(response.attestationObject),\n ...(transports && transports.length > 0 ? { transports } : {}),\n },\n type: credential.type,\n ...(credential.authenticatorAttachment\n ? { authenticatorAttachment: credential.authenticatorAttachment }\n : {}),\n clientExtensionResults: credential.getClientExtensionResults() as Record<string, unknown>,\n };\n}\n\n/** Run `navigator.credentials.get()` and return the JSON form of its answer. */\nasync function getAssertion(\n challenge: WebauthnRequestChallenge,\n options: WebauthnCeremonyOptions | undefined,\n): Promise<WebauthnAuthenticationResponse> {\n const credential = (await navigator.credentials.get({\n publicKey: toRequestOptions(challenge.publicKey),\n ...(options?.conditional ? { mediation: 'conditional' as CredentialMediationRequirement } : {}),\n ...(options?.signal ? { signal: options.signal } : {}),\n })) as PublicKeyCredential | null;\n\n if (!credential) {\n throw new Error('webauthnLogin: the authenticator returned no assertion.');\n }\n\n const response = credential.response as AuthenticatorAssertionResponse;\n return {\n id: credential.id,\n rawId: bytesToBase64Url(credential.rawId),\n response: {\n clientDataJSON: bytesToBase64Url(response.clientDataJSON),\n authenticatorData: bytesToBase64Url(response.authenticatorData),\n signature: bytesToBase64Url(response.signature),\n ...(response.userHandle ? { userHandle: bytesToBase64Url(response.userHandle) } : {}),\n },\n type: credential.type,\n ...(credential.authenticatorAttachment\n ? { authenticatorAttachment: credential.authenticatorAttachment }\n : {}),\n clientExtensionResults: credential.getClientExtensionResults() as Record<string, unknown>,\n };\n}\n\n/**\n * Transcribe the server's creation options into what the DOM API takes.\n *\n * Every optional field is forwarded **only if the server sent it** — §24.0\n * rule 1 forbids expanding an absent `authenticatorSelection` into an empty\n * object or supplying a `timeout` the server did not choose. The string enums\n * (`residentKey`, `userVerification`, `attestation`) are cast rather than\n * validated: §24.0 rule 2 says an SDK may fail to parse but must not refuse\n * options it parsed, and a client-side allow-list of acceptable values is a\n * second policy engine.\n */\nfunction toCreationOptions(\n json: WebauthnCreationOptionsJson,\n kind: AuthenticatorKind | undefined,\n): PublicKeyCredentialCreationOptions {\n const selection = json.authenticatorSelection;\n // The only place this module adds anything (§24.6 rule 4). When the caller\n // passed no kind and the server sent no selection, the key stays absent.\n const authenticatorSelection =\n selection || kind\n ? ({\n ...(selection?.residentKey ? { residentKey: selection.residentKey } : {}),\n ...(selection?.requireResidentKey !== undefined\n ? { requireResidentKey: selection.requireResidentKey }\n : {}),\n ...(selection?.userVerification\n ? { userVerification: selection.userVerification }\n : {}),\n ...(kind\n ? { authenticatorAttachment: kind }\n : selection?.authenticatorAttachment\n ? { authenticatorAttachment: selection.authenticatorAttachment }\n : {}),\n } as AuthenticatorSelectionCriteria)\n : undefined;\n\n return {\n challenge: base64UrlToBytes(json.challenge),\n rp: json.rp,\n user: {\n id: base64UrlToBytes(json.user.id),\n name: json.user.name,\n displayName: json.user.displayName,\n },\n pubKeyCredParams: json.pubKeyCredParams as PublicKeyCredentialParameters[],\n ...(json.timeout !== undefined ? { timeout: json.timeout } : {}),\n ...(json.excludeCredentials\n ? { excludeCredentials: json.excludeCredentials.map(toDescriptor) }\n : {}),\n ...(authenticatorSelection ? { authenticatorSelection } : {}),\n ...(json.attestation\n ? { attestation: json.attestation as AttestationConveyancePreference }\n : {}),\n ...(json.extensions\n ? { extensions: json.extensions as AuthenticationExtensionsClientInputs }\n : {}),\n };\n}\n\n/** The same transcription for an assertion challenge. */\nfunction toRequestOptions(json: WebauthnRequestOptionsJson): PublicKeyCredentialRequestOptions {\n return {\n challenge: base64UrlToBytes(json.challenge),\n ...(json.timeout !== undefined ? { timeout: json.timeout } : {}),\n ...(json.rpId ? { rpId: json.rpId } : {}),\n ...(json.allowCredentials\n ? { allowCredentials: json.allowCredentials.map(toDescriptor) }\n : {}),\n ...(json.userVerification\n ? { userVerification: json.userVerification as UserVerificationRequirement }\n : {}),\n ...(json.extensions\n ? { extensions: json.extensions as AuthenticationExtensionsClientInputs }\n : {}),\n };\n}\n\nfunction toDescriptor(d: WebauthnCredentialDescriptorJson): PublicKeyCredentialDescriptor {\n return {\n id: base64UrlToBytes(d.id),\n type: d.type as PublicKeyCredentialType,\n ...(d.transports ? { transports: d.transports as AuthenticatorTransport[] } : {}),\n };\n}\n"]}
1
+ {"version":3,"sources":["../../src/browser/base64url.ts","../../src/rest/webauthnErrors.ts","../../src/browser/webauthn.ts"],"names":[],"mappings":";AAsBO,SAAS,iBAAiB,KAAA,EAAwC;AACvE,EAAA,MAAM,MAAA,GAAS,MAAM,OAAA,CAAQ,IAAA,EAAM,GAAG,CAAA,CAAE,OAAA,CAAQ,MAAM,GAAG,CAAA;AACzD,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,MAAA,CAAO,MAAA,CAAO,IAAA,CA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url ⇄ ArrayBuffer, for the WebAuthn JSON form (CONTRACT.md §24.6).\n//\n// Hand-rolled rather than pulled from `@simplewebauthn/browser`, which is what\n// the AXIAM admin UI uses. The conversion is thirty lines and fully specified\n// by RFC 4648 §5; a runtime dependency on every consumer's bundle to avoid\n// writing them, in a package whose whole job is to add as little as possible\n// to a browser bundle, is the wrong trade. The test file pins both directions\n// against fixed vectors, including the padding cases that are the only part\n// anyone gets wrong.\n//\n// Every buffer in a WebAuthn JSON message is base64url, **unpadded**. We\n// accept padding on the way in, because a server or a library that emits it is\n// not wrong, and never emit it on the way out.\n\n/**\n * Decode an unpadded (or padded) base64url string to bytes.\n *\n * Typed `Uint8Array<ArrayBuffer>` rather than the bare `Uint8Array`, whose\n * default parameter is `ArrayBufferLike` and therefore admits\n * `SharedArrayBuffer` — which `BufferSource`, and so every WebAuthn DOM\n * option, does not. The buffer is freshly allocated here and is never shared.\n */\nexport function base64UrlToBytes(value: string): Uint8Array<ArrayBuffer> {\n const padded = value.replace(/-/g, '+').replace(/_/g, '/');\n const binary = atob(padded.padEnd(Math.ceil(padded.length / 4) * 4, '='));\n const bytes = new Uint8Array(new ArrayBuffer(binary.length));\n for (let i = 0; i < binary.length; i += 1) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\n/** Encode bytes as unpadded base64url. */\nexport function bytesToBase64Url(buffer: ArrayBuffer | Uint8Array): string {\n const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);\n let binary = '';\n // Chunked: `String.fromCharCode(...bytes)` blows the argument limit on an\n // attestation object, which is routinely a few kilobytes.\n const CHUNK = 0x8000;\n for (let i = 0; i < bytes.length; i += CHUNK) {\n binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n","// Ceremony failure classification (CONTRACT.md §24.6b rule 5).\n//\n// Isomorphic on purpose. §24.6b rule 5's closing paragraph puts this in the\n// core rather than beside the linked-API helper: an Android app catching a\n// `CreateCredentialException`, or a Node service handed an error string by the\n// handset that ran the ceremony, has the same five outcomes and the same reason\n// to want one vocabulary for them. Nothing here touches the DOM — it reads the\n// error's `name`, which is the only machine-readable part any platform gives.\n\n/**\n * A ceremony failure a caller can say something useful about.\n *\n * Five outcomes, and the interesting ones are the first two.\n */\nexport type WebauthnFailure =\n | 'cancelled'\n | 'already_registered'\n | 'timeout'\n | 'unsupported'\n | 'unknown';\n\n/**\n * Map a platform ceremony error to its canonical classification (§24.6b rule 5).\n *\n * Accepts anything: a browser `DOMException`, an Android\n * `CreateCredentialException` name relayed as a string, an\n * `ASAuthorizationError` code relayed by name. Everything unrecognized is\n * `unknown` rather than a throw — a classifier that can fail is one more thing\n * for an error handler to handle.\n */\nexport function classifyWebauthnError(err: unknown): WebauthnFailure {\n const name = errorName(err);\n switch (name) {\n // NotAllowedError covers BOTH an explicit refusal and a silent timeout.\n // The spec deliberately refuses to distinguish them, because telling a\n // website which one happened leaks whether an authenticator was present.\n // \"cancelled\" is therefore the honest label for both — and it must not be\n // recovered by timing the call.\n case 'NotAllowedError':\n case 'canceled':\n case 'cancelled':\n return 'cancelled';\n // The authenticator already holds a credential for this account: the\n // server sent it in `excludeCredentials` and the authenticator refused to\n // silently mint a second. That is the exclusion list working, not a\n // failure — and it is the only classification whose remedy is \"use a\n // different device\" rather than \"try again\".\n case 'InvalidStateError':\n return 'already_registered';\n case 'AbortError':\n case 'timeout':\n return 'timeout';\n case 'NotSupportedError':\n case 'SecurityError':\n return 'unsupported';\n default:\n return 'unknown';\n }\n}\n\n/**\n * Copy for each failure, safe to show a user.\n *\n * The `cancelled` string deliberately does not accuse anyone of cancelling: the\n * same classification covers a silent timeout, and the spec will not say which\n * happened.\n */\nexport function webauthnErrorMessage(failure: WebauthnFailure): string {\n switch (failure) {\n case 'cancelled':\n return 'The request was cancelled or timed out. You can try again.';\n case 'already_registered':\n return 'This device is already registered on your account. Try a different device, or remove the existing one first.';\n case 'timeout':\n return 'The request timed out before it completed. Please try again.';\n case 'unsupported':\n return 'This browser or device cannot be used for passkeys. Try a different browser, or use another sign-in method.';\n case 'unknown':\n return 'Something went wrong. Please try again.';\n }\n}\n\n/** The platform's own error name, however it arrived. */\nfunction errorName(err: unknown): string | undefined {\n if (typeof err === 'string') return err;\n if (typeof err !== 'object' || err === null) return undefined;\n const name = (err as { name?: unknown }).name;\n return typeof name === 'string' ? name : undefined;\n}\n","// The WebAuthn platform ceremony (CONTRACT.md §24.6).\n//\n// This is the half of a passkey ceremony that talks to an *authenticator*, and\n// the only half that needs a browser. It lives on its own subpath so the\n// isomorphic `/rest` core stays free of DOM code: a Node consumer gets the\n// §24.1 relying-party layer and nothing here, which is §24.7's posture for the\n// Node build stated as a module boundary rather than as a runtime throw.\n//\n// ## What this module is allowed to change, which is almost nothing\n//\n// §24.0: the server picks every option and verifies every response, so the\n// options reach `navigator.credentials` as the server sent them and the\n// authenticator's answer goes back untouched. The two things that happen here\n// look like exceptions and are not:\n//\n// 1. **base64url → ArrayBuffer.** The DOM API takes `BufferSource` where the\n// JSON form carries a base64url string. Those are the same bytes in the\n// representation each side demands, which is a transcription, not an\n// adjustment. Nothing is defaulted, dropped, reordered or re-derived —\n// the round-trip test asserts exactly that.\n// 2. **`authenticatorAttachment`.** §24.6 rule 4's single permitted\n// addition, and only from an explicit caller argument. It selects which\n// authenticator the user is prompted for; it cannot weaken what the\n// server will accept. Without it, a user who asked for a security key is\n// prompted for the platform biometric instead.\n\nimport type {\n AxiamClient,\n LoginResult,\n Sensitive,\n WebauthnAuthenticationResponse,\n WebauthnCreationChallenge,\n WebauthnCreationOptionsJson,\n WebauthnCredential,\n WebauthnCredentialDescriptorJson,\n WebauthnLoginResult,\n WebauthnRegistrationResponse,\n WebauthnRequestChallenge,\n WebauthnRequestOptionsJson,\n WebauthnWorkspace,\n} from '../rest/index.js';\nimport { base64UrlToBytes, bytesToBase64Url } from './base64url.js';\n\n// §24.6b rule 5's classification lives in the isomorphic core, not here: an\n// Android app catching a `CreateCredentialException` wants the same vocabulary,\n// and it never loads this module. Re-exported so a browser consumer still finds\n// it on the subpath it is already importing from.\nexport { classifyWebauthnError, webauthnErrorMessage } from '../rest/index.js';\nexport type { WebauthnFailure } from '../rest/index.js';\n\n// ---------------------------------------------------------------------------\n// Feature detection (§24.6 rule 6)\n// ---------------------------------------------------------------------------\n\n/**\n * Whether this runtime can perform a WebAuthn ceremony at all.\n *\n * A query, not an exception (§24.6 rule 6) — a caller hides the enrolment\n * button rather than offering one that throws. Answers `false` in Node, where\n * the §24.1 relying-party layer still works fine.\n */\nexport function isWebauthnSupported(): boolean {\n return (\n typeof globalThis !== 'undefined' &&\n typeof (globalThis as { PublicKeyCredential?: unknown }).PublicKeyCredential !== 'undefined' &&\n typeof navigator !== 'undefined' &&\n typeof navigator.credentials?.get === 'function'\n );\n}\n\n/**\n * Whether this browser supports **conditional mediation** — passkey autofill,\n * where saved passkeys are offered from inside the username field rather than\n * behind a button.\n *\n * Returns `false` rather than throwing where the probe itself is missing\n * (§24.6 rule 3): conditional UI is a progressive enhancement, and its absence\n * must degrade to the explicit prompt, never to a broken sign-in page.\n */\nexport async function isConditionalMediationAvailable(): Promise<boolean> {\n if (!isWebauthnSupported()) return false;\n const ctor = (globalThis as { PublicKeyCredential?: { isConditionalMediationAvailable?: unknown } })\n .PublicKeyCredential;\n const probe = ctor?.isConditionalMediationAvailable;\n if (typeof probe !== 'function') return false;\n try {\n return await (probe as () => Promise<boolean>).call(ctor);\n } catch {\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Composed helpers (§24.6 rule 1 — additive; the six wire ops stay public)\n// ---------------------------------------------------------------------------\n\n/**\n * Which kind of authenticator the user reached for.\n *\n * A hint only (§24.6 rule 4). `platform` is a passkey built into the device\n * (Touch ID, Windows Hello, a phone); `cross-platform` is a removable security\n * key.\n */\nexport type AuthenticatorKind = 'platform' | 'cross-platform';\n\n/** Options shared by the two sign-in helpers. */\nexport interface WebauthnCeremonyOptions {\n /**\n * Use conditional mediation (passkey autofill) instead of a modal prompt.\n *\n * The returned promise may never settle — the user simply may not pick a\n * passkey — so a caller using this must be prepared to abandon it, and MUST\n * NOT surface an abandoned ceremony as an authentication failure (§24.6\n * rule 3). The browser aborts it when the page navigates.\n */\n conditional?: boolean;\n /** Abort the ceremony. Also how a conditional ceremony is abandoned. */\n signal?: AbortSignal;\n}\n\n/**\n * Enrol a passkey or security key for the signed-in user (§24.6).\n *\n * Runs the full ceremony: `register/start`, the authenticator, then\n * `register/finish`. The three steps stay individually callable on\n * `AxiamClient` — a caller driving a virtual authenticator in a test needs the\n * pair directly, which is why this helper is additive rather than the only way\n * in (§24.6 rule 1).\n *\n * @param kind optional `authenticatorAttachment` hint. Omitted entirely when\n * not passed — the SDK never infers it and never defaults it.\n */\nexport async function webauthnRegister(\n client: AxiamClient,\n credentialName: string,\n kind?: AuthenticatorKind,\n options?: WebauthnCeremonyOptions,\n): Promise<WebauthnCredential> {\n requireSupport('webauthnRegister');\n\n const { challenge, stateToken } = await client.webauthnRegisterStart();\n const credential = await createCredential(challenge, kind, options?.signal);\n return client.webauthnRegisterFinish(stateToken, credentialName, credential);\n}\n\n/**\n * Enrol a passkey or security key as the account's **first** factor, during\n * forced login setup (§24.6, contract 1.45) — the setup-token twin of\n * {@link webauthnRegister}, reached where `mfaSetupEnroll`/`mfaSetupConfirm`'s\n * TOTP path is reached: `login()` answered `mfa_setup_required` because the\n * tenant requires MFA and this account has none.\n *\n * Runs the full ceremony: `setup/register/start`, the authenticator, then\n * `setup/register/finish` — which, unlike `webauthnRegisterFinish`,\n * adopts credentials and completes the interrupted login (§25.2 rule 2,\n * mirrored). The pair stays individually callable on `AxiamClient` for the\n * same reason {@link webauthnRegister} is additive rather than the only way\n * in (§24.6 rule 1).\n *\n * @param setupToken the token from `login()`'s `mfa_setup_required` outcome.\n * @param kind optional `authenticatorAttachment` hint. Omitted entirely when\n * not passed — the SDK never infers it and never defaults it.\n */\nexport async function webauthnSetupRegister(\n client: AxiamClient,\n setupToken: Sensitive<string> | string,\n credentialName: string,\n kind?: AuthenticatorKind,\n options?: WebauthnCeremonyOptions,\n): Promise<LoginResult> {\n requireSupport('webauthnSetupRegister');\n\n const { challenge, stateToken } = await client.webauthnSetupRegisterStart(setupToken);\n const credential = await createCredential(challenge, kind, options?.signal);\n return client.webauthnSetupRegisterFinish(setupToken, stateToken, credentialName, credential);\n}\n\n/**\n * Sign in with a passkey as a **second factor** (§24.6).\n *\n * `challengeToken` is the `mfaToken` from a `login()` that answered\n * `mfa_required` with `\"webauthn\"` among its methods.\n */\nexport async function webauthnLogin(\n client: AxiamClient,\n challengeToken: string,\n options?: WebauthnCeremonyOptions,\n): Promise<WebauthnLoginResult> {\n requireSupport('webauthnLogin');\n\n const { challenge, stateToken } = await client.webauthnAuthenticateStart(challengeToken);\n const assertion = await getAssertion(challenge, options);\n return client.webauthnAuthenticateFinish(stateToken, assertion);\n}\n\n/**\n * Sign in with a passkey **without typing a username first** (§24.6).\n *\n * The workspace still has to be named — a discoverable credential is resolved\n * inside one tenant — but it comes from the client's own configuration unless\n * overridden, and slugs are accepted.\n */\nexport async function webauthnDiscoverableLogin(\n client: AxiamClient,\n workspace?: WebauthnWorkspace,\n options?: WebauthnCeremonyOptions,\n): Promise<WebauthnLoginResult> {\n requireSupport('webauthnDiscoverableLogin');\n\n const { challenge, stateToken } = await client.webauthnDiscoverableStart(workspace);\n const assertion = await getAssertion(challenge, options);\n return client.webauthnDiscoverableFinish(stateToken, assertion);\n}\n\n// ---------------------------------------------------------------------------\n// Ceremony internals\n// ---------------------------------------------------------------------------\n\nfunction requireSupport(operation: string): void {\n if (!isWebauthnSupported()) {\n throw new Error(\n `${operation}: this runtime has no WebAuthn authenticator. Check isWebauthnSupported() first, ` +\n 'or use the relying-party operations on AxiamClient with a response produced elsewhere ' +\n '(CONTRACT.md §24.6).',\n );\n }\n}\n\n/** Run `navigator.credentials.create()` and return the JSON form of its answer. */\nasync function createCredential(\n challenge: WebauthnCreationChallenge,\n kind: AuthenticatorKind | undefined,\n signal: AbortSignal | undefined,\n): Promise<WebauthnRegistrationResponse> {\n const credential = (await navigator.credentials.create({\n publicKey: toCreationOptions(challenge.publicKey, kind),\n ...(signal ? { signal } : {}),\n })) as PublicKeyCredential | null;\n\n if (!credential) {\n // Spec-wise unreachable — a rejection is how failure is reported — but a\n // `null` here would otherwise become a confusing property access.\n throw new Error('webauthnRegister: the authenticator returned no credential.');\n }\n\n const response = credential.response as AuthenticatorAttestationResponse;\n const transports =\n typeof response.getTransports === 'function' ? response.getTransports() : undefined;\n\n return {\n id: credential.id,\n rawId: bytesToBase64Url(credential.rawId),\n response: {\n clientDataJSON: bytesToBase64Url(response.clientDataJSON),\n attestationObject: bytesToBase64Url(response.attestationObject),\n ...(transports && transports.length > 0 ? { transports } : {}),\n },\n type: credential.type,\n ...(credential.authenticatorAttachment\n ? { authenticatorAttachment: credential.authenticatorAttachment }\n : {}),\n clientExtensionResults: credential.getClientExtensionResults() as Record<string, unknown>,\n };\n}\n\n/** Run `navigator.credentials.get()` and return the JSON form of its answer. */\nasync function getAssertion(\n challenge: WebauthnRequestChallenge,\n options: WebauthnCeremonyOptions | undefined,\n): Promise<WebauthnAuthenticationResponse> {\n const credential = (await navigator.credentials.get({\n publicKey: toRequestOptions(challenge.publicKey),\n ...(options?.conditional ? { mediation: 'conditional' as CredentialMediationRequirement } : {}),\n ...(options?.signal ? { signal: options.signal } : {}),\n })) as PublicKeyCredential | null;\n\n if (!credential) {\n throw new Error('webauthnLogin: the authenticator returned no assertion.');\n }\n\n const response = credential.response as AuthenticatorAssertionResponse;\n return {\n id: credential.id,\n rawId: bytesToBase64Url(credential.rawId),\n response: {\n clientDataJSON: bytesToBase64Url(response.clientDataJSON),\n authenticatorData: bytesToBase64Url(response.authenticatorData),\n signature: bytesToBase64Url(response.signature),\n ...(response.userHandle ? { userHandle: bytesToBase64Url(response.userHandle) } : {}),\n },\n type: credential.type,\n ...(credential.authenticatorAttachment\n ? { authenticatorAttachment: credential.authenticatorAttachment }\n : {}),\n clientExtensionResults: credential.getClientExtensionResults() as Record<string, unknown>,\n };\n}\n\n/**\n * Transcribe the server's creation options into what the DOM API takes.\n *\n * Every optional field is forwarded **only if the server sent it** — §24.0\n * rule 1 forbids expanding an absent `authenticatorSelection` into an empty\n * object or supplying a `timeout` the server did not choose. The string enums\n * (`residentKey`, `userVerification`, `attestation`) are cast rather than\n * validated: §24.0 rule 2 says an SDK may fail to parse but must not refuse\n * options it parsed, and a client-side allow-list of acceptable values is a\n * second policy engine.\n */\nfunction toCreationOptions(\n json: WebauthnCreationOptionsJson,\n kind: AuthenticatorKind | undefined,\n): PublicKeyCredentialCreationOptions {\n const selection = json.authenticatorSelection;\n // The only place this module adds anything (§24.6 rule 4). When the caller\n // passed no kind and the server sent no selection, the key stays absent.\n const authenticatorSelection =\n selection || kind\n ? ({\n ...(selection?.residentKey ? { residentKey: selection.residentKey } : {}),\n ...(selection?.requireResidentKey !== undefined\n ? { requireResidentKey: selection.requireResidentKey }\n : {}),\n ...(selection?.userVerification\n ? { userVerification: selection.userVerification }\n : {}),\n ...(kind\n ? { authenticatorAttachment: kind }\n : selection?.authenticatorAttachment\n ? { authenticatorAttachment: selection.authenticatorAttachment }\n : {}),\n } as AuthenticatorSelectionCriteria)\n : undefined;\n\n return {\n challenge: base64UrlToBytes(json.challenge),\n rp: json.rp,\n user: {\n id: base64UrlToBytes(json.user.id),\n name: json.user.name,\n displayName: json.user.displayName,\n },\n pubKeyCredParams: json.pubKeyCredParams as PublicKeyCredentialParameters[],\n ...(json.timeout !== undefined ? { timeout: json.timeout } : {}),\n ...(json.excludeCredentials\n ? { excludeCredentials: json.excludeCredentials.map(toDescriptor) }\n : {}),\n ...(authenticatorSelection ? { authenticatorSelection } : {}),\n ...(json.attestation\n ? { attestation: json.attestation as AttestationConveyancePreference }\n : {}),\n ...(json.extensions\n ? { extensions: json.extensions as AuthenticationExtensionsClientInputs }\n : {}),\n };\n}\n\n/** The same transcription for an assertion challenge. */\nfunction toRequestOptions(json: WebauthnRequestOptionsJson): PublicKeyCredentialRequestOptions {\n return {\n challenge: base64UrlToBytes(json.challenge),\n ...(json.timeout !== undefined ? { timeout: json.timeout } : {}),\n ...(json.rpId ? { rpId: json.rpId } : {}),\n ...(json.allowCredentials\n ? { allowCredentials: json.allowCredentials.map(toDescriptor) }\n : {}),\n ...(json.userVerification\n ? { userVerification: json.userVerification as UserVerificationRequirement }\n : {}),\n ...(json.extensions\n ? { extensions: json.extensions as AuthenticationExtensionsClientInputs }\n : {}),\n };\n}\n\nfunction toDescriptor(d: WebauthnCredentialDescriptorJson): PublicKeyCredentialDescriptor {\n return {\n id: base64UrlToBytes(d.id),\n type: d.type as PublicKeyCredentialType,\n ...(d.transports ? { transports: d.transports as AuthenticatorTransport[] } : {}),\n };\n}\n"]}