@owlmeans/server-auth-otp 0.1.19-rc.0 → 0.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,7 +12,7 @@ types the service, and on this package only where the server wires itself up.
12
12
  ## Installation
13
13
 
14
14
  ```bash
15
- bun add @owlmeans/server-auth-otp@^0.1.19-rc.0
15
+ bun add @owlmeans/server-auth-otp@^0.1.19
16
16
  ```
17
17
 
18
18
  ## Concepts
@@ -20,9 +20,17 @@ bun add @owlmeans/server-auth-otp@^0.1.19-rc.0
20
20
  - **Issuance** — `issueChallenge(email)` creates a random 6-digit code (`OTP_CODE_LENGTH`), stores it
21
21
  for `OTP_TTL_SECONDS` (600 s) under an opaque issuance id, mails it and returns the id. The id
22
22
  never contains the address or the code.
23
+ - **Message** — `issueChallenge(email, { message })` mails an `OtpMessage` instead of the default
24
+ English mail: `{{code}}` and `{{minutes}}` are substituted in its `subject`, `text` and `html`.
25
+ Without `message` the default mail is sent byte for byte as before.
23
26
  - **Challenge store** — `OtpChallengeStore`, keyed by digests from `otpKeyHelper`. `verify`
24
27
  compares, counts failures and consumes in one operation; after `OTP_MAX_FAILED_ATTEMPTS` (5) the
25
- issuance is exhausted.
28
+ issuance is exhausted. The optional `rewrite(id, emailKey, codeHash)` (memory and Redis stores
29
+ implement it; Redis in one Lua call) replaces the code of a live challenge of the same address,
30
+ resets its failed attempts and keeps its remaining TTL.
31
+ - **Rewrite seam** — `rewriteChallenge(email, issuanceId, code)` is a developer seam for test
32
+ tooling: `false` when the code is not `OTP_CODE_LENGTH` digits, the store cannot rewrite, or the
33
+ issuance is gone or belongs to another address. Expose it only behind a developer-only guard.
26
34
  - **Throttle** — `AuthThrottleService.consume(key, rules, token?)` applies every `ThrottleRule`
27
35
  (`{ limit, windowSeconds }`) together. Enabled only when `cfg.otp.throttleAlias` and
28
36
  `cfg.otp.throttleRules` are both set.
@@ -96,9 +104,9 @@ here). The memory factories accept a clock as their second argument for determin
96
104
 
97
105
  | Symbol | Purpose |
98
106
  |---|---|
99
- | `makeOtpService(alias = OTP_SERVICE)` | `OtpService`: `issueChallenge(email) → issuanceId`, `verifyChallenge(email, issuanceId, code)` |
107
+ | `makeOtpService(alias = OTP_SERVICE)` | `OtpService`: `issueChallenge(email, { message? }) → issuanceId`, `verifyChallenge(email, issuanceId, code)`, `rewriteChallenge(email, issuanceId, code) → boolean` |
100
108
  | `appendOtpPlugin(context)` | registers the `'email-otp'` plugin factory; returns the context |
101
- | `makeRedisOtpChallengeStore(alias?, resourceAlias?)` | atomic Redis store (`SET NX EX` + one Lua verify) |
109
+ | `makeRedisOtpChallengeStore(alias?, resourceAlias?)` | atomic Redis store (`SET NX EX` + one Lua verify, one Lua rewrite) |
102
110
  | `makeMemoryOtpChallengeStore(alias?, now?)` | in-memory store for a single process or tests |
103
111
  | `makeRedisThrottleService(alias?, resourceAlias?)` | every window checked and consumed in one Lua call |
104
112
  | `makeMemoryThrottleService(alias?, now?)` | in-memory sliding-window throttle |
@@ -179,7 +187,7 @@ This package ships embedded agent skills under `agent-meta/`. After installing y
179
187
  your project's skill store (`.agents/skills/`):
180
188
 
181
189
  ```sh
182
- npx @owlmeans/agent-skills@^0.1.19-rc.0
190
+ npx @owlmeans/agent-skills@^0.1.19
183
191
  ```
184
192
 
185
193
  The embedded files are version-matched to this package release. Do not edit them
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "schemaVersion": 3,
3
3
  "package": "@owlmeans/server-auth-otp",
4
- "version": "0.1.19-rc.0",
5
- "generatedAt": "2026-10-31T12:13:02.377Z",
4
+ "version": "0.1.19",
5
+ "generatedAt": "2026-11-01T22:22:22.300Z",
6
6
  "canonicalRepo": "https://github.com/owlmeans/common",
