@prunellejs/auth 0.1.1 → 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/src/sqlite.ts CHANGED
@@ -2,10 +2,12 @@
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 { keptInMemory, normalizeEmail, toPublicUser } from './store'
8
+ import { getAppContext } from 'prunelle/internal/server'
9
+ import { createSqliteStoreExt } from './sqlite-ext'
10
+ import { keptInMemory, markSyncStore, normalizeEmail, toPublicUser } from './store'
9
11
 
10
12
  interface UserRow {
11
13
  id: string
@@ -95,6 +97,7 @@ function createSchema(db: Database): void {
95
97
  PRAGMA busy_timeout = 5000;
96
98
  PRAGMA journal_mode = WAL;
97
99
  PRAGMA foreign_keys = ON;
100
+ PRAGMA secure_delete = ON;
98
101
  `)
99
102
  adoptKayTables(db)
100
103
  db.exec(`
@@ -109,6 +112,7 @@ function createSchema(db: Database): void {
109
112
  created_at INTEGER NOT NULL,
110
113
  updated_at INTEGER NOT NULL
111
114
  );
115
+ CREATE INDEX IF NOT EXISTS idx_prunelle_auth_users_unverified ON prunelle_auth_users(created_at) WHERE email_verified = 0;
112
116
 
113
117
  CREATE TABLE IF NOT EXISTS prunelle_auth_sessions (
114
118
  id TEXT PRIMARY KEY,
@@ -141,67 +145,137 @@ function createSchema(db: Database): void {
141
145
  `)
142
146
  }
143
147
 
144
- export function sqliteAuthStore(dbOrPath: string | Database = ':memory:'): AuthStore & { readonly db: Database } {
148
+ function prepareCoreQueries(db: Database) {
149
+ return {
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 < ?'),
152
+ qUserByEmail: db.query<UserRow, [string]>('SELECT * FROM prunelle_auth_users WHERE email = ?'),
153
+ qInsertUser: db.query<null, [string, string, string | null, string | null, string, number, string | null, number, number]>(
154
+ 'INSERT INTO prunelle_auth_users (id, email, name, avatar_url, role, email_verified, password_hash, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
155
+ ),
156
+ qUpdateUser: db.query<null, [string, string | null, string | null, string, number, string | null, number, string]>(
157
+ 'UPDATE prunelle_auth_users SET email = ?, name = ?, avatar_url = ?, role = ?, email_verified = ?, password_hash = ?, updated_at = ? WHERE id = ?',
158
+ ),
159
+ qDelUser: db.query<null, [string]>('DELETE FROM prunelle_auth_users WHERE id = ?'),
160
+ qGetSession: db.query<SessionRow, [string]>('SELECT * FROM prunelle_auth_sessions WHERE id = ?'),
161
+ qListUserSessions: db.query<SessionRow, [string, number]>(
162
+ 'SELECT * FROM prunelle_auth_sessions WHERE user_id = ? AND expires_at > ? ORDER BY created_at DESC',
163
+ ),
164
+ qInsertSession: db.query<null, [string, string, number, number, string | null, string | null]>(
165
+ 'INSERT INTO prunelle_auth_sessions (id, user_id, expires_at, created_at, user_agent, ip) VALUES (?, ?, ?, ?, ?, ?)',
166
+ ),
167
+ qTouchSession: db.query<null, [number, string]>('UPDATE prunelle_auth_sessions SET expires_at = ? WHERE id = ?'),
168
+ qDelSession: db.query<null, [string]>('DELETE FROM prunelle_auth_sessions WHERE id = ?'),
169
+ qDelUserSessions: db.query<null, [string]>('DELETE FROM prunelle_auth_sessions WHERE user_id = ?'),
170
+ qGetOAuth: db.query<OAuthRow, [string, string]>('SELECT * FROM prunelle_auth_oauth WHERE provider = ? AND provider_account_id = ?'),
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
+ ),
175
+ qLinkOAuth: db.query<null, [string, string, string, number]>(
176
+ 'INSERT OR REPLACE INTO prunelle_auth_oauth (provider, provider_account_id, user_id, created_at) VALUES (?, ?, ?, ?)',
177
+ ),
178
+ qDelUserOAuth: db.query<null, [string]>('DELETE FROM prunelle_auth_oauth WHERE user_id = ?'),
179
+ qInsertToken: db.query<null, [string, string | null, string, TokenKind, number]>(
180
+ 'INSERT INTO prunelle_auth_tokens (token_hash, user_id, email, kind, expires_at) VALUES (?, ?, ?, ?, ?)',
181
+ ),
182
+ qConsumeToken: db.query<TokenRow, [string, TokenKind]>(
183
+ 'DELETE FROM prunelle_auth_tokens WHERE token_hash = ? AND kind = ? RETURNING *',
184
+ ),
185
+ qDelUserTokens: db.query<null, [string]>('DELETE FROM prunelle_auth_tokens WHERE user_id = ?'),
186
+ qDelEmailTokens: db.query<null, [string]>('DELETE FROM prunelle_auth_tokens WHERE email = ?'),
187
+ }
188
+ }
189
+
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 {
145
250
  const ownsDb = typeof dbOrPath === 'string'
146
- if (ownsDb && dbOrPath !== ':memory:' && !dbOrPath.startsWith('file:'))
251
+ if (ownsDb && dbOrPath !== ':memory:' && !dbOrPath.startsWith('file:')) {
147
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
+ }
148
257
  const db = ownsDb ? new Database(dbOrPath, { create: true }) : dbOrPath
149
258
  let closed = false
150
259
 
151
260
  createSchema(db)
261
+ const queries = prepareCoreQueries(db)
262
+ const {
263
+ qUserById, qUnverifiedUserIds, qUserByEmail, qInsertUser, qUpdateUser,
264
+ qGetSession, qListUserSessions, qInsertSession, qTouchSession, qDelSession, qDelUserSessions,
265
+ qGetOAuth, qLinkOAuth, qDelUserOAuth,
266
+ qInsertToken, qConsumeToken,
267
+ } = queries
152
268
 
153
- const qUserById = db.query<UserRow, [string]>('SELECT * FROM prunelle_auth_users WHERE id = ?')
154
- const qUserByEmail = db.query<UserRow, [string]>('SELECT * FROM prunelle_auth_users WHERE email = ?')
155
- const qInsertUser = db.query<null, [string, string, string | null, string | null, string, number, string | null, number, number]>(
156
- 'INSERT INTO prunelle_auth_users (id, email, name, avatar_url, role, email_verified, password_hash, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
157
- )
158
- const qUpdateUser = db.query<null, [string, string | null, string | null, string, number, string | null, number, string]>(
159
- 'UPDATE prunelle_auth_users SET email = ?, name = ?, avatar_url = ?, role = ?, email_verified = ?, password_hash = ?, updated_at = ? WHERE id = ?',
160
- )
161
- const qDelUser = db.query<null, [string]>('DELETE FROM prunelle_auth_users WHERE id = ?')
162
-
163
- const qGetSession = db.query<SessionRow, [string]>('SELECT * FROM prunelle_auth_sessions WHERE id = ?')
164
- const qListUserSessions = db.query<SessionRow, [string, number]>(
165
- 'SELECT * FROM prunelle_auth_sessions WHERE user_id = ? AND expires_at > ? ORDER BY created_at DESC',
166
- )
167
- const qInsertSession = db.query<null, [string, string, number, number, string | null, string | null]>(
168
- 'INSERT INTO prunelle_auth_sessions (id, user_id, expires_at, created_at, user_agent, ip) VALUES (?, ?, ?, ?, ?, ?)',
169
- )
170
- const qTouchSession = db.query<null, [number, string]>('UPDATE prunelle_auth_sessions SET expires_at = ? WHERE id = ?')
171
- const qDelSession = db.query<null, [string]>('DELETE FROM prunelle_auth_sessions WHERE id = ?')
172
- const qDelUserSessions = db.query<null, [string]>('DELETE FROM prunelle_auth_sessions WHERE user_id = ?')
173
-
174
- const qGetOAuth = db.query<OAuthRow, [string, string]>('SELECT * FROM prunelle_auth_oauth WHERE provider = ? AND provider_account_id = ?')
175
- const qListUserOAuth = db.query<OAuthRow, [string]>('SELECT * FROM prunelle_auth_oauth WHERE user_id = ? ORDER BY created_at ASC')
176
- const qLinkOAuth = db.query<null, [string, string, string, number]>(
177
- 'INSERT OR REPLACE INTO prunelle_auth_oauth (provider, provider_account_id, user_id, created_at) VALUES (?, ?, ?, ?)',
178
- )
179
- const qDelUserOAuth = db.query<null, [string]>('DELETE FROM prunelle_auth_oauth WHERE user_id = ?')
180
-
181
- const qInsertToken = db.query<null, [string, string | null, string, TokenKind, number]>(
182
- 'INSERT INTO prunelle_auth_tokens (token_hash, user_id, email, kind, expires_at) VALUES (?, ?, ?, ?, ?)',
183
- )
184
- const qConsumeToken = db.query<TokenRow, [string, TokenKind]>(
185
- 'DELETE FROM prunelle_auth_tokens WHERE token_hash = ? AND kind = ? RETURNING *',
186
- )
187
- const qDelUserTokens = db.query<null, [string]>('DELETE FROM prunelle_auth_tokens WHERE user_id = ?')
188
- const qDelEmailTokens = db.query<null, [string]>('DELETE FROM prunelle_auth_tokens WHERE email = ?')
269
+ const ext = createSqliteStoreExt(db)
189
270
 
190
- const delUserTx = db.transaction((userId: string) => {
191
- const user = qUserById.get(userId)
192
- qDelUserSessions.run(userId)
193
- qDelUserOAuth.run(userId)
194
- qDelUserTokens.run(userId)
195
- if (user)
196
- qDelEmailTokens.run(user.email)
197
- qDelUser.run(userId)
198
- })
271
+ const delUserTx = userDeletion(db, queries, ext)
199
272
 
200
- function listActiveSessions(userId: string, now = Date.now()): AuthSession[] {
201
- 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)!)
202
275
  }
203
276
 
204
- return keptInMemory(db.filename === ':memory:', {
277
+ return markSyncStore(keptInMemory(db.filename === ':memory:', {
278
+ ...ext.methods,
205
279
  db,
206
280
  close() {
207
281
  if (closed)
@@ -210,10 +284,16 @@ export function sqliteAuthStore(dbOrPath: string | Database = ':memory:'): AuthS
210
284
  if (ownsDb)
211
285
  db.close()
212
286
  },
213
- pruneExpired() {
287
+ pruneExpired(options) {
214
288
  const now = Date.now()
215
289
  db.run('DELETE FROM prunelle_auth_sessions WHERE expires_at <= ?', [now])
216
290
  db.run('DELETE FROM prunelle_auth_tokens WHERE expires_at <= ?', [now])
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
+ }
217
297
  },
218
298
  getUserById(id) {
219
299
  return rowToUser(qUserById.get(id))
@@ -262,22 +342,7 @@ export function sqliteAuthStore(dbOrPath: string | Database = ':memory:'): AuthS
262
342
  delUserTx(userId)
263
343
  },
264
344
  exportUser(userId): UserExport | null {
265
- const user = rowToUser(qUserById.get(userId))
266
- if (!user)
267
- return null
268
- const now = Date.now()
269
- const sessions = listActiveSessions(userId, now)
270
- const oauthAccounts = qListUserOAuth.all(userId).map(r => ({
271
- provider: r.provider,
272
- providerAccountId: r.provider_account_id,
273
- createdAt: r.created_at,
274
- }))
275
- return {
276
- user: toPublicUser(user),
277
- sessions,
278
- oauthAccounts,
279
- exportedAt: now,
280
- }
345
+ return exportSqliteUser(queries, ext, userId)
281
346
  },
282
347
  getSession(tokenHash) {
283
348
  const s = rowToSession(qGetSession.get(tokenHash))
@@ -333,5 +398,5 @@ export function sqliteAuthStore(dbOrPath: string | Database = ':memory:'): AuthS
333
398
  expiresAt: row.expires_at,
334
399
  }
335
400
  },
336
- })
401
+ }))
337
402
  }
@@ -0,0 +1,425 @@
1
+ // Extended AuthStore types (TOTP 2FA, Passkeys/WebAuthn, Organizations) and in-memory implementation.
2
+ // All extension methods are optional on `AuthStore` so existing custom stores remain 100% compatible.
3
+
4
+ export interface TotpRecord {
5
+ userId: string
6
+ /** AES-256-GCM encrypted base32 secret (`v1.<iv>.<ciphertext>`). */
7
+ encryptedSecret: string
8
+ enabled: boolean
9
+ /** Last accepted 30-second TOTP time step (prevents replay within the same window). */
10
+ lastUsedStep?: number | undefined
11
+ createdAt: number
12
+ updatedAt: number
13
+ }
14
+
15
+ export interface RecoveryCodeRecord {
16
+ id: string
17
+ userId: string
18
+ codeHash: string
19
+ salt: string
20
+ createdAt: number
21
+ }
22
+
23
+ export interface PasskeyRecord {
24
+ /** Base64url-encoded WebAuthn credential ID. */
25
+ id: string
26
+ userId: string
27
+ /** JSON-serialized JWK public key derived from the COSE key. */
28
+ publicKeyJwk: string
29
+ /** COSE algorithm identifier: -7 (ES256), -257 (RS256), -8 (EdDSA). */
30
+ algorithm: number
31
+ signCount: number
32
+ transports?: string[] | undefined
33
+ name?: string | undefined
34
+ aaguid?: string | undefined
35
+ createdAt: number
36
+ lastUsedAt?: number | undefined
37
+ }
38
+
39
+ export interface PasskeySummary {
40
+ id: string
41
+ name?: string | undefined
42
+ createdAt: number
43
+ lastUsedAt?: number | undefined
44
+ transports?: string[] | undefined
45
+ }
46
+
47
+ export interface Organization {
48
+ id: string
49
+ slug: string
50
+ name: string
51
+ createdAt: number
52
+ updatedAt: number
53
+ }
54
+
55
+ export interface OrgMembership {
56
+ orgId: string
57
+ userId: string
58
+ role: string
59
+ createdAt: number
60
+ }
61
+
62
+ export interface OrgInvitation {
63
+ id: string
64
+ orgId: string
65
+ email: string
66
+ role: string
67
+ invitedBy: string
68
+ tokenHash: string
69
+ expiresAt: number
70
+ createdAt: number
71
+ }
72
+
73
+ export interface UserOrgSummary {
74
+ org: Organization
75
+ role: string
76
+ joinedAt: number
77
+ }
78
+
79
+ export interface UserExportExt {
80
+ totp?: { enabled: boolean, createdAt: number, recoveryCodesRemaining: number } | undefined
81
+ passkeys?: PasskeySummary[] | undefined
82
+ organizations?: Array<{ orgId: string, slug: string, name: string, role: string, joinedAt: number }> | undefined
83
+ invitations?: Array<{ id: string, orgId: string, email: string, role: string, expiresAt: number, createdAt: number }> | undefined
84
+ }
85
+
86
+ export interface AuthStoreExt {
87
+ getTotp?(userId: string): TotpRecord | undefined | Promise<TotpRecord | undefined>
88
+ setTotp?(record: TotpRecord): void | Promise<void>
89
+ deleteTotp?(userId: string): void | Promise<void>
90
+ listRecoveryCodes?(userId: string): RecoveryCodeRecord[] | Promise<RecoveryCodeRecord[]>
91
+ setRecoveryCodes?(userId: string, codes: RecoveryCodeRecord[]): void | Promise<void>
92
+ consumeRecoveryCode?(id: string): boolean | Promise<boolean>
93
+ deleteRecoveryCodes?(userId: string): void | Promise<void>
94
+
95
+ getPasskey?(credentialId: string): PasskeyRecord | undefined | Promise<PasskeyRecord | undefined>
96
+ listPasskeys?(userId: string): PasskeyRecord[] | Promise<PasskeyRecord[]>
97
+ createPasskey?(record: PasskeyRecord): void | Promise<void>
98
+ updatePasskeyUsage?(credentialId: string, signCount: number, lastUsedAt: number): void | Promise<void>
99
+ deletePasskey?(userId: string, credentialId: string): boolean | Promise<boolean>
100
+ deleteUserPasskeys?(userId: string): void | Promise<void>
101
+
102
+ createOrg?(org: Organization): Organization | Promise<Organization>
103
+ getOrgById?(id: string): Organization | undefined | Promise<Organization | undefined>
104
+ getOrgBySlug?(slug: string): Organization | undefined | Promise<Organization | undefined>
105
+ deleteOrg?(orgId: string): void | Promise<void>
106
+ getOrgMember?(orgId: string, userId: string): OrgMembership | undefined | Promise<OrgMembership | undefined>
107
+ listOrgMembers?(orgId: string): OrgMembership[] | Promise<OrgMembership[]>
108
+ listUserOrgMemberships?(userId: string): UserOrgSummary[] | Promise<UserOrgSummary[]>
109
+ addOrgMember?(membership: OrgMembership): OrgMembership | Promise<OrgMembership>
110
+ updateOrgMemberRole?(orgId: string, userId: string, role: string): OrgMembership | undefined | Promise<OrgMembership | undefined>
111
+ removeOrgMember?(orgId: string, userId: string): boolean | Promise<boolean>
112
+ createOrgInvite?(invite: OrgInvitation): OrgInvitation | Promise<OrgInvitation>
113
+ getOrgInviteByTokenHash?(tokenHash: string): OrgInvitation | undefined | Promise<OrgInvitation | undefined>
114
+ listOrgInvites?(orgId: string): OrgInvitation[] | Promise<OrgInvitation[]>
115
+ deleteOrgInvite?(orgId: string, inviteId: string): boolean | Promise<boolean>
116
+ consumeOrgInvite?(tokenHash: string): OrgInvitation | undefined | Promise<OrgInvitation | undefined>
117
+ }
118
+
119
+ export function toPasskeySummary(record: PasskeyRecord): PasskeySummary {
120
+ return {
121
+ id: record.id,
122
+ createdAt: record.createdAt,
123
+ ...(record.name !== undefined ? { name: record.name } : {}),
124
+ ...(record.lastUsedAt !== undefined ? { lastUsedAt: record.lastUsedAt } : {}),
125
+ ...(record.transports !== undefined ? { transports: [...record.transports] } : {}),
126
+ }
127
+ }
128
+
129
+ export interface MemoryStoreExtHooks {
130
+ methods: Required<AuthStoreExt>
131
+ exportUserExt: (userId: string, email: string, now: number) => UserExportExt
132
+ deleteUserExt: (userId: string, email: string | undefined) => void
133
+ pruneExpiredExt: (now: number) => void
134
+ }
135
+
136
+ interface MemoryExtState {
137
+ totp: Map<string, TotpRecord>
138
+ recoveryCodes: Map<string, RecoveryCodeRecord>
139
+ passkeys: Map<string, PasskeyRecord>
140
+ orgs: Map<string, Organization>
141
+ orgsBySlug: Map<string, string>
142
+ orgMembers: Map<string, OrgMembership>
143
+ orgInvites: Map<string, OrgInvitation>
144
+ }
145
+
146
+ const memberKey = (orgId: string, userId: string): string => `${orgId}:${userId}`
147
+
148
+ function buildMemoryTotpPasskeyMethods(state: MemoryExtState) {
149
+ const clonePasskey = (rec: PasskeyRecord): PasskeyRecord => ({
150
+ ...rec,
151
+ ...(rec.transports ? { transports: [...rec.transports] } : {}),
152
+ })
153
+ return {
154
+ getTotp(userId: string): TotpRecord | undefined {
155
+ const rec = state.totp.get(userId)
156
+ return rec ? { ...rec } : undefined
157
+ },
158
+ setTotp(record: TotpRecord): void {
159
+ state.totp.set(record.userId, { ...record })
160
+ },
161
+ deleteTotp(userId: string): void {
162
+ state.totp.delete(userId)
163
+ },
164
+ listRecoveryCodes(userId: string): RecoveryCodeRecord[] {
165
+ const out: RecoveryCodeRecord[] = []
166
+ for (const rec of state.recoveryCodes.values()) {
167
+ if (rec.userId === userId)
168
+ out.push({ ...rec })
169
+ }
170
+ return out
171
+ },
172
+ setRecoveryCodes(userId: string, codes: RecoveryCodeRecord[]): void {
173
+ for (const [id, rec] of state.recoveryCodes) {
174
+ if (rec.userId === userId)
175
+ state.recoveryCodes.delete(id)
176
+ }
177
+ for (const rec of codes)
178
+ state.recoveryCodes.set(rec.id, { ...rec })
179
+ },
180
+ consumeRecoveryCode(id: string): boolean {
181
+ return state.recoveryCodes.delete(id)
182
+ },
183
+ deleteRecoveryCodes(userId: string): void {
184
+ for (const [id, rec] of state.recoveryCodes) {
185
+ if (rec.userId === userId)
186
+ state.recoveryCodes.delete(id)
187
+ }
188
+ },
189
+ getPasskey(credentialId: string): PasskeyRecord | undefined {
190
+ const rec = state.passkeys.get(credentialId)
191
+ return rec ? clonePasskey(rec) : undefined
192
+ },
193
+ listPasskeys(userId: string): PasskeyRecord[] {
194
+ const out: PasskeyRecord[] = []
195
+ for (const rec of state.passkeys.values()) {
196
+ if (rec.userId === userId)
197
+ out.push(clonePasskey(rec))
198
+ }
199
+ out.sort((a, b) => a.createdAt - b.createdAt)
200
+ return out
201
+ },
202
+ createPasskey(record: PasskeyRecord): void {
203
+ state.passkeys.set(record.id, clonePasskey(record))
204
+ },
205
+ updatePasskeyUsage(credentialId: string, signCount: number, lastUsedAt: number): void {
206
+ const rec = state.passkeys.get(credentialId)
207
+ if (rec) {
208
+ rec.signCount = signCount
209
+ rec.lastUsedAt = lastUsedAt
210
+ }
211
+ },
212
+ deletePasskey(userId: string, credentialId: string): boolean {
213
+ const rec = state.passkeys.get(credentialId)
214
+ if (!rec || rec.userId !== userId)
215
+ return false
216
+ return state.passkeys.delete(credentialId)
217
+ },
218
+ deleteUserPasskeys(userId: string): void {
219
+ for (const [id, rec] of state.passkeys) {
220
+ if (rec.userId === userId)
221
+ state.passkeys.delete(id)
222
+ }
223
+ },
224
+ }
225
+ }
226
+
227
+ function buildMemoryOrgMethods(state: MemoryExtState) {
228
+ return {
229
+ createOrg(org: Organization): Organization {
230
+ const copy: Organization = { ...org, slug: org.slug.toLowerCase() }
231
+ if (state.orgsBySlug.has(copy.slug))
232
+ throw new Error(`prunelle: organization slug "${copy.slug}" already exists`)
233
+ state.orgs.set(copy.id, copy)
234
+ state.orgsBySlug.set(copy.slug, copy.id)
235
+ return { ...copy }
236
+ },
237
+ getOrgById(id: string): Organization | undefined {
238
+ const rec = state.orgs.get(id)
239
+ return rec ? { ...rec } : undefined
240
+ },
241
+ getOrgBySlug(slug: string): Organization | undefined {
242
+ const id = state.orgsBySlug.get(slug.toLowerCase())
243
+ if (id === undefined)
244
+ return undefined
245
+ const rec = state.orgs.get(id)
246
+ return rec ? { ...rec } : undefined
247
+ },
248
+ deleteOrg(orgId: string): void {
249
+ const rec = state.orgs.get(orgId)
250
+ if (rec)
251
+ state.orgsBySlug.delete(rec.slug)
252
+ state.orgs.delete(orgId)
253
+ for (const [k, m] of state.orgMembers) {
254
+ if (m.orgId === orgId)
255
+ state.orgMembers.delete(k)
256
+ }
257
+ for (const [k, inv] of state.orgInvites) {
258
+ if (inv.orgId === orgId)
259
+ state.orgInvites.delete(k)
260
+ }
261
+ },
262
+ getOrgMember(orgId: string, userId: string): OrgMembership | undefined {
263
+ const m = state.orgMembers.get(memberKey(orgId, userId))
264
+ return m ? { ...m } : undefined
265
+ },
266
+ listOrgMembers(orgId: string): OrgMembership[] {
267
+ const out: OrgMembership[] = []
268
+ for (const m of state.orgMembers.values()) {
269
+ if (m.orgId === orgId)
270
+ out.push({ ...m })
271
+ }
272
+ out.sort((a, b) => a.createdAt - b.createdAt)
273
+ return out
274
+ },
275
+ listUserOrgMemberships(userId: string): UserOrgSummary[] {
276
+ const out: UserOrgSummary[] = []
277
+ for (const m of state.orgMembers.values()) {
278
+ if (m.userId !== userId)
279
+ continue
280
+ const org = state.orgs.get(m.orgId)
281
+ if (org)
282
+ out.push({ org: { ...org }, role: m.role, joinedAt: m.createdAt })
283
+ }
284
+ out.sort((a, b) => a.joinedAt - b.joinedAt)
285
+ return out
286
+ },
287
+ addOrgMember(membership: OrgMembership): OrgMembership {
288
+ const copy: OrgMembership = { ...membership }
289
+ state.orgMembers.set(memberKey(copy.orgId, copy.userId), copy)
290
+ return { ...copy }
291
+ },
292
+ updateOrgMemberRole(orgId: string, userId: string, role: string): OrgMembership | undefined {
293
+ const cur = state.orgMembers.get(memberKey(orgId, userId))
294
+ if (!cur)
295
+ return undefined
296
+ cur.role = role
297
+ return { ...cur }
298
+ },
299
+ removeOrgMember(orgId: string, userId: string): boolean {
300
+ return state.orgMembers.delete(memberKey(orgId, userId))
301
+ },
302
+ createOrgInvite(invite: OrgInvitation): OrgInvitation {
303
+ const copy: OrgInvitation = { ...invite, email: invite.email.trim().toLowerCase() }
304
+ state.orgInvites.set(copy.tokenHash, copy)
305
+ return { ...copy }
306
+ },
307
+ getOrgInviteByTokenHash(tokenHash: string): OrgInvitation | undefined {
308
+ const inv = state.orgInvites.get(tokenHash)
309
+ if (!inv)
310
+ return undefined
311
+ if (inv.expiresAt <= Date.now()) {
312
+ state.orgInvites.delete(tokenHash)
313
+ return undefined
314
+ }
315
+ return { ...inv }
316
+ },
317
+ listOrgInvites(orgId: string): OrgInvitation[] {
318
+ const now = Date.now()
319
+ const out: OrgInvitation[] = []
320
+ for (const [k, inv] of state.orgInvites) {
321
+ if (inv.expiresAt <= now) {
322
+ state.orgInvites.delete(k)
323
+ continue
324
+ }
325
+ if (inv.orgId === orgId)
326
+ out.push({ ...inv })
327
+ }
328
+ out.sort((a, b) => a.createdAt - b.createdAt)
329
+ return out
330
+ },
331
+ deleteOrgInvite(orgId: string, inviteId: string): boolean {
332
+ for (const [k, inv] of state.orgInvites) {
333
+ if (inv.orgId === orgId && inv.id === inviteId) {
334
+ state.orgInvites.delete(k)
335
+ return true
336
+ }
337
+ }
338
+ return false
339
+ },
340
+ consumeOrgInvite(tokenHash: string): OrgInvitation | undefined {
341
+ const inv = state.orgInvites.get(tokenHash)
342
+ if (!inv)
343
+ return undefined
344
+ state.orgInvites.delete(tokenHash)
345
+ if (inv.expiresAt <= Date.now())
346
+ return undefined
347
+ return { ...inv }
348
+ },
349
+ }
350
+ }
351
+
352
+ export function createMemoryStoreExt(): MemoryStoreExtHooks {
353
+ const state: MemoryExtState = {
354
+ totp: new Map(),
355
+ recoveryCodes: new Map(),
356
+ passkeys: new Map(),
357
+ orgs: new Map(),
358
+ orgsBySlug: new Map(),
359
+ orgMembers: new Map(),
360
+ orgInvites: new Map(),
361
+ }
362
+ const tp = buildMemoryTotpPasskeyMethods(state)
363
+ const org = buildMemoryOrgMethods(state)
364
+
365
+ return {
366
+ methods: { ...tp, ...org },
367
+ exportUserExt(userId, email, now) {
368
+ const totpRec = state.totp.get(userId)
369
+ const rcCount = tp.listRecoveryCodes(userId).length
370
+ const userPasskeys = tp.listPasskeys(userId).map(toPasskeySummary)
371
+ const organizations = org.listUserOrgMemberships(userId).map(item => ({
372
+ orgId: item.org.id,
373
+ slug: item.org.slug,
374
+ name: item.org.name,
375
+ role: item.role,
376
+ joinedAt: item.joinedAt,
377
+ }))
378
+ const invitations: NonNullable<UserExportExt['invitations']> = []
379
+ const normEmail = email.trim().toLowerCase()
380
+ for (const [k, inv] of state.orgInvites) {
381
+ if (inv.expiresAt <= now) {
382
+ state.orgInvites.delete(k)
383
+ continue
384
+ }
385
+ if (inv.email === normEmail || inv.invitedBy === userId) {
386
+ invitations.push({
387
+ id: inv.id,
388
+ orgId: inv.orgId,
389
+ email: inv.email,
390
+ role: inv.role,
391
+ expiresAt: inv.expiresAt,
392
+ createdAt: inv.createdAt,
393
+ })
394
+ }
395
+ }
396
+ invitations.sort((a, b) => a.createdAt - b.createdAt)
397
+ return {
398
+ ...(totpRec ? { totp: { enabled: totpRec.enabled, createdAt: totpRec.createdAt, recoveryCodesRemaining: rcCount } } : {}),
399
+ passkeys: userPasskeys,
400
+ organizations,
401
+ invitations,
402
+ }
403
+ },
404
+ deleteUserExt(userId, email) {
405
+ state.totp.delete(userId)
406
+ tp.deleteRecoveryCodes(userId)
407
+ tp.deleteUserPasskeys(userId)
408
+ for (const [k, m] of state.orgMembers) {
409
+ if (m.userId === userId)
410
+ state.orgMembers.delete(k)
411
+ }
412
+ const normEmail = email?.trim().toLowerCase()
413
+ for (const [k, inv] of state.orgInvites) {
414
+ if (inv.invitedBy === userId || (normEmail !== undefined && inv.email === normEmail))
415
+ state.orgInvites.delete(k)
416
+ }
417
+ },
418
+ pruneExpiredExt(now) {
419
+ for (const [k, inv] of state.orgInvites) {
420
+ if (inv.expiresAt <= now)
421
+ state.orgInvites.delete(k)
422
+ }
423
+ },
424
+ }
425
+ }