@prunellejs/auth 0.1.1 → 0.7.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kaynooo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/llms.txt CHANGED
@@ -1,46 +1,69 @@
1
1
  # @prunellejs/auth Reference
2
2
 
3
- > Zero-dependency Bun-native authentication: Argon2id passwords, hashed DB sessions, email verification, magic links, OAuth 2.0 + PKCE, route guards, and RGPD helpers.
3
+ > Zero-dependency Bun-native authentication: Argon2id passwords, hashed DB sessions, email verification, magic links, OAuth 2.0 + PKCE, TOTP 2FA with recovery codes, WebAuthn Passkeys, Organizations & org-scoped guards, and RGPD helpers.
4
4
 
5
5
  ## Imports
6
6
 
7
- - `@prunellejs/auth`: `createAuth`, `memoryAuthStore`, `normalizeEmail`, `toPublicUser`, `safeRedirect` (re-exported from `prunelle/server`), `createRateLimiter` (deprecated: `rateLimit` on `api.route()` and `action()`, or `api.rateLimiter()`), `github`, `discord`, `google`, `oauthProvider`; types `Auth`, `AuthOptions`, `GuardOptions`, `AuthStore`, `AuthUser`, `PublicUser`, `AuthSession`, `OAuthAccount`, `TokenKind`, `VerificationToken`, `UserExport`, `AuthMailPayload`, `AuthMailer`, `CreateUserInput`, `OAuthProvider`, `OAuthPresetConfig`, `OAuthProfile`, `RateLimiter`, `RateLimitOptions`.
8
- - `@prunellejs/auth/sqlite`: `sqliteAuthStore(dbOrPath?: string | Database)` (returns `AuthStore & { readonly db: Database }`, uses `bun:sqlite` in WAL mode).
7
+ - `@prunellejs/auth`: `createAuth`, `memoryAuthStore`, `FRESH_SIGNIN_MS`, `normalizeEmail`, `toPublicUser`, `toPasskeySummary`, `generateTotpCode`, `generateTotpSecret`, `buildOtpauthUrl`, `safeRedirect` (re-exported from `prunelle/server`), `github`, `discord`, `google`, `oauthProvider`; types `Auth`, `AuthOptions`, `GuardOptions`, `AuthStore`, `AuthStoreExt`, `AuthUser`, `PublicUser`, `AuthSession`, `OAuthAccount`, `TokenKind`, `VerificationToken`, `TotpOptions`, `TotpRecord`, `RecoveryCodeRecord`, `TwoFactorMethod`, `PasskeyOptions`, `PasskeyUserVerification`, `PasskeyRecord`, `PasskeySummary`, `Organization`, `OrgMembership`, `OrgInvitation`, `UserOrgSummary`, `CreateOrgInput`, `InviteToOrgInput`, `UserExport`, `UserExportExt`, `AuthMailPayload`, `AuthMailer`, `CreateUserInput`, `PruneOptions`, `OAuthProvider`, `OAuthPresetConfig`, `OAuthProfile`, `RateLimitOptions`.
8
+ - `@prunellejs/auth/sqlite`: `sqliteAuthStore(dbOrPath?: string | Database)` (returns `AuthStore & { readonly db: Database }`, uses `bun:sqlite` in WAL mode with `secure_delete` on; a file it creates is `0600`; a file path opens, and its folder is created, at first use, so a build creates no database; a relative path resolves against the app root; TOTP, passkeys, and org tables are migrated lazily on first use).
9
9
  - `@prunellejs/auth/oauth`: `github`, `discord`, `google`, `oauthProvider`.
10
+ - `@prunellejs/auth/passkey`: browser-only WebAuthn client helper (`isPasskeySupported`, `registerPasskey`, `signInWithPasskey`, `verifyPasskey2FA`). Pages that do not import this subpath ship 0 B of passkey client code.
10
11
 
11
12
  ## Configuration (`createAuth(options)`)
12
13
 
13
14
  `createAuth()` returns a single object that is both the `PrunellePlugin` (register in `prunelle.config.ts`) and the app handle (import in routes/middleware):
14
15
 
15
16
  - `store`: `AuthStore` (default `memoryAuthStore()`; a production start refuses it and `sqliteAuthStore()` on `:memory:`: use `sqliteAuthStore('./data/auth.sqlite')`).
16
- - `secret`: string (defaults to `process.env.AUTH_SECRET`; required and ≥32 UTF-8 bytes in `NODE_ENV=production`).
17
- - `site`: public origin (`https://example.com`, inherits `PrunelleConfig.site`; required off localhost for mailed links & OAuth callbacks).
17
+ - `secret`: string (defaults to `process.env.AUTH_SECRET`; required and ≥32 UTF-8 bytes in `NODE_ENV=production`, checked by `requires()` at start, so a build runs without it). Also derives the AES-256-GCM key (via HKDF-SHA256) encrypting TOTP seeds at rest.
18
+ - `site`: public origin (`https://example.com`, inherits `PrunelleConfig.site`; required off localhost for mailed links, OAuth callbacks, and WebAuthn origin/rpId defaults).
18
19
  - `basePath`: route prefix (default `'/auth'`).
