@prunellejs/auth 0.0.0-stage → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/sqlite.ts ADDED
@@ -0,0 +1,410 @@
1
+ // Zero-dependency production SQLite AuthStore built natively on `bun:sqlite`.
2
+ // Works out-of-the-box in single-binary `prunelle build --compile` deployments.
3
+
4
+ import type { AuthSession, AuthStore, AuthUser, OAuthAccount, TokenKind, UserExport, VerificationToken } from './store'
5
+ import { mkdirSync, writeFileSync } from 'node:fs'
6
+ import { dirname, isAbsolute, resolve } from 'node:path'
7
+ import { Database } from 'bun:sqlite'
8
+ import { getAppContext } from 'prunelle/internal/server'
9
+ import { createSqliteStoreExt } from './sqlite-ext'
10
+ import { keptInMemory, markSyncStore, normalizeEmail, toPublicUser } from './store'
11
+
12
+ interface UserRow {
13
+ id: string
14
+ email: string
15
+ name: string | null
16
+ avatar_url: string | null
17
+ role: string
18
+ email_verified: number
19
+ password_hash: string | null
20
+ created_at: number
21
+ updated_at: number
22
+ }
23
+
24
+ interface SessionRow {
25
+ id: string
26
+ user_id: string
27
+ expires_at: number
28
+ created_at: number
29
+ user_agent: string | null
30
+ ip: string | null
31
+ }
32
+
33
+ interface OAuthRow {
34
+ provider: string
35
+ provider_account_id: string
36
+ user_id: string
37
+ created_at: number
38
+ }
39
+
40
+ interface TokenRow {
41
+ token_hash: string
42
+ user_id: string | null
43
+ email: string
44
+ kind: TokenKind
45
+ expires_at: number
46
+ }
47
+
48
+ function rowToUser(row: UserRow | null): AuthUser | undefined {
49
+ if (!row)
50
+ return undefined
51
+ return {
52
+ id: row.id,
53
+ email: row.email,
54
+ ...(row.name !== null ? { name: row.name } : {}),
55
+ ...(row.avatar_url !== null ? { avatarUrl: row.avatar_url } : {}),
56
+ role: row.role,
57
+ emailVerified: row.email_verified === 1,
58
+ ...(row.password_hash !== null ? { passwordHash: row.password_hash } : {}),
59
+ createdAt: row.created_at,
60
+ updatedAt: row.updated_at,
61
+ }
62
+ }
63
+
64
+ function rowToSession(row: SessionRow | null): AuthSession | undefined {
65
+ if (!row)
66
+ return undefined
67
+ return {
68
+ id: row.id,
69
+ userId: row.user_id,
70
+ expiresAt: row.expires_at,
71
+ createdAt: row.created_at,
72
+ ...(row.user_agent !== null ? { userAgent: row.user_agent } : {}),
73
+ ...(row.ip !== null ? { ip: row.ip } : {}),
74
+ }
75
+ }
76
+
77
+ const AUTH_TABLES = ['users', 'sessions', 'oauth', 'tokens']
78
+ const KAY_INDEXES = ['sessions_user', 'sessions_exp', 'oauth_user', 'tokens_exp']
79
+
80
+ // A database kay created keeps its accounts: its kay_auth_* tables take prunelle's names, SQLite moving the foreign keys with them.
81
+ function adoptKayTables(db: Database): void {
82
+ const tables = new Set(db.query<{ name: string }, []>(`SELECT name FROM sqlite_master WHERE type = 'table'`).all().map(row => row.name))
83
+ if (!tables.has('kay_auth_users') || tables.has('prunelle_auth_users'))
84
+ return
85
+ db.transaction(() => {
86
+ for (const table of AUTH_TABLES) {
87
+ if (tables.has(`kay_auth_${table}`))
88
+ db.exec(`ALTER TABLE kay_auth_${table} RENAME TO prunelle_auth_${table}`)
89
+ }
90
+ for (const index of KAY_INDEXES)
91
+ db.exec(`DROP INDEX IF EXISTS idx_kay_auth_${index}`)
92
+ })()
93
+ }
94
+
95
+ function createSchema(db: Database): void {
96
+ db.exec(`
97
+ PRAGMA busy_timeout = 5000;
98
+ PRAGMA journal_mode = WAL;
99
+ PRAGMA foreign_keys = ON;
100
+ PRAGMA secure_delete = ON;
101
+ `)
102
+ adoptKayTables(db)
103
+ db.exec(`
104
+ CREATE TABLE IF NOT EXISTS prunelle_auth_users (
105
+ id TEXT PRIMARY KEY,
106
+ email TEXT NOT NULL UNIQUE,
107
+ name TEXT,
108
+ avatar_url TEXT,
109
+ role TEXT NOT NULL DEFAULT 'user',
110
+ email_verified INTEGER NOT NULL DEFAULT 0,
111
+ password_hash TEXT,
112
+ created_at INTEGER NOT NULL,
113
+ updated_at INTEGER NOT NULL
114
+ );
115
+ CREATE INDEX IF NOT EXISTS idx_prunelle_auth_users_unverified ON prunelle_auth_users(created_at) WHERE email_verified = 0;
116
+
117
+ CREATE TABLE IF NOT EXISTS prunelle_auth_sessions (
118
+ id TEXT PRIMARY KEY,
119
+ user_id TEXT NOT NULL REFERENCES prunelle_auth_users(id) ON DELETE CASCADE,
120
+ expires_at INTEGER NOT NULL,
121
+ created_at INTEGER NOT NULL,
122
+ user_agent TEXT,
123
+ ip TEXT
124
+ );
125
+ CREATE INDEX IF NOT EXISTS idx_prunelle_auth_sessions_user ON prunelle_auth_sessions(user_id);
126
+ CREATE INDEX IF NOT EXISTS idx_prunelle_auth_sessions_exp ON prunelle_auth_sessions(expires_at);
127
+
128
+ CREATE TABLE IF NOT EXISTS prunelle_auth_oauth (
129
+ provider TEXT NOT NULL,
130
+ provider_account_id TEXT NOT NULL,
131
+ user_id TEXT NOT NULL REFERENCES prunelle_auth_users(id) ON DELETE CASCADE,
132
+ created_at INTEGER NOT NULL,
133
+ PRIMARY KEY (provider, provider_account_id)
134
+ );
135
+ CREATE INDEX IF NOT EXISTS idx_prunelle_auth_oauth_user ON prunelle_auth_oauth(user_id);
136
+
137
+ CREATE TABLE IF NOT EXISTS prunelle_auth_tokens (
138
+ token_hash TEXT PRIMARY KEY,
139
+ user_id TEXT REFERENCES prunelle_auth_users(id) ON DELETE CASCADE,
140
+ email TEXT NOT NULL,
141
+ kind TEXT NOT NULL,
142
+ expires_at INTEGER NOT NULL
143
+ );
144
+ CREATE INDEX IF NOT EXISTS idx_prunelle_auth_tokens_exp ON prunelle_auth_tokens(expires_at);
145
+ `)
146
+ }
147
+
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
+ // 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 {
262
+ const ownsDb = typeof dbOrPath === 'string'
263
+ if (ownsDb && dbOrPath !== ':memory:' && !dbOrPath.startsWith('file:'))
264
+ ensurePrivateDbFile(dbOrPath)
265
+ const db = ownsDb ? new Database(dbOrPath, { create: true }) : dbOrPath
266
+ let closed = false
267
+
268
+ createSchema(db)
269
+ const queries = prepareCoreQueries(db)
270
+ const {
271
+ qUserById, qUnverifiedUserIds, qUserByEmail, qInsertUser, qUpdateUser,
272
+ qGetSession, qListUserSessions, qInsertSession, qTouchSession, qDelSession, qDelUserSessions,
273
+ qGetOAuth, qLinkOAuth, qDelUserOAuth,
274
+ qInsertToken, qConsumeToken,
275
+ } = queries
276
+
277
+ const ext = createSqliteStoreExt(db)
278
+
279
+ const delUserTx = userDeletion(db, queries, ext)
280
+
281
+ function listActiveSessions(userId: string): AuthSession[] {
282
+ return qListUserSessions.all(userId, Date.now()).map(row => rowToSession(row)!)
283
+ }
284
+
285
+ return markSyncStore(keptInMemory(db.filename === ':memory:', {
286
+ ...ext.methods,
287
+ db,
288
+ close() {
289
+ if (closed)
290
+ return
291
+ closed = true
292
+ if (ownsDb)
293
+ db.close()
294
+ },
295
+ pruneExpired(options) {
296
+ const now = Date.now()
297
+ db.run('DELETE FROM prunelle_auth_sessions WHERE expires_at <= ?', [now])
298
+ db.run('DELETE FROM prunelle_auth_tokens WHERE expires_at <= ?', [now])
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
+ }
305
+ },
306
+ getUserById(id) {
307
+ return rowToUser(qUserById.get(id))
308
+ },
309
+ getUserByEmail(email) {
310
+ return rowToUser(qUserByEmail.get(normalizeEmail(email)))
311
+ },
312
+ createUser(user) {
313
+ const norm: AuthUser = { ...user, email: normalizeEmail(user.email) }
314
+ qInsertUser.run(
315
+ norm.id,
316
+ norm.email,
317
+ norm.name ?? null,
318
+ norm.avatarUrl ?? null,
319
+ norm.role,
320
+ norm.emailVerified ? 1 : 0,
321
+ norm.passwordHash ?? null,
322
+ norm.createdAt,
323
+ norm.updatedAt,
324
+ )
325
+ return norm
326
+ },
327
+ updateUser(id, patch) {
328
+ const cur = rowToUser(qUserById.get(id))
329
+ if (!cur)
330
+ return undefined
331
+ const next: AuthUser = {
332
+ ...cur,
333
+ ...patch,
334
+ email: patch.email !== undefined ? normalizeEmail(patch.email) : cur.email,
335
+ updatedAt: patch.updatedAt ?? Date.now(),
336
+ }
337
+ qUpdateUser.run(
338
+ next.email,
339
+ next.name ?? null,
340
+ next.avatarUrl ?? null,
341
+ next.role,
342
+ next.emailVerified ? 1 : 0,
343
+ next.passwordHash ?? null,
344
+ next.updatedAt,
345
+ id,
346
+ )
347
+ return next
348
+ },
349
+ deleteUser(userId) {
350
+ delUserTx(userId)
351
+ },
352
+ exportUser(userId): UserExport | null {
353
+ return exportSqliteUser(queries, ext, userId)
354
+ },
355
+ getSession(tokenHash) {
356
+ const s = rowToSession(qGetSession.get(tokenHash))
357
+ if (!s)
358
+ return undefined
359
+ if (s.expiresAt <= Date.now()) {
360
+ qDelSession.run(tokenHash)
361
+ return undefined
362
+ }
363
+ return s
364
+ },
365
+ listSessions(userId) {
366
+ return listActiveSessions(userId)
367
+ },
368
+ createSession(session) {
369
+ qInsertSession.run(session.id, session.userId, session.expiresAt, session.createdAt, session.userAgent ?? null, session.ip ?? null)
370
+ },
371
+ updateSessionExpiry(tokenHash, expiresAt) {
372
+ qTouchSession.run(expiresAt, tokenHash)
373
+ },
374
+ deleteSession(tokenHash) {
375
+ qDelSession.run(tokenHash)
376
+ },
377
+ deleteUserSessions(userId) {
378
+ qDelUserSessions.run(userId)
379
+ },
380
+ getOAuthAccount(provider, providerAccountId) {
381
+ const r = qGetOAuth.get(provider, providerAccountId)
382
+ if (!r)
383
+ return undefined
384
+ return { provider: r.provider, providerAccountId: r.provider_account_id, userId: r.user_id, createdAt: r.created_at }
385
+ },
386
+ linkOAuthAccount(account: OAuthAccount) {
387
+ qLinkOAuth.run(account.provider, account.providerAccountId, account.userId, account.createdAt)
388
+ },
389
+ deleteUserOAuthAccounts(userId) {
390
+ qDelUserOAuth.run(userId)
391
+ },
392
+ createToken(token: VerificationToken) {
393
+ qInsertToken.run(token.tokenHash, token.userId ?? null, normalizeEmail(token.email), token.kind, token.expiresAt)
394
+ },
395
+ consumeToken(tokenHash, kind) {
396
+ const row = qConsumeToken.get(tokenHash, kind)
397
+ if (!row)
398
+ return undefined
399
+ if (row.expires_at <= Date.now())
400
+ return undefined
401
+ return {
402
+ tokenHash: row.token_hash,
403
+ ...(row.user_id !== null ? { userId: row.user_id } : {}),
404
+ email: row.email,
405
+ kind: row.kind,
406
+ expiresAt: row.expires_at,
407
+ }
408
+ },
409
+ }))
410
+ }