@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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owlmeans/server-auth-otp",
3
- "version": "0.1.18-rc.8",
3
+ "version": "0.1.18",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -22,21 +22,22 @@
22
22
  }
23
23
  },
24
24
  "dependencies": {
25
- "@owlmeans/auth": "^0.1.18-rc.6",
26
- "@owlmeans/auth-otp": "^0.1.18-rc.6",
27
- "@owlmeans/basic-ids": "^0.1.18-rc.6",
28
- "@owlmeans/context": "^0.1.18-rc.6",
29
- "@owlmeans/mailer": "^0.1.18-rc.6",
30
- "@owlmeans/oidc": "^0.1.18-rc.6",
31
- "@owlmeans/redis-resource": "^0.1.18-rc.6",
32
- "@owlmeans/resource": "^0.1.18-rc.6",
33
- "@owlmeans/server-auth": "^0.1.18-rc.8",
34
- "@owlmeans/server-auth-identity": "^0.1.18-rc.6",
35
- "@owlmeans/server-context": "^0.1.18-rc.6"
25
+ "@owlmeans/auth": "^0.1.18",
26
+ "@owlmeans/auth-otp": "^0.1.18",
27
+ "@owlmeans/context": "^0.1.18",
28
+ "@owlmeans/error": "^0.1.18",
29
+ "@owlmeans/log": "^0.1.18",
30
+ "@owlmeans/mailer": "^0.1.18",
31
+ "@owlmeans/oidc": "^0.1.18",
32
+ "@owlmeans/redis-resource": "^0.1.18",
33
+ "@owlmeans/resource": "^0.1.18",
34
+ "@owlmeans/server-auth": "^0.1.18",
35
+ "@owlmeans/server-auth-identity": "^0.1.18",
36
+ "@owlmeans/server-context": "^0.1.18"
36
37
  },
37
38
  "devDependencies": {
38
- "@owlmeans/dep-config": "workspace:*",
39
- "@types/bun": "^1.3.14",
39
+ "@owlmeans/dep-config": "^0.1.18",
40
+ "@types/bun": "^1.4.2",
40
41
  "nodemon": "^3.1.14",
41
42
  "typescript": "^7.0.2"
42
43
  },
