@c9up/warden 0.1.26 → 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.
Files changed (41) hide show
  1. package/dist/WardenProvider.d.ts +1 -0
  2. package/dist/WardenProvider.d.ts.map +1 -1
  3. package/dist/WardenProvider.js +16 -2
  4. package/dist/WardenProvider.js.map +1 -1
  5. package/dist/mfa/OtpProvider.d.ts +39 -1
  6. package/dist/mfa/OtpProvider.d.ts.map +1 -1
  7. package/dist/mfa/OtpProvider.js +97 -5
  8. package/dist/mfa/OtpProvider.js.map +1 -1
  9. package/dist/mfa/WebauthnProvider.d.ts +60 -10
  10. package/dist/mfa/WebauthnProvider.d.ts.map +1 -1
  11. package/dist/mfa/WebauthnProvider.js +207 -47
  12. package/dist/mfa/WebauthnProvider.js.map +1 -1
  13. package/dist/native.d.ts.map +1 -1
  14. package/dist/native.js +7 -23
  15. package/dist/native.js.map +1 -1
  16. package/dist/quasar.d.ts +6 -9
  17. package/dist/quasar.d.ts.map +1 -1
  18. package/dist/quasar.js +17 -47
  19. package/dist/quasar.js.map +1 -1
  20. package/dist/services/main.d.ts +10 -0
  21. package/dist/services/main.d.ts.map +1 -1
  22. package/dist/services/main.js +12 -0
  23. package/dist/services/main.js.map +1 -1
  24. package/dist/vendor/nativeBinary.d.ts +43 -0
  25. package/dist/vendor/nativeBinary.d.ts.map +1 -0
  26. package/dist/vendor/nativeBinary.js +99 -0
  27. package/dist/vendor/nativeBinary.js.map +1 -0
  28. package/dist/vendor/quasarConnection.d.ts +35 -0
  29. package/dist/vendor/quasarConnection.d.ts.map +1 -0
  30. package/dist/vendor/quasarConnection.js +62 -0
  31. package/dist/vendor/quasarConnection.js.map +1 -0
  32. package/index.win32-x64-msvc.node +0 -0
  33. package/package.json +1 -1
  34. package/src/WardenProvider.ts +18 -2
  35. package/src/mfa/OtpProvider.ts +133 -6
  36. package/src/mfa/WebauthnProvider.ts +289 -71
  37. package/src/native.ts +7 -25
  38. package/src/quasar.ts +18 -64
  39. package/src/services/main.ts +13 -0
  40. package/src/vendor/nativeBinary.ts +110 -0
  41. package/src/vendor/quasarConnection.ts +129 -0
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Every `platform-arch` a binary is built for.
3
+ *
4
+ * For the message a package raises when it refuses: "no binary for
5
+ * linux-riscv64" is only actionable next to the list of what there IS.
6
+ */
7
+ export declare function supportedTargets(): readonly string[];
8
+ /** The suffix a given `platform-arch` builds under, or `undefined`. */
9
+ export declare function nativeTargetSuffix(target: string): string | undefined;
10
+ /** The suffix for THIS platform, or `undefined` where no binary is built. */
11
+ export declare function nativeBinarySuffix(): string | undefined;
12
+ /**
13
+ * Why the binary is not there, phrased for whoever has to fix it.
14
+ *
15
+ * "not found" and "not built for your platform" call for different actions,
16
+ * and a single "unavailable" leaves the reader to guess which one they are
17
+ * looking at.
18
+ */
19
+ export declare function unavailableReason(cause?: unknown): string;
20
+ /**
21
+ * `musl` builds under a different suffix, and the failure is otherwise
22
+ * baffling: the file is there, and `require` still refuses it. Worth saying so
23
+ * in a message rather than leaving a reader to discover glibc.
24
+ */
25
+ export declare function muslHint(): string;
26
+ /** What a load attempt did, so the caller can apply its own policy. */
27
+ export type NativeBinaryResult<T> = {
28
+ loaded: true;
29
+ binary: T;
30
+ } | {
31
+ loaded: false;
32
+ suffix: string | undefined;
33
+ cause?: unknown;
34
+ };
35
+ /**
36
+ * Load `<package root>/index.<suffix>.node`.
37
+ *
38
+ * The path is fixed rather than passed: this file is generated into
39
+ * `<package>/src/vendor/`, so the package root is always two levels up, from
40
+ * `src` and from `dist` alike.
41
+ */
42
+ export declare function loadNativeBinary<T>(): NativeBinaryResult<T>;
43
+ //# sourceMappingURL=nativeBinary.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nativeBinary.d.ts","sourceRoot":"","sources":["../../src/vendor/nativeBinary.ts"],"names":[],"mappings":"AAoCA;;;;;GAKG;AACH,wBAAgB,gBAAgB,IAAI,SAAS,MAAM,EAAE,CAEpD;AAED,uEAAuE;AACvE,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAErE;AAED,6EAA6E;AAC7E,wBAAgB,kBAAkB,IAAI,MAAM,GAAG,SAAS,CAEvD;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,CAAC,EAAE,OAAO,GAAG,MAAM,CAQzD;AAED;;;;GAIG;AACH,wBAAgB,QAAQ,IAAI,MAAM,CAIjC;AAED,uEAAuE;AACvE,MAAM,MAAM,kBAAkB,CAAC,CAAC,IAC7B;IAAE,MAAM,EAAE,IAAI,CAAC;IAAC,MAAM,EAAE,CAAC,CAAA;CAAE,GAC3B;IAAE,MAAM,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IAAC,KAAK,CAAC,EAAE,OAAO,CAAA;CAAE,CAAC;AAElE;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,KAAK,kBAAkB,CAAC,CAAC,CAAC,CAa3D"}
@@ -0,0 +1,99 @@
1
+ // Generated from scripts/vendor/nativeBinary.ts — do not edit.
2
+ //
3
+ // This package is published and built from its own repository, so the file
4
+ // has to exist here rather than be imported. `pnpm vendor:sync` rewrites it,
5
+ // and `pnpm vendor:check` fails if this copy has drifted from the original.
6
+ /**
7
+ * Finding the NAPI binary a package ships beside itself.
8
+ *
9
+ * Every package with a Rust engine repeats the same table: napi-rs names its
10
+ * artefacts `index.<platform>-<arch>-<abi>.node`, and the mapping from Node's
11
+ * `platform`/`arch` to that suffix is the part that must never differ between
12
+ * packages. Adding a target means adding it everywhere, and a package that
13
+ * missed the edit fails only on that platform — which is exactly the failure
14
+ * nobody reproduces.
15
+ *
16
+ * What is NOT here is the policy. Some packages degrade when the binary is
17
+ * absent and answer `undefined`; others refuse loudly with build instructions.
18
+ * Both are right for their package, so the loader reports what happened and
19
+ * the caller decides.
20
+ */
21
+ import { createRequire } from "node:module";
22
+ import { dirname, join } from "node:path";
23
+ import { arch, platform } from "node:process";
24
+ import { fileURLToPath } from "node:url";
25
+ /** Node's `platform-arch` → the suffix napi-rs builds under. */
26
+ const TARGETS = {
27
+ "linux-x64": "linux-x64-gnu",
28
+ "linux-arm64": "linux-arm64-gnu",
29
+ "darwin-x64": "darwin-x64",
30
+ "darwin-arm64": "darwin-arm64",
31
+ "win32-x64": "win32-x64-msvc",
32
+ };
33
+ /**
34
+ * Every `platform-arch` a binary is built for.
35
+ *
36
+ * For the message a package raises when it refuses: "no binary for
37
+ * linux-riscv64" is only actionable next to the list of what there IS.
38
+ */
39
+ export function supportedTargets() {
40
+ return Object.keys(TARGETS);
41
+ }
42
+ /** The suffix a given `platform-arch` builds under, or `undefined`. */
43
+ export function nativeTargetSuffix(target) {
44
+ return TARGETS[target];
45
+ }
46
+ /** The suffix for THIS platform, or `undefined` where no binary is built. */
47
+ export function nativeBinarySuffix() {
48
+ return nativeTargetSuffix(`${platform}-${arch}`);
49
+ }
50
+ /**
51
+ * Why the binary is not there, phrased for whoever has to fix it.
52
+ *
53
+ * "not found" and "not built for your platform" call for different actions,
54
+ * and a single "unavailable" leaves the reader to guess which one they are
55
+ * looking at.
56
+ */
57
+ export function unavailableReason(cause) {
58
+ if (cause !== undefined) {
59
+ return `failed to load (${cause instanceof Error ? cause.message : String(cause)})`;
60
+ }
61
+ const target = `${platform}-${arch}`;
62
+ return nativeTargetSuffix(target) !== undefined
63
+ ? "binary not found"
64
+ : `no prebuilt binary for ${target}`;
65
+ }
66
+ /**
67
+ * `musl` builds under a different suffix, and the failure is otherwise
68
+ * baffling: the file is there, and `require` still refuses it. Worth saying so
69
+ * in a message rather than leaving a reader to discover glibc.
70
+ */
71
+ export function muslHint() {
72
+ return platform === "linux"
73
+ ? " On Alpine/musl, the gnu binary will not load — build the musl target."
74
+ : "";
75
+ }
76
+ /**
77
+ * Load `<package root>/index.<suffix>.node`.
78
+ *
79
+ * The path is fixed rather than passed: this file is generated into
80
+ * `<package>/src/vendor/`, so the package root is always two levels up, from
81
+ * `src` and from `dist` alike.
82
+ */
83
+ export function loadNativeBinary() {
84
+ const suffix = nativeBinarySuffix();
85
+ if (suffix === undefined)
86
+ return { loaded: false, suffix };
87
+ const here = dirname(fileURLToPath(import.meta.url));
88
+ try {
89
+ const nodeRequire = createRequire(import.meta.url);
90
+ return {
91
+ loaded: true,
92
+ binary: nodeRequire(join(here, `../../index.${suffix}.node`)),
93
+ };
94
+ }
95
+ catch (cause) {
96
+ return { loaded: false, suffix, cause };
97
+ }
98
+ }
99
+ //# sourceMappingURL=nativeBinary.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nativeBinary.js","sourceRoot":"","sources":["../../src/vendor/nativeBinary.ts"],"names":[],"mappings":"AAAA,+DAA+D;AAC/D,EAAE;AACF,2EAA2E;AAC3E,6EAA6E;AAC7E,4EAA4E;AAE5E;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,gEAAgE;AAChE,MAAM,OAAO,GAA2B;IACvC,WAAW,EAAE,eAAe;IAC5B,aAAa,EAAE,iBAAiB;IAChC,YAAY,EAAE,YAAY;IAC1B,cAAc,EAAE,cAAc;IAC9B,WAAW,EAAE,gBAAgB;CAC7B,CAAC;AAEF;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB;IAC/B,OAAO,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AAC7B,CAAC;AAED,uEAAuE;AACvE,MAAM,UAAU,kBAAkB,CAAC,MAAc;IAChD,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC;AACxB,CAAC;AAED,6EAA6E;AAC7E,MAAM,UAA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,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;IACzC,CAAC;AACF,CAAC"}
@@ -0,0 +1,35 @@
1
+ export interface QuasarConnectionRequest {
2
+ /** The package asking. It prefixes every message this can raise. */
3
+ pkg: string;
4
+ /**
5
+ * How this package builds an error.
6
+ *
7
+ * Not optional, and not `new Error` by default: a package with its own
8
+ * error type carries codes (`E_<PKG>_<REASON>`) that a caller catches on,
9
+ * and a shared helper throwing a bare Error would silently drop them. The
10
+ * two reasons are distinguished so the codes can be too.
11
+ */
12
+ raise: (reason: "quasar-missing" | "incomplete-connection", message: string, cause?: unknown) => Error;
13
+ /** Connection name, or `undefined` for quasar's default. */
14
+ name?: string;
15
+ /** The commands the caller will actually issue. */
16
+ required: readonly string[];
17
+ /** What the caller does with them, for the message that names a gap. */
18
+ what: string;
19
+ /**
20
+ * A second way out, when this package has one.
21
+ *
22
+ * Several of them accept a client object directly, so "pass a client
23
+ * instead of a connection name" is actionable — and it was in each
24
+ * package's own message before this was shared. Dropping it to unify the
25
+ * wording would have made the error strictly less useful.
26
+ */
27
+ alternative?: string;
28
+ }
29
+ /**
30
+ * The named connection, checked for the commands the caller needs BEFORE it is
31
+ * handed over — a connection missing one would otherwise fail on the first
32
+ * command, far from the line that asked for it.
33
+ */
34
+ export declare function quasarConnection<T>(request: QuasarConnectionRequest): Promise<T>;
35
+ //# sourceMappingURL=quasarConnection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"quasarConnection.d.ts","sourceRoot":"","sources":["../../src/vendor/quasarConnection.ts"],"names":[],"mappings":"AAiDA,MAAM,WAAW,uBAAuB;IACvC,oEAAoE;IACpE,GAAG,EAAE,MAAM,CAAC;IACZ;;;;;;;OAOG;IACH,KAAK,EAAE,CACN,MAAM,EAAE,gBAAgB,GAAG,uBAAuB,EAClD,OAAO,EAAE,MAAM,EACf,KAAK,CAAC,EAAE,OAAO,KACX,KAAK,CAAC;IACX,4DAA4D;IAC5D,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,mDAAmD;IACnD,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5B,wEAAwE;IACxE,IAAI,EAAE,MAAM,CAAC;IACb;;;;;;;OAOG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;;;GAIG;AACH,wBAAsB,gBAAgB,CAAC,CAAC,EACvC,OAAO,EAAE,uBAAuB,GAC9B,OAAO,CAAC,CAAC,CAAC,CAuCZ"}
@@ -0,0 +1,62 @@
1
+ // Generated from scripts/vendor/quasarConnection.ts — do not edit.
2
+ //
3
+ // This package is published and built from its own repository, so the file
4
+ // has to exist here rather than be imported. `pnpm vendor:sync` rewrites it,
5
+ // and `pnpm vendor:check` fails if this copy has drifted from the original.
6
+ /**
7
+ * Read a member without assuming how the object answers.
8
+ *
9
+ * Two shapes have to work, and they disagree about `in`. Quasar's accessor is
10
+ * a Proxy over an empty null-prototype object with only a `get` trap, so
11
+ * `"connection" in manager` is FALSE while reading it returns the function —
12
+ * gating on `in` rejected the real manager. And a module namespace under a
13
+ * test double RAISES for an export it does not have, rather than answering
14
+ * undefined, so a bare read fails on the mock. Reading through a catch is what
15
+ * satisfies both.
16
+ */
17
+ function readMember(value, name) {
18
+ if (typeof value !== "object" || value === null)
19
+ return undefined;
20
+ try {
21
+ return Reflect.get(value, name);
22
+ }
23
+ catch {
24
+ return undefined;
25
+ }
26
+ }
27
+ function isConnectionSource(value) {
28
+ return typeof readMember(value, "connection") === "function";
29
+ }
30
+ /**
31
+ * The named connection, checked for the commands the caller needs BEFORE it is
32
+ * handed over — a connection missing one would otherwise fail on the first
33
+ * command, far from the line that asked for it.
34
+ */
35
+ export async function quasarConnection(request) {
36
+ const { pkg, name, required, what, raise, alternative } = request;
37
+ const specifier = "@c9up/quasar/services/main";
38
+ let loaded;
39
+ try {
40
+ loaded = await import(/* @vite-ignore */ specifier);
41
+ }
42
+ catch (cause) {
43
+ throw raise("quasar-missing", `[${pkg}] ${what} asks for the quasar connection "${name ?? "default"}", but @c9up/quasar is not installed.\n` +
44
+ ` pnpm add @c9up/quasar${alternative ? `, ${alternative}` : ""}`, cause);
45
+ }
46
+ const manager = isConnectionSource(loaded)
47
+ ? loaded
48
+ : Reflect.get(Object(loaded), "default");
49
+ if (!isConnectionSource(manager)) {
50
+ throw raise("quasar-missing", `[${pkg}] @c9up/quasar/services/main did not expose a connection() manager`);
51
+ }
52
+ const connection = manager.connection(name);
53
+ const missing = required.filter((command) => typeof readMember(connection, command) !== "function");
54
+ if (missing.length > 0) {
55
+ throw raise("incomplete-connection", `[${pkg}] the quasar connection${name ? ` '${name}'` : ""} is missing ${missing.join(", ")}, which ${what} issues`);
56
+ }
57
+ // Load-bearing: every member of `required` has just been checked to be a
58
+ // function on this object. The caller names the type it needs because only
59
+ // the caller knows which commands it asked for.
60
+ return connection;
61
+ }
62
+ //# sourceMappingURL=quasarConnection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"quasarConnection.js","sourceRoot":"","sources":["../../src/vendor/quasarConnection.ts"],"names":[],"mappings":"AAAA,mEAAmE;AACnE,EAAE;AACF,2EAA2E;AAC3E,6EAA6E;AAC7E,4EAA4E;AAqB5E;;;;;;;;;;GAUG;AACH,SAAS,UAAU,CAAC,KAAc,EAAE,IAAY;IAC/C,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,SAAS,CAAC;IAClE,IAAI,CAAC;QACJ,OAAO,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IACjC,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,SAAS,CAAC;IAClB,CAAC;AACF,CAAC;AAED,SAAS,kBAAkB,CAAC,KAAc;IACzC,OAAO,OAAO,UAAU,CAAC,KAAK,EAAE,YAAY,CAAC,KAAK,UAAU,CAAC;AAC9D,CAAC;AAmCD;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACrC,OAAgC;IAEhC,MA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,IAAI,CAAC,WAAW,IAAI,SAAS,CAClH,CAAC;IACH,CAAC;IACD,yEAAyE;IACzE,2EAA2E;IAC3E,gDAAgD;IAChD,OAAO,UAAe,CAAC;AACxB,CAAC"}
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@c9up/warden",
3
- "version": "0.1.26",
3
+ "version": "0.2.0",
4
4
  "description": "Warden — Authentication & authorization for the Ream framework",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -6,7 +6,7 @@ import { MfaManager } from "./mfa/MfaManager.js";
