@tensile-tools/auth-client 0.0.0-stage → 0.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.
Files changed (44) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +62 -2
  3. package/dist/client.d.ts +569 -0
  4. package/dist/client.js +637 -0
  5. package/dist/devtools.d.ts +12 -0
  6. package/dist/devtools.js +44 -0
  7. package/dist/elements/account.d.ts +63 -0
  8. package/dist/elements/account.js +331 -0
  9. package/dist/elements/approvals.d.ts +61 -0
  10. package/dist/elements/approvals.js +252 -0
  11. package/dist/elements/auth.d.ts +48 -0
  12. package/dist/elements/auth.js +238 -0
  13. package/dist/elements/base.d.ts +176 -0
  14. package/dist/elements/base.js +540 -0
  15. package/dist/elements/config.d.ts +70 -0
  16. package/dist/elements/config.js +119 -0
  17. package/dist/elements/format.d.ts +32 -0
  18. package/dist/elements/format.js +67 -0
  19. package/dist/elements/index.d.ts +21 -0
  20. package/dist/elements/index.js +31 -0
  21. package/dist/elements/qr.d.ts +9 -0
  22. package/dist/elements/qr.js +302 -0
  23. package/dist/elements/returnto.d.ts +17 -0
  24. package/dist/elements/returnto.js +63 -0
  25. package/dist/elements/setup.d.ts +70 -0
  26. package/dist/elements/setup.js +316 -0
  27. package/dist/elements/styles.d.ts +3 -0
  28. package/dist/elements/styles.js +194 -0
  29. package/dist/elements/text.d.ts +21 -0
  30. package/dist/elements/text.js +302 -0
  31. package/dist/fonts/OFL-geist-mono.txt +93 -0
  32. package/dist/fonts/OFL-geist.txt +93 -0
  33. package/dist/fonts/OFL-inter.txt +93 -0
  34. package/dist/fonts/README.md +18 -0
  35. package/dist/fonts/geist-mono.woff2 +0 -0
  36. package/dist/fonts/geist.woff2 +0 -0
  37. package/dist/fonts/inter.woff2 +0 -0
  38. package/dist/index.d.ts +4 -0
  39. package/dist/index.js +5 -0
  40. package/dist/problem.d.ts +54 -0
  41. package/dist/problem.js +40 -0
  42. package/dist/webauthn.d.ts +46 -0
  43. package/dist/webauthn.js +102 -0
  44. package/package.json +51 -4