19
- - `cookieName`: session cookie name (default `'pru_session'`).
20
- - `sessionTtlSeconds` (default 30 days), `renewalIntervalSeconds` (sliding renewal), `tokenTtlSeconds` (default 15 min).
21
- - `minPasswordLength`: default `12` (CNIL guidance). `defaultRole`: `'user'`. `defaultRedirect`: `'/'`.
22
- - `requireEmailVerification`: default `true` (signup sends verification link and returns `202` without opening a session; signin refuses unverified users with `403`).
23
- - `mailer`: pass a `@prunellejs/mail` `Mailer` directly, or `sendMail(mail: AuthMailPayload)`.
20
+ - `cookieName`: session cookie name (default `'pru_session'`; sent as `__Host-pru_session` over https, a session under the plain name is moved on its next request). Short-lived signed cookies use `${cookieName}_oauth`, `${cookieName}_2fa`, and `${cookieName}_webauthn`.
21
+ - `storeOAuthProfile` (default `false`): keep the provider's name and avatar URL on an OAuth sign-up; off, the account holds the email alone.
22
+ - `sessionTtlSeconds` (default 30 days), `absoluteTtlSeconds` (default 90 days from sign-in, however often the session is used; `false` for none), `renewalIntervalSeconds` (sliding renewal), `tokenTtlSeconds` (default 15 min), `orgInviteTtlSeconds` (default 7 days).
23
+ - `minPasswordLength`: default `12` (CNIL guidance). `maxPasswordLength`: default `1024` (chars/UTF-8 bytes, capped before Argon2id). `defaultRole`: `'user'`. `defaultRedirect`: `'/'`.
24
+ - `requireEmailVerification`: default `true` (signup sends verification link and returns `202` without opening a session; a second signup on an unverified address clears its password and name, so only the mailed link signs the owner in; signin refuses unverified users with `403`; unverified OAuth callbacks require email verification and do not open a session or persist an unverified link). With no `mailer` or `sendMail`, a production start refuses, since no account could ever be verified.
25
+ - `unverifiedTtlSeconds`: default 7 days; each prune deletes an account whose address is still unverified that long after sign-up, with its tokens (`false` keeps them; ignored when `requireEmailVerification` is `false`).
26
+ - `onExportUser(user)`: returns the app's own data about a user, added to the export under `app`. `onDeleteUser(user)`: erases it before the account goes (e.g. ``files.deleteWhere(`users/${user.id}`)``), a throw keeping the account.
27
+ - `mailer`: pass a `@prunellejs/mail` `Mailer` directly, or `sendMail(mail: AuthMailPayload)` (handles `kind: 'magic-link' | 'verify-email' | 'reset-password' | 'org-invite'`).
24
28
  - `providers`: `[github({ clientId, clientSecret, scopes? }), discord(...), google(...), oauthProvider(...)]`.
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).
25
31
  - `trustProxy`: inherits `PrunelleConfig.trustProxy`. `trustedOrigins`: merged with `PrunelleConfig.trustedOrigins`.
26
- - `rateLimit`: `{ max?, windowMs? } | false` (default 15 a minute, per scope and address and per scope and email, counted in the server's store; a refusal is a `429` with `Retry-After`). `pruneIntervalMs`: default 15 min (`false` disables).
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).
27
33
  - RGPD minimization: `storeIp`: `'truncate'` (default, /24 IPv4 and /48 IPv6) | `true` | `false`; `storeUserAgent`: `true` (default) | `false`.
28
34
  - `defaultUserFields`: extra columns/fields merged on user creation when extending `AuthUser`.
29
35
 
30
36
  ## Mounted Routes (default `basePath = '/auth'`) & `ctx.locals`
31
37
 
