@prunellejs/auth 0.1.1 → 0.7.3

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 { 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,145 @@ 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
+ // 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 {
145
262
  const ownsDb = typeof dbOrPath === 'string'
146
263
  if (ownsDb && dbOrPath !== ':memory:' && !dbOrPath.startsWith('file:'))
147
- mkdirSync(dirname(dbOrPath), { recursive: true })
264
+ ensurePrivateDbFile(dbOrPath)
148
265
  const db = ownsDb ? new Database(dbOrPath, { create: true }) : dbOrPath
149
266
  let closed = false
150
267
 
151
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
152
276
 
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 = ?')
277
+ const ext = createSqliteStoreExt(db)
173
278
 
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 = ?')
279
+ const delUserTx = userDeletion(db, queries, ext)
180
280
 
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 = ?')
189
-
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
- })
199
-
200
- function listActiveSessions(userId: string, now = Date.now()): AuthSession[] {
201
- 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)!)
202
283
  }
203
284
 
204
- return keptInMemory(db.filename === ':memory:', {
285
+ return markSyncStore(keptInMemory(db.filename === ':memory:', {
286
+ ...ext.methods,
205
287
  db,
206
288
  close() {
207
289
  if (closed)
@@ -210,10 +292,16 @@ export function sqliteAuthStore(dbOrPath: string | Database = ':memory:'): AuthS
210
292
  if (ownsDb)
211
293
  db.close()
212
294
  },
213
- pruneExpired() {
295
+ pruneExpired(options) {
214
296
  const now = Date.now()
215
297
  db.run('DELETE FROM prunelle_auth_sessions WHERE expires_at <= ?', [now])
216
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
+ }
217
305
  },
218
306
  getUserById(id) {
219
307
  return rowToUser(qUserById.get(id))
@@ -262,22 +350,7 @@ export function sqliteAuthStore(dbOrPath: string | Database = ':memory:'): AuthS
262
350
  delUserTx(userId)
263
351
  },
264
352
  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
- }
353
+ return exportSqliteUser(queries, ext, userId)
281
354
  },
282
355
  getSession(tokenHash) {
283
356
  const s = rowToSession(qGetSession.get(tokenHash))
@@ -333,5 +406,5 @@ export function sqliteAuthStore(dbOrPath: string | Database = ':memory:'): AuthS
333
406
  expiresAt: row.expires_at,
334
407
  }
335
408
  },
336
- })
409
+ }))
337
410
  }