package/dist/client.js ADDED
@@ -0,0 +1,637 @@
1
+ // The auth client: ceremonies with honest outcomes, one entry point,
2
+ // step-up before the error, approvals, password-manager sync, PRF keys,
3
+ // and tab sync.
4
+ import { ProblemError, readProblem, stepUpCodes } from "./problem.js";
5
+ import { capabilities, credentialJSON, creationOptions, pkc, requestOptions, toBase64url } from "./webauthn.js";
6
+ /** Default routes, under `base`. */
7
+ export const defaultEndpoints = {
8
+ signInBegin: '/auth/passkey/sign-in/begin',
9
+ signInFinish: '/auth/passkey/sign-in/finish',
10
+ signUpBegin: '/auth/passkey/sign-up/begin',
11
+ signUpFinish: '/auth/passkey/sign-up/finish',
12
+ stepUpBegin: '/auth/passkey/step-up/begin',
13
+ stepUpFinish: '/auth/passkey/step-up/finish',
14
+ addPasskeyBegin: '/auth/passkey/add/begin',
15
+ addPasskeyFinish: '/auth/passkey/add/finish',
16
+ signOut: '/auth/sign-out',
17
+ credentials: '/auth/passkey/credentials',
18
+ totpVerify: '/auth/totp/verify',
19
+ recoverySignIn: '/auth/recovery/sign-in',
20
+ passwordSignUp: '/auth/password/sign-up',
21
+ passwordSignIn: '/auth/password/sign-in',
22
+ passwordConfirm: '/auth/password/confirm',
23
+ passwordForgot: '/auth/password/forgot',
24
+ passwordReset: '/auth/password/reset',
25
+ passwordStepUp: '/auth/password/step-up',
26
+ passwordChange: '/auth/password/change',
27
+ passwordAdd: '/auth/password/add',
28
+ passwordRemove: '/auth/password/remove',
29
+ emailChange: '/auth/email/change',
30
+ emailResend: '/auth/email/resend',
31
+ passwordStatus: '/auth/password/status',
32
+ me: '/auth/me',
33
+ totpEnroll: '/auth/totp/enroll',
34
+ totpConfirm: '/auth/totp/confirm',
35
+ totpStatus: '/auth/totp/status',
36
+ totpRemove: '/auth/totp/remove',
37
+ recoveryGenerate: '/auth/recovery/generate',
38
+ recoveryConfirm: '/auth/recovery/confirm',
39
+ approvals: '/auth/approvals',
40
+ approval: '/auth/approvals/{id}',
41
+ sessions: '/auth/sessions',
42
+ revokeSession: '/auth/sessions/{id}/revoke',
43
+ revokeOthers: '/auth/sessions/revoke-others',
44
+ activity: '/auth/activity',
45
+ recoverySignIns: '/auth/recovery/sign-ins',
46
+ recoveryUndo: '/auth/recovery/undo',
47
+ agentsTree: '/auth/agents/tree',
48
+ agents: '/auth/agents',
49
+ agent: '/auth/agents/{id}',
50
+ tokens: '/auth/tokens',
51
+ claimPeek: '/auth/claims/peek',
52
+ claimClaim: '/auth/claims/claim',
53
+ oauthRequest: '/auth/oauth/requests/{id}',
54
+ deviceRequest: '/auth/device/{id}',
55
+ };
56
+ /** Sentinel for "the browser answered that no passkey exists". */
57
+ const noPasskey = Symbol('no passkey');
58
+ export class AuthClient {
59
+ endpoints;
60
+ base;
61
+ rpId;
62
+ doFetch;
63
+ channel;
64
+ listeners = new Set();
65
+ conditional;
66
+ fresh;
67
+ constructor(opts = {}) {
68
+ this.base = opts.base ?? '';
69
+ this.endpoints = { ...defaultEndpoints, ...opts.endpoints };
70
+ this.rpId = opts.rpId ?? globalThis.location?.hostname;
71
+ this.doFetch = opts.fetch ?? globalThis.fetch.bind(globalThis);
72
+ if (typeof BroadcastChannel !== 'undefined') {
73
+ this.channel = new BroadcastChannel(opts.channel ?? 'tensile-auth');
74
+ this.channel.onmessage = (m) => this.notify(m.data, false);
75
+ }
76
+ }
77
+ /** Runs `fn` on every session event in this tab and others. Returns an unsubscribe function. */
78
+ onSessionChange(fn) {
79
+ this.listeners.add(fn);
80
+ return () => this.listeners.delete(fn);
81
+ }
82
+ /** Stops listening to other tabs. */
83
+ close() {
84
+ this.channel?.close();
85
+ }
86
+ /** Reports what this browser supports, to choose screens. */
87
+ capabilities() {
88
+ return capabilities();
89
+ }
90
+ /** Signs in with a passkey through the browser's account chooser. */
91
+ signIn() {
92
+ return this.assert(this.endpoints.signInBegin, this.endpoints.signInFinish, {}, 'signed-in');
93
+ }
94
+ /** Creates an account with a passkey. */
95
+ signUp(opts) {
96
+ return this.register(this.endpoints.signUpBegin, this.endpoints.signUpFinish, opts, 'signed-in');
97
+ }
98
+ /** Adds a passkey to the signed-in account. */
99
+ addPasskey(opts = {}) {
100
+ return this.register(this.endpoints.addPasskeyBegin, this.endpoints.addPasskeyFinish, opts, undefined);
101
+ }
102
+ /** Confirms it's you with a passkey, for the whole session or for one purpose. */
103
+ stepUp(opts = {}) {
104
+ return this.assert(this.endpoints.stepUpBegin, this.endpoints.stepUpFinish, opts.for ? { for: opts.for } : {}, 'stepped-up');
105
+ }
106
+ /** Finishes a sign-in that answered `needs_factor` with a TOTP code. */
107
+ verifyTOTP(code) {
108
+ return this.postCode(this.endpoints.totpVerify, code);
109
+ }
110
+ /** Signs in with a recovery code. It may answer `needs_factor` when the account has TOTP. */
111
+ signInWithRecoveryCode(code) {
112
+ return this.postCode(this.endpoints.recoverySignIn, code);
113
+ }
114
+ /**
115
+ * Starts an email and password sign-up. It answers `ok` for every
116
+ * address: the person learns what happened by email. A refusal names
117
+ * the password rule, for example `password_too_short`.
118
+ */
119
+ signUpWithPassword(opts) {
120
+ return this.post(this.endpoints.passwordSignUp, opts);
121
+ }
122
+ /**
123
+ * Signs in with an email address and a password. It may answer
124
+ * `needs_factor` when the account has TOTP. Every failure is the same
125
+ * `factor_rejected` problem. Use `<input type="password">` and allow
126
+ * paste, so password managers work.
127
+ */
128
+ async signInWithPassword(opts) {
129
+ this.cancelAutofill();
130
+ const r = await this.post(this.endpoints.passwordSignIn, opts);
131
+ return r.outcome === 'ok' ? this.settled(r.data) : r;
132
+ }
133
+ /**
134
+ * Redeems the code of a confirmation link. The code comes from `code`,
135
+ * or from the page's URL fragment (`#code=…`), which browsers don't
136
+ * send to servers or in Referer; it is removed from the address bar
137
+ * before the request, so it is posted once. When the answer is the
138
+ * `confirm_sign_in` problem, ask the person to sign in, or for their
139
+ * password, and call it again with `password`.
140
+ */
141
+ confirmEmail(opts = {}) {
142
+ const code = opts.code ?? takeCodeFromFragment();
143
+ if (!code)
144
+ return Promise.resolve(problemOutcome(missingCode));
145
+ return this.post(this.endpoints.passwordConfirm, { code, password: opts.password });
146
+ }
147
+ /** Asks for a reset link. It answers `ok` for every address. */
148
+ forgotPassword(email) {
149
+ return this.post(this.endpoints.passwordForgot, { email });
150
+ }
151
+ /**
152
+ * Sets a new password with the code of a reset link, from `code` or the
153
+ * URL fragment as for `confirmEmail`. A reset ends every session, this
154
+ * one too; `keepTokens` keeps personal access tokens and OAuth grants.
155
+ */
156
+ async resetPassword(opts) {
157
+ const code = opts.code ?? takeCodeFromFragment();
158
+ if (!code)
159
+ return problemOutcome(missingCode);
160
+ const r = await this.post(this.endpoints.passwordReset, { code, password: opts.password, keepTokens: opts.keepTokens ?? false });
161
+ if (r.outcome === 'ok')
162
+ this.notify({ type: 'signed-out' }, true);
163
+ return r;
164
+ }
165
+ /** Confirms it's you with your password. The server refuses it on an account with a passkey or TOTP. */
166
+ stepUpWithPassword(password) {
167
+ return this.post(this.endpoints.passwordStepUp, { password }, 'stepped-up');
168
+ }
169
+ /** Changes the password, after checking the current one. */
170
+ changePassword(opts) {
171
+ return this.post(this.endpoints.passwordChange, opts);
172
+ }
173
+ /** Adds a password; `email` is needed when the account has no confirmed address. */
174
+ addPassword(opts) {
175
+ return this.post(this.endpoints.passwordAdd, opts);
176
+ }
177
+ /** Removes the password, when the account has another way to sign in. */
178
+ removePassword(opts = {}) {
179
+ return this.post(this.endpoints.passwordRemove, opts);
180
+ }
181
+ /** Asks to change the email address; the new one must be confirmed. */
182
+ changeEmail(email) {
183
+ return this.post(this.endpoints.emailChange, { email });
184
+ }
185
+ /** Sends a fresh confirmation link to an unconfirmed address. */
186
+ resendVerification() {
187
+ return this.post(this.endpoints.emailResend, {});
188
+ }
189
+ /** Reads the account's address and whether it has a password. */
190
+ async passwordStatus() {
191
+ const res = await this.doFetch(this.base + this.endpoints.passwordStatus, { credentials: 'same-origin' });
192
+ if (!res.ok)
193
+ return problemOutcome(await readProblem(res));
194
+ return { outcome: 'ok', data: await res.json() };
195
+ }
196
+ /** Reads the signed-in session. */
197
+ me() {
198
+ return this.call('GET', this.endpoints.me);
199
+ }
200
+ /** Lists the approvals that wait for the person, newest first. */
201
+ async approvals() {
202
+ const r = await this.call('GET', this.endpoints.approvals);
203
+ return r.outcome === 'ok' ? { outcome: 'ok', data: r.data.items } : r;
204
+ }
205
+ /** Reads one approval. */
206
+ approval(id) {
207
+ return this.call('GET', this.path('approval', id));
208
+ }
209
+ /**
210
+ * Approves an agent's request with a passkey. The passkey signs the
211
+ * approval's challenge, which covers the exact action.
212
+ */
213
+ approve(id) {
214
+ const base = this.path('approval', id);
215
+ return this.assert(base + '/begin', base + '/finish', {}, undefined);
216
+ }
217
+ /** Declines an agent's request. */
218
+ deny(id) {
219
+ return this.call('POST', this.path('approval', id) + '/deny');
220
+ }
221
+ /** Reads the person's session tree and which session is this one. */
222
+ sessions() {
223
+ return this.call('GET', this.endpoints.sessions);
224
+ }
225
+ /** Revokes one of the person's sessions and everything delegated from it. */
226
+ revokeSession(id) {
227
+ return this.call('POST', this.path('revokeSession', id));
228
+ }
229
+ /** Signs out every other device. It steps up first when the server asks. */
230
+ signOutOthers() {
231
+ return this.call('POST', this.endpoints.revokeOthers);
232
+ }
233
+ /** Reads the person's latest audit events and the chain state. */
234
+ activity(opts = {}) {
235
+ return this.call('GET', this.endpoints.activity + (opts.before ? `?before=${encodeURIComponent(opts.before)}` : ''));
236
+ }
237
+ /** Lists recovery sign-ins the person can still undo. */
238
+ async recoverySignIns() {
239
+ const r = await this.call('GET', this.endpoints.recoverySignIns);
240
+ return r.outcome === 'ok' ? { outcome: 'ok', data: r.data.items } : r;
241
+ }
242
+ /** Undoes a recovery sign-in the person says wasn't them. */
243
+ undoRecovery(session) {
244
+ return this.call('POST', this.endpoints.recoveryUndo, { session });
245
+ }
246
+ /** Reads the person's sessions as a tree, with each agent's sessions under the session that delegated them. */
247
+ agentsTree() {
248
+ return this.call('GET', this.endpoints.agentsTree);
249
+ }
250
+ /** Creates an agent the person owns. */
251
+ createAgent(opts) {
252
+ return this.call('POST', this.endpoints.agents, { name: opts.name, scopes: opts.scopes ?? [] });
253
+ }
254
+ /** Issues a token for one of the person's agents. It steps up first when the server asks. */
255
+ delegate(agent, opts = {}) {
256
+ return this.call('POST', this.path('agent', agent) + '/delegate', {
257
+ name: opts.name ?? '', scopes: opts.scopes ?? [], ttl_seconds: opts.ttlSeconds ?? 0, key_thumbprint: opts.keyThumbprint ?? '',
258
+ });
259
+ }
260
+ /** Revokes one of the person's agents and every session it holds. */
261
+ revokeAgent(agent) {
262
+ return this.call('POST', this.path('agent', agent) + '/revoke');
263
+ }
264
+ /** Creates a personal access token. It steps up first when the server asks. */
265
+ createToken(opts) {
266
+ return this.call('POST', this.endpoints.tokens, { name: opts.name, scopes: opts.scopes ?? [], ttl_seconds: opts.ttlSeconds ?? 0 });
267
+ }
268
+ /** Reads what claiming an agent with a claim code would do, and the words the agent shows, without claiming it. */
269
+ peekClaim(code) {
270
+ return this.call('POST', this.endpoints.claimPeek, { code });
271
+ }
272
+ /** Claims an agent that signed up by itself. */
273
+ claimAgent(code, opts = {}) {
274
+ return this.call('POST', this.endpoints.claimClaim, {
275
+ code, scopes: opts.scopes ?? [], ttl_seconds: opts.ttlSeconds ?? 0, key_thumbprint: opts.keyThumbprint ?? '',
276
+ });
277
+ }
278
+ /** Reads a pending OAuth authorization request, for the consent page. */
279
+ authorization(id) {
280
+ return this.call('GET', this.path('oauthRequest', id));
281
+ }
282
+ /** Approves an OAuth authorization request and answers where to send the browser. It steps up first when the server asks. */
283
+ approveAuthorization(id) {
284
+ return this.call('POST', this.path('oauthRequest', id) + '/approve');
285
+ }
286
+ /** Denies an OAuth authorization request and answers where to send the browser. */
287
+ denyAuthorization(id) {
288
+ return this.call('POST', this.path('oauthRequest', id) + '/deny');
289
+ }
290
+ /** Reads the pending device request for the code the person typed. */
291
+ deviceRequest(userCode) {
292
+ return this.call('GET', this.path('deviceRequest', userCode));
293
+ }
294
+ /** Approves the device request for a user code. It steps up first when the server asks. */
295
+ approveDevice(userCode) {
296
+ return this.call('POST', this.path('deviceRequest', userCode) + '/approve');
297
+ }
298
+ /** Denies the device request for a user code. */
299
+ denyDevice(userCode) {
300
+ return this.call('POST', this.path('deviceRequest', userCode) + '/deny');
301
+ }
302
+ /** Starts TOTP enrolment and answers the `otpauth://` URI. */
303
+ enrollTOTP() {
304
+ return this.call('POST', this.endpoints.totpEnroll);
305
+ }
306
+ /** Turns TOTP on with a code from the app. */
307
+ confirmTOTP(code) {
308
+ return this.call('POST', this.endpoints.totpConfirm, { code });
309
+ }
310
+ /** Answers whether the person's authenticator app is on, locked, or not set up. */
311
+ totpStatus() {
312
+ return this.call('GET', this.endpoints.totpStatus);
313
+ }
314
+ /** Removes the person's authenticator app. It steps up first when the server asks for a fresh sign-in. */
315
+ removeTOTP() {
316
+ return this.call('POST', this.endpoints.totpRemove);
317
+ }
318
+ /** Makes a new set of recovery codes, which replaces the old set. */
319
+ generateRecoveryCodes() {
320
+ return this.call('POST', this.endpoints.recoveryGenerate);
321
+ }
322
+ /** Checks one recovery code typed back, so the person proves they saved the set. */
323
+ confirmRecoveryCodes(code) {
324
+ return this.call('POST', this.endpoints.recoveryConfirm, { code });
325
+ }
326
+ path(name, id) {
327
+ return this.endpoints[name].replace('{id}', encodeURIComponent(id));
328
+ }
329
+ /**
330
+ * Calls an account route like `fetch` does, stepping up when the server
331
+ * asks, and turns the answer into an outcome instead of throwing.
332
+ */
333
+ async call(method, path, body) {
334
+ const init = { method };
335
+ if (body !== undefined) {
336
+ init.headers = { 'content-type': 'application/json' };
337
+ init.body = JSON.stringify(body);
338
+ }
339
+ try {
340
+ const res = await this.fetch(path, init);
341
+ const data = res.headers.get('content-type')?.includes('json') ? await res.json() : undefined;
342
+ return { outcome: 'ok', data: data };
343
+ }
344
+ catch (e) {
345
+ if (e instanceof ProblemError)
346
+ return problemOutcome(e.problem);
347
+ throw e;
348
+ }
349
+ }
350
+ /** Posts JSON and turns the answer into an outcome. */
351
+ async post(path, body, event) {
352
+ const res = await this.doFetch(this.base + path, {
353
+ method: 'POST', credentials: 'same-origin',
354
+ headers: { 'content-type': 'application/json' }, body: JSON.stringify(body),
355
+ });
356
+ this.readFresh(res);
357
+ if (!res.ok)
358
+ return problemOutcome(await readProblem(res));
359
+ const data = res.headers.get('content-type')?.includes('json') ? await res.json() : undefined;
360
+ if (event)
361
+ this.notify({ type: event }, true);
362
+ return { outcome: 'ok', data };
363
+ }
364
+ async postCode(path, code) {
365
+ const res = await this.doFetch(this.base + path, {
366
+ method: 'POST', credentials: 'same-origin',
367
+ headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code }),
368
+ });
369
+ if (!res.ok)
370
+ return problemOutcome(await readProblem(res));
371
+ return this.settled(await res.json());
372
+ }
373
+ /** Turns a successful finish into ok, or needs_factor when the server asks for more. */
374
+ settled(data) {
375
+ const needs = data?.needs;
376
+ if (Array.isArray(needs) && needs.length > 0)
377
+ return { outcome: 'needs_factor', needs };
378
+ this.notify({ type: 'signed-in' }, true);
379
+ return { outcome: 'ok', data };
380
+ }
381
+ /** Signs out of this session in every tab. */
382
+ async signOut() {
383
+ await this.doFetch(this.base + this.endpoints.signOut, { method: 'POST', credentials: 'same-origin' });
384
+ this.notify({ type: 'signed-out' }, true);
385
+ }
386
+ /**
387
+ * One entry point for "Continue". It asks the browser to answer at once
388
+ * when it supports immediate mediation, so a person without a passkey
389
+ * goes straight to sign-up with no failed prompt; elsewhere it shows the
390
+ * normal prompt. Returns `no_passkey_or_cancelled` when there's no
391
+ * passkey, so the page can offer sign-up, a phone, or a recovery code.
392
+ * It cancels any background autofill request first, which otherwise
393
+ * makes the modal prompt fail without a word.
394
+ */
395
+ async enter(opts = {}) {
396
+ this.cancelAutofill();
397
+ const caps = await capabilities();
398
+ if (!caps.webauthn)
399
+ return { outcome: 'unsupported' };
400
+ return this.assert(this.endpoints.signInBegin, this.endpoints.signInFinish, {}, 'signed-in', caps.immediateGet ? 'immediate' : undefined, opts.signal);
401
+ }
402
+ /**
403
+ * Offers passkeys in the autofill of an input with
404
+ * `autocomplete="username webauthn"`. It resolves when the person picks
405
+ * one, and is cancelled by any other ceremony this client starts.
406
+ */
407
+ async autofill() {
408
+ const caps = await capabilities();
409
+ if (!caps.conditionalGet)
410
+ return { outcome: 'unsupported' };
411
+ this.cancelAutofill();
412
+ this.conditional = new AbortController();
413
+ return this.assert(this.endpoints.signInBegin, this.endpoints.signInFinish, {}, 'signed-in', 'conditional', this.conditional.signal);
414
+ }
415
+ /**
416
+ * Until when the session passes step-up checks, from the server's
417
+ * Tensile-Auth-Fresh-Until header on the last response, or undefined.
418
+ * Show it as a timer, or prompt before a sensitive action.
419
+ */
420
+ get freshUntil() {
421
+ return this.fresh;
422
+ }
423
+ /**
424
+ * `fetch` that answers refusals the way a person would: on a step-up
425
+ * challenge it runs the step-up (for the challenge's purpose, if any)
426
+ * and retries once. Any other failure throws a `ProblemError`. A 401
427
+ * tells every tab the session is gone.
428
+ */
429
+ async fetch(input, init = {}) {
430
+ const { stepUpFirst, ...rest } = init;
431
+ init = rest;
432
+ if (stepUpFirst && !(this.fresh && this.fresh.getTime() > Date.now())) {
433
+ const step = await this.stepUp();
434
+ if (step.outcome !== 'ok')
435
+ throw new ProblemError(step.outcome === 'problem' ? step.problem : cancelled);
436
+ }
437
+ const res = await this.doFetch(this.base + input, { credentials: 'same-origin', ...init });
438
+ this.readFresh(res);
439
+ if (res.ok)
440
+ return res;
441
+ const problem = await readProblem(res);
442
+ if (res.status === 401 && problem.code === 'unauthenticated')
443
+ this.notify({ type: 'session-lost' }, true);
444
+ if (stepUpCodes.has(problem.code) && problem.challenge?.satisfy_with.includes('passkey')) {
445
+ const step = await this.stepUp({ for: problem.challenge.purpose });
446
+ if (step.outcome === 'ok') {
447
+ const again = await this.doFetch(this.base + input, { credentials: 'same-origin', ...init });
448
+ if (again.ok)
449
+ return again;
450
+ throw new ProblemError(await readProblem(again));
451
+ }
452
+ }
453
+ throw new ProblemError(problem);
454
+ }
455
+ /**
456
+ * Tells password managers which of this account's passkeys still exist
457
+ * and the account's current name, through the WebAuthn Signal API, so
458
+ * they stop offering removed passkeys. Call it after sign-in, after
459
+ * removing a passkey, and after a rename. It does nothing where the
460
+ * browser lacks the API.
461
+ */
462
+ async syncPasskeys() {
463
+ const p = pkc();
464
+ if (!p?.signalAllAcceptedCredentials || !this.rpId)
465
+ return;
466
+ const res = await this.doFetch(this.base + this.endpoints.credentials, { credentials: 'same-origin' });
467
+ if (!res.ok)
468
+ return;
469
+ const info = (await res.json());
470
+ await p.signalAllAcceptedCredentials({ rpId: this.rpId, userId: info.userId, allAcceptedCredentialIds: info.credentialIds });
471
+ if (info.name && p.signalCurrentUserDetails) {
472
+ await p.signalCurrentUserDetails({ rpId: this.rpId, userId: info.userId, name: info.name, displayName: info.displayName ?? info.name });
473
+ }
474
+ }
475
+ readFresh(res) {
476
+ const until = res.headers.get('tensile-auth-fresh-until');
477
+ if (until)
478
+ this.fresh = new Date(until);
479
+ else if (res.headers.has('tensile-auth-assurance'))
480
+ this.fresh = undefined;
481
+ }
482
+ cancelAutofill() {
483
+ this.conditional?.abort();
484
+ this.conditional = undefined;
485
+ }
486
+ notify(e, broadcast) {
487
+ for (const fn of this.listeners)
488
+ fn(e);
489
+ if (broadcast)
490
+ this.channel?.postMessage(e);
491
+ }
492
+ async begin(path, body) {
493
+ const res = await this.doFetch(this.base + path, {
494
+ method: 'POST', credentials: 'same-origin',
495
+ headers: { 'content-type': 'application/json' }, body: JSON.stringify(body),
496
+ });
497
+ if (!res.ok)
498
+ return problemOutcome(await readProblem(res));
499
+ return (await res.json());
500
+ }
501
+ async finish(path, cred, event) {
502
+ const res = await this.doFetch(this.base + path, {
503
+ method: 'POST', credentials: 'same-origin',
504
+ headers: { 'content-type': 'application/json' }, body: JSON.stringify(credentialJSON(cred)),
505
+ });
506
+ if (!res.ok) {
507
+ // A rejection is generic on purpose: it can mean an expired ceremony
508
+ // or a failed check as well as a removed passkey. Signalling the
509
+ // passkey as unknown here could make a password manager delete one
510
+ // that still works, so only syncPasskeys tells it what exists.
511
+ return problemOutcome(await readProblem(res));
512
+ }
513
+ const data = res.headers.get('content-type')?.includes('json') ? await res.json() : undefined;
514
+ if (event === 'signed-in')
515
+ return this.settled(data);
516
+ if (event)
517
+ this.notify({ type: event }, true);
518
+ return { outcome: 'ok', data };
519
+ }
520
+ async assert(beginPath, finishPath, body, event, mediation, signal) {
521
+ if (!pkc() || !globalThis.navigator?.credentials)
522
+ return { outcome: 'unsupported' };
523
+ if (mediation !== 'conditional')
524
+ this.cancelAutofill();
525
+ const opts = await this.begin(beginPath, body);
526
+ if ('outcome' in opts)
527
+ return opts;
528
+ let cred;
529
+ try {
530
+ // "immediate" is newer than the DOM types: the browser answers at once
531
+ // when no passkey exists instead of showing a prompt.
532
+ const req = { publicKey: requestOptions(opts), signal, mediation };
533
+ cred = await navigator.credentials.get(req);
534
+ }
535
+ catch (e) {
536
+ // Some browsers report immediate mediation in getClientCapabilities
537
+ // but reject the value itself: fall back to the normal prompt.
538
+ if (mediation === 'immediate' && e instanceof TypeError) {
539
+ return this.assert(beginPath, finishPath, body, event, undefined, signal);
540
+ }
541
+ const r = ceremonyError(e);
542
+ if (r === noPasskey)
543
+ return { outcome: 'no_passkey_or_cancelled' };
544
+ return r;
545
+ }
546
+ if (cred === null)
547
+ return { outcome: 'no_passkey_or_cancelled' };
548
+ return this.finish(finishPath, cred, event);
549
+ }
550
+ async register(beginPath, finishPath, body, event) {
551
+ if (!pkc() || !globalThis.navigator?.credentials)
552
+ return { outcome: 'unsupported' };
553
+ this.cancelAutofill();
554
+ const opts = await this.begin(beginPath, body);
555
+ if ('outcome' in opts)
556
+ return opts;
557
+ let cred;
558
+ try {
559
+ cred = await navigator.credentials.create({ publicKey: creationOptions(opts) });
560
+ }
561
+ catch (e) {
562
+ if (e instanceof Error && e.name === 'InvalidStateError')
563
+ return { outcome: 'already_registered' };
564
+ const r = ceremonyError(e);
565
+ if (r === noPasskey)
566
+ return { outcome: 'no_passkey_or_cancelled' };
567
+ return r;
568
+ }
569
+ if (!cred)
570
+ return { outcome: 'no_passkey_or_cancelled' };
571
+ return this.finish(finishPath, cred, event);
572
+ }
573
+ }
574
+ /** Maps a WebAuthn exception to what a person can act on. */
575
+ function ceremonyError(e) {
576
+ if (!(e instanceof Error))
577
+ return { outcome: 'problem', problem: genericProblem(String(e)) };
578
+ switch (e.name) {
579
+ case 'NotAllowedError':
580
+ case 'AbortError':
581
+ case 'TimeoutError':
582
+ return noPasskey;
583
+ case 'NotSupportedError':
584
+ case 'SecurityError':
585
+ return { outcome: 'unsupported' };
586
+ default:
587
+ return { outcome: 'problem', problem: genericProblem(e.message) };
588
+ }
589
+ }
590
+ const cancelled = {
591
+ type: 'about:blank', title: 'Confirmation cancelled', status: 0, code: 'step_up_cancelled', fix: 'Confirm it\'s you to continue.',
592
+ };
593
+ function genericProblem(detail) {
594
+ return { type: 'about:blank', title: 'The passkey prompt failed', status: 0, code: 'passkey_failed', detail, fix: 'Try again.' };
595
+ }
596
+ const missingCode = {
597
+ type: 'about:blank', title: 'That link doesn\'t work', status: 0, code: 'code_invalid', fix: 'Open the link from the message again.',
598
+ };
599
+ /**
600
+ * Reads `code` from the URL fragment and removes it from the address bar,
601
+ * so the code is posted once and never reaches history or a Referer.
602
+ */
603
+ function takeCodeFromFragment() {
604
+ const loc = globalThis.location;
605
+ if (!loc?.hash)
606
+ return undefined;
607
+ const params = new URLSearchParams(loc.hash.slice(1));
608
+ const code = params.get('code') ?? undefined;
609
+ if (code) {
610
+ params.delete('code');
611
+ const rest = params.toString();
612
+ globalThis.history?.replaceState(null, '', loc.pathname + loc.search + (rest ? '#' + rest : ''));
613
+ }
614
+ return code;
615
+ }
616
+ function problemOutcome(problem) {
617
+ if (problem.code === 'throttled')
618
+ return { outcome: 'throttled', retryAfter: problem.retry_after ?? 1 };
619
+ return { outcome: 'problem', problem };
620
+ }
621
+ /**
622
+ * Derives a non-extractable AES-GCM key from a passkey's PRF output, for
623
+ * secrets the server never sees. `purpose` separates keys for different
624
+ * uses of the same passkey. It returns `unsupported` when the output is
625
+ * missing, so the page can offer its fallback, such as a passphrase.
626
+ */
627
+ export async function deriveKey(prfOutput, purpose) {
628
+ if (!prfOutput || !globalThis.crypto?.subtle)
629
+ return 'unsupported';
630
+ const base = await crypto.subtle.importKey('raw', prfOutput, 'HKDF', false, ['deriveKey']);
631
+ return crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: new TextEncoder().encode('tensile-auth prf'), info: new TextEncoder().encode(purpose) }, base, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
632
+ }
633
+ /** Creates an auth client. */
634
+ export function createAuthClient(opts = {}) {
635
+ return new AuthClient(opts);
636
+ }
637
+ export { toBase64url };
@@ -0,0 +1,12 @@
1
+ import type { AuthClient } from './client.ts';
2
+ export interface DevToolsOptions {
3
+ /** Where authhttp.DevTools is mounted. Default `/auth/dev`. */
4
+ endpoint?: string;
5
+ }
6
+ /**
7
+ * Mounts the developer panel and returns a function that removes it. It
8
+ * shows the principal, its assurance, methods, and freshness, and buttons
9
+ * to make the session stale or switch to recovery mode, so step-up and
10
+ * recovery screens can be tried in seconds.
11
+ */
12
+ export declare function mountDevTools(client: AuthClient, opts?: DevToolsOptions): () => void;