@prunellejs/auth 0.0.0-stage → 0.6.0

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