@prunellejs/auth 0.0.0-stage → 0.7.2

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/src/store.ts ADDED
@@ -0,0 +1,339 @@
1
+ // Clean pluggable AuthStore contract + zero-setup in-memory store for dev & tests.
2
+
3
+ import type { AuthStoreExt, UserExportExt } from './store-ext'
4
+ import { createMemoryStoreExt } from './store-ext'
5
+
6
+ export type {
7
+ AuthStoreExt,
8
+ Organization,
9
+ OrgInvitation,
10
+ OrgMembership,
11
+ PasskeyRecord,
12
+ PasskeySummary,
13
+ RecoveryCodeRecord,
14
+ TotpRecord,
15
+ UserExportExt,
16
+ UserOrgSummary,
17
+ } from './store-ext'
18
+ export { toPasskeySummary } from './store-ext'
19
+
20
+ export interface AuthUser {
21
+ id: string
22
+ email: string
23
+ name?: string | undefined
24
+ avatarUrl?: string | undefined
25
+ role: string
26
+ emailVerified: boolean
27
+ passwordHash?: string | undefined
28
+ createdAt: number
29
+ updatedAt: number
30
+ }
31
+
32
+ export type PublicUser<TUser extends AuthUser = AuthUser> = Omit<TUser, 'passwordHash'>
33
+
34
+ export interface AuthSession {
35
+ /** SHA-256 hex digest of the raw session cookie token (never store raw tokens!). */
36
+ id: string
37
+ userId: string
38
+ expiresAt: number
39
+ createdAt: number
40
+ userAgent?: string | undefined
41
+ ip?: string | undefined
42
+ }
43
+
44
+ export interface OAuthAccount {
45
+ provider: string
46
+ providerAccountId: string
47
+ userId: string
48
+ createdAt: number
49
+ }
50
+
51
+ /** Verification token purposes. `'reset-password'` is reserved for app-defined password-reset flows via `store.createToken`/`store.consumeToken`. */
52
+ export type TokenKind = 'magic-link' | 'verify-email' | 'reset-password'
53
+
54
+ export interface VerificationToken {
55
+ tokenHash: string
56
+ userId?: string | undefined
57
+ email: string
58
+ kind: TokenKind
59
+ expiresAt: number
60
+ }
61
+
62
+ export interface UserExport<TUser extends AuthUser = AuthUser> extends UserExportExt {
63
+ user: PublicUser<TUser>
64
+ sessions: AuthSession[]
65
+ oauthAccounts: Array<{ provider: string, providerAccountId: string, createdAt: number }>
66
+ /** Unexpired sign-in, verification and reset links mailed to the user, without their token. */
67
+ pendingTokens?: Array<{ kind: TokenKind, expiresAt: number }> | undefined
68
+ /** What `onExportUser` returned for this user. */
69
+ app?: unknown
70
+ exportedAt: number
71
+ }
72
+
73
+ export interface AuthStore<TUser extends AuthUser = AuthUser> extends AuthStoreExt {
74
+ getUserById(id: string): TUser | undefined | Promise<TUser | undefined>
75
+ getUserByEmail(email: string): TUser | undefined | Promise<TUser | undefined>
76
+ createUser(user: TUser): TUser | Promise<TUser>
77
+ updateUser(id: string, patch: Partial<Omit<TUser, 'id' | 'createdAt'>>): TUser | undefined | Promise<TUser | undefined>
78
+ deleteUser(userId: string): void | Promise<void>
79
+ exportUser(userId: string): UserExport<TUser> | null | Promise<UserExport<TUser> | null>
80
+
81
+ getSession(tokenHash: string): AuthSession | undefined | Promise<AuthSession | undefined>
82
+ listSessions(userId: string): AuthSession[] | Promise<AuthSession[]>
83
+ createSession(session: AuthSession): void | Promise<void>
84
+ updateSessionExpiry(tokenHash: string, expiresAt: number): void | Promise<void>
85
+ deleteSession(tokenHash: string): void | Promise<void>
86
+ deleteUserSessions(userId: string): void | Promise<void>
87
+
88
+ getOAuthAccount(provider: string, providerAccountId: string): OAuthAccount | undefined | Promise<OAuthAccount | undefined>
89
+ linkOAuthAccount(account: OAuthAccount): void | Promise<void>
90
+ deleteUserOAuthAccounts(userId: string): void | Promise<void>
91
+
92
+ createToken(token: VerificationToken): void | Promise<void>
93
+ consumeToken(tokenHash: string, kind: TokenKind): VerificationToken | undefined | Promise<VerificationToken | undefined>
94
+
95
+ pruneExpired(options?: PruneOptions): void | Promise<void>
96
+ close?(): void | Promise<void>
97
+ }
98
+
99
+ export interface PruneOptions {
100
+ /** Also delete every user whose email was never verified and who was created before this time (ms), with all their data. */
101
+ unverifiedCreatedBefore?: number | undefined
102
+ }
103
+
104
+ export function normalizeEmail(email: string): string {
105
+ return email.trim().toLowerCase()
106
+ }
107
+
108
+ export function toPublicUser<TUser extends AuthUser = AuthUser>(user: TUser): PublicUser<TUser> {
109
+ const { passwordHash: _hash, ...pub } = user
110
+ return pub
111
+ }
112
+
113
+ interface MemoryState<TUser extends AuthUser = AuthUser> {
114
+ users: Map<string, TUser>
115
+ usersByEmail: Map<string, string>
116
+ sessions: Map<string, AuthSession>
117
+ oauth: Map<string, OAuthAccount>
118
+ tokens: Map<string, VerificationToken>
119
+ }
120
+
121
+ const inMemoryStores = new WeakSet<object>()
122
+ const syncStores = new WeakSet<object>()
123
+
124
+ /** Marks `store` as one whose data lives in the process alone when `inMemory`, for `requires` to refuse it in production. */
125
+ export function keptInMemory<T extends object>(inMemory: boolean, store: T): T {
126
+ if (inMemory)
127
+ inMemoryStores.add(store)
128
+ return store
129
+ }
130
+
131
+ /** Whether the store loses every account and session when the process stops: `memoryAuthStore()`, or `sqliteAuthStore()` on `:memory:`. */
132
+ export function isKeptInMemory(store: object): boolean {
133
+ return inMemoryStores.has(store)
134
+ }
135
+
136
+ /** Marks a built-in store whose methods are guaranteed synchronous, enabling lazy session resolution on the very first request. */
137
+ export function markSyncStore<T extends object>(store: T): T {
138
+ syncStores.add(store)
139
+ return store
140
+ }
141
+
142
+ /** Whether `store` is a known built-in synchronous `AuthStore`. */
143
+ export function isKnownSyncStore(store: object): boolean {
144
+ return syncStores.has(store)
145
+ }
146
+
147
+ function deleteMemoryUser<TUser extends AuthUser>(
148
+ state: MemoryState<TUser>,
149
+ ext: ReturnType<typeof createMemoryStoreExt>,
150
+ userId: string,
151
+ ): void {
152
+ const cur = state.users.get(userId)
153
+ state.users.delete(userId)
154
+ if (cur)
155
+ state.usersByEmail.delete(cur.email)
156
+ for (const [k, s] of state.sessions) {
157
+ if (s.userId === userId)
158
+ state.sessions.delete(k)
159
+ }
160
+ for (const [k, a] of state.oauth) {
161
+ if (a.userId === userId)
162
+ state.oauth.delete(k)
163
+ }
164
+ for (const [k, t] of state.tokens) {
165
+ if (t.userId === userId || (cur && t.email === cur.email))
166
+ state.tokens.delete(k)
167
+ }
168
+ ext.deleteUserExt(userId, cur?.email)
169
+ }
170
+
171
+ function exportMemoryUser<TUser extends AuthUser>(
172
+ state: MemoryState<TUser>,
173
+ ext: ReturnType<typeof createMemoryStoreExt>,
174
+ userId: string,
175
+ ): UserExport<TUser> | null {
176
+ const cur = state.users.get(userId)
177
+ if (!cur)
178
+ return null
179
+ const now = Date.now()
180
+ const sessions: AuthSession[] = []
181
+ for (const [k, s] of state.sessions) {
182
+ if (s.expiresAt <= now) {
183
+ state.sessions.delete(k)
184
+ continue
185
+ }
186
+ if (s.userId === userId)
187
+ sessions.push({ ...s })
188
+ }
189
+ sessions.sort((a, b) => b.createdAt - a.createdAt)
190
+ const oauthAccounts: UserExport['oauthAccounts'] = []
191
+ for (const a of state.oauth.values()) {
192
+ if (a.userId === userId)
193
+ oauthAccounts.push({ provider: a.provider, providerAccountId: a.providerAccountId, createdAt: a.createdAt })
194
+ }
195
+ oauthAccounts.sort((a, b) => a.createdAt - b.createdAt)
196
+ const pendingTokens = [...state.tokens.values()]
197
+ .filter(t => t.expiresAt > now && (t.userId === userId || t.email === cur.email))
198
+ .sort((a, b) => a.expiresAt - b.expiresAt)
199
+ .map(t => ({ kind: t.kind, expiresAt: t.expiresAt }))
200
+ return {
201
+ user: toPublicUser(cur),
202
+ sessions,
203
+ oauthAccounts,
204
+ pendingTokens,
205
+ ...ext.exportUserExt(userId, cur.email, now),
206
+ exportedAt: now,
207
+ }
208
+ }
209
+
210
+ export function memoryAuthStore<TUser extends AuthUser = AuthUser>(): AuthStore<TUser> {
211
+ const state: MemoryState<TUser> = {
212
+ users: new Map(),
213
+ usersByEmail: new Map(),
214
+ sessions: new Map(),
215
+ oauth: new Map(),
216
+ tokens: new Map(),
217
+ }
218
+ const ext = createMemoryStoreExt()
219
+
220
+ return markSyncStore(keptInMemory(true, {
221
+ ...ext.methods,
222
+ getUserById(userId) {
223
+ return state.users.get(userId)
224
+ },
225
+ getUserByEmail(email) {
226
+ const uid = state.usersByEmail.get(normalizeEmail(email))
227
+ return uid !== undefined ? state.users.get(uid) : undefined
228
+ },
229
+ createUser(user) {
230
+ const norm: TUser = { ...user, email: normalizeEmail(user.email) }
231
+ state.users.set(norm.id, norm)
232
+ state.usersByEmail.set(norm.email, norm.id)
233
+ return norm
234
+ },
235
+ updateUser(userId, patch) {
236
+ const cur = state.users.get(userId)
237
+ if (!cur)
238
+ return undefined
239
+ const nextEmail = patch.email !== undefined ? normalizeEmail(patch.email) : cur.email
240
+ if (nextEmail !== cur.email) {
241
+ state.usersByEmail.delete(cur.email)
242
+ state.usersByEmail.set(nextEmail, userId)
243
+ }
244
+ const next: TUser = { ...cur, ...patch, email: nextEmail, updatedAt: patch.updatedAt ?? Date.now() }
245
+ state.users.set(userId, next)
246
+ return next
247
+ },
248
+ deleteUser(userId) {
249
+ deleteMemoryUser(state, ext, userId)
250
+ },
251
+ exportUser(userId) {
252
+ return exportMemoryUser(state, ext, userId)
253
+ },
254
+ getSession(tokenHash) {
255
+ const s = state.sessions.get(tokenHash)
256
+ if (!s)
257
+ return undefined
258
+ if (s.expiresAt <= Date.now()) {
259
+ state.sessions.delete(tokenHash)
260
+ return undefined
261
+ }
262
+ return s
263
+ },
264
+ listSessions(userId) {
265
+ const now = Date.now()
266
+ const sessions: AuthSession[] = []
267
+ for (const [k, s] of state.sessions) {
268
+ if (s.expiresAt <= now) {
269
+ state.sessions.delete(k)
270
+ continue
271
+ }
272
+ if (s.userId === userId)
273
+ sessions.push({ ...s })
274
+ }
275
+ sessions.sort((a, b) => b.createdAt - a.createdAt)
276
+ return sessions
277
+ },
278
+ createSession(session) {
279
+ state.sessions.set(session.id, session)
280
+ },
281
+ updateSessionExpiry(tokenHash, expiresAt) {
282
+ const s = state.sessions.get(tokenHash)
283
+ if (s)
284
+ s.expiresAt = expiresAt
285
+ },
286
+ deleteSession(tokenHash) {
287
+ state.sessions.delete(tokenHash)
288
+ },
289
+ deleteUserSessions(userId) {
290
+ for (const [k, s] of state.sessions) {
291
+ if (s.userId === userId)
292
+ state.sessions.delete(k)
293
+ }
294
+ },
295
+ getOAuthAccount(provider, providerAccountId) {
296
+ return state.oauth.get(`${provider}:${providerAccountId}`)
297
+ },
298
+ linkOAuthAccount(account) {
299
+ state.oauth.set(`${account.provider}:${account.providerAccountId}`, account)
300
+ },
301
+ deleteUserOAuthAccounts(userId) {
302
+ for (const [k, a] of state.oauth) {
303
+ if (a.userId === userId)
304
+ state.oauth.delete(k)
305
+ }
306
+ },
307
+ createToken(token) {
308
+ state.tokens.set(token.tokenHash, { ...token, email: normalizeEmail(token.email) })
309
+ },
310
+ consumeToken(tokenHash, kind) {
311
+ const tok = state.tokens.get(tokenHash)
312
+ if (!tok || tok.kind !== kind)
313
+ return undefined
314
+ state.tokens.delete(tokenHash)
315
+ if (tok.expiresAt <= Date.now())
316
+ return undefined
317
+ return tok
318
+ },
319
+ pruneExpired(options) {
320
+ const now = Date.now()
321
+ for (const [k, s] of state.sessions) {
322
+ if (s.expiresAt <= now)
323
+ state.sessions.delete(k)
324
+ }
325
+ for (const [k, t] of state.tokens) {
326
+ if (t.expiresAt <= now)
327
+ state.tokens.delete(k)
328
+ }
329
+ ext.pruneExpiredExt(now)
330
+ const cutoff = options?.unverifiedCreatedBefore
331
+ if (cutoff === undefined)
332
+ return
333
+ for (const user of [...state.users.values()]) {
334
+ if (!user.emailVerified && user.createdAt < cutoff)
335
+ deleteMemoryUser(state, ext, user.id)
336
+ }
337
+ },
338
+ }))
339
+ }
@@ -0,0 +1,144 @@
1
+ // HTTP routes for TOTP second factor setup, confirmation, verification (2FA), and disabling.
2
+ // Works both with JSON clients and with zero-JS HTML forms.
3
+
4
+ import type { RequestContext } from 'prunelle/server'
5
+ import type { AuthFormMessages } from './form-messages'
6
+ import type { AuthRouteRegistrar } from './http'
7
+ import type { SessionManager } from './session'
8
+ import type { AuthStore, AuthUser } from './store'
9
+ import type { TotpManager } from './totp'
10
+ import { safeRedirect, wantsJson } from 'prunelle/server'
11
+ import { readFormMessage } from './form-messages'
12
+ import { escapeHtml, fail, respondAuthError } from './http'
13
+ import { toPublicUser } from './store'
14
+
15
+ export interface TotpRoutesDeps<TUser extends AuthUser = AuthUser> {
16
+ authRoute: AuthRouteRegistrar
17
+ store: AuthStore<TUser>
18
+ sessions: SessionManager<TUser>
19
+ totp: TotpManager
20
+ basePath: string
21
+ defaultRedirect: string
22
+ messages: AuthFormMessages
23
+ }
24
+
25
+ function renderHtmlPage(title: string, bodyHtml: string): Response {
26
+ const html = `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><meta name="referrer" content="same-origin"><title>${escapeHtml(title)}</title></head><body><main>${bodyHtml}</main></body></html>`
27
+ return new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8' } })
28
+ }
29
+
30
+ export function registerTotpRoutes<TUser extends AuthUser = AuthUser>(deps: TotpRoutesDeps<TUser>): void {
31
+ const { authRoute, store, sessions, totp, basePath, defaultRedirect, messages } = deps
32
+
33
+ authRoute('POST', '/totp/setup', { limit: 'totp-setup', readBody: true }, async (ctx, body) => {
34
+ const resolved = await sessions.resolve(ctx)
35
+ if (!resolved)
36
+ return fail(ctx, 401, 'Authentication required')
37
+
38
+ try {
39
+ const setup = await totp.setupTotp(resolved.user.id, body.issuer ? { issuer: body.issuer } : undefined)
40
+ if (wantsJson(ctx.request))
41
+ return ctx.json({ ok: true, secret: setup.secret, otpauthUrl: setup.otpauthUrl }, { status: 200 })
42
+ const redirect = safeRedirect(body.redirect ?? body.next, '')
43
+ const redirectInput = redirect ? `<input type="hidden" name="redirect" value="${escapeHtml(redirect)}">` : ''
44
+ return renderHtmlPage(
45
+ 'Set up two-factor authentication',
46
+ `<h1>Set up two-factor authentication</h1><p>Secret: <code>${escapeHtml(setup.secret)}</code></p><p>URI: <code>${escapeHtml(setup.otpauthUrl)}</code></p><form method="post" action="${escapeHtml(`${basePath}/totp/confirm`)}">${redirectInput}<label>Verification code <input type="text" name="code" inputmode="numeric" autocomplete="one-time-code" required></label><button type="submit">Enable 2FA</button></form>`,
47
+ )
48
+ }
49
+ catch (err) {
50
+ const msg = err instanceof Error ? err.message : 'Unable to start TOTP setup'
51
+ const status = msg.includes('already enabled') ? 409 : 400
52
+ return fail(ctx, status, msg)
53
+ }
54
+ })
55
+
56
+ authRoute('POST', '/totp/confirm', { limit: 'totp-confirm', readBody: true }, async (ctx, body) => {
57
+ const resolved = await sessions.resolve(ctx)
58
+ if (!resolved)
59
+ return fail(ctx, 401, 'Authentication required')
60
+
61
+ const code = (body.code ?? '').trim()
62
+ if (!code)
63
+ return fail(ctx, 400, 'Verification code is required')
64
+
65
+ try {
66
+ const result = await totp.confirmTotp(resolved.user.id, code)
67
+ if (wantsJson(ctx.request))
68
+ return ctx.json({ ok: true, enabled: true, recoveryCodes: result.recoveryCodes }, { status: 200 })
69
+ if (body.redirect || body.next)
70
+ return ctx.redirect(safeRedirect(body.redirect ?? body.next, defaultRedirect), 303)
71
+ const list = result.recoveryCodes.map(c => `<li><code>${escapeHtml(c)}</code></li>`).join('')
72
+ return renderHtmlPage(
73
+ 'Two-factor authentication enabled',
74
+ `<h1>Two-factor authentication enabled</h1><p>Save these single-use recovery codes in a safe place:</p><ul>${list}</ul>`,
75
+ )
76
+ }
77
+ catch (err) {
78
+ const msg = err instanceof Error ? err.message : 'Invalid verification code'
79
+ const status = msg.includes('already enabled') ? 409 : 400
80
+ return fail(ctx, status, msg)
81
+ }
82
+ })
83
+
84
+ authRoute('GET', '/totp/verify', { limit: 'totp-verify' }, (ctx: RequestContext) => {
85
+ const pending = totp.readPendingCookie(ctx)
86
+ if (!pending)
87
+ return fail(ctx, 401, 'Two-factor session expired or invalid')
88
+ const redirect = safeRedirect(ctx.url.searchParams.get('next') ?? ctx.url.searchParams.get('redirect') ?? pending.redirect, defaultRedirect)
89
+ const message = readFormMessage(messages, ctx.url)
90
+ const error = message?.form === 'totp' ? message.text : undefined
91
+ const described = error !== undefined ? ' aria-invalid="true" aria-describedby="code-error"' : ''
92
+ return renderHtmlPage(
93
+ 'Two-factor verification',
94
+ `<h1>Two-factor verification</h1><form method="post" action="${escapeHtml(`${basePath}/totp/verify`)}"><input type="hidden" name="redirect" value="${escapeHtml(redirect)}"><label>Authentication or recovery code <input type="text" name="code" autocomplete="one-time-code" required${described}></label>${error !== undefined ? `<p id="code-error" role="alert">${escapeHtml(error)}</p>` : ''}<button type="submit">Verify</button></form>`,
95
+ )
96
+ })
97
+
98
+ authRoute('POST', '/totp/verify', { limit: 'totp-verify', readBody: true }, async (ctx, body) => {
99
+ const pending = totp.readPendingCookie(ctx)
100
+ if (!pending)
101
+ return fail(ctx, 401, 'Two-factor session expired or invalid')
102
+
103
+ const code = (body.code ?? '').trim()
104
+ if (!code)
105
+ return respondAuthError(ctx, 400, messages['totp.code-required'])
106
+
107
+ const check = await totp.verifyTotp(pending.userId, code)
108
+ if (!check.valid)
109
+ return respondAuthError(ctx, 401, messages['totp.invalid-code'])
110
+
111
+ const userRecord = await sessions.observeAsync(store.getUserById(pending.userId))
112
+ if (!userRecord) {
113
+ totp.clearPendingCookie(ctx)
114
+ return fail(ctx, 401, 'Unable to resolve user account')
115
+ }
116
+
117
+ totp.clearPendingCookie(ctx)
118
+ const pub = toPublicUser(userRecord)
119
+ await sessions.createSessionForUser(userRecord.id, ctx, pub)
120
+ const redirectTarget = safeRedirect(body.redirect ?? body.next ?? pending.redirect, defaultRedirect)
121
+
122
+ if (wantsJson(ctx.request))
123
+ return ctx.json({ ok: true, user: pub, usedRecoveryCode: check.method === 'recovery' }, { status: 200 })
124
+ return ctx.redirect(redirectTarget, 303)
125
+ })
126
+
127
+ authRoute('POST', '/totp/disable', { limit: 'totp-disable', readBody: true }, async (ctx, body) => {
128
+ const resolved = await sessions.resolve(ctx)
129
+ if (!resolved)
130
+ return fail(ctx, 401, 'Authentication required')
131
+
132
+ const code = (body.code ?? '').trim()
133
+ if (!code)
134
+ return fail(ctx, 400, 'Verification code is required')
135
+
136
+ const disabled = await totp.disableTotp(resolved.user.id, code)
137
+ if (!disabled)
138
+ return fail(ctx, 401, 'Invalid verification code')
139
+
140
+ if (wantsJson(ctx.request))
141
+ return ctx.json({ ok: true, enabled: false }, { status: 200 })
142
+ return ctx.redirect(safeRedirect(body.redirect ?? body.next, defaultRedirect), 303)
143
+ })
144
+ }