@prunellejs/auth 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/sqlite.ts ADDED
@@ -0,0 +1,351 @@
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 } from 'node:fs'
6
+ import { dirname } from 'node:path'
7
+ import { Database } from 'bun:sqlite'
8
+ import { createSqliteStoreExt } from './sqlite-ext'
9
+ import { keptInMemory, markSyncStore, normalizeEmail, toPublicUser } from './store'
10
+
11
+ interface UserRow {
12
+ id: string
13
+ email: string
14
+ name: string | null
15
+ avatar_url: string | null
16
+ role: string
17
+ email_verified: number
18
+ password_hash: string | null
19
+ created_at: number
20
+ updated_at: number
21
+ }
22
+
23
+ interface SessionRow {
24
+ id: string
25
+ user_id: string
26
+ expires_at: number
27
+ created_at: number
28
+ user_agent: string | null
29
+ ip: string | null
30
+ }
31
+
32
+ interface OAuthRow {
33
+ provider: string
34
+ provider_account_id: string
35
+ user_id: string
36
+ created_at: number
37
+ }
38
+
39
+ interface TokenRow {
40
+ token_hash: string
41
+ user_id: string | null
42
+ email: string
43
+ kind: TokenKind
44
+ expires_at: number
45
+ }
46
+
47
+ function rowToUser(row: UserRow | null): AuthUser | undefined {
48
+ if (!row)
49
+ return undefined
50
+ return {
51
+ id: row.id,
52
+ email: row.email,
53
+ ...(row.name !== null ? { name: row.name } : {}),
54
+ ...(row.avatar_url !== null ? { avatarUrl: row.avatar_url } : {}),
55
+ role: row.role,
56
+ emailVerified: row.email_verified === 1,
57
+ ...(row.password_hash !== null ? { passwordHash: row.password_hash } : {}),
58
+ createdAt: row.created_at,
59
+ updatedAt: row.updated_at,
60
+ }
61
+ }
62
+
63
+ function rowToSession(row: SessionRow | null): AuthSession | undefined {
64
+ if (!row)
65
+ return undefined
66
+ return {
67
+ id: row.id,
68
+ userId: row.user_id,
69
+ expiresAt: row.expires_at,
70
+ createdAt: row.created_at,
71
+ ...(row.user_agent !== null ? { userAgent: row.user_agent } : {}),
72
+ ...(row.ip !== null ? { ip: row.ip } : {}),
73
+ }
74
+ }
75
+
76
+ const AUTH_TABLES = ['users', 'sessions', 'oauth', 'tokens']
77
+ const KAY_INDEXES = ['sessions_user', 'sessions_exp', 'oauth_user', 'tokens_exp']
78
+
79
+ // A database kay created keeps its accounts: its kay_auth_* tables take prunelle's names, SQLite moving the foreign keys with them.
80
+ function adoptKayTables(db: Database): void {
81
+ const tables = new Set(db.query<{ name: string }, []>(`SELECT name FROM sqlite_master WHERE type = 'table'`).all().map(row => row.name))
82
+ if (!tables.has('kay_auth_users') || tables.has('prunelle_auth_users'))
83
+ return
84
+ db.transaction(() => {
85
+ for (const table of AUTH_TABLES) {
86
+ if (tables.has(`kay_auth_${table}`))
87
+ db.exec(`ALTER TABLE kay_auth_${table} RENAME TO prunelle_auth_${table}`)
88
+ }
89
+ for (const index of KAY_INDEXES)
90
+ db.exec(`DROP INDEX IF EXISTS idx_kay_auth_${index}`)
91
+ })()
92
+ }
93
+
94
+ function createSchema(db: Database): void {
95
+ db.exec(`
96
+ PRAGMA busy_timeout = 5000;
97
+ PRAGMA journal_mode = WAL;
98
+ PRAGMA foreign_keys = ON;
99
+ `)
100
+ adoptKayTables(db)
101
+ db.exec(`
102
+ CREATE TABLE IF NOT EXISTS prunelle_auth_users (
103
+ id TEXT PRIMARY KEY,
104
+ email TEXT NOT NULL UNIQUE,
105
+ name TEXT,
106
+ avatar_url TEXT,
107
+ role TEXT NOT NULL DEFAULT 'user',
108
+ email_verified INTEGER NOT NULL DEFAULT 0,
109
+ password_hash TEXT,
110
+ created_at INTEGER NOT NULL,
111
+ updated_at INTEGER NOT NULL
112
+ );
113
+
114
+ CREATE TABLE IF NOT EXISTS prunelle_auth_sessions (
115
+ id TEXT PRIMARY KEY,
116
+ user_id TEXT NOT NULL REFERENCES prunelle_auth_users(id) ON DELETE CASCADE,
117
+ expires_at INTEGER NOT NULL,
118
+ created_at INTEGER NOT NULL,
119
+ user_agent TEXT,
120
+ ip TEXT
121
+ );
122
+ CREATE INDEX IF NOT EXISTS idx_prunelle_auth_sessions_user ON prunelle_auth_sessions(user_id);
123
+ CREATE INDEX IF NOT EXISTS idx_prunelle_auth_sessions_exp ON prunelle_auth_sessions(expires_at);
124
+
125
+ CREATE TABLE IF NOT EXISTS prunelle_auth_oauth (
126
+ provider TEXT NOT NULL,
127
+ provider_account_id TEXT NOT NULL,
128
+ user_id TEXT NOT NULL REFERENCES prunelle_auth_users(id) ON DELETE CASCADE,
129
+ created_at INTEGER NOT NULL,
130
+ PRIMARY KEY (provider, provider_account_id)
131
+ );
132
+ CREATE INDEX IF NOT EXISTS idx_prunelle_auth_oauth_user ON prunelle_auth_oauth(user_id);
133
+
134
+ CREATE TABLE IF NOT EXISTS prunelle_auth_tokens (
135
+ token_hash TEXT PRIMARY KEY,
136
+ user_id TEXT REFERENCES prunelle_auth_users(id) ON DELETE CASCADE,
137
+ email TEXT NOT NULL,
138
+ kind TEXT NOT NULL,
139
+ expires_at INTEGER NOT NULL
140
+ );
141
+ CREATE INDEX IF NOT EXISTS idx_prunelle_auth_tokens_exp ON prunelle_auth_tokens(expires_at);
142
+ `)
143
+ }
144
+
145
+ function prepareCoreQueries(db: Database) {
146
+ return {
147
+ qUserById: db.query<UserRow, [string]>('SELECT * FROM prunelle_auth_users WHERE id = ?'),
148
+ qUserByEmail: db.query<UserRow, [string]>('SELECT * FROM prunelle_auth_users WHERE email = ?'),
149
+ qInsertUser: db.query<null, [string, string, string | null, string | null, string, number, string | null, number, number]>(
150
+ 'INSERT INTO prunelle_auth_users (id, email, name, avatar_url, role, email_verified, password_hash, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
151
+ ),
152
+ qUpdateUser: db.query<null, [string, string | null, string | null, string, number, string | null, number, string]>(
153
+ 'UPDATE prunelle_auth_users SET email = ?, name = ?, avatar_url = ?, role = ?, email_verified = ?, password_hash = ?, updated_at = ? WHERE id = ?',
154
+ ),
155
+ qDelUser: db.query<null, [string]>('DELETE FROM prunelle_auth_users WHERE id = ?'),
156
+ qGetSession: db.query<SessionRow, [string]>('SELECT * FROM prunelle_auth_sessions WHERE id = ?'),
157
+ qListUserSessions: db.query<SessionRow, [string, number]>(
158
+ 'SELECT * FROM prunelle_auth_sessions WHERE user_id = ? AND expires_at > ? ORDER BY created_at DESC',
159
+ ),
160
+ qInsertSession: db.query<null, [string, string, number, number, string | null, string | null]>(
161
+ 'INSERT INTO prunelle_auth_sessions (id, user_id, expires_at, created_at, user_agent, ip) VALUES (?, ?, ?, ?, ?, ?)',
162
+ ),
163
+ qTouchSession: db.query<null, [number, string]>('UPDATE prunelle_auth_sessions SET expires_at = ? WHERE id = ?'),
164
+ qDelSession: db.query<null, [string]>('DELETE FROM prunelle_auth_sessions WHERE id = ?'),
165
+ qDelUserSessions: db.query<null, [string]>('DELETE FROM prunelle_auth_sessions WHERE user_id = ?'),
166
+ qGetOAuth: db.query<OAuthRow, [string, string]>('SELECT * FROM prunelle_auth_oauth WHERE provider = ? AND provider_account_id = ?'),
167
+ qListUserOAuth: db.query<OAuthRow, [string]>('SELECT * FROM prunelle_auth_oauth WHERE user_id = ? ORDER BY created_at ASC'),
168
+ qLinkOAuth: db.query<null, [string, string, string, number]>(
169
+ 'INSERT OR REPLACE INTO prunelle_auth_oauth (provider, provider_account_id, user_id, created_at) VALUES (?, ?, ?, ?)',
170
+ ),
171
+ qDelUserOAuth: db.query<null, [string]>('DELETE FROM prunelle_auth_oauth WHERE user_id = ?'),
172
+ qInsertToken: db.query<null, [string, string | null, string, TokenKind, number]>(
173
+ 'INSERT INTO prunelle_auth_tokens (token_hash, user_id, email, kind, expires_at) VALUES (?, ?, ?, ?, ?)',
174
+ ),
175
+ qConsumeToken: db.query<TokenRow, [string, TokenKind]>(
176
+ 'DELETE FROM prunelle_auth_tokens WHERE token_hash = ? AND kind = ? RETURNING *',
177
+ ),
178
+ qDelUserTokens: db.query<null, [string]>('DELETE FROM prunelle_auth_tokens WHERE user_id = ?'),
179
+ qDelEmailTokens: db.query<null, [string]>('DELETE FROM prunelle_auth_tokens WHERE email = ?'),
180
+ }
181
+ }
182
+
183
+ export function sqliteAuthStore(dbOrPath: string | Database = ':memory:'): AuthStore & { readonly db: Database } {
184
+ const ownsDb = typeof dbOrPath === 'string'
185
+ if (ownsDb && dbOrPath !== ':memory:' && !dbOrPath.startsWith('file:'))
186
+ mkdirSync(dirname(dbOrPath), { recursive: true })
187
+ const db = ownsDb ? new Database(dbOrPath, { create: true }) : dbOrPath
188
+ let closed = false
189
+
190
+ createSchema(db)
191
+ const {
192
+ qUserById, qUserByEmail, qInsertUser, qUpdateUser, qDelUser,
193
+ qGetSession, qListUserSessions, qInsertSession, qTouchSession, qDelSession, qDelUserSessions,
194
+ qGetOAuth, qListUserOAuth, qLinkOAuth, qDelUserOAuth,
195
+ qInsertToken, qConsumeToken, qDelUserTokens, qDelEmailTokens,
196
+ } = prepareCoreQueries(db)
197
+
198
+ const ext = createSqliteStoreExt(db)
199
+
200
+ const delUserTx = db.transaction((userId: string) => {
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
+ })
210
+
211
+ function listActiveSessions(userId: string, now = Date.now()): AuthSession[] {
212
+ return qListUserSessions.all(userId, now).map(row => rowToSession(row)!)
213
+ }
214
+
215
+ return markSyncStore(keptInMemory(db.filename === ':memory:', {
216
+ ...ext.methods,
217
+ db,
218
+ close() {
219
+ if (closed)
220
+ return
221
+ closed = true
222
+ if (ownsDb)
223
+ db.close()
224
+ },
225
+ pruneExpired() {
226
+ const now = Date.now()
227
+ db.run('DELETE FROM prunelle_auth_sessions WHERE expires_at <= ?', [now])
228
+ db.run('DELETE FROM prunelle_auth_tokens WHERE expires_at <= ?', [now])
229
+ ext.pruneExpiredExt(now)
230
+ },
231
+ getUserById(id) {
232
+ return rowToUser(qUserById.get(id))
233
+ },
234
+ getUserByEmail(email) {
235
+ return rowToUser(qUserByEmail.get(normalizeEmail(email)))
236
+ },
237
+ createUser(user) {
238
+ const norm: AuthUser = { ...user, email: normalizeEmail(user.email) }
239
+ qInsertUser.run(
240
+ norm.id,
241
+ norm.email,
242
+ norm.name ?? null,
243
+ norm.avatarUrl ?? null,
244
+ norm.role,
245
+ norm.emailVerified ? 1 : 0,
246
+ norm.passwordHash ?? null,
247
+ norm.createdAt,
248
+ norm.updatedAt,
249
+ )
250
+ return norm
251
+ },
252
+ updateUser(id, patch) {
253
+ const cur = rowToUser(qUserById.get(id))
254
+ if (!cur)
255
+ return undefined
256
+ const next: AuthUser = {
257
+ ...cur,
258
+ ...patch,
259
+ email: patch.email !== undefined ? normalizeEmail(patch.email) : cur.email,
260
+ updatedAt: patch.updatedAt ?? Date.now(),
261
+ }
262
+ qUpdateUser.run(
263
+ next.email,
264
+ next.name ?? null,
265
+ next.avatarUrl ?? null,
266
+ next.role,
267
+ next.emailVerified ? 1 : 0,
268
+ next.passwordHash ?? null,
269
+ next.updatedAt,
270
+ id,
271
+ )
272
+ return next
273
+ },
274
+ deleteUser(userId) {
275
+ delUserTx(userId)
276
+ },
277
+ exportUser(userId): UserExport | null {
278
+ const user = rowToUser(qUserById.get(userId))
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
+ }
295
+ },
296
+ getSession(tokenHash) {
297
+ const s = rowToSession(qGetSession.get(tokenHash))
298
+ if (!s)
299
+ return undefined
300
+ if (s.expiresAt <= Date.now()) {
301
+ qDelSession.run(tokenHash)
302
+ return undefined
303
+ }
304
+ return s
305
+ },
306
+ listSessions(userId) {
307
+ return listActiveSessions(userId)
308
+ },
309
+ createSession(session) {
310
+ qInsertSession.run(session.id, session.userId, session.expiresAt, session.createdAt, session.userAgent ?? null, session.ip ?? null)
311
+ },
312
+ updateSessionExpiry(tokenHash, expiresAt) {
313
+ qTouchSession.run(expiresAt, tokenHash)
314
+ },
315
+ deleteSession(tokenHash) {
316
+ qDelSession.run(tokenHash)
317
+ },
318
+ deleteUserSessions(userId) {
319
+ qDelUserSessions.run(userId)
320
+ },
321
+ getOAuthAccount(provider, providerAccountId) {
322
+ const r = qGetOAuth.get(provider, providerAccountId)
323
+ if (!r)
324
+ return undefined
325
+ return { provider: r.provider, providerAccountId: r.provider_account_id, userId: r.user_id, createdAt: r.created_at }
326
+ },
327
+ linkOAuthAccount(account: OAuthAccount) {
328
+ qLinkOAuth.run(account.provider, account.providerAccountId, account.userId, account.createdAt)
329
+ },
330
+ deleteUserOAuthAccounts(userId) {
331
+ qDelUserOAuth.run(userId)
332
+ },
333
+ createToken(token: VerificationToken) {
334
+ qInsertToken.run(token.tokenHash, token.userId ?? null, normalizeEmail(token.email), token.kind, token.expiresAt)
335
+ },
336
+ consumeToken(tokenHash, kind) {
337
+ const row = qConsumeToken.get(tokenHash, kind)
338
+ if (!row)
339
+ return undefined
340
+ if (row.expires_at <= Date.now())
341
+ return undefined
342
+ return {
343
+ tokenHash: row.token_hash,
344
+ ...(row.user_id !== null ? { userId: row.user_id } : {}),
345
+ email: row.email,
346
+ kind: row.kind,
347
+ expiresAt: row.expires_at,
348
+ }
349
+ },
350
+ }))
351
+ }