@owlmeans/server-auth-otp 0.1.18-rc.8 → 0.1.18

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 (74) hide show
  1. package/README.md +156 -24
  2. package/agent-meta/manifest.json +3 -3
  3. package/agent-meta/skills/server-auth-otp/SKILL.md +64 -30
  4. package/build/challenge.d.ts +7 -0
  5. package/build/challenge.d.ts.map +1 -0
  6. package/build/challenge.js +77 -0
  7. package/build/challenge.js.map +1 -0
  8. package/build/consts.d.ts +16 -1
  9. package/build/consts.d.ts.map +1 -1
  10. package/build/consts.js +14 -1
  11. package/build/consts.js.map +1 -1
  12. package/build/consts.local.d.ts +4 -0
  13. package/build/consts.local.d.ts.map +1 -0
  14. package/build/consts.local.js +50 -0
  15. package/build/consts.local.js.map +1 -0
  16. package/build/errors.d.ts +18 -0
  17. package/build/errors.d.ts.map +1 -0
  18. package/build/errors.js +32 -0
  19. package/build/errors.js.map +1 -0
  20. package/build/index.d.ts +8 -1
  21. package/build/index.d.ts.map +1 -1
  22. package/build/index.js +6 -0
  23. package/build/index.js.map +1 -1
  24. package/build/keys/types.d.ts +10 -0
  25. package/build/keys/types.d.ts.map +1 -0
  26. package/build/keys/types.js +2 -0
  27. package/build/keys/types.js.map +1 -0
  28. package/build/keys.d.ts +4 -0
  29. package/build/keys.d.ts.map +1 -0
  30. package/build/keys.js +10 -0
  31. package/build/keys.js.map +1 -0
  32. package/build/plugin.d.ts.map +1 -1
  33. package/build/plugin.js +18 -18
  34. package/build/plugin.js.map +1 -1
  35. package/build/service.d.ts +1 -1
  36. package/build/service.d.ts.map +1 -1
  37. package/build/service.js +56 -25
  38. package/build/service.js.map +1 -1
  39. package/build/throttle-keys/types.d.ts +8 -0
  40. package/build/throttle-keys/types.d.ts.map +1 -0
  41. package/build/throttle-keys/types.js +2 -0
  42. package/build/throttle-keys/types.js.map +1 -0
  43. package/build/throttle-keys.d.ts +4 -0
  44. package/build/throttle-keys.d.ts.map +1 -0
  45. package/build/throttle-keys.js +9 -0
  46. package/build/throttle-keys.js.map +1 -0
  47. package/build/throttle.d.ts +11 -0
  48. package/build/throttle.d.ts.map +1 -0
  49. package/build/throttle.js +67 -0
  50. package/build/throttle.js.map +1 -0
  51. package/build/types.d.ts +29 -0
  52. package/build/types.d.ts.map +1 -1
  53. package/build/types.local.d.ts +16 -0
  54. package/build/types.local.d.ts.map +1 -0
  55. package/build/types.local.js +2 -0
  56. package/build/types.local.js.map +1 -0
  57. package/package.json +15 -14
  58. package/src/challenge.ts +86 -0
  59. package/src/consts.local.ts +51 -0
  60. package/src/consts.ts +18 -1
  61. package/src/errors.ts +37 -0
  62. package/src/index.ts +8 -1
  63. package/src/keys/types.ts +9 -0
  64. package/src/keys.ts +16 -0
  65. package/src/plugin.ts +21 -25
  66. package/src/service.ts +68 -41
  67. package/src/throttle-keys/types.ts +7 -0
  68. package/src/throttle-keys.ts +17 -0
  69. package/src/throttle.ts +85 -0
  70. package/src/types.local.ts +10 -0
  71. package/src/types.ts +36 -0
  72. package/tests/context.ts +43 -0
  73. package/tests/keys.spec.ts +23 -0
  74. package/tests/service.spec.ts +88 -0
package/README.md CHANGED
@@ -1,43 +1,175 @@
1
1
  # @owlmeans/server-auth-otp
2
2
 
3
- Email OTP `AuthPlugin` for OwlMeans servers — passwordless login via time-limited one-time codes.
4
-
5
- ## Overview
6
-
7
- - `appendOtpPlugin(context)` — registers the `AuthPlugin` that handles `OTP_AUTH_TYPE` (`'email-otp'`) authentication requests
8
- - `makeOtpService(alias?)` — issues email challenges and verifies submitted codes; backed by `@owlmeans/auth-otp`
9
- - Integrates with the `@owlmeans/server-auth` plugin registry — plugs in alongside other auth strategies
10
- - Resolves identities through `@owlmeans/server-auth-identity` after OTP verification
3
+ Email one-time-code login for an OwlMeans server: the `OtpService` implementation that issues and
4
+ verifies codes, the `'email-otp'` `AuthPlugin` for the `@owlmeans/server-auth` plugin registry,
5
+ atomic challenge stores and sliding-window throttles (Redis for production, memory for development
6
+ and tests), and the OTP errors. A server uses it to offer passwordless sign-in by e-mail; the
7
+ verified address is resolved to an account through `@owlmeans/server-auth-identity`. It does not send
8
+ mail itself — a `MailerService` must be registered — and it is not the place for shared constants or
9
+ the `OtpService` type: depend on `@owlmeans/auth-otp` from a package that only names the auth type or
10
+ types the service, and on this package only where the server wires itself up.
11
11
 
12
12
  ## Installation
13
13
 
14
14
  ```bash
15
- bun add @owlmeans/server-auth-otp
15
+ bun add @owlmeans/server-auth-otp@^0.1.18
16
16
  ```
