@prunellejs/auth 0.6.0 → 0.7.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/LICENSE +21 -0
- package/llms.txt +15 -9
- package/package.json +2 -2
- package/src/account.ts +101 -0
- package/src/form-messages.ts +58 -0
- package/src/http.ts +77 -26
- package/src/index.ts +114 -50
- package/src/links.ts +43 -39
- package/src/oauth-routes.ts +21 -24
- package/src/org-routes.ts +1 -1
- package/src/orgs.ts +17 -0
- package/src/passkeys.ts +5 -9
- package/src/routes.ts +97 -82
- package/src/session-cookie.ts +55 -0
- package/src/session.ts +45 -42
- package/src/sqlite.ts +89 -38
- package/src/store.ts +48 -19
- package/src/totp-routes.ts +11 -5
- package/src/totp.ts +8 -12
package/src/sqlite.ts
CHANGED
|
@@ -2,9 +2,10 @@
|
|
|
2
2
|
// Works out-of-the-box in single-binary `prunelle build --compile` deployments.
|
|
3
3
|
|
|
4
4
|
import type { AuthSession, AuthStore, AuthUser, OAuthAccount, TokenKind, UserExport, VerificationToken } from './store'
|
|
5
|
-
import { mkdirSync } from 'node:fs'
|
|
6
|
-
import { dirname } from 'node:path'
|
|
5
|
+
import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
|
|
6
|
+
import { dirname, isAbsolute, resolve } from 'node:path'
|
|
7
7
|
import { Database } from 'bun:sqlite'
|
|
8
|
+
import { getAppContext } from 'prunelle/internal/server'
|
|
8
9
|
import { createSqliteStoreExt } from './sqlite-ext'
|
|
9
10
|
import { keptInMemory, markSyncStore, normalizeEmail, toPublicUser } from './store'
|
|
10
11
|
|
|
@@ -96,6 +97,7 @@ function createSchema(db: Database): void {
|
|
|
96
97
|
PRAGMA busy_timeout = 5000;
|
|
97
98
|
PRAGMA journal_mode = WAL;
|
|
98
99
|
PRAGMA foreign_keys = ON;
|
|
100
|
+
PRAGMA secure_delete = ON;
|
|
99
101
|
`)
|
|
100
102
|
adoptKayTables(db)
|
|
101
103
|
db.exec(`
|
|
@@ -110,6 +112,7 @@ function createSchema(db: Database): void {
|
|
|
110
112
|
created_at INTEGER NOT NULL,
|
|
111
113
|
updated_at INTEGER NOT NULL
|
|
112
114
|
);
|
|
115
|
+
CREATE INDEX IF NOT EXISTS idx_prunelle_auth_users_unverified ON prunelle_auth_users(created_at) WHERE email_verified = 0;
|
|
113
116
|
|
|
114
117
|
CREATE TABLE IF NOT EXISTS prunelle_auth_sessions (
|
|
115
118
|
id TEXT PRIMARY KEY,
|
|
@@ -145,6 +148,7 @@ function createSchema(db: Database): void {
|
|
|
145
148
|
function prepareCoreQueries(db: Database) {
|
|
146
149
|
return {
|
|
147
150
|
qUserById: db.query<UserRow, [string]>('SELECT * FROM prunelle_auth_users WHERE id = ?'),
|
|
151
|
+
qUnverifiedUserIds: db.query<{ id: string }, [number]>('SELECT id FROM prunelle_auth_users WHERE email_verified = 0 AND created_at < ?'),
|
|
148
152
|
qUserByEmail: db.query<UserRow, [string]>('SELECT * FROM prunelle_auth_users WHERE email = ?'),
|
|
149
153
|
qInsertUser: db.query<null, [string, string, string | null, string | null, string, number, string | null, number, number]>(
|
|
150
154
|
'INSERT INTO prunelle_auth_users (id, email, name, avatar_url, role, email_verified, password_hash, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
|
|
@@ -165,6 +169,9 @@ function prepareCoreQueries(db: Database) {
|
|
|
165
169
|
qDelUserSessions: db.query<null, [string]>('DELETE FROM prunelle_auth_sessions WHERE user_id = ?'),
|
|
166
170
|
qGetOAuth: db.query<OAuthRow, [string, string]>('SELECT * FROM prunelle_auth_oauth WHERE provider = ? AND provider_account_id = ?'),
|
|
167
171
|
qListUserOAuth: db.query<OAuthRow, [string]>('SELECT * FROM prunelle_auth_oauth WHERE user_id = ? ORDER BY created_at ASC'),
|
|
172
|
+
qListPendingTokens: db.query<{ kind: TokenKind, expires_at: number }, [string, string, number]>(
|
|
173
|
+
'SELECT kind, expires_at FROM prunelle_auth_tokens WHERE (user_id = ? OR email = ?) AND expires_at > ? ORDER BY expires_at',
|
|
174
|
+
),
|
|
168
175
|
qLinkOAuth: db.query<null, [string, string, string, number]>(
|
|
169
176
|
'INSERT OR REPLACE INTO prunelle_auth_oauth (provider, provider_account_id, user_id, created_at) VALUES (?, ?, ?, ?)',
|
|
170
177
|
),
|
|
@@ -180,36 +187,91 @@ function prepareCoreQueries(db: Database) {
|
|
|
180
187
|
}
|
|
181
188
|
}
|
|
182
189
|
|
|
183
|
-
|
|
190
|
+
/** Deletes a user with its sessions, OAuth links, tokens and extension rows, in one transaction. */
|
|
191
|
+
function userDeletion(
|
|
192
|
+
db: Database,
|
|
193
|
+
q: ReturnType<typeof prepareCoreQueries>,
|
|
194
|
+
ext: ReturnType<typeof createSqliteStoreExt>,
|
|
195
|
+
): (userId: string) => void {
|
|
196
|
+
return db.transaction((userId: string) => {
|
|
197
|
+
const user = q.qUserById.get(userId)
|
|
198
|
+
q.qDelUserSessions.run(userId)
|
|
199
|
+
q.qDelUserOAuth.run(userId)
|
|
200
|
+
q.qDelUserTokens.run(userId)
|
|
201
|
+
if (user)
|
|
202
|
+
q.qDelEmailTokens.run(user.email)
|
|
203
|
+
ext.deleteUserExt(userId, user?.email)
|
|
204
|
+
q.qDelUser.run(userId)
|
|
205
|
+
})
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function exportSqliteUser(
|
|
209
|
+
q: ReturnType<typeof prepareCoreQueries>,
|
|
210
|
+
ext: ReturnType<typeof createSqliteStoreExt>,
|
|
211
|
+
userId: string,
|
|
212
|
+
): UserExport | null {
|
|
213
|
+
const user = rowToUser(q.qUserById.get(userId))
|
|
214
|
+
if (!user)
|
|
215
|
+
return null
|
|
216
|
+
const now = Date.now()
|
|
217
|
+
return {
|
|
218
|
+
user: toPublicUser(user),
|
|
219
|
+
sessions: q.qListUserSessions.all(userId, now).map(row => rowToSession(row)!),
|
|
220
|
+
oauthAccounts: q.qListUserOAuth.all(userId).map(r => ({ provider: r.provider, providerAccountId: r.provider_account_id, createdAt: r.created_at })),
|
|
221
|
+
pendingTokens: q.qListPendingTokens.all(userId, user.email, now).map(r => ({ kind: r.kind, expiresAt: r.expires_at })),
|
|
222
|
+
...ext.exportUserExt(userId, user.email, now),
|
|
223
|
+
exportedAt: now,
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
type SqliteAuthStore = AuthStore & { readonly db: Database }
|
|
228
|
+
|
|
229
|
+
export function sqliteAuthStore(dbOrPath: string | Database = ':memory:'): SqliteAuthStore {
|
|
230
|
+
if (typeof dbOrPath !== 'string' || dbOrPath === ':memory:')
|
|
231
|
+
return openSqliteAuthStore(dbOrPath)
|
|
232
|
+
// A file opens at first use, so a build importing prunelle.config.ts creates no database.
|
|
233
|
+
let opened: SqliteAuthStore | undefined
|
|
234
|
+
const open = (): SqliteAuthStore => (opened ??= openSqliteAuthStore(appPath(dbOrPath)))
|
|
235
|
+
const target = Object.create(null) as SqliteAuthStore
|
|
236
|
+
return markSyncStore(new Proxy(target, {
|
|
237
|
+
get: (_, key) => key === 'close' && opened === undefined ? () => {} : Reflect.get(open(), key),
|
|
238
|
+
has: (_, key) => Reflect.has(open(), key),
|
|
239
|
+
}))
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// A relative path belongs to the app: under its root, wherever the server was started from.
|
|
243
|
+
function appPath(path: string): string {
|
|
244
|
+
if (path.startsWith('file:') || isAbsolute(path))
|
|
245
|
+
return path
|
|
246
|
+
return resolve(getAppContext()?.root ?? process.cwd(), path)
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function openSqliteAuthStore(dbOrPath: string | Database): SqliteAuthStore {
|
|
184
250
|
const ownsDb = typeof dbOrPath === 'string'
|
|
185
|
-
if (ownsDb && dbOrPath !== ':memory:' && !dbOrPath.startsWith('file:'))
|
|
251
|
+
if (ownsDb && dbOrPath !== ':memory:' && !dbOrPath.startsWith('file:')) {
|
|
186
252
|
mkdirSync(dirname(dbOrPath), { recursive: true })
|
|
253
|
+
// SQLite gives the -wal and -shm files the mode of the main file: accounts, hashes and sessions are for the server's user alone.
|
|
254
|
+
if (!existsSync(dbOrPath))
|
|
255
|
+
writeFileSync(dbOrPath, '', { mode: 0o600 })
|
|
256
|
+
}
|
|
187
257
|
const db = ownsDb ? new Database(dbOrPath, { create: true }) : dbOrPath
|
|
188
258
|
let closed = false
|
|
189
259
|
|
|
190
260
|
createSchema(db)
|
|
261
|
+
const queries = prepareCoreQueries(db)
|
|
191
262
|
const {
|
|
192
|
-
qUserById, qUserByEmail, qInsertUser, qUpdateUser,
|
|
263
|
+
qUserById, qUnverifiedUserIds, qUserByEmail, qInsertUser, qUpdateUser,
|
|
193
264
|
qGetSession, qListUserSessions, qInsertSession, qTouchSession, qDelSession, qDelUserSessions,
|
|
194
|
-
qGetOAuth,
|
|
195
|
-
qInsertToken, qConsumeToken,
|
|
196
|
-
} =
|
|
265
|
+
qGetOAuth, qLinkOAuth, qDelUserOAuth,
|
|
266
|
+
qInsertToken, qConsumeToken,
|
|
267
|
+
} = queries
|
|
197
268
|
|
|
198
269
|
const ext = createSqliteStoreExt(db)
|
|
199
270
|
|
|
200
|
-
const delUserTx = db
|
|
201
|
-
const user = qUserById.get(userId)
|
|
202
|
-
qDelUserSessions.run(userId)
|
|
203
|
-
qDelUserOAuth.run(userId)
|
|
204
|
-
qDelUserTokens.run(userId)
|
|
205
|
-
if (user)
|
|
206
|
-
qDelEmailTokens.run(user.email)
|
|
207
|
-
ext.deleteUserExt(userId, user?.email)
|
|
208
|
-
qDelUser.run(userId)
|
|
209
|
-
})
|
|
271
|
+
const delUserTx = userDeletion(db, queries, ext)
|
|
210
272
|
|
|
211
|
-
function listActiveSessions(userId: string
|
|
212
|
-
return qListUserSessions.all(userId, now).map(row => rowToSession(row)!)
|
|
273
|
+
function listActiveSessions(userId: string): AuthSession[] {
|
|
274
|
+
return qListUserSessions.all(userId, Date.now()).map(row => rowToSession(row)!)
|
|
213
275
|
}
|
|
214
276
|
|
|
215
277
|
return markSyncStore(keptInMemory(db.filename === ':memory:', {
|
|
@@ -222,11 +284,16 @@ export function sqliteAuthStore(dbOrPath: string | Database = ':memory:'): AuthS
|
|
|
222
284
|
if (ownsDb)
|
|
223
285
|
db.close()
|
|
224
286
|
},
|
|
225
|
-
pruneExpired() {
|
|
287
|
+
pruneExpired(options) {
|
|
226
288
|
const now = Date.now()
|
|
227
289
|
db.run('DELETE FROM prunelle_auth_sessions WHERE expires_at <= ?', [now])
|
|
228
290
|
db.run('DELETE FROM prunelle_auth_tokens WHERE expires_at <= ?', [now])
|
|
229
291
|
ext.pruneExpiredExt(now)
|
|
292
|
+
const cutoff = options?.unverifiedCreatedBefore
|
|
293
|
+
if (cutoff !== undefined) {
|
|
294
|
+
for (const { id } of qUnverifiedUserIds.all(cutoff))
|
|
295
|
+
delUserTx(id)
|
|
296
|
+
}
|
|
230
297
|
},
|
|
231
298
|
getUserById(id) {
|
|
232
299
|
return rowToUser(qUserById.get(id))
|
|
@@ -275,23 +342,7 @@ export function sqliteAuthStore(dbOrPath: string | Database = ':memory:'): AuthS
|
|
|
275
342
|
delUserTx(userId)
|
|
276
343
|
},
|
|
277
344
|
exportUser(userId): UserExport | null {
|
|
278
|
-
|
|
279
|
-
if (!user)
|
|
280
|
-
return null
|
|
281
|
-
const now = Date.now()
|
|
282
|
-
const sessions = listActiveSessions(userId, now)
|
|
283
|
-
const oauthAccounts = qListUserOAuth.all(userId).map(r => ({
|
|
284
|
-
provider: r.provider,
|
|
285
|
-
providerAccountId: r.provider_account_id,
|
|
286
|
-
createdAt: r.created_at,
|
|
287
|
-
}))
|
|
288
|
-
return {
|
|
289
|
-
user: toPublicUser(user),
|
|
290
|
-
sessions,
|
|
291
|
-
oauthAccounts,
|
|
292
|
-
...ext.exportUserExt(userId, user.email, now),
|
|
293
|
-
exportedAt: now,
|
|
294
|
-
}
|
|
345
|
+
return exportSqliteUser(queries, ext, userId)
|
|
295
346
|
},
|
|
296
347
|
getSession(tokenHash) {
|
|
297
348
|
const s = rowToSession(qGetSession.get(tokenHash))
|
package/src/store.ts
CHANGED
|
@@ -63,6 +63,10 @@ export interface UserExport<TUser extends AuthUser = AuthUser> extends UserExpor
|
|
|
63
63
|
user: PublicUser<TUser>
|
|
64
64
|
sessions: AuthSession[]
|
|
65
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
|
|
66
70
|
exportedAt: number
|
|
67
71
|
}
|
|
68
72
|
|
|
@@ -88,10 +92,15 @@ export interface AuthStore<TUser extends AuthUser = AuthUser> extends AuthStoreE
|
|
|
88
92
|
createToken(token: VerificationToken): void | Promise<void>
|
|
89
93
|
consumeToken(tokenHash: string, kind: TokenKind): VerificationToken | undefined | Promise<VerificationToken | undefined>
|
|
90
94
|
|
|
91
|
-
pruneExpired(): void | Promise<void>
|
|
95
|
+
pruneExpired(options?: PruneOptions): void | Promise<void>
|
|
92
96
|
close?(): void | Promise<void>
|
|
93
97
|
}
|
|
94
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
|
+
|
|
95
104
|
export function normalizeEmail(email: string): string {
|
|
96
105
|
return email.trim().toLowerCase()
|
|
97
106
|
}
|
|
@@ -135,6 +144,30 @@ export function isKnownSyncStore(store: object): boolean {
|
|
|
135
144
|
return syncStores.has(store)
|
|
136
145
|
}
|
|
137
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
|
+
|
|
138
171
|
function exportMemoryUser<TUser extends AuthUser>(
|
|
139
172
|
state: MemoryState<TUser>,
|
|
140
173
|
ext: ReturnType<typeof createMemoryStoreExt>,
|
|
@@ -160,10 +193,15 @@ function exportMemoryUser<TUser extends AuthUser>(
|
|
|
160
193
|
oauthAccounts.push({ provider: a.provider, providerAccountId: a.providerAccountId, createdAt: a.createdAt })
|
|
161
194
|
}
|
|
162
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 }))
|
|
163
200
|
return {
|
|
164
201
|
user: toPublicUser(cur),
|
|
165
202
|
sessions,
|
|
166
203
|
oauthAccounts,
|
|
204
|
+
pendingTokens,
|
|
167
205
|
...ext.exportUserExt(userId, cur.email, now),
|
|
168
206
|
exportedAt: now,
|
|
169
207
|
}
|
|
@@ -208,23 +246,7 @@ export function memoryAuthStore<TUser extends AuthUser = AuthUser>(): AuthStore<
|
|
|
208
246
|
return next
|
|
209
247
|
},
|
|
210
248
|
deleteUser(userId) {
|
|
211
|
-
|
|
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)
|
|
249
|
+
deleteMemoryUser(state, ext, userId)
|
|
228
250
|
},
|
|
229
251
|
exportUser(userId) {
|
|
230
252
|
return exportMemoryUser(state, ext, userId)
|
|
@@ -294,7 +316,7 @@ export function memoryAuthStore<TUser extends AuthUser = AuthUser>(): AuthStore<
|
|
|
294
316
|
return undefined
|
|
295
317
|
return tok
|
|
296
318
|
},
|
|
297
|
-
pruneExpired() {
|
|
319
|
+
pruneExpired(options) {
|
|
298
320
|
const now = Date.now()
|
|
299
321
|
for (const [k, s] of state.sessions) {
|
|
300
322
|
if (s.expiresAt <= now)
|
|
@@ -305,6 +327,13 @@ export function memoryAuthStore<TUser extends AuthUser = AuthUser>(): AuthStore<
|
|
|
305
327
|
state.tokens.delete(k)
|
|
306
328
|
}
|
|
307
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
|
+
}
|
|
308
337
|
},
|
|
309
338
|
}))
|
|
310
339
|
}
|
package/src/totp-routes.ts
CHANGED
|
@@ -2,11 +2,13 @@
|
|
|
2
2
|
// Works both with JSON clients and with zero-JS HTML forms.
|
|
3
3
|
|
|
4
4
|
import type { RequestContext } from 'prunelle/server'
|
|
5
|
+
import type { AuthFormMessages } from './form-messages'
|
|
5
6
|
import type { AuthRouteRegistrar } from './http'
|
|
6
7
|
import type { SessionManager } from './session'
|
|
7
8
|
import type { AuthStore, AuthUser } from './store'
|
|
8
9
|
import type { TotpManager } from './totp'
|
|
9
10
|
import { safeRedirect, wantsJson } from 'prunelle/server'
|
|
11
|
+
import { readFormMessage } from './form-messages'
|
|
10
12
|
import { escapeHtml, fail, respondAuthError } from './http'
|
|
11
13
|
import { toPublicUser } from './store'
|
|
12
14
|
|
|
@@ -17,15 +19,16 @@ export interface TotpRoutesDeps<TUser extends AuthUser = AuthUser> {
|
|
|
17
19
|
totp: TotpManager
|
|
18
20
|
basePath: string
|
|
19
21
|
defaultRedirect: string
|
|
22
|
+
messages: AuthFormMessages
|
|
20
23
|
}
|
|
21
24
|
|
|
22
25
|
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="
|
|
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>`
|
|
24
27
|
return new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8' } })
|
|
25
28
|
}
|
|
26
29
|
|
|
27
30
|
export function registerTotpRoutes<TUser extends AuthUser = AuthUser>(deps: TotpRoutesDeps<TUser>): void {
|
|
28
|
-
const { authRoute, store, sessions, totp, basePath, defaultRedirect } = deps
|
|
31
|
+
const { authRoute, store, sessions, totp, basePath, defaultRedirect, messages } = deps
|
|
29
32
|
|
|
30
33
|
authRoute('POST', '/totp/setup', { limit: 'totp-setup', readBody: true }, async (ctx, body) => {
|
|
31
34
|
const resolved = await sessions.resolve(ctx)
|
|
@@ -83,9 +86,12 @@ export function registerTotpRoutes<TUser extends AuthUser = AuthUser>(deps: Totp
|
|
|
83
86
|
if (!pending)
|
|
84
87
|
return fail(ctx, 401, 'Two-factor session expired or invalid')
|
|
85
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"' : ''
|
|
86
92
|
return renderHtmlPage(
|
|
87
93
|
'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
|
|
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>`,
|
|
89
95
|
)
|
|
90
96
|
})
|
|
91
97
|
|
|
@@ -96,11 +102,11 @@ export function registerTotpRoutes<TUser extends AuthUser = AuthUser>(deps: Totp
|
|
|
96
102
|
|
|
97
103
|
const code = (body.code ?? '').trim()
|
|
98
104
|
if (!code)
|
|
99
|
-
return respondAuthError(ctx, 400, '
|
|
105
|
+
return respondAuthError(ctx, 400, messages['totp.code-required'])
|
|
100
106
|
|
|
101
107
|
const check = await totp.verifyTotp(pending.userId, code)
|
|
102
108
|
if (!check.valid)
|
|
103
|
-
return respondAuthError(ctx, 401, '
|
|
109
|
+
return respondAuthError(ctx, 401, messages['totp.invalid-code'])
|
|
104
110
|
|
|
105
111
|
const userRecord = await sessions.observeAsync(store.getUserById(pending.userId))
|
|
106
112
|
if (!userRecord) {
|
package/src/totp.ts
CHANGED
|
@@ -6,6 +6,7 @@ import type { SessionManager } from './session'
|
|
|
6
6
|
import type { AuthStore, AuthUser, RecoveryCodeRecord } from './store'
|
|
7
7
|
import { safeEqual } from 'prunelle/server'
|
|
8
8
|
import { decryptSecret, encryptSecret, randomToken, sha256Hex, signPayload, verifyPayload } from './crypto'
|
|
9
|
+
import { authCookie } from './http'
|
|
9
10
|
|
|
10
11
|
const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
|
|
11
12
|
const RECOVERY_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
|
|
@@ -142,7 +143,8 @@ function generateRecoveryCodeBatch(userId: string): { plain: string[], records:
|
|
|
142
143
|
export interface TotpManagerDeps<TUser extends AuthUser = AuthUser> {
|
|
143
144
|
store: AuthStore<TUser>
|
|
144
145
|
sessions: SessionManager<TUser>
|
|
145
|
-
secret
|
|
146
|
+
/** The app's signing secret, resolved at first use. */
|
|
147
|
+
secret: () => string
|
|
146
148
|
twoFactorCookieName: string
|
|
147
149
|
getDefaultIssuer: () => string
|
|
148
150
|
isSecureCookie: (ctx: RequestContext) => boolean
|
|
@@ -200,7 +202,7 @@ export function createTotpManager<TUser extends AuthUser = AuthUser>(deps: TotpM
|
|
|
200
202
|
if (!record || !record.enabled)
|
|
201
203
|
return { valid: false }
|
|
202
204
|
|
|
203
|
-
const plainSecret = await decryptSecret(secret, record.encryptedSecret)
|
|
205
|
+
const plainSecret = await decryptSecret(secret(), record.encryptedSecret)
|
|
204
206
|
const matchedStep = matchTotpStep(plainSecret, code, Date.now(), record.lastUsedStep)
|
|
205
207
|
if (matchedStep !== undefined) {
|
|
206
208
|
await sessions.observeAsync(ts.setTotp({
|
|
@@ -228,7 +230,7 @@ export function createTotpManager<TUser extends AuthUser = AuthUser>(deps: TotpM
|
|
|
228
230
|
throw new Error('prunelle: TOTP is already enabled for this account')
|
|
229
231
|
|
|
230
232
|
const base32Secret = generateTotpSecret()
|
|
231
|
-
const encryptedSecret = await encryptSecret(secret, base32Secret)
|
|
233
|
+
const encryptedSecret = await encryptSecret(secret(), base32Secret)
|
|
232
234
|
const now = Date.now()
|
|
233
235
|
await sessions.observeAsync(ts.setTotp({
|
|
234
236
|
userId,
|
|
@@ -252,7 +254,7 @@ export function createTotpManager<TUser extends AuthUser = AuthUser>(deps: TotpM
|
|
|
252
254
|
if (record.enabled)
|
|
253
255
|
throw new Error('prunelle: TOTP is already enabled for this account')
|
|
254
256
|
|
|
255
|
-
const plainSecret = await decryptSecret(secret, record.encryptedSecret)
|
|
257
|
+
const plainSecret = await decryptSecret(secret(), record.encryptedSecret)
|
|
256
258
|
const matchedStep = matchTotpStep(plainSecret, code, Date.now())
|
|
257
259
|
if (matchedStep === undefined)
|
|
258
260
|
throw new Error('prunelle: invalid TOTP verification code')
|
|
@@ -312,20 +314,14 @@ export function createTotpManager<TUser extends AuthUser = AuthUser>(deps: TotpM
|
|
|
312
314
|
methods,
|
|
313
315
|
exp: Date.now() + PENDING_2FA_TTL_MS,
|
|
314
316
|
}
|
|
315
|
-
ctx.cookies.set(twoFactorCookieName, signPayload(secret, payload),
|
|
316
|
-
path: '/',
|
|
317
|
-
httpOnly: true,
|
|
318
|
-
sameSite: 'lax',
|
|
319
|
-
secure: isSecureCookie(ctx),
|
|
320
|
-
maxAge: Math.floor(PENDING_2FA_TTL_MS / 1000),
|
|
321
|
-
})
|
|
317
|
+
ctx.cookies.set(twoFactorCookieName, signPayload(secret(), payload), authCookie(isSecureCookie(ctx), Math.floor(PENDING_2FA_TTL_MS / 1000)))
|
|
322
318
|
},
|
|
323
319
|
|
|
324
320
|
readPendingCookie(ctx) {
|
|
325
321
|
const raw = ctx.cookies.get(twoFactorCookieName)
|
|
326
322
|
if (!raw)
|
|
327
323
|
return undefined
|
|
328
|
-
const parsed = verifyPayload<PendingTwoFactor>(secret, raw)
|
|
324
|
+
const parsed = verifyPayload<PendingTwoFactor>(secret(), raw)
|
|
329
325
|
if (!parsed || parsed.exp <= Date.now() || !parsed.userId)
|
|
330
326
|
return undefined
|
|
331
327
|
return parsed
|