@@ -0,0 +1,86 @@
1
+ import { appendContextual, createService } from '@owlmeans/context'
2
+ import type { RedisResource } from '@owlmeans/redis-resource'
3
+ import { OtpUnavailable } from './errors.js'
4
+ import { OTP_CHALLENGE_STORE, OTP_RESOURCE, type OtpChallengeOutcome, OtpChallengeOutcome as Outcome } from './consts.js'
5
+ import type { OtpChallengeStore, OtpConfig, OtpContext } from './types.js'
6
+ import { REDIS_VERIFY_SCRIPT } from './consts.local.js'
7
+ import type { ChallengeResourceRecord, Clock, StoredChallenge } from './types.local.js'
8
+
9
+
10
+ /** Real in-memory challenge store with synchronous consume/update semantics. */
11
+ export const makeMemoryOtpChallengeStore = (
12
+ alias = OTP_CHALLENGE_STORE, now: Clock = Date.now
13
+ ): OtpChallengeStore => {
14
+ const records = new Map<string, StoredChallenge>()
15
+
16
+ return createService<OtpChallengeStore>(alias, {
17
+ issue: async (challenge, ttlSeconds): Promise<boolean> => {
18
+ const current = records.get(challenge.id)
19
+ if (current != null && current.expiresAt > now()) return false
20
+ records.set(challenge.id, {
21
+ ...challenge, failedAttempts: 0, expiresAt: now() + ttlSeconds * 1000,
22
+ })
23
+ return true
24
+ },
25
+ verify: async (id, emailKey, codeHash, maxFailedAttempts): Promise<OtpChallengeOutcome> => {
26
+ const record = records.get(id)
27
+ if (record == null || record.expiresAt <= now()) {
28
+ records.delete(id)
29
+ return Outcome.Missing
30
+ }
31
+ if (record.emailKey === emailKey && record.codeHash === codeHash) {
32
+ records.delete(id)
33
+ return Outcome.Verified
34
+ }
35
+ record.failedAttempts += 1
36
+ if (record.failedAttempts >= maxFailedAttempts) {
37
+ records.delete(id)
38
+ return Outcome.Exhausted
39
+ }
40
+
41
+ return Outcome.Invalid
42
+ },
43
+ })
44
+ }
45
+
46
+ /** Redis challenge store: compare, attempt increment, exhaustion, and consume are one operation. */
47
+ export const makeRedisOtpChallengeStore = (
48
+ alias = OTP_CHALLENGE_STORE, resourceAlias = OTP_RESOURCE
49
+ ): OtpChallengeStore => {
50
+ const service = appendContextual<OtpChallengeStore>(alias, {
51
+ issue: async (challenge, ttlSeconds): Promise<boolean> => {
52
+ const ctx = service.ctx as OtpContext<OtpConfig>
53
+ const resource = ctx.resource<RedisResource<ChallengeResourceRecord>>(resourceAlias)
54
+ try {
55
+ const result = await resource.db.client.set(
56
+ resource.key(challenge.id), JSON.stringify({ ...challenge, failedAttempts: 0 }),
57
+ 'EX', ttlSeconds, 'NX'
58
+ )
59
+ return result === 'OK'
60
+ } catch (error) {
61
+ const unavailable = new OtpUnavailable('challenge')
62
+ if (error instanceof Error) unavailable.oiriginalStack = `${error}: ${error.stack}`
63
+ throw unavailable
64
+ }
65
+ },
66
+ verify: async (id, emailKey, codeHash, maxFailedAttempts): Promise<OtpChallengeOutcome> => {
67
+ const ctx = service.ctx as OtpContext<OtpConfig>
68
+ const resource = ctx.resource<RedisResource<ChallengeResourceRecord>>(resourceAlias)
69
+ try {
70
+ const result = Number(await resource.db.client.eval(
71
+ REDIS_VERIFY_SCRIPT, 1, resource.key(id), emailKey, codeHash, String(maxFailedAttempts)
72
+ ))
73
+ if (result === 1) return Outcome.Verified
74
+ if (result === -1) return Outcome.Invalid
75
+ if (result === -2) return Outcome.Exhausted
76
+ return Outcome.Missing
77
+ } catch (error) {
78
+ const unavailable = new OtpUnavailable('challenge')
79
+ if (error instanceof Error) unavailable.oiriginalStack = `${error}: ${error.stack}`
80
+ throw unavailable
81
+ }
82
+ },
83
+ })
84
+
85
+ return service
86
+ }
@@ -0,0 +1,51 @@
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
+
23
+ // Separates the email from the opaque issuance id inside the signed challenge.
24
+ export const CHALLENGE_DELIMITER = '::'
25
+
26
+ export const REDIS_THROTTLE_SCRIPT = `
27
+ local time = redis.call('TIME')
28
+ local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
29
+ local retry = 0
30
+ for index = 1, #KEYS do
31
+ local offset = (index - 1) * 2
32
+ local limit = tonumber(ARGV[offset + 1])
33
+ local window = tonumber(ARGV[offset + 2])
34
+ redis.call('ZREMRANGEBYSCORE', KEYS[index], '-inf', now - window)
35
+ local count = redis.call('ZCARD', KEYS[index])
36
+ if count >= limit then
37
+ local oldest = redis.call('ZRANGE', KEYS[index], 0, 0, 'WITHSCORES')
38
+ if #oldest == 2 then
39
+ retry = math.max(retry, math.ceil((tonumber(oldest[2]) + window - now) / 1000))
40
+ end
41
+ end
42
+ end
43
+ if retry > 0 then return {0, retry} end
44
+ local token = ARGV[#KEYS * 2 + 1]
45
+ for index = 1, #KEYS do
46
+ local window = tonumber(ARGV[(index - 1) * 2 + 2])
47
+ redis.call('ZADD', KEYS[index], now, token .. ':' .. index)
48
+ redis.call('PEXPIRE', KEYS[index], window)
49
+ end
50
+ return {1, 0}
51
+ `
package/src/consts.ts CHANGED
@@ -1,4 +1,21 @@
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
+
5
+ export const OTP_EMAIL_THROTTLE_RULES = Object.freeze([
6
+ Object.freeze({ limit: 1, windowSeconds: 60 }),
7
+ Object.freeze({ limit: 10, windowSeconds: 60 * 60 }),
8
+ ])
2
9
 
