@aooth/auth 0.1.85 → 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 +2 -2
- package/dist/store-CVD1nd2j.d.mts +0 -41
- package/dist/store-ClQnA8yh.d.cts +0 -41
package/dist/index.cjs
CHANGED
|
@@ -1,30 +1,9 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_payload = require("./payload-C1cQW7p_.cjs");
|
|
2
3
|
const require_clock = require("./clock-Bl-H3eqE.cjs");
|
|
3
|
-
const require_payload = require("./payload-HPgyPiek.cjs");
|
|
4
4
|
const require_opaque_token = require("./opaque-token-CaZgD2i6.cjs");
|
|
5
5
|
let node_crypto = require("node:crypto");
|
|
6
6
|
let jose = require("jose");
|
|
7
|
-
//#region src/errors.ts
|
|
8
|
-
const defaultMessages = {
|
|
9
|
-
INVALID_TOKEN: "Invalid token",
|
|
10
|
-
TOKEN_EXPIRED: "Token has expired",
|
|
11
|
-
TOKEN_REVOKED: "Token has been revoked",
|
|
12
|
-
REFRESH_REUSE_DETECTED: "Refresh token reuse detected",
|
|
13
|
-
STATELESS_OPERATION_UNSUPPORTED: "Operation is not supported by stateless credential store",
|
|
14
|
-
MAX_CONCURRENT_REACHED: "Maximum concurrent credentials reached for user",
|
|
15
|
-
INVALID_CONFIG: "Invalid auth configuration"
|
|
16
|
-
};
|
|
17
|
-
var AuthError = class extends Error {
|
|
18
|
-
type;
|
|
19
|
-
details;
|
|
20
|
-
name = "AuthError";
|
|
21
|
-
constructor(type, message, details) {
|
|
22
|
-
super(message ?? defaultMessages[type]);
|
|
23
|
-
this.type = type;
|
|
24
|
-
this.details = details;
|
|
25
|
-
}
|
|
26
|
-
};
|
|
27
|
-
//#endregion
|
|
28
7
|
//#region src/stores/memory.ts
|
|
29
8
|
/**
|
|
30
9
|
* In-memory implementation of CredentialStore using random opaque token IDs.
|
|
@@ -43,11 +22,14 @@ var CredentialStoreMemory = class {
|
|
|
43
22
|
}
|
|
44
23
|
async persist(state, ttl) {
|
|
45
24
|
const token = (0, node_crypto.randomUUID)();
|
|
25
|
+
await this.persistAs(token, state, ttl);
|
|
26
|
+
return token;
|
|
27
|
+
}
|
|
28
|
+
async persistAs(id, state, ttl) {
|
|
46
29
|
const stored = { ...state };
|
|
47
30
|
if (typeof ttl === "number") stored.expiresAt = this.clock.now() + ttl;
|
|
48
|
-
this.states.set(
|
|
49
|
-
this.indexAdd(stored.userId,
|
|
50
|
-
return token;
|
|
31
|
+
this.states.set(id, stored);
|
|
32
|
+
this.indexAdd(stored.userId, id);
|
|
51
33
|
}
|
|
52
34
|
async retrieve(token) {
|
|
53
35
|
const state = this.states.get(token);
|
|
@@ -239,12 +221,12 @@ var CredentialStoreJwt = class {
|
|
|
239
221
|
this.denylist = opts.denylist;
|
|
240
222
|
this.clock = opts.clock ?? require_clock.defaultClock;
|
|
241
223
|
if (HS_ALGS.has(this.algorithm)) {
|
|
242
|
-
if (opts.secret == null) throw new AuthError("INVALID_CONFIG", `Algorithm ${this.algorithm} requires a 'secret' option`);
|
|
224
|
+
if (opts.secret == null) throw new require_payload.AuthError("INVALID_CONFIG", `Algorithm ${this.algorithm} requires a 'secret' option`);
|
|
243
225
|
const key = normalizeSecret(opts.secret);
|
|
244
226
|
this.signingKey = key;
|
|
245
227
|
this.verifyingKey = key;
|
|
246
228
|
} else {
|
|
247
|
-
if (opts.privateKey == null || opts.publicKey == null) throw new AuthError("INVALID_CONFIG", `Algorithm ${this.algorithm} requires both 'privateKey' and 'publicKey' options`);
|
|
229
|
+
if (opts.privateKey == null || opts.publicKey == null) throw new require_payload.AuthError("INVALID_CONFIG", `Algorithm ${this.algorithm} requires both 'privateKey' and 'publicKey' options`);
|
|
248
230
|
this.signingKey = opts.privateKey;
|
|
249
231
|
this.verifyingKey = opts.publicKey;
|
|
250
232
|
}
|
|
@@ -307,10 +289,10 @@ var CredentialStoreJwt = class {
|
|
|
307
289
|
}
|
|
308
290
|
deriveSubkey(label) {
|
|
309
291
|
if (this.signingKey instanceof Uint8Array) return hkdfSubkey(this.signingKey, label);
|
|
310
|
-
throw new AuthError("INVALID_CONFIG", "deriveSubkey requires a symmetric (HS*) secret; this JWT store uses an asymmetric key — provide an explicit wfStateSecret");
|
|
292
|
+
throw new require_payload.AuthError("INVALID_CONFIG", "deriveSubkey requires a symmetric (HS*) secret; this JWT store uses an asymmetric key — provide an explicit wfStateSecret");
|
|
311
293
|
}
|
|
312
294
|
requireDenylist(op) {
|
|
313
|
-
if (!this.denylist) throw new AuthError("STATELESS_OPERATION_UNSUPPORTED", `${op} requires a denylist on stateless JWT store`);
|
|
295
|
+
if (!this.denylist) throw new require_payload.AuthError("STATELESS_OPERATION_UNSUPPORTED", `${op} requires a denylist on stateless JWT store`);
|
|
314
296
|
return this.denylist;
|
|
315
297
|
}
|
|
316
298
|
/** Convert payload `exp` (seconds) to ms; fall back to a 60s window. */
|
|
@@ -423,7 +405,7 @@ var CredentialStoreEncapsulated = class {
|
|
|
423
405
|
*/
|
|
424
406
|
epochs = /* @__PURE__ */ new Map();
|
|
425
407
|
constructor(opts) {
|
|
426
|
-
if (opts.secret == null) throw new AuthError("INVALID_CONFIG", "CredentialStoreEncapsulated requires a 'secret'");
|
|
408
|
+
if (opts.secret == null) throw new require_payload.AuthError("INVALID_CONFIG", "CredentialStoreEncapsulated requires a 'secret'");
|
|
427
409
|
this.key = deriveKey(opts.secret);
|
|
428
410
|
this.denylist = opts.denylist;
|
|
429
411
|
this.clock = opts.clock ?? require_clock.defaultClock;
|
|
@@ -495,7 +477,7 @@ var CredentialStoreEncapsulated = class {
|
|
|
495
477
|
return payload.issuedAt >= epoch;
|
|
496
478
|
}
|
|
497
479
|
requireDenylist(op) {
|
|
498
|
-
if (!this.denylist) throw new AuthError("STATELESS_OPERATION_UNSUPPORTED", `${op} requires a denylist on stateless encapsulated store`);
|
|
480
|
+
if (!this.denylist) throw new require_payload.AuthError("STATELESS_OPERATION_UNSUPPORTED", `${op} requires a denylist on stateless encapsulated store`);
|
|
499
481
|
return this.denylist;
|
|
500
482
|
}
|
|
501
483
|
decrypt(token) {
|
|
@@ -557,6 +539,34 @@ function lazyCredentialId(ctx, token) {
|
|
|
557
539
|
}
|
|
558
540
|
/** Smallest map size an amortized expiry sweep runs at. */
|
|
559
541
|
const MIN_SWEEP_SIZE$1 = 1024;
|
|
542
|
+
/** A store key that is the SHA-256 hex of a token (`tokens.hashAtRest`). */
|
|
543
|
+
const HASHED_KEY = /^[0-9a-f]{64}$/i;
|
|
544
|
+
/** The token shape the bundled stores minted before `hashAtRest` (`randomUUID`). */
|
|
545
|
+
const UUID_TOKEN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
546
|
+
/** Prefix of a successor token encrypted at rest (`tokens.hashAtRest`). */
|
|
547
|
+
const SEALED_PREFIX = "enc1.";
|
|
548
|
+
/** AES-256-GCM key for the successor pair, derived from the presented (old) refresh token. */
|
|
549
|
+
function successorKey(oldRefreshToken) {
|
|
550
|
+
return Buffer.from((0, node_crypto.hkdfSync)("sha256", oldRefreshToken, "", "aooth-refresh-successor", 32));
|
|
551
|
+
}
|
|
552
|
+
function sealToken(key, token) {
|
|
553
|
+
const iv = (0, node_crypto.randomBytes)(12);
|
|
554
|
+
const cipher = (0, node_crypto.createCipheriv)("aes-256-gcm", key, iv);
|
|
555
|
+
const body = Buffer.concat([cipher.update(token, "utf8"), cipher.final()]);
|
|
556
|
+
return `${SEALED_PREFIX}${iv.toString("base64url")}.${body.toString("base64url")}.${cipher.getAuthTag().toString("base64url")}`;
|
|
557
|
+
}
|
|
558
|
+
/** Decrypt a sealed token; a plain (legacy) value passes through; `null` on a failed decrypt. */
|
|
559
|
+
function openToken(key, value) {
|
|
560
|
+
if (!value.startsWith(SEALED_PREFIX)) return value;
|
|
561
|
+
const [iv, body, tag] = value.slice(5).split(".");
|
|
562
|
+
try {
|
|
563
|
+
const decipher = (0, node_crypto.createDecipheriv)("aes-256-gcm", key, Buffer.from(iv, "base64url"));
|
|
564
|
+
decipher.setAuthTag(Buffer.from(tag, "base64url"));
|
|
565
|
+
return Buffer.concat([decipher.update(Buffer.from(body, "base64url")), decipher.final()]).toString("utf8");
|
|
566
|
+
} catch {
|
|
567
|
+
return null;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
560
570
|
/**
|
|
561
571
|
* The opt-in `validateCache`: token → validated state for `ttlMs`, bounded
|
|
562
572
|
* (oldest dropped first). `epoch` moves on every eviction so a validation
|
|
@@ -660,8 +670,11 @@ var AuthCredential = class {
|
|
|
660
670
|
consumedRefreshes = /* @__PURE__ */ new Map();
|
|
661
671
|
/** Map size at which `consumedRefreshes` next sweeps its expired entries. */
|
|
662
672
|
consumedSweepAt = MIN_SWEEP_SIZE$1;
|
|
663
|
-
/** Opt-in validated-state cache (`validateCache`). */
|
|
673
|
+
/** Opt-in validated-state cache (`validateCache`), keyed by store key. */
|
|
664
674
|
validated;
|
|
675
|
+
hashAtRest;
|
|
676
|
+
generateToken;
|
|
677
|
+
isLegacyToken;
|
|
665
678
|
constructor(opts) {
|
|
666
679
|
this.store = opts.store;
|
|
667
680
|
this.method = opts.method ?? "token";
|
|
@@ -672,14 +685,18 @@ var AuthCredential = class {
|
|
|
672
685
|
this.onLimit = opts.onLimit ?? "reject";
|
|
673
686
|
this.trackLastSeen = opts.trackLastSeen ?? false;
|
|
674
687
|
this.clock = opts.clock ?? require_clock.defaultClock;
|
|
688
|
+
this.hashAtRest = opts.tokens?.hashAtRest ?? false;
|
|
689
|
+
this.generateToken = opts.tokens?.generate;
|
|
690
|
+
this.isLegacyToken = opts.tokens?.isLegacyToken ?? ((token) => UUID_TOKEN.test(token));
|
|
691
|
+
if ((this.hashAtRest || this.generateToken) && !this.store.persistAs) throw new require_payload.AuthError("INVALID_CONFIG", "tokens.hashAtRest / tokens.generate need a store that implements persistAs (memory, Redis, atscript-db)");
|
|
675
692
|
if (opts.validateCache) {
|
|
676
|
-
if (!(opts.validateCache.ttlMs > 0)) throw new AuthError("INVALID_CONFIG", `validateCache.ttlMs must be > 0 (got ${opts.validateCache.ttlMs})`);
|
|
693
|
+
if (!(opts.validateCache.ttlMs > 0)) throw new require_payload.AuthError("INVALID_CONFIG", `validateCache.ttlMs must be > 0 (got ${opts.validateCache.ttlMs})`);
|
|
677
694
|
this.validated = new ValidateCache(opts.validateCache.ttlMs, opts.validateCache.max ?? 1e4);
|
|
678
695
|
}
|
|
679
|
-
if (this.accessTtl <= 0) throw new AuthError("INVALID_CONFIG", `accessTtl must be > 0 (got ${this.accessTtl})`);
|
|
680
|
-
if (this.refreshConfig && this.refreshConfig.ttl <= 0) throw new AuthError("INVALID_CONFIG", `refresh.ttl must be > 0 (got ${this.refreshConfig.ttl})`);
|
|
696
|
+
if (this.accessTtl <= 0) throw new require_payload.AuthError("INVALID_CONFIG", `accessTtl must be > 0 (got ${this.accessTtl})`);
|
|
697
|
+
if (this.refreshConfig && this.refreshConfig.ttl <= 0) throw new require_payload.AuthError("INVALID_CONFIG", `refresh.ttl must be > 0 (got ${this.refreshConfig.ttl})`);
|
|
681
698
|
const graceMs = this.refreshConfig?.rotationGraceMs;
|
|
682
|
-
if (graceMs !== void 0 && graceMs < 0) throw new AuthError("INVALID_CONFIG", `refresh.rotationGraceMs must be >= 0 (got ${graceMs})`);
|
|
699
|
+
if (graceMs !== void 0 && graceMs < 0) throw new require_payload.AuthError("INVALID_CONFIG", `refresh.rotationGraceMs must be >= 0 (got ${graceMs})`);
|
|
683
700
|
}
|
|
684
701
|
async issue(userId, options) {
|
|
685
702
|
if (this.maxConcurrent !== void 0 && this.store.listForUser) await this.enforceConcurrencyLimit(userId);
|
|
@@ -689,9 +706,9 @@ var AuthCredential = class {
|
|
|
689
706
|
if (refresh === void 0) refreshTtl = this.refreshConfig?.ttl;
|
|
690
707
|
else if (refresh !== false) {
|
|
691
708
|
refreshTtl = refresh.ttl ?? this.refreshConfig?.ttl;
|
|
692
|
-
if (refreshTtl === void 0) throw new AuthError("INVALID_CONFIG", "issue: per-mint refresh needs a ttl when no instance refresh config exists");
|
|
693
|
-
if (refreshTtl <= 0) throw new AuthError("INVALID_CONFIG", `issue: refresh.ttl must be > 0 (got ${refreshTtl})`);
|
|
694
|
-
if (refresh.graceMs !== void 0 && refresh.graceMs < 0) throw new AuthError("INVALID_CONFIG", `issue: refresh.graceMs must be >= 0 (got ${refresh.graceMs})`);
|
|
709
|
+
if (refreshTtl === void 0) throw new require_payload.AuthError("INVALID_CONFIG", "issue: per-mint refresh needs a ttl when no instance refresh config exists");
|
|
710
|
+
if (refreshTtl <= 0) throw new require_payload.AuthError("INVALID_CONFIG", `issue: refresh.ttl must be > 0 (got ${refreshTtl})`);
|
|
711
|
+
if (refresh.graceMs !== void 0 && refresh.graceMs < 0) throw new require_payload.AuthError("INVALID_CONFIG", `issue: refresh.graceMs must be >= 0 (got ${refresh.graceMs})`);
|
|
695
712
|
}
|
|
696
713
|
const perMintRefresh = refresh !== void 0 && refresh !== false;
|
|
697
714
|
const stampAccessTtl = refreshTtl !== void 0 && ttl !== void 0;
|
|
@@ -702,8 +719,8 @@ var AuthCredential = class {
|
|
|
702
719
|
...perMintRefresh && { refreshRotation: "always" },
|
|
703
720
|
...perMintRefresh && refresh.graceMs !== void 0 && { rotationGraceMs: refresh.graceMs }
|
|
704
721
|
} : metadata;
|
|
705
|
-
if (ttl !== void 0 && expiresAt !== void 0) throw new AuthError("INVALID_CONFIG", "issue: pass either `ttl` or `expiresAt`, not both");
|
|
706
|
-
if (ttl !== void 0 && ttl <= 0) throw new AuthError("INVALID_CONFIG", `issue: ttl must be > 0 (got ${ttl})`);
|
|
722
|
+
if (ttl !== void 0 && expiresAt !== void 0) throw new require_payload.AuthError("INVALID_CONFIG", "issue: pass either `ttl` or `expiresAt`, not both");
|
|
723
|
+
if (ttl !== void 0 && ttl <= 0) throw new require_payload.AuthError("INVALID_CONFIG", `issue: ttl must be > 0 (got ${ttl})`);
|
|
707
724
|
const accessExpiresAt = expiresAt ?? now + (ttl ?? this.accessTtl);
|
|
708
725
|
const accessStoreTtl = accessExpiresAt - now;
|
|
709
726
|
const sessionId = providedSessionId ?? (0, node_crypto.randomUUID)();
|
|
@@ -715,7 +732,7 @@ var AuthCredential = class {
|
|
|
715
732
|
metadata: effectiveMetadata,
|
|
716
733
|
sessionId
|
|
717
734
|
});
|
|
718
|
-
const accessToken = await this.
|
|
735
|
+
const accessToken = await this.put(accessState, accessStoreTtl);
|
|
719
736
|
let refreshToken;
|
|
720
737
|
let refreshExpiresAt;
|
|
721
738
|
if (refreshTtl !== void 0) {
|
|
@@ -727,7 +744,7 @@ var AuthCredential = class {
|
|
|
727
744
|
metadata: effectiveMetadata,
|
|
728
745
|
sessionId
|
|
729
746
|
});
|
|
730
|
-
refreshToken = await this.
|
|
747
|
+
refreshToken = await this.put(refreshState, refreshTtl);
|
|
731
748
|
refreshExpiresAt = now + refreshTtl;
|
|
732
749
|
}
|
|
733
750
|
return {
|
|
@@ -738,59 +755,103 @@ var AuthCredential = class {
|
|
|
738
755
|
};
|
|
739
756
|
}
|
|
740
757
|
async validate(accessToken) {
|
|
741
|
-
let
|
|
758
|
+
let key = this.keyOf(accessToken);
|
|
759
|
+
let state = this.validated?.get(key, this.clock.now());
|
|
742
760
|
let fresh = false;
|
|
743
761
|
if (!state) {
|
|
744
762
|
fresh = true;
|
|
745
763
|
const epoch = this.validated?.epoch;
|
|
746
|
-
|
|
747
|
-
if (!
|
|
764
|
+
const found = await this.retrieveUnlessDenied(accessToken, key);
|
|
765
|
+
if (!found) return null;
|
|
766
|
+
({key, state} = found);
|
|
748
767
|
if (state.expiresAt <= this.clock.now()) return null;
|
|
749
768
|
if (state.kind === "refresh") return null;
|
|
750
|
-
if (this.validated && this.validated.epoch === epoch) this.validated.set(
|
|
769
|
+
if (this.validated && this.validated.epoch === epoch) this.validated.set(key, state, this.clock.now());
|
|
751
770
|
} else if (state.expiresAt <= this.clock.now()) {
|
|
752
|
-
this.validated.delete(
|
|
771
|
+
this.validated.delete(key);
|
|
753
772
|
return null;
|
|
754
773
|
}
|
|
755
|
-
if (this.trackLastSeen === "validate" && this.store.touch) await this.store.touch(
|
|
774
|
+
if (this.trackLastSeen === "validate" && this.store.touch) await this.store.touch(key, this.clock.now(), fresh ? state : void 0);
|
|
756
775
|
const ctx = {
|
|
757
776
|
...require_payload.credentialPayloadOf(state),
|
|
758
777
|
userId: state.userId,
|
|
759
778
|
method: this.method,
|
|
760
779
|
credentialId: "",
|
|
761
|
-
sessionId:
|
|
780
|
+
sessionId: state.sessionId ?? this.fingerprintOfKey(key),
|
|
762
781
|
expiresAt: state.expiresAt
|
|
763
782
|
};
|
|
764
|
-
|
|
783
|
+
if (key !== accessToken) ctx.credentialId = key;
|
|
784
|
+
else lazyCredentialId(ctx, accessToken);
|
|
765
785
|
return ctx;
|
|
766
786
|
}
|
|
767
787
|
/**
|
|
768
788
|
* The stored state of `accessToken` unless the orchestrator's denylist has
|
|
769
789
|
* it — both looked up concurrently (one round trip on remote stores).
|
|
770
790
|
*/
|
|
771
|
-
async retrieveUnlessDenied(accessToken) {
|
|
772
|
-
const retrieving = this.
|
|
791
|
+
async retrieveUnlessDenied(accessToken, key) {
|
|
792
|
+
const retrieving = this.find(accessToken, key);
|
|
773
793
|
if (!this.denylist) return await retrieving;
|
|
774
794
|
retrieving.catch(() => {});
|
|
775
795
|
if (await this.denylist.has(accessToken)) return null;
|
|
776
796
|
return await retrieving;
|
|
777
797
|
}
|
|
798
|
+
/** The store key a token's row lives under: its SHA-256 when hashing, else the token. */
|
|
799
|
+
keyOf(token) {
|
|
800
|
+
return this.hashAtRest ? fingerprint(token) : token;
|
|
801
|
+
}
|
|
802
|
+
/** `credentialId` (the token's SHA-256) of a stored row, from its store key. */
|
|
803
|
+
fingerprintOfKey(key) {
|
|
804
|
+
return this.hashAtRest && HASHED_KEY.test(key) ? key : fingerprint(key);
|
|
805
|
+
}
|
|
806
|
+
/** Persist a new credential; returns the token the client will hold. */
|
|
807
|
+
async put(state, ttl) {
|
|
808
|
+
if (!this.hashAtRest && !this.generateToken) return await this.store.persist(state, ttl);
|
|
809
|
+
const token = this.generateToken?.() ?? (0, node_crypto.randomBytes)(32).toString("base64url");
|
|
810
|
+
await this.store.persistAs(this.keyOf(token), state, ttl);
|
|
811
|
+
return token;
|
|
812
|
+
}
|
|
813
|
+
/**
|
|
814
|
+
* Look a token up: by its store key, and — under `hashAtRest: 'migrate'` —
|
|
815
|
+
* by the token itself for a row written before hashing was enabled.
|
|
816
|
+
*/
|
|
817
|
+
async find(token, key = this.keyOf(token)) {
|
|
818
|
+
const state = await this.store.retrieve(key);
|
|
819
|
+
if (state) return {
|
|
820
|
+
key,
|
|
821
|
+
state
|
|
822
|
+
};
|
|
823
|
+
if (!this.mayBeLegacyKey(token)) return null;
|
|
824
|
+
const legacy = await this.store.retrieve(token);
|
|
825
|
+
return legacy ? {
|
|
826
|
+
key: token,
|
|
827
|
+
state: legacy
|
|
828
|
+
} : null;
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* `'migrate'`: may `token` be a row written before hashing, stored under
|
|
832
|
+
* the token itself? Never for a hash-shaped value — that is what a database
|
|
833
|
+
* read yields, and accepting it would turn a leaked row key into a session.
|
|
834
|
+
*/
|
|
835
|
+
mayBeLegacyKey(token) {
|
|
836
|
+
return this.hashAtRest === "migrate" && !HASHED_KEY.test(token) && !/\s/.test(token) && this.isLegacyToken(token);
|
|
837
|
+
}
|
|
778
838
|
async refresh(refreshToken, opts) {
|
|
779
839
|
const now = this.clock.now();
|
|
780
|
-
const
|
|
781
|
-
|
|
840
|
+
const found = await this.find(refreshToken);
|
|
841
|
+
const oldState = found?.state;
|
|
842
|
+
if (!found || !oldState) {
|
|
782
843
|
const consumed = this.lookupConsumedRefresh(refreshToken);
|
|
783
844
|
if (consumed) await this.fireRefreshReuseTheftResponse(consumed, refreshToken);
|
|
784
|
-
throw new AuthError("INVALID_TOKEN");
|
|
845
|
+
throw new require_payload.AuthError("INVALID_TOKEN");
|
|
785
846
|
}
|
|
786
|
-
if (oldState.kind !== "refresh") throw new AuthError("INVALID_TOKEN", "Token is not a refresh credential");
|
|
847
|
+
if (oldState.kind !== "refresh") throw new require_payload.AuthError("INVALID_TOKEN", "Token is not a refresh credential");
|
|
787
848
|
await opts?.guard?.(oldState);
|
|
788
849
|
const rotation = oldState.metadata?.refreshRotation ?? (this.refreshConfig ? this.refreshConfig.rotation ?? "sliding" : "always");
|
|
789
850
|
switch (rotation) {
|
|
790
851
|
case "none": return await this.refreshNone(oldState, refreshToken, now);
|
|
791
|
-
case "always": return await this.refreshAlways(oldState, refreshToken, now);
|
|
792
|
-
case "sliding": return await this.refreshSliding(oldState, refreshToken, now);
|
|
793
|
-
default: throw new AuthError("INVALID_CONFIG", `Unknown rotation: ${String(rotation)}`);
|
|
852
|
+
case "always": return await this.refreshAlways(oldState, refreshToken, found.key, now);
|
|
853
|
+
case "sliding": return await this.refreshSliding(oldState, refreshToken, found.key, now);
|
|
854
|
+
default: throw new require_payload.AuthError("INVALID_CONFIG", `Unknown rotation: ${String(rotation)}`);
|
|
794
855
|
}
|
|
795
856
|
}
|
|
796
857
|
async refreshNone(oldState, refreshToken, now) {
|
|
@@ -808,8 +869,8 @@ var AuthCredential = class {
|
|
|
808
869
|
* forward (rolling session). Grace-tolerant via the shared store-backed
|
|
809
870
|
* window.
|
|
810
871
|
*/
|
|
811
|
-
async refreshSliding(oldState, refreshToken, now) {
|
|
812
|
-
return await this.rotateWithGrace(oldState, refreshToken, now, false);
|
|
872
|
+
async refreshSliding(oldState, refreshToken, key, now) {
|
|
873
|
+
return await this.rotateWithGrace(oldState, refreshToken, key, now, false);
|
|
813
874
|
}
|
|
814
875
|
/**
|
|
815
876
|
* `always` rotation: rotate on every use but keep a FIXED session ceiling —
|
|
@@ -821,9 +882,9 @@ var AuthCredential = class {
|
|
|
821
882
|
* kept valid (`update` re-issues), so it falls back to single-use semantics
|
|
822
883
|
* with a process-local reuse signal — the only mechanism possible there.
|
|
823
884
|
*/
|
|
824
|
-
async refreshAlways(oldState, refreshToken, now) {
|
|
885
|
+
async refreshAlways(oldState, refreshToken, key, now) {
|
|
825
886
|
if (!this.store.listForUser) {
|
|
826
|
-
await this.store.consume(
|
|
887
|
+
await this.store.consume(key);
|
|
827
888
|
this.sweepConsumedRefreshes();
|
|
828
889
|
this.consumedRefreshes.set(refreshToken, {
|
|
829
890
|
userId: oldState.userId,
|
|
@@ -831,9 +892,9 @@ var AuthCredential = class {
|
|
|
831
892
|
exp: oldState.expiresAt,
|
|
832
893
|
...oldState.sessionId !== void 0 && { sessionId: oldState.sessionId }
|
|
833
894
|
});
|
|
834
|
-
return await this.issueRotatedPair(oldState, refreshToken, false, now, true);
|
|
895
|
+
return await this.issueRotatedPair(oldState, refreshToken, key, false, now, true);
|
|
835
896
|
}
|
|
836
|
-
return await this.rotateWithGrace(oldState, refreshToken, now, true);
|
|
897
|
+
return await this.rotateWithGrace(oldState, refreshToken, key, now, true);
|
|
837
898
|
}
|
|
838
899
|
/**
|
|
839
900
|
* Shared rotation-with-grace mechanism for `sliding` and `always` on stateful
|
|
@@ -850,9 +911,9 @@ var AuthCredential = class {
|
|
|
850
911
|
* mint-time `metadata.rotationGraceMs` (when stamped) wins over the instance
|
|
851
912
|
* window, and a window of `0` is strict single-use.
|
|
852
913
|
*/
|
|
853
|
-
async rotateWithGrace(oldState, refreshToken, now, preserveExpiry) {
|
|
914
|
+
async rotateWithGrace(oldState, refreshToken, key, now, preserveExpiry) {
|
|
854
915
|
const graceMs = oldState.metadata?.rotationGraceMs ?? this.refreshConfig?.rotationGraceMs ?? DEFAULT_ROTATION_GRACE_MS;
|
|
855
|
-
if (typeof oldState.rotatedAt !== "number") return await this.issueRotatedPair(oldState, refreshToken, true, now, preserveExpiry);
|
|
916
|
+
if (typeof oldState.rotatedAt !== "number") return await this.issueRotatedPair(oldState, refreshToken, key, true, now, preserveExpiry);
|
|
856
917
|
const reuse = {
|
|
857
918
|
userId: oldState.userId,
|
|
858
919
|
sessionId: oldState.sessionId,
|
|
@@ -861,8 +922,8 @@ var AuthCredential = class {
|
|
|
861
922
|
rotatedAt: oldState.rotatedAt
|
|
862
923
|
};
|
|
863
924
|
if (graceMs <= 0 || now - oldState.rotatedAt > graceMs) return await this.respondToRefreshReuse(reuse);
|
|
864
|
-
const successor = oldState.successor;
|
|
865
|
-
const successorState = successor === void 0 ? null : await this.
|
|
925
|
+
const successor = oldState.successor === void 0 ? void 0 : this.openSuccessor(oldState.successor, refreshToken);
|
|
926
|
+
const successorState = successor === void 0 ? null : (await this.find(successor.refreshToken))?.state ?? null;
|
|
866
927
|
if (successor === void 0 || successorState === null || typeof successorState.rotatedAt === "number") return await this.respondToRefreshReuse(reuse);
|
|
867
928
|
this.refreshConfig?.onRotationGraceHit?.({
|
|
868
929
|
userId: oldState.userId,
|
|
@@ -881,11 +942,16 @@ var AuthCredential = class {
|
|
|
881
942
|
};
|
|
882
943
|
}
|
|
883
944
|
async revoke(token) {
|
|
884
|
-
this.
|
|
945
|
+
await this.revokeKey(this.keyOf(token));
|
|
946
|
+
if (this.mayBeLegacyKey(token)) await this.revokeKey(token);
|
|
947
|
+
}
|
|
948
|
+
/** Revoke the row stored under `key` (a store key, as `listForUser` returns it). */
|
|
949
|
+
async revokeKey(key) {
|
|
950
|
+
this.validated?.delete(key);
|
|
885
951
|
try {
|
|
886
|
-
await this.store.revoke(
|
|
952
|
+
await this.store.revoke(key);
|
|
887
953
|
} finally {
|
|
888
|
-
this.validated?.delete(
|
|
954
|
+
this.validated?.delete(key);
|
|
889
955
|
}
|
|
890
956
|
}
|
|
891
957
|
async revokeAllForUser(userId) {
|
|
@@ -902,24 +968,19 @@ var AuthCredential = class {
|
|
|
902
968
|
...require_payload.credentialPayloadOf(entry),
|
|
903
969
|
userId: entry.userId,
|
|
904
970
|
method: this.method,
|
|
905
|
-
credentialId:
|
|
971
|
+
credentialId: this.fingerprintOfKey(entry.token),
|
|
906
972
|
sessionId: this.sessionKeyOf(entry),
|
|
907
973
|
expiresAt: entry.expiresAt
|
|
908
974
|
}));
|
|
909
975
|
}
|
|
910
976
|
/**
|
|
911
|
-
*
|
|
912
|
-
*
|
|
913
|
-
*
|
|
914
|
-
* `validate()
|
|
915
|
-
* device" matching stays consistent across all of them.
|
|
977
|
+
* Session-grouping key for a stored credential entry (its store key
|
|
978
|
+
* attached): its stored `sessionId`, or the token fingerprint for legacy
|
|
979
|
+
* rows predating sessionId (so they surface as singleton sessions) — the
|
|
980
|
+
* same fallback `validate()` applies, so "this device" matching holds.
|
|
916
981
|
*/
|
|
917
|
-
sessionIdOf(sessionId, token) {
|
|
918
|
-
return sessionId ?? fingerprint(token);
|
|
919
|
-
}
|
|
920
|
-
/** Session-grouping key for a stored credential entry (token attached). */
|
|
921
982
|
sessionKeyOf(entry) {
|
|
922
|
-
return
|
|
983
|
+
return entry.sessionId ?? this.fingerprintOfKey(entry.token);
|
|
923
984
|
}
|
|
924
985
|
/**
|
|
925
986
|
* List the user's active sessions, one row per token family (access +
|
|
@@ -978,7 +1039,7 @@ var AuthCredential = class {
|
|
|
978
1039
|
async revokeSession(userId, sessionId) {
|
|
979
1040
|
if (!this.store.listForUser) return;
|
|
980
1041
|
const all = await this.store.listForUser(userId);
|
|
981
|
-
await Promise.all(all.filter((entry) => this.sessionKeyOf(entry) === sessionId).map((entry) => this.
|
|
1042
|
+
await Promise.all(all.filter((entry) => this.sessionKeyOf(entry) === sessionId).map((entry) => this.revokeKey(entry.token)));
|
|
982
1043
|
}
|
|
983
1044
|
/**
|
|
984
1045
|
* Revoke every session for the user EXCEPT `keepSessionId` ("log out
|
|
@@ -994,7 +1055,7 @@ var AuthCredential = class {
|
|
|
994
1055
|
const key = this.sessionKeyOf(entry);
|
|
995
1056
|
if (key === keepSessionId) continue;
|
|
996
1057
|
revokedSessions.add(key);
|
|
997
|
-
revokes.push(this.
|
|
1058
|
+
revokes.push(this.revokeKey(entry.token));
|
|
998
1059
|
}
|
|
999
1060
|
await Promise.all(revokes);
|
|
1000
1061
|
return revokedSessions.size;
|
|
@@ -1007,21 +1068,21 @@ var AuthCredential = class {
|
|
|
1007
1068
|
* should then require an explicit secret.
|
|
1008
1069
|
*/
|
|
1009
1070
|
deriveStateKey(label = "wf-state") {
|
|
1010
|
-
if (!this.store.deriveSubkey) throw new AuthError("INVALID_CONFIG", "credential store has no reusable secret; provide an explicit wfStateSecret");
|
|
1071
|
+
if (!this.store.deriveSubkey) throw new require_payload.AuthError("INVALID_CONFIG", "credential store has no reusable secret; provide an explicit wfStateSecret");
|
|
1011
1072
|
return this.store.deriveSubkey(label);
|
|
1012
1073
|
}
|
|
1013
1074
|
async enforceConcurrencyLimit(userId) {
|
|
1014
1075
|
if (!this.store.listForUser || this.maxConcurrent === void 0) return;
|
|
1015
1076
|
const accessOnly = (await this.store.listForUser(userId)).filter((entry) => entry.kind !== "refresh");
|
|
1016
1077
|
if (accessOnly.length < this.maxConcurrent) return;
|
|
1017
|
-
if (this.onLimit === "reject") throw new AuthError("MAX_CONCURRENT_REACHED", void 0, {
|
|
1078
|
+
if (this.onLimit === "reject") throw new require_payload.AuthError("MAX_CONCURRENT_REACHED", void 0, {
|
|
1018
1079
|
userId,
|
|
1019
1080
|
limit: this.maxConcurrent,
|
|
1020
1081
|
active: accessOnly.length
|
|
1021
1082
|
});
|
|
1022
1083
|
const sorted = accessOnly.toSorted((a, b) => a.issuedAt - b.issuedAt);
|
|
1023
1084
|
const toEvict = accessOnly.length - this.maxConcurrent + 1;
|
|
1024
|
-
for (let i = 0; i < toEvict && i < sorted.length; i++) await this.
|
|
1085
|
+
for (let i = 0; i < toEvict && i < sorted.length; i++) await this.revokeKey(sorted[i].token);
|
|
1025
1086
|
}
|
|
1026
1087
|
async issueAccessFromRefresh(refreshState, now) {
|
|
1027
1088
|
const accessTtl = refreshState.metadata?.accessTtl ?? this.accessTtl;
|
|
@@ -1035,7 +1096,7 @@ var AuthCredential = class {
|
|
|
1035
1096
|
...this.trackLastSeen === "refresh" && { lastSeenAt: now }
|
|
1036
1097
|
});
|
|
1037
1098
|
return {
|
|
1038
|
-
token: await this.
|
|
1099
|
+
token: await this.put(accessState, accessTtl),
|
|
1039
1100
|
expiresAt: now + accessTtl
|
|
1040
1101
|
};
|
|
1041
1102
|
}
|
|
@@ -1046,9 +1107,9 @@ var AuthCredential = class {
|
|
|
1046
1107
|
* `now + ttl` (used by `sliding`). `rotateOld` stamps the old refresh as
|
|
1047
1108
|
* rotated (keeping it valid through the grace window) instead of consuming it.
|
|
1048
1109
|
*/
|
|
1049
|
-
async issueRotatedPair(oldRefreshState, oldRefreshToken, rotateOld, now, preserveExpiry = false) {
|
|
1110
|
+
async issueRotatedPair(oldRefreshState, oldRefreshToken, oldKey, rotateOld, now, preserveExpiry = false) {
|
|
1050
1111
|
const slidingTtl = this.refreshConfig?.ttl;
|
|
1051
|
-
if (!preserveExpiry && slidingTtl === void 0) throw new AuthError("INVALID_CONFIG", "Refresh not enabled");
|
|
1112
|
+
if (!preserveExpiry && slidingTtl === void 0) throw new require_payload.AuthError("INVALID_CONFIG", "Refresh not enabled");
|
|
1052
1113
|
const refreshExpiresAt = preserveExpiry ? oldRefreshState.expiresAt : now + slidingTtl;
|
|
1053
1114
|
const refreshTtl = preserveExpiry ? Math.max(0, oldRefreshState.expiresAt - now) : slidingTtl;
|
|
1054
1115
|
const newRefreshState = stateWithPayload(require_payload.credentialPayloadOf(oldRefreshState), {
|
|
@@ -1057,24 +1118,24 @@ var AuthCredential = class {
|
|
|
1057
1118
|
expiresAt: refreshExpiresAt,
|
|
1058
1119
|
kind: "refresh",
|
|
1059
1120
|
metadata: oldRefreshState.metadata,
|
|
1060
|
-
parentCredentialId: oldRefreshToken,
|
|
1121
|
+
parentCredentialId: this.hashAtRest ? fingerprint(oldRefreshToken) : oldRefreshToken,
|
|
1061
1122
|
sessionId: oldRefreshState.sessionId,
|
|
1062
1123
|
...this.trackLastSeen === "refresh" && { lastSeenAt: now }
|
|
1063
1124
|
});
|
|
1064
1125
|
const access = await this.issueAccessFromRefresh(oldRefreshState, now);
|
|
1065
|
-
const newRefreshToken = await this.
|
|
1126
|
+
const newRefreshToken = await this.put(newRefreshState, refreshTtl);
|
|
1066
1127
|
if (rotateOld) {
|
|
1067
1128
|
const rotatedState = {
|
|
1068
1129
|
...oldRefreshState,
|
|
1069
1130
|
rotatedAt: now,
|
|
1070
|
-
successor: {
|
|
1131
|
+
successor: this.sealSuccessor({
|
|
1071
1132
|
accessToken: access.token,
|
|
1072
1133
|
accessExpiresAt: access.expiresAt,
|
|
1073
1134
|
refreshToken: newRefreshToken,
|
|
1074
1135
|
refreshExpiresAt
|
|
1075
|
-
}
|
|
1136
|
+
}, oldRefreshToken)
|
|
1076
1137
|
};
|
|
1077
|
-
await this.store.update(
|
|
1138
|
+
await this.store.update(oldKey, rotatedState);
|
|
1078
1139
|
}
|
|
1079
1140
|
return {
|
|
1080
1141
|
accessToken: access.token,
|
|
@@ -1084,6 +1145,33 @@ var AuthCredential = class {
|
|
|
1084
1145
|
userId: oldRefreshState.userId
|
|
1085
1146
|
};
|
|
1086
1147
|
}
|
|
1148
|
+
/**
|
|
1149
|
+
* Under `hashAtRest` the successor pair is stored encrypted with a key
|
|
1150
|
+
* derived from the old refresh token — only a holder of that token (the
|
|
1151
|
+
* grace-window re-presentation) can read the pair back.
|
|
1152
|
+
*/
|
|
1153
|
+
sealSuccessor(successor, oldRefreshToken) {
|
|
1154
|
+
if (!this.hashAtRest) return successor;
|
|
1155
|
+
const key = successorKey(oldRefreshToken);
|
|
1156
|
+
return {
|
|
1157
|
+
...successor,
|
|
1158
|
+
accessToken: sealToken(key, successor.accessToken),
|
|
1159
|
+
refreshToken: sealToken(key, successor.refreshToken)
|
|
1160
|
+
};
|
|
1161
|
+
}
|
|
1162
|
+
/** Inverse of {@link sealSuccessor}; `undefined` when the pair cannot be opened. */
|
|
1163
|
+
openSuccessor(successor, presentedToken) {
|
|
1164
|
+
if (!(successor.accessToken.startsWith(SEALED_PREFIX) || successor.refreshToken.startsWith(SEALED_PREFIX))) return successor;
|
|
1165
|
+
const key = successorKey(presentedToken);
|
|
1166
|
+
const accessToken = openToken(key, successor.accessToken);
|
|
1167
|
+
const refreshToken = openToken(key, successor.refreshToken);
|
|
1168
|
+
if (accessToken === null || refreshToken === null) return void 0;
|
|
1169
|
+
return {
|
|
1170
|
+
...successor,
|
|
1171
|
+
accessToken,
|
|
1172
|
+
refreshToken
|
|
1173
|
+
};
|
|
1174
|
+
}
|
|
1087
1175
|
/** Amortized sweep of expired `consumedRefreshes` entries (each size doubling). */
|
|
1088
1176
|
sweepConsumedRefreshes() {
|
|
1089
1177
|
if (this.consumedRefreshes.size < this.consumedSweepAt) return;
|
|
@@ -1128,7 +1216,7 @@ var AuthCredential = class {
|
|
|
1128
1216
|
});
|
|
1129
1217
|
if ((this.refreshConfig?.reuseResponse ?? "session") === "session" && reuse.sessionId !== void 0 && this.store.listForUser) await this.revokeSession(reuse.userId, reuse.sessionId);
|
|
1130
1218
|
else await this.revokeAllForUser(reuse.userId);
|
|
1131
|
-
throw new AuthError("REFRESH_REUSE_DETECTED", void 0, {
|
|
1219
|
+
throw new require_payload.AuthError("REFRESH_REUSE_DETECTED", void 0, {
|
|
1132
1220
|
userId: reuse.userId,
|
|
1133
1221
|
...reuse.sessionId !== void 0 && { sessionId: reuse.sessionId },
|
|
1134
1222
|
...reuse.rotatedAt !== void 0 && { rotatedAt: reuse.rotatedAt }
|
|
@@ -1224,44 +1312,95 @@ function renderRateLimitMessage(template, rule, retryAfterMs) {
|
|
|
1224
1312
|
var RateLimitStoreMemory = class {
|
|
1225
1313
|
entries = /* @__PURE__ */ new Map();
|
|
1226
1314
|
clock;
|
|
1315
|
+
maxEntries;
|
|
1316
|
+
evictLast;
|
|
1227
1317
|
/** Map size at which `hit` next sweeps expired counters (amortized; doubles). */
|
|
1228
1318
|
sweepAt = MIN_SWEEP_SIZE;
|
|
1319
|
+
/**
|
|
1320
|
+
* Lower bound of every entry's `expiresAt` (exact after a sweep): while
|
|
1321
|
+
* `now` is below it nothing can have expired, so a sweep is skipped.
|
|
1322
|
+
*/
|
|
1323
|
+
minExpiry = Infinity;
|
|
1324
|
+
/**
|
|
1325
|
+
* - `maxEntries` caps the live counters kept (default: unbounded). At the
|
|
1326
|
+
* cap a new key first sweeps expired counters, then evicts the oldest one.
|
|
1327
|
+
* - `evictLast` marks keys to keep while others can go: at the cap the
|
|
1328
|
+
* oldest key it does NOT match is evicted first (the oldest matching one
|
|
1329
|
+
* only when every key matches) — e.g. active lock markers that a flood of
|
|
1330
|
+
* fresh counters must not push out.
|
|
1331
|
+
*/
|
|
1229
1332
|
constructor(opts) {
|
|
1230
1333
|
this.clock = opts?.clock ?? require_clock.defaultClock;
|
|
1334
|
+
this.maxEntries = opts?.maxEntries ?? Infinity;
|
|
1335
|
+
this.evictLast = opts?.evictLast;
|
|
1231
1336
|
}
|
|
1232
1337
|
async hit(key, ttlMs) {
|
|
1233
1338
|
const now = this.clock.now();
|
|
1234
1339
|
const entry = this.entries.get(key);
|
|
1235
1340
|
if (!entry || entry.expiresAt <= now) {
|
|
1236
|
-
if (!entry && this.entries.size >= this.
|
|
1237
|
-
this.sweep(now);
|
|
1341
|
+
if (!entry && this.entries.size >= this.maxEntries) {
|
|
1342
|
+
if (now >= this.minExpiry) this.sweep(now);
|
|
1343
|
+
while (this.entries.size >= this.maxEntries) this.evictOne();
|
|
1344
|
+
} else if (!entry && this.entries.size >= this.sweepAt) {
|
|
1345
|
+
if (now >= this.minExpiry) this.sweep(now);
|
|
1238
1346
|
this.sweepAt = Math.max(MIN_SWEEP_SIZE, this.entries.size * 2);
|
|
1239
1347
|
}
|
|
1348
|
+
const expiresAt = now + ttlMs;
|
|
1349
|
+
if (expiresAt < this.minExpiry) this.minExpiry = expiresAt;
|
|
1350
|
+
this.entries.delete(key);
|
|
1240
1351
|
this.entries.set(key, {
|
|
1241
1352
|
count: 1,
|
|
1242
|
-
expiresAt
|
|
1353
|
+
expiresAt
|
|
1243
1354
|
});
|
|
1244
1355
|
return 1;
|
|
1245
1356
|
}
|
|
1246
1357
|
entry.count += 1;
|
|
1247
1358
|
return entry.count;
|
|
1248
1359
|
}
|
|
1360
|
+
/** Drop the oldest key (Map keeps insertion order), sparing `evictLast` keys while it can. */
|
|
1361
|
+
evictOne() {
|
|
1362
|
+
let victim;
|
|
1363
|
+
for (const key of this.entries.keys()) {
|
|
1364
|
+
if (!this.evictLast?.(key)) {
|
|
1365
|
+
victim = key;
|
|
1366
|
+
break;
|
|
1367
|
+
}
|
|
1368
|
+
victim ??= key;
|
|
1369
|
+
}
|
|
1370
|
+
if (victim !== void 0) this.entries.delete(victim);
|
|
1371
|
+
}
|
|
1372
|
+
async get(key) {
|
|
1373
|
+
const entry = this.entries.get(key);
|
|
1374
|
+
return entry && entry.expiresAt > this.clock.now() ? entry.count : 0;
|
|
1375
|
+
}
|
|
1376
|
+
async expire(key, ttlMs) {
|
|
1377
|
+
const entry = this.entries.get(key);
|
|
1378
|
+
const now = this.clock.now();
|
|
1379
|
+
if (!entry || entry.expiresAt <= now) return;
|
|
1380
|
+
entry.expiresAt = now + ttlMs;
|
|
1381
|
+
if (entry.expiresAt < this.minExpiry) this.minExpiry = entry.expiresAt;
|
|
1382
|
+
this.entries.delete(key);
|
|
1383
|
+
this.entries.set(key, entry);
|
|
1384
|
+
}
|
|
1249
1385
|
async reset(key) {
|
|
1250
1386
|
this.entries.delete(key);
|
|
1251
1387
|
}
|
|
1252
1388
|
/** Drop every counter — test-harness reset between cases. */
|
|
1253
1389
|
clear() {
|
|
1254
1390
|
this.entries.clear();
|
|
1391
|
+
this.minExpiry = Infinity;
|
|
1255
1392
|
}
|
|
1256
1393
|
async cleanup() {
|
|
1257
1394
|
return this.sweep(this.clock.now());
|
|
1258
1395
|
}
|
|
1259
1396
|
sweep(now) {
|
|
1260
1397
|
let removed = 0;
|
|
1398
|
+
let min = Infinity;
|
|
1261
1399
|
for (const [key, entry] of this.entries) if (entry.expiresAt <= now) {
|
|
1262
1400
|
this.entries.delete(key);
|
|
1263
1401
|
removed++;
|
|
1264
|
-
}
|
|
1402
|
+
} else if (entry.expiresAt < min) min = entry.expiresAt;
|
|
1403
|
+
this.minExpiry = min;
|
|
1265
1404
|
return removed;
|
|
1266
1405
|
}
|
|
1267
1406
|
};
|
|
@@ -1277,6 +1416,18 @@ const MIN_SWEEP_SIZE = 1024;
|
|
|
1277
1416
|
* key and one atomic store increment decides. All rules are hit on every
|
|
1278
1417
|
* check (rejected requests count too — they cannot extend a fixed window).
|
|
1279
1418
|
*/
|
|
1419
|
+
/**
|
|
1420
|
+
* The item that governs a combined decision: among the rejected ones (when
|
|
1421
|
+
* any), the one whose window frees capacity LAST — the request only becomes
|
|
1422
|
+
* allowed once every one passes, so a shorter hint would invite
|
|
1423
|
+
* guaranteed-rejected retries; otherwise the one with the least remaining
|
|
1424
|
+
* budget. Used across the rules of one check and across stacked policies.
|
|
1425
|
+
*/
|
|
1426
|
+
function pickGoverning(items, rejected) {
|
|
1427
|
+
const failing = items.filter(rejected);
|
|
1428
|
+
if (failing.length > 0) return failing.reduce((a, b) => b.resetAt > a.resetAt ? b : a);
|
|
1429
|
+
return items.reduce((a, b) => b.remaining < a.remaining ? b : a);
|
|
1430
|
+
}
|
|
1280
1431
|
var RateLimiter = class {
|
|
1281
1432
|
store;
|
|
1282
1433
|
clock;
|
|
@@ -1296,24 +1447,35 @@ var RateLimiter = class {
|
|
|
1296
1447
|
* retries.
|
|
1297
1448
|
*/
|
|
1298
1449
|
async check(scope, subject, rules, opts) {
|
|
1299
|
-
|
|
1450
|
+
return this.evaluate(scope, subject, rules, opts, (key, rule) => this.store.hit(key, rule.window * 2));
|
|
1451
|
+
}
|
|
1452
|
+
/**
|
|
1453
|
+
* Read the budget `check()` would see — without spending it. `remaining`
|
|
1454
|
+
* is what is left in each window; `allowed` says whether a `check()` made
|
|
1455
|
+
* now would pass. Use it for a "N left today" status line. Requires a store
|
|
1456
|
+
* with `get()` (both bundled stores have it).
|
|
1457
|
+
*/
|
|
1458
|
+
async peek(scope, subject, rules, opts) {
|
|
1459
|
+
if (!this.store.get) throw new Error("RateLimiter.peek: the rate-limit store does not implement get()");
|
|
1460
|
+
const get = this.store.get.bind(this.store);
|
|
1461
|
+
return this.evaluate(scope, subject, rules, opts, async (key) => await get(key) + 1, 1);
|
|
1462
|
+
}
|
|
1463
|
+
async evaluate(scope, subject, rules, opts, count, offset = 0) {
|
|
1464
|
+
if (rules.length === 0) throw new Error("RateLimiter: at least one rule is required");
|
|
1300
1465
|
const parsed = rules.map((r) => parseRateLimitRule(r));
|
|
1301
1466
|
const now = this.clock.now();
|
|
1302
1467
|
const keyBase = `${encodeURIComponent(scope)}:${encodeURIComponent(subject)}`;
|
|
1303
|
-
const
|
|
1468
|
+
const governing = pickGoverning(await Promise.all(parsed.map(async (rule, i) => {
|
|
1304
1469
|
const windowStart = Math.floor(now / rule.window) * rule.window;
|
|
1305
|
-
const
|
|
1306
|
-
const count = await this.store.hit(key, rule.window * 2);
|
|
1470
|
+
const n = await count(`${keyBase}:${i}:${windowStart}`, rule);
|
|
1307
1471
|
return {
|
|
1308
1472
|
rule,
|
|
1309
|
-
remaining: Math.max(0, rule.limit -
|
|
1473
|
+
remaining: Math.max(0, rule.limit - n + offset),
|
|
1310
1474
|
resetAt: windowStart + rule.window,
|
|
1311
|
-
violated:
|
|
1475
|
+
violated: n > rule.limit
|
|
1312
1476
|
};
|
|
1313
|
-
}));
|
|
1314
|
-
const
|
|
1315
|
-
const rejected = violated.length > 0;
|
|
1316
|
-
const governing = rejected ? violated.reduce((a, b) => b.resetAt > a.resetAt ? b : a) : evaluated.reduce((a, b) => b.remaining < a.remaining ? b : a);
|
|
1477
|
+
})), (e) => e.violated);
|
|
1478
|
+
const rejected = governing.violated;
|
|
1317
1479
|
const resetAfterMs = governing.resetAt - now;
|
|
1318
1480
|
return {
|
|
1319
1481
|
allowed: !rejected,
|
|
@@ -1337,7 +1499,7 @@ function generateMagicLinkToken() {
|
|
|
1337
1499
|
}
|
|
1338
1500
|
//#endregion
|
|
1339
1501
|
exports.AuthCredential = AuthCredential;
|
|
1340
|
-
exports.AuthError = AuthError;
|
|
1502
|
+
exports.AuthError = require_payload.AuthError;
|
|
1341
1503
|
exports.CredentialStoreEncapsulated = CredentialStoreEncapsulated;
|
|
1342
1504
|
exports.CredentialStoreJwt = CredentialStoreJwt;
|
|
1343
1505
|
exports.CredentialStoreMemory = CredentialStoreMemory;
|
|
@@ -1351,4 +1513,5 @@ exports.generateMagicLinkToken = generateMagicLinkToken;
|
|
|
1351
1513
|
exports.generateOpaqueToken = require_opaque_token.generateOpaqueToken;
|
|
1352
1514
|
exports.parseDurationMs = parseDurationMs;
|
|
1353
1515
|
exports.parseRateLimitRule = parseRateLimitRule;
|
|
1516
|
+
exports.pickGoverning = pickGoverning;
|
|
1354
1517
|
exports.renderRateLimitMessage = renderRateLimitMessage;
|