@c9up/warden 0.1.27 → 0.2.1

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.
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Duration parsing for token lifetimes.
3
+ *
4
+ * Upstream's `expiresIn` takes either a number of seconds or a human string
5
+ * (`'1h'`, `'7 days'`), and a config copied from an Adonis app carries the
6
+ * string form. Accepting only the number meant such a config was rejected for
7
+ * a reason that had nothing to do with authentication.
8
+ *
9
+ * The unit table is the one `@c9up/echo` parses its TTLs with, transcribed
10
+ * rather than imported: every package here installs on its own, so a shared
11
+ * helper would be a dependency edge bought for forty lines. Transcribed, not
12
+ * reinvented — two packages that disagreed on what `'1d'` means would be worse
13
+ * than either one being wrong alone.
14
+ */
15
+
16
+ const UNIT_SECONDS: Record<string, number> = {
17
+ ms: 1 / 1000,
18
+ msec: 1 / 1000,
19
+ msecs: 1 / 1000,
20
+ millisecond: 1 / 1000,
21
+ milliseconds: 1 / 1000,
22
+ s: 1,
23
+ sec: 1,
24
+ secs: 1,
25
+ second: 1,
26
+ seconds: 1,
27
+ m: 60,
28
+ min: 60,
29
+ mins: 60,
30
+ minute: 60,
31
+ minutes: 60,
32
+ h: 3600,
33
+ hr: 3600,
34
+ hrs: 3600,
35
+ hour: 3600,
36
+ hours: 3600,
37
+ d: 86_400,
38
+ day: 86_400,
39
+ days: 86_400,
40
+ w: 604_800,
41
+ week: 604_800,
42
+ weeks: 604_800,
43
+ };
44
+
45
+ const DURATION_RE = /^\s*(\d+(?:\.\d+)?)\s*([a-z]+)?\s*$/i;
46
+
47
+ /**
48
+ * A token lifetime: seconds as a number, or a human duration string.
49
+ *
50
+ * A bare number is SECONDS, not milliseconds — that is what `expiresInSeconds`
51
+ * has always meant here, and a silent change of unit is the kind of thing
52
+ * nobody notices until tokens live a thousand times too long.
53
+ */
54
+ export type TokenDuration = number | string;
55
+
56
+ /**
57
+ * Parse a human duration into seconds.
58
+ *
59
+ * Rejects rather than guesses: a lifetime that silently reads as zero, or as
60
+ * the wrong unit, is an authentication bug that surfaces as "users are
61
+ * randomly logged out" weeks later.
62
+ */
63
+ export function parseDurationSeconds(value: string): number {
64
+ const match = DURATION_RE.exec(value);
65
+ if (!match) {
66
+ throw new TypeError(`Warden: invalid duration "${value}"`);
67
+ }
68
+ const amount = Number(match[1]);
69
+ const unit = match[2]?.toLowerCase();
70
+ if (unit === undefined) return amount;
71
+ const factor = UNIT_SECONDS[unit];
72
+ if (factor === undefined) {
73
+ throw new TypeError(
74
+ `Warden: unknown duration unit "${unit}" in "${value}"`,
75
+ );
76
+ }
77
+ return amount * factor;
78
+ }
79
+
80
+ /**
81
+ * Resolve a lifetime to seconds.
82
+ *
83
+ * `expiresIn` is upstream's spelling and wins when both are given; a config
84
+ * that sets the two disagrees with itself, and the portable name is the one to
85
+ * honour.
86
+ */
87
+ export function resolveExpiresInSeconds(
88
+ expiresIn: TokenDuration | undefined,
89
+ expiresInSeconds: number | undefined,
90
+ fallbackSeconds: number,
91
+ ): number {
92
+ const chosen = expiresIn ?? expiresInSeconds ?? fallbackSeconds;
93
+ const seconds =
94
+ typeof chosen === "number" ? chosen : parseDurationSeconds(chosen);
95
+ if (!Number.isFinite(seconds) || seconds <= 0) {
96
+ throw new TypeError(
97
+ `Warden: token lifetime must be a positive duration, got ${JSON.stringify(chosen)}`,
98
+ );
99
+ }
100
+ return seconds;
101
+ }
package/src/index.ts CHANGED
@@ -56,6 +56,8 @@ export {
56
56
  sessionGuard,
57
57
  } from "./config.js";
58
58
  export { configure } from "./configure.js";
59
+ export type { TokenDuration } from "./duration.js";
60
+ export { parseDurationSeconds } from "./duration.js";
59
61
  export {
60
62
  E_INVALID_CREDENTIALS,
61
63
  E_UNAUTHORIZED_ACCESS,
@@ -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
  }