32
- - `GET /auth/session` → `{ user, session }`
33
- - `POST /auth/signup`, `POST /auth/signin`, `POST /auth/signout` (accept form or JSON; redirect or JSON based on `Accept`)
34
- - `GET /auth/verify-email?token=...` and `GET /auth/magic-link/verify?token=...` (the mailed links) show a no-JS page whose button POSTs the token to the same URL; only that `POST` (form or JSON `{ token }`) consumes it, so mail scanners don't burn links
35
- - `POST /auth/magic-link` mails the sign-in link; the first claim of an unverified account drops prior password, sessions, and OAuth links
36
- - `GET /auth/oauth/:provider`, `GET /auth/oauth/:provider/callback`
37
- - `ctx.locals.user` (`PublicUser | undefined`) and `ctx.locals.session` (`AuthSession | undefined`) — lazily resolved on first read. The session middleware has `scope: 'rendered'`: a prerendered page, built before any visitor, never resolves or renews a session, and stays on Bun's route table.
38
+ - A sign-up mails its verification link after the answer, whatever the address (a failed send is logged and undone), and an address with whitespace, `,`, `;`, `<` or `>` is refused.
39
+ - Core: `GET /auth/session`, `POST /auth/signup`, `POST /auth/signin`, `POST /auth/signout`, `GET|POST /auth/verify-email`, `POST /auth/magic-link`, `GET|POST /auth/magic-link/verify`, `GET /auth/oauth/:provider`, `GET /auth/oauth/:provider/callback`.
40
+ - Account (RGPD art. 15, 17, 20), both refusing `401` when signed out and `403` `{ code: 'reauth-required' }` when the session opened more than 10 minutes ago (`FRESH_SIGNIN_MS`): `GET /auth/me/export` downloads `auth.exportUser()` as `account.json`; `POST /auth/me/delete` runs `auth.deleteUser()`, signs out and answers `{ ok: true }` or redirects to `redirect` (default `/`). Deleting takes the orgs the user alone belongs to and refuses `409` while they are the last owner of one with other members.
41
+ - TOTP 2FA (works without JS via HTML forms or JSON):
42
+ - When a user with TOTP enabled signs in via `POST /auth/signin`, no session is opened yet: a 5-minute HttpOnly signed `${cookieName}_2fa` cookie is issued; HTML redirects to `/auth/totp/verify?next=...` and JSON returns `{ ok: true, twoFactorRequired: true, methods: ['totp', ...], userId }`.
43
+ - `POST /auth/totp/setup` (authenticated) → creates pending enrollment `{ secret, otpauthUrl }`.
44
+ - `POST /auth/totp/confirm` (authenticated, `code`) → enables TOTP and returns 10 single-use recovery codes (`XXXX-XXXX`).
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
+ - `POST /auth/totp/disable` (authenticated, `code` = TOTP or recovery code) → disables TOTP and deletes recovery codes.
47
+ - Passkeys (WebAuthn L2, passwordless sign-in & 2FA):
48
+ - `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).
50
+ - `POST /auth/passkeys/2fa/options` & `POST /auth/passkeys/2fa/verify` (pending 2FA cookie; completes 2FA when user has registered passkeys).
51
+ - `GET /auth/passkeys` & `POST /auth/passkeys/delete` (authenticated, own passkeys only).
52
+ - Organizations (HTML form POST or JSON):
53
+ - `POST /auth/orgs` (authenticated, `{ name, slug? }`) → creates org with caller as `'owner'`.
54
+ - `POST /auth/orgs/invite` (authenticated `'owner'`/`'admin'`, `{ orgId | org | slug, email, role? }`) → mails one-time invite link (`kind: 'org-invite'`).
55
+ - `GET /auth/orgs/invite/accept?token=...` (no-JS confirm page) & `POST /auth/orgs/invite/accept` (authenticated; verifies user email matches invite).
56
+ - `POST /auth/orgs/member/role` (authenticated `'owner'`/`'admin'`) & `POST /auth/orgs/member/remove` (authenticated `'owner'`/`'admin'` or self-leave; refuses removing/demoting the last `'owner'`).
57
+ - Form errors (no JS): a sign-up, sign-in or `/auth/totp/verify` form post that fails goes back `303` to the same-origin page it came from (its `Referer`) with `?error=<code>`; a sign-up awaiting verification goes back with `?notice=signup.verification-sent`. `GET /auth/me/export` and `POST /auth/me/delete` do the same with a refusal. `auth.formMessage(url)` reads it as `{ code, form: 'signin' | 'signup' | 'totp' | 'account', field?: 'email' | 'password' | 'code', tone: 'danger' | 'success', text }`, and only from the plugin's own codes, so a crafted link cannot put words on the page. JSON callers, and a form with no same-origin `Referer`, get `{ ok: false, error, code }`. Codes: `signin.{invalid-credentials,email-not-verified,password-too-long}`, `signup.{invalid-email,password-too-short,password-too-long,email-taken,verification-sent}`, `totp.{code-required,invalid-code}`, `account.{reauth-required,last-owner}`.
58
+ - `ctx.locals`: `user` (`PublicUser | undefined`), `session` (`AuthSession | undefined`) — lazily resolved on first read (`scope: 'rendered'`); `org` (`Organization | undefined`) and `orgMembership` (`OrgMembership | undefined`) populated by `auth.guard({ org })`.
38
59
 
39
60
  ## Handle Methods (`auth`)
40
61
 
41
- - `auth.guard({ redirectTo?, role?, allow? })`: returns a `Middleware` (HTML redirects to `redirectTo?next=...`, JSON gets `401`, wrong role/predicate gets `403`).
42
- - `auth.getUser(ctx)`, `auth.getSession(ctx)`, `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?)`.
43
- - RGPD & maintenance: `auth.listSessions(userId)`, `auth.exportUser(userId)`, `auth.deleteUser(userId)`, `auth.pruneExpired()`, `auth.dispose()`.
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]` or looks up that slug/id; when a function, calls `await org(ctx)`; checks `role` against the member's org role 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
+ - TOTP: `auth.setupTotp(userId, opts?)`, `auth.confirmTotp(userId, code)`, `auth.verifyTotp(userId, code)`, `auth.disableTotp(userId, code)`, `auth.regenerateRecoveryCodes(userId)`.
64
+ - Passkeys: `auth.listPasskeys(userId)`, `auth.deletePasskey(userId, credentialId)`.
65
+ - 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`, `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`.
44
67
 
45
68
  ## Snippets
46
69
 
@@ -53,13 +76,20 @@ import { mail } from './mail'
53
76
  export const auth = createAuth({
54
77
  store: sqliteAuthStore('./data/app.sqlite'),
55
78
  mailer: mail,
79
+ totp: { issuer: 'Acme' },
80
+ passkeys: { rpName: 'Acme' },
56
81
  providers: [github({ clientId: process.env.GITHUB_ID!, clientSecret: process.env.GITHUB_SECRET! })],
57
82
  })
58
83
  ```