6
6
  import type { BouncerRegistry } from "./middleware.js";
7
7
  import { MemoryRightsStore } from "./rights/MemoryRightsStore.js";
8
8
  import { RightsResolver } from "./rights/RightsResolver.js";
9
- import { setAuth } from "./services/main.js";
9
+ import { clearAuth, getAuth, setAuth } from "./services/main.js";
10
10
  import { ApiKeyStrategy } from "./strategies/ApiKeyStrategy.js";
11
11
  import { JwtStrategy } from "./strategies/JwtStrategy.js";
12
12
  import { SessionStrategy } from "./strategies/SessionStrategy.js";
@@ -26,6 +26,9 @@ export interface WardenAppContext {
26
26
  }
27
27
 
28
28
  export default class WardenProvider {
29
+ /** The manager this provider installed, so shutdown only clears its own. */
30
+ #auth: AuthManager | undefined;
31
+
29
32
  constructor(protected app: WardenAppContext) {}
30
33
 
31
34
  register() {
@@ -162,10 +165,23 @@ export default class WardenProvider {
162
165
 
163
166
  async boot() {
164
167
  const manager = await this.app.container.resolve(AuthManager);
165
- if (manager instanceof AuthManager) setAuth(manager);
168
+ if (manager instanceof AuthManager) {
169
+ this.#auth = manager;
170
+ setAuth(manager);
171
+ }
166
172
  await this.#registerTemplateTags();
167
173
  }
168
174
 
175
+ async shutdown() {
176
+ // Release the module-level singleton, but only while it is still ours.
177
+ // A stopped application left a dead AuthManager reachable through
178
+ // `import auth from '@c9up/warden/services/main'`; and with two
179
+ // applications in one process, clearing unconditionally would take the
180
+ // survivor's auth down with it.
181
+ if (this.#auth !== undefined && getAuth() === this.#auth) clearAuth();
182
+ this.#auth = undefined;
183
+ }
184
+
169
185
  /**
170
186
  * Publish `@can` / `@cannot` to the template engine, as AdonisJS's bouncer
171
187
  * does. A migrated template keeps `@can('PostPolicy.edit', post) … @endcan`
@@ -31,17 +31,105 @@ export interface OtpChallenge {
31
31
  attempts: number;
32
32
  }
33
33
 
34
- /** Storage for pending challenges. */
34
+ /**
35
+ * Storage for pending challenges.
36
+ *
37
+ * {@link take} is what makes a one-time code one-time. Verification used to be
38
+ * `find` then compare then `delete` — three operations with `await` between
39
+ * them — so two requests carrying the same correct code both read the challenge
40
+ * before either removed it, and both were told `ok`. The attempt budget had the
41
+ * same shape: concurrent wrong guesses each read `attempts: 0` and wrote `1`,
42
+ * so twenty of them burned one attempt. A store backed by a network widens that
43
+ * window from microseconds to a round trip.
44
+ *
45
+ * A custom store MUST implement `take` as a single indivisible operation:
46
+ * `DELETE ... RETURNING` on SQL, `GETDEL` or a Lua script on Redis, a
47
+ * compare-and-set on anything else. Handing back a copy and deleting separately
48
+ * reopens the hole this exists to close.
49
+ */
35
50
  export interface OtpChallengeStore {
36
51
  save(challenge: OtpChallenge): Promise<void>;
37
52
  find(id: string): Promise<OtpChallenge | null>;
38
53
  delete(id: string): Promise<void>;
54
+ /**
55
+ * Atomically remove the challenge and return what was removed.
56
+ *
57
+ * At most one concurrent caller can be handed a given challenge; every
58
+ * other gets `null`. Whoever holds it decides what happens next — spend it,
59
+ * or put it back with one more attempt recorded.
60
+ */
61
+ take(id: string): Promise<OtpChallenge | null>;
39
62
  }
40
63
 
41
64
  export class MemoryOtpChallengeStore implements OtpChallengeStore {
42
65
  #store = new Map<string, OtpChallenge>();
66
+ /**
67
+ * Size at which the next sweep runs, doubling each time.
68
+ *
69
+ * Entries only ever left when their id was reused or taken, so a challenge
70
+ * nobody came back for — a code requested and never submitted, which is the
71
+ * ordinary abandoned login — stayed for the life of the process. Sweeping on
72
+ * write keeps it bounded without a timer: a timer would hold the event loop
73
+ * open and need a disposal contract this store does not have.
74
+ *
75
+ * Doubling makes the cost amortised O(1) per save rather than a scan on
76
+ * every one, and the floor keeps a small deployment from sweeping constantly.
77
+ */
78
+ #sweepAt = 64;
79
+ readonly #maxEntries: number;
80
+
81
+ /**
82
+ * @param maxEntries How many pending challenges this process will hold.
83
+ * Sweeping only removes EXPIRED entries, so a flood of still-valid ones —
84
+ * an unauthenticated endpoint being hammered — grew the map without any
85
+ * ceiling. Default 10 000, which is far above a real login rate and far
86
+ * below a memory problem.
87
+ */
88
+ constructor(maxEntries = 10_000) {
89
+ // A ceiling of 0, a negative, NaN or Infinity is not a ceiling: the
90
+ // first two refuse every write and the last two disable the bound this
91
+ // exists to provide, silently. A caller asking for one of those means
92
+ // something, and none of the meanings is what would have happened.
93
+ if (!Number.isInteger(maxEntries) || maxEntries < 1) {
94
+ throw new WardenError(
95
+ "E_WARDEN_STORE_LIMIT_INVALID",
96
+ `maxEntries must be a positive integer, got ${String(maxEntries)}.`,
97
+ {
98
+ hint: "Pass the number of pending entries this process may hold — the default is 10_000.",
99
+ },
100
+ );
101
+ }
102
+ this.#maxEntries = maxEntries;
103
+ }
104
+
43
105
  async save(c: OtpChallenge): Promise<void> {
106
+ if (this.#store.size >= this.#maxEntries && !this.#store.has(c.id)) {
107
+ // Swept first: the ceiling is about live challenges, not stale ones.
108
+ this.#sweep();
109
+ }
110
+ if (this.#store.size >= this.#maxEntries && !this.#store.has(c.id)) {
111
+ // REFUSED, not evicted. Evicting to make room lets whoever is
112
+ // flooding push a legitimate user's challenge out and lock them out;
113
+ // refusing the new one fails the attacker instead.
114
+ throw new WardenError(
115
+ "E_WARDEN_OTP_STORE_FULL",
116
+ `The in-memory OTP store is full (${this.#maxEntries} pending challenges).`,
117
+ {
118
+ hint: "Rate-limit the endpoint that mints codes, or move to a persistent store with its own TTL.",
119
+ },
120
+ );
121
+ }
44
122
  this.#store.set(c.id, c);
123
+ if (this.#store.size > this.#sweepAt) this.#sweep();
124
+ }
125
+
126
+ /** Drop everything already expired. */
127
+ #sweep(): void {
128
+ const now = Date.now();
129
+ for (const [id, challenge] of this.#store) {
130
+ if (challenge.expiresAt < now) this.#store.delete(id);
131
+ }
132
+ this.#sweepAt = Math.max(64, this.#store.size * 2);
45
133
  }
46
134
  async find(id: string): Promise<OtpChallenge | null> {
47
135
  return this.#store.get(id) ?? null;
@@ -49,6 +137,17 @@ export class MemoryOtpChallengeStore implements OtpChallengeStore {
49
137
  async delete(id: string): Promise<void> {
50
138
  this.#store.delete(id);
51
139
  }
140
+ /**
141
+ * Atomic here for free: a synchronous read-and-remove with no `await`
142
+ * between the two cannot be interleaved on a single-threaded runtime.
143
+ * Written as one statement pair on purpose — adding an `await` inside would
144
+ * silently reintroduce the race.
145
+ */
146
+ async take(id: string): Promise<OtpChallenge | null> {
147
+ const challenge = this.#store.get(id) ?? null;
148
+ this.#store.delete(id);
149
+ return challenge;
150
+ }
52
151
  }
53
152
 
54
153
  export interface OtpConfig {
@@ -88,6 +187,21 @@ export class OtpProvider {
88
187
  readonly #maxAttempts: number;
89
188
 
90
189
  constructor(config: OtpConfig) {
190
+ // `take` became part of the contract in 0.2.0 because a one-time code
191
+ // cannot be one-time without it. A store written against the old
192
+ // interface would otherwise fail at the first verification with
193
+ // "take is not a function" — during a login, far from the cause — so it
194
+ // is refused here, where the fix is obvious.
195
+ const store = config.store;
196
+ if (store !== undefined && typeof store.take !== "function") {
197
+ throw new WardenError(
198
+ "E_WARDEN_OTP_STORE_CONTRACT",
199
+ "The OTP challenge store does not implement take().",
200
+ {
201
+ hint: "take(id) must remove the challenge AND return it in ONE indivisible operation — `DELETE ... RETURNING` on SQL, GETDEL or a Lua script on Redis. Reading then deleting separately lets two requests with the same correct code both succeed.",
202
+ },
203
+ );
204
+ }
91
205
  if (!config?.channel) {
92
206
  throw new WardenError(
93
207
  "INVALID_CONFIG",
@@ -144,7 +258,16 @@ export class OtpProvider {
144
258
  expiresAt,
145
259
  attempts: 0,
146
260
  });
147
- await this.#channel.send(recipient, code);
261
+ // Saved BEFORE the send, so a code that arrives can always be verified —
262
+ // but a send that fails must not leave the challenge behind. It could
263
+ // never be used (nobody has the code) and never be swept before its TTL,
264
+ // so an SMS gateway having a bad hour quietly filled the store.
265
+ try {
266
+ await this.#channel.send(recipient, code);
267
+ } catch (error) {
268
+ await this.#store.delete(id);
269
+ throw error;
270
+ }
148
271
  return { challengeId: id, expiresAt };
149
272
  }
150
273
 
@@ -157,23 +280,27 @@ export class OtpProvider {
157
280
  code: string,
158
281
  nowMs: number = Date.now(),
159
282
  ): Promise<OtpVerification> {
160
- const challenge = await this.#store.find(challengeId);
283
+ // TAKE, do not read. The challenge leaves the store before anything is
284
+ // compared, so a second request racing this one finds nothing and is
285
+ // refused — whatever the outcome here. Every path below either keeps it
286
+ // removed or puts it back deliberately.
287
+ const challenge = await this.#store.take(challengeId);
161
288
  if (!challenge) {
162
289
  return { ok: false, reason: "not_found" };
163
290
  }
164
291
  if (nowMs > challenge.expiresAt) {
165
- await this.#store.delete(challengeId);
166
292
  return { ok: false, reason: "expired" };
167
293
  }
168
294
  if (matchesStored(challenge.hash, code.replace(/\s/g, ""))) {
169
- await this.#store.delete(challengeId);
170
295
  return { ok: true };
171
296
  }
172
297
  const attempts = challenge.attempts + 1;
173
298
  if (attempts >= this.#maxAttempts) {
174
- await this.#store.delete(challengeId);
175
299
  return { ok: false, reason: "too_many_attempts" };
176
300
  }
301
+ // Wrong, but budget remains: put it back with the attempt recorded.
302
+ // Holding it for the length of the comparison is also what makes the
303
+ // counter reliable — no two callers can be incrementing the same value.
177
304
  await this.#store.save({ ...challenge, attempts });
178
305
  return { ok: false, reason: "mismatch" };
179
306
  }