@aooth/auth 0.1.84 → 0.2.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/atscript-db.cjs +80 -4
- package/dist/atscript-db.d.cts +51 -10
- package/dist/atscript-db.d.mts +51 -10
- package/dist/atscript-db.mjs +79 -5
- package/dist/{auth-credential-CLAQgjCS.d.mts → auth-credential-BsH0E8hG.d.mts} +73 -9
- package/dist/{auth-credential-GRAK230V.d.cts → auth-credential-D1V5-2uy.d.cts} +73 -9
- package/dist/authz.d.cts +2 -2
- package/dist/authz.d.mts +2 -2
- package/dist/client.cjs +25 -12
- package/dist/client.d.cts +59 -13
- package/dist/client.d.mts +59 -13
- package/dist/client.mjs +25 -12
- package/dist/{clock-CyjqzLxc.d.cts → clock-CzAaCoZ5.d.cts} +7 -0
- package/dist/{clock-CyjqzLxc.d.mts → clock-CzAaCoZ5.d.mts} +7 -0
- package/dist/{dynamic-client-store-BF4nXMK2.d.mts → dynamic-client-store-CUGQiS08.d.mts} +2 -2
- package/dist/{dynamic-client-store-HLfcl2FJ.d.cts → dynamic-client-store-D0RDGSSJ.d.cts} +2 -2
- package/dist/index.cjs +276 -113
- package/dist/index.d.cts +26 -4
- package/dist/index.d.mts +26 -4
- package/dist/index.mjs +253 -91
- package/dist/{payload-HPgyPiek.cjs → payload-C1cQW7p_.cjs} +27 -0
- package/dist/{payload-DP5zRiXT.mjs → payload-DDlf38B-.mjs} +22 -1
- package/dist/redis.cjs +11 -1
- package/dist/redis.d.cts +5 -2
- package/dist/redis.d.mts +5 -2
- package/dist/redis.mjs +11 -1
- package/dist/store-BaFYDHxn.d.cts +69 -0
- package/dist/store-h-bLOAaS.d.mts +69 -0
- package/package.json +6 -6
- package/dist/store-CVD1nd2j.d.mts +0 -41
- package/dist/store-ClQnA8yh.d.cts +0 -41
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as AuthContext, d as RefreshConfig, f as RefreshResult, i as DenylistStore, l as EnrichedSession, m as SessionInfo, o as CredentialMetadata, p as SessionEnricher, r as CredentialStore, s as CredentialState, t as Clock, u as IssueResult } from "./clock-
|
|
1
|
+
import { a as AuthContext, d as RefreshConfig, f as RefreshResult, i as DenylistStore, l as EnrichedSession, m as SessionInfo, o as CredentialMetadata, p as SessionEnricher, r as CredentialStore, s as CredentialState, t as Clock, u as IssueResult } from "./clock-CzAaCoZ5.cjs";
|
|
2
2
|
//#region src/credential/auth-credential.d.ts
|
|
3
3
|
interface AuthCredentialOptions<TPayload extends object = object> {
|
|
4
4
|
/** Pluggable credential store (Memory, JWT, Encapsulated, ...). */
|
|
@@ -48,6 +48,43 @@ interface AuthCredentialOptions<TPayload extends object = object> {
|
|
|
48
48
|
ttlMs: number;
|
|
49
49
|
max?: number;
|
|
50
50
|
};
|
|
51
|
+
/**
|
|
52
|
+
* How tokens are minted and stored. Both options need a store with
|
|
53
|
+
* `persistAs` (memory, Redis, atscript-db — not the stateless JWT /
|
|
54
|
+
* encapsulated stores, whose token IS the state).
|
|
55
|
+
*/
|
|
56
|
+
tokens?: {
|
|
57
|
+
/**
|
|
58
|
+
* Store a SHA-256 of each token instead of the token itself, so a
|
|
59
|
+
* database / backup / replica read yields no usable session, refresh token
|
|
60
|
+
* or PAT. The successor pair kept on a rotated refresh row is encrypted
|
|
61
|
+
* with a key derived from that refresh token (only its holder can read it
|
|
62
|
+
* back during the grace window), and `parentCredentialId` holds the hash.
|
|
63
|
+
* Tokens become 256-bit random strings unless `generate` is given.
|
|
64
|
+
* - `true` — hash every token; rows written before are not found (a
|
|
65
|
+
* one-time sign-out of existing sessions).
|
|
66
|
+
* - `'migrate'` — also look up the token itself when its hash is not
|
|
67
|
+
* found, so existing sessions keep working; a legacy refresh token is
|
|
68
|
+
* re-issued hashed on its next rotation. Switch to `true` once the
|
|
69
|
+
* longest refresh lifetime has passed.
|
|
70
|
+
* Default `false`.
|
|
71
|
+
*/
|
|
72
|
+
hashAtRest?: boolean | "migrate";
|
|
73
|
+
/**
|
|
74
|
+
* Token generator (e.g. to add a recognisable prefix). Must return at
|
|
75
|
+
* least 128 bits of randomness — the stored SHA-256 is only as strong as
|
|
76
|
+
* the token it hashes. Default: 256 random bits, base64url.
|
|
77
|
+
*/
|
|
78
|
+
generate?: () => string;
|
|
79
|
+
/**
|
|
80
|
+
* `'migrate'` only: which presented tokens may be looked up as-is (rows
|
|
81
|
+
* written before hashing). Default: the `randomUUID` shape the bundled
|
|
82
|
+
* stores minted. Pass a predicate when earlier tokens came from a custom
|
|
83
|
+
* `generate`. A 64-hex string (the shape of a stored hash) is never looked
|
|
84
|
+
* up as-is, so a value read from the database cannot be replayed as a token.
|
|
85
|
+
*/
|
|
86
|
+
isLegacyToken?: (token: string) => boolean;
|
|
87
|
+
};
|
|
51
88
|
/** Optional clock for testability. */
|
|
52
89
|
clock?: Clock;
|
|
53
90
|
}
|
|
@@ -166,8 +203,11 @@ declare class AuthCredential<TPayload extends object = object> {
|
|
|
166
203
|
private readonly consumedRefreshes;
|
|
167
204
|
/** Map size at which `consumedRefreshes` next sweeps its expired entries. */
|
|
168
205
|
private consumedSweepAt;
|
|
169
|
-
/** Opt-in validated-state cache (`validateCache`). */
|
|
206
|
+
/** Opt-in validated-state cache (`validateCache`), keyed by store key. */
|
|
170
207
|
private readonly validated?;
|
|
208
|
+
private readonly hashAtRest;
|
|
209
|
+
private readonly generateToken?;
|
|
210
|
+
private readonly isLegacyToken;
|
|
171
211
|
constructor(opts: AuthCredentialOptions<TPayload>);
|
|
172
212
|
issue(userId: string, options?: IssueOptions<TPayload>): Promise<IssueResult>;
|
|
173
213
|
validate(accessToken: string): Promise<AuthContext<TPayload> | null>;
|
|
@@ -176,6 +216,23 @@ declare class AuthCredential<TPayload extends object = object> {
|
|
|
176
216
|
* it — both looked up concurrently (one round trip on remote stores).
|
|
177
217
|
*/
|
|
178
218
|
private retrieveUnlessDenied;
|
|
219
|
+
/** The store key a token's row lives under: its SHA-256 when hashing, else the token. */
|
|
220
|
+
private keyOf;
|
|
221
|
+
/** `credentialId` (the token's SHA-256) of a stored row, from its store key. */
|
|
222
|
+
private fingerprintOfKey;
|
|
223
|
+
/** Persist a new credential; returns the token the client will hold. */
|
|
224
|
+
private put;
|
|
225
|
+
/**
|
|
226
|
+
* Look a token up: by its store key, and — under `hashAtRest: 'migrate'` —
|
|
227
|
+
* by the token itself for a row written before hashing was enabled.
|
|
228
|
+
*/
|
|
229
|
+
private find;
|
|
230
|
+
/**
|
|
231
|
+
* `'migrate'`: may `token` be a row written before hashing, stored under
|
|
232
|
+
* the token itself? Never for a hash-shaped value — that is what a database
|
|
233
|
+
* read yields, and accepting it would turn a leaked row key into a session.
|
|
234
|
+
*/
|
|
235
|
+
private mayBeLegacyKey;
|
|
179
236
|
refresh(refreshToken: string, opts?: RefreshCallOptions<TPayload>): Promise<RefreshResult>;
|
|
180
237
|
private refreshNone;
|
|
181
238
|
/**
|
|
@@ -212,17 +269,16 @@ declare class AuthCredential<TPayload extends object = object> {
|
|
|
212
269
|
*/
|
|
213
270
|
private rotateWithGrace;
|
|
214
271
|
revoke(token: string): Promise<void>;
|
|
272
|
+
/** Revoke the row stored under `key` (a store key, as `listForUser` returns it). */
|
|
273
|
+
private revokeKey;
|
|
215
274
|
revokeAllForUser(userId: string): Promise<number>;
|
|
216
275
|
listForUser(userId: string): Promise<Array<AuthContext<TPayload>>>;
|
|
217
276
|
/**
|
|
218
|
-
*
|
|
219
|
-
*
|
|
220
|
-
*
|
|
221
|
-
* `validate()
|
|
222
|
-
* device" matching stays consistent across all of them.
|
|
277
|
+
* Session-grouping key for a stored credential entry (its store key
|
|
278
|
+
* attached): its stored `sessionId`, or the token fingerprint for legacy
|
|
279
|
+
* rows predating sessionId (so they surface as singleton sessions) — the
|
|
280
|
+
* same fallback `validate()` applies, so "this device" matching holds.
|
|
223
281
|
*/
|
|
224
|
-
private sessionIdOf;
|
|
225
|
-
/** Session-grouping key for a stored credential entry (token attached). */
|
|
226
282
|
private sessionKeyOf;
|
|
227
283
|
/**
|
|
228
284
|
* List the user's active sessions, one row per token family (access +
|
|
@@ -265,6 +321,14 @@ declare class AuthCredential<TPayload extends object = object> {
|
|
|
265
321
|
* rotated (keeping it valid through the grace window) instead of consuming it.
|
|
266
322
|
*/
|
|
267
323
|
private issueRotatedPair;
|
|
324
|
+
/**
|
|
325
|
+
* Under `hashAtRest` the successor pair is stored encrypted with a key
|
|
326
|
+
* derived from the old refresh token — only a holder of that token (the
|
|
327
|
+
* grace-window re-presentation) can read the pair back.
|
|
328
|
+
*/
|
|
329
|
+
private sealSuccessor;
|
|
330
|
+
/** Inverse of {@link sealSuccessor}; `undefined` when the pair cannot be opened. */
|
|
331
|
+
private openSuccessor;
|
|
268
332
|
/** Amortized sweep of expired `consumedRefreshes` entries (each size doubling). */
|
|
269
333
|
private sweepConsumedRefreshes;
|
|
270
334
|
private lookupConsumedRefresh;
|
package/dist/authz.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as Clock } from "./clock-
|
|
2
|
-
import { _ as PendingAuthorizationStoreMemoryOptions, a as DynamicClientStoreMemoryOptions, b as tokenPolicyToIssueOptions, c as AuthCodeStore, d as NewAuthCode, f as DEFAULT_PENDING_TTL_MS, g as PendingAuthorizationStoreMemory, h as PendingAuthorizationStore, i as DynamicClientStoreMemory, l as AuthCodeStoreMemory, m as PendingAuthorization, n as DynamicClientAuthMethod, o as NewDynamicClient, p as NewPendingAuthorization, r as DynamicClientStore, s as AuthCode, t as DynamicClient, u as AuthCodeStoreMemoryOptions, v as DEFAULT_AUTHZ_REFRESH_TTL_MS, y as TokenPolicy } from "./dynamic-client-store-
|
|
1
|
+
import { t as Clock } from "./clock-CzAaCoZ5.cjs";
|
|
2
|
+
import { _ as PendingAuthorizationStoreMemoryOptions, a as DynamicClientStoreMemoryOptions, b as tokenPolicyToIssueOptions, c as AuthCodeStore, d as NewAuthCode, f as DEFAULT_PENDING_TTL_MS, g as PendingAuthorizationStoreMemory, h as PendingAuthorizationStore, i as DynamicClientStoreMemory, l as AuthCodeStoreMemory, m as PendingAuthorization, n as DynamicClientAuthMethod, o as NewDynamicClient, p as NewPendingAuthorization, r as DynamicClientStore, s as AuthCode, t as DynamicClient, u as AuthCodeStoreMemoryOptions, v as DEFAULT_AUTHZ_REFRESH_TTL_MS, y as TokenPolicy } from "./dynamic-client-store-D0RDGSSJ.cjs";
|
|
3
3
|
import { JWK } from "jose";
|
|
4
4
|
//#region src/authz/authz-errors.d.ts
|
|
5
5
|
/**
|
package/dist/authz.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as Clock } from "./clock-
|
|
2
|
-
import { _ as PendingAuthorizationStoreMemoryOptions, a as DynamicClientStoreMemoryOptions, b as tokenPolicyToIssueOptions, c as AuthCodeStore, d as NewAuthCode, f as DEFAULT_PENDING_TTL_MS, g as PendingAuthorizationStoreMemory, h as PendingAuthorizationStore, i as DynamicClientStoreMemory, l as AuthCodeStoreMemory, m as PendingAuthorization, n as DynamicClientAuthMethod, o as NewDynamicClient, p as NewPendingAuthorization, r as DynamicClientStore, s as AuthCode, t as DynamicClient, u as AuthCodeStoreMemoryOptions, v as DEFAULT_AUTHZ_REFRESH_TTL_MS, y as TokenPolicy } from "./dynamic-client-store-
|
|
1
|
+
import { t as Clock } from "./clock-CzAaCoZ5.mjs";
|
|
2
|
+
import { _ as PendingAuthorizationStoreMemoryOptions, a as DynamicClientStoreMemoryOptions, b as tokenPolicyToIssueOptions, c as AuthCodeStore, d as NewAuthCode, f as DEFAULT_PENDING_TTL_MS, g as PendingAuthorizationStoreMemory, h as PendingAuthorizationStore, i as DynamicClientStoreMemory, l as AuthCodeStoreMemory, m as PendingAuthorization, n as DynamicClientAuthMethod, o as NewDynamicClient, p as NewPendingAuthorization, r as DynamicClientStore, s as AuthCode, t as DynamicClient, u as AuthCodeStoreMemoryOptions, v as DEFAULT_AUTHZ_REFRESH_TTL_MS, y as TokenPolicy } from "./dynamic-client-store-CUGQiS08.mjs";
|
|
3
3
|
import { JWK } from "jose";
|
|
4
4
|
//#region src/authz/authz-errors.d.ts
|
|
5
5
|
/**
|
package/dist/client.cjs
CHANGED
|
@@ -5,8 +5,10 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
5
5
|
* credentials; a response whose status is in `refreshOn` (401 by default)
|
|
6
6
|
* triggers a **single-flight** refresh — N concurrent failing requests share
|
|
7
7
|
* exactly one `POST {refreshPath}` — and, on success, the original request is
|
|
8
|
-
* retried **once**. A
|
|
9
|
-
*
|
|
8
|
+
* retried **once**. A refresh rejected with 400/401/403 fires `onLogout()` once;
|
|
9
|
+
* a transient failure (offline, 429, 5xx) fires `onRefreshError()` and keeps the
|
|
10
|
+
* session. Either way the original failing response is returned (no retry, no
|
|
11
|
+
* refresh storm).
|
|
10
12
|
*
|
|
11
13
|
* Browser-safe: pairs with the bundled `@aooth/auth-moost` httpOnly-cookie
|
|
12
14
|
* transport, so the SPA never touches token material. The retried request reuses
|
|
@@ -22,22 +24,33 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
22
24
|
*/
|
|
23
25
|
function createAuthedFetch(options = {}) {
|
|
24
26
|
const refreshPath = options.refreshPath ?? "/auth/refresh";
|
|
25
|
-
const onLogout = options
|
|
27
|
+
const { onLogout, onRefreshError } = options;
|
|
28
|
+
const logoutOnAny = options.logoutOn === "any-failure";
|
|
26
29
|
const refreshOn = options.refreshOn ?? [401];
|
|
27
|
-
const
|
|
28
|
-
|
|
30
|
+
const resolveFetch = () => {
|
|
31
|
+
const f = options.fetch ?? globalThis.fetch;
|
|
32
|
+
if (typeof f !== "function") throw new Error("createAuthedFetch: no fetch implementation available — pass options.fetch");
|
|
33
|
+
return f;
|
|
34
|
+
};
|
|
29
35
|
let refreshInFlight = null;
|
|
36
|
+
const failed = (reason) => {
|
|
37
|
+
if (reason.status === 400 || reason.status === 401 || reason.status === 403 || logoutOnAny) onLogout?.(reason);
|
|
38
|
+
else onRefreshError?.(reason);
|
|
39
|
+
return false;
|
|
40
|
+
};
|
|
30
41
|
const runRefresh = () => {
|
|
31
42
|
if (refreshInFlight) return refreshInFlight;
|
|
32
43
|
refreshInFlight = (async () => {
|
|
44
|
+
let res;
|
|
33
45
|
try {
|
|
34
|
-
|
|
46
|
+
res = await resolveFetch()(refreshPath, {
|
|
35
47
|
method: "POST",
|
|
36
48
|
credentials: "include"
|
|
37
|
-
})
|
|
38
|
-
} catch {
|
|
39
|
-
|
|
40
|
-
|
|
49
|
+
});
|
|
50
|
+
} catch (error) {
|
|
51
|
+
return failed({ error });
|
|
52
|
+
}
|
|
53
|
+
return res.ok || failed({ status: res.status });
|
|
41
54
|
})().finally(() => {
|
|
42
55
|
refreshInFlight = null;
|
|
43
56
|
});
|
|
@@ -48,10 +61,10 @@ function createAuthedFetch(options = {}) {
|
|
|
48
61
|
credentials: "include",
|
|
49
62
|
...init
|
|
50
63
|
};
|
|
51
|
-
const res = await
|
|
64
|
+
const res = await resolveFetch()(input, withCreds);
|
|
52
65
|
if (!refreshOn.includes(res.status)) return res;
|
|
53
66
|
if (!await runRefresh()) return res;
|
|
54
|
-
return
|
|
67
|
+
return resolveFetch()(input, withCreds);
|
|
55
68
|
};
|
|
56
69
|
return authedFetch;
|
|
57
70
|
}
|
package/dist/client.d.cts
CHANGED
|
@@ -4,17 +4,37 @@ interface MinimalResponse {
|
|
|
4
4
|
readonly ok: boolean;
|
|
5
5
|
readonly status: number;
|
|
6
6
|
}
|
|
7
|
-
/**
|
|
7
|
+
/**
|
|
8
|
+
* Subset of `RequestInit` this helper sets or forwards. The DOM `RequestInit`
|
|
9
|
+
* (and Node's) is assignable to it: fields the helper never inspects are typed
|
|
10
|
+
* `unknown` so `Headers` instances, `AbortSignal`s and any body type pass through.
|
|
11
|
+
*/
|
|
8
12
|
interface MinimalRequestInit {
|
|
9
13
|
method?: string;
|
|
10
|
-
headers?:
|
|
14
|
+
headers?: unknown;
|
|
11
15
|
body?: unknown;
|
|
12
16
|
credentials?: "omit" | "same-origin" | "include";
|
|
13
17
|
signal?: unknown;
|
|
14
|
-
|
|
18
|
+
cache?: unknown;
|
|
19
|
+
mode?: unknown;
|
|
20
|
+
redirect?: unknown;
|
|
21
|
+
referrer?: unknown;
|
|
22
|
+
referrerPolicy?: unknown;
|
|
23
|
+
integrity?: unknown;
|
|
24
|
+
keepalive?: unknown;
|
|
25
|
+
priority?: unknown;
|
|
26
|
+
window?: unknown;
|
|
27
|
+
duplex?: unknown;
|
|
28
|
+
dispatcher?: unknown;
|
|
15
29
|
}
|
|
16
|
-
/**
|
|
17
|
-
|
|
30
|
+
/**
|
|
31
|
+
* A `fetch`-compatible function. The global `fetch` (DOM or Node) satisfies it.
|
|
32
|
+
* Declared method-style so its parameters are compared bivariantly — the DOM
|
|
33
|
+
* `fetch`'s wider `RequestInfo` / `RequestInit` parameters still match.
|
|
34
|
+
*/
|
|
35
|
+
type FetchFn = {
|
|
36
|
+
fetch(input: string | URL, init?: MinimalRequestInit): Promise<MinimalResponse>;
|
|
37
|
+
}["fetch"];
|
|
18
38
|
/**
|
|
19
39
|
* Resolves to the ambient `fetch` type when the consumer's tsconfig includes the
|
|
20
40
|
* DOM lib — so the returned wrapper yields a real `Response` with `.json()` etc.
|
|
@@ -25,16 +45,40 @@ type FetchFn = (input: string | URL, init?: MinimalRequestInit) => Promise<Minim
|
|
|
25
45
|
type DefaultFetch = typeof globalThis extends {
|
|
26
46
|
fetch: infer F extends FetchFn;
|
|
27
47
|
} ? F : FetchFn;
|
|
48
|
+
/**
|
|
49
|
+
* Why a refresh failed: `status` is the refresh endpoint's HTTP status when it
|
|
50
|
+
* answered; `error` is the thrown value when the request itself failed
|
|
51
|
+
* (offline, aborted, DNS, CORS).
|
|
52
|
+
*/
|
|
53
|
+
interface AuthedFetchRefreshFailure {
|
|
54
|
+
status?: number;
|
|
55
|
+
error?: unknown;
|
|
56
|
+
}
|
|
28
57
|
interface CreateAuthedFetchOptions<TFetch extends FetchFn = DefaultFetch> {
|
|
29
58
|
/** Refresh endpoint path or URL. Default `'/auth/refresh'`. Match your `AuthController` mount. */
|
|
30
59
|
refreshPath?: string;
|
|
31
60
|
/**
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
61
|
+
* Which refresh failures end the session (fire {@link onLogout}):
|
|
62
|
+
* - `'auth-failure'` (default) — only when the refresh endpoint answers
|
|
63
|
+
* 400, 401 or 403 (the refresh token is missing, invalid, expired or revoked).
|
|
64
|
+
* A network error, abort, 429 or 5xx is transient: the session is kept and
|
|
65
|
+
* {@link onRefreshError} fires instead.
|
|
66
|
+
* - `'any-failure'` — every failed refresh logs out (the pre-0.2 behaviour).
|
|
67
|
+
*/
|
|
68
|
+
logoutOn?: "auth-failure" | "any-failure";
|
|
69
|
+
/**
|
|
70
|
+
* Called exactly once per failed single-flight refresh that ends the session
|
|
71
|
+
* (see {@link logoutOn}). Use it to redirect to login / clear app state.
|
|
72
|
+
* Never called on a successful refresh.
|
|
73
|
+
*/
|
|
74
|
+
onLogout?: (reason: AuthedFetchRefreshFailure) => void;
|
|
75
|
+
/**
|
|
76
|
+
* Called once per failed single-flight refresh that does NOT end the session
|
|
77
|
+
* (a transient failure under `logoutOn: 'auth-failure'`). The original
|
|
78
|
+
* failing response is returned to the caller; the next 401 tries again.
|
|
35
79
|
*/
|
|
36
|
-
|
|
37
|
-
/** Underlying fetch implementation. Default: the global `fetch
|
|
80
|
+
onRefreshError?: (reason: AuthedFetchRefreshFailure) => void;
|
|
81
|
+
/** Underlying fetch implementation. Default: the global `fetch`, resolved on every call. */
|
|
38
82
|
fetch?: TFetch;
|
|
39
83
|
/** Response status codes that trigger a refresh + single retry. Default `[401]`. */
|
|
40
84
|
refreshOn?: number[];
|
|
@@ -44,8 +88,10 @@ interface CreateAuthedFetchOptions<TFetch extends FetchFn = DefaultFetch> {
|
|
|
44
88
|
* credentials; a response whose status is in `refreshOn` (401 by default)
|
|
45
89
|
* triggers a **single-flight** refresh — N concurrent failing requests share
|
|
46
90
|
* exactly one `POST {refreshPath}` — and, on success, the original request is
|
|
47
|
-
* retried **once**. A
|
|
48
|
-
*
|
|
91
|
+
* retried **once**. A refresh rejected with 400/401/403 fires `onLogout()` once;
|
|
92
|
+
* a transient failure (offline, 429, 5xx) fires `onRefreshError()` and keeps the
|
|
93
|
+
* session. Either way the original failing response is returned (no retry, no
|
|
94
|
+
* refresh storm).
|
|
49
95
|
*
|
|
50
96
|
* Browser-safe: pairs with the bundled `@aooth/auth-moost` httpOnly-cookie
|
|
51
97
|
* transport, so the SPA never touches token material. The retried request reuses
|
|
@@ -61,4 +107,4 @@ interface CreateAuthedFetchOptions<TFetch extends FetchFn = DefaultFetch> {
|
|
|
61
107
|
*/
|
|
62
108
|
declare function createAuthedFetch<TFetch extends FetchFn = DefaultFetch>(options?: CreateAuthedFetchOptions<TFetch>): TFetch;
|
|
63
109
|
//#endregion
|
|
64
|
-
export { CreateAuthedFetchOptions, DefaultFetch, FetchFn, MinimalRequestInit, MinimalResponse, createAuthedFetch };
|
|
110
|
+
export { AuthedFetchRefreshFailure, CreateAuthedFetchOptions, DefaultFetch, FetchFn, MinimalRequestInit, MinimalResponse, createAuthedFetch };
|
package/dist/client.d.mts
CHANGED
|
@@ -4,17 +4,37 @@ interface MinimalResponse {
|
|
|
4
4
|
readonly ok: boolean;
|
|
5
5
|
readonly status: number;
|
|
6
6
|
}
|
|
7
|
-
/**
|
|
7
|
+
/**
|
|
8
|
+
* Subset of `RequestInit` this helper sets or forwards. The DOM `RequestInit`
|
|
9
|
+
* (and Node's) is assignable to it: fields the helper never inspects are typed
|
|
10
|
+
* `unknown` so `Headers` instances, `AbortSignal`s and any body type pass through.
|
|
11
|
+
*/
|
|
8
12
|
interface MinimalRequestInit {
|
|
9
13
|
method?: string;
|
|
10
|
-
headers?:
|
|
14
|
+
headers?: unknown;
|
|
11
15
|
body?: unknown;
|
|
12
16
|
credentials?: "omit" | "same-origin" | "include";
|
|
13
17
|
signal?: unknown;
|
|
14
|
-
|
|
18
|
+
cache?: unknown;
|
|
19
|
+
mode?: unknown;
|
|
20
|
+
redirect?: unknown;
|
|
21
|
+
referrer?: unknown;
|
|
22
|
+
referrerPolicy?: unknown;
|
|
23
|
+
integrity?: unknown;
|
|
24
|
+
keepalive?: unknown;
|
|
25
|
+
priority?: unknown;
|
|
26
|
+
window?: unknown;
|
|
27
|
+
duplex?: unknown;
|
|
28
|
+
dispatcher?: unknown;
|
|
15
29
|
}
|
|
16
|
-
/**
|
|
17
|
-
|
|
30
|
+
/**
|
|
31
|
+
* A `fetch`-compatible function. The global `fetch` (DOM or Node) satisfies it.
|
|
32
|
+
* Declared method-style so its parameters are compared bivariantly — the DOM
|
|
33
|
+
* `fetch`'s wider `RequestInfo` / `RequestInit` parameters still match.
|
|
34
|
+
*/
|
|
35
|
+
type FetchFn = {
|
|
36
|
+
fetch(input: string | URL, init?: MinimalRequestInit): Promise<MinimalResponse>;
|
|
37
|
+
}["fetch"];
|
|
18
38
|
/**
|
|
19
39
|
* Resolves to the ambient `fetch` type when the consumer's tsconfig includes the
|
|
20
40
|
* DOM lib — so the returned wrapper yields a real `Response` with `.json()` etc.
|
|
@@ -25,16 +45,40 @@ type FetchFn = (input: string | URL, init?: MinimalRequestInit) => Promise<Minim
|
|
|
25
45
|
type DefaultFetch = typeof globalThis extends {
|
|
26
46
|
fetch: infer F extends FetchFn;
|
|
27
47
|
} ? F : FetchFn;
|
|
48
|
+
/**
|
|
49
|
+
* Why a refresh failed: `status` is the refresh endpoint's HTTP status when it
|
|
50
|
+
* answered; `error` is the thrown value when the request itself failed
|
|
51
|
+
* (offline, aborted, DNS, CORS).
|
|
52
|
+
*/
|
|
53
|
+
interface AuthedFetchRefreshFailure {
|
|
54
|
+
status?: number;
|
|
55
|
+
error?: unknown;
|
|
56
|
+
}
|
|
28
57
|
interface CreateAuthedFetchOptions<TFetch extends FetchFn = DefaultFetch> {
|
|
29
58
|
/** Refresh endpoint path or URL. Default `'/auth/refresh'`. Match your `AuthController` mount. */
|
|
30
59
|
refreshPath?: string;
|
|
31
60
|
/**
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
61
|
+
* Which refresh failures end the session (fire {@link onLogout}):
|
|
62
|
+
* - `'auth-failure'` (default) — only when the refresh endpoint answers
|
|
63
|
+
* 400, 401 or 403 (the refresh token is missing, invalid, expired or revoked).
|
|
64
|
+
* A network error, abort, 429 or 5xx is transient: the session is kept and
|
|
65
|
+
* {@link onRefreshError} fires instead.
|
|
66
|
+
* - `'any-failure'` — every failed refresh logs out (the pre-0.2 behaviour).
|
|
67
|
+
*/
|
|
68
|
+
logoutOn?: "auth-failure" | "any-failure";
|
|
69
|
+
/**
|
|
70
|
+
* Called exactly once per failed single-flight refresh that ends the session
|
|
71
|
+
* (see {@link logoutOn}). Use it to redirect to login / clear app state.
|
|
72
|
+
* Never called on a successful refresh.
|
|
73
|
+
*/
|
|
74
|
+
onLogout?: (reason: AuthedFetchRefreshFailure) => void;
|
|
75
|
+
/**
|
|
76
|
+
* Called once per failed single-flight refresh that does NOT end the session
|
|
77
|
+
* (a transient failure under `logoutOn: 'auth-failure'`). The original
|
|
78
|
+
* failing response is returned to the caller; the next 401 tries again.
|
|
35
79
|
*/
|
|
36
|
-
|
|
37
|
-
/** Underlying fetch implementation. Default: the global `fetch
|
|
80
|
+
onRefreshError?: (reason: AuthedFetchRefreshFailure) => void;
|
|
81
|
+
/** Underlying fetch implementation. Default: the global `fetch`, resolved on every call. */
|
|
38
82
|
fetch?: TFetch;
|
|
39
83
|
/** Response status codes that trigger a refresh + single retry. Default `[401]`. */
|
|
40
84
|
refreshOn?: number[];
|
|
@@ -44,8 +88,10 @@ interface CreateAuthedFetchOptions<TFetch extends FetchFn = DefaultFetch> {
|
|
|
44
88
|
* credentials; a response whose status is in `refreshOn` (401 by default)
|
|
45
89
|
* triggers a **single-flight** refresh — N concurrent failing requests share
|
|
46
90
|
* exactly one `POST {refreshPath}` — and, on success, the original request is
|
|
47
|
-
* retried **once**. A
|
|
48
|
-
*
|
|
91
|
+
* retried **once**. A refresh rejected with 400/401/403 fires `onLogout()` once;
|
|
92
|
+
* a transient failure (offline, 429, 5xx) fires `onRefreshError()` and keeps the
|
|
93
|
+
* session. Either way the original failing response is returned (no retry, no
|
|
94
|
+
* refresh storm).
|
|
49
95
|
*
|
|
50
96
|
* Browser-safe: pairs with the bundled `@aooth/auth-moost` httpOnly-cookie
|
|
51
97
|
* transport, so the SPA never touches token material. The retried request reuses
|
|
@@ -61,4 +107,4 @@ interface CreateAuthedFetchOptions<TFetch extends FetchFn = DefaultFetch> {
|
|
|
61
107
|
*/
|
|
62
108
|
declare function createAuthedFetch<TFetch extends FetchFn = DefaultFetch>(options?: CreateAuthedFetchOptions<TFetch>): TFetch;
|
|
63
109
|
//#endregion
|
|
64
|
-
export { CreateAuthedFetchOptions, DefaultFetch, FetchFn, MinimalRequestInit, MinimalResponse, createAuthedFetch };
|
|
110
|
+
export { AuthedFetchRefreshFailure, CreateAuthedFetchOptions, DefaultFetch, FetchFn, MinimalRequestInit, MinimalResponse, createAuthedFetch };
|
package/dist/client.mjs
CHANGED
|
@@ -4,8 +4,10 @@
|
|
|
4
4
|
* credentials; a response whose status is in `refreshOn` (401 by default)
|
|
5
5
|
* triggers a **single-flight** refresh — N concurrent failing requests share
|
|
6
6
|
* exactly one `POST {refreshPath}` — and, on success, the original request is
|
|
7
|
-
* retried **once**. A
|
|
8
|
-
*
|
|
7
|
+
* retried **once**. A refresh rejected with 400/401/403 fires `onLogout()` once;
|
|
8
|
+
* a transient failure (offline, 429, 5xx) fires `onRefreshError()` and keeps the
|
|
9
|
+
* session. Either way the original failing response is returned (no retry, no
|
|
10
|
+
* refresh storm).
|
|
9
11
|
*
|
|
10
12
|
* Browser-safe: pairs with the bundled `@aooth/auth-moost` httpOnly-cookie
|
|
11
13
|
* transport, so the SPA never touches token material. The retried request reuses
|
|
@@ -21,22 +23,33 @@
|
|
|
21
23
|
*/
|
|
22
24
|
function createAuthedFetch(options = {}) {
|
|
23
25
|
const refreshPath = options.refreshPath ?? "/auth/refresh";
|
|
24
|
-
const onLogout = options
|
|
26
|
+
const { onLogout, onRefreshError } = options;
|
|
27
|
+
const logoutOnAny = options.logoutOn === "any-failure";
|
|
25
28
|
const refreshOn = options.refreshOn ?? [401];
|
|
26
|
-
const
|
|
27
|
-
|
|
29
|
+
const resolveFetch = () => {
|
|
30
|
+
const f = options.fetch ?? globalThis.fetch;
|
|
31
|
+
if (typeof f !== "function") throw new Error("createAuthedFetch: no fetch implementation available — pass options.fetch");
|
|
32
|
+
return f;
|
|
33
|
+
};
|
|
28
34
|
let refreshInFlight = null;
|
|
35
|
+
const failed = (reason) => {
|
|
36
|
+
if (reason.status === 400 || reason.status === 401 || reason.status === 403 || logoutOnAny) onLogout?.(reason);
|
|
37
|
+
else onRefreshError?.(reason);
|
|
38
|
+
return false;
|
|
39
|
+
};
|
|
29
40
|
const runRefresh = () => {
|
|
30
41
|
if (refreshInFlight) return refreshInFlight;
|
|
31
42
|
refreshInFlight = (async () => {
|
|
43
|
+
let res;
|
|
32
44
|
try {
|
|
33
|
-
|
|
45
|
+
res = await resolveFetch()(refreshPath, {
|
|
34
46
|
method: "POST",
|
|
35
47
|
credentials: "include"
|
|
36
|
-
})
|
|
37
|
-
} catch {
|
|
38
|
-
|
|
39
|
-
|
|
48
|
+
});
|
|
49
|
+
} catch (error) {
|
|
50
|
+
return failed({ error });
|
|
51
|
+
}
|
|
52
|
+
return res.ok || failed({ status: res.status });
|
|
40
53
|
})().finally(() => {
|
|
41
54
|
refreshInFlight = null;
|
|
42
55
|
});
|
|
@@ -47,10 +60,10 @@ function createAuthedFetch(options = {}) {
|
|
|
47
60
|
credentials: "include",
|
|
48
61
|
...init
|
|
49
62
|
};
|
|
50
|
-
const res = await
|
|
63
|
+
const res = await resolveFetch()(input, withCreds);
|
|
51
64
|
if (!refreshOn.includes(res.status)) return res;
|
|
52
65
|
if (!await runRefresh()) return res;
|
|
53
|
-
return
|
|
66
|
+
return resolveFetch()(input, withCreds);
|
|
54
67
|
};
|
|
55
68
|
return authedFetch;
|
|
56
69
|
}
|
|
@@ -301,6 +301,13 @@ interface RefreshConfig {
|
|
|
301
301
|
interface CredentialStore<TPayload extends object = object> {
|
|
302
302
|
/** Persist state, return token. For stateless stores, token IS the state. */
|
|
303
303
|
persist(state: CredentialState & TPayload, ttl?: number): Promise<string>;
|
|
304
|
+
/**
|
|
305
|
+
* Optional: persist `state` under a caller-chosen `id` instead of minting
|
|
306
|
+
* one. Stateful stores implement it; `AuthCredential`'s
|
|
307
|
+
* `tokens.hashAtRest` requires it (the row is keyed by a hash of the token
|
|
308
|
+
* the client holds, so a database read yields no usable token).
|
|
309
|
+
*/
|
|
310
|
+
persistAs?(id: string, state: CredentialState & TPayload, ttl?: number): Promise<void>;
|
|
304
311
|
/** Retrieve state from token. Returns null if expired/invalid/revoked. */
|
|
305
312
|
retrieve(token: string): Promise<(CredentialState & TPayload) | null>;
|
|
306
313
|
/** Retrieve + invalidate (single-use). For stateless: needs denylist. */
|
|
@@ -301,6 +301,13 @@ interface RefreshConfig {
|
|
|
301
301
|
interface CredentialStore<TPayload extends object = object> {
|
|
302
302
|
/** Persist state, return token. For stateless stores, token IS the state. */
|
|
303
303
|
persist(state: CredentialState & TPayload, ttl?: number): Promise<string>;
|
|
304
|
+
/**
|
|
305
|
+
* Optional: persist `state` under a caller-chosen `id` instead of minting
|
|
306
|
+
* one. Stateful stores implement it; `AuthCredential`'s
|
|
307
|
+
* `tokens.hashAtRest` requires it (the row is keyed by a hash of the token
|
|
308
|
+
* the client holds, so a database read yields no usable token).
|
|
309
|
+
*/
|
|
310
|
+
persistAs?(id: string, state: CredentialState & TPayload, ttl?: number): Promise<void>;
|
|
304
311
|
/** Retrieve state from token. Returns null if expired/invalid/revoked. */
|
|
305
312
|
retrieve(token: string): Promise<(CredentialState & TPayload) | null>;
|
|
306
313
|
/** Retrieve + invalidate (single-use). For stateless: needs denylist. */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as Clock } from "./clock-
|
|
2
|
-
import { r as IssueOptions } from "./auth-credential-
|
|
1
|
+
import { t as Clock } from "./clock-CzAaCoZ5.mjs";
|
|
2
|
+
import { r as IssueOptions } from "./auth-credential-BsH0E8hG.mjs";
|
|
3
3
|
//#region src/authz/token-policy.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* What the authorization server mints for a completed grant — forwarded verbatim
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as Clock } from "./clock-
|
|
2
|
-
import { r as IssueOptions } from "./auth-credential-
|
|
1
|
+
import { t as Clock } from "./clock-CzAaCoZ5.cjs";
|
|
2
|
+
import { r as IssueOptions } from "./auth-credential-D1V5-2uy.cjs";
|
|
3
3
|
//#region src/authz/token-policy.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* What the authorization server mints for a completed grant — forwarded verbatim
|