59
84
 
60
85
  ```ts
61
- // src/routes/app/_middleware.ts
62
- import { auth } from '../../auth'
86
+ // src/routes/org/[org]/settings/_middleware.ts
87
+ import { auth } from '../../../../auth'
63
88
 
64
- export default auth.guard({ redirectTo: '/login' })
89
+ export default auth.guard({ redirectTo: '/login', org: true, role: ['owner', 'admin'] })
90
+ ```
91
+
92
+ ```ts
93
+ // Browser island (ships passkey client code ONLY where imported)
94
+ import { isPasskeySupported, registerPasskey, signInWithPasskey } from '@prunellejs/auth/passkey'
65
95
  ```
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@prunellejs/auth",
3
- "version": "0.1.1",
4
- "description": "Zero-dependency Bun-native auth plugin for Prunelle (Argon2id, hashed sessions, SQLite, magic links, OAuth2 PKCE)",
3
+ "version": "0.7.0",
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",
7
7
  "sideEffects": false,
@@ -12,7 +12,8 @@
12
12
  "exports": {
13
13
  ".": "./src/index.ts",
14
14
  "./sqlite": "./src/sqlite.ts",
15
- "./oauth": "./src/oauth.ts"
15
+ "./oauth": "./src/oauth.ts",
16
+ "./passkey": "./src/passkey-client.ts"
16
17
  },
17
18
  "engines": {
18
19
  "bun": ">=1.4.0"
@@ -23,6 +24,6 @@
23
24
  "directory": "packages/plugin-auth"
24
25
  },
25
26
  "peerDependencies": {
26
- "prunelle": "^0.1.1"
27
+ "prunelle": "^0.7.0"
27
28
  }
28
29
  }
package/src/account.ts ADDED
@@ -0,0 +1,101 @@
1
+ import type { RequestContext } from 'prunelle/server'
2
+ import type { AuthRouteRegistrar } from './http'
3
+ import type { OrgError } from './orgs'
4
+ import type { SessionManager } from './session'
5
+ import type { AuthSession, AuthStore, AuthUser, PublicUser, UserExport } from './store'
6
+ import { safeRedirect, wantsJson } from 'prunelle/server'
7
+ import { fail, formPagePath } from './http'
8
+ import { orgsDeletedWithUser } from './orgs'
9
+ import { toPublicUser } from './store'
10
+
11
+ /** How recent a sign-in must be to export or delete the account it opened. */
12
+ export const FRESH_SIGNIN_MS = 10 * 60 * 1000
13
+
14
+ export interface AccountHooks<TUser extends AuthUser> {
15
+ onExportUser?: ((user: PublicUser<TUser>) => unknown) | undefined
16
+ onDeleteUser?: ((user: PublicUser<TUser>) => void | Promise<void>) | undefined
17
+ }
18
+
19
+ export interface AccountService<TUser extends AuthUser> {
20
+ exportUser(userId: string): Promise<UserExport<TUser> | null>
21
+ deleteUser(userId: string): Promise<void>
22
+ }
23
+
24
+ export function createAccountService<TUser extends AuthUser>(
25
+ store: AuthStore<TUser>,
26
+ sessions: SessionManager<TUser>,
27
+ hooks: AccountHooks<TUser>,
28
+ ): AccountService<TUser> {
29
+ return {
30
+ async exportUser(userId) {
31
+ const dump = await sessions.observeAsync(store.exportUser(userId))
32
+ if (!dump || !hooks.onExportUser)
33
+ return dump
34
+ return { ...dump, app: await hooks.onExportUser(dump.user) }
35
+ },
36
+ async deleteUser(userId) {
37
+ const user = await sessions.observeAsync(store.getUserById(userId))
38
+ if (!user)
39
+ return
40
+ const orgIds = await orgsDeletedWithUser(store, userId)
41
+ await hooks.onDeleteUser?.(toPublicUser(user))
42
+ for (const orgId of orgIds)
43
+ await store.deleteOrg?.(orgId)
44
+ await sessions.observeAsync(store.deleteUser(userId))
45
+ },
46
+ }
47
+ }
48
+
49
+ interface AccountRoutesDeps<TUser extends AuthUser> {
50
+ authRoute: AuthRouteRegistrar
51
+ sessions: SessionManager<TUser>
52
+ account: AccountService<TUser>
53
+ clearPendingCookie: (ctx: RequestContext) => void
54
+ }
55
+
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'
57
+
58
+ // 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
+ function refuse(ctx: RequestContext, code: 'account.reauth-required' | 'account.last-owner', json: () => Response): Response {
60
+ const back = formPagePath(ctx, 'error', code)
61
+ return back === undefined ? json() : ctx.redirect(back, 303)
62
+ }
63
+
64
+ async function freshSignin<TUser extends AuthUser>(ctx: RequestContext, sessions: SessionManager<TUser>): Promise<{ user: PublicUser<TUser>, session: AuthSession } | Response> {
65
+ const resolved = await sessions.resolve(ctx)
66
+ if (!resolved)
67
+ return fail(ctx, 401, 'Authentication required')
68
+ if (Date.now() - resolved.session.createdAt > FRESH_SIGNIN_MS)
69
+ return refuse(ctx, 'account.reauth-required', () => ctx.json({ ok: false, error: REAUTH_REQUIRED, code: 'reauth-required' }, { status: 403 }))
70
+ return resolved
71
+ }
72
+
73
+ export function registerAccountRoutes<TUser extends AuthUser>({ authRoute, sessions, account, clearPendingCookie }: AccountRoutesDeps<TUser>): void {
74
+ authRoute('GET', '/me/export', { limit: 'account-export' }, async (ctx) => {
75
+ const resolved = await freshSignin(ctx, sessions)
76
+ if (resolved instanceof Response)
77
+ return resolved
78
+ const dump = await account.exportUser(resolved.user.id)
79
+ return ctx.json(dump, { status: 200, headers: { 'content-disposition': 'attachment; filename="account.json"' } })
80
+ })
81
+
82
+ authRoute('POST', '/me/delete', { limit: 'account-delete', readBody: true }, async (ctx, body) => {
83
+ const resolved = await freshSignin(ctx, sessions)
84
+ if (resolved instanceof Response)
85
+ return resolved
86
+ try {
87
+ await account.deleteUser(resolved.user.id)
88
+ }
89
+ catch (err) {
90
+ const status = (err as Partial<OrgError>).status
91
+ if (status === 409)
92
+ return refuse(ctx, 'account.last-owner', () => fail(ctx, 409, (err as Error).message.replace(/^prunelle: /, '')))
93
+ throw err
94
+ }
95
+ clearPendingCookie(ctx)
96
+ await sessions.signOut(ctx)
97
+ if (wantsJson(ctx.request))
98
+ return ctx.json({ ok: true })
99
+ return ctx.redirect(safeRedirect(body.redirect ?? body.next, '/'), 303)
100
+ })
101
+ }
package/src/crypto.ts CHANGED
@@ -7,6 +7,10 @@ export function toBase64Url(bytes: Uint8Array): string {
7
7
  return Buffer.from(bytes).toString('base64url')
8
8
  }
