@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/llms.txt +65 -0
- package/package.json +26 -4
- package/src/crypto.ts +73 -0
- package/src/http.ts +111 -0
- package/src/index.ts +552 -0
- package/src/oauth-routes.ts +193 -0
- package/src/oauth.ts +155 -0
- package/src/routes.ts +269 -0
- package/src/session.ts +330 -0
- package/src/sqlite.ts +337 -0
- package/src/store.ts +267 -0
- package/README.md +0 -3
package/src/index.ts
ADDED
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
// @prunellejs/auth — Zero-dependency Bun-native authentication plugin for Prunelle.
|
|
2
|
+
// Built strictly on the public PrunellePlugin API (`api.use` + `api.route`).
|
|
3
|
+
// Supports Argon2id passwords, hashed DB sessions with sliding renewal, email verification,
|
|
4
|
+
// magic links, OAuth 2.0 + PKCE (S256), role/route guards, RGPD helpers, and memory or `bun:sqlite` stores.
|
|
5
|
+
|
|
6
|
+
import type { PrunellePlugin } from 'prunelle/config'
|
|
7
|
+
import type { PrunelleLocals, Middleware, RequestContext, TrustProxy } from 'prunelle/server'
|
|
8
|
+
import type { OAuthProvider } from './oauth'
|
|
9
|
+
|
|
10
|
+
import type { AuthSession, AuthStore, AuthUser, PublicUser, UserExport } from './store'
|
|
11
|
+
import { definePlugin } from 'prunelle/config'
|
|
12
|
+
import { createRateLimitStore, isHttpsRequest, nodeEnv, safeRedirect, wantsJson } from 'prunelle/server'
|
|
13
|
+
import { hashPassword, randomToken, sha256Hex } from './crypto'
|
|
14
|
+
import { authLimits, fail, isValidEmail } from './http'
|
|
15
|
+
import { registerOAuthRoutes } from './oauth-routes'
|
|
16
|
+
|
|
17
|
+
import { registerAuthRoutes } from './routes'
|
|
18
|
+
import { createSessionManager } from './session'
|
|
19
|
+
import { isKeptInMemory, memoryAuthStore, normalizeEmail, toPublicUser } from './store'
|
|
20
|
+
|
|
21
|
+
declare module 'prunelle/server' {
|
|
22
|
+
interface PrunelleLocals {
|
|
23
|
+
user?: PublicUser | undefined
|
|
24
|
+
session?: AuthSession | undefined
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface RateLimitOptions {
|
|
29
|
+
/** Attempts per window, per scope and address and per scope and email (default: 15). */
|
|
30
|
+
max?: number | undefined
|
|
31
|
+
/** Window duration in ms (default: 60_000). */
|
|
32
|
+
windowMs?: number | undefined
|
|
33
|
+
/** @deprecated Read by `createRateLimiter` only: the server's store bounds the auth limits. Removed in the next release. */
|
|
34
|
+
maxKeys?: number | undefined
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** @deprecated Use `api.rateLimiter()` in a plugin, or `rateLimit` on `api.route` and `action()`. Removed in the next release. */
|
|
38
|
+
export interface RateLimiter {
|
|
39
|
+
allow(key: string): boolean
|
|
40
|
+
sweep(now?: number): number
|
|
41
|
+
size(): number
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** @deprecated Use `api.rateLimiter()` in a plugin, or `rateLimit` on `api.route` and `action()`. Removed in the next release. */
|
|
45
|
+
export function createRateLimiter(opts: RateLimitOptions | false | undefined): RateLimiter {
|
|
46
|
+
if (opts === false)
|
|
47
|
+
return { allow: () => true, sweep: () => 0, size: () => 0 }
|
|
48
|
+
const store = createRateLimitStore({ maxKeys: opts?.maxKeys })
|
|
49
|
+
const limiter = store.limiter({ max: opts?.max ?? 15, windowMs: opts?.windowMs ?? 60_000 })
|
|
50
|
+
return { allow: key => limiter.hit(key) === 0, sweep: now => store.sweep(now), size: () => store.size }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export { safeRedirect } from 'prunelle/server'
|
|
54
|
+
export { discord, github, google, oauthProvider } from './oauth'
|
|
55
|
+
export type { OAuthPresetConfig, OAuthProfile, OAuthProvider } from './oauth'
|
|
56
|
+
export { memoryAuthStore, normalizeEmail, toPublicUser } from './store'
|
|
57
|
+
export type { AuthSession, AuthStore, AuthUser, OAuthAccount, PublicUser, TokenKind, UserExport, VerificationToken } from './store'
|
|
58
|
+
|
|
59
|
+
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
|
|
60
|
+
const DEFAULT_PRUNE_INTERVAL_MS = 15 * 60 * 1000
|
|
61
|
+
const MIN_PROD_SECRET_BYTES = 32
|
|
62
|
+
const LINK_PATHS = { 'magic-link': 'magic-link/verify', 'verify-email': 'verify-email' } as const
|
|
63
|
+
const LINK_MAILS = {
|
|
64
|
+
'magic-link': { subject: 'Your sign-in link', text: 'Sign in using this one-time link', html: 'Click to sign in', label: 'Sign in' },
|
|
65
|
+
'verify-email': { subject: 'Verify your email address', text: 'Confirm your email address using this one-time link', html: 'Click to verify your email address', label: 'Verify email' },
|
|
66
|
+
} as const
|
|
67
|
+
|
|
68
|
+
// Mailed links and OAuth callbacks start with `site`, so anything but an http(s) origin is a config mistake.
|
|
69
|
+
function siteOrigin(value: string): string {
|
|
70
|
+
const url = new URL(value)
|
|
71
|
+
if (url.protocol !== 'https:' && url.protocol !== 'http:')
|
|
72
|
+
throw new Error(`[prunelle/auth] \`site\` must be an http or https origin, got ${value}`)
|
|
73
|
+
return url.origin
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface AuthMailPayload {
|
|
77
|
+
to: string
|
|
78
|
+
subject: string
|
|
79
|
+
text: string
|
|
80
|
+
html?: string | undefined
|
|
81
|
+
url: string
|
|
82
|
+
kind: 'magic-link' | 'verify-email' | 'reset-password'
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Structural interface matching `@prunellejs/mail`'s `Mailer` so `createAuth({ mailer })` needs no glue callback. */
|
|
86
|
+
export interface AuthMailer {
|
|
87
|
+
send(message: {
|
|
88
|
+
to: string
|
|
89
|
+
subject: string
|
|
90
|
+
text?: string | undefined
|
|
91
|
+
html?: string | undefined
|
|
92
|
+
}): unknown
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export type CreateUserInput<TUser extends AuthUser = AuthUser> = {
|
|
96
|
+
email: string
|
|
97
|
+
password?: string | undefined
|
|
98
|
+
name?: string | undefined
|
|
99
|
+
avatarUrl?: string | undefined
|
|
100
|
+
role?: string | undefined
|
|
101
|
+
emailVerified?: boolean | undefined
|
|
102
|
+
} & Omit<TUser, keyof AuthUser>
|
|
103
|
+
|
|
104
|
+
export interface AuthOptions<TUser extends AuthUser = AuthUser> {
|
|
105
|
+
/** Storage adapter (defaults to `memoryAuthStore()`). Use `sqliteAuthStore()` for production SQLite. */
|
|
106
|
+
store?: AuthStore<TUser> | undefined
|
|
107
|
+
/** Default custom fields merged into users created by signup, magic-link, or OAuth flows. */
|
|
108
|
+
defaultUserFields?: Omit<TUser, keyof AuthUser> | (() => Omit<TUser, keyof AuthUser>) | undefined
|
|
109
|
+
/**
|
|
110
|
+
* Secret used to sign short-lived OAuth state/PKCE cookies.
|
|
111
|
+
* Defaults to `AUTH_SECRET` env, or a random per-process key in development.
|
|
112
|
+
* In `NODE_ENV=production`, a non-empty secret of at least 32 UTF-8 bytes is required.
|
|
113
|
+
*/
|
|
114
|
+
secret?: string | undefined
|
|
115
|
+
/** Route prefix (default: '/auth'). */
|
|
116
|
+
basePath?: string | undefined
|
|
117
|
+
/** Session cookie name (default: 'pru_session'). */
|
|
118
|
+
cookieName?: string | undefined
|
|
119
|
+
/** Session lifetime in seconds (default: 30 days). */
|
|
120
|
+
sessionTtlSeconds?: number | undefined
|
|
121
|
+
/** Minimum interval in seconds between sliding-expiry DB writes for the same session (default: up to 1 hour). */
|
|
122
|
+
renewalIntervalSeconds?: number | undefined
|
|
123
|
+
/** Magic-link / verification token lifetime in seconds (default: 15 minutes). */
|
|
124
|
+
tokenTtlSeconds?: number | undefined
|
|
125
|
+
/** Minimum password length (default: 12, aligned with CNIL guidance). */
|
|
126
|
+
minPasswordLength?: number | undefined
|
|
127
|
+
/** Default role assigned to newly created users (default: 'user'). */
|
|
128
|
+
defaultRole?: string | undefined
|
|
129
|
+
/** Default redirect after successful form login/signup/OAuth (default: '/'). */
|
|
130
|
+
defaultRedirect?: string | undefined
|
|
131
|
+
/** Additional trusted cross-origin origins merged with `PrunelleConfig.trustedOrigins` for auth POST routes. */
|
|
132
|
+
trustedOrigins?: string[] | undefined
|
|
133
|
+
/** Public origin of the site (`https://example.com`), defaults to `PrunelleConfig.site`. Without it, mailed links are only built for a loopback host. */
|
|
134
|
+
site?: string | undefined
|
|
135
|
+
/** OAuth 2.0 providers (e.g. `[github(...), discord(...), google(...)]`). */
|
|
136
|
+
providers?: OAuthProvider[] | undefined
|
|
137
|
+
/** Pass a `@prunellejs/mail` `Mailer` instance directly for magic links & verification emails (shorthand for `sendMail`). */
|
|
138
|
+
mailer?: AuthMailer | undefined
|
|
139
|
+
/** Custom mail sender for magic links / verification emails (overrides `mailer` when both are provided). */
|
|
140
|
+
sendMail?: ((mail: AuthMailPayload) => void | Promise<void>) | undefined
|
|
141
|
+
/**
|
|
142
|
+
* Require email verification before opening a session on password sign-up / sign-in (default: `true`).
|
|
143
|
+
* Set explicitly to `false` only when you intentionally allow unverified password sessions (e.g. local dev without mail).
|
|
144
|
+
*/
|
|
145
|
+
requireEmailVerification?: boolean | undefined
|
|
146
|
+
/**
|
|
147
|
+
* Trust `X-Forwarded-For` / `X-Real-IP` headers as a fallback when `ctx.ip` is not populated by the server (default: `false`).
|
|
148
|
+
* When `ctx.ip` is provided by Prunelle's `trustProxy`-aware server, `ctx.ip` is always used.
|
|
149
|
+
*/
|
|
150
|
+
trustProxy?: TrustProxy | undefined
|
|
151
|
+
/** Optional per-key rate limit on auth endpoints (`false` disables). */
|
|
152
|
+
rateLimit?: RateLimitOptions | false | undefined
|
|
153
|
+
/** Periodic interval in ms to purge expired sessions and tokens (default: 15 minutes; `false` disables). */
|
|
154
|
+
pruneIntervalMs?: number | false | undefined
|
|
155
|
+
/**
|
|
156
|
+
* Control recording of client IP addresses on sessions (RGPD data minimization):
|
|
157
|
+
* - `'truncate'`: anonymize IPv4 to /24 (`a.b.c.0`) and IPv6 to /48 (`a:b:c::`) (default)
|
|
158
|
+
* - `true`: store full client IP
|
|
159
|
+
* - `false`: do not record IP on sessions
|
|
160
|
+
*/
|
|
161
|
+
storeIp?: boolean | 'truncate' | undefined
|
|
162
|
+
/** Whether to record the `User-Agent` header on sessions (default: `true`). */
|
|
163
|
+
storeUserAgent?: boolean | undefined
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export interface GuardOptions<TUser extends AuthUser = AuthUser> {
|
|
167
|
+
/** Redirect unauthenticated HTML requests here (JSON/API requests always receive 401). */
|
|
168
|
+
redirectTo?: string | undefined
|
|
169
|
+
/** Required user role(s); authenticated users without a matching role receive 403. */
|
|
170
|
+
role?: string | string[] | undefined
|
|
171
|
+
/** Custom authorization predicate. */
|
|
172
|
+
allow?: ((user: PublicUser<TUser>, ctx: RequestContext) => boolean | Promise<boolean>) | undefined
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** The plugin `prunelle.config.ts` registers, and the handle routes and actions call. */
|
|
176
|
+
export interface Auth<TUser extends AuthUser = AuthUser> extends PrunellePlugin {
|
|
177
|
+
readonly store: AuthStore<TUser>
|
|
178
|
+
readonly basePath: string
|
|
179
|
+
getUser(ctx: { locals: PrunelleLocals }): PublicUser<TUser> | undefined
|
|
180
|
+
getSession(ctx: { locals: PrunelleLocals }): AuthSession | undefined
|
|
181
|
+
resolve(ctx: RequestContext): Promise<{ user: PublicUser<TUser>, session: AuthSession } | undefined>
|
|
182
|
+
guard(options?: GuardOptions<TUser>): Middleware
|
|
183
|
+
createUser(input: CreateUserInput<TUser>): Promise<PublicUser<TUser>>
|
|
184
|
+
createSessionForUser(userId: string, ctx: RequestContext): Promise<AuthSession>
|
|
185
|
+
signOut(ctx: RequestContext): Promise<void>
|
|
186
|
+
revokeAllSessions(userId: string): Promise<void>
|
|
187
|
+
sendMagicLink(email: string, origin: string, redirectTo?: string): Promise<string>
|
|
188
|
+
sendVerificationEmail(email: string, origin: string, redirectTo?: string): Promise<string>
|
|
189
|
+
listSessions(userId: string): Promise<AuthSession[]>
|
|
190
|
+
exportUser(userId: string): Promise<UserExport<TUser> | null>
|
|
191
|
+
deleteUser(userId: string): Promise<void>
|
|
192
|
+
pruneExpired(): Promise<void>
|
|
193
|
+
dispose(): void
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const STORE_IN_MEMORY = '`store` keeps accounts and sessions in memory, so a restart signs everyone out and loses every account: pass `store: sqliteAuthStore(\'data/auth.db\')` from `@prunellejs/auth/sqlite`, or your own `AuthStore`.'
|
|
197
|
+
|
|
198
|
+
function resolveSecret(optionSecret: string | undefined): string {
|
|
199
|
+
if (optionSecret !== undefined && optionSecret.trim().length === 0)
|
|
200
|
+
throw new Error('[prunelle/auth] `secret` must not be empty')
|
|
201
|
+
|
|
202
|
+
const envSecret = process.env.AUTH_SECRET
|
|
203
|
+
const configured = optionSecret ?? (envSecret && envSecret.trim().length > 0 ? envSecret : undefined)
|
|
204
|
+
if (nodeEnv() === 'production') {
|
|
205
|
+
if (configured === undefined)
|
|
206
|
+
throw new Error('[prunelle/auth] `secret` (or `AUTH_SECRET` env) is required in production and must be at least 32 bytes')
|
|
207
|
+
if (Buffer.byteLength(configured, 'utf8') < MIN_PROD_SECRET_BYTES)
|
|
208
|
+
throw new Error(`[prunelle/auth] \`secret\` must be at least ${MIN_PROD_SECRET_BYTES} UTF-8 bytes in production`)
|
|
209
|
+
}
|
|
210
|
+
return configured ?? randomToken(32)
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptions<TUser> = {}): Auth<TUser> {
|
|
214
|
+
const secret = resolveSecret(options.secret)
|
|
215
|
+
const store = options.store ?? memoryAuthStore<TUser>()
|
|
216
|
+
const basePath = (options.basePath ?? '/auth').replace(/\/$/, '')
|
|
217
|
+
const cookieName = options.cookieName ?? 'pru_session'
|
|
218
|
+
const oauthCookieName = `${cookieName}_oauth`
|
|
219
|
+
const sessionTtlSeconds = options.sessionTtlSeconds ?? 60 * 60 * 24 * 30
|
|
220
|
+
const sessionTtlMs = sessionTtlSeconds * 1000
|
|
221
|
+
const renewalIntervalMs = Math.max(0, (options.renewalIntervalSeconds ?? Math.min(60 * 60, Math.max(1, Math.floor(sessionTtlSeconds / 4)))) * 1000)
|
|
222
|
+
const tokenTtlMs = (options.tokenTtlSeconds ?? 60 * 15) * 1000
|
|
223
|
+
const minPasswordLength = options.minPasswordLength ?? 12
|
|
224
|
+
const defaultRole = options.defaultRole ?? 'user'
|
|
225
|
+
const defaultRedirect = options.defaultRedirect ?? '/'
|
|
226
|
+
const authRouteOpts = {
|
|
227
|
+
...(options.trustedOrigins !== undefined ? { trustedOrigins: options.trustedOrigins } : {}),
|
|
228
|
+
...(options.trustProxy !== undefined ? { trustProxy: options.trustProxy } : {}),
|
|
229
|
+
}
|
|
230
|
+
let site = options.site !== undefined ? siteOrigin(options.site) : undefined
|
|
231
|
+
const deliverMail: ((mail: AuthMailPayload) => void | Promise<void>) | undefined = options.sendMail
|
|
232
|
+
?? (options.mailer !== undefined
|
|
233
|
+
? async (mail) => {
|
|
234
|
+
await options.mailer!.send({
|
|
235
|
+
to: mail.to,
|
|
236
|
+
subject: mail.subject,
|
|
237
|
+
text: mail.text,
|
|
238
|
+
html: mail.html,
|
|
239
|
+
})
|
|
240
|
+
}
|
|
241
|
+
: undefined)
|
|
242
|
+
const requireEmailVerification = options.requireEmailVerification !== false
|
|
243
|
+
let trustProxy = options.trustProxy ?? false
|
|
244
|
+
|
|
245
|
+
const pruneIntervalMs = options.pruneIntervalMs === false
|
|
246
|
+
? undefined
|
|
247
|
+
: (options.pruneIntervalMs ?? DEFAULT_PRUNE_INTERVAL_MS)
|
|
248
|
+
|
|
249
|
+
const providers = new Map<string, OAuthProvider>()
|
|
250
|
+
for (const p of options.providers ?? [])
|
|
251
|
+
providers.set(p.id, p)
|
|
252
|
+
|
|
253
|
+
const isSecureCookie = (ctx: RequestContext): boolean =>
|
|
254
|
+
ctx.url.protocol === 'https:'
|
|
255
|
+
|| isHttpsRequest(ctx.request, trustProxy)
|
|
256
|
+
|| nodeEnv() === 'production'
|
|
257
|
+
|
|
258
|
+
const sessions = createSessionManager({
|
|
259
|
+
store,
|
|
260
|
+
cookieName,
|
|
261
|
+
sessionTtlMs,
|
|
262
|
+
renewalIntervalMs,
|
|
263
|
+
storeIp: options.storeIp ?? 'truncate',
|
|
264
|
+
storeUserAgent: options.storeUserAgent !== false,
|
|
265
|
+
getTrustProxy: () => trustProxy,
|
|
266
|
+
isSecureCookie,
|
|
267
|
+
})
|
|
268
|
+
|
|
269
|
+
// One timer per server the plugin runs on: `prunelle dev` starts the next server before it shuts the previous one down.
|
|
270
|
+
const pruneTimers = new Set<ReturnType<typeof setInterval>>()
|
|
271
|
+
let activeServers = 0
|
|
272
|
+
const startPruneTimer = (): (() => void) | undefined => {
|
|
273
|
+
if (pruneIntervalMs === undefined || pruneIntervalMs <= 0)
|
|
274
|
+
return undefined
|
|
275
|
+
const timer = setInterval(() => {
|
|
276
|
+
try {
|
|
277
|
+
void Promise.resolve(store.pruneExpired?.()).catch(() => {})
|
|
278
|
+
sessions.sweepRenewedAt()
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
// Ignore prune errors if the underlying store has been closed
|
|
282
|
+
}
|
|
283
|
+
}, pruneIntervalMs)
|
|
284
|
+
timer.unref?.()
|
|
285
|
+
pruneTimers.add(timer)
|
|
286
|
+
return () => {
|
|
287
|
+
clearInterval(timer)
|
|
288
|
+
pruneTimers.delete(timer)
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
async function insertUser(fields: Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>): Promise<TUser> {
|
|
293
|
+
const now = Date.now()
|
|
294
|
+
const defaults = typeof options.defaultUserFields === 'function'
|
|
295
|
+
? (options.defaultUserFields as () => Partial<TUser>)()
|
|
296
|
+
: (options.defaultUserFields as Partial<TUser> | undefined)
|
|
297
|
+
return sessions.observeAsync(store.createUser({
|
|
298
|
+
id: crypto.randomUUID(),
|
|
299
|
+
role: defaultRole,
|
|
300
|
+
createdAt: now,
|
|
301
|
+
updatedAt: now,
|
|
302
|
+
...defaults,
|
|
303
|
+
...fields,
|
|
304
|
+
} as TUser))
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
async function createUser(input: CreateUserInput<TUser>): Promise<PublicUser<TUser>> {
|
|
308
|
+
const { email: rawEmail, password, name, avatarUrl, role, emailVerified, ...extra } = input
|
|
309
|
+
const email = normalizeEmail(rawEmail)
|
|
310
|
+
if (!isValidEmail(email))
|
|
311
|
+
throw new Error('Invalid email address')
|
|
312
|
+
if (await sessions.observeAsync(store.getUserByEmail(email)))
|
|
313
|
+
throw new Error('Email is already registered')
|
|
314
|
+
|
|
315
|
+
const passwordHash = password !== undefined ? await hashPassword(password) : undefined
|
|
316
|
+
const created = await insertUser({
|
|
317
|
+
...extra,
|
|
318
|
+
email,
|
|
319
|
+
...(name !== undefined ? { name } : {}),
|
|
320
|
+
...(avatarUrl !== undefined ? { avatarUrl } : {}),
|
|
321
|
+
...(role !== undefined ? { role } : {}),
|
|
322
|
+
emailVerified: emailVerified ?? false,
|
|
323
|
+
...(passwordHash !== undefined ? { passwordHash } : {}),
|
|
324
|
+
} as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
|
|
325
|
+
return toPublicUser(created)
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// The request URL comes from the Host header, which the client controls: a link mailed to a victim must not point at it.
|
|
329
|
+
function mailedLinkOrigin(url: URL): string | undefined {
|
|
330
|
+
if (site !== undefined)
|
|
331
|
+
return site
|
|
332
|
+
return LOOPBACK_HOSTS.has(url.hostname) ? url.origin : undefined
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// Whoever signed up with an address before it was proven may hold its password, sessions and provider links; proving it hands the account to the owner alone.
|
|
336
|
+
// The password goes first, so a squatter cannot sign in again between the purge and the update.
|
|
337
|
+
async function claimUnverified(user: TUser): Promise<TUser> {
|
|
338
|
+
const claimed = (await sessions.observeAsync(store.updateUser(user.id, { emailVerified: true, passwordHash: undefined } as Partial<Omit<TUser, 'id' | 'createdAt'>>))) ?? user
|
|
339
|
+
await sessions.observeAsync(store.deleteUserSessions(user.id))
|
|
340
|
+
await sessions.observeAsync(store.deleteUserOAuthAccounts(user.id))
|
|
341
|
+
return claimed
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// One-time emailed link: stores the hashed token, builds the URL and mails it when a transport is configured.
|
|
345
|
+
async function issueLink(kind: 'magic-link' | 'verify-email', userId: string | undefined, email: string, origin: string | undefined, redirectTo: string | undefined): Promise<string> {
|
|
346
|
+
const normalized = normalizeEmail(email)
|
|
347
|
+
const rawToken = randomToken(32)
|
|
348
|
+
const tokenHash = sha256Hex(rawToken)
|
|
349
|
+
await sessions.observeAsync(store.createToken({
|
|
350
|
+
tokenHash,
|
|
351
|
+
...(userId !== undefined ? { userId } : {}),
|
|
352
|
+
email: normalized,
|
|
353
|
+
kind,
|
|
354
|
+
expiresAt: Date.now() + tokenTtlMs,
|
|
355
|
+
}))
|
|
356
|
+
|
|
357
|
+
const next = safeRedirect(redirectTo, defaultRedirect)
|
|
358
|
+
const path = `${basePath}/${LINK_PATHS[kind]}?token=${encodeURIComponent(rawToken)}&redirect=${encodeURIComponent(next)}`
|
|
359
|
+
const url = origin !== undefined ? `${origin.replace(/\/$/, '')}${path}` : path
|
|
360
|
+
|
|
361
|
+
if (deliverMail && origin !== undefined) {
|
|
362
|
+
const mail = LINK_MAILS[kind]
|
|
363
|
+
try {
|
|
364
|
+
await deliverMail({
|
|
365
|
+
to: normalized,
|
|
366
|
+
subject: mail.subject,
|
|
367
|
+
text: `${mail.text}: ${url}`,
|
|
368
|
+
html: `<p>${mail.html}: <a href="${url}">${mail.label}</a></p>`,
|
|
369
|
+
url,
|
|
370
|
+
kind,
|
|
371
|
+
})
|
|
372
|
+
}
|
|
373
|
+
catch (err) {
|
|
374
|
+
try {
|
|
375
|
+
await sessions.observeAsync(store.consumeToken(tokenHash, kind))
|
|
376
|
+
}
|
|
377
|
+
catch {
|
|
378
|
+
// Best-effort token cleanup if delivery fails.
|
|
379
|
+
}
|
|
380
|
+
throw err
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
return url
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
async function sendVerificationEmail(email: string, origin: string, redirectTo?: string): Promise<string> {
|
|
387
|
+
const normalized = normalizeEmail(email)
|
|
388
|
+
const existing = await sessions.observeAsync(store.getUserByEmail(normalized))
|
|
389
|
+
return issueLink('verify-email', existing?.id, normalized, origin, redirectTo)
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
async function sendMagicLink(email: string, origin: string, redirectTo?: string): Promise<string> {
|
|
393
|
+
const normalized = normalizeEmail(email)
|
|
394
|
+
const existing = await sessions.observeAsync(store.getUserByEmail(normalized))
|
|
395
|
+
return issueLink('magic-link', existing?.id, normalized, origin, redirectTo)
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// Consumes a one-time token and loads the user it was issued for (by id, else by email).
|
|
399
|
+
async function consumeLink(kind: 'magic-link' | 'verify-email', rawToken: string): Promise<{ email: string, user: TUser | undefined } | undefined> {
|
|
400
|
+
const consumed = await sessions.observeAsync(store.consumeToken(sha256Hex(rawToken), kind))
|
|
401
|
+
if (!consumed)
|
|
402
|
+
return undefined
|
|
403
|
+
const user = consumed.userId
|
|
404
|
+
? await sessions.observeAsync(store.getUserById(consumed.userId))
|
|
405
|
+
: await sessions.observeAsync(store.getUserByEmail(consumed.email))
|
|
406
|
+
return { email: consumed.email, user }
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
function guard(guardOpts: GuardOptions<TUser> = {}): Middleware {
|
|
410
|
+
const roles = guardOpts.role === undefined ? undefined : (Array.isArray(guardOpts.role) ? guardOpts.role : [guardOpts.role])
|
|
411
|
+
return async (ctx, next) => {
|
|
412
|
+
const resolved = await sessions.resolve(ctx)
|
|
413
|
+
if (!resolved) {
|
|
414
|
+
if (!wantsJson(ctx.request) && guardOpts.redirectTo) {
|
|
415
|
+
const nextParam = encodeURIComponent(ctx.url.pathname + ctx.url.search)
|
|
416
|
+
const sep = guardOpts.redirectTo.includes('?') ? '&' : '?'
|
|
417
|
+
return ctx.redirect(`${guardOpts.redirectTo}${sep}next=${nextParam}`, 302)
|
|
418
|
+
}
|
|
419
|
+
return fail(ctx, 401, 'Authentication required')
|
|
420
|
+
}
|
|
421
|
+
if (roles && !roles.includes(resolved.user.role))
|
|
422
|
+
return fail(ctx, 403, 'Forbidden')
|
|
423
|
+
if (guardOpts.allow && !(await guardOpts.allow(resolved.user, ctx)))
|
|
424
|
+
return fail(ctx, 403, 'Forbidden')
|
|
425
|
+
return next()
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
const dispose = (): void => {
|
|
430
|
+
for (const timer of pruneTimers)
|
|
431
|
+
clearInterval(timer)
|
|
432
|
+
pruneTimers.clear()
|
|
433
|
+
activeServers = 0
|
|
434
|
+
void Promise.resolve(store.close?.()).catch(() => {})
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
const plugin: PrunellePlugin = definePlugin({
|
|
438
|
+
name: '@prunellejs/auth',
|
|
439
|
+
enforce: 'pre',
|
|
440
|
+
providesLocals: ['user', 'session'],
|
|
441
|
+
requires: () => isKeptInMemory(store) ? [STORE_IN_MEMORY] : [],
|
|
442
|
+
server(api) {
|
|
443
|
+
if (options.trustProxy === undefined)
|
|
444
|
+
trustProxy = api.trustProxy
|
|
445
|
+
if (options.site === undefined && api.site !== undefined)
|
|
446
|
+
site = siteOrigin(api.site)
|
|
447
|
+
activeServers++
|
|
448
|
+
const stopPruneTimer = startPruneTimer()
|
|
449
|
+
let stopped = false
|
|
450
|
+
api.onShutdown(async () => {
|
|
451
|
+
if (stopped)
|
|
452
|
+
return
|
|
453
|
+
stopped = true
|
|
454
|
+
stopPruneTimer?.()
|
|
455
|
+
activeServers = Math.max(0, activeServers - 1)
|
|
456
|
+
if (activeServers === 0)
|
|
457
|
+
await store.close?.()
|
|
458
|
+
})
|
|
459
|
+
|
|
460
|
+
// Sync stores resolve lazily on first read of ctx.locals.user/session; async stores resolve before next().
|
|
461
|
+
const internalPrefix = `${api.assetPrefix.replace(/\/$/, '')}/`
|
|
462
|
+
const actionPrefix = `${internalPrefix}action/`
|
|
463
|
+
api.use((ctx, next) => {
|
|
464
|
+
const p = ctx.url.pathname
|
|
465
|
+
if (!p.startsWith(internalPrefix) || p.startsWith(actionPrefix)) {
|
|
466
|
+
if (sessions.isAsyncStore()) {
|
|
467
|
+
if (ctx.cookies.get(cookieName))
|
|
468
|
+
return sessions.resolve(ctx).then(() => next())
|
|
469
|
+
}
|
|
470
|
+
else {
|
|
471
|
+
sessions.attachLazy(ctx)
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
return next()
|
|
475
|
+
}, { scope: 'rendered' })
|
|
476
|
+
|
|
477
|
+
// Counted in this server's store, so a `prunelle dev` restart or a test's new server starts from zero.
|
|
478
|
+
const limits = options.rateLimit === false ? undefined : api.rateLimiter({ max: options.rateLimit?.max ?? 15, windowMs: options.rateLimit?.windowMs ?? 60_000 })
|
|
479
|
+
const { limitIp, limitEmail } = authLimits(limits, () => trustProxy)
|
|
480
|
+
registerAuthRoutes({
|
|
481
|
+
api,
|
|
482
|
+
store,
|
|
483
|
+
sessions,
|
|
484
|
+
limitEmail,
|
|
485
|
+
limitIp,
|
|
486
|
+
basePath,
|
|
487
|
+
authRouteOpts,
|
|
488
|
+
minPasswordLength,
|
|
489
|
+
defaultRedirect,
|
|
490
|
+
requireEmailVerification,
|
|
491
|
+
hasMailTransport: deliverMail !== undefined,
|
|
492
|
+
mailedLinkOrigin,
|
|
493
|
+
createUser,
|
|
494
|
+
insertUser,
|
|
495
|
+
claimUnverified,
|
|
496
|
+
issueLink,
|
|
497
|
+
consumeLink,
|
|
498
|
+
sendMagicLink,
|
|
499
|
+
})
|
|
500
|
+
|
|
501
|
+
registerOAuthRoutes({
|
|
502
|
+
route: (method, path, handler) => api.route(method, path, handler),
|
|
503
|
+
store,
|
|
504
|
+
providers,
|
|
505
|
+
secret,
|
|
506
|
+
site,
|
|
507
|
+
basePath,
|
|
508
|
+
stateCookieName: oauthCookieName,
|
|
509
|
+
defaultRedirect,
|
|
510
|
+
limitIp,
|
|
511
|
+
isSecureCookie,
|
|
512
|
+
claimUnverified,
|
|
513
|
+
insertUser,
|
|
514
|
+
createSessionForUser: sessions.createSessionForUser,
|
|
515
|
+
setResolvedUser: sessions.setResolvedUser,
|
|
516
|
+
observeAsync: sessions.observeAsync,
|
|
517
|
+
})
|
|
518
|
+
},
|
|
519
|
+
})
|
|
520
|
+
|
|
521
|
+
return {
|
|
522
|
+
...plugin,
|
|
523
|
+
store,
|
|
524
|
+
basePath,
|
|
525
|
+
getUser: sessions.getUser,
|
|
526
|
+
getSession: sessions.getSession,
|
|
527
|
+
resolve: sessions.resolve,
|
|
528
|
+
guard,
|
|
529
|
+
createUser,
|
|
530
|
+
createSessionForUser: sessions.createSessionForUser,
|
|
531
|
+
signOut: sessions.signOut,
|
|
532
|
+
async revokeAllSessions(userId) {
|
|
533
|
+
await sessions.observeAsync(store.deleteUserSessions(userId))
|
|
534
|
+
},
|
|
535
|
+
sendMagicLink,
|
|
536
|
+
sendVerificationEmail,
|
|
537
|
+
async listSessions(userId) {
|
|
538
|
+
return await sessions.observeAsync(store.listSessions(userId))
|
|
539
|
+
},
|
|
540
|
+
async exportUser(userId) {
|
|
541
|
+
return await sessions.observeAsync(store.exportUser(userId))
|
|
542
|
+
},
|
|
543
|
+
async deleteUser(userId) {
|
|
544
|
+
await sessions.observeAsync(store.deleteUser(userId))
|
|
545
|
+
},
|
|
546
|
+
async pruneExpired() {
|
|
547
|
+
await store.pruneExpired?.()
|
|
548
|
+
sessions.sweepRenewedAt()
|
|
549
|
+
},
|
|
550
|
+
dispose,
|
|
551
|
+
}
|
|
552
|
+
}
|