7
7
  "entries": [
8
8
  {
@@ -8,17 +8,19 @@ metadata:
8
8
 
9
9
  # Using `@owlmeans/server-auth-otp`
10
10
 
11
- **Install:** `"@owlmeans/server-auth-otp": "^0.1.19-rc.0"` in `dependencies`
11
+ **Install:** `"@owlmeans/server-auth-otp": "^0.1.19"` in `dependencies`
12
12
 
13
13
  Email OTP authentication plugin for the OwlMeans auth-manager plugin system. Relies on `@owlmeans/auth-otp` for the OTP service interface, a Redis resource for code storage, and a `MailerService` to send codes.
14
14
 
15
15
  ## `@owlmeans/auth-otp` — the contracts
16
16
 
17
17
  `@owlmeans/auth-otp` has no skill of its own because it is the contracts half of this pair. Its
18
- `OtpService` issues an opaque issuance id, persists and mails a code, and verifies that exact
19
- issuance; it also owns `OTP_SERVICE`, `OTP_AUTH_TYPE` (`'email-otp'`), `OTP_RESOURCE`,
20
- `OTP_TTL_SECONDS` (600), `OTP_CODE_LENGTH` (6), and the five-attempt policy. The server package
21
- provides the challenge stores, throttles, mailer integration and plugin.
18
+ `OtpService` issues an opaque issuance id, persists and mails a code
19
+ (`issueChallenge(email, { message? })`), verifies that exact issuance, and may rewrite a pending
20
+ code (`rewriteChallenge?`, below); it also owns `OtpMessage` / `OtpIssueOptions`, `OTP_SERVICE`,
21
+ `OTP_AUTH_TYPE` (`'email-otp'`), `OTP_RESOURCE`, `OTP_TTL_SECONDS` (600), `OTP_CODE_LENGTH` (6), and
22
+ the five-attempt policy. The server package provides the challenge stores, throttles, mailer
23
+ integration and plugin.
22
24
 
23
25
  Depend on it from a shared package that must name the auth type or type the service, and depend on
24
26
  `@owlmeans/server-auth-otp` only where the server wires itself up — the same producer/consumer split
@@ -29,7 +31,9 @@ the contracts package, never to the implementation.
29
31
 
30
32
  | Symbol | Kind | Purpose |
31
33
  |--------|------|---------|
32
- | `makeOtpService(alias?)` | fn | Service factory — stores/verifies OTP codes |
34
+ | `makeOtpService(alias?)` | fn | Service factory — `issueChallenge(email, { message? })`, `verifyChallenge(email, issuanceId, code)`, `rewriteChallenge(email, issuanceId, code) → boolean` |
35
+ | `makeRedisOtpChallengeStore(alias?, resourceAlias?)`, `makeMemoryOtpChallengeStore(alias?, now?)` | fn | Challenge stores: `SET NX EX` + one Lua verify and one Lua rewrite; the memory one for a single process or tests |
36
+ | `makeRedisThrottleService(alias?, resourceAlias?)`, `makeMemoryThrottleService(alias?, now?)` | fn | `AuthThrottleService.consume(key, rules, token?)` — every window in one call |
33
37
  | `appendOtpPlugin(context)` | fn | Registers the OTP `AuthPlugin` into the server-auth plugin registry |
34
38
  | `OTP_SERVICE` | const | `'auth-otp-service'` — the service alias `makeOtpService` registers under |
35
39
  | `OTP_AUTH_TYPE` | const | `'email-otp'` — the auth type string to pass in `init` requests |
@@ -91,12 +95,34 @@ Pass `ctx.cfg.otp` to override defaults:
91
95
 
92
96
  ```ts
93
97
  cfg.otp = {
94
- mailerAlias: 'my-mailer', // default: MAILER_SERVICE ('mailer-service')
95
- resourceAlias: 'my-otp-cache', // default: OTP_RESOURCE ('auth-otp-cache')
96
- identityAlias: 'my-identity', // default: AUTH_IDENTITY_LINKING
98
+ mailerAlias: 'my-mailer', // default: MAILER_SERVICE ('mailer-service')
99
+ resourceAlias: 'my-otp-cache', // default: OTP_RESOURCE ('auth-otp-cache')
100
+ challengeStoreAlias: 'my-challenges', // default: OTP_CHALLENGE_STORE
101
+ throttleAlias: 'my-throttle', // issuance throttle — only together with throttleRules
102
+ throttleRules: OTP_EMAIL_THROTTLE_RULES,
103
+ identityAlias: 'my-identity', // default: AUTH_IDENTITY_LINKING
97
104
  }
98
105
  ```
99
106
 
107
+ A consumer that throttles every route on its own keys (`server-auth-email`) leaves
108
+ `throttleRules` unset: the service's issuance throttle cannot be waived and would double-count.
109
+
110
+ ## The message seam
111
+
112
+ `issueChallenge(email, { message })` mails an `OtpMessage` (`subject`, `text`, `html` templates;
113
+ `{{code}}` and `{{minutes}}` are substituted in all three) instead of the default English mail —
114
+ a localized or purpose-specific mail. Without `message` the default mail is sent unchanged.
115
+ **Never put `{{code}}` in a subject**: the console mailer logs subjects, and a lock screen shows them.
116
+
117
+ ## The rewrite seam (developer tooling)
118
+
119
+ `rewriteChallenge(email, issuanceId, code)` replaces the code of a LIVE issuance of that address —
120
+ remaining TTL kept, failed attempts reset — so an end-to-end run can sign in without reading a
121
+ mailbox. It answers `false` when the code is not `OTP_CODE_LENGTH` digits, the store has no
122
+ `rewrite` (`OtpChallengeStore.rewrite?`; memory and Redis implement it), or the issuance is gone or
123
+ names another address. Expose it only behind a developer-only, signed and allow-listed route
124
+ (`server-auth-email`'s `tech.pin`), never to the public.
125
+
100
126
  ## Rules
101
127
 
102
128
  - Always register the Redis challenge store, Redis throttle service, and mailer service BEFORE the
@@ -137,7 +163,9 @@ cfg.otp = {
137
163
  - **The resulting auth token can exceed 1024 characters** — it wraps the full `AuthCredentials`
138
164
  envelope, including the original allowance challenge, base64-encoded. A consumer route that
139
165
  accepts this token (e.g. an OIDC `PROVIDER_INTERACTION` finalizer) must size its own `token`
140
- field schema accordingly; the generic `AuthTokenSchema` (`maxLength: 1024`) is too small.
166
+ field schema accordingly; the generic `AuthTokenSchema` (`maxLength: 1024`) is too small. A
167
+ plugin whose token must pass a bearer exchange returns a short digest of its challenge as `token`
168
+ instead (`server-auth` → Rules; `server-auth-email` does).
141
169
 
142
170
  ## Related
143
171
 
@@ -1 +1 @@
1
- {"version":3,"file":"challenge.d.ts","sourceRoot":"","sources":["../src/challenge.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,iBAAiB,EAAyB,MAAM,YAAY,CAAA;AAE1E,OAAO,KAAK,EAA2B,KAAK,EAAmB,MAAM,kBAAkB,CAAA;AAGvF,gFAAgF;AAChF,eAAO,MAAM,2BAA2B,yBACJ,KAAK,KACtC,iBA+BF,CAAA;AAED,oGAAoG;AACpG,eAAO,MAAM,0BAA0B,8CAEpC,iBAqCF,CAAA"}
1
+ {"version":3,"file":"challenge.d.ts","sourceRoot":"","sources":["../src/challenge.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,iBAAiB,EAAyB,MAAM,YAAY,CAAA;AAE1E,OAAO,KAAK,EAA2B,KAAK,EAAmB,MAAM,kBAAkB,CAAA;AAGvF,gFAAgF;AAChF,eAAO,MAAM,2BAA2B,yBACJ,KAAK,KACtC,iBA2CF,CAAA;AAED,oGAAoG;AACpG,eAAO,MAAM,0BAA0B,8CAEpC,iBAkDF,CAAA"}
@@ -1,7 +1,7 @@
1
1
  import { appendContextual, createService } from '@owlmeans/context';
2
2
  import { OtpUnavailable } from './errors.js';
3
3
  import { OTP_CHALLENGE_STORE, OTP_RESOURCE, OtpChallengeOutcome as Outcome } from './consts.js';
4
- import { REDIS_VERIFY_SCRIPT } from './consts.local.js';
4
+ import { REDIS_REWRITE_SCRIPT, REDIS_VERIFY_SCRIPT } from './consts.local.js';
5
5
  /** Real in-memory challenge store with synchronous consume/update semantics. */
6
6
  export const makeMemoryOtpChallengeStore = (alias = OTP_CHALLENGE_STORE, now = Date.now) => {
7
7
  const records = new Map();
@@ -32,6 +32,18 @@ export const makeMemoryOtpChallengeStore = (alias = OTP_CHALLENGE_STORE, now = D
32
32
  }
33
33
  return Outcome.Invalid;
34
34
  },
35
+ rewrite: async (id, emailKey, codeHash) => {
36
+ const record = records.get(id);
37
+ if (record == null || record.expiresAt <= now()) {
38
+ records.delete(id);
39
+ return false;
40
+ }
41
+ if (record.emailKey !== emailKey)
42
+ return false;
43
+ record.codeHash = codeHash;
44
+ record.failedAttempts = 0;
45
+ return true;
46
+ },
35
47
  });
36
48
  };
37
49
  /** Redis challenge store: compare, attempt increment, exhaustion, and consume are one operation. */
@@ -71,6 +83,19 @@ export const makeRedisOtpChallengeStore = (alias = OTP_CHALLENGE_STORE, resource
71
83
  throw unavailable;
72
84
  }
73
85
  },
86
+ rewrite: async (id, emailKey, codeHash) => {
87
+ const ctx = service.ctx;
88
+ const resource = ctx.resource(resourceAlias);
89
+ try {
90
+ return Number(await resource.db.client.eval(REDIS_REWRITE_SCRIPT, 1, resource.key(id), emailKey, codeHash)) === 1;
91
+ }
92
+ catch (error) {
93
+ const unavailable = new OtpUnavailable('challenge');
94
+ if (error instanceof Error)
95
+ unavailable.oiriginalStack = `${error}: ${error.stack}`;
96
+ throw unavailable;
97
+ }
98
+ },
74
99
  });
75
100
  return service;
76
101
  };
