@prunellejs/auth 0.6.0 → 0.7.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/LICENSE +21 -0
- package/llms.txt +17 -11
- package/package.json +2 -2
- package/src/account.ts +101 -0
- package/src/form-messages.ts +58 -0
- package/src/http.ts +75 -29
- package/src/index.ts +124 -55
- package/src/links.ts +67 -39
- package/src/oauth-routes.ts +29 -24
- package/src/org-routes.ts +15 -5
- package/src/orgs.ts +17 -0
- package/src/passkey-client.ts +8 -4
- package/src/passkey-routes.ts +12 -2
- package/src/passkeys.ts +11 -14
- package/src/routes.ts +125 -92
- package/src/session-cookie.ts +62 -0
- package/src/session.ts +46 -42
- package/src/sqlite-ext.ts +6 -1
- package/src/sqlite.ts +97 -38
- package/src/store-ext.ts +9 -0
- package/src/store.ts +48 -19
- package/src/totp-routes.ts +11 -5
- package/src/totp.ts +99 -42
package/src/sqlite-ext.ts
CHANGED
|
@@ -223,6 +223,7 @@ function createExtSchema(db: Database): void {
|
|
|
223
223
|
interface ExtQueries {
|
|
224
224
|
getTotp: Statement<TotpRow, [string]>
|
|
225
225
|
upsertTotp: Statement<null, [string, string, number, number | null, number, number]>
|
|
226
|
+
advanceTotpStep: Statement<{ user_id: string }, [number, number, string, number]>
|
|
226
227
|
delTotp: Statement<null, [string]>
|
|
227
228
|
listRecovery: Statement<RecoveryRow, [string]>
|
|
228
229
|
insertRecovery: Statement<null, [string, string, string, string, number]>
|
|
@@ -259,6 +260,7 @@ function prepareExtQueries(db: Database): ExtQueries {
|
|
|
259
260
|
return {
|
|
260
261
|
getTotp: db.query('SELECT * FROM prunelle_auth_totp WHERE user_id = ?'),
|
|
261
262
|
upsertTotp: db.query('INSERT OR REPLACE INTO prunelle_auth_totp (user_id, encrypted_secret, enabled, last_used_step, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)'),
|
|
263
|
+
advanceTotpStep: db.query('UPDATE prunelle_auth_totp SET last_used_step = ?, updated_at = ? WHERE user_id = ? AND enabled = 1 AND (last_used_step IS NULL OR last_used_step < ?) RETURNING user_id'),
|
|
262
264
|
delTotp: db.query('DELETE FROM prunelle_auth_totp WHERE user_id = ?'),
|
|
263
265
|
listRecovery: db.query('SELECT * FROM prunelle_auth_recovery_codes WHERE user_id = ? ORDER BY created_at ASC'),
|
|
264
266
|
insertRecovery: db.query('INSERT INTO prunelle_auth_recovery_codes (id, user_id, code_hash, salt, created_at) VALUES (?, ?, ?, ?, ?)'),
|
|
@@ -306,7 +308,7 @@ function hasExistingExtTable(db: Database): boolean {
|
|
|
306
308
|
|
|
307
309
|
function buildTotpAndPasskeyMethods(db: Database, ensure: () => ExtQueries): Pick<
|
|
308
310
|
Required<AuthStoreExt>,
|
|
309
|
-
'getTotp' | 'setTotp' | 'deleteTotp' | 'listRecoveryCodes' | 'setRecoveryCodes' | 'consumeRecoveryCode' | 'deleteRecoveryCodes' | 'getPasskey' | 'listPasskeys' | 'createPasskey' | 'updatePasskeyUsage' | 'deletePasskey' | 'deleteUserPasskeys'
|
|
311
|
+
'getTotp' | 'setTotp' | 'advanceTotpStep' | 'deleteTotp' | 'listRecoveryCodes' | 'setRecoveryCodes' | 'consumeRecoveryCode' | 'deleteRecoveryCodes' | 'getPasskey' | 'listPasskeys' | 'createPasskey' | 'updatePasskeyUsage' | 'deletePasskey' | 'deleteUserPasskeys'
|
|
310
312
|
> {
|
|
311
313
|
return {
|
|
312
314
|
getTotp(userId) {
|
|
@@ -315,6 +317,9 @@ function buildTotpAndPasskeyMethods(db: Database, ensure: () => ExtQueries): Pic
|
|
|
315
317
|
setTotp(record) {
|
|
316
318
|
ensure().upsertTotp.run(record.userId, record.encryptedSecret, record.enabled ? 1 : 0, record.lastUsedStep ?? null, record.createdAt, record.updatedAt)
|
|
317
319
|
},
|
|
320
|
+
advanceTotpStep(userId, step, updatedAt) {
|
|
321
|
+
return ensure().advanceTotpStep.get(step, updatedAt, userId, step) !== null
|
|
322
|
+
},
|
|
318
323
|
deleteTotp(userId) {
|
|
319
324
|
ensure().delTotp.run(userId)
|
|
320
325
|
},
|
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 { 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,99 @@ 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
|
+
// SQLite gives the -wal and -shm files the mode of the main file: accounts, hashes and sessions are for the server's user alone.
|
|
250
|
+
function ensurePrivateDbFile(dbPath: string): void {
|
|
251
|
+
mkdirSync(dirname(dbPath), { recursive: true })
|
|
252
|
+
try {
|
|
253
|
+
writeFileSync(dbPath, '', { mode: 0o600, flag: 'wx' })
|
|
254
|
+
}
|
|
255
|
+
catch (err) {
|
|
256
|
+
if ((err as NodeJS.ErrnoException).code !== 'EEXIST')
|
|
257
|
+
throw err
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function openSqliteAuthStore(dbOrPath: string | Database): SqliteAuthStore {
|
|
184
262
|
const ownsDb = typeof dbOrPath === 'string'
|
|
185
263
|
if (ownsDb && dbOrPath !== ':memory:' && !dbOrPath.startsWith('file:'))
|
|
186
|
-
|
|
264
|
+
ensurePrivateDbFile(dbOrPath)
|
|
187
265
|
const db = ownsDb ? new Database(dbOrPath, { create: true }) : dbOrPath
|
|
188
266
|
let closed = false
|
|
189
267
|
|
|
190
268
|
createSchema(db)
|
|
269
|
+
const queries = prepareCoreQueries(db)
|
|
191
270
|
const {
|
|
192
|
-
qUserById, qUserByEmail, qInsertUser, qUpdateUser,
|
|
271
|
+
qUserById, qUnverifiedUserIds, qUserByEmail, qInsertUser, qUpdateUser,
|
|
193
272
|
qGetSession, qListUserSessions, qInsertSession, qTouchSession, qDelSession, qDelUserSessions,
|
|
194
|
-
qGetOAuth,
|
|
195
|
-
qInsertToken, qConsumeToken,
|
|
196
|
-
} =
|
|
273
|
+
qGetOAuth, qLinkOAuth, qDelUserOAuth,
|
|
274
|
+
qInsertToken, qConsumeToken,
|
|
275
|
+
} = queries
|
|
197
276
|
|
|
198
277
|
const ext = createSqliteStoreExt(db)
|
|
199
278
|
|
|
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
|
-
})
|
|
279
|
+
const delUserTx = userDeletion(db, queries, ext)
|
|
210
280
|
|
|
211
|
-
function listActiveSessions(userId: string
|
|
212
|
-
return qListUserSessions.all(userId, now).map(row => rowToSession(row)!)
|
|
281
|
+
function listActiveSessions(userId: string): AuthSession[] {
|
|
282
|
+
return qListUserSessions.all(userId, Date.now()).map(row => rowToSession(row)!)
|
|
213
283
|
}
|
|
214
284
|
|
|
215
285
|
return markSyncStore(keptInMemory(db.filename === ':memory:', {
|
|
@@ -222,11 +292,16 @@ export function sqliteAuthStore(dbOrPath: string | Database = ':memory:'): AuthS
|
|
|
222
292
|
if (ownsDb)
|
|
223
293
|
db.close()
|
|
224
294
|
},
|
|
225
|
-
pruneExpired() {
|
|
295
|
+
pruneExpired(options) {
|
|
226
296
|
const now = Date.now()
|
|
227
297
|
db.run('DELETE FROM prunelle_auth_sessions WHERE expires_at <= ?', [now])
|
|
228
298
|
db.run('DELETE FROM prunelle_auth_tokens WHERE expires_at <= ?', [now])
|
|
229
299
|
ext.pruneExpiredExt(now)
|
|
300
|
+
const cutoff = options?.unverifiedCreatedBefore
|
|
301
|
+
if (cutoff !== undefined) {
|
|
302
|
+
for (const { id } of qUnverifiedUserIds.all(cutoff))
|
|
303
|
+
delUserTx(id)
|
|
304
|
+
}
|
|
230
305
|
},
|
|
231
306
|
getUserById(id) {
|
|
232
307
|
return rowToUser(qUserById.get(id))
|
|
@@ -275,23 +350,7 @@ export function sqliteAuthStore(dbOrPath: string | Database = ':memory:'): AuthS
|
|
|
275
350
|
delUserTx(userId)
|
|
276
351
|
},
|
|
277
352
|
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
|
-
}
|
|
353
|
+
return exportSqliteUser(queries, ext, userId)
|
|
295
354
|
},
|
|
296
355
|
getSession(tokenHash) {
|
|
297
356
|
const s = rowToSession(qGetSession.get(tokenHash))
|
package/src/store-ext.ts
CHANGED
|
@@ -86,6 +86,7 @@ export interface UserExportExt {
|
|
|
86
86
|
export interface AuthStoreExt {
|
|
87
87
|
getTotp?(userId: string): TotpRecord | undefined | Promise<TotpRecord | undefined>
|
|
88
88
|
setTotp?(record: TotpRecord): void | Promise<void>
|
|
89
|
+
advanceTotpStep?(userId: string, step: number, updatedAt: number): boolean | Promise<boolean>
|
|
89
90
|
deleteTotp?(userId: string): void | Promise<void>
|
|
90
91
|
listRecoveryCodes?(userId: string): RecoveryCodeRecord[] | Promise<RecoveryCodeRecord[]>
|
|
91
92
|
setRecoveryCodes?(userId: string, codes: RecoveryCodeRecord[]): void | Promise<void>
|
|
@@ -158,6 +159,14 @@ function buildMemoryTotpPasskeyMethods(state: MemoryExtState) {
|
|
|
158
159
|
setTotp(record: TotpRecord): void {
|
|
159
160
|
state.totp.set(record.userId, { ...record })
|
|
160
161
|
},
|
|
162
|
+
advanceTotpStep(userId: string, step: number, updatedAt: number): boolean {
|
|
163
|
+
const rec = state.totp.get(userId)
|
|
164
|
+
if (!rec || !rec.enabled || (rec.lastUsedStep !== undefined && rec.lastUsedStep >= step))
|
|
165
|
+
return false
|
|
166
|
+
rec.lastUsedStep = step
|
|
167
|
+
rec.updatedAt = updatedAt
|
|
168
|
+
return true
|
|
169
|
+
},
|
|
161
170
|
deleteTotp(userId: string): void {
|
|
162
171
|
state.totp.delete(userId)
|
|
163
172
|
},
|
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
|
@@ -4,8 +4,9 @@
|
|
|
4
4
|
import type { RequestContext } from 'prunelle/server'
|
|
5
5
|
import type { SessionManager } from './session'
|
|
6
6
|
import type { AuthStore, AuthUser, RecoveryCodeRecord } from './store'
|
|
7
|
-
import { safeEqual } from 'prunelle/server'
|
|
7
|
+
import { safeEqual, wantsJson } 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
|
|
@@ -174,8 +176,77 @@ function requireTotpStore<TUser extends AuthUser>(store: AuthStore<TUser>) {
|
|
|
174
176
|
}
|
|
175
177
|
}
|
|
176
178
|
|
|
179
|
+
function createKeyedLock() {
|
|
180
|
+
const queues = new Map<string, Promise<void>>()
|
|
181
|
+
return async function withLock<T>(key: string, fn: () => Promise<T>): Promise<T> {
|
|
182
|
+
const prev = queues.get(key) ?? Promise.resolve()
|
|
183
|
+
let release!: () => void
|
|
184
|
+
const current = new Promise<void>((resolve) => { release = resolve })
|
|
185
|
+
const tail = prev.then(() => current)
|
|
186
|
+
queues.set(key, tail)
|
|
187
|
+
await prev
|
|
188
|
+
try {
|
|
189
|
+
return await fn()
|
|
190
|
+
}
|
|
191
|
+
finally {
|
|
192
|
+
release()
|
|
193
|
+
if (queues.get(key) === tail)
|
|
194
|
+
queues.delete(key)
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export function respondTwoFactorChallenge(
|
|
200
|
+
totp: Pick<TotpManager, 'issuePendingCookie'>,
|
|
201
|
+
ctx: RequestContext,
|
|
202
|
+
userId: string,
|
|
203
|
+
redirectTarget: string,
|
|
204
|
+
twoFactorRedirect: string,
|
|
205
|
+
methods: TwoFactorMethod[],
|
|
206
|
+
redirectStatus: 302 | 303 = 303,
|
|
207
|
+
): Response {
|
|
208
|
+
totp.issuePendingCookie(ctx, userId, redirectTarget, methods)
|
|
209
|
+
if (wantsJson(ctx.request))
|
|
210
|
+
return ctx.json({ ok: true, twoFactorRequired: true, methods, userId }, { status: 200 })
|
|
211
|
+
const sep = twoFactorRedirect.includes('?') ? '&' : '?'
|
|
212
|
+
return ctx.redirect(`${twoFactorRedirect}${sep}next=${encodeURIComponent(redirectTarget)}`, redirectStatus)
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function createPendingCookieHelpers(
|
|
216
|
+
secret: () => string,
|
|
217
|
+
twoFactorCookieName: string,
|
|
218
|
+
isSecureCookie: (ctx: RequestContext) => boolean,
|
|
219
|
+
): Pick<TotpManager, 'issuePendingCookie' | 'readPendingCookie' | 'clearPendingCookie'> {
|
|
220
|
+
return {
|
|
221
|
+
issuePendingCookie(ctx, userId, redirect, methods) {
|
|
222
|
+
const payload: PendingTwoFactor = {
|
|
223
|
+
userId,
|
|
224
|
+
redirect,
|
|
225
|
+
methods,
|
|
226
|
+
exp: Date.now() + PENDING_2FA_TTL_MS,
|
|
227
|
+
}
|
|
228
|
+
ctx.cookies.set(twoFactorCookieName, signPayload(secret(), payload), authCookie(isSecureCookie(ctx), Math.floor(PENDING_2FA_TTL_MS / 1000)))
|
|
229
|
+
},
|
|
230
|
+
|
|
231
|
+
readPendingCookie(ctx) {
|
|
232
|
+
const raw = ctx.cookies.get(twoFactorCookieName)
|
|
233
|
+
if (!raw)
|
|
234
|
+
return undefined
|
|
235
|
+
const parsed = verifyPayload<PendingTwoFactor>(secret(), raw)
|
|
236
|
+
if (!parsed || parsed.exp <= Date.now() || !parsed.userId)
|
|
237
|
+
return undefined
|
|
238
|
+
return parsed
|
|
239
|
+
},
|
|
240
|
+
|
|
241
|
+
clearPendingCookie(ctx) {
|
|
242
|
+
ctx.cookies.delete(twoFactorCookieName, { path: '/' })
|
|
243
|
+
},
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
177
247
|
export function createTotpManager<TUser extends AuthUser = AuthUser>(deps: TotpManagerDeps<TUser>): TotpManager {
|
|
178
248
|
const { store, sessions, secret, twoFactorCookieName, getDefaultIssuer, isSecureCookie } = deps
|
|
249
|
+
const withUserLock = createKeyedLock()
|
|
179
250
|
|
|
180
251
|
async function tryConsumeRecoveryCode(userId: string, rawCode: string): Promise<boolean> {
|
|
181
252
|
const ts = requireTotpStore(store)
|
|
@@ -194,21 +265,33 @@ export function createTotpManager<TUser extends AuthUser = AuthUser>(deps: TotpM
|
|
|
194
265
|
return false
|
|
195
266
|
}
|
|
196
267
|
|
|
268
|
+
async function claimTotpStep(userId: string, encryptedSecret: string, matchedStep: number): Promise<boolean> {
|
|
269
|
+
const now = Date.now()
|
|
270
|
+
if (store.advanceTotpStep)
|
|
271
|
+
return await sessions.observeAsync(store.advanceTotpStep(userId, matchedStep, now))
|
|
272
|
+
return withUserLock(userId, async () => {
|
|
273
|
+
const ts = requireTotpStore(store)
|
|
274
|
+
const latest = await sessions.observeAsync(ts.getTotp(userId))
|
|
275
|
+
if (!latest || !latest.enabled || latest.encryptedSecret !== encryptedSecret)
|
|
276
|
+
return false
|
|
277
|
+
if (latest.lastUsedStep !== undefined && matchedStep <= latest.lastUsedStep)
|
|
278
|
+
return false
|
|
279
|
+
await sessions.observeAsync(ts.setTotp({ ...latest, lastUsedStep: matchedStep, updatedAt: now }))
|
|
280
|
+
return true
|
|
281
|
+
})
|
|
282
|
+
}
|
|
283
|
+
|
|
197
284
|
async function verifyTotp(userId: string, code: string): Promise<{ valid: boolean, method?: 'totp' | 'recovery' | undefined }> {
|
|
198
285
|
const ts = requireTotpStore(store)
|
|
199
286
|
const record = await sessions.observeAsync(ts.getTotp(userId))
|
|
200
287
|
if (!record || !record.enabled)
|
|
201
288
|
return { valid: false }
|
|
202
289
|
|
|
203
|
-
const plainSecret = await decryptSecret(secret, record.encryptedSecret)
|
|
290
|
+
const plainSecret = await decryptSecret(secret(), record.encryptedSecret)
|
|
204
291
|
const matchedStep = matchTotpStep(plainSecret, code, Date.now(), record.lastUsedStep)
|
|
205
292
|
if (matchedStep !== undefined) {
|
|
206
|
-
await
|
|
207
|
-
|
|
208
|
-
lastUsedStep: matchedStep,
|
|
209
|
-
updatedAt: Date.now(),
|
|
210
|
-
}))
|
|
211
|
-
return { valid: true, method: 'totp' }
|
|
293
|
+
const claimed = await claimTotpStep(userId, record.encryptedSecret, matchedStep)
|
|
294
|
+
return claimed ? { valid: true, method: 'totp' } : { valid: false }
|
|
212
295
|
}
|
|
213
296
|
|
|
214
297
|
if (await tryConsumeRecoveryCode(userId, code))
|
|
@@ -228,7 +311,7 @@ export function createTotpManager<TUser extends AuthUser = AuthUser>(deps: TotpM
|
|
|
228
311
|
throw new Error('prunelle: TOTP is already enabled for this account')
|
|
229
312
|
|
|
230
313
|
const base32Secret = generateTotpSecret()
|
|
231
|
-
const encryptedSecret = await encryptSecret(secret, base32Secret)
|
|
314
|
+
const encryptedSecret = await encryptSecret(secret(), base32Secret)
|
|
232
315
|
const now = Date.now()
|
|
233
316
|
await sessions.observeAsync(ts.setTotp({
|
|
234
317
|
userId,
|
|
@@ -252,7 +335,7 @@ export function createTotpManager<TUser extends AuthUser = AuthUser>(deps: TotpM
|
|
|
252
335
|
if (record.enabled)
|
|
253
336
|
throw new Error('prunelle: TOTP is already enabled for this account')
|
|
254
337
|
|
|
255
|
-
const plainSecret = await decryptSecret(secret, record.encryptedSecret)
|
|
338
|
+
const plainSecret = await decryptSecret(secret(), record.encryptedSecret)
|
|
256
339
|
const matchedStep = matchTotpStep(plainSecret, code, Date.now())
|
|
257
340
|
if (matchedStep === undefined)
|
|
258
341
|
throw new Error('prunelle: invalid TOTP verification code')
|
|
@@ -275,8 +358,10 @@ export function createTotpManager<TUser extends AuthUser = AuthUser>(deps: TotpM
|
|
|
275
358
|
const result = await verifyTotp(userId, code)
|
|
276
359
|
if (!result.valid)
|
|
277
360
|
return false
|
|
278
|
-
await
|
|
279
|
-
|
|
361
|
+
await withUserLock(userId, async () => {
|
|
362
|
+
await sessions.observeAsync(ts.deleteTotp(userId))
|
|
363
|
+
await sessions.observeAsync(ts.deleteRecoveryCodes(userId))
|
|
364
|
+
})
|
|
280
365
|
return true
|
|
281
366
|
},
|
|
282
367
|
|
|
@@ -305,34 +390,6 @@ export function createTotpManager<TUser extends AuthUser = AuthUser>(deps: TotpM
|
|
|
305
390
|
return methods
|
|
306
391
|
},
|
|
307
392
|
|
|
308
|
-
|
|
309
|
-
const payload: PendingTwoFactor = {
|
|
310
|
-
userId,
|
|
311
|
-
redirect,
|
|
312
|
-
methods,
|
|
313
|
-
exp: Date.now() + PENDING_2FA_TTL_MS,
|
|
314
|
-
}
|
|
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
|
-
})
|
|
322
|
-
},
|
|
323
|
-
|
|
324
|
-
readPendingCookie(ctx) {
|
|
325
|
-
const raw = ctx.cookies.get(twoFactorCookieName)
|
|
326
|
-
if (!raw)
|
|
327
|
-
return undefined
|
|
328
|
-
const parsed = verifyPayload<PendingTwoFactor>(secret, raw)
|
|
329
|
-
if (!parsed || parsed.exp <= Date.now() || !parsed.userId)
|
|
330
|
-
return undefined
|
|
331
|
-
return parsed
|
|
332
|
-
},
|
|
333
|
-
|
|
334
|
-
clearPendingCookie(ctx) {
|
|
335
|
-
ctx.cookies.delete(twoFactorCookieName, { path: '/' })
|
|
336
|
-
},
|
|
393
|
+
...createPendingCookieHelpers(secret, twoFactorCookieName, isSecureCookie),
|
|
337
394
|
}
|
|
338
395
|
}
|