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