@@ -1 +1 @@
1
- {"version":3,"file":"challenge.js","sourceRoot":"","sources":["../src/challenge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AAEnE,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAC5C,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAA4B,mBAAmB,IAAI,OAAO,EAAE,MAAM,aAAa,CAAA;AAEzH,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAA;AAIvD,gFAAgF;AAChF,MAAM,CAAC,MAAM,2BAA2B,GAAG,CACzC,KAAK,GAAG,mBAAmB,EAAE,GAAG,GAAU,IAAI,CAAC,GAAG,EAC/B,EAAE;IACrB,MAAM,OAAO,GAAG,IAAI,GAAG,EAA2B,CAAA;IAElD,OAAO,aAAa,CAAoB,KAAK,EAAE;QAC7C,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,UAAU,EAAoB,EAAE;YACvD,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC,CAAA;YACzC,IAAI,OAAO,IAAI,IAAI,IAAI,OAAO,CAAC,SAAS,GAAG,GAAG,EAAE;gBAAE,OAAO,KAAK,CAAA;YAC9D,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,EAAE;gBACxB,GAAG,SAAS,EAAE,cAAc,EAAE,CAAC,EAAE,SAAS,EAAE,GAAG,EAAE,GAAG,UAAU,GAAG,IAAI;aACtE,CAAC,CAAA;YACF,OAAO,IAAI,CAAA;QACb,CAAC;QACD,MAAM,EAAE,KAAK,EAAE,EAAE,EAAE,QAAQ,EAAE,QAAQ,EAAE,iBAAiB,EAAgC,EAAE;YACxF,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;YAC9B,IAAI,MAAM,IA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AAG,GAAG,KAAK,KAAK,KAAK,CAAC,KAAK,EAAE,CAAA;gBACnF,MAAM,WAAW,CAAA;YACnB,CAAC;QACH,CAAC;KACF,CAAC,CAAA;IAEF,OAAO,OAAO,CAAA;AAChB,CAAC,CAAA"}
@@ -1,4 +1,11 @@
1
1
  export declare const REDIS_VERIFY_SCRIPT = "\nlocal raw = redis.call('GET', KEYS[1])\nif not raw then return 0 end\nlocal record = cjson.decode(raw)\nif record.emailKey == ARGV[1] and record.codeHash == ARGV[2] then\n redis.call('DEL', KEYS[1])\n return 1\nend\nrecord.failedAttempts = tonumber(record.failedAttempts or 0) + 1\nif record.failedAttempts >= tonumber(ARGV[3]) then\n redis.call('DEL', KEYS[1])\n return -2\nend\nlocal ttl = redis.call('PTTL', KEYS[1])\nif ttl <= 0 then\n redis.call('DEL', KEYS[1])\n return 0\nend\nredis.call('SET', KEYS[1], cjson.encode(record), 'XX', 'PX', ttl)\nreturn -1\n";
2
+ /** Rewrite a live challenge of the same address: new code hash, attempts reset, remaining TTL kept. */
3
+ export declare const REDIS_REWRITE_SCRIPT = "\nlocal raw = redis.call('GET', KEYS[1])\nif not raw then return 0 end\nlocal record = cjson.decode(raw)\nif record.emailKey ~= ARGV[1] then return 0 end\nlocal ttl = redis.call('PTTL', KEYS[1])\nif ttl <= 0 then\n redis.call('DEL', KEYS[1])\n return 0\nend\nrecord.codeHash = ARGV[2]\nrecord.failedAttempts = 0\nredis.call('SET', KEYS[1], cjson.encode(record), 'XX', 'PX', ttl)\nreturn 1\n";
4
+ /** The placeholders an `OtpMessage` template may carry. */
5
+ export declare const OTP_MESSAGE_CODE = "{{code}}";
6
+ export declare const OTP_MESSAGE_MINUTES = "{{minutes}}";
7
+ /** The only shape a rewritten code may take: exactly `OTP_CODE_LENGTH` digits. */
8
+ export declare const OTP_CODE_PATTERN: RegExp;
2
9
  export declare const CHALLENGE_DELIMITER = "::";
3
10
  export declare const REDIS_THROTTLE_SCRIPT = "\nlocal time = redis.call('TIME')\nlocal now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)\nlocal retry = 0\nfor index = 1, #KEYS do\n local offset = (index - 1) * 2\n local limit = tonumber(ARGV[offset + 1])\n local window = tonumber(ARGV[offset + 2])\n redis.call('ZREMRANGEBYSCORE', KEYS[index], '-inf', now - window)\n local count = redis.call('ZCARD', KEYS[index])\n if count >= limit then\n local oldest = redis.call('ZRANGE', KEYS[index], 0, 0, 'WITHSCORES')\n if #oldest == 2 then\n retry = math.max(retry, math.ceil((tonumber(oldest[2]) + window - now) / 1000))\n end\n end\nend\nif retry > 0 then return {0, retry} end\nlocal token = ARGV[#KEYS * 2 + 1]\nfor index = 1, #KEYS do\n local window = tonumber(ARGV[(index - 1) * 2 + 2])\n redis.call('ZADD', KEYS[index], now, token .. ':' .. index)\n redis.call('PEXPIRE', KEYS[index], window)\nend\nreturn {1, 0}\n";
4
11
  //# sourceMappingURL=consts.local.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"consts.local.d.ts","sourceRoot":"","sources":["../src/consts.local.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,mBAAmB,+jBAoB/B,CAAA;AAGD,eAAO,MAAM,mBAAmB,OAAO,CAAA;AAEvC,eAAO,MAAM,qBAAqB,u5BAyBjC,CAAA"}
1
+ {"version":3,"file":"consts.local.d.ts","sourceRoot":"","sources":["../src/consts.local.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,mBAAmB,+jBAoB/B,CAAA;AAED,uGAAuG;AACvG,eAAO,MAAM,oBAAoB,6YAchC,CAAA;AAED,2DAA2D;AAC3D,eAAO,MAAM,gBAAgB,aAAa,CAAA;AAC1C,eAAO,MAAM,mBAAmB,gBAAgB,CAAA;AAEhD,kFAAkF;AAClF,eAAO,MAAM,gBAAgB,QAA0C,CAAA;AAGvE,eAAO,MAAM,mBAAmB,OAAO,CAAA;AAEvC,eAAO,MAAM,qBAAqB,u5BAyBjC,CAAA"}
@@ -1,3 +1,4 @@
1
+ import { OTP_CODE_LENGTH } from '@owlmeans/auth-otp';
1
2
  export const REDIS_VERIFY_SCRIPT = `
2
3
  local raw = redis.call('GET', KEYS[1])
3
4
  if not raw then return 0 end
@@ -19,6 +20,27 @@ end
19
20
  redis.call('SET', KEYS[1], cjson.encode(record), 'XX', 'PX', ttl)
20
21
  return -1
21
22
  `;
23
+ /** Rewrite a live challenge of the same address: new code hash, attempts reset, remaining TTL kept. */
24
+ export const REDIS_REWRITE_SCRIPT = `
25
+ local raw = redis.call('GET', KEYS[1])
26
+ if not raw then return 0 end
27
+ local record = cjson.decode(raw)
28
+ if record.emailKey ~= ARGV[1] then return 0 end
29
+ local ttl = redis.call('PTTL', KEYS[1])
30
+ if ttl <= 0 then
31
+ redis.call('DEL', KEYS[1])
32
+ return 0
33
+ end
34
+ record.codeHash = ARGV[2]
35
+ record.failedAttempts = 0
36
+ redis.call('SET', KEYS[1], cjson.encode(record), 'XX', 'PX', ttl)
37
+ return 1
38
+ `;
39
+ /** The placeholders an `OtpMessage` template may carry. */
40
+ export const OTP_MESSAGE_CODE = '{{code}}';
41
+ export const OTP_MESSAGE_MINUTES = '{{minutes}}';
42
+ /** The only shape a rewritten code may take: exactly `OTP_CODE_LENGTH` digits. */
43
+ export const OTP_CODE_PATTERN = new RegExp(`^\\d{${OTP_CODE_LENGTH}}$`);
22
44
  // Separates the email from the opaque issuance id inside the signed challenge.
23
45
  export const CHALLENGE_DELIMITER = '::';
24
46
  export const REDIS_THROTTLE_SCRIPT = `
@@ -1 +1 @@
1
- {"version":3,"file":"consts.local.js","sourceRoot":"","sources":["../src/consts.local.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,mBAAmB,GAAG;;;;;;;;;;;;;;;;;;;;CAoBlC,CAAA;AAED,+EAA+E;AAC/E,MAAM,CAAC,MAAM,mBAAmB,GAAG,IAAI,CAAA;AAEvC,MAAM,CAAC,MAAM,qBAAqB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;CAyBpC,CAAA"}
1
+ {"version":3,"file":"consts.local.js","sourceRoot":"","sources":["../src/consts.local.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AAEpD,MAAM,CAAC,MAAM,mBAAmB,GAAG;;;;;;;;;;;;;;;;;;;;CAoBlC,CAAA;AAED,uGAAuG;AACvG,MAAM,CAAC,MAAM,oBAAoB,GAAG;;;;;;;;;;;;;;CAcnC,CAAA;AAED,2DAA2D;AAC3D,MAAM,CAAC,MAAM,gBAAgB,GAAG,UAAU,CAAA;AAC1C,MAAM,CAAC,MAAM,mBAAmB,GAAG,aAAa,CAAA;AAEhD,kFAAkF;AAClF,MAAM,CAAC,MAAM,gBAAgB,GAAG,IAAI,MAAM,CAAC,QAAQ,eAAe,IAAI,CAAC,CAAA;AAEvE,+EAA+E;AAC/E,MAAM,CAAC,MAAM,mBAAmB,GAAG,IAAI,CAAA;AAEvC,MAAM,CAAC,MAAM,qBAAqB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;CAyBpC,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,UAAU,EAAwF,MAAM,oBAAoB,CAAA;AAqB1I,eAAO,MAAM,cAAc,sBAA0B,UA0EpD,CAAA"}
1
+ {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":"AAEA,OAAO,EACkC,KAAK,UAAU,EAEvD,MAAM,oBAAoB,CAAA;AA+B3B,eAAO,MAAM,cAAc,sBAA0B,UAmGpD,CAAA"}
package/build/service.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { appendContextual } from '@owlmeans/context';
2
2
  import { AuthenFailed } from '@owlmeans/auth';
3
- import { OTP_SERVICE, OTP_TTL_SECONDS, OTP_CODE_LENGTH, OTP_MAX_FAILED_ATTEMPTS, OTP_RESOURCE } from '@owlmeans/auth-otp';
3
+ import { OTP_SERVICE, OTP_TTL_SECONDS, OTP_CODE_LENGTH, OTP_MAX_FAILED_ATTEMPTS, OTP_RESOURCE, } from '@owlmeans/auth-otp';
4
4
  import { MAILER_SERVICE } from '@owlmeans/mailer';
5
5
  import { randomBytes, randomInt } from 'node:crypto';
6
6
  import { OtpChallengeOutcome, OTP_CHALLENGE_STORE } from './consts.js';
@@ -8,6 +8,7 @@ import { throttleKeyHelper } from './throttle-keys.js';
8
8
  import { otpKeyHelper } from './keys.js';
9
9
  import { OtpThrottled, OtpUnavailable } from './errors.js';
10
10
  import { makeRedisOtpChallengeStore } from './challenge.js';
11
+ import { OTP_CODE_PATTERN, OTP_MESSAGE_CODE, OTP_MESSAGE_MINUTES } from './consts.local.js';
11
12
  import { logger, logThrottle } from '@owlmeans/log';
12
13
  const log = logger('server-auth-otp');
13
14
  /** An e-mail as a log may carry it: its domain only. */
@@ -16,6 +17,13 @@ const generateCode = () => {
16
17
  const digits = randomInt(0, Math.pow(10, OTP_CODE_LENGTH));
17
18
  return String(digits).padStart(OTP_CODE_LENGTH, '0');
18
19
  };
20
+ /** An application's login-code mail with its placeholders filled in. */
21
+ const renderMessage = (message, code) => {
22
+ const fill = (template) => template
23
+ .replaceAll(OTP_MESSAGE_CODE, code)
24
+ .replaceAll(OTP_MESSAGE_MINUTES, String(OTP_TTL_SECONDS / 60));
25
+ return { subject: fill(message.subject), text: fill(message.text), html: fill(message.html) };
26
+ };
19
27
  export const makeOtpService = (alias = OTP_SERVICE) => {
20
28
  let fallbackChallenges;
21
29
  const challengeStore = (ctx) => {
@@ -31,7 +39,7 @@ export const makeOtpService = (alias = OTP_SERVICE) => {
31
39
  return fallbackChallenges;
32
40
  };
33
41
  const service = appendContextual(alias, {
34
- issueChallenge: async (email) => {
42
+ issueChallenge: async (email, opts) => {
35
43
  const ctx = service.ctx;
36
44
  const mailerAlias = ctx.cfg.otp?.mailerAlias ?? MAILER_SERVICE;
37
45
  const challenges = challengeStore(ctx);
@@ -59,12 +67,17 @@ export const makeOtpService = (alias = OTP_SERVICE) => {
59
67
  }, OTP_TTL_SECONDS);
60
68
  if (!issued)
61
69
  throw new OtpUnavailable('issuance-collision');
62
- await mailer.send({
63
- to: email,
64
- subject: 'Your login code',
65
- text: `Your one-time login code is: ${code}\n\nIt expires in ${OTP_TTL_SECONDS / 60} minutes.`,
66
- html: `<p>Your one-time login code is: <strong>${code}</strong></p><p>It expires in ${OTP_TTL_SECONDS / 60} minutes.</p>`,
67
- });
70
+ if (opts?.message != null) {
71
+ await mailer.send({ to: email, ...renderMessage(opts.message, code) });
72
+ }
73
+ else {
74
+ await mailer.send({
75
+ to: email,
76
+ subject: 'Your login code',
77
+ text: `Your one-time login code is: ${code}\n\nIt expires in ${OTP_TTL_SECONDS / 60} minutes.`,
78
+ html: `<p>Your one-time login code is: <strong>${code}</strong></p><p>It expires in ${OTP_TTL_SECONDS / 60} minutes.</p>`,
79
+ });
80
+ }
68
81
  return issuanceId;
69
82
  },
70
83
  verifyChallenge: async (email, issuanceId, code) => {
@@ -76,6 +89,24 @@ export const makeOtpService = (alias = OTP_SERVICE) => {
76
89
  throw new AuthenFailed('otp:code');
77
90
  }
78
91
  },
92
+ rewriteChallenge: async (email, issuanceId, code) => {
93
+ const ctx = service.ctx;
94
+ const challenges = challengeStore(ctx);
95
+ if (!OTP_CODE_PATTERN.test(code) || challenges.rewrite == null) {
96
+ log.debug('OTP challenge rewrite refused', {
97
+ reason: challenges.rewrite == null ? 'unsupported' : 'code-shape', emailDomain: domainOf(email),
98
+ });
99
+ return false;
100
+ }
101
+ const rewritten = await challenges.rewrite(otpKeyHelper.otpChallengeKey(issuanceId), otpKeyHelper.otpEmailKey(email), otpKeyHelper.otpCodeHash(issuanceId, code));
102
+ if (rewritten) {
103
+ log.info('Login code rewritten', { emailDomain: domainOf(email) }, { event: 'auth.otp-rewritten' });
104
+ }
105
+ else {
106
+ log.debug('OTP challenge rewrite refused', { reason: 'missing', emailDomain: domainOf(email) });
107
+ }
108
+ return rewritten;
109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,MAAM,UAAU,GAAG,cAAc,CAAC,GAAG,CAAC,CAAA;YACtC,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,OAAO,IAAI,IAAI,EAAE,CAAC;gBAC/D,GAAG,CAAC,KAAK,CAAC,+BAA+B,EAAE;oBACzC,MAAM,EAAE,UAAU,CAAC,OAAO,IAAI,IAAI,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,YAAY,EAAE,WAAW,EAAE,QAAQ,CAAC,KAAK,CAAC;iBAChG,CAAC,CAAA;gBACF,OAAO,KAAK,CAAA;YACd,CAAC;YACD,MAAM,SAAS,GAAG,MAAM,UAAU,CAAC,OAAO,CACxC,YAAY,CAAC,eAAe,CAAC,UAAU,CAAC,EAAE,YAAY,CAAC,WAAW,CAAC,KAAK,CAAC,EAAE,YAAY,CAAC,WAAW,CAAC,UAAU,EAAE,IAAI,CAAC,CACtH,CAAA;YACD,IAAI,SAAS,EAAE,CAAC;gBACd,GAAG,CAAC,IAAI,CAAC,sBAAsB,EAAE,EAAE,WAAW,EAAE,QAAQ,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,oBAAoB,EAAE,CAAC,CAAA;YACrG,CAAC;iBAAM,CAAC;gBACN,GAAG,CAAC,KAAK,CAAC,+BAA+B,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,WAAW,EAAE,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;YACjG,CAAC;YAED,OAAO,SAAS,CAAA;QAClB,CAAC;KACF,CAAC,CAAA;IAEF,OAAO,OAAO,CAAA;AAChB,CAAC,CAAA"}
package/build/types.d.ts CHANGED
@@ -21,6 +21,11 @@ export interface OtpChallenge {
21
21
  export interface OtpChallengeStore extends InitializedService {
22
22
  issue: (challenge: OtpChallenge, ttlSeconds: number) => Promise<boolean>;
23
23
  verify: (id: string, emailKey: string, codeHash: string, maxFailedAttempts: number) => Promise<OtpChallengeOutcome>;
24
+ /**
25
+ * Replace the code of a live challenge whose address matches, resetting its failed attempts and
26
+ * keeping its expiry. `false` when the challenge is gone or names another address.
27
+ */
28
+ rewrite?: (id: string, emailKey: string, codeHash: string) => Promise<boolean>;
24
29
  }
25
30
  export interface OtpConfig extends ServerConfig {
26
31
  otp?: {
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAA;AAC3E,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAA;AAC3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAA;AAEjD,MAAM,WAAW,YAAY;IAC3B,KAAK,EAAE,MAAM,CAAA;IACb,aAAa,EAAE,MAAM,CAAA;CACtB;AAED,MAAM,WAAW,gBAAgB;IAC/B,OAAO,EAAE,OAAO,CAAA;IAChB,UAAU,EAAE,MAAM,CAAA;CACnB;AAED,sFAAsF;AACtF,MAAM,WAAW,mBAAoB,SAAQ,kBAAkB;IAC7D,OAAO,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,YAAY,EAAE,EAAE,KAAK,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,gBAAgB,CAAC,CAAA;CACpG;AAED,MAAM,WAAW,YAAY;IAC3B,EAAE,EAAE,MAAM,CAAA;IACV,QAAQ,EAAE,MAAM,CAAA;IAChB,QAAQ,EAAE,MAAM,CAAA;CACjB;AAED,MAAM,WAAW,iBAAkB,SAAQ,kBAAkB;IAC3D,KAAK,EAAE,CAAC,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;IACxE,MAAM,EAAE,CACN,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,KACt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,CAAA;IACV,QAAQ,EAAE,MAAM,CAAA;IAChB,QAAQ,EAAE,MAAM,CAAA;CACjB;AAED,MAAM,WAAW,iBAAkB,SAAQ,kBAAkB;IAC3D,KAAK,EAAE,CAAC,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;IACxE,MAAM,EAAE,CACN,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,KACtE,OAAO,CAAC,mBAAmB,CAAC,CAAA;IACjC;;;OAGG;IACH,OAAO,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;CAC/E;AAED,MAAM,WAAW,SAAU,SAAQ,YAAY;IAC7C,GAAG,CAAC,EAAE;QACJ,yEAAyE;QACzE,WAAW,CAAC,EAAE,MAAM,CAAA;QACpB,8EAA8E;QAC9E,aAAa,CAAC,EAAE,MAAM,CAAA;QACtB,sEAAsE;QACtE,mBAAmB,CAAC,EAAE,MAAM,CAAA;QAC5B,8EAA8E;QAC9E,aAAa,CAAC,EAAE,MAAM,CAAA;QACtB,sEAAsE;QACtE,aAAa,CAAC,EAAE,SAAS,YAAY,EAAE,CAAA;QACvC,8EAA8E;QAC9E,aAAa,CAAC,EAAE,MAAM,CAAA;KACvB,CAAA;CACF;AAED,MAAM,WAAW,UAAU,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS,CAAE,SAAQ,aAAa,CAAC,CAAC,CAAC;CAAG"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owlmeans/server-auth-otp",
3
- "version": "0.1.19-rc.0",
3
+ "version": "0.1.19",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -22,21 +22,23 @@
22
22
  }
23
23
  },
24
24
  "dependencies": {
25
- "@owlmeans/auth": "^0.1.19-rc.0",
26
- "@owlmeans/auth-otp": "^0.1.19-rc.0",
27
- "@owlmeans/context": "^0.1.18",
28
- "@owlmeans/error": "^0.1.18",
29
- "@owlmeans/log": "^0.1.19-rc.0",
30
- "@owlmeans/mailer": "^0.1.19-rc.0",
31
- "@owlmeans/oidc": "^0.1.19-rc.0",
32
- "@owlmeans/redis-resource": "^0.1.19-rc.0",
33
- "@owlmeans/resource": "^0.1.19-rc.0",
34
- "@owlmeans/server-auth": "^0.1.19-rc.0",
35
- "@owlmeans/server-auth-identity": "^0.1.19-rc.0",
36
- "@owlmeans/server-context": "^0.1.19-rc.0"
25
+ "@owlmeans/auth": "^0.1.19",
26
+ "@owlmeans/auth-otp": "^0.1.19",
27
+ "@owlmeans/context": "^0.1.19",
28
+ "@owlmeans/error": "^0.1.19",
29
+ "@owlmeans/log": "^0.1.19",
30
+ "@owlmeans/mailer": "^0.1.19",
31
+ "@owlmeans/oidc": "^0.1.19",
32
+ "@owlmeans/redis-resource": "^0.1.19",
33
+ "@owlmeans/resource": "^0.1.19",
34
+ "@owlmeans/server-auth": "^0.1.19",
35
+ "@owlmeans/server-auth-identity": "^0.1.19",
36
+ "@owlmeans/server-context": "^0.1.19"
37
37
  },
38
38
  "devDependencies": {
39
- "@owlmeans/dep-config": "^0.1.18",
39
+ "@owlmeans/dep-config": "^0.1.19",
40
+ "@owlmeans/redis": "^0.1.19",
41
+ "@owlmeans/test-integration": "^0.1.19",
40
42
  "@types/bun": "^1.4.4",
41
43
  "nodemon": "^3.1.14",
42
44
  "typescript": "^7.0.2"
package/src/challenge.ts CHANGED
@@ -3,7 +3,7 @@ import type { RedisResource } from '@owlmeans/redis-resource'
3
3
  import { OtpUnavailable } from './errors.js'
4
4
  import { OTP_CHALLENGE_STORE, OTP_RESOURCE, type OtpChallengeOutcome, OtpChallengeOutcome as Outcome } from './consts.js'
5
5
  import type { OtpChallengeStore, OtpConfig, OtpContext } from './types.js'
6
- import { REDIS_VERIFY_SCRIPT } from './consts.local.js'
6
+ import { REDIS_REWRITE_SCRIPT, REDIS_VERIFY_SCRIPT } from './consts.local.js'
7
7
  import type { ChallengeResourceRecord, Clock, StoredChallenge } from './types.local.js'
8
8
 
9
9
 
@@ -40,6 +40,18 @@ export const makeMemoryOtpChallengeStore = (
40
40
 
41
41
  return Outcome.Invalid
42
42
  },
43
+ rewrite: async (id, emailKey, codeHash): Promise<boolean> => {
44
+ const record = records.get(id)
45
+ if (record == null || record.expiresAt <= now()) {
46
+ records.delete(id)
47
+ return false
48
+ }
49
+ if (record.emailKey !== emailKey) return false
50
+ record.codeHash = codeHash
51
+ record.failedAttempts = 0
52
+
53
+ return true
54
+ },
43
55
  })
44
56
  }
45
57
 
@@ -80,6 +92,19 @@ export const makeRedisOtpChallengeStore = (
80
92
  throw unavailable
81
93
  }
82
94
  },
95
+ rewrite: async (id, emailKey, codeHash): Promise<boolean> => {
96
+ const ctx = service.ctx as OtpContext<OtpConfig>
97
+ const resource = ctx.resource<RedisResource<ChallengeResourceRecord>>(resourceAlias)
98
+ try {
99
+ return Number(await resource.db.client.eval(
100
+ REDIS_REWRITE_SCRIPT, 1, resource.key(id), emailKey, codeHash
101
+ )) === 1
102
+ } catch (error) {
103
+ const unavailable = new OtpUnavailable('challenge')
104
+ if (error instanceof Error) unavailable.oiriginalStack = `${error}: ${error.stack}`
105
+ throw unavailable
106
+ }
107
+ },
83
108
  })
84
109
 
85
110
  return service
@@ -1,3 +1,5 @@
1
+ import { OTP_CODE_LENGTH } from '@owlmeans/auth-otp'
2
+
1
3
  export const REDIS_VERIFY_SCRIPT = `
2
4
  local raw = redis.call('GET', KEYS[1])
3
5
  if not raw then return 0 end
@@ -20,6 +22,30 @@ redis.call('SET', KEYS[1], cjson.encode(record), 'XX', 'PX', ttl)
20
22
  return -1
21
23
  `
22
24
 
25
+ /** Rewrite a live challenge of the same address: new code hash, attempts reset, remaining TTL kept. */
26
+ export const REDIS_REWRITE_SCRIPT = `
27
+ local raw = redis.call('GET', KEYS[1])
28
+ if not raw then return 0 end
29
+ local record = cjson.decode(raw)
30
+ if record.emailKey ~= ARGV[1] then return 0 end
31
+ local ttl = redis.call('PTTL', KEYS[1])
32
+ if ttl <= 0 then
33
+ redis.call('DEL', KEYS[1])
34
+ return 0
35
+ end
36
+ record.codeHash = ARGV[2]
37
+ record.failedAttempts = 0
38
+ redis.call('SET', KEYS[1], cjson.encode(record), 'XX', 'PX', ttl)
39
+ return 1
40
+ `
41
+
42
+ /** The placeholders an `OtpMessage` template may carry. */
43
+ export const OTP_MESSAGE_CODE = '{{code}}'
44
+ export const OTP_MESSAGE_MINUTES = '{{minutes}}'
45
+
46
+ /** The only shape a rewritten code may take: exactly `OTP_CODE_LENGTH` digits. */
47
+ export const OTP_CODE_PATTERN = new RegExp(`^\\d{${OTP_CODE_LENGTH}}$`)
48
+
23
49
  // Separates the email from the opaque issuance id inside the signed challenge.
24
50
  export const CHALLENGE_DELIMITER = '::'
25
51
 
package/src/service.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  import { appendContextual } from '@owlmeans/context'
2
2
  import { AuthenFailed } from '@owlmeans/auth'
3
- import { type OtpService, OTP_SERVICE, OTP_TTL_SECONDS, OTP_CODE_LENGTH, OTP_MAX_FAILED_ATTEMPTS, OTP_RESOURCE } from '@owlmeans/auth-otp'
3
+ import {
4
+ type OtpIssueOptions, type OtpMessage, type OtpService, OTP_SERVICE, OTP_TTL_SECONDS, OTP_CODE_LENGTH,
5
+ OTP_MAX_FAILED_ATTEMPTS, OTP_RESOURCE,
6
+ } from '@owlmeans/auth-otp'
4
7
  import { type MailerService, MAILER_SERVICE } from '@owlmeans/mailer'
5
8
  import { randomBytes, randomInt } from 'node:crypto'
6
9
  import type { AuthThrottleService, OtpChallengeStore, OtpConfig, OtpContext } from './types.js'
@@ -9,6 +12,7 @@ import { throttleKeyHelper } from './throttle-keys.js'
9
12
  import { otpKeyHelper } from './keys.js'
10
13
  import { OtpThrottled, OtpUnavailable } from './errors.js'
11
14
  import { makeRedisOtpChallengeStore } from './challenge.js'
15
+ import { OTP_CODE_PATTERN, OTP_MESSAGE_CODE, OTP_MESSAGE_MINUTES } from './consts.local.js'
12
16
  import { logger, logThrottle } from '@owlmeans/log'
13
17
 
14
18
  const log = logger('server-auth-otp')
@@ -21,6 +25,15 @@ const generateCode = (): string => {
21
25
  return String(digits).padStart(OTP_CODE_LENGTH, '0')
22
26
  }
23
27
 
28
+ /** An application's login-code mail with its placeholders filled in. */
29
+ const renderMessage = (message: OtpMessage, code: string): OtpMessage => {
30
+ const fill = (template: string): string => template
31
+ .replaceAll(OTP_MESSAGE_CODE, code)
32
+ .replaceAll(OTP_MESSAGE_MINUTES, String(OTP_TTL_SECONDS / 60))
33
+
34
+ return { subject: fill(message.subject), text: fill(message.text), html: fill(message.html) }
35
+ }
36
+
24
37
  export const makeOtpService = (alias = OTP_SERVICE): OtpService => {
25
38
  let fallbackChallenges: OtpChallengeStore | undefined
26
39
 
@@ -40,7 +53,7 @@ export const makeOtpService = (alias = OTP_SERVICE): OtpService => {
40
53
  }
41
54
 
42
55
  const service: OtpService = appendContextual<OtpService>(alias, {
43
- issueChallenge: async (email: string): Promise<string> => {
56
+ issueChallenge: async (email: string, opts?: OtpIssueOptions): Promise<string> => {
44
57
  const ctx = service.ctx as OtpContext<OtpConfig>
45
58
  const mailerAlias = ctx.cfg.otp?.mailerAlias ?? MAILER_SERVICE
46
59
  const challenges = challengeStore(ctx)
@@ -70,12 +83,16 @@ export const makeOtpService = (alias = OTP_SERVICE): OtpService => {
70
83
  }, OTP_TTL_SECONDS)
71
84
  if (!issued) throw new OtpUnavailable('issuance-collision')
72
85
 
73
- await mailer.send({
74
- to: email,
75
- subject: 'Your login code',
76
- text: `Your one-time login code is: ${code}\n\nIt expires in ${OTP_TTL_SECONDS / 60} minutes.`,
77
- html: `<p>Your one-time login code is: <strong>${code}</strong></p><p>It expires in ${OTP_TTL_SECONDS / 60} minutes.</p>`,
78
- })
86
+ if (opts?.message != null) {
87
+ await mailer.send({ to: email, ...renderMessage(opts.message, code) })
88
+ } else {
89
+ await mailer.send({
90
+ to: email,
91
+ subject: 'Your login code',
92
+ text: `Your one-time login code is: ${code}\n\nIt expires in ${OTP_TTL_SECONDS / 60} minutes.`,
93
+ html: `<p>Your one-time login code is: <strong>${code}</strong></p><p>It expires in ${OTP_TTL_SECONDS / 60} minutes.</p>`,
94
+ })
95
+ }
79
96
 
80
97
  return issuanceId
81
98
  },
@@ -92,6 +109,27 @@ export const makeOtpService = (alias = OTP_SERVICE): OtpService => {
92
109
  throw new AuthenFailed('otp:code')
93
110
  }
94
111
  },
112
+
113
+ rewriteChallenge: async (email: string, issuanceId: string, code: string): Promise<boolean> => {
114
+ const ctx = service.ctx as OtpContext<OtpConfig>
115
+ const challenges = challengeStore(ctx)
116
+ if (!OTP_CODE_PATTERN.test(code) || challenges.rewrite == null) {
117
+ log.debug('OTP challenge rewrite refused', {
118
+ reason: challenges.rewrite == null ? 'unsupported' : 'code-shape', emailDomain: domainOf(email),
119
+ })
120
+ return false
121
+ }
122
+ const rewritten = await challenges.rewrite(
123
+ otpKeyHelper.otpChallengeKey(issuanceId), otpKeyHelper.otpEmailKey(email), otpKeyHelper.otpCodeHash(issuanceId, code)
124
+ )
125
+ if (rewritten) {
126
+ log.info('Login code rewritten', { emailDomain: domainOf(email) }, { event: 'auth.otp-rewritten' })
127
+ } else {
128
+ log.debug('OTP challenge rewrite refused', { reason: 'missing', emailDomain: domainOf(email) })
129
+ }
130
+
131
+ return rewritten
132
+ },
95
133
  })
96
134
 
97
135
  return service
package/src/types.ts CHANGED
@@ -28,6 +28,11 @@ export interface OtpChallengeStore extends InitializedService {
28
28
  verify: (
29
29
  id: string, emailKey: string, codeHash: string, maxFailedAttempts: number
30
30
  ) => Promise<OtpChallengeOutcome>
31
+ /**
32
+ * Replace the code of a live challenge whose address matches, resetting its failed attempts and
33
+ * keeping its expiry. `false` when the challenge is gone or names another address.
34
+ */
35
+ rewrite?: (id: string, emailKey: string, codeHash: string) => Promise<boolean>
31
36
  }
32
37
 
33
38
  export interface OtpConfig extends ServerConfig {
package/tests/context.ts CHANGED
@@ -1,12 +1,22 @@
1
1
  import { AppType, makeBasicContext } from '@owlmeans/context'
2
2
  import { MAILER_SERVICE, makeConsoleMailerService } from '@owlmeans/mailer'
3
- import { makeMemoryOtpChallengeStore } from '../src/challenge.js'
3
+ import type { ConsoleMailerService } from '@owlmeans/mailer'
4
+ import { config, makeServerContext } from '@owlmeans/server-context'
5
+ import { makeRedisResource } from '@owlmeans/redis-resource'
6
+ import type { RedisResource } from '@owlmeans/redis-resource'
7
+ import type { ResourceRecord } from '@owlmeans/resource'
8
+ import { appendRedis, DEFAULT_ALIAS } from '@owlmeans/redis'
9
+ import { gateHelper, randomNamespace } from '@owlmeans/test-integration'
10
+ import type { IntegrationGate, RedisEnv } from '@owlmeans/test-integration'
11
+ import type { OtpService } from '@owlmeans/auth-otp'
12
+ import { makeMemoryOtpChallengeStore, makeRedisOtpChallengeStore } from '../src/challenge.js'
4
13
  import { makeMemoryThrottleService } from '../src/throttle.js'
5
14
  import { makeOtpService } from '../src/service.js'
15
+ import { otpKeyHelper } from '../src/keys.js'
6
16
  import {
7
- OTP_CHALLENGE_STORE, OTP_EMAIL_THROTTLE_RULES, OTP_THROTTLE_SERVICE,
17
+ OTP_CHALLENGE_STORE, OTP_EMAIL_THROTTLE_RULES, OTP_RESOURCE, OTP_THROTTLE_SERVICE,
8
18
  } from '../src/consts.js'
9
- import type { OtpConfig } from '../src/types.js'
19
+ import type { OtpConfig, OtpContext } from '../src/types.js'
10
20
 
11
21
  export const makeOtpTestContext = (opts: { throttle?: boolean, now?: () => number } = {}) => {
12
22
  const cfg: OtpConfig = {
@@ -41,3 +51,89 @@ export const codeFrom = (text: string | undefined): string => {
41
51
  if (match == null) throw new Error('OTP code missing from captured message')
42
52
  return match[1]
43
53
  }
54
+
55
+ /** A six-digit code other than `code`. */
56
+ export const otherCode = (code: string): string => code === '123456' ? '654321' : '123456'
57
+
58
+ // --- Redis-backed challenge store (env-gated) ---------------------------------------------------
59
+
60
+ export const redisGate: IntegrationGate<RedisEnv> = gateHelper.redisGate()
61
+
62
+ /** Hook budget for a suite's teardown: a prefix walk over a shared store, through a port-forward. */
63
+ export const TEARDOWN_TIMEOUT = 60_000
64
+
65
+ export interface RedisOtpFixture {
66
+ otp: OtpService
67
+ mailer: ConsoleMailerService
68
+ /** Remaining lifetime of an issuance's challenge record, in milliseconds. */
69
+ pttl: (issuanceId: string) => Promise<number>
70
+ }
71
+
72
+ export interface RedisOtpSuite {
73
+ boot: () => Promise<RedisOtpFixture>
74
+ teardown: () => Promise<void>
75
+ }
76
+
77
+ /** One key prefix per spec file, dropped by that file's own `afterAll`. */
78
+ export const makeRedisOtpSuite = (label: string): RedisOtpSuite => {
79
+ const prefix = randomNamespace(`${process.env.REDIS_TEST_KEY_PREFIX ?? 'omt'}_${label}`)
80
+ const resources: Array<RedisResource<ResourceRecord>> = []
81
+
82
+ const boot = async (): Promise<RedisOtpFixture> => {
83
+ const url = new URL(redisGate.env.REDIS_URL as string)
84
+ const cfg = config<OtpConfig>('server-auth-otp-redis-tests', {
85
+ dbs: [{
86
+ service: DEFAULT_ALIAS,
87
+ alias: DEFAULT_ALIAS,
88
+ host: url.hostname,
89
+ port: url.port !== '' ? Number(url.port) : 6379,
90
+ user: url.username !== '' ? url.username : undefined,
91
+ secret: decodeURIComponent(url.password),
92
+ schema: prefix,
93
+ }],
94
+ otp: { mailerAlias: MAILER_SERVICE, challengeStoreAlias: OTP_CHALLENGE_STORE },
95
+ } as Partial<OtpConfig>)
96
+
97
+ const context = makeServerContext(cfg) as OtpContext<OtpConfig>
98
+ appendRedis(context)
99
+ context.registerResource(makeRedisResource(OTP_RESOURCE) as never)
100
+ const mailer = makeConsoleMailerService(MAILER_SERVICE)
101
+ context.registerService(mailer)
102
+ context.registerService(makeRedisOtpChallengeStore(OTP_CHALLENGE_STORE, OTP_RESOURCE))
103
+ const otp = makeOtpService()
104
+ context.registerService(otp)
105
+ context.configure()
106
+ await context.init()
107
+
108
+ const resource = context.resource<RedisResource<ResourceRecord>>(OTP_RESOURCE)
109
+ resources.push(resource)
110
+ const pttl = async (issuanceId: string): Promise<number> =>
111
+ await resource.db.client.pttl(resource.key(otpKeyHelper.otpChallengeKey(issuanceId)))
112
+
113
+ return { otp, mailer, pttl }
114
+ }
115
+
116
+ const teardown = async (): Promise<void> => {
117
+ if (redisGate.skip) return
118
+ for (const resource of resources) {
119
+ const client = resource.db?.client
120
+ if (client == null) continue
121
+ try {
122
+ const keys: string[] = []
123
+ let cursor = '0'
124
+ do {
125
+ const [next, batch] = await client.scan(cursor, 'MATCH', `${prefix}*`, 'COUNT', 10_000)
126
+ cursor = next
127
+ keys.push(...batch)
128
+ } while (cursor !== '0')
129
+ if (keys.length > 0) await client.del(keys)
130
+ } catch {
131
+ // The prefix is unique per run, so anything a lost connection leaves behind never collides.
132
+ }
133
+ await client.quit().catch(() => undefined)
134
+ }
135
+ resources.length = 0
136
+ }
137
+
138
+ return { boot, teardown }
139
+ }
@@ -0,0 +1,56 @@
1
+ import { afterAll, describe, expect, test } from 'bun:test'
2
+ import { AuthenFailed } from '@owlmeans/auth'
3
+ import { codeFrom, makeRedisOtpSuite, otherCode, redisGate, TEARDOWN_TIMEOUT } from './context.js'
4
+
5
+ const wrongFor = (code: string): string => code === '000000' ? '999999' : '000000'
6
+
7
+ describe('@owlmeans/server-auth-otp — Redis challenge store rewrite', () => {
8
+ if (redisGate.skip) {
9
+ test.skip(redisGate.reason ?? 'redis gate closed', () => { })
10
+ return
11
+ }
12
+
13
+ const suite = makeRedisOtpSuite('otp_rewrite')
14
+
15
+ afterAll(async () => {
16
+ await suite.teardown()
17
+ }, TEARDOWN_TIMEOUT)
18
+
19
+ test('keeps the remaining TTL, swaps the code and resets the failed attempts', async () => {
20
+ const { otp, mailer, pttl } = await suite.boot()
21
+ const email = 'ttl@example.com'
22
+ const issuanceId = await otp.issueChallenge(email)
23
+ const mailed = codeFrom(mailer.captured[0].text)
24
+ const next = otherCode(mailed)
25
+
26
+ for (let attempt = 0; attempt < 4; attempt += 1) {
27
+ await expect(otp.verifyChallenge(email, issuanceId, wrongFor(next))).rejects.toBeInstanceOf(AuthenFailed)
28
+ }
29
+ const before = await pttl(issuanceId)
30
+ await Bun.sleep(1_100)
31
+ expect(await otp.rewriteChallenge!(email, issuanceId, next)).toBe(true)
32
+ const after = await pttl(issuanceId)
33
+
34
+ expect(after).toBeGreaterThan(0)
35
+ expect(after).toBeLessThanOrEqual(before - 1_000)
36
+ // Four guesses before the rewrite and four after (the mailed code among them) would exhaust an
37
+ // issuance whose counter was not reset.
38
+ await expect(otp.verifyChallenge(email, issuanceId, mailed)).rejects.toBeInstanceOf(AuthenFailed)
39
+ for (let attempt = 0; attempt < 3; attempt += 1) {
40
+ await expect(otp.verifyChallenge(email, issuanceId, wrongFor(next))).rejects.toBeInstanceOf(AuthenFailed)
41
+ }
42
+ await expect(otp.verifyChallenge(email, issuanceId, next)).resolves.toBeUndefined()
43
+ }, 15_000)
44
+
45
+ test('refuses another address and a missing issuance, leaving the challenge as it was', async () => {
46
+ const { otp, mailer, pttl } = await suite.boot()
47
+ const issuanceId = await otp.issueChallenge('owner@example.com')
48
+ const mailed = codeFrom(mailer.captured[0].text)
49
+ const next = otherCode(mailed)
50
+
51
+ expect(await otp.rewriteChallenge!('intruder@example.com', issuanceId, next)).toBe(false)
52
+ expect(await otp.rewriteChallenge!('owner@example.com', 'no-such-issuance', next)).toBe(false)
53
+ expect(await pttl('no-such-issuance')).toBe(-2)
54
+ await expect(otp.verifyChallenge('owner@example.com', issuanceId, mailed)).resolves.toBeUndefined()
55
+ }, 15_000)
56
+ })
@@ -1,7 +1,8 @@
1
1
  import { describe, expect, test } from 'bun:test'
2
2
  import { AuthenFailed } from '@owlmeans/auth'
3
3
  import { OtpThrottled } from '../src/errors.js'
4
- import { codeFrom, makeOtpTestContext } from './context.js'
4
+ import { OTP_TTL_SECONDS } from '../src/consts.js'
5
+ import { codeFrom, makeOtpTestContext, otherCode } from './context.js'
5
6
 
6
7
  const wrongFor = (code: string): string => code === '000000' ? '999999' : '000000'
7
8
 
@@ -86,3 +87,101 @@ describe('@owlmeans/server-auth-otp — issuance throttle', () => {
86
87
  expect((hour as OtpThrottled).retryAfter).toBeGreaterThan(0)
87
88
  })
88
89
  })
90
+
91
+ describe('@owlmeans/server-auth-otp — login-code mail', () => {
92
+ test('the default mail stays the unchanged English text', async () => {
93
+ const { context, mailer, otp } = makeOtpTestContext()
94
+ await context.configure().init()
95
+ await otp.issueChallenge('default@example.com')
96
+ const code = codeFrom(mailer.captured[0].text)
97
+
98
+ expect(mailer.captured[0]).toEqual({
99
+ to: 'default@example.com',
100
+ subject: 'Your login code',
101
+ text: `Your one-time login code is: ${code}\n\nIt expires in 10 minutes.`,
102
+ html: `<p>Your one-time login code is: <strong>${code}</strong></p><p>It expires in 10 minutes.</p>`,
103
+ })
104
+ })
105
+
106
+ test('a message override fills {{code}} and {{minutes}} in every part', async () => {
107
+ const { context, mailer, otp } = makeOtpTestContext()
108
+ await context.configure().init()
109
+ const issuanceId = await otp.issueChallenge('custom@example.com', {
110
+ message: {
111
+ subject: 'Kod {{code}}',
112
+ text: 'Twój kod: {{code}} ({{minutes}} min) — {{code}}',
113
+ html: '<p><b>{{code}}</b> · {{minutes}}</p>',
114
+ },
115
+ })
116
+ const code = codeFrom(mailer.captured[0].text)
117
+ const minutes = String(OTP_TTL_SECONDS / 60)
118
+
119
+ expect(mailer.captured[0]).toEqual({
120
+ to: 'custom@example.com',
121
+ subject: `Kod ${code}`,
122
+ text: `Twój kod: ${code} (${minutes} min) — ${code}`,
123
+ html: `<p><b>${code}</b> · ${minutes}</p>`,
124
+ })
125
+ await expect(otp.verifyChallenge('custom@example.com', issuanceId, code)).resolves.toBeUndefined()
126
+ })
127
+ })
128
+
129
+ describe('@owlmeans/server-auth-otp — developer rewrite', () => {
130
+ test('a rewritten code verifies and the mailed one no longer does', async () => {
131
+ const { context, mailer, otp } = makeOtpTestContext()
132
+ await context.configure().init()
133
+ const issuanceId = await otp.issueChallenge('swap@example.com')
134
+ const mailed = codeFrom(mailer.captured[0].text)
135
+ const next = otherCode(mailed)
136
+
137
+ expect(await otp.rewriteChallenge!('SWAP@example.com', issuanceId, next)).toBe(true)
138
+ await expect(otp.verifyChallenge('swap@example.com', issuanceId, mailed)).rejects.toBeInstanceOf(AuthenFailed)
139
+ await expect(otp.verifyChallenge('swap@example.com', issuanceId, next)).resolves.toBeUndefined()
140
+ })
141
+
142
+ test('a rewrite resets the failed attempts', async () => {
143
+ const { context, mailer, otp } = makeOtpTestContext()
144
+ await context.configure().init()
145
+ const issuanceId = await otp.issueChallenge('reset@example.com')
146
+ const next = otherCode(codeFrom(mailer.captured[0].text))
147
+
148
+ for (let attempt = 0; attempt < 4; attempt += 1) {
149
+ await expect(otp.verifyChallenge('reset@example.com', issuanceId, wrongFor(next)))
150
+ .rejects.toBeInstanceOf(AuthenFailed)
151
+ }
152
+ expect(await otp.rewriteChallenge!('reset@example.com', issuanceId, next)).toBe(true)
153
+ for (let attempt = 0; attempt < 4; attempt += 1) {
154
+ await expect(otp.verifyChallenge('reset@example.com', issuanceId, wrongFor(next)))
155
+ .rejects.toBeInstanceOf(AuthenFailed)
156
+ }
157
+ await expect(otp.verifyChallenge('reset@example.com', issuanceId, next)).resolves.toBeUndefined()
158
+ })
159
+
160
+ test('a rewrite keeps the original lifetime', async () => {
161
+ let now = 0
162
+ const { context, mailer, otp } = makeOtpTestContext({ now: () => now })
163
+ await context.configure().init()
164
+ const issuanceId = await otp.issueChallenge('ttl@example.com')
165
+ const next = otherCode(codeFrom(mailer.captured[0].text))
166
+
167
+ now = (OTP_TTL_SECONDS - 100) * 1000
168
+ expect(await otp.rewriteChallenge!('ttl@example.com', issuanceId, next)).toBe(true)
169
+ now = OTP_TTL_SECONDS * 1000 + 1
170
+ await expect(otp.verifyChallenge('ttl@example.com', issuanceId, next)).rejects.toBeInstanceOf(AuthenFailed)
171
+ })
172
+
173
+ test('refuses another address, a malformed code and a missing issuance', async () => {
174
+ const { context, mailer, otp } = makeOtpTestContext()
175
+ await context.configure().init()
176
+ const issuanceId = await otp.issueChallenge('owner@example.com')
177
+ const mailed = codeFrom(mailer.captured[0].text)
178
+ const next = otherCode(mailed)
179
+
180
+ expect(await otp.rewriteChallenge!('intruder@example.com', issuanceId, next)).toBe(false)
181
+ for (const malformed of ['12345', '1234567', 'abcdef', ' 123456', '12345a']) {
182
+ expect(await otp.rewriteChallenge!('owner@example.com', issuanceId, malformed)).toBe(false)
183
+ }
184
+ expect(await otp.rewriteChallenge!('owner@example.com', 'no-such-issuance', next)).toBe(false)
185
+ await expect(otp.verifyChallenge('owner@example.com', issuanceId, mailed)).resolves.toBeUndefined()
186
+ })
187
+ })