@prunellejs/auth 0.7.4 → 0.8.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 +7 -5
- package/package.json +2 -2
- package/src/account.ts +18 -5
- package/src/crypto.ts +11 -13
- package/src/http.ts +22 -2
- package/src/index.ts +21 -14
- package/src/links.ts +4 -4
- package/src/oauth-routes.ts +3 -3
- package/src/org-routes.ts +1 -1
- package/src/orgs.ts +84 -36
- package/src/passkey-routes.ts +34 -24
- package/src/passkeys.ts +43 -49
- package/src/routes.ts +28 -11
- package/src/sqlite-ext.ts +5 -11
- package/src/sqlite.ts +45 -21
- package/src/store-ext.ts +17 -17
- package/src/store.ts +20 -2
- package/src/totp-routes.ts +43 -13
- package/src/totp.ts +18 -9
- package/src/webauthn-crypto.ts +49 -15
package/llms.txt
CHANGED
|
@@ -27,9 +27,9 @@
|
|
|
27
27
|
- `mailer`: pass a `@prunellejs/mail` `Mailer` directly, or `sendMail(mail: AuthMailPayload)` (handles `kind: 'magic-link' | 'verify-email' | 'reset-password' | 'org-invite'`).
|
|
28
28
|
- `providers`: `[github({ clientId, clientSecret, scopes? }), discord(...), google(...), oauthProvider(...)]`.
|
|
29
29
|
- `totp`: `{ issuer?, verifyPath? }`. `twoFactorRedirect`: custom redirect target for HTML form sign-ins when 2FA is required (default `${basePath}/totp/verify`).
|
|
30
|
-
- `passkeys`: `{ rpId?, rpName?, origin?, userVerification? }` (WebAuthn L2 ES256 / RS256 / EdDSA, zero npm deps). By default `userVerification` is `'required'` for registration and passwordless login (refusing assertions without UV) and `'preferred'` when used as 2FA; set `userVerification: 'preferred' | 'discouraged'` to opt out explicitly.
|
|
30
|
+
- `passkeys`: `{ rpId?, rpName?, origin?, userVerification? }` (WebAuthn L2 ES256 / RS256 / EdDSA, zero npm deps; registration refuses an off-curve EC point, an RSA key under 2048 bits, repeated CBOR keys and trailing bytes). By default `userVerification` is `'required'` for registration and passwordless login (refusing assertions without UV) and `'preferred'` when used as 2FA; set `userVerification: 'preferred' | 'discouraged'` to opt out explicitly.
|
|
31
31
|
- `trustProxy`: inherits `PrunelleConfig.trustProxy`. `trustedOrigins`: merged with `PrunelleConfig.trustedOrigins`.
|
|
32
|
-
- `rateLimit`: `{ max?, windowMs?, mailsPerAddress?, failuresPerAccount? } | false`, counted in the server's store, a refusal being a `429` with `Retry-After`: `max` attempts per `windowMs` per scope and address (default 15 a minute); `mailsPerAddress` mails to one address per 10 minutes from sign-up, magic links and org invites (default 3); `failuresPerAccount` wrong passwords per hour on one account across all addresses (default 100), past which sign-in refuses that account before checking the password. A right password never counts, so a guesser can lock an account only by sending that many wrong ones. `pruneIntervalMs`: default 15 min (`false` disables).
|
|
32
|
+
- `rateLimit`: `{ max?, windowMs?, mailsPerAddress?, failuresPerAccount?, twoFactorFailuresPerAccount? } | false`, counted in the server's store, a refusal being a `429` with `Retry-After`: `max` attempts per `windowMs` per scope and address (default 15 a minute); `mailsPerAddress` mails to one address per 10 minutes from sign-up, magic links and org invites (default 3); `failuresPerAccount` wrong passwords per hour on one account across all addresses (default 100), past which sign-in refuses that account before checking the password. A right password never counts, so a guesser can lock an account only by sending that many wrong ones. `twoFactorFailuresPerAccount`: wrong TOTP codes, recovery codes and passkey assertions per hour on one account (default 10), past which `/totp/verify` and `/passkeys/2fa/verify` answer `429` and drop the pending 2FA cookie. `pruneIntervalMs`: default 15 min (`false` disables).
|
|
33
33
|
- RGPD minimization: `storeIp`: `'truncate'` (default, /24 IPv4 and /48 IPv6) | `true` | `false`; `storeUserAgent`: `true` (default) | `false`.
|
|
34
34
|
- `defaultUserFields`: extra columns/fields merged on user creation when extending `AuthUser`.
|
|
35
35
|
|
|
@@ -44,9 +44,11 @@
|
|
|
44
44
|
- `POST /auth/totp/confirm` (authenticated, `code`) → enables TOTP and returns 10 single-use recovery codes (`XXXX-XXXX`).
|
|
45
45
|
- `GET /auth/totp/verify` & `POST /auth/totp/verify` (pending 2FA cookie, `code` = 6-digit TOTP or recovery code) → clears pending cookie and opens session.
|
|
46
46
|
- `POST /auth/totp/disable` (authenticated, `code` = TOTP or recovery code) → disables TOTP and deletes recovery codes.
|
|
47
|
+
- `POST /auth/totp/recovery-codes` (authenticated, TOTP enabled) → 10 new recovery codes, the earlier ones no longer working.
|
|
48
|
+
- Setup, confirm, disable and recovery codes, like passkey registration and deletion, need a sign-in from the last 10 minutes (`FRESH_SIGNIN_MS`), else `403` `{ code: 'reauth-required' }`; adding or removing a factor signs out the user's other sessions and renews this one's cookie.
|
|
47
49
|
- Passkeys (WebAuthn L2, passwordless sign-in & 2FA):
|
|
48
50
|
- `POST /auth/passkeys/register/options` & `POST /auth/passkeys/register/verify` (authenticated).
|
|
49
|
-
- `POST /auth/passkeys/login/options` & `POST /auth/passkeys/login/verify` (public, discoverable or with optional `email` hint).
|
|
51
|
+
- `POST /auth/passkeys/login/options` & `POST /auth/passkeys/login/verify` (public, discoverable or with optional `email` hint; an email with no passkey, or unknown, gets a decoy credential id stable per email, so the answer never tells whether the account exists or has passkeys).
|
|
50
52
|
- `POST /auth/passkeys/2fa/options` & `POST /auth/passkeys/2fa/verify` (pending 2FA cookie; completes 2FA when user has registered passkeys).
|
|
51
53
|
- `GET /auth/passkeys` & `POST /auth/passkeys/delete` (authenticated, own passkeys only).
|
|
52
54
|
- Organizations (HTML form POST or JSON):
|
|
@@ -59,11 +61,11 @@
|
|
|
59
61
|
|
|
60
62
|
## Handle Methods (`auth`)
|
|
61
63
|
|
|
62
|
-
- Guards & sessions: `auth.guard({ redirectTo?, org?, role?, allow? })` (when `org` is `true`, reads `ctx.params.org ?? ctx.params.orgId ?? ctx.params.slug`; when a string, reads `ctx.params[org]`
|
|
64
|
+
- Guards & sessions: `auth.guard({ redirectTo?, org?, role?, allow? })` (when `org` is `true`, reads `ctx.params.org ?? ctx.params.orgId ?? ctx.params.slug`; when a string, reads `ctx.params[org]` and answers `403` on a route without that param (a fixed org goes through a function); when a function, calls `await org(ctx)`; checks `role` against the member's org role, `owner` outranking `admin` outranking `member` and a custom role matching only itself, and populates `ctx.locals.org` & `ctx.locals.orgMembership`). `auth.getUser(ctx)`, `auth.getSession(ctx)`, `auth.formMessage(url)`, `auth.resolve(ctx)`, `auth.createUser(input)`, `auth.createSessionForUser(userId, ctx)`, `auth.signOut(ctx)`, `auth.revokeAllSessions(userId)`, `auth.sendMagicLink(email, origin, redirectTo?)`, `auth.sendVerificationEmail(email, origin, redirectTo?)`.
|
|
63
65
|
- TOTP: `auth.setupTotp(userId, opts?)`, `auth.confirmTotp(userId, code)`, `auth.verifyTotp(userId, code)`, `auth.disableTotp(userId, code)`, `auth.regenerateRecoveryCodes(userId)`.
|
|
64
66
|
- Passkeys: `auth.listPasskeys(userId)`, `auth.deletePasskey(userId, credentialId)`.
|
|
65
67
|
- Organizations: `auth.createOrg(ownerUserId, { name, slug? })`, `auth.getOrg(idOrSlug)`, `auth.listUserOrgs(userId)`, `auth.listOrgMembers(orgId)`, `auth.addOrgMember(orgId, userId, role?)`, `auth.updateOrgMemberRole(orgId, userId, role)`, `auth.removeOrgMember(orgId, userId)`, `auth.inviteToOrg(orgId, { email, role?, invitedBy, origin?, redirectTo? })`, `auth.acceptOrgInvite(token, userId)`, `auth.revokeOrgInvite(orgId, inviteId)`, `auth.deleteOrg(orgId)`.
|
|
66
|
-
- RGPD & maintenance: `auth.listSessions(userId)`, `auth.exportUser(userId)` (includes `user`, `sessions`, `oauthAccounts`, `totp` status/remaining recovery count without secrets, `passkeys` metadata, `organizations`, pending `invitations
|
|
68
|
+
- RGPD & maintenance: `auth.listSessions(userId)`, `auth.exportUser(userId)` (includes `user`, `sessions`, `oauthAccounts`, `totp` status/remaining recovery count without secrets, `passkeys` metadata, `organizations`, pending `invitations` to their email, `sentInvitations` (no invitee email), `pendingTokens` (kind and expiry of unexpired mailed links), and `app` from `onExportUser`), `auth.deleteUser(userId)` (runs `onDeleteUser` first, a throw keeping the account; cascades sessions, OAuth links, tokens, TOTP, recovery codes, passkeys, org memberships, and pending invitations), `auth.pruneExpired()` (expired sessions and tokens, and accounts left unverified past `unverifiedTtlSeconds`), `auth.dispose()`. A custom store implements `pruneExpired({ unverifiedCreatedBefore })`, deleting unverified users created before that timestamp like `deleteUser`. A custom store should also implement the atomic `updateUserIfUnverified(id, updatedAt, patch)`, `deleteUserIfUnverified(id, updatedAt)`, `advanceTotpStep(userId, step, updatedAt)` (with TOTP), `updateOrgMemberRoleIfNotLastOwner(orgId, userId, role)` and `removeOrgMemberIfNotLastOwner(orgId, userId)` (with orgs), each one transaction; without them prunelle checks then writes under an in-process lock and `prunelle check` warns `[auth/store-not-atomic]`.
|
|
67
69
|
|
|
68
70
|
## Snippets
|
|
69
71
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/auth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Zero-dependency Bun-native auth plugin for Prunelle (Argon2id, hashed sessions, SQLite, magic links, OAuth2 PKCE, TOTP 2FA, Passkeys, Organizations)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -24,6 +24,6 @@
|
|
|
24
24
|
"directory": "packages/plugin-auth"
|
|
25
25
|
},
|
|
26
26
|
"peerDependencies": {
|
|
27
|
-
"prunelle": "^0.
|
|
27
|
+
"prunelle": "^0.8.0"
|
|
28
28
|
}
|
|
29
29
|
}
|
package/src/account.ts
CHANGED
|
@@ -5,7 +5,7 @@ import type { SessionManager } from './session'
|
|
|
5
5
|
import type { AuthSession, AuthStore, AuthUser, PublicUser, UserExport } from './store'
|
|
6
6
|
import { safeRedirect, wantsJson } from 'prunelle/server'
|
|
7
7
|
import { fail, formPagePath } from './http'
|
|
8
|
-
import {
|
|
8
|
+
import { leaveOrgsForDeletion } from './orgs'
|
|
9
9
|
import { toPublicUser } from './store'
|
|
10
10
|
|
|
11
11
|
/** How recent a sign-in must be to export or delete the account it opened. */
|
|
@@ -37,8 +37,14 @@ export function createAccountService<TUser extends AuthUser>(
|
|
|
37
37
|
const user = await sessions.observeAsync(store.getUserById(userId))
|
|
38
38
|
if (!user)
|
|
39
39
|
return
|
|
40
|
-
const orgIds = await
|
|
41
|
-
|
|
40
|
+
const { deleted: orgIds, undo } = await leaveOrgsForDeletion(store, sessions, userId)
|
|
41
|
+
try {
|
|
42
|
+
await hooks.onDeleteUser?.(toPublicUser(user))
|
|
43
|
+
}
|
|
44
|
+
catch (err) {
|
|
45
|
+
await undo()
|
|
46
|
+
throw err
|
|
47
|
+
}
|
|
42
48
|
for (const orgId of orgIds)
|
|
43
49
|
await store.deleteOrg?.(orgId)
|
|
44
50
|
await sessions.observeAsync(store.deleteUser(userId))
|
|
@@ -53,7 +59,7 @@ interface AccountRoutesDeps<TUser extends AuthUser> {
|
|
|
53
59
|
clearPendingCookie: (ctx: RequestContext) => void
|
|
54
60
|
}
|
|
55
61
|
|
|
56
|
-
export const REAUTH_REQUIRED = 'Sign in again to confirm it is you: exporting or deleting an account needs a sign-in from the last 10 minutes'
|
|
62
|
+
export const REAUTH_REQUIRED = 'Sign in again to confirm it is you: exporting or deleting an account, or changing how you sign in, needs a sign-in from the last 10 minutes'
|
|
57
63
|
|
|
58
64
|
// A form or a link from a page goes back to it with the refusal's code, which `auth.formMessage(url)` reads; a JSON caller gets `json`.
|
|
59
65
|
function refuse(ctx: RequestContext, code: 'account.reauth-required' | 'account.last-owner', json: () => Response): Response {
|
|
@@ -61,7 +67,8 @@ function refuse(ctx: RequestContext, code: 'account.reauth-required' | 'account.
|
|
|
61
67
|
return back === undefined ? json() : ctx.redirect(back, 303)
|
|
62
68
|
}
|
|
63
69
|
|
|
64
|
-
|
|
70
|
+
/** The signed-in user when the session opened in the last `FRESH_SIGNIN_MS`; else the refusal, `401` signed out and `403` `reauth-required` on a stale session. */
|
|
71
|
+
export async function freshSignin<TUser extends AuthUser>(ctx: RequestContext, sessions: SessionManager<TUser>): Promise<{ user: PublicUser<TUser>, session: AuthSession } | Response> {
|
|
65
72
|
const resolved = await sessions.resolve(ctx)
|
|
66
73
|
if (!resolved)
|
|
67
74
|
return fail(ctx, 401, 'Authentication required')
|
|
@@ -70,6 +77,12 @@ async function freshSignin<TUser extends AuthUser>(ctx: RequestContext, sessions
|
|
|
70
77
|
return resolved
|
|
71
78
|
}
|
|
72
79
|
|
|
80
|
+
/** After a sign-in factor is added or removed: every other session of the user ends, as one may be the attacker's, and this one carries on under a new cookie. */
|
|
81
|
+
export async function keepOnlyThisSession<TUser extends AuthUser>(ctx: RequestContext, sessions: SessionManager<TUser>, store: AuthStore<TUser>, userId: string): Promise<void> {
|
|
82
|
+
await sessions.observeAsync(store.deleteUserSessions(userId))
|
|
83
|
+
await sessions.createSessionForUser(userId, ctx)
|
|
84
|
+
}
|
|
85
|
+
|
|
73
86
|
export function registerAccountRoutes<TUser extends AuthUser>({ authRoute, sessions, account, clearPendingCookie }: AccountRoutesDeps<TUser>): void {
|
|
74
87
|
authRoute('GET', '/me/export', { limit: 'account-export' }, async (ctx) => {
|
|
75
88
|
const resolved = await freshSignin(ctx, sessions)
|
package/src/crypto.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Zero-dependency Bun-native crypto helpers for @prunellejs/auth.
|
|
2
2
|
// Uses crypto.getRandomValues, Bun.CryptoHasher (SHA-256 / HMAC-SHA256), and Bun.password (Argon2id).
|
|
3
3
|
|
|
4
|
-
import {
|
|
4
|
+
import { signPayload, verifyPayload } from 'prunelle/server'
|
|
5
5
|
|
|
6
6
|
export function toBase64Url(bytes: Uint8Array): string {
|
|
7
7
|
return Buffer.from(bytes).toString('base64url')
|
|
@@ -83,20 +83,18 @@ export function pkceChallenge(verifier: string): string {
|
|
|
83
83
|
}
|
|
84
84
|
|
|
85
85
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
86
|
+
/** What a signed auth cookie is for: its MAC covers it, so a cookie of one kind never verifies as another. */
|
|
87
|
+
export type SignedPurpose = 'oauth' | '2fa' | 'webauthn'
|
|
88
|
+
|
|
89
|
+
/** `payload` as base64url JSON, signed by prunelle's `signPayload` under the auth secret for `purpose`, so it fits a cookie. */
|
|
90
|
+
export function signJson(secret: string, purpose: SignedPurpose, payload: unknown): string {
|
|
91
|
+
return signPayload(`auth-${purpose}`, Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url'), secret)
|
|
90
92
|
}
|
|
91
93
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
const encoded = token.slice(0, dot)
|
|
97
|
-
const providedMac = token.slice(dot + 1)
|
|
98
|
-
const expectedMac = new Bun.CryptoHasher('sha256', secret).update(encoded).digest().toString('base64url')
|
|
99
|
-
if (!safeEqual(providedMac, expectedMac))
|
|
94
|
+
/** The value a `signJson` token for `purpose` carries, or undefined when its signature does not match. */
|
|
95
|
+
export function verifyJson<T>(secret: string, purpose: SignedPurpose, token: string): T | undefined {
|
|
96
|
+
const encoded = verifyPayload(`auth-${purpose}`, token, secret)
|
|
97
|
+
if (encoded === undefined)
|
|
100
98
|
return undefined
|
|
101
99
|
try {
|
|
102
100
|
return JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8')) as T
|
package/src/http.ts
CHANGED
|
@@ -125,8 +125,8 @@ export function createAuthRouteRegistrar(
|
|
|
125
125
|
}
|
|
126
126
|
}
|
|
127
127
|
|
|
128
|
-
// Control characters (C0
|
|
129
|
-
const EMAIL_FORBIDDEN_RE = /[\u0000-\u001F\u007F\s,;<>]/
|
|
128
|
+
// Control characters (C0, DEL, C1 such as U+0085), whitespace, and the characters that split or wrap an address list.
|
|
129
|
+
const EMAIL_FORBIDDEN_RE = /[\u0000-\u001F\u007F-\u009F\s,;<>]/
|
|
130
130
|
|
|
131
131
|
export function isValidEmail(email: string): boolean {
|
|
132
132
|
const e = email.trim()
|
|
@@ -147,12 +147,17 @@ export interface AuthLimits {
|
|
|
147
147
|
refuseLockedAccount: (ctx: RequestContext, email: string) => Response | undefined
|
|
148
148
|
/** Counts a wrong password against the account. */
|
|
149
149
|
countFailedSignin: (email: string) => void
|
|
150
|
+
/** The 429 to answer, before a second factor is checked, when this account is past its wrong second-factor attempts across addresses. */
|
|
151
|
+
refuseLockedSecondFactor: (ctx: RequestContext, userId: string) => Response | undefined
|
|
152
|
+
/** Counts a wrong TOTP, recovery code or passkey assertion against the account, answering the 429 once it reaches the limit. */
|
|
153
|
+
countFailedSecondFactor: (ctx: RequestContext, userId: string) => Response | undefined
|
|
150
154
|
}
|
|
151
155
|
|
|
152
156
|
export interface AuthLimiters {
|
|
153
157
|
attempts: RateLimiter
|
|
154
158
|
mails: RateLimiter
|
|
155
159
|
failures: RateLimiter
|
|
160
|
+
secondFactors: RateLimiter
|
|
156
161
|
}
|
|
157
162
|
|
|
158
163
|
export function createAuthLimiters(api: ServerPluginAPI, rateLimit: RateLimitOptions | false | undefined): AuthLimiters | undefined {
|
|
@@ -162,6 +167,7 @@ export function createAuthLimiters(api: ServerPluginAPI, rateLimit: RateLimitOpt
|
|
|
162
167
|
attempts: api.rateLimiter({ max: rateLimit?.max ?? 15, windowMs: rateLimit?.windowMs ?? 60_000 }),
|
|
163
168
|
mails: api.rateLimiter({ max: rateLimit?.mailsPerAddress ?? 3, windowMs: 600_000 }),
|
|
164
169
|
failures: api.rateLimiter({ max: rateLimit?.failuresPerAccount ?? 100, windowMs: 3_600_000 }),
|
|
170
|
+
secondFactors: api.rateLimiter({ max: rateLimit?.twoFactorFailuresPerAccount ?? 10, windowMs: 3_600_000 }),
|
|
165
171
|
}
|
|
166
172
|
}
|
|
167
173
|
|
|
@@ -185,6 +191,11 @@ export function authLimits(limiters: AuthLimiters | undefined, getTrustProxy: ()
|
|
|
185
191
|
if (email)
|
|
186
192
|
limiters?.failures.hit(`signin:${email}`)
|
|
187
193
|
},
|
|
194
|
+
refuseLockedSecondFactor: (ctx, userId) => tooMany(ctx, limiters?.secondFactors.peek(userId) ?? 0),
|
|
195
|
+
countFailedSecondFactor(ctx, userId) {
|
|
196
|
+
limiters?.secondFactors.hit(userId)
|
|
197
|
+
return tooMany(ctx, limiters?.secondFactors.peek(userId) ?? 0)
|
|
198
|
+
},
|
|
188
199
|
}
|
|
189
200
|
}
|
|
190
201
|
|
|
@@ -212,3 +223,12 @@ export function formatSessionIp(ip: string, mode: boolean | 'truncate'): string
|
|
|
212
223
|
}
|
|
213
224
|
return undefined
|
|
214
225
|
}
|
|
226
|
+
|
|
227
|
+
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
|
|
228
|
+
|
|
229
|
+
/** The origin a mailed link or a WebAuthn ceremony is bound to: `site`, else the request's own on a loopback host only, as elsewhere its Host header is the client's to choose. */
|
|
230
|
+
export function linkOrigin(site: string | undefined, url: URL): string | undefined {
|
|
231
|
+
if (site !== undefined)
|
|
232
|
+
return site
|
|
233
|
+
return LOOPBACK_HOSTS.has(url.hostname) ? url.origin : undefined
|
|
234
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -26,7 +26,7 @@ import type { TotpOptions } from './totp'
|
|
|
26
26
|
import { definePlugin } from 'prunelle/config'
|
|
27
27
|
import { isHttpsRequest, nodeEnv } from 'prunelle/server'
|
|
28
28
|
import { hashPassword, randomToken } from './crypto'
|
|
29
|
-
import { authLimits, createAuthLimiters, createAuthRouteRegistrar, isValidEmail } from './http'
|
|
29
|
+
import { authLimits, createAuthLimiters, createAuthRouteRegistrar, isValidEmail, linkOrigin } from './http'
|
|
30
30
|
import { buildMailDeliverer, createLinkService } from './links'
|
|
31
31
|
import { registerOAuthRoutes } from './oauth-routes'
|
|
32
32
|
import { registerOrgRoutes } from './org-routes'
|
|
@@ -59,6 +59,8 @@ export interface RateLimitOptions {
|
|
|
59
59
|
mailsPerAddress?: number | undefined
|
|
60
60
|
/** Wrong passwords one account takes across all addresses per hour before sign-in refuses it (default: 100). */
|
|
61
61
|
failuresPerAccount?: number | undefined
|
|
62
|
+
/** Wrong TOTP codes, recovery codes and passkey assertions one account takes across all addresses per hour before its second-factor step refuses it (default: 10). */
|
|
63
|
+
twoFactorFailuresPerAccount?: number | undefined
|
|
62
64
|
}
|
|
63
65
|
|
|
64
66
|
export { FRESH_SIGNIN_MS } from './account'
|
|
@@ -93,17 +95,10 @@ export type {
|
|
|
93
95
|
export { buildOtpauthUrl, generateTotpCode, generateTotpSecret } from './totp'
|
|
94
96
|
export type { TotpOptions, TwoFactorMethod } from './totp'
|
|
95
97
|
|
|
96
|
-
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
|
|
97
98
|
const DEFAULT_PRUNE_INTERVAL_MS = 15 * 60 * 1000
|
|
98
99
|
const MIN_PROD_SECRET_BYTES = 32
|
|
99
100
|
const DEFAULT_MAX_PASSWORD_LENGTH = 1024
|
|
100
101
|
|
|
101
|
-
// The request URL comes from the Host header, which the client controls: a link mailed to a victim must not point at it.
|
|
102
|
-
function linkOrigin(site: string | undefined, url: URL): string | undefined {
|
|
103
|
-
if (site !== undefined)
|
|
104
|
-
return site
|
|
105
|
-
return LOOPBACK_HOSTS.has(url.hostname) ? url.origin : undefined
|
|
106
|
-
}
|
|
107
102
|
|
|
108
103
|
// Mailed links and OAuth callbacks start with `site`, so anything but an http(s) origin is a config mistake.
|
|
109
104
|
function siteOrigin(value: string): string {
|
|
@@ -228,12 +223,12 @@ export interface AuthOptions<TUser extends AuthUser = AuthUser> {
|
|
|
228
223
|
export interface GuardOptions<TUser extends AuthUser = AuthUser> {
|
|
229
224
|
/** Redirect unauthenticated HTML requests here (JSON/API requests always receive 401). */
|
|
230
225
|
redirectTo?: string | undefined
|
|
231
|
-
/** Required role(s): checks `orgMembership.role` when `org` is set, otherwise `user.role
|
|
226
|
+
/** Required role(s): checks `orgMembership.role` when `org` is set, where `owner` outranks `admin`, which outranks `member`, and a custom role matches only itself; otherwise `user.role`, matched exactly. */
|
|
232
227
|
role?: string | string[] | undefined
|
|
233
228
|
/**
|
|
234
229
|
* Require organization membership and populate `ctx.locals.org` & `ctx.locals.orgMembership`:
|
|
235
230
|
* - `true`: reads `ctx.params.org ?? ctx.params.orgId ?? ctx.params.slug`
|
|
236
|
-
* - `string`: reads `ctx.params[org]
|
|
231
|
+
* - `string`: reads `ctx.params[org]`, answering `403` on a route without that param
|
|
237
232
|
* - function: calls `await org(ctx)` to resolve the org id or slug
|
|
238
233
|
*/
|
|
239
234
|
org?: boolean | string | ((ctx: RequestContext) => string | undefined | Promise<string | undefined>) | undefined
|
|
@@ -309,6 +304,19 @@ function unverifiedPruneOptions(ttlSeconds: number | false | undefined, requireE
|
|
|
309
304
|
|
|
310
305
|
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`.'
|
|
311
306
|
|
|
307
|
+
// The store methods that make a check and its write one step; without one, prunelle reads then writes under an in-process lock.
|
|
308
|
+
function warnIfStoreNotAtomic(store: AuthStore<AuthUser>, warn: (message: string) => void): void {
|
|
309
|
+
const methods = [
|
|
310
|
+
'updateUserIfUnverified',
|
|
311
|
+
'deleteUserIfUnverified',
|
|
312
|
+
...(store.setTotp ? ['advanceTotpStep'] as const : []),
|
|
313
|
+
...(store.createOrg ? ['updateOrgMemberRoleIfNotLastOwner', 'removeOrgMemberIfNotLastOwner'] as const : []),
|
|
314
|
+
] as const
|
|
315
|
+
const missing = methods.filter(name => typeof store[name] !== 'function')
|
|
316
|
+
if (missing.length > 0)
|
|
317
|
+
warn(`[auth/store-not-atomic] the AuthStore has no ${missing.join(', ')}, so prunelle checks then writes under a lock that only holds within one process: a second instance or a write from outside the app can slip between (a verification overwritten by the sign-up rollback, a TOTP code accepted twice, an org left with no owner). Implement them in the store, each as one transaction, as memoryAuthStore and sqliteAuthStore do.`)
|
|
318
|
+
}
|
|
319
|
+
|
|
312
320
|
function routeOriginOptions(options: Pick<AuthOptions, 'trustedOrigins' | 'trustProxy'>) {
|
|
313
321
|
return {
|
|
314
322
|
...(options.trustedOrigins !== undefined ? { trustedOrigins: options.trustedOrigins } : {}),
|
|
@@ -454,7 +462,6 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
454
462
|
try {
|
|
455
463
|
void Promise.resolve(store.pruneExpired?.(pruneOptions())).catch(() => {})
|
|
456
464
|
sessions.sweepRenewedAt()
|
|
457
|
-
passkeys.pruneChallenges()
|
|
458
465
|
}
|
|
459
466
|
catch {
|
|
460
467
|
// Ignore prune errors if the underlying store has been closed
|
|
@@ -536,8 +543,8 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
536
543
|
consumeLink,
|
|
537
544
|
sendMagicLink,
|
|
538
545
|
})
|
|
539
|
-
registerTotpRoutes({ authRoute, store, sessions, totp, basePath, defaultRedirect, messages })
|
|
540
|
-
registerPasskeyRoutes({ authRoute, store, sessions, passkeys, totp, twoFactorRedirect, defaultRedirect, requireEmailVerification })
|
|
546
|
+
registerTotpRoutes({ authRoute, limits: authLimitsObj, store, sessions, totp, basePath, defaultRedirect, messages })
|
|
547
|
+
registerPasskeyRoutes({ authRoute, limits: authLimitsObj, store, sessions, passkeys, totp, twoFactorRedirect, defaultRedirect, requireEmailVerification })
|
|
541
548
|
registerOrgRoutes({ authRoute, limits: authLimitsObj, sessions, orgs, defaultRedirect, hasMailTransport, mailedLinkOrigin })
|
|
542
549
|
registerAccountRoutes({ authRoute, sessions, account, clearPendingCookie: ctx => totp.clearPendingCookie(ctx) })
|
|
543
550
|
registerOAuthRoutes({
|
|
@@ -570,6 +577,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
570
577
|
enforce: 'pre',
|
|
571
578
|
providesLocals: ['user', 'session', 'org', 'orgMembership'],
|
|
572
579
|
requires: () => [isKeptInMemory(store) ? STORE_IN_MEMORY : undefined, requireEmailVerification && deliverMail === undefined ? NO_MAILER : undefined, secretProblem(configuredSecret(options.secret))].filter(line => line !== undefined),
|
|
580
|
+
check: ctx => warnIfStoreNotAtomic(store, ctx.warn),
|
|
573
581
|
server(api) {
|
|
574
582
|
if (options.trustProxy === undefined)
|
|
575
583
|
trustProxy = api.trustProxy
|
|
@@ -644,7 +652,6 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
644
652
|
async pruneExpired() {
|
|
645
653
|
await store.pruneExpired?.(pruneOptions())
|
|
646
654
|
sessions.sweepRenewedAt()
|
|
647
|
-
passkeys.pruneChallenges()
|
|
648
655
|
},
|
|
649
656
|
dispose,
|
|
650
657
|
}
|
package/src/links.ts
CHANGED
|
@@ -13,8 +13,8 @@ const LINK_MAILS = {
|
|
|
13
13
|
'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' },
|
|
14
14
|
} as const
|
|
15
15
|
|
|
16
|
-
//
|
|
17
|
-
function
|
|
16
|
+
// A tag of the user's current password, carried by a verify-email link so a password change invalidates the links sent before it.
|
|
17
|
+
function passwordTag(user: { id: string, passwordHash?: string | undefined }): string {
|
|
18
18
|
return sha256Hex(`verify:${user.id}:${user.passwordHash ?? ''}`).slice(0, 32)
|
|
19
19
|
}
|
|
20
20
|
|
|
@@ -61,7 +61,7 @@ export function createLinkService<TUser extends AuthUser = AuthUser>(deps: LinkS
|
|
|
61
61
|
): Promise<string> {
|
|
62
62
|
const normalized = normalizeEmail(email)
|
|
63
63
|
const boundUser = kind === 'verify-email' && userId !== undefined ? await sessions.observeAsync(store.getUserById(userId)) : undefined
|
|
64
|
-
const rawToken = boundUser ? `${randomToken(32)}.${
|
|
64
|
+
const rawToken = boundUser ? `${randomToken(32)}.${passwordTag(boundUser)}` : randomToken(32)
|
|
65
65
|
const tokenHash = sha256Hex(rawToken)
|
|
66
66
|
await sessions.observeAsync(store.createToken({
|
|
67
67
|
tokenHash,
|
|
@@ -143,7 +143,7 @@ export function createLinkService<TUser extends AuthUser = AuthUser>(deps: LinkS
|
|
|
143
143
|
: await sessions.observeAsync(store.getUserByEmail(consumed.email))
|
|
144
144
|
if (kind === 'verify-email') {
|
|
145
145
|
const dot = rawToken.lastIndexOf('.')
|
|
146
|
-
if (!user || dot <= 0 || !safeEqual(rawToken.slice(dot + 1),
|
|
146
|
+
if (!user || dot <= 0 || !safeEqual(rawToken.slice(dot + 1), passwordTag(user)))
|
|
147
147
|
return undefined
|
|
148
148
|
}
|
|
149
149
|
return { email: consumed.email, user }
|
package/src/oauth-routes.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { safeEqual, safeRedirect } from 'prunelle/server'
|
|
|
5
5
|
import type { OAuthProfile, OAuthProvider } from './oauth'
|
|
6
6
|
import type { AuthStore, AuthUser, PublicUser } from './store'
|
|
7
7
|
import type { TotpManager } from './totp'
|
|
8
|
-
import { pkceChallenge, randomToken,
|
|
8
|
+
import { pkceChallenge, randomToken, signJson, verifyJson } from './crypto'
|
|
9
9
|
import { authCookie, fail, withNoStore } from './http'
|
|
10
10
|
import { OAUTH_FETCH_TIMEOUT_MS } from './oauth'
|
|
11
11
|
import { normalizeEmail, toPublicUser } from './store'
|
|
@@ -157,7 +157,7 @@ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAu
|
|
|
157
157
|
const verifier = provider.pkce !== false ? randomToken(32) : undefined
|
|
158
158
|
const redirectTarget = safeRedirect(ctx.url.searchParams.get('redirect') ?? ctx.url.searchParams.get('next'), defaultRedirect)
|
|
159
159
|
|
|
160
|
-
const cookieVal =
|
|
160
|
+
const cookieVal = signJson(secret(), 'oauth', {
|
|
161
161
|
provider: provider.id,
|
|
162
162
|
state,
|
|
163
163
|
verifier,
|
|
@@ -198,7 +198,7 @@ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAu
|
|
|
198
198
|
if (!code || !returnedState || !rawCookie)
|
|
199
199
|
return fail(ctx, 400, 'Invalid OAuth callback parameters')
|
|
200
200
|
|
|
201
|
-
const saved =
|
|
201
|
+
const saved = verifyJson<OAuthStateCookie>(secret(), 'oauth', rawCookie)
|
|
202
202
|
if (!saved || saved.exp <= Date.now() || saved.provider !== provider.id || !safeEqual(saved.state, returnedState))
|
|
203
203
|
return fail(ctx, 400, 'Invalid or expired OAuth state')
|
|
204
204
|
|
package/src/org-routes.ts
CHANGED
|
@@ -153,7 +153,7 @@ export function registerOrgRoutes<TUser extends AuthUser = AuthUser>(deps: OrgRo
|
|
|
153
153
|
|
|
154
154
|
const email = normalizeEmail(body.email ?? '')
|
|
155
155
|
if (!isValidEmail(email))
|
|
156
|
-
return fail(ctx, 400, '
|
|
156
|
+
return fail(ctx, 400, 'Please enter a valid email address')
|
|
157
157
|
|
|
158
158
|
const linkOrigin = mailedLinkOrigin(ctx.url)
|
|
159
159
|
if (hasMailTransport && linkOrigin === undefined) {
|
package/src/orgs.ts
CHANGED
|
@@ -8,6 +8,7 @@ import { safeRedirect, wantsJson } from 'prunelle/server'
|
|
|
8
8
|
import { randomToken, sha256Hex } from './crypto'
|
|
9
9
|
import { escapeHtml, fail, isValidEmail } from './http'
|
|
10
10
|
import { normalizeEmail } from './store'
|
|
11
|
+
import type { RemoveOrgMemberResult } from './store-ext'
|
|
11
12
|
import { createKeyedLock } from './store-ext'
|
|
12
13
|
|
|
13
14
|
const ORG_SLUG_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/
|
|
@@ -23,21 +24,60 @@ function orgError(status: number, message: string): OrgError {
|
|
|
23
24
|
return err
|
|
24
25
|
}
|
|
25
26
|
|
|
26
|
-
//
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
27
|
+
// One in-process lock per store, shared by the org API and account deletion, for a store without the atomic last-owner methods.
|
|
28
|
+
const orgLocks = new WeakMap<object, ReturnType<typeof createKeyedLock>>()
|
|
29
|
+
|
|
30
|
+
function orgLockFor(store: object): ReturnType<typeof createKeyedLock> {
|
|
31
|
+
let lock = orgLocks.get(store)
|
|
32
|
+
if (lock === undefined) {
|
|
33
|
+
lock = createKeyedLock()
|
|
34
|
+
orgLocks.set(store, lock)
|
|
35
|
+
}
|
|
36
|
+
return lock
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Removes a member unless they are the org's last owner, in one step: through the store's atomic method, else under the store's in-process lock. */
|
|
40
|
+
export async function removeMemberUnlessLastOwner<TUser extends AuthUser>(store: AuthStore<TUser>, sessions: SessionManager<TUser>, orgId: string, userId: string): Promise<RemoveOrgMemberResult> {
|
|
41
|
+
if (store.removeOrgMemberIfNotLastOwner)
|
|
42
|
+
return await sessions.observeAsync(store.removeOrgMemberIfNotLastOwner(orgId, userId))
|
|
43
|
+
const os = requireOrgStore(store)
|
|
44
|
+
return orgLockFor(store)(orgId, async () => {
|
|
45
|
+
const current = await sessions.observeAsync(os.getOrgMember(orgId, userId))
|
|
46
|
+
if (!current)
|
|
47
|
+
return 'not-found'
|
|
48
|
+
if (current.role === 'owner' && (await sessions.observeAsync(os.listOrgMembers(orgId))).filter(m => m.role === 'owner').length <= 1)
|
|
49
|
+
return 'last-owner'
|
|
50
|
+
return await sessions.observeAsync(os.removeOrgMember(orgId, userId)) ? 'removed' : 'not-found'
|
|
51
|
+
})
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** What deleting a user does to their orgs: those they are the only member of go with them, and they leave the ones they own with others, refused with 409 where they are the last owner. Call `undo` if the deletion then fails. */
|
|
55
|
+
export async function leaveOrgsForDeletion<TUser extends AuthUser>(store: AuthStore<TUser>, sessions: SessionManager<TUser>, userId: string): Promise<{ deleted: string[], undo: () => Promise<void> }> {
|
|
30
56
|
const deleted: string[] = []
|
|
57
|
+
const left: OrgMembership[] = []
|
|
58
|
+
const undo = async (): Promise<void> => {
|
|
59
|
+
for (const membership of left)
|
|
60
|
+
await store.addOrgMember?.(membership)
|
|
61
|
+
}
|
|
62
|
+
if (!store.listUserOrgMemberships || !store.listOrgMembers || !store.getOrgMember)
|
|
63
|
+
return { deleted, undo }
|
|
31
64
|
for (const { org, role } of await store.listUserOrgMemberships(userId)) {
|
|
32
65
|
if (role !== 'owner')
|
|
33
66
|
continue
|
|
34
|
-
|
|
35
|
-
if (members.length === 1)
|
|
67
|
+
if ((await store.listOrgMembers(org.id)).length === 1) {
|
|
36
68
|
deleted.push(org.id)
|
|
37
|
-
|
|
69
|
+
continue
|
|
70
|
+
}
|
|
71
|
+
const membership = await store.getOrgMember(org.id, userId)
|
|
72
|
+
const result = await removeMemberUnlessLastOwner(store, sessions, org.id, userId)
|
|
73
|
+
if (result === 'last-owner') {
|
|
74
|
+
await undo()
|
|
38
75
|
throw orgError(409, `prunelle: this account is the last owner of "${org.name}": make another member owner, or delete the organization, before deleting the account`)
|
|
76
|
+
}
|
|
77
|
+
if (result === 'removed' && membership)
|
|
78
|
+
left.push(membership)
|
|
39
79
|
}
|
|
40
|
-
return deleted
|
|
80
|
+
return { deleted, undo }
|
|
41
81
|
}
|
|
42
82
|
|
|
43
83
|
export function slugifyOrgName(name: string): string {
|
|
@@ -196,14 +236,26 @@ function createInviteMethods<TUser extends AuthUser>(
|
|
|
196
236
|
if (!consumed)
|
|
197
237
|
throw orgError(400, 'prunelle: invitation has already been used')
|
|
198
238
|
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
239
|
+
try {
|
|
240
|
+
const existing = await sessions.observeAsync(os.getOrgMember(org.id, user.id))
|
|
241
|
+
const membership = existing ?? await sessions.observeAsync(os.addOrgMember({
|
|
242
|
+
orgId: org.id,
|
|
243
|
+
userId: user.id,
|
|
244
|
+
role: consumed.role,
|
|
245
|
+
createdAt: Date.now(),
|
|
246
|
+
}))
|
|
247
|
+
return { org, membership }
|
|
248
|
+
}
|
|
249
|
+
catch (err) {
|
|
250
|
+
// The invitee did nothing wrong: put the invitation back so the same link works once the store recovers.
|
|
251
|
+
try {
|
|
252
|
+
await sessions.observeAsync(os.createOrgInvite(consumed))
|
|
253
|
+
}
|
|
254
|
+
catch (restoreErr) {
|
|
255
|
+
console.error('[prunelle/auth] failed to restore an org invite after a failed acceptance:', restoreErr)
|
|
256
|
+
}
|
|
257
|
+
throw err
|
|
258
|
+
}
|
|
207
259
|
},
|
|
208
260
|
|
|
209
261
|
async revokeOrgInvite(orgId, inviteId) {
|
|
@@ -217,7 +269,7 @@ export function createOrgManager<TUser extends AuthUser = AuthUser>(deps: OrgMan
|
|
|
217
269
|
const { store, sessions } = deps
|
|
218
270
|
const inviteTtlMs = deps.orgInviteTtlMs ?? DEFAULT_ORG_INVITE_TTL_MS
|
|
219
271
|
const invites = createInviteMethods(deps, inviteTtlMs)
|
|
220
|
-
const withOrgLock =
|
|
272
|
+
const withOrgLock = orgLockFor(store)
|
|
221
273
|
|
|
222
274
|
async function getOrg(idOrSlug: string): Promise<Organization | undefined> {
|
|
223
275
|
const os = requireOrgStore(store)
|
|
@@ -338,19 +390,10 @@ export function createOrgManager<TUser extends AuthUser = AuthUser>(deps: OrgMan
|
|
|
338
390
|
},
|
|
339
391
|
|
|
340
392
|
async removeOrgMember(orgId, userId) {
|
|
341
|
-
const
|
|
342
|
-
if (
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
throw orgError(400, 'prunelle: cannot remove the last owner of an organization')
|
|
346
|
-
return res === 'removed'
|
|
347
|
-
}
|
|
348
|
-
return withOrgLock(orgId, async () => {
|
|
349
|
-
const existing = await assertNotLastOwner(orgId, userId, 'remove')
|
|
350
|
-
if (!existing)
|
|
351
|
-
return false
|
|
352
|
-
return await sessions.observeAsync(os.removeOrgMember(orgId, userId))
|
|
353
|
-
})
|
|
393
|
+
const res = await removeMemberUnlessLastOwner(store, sessions, orgId, userId)
|
|
394
|
+
if (res === 'last-owner')
|
|
395
|
+
throw orgError(400, 'prunelle: cannot remove the last owner of an organization')
|
|
396
|
+
return res === 'removed'
|
|
354
397
|
},
|
|
355
398
|
|
|
356
399
|
...invites,
|
|
@@ -368,16 +411,21 @@ async function resolveGuardOrgRef(
|
|
|
368
411
|
): Promise<string | undefined> {
|
|
369
412
|
if (orgOpt === true)
|
|
370
413
|
return ctx.params.org ?? ctx.params.orgId ?? ctx.params.slug
|
|
371
|
-
if (typeof orgOpt === 'string')
|
|
372
|
-
|
|
373
|
-
return ctx.params[orgOpt]
|
|
374
|
-
return orgOpt
|
|
375
|
-
}
|
|
414
|
+
if (typeof orgOpt === 'string')
|
|
415
|
+
return Object.hasOwn(ctx.params, orgOpt) ? ctx.params[orgOpt] : undefined
|
|
376
416
|
if (typeof orgOpt === 'function')
|
|
377
417
|
return await orgOpt(ctx)
|
|
378
418
|
return undefined
|
|
379
419
|
}
|
|
380
420
|
|
|
421
|
+
// Built-in org roles by rank: a guard for one lets the higher ones through. A custom role matches only itself.
|
|
422
|
+
const ORG_ROLE_RANK: Readonly<Record<string, number>> = { member: 1, admin: 2, owner: 3 }
|
|
423
|
+
|
|
424
|
+
function hasOrgRole(held: string, wanted: readonly string[]): boolean {
|
|
425
|
+
const rank = ORG_ROLE_RANK[held]
|
|
426
|
+
return wanted.some(role => role === held || (rank !== undefined && rank > (ORG_ROLE_RANK[role] ?? Infinity)))
|
|
427
|
+
}
|
|
428
|
+
|
|
381
429
|
export function createAuthGuard<TUser extends AuthUser>(
|
|
382
430
|
resolve: (ctx: RequestContext) => Promise<{ user: PublicUser<TUser>, session: AuthSession } | undefined>,
|
|
383
431
|
orgs: OrgManager,
|
|
@@ -405,7 +453,7 @@ export function createAuthGuard<TUser extends AuthUser>(
|
|
|
405
453
|
const membership = await orgs.getOrgMember(org.id, resolved.user.id)
|
|
406
454
|
if (!membership)
|
|
407
455
|
return fail(ctx, 403, 'Forbidden')
|
|
408
|
-
if (roles && !
|
|
456
|
+
if (roles && !hasOrgRole(membership.role, roles))
|
|
409
457
|
return fail(ctx, 403, 'Forbidden')
|
|
410
458
|
ctx.locals.org = org
|
|
411
459
|
ctx.locals.orgMembership = membership
|