@koshirepo/auth-client 0.0.0-stage → 0.1.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/README.md +27 -3
- package/dist/channel.d.ts +15 -0
- package/dist/channel.d.ts.map +1 -0
- package/dist/channel.js +23 -0
- package/dist/channel.js.map +1 -0
- package/dist/client.d.ts +11 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +396 -0
- package/dist/client.js.map +1 -0
- package/dist/dpop.d.ts +42 -0
- package/dist/dpop.d.ts.map +1 -0
- package/dist/dpop.js +131 -0
- package/dist/dpop.js.map +1 -0
- package/dist/guards.d.ts +40 -0
- package/dist/guards.d.ts.map +1 -0
- package/dist/guards.js +38 -0
- package/dist/guards.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/locks.d.ts +13 -0
- package/dist/locks.d.ts.map +1 -0
- package/dist/locks.js +28 -0
- package/dist/locks.js.map +1 -0
- package/dist/react/index.d.ts +74 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +94 -0
- package/dist/react/index.js.map +1 -0
- package/dist/types.d.ts +154 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/package.json +56 -3
package/dist/dpop.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { SignJWT, base64url, calculateJwkThumbprint } from 'jose';
|
|
2
|
+
/** Keeps the key for the lifetime of the page only. Every reload is a new device to the server. */
|
|
3
|
+
export function memoryKeyStore() {
|
|
4
|
+
let stored = null;
|
|
5
|
+
return {
|
|
6
|
+
load: async () => stored,
|
|
7
|
+
save: async (keys) => {
|
|
8
|
+
stored = keys;
|
|
9
|
+
},
|
|
10
|
+
clear: async () => {
|
|
11
|
+
stored = null;
|
|
12
|
+
},
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
const STORE = 'keys';
|
|
16
|
+
const RECORD = 'dpop';
|
|
17
|
+
/**
|
|
18
|
+
* Keeps the key in IndexedDB. `CryptoKey` objects are stored as they are, so the private key
|
|
19
|
+
* never exists as bytes that script could read or send anywhere.
|
|
20
|
+
*/
|
|
21
|
+
export function indexedDbKeyStore(options = {}) {
|
|
22
|
+
const databaseName = options.databaseName ?? 'koshi-auth';
|
|
23
|
+
const open = () => new Promise((resolve, reject) => {
|
|
24
|
+
const request = indexedDB.open(databaseName, 1);
|
|
25
|
+
request.onupgradeneeded = () => {
|
|
26
|
+
request.result.createObjectStore(STORE);
|
|
27
|
+
};
|
|
28
|
+
request.onsuccess = () => resolve(request.result);
|
|
29
|
+
request.onerror = () => reject(request.error ?? new Error('IndexedDB could not be opened.'));
|
|
30
|
+
});
|
|
31
|
+
const run = async (mode, action) => {
|
|
32
|
+
const database = await open();
|
|
33
|
+
try {
|
|
34
|
+
return await new Promise((resolve, reject) => {
|
|
35
|
+
const transaction = database.transaction(STORE, mode);
|
|
36
|
+
const request = action(transaction.objectStore(STORE));
|
|
37
|
+
transaction.oncomplete = () => resolve(request.result);
|
|
38
|
+
transaction.onerror = () => reject(transaction.error ?? new Error('IndexedDB transaction failed.'));
|
|
39
|
+
transaction.onabort = () => reject(transaction.error ?? new Error('IndexedDB transaction was aborted.'));
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
finally {
|
|
43
|
+
database.close();
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
return {
|
|
47
|
+
async load() {
|
|
48
|
+
const stored = await run('readonly', (store) => store.get(RECORD));
|
|
49
|
+
return stored?.privateKey && stored.publicKey ? stored : null;
|
|
50
|
+
},
|
|
51
|
+
async save(keys) {
|
|
52
|
+
await run('readwrite', (store) => store.put(keys, RECORD));
|
|
53
|
+
},
|
|
54
|
+
async clear() {
|
|
55
|
+
await run('readwrite', (store) => store.delete(RECORD));
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/** IndexedDB where it exists, otherwise memory. */
|
|
60
|
+
export function defaultKeyStore() {
|
|
61
|
+
return typeof indexedDB === 'undefined' ? memoryKeyStore() : indexedDbKeyStore();
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Creates the device key on first use and signs DPoP proofs (RFC 9449) with it.
|
|
65
|
+
*
|
|
66
|
+
* The key is ES256, which every browser's WebCrypto supports, and its private half is generated
|
|
67
|
+
* as non-extractable. Script running in the page can ask for a signature but cannot export the key.
|
|
68
|
+
*/
|
|
69
|
+
export class DpopSigner {
|
|
70
|
+
store;
|
|
71
|
+
now;
|
|
72
|
+
locks;
|
|
73
|
+
loading = null;
|
|
74
|
+
constructor(store,
|
|
75
|
+
/** Epoch milliseconds, already corrected for any known offset from the server clock. */
|
|
76
|
+
now, locks) {
|
|
77
|
+
this.store = store;
|
|
78
|
+
this.now = now;
|
|
79
|
+
this.locks = locks;
|
|
80
|
+
}
|
|
81
|
+
/** A proof for one request. `accessToken` is included by hash when the request carries one. */
|
|
82
|
+
async proof(method, url, accessToken) {
|
|
83
|
+
const { privateKey, publicJwk } = await this.key();
|
|
84
|
+
const target = new URL(url);
|
|
85
|
+
const claims = {
|
|
86
|
+
jti: crypto.randomUUID(),
|
|
87
|
+
htm: method.toUpperCase(),
|
|
88
|
+
// The proof covers the URL without its query string and fragment.
|
|
89
|
+
htu: `${target.origin}${target.pathname}`,
|
|
90
|
+
iat: Math.floor(this.now() / 1000),
|
|
91
|
+
};
|
|
92
|
+
if (accessToken !== undefined) {
|
|
93
|
+
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(accessToken));
|
|
94
|
+
claims.ath = base64url.encode(new Uint8Array(digest));
|
|
95
|
+
}
|
|
96
|
+
return new SignJWT(claims).setProtectedHeader({ alg: 'ES256', typ: 'dpop+jwt', jwk: publicJwk }).sign(privateKey);
|
|
97
|
+
}
|
|
98
|
+
/** The RFC 7638 thumbprint the server knows this device by. */
|
|
99
|
+
async thumbprint() {
|
|
100
|
+
return calculateJwkThumbprint((await this.key()).publicJwk);
|
|
101
|
+
}
|
|
102
|
+
key() {
|
|
103
|
+
this.loading ??= this.loadOrCreate().catch((error) => {
|
|
104
|
+
this.loading = null;
|
|
105
|
+
throw error;
|
|
106
|
+
});
|
|
107
|
+
return this.loading;
|
|
108
|
+
}
|
|
109
|
+
async loadOrCreate() {
|
|
110
|
+
const existing = await this.store.load();
|
|
111
|
+
if (existing)
|
|
112
|
+
return this.describe(existing);
|
|
113
|
+
// Two tabs opening at once must agree on one key, so creation happens under a lock.
|
|
114
|
+
const create = async () => {
|
|
115
|
+
const raced = await this.store.load();
|
|
116
|
+
if (raced)
|
|
117
|
+
return raced;
|
|
118
|
+
const generated = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign', 'verify']);
|
|
119
|
+
await this.store.save(generated);
|
|
120
|
+
return generated;
|
|
121
|
+
};
|
|
122
|
+
const pair = this.locks ? await this.locks.request('koshi-auth:dpop-key', create) : await create();
|
|
123
|
+
return this.describe(pair);
|
|
124
|
+
}
|
|
125
|
+
async describe(pair) {
|
|
126
|
+
const exported = await crypto.subtle.exportKey('jwk', pair.publicKey);
|
|
127
|
+
const publicJwk = { kty: exported.kty, crv: exported.crv, x: exported.x, y: exported.y };
|
|
128
|
+
return { privateKey: pair.privateKey, publicJwk };
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
//# sourceMappingURL=dpop.js.map
|
package/dist/dpop.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dpop.js","sourceRoot":"","sources":["../src/dpop.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,sBAAsB,EAAY,MAAM,MAAM,CAAC;AAU5E,mGAAmG;AACnG,MAAM,UAAU,cAAc;IAC5B,IAAI,MAAM,GAAyB,IAAI,CAAC;IACxC,OAAO;QACL,IAAI,EAAE,KAAK,IAAI,EAAE,CA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,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,MAAM,EAAE,CAAC;QACnG,OAAO,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC7B,CAAC;IAEO,KAAK,CAAC,QAAQ,CAAC,IAAmB;QACxC,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;QACtE,MAAM,SAAS,GAAQ,EAAE,GAAG,EAAE,QAAQ,CAAC,GAAa,EAAE,GAAG,EAAE,QAAQ,CAAC,GAAa,EAAE,CAAC,EAAE,QAAQ,CAAC,CAAW,EAAE,CAAC,EAAE,QAAQ,CAAC,CAAW,EAAE,CAAC;QACtI,OAAO,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU,EAAE,SAAS,EAAE,CAAC;IACpD,CAAC;CACF"}
|
package/dist/guards.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { Rbac } from '@koshirepo/auth-core';
|
|
2
|
+
import type { AuthState } from './types.js';
|
|
3
|
+
/** What a route or a piece of interface needs. Every field given must hold. */
|
|
4
|
+
export interface GuardRequirement {
|
|
5
|
+
/** The user needs at least one of these roles. */
|
|
6
|
+
roles?: readonly string[];
|
|
7
|
+
/** The user needs all of these permissions, resolved through the role map. */
|
|
8
|
+
permissions?: readonly string[];
|
|
9
|
+
/** Two factors, or a passkey with user verification. */
|
|
10
|
+
assurance?: 'aal2';
|
|
11
|
+
/** The last interactive authentication must be at most this old. */
|
|
12
|
+
maxAuthAgeSec?: number;
|
|
13
|
+
}
|
|
14
|
+
export type GuardResult = {
|
|
15
|
+
status: 'allow';
|
|
16
|
+
}
|
|
17
|
+
/** The session is still being restored. Render nothing or a placeholder. */
|
|
18
|
+
| {
|
|
19
|
+
status: 'pending';
|
|
20
|
+
} | {
|
|
21
|
+
status: 'deny';
|
|
22
|
+
/**
|
|
23
|
+
* What would help: `login` and `mfa` continue the sign-in, `step_up` means re-authenticate,
|
|
24
|
+
* `forbidden` means nothing will.
|
|
25
|
+
*/
|
|
26
|
+
action: 'login' | 'mfa' | 'step_up' | 'forbidden';
|
|
27
|
+
reason: string;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Decides what to show for a state and a requirement. It performs no navigation: your router
|
|
31
|
+
* decides what each `action` means.
|
|
32
|
+
*
|
|
33
|
+
* This is an interface convenience. A user can change anything in their own browser, so access
|
|
34
|
+
* is always enforced again by the server.
|
|
35
|
+
*/
|
|
36
|
+
export declare function evaluateGuard(state: AuthState, requirement: GuardRequirement | undefined, options: {
|
|
37
|
+
rbac?: Rbac<string, string> | undefined;
|
|
38
|
+
nowSec: number;
|
|
39
|
+
}): GuardResult;
|
|
40
|
+
//# sourceMappingURL=guards.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guards.d.ts","sourceRoot":"","sources":["../src/guards.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,sBAAsB,CAAC;AACjD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE5C,+EAA+E;AAC/E,MAAM,WAAW,gBAAgB;IAC/B,kDAAkD;IAClD,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1B,8EAA8E;IAC9E,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAChC,wDAAwD;IACxD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,oEAAoE;IACpE,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,MAAM,WAAW,GACnB;IAAE,MAAM,EAAE,OAAO,CAAA;CAAE;AACrB,4EAA4E;GAC1E;IAAE,MAAM,EAAE,SAAS,CAAA;CAAE,GACrB;IACE,MAAM,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,MAAM,EAAE,OAAO,GAAG,KAAK,GAAG,SAAS,GAAG,WAAW,CAAC;IAClD,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEN;;;;;;GAMG;AACH,wBAAgB,aAAa,CAC3B,KAAK,EAAE,SAAS,EAChB,WAAW,EAAE,gBAAgB,YAAK,EAClC,OAAO,EAAE;IAAE,IAAI,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACnE,WAAW,CA2Bb"}
|
package/dist/guards.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Decides what to show for a state and a requirement. It performs no navigation: your router
|
|
3
|
+
* decides what each `action` means.
|
|
4
|
+
*
|
|
5
|
+
* This is an interface convenience. A user can change anything in their own browser, so access
|
|
6
|
+
* is always enforced again by the server.
|
|
7
|
+
*/
|
|
8
|
+
export function evaluateGuard(state, requirement = {}, options) {
|
|
9
|
+
if (state.status === 'loading')
|
|
10
|
+
return { status: 'pending' };
|
|
11
|
+
if (state.status === 'unauthenticated')
|
|
12
|
+
return { status: 'deny', action: 'login', reason: 'not signed in' };
|
|
13
|
+
if (state.status === 'mfa_required')
|
|
14
|
+
return { status: 'deny', action: 'mfa', reason: 'a second factor is required' };
|
|
15
|
+
const { user, session } = state;
|
|
16
|
+
if (requirement.roles && requirement.roles.length > 0 && !requirement.roles.some((role) => user.roles.includes(role))) {
|
|
17
|
+
return { status: 'deny', action: 'forbidden', reason: `requires one of the roles: ${requirement.roles.join(', ')}` };
|
|
18
|
+
}
|
|
19
|
+
if (requirement.permissions && requirement.permissions.length > 0) {
|
|
20
|
+
if (!options.rbac) {
|
|
21
|
+
return { status: 'deny', action: 'forbidden', reason: 'no role map is configured to resolve permissions' };
|
|
22
|
+
}
|
|
23
|
+
const granted = options.rbac.permissionsFor(user.roles);
|
|
24
|
+
const missing = requirement.permissions.filter((permission) => !granted.has(permission));
|
|
25
|
+
if (missing.length > 0) {
|
|
26
|
+
return { status: 'deny', action: 'forbidden', reason: `missing permission: ${missing.join(', ')}` };
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
// Step-up comes last: there is no point asking for it if the user lacks the permission anyway.
|
|
30
|
+
if (requirement.assurance === 'aal2' && session.assurance !== 'aal2') {
|
|
31
|
+
return { status: 'deny', action: 'step_up', reason: 'requires a second factor' };
|
|
32
|
+
}
|
|
33
|
+
if (requirement.maxAuthAgeSec !== undefined && options.nowSec - session.authenticatedAt > requirement.maxAuthAgeSec) {
|
|
34
|
+
return { status: 'deny', action: 'step_up', reason: 'requires a recent sign-in' };
|
|
35
|
+
}
|
|
36
|
+
return { status: 'allow' };
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=guards.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guards.js","sourceRoot":"","sources":["../src/guards.ts"],"names":[],"mappings":"AA6BA;;;;;;GAMG;AACH,MAAM,UAAU,aAAa,CAC3B,KAAgB,EAChB,WAAW,GAAqB,EAAE,EAClC,OAAoE;IAEpE,IAAI,KAAK,CAAC,MAAM,KAAK,SAAS;QAAE,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;IAC7D,IAAI,KAAK,CAAC,MAAM,KAAK,iBAAiB;QAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,CAAC;IAC5G,IAAI,KAAK,CAAC,MAAM,KAAK,cAAc;QAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,6BAA6B,EAAE,CAAC;IAErH,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC;IAChC,IAAI,WAAW,CAAC,KAAK,IAAI,WAAW,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CA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AAG,WAAW,CAAC,aAAa,EAAE,CAAC;QACpH,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,2BAA2B,EAAE,CAAC;IACpF,CAAC;IACD,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;AAC7B,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { createAuthClient } from './client.js';
|
|
2
|
+
export type { AuthClient, AuthClientOptions, AuthState, ReauthFactor, WebAuthnBrowser } from './types.js';
|
|
3
|
+
export { evaluateGuard, type GuardRequirement, type GuardResult } from './guards.js';
|
|
4
|
+
export { DpopSigner, defaultKeyStore, indexedDbKeyStore, memoryKeyStore, type DpopKeyStore } from './dpop.js';
|
|
5
|
+
export { defaultLocks, inPageLocks, type LockManagerLike } from './locks.js';
|
|
6
|
+
export { broadcastChannel, type ChannelLike, type ChannelMessage } from './channel.js';
|
|
7
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,YAAY,EAAE,UAAU,EAAE,iBAAiB,EAAE,SAAS,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC1G,OAAO,EAAE,aAAa,EAAE,KAAK,gBAAgB,EAAE,KAAK,WAAW,EAAE,MAAM,aAAa,CAAC;AACrF,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,iBAAiB,EAAE,cAAc,EAAE,KAAK,YAAY,EAAE,MAAM,WAAW,CAAC;AAC9G,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,KAAK,eAAe,EAAE,MAAM,YAAY,CAAC;AAC7E,OAAO,EAAE,gBAAgB,EAAE,KAAK,WAAW,EAAE,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { createAuthClient } from './client.js';
|
|
2
|
+
export { evaluateGuard } from './guards.js';
|
|
3
|
+
export { DpopSigner, defaultKeyStore, indexedDbKeyStore, memoryKeyStore } from './dpop.js';
|
|
4
|
+
export { defaultLocks, inPageLocks } from './locks.js';
|
|
5
|
+
export { broadcastChannel } from './channel.js';
|
|
6
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/C,OAAO,EAAE,aAAa,EAA2C,MAAM,aAAa,CAAC;AACrF,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,iBAAiB,EAAE,cAAc,EAAqB,MAAM,WAAW,CAAC;AAC9G,OAAO,EAAE,YAAY,EAAE,WAAW,EAAwB,MAAM,YAAY,CAAC;AAC7E,OAAO,EAAE,gBAAgB,EAAyC,MAAM,cAAc,CAAC"}
|
package/dist/locks.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** The part of the Web Locks API the client uses. */
|
|
2
|
+
export interface LockManagerLike {
|
|
3
|
+
/** Runs `callback` while holding the named lock, and resolves with its result. */
|
|
4
|
+
request<T>(name: string, callback: () => Promise<T>): Promise<T>;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* A lock that works inside one page only. Used when the Web Locks API is missing. It still
|
|
8
|
+
* serialises several clients in the same page, but not several tabs.
|
|
9
|
+
*/
|
|
10
|
+
export declare const inPageLocks: LockManagerLike;
|
|
11
|
+
/** The browser's lock manager when there is one, which also coordinates across tabs. */
|
|
12
|
+
export declare function defaultLocks(): LockManagerLike;
|
|
13
|
+
//# sourceMappingURL=locks.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"locks.d.ts","sourceRoot":"","sources":["../src/locks.ts"],"names":[],"mappings":"AAAA,qDAAqD;AACrD,MAAM,WAAW,eAAe;IAC9B,kFAAkF;IAClF,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CAClE;AAID;;;GAGG;AACH,eAAO,MAAM,WAAW,EAAE,eAczB,CAAC;AAEF,wFAAwF;AACxF,wBAAgB,YAAY,IAAI,eAAe,CAO9C"}
|
package/dist/locks.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
const queues = new Map();
|
|
2
|
+
/**
|
|
3
|
+
* A lock that works inside one page only. Used when the Web Locks API is missing. It still
|
|
4
|
+
* serialises several clients in the same page, but not several tabs.
|
|
5
|
+
*/
|
|
6
|
+
export const inPageLocks = {
|
|
7
|
+
request(name, callback) {
|
|
8
|
+
const previous = queues.get(name) ?? Promise.resolve();
|
|
9
|
+
const result = previous.then(callback);
|
|
10
|
+
const settled = result.then(() => undefined, () => undefined);
|
|
11
|
+
queues.set(name, settled);
|
|
12
|
+
void settled.then(() => {
|
|
13
|
+
if (queues.get(name) === settled)
|
|
14
|
+
queues.delete(name);
|
|
15
|
+
});
|
|
16
|
+
return result;
|
|
17
|
+
},
|
|
18
|
+
};
|
|
19
|
+
/** The browser's lock manager when there is one, which also coordinates across tabs. */
|
|
20
|
+
export function defaultLocks() {
|
|
21
|
+
const locks = globalThis.navigator?.locks;
|
|
22
|
+
if (locks && typeof locks.request === 'function') {
|
|
23
|
+
const manager = locks;
|
|
24
|
+
return { request: (name, callback) => manager.request(name, callback) };
|
|
25
|
+
}
|
|
26
|
+
return inPageLocks;
|
|
27
|
+
}
|
|
28
|
+
//# sourceMappingURL=locks.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"locks.js","sourceRoot":"","sources":["../src/locks.ts"],"names":[],"mappings":"AAMA,MAAM,MAAM,GAAG,IAAI,GAAG,EAAyB,CAAC;AAEhD;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAoB;IAC1C,OAAO,CAAI,IAAY,EAAE,QAA0B;QACjD,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;QACvD,MAAM,MAAM,GAAG,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACvC,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CACzB,GAAG,EAAE,CAAC,SAAS,EACf,GAAG,EAAE,CAAC,SAAS,CAChB,CAAC;QACF,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC1B,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE;YACrB,IAAI,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,OAAO;gBAAE,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QACxD,CAAC,CAAC,CAAC;QACH,OAAO,MAAM,CAAC;IAChB,CAAC;CACF,CAAC;AAEF,wFAAwF;AACxF,MAAM,UAAU,YAAY;IAC1B,MAAM,KAAK,GAAI,UAAgE,CAAC,SAAS,EAAE,KAAK,CAAC;IACjG,IAAI,KAAK,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;QACjD,MAAM,OAAO,GAAG,KAAwF,CAAC;QACzG,OAAO,EAAE,OAAO,EAAE,CAAC,IAAI,EAAE,QAAQ,EAAE,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,EAAE,CAAC;IAC1E,CAAC;IACD,OAAO,WAAW,CAAC;AACrB,CAAC"}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* React bindings. Everything here is headless: there is no markup, class name or style.
|
|
3
|
+
* `AuthProvider` and `AuthGuard` render only what you pass them.
|
|
4
|
+
*/
|
|
5
|
+
import type { AuthError, MfaMethod, PublicUser, SessionInfo } from '@koshirepo/auth-core';
|
|
6
|
+
import { type ReactElement, type ReactNode } from 'react';
|
|
7
|
+
import type { GuardRequirement, GuardResult } from '../guards.js';
|
|
8
|
+
import type { AuthClient, AuthState } from '../types.js';
|
|
9
|
+
/** Makes a client available to the hooks below. */
|
|
10
|
+
export declare function AuthProvider(props: {
|
|
11
|
+
client: AuthClient;
|
|
12
|
+
children?: ReactNode;
|
|
13
|
+
}): ReactElement;
|
|
14
|
+
/** The client given to the nearest `AuthProvider`. */
|
|
15
|
+
export declare function useAuthClient(): AuthClient;
|
|
16
|
+
/** The current auth state. The component re-renders whenever it changes. */
|
|
17
|
+
export declare function useAuthState(): AuthState;
|
|
18
|
+
export interface UseAuthResult {
|
|
19
|
+
state: AuthState;
|
|
20
|
+
/** True while the session is being restored on page load. */
|
|
21
|
+
isLoading: boolean;
|
|
22
|
+
isAuthenticated: boolean;
|
|
23
|
+
user: PublicUser | null;
|
|
24
|
+
session: SessionInfo | null;
|
|
25
|
+
logout: AuthClient['logout'];
|
|
26
|
+
client: AuthClient;
|
|
27
|
+
}
|
|
28
|
+
/** State plus the most common derived values. */
|
|
29
|
+
export declare function useAuth(): UseAuthResult;
|
|
30
|
+
export interface UseLoginResult {
|
|
31
|
+
state: AuthState;
|
|
32
|
+
loginWithPassword(input: {
|
|
33
|
+
identifier: string;
|
|
34
|
+
password: string;
|
|
35
|
+
}): Promise<AuthState | undefined>;
|
|
36
|
+
loginWithPasskey(input?: {
|
|
37
|
+
identifier?: string;
|
|
38
|
+
}): Promise<AuthState | undefined>;
|
|
39
|
+
submitMfa(input: {
|
|
40
|
+
method: MfaMethod;
|
|
41
|
+
code: string;
|
|
42
|
+
}): Promise<AuthState | undefined>;
|
|
43
|
+
cancelMfa(): void;
|
|
44
|
+
/** True while a request is in flight. */
|
|
45
|
+
pending: boolean;
|
|
46
|
+
/** The error of the last attempt, or null. Show `error.message`, which is always safe to display. */
|
|
47
|
+
error: AuthError | Error | null;
|
|
48
|
+
reset(): void;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Sign-in actions with `pending` and `error` tracked for you. The actions resolve with the new
|
|
52
|
+
* state, or with `undefined` after a failure, which is reported through `error` instead of thrown.
|
|
53
|
+
*/
|
|
54
|
+
export declare function useLogin(): UseLoginResult;
|
|
55
|
+
/** The guard decision for a requirement, re-evaluated whenever the auth state changes. */
|
|
56
|
+
export declare function useGuard(requirement?: GuardRequirement): GuardResult;
|
|
57
|
+
/** Whether the signed-in user may do `action`, according to the roles and policies given to the client. */
|
|
58
|
+
export declare function useCan(action: string, resource?: unknown, context?: Record<string, unknown>): boolean;
|
|
59
|
+
export interface AuthGuardProps {
|
|
60
|
+
require?: GuardRequirement;
|
|
61
|
+
/** Rendered when access is denied. Receives the decision, so it can redirect to login or step-up. */
|
|
62
|
+
fallback?: ReactNode | ((result: Extract<GuardResult, {
|
|
63
|
+
status: 'deny';
|
|
64
|
+
}>) => ReactNode);
|
|
65
|
+
/** Rendered while the session is being restored. Default: nothing. */
|
|
66
|
+
pending?: ReactNode;
|
|
67
|
+
children?: ReactNode;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Renders its children when the requirement is met, `pending` while the session is loading, and
|
|
71
|
+
* `fallback` otherwise. It hides interface. It does not protect data: the server does that.
|
|
72
|
+
*/
|
|
73
|
+
export declare function AuthGuard(props: AuthGuardProps): ReactNode;
|
|
74
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/react/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAC1F,OAAO,EAQL,KAAK,YAAY,EACjB,KAAK,SAAS,EACf,MAAM,OAAO,CAAC;AACf,OA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,CAAC;IAClB,yCAAyC;IACzC,OAAO,EAAE,OAAO,CAAC;IACjB,qGAAqG;IACrG,KAAK,EAAE,SAAS,GAAG,KAAK,GAAG,IAAI,CAAC;IAChC,KAAK,IAAI,IAAI,CAAC;CACf;AAED;;;GAGG;AACH,wBAAgB,QAAQ,IAAI,cAAc,CAmCzC;AAED,0FAA0F;AAC1F,wBAAgB,QAAQ,CAAC,WAAW,CAAC,EAAE,gBAAgB,GAAG,WAAW,CAIpE;AAED,2GAA2G;AAC3G,wBAAgB,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAIrG;AAED,MAAM,WAAW,cAAc;IAC7B,OAAO,CAAC,EAAE,gBAAgB,CAAC;IAC3B,qGAAqG;IACrG,QAAQ,CAAC,EAAE,SAAS,GAAG,CAAC,CAAC,MAAM,EAAE,OAAO,CAAC,WAAW,EAAE;QAAE,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,KAAK,SAAS,CAAC,CAAC;IACzF,sEAAsE;IACtE,OAAO,CAAC,EAAE,SAAS,CAAC;IACpB,QAAQ,CAAC,EAAE,SAAS,CAAC;CACtB;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,cAAc,GAAG,SAAS,CAK1D"}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { createContext, createElement, useCallback, useContext, useMemo, useState, useSyncExternalStore, } from 'react';
|
|
2
|
+
const AuthClientContext = createContext(null);
|
|
3
|
+
/** Makes a client available to the hooks below. */
|
|
4
|
+
export function AuthProvider(props) {
|
|
5
|
+
return createElement(AuthClientContext.Provider, { value: props.client }, props.children);
|
|
6
|
+
}
|
|
7
|
+
/** The client given to the nearest `AuthProvider`. */
|
|
8
|
+
export function useAuthClient() {
|
|
9
|
+
const client = useContext(AuthClientContext);
|
|
10
|
+
if (!client)
|
|
11
|
+
throw new Error('useAuthClient must be used inside an <AuthProvider>.');
|
|
12
|
+
return client;
|
|
13
|
+
}
|
|
14
|
+
/** The current auth state. The component re-renders whenever it changes. */
|
|
15
|
+
export function useAuthState() {
|
|
16
|
+
const client = useAuthClient();
|
|
17
|
+
return useSyncExternalStore(client.subscribe, client.getState, client.getState);
|
|
18
|
+
}
|
|
19
|
+
/** State plus the most common derived values. */
|
|
20
|
+
export function useAuth() {
|
|
21
|
+
const client = useAuthClient();
|
|
22
|
+
const state = useAuthState();
|
|
23
|
+
return useMemo(() => ({
|
|
24
|
+
state,
|
|
25
|
+
isLoading: state.status === 'loading',
|
|
26
|
+
isAuthenticated: state.status === 'authenticated',
|
|
27
|
+
user: state.status === 'authenticated' ? state.user : null,
|
|
28
|
+
session: state.status === 'authenticated' ? state.session : null,
|
|
29
|
+
logout: client.logout,
|
|
30
|
+
client,
|
|
31
|
+
}), [client, state]);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Sign-in actions with `pending` and `error` tracked for you. The actions resolve with the new
|
|
35
|
+
* state, or with `undefined` after a failure, which is reported through `error` instead of thrown.
|
|
36
|
+
*/
|
|
37
|
+
export function useLogin() {
|
|
38
|
+
const client = useAuthClient();
|
|
39
|
+
const state = useAuthState();
|
|
40
|
+
const [pending, setPending] = useState(false);
|
|
41
|
+
const [error, setError] = useState(null);
|
|
42
|
+
const run = useCallback(async (action) => {
|
|
43
|
+
setPending(true);
|
|
44
|
+
setError(null);
|
|
45
|
+
try {
|
|
46
|
+
return await action();
|
|
47
|
+
}
|
|
48
|
+
catch (caught) {
|
|
49
|
+
setError(caught instanceof Error ? caught : new Error(String(caught)));
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
finally {
|
|
53
|
+
setPending(false);
|
|
54
|
+
}
|
|
55
|
+
}, []);
|
|
56
|
+
return useMemo(() => ({
|
|
57
|
+
state,
|
|
58
|
+
loginWithPassword: (input) => run(() => client.loginWithPassword(input)),
|
|
59
|
+
loginWithPasskey: (input) => run(() => client.loginWithPasskey(input)),
|
|
60
|
+
submitMfa: (input) => run(() => client.submitMfa(input)),
|
|
61
|
+
cancelMfa: () => {
|
|
62
|
+
setError(null);
|
|
63
|
+
client.cancelMfa();
|
|
64
|
+
},
|
|
65
|
+
pending,
|
|
66
|
+
error,
|
|
67
|
+
reset: () => setError(null),
|
|
68
|
+
}), [client, state, run, pending, error]);
|
|
69
|
+
}
|
|
70
|
+
/** The guard decision for a requirement, re-evaluated whenever the auth state changes. */
|
|
71
|
+
export function useGuard(requirement) {
|
|
72
|
+
const client = useAuthClient();
|
|
73
|
+
useAuthState();
|
|
74
|
+
return client.check(requirement);
|
|
75
|
+
}
|
|
76
|
+
/** Whether the signed-in user may do `action`, according to the roles and policies given to the client. */
|
|
77
|
+
export function useCan(action, resource, context) {
|
|
78
|
+
const client = useAuthClient();
|
|
79
|
+
useAuthState();
|
|
80
|
+
return client.can(action, resource, context);
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Renders its children when the requirement is met, `pending` while the session is loading, and
|
|
84
|
+
* `fallback` otherwise. It hides interface. It does not protect data: the server does that.
|
|
85
|
+
*/
|
|
86
|
+
export function AuthGuard(props) {
|
|
87
|
+
const result = useGuard(props.require);
|
|
88
|
+
if (result.status === 'allow')
|
|
89
|
+
return props.children ?? null;
|
|
90
|
+
if (result.status === 'pending')
|
|
91
|
+
return props.pending ?? null;
|
|
92
|
+
return typeof props.fallback === 'function' ? props.fallback(result) : (props.fallback ?? null);
|
|
93
|
+
}
|
|
94
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/react/index.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,aAAa,EACb,aAAa,EACb,WAAW,EACX,UAAU,EACV,OAAO,EACP,QAAQ,EACR,oBAAoB,GAGrB,MAAM,OAAO,CAAC;AAIf,MAAM,iBAAiB,GAAG,aAA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package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import type { AccountSecurity, MfaMethod, PasskeyInfo, Policy, PublicUser, Rbac, SessionInfo } from '@koshirepo/auth-core';
|
|
2
|
+
import type { ChannelLike } from './channel.js';
|
|
3
|
+
import type { DpopKeyStore } from './dpop.js';
|
|
4
|
+
import type { GuardRequirement, GuardResult } from './guards.js';
|
|
5
|
+
import type { LockManagerLike } from './locks.js';
|
|
6
|
+
/** Everything the interface needs to know about who is signed in. */
|
|
7
|
+
export type AuthState =
|
|
8
|
+
/** The client is restoring a session from the cookie. Render nothing or a placeholder. */
|
|
9
|
+
{
|
|
10
|
+
status: 'loading';
|
|
11
|
+
} | {
|
|
12
|
+
status: 'unauthenticated';
|
|
13
|
+
}
|
|
14
|
+
/** The first factor succeeded. Call `submitMfa` with a code. */
|
|
15
|
+
| {
|
|
16
|
+
status: 'mfa_required';
|
|
17
|
+
methods: MfaMethod[];
|
|
18
|
+
reason: 'enrolled' | 'risk';
|
|
19
|
+
expiresAt: number;
|
|
20
|
+
} | {
|
|
21
|
+
status: 'authenticated';
|
|
22
|
+
user: PublicUser;
|
|
23
|
+
session: SessionInfo;
|
|
24
|
+
};
|
|
25
|
+
/** The browser half of the WebAuthn ceremonies. `@simplewebauthn/browser` has exactly this shape. */
|
|
26
|
+
export interface WebAuthnBrowser {
|
|
27
|
+
startRegistration(input: {
|
|
28
|
+
optionsJSON: never;
|
|
29
|
+
}): Promise<unknown>;
|
|
30
|
+
startAuthentication(input: {
|
|
31
|
+
optionsJSON: never;
|
|
32
|
+
}): Promise<unknown>;
|
|
33
|
+
}
|
|
34
|
+
/** A factor presented to re-authenticate inside the current session. */
|
|
35
|
+
export type ReauthFactor = {
|
|
36
|
+
method: 'password';
|
|
37
|
+
password: string;
|
|
38
|
+
} | {
|
|
39
|
+
method: MfaMethod;
|
|
40
|
+
code: string;
|
|
41
|
+
}
|
|
42
|
+
/** Runs the passkey ceremony in the browser. */
|
|
43
|
+
| {
|
|
44
|
+
method: 'passkey';
|
|
45
|
+
};
|
|
46
|
+
export interface AuthClientOptions {
|
|
47
|
+
/**
|
|
48
|
+
* Where the auth endpoints live, for example `https://api.example.com/auth`. A path such as
|
|
49
|
+
* `/auth` is resolved against the page's origin.
|
|
50
|
+
*/
|
|
51
|
+
baseUrl: string;
|
|
52
|
+
/** Default: the global `fetch`. */
|
|
53
|
+
fetch?: typeof fetch;
|
|
54
|
+
/**
|
|
55
|
+
* Device binding. Default `true`: an ES256 key is created with WebCrypto, marked non-extractable
|
|
56
|
+
* and kept in IndexedDB, and every request carries a DPoP proof signed by it. Pass
|
|
57
|
+
* `{ keyStore }` to control where the key lives, or `false` if the server has binding off.
|
|
58
|
+
*/
|
|
59
|
+
dpop?: boolean | {
|
|
60
|
+
keyStore?: DpopKeyStore;
|
|
61
|
+
};
|
|
62
|
+
/** The role map and policies the server uses, for `check()`, `can()` and the React guards. */
|
|
63
|
+
access?: {
|
|
64
|
+
rbac?: Rbac<string, string>;
|
|
65
|
+
policies?: readonly Policy<any, any, any, any>[];
|
|
66
|
+
};
|
|
67
|
+
/** Refresh this many seconds before the access token expires. Default 30. */
|
|
68
|
+
refreshSkewSec?: number;
|
|
69
|
+
/** Try to restore the session from the cookie as soon as the client is created. Default true. */
|
|
70
|
+
restoreOnStart?: boolean;
|
|
71
|
+
/**
|
|
72
|
+
* Serialises refreshes across tabs. Default: the Web Locks API, falling back to a lock inside
|
|
73
|
+
* this page. Pass `null` to disable, which makes two tabs refreshing at once trip reuse detection.
|
|
74
|
+
*/
|
|
75
|
+
locks?: LockManagerLike | null;
|
|
76
|
+
/** Tells other tabs about sign-in and sign-out. Default: a `BroadcastChannel`. Pass `null` to disable. */
|
|
77
|
+
channel?: ChannelLike | null;
|
|
78
|
+
/** Default: `@simplewebauthn/browser`, loaded on first use. */
|
|
79
|
+
webauthn?: WebAuthnBrowser;
|
|
80
|
+
/** Epoch milliseconds. Default `Date.now`. */
|
|
81
|
+
now?: () => number;
|
|
82
|
+
}
|
|
83
|
+
export interface AuthClient {
|
|
84
|
+
getState(): AuthState;
|
|
85
|
+
/** Calls `listener` on every state change. Returns a function that unsubscribes. */
|
|
86
|
+
subscribe(listener: (state: AuthState) => void): () => void;
|
|
87
|
+
/** Settles once the initial session restore has finished. Never rejects. */
|
|
88
|
+
ready(): Promise<AuthState>;
|
|
89
|
+
loginWithPassword(input: {
|
|
90
|
+
identifier: string;
|
|
91
|
+
password: string;
|
|
92
|
+
}): Promise<AuthState>;
|
|
93
|
+
loginWithPasskey(input?: {
|
|
94
|
+
identifier?: string;
|
|
95
|
+
}): Promise<AuthState>;
|
|
96
|
+
submitMfa(input: {
|
|
97
|
+
method: MfaMethod;
|
|
98
|
+
code: string;
|
|
99
|
+
}): Promise<AuthState>;
|
|
100
|
+
/** Abandons a login that is waiting for its second factor. */
|
|
101
|
+
cancelMfa(): void;
|
|
102
|
+
reauthenticate(factor: ReauthFactor): Promise<AuthState>;
|
|
103
|
+
logout(options?: {
|
|
104
|
+
allSessions?: boolean;
|
|
105
|
+
}): Promise<void>;
|
|
106
|
+
/**
|
|
107
|
+
* The current access token, refreshed first if it is about to expire. Null when signed out.
|
|
108
|
+
* Concurrent callers share one refresh request.
|
|
109
|
+
*/
|
|
110
|
+
getAccessToken(options?: {
|
|
111
|
+
forceRefresh?: boolean;
|
|
112
|
+
}): Promise<string | null>;
|
|
113
|
+
/**
|
|
114
|
+
* `fetch` with the access token and a DPoP proof attached. On a 401 it refreshes once and
|
|
115
|
+
* retries once.
|
|
116
|
+
*/
|
|
117
|
+
fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
|
|
118
|
+
mfa: {
|
|
119
|
+
status(): Promise<AccountSecurity>;
|
|
120
|
+
beginTotpEnrollment(): Promise<{
|
|
121
|
+
enrollmentId: string;
|
|
122
|
+
secret: string;
|
|
123
|
+
otpauthUri: string;
|
|
124
|
+
}>;
|
|
125
|
+
confirmTotpEnrollment(input: {
|
|
126
|
+
enrollmentId: string;
|
|
127
|
+
code: string;
|
|
128
|
+
}): Promise<{
|
|
129
|
+
recoveryCodes: string[];
|
|
130
|
+
}>;
|
|
131
|
+
removeTotp(): Promise<void>;
|
|
132
|
+
regenerateRecoveryCodes(): Promise<string[]>;
|
|
133
|
+
};
|
|
134
|
+
passkeys: {
|
|
135
|
+
register(input?: {
|
|
136
|
+
name?: string;
|
|
137
|
+
}): Promise<PasskeyInfo>;
|
|
138
|
+
list(): Promise<PasskeyInfo[]>;
|
|
139
|
+
remove(id: string): Promise<void>;
|
|
140
|
+
};
|
|
141
|
+
sessions: {
|
|
142
|
+
list(): Promise<SessionInfo[]>;
|
|
143
|
+
revoke(id: string): Promise<void>;
|
|
144
|
+
};
|
|
145
|
+
changePassword(input: {
|
|
146
|
+
currentPassword: string;
|
|
147
|
+
newPassword: string;
|
|
148
|
+
}): Promise<void>;
|
|
149
|
+
check(requirement?: GuardRequirement): GuardResult;
|
|
150
|
+
can(action: string, resource?: unknown, context?: Record<string, unknown>): boolean;
|
|
151
|
+
/** Stops listening to other tabs. Call it when the client is thrown away, for example in tests. */
|
|
152
|
+
dispose(): void;
|
|
153
|
+
}
|
|
154
|
+
//# sourceMappingURL=types.d.ts.map
|