@prunellejs/auth 0.0.0-stage → 0.5.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 ADDED
@@ -0,0 +1,337 @@
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 { keptInMemory, markSyncStore, normalizeEmail, toPublicUser } from './store'
9
+
10
+ interface UserRow {
11
+ id: string
12
+ email: string
13
+ name: string | null
14
+ avatar_url: string | null
15
+ role: string
16
+ email_verified: number
17
+ password_hash: string | null
18
+ created_at: number
19
+ updated_at: number
20
+ }
21
+
22
+ interface SessionRow {
23
+ id: string
24
+ user_id: string
25
+ expires_at: number
26
+ created_at: number
27
+ user_agent: string | null
28
+ ip: string | null
29
+ }
30
+
31
+ interface OAuthRow {
32
+ provider: string
33
+ provider_account_id: string
34
+ user_id: string
35
+ created_at: number
36
+ }
37
+
38
+ interface TokenRow {
39
+ token_hash: string
40
+ user_id: string | null
41
+ email: string
42
+ kind: TokenKind
43
+ expires_at: number
44
+ }
45
+
46
+ function rowToUser(row: UserRow | null): AuthUser | undefined {
47
+ if (!row)
48
+ return undefined
49
+ return {
50
+ id: row.id,
51
+ email: row.email,
52
+ ...(row.name !== null ? { name: row.name } : {}),
53
+ ...(row.avatar_url !== null ? { avatarUrl: row.avatar_url } : {}),
54
+ role: row.role,
55
+ emailVerified: row.email_verified === 1,
56
+ ...(row.password_hash !== null ? { passwordHash: row.password_hash } : {}),
57
+ createdAt: row.created_at,
58
+ updatedAt: row.updated_at,
59
+ }
60
+ }
61
+
62
+ function rowToSession(row: SessionRow | null): AuthSession | undefined {
63
+ if (!row)
64
+ return undefined
65
+ return {
66
+ id: row.id,
67
+ userId: row.user_id,
68
+ expiresAt: row.expires_at,
69
+ createdAt: row.created_at,
70
+ ...(row.user_agent !== null ? { userAgent: row.user_agent } : {}),
71
+ ...(row.ip !== null ? { ip: row.ip } : {}),
72
+ }
73
+ }
74
+
75
+ const AUTH_TABLES = ['users', 'sessions', 'oauth', 'tokens']
76
+ const KAY_INDEXES = ['sessions_user', 'sessions_exp', 'oauth_user', 'tokens_exp']
77
+
78
+ // A database kay created keeps its accounts: its kay_auth_* tables take prunelle's names, SQLite moving the foreign keys with them.
79
+ function adoptKayTables(db: Database): void {
80
+ const tables = new Set(db.query<{ name: string }, []>(`SELECT name FROM sqlite_master WHERE type = 'table'`).all().map(row => row.name))
81
+ if (!tables.has('kay_auth_users') || tables.has('prunelle_auth_users'))
82
+ return
83
+ db.transaction(() => {
84
+ for (const table of AUTH_TABLES) {
85
+ if (tables.has(`kay_auth_${table}`))
86
+ db.exec(`ALTER TABLE kay_auth_${table} RENAME TO prunelle_auth_${table}`)
87
+ }
88
+ for (const index of KAY_INDEXES)
89
+ db.exec(`DROP INDEX IF EXISTS idx_kay_auth_${index}`)
90
+ })()
91
+ }
92
+
93
+ function createSchema(db: Database): void {
94
+ db.exec(`
95
+ PRAGMA busy_timeout = 5000;
96
+ PRAGMA journal_mode = WAL;
97
+ PRAGMA foreign_keys = ON;
98
+ `)
99
+ adoptKayTables(db)
100
+ db.exec(`
101
+ CREATE TABLE IF NOT EXISTS prunelle_auth_users (
102
+ id TEXT PRIMARY KEY,
103
+ email TEXT NOT NULL UNIQUE,
104
+ name TEXT,
105
+ avatar_url TEXT,
106
+ role TEXT NOT NULL DEFAULT 'user',
107
+ email_verified INTEGER NOT NULL DEFAULT 0,
108
+ password_hash TEXT,
109
+ created_at INTEGER NOT NULL,
110
+ updated_at INTEGER NOT NULL
111
+ );
112
+
113
+ CREATE TABLE IF NOT EXISTS prunelle_auth_sessions (
114
+ id TEXT PRIMARY KEY,
115
+ user_id TEXT NOT NULL REFERENCES prunelle_auth_users(id) ON DELETE CASCADE,
116
+ expires_at INTEGER NOT NULL,
117
+ created_at INTEGER NOT NULL,
118
+ user_agent TEXT,
119
+ ip TEXT
120
+ );
121
+ CREATE INDEX IF NOT EXISTS idx_prunelle_auth_sessions_user ON prunelle_auth_sessions(user_id);
122
+ CREATE INDEX IF NOT EXISTS idx_prunelle_auth_sessions_exp ON prunelle_auth_sessions(expires_at);
123
+
124
+ CREATE TABLE IF NOT EXISTS prunelle_auth_oauth (
125
+ provider TEXT NOT NULL,
126
+ provider_account_id TEXT NOT NULL,
127
+ user_id TEXT NOT NULL REFERENCES prunelle_auth_users(id) ON DELETE CASCADE,
128
+ created_at INTEGER NOT NULL,
129
+ PRIMARY KEY (provider, provider_account_id)
130
+ );
131
+ CREATE INDEX IF NOT EXISTS idx_prunelle_auth_oauth_user ON prunelle_auth_oauth(user_id);
132
+
133
+ CREATE TABLE IF NOT EXISTS prunelle_auth_tokens (
134
+ token_hash TEXT PRIMARY KEY,
135
+ user_id TEXT REFERENCES prunelle_auth_users(id) ON DELETE CASCADE,
136
+ email TEXT NOT NULL,
137
+ kind TEXT NOT NULL,
138
+ expires_at INTEGER NOT NULL
139
+ );
140
+ CREATE INDEX IF NOT EXISTS idx_prunelle_auth_tokens_exp ON prunelle_auth_tokens(expires_at);
141
+ `)
142
+ }
143
+
144
+ export function sqliteAuthStore(dbOrPath: string | Database = ':memory:'): AuthStore & { readonly db: Database } {
145
+ const ownsDb = typeof dbOrPath === 'string'
146
+ if (ownsDb && dbOrPath !== ':memory:' && !dbOrPath.startsWith('file:'))
147
+ mkdirSync(dirname(dbOrPath), { recursive: true })
148
+ const db = ownsDb ? new Database(dbOrPath, { create: true }) : dbOrPath
149
+ let closed = false
150
+
151
+ createSchema(db)
152
+
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 = ?')
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)!)
202
+ }
203
+
204
+ return markSyncStore(keptInMemory(db.filename === ':memory:', {
205
+ db,
206
+ close() {
207
+ if (closed)
208
+ return
209
+ closed = true
210
+ if (ownsDb)
211
+ db.close()
212
+ },
213
+ pruneExpired() {
214
+ const now = Date.now()
215
+ db.run('DELETE FROM prunelle_auth_sessions WHERE expires_at <= ?', [now])
216
+ db.run('DELETE FROM prunelle_auth_tokens WHERE expires_at <= ?', [now])
217
+ },
218
+ getUserById(id) {
219
+ return rowToUser(qUserById.get(id))
220
+ },
221
+ getUserByEmail(email) {
222
+ return rowToUser(qUserByEmail.get(normalizeEmail(email)))
223
+ },
224
+ createUser(user) {
225
+ const norm: AuthUser = { ...user, email: normalizeEmail(user.email) }
226
+ qInsertUser.run(
227
+ norm.id,
228
+ norm.email,
229
+ norm.name ?? null,
230
+ norm.avatarUrl ?? null,
231
+ norm.role,
232
+ norm.emailVerified ? 1 : 0,
233
+ norm.passwordHash ?? null,
234
+ norm.createdAt,
235
+ norm.updatedAt,
236
+ )
237
+ return norm
238
+ },
239
+ updateUser(id, patch) {
240
+ const cur = rowToUser(qUserById.get(id))
241
+ if (!cur)
242
+ return undefined
243
+ const next: AuthUser = {
244
+ ...cur,
245
+ ...patch,
246
+ email: patch.email !== undefined ? normalizeEmail(patch.email) : cur.email,
247
+ updatedAt: patch.updatedAt ?? Date.now(),
248
+ }
249
+ qUpdateUser.run(
250
+ next.email,
251
+ next.name ?? null,
252
+ next.avatarUrl ?? null,
253
+ next.role,
254
+ next.emailVerified ? 1 : 0,
255
+ next.passwordHash ?? null,
256
+ next.updatedAt,
257
+ id,
258
+ )
259
+ return next
260
+ },
261
+ deleteUser(userId) {
262
+ delUserTx(userId)
263
+ },
264
+ 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
+ }
281
+ },
282
+ getSession(tokenHash) {
283
+ const s = rowToSession(qGetSession.get(tokenHash))
284
+ if (!s)
285
+ return undefined
286
+ if (s.expiresAt <= Date.now()) {
287
+ qDelSession.run(tokenHash)
288
+ return undefined
289
+ }
290
+ return s
291
+ },
292
+ listSessions(userId) {
293
+ return listActiveSessions(userId)
294
+ },
295
+ createSession(session) {
296
+ qInsertSession.run(session.id, session.userId, session.expiresAt, session.createdAt, session.userAgent ?? null, session.ip ?? null)
297
+ },
298
+ updateSessionExpiry(tokenHash, expiresAt) {
299
+ qTouchSession.run(expiresAt, tokenHash)
300
+ },
301
+ deleteSession(tokenHash) {
302
+ qDelSession.run(tokenHash)
303
+ },
304
+ deleteUserSessions(userId) {
305
+ qDelUserSessions.run(userId)
306
+ },
307
+ getOAuthAccount(provider, providerAccountId) {
308
+ const r = qGetOAuth.get(provider, providerAccountId)
309
+ if (!r)
310
+ return undefined
311
+ return { provider: r.provider, providerAccountId: r.provider_account_id, userId: r.user_id, createdAt: r.created_at }
312
+ },
313
+ linkOAuthAccount(account: OAuthAccount) {
314
+ qLinkOAuth.run(account.provider, account.providerAccountId, account.userId, account.createdAt)
315
+ },
316
+ deleteUserOAuthAccounts(userId) {
317
+ qDelUserOAuth.run(userId)
318
+ },
319
+ createToken(token: VerificationToken) {
320
+ qInsertToken.run(token.tokenHash, token.userId ?? null, normalizeEmail(token.email), token.kind, token.expiresAt)
321
+ },
322
+ consumeToken(tokenHash, kind) {
323
+ const row = qConsumeToken.get(tokenHash, kind)
324
+ if (!row)
325
+ return undefined
326
+ if (row.expires_at <= Date.now())
327
+ return undefined
328
+ return {
329
+ tokenHash: row.token_hash,
330
+ ...(row.user_id !== null ? { userId: row.user_id } : {}),
331
+ email: row.email,
332
+ kind: row.kind,
333
+ expiresAt: row.expires_at,
334
+ }
335
+ },
336
+ }))
337
+ }
package/src/store.ts ADDED
@@ -0,0 +1,280 @@
1
+ // Clean pluggable AuthStore contract + zero-setup in-memory store for dev & tests.
2
+
3
+ export interface AuthUser {
4
+ id: string
5
+ email: string
6
+ name?: string | undefined
7
+ avatarUrl?: string | undefined
8
+ role: string
9
+ emailVerified: boolean
10
+ passwordHash?: string | undefined
11
+ createdAt: number
12
+ updatedAt: number
13
+ }
14
+
15
+ export type PublicUser<TUser extends AuthUser = AuthUser> = Omit<TUser, 'passwordHash'>
16
+
17
+ export interface AuthSession {
18
+ /** SHA-256 hex digest of the raw session cookie token (never store raw tokens!). */
19
+ id: string
20
+ userId: string
21
+ expiresAt: number
22
+ createdAt: number
23
+ userAgent?: string | undefined
24
+ ip?: string | undefined
25
+ }
26
+
27
+ export interface OAuthAccount {
28
+ provider: string
29
+ providerAccountId: string
30
+ userId: string
31
+ createdAt: number
32
+ }
33
+
34
+ /** Verification token purposes. `'reset-password'` is reserved for app-defined password-reset flows via `store.createToken`/`store.consumeToken`. */
35
+ export type TokenKind = 'magic-link' | 'verify-email' | 'reset-password'
36
+
37
+ export interface VerificationToken {
38
+ tokenHash: string
39
+ userId?: string | undefined
40
+ email: string
41
+ kind: TokenKind
42
+ expiresAt: number
43
+ }
44
+
45
+ export interface UserExport<TUser extends AuthUser = AuthUser> {
46
+ user: PublicUser<TUser>
47
+ sessions: AuthSession[]
48
+ oauthAccounts: Array<{ provider: string, providerAccountId: string, createdAt: number }>
49
+ exportedAt: number
50
+ }
51
+
52
+ export interface AuthStore<TUser extends AuthUser = AuthUser> {
53
+ getUserById(id: string): TUser | undefined | Promise<TUser | undefined>
54
+ getUserByEmail(email: string): TUser | undefined | Promise<TUser | undefined>
55
+ createUser(user: TUser): TUser | Promise<TUser>
56
+ updateUser(id: string, patch: Partial<Omit<TUser, 'id' | 'createdAt'>>): TUser | undefined | Promise<TUser | undefined>
57
+ deleteUser(userId: string): void | Promise<void>
58
+ exportUser(userId: string): UserExport<TUser> | null | Promise<UserExport<TUser> | null>
59
+
60
+ getSession(tokenHash: string): AuthSession | undefined | Promise<AuthSession | undefined>
61
+ listSessions(userId: string): AuthSession[] | Promise<AuthSession[]>
62
+ createSession(session: AuthSession): void | Promise<void>
63
+ updateSessionExpiry(tokenHash: string, expiresAt: number): void | Promise<void>
64
+ deleteSession(tokenHash: string): void | Promise<void>
65
+ deleteUserSessions(userId: string): void | Promise<void>
66
+
67
+ getOAuthAccount(provider: string, providerAccountId: string): OAuthAccount | undefined | Promise<OAuthAccount | undefined>
68
+ linkOAuthAccount(account: OAuthAccount): void | Promise<void>
69
+ deleteUserOAuthAccounts(userId: string): void | Promise<void>
70
+
71
+ createToken(token: VerificationToken): void | Promise<void>
72
+ consumeToken(tokenHash: string, kind: TokenKind): VerificationToken | undefined | Promise<VerificationToken | undefined>
73
+
74
+ pruneExpired(): void | Promise<void>
75
+ close?(): void | Promise<void>
76
+ }
77
+
78
+ export function normalizeEmail(email: string): string {
79
+ return email.trim().toLowerCase()
80
+ }
81
+
82
+ export function toPublicUser<TUser extends AuthUser = AuthUser>(user: TUser): PublicUser<TUser> {
83
+ const { passwordHash: _hash, ...pub } = user
84
+ return pub
85
+ }
86
+
87
+ interface MemoryState<TUser extends AuthUser = AuthUser> {
88
+ users: Map<string, TUser>
89
+ usersByEmail: Map<string, string>
90
+ sessions: Map<string, AuthSession>
91
+ oauth: Map<string, OAuthAccount>
92
+ tokens: Map<string, VerificationToken>
93
+ }
94
+
95
+ const inMemoryStores = new WeakSet<object>()
96
+ const syncStores = new WeakSet<object>()
97
+
98
+ /** Marks `store` as one whose data lives in the process alone when `inMemory`, for `requires` to refuse it in production. */
99
+ export function keptInMemory<T extends object>(inMemory: boolean, store: T): T {
100
+ if (inMemory)
101
+ inMemoryStores.add(store)
102
+ return store
103
+ }
104
+
105
+ /** Whether the store loses every account and session when the process stops: `memoryAuthStore()`, or `sqliteAuthStore()` on `:memory:`. */
106
+ export function isKeptInMemory(store: object): boolean {
107
+ return inMemoryStores.has(store)
108
+ }
109
+
110
+ /** Marks a built-in store whose methods are guaranteed synchronous, enabling lazy session resolution on the very first request. */
111
+ export function markSyncStore<T extends object>(store: T): T {
112
+ syncStores.add(store)
113
+ return store
114
+ }
115
+
116
+ /** Whether `store` is a known built-in synchronous `AuthStore`. */
117
+ export function isKnownSyncStore(store: object): boolean {
118
+ return syncStores.has(store)
119
+ }
120
+
121
+ export function memoryAuthStore<TUser extends AuthUser = AuthUser>(): AuthStore<TUser> {
122
+ const state: MemoryState<TUser> = {
123
+ users: new Map(),
124
+ usersByEmail: new Map(),
125
+ sessions: new Map(),
126
+ oauth: new Map(),
127
+ tokens: new Map(),
128
+ }
129
+
130
+ return markSyncStore(keptInMemory(true, {
131
+ getUserById(userId) {
132
+ return state.users.get(userId)
133
+ },
134
+ getUserByEmail(email) {
135
+ const uid = state.usersByEmail.get(normalizeEmail(email))
136
+ return uid !== undefined ? state.users.get(uid) : undefined
137
+ },
138
+ createUser(user) {
139
+ const norm: TUser = { ...user, email: normalizeEmail(user.email) }
140
+ state.users.set(norm.id, norm)
141
+ state.usersByEmail.set(norm.email, norm.id)
142
+ return norm
143
+ },
144
+ updateUser(userId, patch) {
145
+ const cur = state.users.get(userId)
146
+ if (!cur)
147
+ return undefined
148
+ const nextEmail = patch.email !== undefined ? normalizeEmail(patch.email) : cur.email
149
+ if (nextEmail !== cur.email) {
150
+ state.usersByEmail.delete(cur.email)
151
+ state.usersByEmail.set(nextEmail, userId)
152
+ }
153
+ const next: TUser = { ...cur, ...patch, email: nextEmail, updatedAt: patch.updatedAt ?? Date.now() }
154
+ state.users.set(userId, next)
155
+ return next
156
+ },
157
+ deleteUser(userId) {
158
+ const cur = state.users.get(userId)
159
+ state.users.delete(userId)
160
+ if (cur)
161
+ state.usersByEmail.delete(cur.email)
162
+ for (const [k, s] of state.sessions) {
163
+ if (s.userId === userId)
164
+ state.sessions.delete(k)
165
+ }
166
+ for (const [k, a] of state.oauth) {
167
+ if (a.userId === userId)
168
+ state.oauth.delete(k)
169
+ }
170
+ for (const [k, t] of state.tokens) {
171
+ if (t.userId === userId || (cur && t.email === cur.email))
172
+ state.tokens.delete(k)
173
+ }
174
+ },
175
+ exportUser(userId) {
176
+ const cur = state.users.get(userId)
177
+ if (!cur)
178
+ return null
179
+ const now = Date.now()
180
+ const sessions: AuthSession[] = []
181
+ for (const [k, s] of state.sessions) {
182
+ if (s.expiresAt <= now) {
183
+ state.sessions.delete(k)
184
+ continue
185
+ }
186
+ if (s.userId === userId)
187
+ sessions.push({ ...s })
188
+ }
189
+ sessions.sort((a, b) => b.createdAt - a.createdAt)
190
+ const oauthAccounts: UserExport['oauthAccounts'] = []
191
+ for (const a of state.oauth.values()) {
192
+ if (a.userId === userId)
193
+ oauthAccounts.push({ provider: a.provider, providerAccountId: a.providerAccountId, createdAt: a.createdAt })
194
+ }
195
+ oauthAccounts.sort((a, b) => a.createdAt - b.createdAt)
196
+ return {
197
+ user: toPublicUser(cur),
198
+ sessions,
199
+ oauthAccounts,
200
+ exportedAt: now,
201
+ }
202
+ },
203
+ getSession(tokenHash) {
204
+ const s = state.sessions.get(tokenHash)
205
+ if (!s)
206
+ return undefined
207
+ if (s.expiresAt <= Date.now()) {
208
+ state.sessions.delete(tokenHash)
209
+ return undefined
210
+ }
211
+ return s
212
+ },
213
+ listSessions(userId) {
214
+ const now = Date.now()
215
+ const sessions: AuthSession[] = []
216
+ for (const [k, s] of state.sessions) {
217
+ if (s.expiresAt <= now) {
218
+ state.sessions.delete(k)
219
+ continue
220
+ }
221
+ if (s.userId === userId)
222
+ sessions.push({ ...s })
223
+ }
224
+ sessions.sort((a, b) => b.createdAt - a.createdAt)
225
+ return sessions
226
+ },
227
+ createSession(session) {
228
+ state.sessions.set(session.id, session)
229
+ },
230
+ updateSessionExpiry(tokenHash, expiresAt) {
231
+ const s = state.sessions.get(tokenHash)
232
+ if (s)
233
+ s.expiresAt = expiresAt
234
+ },
235
+ deleteSession(tokenHash) {
236
+ state.sessions.delete(tokenHash)
237
+ },
238
+ deleteUserSessions(userId) {
239
+ for (const [k, s] of state.sessions) {
240
+ if (s.userId === userId)
241
+ state.sessions.delete(k)
242
+ }
243
+ },
244
+ getOAuthAccount(provider, providerAccountId) {
245
+ return state.oauth.get(`${provider}:${providerAccountId}`)
246
+ },
247
+ linkOAuthAccount(account) {
248
+ state.oauth.set(`${account.provider}:${account.providerAccountId}`, account)
249
+ },
250
+ deleteUserOAuthAccounts(userId) {
251
+ for (const [k, a] of state.oauth) {
252
+ if (a.userId === userId)
253
+ state.oauth.delete(k)
254
+ }
255
+ },
256
+ createToken(token) {
257
+ state.tokens.set(token.tokenHash, { ...token, email: normalizeEmail(token.email) })
258
+ },
259
+ consumeToken(tokenHash, kind) {
260
+ const tok = state.tokens.get(tokenHash)
261
+ if (!tok || tok.kind !== kind)
262
+ return undefined
263
+ state.tokens.delete(tokenHash)
264
+ if (tok.expiresAt <= Date.now())
265
+ return undefined
266
+ return tok
267
+ },
268
+ pruneExpired() {
269
+ const now = Date.now()
270
+ for (const [k, s] of state.sessions) {
271
+ if (s.expiresAt <= now)
272
+ state.sessions.delete(k)
273
+ }
274
+ for (const [k, t] of state.tokens) {
275
+ if (t.expiresAt <= now)
276
+ state.tokens.delete(k)
277
+ }
278
+ },
279
+ }))
280
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.