3
10
  /** The OTP auth plugin type key — passed as credential.type in init requests */
4
- export { OTP_AUTH_TYPE, OTP_SERVICE, OTP_RESOURCE, OTP_TTL_SECONDS, OTP_CODE_LENGTH } from '@owlmeans/auth-otp'
11
+ export {
12
+ OTP_AUTH_TYPE, OTP_SERVICE, OTP_RESOURCE, OTP_TTL_SECONDS, OTP_CODE_LENGTH,
13
+ OTP_MAX_FAILED_ATTEMPTS,
14
+ } from '@owlmeans/auth-otp'
15
+
16
+ export enum OtpChallengeOutcome {
17
+ Verified = 'verified',
18
+ Invalid = 'invalid',
19
+ Exhausted = 'exhausted',
20
+ Missing = 'missing',
21
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { ResilientError } from '@owlmeans/error'
2
+
3
+ export class OtpError extends ResilientError {
4
+ public static override typeName = 'OtpError'
5
+
6
+ constructor(message: string = 'error') {
7
+ super(OtpError.typeName, `otp:${message}`)
8
+ }
9
+ }
10
+
11
+ export class OtpThrottled extends OtpError {
12
+ public static override typeName = `${OtpError.typeName}Throttled`
13
+ public static httpStatus = 429
14
+ public readonly retryAfter: number
15
+
16
+ constructor(retryAfter: number | string = 1, stack?: string) {
17
+ super(typeof retryAfter === 'string' ? retryAfter : 'throttled')
18
+ this.type = OtpThrottled.typeName
19
+ this.retryAfter = typeof retryAfter === 'number' ? Math.max(1, Math.ceil(retryAfter)) : 1
20
+ if (stack != null) this.oiriginalStack = stack
21
+ }
22
+ }
23
+
24
+ export class OtpUnavailable extends OtpError {
25
+ public static override typeName = `${OtpError.typeName}Unavailable`
26
+ public static httpStatus = 503
27
+ public static allowServerErrorStatus = true
28
+
29
+ constructor(message: string = 'store') {
30
+ super(`unavailable:${message}`)
31
+ this.type = OtpUnavailable.typeName
32
+ }
33
+ }
34
+
35
+ ResilientError.registerErrorClass(OtpError)
36
+ ResilientError.registerErrorClass(OtpThrottled)
37
+ ResilientError.registerErrorClass(OtpUnavailable)
package/src/index.ts CHANGED
@@ -1,4 +1,11 @@
1
- export type * from './types.js'
1
+ export * from './types.js'
2
+ export type * from './keys/types.js'
3
+ export type * from './throttle-keys/types.js'
2
4
  export * from './consts.js'
3
5
  export * from './service.js'
4
6
  export * from './plugin.js'
7
+ export * from './errors.js'
8
+ export * from './throttle.js'
9
+ export * from './challenge.js'
10
+ export * from './keys.js'
11
+ export * from './throttle-keys.js'
@@ -0,0 +1,9 @@
1
+ /** The storage keys of one OTP issuance: digests, never the raw address, id or code. */
2
+ export interface OtpKeyHelper {
3
+ /** The challenge record key of an issuance id. */
4
+ otpChallengeKey: (issuanceId: string) => string
5
+ /** The case-insensitive digest of the address a code was sent to. */
6
+ otpEmailKey: (email: string) => string
7
+ /** The digest of a code, bound to its issuance. */
8
+ otpCodeHash: (issuanceId: string, code: string) => string
9
+ }
package/src/keys.ts ADDED
@@ -0,0 +1,16 @@
1
+ import { createHash } from 'node:crypto'
2
+ import type { OtpKeyHelper } from './keys/types.js'
3
+
4
+ const digest = (scope: string, value: string): string =>
5
+ createHash('sha256').update(`owlmeans:otp:${scope}\0${value}`).digest('hex')
6
+
7
+ export const createOtpKeyHelper = (): OtpKeyHelper => {
8
+ const otpChallengeKey = (issuanceId: string): string => `challenge:${digest('issuance', issuanceId)}`
9
+ const otpEmailKey = (email: string): string => digest('email', email.trim().toLowerCase())
10
+ const otpCodeHash = (issuanceId: string, code: string): string =>
11
+ digest('code', `${issuanceId}\0${code.trim()}`)
12
+
13
+ return { otpChallengeKey, otpEmailKey, otpCodeHash }
14
+ }
15
+
16
+ export const otpKeyHelper = createOtpKeyHelper()
package/src/plugin.ts CHANGED
@@ -1,19 +1,14 @@
1
1
  import { ALL_SCOPES, AuthenFailed, AuthRole, AuthenticationType } from '@owlmeans/auth'
2
- import type { AuthPlugin } from '@owlmeans/server-auth/manager/plugins'
3
- import { registerPlugin } from '@owlmeans/server-auth/manager/plugins'
4
- import type { OtpService } from '@owlmeans/auth-otp'
5
- import { OTP_AUTH_TYPE, OTP_SERVICE } from '@owlmeans/auth-otp'
6
- import type { IdentityLinkingService } from '@owlmeans/server-auth-identity'
7
- import { AUTH_IDENTITY_LINKING } from '@owlmeans/server-auth-identity'
8
- import { createIdOfLength, IdStyle } from '@owlmeans/basic-ids'
2
+ import { type AuthPlugin, type AuthPluginFactory, AuthChallengeReplayPolicy, registerPlugin } from '@owlmeans/server-auth/manager/plugins'
3
+ import { type OtpService, OTP_AUTH_TYPE, OTP_SERVICE } from '@owlmeans/auth-otp'
4
+ import { type IdentityLinkingService, AUTH_IDENTITY_LINKING } from '@owlmeans/server-auth-identity'
9
5
  import type { OtpConfig, OtpContext } from './types.js'
10
-
11
- // Separates the email from the per-request nonce inside the challenge (see init() below).
12
- const CHALLENGE_DELIMITER = '::'
6
+ import { CHALLENGE_DELIMITER } from './consts.local.js'
13
7
 
14
8
  /** Factory that creates the email-OTP AuthPlugin bound to the given context. */
15
9
  const otpPlugin = <C extends OtpConfig, T extends OtpContext<C>>(context: T): AuthPlugin => ({
16
10
  type: OTP_AUTH_TYPE,
11
+ challengeReplayPolicy: AuthChallengeReplayPolicy.Plugin,
17
12
 
18
13
  init: async request => {
19
14
  if (request.userId == null || !request.userId.includes('@')) {
@@ -21,20 +16,18 @@ const otpPlugin = <C extends OtpConfig, T extends OtpContext<C>>(context: T): Au
21
16
  }
22
17
  const email = request.userId.trim().toLowerCase()
23
18
  const otp = context.service<OtpService>(OTP_SERVICE)
24
- await otp.issueChallenge(email)
25
- // The auth manager's anti-replay cache (AUTH_CACHE) keys on this decoded challenge, so it
26
- // must be unique per request — the plaintext email alone would be identical across every
27
- // independent login attempt for that address and collide with a still-cached prior one.
28
- const nonce = createIdOfLength(16, IdStyle.Base58)
29
- return { challenge: `${email}${CHALLENGE_DELIMITER}${nonce}` }
19
+ const issuanceId = await otp.issueChallenge(email)
20
+ return { challenge: `${email}${CHALLENGE_DELIMITER}${issuanceId}` }
30
21
  },
31
22
 
32
23
  authenticate: async credential => {
33
- // credential.challenge is "email::nonce" (opened from the signed envelope in makeAuthModel).
34
- const email = credential.challenge?.split(CHALLENGE_DELIMITER)[0]
24
+ // credential.challenge is "email::issuanceId" (opened from the signed envelope).
25
+ const parts = credential.challenge?.split(CHALLENGE_DELIMITER) ?? []
26
+ const email = parts.length === 2 ? parts[0] : undefined
27
+ const issuanceId = parts.length === 2 ? parts[1] : undefined
35
28
  const code = credential.credential
36
29
 
37
- if (!email || !email.includes('@')) {
30
+ if (!email || !email.includes('@') || !issuanceId) {
38
31
  throw new AuthenFailed('otp:email')
39
32
  }
40
33
  if (!code) {
@@ -42,18 +35,21 @@ const otpPlugin = <C extends OtpConfig, T extends OtpContext<C>>(context: T): Au
42
35
  }
43
36
 
44
37
  const otp = context.service<OtpService>(OTP_SERVICE)
45
- await otp.verifyChallenge(email, code)
38
+ await otp.verifyChallenge(email, issuanceId, code)
46
39
 
47
40
  const identityAlias = (context.cfg as any).otp?.identityAlias ?? AUTH_IDENTITY_LINKING
48
41
  const identity = context.service<IdentityLinkingService>(identityAlias)
49
42
 
50
- const entityId = credential.entityId
43
+ // What arrives on the credential is the organization SLUG the user is logging into — it is
44
+ // what a person can be asked to type. The linked profile below answers with the canonical
45
+ // slug, which is what the token ends up carrying.
46
+ const entitySlug = credential.entitySlug
51
47
  const details = {
52
48
  type: OTP_AUTH_TYPE,
53
49
  service: 'email',
54
- clientId: entityId ?? 'default',
50
+ clientId: entitySlug ?? 'default',
55
51
  userId: email,
56
- entityId,
52
+ entityId: entitySlug,
57
53
  }
58
54
 
59
55
  let payload = await identity.getLinkedProfile(details)
@@ -65,7 +61,7 @@ const otpPlugin = <C extends OtpConfig, T extends OtpContext<C>>(context: T): Au
65
61
  credential.type = AuthenticationType.OneTimeToken
66
62
  credential.userId = payload.userId
67
63
  credential.profileId = payload.profileId
68
- credential.entityId = payload.entityId
64
+ credential.entitySlug = payload.entitySlug
69
65
  credential.role = payload.role ?? AuthRole.User
70
66
  credential.scopes = payload.scopes ?? [ALL_SCOPES]
71
67
 
@@ -75,6 +71,6 @@ const otpPlugin = <C extends OtpConfig, T extends OtpContext<C>>(context: T): Au
75
71
 
76
72
  /** Register the email-OTP plugin into the server-auth plugin registry. Call once at context setup. */
77
73
  export const appendOtpPlugin = <C extends OtpConfig, T extends OtpContext<C>>(context: T): T => {
78
- registerPlugin(OTP_AUTH_TYPE, otpPlugin as Parameters<typeof registerPlugin>[1])
74
+ registerPlugin(OTP_AUTH_TYPE, otpPlugin as AuthPluginFactory)
79
75
  return context
80
76
  }
package/src/service.ts CHANGED
@@ -1,39 +1,74 @@
1
1
  import { appendContextual } from '@owlmeans/context'
2
2
  import { AuthenFailed } from '@owlmeans/auth'
3
- import type { OtpService } from '@owlmeans/auth-otp'
4
- import { OTP_SERVICE, OTP_RESOURCE, OTP_TTL_SECONDS, OTP_CODE_LENGTH } from '@owlmeans/auth-otp'
5
- import type { RedisResource } from '@owlmeans/redis-resource'
6
- import type { ResourceRecord } from '@owlmeans/resource'
7
- import type { MailerService } from '@owlmeans/mailer'
8
- import { MAILER_SERVICE } from '@owlmeans/mailer'
9
- import type { OtpConfig, OtpContext } from './types.js'
3
+ import { type OtpService, OTP_SERVICE, OTP_TTL_SECONDS, OTP_CODE_LENGTH, OTP_MAX_FAILED_ATTEMPTS, OTP_RESOURCE } from '@owlmeans/auth-otp'
4
+ import { type MailerService, MAILER_SERVICE } from '@owlmeans/mailer'
5
+ import { randomBytes, randomInt } from 'node:crypto'
6
+ import type { AuthThrottleService, OtpChallengeStore, OtpConfig, OtpContext } from './types.js'
7
+ import { OtpChallengeOutcome, OTP_CHALLENGE_STORE } from './consts.js'
8
+ import { throttleKeyHelper } from './throttle-keys.js'
9
+ import { otpKeyHelper } from './keys.js'
10
+ import { OtpThrottled, OtpUnavailable } from './errors.js'
11
+ import { makeRedisOtpChallengeStore } from './challenge.js'
12
+ import { logger, logThrottle } from '@owlmeans/log'
10
13
 
11
- interface OtpRecord extends ResourceRecord {
12
- id: string
13
- code: string
14
- }
14
+ const log = logger('server-auth-otp')
15
+
16
+ /** An e-mail as a log may carry it: its domain only. */
17
+ const domainOf = (email: string): string => email.slice(email.lastIndexOf('@') + 1)
15
18
 
16
- const codeKey = (email: string): string =>
17
- email.toLowerCase().replace(/[^a-z0-9]/g, '_')
19
+ const generateCode = (): string => {
20
+ const digits = randomInt(0, Math.pow(10, OTP_CODE_LENGTH))
21
+ return String(digits).padStart(OTP_CODE_LENGTH, '0')
22
+ }
18
23
 
19
24
  export const makeOtpService = (alias = OTP_SERVICE): OtpService => {
25
+ let fallbackChallenges: OtpChallengeStore | undefined
26
+
27
+ const challengeStore = (ctx: OtpContext<OtpConfig>): OtpChallengeStore => {
28
+ const challengeAlias = ctx.cfg.otp?.challengeStoreAlias ?? OTP_CHALLENGE_STORE
29
+ if (ctx.hasService(challengeAlias)) return ctx.service<OtpChallengeStore>(challengeAlias)
30
+
31
+ // Backwards-compatible secure default: existing consumers that registered only OTP_RESOURCE
32
+ // still get the atomic Redis store. New consumers can inject the real memory implementation.
33
+ if (fallbackChallenges == null) {
34
+ fallbackChallenges = makeRedisOtpChallengeStore(
35
+ `${alias}:redis-challenge`, ctx.cfg.otp?.resourceAlias ?? OTP_RESOURCE
36
+ )
37
+ fallbackChallenges.registerContext(ctx)
38
+ }
39
+ return fallbackChallenges
40
+ }
41
+
20
42
  const service: OtpService = appendContextual<OtpService>(alias, {
21
- issueChallenge: async (email: string): Promise<void> => {
43
+ issueChallenge: async (email: string): Promise<string> => {
22
44
  const ctx = service.ctx as OtpContext<OtpConfig>
23
- const resourceAlias = ctx.cfg.otp?.resourceAlias ?? OTP_RESOURCE
24
45
  const mailerAlias = ctx.cfg.otp?.mailerAlias ?? MAILER_SERVICE
25
- const resource = ctx.resource<RedisResource<OtpRecord>>(resourceAlias)
46
+ const challenges = challengeStore(ctx)
26
47
  const mailer = ctx.service<MailerService>(mailerAlias)
27
-
28
48
  const code = generateCode()
29
- const id = codeKey(email)
49
+ const issuanceId = randomBytes(18).toString('base64url')
30
50
 
31
- // Upsert: delete previous code if any, then create fresh.
32
- try {
33
- await resource.delete(id)
34
- } catch { /* key may not exist */ }
51
+ const throttleAlias = ctx.cfg.otp?.throttleAlias
52
+ const throttleRules = ctx.cfg.otp?.throttleRules
53
+ if (throttleAlias != null && throttleRules != null) {
54
+ const decision = await ctx.service<AuthThrottleService>(throttleAlias)
55
+ .consume(throttleKeyHelper.emailThrottleKey(email), throttleRules, issuanceId)
56
+ if (!decision.allowed) {
57
+ if (logThrottle(`otp-throttled:${otpKeyHelper.otpEmailKey(email)}`, 60_000)) {
58
+ log.warn('Login code refused: throttled', {
59
+ reason: 'otp-throttled', emailDomain: domainOf(email), retryAfter: decision.retryAfter,
60
+ }, { event: 'auth.refused' })
61
+ }
62
+ throw new OtpThrottled(decision.retryAfter)
63
+ }
64
+ }
35
65
 
36
- await resource.create({ id, code }, { ttl: OTP_TTL_SECONDS })
66
+ const issued = await challenges.issue({
67
+ id: otpKeyHelper.otpChallengeKey(issuanceId),
68
+ emailKey: otpKeyHelper.otpEmailKey(email),
69
+ codeHash: otpKeyHelper.otpCodeHash(issuanceId, code),
70
+ }, OTP_TTL_SECONDS)
71
+ if (!issued) throw new OtpUnavailable('issuance-collision')
37
72
 
38
73
  await mailer.send({
39
74
  to: email,
@@ -41,31 +76,23 @@ export const makeOtpService = (alias = OTP_SERVICE): OtpService => {
41
76
  text: `Your one-time login code is: ${code}\n\nIt expires in ${OTP_TTL_SECONDS / 60} minutes.`,
42
77
  html: `<p>Your one-time login code is: <strong>${code}</strong></p><p>It expires in ${OTP_TTL_SECONDS / 60} minutes.</p>`,
43
78
  })
79
+
80
+ return issuanceId
44
81
  },
45
82
 
46
- verifyChallenge: async (email: string, code: string): Promise<void> => {
83
+ verifyChallenge: async (email: string, issuanceId: string, code: string): Promise<void> => {
47
84
  const ctx = service.ctx as OtpContext<OtpConfig>
48
- const resourceAlias = ctx.cfg.otp?.resourceAlias ?? OTP_RESOURCE
49
- const resource = ctx.resource<RedisResource<OtpRecord>>(resourceAlias)
50
-
51
- const id = codeKey(email)
52
- const record = await resource.load(id)
53
-
54
- if (record == null || record.code !== code.trim()) {
85
+ const outcome = await challengeStore(ctx).verify(
86
+ otpKeyHelper.otpChallengeKey(issuanceId), otpKeyHelper.otpEmailKey(email), otpKeyHelper.otpCodeHash(issuanceId, code),
87
+ OTP_MAX_FAILED_ATTEMPTS
88
+ )
89
+ if (outcome !== OtpChallengeOutcome.Verified) {
90
+ // The sign-in refusal itself (`auth.refused`) is logged where the manager decides sign-in.
91
+ log.debug('OTP challenge refused', { outcome, emailDomain: domainOf(email) })
55
92
  throw new AuthenFailed('otp:code')
56
93
  }
57
-
58
- // Consume: delete so the code cannot be reused.
59
- try {
60
- await resource.delete(id)
61
- } catch { /* already expired */ }
62
94
  },
63
95
  })
64
96
 
65
97
  return service
66
98
  }
67
-
68
- const generateCode = (): string => {
69
- const digits = Math.floor(Math.random() * Math.pow(10, OTP_CODE_LENGTH))
70
- return String(digits).padStart(OTP_CODE_LENGTH, '0')
71
- }
@@ -0,0 +1,7 @@
1
+ /** Throttle subjects as non-raw keys: digests of what a request is throttled by. */
2
+ export interface ThrottleKeyHelper {
3
+ /** Collision-resistant, non-raw key for case-insensitive email throttles. */
4
+ emailThrottleKey: (email: string) => string
5
+ /** Non-raw key for request-source throttles. Callers remain responsible for trusted-proxy parsing. */
6
+ ipThrottleKey: (ip: string) => string
7
+ }
@@ -0,0 +1,17 @@
1
+ import { createHash } from 'node:crypto'
2
+ import type { ThrottleKeyHelper } from './throttle-keys/types.js'
3
+
4
+ const digestKey = (kind: string, value: string): string =>
5
+ createHash('sha256').update(`owlmeans:throttle:${kind}\0${value}`).digest('hex')
6
+
7
+ export const createThrottleKeyHelper = (): ThrottleKeyHelper => {
8
+ const emailThrottleKey = (email: string): string =>
9
+ `email:${digestKey('email', email.trim().toLowerCase())}`
10
+
11
+ const ipThrottleKey = (ip: string): string =>
12
+ `ip:${digestKey('ip', ip.trim().toLowerCase())}`
13
+
14
+ return { emailThrottleKey, ipThrottleKey }
15
+ }
16
+
17
+ export const throttleKeyHelper = createThrottleKeyHelper()
@@ -0,0 +1,85 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { createService, appendContextual } from '@owlmeans/context'
3
+ import type { RedisResource } from '@owlmeans/redis-resource'
4
+ import { OtpUnavailable } from './errors.js'
5
+ import type { AuthThrottleService, OtpConfig, OtpContext, ThrottleDecision, ThrottleRule } from './types.js'
6
+ import { OTP_RESOURCE, OTP_THROTTLE_SERVICE } from './consts.js'
7
+ import { REDIS_THROTTLE_SCRIPT } from './consts.local.js'
8
+ import type { Clock, ThrottleResourceRecord } from './types.local.js'
9
+ import { throttleKeyHelper } from './throttle-keys.js'
10
+
11
+ const assertRules = (rules: readonly ThrottleRule[]): void => {
12
+ if (rules.length === 0 || rules.some(rule => !Number.isInteger(rule.limit) || rule.limit < 1
13
+ || !Number.isInteger(rule.windowSeconds) || rule.windowSeconds < 1)) {
14
+ throw new SyntaxError('auth-otp throttle rules require positive integer limits and windows')
15
+ }
16
+ }
17
+
18
+ /** Real in-memory implementation for single-process development and deterministic unit tests. */
19
+ export const makeMemoryThrottleService = (
20
+ alias = OTP_THROTTLE_SERVICE, now: Clock = Date.now
21
+ ): AuthThrottleService => {
22
+ const events = new Map<string, number[]>()
23
+
24
+ return createService<AuthThrottleService>(alias, {
25
+ consume: async (key, rules): Promise<ThrottleDecision> => {
26
+ assertRules(rules)
27
+ const at = now()
28
+ let retryAfter = 0
29
+ const active = rules.map(rule => {
30
+ const bucket = `${key}:${rule.limit}:${rule.windowSeconds}`
31
+ const threshold = at - rule.windowSeconds * 1000
32
+ const values = (events.get(bucket) ?? []).filter(value => value > threshold)
33
+ events.set(bucket, values)
34
+ if (values.length >= rule.limit) {
35
+ retryAfter = Math.max(retryAfter, Math.ceil((values[0] + rule.windowSeconds * 1000 - at) / 1000))
36
+ }
37
+ return { bucket, values }
38
+ })
39
+
40
+ if (retryAfter > 0) return { allowed: false, retryAfter }
41
+ active.forEach(({ bucket, values }) => events.set(bucket, [...values, at]))
42
+
43
+ return { allowed: true, retryAfter: 0 }
44
+ },
45
+ })
46
+ }
47
+
48
+ /** Redis implementation: every configured window is checked and consumed in one Lua operation. */
49
+ export const makeRedisThrottleService = (
50
+ alias = OTP_THROTTLE_SERVICE, resourceAlias = OTP_RESOURCE
51
+ ): AuthThrottleService => {
52
+ const service = appendContextual<AuthThrottleService>(alias, {
53
+ consume: async (key, rules, token): Promise<ThrottleDecision> => {
54
+ assertRules(rules)
55
+ const ctx = service.ctx as OtpContext<OtpConfig>
56
+ const resource = ctx.resource<RedisResource<ThrottleResourceRecord>>(resourceAlias)
57
+ // The shared hash tag keeps all windows in one Redis Cluster slot, which EVAL requires.
58
+ const keys = rules.map(rule => resource.key(
59
+ `throttle:{${key}}:${rule.limit}:${rule.windowSeconds}`
60
+ ))
61
+ const args = rules.flatMap(rule => [String(rule.limit), String(rule.windowSeconds * 1000)])
62
+ args.push(token ?? randomBytes(16).toString('hex'))
63
+
64
+ try {
65
+ const result = await resource.db.client.eval(
66
+ REDIS_THROTTLE_SCRIPT, keys.length, ...keys, ...args
67
+ ) as [number, number]
68
+
69
+ return { allowed: Number(result[0]) === 1, retryAfter: Number(result[1]) }
70
+ } catch (error) {
71
+ const unavailable = new OtpUnavailable('throttle')
72
+ if (error instanceof Error) unavailable.oiriginalStack = `${error}: ${error.stack}`
73
+ throw unavailable
74
+ }
75
+ },
76
+ })
77
+
78
+ return service
79
+ }
80
+
81
+ /** @deprecated compat:factory-refactor — use `throttleKeyHelper.emailThrottleKey(…)` */
82
+ export const emailThrottleKey = (email: string): string => throttleKeyHelper.emailThrottleKey(email)
83
+
84
+ /** @deprecated compat:factory-refactor — use `throttleKeyHelper.ipThrottleKey(…)` */
85
+ export const ipThrottleKey = (ip: string): string => throttleKeyHelper.ipThrottleKey(ip)
@@ -0,0 +1,10 @@
1
+ import type { OtpChallenge } from './types.js'
2
+ import type { ResourceRecord } from '@owlmeans/resource'
3
+
4
+ export interface Clock { (): number }
5
+
6
+ export interface StoredChallenge extends OtpChallenge { failedAttempts: number, expiresAt: number }
7
+
8
+ export interface ChallengeResourceRecord extends ResourceRecord { id: string }
9
+
10
+ export interface ThrottleResourceRecord extends ResourceRecord { id: string }