@prunellejs/auth 0.0.0-stage → 0.1.1

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/store.ts ADDED
@@ -0,0 +1,267 @@
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
+ export type TokenKind = 'magic-link' | 'verify-email' | 'reset-password'
35
+
36
+ export interface VerificationToken {
37
+ tokenHash: string
38
+ userId?: string | undefined
39
+ email: string
40
+ kind: TokenKind
41
+ expiresAt: number
42
+ }
43
+
44
+ export interface UserExport<TUser extends AuthUser = AuthUser> {
45
+ user: PublicUser<TUser>
46
+ sessions: AuthSession[]
47
+ oauthAccounts: Array<{ provider: string, providerAccountId: string, createdAt: number }>
48
+ exportedAt: number
49
+ }
50
+
51
+ export interface AuthStore<TUser extends AuthUser = AuthUser> {
52
+ getUserById(id: string): TUser | undefined | Promise<TUser | undefined>
53
+ getUserByEmail(email: string): TUser | undefined | Promise<TUser | undefined>
54
+ createUser(user: TUser): TUser | Promise<TUser>
55
+ updateUser(id: string, patch: Partial<Omit<TUser, 'id' | 'createdAt'>>): TUser | undefined | Promise<TUser | undefined>
56
+ deleteUser(userId: string): void | Promise<void>
57
+ exportUser(userId: string): UserExport<TUser> | null | Promise<UserExport<TUser> | null>
58
+
59
+ getSession(tokenHash: string): AuthSession | undefined | Promise<AuthSession | undefined>
60
+ listSessions(userId: string): AuthSession[] | Promise<AuthSession[]>
61
+ createSession(session: AuthSession): void | Promise<void>
62
+ updateSessionExpiry(tokenHash: string, expiresAt: number): void | Promise<void>
63
+ deleteSession(tokenHash: string): void | Promise<void>
64
+ deleteUserSessions(userId: string): void | Promise<void>
65
+
66
+ getOAuthAccount(provider: string, providerAccountId: string): OAuthAccount | undefined | Promise<OAuthAccount | undefined>
67
+ linkOAuthAccount(account: OAuthAccount): void | Promise<void>
68
+ deleteUserOAuthAccounts(userId: string): void | Promise<void>
69
+
70
+ createToken(token: VerificationToken): void | Promise<void>
71
+ consumeToken(tokenHash: string, kind: TokenKind): VerificationToken | undefined | Promise<VerificationToken | undefined>
72
+
73
+ pruneExpired(): void | Promise<void>
74
+ close?(): void | Promise<void>
75
+ }
76
+
77
+ export function normalizeEmail(email: string): string {
78
+ return email.trim().toLowerCase()
79
+ }
80
+
81
+ export function toPublicUser<TUser extends AuthUser = AuthUser>(user: TUser): PublicUser<TUser> {
82
+ const { passwordHash: _hash, ...pub } = user
83
+ return pub
84
+ }
85
+
86
+ interface MemoryState<TUser extends AuthUser = AuthUser> {
87
+ users: Map<string, TUser>
88
+ usersByEmail: Map<string, string>
89
+ sessions: Map<string, AuthSession>
90
+ oauth: Map<string, OAuthAccount>
91
+ tokens: Map<string, VerificationToken>
92
+ }
93
+
94
+ const inMemoryStores = new WeakSet<object>()
95
+
96
+ /** Marks `store` as one whose data lives in the process alone when `inMemory`, for `requires` to refuse it in production. */
97
+ export function keptInMemory<T extends object>(inMemory: boolean, store: T): T {
98
+ if (inMemory)
99
+ inMemoryStores.add(store)
100
+ return store
101
+ }
102
+
103
+ /** Whether the store loses every account and session when the process stops: `memoryAuthStore()`, or `sqliteAuthStore()` on `:memory:`. */
104
+ export function isKeptInMemory(store: object): boolean {
105
+ return inMemoryStores.has(store)
106
+ }
107
+
108
+ export function memoryAuthStore<TUser extends AuthUser = AuthUser>(): AuthStore<TUser> {
109
+ const state: MemoryState<TUser> = {
110
+ users: new Map(),
111
+ usersByEmail: new Map(),
112
+ sessions: new Map(),
113
+ oauth: new Map(),
114
+ tokens: new Map(),
115
+ }
116
+
117
+ return keptInMemory(true, {
118
+ getUserById(userId) {
119
+ return state.users.get(userId)
120
+ },
121
+ getUserByEmail(email) {
122
+ const uid = state.usersByEmail.get(normalizeEmail(email))
123
+ return uid !== undefined ? state.users.get(uid) : undefined
124
+ },
125
+ createUser(user) {
126
+ const norm: TUser = { ...user, email: normalizeEmail(user.email) }
127
+ state.users.set(norm.id, norm)
128
+ state.usersByEmail.set(norm.email, norm.id)
129
+ return norm
130
+ },
131
+ updateUser(userId, patch) {
132
+ const cur = state.users.get(userId)
133
+ if (!cur)
134
+ return undefined
135
+ const nextEmail = patch.email !== undefined ? normalizeEmail(patch.email) : cur.email
136
+ if (nextEmail !== cur.email) {
137
+ state.usersByEmail.delete(cur.email)
138
+ state.usersByEmail.set(nextEmail, userId)
139
+ }
140
+ const next: TUser = { ...cur, ...patch, email: nextEmail, updatedAt: patch.updatedAt ?? Date.now() }
141
+ state.users.set(userId, next)
142
+ return next
143
+ },
144
+ deleteUser(userId) {
145
+ const cur = state.users.get(userId)
146
+ state.users.delete(userId)
147
+ if (cur)
148
+ state.usersByEmail.delete(cur.email)
149
+ for (const [k, s] of state.sessions) {
150
+ if (s.userId === userId)
151
+ state.sessions.delete(k)
152
+ }
153
+ for (const [k, a] of state.oauth) {
154
+ if (a.userId === userId)
155
+ state.oauth.delete(k)
156
+ }
157
+ for (const [k, t] of state.tokens) {
158
+ if (t.userId === userId || (cur && t.email === cur.email))
159
+ state.tokens.delete(k)
160
+ }
161
+ },
162
+ exportUser(userId) {
163
+ const cur = state.users.get(userId)
164
+ if (!cur)
165
+ return null
166
+ const now = Date.now()
167
+ const sessions: AuthSession[] = []
168
+ for (const [k, s] of state.sessions) {
169
+ if (s.expiresAt <= now) {
170
+ state.sessions.delete(k)
171
+ continue
172
+ }
173
+ if (s.userId === userId)
174
+ sessions.push({ ...s })
175
+ }
176
+ sessions.sort((a, b) => b.createdAt - a.createdAt)
177
+ const oauthAccounts: UserExport['oauthAccounts'] = []
178
+ for (const a of state.oauth.values()) {
179
+ if (a.userId === userId)
180
+ oauthAccounts.push({ provider: a.provider, providerAccountId: a.providerAccountId, createdAt: a.createdAt })
181
+ }
182
+ oauthAccounts.sort((a, b) => a.createdAt - b.createdAt)
183
+ return {
184
+ user: toPublicUser(cur),
185
+ sessions,
186
+ oauthAccounts,
187
+ exportedAt: now,
188
+ }
189
+ },
190
+ getSession(tokenHash) {
191
+ const s = state.sessions.get(tokenHash)
192
+ if (!s)
193
+ return undefined
194
+ if (s.expiresAt <= Date.now()) {
195
+ state.sessions.delete(tokenHash)
196
+ return undefined
197
+ }
198
+ return s
199
+ },
200
+ listSessions(userId) {
201
+ const now = Date.now()
202
+ const sessions: AuthSession[] = []
203
+ for (const [k, s] of state.sessions) {
204
+ if (s.expiresAt <= now) {
205
+ state.sessions.delete(k)
206
+ continue
207
+ }
208
+ if (s.userId === userId)
209
+ sessions.push({ ...s })
210
+ }
211
+ sessions.sort((a, b) => b.createdAt - a.createdAt)
212
+ return sessions
213
+ },
214
+ createSession(session) {
215
+ state.sessions.set(session.id, session)
216
+ },
217
+ updateSessionExpiry(tokenHash, expiresAt) {
218
+ const s = state.sessions.get(tokenHash)
219
+ if (s)
220
+ s.expiresAt = expiresAt
221
+ },
222
+ deleteSession(tokenHash) {
223
+ state.sessions.delete(tokenHash)
224
+ },
225
+ deleteUserSessions(userId) {
226
+ for (const [k, s] of state.sessions) {
227
+ if (s.userId === userId)
228
+ state.sessions.delete(k)
229
+ }
230
+ },
231
+ getOAuthAccount(provider, providerAccountId) {
232
+ return state.oauth.get(`${provider}:${providerAccountId}`)
233
+ },
234
+ linkOAuthAccount(account) {
235
+ state.oauth.set(`${account.provider}:${account.providerAccountId}`, account)
236
+ },
237
+ deleteUserOAuthAccounts(userId) {
238
+ for (const [k, a] of state.oauth) {
239
+ if (a.userId === userId)
240
+ state.oauth.delete(k)
241
+ }
242
+ },
243
+ createToken(token) {
244
+ state.tokens.set(token.tokenHash, { ...token, email: normalizeEmail(token.email) })
245
+ },
246
+ consumeToken(tokenHash, kind) {
247
+ const tok = state.tokens.get(tokenHash)
248
+ if (!tok || tok.kind !== kind)
249
+ return undefined
250
+ state.tokens.delete(tokenHash)
251
+ if (tok.expiresAt <= Date.now())
252
+ return undefined
253
+ return tok
254
+ },
255
+ pruneExpired() {
256
+ const now = Date.now()
257
+ for (const [k, s] of state.sessions) {
258
+ if (s.expiresAt <= now)
259
+ state.sessions.delete(k)
260
+ }
261
+ for (const [k, t] of state.tokens) {
262
+ if (t.expiresAt <= now)
263
+ state.tokens.delete(k)
264
+ }
265
+ },
266
+ })
267
+ }
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.