17
17
 
18
+ ## Concepts
19
+
20
+ - **Issuance** — `issueChallenge(email)` creates a random 6-digit code (`OTP_CODE_LENGTH`), stores it
21
+ for `OTP_TTL_SECONDS` (600 s) under an opaque issuance id, mails it and returns the id. The id
22
+ never contains the address or the code.
23
+ - **Challenge store** — `OtpChallengeStore`, keyed by digests from `otpKeyHelper`. `verify`
24
+ compares, counts failures and consumes in one operation; after `OTP_MAX_FAILED_ATTEMPTS` (5) the
25
+ issuance is exhausted.
26
+ - **Throttle** — `AuthThrottleService.consume(key, rules, token?)` applies every `ThrottleRule`
27
+ (`{ limit, windowSeconds }`) together. Enabled only when `cfg.otp.throttleAlias` and
28
+ `cfg.otp.throttleRules` are both set.
29
+ - **Plugin** — `appendOtpPlugin` registers the plugin factory under `OTP_AUTH_TYPE` in the
30
+ server-auth registry. `init` issues a challenge `"<email>::<issuanceId>"`; `authenticate`
31
+ verifies the code, links or finds the profile and fills the credential
32
+ (`AuthenticationType.OneTimeToken`).
33
+
18
34
  ## Usage
19
35
 
36
+ ### Wire the server
37
+
20
38
  ```typescript
21
- import { makeRedisResource } from '@owlmeans/redis-resource'
22
- import { OTP_RESOURCE, OTP_SERVICE } from '@owlmeans/auth-otp'
23
- import { appendOtpPlugin, makeOtpService } from '@owlmeans/server-auth-otp'
24
39
  import { MAILER_SERVICE } from '@owlmeans/mailer'
25
- import { makeSmtpMailerService } from '@owlmeans/mailer-smtp'
40
+ import { makeMailgunMailerService } from '@owlmeans/server-mailer-mailgun'
41
+ import { makeRedisResource } from '@owlmeans/redis-resource'
42
+ import {
43
+ OTP_RESOURCE, appendOtpPlugin, makeOtpService, makeRedisOtpChallengeStore, makeRedisThrottleService,
44
+ } from '@owlmeans/server-auth-otp'
45
+
46
+ context.registerResource(makeRedisResource(OTP_RESOURCE)) // challenge and throttle storage
47
+ context.registerService(makeRedisOtpChallengeStore()) // OTP_CHALLENGE_STORE
48
+ context.registerService(makeRedisThrottleService()) // OTP_THROTTLE_SERVICE
49
+ context.registerService(makeMailgunMailerService(MAILER_SERVICE)) // delivers the code
50
+ context.registerService(makeOtpService()) // OTP_SERVICE
51
+
52
+ appendOtpPlugin(context) // plugin under 'email-otp'
53
+ ```
54
+
55
+ ### Configure
56
+
57
+ ```typescript
58
+ import { OTP_EMAIL_THROTTLE_RULES, OTP_THROTTLE_SERVICE } from '@owlmeans/server-auth-otp'
59
+ import type { OtpConfig } from '@owlmeans/server-auth-otp'
60
+
61
+ const otp: OtpConfig['otp'] = {
62
+ throttleAlias: OTP_THROTTLE_SERVICE,
63
+ throttleRules: OTP_EMAIL_THROTTLE_RULES, // 1 per minute, 10 per hour
64
+ // mailerAlias, resourceAlias, challengeStoreAlias, identityAlias override the defaults
65
+ }
66
+ ```
67
+
68
+ ### Test with in-memory stores and the console mailer
69
+
70
+ ```typescript
71
+ import type { OtpService } from '@owlmeans/auth-otp'
72
+ import { makeDefaultConsoleMailerService } from '@owlmeans/mailer'
73
+ import {
74
+ OTP_SERVICE, makeMemoryOtpChallengeStore, makeMemoryThrottleService, makeOtpService,
75
+ } from '@owlmeans/server-auth-otp'
26
76
 
27
- context.registerResource(makeRedisResource(OTP_RESOURCE)) // challenge store
28
- context.registerService(makeSmtpMailerService(MAILER_SERVICE))
29
- context.registerService(makeOtpService(OTP_SERVICE))
77
+ const mailer = makeDefaultConsoleMailerService()
78
+ context.registerService(mailer)
79
+ context.registerService(makeMemoryOtpChallengeStore())
80
+ context.registerService(makeMemoryThrottleService())
81
+ context.registerService(makeOtpService())
82
+ await context.configure().init()
30
83
 
31
- appendOtpPlugin(context) // registers the plugin factory under 'email-otp'
84
+ const otp = context.service<OtpService>(OTP_SERVICE)
85
+ const issuanceId = await otp.issueChallenge('user@example.com')
86
+ const code = mailer.captured[0].text?.match(/\d{6}/)?.[0] ?? ''
87
+ await otp.verifyChallenge('user@example.com', issuanceId, code) // throws AuthenFailed('otp:code') on a mismatch
32
88
  ```
33
89
 
