@cslug/auth 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # @cslug/auth
2
2
 
3
- `AuthProvider` binds `Hash`, `Gate`, `Tokens`, `MagicLinks`, adds `authenticate()` to the web and api route groups
4
- (through `@cslug/http`'s `WEB_MIDDLEWARE` / `API_MIDDLEWARE` tags), and registers the `cslug_access_tokens`
5
- migration (`@cslug/database`'s `addMigrations`).
3
+ `AuthProvider` binds `Hash`, `Gate`, `Tokens`, `MagicLinks`, `TwoFactor`, adds `authenticate()` to the web and api
4
+ route groups (through `@cslug/http`'s `WEB_MIDDLEWARE` / `API_MIDDLEWARE` tags), and registers the
5
+ `cslug_access_tokens` and `cslug_two_factor` migrations (`@cslug/database`'s `addMigrations`).
6
6
 
7
7
  Per request, `authenticate()` creates `ctx.auth` and loads the user (one primary-key lookup) from a `Bearer`
8
8
  token or the session's `auth.id`, so `auth.user()` is synchronous and views can read `useRequest().user`.
@@ -13,5 +13,10 @@ Security notes:
13
13
  failures without the password, and rehashes when parameters change.
14
14
  - Token secrets are stored as SHA-256 and compared in constant time.
15
15
  - Magic-link redirects must be local paths.
16
+ - Two-factor (TOTP, RFC 6238, checked against the RFC's test vectors): secrets encrypted with `APP_KEY`, recovery
17
+ codes stored as SHA-256 hashes and used up atomically, each time step accepted once (atomic `last_counter` update,
18
+ so a code cannot be replayed even across processes), codes compared in constant time, failed codes throttled.
19
+ `attempt()` and `beginLogin()` leave a 2FA user signed out until `completeTwoFactor(code)`; `login(user)` is the
20
+ explicit, unconditional sign-in (use it only after a second factor or for users without one).
16
21
 
17
22
  Testing: `t.actingAs(user)` (from `@cslug/testing`) signs requests in through the session.
package/docs/api.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  | | |
4
4
  |---|---|
5
- | `ctx.auth` (`Auth`) | `user()`, `userOrNull()`, `check()`, `id`, `guard` (`'web' \| 'token'`), `token`, `login(user)`, `logout()`, `attempt(email, password)`, `can/cannot/authorize(Policy, ability, ...args)` or `(gate, ...args)`, `tokenCan(ability)` |
5
+ | `ctx.auth` (`Auth`) | `user()`, `userOrNull()`, `check()`, `id`, `guard` (`'web' \| 'token'`), `token`, `login(user)`, `beginLogin(user)` → `'logged-in' \| 'two-factor'`, `twoFactorPending`, `completeTwoFactor(code)` → boolean, `logout()`, `attempt(email, password)` (respects 2FA), `can/cannot/authorize(Policy, ability, ...args)` or `(gate, ...args)`, `tokenCan(ability)` |
6
6
  | `ctx.user` | The user or null |
7
7
  | `Hash` | `make`, `verify`, `needsRehash` (argon2id via `Bun.password`; bcrypt supported) |
8
8
  | `Policy` | Base class; methods `(user, ...args) => boolean`, optional `before(user)` |
@@ -11,8 +11,10 @@
11
11
  | `userSource(app)` | The users repository of `config/auth.ts` (used by the guards and by `t.auth` in tests) |
12
12
  | `Tokens` | `create(user, { name, abilities?, expiresIn? })` → `{ plainText, token }`, `verify`, `list`, `revoke`, `revokeAll` |
13
13
  | `MagicLinks` | `create(user, { redirect?, lifetime? })` → `{ token, expiresAt }`; `consume(token)` → `{ user, redirectTo }` or `MagicLinkError` (400: invalid, expired, used) |
14
+ | `TwoFactor` | `enable(user, account)` → `{ secret, uri }` (`ConflictError` when already on), `confirm(user, code)` → recovery codes or null, `enabled(user)`, `verify(user, code)` (TOTP or recovery code, once), `regenerateRecoveryCodes(user)`, `remainingRecoveryCodes(user)`, `disable(user)` |
15
+ | TOTP helpers | `totpSecret()`, `totpCode(secret, at, options?)`, `verifyTotp(secret, code, at, { window, digits, period })` → time step or null, `hotp(secret, counter, digits?)`, `otpauthUri(secret, account, issuer)`, `base32Encode/Decode` |
14
16
  | Middleware | `authenticate()`, `auth(guard?)`, `guest()`, `ability(...)`, `can(gate)` |
15
- | `AuthProvider` | Config `auth`: `users`, `fields`, `passwords`, `magicLinks`, `throttle`, `loginRoute`, `home` |
17
+ | `AuthProvider` | Config `auth`: `users`, `fields`, `passwords`, `magicLinks`, `throttle`, `loginRoute`, `home`, `twoFactor` (`issuer` = `app.name`, `window` 1, `recoveryCodes` 8, `challengeLifetime` `'10m'`) |
16
18
  | `UserSource` | What `users` must provide: `find(id)`, `findBy(where)`, and optionally `update(id, values)` (stores a rehashed password on login; a database repository has it) |
17
19
 
18
20
  Type the user once: `declare module '@cslug/core' { interface AuthUser extends User {} }`.
@@ -0,0 +1,14 @@
1
+ -- up
2
+ -- TOTP second factor, one row per user: the secret (encrypted with APP_KEY), when it was confirmed, the hashes of the
3
+ -- unused recovery codes, and the last time step accepted (a code is never accepted twice).
4
+ create table cslug_two_factor (
5
+ user_id text primary key,
6
+ secret text not null,
7
+ confirmed_at timestamptz,
8
+ recovery_codes jsonb not null default '[]',
9
+ last_counter bigint not null default 0,
10
+ created_at timestamptz not null default now()
11
+ );
12
+
13
+ -- down
14
+ drop table cslug_two_factor;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cslug/auth",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "description": "Session and token guards, password hashing, magic links, policies and gates.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -29,9 +29,9 @@
29
29
  "bun": ">=1.3.14"
30
30
  },
31
31
  "peerDependencies": {
32
- "@cslug/core": "0.6.0",
33
- "@cslug/http": "0.6.0",
34
- "@cslug/database": "0.6.0"
32
+ "@cslug/core": "0.6.1",
33
+ "@cslug/http": "0.6.1",
34
+ "@cslug/database": "0.6.1"
35
35
  },
36
36
  "devDependencies": {
37
37
  "@cslug/testing": "workspace:*",
package/src/auth.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import {
2
2
  type AuthUser,
3
+ Clock,
3
4
  currentContext,
4
5
  ForbiddenError,
6
+ parseDuration,
5
7
  RateLimiter,
6
8
  TooManyRequestsError,
7
9
  UnauthorizedError,
@@ -11,15 +13,19 @@ import { type AuthConfig, field, idOf, type UserSource } from './config'
11
13
  import type { Hash } from './hash'
12
14
  import { type Abilities, type AbilityArgs, checkPolicy, Gate, type PolicyClass } from './policy'
13
15
  import { type AccessToken, type Tokens, tokenCan } from './tokens'
16
+ import type { TwoFactor } from './two-factor'
14
17
 
15
18
  /** The session key holding the signed-in user's id. */
16
19
  export const SESSION_KEY = 'auth.id'
20
+ /** The session key of a password login waiting for its second factor: `{ id, until }` (ms). */
21
+ export const PENDING_KEY = 'auth.two_factor'
17
22
 
18
23
  export type AuthDeps = {
19
24
  config: AuthConfig
20
25
  users: () => Promise<UserSource>
21
26
  hash: () => Hash
22
27
  tokens: () => Tokens
28
+ twoFactor: () => TwoFactor
23
29
  }
24
30
 
25
31
  /**
@@ -103,6 +109,62 @@ export class Auth {
103
109
  this.set(user, 'web')
104
110
  }
105
111
 
112
+ /**
113
+ * Sign a user in, unless they turned on two-factor authentication: then the login waits for
114
+ * `completeTwoFactor(code)` (the session remembers who, for `twoFactor.challengeLifetime`). `'two-factor'` tells the
115
+ * controller to ask for the code. Use it after any first factor (password, magic link).
116
+ */
117
+ async beginLogin(user: AuthUser): Promise<'logged-in' | 'two-factor'> {
118
+ if (!(await this.deps.twoFactor().enabled(user))) {
119
+ await this.login(user)
120
+ return 'logged-in'
121
+ }
122
+ if (!this.hasSession) throw new Error('auth.beginLogin() needs the session (web routes)')
123
+ const lifetime = parseDuration(this.deps.config.twoFactor?.challengeLifetime ?? '10m')
124
+ this.ctx.session.put(PENDING_KEY, { id: idOf(user), until: this.ctx.resolve(Clock).now().getTime() + lifetime })
125
+ return 'two-factor'
126
+ }
127
+
128
+ /** True while a password (or magic link) login waits for its code. */
129
+ get twoFactorPending(): boolean {
130
+ return this.pending() !== undefined
131
+ }
132
+
133
+ private pending(): string | undefined {
134
+ if (!this.hasSession) return undefined
135
+ const p = this.ctx.session.get<{ id: string; until: number }>(PENDING_KEY)
136
+ if (!p) return undefined
137
+ if (p.until < this.ctx.resolve(Clock).now().getTime()) {
138
+ this.ctx.session.forget(PENDING_KEY)
139
+ return undefined
140
+ }
141
+ return p.id
142
+ }
143
+
144
+ /**
145
+ * Finish a login that `beginLogin` (or `attempt`) left waiting: a code from the authenticator app or a recovery
146
+ * code. Throttled per user like `attempt` (429). True when the user is now signed in; false for a wrong code or
147
+ * when no login is waiting (or it expired).
148
+ */
149
+ async completeTwoFactor(code: string): Promise<boolean> {
150
+ const id = this.pending()
151
+ if (!id) return false
152
+ const limiter = this.ctx.resolve(RateLimiter)
153
+ const key = `two-factor:${id}`
154
+ const hit = await limiter.hit(key, this.deps.config.throttle ?? '5/min')
155
+ if (!hit.allowed) throw new TooManyRequestsError(hit.retryAfter)
156
+ if (!(await this.deps.twoFactor().verify(id, code))) {
157
+ this.ctx.log.warn('auth.two_factor_failed', { userId: id })
158
+ return false
159
+ }
160
+ await limiter.reset(key)
161
+ const user = await (await this.deps.users()).find(id)
162
+ this.ctx.session.forget(PENDING_KEY)
163
+ if (!user) return false
164
+ await this.login(user as AuthUser)
165
+ return true
166
+ }
167
+
106
168
  /** Sign out: the session is emptied and gets a new id. */
107
169
  async logout(): Promise<void> {
108
170
  if (this.hasSession) this.ctx.session.invalidate()
@@ -111,7 +173,8 @@ export class Auth {
111
173
 
112
174
  /**
113
175
  * Check an email and password and sign in. Throttled per email and IP (429 when exceeded), constant-time
114
- * whether or not the email exists, rehashes on login when the hashing parameters changed. Null on failure.
176
+ * whether or not the email exists, rehashes on login when the hashing parameters changed. Null on failure. A user
177
+ * with two-factor authentication is not signed in yet: `twoFactorPending` is then true (see `beginLogin`).
115
178
  */
116
179
  async attempt(email: string, password: string): Promise<AuthUser | null> {
117
180
  const { config } = this.deps
@@ -135,7 +198,7 @@ export class Auth {
135
198
  if (config.passwords?.rehashOnLogin !== false && hash.needsRehash(stored)) {
136
199
  await users.update?.(field(user, 'id'), { [passwordField]: await hash.make(password) })
137
200
  }
138
- await this.login(user as AuthUser)
201
+ await this.beginLogin(user as AuthUser)
139
202
  return user as AuthUser
140
203
  }
141
204
 
package/src/config.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Class } from '@cslug/core'
2
+ import type { TwoFactorConfig } from './two-factor'
2
3
 
3
4
  /** What auth needs from the users repository (a cslug `Repository` has both). */
4
5
  export type UserSource = {
@@ -27,6 +28,8 @@ export type AuthConfig = {
27
28
  loginRoute?: string
28
29
  /** Where `guest()` sends signed-in users. Default `/`. */
29
30
  home?: string
31
+ /** TOTP two-factor authentication: issuer, drift window, recovery codes, how long a login waits for its code. */
32
+ twoFactor?: TwoFactorConfig
30
33
  }
31
34
 
32
35
  /** True for a `class` (not a lazy-import function): `config.users` accepts both. */
package/src/index.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  /**
2
2
  * @cslug/auth: session and token guards (`ctx.auth`), password hashing, magic links, API tokens, policies and
3
- * gates, and the `auth()`, `guest()`, `ability()`, `can()` middleware.
3
+ * gates, TOTP two-factor authentication, and the `auth()`, `guest()`, `ability()`, `can()` middleware.
4
4
  */
5
5
  import './types'
6
6
 
7
- export { Auth, SESSION_KEY } from './auth'
7
+ export { Auth, PENDING_KEY, SESSION_KEY } from './auth'
8
8
  export type { AuthConfig, UserSource } from './config'
9
9
  export { Hash } from './hash'
10
10
  export { isLocalPath, MagicLinkError, MagicLinks } from './magic-links'
@@ -12,3 +12,15 @@ export { ability, auth, authenticate, can, guest } from './middleware'
12
12
  export { type Abilities, type AbilityArgs, Gate, gate, Policy } from './policy'
13
13
  export { AuthProvider, userSource } from './provider'
14
14
  export { type AccessToken, Tokens, tokenCan } from './tokens'
15
+ export {
16
+ base32Decode,
17
+ base32Encode,
18
+ hotp,
19
+ otpauthUri,
20
+ type TotpOptions,
21
+ totpCode,
22
+ totpCounter,
23
+ totpSecret,
24
+ verifyTotp,
25
+ } from './totp'
26
+ export { TwoFactor, type TwoFactorConfig } from './two-factor'
package/src/provider.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { join } from 'node:path'
2
2
  import { type Application, Clock, CslugError, Lock, ServiceProvider, token } from '@cslug/core'
3
- import { addMigrations } from '@cslug/database'
3
+ import { addMigrations, Database } from '@cslug/database'
4
4
  import { API_MIDDLEWARE, type MiddlewareFn, WEB_MIDDLEWARE } from '@cslug/http'
5
5
  import { type AuthConfig, isClass, type UserSource } from './config'
6
6
  import { Hash } from './hash'
@@ -8,6 +8,7 @@ import { MagicLinks } from './magic-links'
8
8
  import { AUTH_DEPS, authenticate } from './middleware'
9
9
  import { Gate } from './policy'
10
10
  import { Tokens } from './tokens'
11
+ import { TwoFactor } from './two-factor'
11
12
 
12
13
  const AUTHENTICATE = token<MiddlewareFn>('auth.authenticate')
13
14
 
@@ -20,8 +21,8 @@ export async function userSource(app: Application): Promise<UserSource> {
20
21
  }
21
22
 
22
23
  /**
23
- * Binds `Hash`, `Gate`, `Tokens` and `MagicLinks`, adds `authenticate()` to the web and api groups, and the
24
- * access-tokens migration. Config: `config/auth.ts`.
24
+ * Binds `Hash`, `Gate`, `Tokens`, `MagicLinks` and `TwoFactor`, adds `authenticate()` to the web and api groups,
25
+ * and the access-tokens and two-factor migrations. Config: `config/auth.ts`.
25
26
  */
26
27
  export class AuthProvider extends ServiceProvider {
27
28
  register() {
@@ -49,6 +50,18 @@ export class AuthProvider extends ServiceProvider {
49
50
  config.magicLinks,
50
51
  ),
51
52
  )
53
+ this.app.singleton(
54
+ TwoFactor,
55
+ (c) =>
56
+ new TwoFactor(
57
+ () => c.resolve(Database),
58
+ () => c.resolve(Clock),
59
+ {
60
+ ...config.twoFactor,
61
+ issuer: config.twoFactor?.issuer ?? String(this.app.config('app.name') ?? 'cslug'),
62
+ },
63
+ ),
64
+ )
52
65
  this.app.instance(AUTHENTICATE, authenticate())
53
66
  this.app.tag([AUTHENTICATE], WEB_MIDDLEWARE)
54
67
  this.app.tag([AUTHENTICATE], API_MIDDLEWARE)
@@ -57,6 +70,7 @@ export class AuthProvider extends ServiceProvider {
57
70
  users,
58
71
  hash: () => this.app.resolve(Hash),
59
72
  tokens: () => this.app.resolve(Tokens),
73
+ twoFactor: () => this.app.resolve(TwoFactor),
60
74
  })
61
75
  }
62
76
  }
package/src/totp.ts ADDED
@@ -0,0 +1,93 @@
1
+ import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'
2
+
3
+ const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
4
+
5
+ /** RFC 4648 Base32 (no padding), as authenticator apps expect secrets. */
6
+ export function base32Encode(bytes: Uint8Array): string {
7
+ let bits = 0
8
+ let value = 0
9
+ let out = ''
10
+ for (const byte of bytes) {
11
+ value = (value << 8) | byte
12
+ bits += 8
13
+ while (bits >= 5) {
14
+ out += ALPHABET[(value >>> (bits - 5)) & 31]
15
+ bits -= 5
16
+ }
17
+ }
18
+ if (bits > 0) out += ALPHABET[(value << (5 - bits)) & 31]
19
+ return out
20
+ }
21
+
22
+ export function base32Decode(text: string): Uint8Array {
23
+ const clean = text.toUpperCase().replace(/[\s=-]/g, '')
24
+ const out: number[] = []
25
+ let bits = 0
26
+ let value = 0
27
+ for (const char of clean) {
28
+ const index = ALPHABET.indexOf(char)
29
+ if (index < 0) throw new Error(`Not a Base32 secret (character "${char}")`)
30
+ value = (value << 5) | index
31
+ bits += 5
32
+ if (bits >= 8) {
33
+ out.push((value >>> (bits - 8)) & 255)
34
+ bits -= 8
35
+ }
36
+ }
37
+ return Uint8Array.from(out)
38
+ }
39
+
40
+ /** A new TOTP secret: 20 random bytes (160 bits, as RFC 4226 recommends), Base32. */
41
+ export const totpSecret = () => base32Encode(randomBytes(20))
42
+
43
+ /** The HOTP value of `counter` (RFC 4226): HMAC-SHA1, dynamic truncation, `digits` digits. */
44
+ export function hotp(secret: string, counter: number, digits = 6): string {
45
+ const message = Buffer.alloc(8)
46
+ message.writeBigUInt64BE(BigInt(counter))
47
+ const mac = createHmac('sha1', base32Decode(secret)).update(message).digest()
48
+ const offset = (mac[mac.length - 1] as number) & 15
49
+ const binary = (mac.readUInt32BE(offset) & 0x7fffffff) % 10 ** digits
50
+ return String(binary).padStart(digits, '0')
51
+ }
52
+
53
+ export type TotpOptions = { period?: number; digits?: number; window?: number }
54
+
55
+ /** The time step of an instant: `floor(unix seconds / period)`. */
56
+ export const totpCounter = (at: Date, period = 30) => Math.floor(at.getTime() / 1000 / period)
57
+
58
+ /** The current code (RFC 6238). */
59
+ export const totpCode = (secret: string, at: Date, options: TotpOptions = {}) =>
60
+ hotp(secret, totpCounter(at, options.period), options.digits)
61
+
62
+ /**
63
+ * The time step `code` belongs to, within `window` steps of `at` (default 1: ±30 s of clock drift), or null.
64
+ * Compared in constant time; spaces in the code are ignored.
65
+ */
66
+ export function verifyTotp(secret: string, code: string, at: Date, options: TotpOptions = {}): number | null {
67
+ const { period = 30, digits = 6, window = 1 } = options
68
+ const given = Buffer.from(code.replace(/\s/g, ''))
69
+ if (given.length !== digits) return null
70
+ const now = totpCounter(at, period)
71
+ let found: number | null = null
72
+ for (let step = now - window; step <= now + window; step++) {
73
+ const expected = Buffer.from(hotp(secret, step, digits))
74
+ if (timingSafeEqual(expected, given) && found === null) found = step
75
+ }
76
+ return found
77
+ }
78
+
79
+ /**
80
+ * The `otpauth://` URI authenticator apps import (usually shown as a QR code):
81
+ * `otpauth://totp/Issuer:account?secret=…&issuer=Issuer&algorithm=SHA1&digits=6&period=30`.
82
+ */
83
+ export function otpauthUri(secret: string, account: string, issuer: string, options: TotpOptions = {}): string {
84
+ const label = `${encodeURIComponent(issuer)}:${encodeURIComponent(account)}`
85
+ const query = new URLSearchParams({
86
+ secret,
87
+ issuer,
88
+ algorithm: 'SHA1',
89
+ digits: String(options.digits ?? 6),
90
+ period: String(options.period ?? 30),
91
+ })
92
+ return `otpauth://totp/${label}?${query}`
93
+ }
@@ -0,0 +1,122 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { type Clock, ConflictError } from '@cslug/core'
3
+ import { type Database, decrypt, encrypt, sql } from '@cslug/database'
4
+ import { idOf } from './config'
5
+ import { base32Encode, otpauthUri, totpSecret, verifyTotp } from './totp'
6
+
7
+ /** `config/auth.ts` → `twoFactor`. */
8
+ export type TwoFactorConfig = {
9
+ /** The name authenticator apps show (default `app.name`). */
10
+ issuer?: string
11
+ /** Time steps of drift accepted on each side (default 1: ±30 s). */
12
+ window?: number
13
+ /** How many recovery codes are made (default 8). */
14
+ recoveryCodes?: number
15
+ /** How long a password login waits for its code (default 10 minutes, in ms or a duration such as `'10m'`). */
16
+ challengeLifetime?: string | number
17
+ }
18
+
19
+ type Row = { secret: string; confirmedAt: Date | null; lastCounter: string | number }
20
+ const hashCode = (code: string) =>
21
+ new Bun.CryptoHasher('sha256').update(code.toLowerCase().replace(/[\s-]/g, '')).digest('hex')
22
+ const recoveryCode = () => {
23
+ const raw = base32Encode(randomBytes(10)).toLowerCase() // 16 characters
24
+ return `${raw.slice(0, 4)}-${raw.slice(4, 8)}-${raw.slice(8, 12)}-${raw.slice(12, 16)}`
25
+ }
26
+
27
+ /**
28
+ * TOTP two-factor authentication (RFC 6238, the codes of Google Authenticator, 1Password, Authy…), stored in
29
+ * `cslug_two_factor`: `enable` gives a secret to scan, `confirm` checks a first code and turns it on (with recovery
30
+ * codes), `verify` checks a code at login. A code is accepted once; a recovery code once.
31
+ */
32
+ export class TwoFactor {
33
+ constructor(
34
+ private readonly db: () => Database,
35
+ private readonly clock: () => Clock,
36
+ private readonly config: TwoFactorConfig & { issuer: string },
37
+ ) {}
38
+
39
+ private async row(user: object | string): Promise<Row | null> {
40
+ const id = typeof user === 'string' ? user : idOf(user)
41
+ return this.db().maybeOne<Row>(
42
+ sql`select secret, confirmed_at, last_counter from cslug_two_factor where user_id = ${id}`,
43
+ )
44
+ }
45
+
46
+ /** True once the user confirmed a code (logins then ask for one). */
47
+ async enabled(user: object | string): Promise<boolean> {
48
+ return !!(await this.row(user))?.confirmedAt
49
+ }
50
+
51
+ /**
52
+ * Start (or restart) enrolment: a new secret, not active until `confirm`. Show `uri` as a QR code (or `secret` to
53
+ * type in). A user who already has 2FA must `disable` it first (`ConflictError`).
54
+ */
55
+ async enable(user: object, account: string): Promise<{ secret: string; uri: string }> {
56
+ if (await this.enabled(user))
57
+ throw new ConflictError('auth.two_factor_enabled', {}, 'Two-factor authentication is already on')
58
+ const secret = totpSecret()
59
+ await this.db().exec(sql`insert into cslug_two_factor (user_id, secret) values (${idOf(user)}, ${encrypt(secret)})
60
+ on conflict (user_id) do update set secret = excluded.secret, confirmed_at = null, recovery_codes = '[]',
61
+ last_counter = 0`)
62
+ return { secret, uri: otpauthUri(secret, account, this.config.issuer) }
63
+ }
64
+
65
+ /** Turn 2FA on with a first code from the app; returns the recovery codes (show them once), or null for a bad code. */
66
+ async confirm(user: object, code: string): Promise<string[] | null> {
67
+ const row = await this.row(user)
68
+ if (!row || row.confirmedAt) return null
69
+ if (!(await this.accept(idOf(user), row, code))) return null
70
+ const codes = this.newCodes()
71
+ await this.db().exec(sql`update cslug_two_factor set confirmed_at = ${this.clock().now()},
72
+ recovery_codes = ${sql.json(codes.map(hashCode))} where user_id = ${idOf(user)}`)
73
+ return codes
74
+ }
75
+
76
+ /** A code from the app, or a recovery code (used up). False for anything else, or when 2FA is off. */
77
+ async verify(user: object | string, code: string): Promise<boolean> {
78
+ const id = typeof user === 'string' ? user : idOf(user)
79
+ const row = await this.row(id)
80
+ if (!row?.confirmedAt) return false
81
+ if (/^\s*\d[\d\s]*$/.test(code)) return this.accept(id, row, code)
82
+ const used = await this.db().exec(sql`update cslug_two_factor
83
+ set recovery_codes = recovery_codes - ${hashCode(code)}::text
84
+ where user_id = ${id} and recovery_codes ? ${hashCode(code)}::text`)
85
+ return used === 1
86
+ }
87
+
88
+ /** New recovery codes (the old ones stop working); null when 2FA is off. */
89
+ async regenerateRecoveryCodes(user: object): Promise<string[] | null> {
90
+ const codes = this.newCodes()
91
+ const n = await this.db().exec(sql`update cslug_two_factor set recovery_codes = ${sql.json(codes.map(hashCode))}
92
+ where user_id = ${idOf(user)} and confirmed_at is not null`)
93
+ return n ? codes : null
94
+ }
95
+
96
+ /** How many recovery codes are left. */
97
+ async remainingRecoveryCodes(user: object): Promise<number> {
98
+ return Number(
99
+ (await this.db().value(
100
+ sql`select jsonb_array_length(recovery_codes) from cslug_two_factor where user_id = ${idOf(user)}`,
101
+ )) ?? 0,
102
+ )
103
+ }
104
+
105
+ /** Turn 2FA off (the secret and recovery codes are deleted). */
106
+ async disable(user: object): Promise<void> {
107
+ await this.db().exec(sql`delete from cslug_two_factor where user_id = ${idOf(user)}`)
108
+ }
109
+
110
+ private newCodes() {
111
+ return Array.from({ length: this.config.recoveryCodes ?? 8 }, recoveryCode)
112
+ }
113
+
114
+ /** The code's time step, if valid and later than the last one accepted (atomically: no replay). */
115
+ private async accept(id: string, row: Row, code: string): Promise<boolean> {
116
+ const step = verifyTotp(decrypt(row.secret), code, this.clock().now(), { window: this.config.window ?? 1 })
117
+ if (step === null) return false
118
+ const n = await this.db().exec(sql`update cslug_two_factor set last_counter = ${step}
119
+ where user_id = ${id} and last_counter < ${step}`)
120
+ return n === 1
121
+ }
122
+ }