9
9
 
10
+ export function fromBase64Url(value: string): Uint8Array {
11
+ return new Uint8Array(Buffer.from(value, 'base64url'))
12
+ }
13
+
10
14
  export function randomToken(byteLength = 32): string {
11
15
  const bytes = new Uint8Array(byteLength)
12
16
  crypto.getRandomValues(bytes)
@@ -19,6 +23,59 @@ export function sha256Hex(value: string): string {
19
23
  return hasher.digest('hex')
20
24
  }
21
25
 
26
+ export function sha256Bytes(value: string | Uint8Array): Uint8Array {
27
+ const hasher = new Bun.CryptoHasher('sha256')
28
+ hasher.update(value)
29
+ return new Uint8Array(hasher.digest())
30
+ }
31
+
32
+ const HKDF_SALT = new TextEncoder().encode('prunelle-auth-v1')
33
+ const TOTP_KEY_INFO = new TextEncoder().encode('totp-secret-aes-256-gcm')
34
+
35
+ async function deriveAesKey(masterSecret: string): Promise<CryptoKey> {
36
+ const baseKey = await crypto.subtle.importKey(
37
+ 'raw',
38
+ new TextEncoder().encode(masterSecret),
39
+ 'HKDF',
40
+ false,
41
+ ['deriveKey'],
42
+ )
43
+ return crypto.subtle.deriveKey(
44
+ { name: 'HKDF', hash: 'SHA-256', salt: HKDF_SALT, info: TOTP_KEY_INFO },
45
+ baseKey,
46
+ { name: 'AES-GCM', length: 256 },
47
+ false,
48
+ ['encrypt', 'decrypt'],
49
+ )
50
+ }
51
+
52
+ export async function encryptSecret(masterSecret: string, plaintext: string): Promise<string> {
53
+ const key = await deriveAesKey(masterSecret)
54
+ const iv = new Uint8Array(12)
55
+ crypto.getRandomValues(iv)
56
+ const ct = await crypto.subtle.encrypt(
57
+ { name: 'AES-GCM', iv },
58
+ key,
59
+ new TextEncoder().encode(plaintext),
60
+ )
61
+ return `v1.${toBase64Url(iv)}.${toBase64Url(new Uint8Array(ct))}`
62
+ }
63
+
64
+ export async function decryptSecret(masterSecret: string, encoded: string): Promise<string> {
65
+ const parts = encoded.split('.')
66
+ if (parts.length !== 3 || parts[0] !== 'v1' || !parts[1] || !parts[2])
67
+ throw new Error('prunelle: invalid encrypted secret format')
68
+ const key = await deriveAesKey(masterSecret)
69
+ const iv = fromBase64Url(parts[1])
70
+ const ct = fromBase64Url(parts[2])
71
+ const plain = await crypto.subtle.decrypt(
72
+ { name: 'AES-GCM', iv: new Uint8Array(iv) },
73
+ key,
74
+ new Uint8Array(ct),
75
+ )
76
+ return new TextDecoder().decode(plain)
77
+ }
78
+
22
79
  export function pkceChallenge(verifier: string): string {
23
80
  const hasher = new Bun.CryptoHasher('sha256')
24
81
  hasher.update(verifier)
@@ -0,0 +1,58 @@
1
+ // The codes a form post carries back to its page in `?error=` or `?notice=`, and the message each one stands for.
2
+
3
+ import { REAUTH_REQUIRED } from './account'
4
+
5
+ export type AuthFormCode =
6
+ | 'signin.invalid-credentials'
7
+ | 'signin.email-not-verified'
8
+ | 'signin.password-too-long'
9
+ | 'signup.invalid-email'
10
+ | 'signup.password-too-short'
11
+ | 'signup.password-too-long'
12
+ | 'signup.email-taken'
13
+ | 'signup.verification-sent'
14
+ | 'totp.code-required'
15
+ | 'totp.invalid-code'
16
+ | 'account.reauth-required'
17
+ | 'account.last-owner'
18
+
19
+ export interface AuthFormMessage {
20
+ code: AuthFormCode
21
+ /** The form the message belongs to, for a page holding several. */
22
+ form: 'signin' | 'signup' | 'totp' | 'account'
23
+ /** The field the message is about, to show it beside that field; absent for a message about the whole form. */
24
+ field?: 'email' | 'password' | 'code' | undefined
25
+ tone: 'danger' | 'success'
26
+ text: string
27
+ }
28
+
29
+ export type AuthFormMessages = Readonly<Record<AuthFormCode, AuthFormMessage>>
30
+
31
+ export function authFormMessages(minPasswordLength: number, maxPasswordLength: number): AuthFormMessages {
32
+ const danger = (code: AuthFormCode, field: AuthFormMessage['field'], text: string): AuthFormMessage =>
33
+ ({ code, form: code.slice(0, code.indexOf('.')) as AuthFormMessage['form'], field, tone: 'danger', text })
34
+ return {
35
+ 'signin.invalid-credentials': danger('signin.invalid-credentials', undefined, 'Invalid email or password'),
36
+ 'signin.email-not-verified': danger('signin.email-not-verified', undefined, 'Email not verified'),
37
+ 'signin.password-too-long': danger('signin.password-too-long', 'password', `Password must be at most ${maxPasswordLength} characters`),
38
+ 'signup.invalid-email': danger('signup.invalid-email', 'email', 'Please enter a valid email address'),
39
+ 'signup.password-too-short': danger('signup.password-too-short', 'password', `Password must be at least ${minPasswordLength} characters`),
40
+ 'signup.password-too-long': danger('signup.password-too-long', 'password', `Password must be at most ${maxPasswordLength} characters`),
41
+ 'signup.email-taken': danger('signup.email-taken', 'email', 'An account with this email already exists'),
42
+ 'signup.verification-sent': { code: 'signup.verification-sent', form: 'signup', tone: 'success', text: 'If that address can be registered, a verification link has been sent.' },
43
+ 'totp.code-required': danger('totp.code-required', 'code', 'Verification code is required'),
44
+ 'totp.invalid-code': danger('totp.invalid-code', 'code', 'Invalid verification code'),
45
+ 'account.reauth-required': danger('account.reauth-required', undefined, REAUTH_REQUIRED),
46
+ 'account.last-owner': danger('account.last-owner', undefined, 'You are the last owner of an organization other members still use: make one of them owner, or delete the organization, before deleting your account'),
47
+ }
48
+ }
49
+
50
+ /** The message a page's URL carries, read only from the codes above, so a crafted link cannot put its own words on the page. */
51
+ export function readFormMessage(messages: AuthFormMessages, url: URL): AuthFormMessage | undefined {
52
+ const error = url.searchParams.get('error')
53
+ const code = error ?? url.searchParams.get('notice')
54
+ if (code === null || !Object.hasOwn(messages, code))
55
+ return undefined
56
+ const found = messages[code as AuthFormCode]
57
+ return (found.tone === 'danger') === (error !== null) ? found : undefined
58
+ }
package/src/http.ts CHANGED
@@ -1,28 +1,56 @@
1
1
  // Request parsing and client-address helpers shared by the auth routes.
2
2
 
3
- import type { RateLimiter, RequestContext, TrustProxy } from 'prunelle/server'
4
- import { getClientIp, readStringFields, wantsJson } from 'prunelle/server'
3
+ import type { PluginRouteOptions, ServerPluginAPI } from 'prunelle/config'
4
+ import type { CookieOptions, RateLimiter, RequestContext, TrustProxy } from 'prunelle/server'
5
+ import type { AuthFormMessage } from './form-messages'
6
+ import type { RateLimitOptions } from './index'
7
+ import { getClientIp, rateLimitAddress, readStringFields, safeRedirect, wantsJson } from 'prunelle/server'
5
8
  import { normalizeEmail } from './store'
6
9
 
10
+ /** Every auth cookie: HttpOnly and Lax, and essential, since no one can sign in without it. */
11
+ export function authCookie(secure: boolean, maxAgeSeconds: number): CookieOptions {
12
+ return { path: '/', httpOnly: true, sameSite: 'lax', secure, maxAge: maxAgeSeconds, category: 'essential' }
13
+ }
14
+
7
15
  export function fail(ctx: RequestContext, status: number, error: string): Response {
8
16
  return ctx.json({ ok: false, error }, { status })
9
17
  }
10
18
 
11
- export function respondAuthError(ctx: RequestContext, status: number, error: string, redirectTo?: string): Response {
12
- if (wantsJson(ctx.request) || !redirectTo)
13
- return ctx.json({ ok: false, error }, { status })
14
- const sep = redirectTo.includes('?') ? '&' : '?'
15
- return ctx.redirect(`${redirectTo}${sep}error=${encodeURIComponent(error)}`, 303)
19
+ /** A JSON caller gets the error as JSON; a form goes back to its page with the error's code, which `auth.formMessage(url)` reads. */
20
+ export function respondAuthError(ctx: RequestContext, status: number, message: AuthFormMessage): Response {
21
+ const back = formPagePath(ctx, 'error', message.code)
22
+ if (back === undefined)
23
+ return ctx.json({ ok: false, error: message.text, code: message.code }, { status })
24
+ return ctx.redirect(back, 303)
25
+ }
26
+
27
+ /** The same-origin page a form was posted from (its Referer), with `param` set to `code` and any earlier error or notice dropped; `undefined` for a JSON caller or a page that cannot be told. */
28
+ export function formPagePath(ctx: RequestContext, param: 'error' | 'notice', code: string): string | undefined {
29
+ const referer = ctx.request.headers.get('referer')
30
+ if (wantsJson(ctx.request) || referer === null)
31
+ return undefined
32
+ const from = URL.parse(referer)
33
+ if (from === null || from.origin !== (ctx.request.headers.get('origin') ?? ctx.url.origin))
34
+ return undefined
35
+ from.searchParams.delete('error')
36
+ from.searchParams.delete('notice')
37
+ from.searchParams.set(param, code)
38
+ const path = safeRedirect(`${from.pathname}${from.search}`, '')
39
+ return path === '' ? undefined : path
16
40
  }
17
41
 
18
42
  const ATTR_SPECIALS_RE = /[&"<>]/g
19
43
  const ATTR_ENTITIES: Record<string, string> = { '&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;' }
20
44
 
45
+ export function escapeHtml(value: string): string {
46
+ return value.replace(ATTR_SPECIALS_RE, c => ATTR_ENTITIES[c]!)
47
+ }
48
+
21
49
  /** The page a mailed link opens: one button posting the token back, so a mail scanner's GET leaves the link unused. No script or style, so any CSP lets it through. */
22
50
  export function linkConfirmPage(copy: { title: string, button: string }, fields: Record<string, string>): Response {
23
51
  let inputs = ''
24
52
  for (const [name, value] of Object.entries(fields))
25
- inputs += `<input type="hidden" name="${name}" value="${value.replace(ATTR_SPECIALS_RE, c => ATTR_ENTITIES[c]!)}">`
53
+ inputs += `<input type="hidden" name="${name}" value="${escapeHtml(value)}">`
26
54
  const html = `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><meta name="referrer" content="no-referrer"><title>${copy.title}</title></head><body><main><h1>${copy.title}</h1><form method="post">${inputs}<button type="submit">${copy.button}</button></form></main></body></html>`
27
55
  return new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8' } })
28
56
  }
@@ -50,10 +78,65 @@ export async function parseBody(ctx: RequestContext): Promise<Record<string, str
50
78
  }
51
79
  }
52
80
 
81
+ export async function parseJsonBody(ctx: RequestContext): Promise<Record<string, unknown> | Response> {
82
+ try {
83
+ const raw = await ctx.request.text()
84
+ if (!raw.trim())
85
+ return {}
86
+ const parsed: unknown = JSON.parse(raw)
87
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
88
+ return fail(ctx, 400, 'Invalid JSON body')
89
+ return parsed as Record<string, unknown>
90
+ }
91
+ catch {
92
+ return fail(ctx, 400, 'Invalid JSON body')
93
+ }
94
+ }
95
+
96
+ export type AuthRouteRegistrar = (
97
+ method: 'GET' | 'POST',
98
+ path: string,
99
+ routeCfg: { limit?: string, mailLimit?: string, readBody?: boolean },
100
+ handler: (ctx: RequestContext, body: Record<string, string>) => Response | Promise<Response>,
101
+ ) => void
102
+
103
+ export function createAuthRouteRegistrar(
104
+ api: ServerPluginAPI,
105
+ basePath: string,
106
+ authRouteOpts: PluginRouteOptions,
107
+ limits: AuthLimits,
108
+ ): AuthRouteRegistrar {
109
+ return (method, path, routeCfg, handler) => {
110
+ api.route(method, `${basePath}${path}`, async (ctx) => {
111
+ if (routeCfg.limit !== undefined) {
112
+ const limited = limits.limitIp(ctx, routeCfg.limit)
113
+ if (limited)
114
+ return withNoStore(limited)
115
+ }
116
+ let body: Record<string, string> = {}
117
+ if (routeCfg.readBody) {
118
+ const parsed = await parseBody(ctx)
119
+ if (parsed instanceof Response)
120
+ return withNoStore(parsed)
121
+ body = parsed
122
+ }
123
+ if (routeCfg.mailLimit !== undefined) {
124
+ const limited = limits.limitMail(ctx, routeCfg.mailLimit, body.email)
125
+ if (limited)
126
+ return withNoStore(limited)
127
+ }
128
+ return withNoStore(await handler(ctx, body))
129
+ }, method === 'POST' ? authRouteOpts : undefined)
130
+ }
131
+ }
132
+
133
+ // Whitespace, and the characters that split or wrap an address list.
134
+ const EMAIL_FORBIDDEN_RE = /[\s,;<>]/
135
+
53
136
  export function isValidEmail(email: string): boolean {
54
137
  const e = email.trim()
55
138
  const at = e.indexOf('@')
56
- return at > 0 && at === e.lastIndexOf('@') && e.indexOf('.', at + 2) > at + 1 && !/\s/.test(e)
139
+ return at > 0 && at === e.lastIndexOf('@') && e.indexOf('.', at + 2) > at + 1 && !EMAIL_FORBIDDEN_RE.test(e)
57
140
  }
58
141
 
59
142
  export function resolveClientIp(ctx: RequestContext, trustProxy: TrustProxy): string {
@@ -63,24 +146,49 @@ export function resolveClientIp(ctx: RequestContext, trustProxy: TrustProxy): st
63
146
  export interface AuthLimits {
64
147
  /** The 429 to answer when this address is past the limit of `scope`, else `undefined`. */
65
148
  limitIp: (ctx: RequestContext, scope: string) => Response | undefined
66
- /** The same per email, for the forms that send one; nothing is counted without an email. */
67
- limitEmail: (ctx: RequestContext, scope: string, email: string | undefined) => Response | undefined
68
- }
69
-
70
- export function authLimits(limiter: RateLimiter | undefined, getTrustProxy: () => TrustProxy): AuthLimits {
71
- const limitKey = (ctx: RequestContext, key: string): Response | undefined => {
72
- const retryAfter = limiter?.hit(key) ?? 0
73
- if (retryAfter === 0)
74
- return undefined
75
- const refused = fail(ctx, 429, 'Too many requests')
76
- refused.headers.set('retry-after', String(retryAfter))
77
- return refused
149
+ /** The same per email across addresses, at the mail limit, for the forms that mail it; nothing is counted without an email. */
150
+ limitMail: (ctx: RequestContext, scope: string, email: string | undefined) => Response | undefined
151
+ /** The 429 to answer, before the password is checked, when this account is past its wrong passwords across addresses. */
152
+ refuseLockedAccount: (ctx: RequestContext, email: string) => Response | undefined
153
+ /** Counts a wrong password against the account. */
154
+ countFailedSignin: (email: string) => void
155
+ }
156
+
157
+ export interface AuthLimiters {
158
+ attempts: RateLimiter
159
+ mails: RateLimiter
160
+ failures: RateLimiter
161
+ }
162
+
163
+ export function createAuthLimiters(api: ServerPluginAPI, rateLimit: RateLimitOptions | false | undefined): AuthLimiters | undefined {
164
+ if (rateLimit === false)
165
+ return undefined
166
+ return {
167
+ attempts: api.rateLimiter({ max: rateLimit?.max ?? 15, windowMs: rateLimit?.windowMs ?? 60_000 }),
168
+ mails: api.rateLimiter({ max: rateLimit?.mailsPerAddress ?? 3, windowMs: 600_000 }),
169
+ failures: api.rateLimiter({ max: rateLimit?.failuresPerAccount ?? 100, windowMs: 3_600_000 }),
78
170
  }
171
+ }
172
+
173
+ function tooMany(ctx: RequestContext, retryAfter: number): Response | undefined {
174
+ if (retryAfter === 0)
175
+ return undefined
176
+ const refused = fail(ctx, 429, 'Too many requests')
177
+ refused.headers.set('retry-after', String(retryAfter))
178
+ return refused
179
+ }
180
+
181
+ export function authLimits(limiters: AuthLimiters | undefined, getTrustProxy: () => TrustProxy): AuthLimits {
79
182
  return {
80
- limitIp: (ctx, scope) => limitKey(ctx, `${scope}:ip:${resolveClientIp(ctx, getTrustProxy())}`),
81
- limitEmail(ctx, scope, email) {
183
+ limitIp: (ctx, scope) => tooMany(ctx, limiters?.attempts.hit(`${scope}:ip:${rateLimitAddress(resolveClientIp(ctx, getTrustProxy()))}`) ?? 0),
184
+ limitMail(ctx, scope, email) {
82
185
  const normalized = normalizeEmail(email ?? '')
83
- return normalized ? limitKey(ctx, `${scope}:email:${normalized}`) : undefined
186
+ return normalized ? tooMany(ctx, limiters?.mails.hit(`${scope}:${normalized}`) ?? 0) : undefined
187
+ },
188
+ refuseLockedAccount: (ctx, email) => tooMany(ctx, email ? limiters?.failures.peek(`signin:${email}`) ?? 0 : 0),
189
+ countFailedSignin(email) {
190
+ if (email)
191
+ limiters?.failures.hit(`signin:${email}`)
84
192
  },
85
193
  }
86
194
  }