34
- `appendOtpPlugin` writes into a module-level registry, so it is a global side effect: the
35
- `context` it takes is only returned for chaining, and the plugin factory receives the live
36
- context per request.
90
+ `OtpService` and `OTP_SERVICE` come from `@owlmeans/auth-otp` (the constant is also re-exported
91
+ here). The memory factories accept a clock as their second argument for deterministic tests.
92
+
93
+ ## API
94
+
95
+ ### Services and plugin
96
+
97
+ | Symbol | Purpose |
98
+ |---|---|
99
+ | `makeOtpService(alias = OTP_SERVICE)` | `OtpService`: `issueChallenge(email) → issuanceId`, `verifyChallenge(email, issuanceId, code)` |
100
+ | `appendOtpPlugin(context)` | registers the `'email-otp'` plugin factory; returns the context |
101
+ | `makeRedisOtpChallengeStore(alias?, resourceAlias?)` | atomic Redis store (`SET NX EX` + one Lua verify) |
102
+ | `makeMemoryOtpChallengeStore(alias?, now?)` | in-memory store for a single process or tests |
103
+ | `makeRedisThrottleService(alias?, resourceAlias?)` | every window checked and consumed in one Lua call |
104
+ | `makeMemoryThrottleService(alias?, now?)` | in-memory sliding-window throttle |
105
+ | `otpKeyHelper` (`createOtpKeyHelper()`) | `otpChallengeKey`, `otpEmailKey`, `otpCodeHash` — SHA-256 digests |
106
+ | `throttleKeyHelper` (`createThrottleKeyHelper()`) | `emailThrottleKey`, `ipThrottleKey` — digests, never raw values |
107
+ | `emailThrottleKey`, `ipThrottleKey` | deprecated standalone forms of the helper members |
108
+
109
+ ### Constants
110
+
111
+ | Symbol | Value |
112
+ |---|---|
113
+ | `SERVER_AUTH_OTP` | `'server-auth-otp'` |
114
+ | `OTP_CHALLENGE_STORE` | `'auth-otp-challenge-store'` |
115
+ | `OTP_THROTTLE_SERVICE` | `'auth-otp-throttle'` |
116
+ | `OTP_EMAIL_THROTTLE_RULES` | `[{ limit: 1, windowSeconds: 60 }, { limit: 10, windowSeconds: 3600 }]` |
117
+ | `OtpChallengeOutcome` | `Verified`, `Invalid`, `Exhausted`, `Missing` |
118
+ | re-exported from `@owlmeans/auth-otp` | `OTP_AUTH_TYPE` (`'email-otp'`), `OTP_SERVICE`, `OTP_RESOURCE` (`'auth-otp-cache'`), `OTP_TTL_SECONDS`, `OTP_CODE_LENGTH`, `OTP_MAX_FAILED_ATTEMPTS` |
119
+
120
+ ### Types
121
+
122
+ `OtpConfig` (`cfg.otp`: `mailerAlias?`, `resourceAlias?`, `challengeStoreAlias?`, `throttleAlias?`,
123
+ `throttleRules?`, `identityAlias?`), `OtpContext`, `OtpChallenge`, `OtpChallengeStore`,
124
+ `AuthThrottleService`, `ThrottleRule`, `ThrottleDecision`, `OtpKeyHelper`, `ThrottleKeyHelper`.
125
+
126
+ ### Errors
127
+
128
+ | Class | Status | Meaning |
129
+ |---|---|---|
130
+ | `OtpError` | — | base, message `otp:<reason>` |
131
+ | `OtpThrottled` | 429 | issuance refused by the throttle; `retryAfter` in seconds |
132
+ | `OtpUnavailable` | 503 | the store or throttle backend failed, or an issuance id collided |
133
+
134
+ A wrong, expired or exhausted code is `AuthenFailed('otp:code')` from `@owlmeans/auth`; a missing or
135
+ malformed address is `AuthenFailed('otp:email')`.
136
+
137
+ ## Auth flow
138
+
139
+ 1. **Init** — the client sends `{ type: 'email-otp', userId: <email> }`; the plugin lowercases the
140
+ address, issues a code and returns the challenge in the signed envelope.
141
+ 2. **Authenticate** — the client sends the envelope as `challenge`, the code as `credential`, plus
142
+ `type`, `role` and `scopes` (required by `AuthCredentialsSchema`). The plugin verifies the
143
+ issuance, resolves the profile through the `IdentityLinkingService` under
144
+ `cfg.otp.identityAlias ?? AUTH_IDENTITY_LINKING` (linking a new one when absent) and copies
145
+ `userId`, `profileId`, `entitySlug`, `role` and `scopes` from it onto the credential.
146
+
147
+ ## Common pitfalls
148
+
149
+ - `makeConsoleMailerService()` registers under `'console-mailer'`; the OTP service resolves
150
+ `cfg.otp.mailerAlias ?? MAILER_SERVICE`. Use `makeDefaultConsoleMailerService()` in tests.
151
+ - Without a registered challenge store the service falls back to a Redis store over `OTP_RESOURCE`;
152
+ register that resource or an explicit store.
153
+ - Throttling is off unless both `throttleAlias` and `throttleRules` are configured.
154
+ - `appendOtpPlugin` writes into a module-level registry — call it once; the context argument is only
155
+ returned for chaining.
156
+ - `credential.entitySlug` on the authenticate request selects nothing: the linked payload's own slug
157
+ overwrites it, so the address alone decides the account and organization entity.
158
+ - The resulting auth token can exceed 1024 characters; a route accepting it must size its schema
159
+ beyond the generic `AuthTokenSchema`.
160
+ - Never encode the address or code into the issuance id, and never replace the attempt counter with
161
+ a bare replay key.
162
+
163
+ ## Related packages
164
+
165
+ - [`@owlmeans/auth-otp`](../auth-otp) — `OtpService` type and the shared OTP constants
166
+ - [`@owlmeans/server-auth`](../server-auth) — the auth-manager plugin registry this plugin joins
167
+ - [`@owlmeans/server-auth-identity`](../server-auth-identity) — `IdentityLinkingService`, which maps the address to an account
168
+ - [`@owlmeans/mailer`](../mailer) — `MailerService` and the console transport for tests
169
+ - [`@owlmeans/server-mailer-mailgun`](../server-mailer-mailgun) / [`@owlmeans/mailer-smtp`](../mailer-smtp) — production transports
170
+ - [`@owlmeans/redis-resource`](../redis-resource) — the Redis resource behind the stores and throttle
37
171
 
