@pk-auth/passkeys-browser 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,383 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // src/base64url.ts
8
+ var base64url_exports = {};
9
+ __export(base64url_exports, {
10
+ decode: () => decode,
11
+ decodeToArrayBuffer: () => decodeToArrayBuffer,
12
+ encode: () => encode
13
+ });
14
+ function encode(input) {
15
+ const bytes = toUint8Array(input);
16
+ let s = "";
17
+ for (let i = 0; i < bytes.length; i++) {
18
+ s += String.fromCharCode(bytes[i]);
19
+ }
20
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
21
+ }
22
+ function decode(input) {
23
+ const pad = "=".repeat((4 - input.length % 4) % 4);
24
+ const normalized = input.replace(/-/g, "+").replace(/_/g, "/") + pad;
25
+ const binary = atob(normalized);
26
+ const bytes = new Uint8Array(binary.length);
27
+ for (let i = 0; i < binary.length; i++) {
28
+ bytes[i] = binary.charCodeAt(i);
29
+ }
30
+ return bytes;
31
+ }
32
+ function decodeToArrayBuffer(input) {
33
+ const bytes = decode(input);
34
+ return bytes.buffer.slice(
35
+ bytes.byteOffset,
36
+ bytes.byteOffset + bytes.byteLength
37
+ );
38
+ }
39
+ function toUint8Array(input) {
40
+ if (input instanceof Uint8Array) return input;
41
+ if (input instanceof ArrayBuffer) return new Uint8Array(input);
42
+ return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
43
+ }
44
+
45
+ // src/http.ts
46
+ var PkAuthHttpError = class extends Error {
47
+ status;
48
+ body;
49
+ data;
50
+ constructor(status, body) {
51
+ super(`HTTP ${status}: ${body}`);
52
+ this.name = "PkAuthHttpError";
53
+ this.status = status;
54
+ this.body = body;
55
+ try {
56
+ const parsed = JSON.parse(body);
57
+ this.data = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
58
+ } catch {
59
+ this.data = void 0;
60
+ }
61
+ }
62
+ /** The `error` field from the parsed response body, if present. */
63
+ get error() {
64
+ return typeof this.data?.["error"] === "string" ? this.data["error"] : void 0;
65
+ }
66
+ /** The `detail` field from the parsed response body, if present. */
67
+ get detail() {
68
+ return typeof this.data?.["detail"] === "string" ? this.data["detail"] : void 0;
69
+ }
70
+ /** The `outcome` field from the parsed response body, if present. */
71
+ get outcome() {
72
+ return typeof this.data?.["outcome"] === "string" ? this.data["outcome"] : void 0;
73
+ }
74
+ };
75
+ async function request(options, method, path, body, authenticated) {
76
+ const fetchImpl = options.fetch ?? globalThis.fetch;
77
+ const base = options.apiBase.endsWith("/") ? options.apiBase.slice(0, -1) : options.apiBase;
78
+ const url = `${base}${path}`;
79
+ const headers = { accept: "application/json" };
80
+ let payload;
81
+ if (body !== void 0) {
82
+ headers["content-type"] = "application/json";
83
+ payload = JSON.stringify(body);
84
+ }
85
+ if (authenticated) {
86
+ const token = options.getToken?.();
87
+ if (!token) {
88
+ throw new Error("pk-auth: authenticated request requires getToken() to return a bearer token");
89
+ }
90
+ headers["authorization"] = `Bearer ${token}`;
91
+ }
92
+ const init = { method, headers };
93
+ if (payload !== void 0) init.body = payload;
94
+ const response = await fetchImpl(url, init);
95
+ const text = await response.text();
96
+ if (!response.ok) {
97
+ throw new PkAuthHttpError(response.status, text);
98
+ }
99
+ if (!text.length) {
100
+ return void 0;
101
+ }
102
+ return JSON.parse(text);
103
+ }
104
+
105
+ // src/results.ts
106
+ function isCeremonySuccess(result) {
107
+ return result.outcome === "success";
108
+ }
109
+ function isCeremonyFailure(result) {
110
+ return result.outcome !== "success";
111
+ }
112
+
113
+ // src/ceremonies.ts
114
+ var PATHS = {
115
+ startReg: "/auth/passkeys/registration/start",
116
+ finishReg: "/auth/passkeys/registration/finish",
117
+ startAuth: "/auth/passkeys/authentication/start",
118
+ finishAuth: "/auth/passkeys/authentication/finish"
119
+ };
120
+ var PkAuthCeremonyClient = class {
121
+ client;
122
+ paths;
123
+ credentials;
124
+ constructor(client, options = {}) {
125
+ this.client = client;
126
+ this.paths = { ...PATHS, ...options.paths };
127
+ this.credentials = options.credentials;
128
+ }
129
+ /**
130
+ * Runs the full registration ceremony: server-start → `navigator.credentials.create` →
131
+ * server-finish. Returns the finish payload (registered credential metadata).
132
+ */
133
+ async register(params) {
134
+ const start = await this.startRegistration({
135
+ username: params.username,
136
+ displayName: params.displayName ?? params.username,
137
+ label: params.label ?? null,
138
+ challenge: null
139
+ });
140
+ const created = await this.createCredential(start.publicKey);
141
+ return this.finishRegistration({
142
+ challengeId: start.challengeId,
143
+ username: params.username,
144
+ label: params.label ?? null,
145
+ response: encodeRegistrationResponse(created)
146
+ });
147
+ }
148
+ /**
149
+ * Runs the full sign-in ceremony: server-start → `navigator.credentials.get` →
150
+ * server-finish. Returns the JWT (consumer is responsible for storage).
151
+ */
152
+ async authenticate(params = {}) {
153
+ const start = await this.startAuthentication({
154
+ username: params.username ?? null,
155
+ challenge: null
156
+ });
157
+ const got = await this.getCredential(start.publicKey, params.conditional ?? false);
158
+ return this.finishAuthentication({
159
+ challengeId: start.challengeId,
160
+ response: encodeAuthenticationResponse(got)
161
+ });
162
+ }
163
+ startRegistration(body) {
164
+ return request(this.client, "POST", this.paths.startReg, body, false);
165
+ }
166
+ finishRegistration(body) {
167
+ return request(this.client, "POST", this.paths.finishReg, body, false);
168
+ }
169
+ startAuthentication(body) {
170
+ return request(this.client, "POST", this.paths.startAuth, body, false);
171
+ }
172
+ finishAuthentication(body) {
173
+ return request(this.client, "POST", this.paths.finishAuth, body, false);
174
+ }
175
+ get credentialsImpl() {
176
+ if (this.credentials) return this.credentials;
177
+ if (typeof navigator === "undefined" || !navigator.credentials) {
178
+ throw new Error("pk-auth: navigator.credentials is not available in this environment");
179
+ }
180
+ return navigator.credentials;
181
+ }
182
+ async createCredential(options) {
183
+ const publicKey = decodeCreationOptions(options);
184
+ const credential = await this.credentialsImpl.create({ publicKey });
185
+ if (!credential) {
186
+ throw new Error("pk-auth: credential creation was cancelled");
187
+ }
188
+ return credential;
189
+ }
190
+ async getCredential(options, conditional) {
191
+ const publicKey = decodeRequestOptions(options);
192
+ const request2 = { publicKey };
193
+ if (conditional) {
194
+ request2.mediation = "conditional";
195
+ }
196
+ const credential = await this.credentialsImpl.get(request2);
197
+ if (!credential) {
198
+ throw new Error("pk-auth: authentication was cancelled");
199
+ }
200
+ return credential;
201
+ }
202
+ };
203
+ function decodeCreationOptions(options) {
204
+ return {
205
+ rp: options.rp,
206
+ user: {
207
+ id: decodeToArrayBuffer(options.user.id),
208
+ name: options.user.name,
209
+ displayName: options.user.displayName
210
+ },
211
+ challenge: decodeToArrayBuffer(options.challenge),
212
+ pubKeyCredParams: options.pubKeyCredParams,
213
+ timeout: options.timeout,
214
+ attestation: options.attestation,
215
+ authenticatorSelection: options.authenticatorSelection,
216
+ excludeCredentials: (options.excludeCredentials ?? []).map((c) => ({
217
+ id: decodeToArrayBuffer(c.id),
218
+ type: c.type,
219
+ transports: c.transports
220
+ }))
221
+ };
222
+ }
223
+ function decodeRequestOptions(options) {
224
+ return {
225
+ challenge: decodeToArrayBuffer(options.challenge),
226
+ timeout: options.timeout,
227
+ rpId: options.rpId,
228
+ userVerification: options.userVerification,
229
+ allowCredentials: (options.allowCredentials ?? []).map((c) => ({
230
+ id: decodeToArrayBuffer(c.id),
231
+ type: c.type,
232
+ transports: c.transports
233
+ }))
234
+ };
235
+ }
236
+ function encodeRegistrationResponse(credential) {
237
+ const response = credential.response;
238
+ const transports = typeof response.getTransports === "function" ? response.getTransports() : [];
239
+ return {
240
+ id: encode(credential.rawId),
241
+ rawId: encode(credential.rawId),
242
+ type: "public-key",
243
+ response: {
244
+ clientDataJSON: encode(response.clientDataJSON),
245
+ attestationObject: encode(response.attestationObject),
246
+ transports
247
+ }
248
+ };
249
+ }
250
+ function encodeAuthenticationResponse(credential) {
251
+ const response = credential.response;
252
+ return {
253
+ id: encode(credential.rawId),
254
+ rawId: encode(credential.rawId),
255
+ type: "public-key",
256
+ response: {
257
+ clientDataJSON: encode(response.clientDataJSON),
258
+ authenticatorData: encode(response.authenticatorData),
259
+ signature: encode(response.signature),
260
+ userHandle: response.userHandle ? encode(response.userHandle) : null
261
+ }
262
+ };
263
+ }
264
+
265
+ // src/admin.ts
266
+ var PATHS2 = {
267
+ account: "/auth/admin/account",
268
+ credentials: "/auth/admin/credentials",
269
+ credentialById: (id) => `/auth/admin/credentials/${encodeURIComponent(id)}`,
270
+ backupRegen: "/auth/admin/backup-codes/regenerate",
271
+ backupCount: "/auth/admin/backup-codes/count",
272
+ emailStart: "/auth/admin/email/start-verification",
273
+ emailComplete: "/auth/admin/email/complete-verification",
274
+ phoneStart: "/auth/admin/phone/start-verification",
275
+ phoneComplete: "/auth/admin/phone/complete-verification"
276
+ };
277
+ var PkAuthAdminClient = class {
278
+ client;
279
+ constructor(client) {
280
+ if (!client.getToken) {
281
+ throw new Error("pk-auth: admin client requires `getToken` in ClientOptions");
282
+ }
283
+ this.client = client;
284
+ }
285
+ getAccount() {
286
+ return request(this.client, "GET", PATHS2.account, void 0, true);
287
+ }
288
+ listCredentials() {
289
+ return request(this.client, "GET", PATHS2.credentials, void 0, true);
290
+ }
291
+ renameCredential(credentialId, label) {
292
+ return request(this.client, "PATCH", PATHS2.credentialById(credentialId), { label }, true);
293
+ }
294
+ removeCredential(credentialId) {
295
+ return request(this.client, "DELETE", PATHS2.credentialById(credentialId), void 0, true);
296
+ }
297
+ regenerateBackupCodes() {
298
+ return request(this.client, "POST", PATHS2.backupRegen, "", true);
299
+ }
300
+ remainingBackupCodes() {
301
+ return request(this.client, "GET", PATHS2.backupCount, void 0, true);
302
+ }
303
+ startEmailVerification(email) {
304
+ return request(this.client, "POST", PATHS2.emailStart, { email }, true);
305
+ }
306
+ completeEmailVerification(token) {
307
+ return request(this.client, "POST", PATHS2.emailComplete, { token }, true);
308
+ }
309
+ startPhoneVerification(phone) {
310
+ return request(this.client, "POST", PATHS2.phoneStart, { phone }, true);
311
+ }
312
+ completePhoneVerification(phone, code) {
313
+ return request(this.client, "POST", PATHS2.phoneComplete, { phone, code }, true);
314
+ }
315
+ };
316
+
317
+ // src/refresh.ts
318
+ function isRefreshSuccess(r) {
319
+ return r.kind === "success";
320
+ }
321
+ function isRefreshFailure(r) {
322
+ return r.kind === "failure";
323
+ }
324
+ var PkAuthRefreshClient = class {
325
+ options;
326
+ path;
327
+ constructor(options, path = "/auth/refresh") {
328
+ this.options = options;
329
+ this.path = path;
330
+ }
331
+ async refresh(refreshToken) {
332
+ try {
333
+ const response = await request(
334
+ this.options,
335
+ "POST",
336
+ this.path,
337
+ { refreshToken },
338
+ false
339
+ );
340
+ return {
341
+ kind: "success",
342
+ accessToken: response.accessToken,
343
+ refreshToken: response.refreshToken,
344
+ expiresAt: response.expiresAt
345
+ };
346
+ } catch (e) {
347
+ if (e instanceof PkAuthHttpError && e.status === 401) {
348
+ const data = e.data;
349
+ const detail = data?.detail;
350
+ if (detail === "expired" || detail === "unknown" || detail === "replayed" || detail === "revoked") {
351
+ return { kind: "failure", reason: detail, revokeReason: data?.reason };
352
+ }
353
+ return { kind: "failure", reason: "unknown" };
354
+ }
355
+ throw e;
356
+ }
357
+ }
358
+ };
359
+
360
+ // src/index.ts
361
+ var PkAuthClient = class {
362
+ ceremonies;
363
+ admin;
364
+ refreshClient;
365
+ constructor(options, ceremonyOptions = {}) {
366
+ this.ceremonies = new PkAuthCeremonyClient(options, ceremonyOptions);
367
+ this.admin = new PkAuthAdminClient(options);
368
+ this.refreshClient = new PkAuthRefreshClient(options);
369
+ }
370
+ /**
371
+ * Convenience shortcut to {@link PkAuthRefreshClient#refresh}. Returns a typed
372
+ * {@link RefreshResult} sum — does not throw on 401.
373
+ *
374
+ * @since 1.1.0
375
+ */
376
+ refresh(refreshToken) {
377
+ return this.refreshClient.refresh(refreshToken);
378
+ }
379
+ };
380
+
381
+ export { PkAuthAdminClient, PkAuthCeremonyClient, PkAuthClient, PkAuthHttpError, PkAuthRefreshClient, base64url_exports as base64url, decodeCreationOptions, decodeRequestOptions, encodeAuthenticationResponse, encodeRegistrationResponse, isCeremonyFailure, isCeremonySuccess, isRefreshFailure, isRefreshSuccess };
382
+ //# sourceMappingURL=index.js.map
383
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/base64url.ts","../src/http.ts","../src/results.ts","../src/ceremonies.ts","../src/admin.ts","../src/refresh.ts","../src/index.ts"],"names":["request","PATHS"],"mappings":";;;;;;;AAAA,IAAA,iBAAA,GAAA;AAAA,QAAA,CAAA,iBAAA,EAAA;AAAA,EAAA,MAAA,EAAA,MAAA,MAAA;AAAA,EAAA,mBAAA,EAAA,MAAA,mBAAA;AAAA,EAAA,MAAA,EAAA,MAAA;AAAA,CAAA,CAAA;AAWO,SAAS,OAAO,KAAA,EAA8D;AACnF,EAAA,MAAM,KAAA,GAAQ,aAAa,KAAK,CAAA;AAChC,EAAA,IAAI,CAAA,GAAI,EAAA;AACR,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,KAAA,CAAM,QAAQ,CAAA,EAAA,EAAK;AACrC,IAAA,CAAA,IAAK,MAAA,CAAO,YAAA,CAAa,KAAA,CAAM,CAAC,CAAE,CAAA;AAAA,EACpC;AACA,EAAA,OAAO,IAAA,CAAK,CAAC,CAAA,CAAE,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAAE,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAAE,OAAA,CAAQ,OAAO,EAAE,CAAA;AAC1E;AAEO,SAAS,OAAO,KAAA,EAA8B;AACnD,EAAA,MAAM,MAAM,GAAA,CAAI,MAAA,CAAA,CAAQ,IAAK,KAAA,CAAM,MAAA,GAAS,KAAM,CAAC,CAAA;AACnD,EAAA,MAAM,UAAA,GAAa,MAAM,OAAA,CAAQ,IAAA,EAAM,GAAG,C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AA,IAAmB,CAAA,CAAE,MAAA,KAAW,GAAA,EAAK;AACpD,QAAA,MAAM,OAAO,CAAA,CAAE,IAAA;AACf,QAAA,MAAM,SAAS,IAAA,EAAM,MAAA;AACrB,QAAA,IACE,WAAW,SAAA,IACX,MAAA,KAAW,aACX,MAAA,KAAW,UAAA,IACX,WAAW,SAAA,EACX;AACA,UAAA,OAAO,EAAE,IAAA,EAAM,SAAA,EAAW,QAAQ,MAAA,EAAQ,YAAA,EAAc,MAAM,MAAA,EAAO;AAAA,QACvE;AAEA,QAAA,OAAO,EAAE,IAAA,EAAM,SAAA,EAAW,MAAA,EAAQ,SAAA,EAAU;AAAA,MAC9C;AACA,MAAA,MAAM,CAAA;AAAA,IACR;AAAA,EACF;AACF;;;AC7DO,IAAM,eAAN,MAAmB;AAAA,EACf,UAAA;AAAA,EACA,KAAA;AAAA,EACA,aAAA;AAAA,EAET,WAAA,CAAY,OAAA,EAAwB,eAAA,GAAmC,EAAC,EAAG;AACzE,IAAA,IAAA,CAAK,UAAA,GAAa,IAAI,oBAAA,CAAqB,OAAA,EAAS,eAAe,CAAA;AACnE,IAAA,IAAA,CAAK,KAAA,GAAQ,IAAI,iBAAA,CAAkB,OAAO,CAAA;AAC1C,IAAA,IAAA,CAAK,aAAA,GAAgB,IAAI,mBAAA,CAAoB,OAAO,CAAA;AAAA,EACtD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,QAAQ,YAAA,EAA8C;AACpD,IAAA,OAAO,IAAA,CAAK,aAAA,CAAc,OAAA,CAAQ,YAAY,CAAA;AAAA,EAChD;AACF","file":"index.js","sourcesContent":["// SPDX-License-Identifier: MIT\n\n/**\n * Base64url (RFC 4648 §5) without padding — matches pk-auth's wire format.\n * The server's Jackson module emits unpadded base64url; browsers can mix\n * Uint8Array, ArrayBuffer, or already-base64url strings, so encode handles\n * all three.\n */\n\nexport type Base64Url = string;\n\nexport function encode(input: ArrayBuffer | Uint8Array | ArrayBufferView): Base64Url {\n const bytes = toUint8Array(input);\n let s = \"\";\n for (let i = 0; i < bytes.length; i++) {\n s += String.fromCharCode(bytes[i]!);\n }\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nexport function decode(input: Base64Url): Uint8Array {\n const pad = \"=\".repeat((4 - (input.length % 4)) % 4);\n const normalized = input.replace(/-/g, \"+\").replace(/_/g, \"/\") + pad;\n const binary = atob(normalized);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\nexport function decodeToArrayBuffer(input: Base64Url): ArrayBuffer {\n const bytes = decode(input);\n return bytes.buffer.slice(\n bytes.byteOffset,\n bytes.byteOffset + bytes.byteLength,\n ) as ArrayBuffer;\n}\n\nfunction toUint8Array(input: ArrayBuffer | Uint8Array | ArrayBufferView): Uint8Array {\n if (input instanceof Uint8Array) return input;\n if (input instanceof ArrayBuffer) return new Uint8Array(input);\n return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);\n}\n","// SPDX-License-Identifier: MIT\n\nimport type { ClientOptions } from \"./types\";\n\nexport class PkAuthHttpError extends Error {\n readonly status: number;\n readonly body: string;\n readonly data: Record<string, unknown> | undefined;\n\n constructor(status: number, body: string) {\n super(`HTTP ${status}: ${body}`);\n this.name = \"PkAuthHttpError\";\n this.status = status;\n this.body = body;\n try {\n const parsed = JSON.parse(body);\n this.data = parsed !== null && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : undefined;\n } catch {\n this.data = undefined;\n }\n }\n\n /** The `error` field from the parsed response body, if present. */\n get error(): string | undefined {\n return typeof this.data?.[\"error\"] === \"string\" ? (this.data[\"error\"] as string) : undefined;\n }\n\n /** The `detail` field from the parsed response body, if present. */\n get detail(): string | undefined {\n return typeof this.data?.[\"detail\"] === \"string\" ? (this.data[\"detail\"] as string) : undefined;\n }\n\n /** The `outcome` field from the parsed response body, if present. */\n get outcome(): string | undefined {\n return typeof this.data?.[\"outcome\"] === \"string\" ? (this.data[\"outcome\"] as string) : undefined;\n }\n}\n\n/** Internal request wrapper. `authenticated: true` adds the bearer header from `getToken`. */\nexport async function request<T>(\n options: ClientOptions,\n method: string,\n path: string,\n body: unknown,\n authenticated: boolean,\n): Promise<T> {\n const fetchImpl = options.fetch ?? globalThis.fetch;\n const base = options.apiBase.endsWith(\"/\")\n ? options.apiBase.slice(0, -1)\n : options.apiBase;\n const url = `${base}${path}`;\n\n const headers: Record<string, string> = { accept: \"application/json\" };\n let payload: BodyInit | undefined;\n if (body !== undefined) {\n headers[\"content-type\"] = \"application/json\";\n payload = JSON.stringify(body);\n }\n if (authenticated) {\n const token = options.getToken?.();\n if (!token) {\n throw new Error(\"pk-auth: authenticated request requires getToken() to return a bearer token\");\n }\n headers[\"authorization\"] = `Bearer ${token}`;\n }\n\n const init: RequestInit = { method, headers };\n if (payload !== undefined) init.body = payload;\n const response = await fetchImpl(url, init);\n\n const text = await response.text();\n if (!response.ok) {\n throw new PkAuthHttpError(response.status, text);\n }\n if (!text.length) {\n return undefined as unknown as T;\n }\n return JSON.parse(text) as T;\n}\n","// SPDX-License-Identifier: MIT\n\n/**\n * Discriminated union mirroring the Java sealed result hierarchies\n * (AuthenticationResult / RegistrationResult) as returned by the pk-auth HTTP adapters.\n *\n * Authentication outcomes: success | challenge_invalid | origin_mismatch |\n * signature_invalid | unknown_credential | failed\n *\n * Registration outcomes: success | challenge_invalid | origin_mismatch |\n * attestation_rejected | duplicate_credential | invalid_payload | failed\n */\nexport type CeremonyResult =\n | { outcome: 'success'; token: string; credentialId?: string }\n | { outcome: 'challenge_invalid'; detail?: string }\n | { outcome: 'origin_mismatch'; detail?: string }\n | { outcome: 'signature_invalid'; detail?: string }\n | { outcome: 'unknown_credential'; detail?: string }\n | { outcome: 'attestation_rejected'; detail?: string }\n | { outcome: 'duplicate_credential'; detail?: string }\n | { outcome: 'invalid_payload'; detail?: string }\n | { outcome: 'failed'; detail?: string };\n\n/** Type guard: narrows a CeremonyResult to the success variant. */\nexport function isCeremonySuccess(\n result: CeremonyResult,\n): result is { outcome: 'success'; token: string; credentialId?: string } {\n return result.outcome === 'success';\n}\n\n/** Type guard: narrows a CeremonyResult to any failure variant. */\nexport function isCeremonyFailure(\n result: CeremonyResult,\n): result is Exclude<CeremonyResult, { outcome: 'success' }> {\n return result.outcome !== 'success';\n}\n","// SPDX-License-Identifier: MIT\n\nimport * as b64u from \"./base64url\";\nimport { request } from \"./http\";\nimport type {\n ClientOptions,\n FinishAuthenticationRequest,\n FinishAuthenticationResponse,\n FinishRegistrationRequest,\n FinishRegistrationResponse,\n PublicKeyCredentialCreationOptionsJson,\n PublicKeyCredentialRequestOptionsJson,\n RegistrationResponseJson,\n AuthenticationResponseJson,\n StartAuthenticationRequest,\n StartAuthenticationResponse,\n StartRegistrationRequest,\n StartRegistrationResponse,\n} from \"./types\";\n\nconst PATHS = {\n startReg: \"/auth/passkeys/registration/start\",\n finishReg: \"/auth/passkeys/registration/finish\",\n startAuth: \"/auth/passkeys/authentication/start\",\n finishAuth: \"/auth/passkeys/authentication/finish\",\n} as const;\n\n// All three adapters (Spring, Dropwizard, Micronaut) now mount ceremony endpoints at\n// /auth/passkeys/<phase>/<step>. The `paths` override remains an escape hatch for hosts that\n// remap the routes but is no longer needed for any pk-auth-provided adapter.\n\nexport interface CeremonyOptions {\n /** Path overrides — kept as an escape hatch for hosts that remap pk-auth's default routes. */\n paths?: Partial<typeof PATHS>;\n /** Optional override for navigator.credentials (tests / non-browser callers). */\n credentials?: CredentialsContainer;\n}\n\nexport interface StartRegistrationParams {\n username: string;\n displayName?: string;\n label?: string;\n}\n\nexport interface FinishRegistrationParams extends StartRegistrationResponse {\n username: string;\n label?: string;\n}\n\nexport interface StartAuthenticationParams {\n username?: string;\n /** When true, hands the call to `navigator.credentials.get` with `mediation: \"conditional\"`. */\n conditional?: boolean;\n}\n\nexport class PkAuthCeremonyClient {\n private readonly client: ClientOptions;\n private readonly paths: typeof PATHS;\n private readonly credentials?: CredentialsContainer;\n\n constructor(client: ClientOptions, options: CeremonyOptions = {}) {\n this.client = client;\n this.paths = { ...PATHS, ...options.paths };\n this.credentials = options.credentials;\n }\n\n /**\n * Runs the full registration ceremony: server-start → `navigator.credentials.create` →\n * server-finish. Returns the finish payload (registered credential metadata).\n */\n async register(params: StartRegistrationParams): Promise<FinishRegistrationResponse> {\n const start = await this.startRegistration({\n username: params.username,\n displayName: params.displayName ?? params.username,\n label: params.label ?? null,\n challenge: null,\n });\n const created = await this.createCredential(start.publicKey);\n return this.finishRegistration({\n challengeId: start.challengeId,\n username: params.username,\n label: params.label ?? null,\n response: encodeRegistrationResponse(created),\n });\n }\n\n /**\n * Runs the full sign-in ceremony: server-start → `navigator.credentials.get` →\n * server-finish. Returns the JWT (consumer is responsible for storage).\n */\n async authenticate(params: StartAuthenticationParams = {}): Promise<FinishAuthenticationResponse> {\n const start = await this.startAuthentication({\n username: params.username ?? null,\n challenge: null,\n });\n const got = await this.getCredential(start.publicKey, params.conditional ?? false);\n return this.finishAuthentication({\n challengeId: start.challengeId,\n response: encodeAuthenticationResponse(got),\n });\n }\n\n startRegistration(body: StartRegistrationRequest): Promise<StartRegistrationResponse> {\n return request(this.client, \"POST\", this.paths.startReg, body, false);\n }\n\n finishRegistration(body: FinishRegistrationRequest): Promise<FinishRegistrationResponse> {\n return request(this.client, \"POST\", this.paths.finishReg, body, false);\n }\n\n startAuthentication(body: StartAuthenticationRequest): Promise<StartAuthenticationResponse> {\n return request(this.client, \"POST\", this.paths.startAuth, body, false);\n }\n\n finishAuthentication(body: FinishAuthenticationRequest): Promise<FinishAuthenticationResponse> {\n return request(this.client, \"POST\", this.paths.finishAuth, body, false);\n }\n\n private get credentialsImpl(): CredentialsContainer {\n if (this.credentials) return this.credentials;\n if (typeof navigator === \"undefined\" || !navigator.credentials) {\n throw new Error(\"pk-auth: navigator.credentials is not available in this environment\");\n }\n return navigator.credentials;\n }\n\n private async createCredential(\n options: PublicKeyCredentialCreationOptionsJson,\n ): Promise<PublicKeyCredential> {\n const publicKey = decodeCreationOptions(options);\n const credential = (await this.credentialsImpl.create({ publicKey })) as PublicKeyCredential | null;\n if (!credential) {\n throw new Error(\"pk-auth: credential creation was cancelled\");\n }\n return credential;\n }\n\n private async getCredential(\n options: PublicKeyCredentialRequestOptionsJson,\n conditional: boolean,\n ): Promise<PublicKeyCredential> {\n const publicKey = decodeRequestOptions(options);\n const request: CredentialRequestOptions = { publicKey };\n if (conditional) {\n (request as CredentialRequestOptions & { mediation?: string }).mediation = \"conditional\";\n }\n const credential = (await this.credentialsImpl.get(request)) as PublicKeyCredential | null;\n if (!credential) {\n throw new Error(\"pk-auth: authentication was cancelled\");\n }\n return credential;\n }\n}\n\nexport function decodeCreationOptions(\n options: PublicKeyCredentialCreationOptionsJson,\n): PublicKeyCredentialCreationOptions {\n return {\n rp: options.rp,\n user: {\n id: b64u.decodeToArrayBuffer(options.user.id),\n name: options.user.name,\n displayName: options.user.displayName,\n },\n challenge: b64u.decodeToArrayBuffer(options.challenge),\n pubKeyCredParams: options.pubKeyCredParams,\n timeout: options.timeout,\n attestation: options.attestation,\n authenticatorSelection: options.authenticatorSelection,\n excludeCredentials: (options.excludeCredentials ?? []).map((c) => ({\n id: b64u.decodeToArrayBuffer(c.id),\n type: c.type,\n transports: c.transports as AuthenticatorTransport[] | undefined,\n })),\n };\n}\n\nexport function decodeRequestOptions(\n options: PublicKeyCredentialRequestOptionsJson,\n): PublicKeyCredentialRequestOptions {\n return {\n challenge: b64u.decodeToArrayBuffer(options.challenge),\n timeout: options.timeout,\n rpId: options.rpId,\n userVerification: options.userVerification,\n allowCredentials: (options.allowCredentials ?? []).map((c) => ({\n id: b64u.decodeToArrayBuffer(c.id),\n type: c.type,\n transports: c.transports as AuthenticatorTransport[] | undefined,\n })),\n };\n}\n\nexport function encodeRegistrationResponse(credential: PublicKeyCredential): RegistrationResponseJson {\n const response = credential.response as AuthenticatorAttestationResponse;\n const transports =\n typeof (response as AuthenticatorAttestationResponse & {\n getTransports?: () => string[];\n }).getTransports === \"function\"\n ? (response as AuthenticatorAttestationResponse & {\n getTransports: () => string[];\n }).getTransports()\n : [];\n return {\n id: b64u.encode(credential.rawId),\n rawId: b64u.encode(credential.rawId),\n type: \"public-key\",\n response: {\n clientDataJSON: b64u.encode(response.clientDataJSON),\n attestationObject: b64u.encode(response.attestationObject),\n transports,\n },\n };\n}\n\nexport function encodeAuthenticationResponse(\n credential: PublicKeyCredential,\n): AuthenticationResponseJson {\n const response = credential.response as AuthenticatorAssertionResponse;\n return {\n id: b64u.encode(credential.rawId),\n rawId: b64u.encode(credential.rawId),\n type: \"public-key\",\n response: {\n clientDataJSON: b64u.encode(response.clientDataJSON),\n authenticatorData: b64u.encode(response.authenticatorData),\n signature: b64u.encode(response.signature),\n userHandle: response.userHandle ? b64u.encode(response.userHandle) : null,\n },\n };\n}\n","// SPDX-License-Identifier: MIT\n\nimport { request } from \"./http\";\nimport type {\n AccountSummary,\n BackupCodeBatch,\n BackupCodeCount,\n ClientOptions,\n CredentialSummary,\n EmailDispatchResult,\n EmailVerificationResult,\n PhoneDispatchResult,\n PhoneVerificationResult,\n} from \"./types\";\n\nconst PATHS = {\n account: \"/auth/admin/account\",\n credentials: \"/auth/admin/credentials\",\n credentialById: (id: string) => `/auth/admin/credentials/${encodeURIComponent(id)}`,\n backupRegen: \"/auth/admin/backup-codes/regenerate\",\n backupCount: \"/auth/admin/backup-codes/count\",\n emailStart: \"/auth/admin/email/start-verification\",\n emailComplete: \"/auth/admin/email/complete-verification\",\n phoneStart: \"/auth/admin/phone/start-verification\",\n phoneComplete: \"/auth/admin/phone/complete-verification\",\n} as const;\n\nexport class PkAuthAdminClient {\n private readonly client: ClientOptions;\n\n constructor(client: ClientOptions) {\n if (!client.getToken) {\n throw new Error(\"pk-auth: admin client requires `getToken` in ClientOptions\");\n }\n this.client = client;\n }\n\n getAccount(): Promise<AccountSummary> {\n return request(this.client, \"GET\", PATHS.account, undefined, true);\n }\n\n listCredentials(): Promise<CredentialSummary[]> {\n return request(this.client, \"GET\", PATHS.credentials, undefined, true);\n }\n\n renameCredential(credentialId: string, label: string): Promise<CredentialSummary> {\n return request(this.client, \"PATCH\", PATHS.credentialById(credentialId), { label }, true);\n }\n\n removeCredential(credentialId: string): Promise<void> {\n return request(this.client, \"DELETE\", PATHS.credentialById(credentialId), undefined, true);\n }\n\n regenerateBackupCodes(): Promise<BackupCodeBatch> {\n return request(this.client, \"POST\", PATHS.backupRegen, \"\", true);\n }\n\n remainingBackupCodes(): Promise<BackupCodeCount> {\n return request(this.client, \"GET\", PATHS.backupCount, undefined, true);\n }\n\n startEmailVerification(email: string): Promise<EmailDispatchResult> {\n return request(this.client, \"POST\", PATHS.emailStart, { email }, true);\n }\n\n completeEmailVerification(token: string): Promise<EmailVerificationResult> {\n return request(this.client, \"POST\", PATHS.emailComplete, { token }, true);\n }\n\n startPhoneVerification(phone: string): Promise<PhoneDispatchResult> {\n return request(this.client, \"POST\", PATHS.phoneStart, { phone }, true);\n }\n\n completePhoneVerification(phone: string, code: string): Promise<PhoneVerificationResult> {\n return request(this.client, \"POST\", PATHS.phoneComplete, { phone, code }, true);\n }\n}\n","// SPDX-License-Identifier: MIT\n\nimport { PkAuthHttpError, request } from \"./http\";\nimport type { ClientOptions } from \"./types\";\n\n/** Typed success: a fresh refresh + access token pair to swap in. */\nexport interface RefreshSuccess {\n readonly kind: \"success\";\n readonly accessToken: string;\n readonly refreshToken: string;\n readonly expiresAt: string;\n}\n\n/** Typed failure mirroring the {@code detail} field on the server's 401 body. */\nexport type RefreshFailureReason = \"expired\" | \"unknown\" | \"replayed\" | \"revoked\";\n\nexport interface RefreshFailure {\n readonly kind: \"failure\";\n readonly reason: RefreshFailureReason;\n /** Categorical revoke reason when `reason === \"revoked\"`. */\n readonly revokeReason?: string;\n}\n\n/** Sealed sum of refresh outcomes. */\nexport type RefreshResult = RefreshSuccess | RefreshFailure;\n\n/** Type guard for {@link RefreshSuccess}. */\nexport function isRefreshSuccess(r: RefreshResult): r is RefreshSuccess {\n return r.kind === \"success\";\n}\n\n/** Type guard for {@link RefreshFailure}. */\nexport function isRefreshFailure(r: RefreshResult): r is RefreshFailure {\n return r.kind === \"failure\";\n}\n\ninterface RawRefreshResponse {\n refreshToken: string;\n accessToken: string;\n expiresAt: string;\n}\n\ninterface RawErrorResponse {\n detail?: string;\n reason?: string;\n}\n\n/**\n * Client for the {@code POST /auth/refresh} endpoint shipped by every pk-auth adapter. Returns\n * a typed {@link RefreshResult} rather than throwing on 401 — the bearer's expected response to\n * an Unknown / Expired / Replayed / Revoked outcome is to redirect to login, not to handle an\n * exception.\n *\n * @since 1.1.0\n */\nexport class PkAuthRefreshClient {\n private readonly options: ClientOptions;\n private readonly path: string;\n\n constructor(options: ClientOptions, path: string = \"/auth/refresh\") {\n this.options = options;\n this.path = path;\n }\n\n async refresh(refreshToken: string): Promise<RefreshResult> {\n try {\n const response = await request<RawRefreshResponse>(\n this.options,\n \"POST\",\n this.path,\n { refreshToken },\n false,\n );\n return {\n kind: \"success\",\n accessToken: response.accessToken,\n refreshToken: response.refreshToken,\n expiresAt: response.expiresAt,\n };\n } catch (e: unknown) {\n if (e instanceof PkAuthHttpError && e.status === 401) {\n const data = e.data as RawErrorResponse | undefined;\n const detail = data?.detail;\n if (\n detail === \"expired\" ||\n detail === \"unknown\" ||\n detail === \"replayed\" ||\n detail === \"revoked\"\n ) {\n return { kind: \"failure\", reason: detail, revokeReason: data?.reason };\n }\n // Server returned a 401 we don't recognise — surface it as the most conservative failure.\n return { kind: \"failure\", reason: \"unknown\" };\n }\n throw e;\n }\n }\n}\n","// SPDX-License-Identifier: MIT\n\nexport * as base64url from \"./base64url\";\nexport { PkAuthHttpError } from \"./http\";\nexport type { CeremonyResult } from \"./results\";\nexport { isCeremonySuccess, isCeremonyFailure } from \"./results\";\nexport {\n PkAuthCeremonyClient,\n decodeCreationOptions,\n decodeRequestOptions,\n encodeAuthenticationResponse,\n encodeRegistrationResponse,\n} from \"./ceremonies\";\nexport type {\n CeremonyOptions,\n FinishRegistrationParams,\n StartAuthenticationParams,\n StartRegistrationParams,\n} from \"./ceremonies\";\nexport { PkAuthAdminClient } from \"./admin\";\nexport { PkAuthRefreshClient, isRefreshSuccess, isRefreshFailure } from \"./refresh\";\nexport type {\n RefreshResult,\n RefreshSuccess,\n RefreshFailure,\n RefreshFailureReason,\n} from \"./refresh\";\nexport type * from \"./types\";\n\nimport { PkAuthAdminClient } from \"./admin\";\nimport { PkAuthCeremonyClient } from \"./ceremonies\";\nimport type { CeremonyOptions } from \"./ceremonies\";\nimport { PkAuthRefreshClient, type RefreshResult } from \"./refresh\";\nimport type { ClientOptions } from \"./types\";\n\n/** Convenience facade: a single object exposing ceremony, admin, and refresh clients. */\nexport class PkAuthClient {\n readonly ceremonies: PkAuthCeremonyClient;\n readonly admin: PkAuthAdminClient;\n readonly refreshClient: PkAuthRefreshClient;\n\n constructor(options: ClientOptions, ceremonyOptions: CeremonyOptions = {}) {\n this.ceremonies = new PkAuthCeremonyClient(options, ceremonyOptions);\n this.admin = new PkAuthAdminClient(options);\n this.refreshClient = new PkAuthRefreshClient(options);\n }\n\n /**\n * Convenience shortcut to {@link PkAuthRefreshClient#refresh}. Returns a typed\n * {@link RefreshResult} sum — does not throw on 401.\n *\n * @since 1.1.0\n */\n refresh(refreshToken: string): Promise<RefreshResult> {\n return this.refreshClient.refresh(refreshToken);\n }\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@pk-auth/passkeys-browser",
3
+ "version": "1.3.0",
4
+ "description": "pk-auth browser SDK: WebAuthn ceremonies + admin operations against the pk-auth wire contract.",
5
+ "license": "MIT",
6
+ "author": "Ned Wolpert",
7
+ "homepage": "https://github.com/codeheadsystems/pk-auth/tree/main/clients/passkeys-browser#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/codeheadsystems/pk-auth.git",
11
+ "directory": "clients/passkeys-browser"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/codeheadsystems/pk-auth/issues"
15
+ },
16
+ "keywords": [
17
+ "webauthn",
18
+ "passkeys",
19
+ "passkey",
20
+ "authentication",
21
+ "fido2",
22
+ "pk-auth",
23
+ "sdk"
24
+ ],
25
+ "type": "module",
26
+ "sideEffects": false,
27
+ "main": "./dist/index.cjs",
28
+ "module": "./dist/index.js",
29
+ "types": "./dist/index.d.ts",
30
+ "exports": {
31
+ ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "import": "./dist/index.js",
34
+ "require": "./dist/index.cjs"
35
+ }
36
+ },
37
+ "files": [
38
+ "dist",
39
+ "src"
40
+ ],
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "engines": {
45
+ "node": ">=20"
46
+ },
47
+ "scripts": {
48
+ "build": "tsup",
49
+ "test": "vitest run",
50
+ "test:watch": "vitest",
51
+ "typecheck": "tsc --noEmit",
52
+ "prepublishOnly": "npm run typecheck && npm test && npm run build"
53
+ },
54
+ "devDependencies": {
55
+ "@types/node": "^22.7.0",
56
+ "jsdom": "^25.0.1",
57
+ "tsup": "^8.3.0",
58
+ "typescript": "^5.6.3",
59
+ "vitest": "^4.1.6"
60
+ }
61
+ }
package/src/admin.ts ADDED
@@ -0,0 +1,77 @@
1
+ // SPDX-License-Identifier: MIT
2
+
3
+ import { request } from "./http";
4
+ import type {
5
+ AccountSummary,
6
+ BackupCodeBatch,
7
+ BackupCodeCount,
8
+ ClientOptions,
9
+ CredentialSummary,
10
+ EmailDispatchResult,
11
+ EmailVerificationResult,
12
+ PhoneDispatchResult,
13
+ PhoneVerificationResult,
14
+ } from "./types";
15
+
16
+ const PATHS = {
17
+ account: "/auth/admin/account",
18
+ credentials: "/auth/admin/credentials",
19
+ credentialById: (id: string) => `/auth/admin/credentials/${encodeURIComponent(id)}`,
20
+ backupRegen: "/auth/admin/backup-codes/regenerate",
21
+ backupCount: "/auth/admin/backup-codes/count",
22
+ emailStart: "/auth/admin/email/start-verification",
23
+ emailComplete: "/auth/admin/email/complete-verification",
24
+ phoneStart: "/auth/admin/phone/start-verification",
25
+ phoneComplete: "/auth/admin/phone/complete-verification",
26
+ } as const;
27
+
28
+ export class PkAuthAdminClient {
29
+ private readonly client: ClientOptions;
30
+
31
+ constructor(client: ClientOptions) {
32
+ if (!client.getToken) {
33
+ throw new Error("pk-auth: admin client requires `getToken` in ClientOptions");
34
+ }
35
+ this.client = client;
36
+ }
37
+
38
+ getAccount(): Promise<AccountSummary> {
39
+ return request(this.client, "GET", PATHS.account, undefined, true);
40
+ }
41
+
42
+ listCredentials(): Promise<CredentialSummary[]> {
43
+ return request(this.client, "GET", PATHS.credentials, undefined, true);
44
+ }
45
+
46
+ renameCredential(credentialId: string, label: string): Promise<CredentialSummary> {
47
+ return request(this.client, "PATCH", PATHS.credentialById(credentialId), { label }, true);
48
+ }
49
+
50
+ removeCredential(credentialId: string): Promise<void> {
51
+ return request(this.client, "DELETE", PATHS.credentialById(credentialId), undefined, true);
52
+ }
53
+
54
+ regenerateBackupCodes(): Promise<BackupCodeBatch> {
55
+ return request(this.client, "POST", PATHS.backupRegen, "", true);
56
+ }
57
+
58
+ remainingBackupCodes(): Promise<BackupCodeCount> {
59
+ return request(this.client, "GET", PATHS.backupCount, undefined, true);
60
+ }
61
+
62
+ startEmailVerification(email: string): Promise<EmailDispatchResult> {
63
+ return request(this.client, "POST", PATHS.emailStart, { email }, true);
64
+ }
65
+
66
+ completeEmailVerification(token: string): Promise<EmailVerificationResult> {
67
+ return request(this.client, "POST", PATHS.emailComplete, { token }, true);
68
+ }
69
+
70
+ startPhoneVerification(phone: string): Promise<PhoneDispatchResult> {
71
+ return request(this.client, "POST", PATHS.phoneStart, { phone }, true);
72
+ }
73
+
74
+ completePhoneVerification(phone: string, code: string): Promise<PhoneVerificationResult> {
75
+ return request(this.client, "POST", PATHS.phoneComplete, { phone, code }, true);
76
+ }
77
+ }
@@ -0,0 +1,44 @@
1
+ // SPDX-License-Identifier: MIT
2
+
3
+ /**
4
+ * Base64url (RFC 4648 §5) without padding — matches pk-auth's wire format.
5
+ * The server's Jackson module emits unpadded base64url; browsers can mix
6
+ * Uint8Array, ArrayBuffer, or already-base64url strings, so encode handles
7
+ * all three.
8
+ */
9
+
10
+ export type Base64Url = string;
11
+
12
+ export function encode(input: ArrayBuffer | Uint8Array | ArrayBufferView): Base64Url {
13
+ const bytes = toUint8Array(input);
14
+ let s = "";
15
+ for (let i = 0; i < bytes.length; i++) {
16
+ s += String.fromCharCode(bytes[i]!);
17
+ }
18
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
19
+ }
20
+
21
+ export function decode(input: Base64Url): Uint8Array {
22
+ const pad = "=".repeat((4 - (input.length % 4)) % 4);
23
+ const normalized = input.replace(/-/g, "+").replace(/_/g, "/") + pad;
24
+ const binary = atob(normalized);
25
+ const bytes = new Uint8Array(binary.length);
26
+ for (let i = 0; i < binary.length; i++) {
27
+ bytes[i] = binary.charCodeAt(i);
28
+ }
29
+ return bytes;
30
+ }
31
+
32
+ export function decodeToArrayBuffer(input: Base64Url): ArrayBuffer {
33
+ const bytes = decode(input);
34
+ return bytes.buffer.slice(
35
+ bytes.byteOffset,
36
+ bytes.byteOffset + bytes.byteLength,
37
+ ) as ArrayBuffer;
38
+ }
39
+
40
+ function toUint8Array(input: ArrayBuffer | Uint8Array | ArrayBufferView): Uint8Array {
41
+ if (input instanceof Uint8Array) return input;
42
+ if (input instanceof ArrayBuffer) return new Uint8Array(input);
43
+ return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
44
+ }