38
- The OTP service must be backed by a transport that can deliver the one-time code —
39
- `@owlmeans/mailer-smtp` (SMTP) or `@owlmeans/server-mailer-mailgun` (Mailgun HTTP API),
40
- registered under `MAILER_SERVICE`. Override the alias with `cfg.otp.mailerAlias`.
172
+ The `server-auth-otp` skill covers the flow and its schema gotchas for agents.
41
173
 
42
174
  <!-- owlmeans:agent-guidance:start -->
43
175
  ## Agent guidance
@@ -47,7 +179,7 @@ This package ships embedded agent skills under `agent-meta/`. After installing y
47
179
  your project's skill store (`.agents/skills/`):
48
180
 
49
181
  ```sh
50
- npx @owlmeans/agent-skills
182
+ npx @owlmeans/agent-skills@^0.1.18
51
183
  ```
52
184
 
53
185
  The embedded files are version-matched to this package release. Do not edit them
@@ -1,8 +1,8 @@
1
1
  {
2
- "schemaVersion": 2,
2
+ "schemaVersion": 3,
3
3
  "package": "@owlmeans/server-auth-otp",
4
- "version": "0.1.18-rc.7",
5
- "generatedAt": "2026-08-21T09:53:56.642Z",
4
+ "version": "0.1.18",
5
+ "generatedAt": "2026-10-28T00:31:34.731Z",
6
6
  "canonicalRepo": "https://github.com/owlmeans/common",
7
7
  "entries": [
8
8
  {
@@ -8,32 +8,50 @@ metadata:
8
8
 
9
9
  # Using `@owlmeans/server-auth-otp`
10
10
 
11
+ **Install:** `"@owlmeans/server-auth-otp": "^0.1.18"` in `dependencies`
12
+
11
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.
12
14
 
15
+ ## `@owlmeans/auth-otp` — the contracts
16
+
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.
22
+
23
+ Depend on it from a shared package that must name the auth type or type the service, and depend on
24
+ `@owlmeans/server-auth-otp` only where the server wires itself up — the same producer/consumer split
25
+ every other contracts-and-driver pair in the framework uses. Add a constant or a method signature to
26
+ the contracts package, never to the implementation.
27
+
13
28
  ## Public API surface
14
29
 
15
30
  | Symbol | Kind | Purpose |
16
31
  |--------|------|---------|
17
32
  | `makeOtpService(alias?)` | fn | Service factory — stores/verifies OTP codes |
18
33
  | `appendOtpPlugin(context)` | fn | Registers the OTP `AuthPlugin` into the server-auth plugin registry |
34
+ | `OTP_SERVICE` | const | `'auth-otp-service'` — the service alias `makeOtpService` registers under |
19
35
  | `OTP_AUTH_TYPE` | const | `'email-otp'` — the auth type string to pass in `init` requests |
20
36
  | `OTP_RESOURCE` | const | Redis resource alias for code storage |
21
37
  | `OTP_TTL_SECONDS` | const | Code TTL (600 s = 10 min) |
22
38
  | `OTP_CODE_LENGTH` | const | 6 |
39
+ | `SERVER_AUTH_OTP` | const | `'server-auth-otp'` — this package's own alias |
40
+ | `OtpConfig`, `OtpContext` | type | The `cfg.otp` overrides below, as a server config/context |
23
41
 
24
42
  ## Registration requirements
25
43
 
26
44
  ```ts
27
45
  import { makeOtpService, appendOtpPlugin, OTP_RESOURCE } from '@owlmeans/server-auth-otp'
28
46
  import { makeRedisResource } from '@owlmeans/redis-resource'
29
- import { makeConsoleMailerService, CONSOLE_MAILER, MAILER_SERVICE } from '@owlmeans/mailer'
47
+ import { makeDefaultConsoleMailerService, MAILER_SERVICE } from '@owlmeans/mailer'
30
48
  import { makeMailgunMailerService } from '@owlmeans/server-mailer-mailgun'
31
49
 
32
50
  // 1. Register the Redis code-cache resource.
33
51
  context.registerResource(makeRedisResource(OTP_RESOURCE))
34
52
 
35
- // 2. Register a MailerService (console for dev/tests, Mailgun for prod).
36
- context.registerService(makeConsoleMailerService(MAILER_SERVICE))
53
+ // 2. Register a MailerService under MAILER_SERVICE (console for dev/tests, Mailgun for prod).
54
+ context.registerService(makeDefaultConsoleMailerService())
37
55
  // or:
38
56
  context.registerService(makeMailgunMailerService(MAILER_SERVICE))
39
57
 
@@ -48,15 +66,21 @@ appendOtpPlugin(context)
48
66
 
49
67
  **Init** — client sends `{ type: 'email-otp', userId: 'user@email.com' }`:
50
68
  - OTP service generates a 6-digit code, stores it in Redis with 10 min TTL, emails it.
51
- - Returns `{ challenge: '<email>::<nonce>' }` in a signed envelope — see Gotchas below for why the
52
- nonce is required, not optional.
69
+ - Returns an opaque issuance id in a signed envelope. The id never contains the email or code.
53
70
 
54
71
  **Authenticate** — client sends `{ challenge: <signed-envelope>, userId: email, credential: '123456', type: 'email-otp', role: AuthRole.User, scopes: [ALL_SCOPES] }`:
55
- - Envelope is opened → `email::nonce` is extracted, split on `::` to recover the email (the nonce
56
- itself is discarded — it only exists to make the challenge unique, see Gotchas).
57
- - OTP service verifies the code (throws `AuthenFailed` if wrong or expired), then deletes it.
58
- - `IdentityLinkingService` finds or creates the user profile scoped to `entityId`.
59
- - Sets `credential.type = AuthenticationType.OneTimeToken` and returns the signed auth token.
72
+ - Envelope is opened → the plugin verifies the opaque issuance and code atomically. Five failed
73
+ attempts invalidate it; one concurrent correct verification can consume it.
74
+ - The `IdentityLinkingService` `cfg.otp.identityAlias` names answers the payload. The identity
75
+ store's own (`AUTH_IDENTITY_LINKING`) follows the e-mail code's credential to the person's
76
+ account, or finds the account by the address — the code becoming another credential on it — or
77
+ registers an account with a personal organization when the address is new; it answers the
78
+ deployment's own row in the account's main organization. An integrated provider's end-user login
79
+ names the e-mail proof linking service instead (`makeEmailProofLinkingService`,
80
+ `@owlmeans/iam-integrated`), which proves the address and writes nothing.
81
+ - Copies `userId`, `profileId`, `entitySlug`, `role` and `scopes` from the resolved payload onto the
82
+ credential, sets `credential.type = AuthenticationType.OneTimeToken`, and returns the signed auth
83
+ token.
60
84
  - `type`, `role`, `scopes` are required by the shared `AuthCredentialsSchema` (spread from
61
85
  `AuthPayloadSchema.required`) even though the OTP plugin overwrites `role`/`scopes`/`type` on
62
86
  success — a caller that omits them never reaches the plugin at all (see Gotchas).
@@ -75,27 +99,36 @@ cfg.otp = {
75
99
 
76
100
  ## Rules
77
101
 
78
- - Always register the Redis resource AND the mailer service BEFORE the OTP service.
102
+ - Always register the Redis challenge store, Redis throttle service, and mailer service BEFORE the
103
+ OTP service. Production uses `makeRedisOtpChallengeStore` and `makeRedisThrottleService`; memory
104
+ implementations are local/test defaults only.
79
105
  - Call `appendOtpPlugin(context)` once per context — it adds to the shared plugin registry singleton.
80
- - The `credential.entityId` in the authenticate request determines which entity the resulting identity profile is scoped to. Pass it from the OIDC interaction.
106
+ - `credential.entitySlug` on the authenticate request **selects nothing**. The plugin copies it into
107
+ the linking details as `clientId` (defaulting to `'default'`) and `entityId`, and
108
+ `@owlmeans/server-auth-identity` reads neither: `getLinkedProfile` keys on the credential built
109
+ from the auth type, the `'email'` service and the address, and `linkProfile` lands on the one
110
+ account of that address (registering it with a personal organization when it is new). Whatever
111
+ the caller sent is then overwritten with the linked payload's own slug before the envelope is
112
+ signed, so the address alone decides which account and which organization the token names.
81
113
  - Errors from this plugin are `AuthenFailed` (from `@owlmeans/auth`) — callers catch that, not raw `Error`.
82
- - For tests, use `makeConsoleMailerService()` and read `svc.captured[n].text` to extract the code.
114
+ - Use the email throttle for the public integrated-IAM flow: one issuance per minute and ten per
115
+ hour, with a 429 and Retry-After. The companion IP throttle is available for an ingress that
116
+ safely supplies a normalized client address; throttle keys hash email/IP values and never store
117
+ the raw identifier.
118
+ - For tests, register `makeDefaultConsoleMailerService()` and read `svc.captured[n].text` to extract
119
+ the code. Bare `makeConsoleMailerService()` registers under `CONSOLE_MAILER` (`'console-mailer'`),
120
+ which is not the alias `makeOtpService` resolves — it looks up `cfg.otp?.mailerAlias ?? MAILER_SERVICE`.
83
121
 
84
122
  ## Gotchas
85
123
 
86
- - **The challenge must never be just the plaintext email.** The auth manager's anti-replay guard
87
- (`AUTH_CACHE` in `@owlmeans/server-auth`) burns the *decoded* challenge into a Redis
88
- create-once record before the plugin's own credential check runs. If `init()` returned the bare
89
- email, that decoded value would be identical across every independent login attempt for the same
90
- address, so a second legitimate login within the cache TTL (`AUTHEN_TIMEFRAME`, 10 min) — right
91
- code or wrong — collides with the still-cached prior attempt and throws
92
- `AuthenFailed('challenge')` (a `RecordExists` underneath), not an OTP-specific error. Fix: `init()`
93
- appends a fresh `createIdOfLength(16, IdStyle.Base58)` nonce (`'<email>::<nonce>'`); `authenticate()`
94
- splits it back apart. Never revert to a bare-email challenge.
124
+ - **The OTP challenge must be opaque and plugin-owned.** The generic auth-manager replay policy
125
+ does not consume it before the OTP store can count attempts; the plugin atomically owns verify
126
+ and consume. Never encode the email or code in the issuance id, and never replace the bounded
127
+ attempt counter with a bare auth-cache replay key.
95
128
  - **`AuthCredentialsSchema.credential` has a `minLength` floor** (from `@owlmeans/auth`) sized for
96
129
  long tokens/signatures from other plugins (Ed25519 signature, OAuth code). A 6-digit OTP code is
97
- legitimately shorter — the schema's floor must stay low enough (`minLength: 1` as of this
98
- writing) to admit it, or every authenticate call 400s before the plugin ever runs.
130
+ legitimately shorter — the floor is `minLength: 1` and must stay low enough to admit it, or every
131
+ authenticate call 400s before the plugin ever runs.
99
132
  - **`scopes`/`role`/`type` are schema-required on the authenticate body**, spread from
100
133
  `AuthPayloadSchema.required` into `AuthCredentialsSchema` — even though this plugin overwrites
101
134
  all three on success. A caller built without going through `@owlmeans/client-auth`'s
@@ -106,10 +139,11 @@ cfg.otp = {
106
139
  accepts this token (e.g. an OIDC `PROVIDER_INTERACTION` finalizer) must size its own `token`
107
140
  field schema accordingly; the generic `AuthTokenSchema` (`maxLength: 1024`) is too small.
108
141
 
109
- ## Related instructions
142
+ ## Related
110
143
 
111
- - `@owlmeans/auth-otp` (common) — `OtpService` interface and constants
112
- - `@owlmeans/mailer` (common) — `MailerService` interface, console transport
113
- - `@owlmeans/server-mailer-mailgun` (common) — production Mailgun transport
114
- - `@owlmeans/server-auth` (common) — auth-manager plugin system
115
- - `auth-protocol` instructions — error hierarchy, identity read rules
144
+ - `@owlmeans/auth-otp` — the `OtpService` interface and the shared constants
145
+ - `@owlmeans/mailer` — `MailerService`, the console transport
146
+ - `@owlmeans/server-mailer-mailgun` — the production Mailgun transport
147
+ - `server-auth` skill — the auth-manager plugin system this plugin registers into
148
+ - `server-auth-identity` skill — how the linked profile and its organization entity are stored
149
+ - `auth-protocol` skill — error hierarchy and identity read rules
@@ -0,0 +1,7 @@
1
+ import type { OtpChallengeStore } from './types.js';
2
+ import type { Clock } from './types.local.js';
3
+ /** Real in-memory challenge store with synchronous consume/update semantics. */
4
+ export declare const makeMemoryOtpChallengeStore: (alias?: string, now?: Clock) => OtpChallengeStore;
5
+ /** Redis challenge store: compare, attempt increment, exhaustion, and consume are one operation. */
6
+ export declare const makeRedisOtpChallengeStore: (alias?: string, resourceAlias?: string) => OtpChallengeStore;
7
+ //# sourceMappingURL=challenge.d.ts.map
@@ -0,0 +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"}
@@ -0,0 +1,77 @@
1
+ import { appendContextual, createService } from '@owlmeans/context';
2
+ import { OtpUnavailable } from './errors.js';
3
+ import { OTP_CHALLENGE_STORE, OTP_RESOURCE, OtpChallengeOutcome as Outcome } from './consts.js';
4
+ import { REDIS_VERIFY_SCRIPT } from './consts.local.js';
5
+ /** Real in-memory challenge store with synchronous consume/update semantics. */
6
+ export const makeMemoryOtpChallengeStore = (alias = OTP_CHALLENGE_STORE, now = Date.now) => {
7
+ const records = new Map();
8
+ return createService(alias, {
9
+ issue: async (challenge, ttlSeconds) => {
10
+ const current = records.get(challenge.id);
11
+ if (current != null && current.expiresAt > now())
12
+ return false;
13
+ records.set(challenge.id, {
14
+ ...challenge, failedAttempts: 0, expiresAt: now() + ttlSeconds * 1000,
15
+ });
16
+ return true;
17
+ },
18
+ verify: async (id, emailKey, codeHash, maxFailedAttempts) => {
19
+ const record = records.get(id);
20
+ if (record == null || record.expiresAt <= now()) {
21
+ records.delete(id);
22
+ return Outcome.Missing;
23
+ }
24
+ if (record.emailKey === emailKey && record.codeHash === codeHash) {
25
+ records.delete(id);
26
+ return Outcome.Verified;
27
+ }
28
+ record.failedAttempts += 1;
29
+ if (record.failedAttempts >= maxFailedAttempts) {
30
+ records.delete(id);
31
+ return Outcome.Exhausted;
32
+ }
33
+ return Outcome.Invalid;
34
+ },
35
+ });
36
+ };
37
+ /** Redis challenge store: compare, attempt increment, exhaustion, and consume are one operation. */
38
+ export const makeRedisOtpChallengeStore = (alias = OTP_CHALLENGE_STORE, resourceAlias = OTP_RESOURCE) => {
39
+ const service = appendContextual(alias, {
40
+ issue: async (challenge, ttlSeconds) => {
41
+ const ctx = service.ctx;
42
+ const resource = ctx.resource(resourceAlias);
43
+ try {
44
+ const result = await resource.db.client.set(resource.key(challenge.id), JSON.stringify({ ...challenge, failedAttempts: 0 }), 'EX', ttlSeconds, 'NX');
45
+ return result === 'OK';
46
+ }
47
+ catch (error) {
48
+ const unavailable = new OtpUnavailable('challenge');
49
+ if (error instanceof Error)
50
+ unavailable.oiriginalStack = `${error}: ${error.stack}`;
51
+ throw unavailable;
52
+ }
53
+ },
54
+ verify: async (id, emailKey, codeHash, maxFailedAttempts) => {
55
+ const ctx = service.ctx;
56
+ const resource = ctx.resource(resourceAlias);
57
+ try {
58
+ const result = Number(await resource.db.client.eval(REDIS_VERIFY_SCRIPT, 1, resource.key(id), emailKey, codeHash, String(maxFailedAttempts)));
59
+ if (result === 1)
60
+ return Outcome.Verified;
61
+ if (result === -1)
62
+ return Outcome.Invalid;
63
+ if (result === -2)
64
+ return Outcome.Exhausted;
65
+ return Outcome.Missing;
66
+ }
67
+ catch (error) {
68
+ const unavailable = new OtpUnavailable('challenge');
69
+ if (error instanceof Error)
70
+ unavailable.oiriginalStack = `${error}: ${error.stack}`;
71
+ throw unavailable;
72
+ }
73
+ },
74
+ });
75
+ return service;
76
+ };
77
+ //# sourceMappingURL=challenge.js.map
@@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CAAC;QACH,CAAC;KACF,CAAC,CAAA;IAEF,OAAO,OAAO,CAAA;AAChB,CAAC,CAAA"}
package/build/consts.d.ts CHANGED
@@ -1,4 +1,19 @@
1
1
  export declare const SERVER_AUTH_OTP = "server-auth-otp";
2
+ export declare const OTP_CHALLENGE_STORE = "auth-otp-challenge-store";
3
+ export declare const OTP_THROTTLE_SERVICE = "auth-otp-throttle";
4
+ export declare const OTP_EMAIL_THROTTLE_RULES: readonly (Readonly<{
5
+ limit: 1;
6
+ windowSeconds: 60;
7
+ }> | Readonly<{
8
+ limit: 10;
9
+ windowSeconds: number;
10
+ }>)[];
2
11
  /** The OTP auth plugin type key — passed as credential.type in init requests */
3
- export { OTP_AUTH_TYPE, OTP_SERVICE, OTP_RESOURCE, OTP_TTL_SECONDS, OTP_CODE_LENGTH } from '@owlmeans/auth-otp';
12
+ export { OTP_AUTH_TYPE, OTP_SERVICE, OTP_RESOURCE, OTP_TTL_SECONDS, OTP_CODE_LENGTH, OTP_MAX_FAILED_ATTEMPTS, } from '@owlmeans/auth-otp';
13
+ export declare enum OtpChallengeOutcome {
14
+ Verified = "verified",
15
+ Invalid = "invalid",
16
+ Exhausted = "exhausted",
17
+ Missing = "missing"
18
+ }
4
19
  //# sourceMappingURL=consts.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"consts.d.ts","sourceRoot":"","sources":["../src/consts.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,eAAe,oBAAoB,CAAA;AAEhD,gFAAgF;AAChF,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,YAAY,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA"}
1
+ {"version":3,"file":"consts.d.ts","sourceRoot":"","sources":["../src/consts.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,eAAe,oBAAoB,CAAA;AAChD,eAAO,MAAM,mBAAmB,6BAA6B,CAAA;AAC7D,eAAO,MAAM,oBAAoB,sBAAsB,CAAA;AAEvD,eAAO,MAAM,wBAAwB;;;;;;KAGnC,CAAA;AAEF,gFAAgF;AAChF,OAAO,EACL,aAAa,EAAE,WAAW,EAAE,YAAY,EAAE,eAAe,EAAE,eAAe,EAC1E,uBAAuB,GACxB,MAAM,oBAAoB,CAAA;AAE3B,oBAAY,mBAAmB;IAC7B,QAAQ,aAAa;IACrB,OAAO,YAAY;IACnB,SAAS,cAAc;IACvB,OAAO,YAAY;CACpB"}
package/build/consts.js CHANGED
@@ -1,4 +1,17 @@
1
1
  export const SERVER_AUTH_OTP = 'server-auth-otp';
2
+ export const OTP_CHALLENGE_STORE = 'auth-otp-challenge-store';
3
+ export const OTP_THROTTLE_SERVICE = 'auth-otp-throttle';
4
+ export const OTP_EMAIL_THROTTLE_RULES = Object.freeze([
5
+ Object.freeze({ limit: 1, windowSeconds: 60 }),
6
+ Object.freeze({ limit: 10, windowSeconds: 60 * 60 }),
7
+ ]);
2
8
  /** The OTP auth plugin type key — passed as credential.type in init requests */
3
- export { OTP_AUTH_TYPE, OTP_SERVICE, OTP_RESOURCE, OTP_TTL_SECONDS, OTP_CODE_LENGTH } from '@owlmeans/auth-otp';
9
+ export { OTP_AUTH_TYPE, OTP_SERVICE, OTP_RESOURCE, OTP_TTL_SECONDS, OTP_CODE_LENGTH, OTP_MAX_FAILED_ATTEMPTS, } from '@owlmeans/auth-otp';
10
+ export var OtpChallengeOutcome;
11
+ (function (OtpChallengeOutcome) {
12
+ OtpChallengeOutcome["Verified"] = "verified";
13
+ OtpChallengeOutcome["Invalid"] = "invalid";
14
+ OtpChallengeOutcome["Exhausted"] = "exhausted";
15
+ OtpChallengeOutcome["Missing"] = "missing";
16
+ })(OtpChallengeOutcome || (OtpChallengeOutcome = {}));
4
17
  //# sourceMappingURL=consts.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"consts.js","sourceRoot":"","sources":["../src/consts.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,eAAe,GAAG,iBAAiB,CAAA;AAEhD,gFAAgF;AAChF,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,YAAY,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA"}
1
+ {"version":3,"file":"consts.js","sourceRoot":"","sources":["../src/consts.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,eAAe,GAAG,iBAAiB,CAAA;AAChD,MAAM,CAAC,MAAM,mBAAmB,GAAG,0BAA0B,CAAA;AAC7D,MAAM,CAAC,MAAM,oBAAoB,GAAG,mBAAmB,CAAA;AAEvD,MAAM,CAAC,MAAM,wBAAwB,GAAG,MAAM,CAAC,MAAM,CAAC;IACpD,MAAM,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,aAAa,EAAE,EAAE,EAAE,CAAC;IAC9C,MAAM,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,aAAa,EAAE,EAAE,GAAG,EAAE,EAAE,CAAC;CACrD,CAAC,CAAA;AAEF,gFAAgF;AAChF,OAAO,EACL,aAAa,EAAE,WAAW,EAAE,YAAY,EAAE,eAAe,EAAE,eAAe,EAC1E,uBAAuB,GACxB,MAAM,oBAAoB,CAAA;AAE3B,MAAM,CAAN,IAAY,mBAKX;AALD,WAAY,mBAAmB;IAC7B,4CAAqB,CAAA;IACrB,0CAAmB,CAAA;IACnB,8CAAuB,CAAA;IACvB,0CAAmB,CAAA;AACrB,CAAC,EALW,mBAAmB,KAAnB,mBAAmB,QAK9B"}
@@ -0,0 +1,4 @@
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
+ export declare const CHALLENGE_DELIMITER = "::";
3
+ 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
+ //# sourceMappingURL=consts.local.d.ts.map
@@ -0,0 +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"}
@@ -0,0 +1,50 @@
1
+ export const REDIS_VERIFY_SCRIPT = `
2
+ local raw = redis.call('GET', KEYS[1])
3
+ if not raw then return 0 end
4
+ local record = cjson.decode(raw)
5
+ if record.emailKey == ARGV[1] and record.codeHash == ARGV[2] then
6
+ redis.call('DEL', KEYS[1])
7
+ return 1
8
+ end
9
+ record.failedAttempts = tonumber(record.failedAttempts or 0) + 1
10
+ if record.failedAttempts >= tonumber(ARGV[3]) then
11
+ redis.call('DEL', KEYS[1])
12
+ return -2
13
+ end
14
+ local ttl = redis.call('PTTL', KEYS[1])
15
+ if ttl <= 0 then
16
+ redis.call('DEL', KEYS[1])
17
+ return 0
18
+ end
19
+ redis.call('SET', KEYS[1], cjson.encode(record), 'XX', 'PX', ttl)
20
+ return -1
21
+ `;
22
+ // Separates the email from the opaque issuance id inside the signed challenge.
23
+ export const CHALLENGE_DELIMITER = '::';
24
+ export const REDIS_THROTTLE_SCRIPT = `
25
+ local time = redis.call('TIME')
26
+ local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
27
+ local retry = 0
28
+ for index = 1, #KEYS do
29
+ local offset = (index - 1) * 2
30
+ local limit = tonumber(ARGV[offset + 1])
31
+ local window = tonumber(ARGV[offset + 2])
32
+ redis.call('ZREMRANGEBYSCORE', KEYS[index], '-inf', now - window)
33
+ local count = redis.call('ZCARD', KEYS[index])
34
+ if count >= limit then
35
+ local oldest = redis.call('ZRANGE', KEYS[index], 0, 0, 'WITHSCORES')
36
+ if #oldest == 2 then
37
+ retry = math.max(retry, math.ceil((tonumber(oldest[2]) + window - now) / 1000))
38
+ end
39
+ end
40
+ end
41
+ if retry > 0 then return {0, retry} end
42
+ local token = ARGV[#KEYS * 2 + 1]
43
+ for index = 1, #KEYS do
44
+ local window = tonumber(ARGV[(index - 1) * 2 + 2])
45
+ redis.call('ZADD', KEYS[index], now, token .. ':' .. index)
46
+ redis.call('PEXPIRE', KEYS[index], window)
47
+ end
48
+ return {1, 0}
49
+ `;
50
+ //# sourceMappingURL=consts.local.js.map
@@ -0,0 +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"}
@@ -0,0 +1,18 @@
1
+ import { ResilientError } from '@owlmeans/error';
2
+ export declare class OtpError extends ResilientError {
3
+ static typeName: string;
4
+ constructor(message?: string);
5
+ }
6
+ export declare class OtpThrottled extends OtpError {
7
+ static typeName: string;
8
+ static httpStatus: number;
9
+ readonly retryAfter: number;
10
+ constructor(retryAfter?: number | string, stack?: string);
11
+ }
12
+ export declare class OtpUnavailable extends OtpError {
13
+ static typeName: string;
14
+ static httpStatus: number;
15
+ static allowServerErrorStatus: boolean;
16
+ constructor(message?: string);
17
+ }
18
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAEhD,qBAAa,QAAS,SAAQ,cAAc;IAC1C,OAAuB,QAAQ,SAAa;IAE5C,YAAY,OAAO,GAAE,MAAgB,EAEpC;CACF;AAED,qBAAa,YAAa,SAAQ,QAAQ;IACxC,OAAuB,QAAQ,SAAkC;IACjE,OAAc,UAAU,SAAM;IAC9B,SAAgB,UAAU,EAAE,MAAM,CAAA;IAElC,YAAY,UAAU,GAAE,MAAM,GAAG,MAAU,EAAE,KAAK,CAAC,EAAE,MAAM,EAK1D;CACF;AAED,qBAAa,cAAe,SAAQ,QAAQ;IAC1C,OAAuB,QAAQ,SAAoC;IACnE,OAAc,UAAU,SAAM;IAC9B,OAAc,sBAAsB,UAAO;IAE3C,YAAY,OAAO,GAAE,MAAgB,EAGpC;CACF"}