@prunellejs/auth 0.0.0-stage → 0.7.2

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 ADDED
@@ -0,0 +1,95 @@
1
+ # @prunellejs/auth Reference
2
+
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
+
5
+ ## Imports
6
+
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
+ - `@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.
11
+
12
+ ## Configuration (`createAuth(options)`)
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):
15
+
16
+ - `store`: `AuthStore` (default `memoryAuthStore()`; a production start refuses it and `sqliteAuthStore()` on `:memory:`: use `sqliteAuthStore('./data/auth.sqlite')`).
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).
19
+ - `basePath`: route prefix (default `'/auth'`).
20
+ - `cookieName`: session cookie name (default `'pru_session'`; sent as `__Host-pru_session` over https). Set `acceptLegacyCookie: true` temporarily when upgrading to accept and migrate sessions still under the unprefixed name over https (default `false` so sibling subdomains cannot fixate sessions). 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'`).
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). 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
+ - `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).
33
+ - RGPD minimization: `storeIp`: `'truncate'` (default, /24 IPv4 and /48 IPv6) | `true` | `false`; `storeUserAgent`: `true` (default) | `false`.
34
+ - `defaultUserFields`: extra columns/fields merged on user creation when extending `AuthUser`.
35
+
36
+ ## Mounted Routes (default `basePath = '/auth'`) & `ctx.locals`
37
+
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 any path (`POST /auth/signin`, magic link verify, OAuth callback, or passkey login), 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 }` (passkey login requires TOTP/recovery code and excludes `'passkey'` from `methods`).
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 })`.
59
+
60
+ ## Handle Methods (`auth`)
61
+
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`.
67
+
68
+ ## Snippets
69
+
70
+ ```ts
71
+ // src/auth.ts
72
+ import { createAuth, github } from '@prunellejs/auth'
73
+ import { sqliteAuthStore } from '@prunellejs/auth/sqlite'
74
+ import { mail } from './mail'
75
+
76
+ export const auth = createAuth({
77
+ store: sqliteAuthStore('./data/app.sqlite'),
78
+ mailer: mail,
79
+ totp: { issuer: 'Acme' },
80
+ passkeys: { rpName: 'Acme' },
81
+ providers: [github({ clientId: process.env.GITHUB_ID!, clientSecret: process.env.GITHUB_SECRET! })],
82
+ })
83
+ ```
84
+
85
+ ```ts
86
+ // src/routes/org/[org]/settings/_middleware.ts
87
+ import { auth } from '../../../../auth'
88
+
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'
95
+ ```
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "@prunellejs/auth",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.7.2",
4
+ "description": "Zero-dependency Bun-native auth plugin for Prunelle (Argon2id, hashed sessions, SQLite, magic links, OAuth2 PKCE, TOTP 2FA, Passkeys, Organizations)",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "files": [
9
+ "src",
10
+ "llms.txt"
11
+ ],
12
+ "exports": {
13
+ ".": "./src/index.ts",
14
+ "./sqlite": "./src/sqlite.ts",
15
+ "./oauth": "./src/oauth.ts",
16
+ "./passkey": "./src/passkey-client.ts"
17
+ },
18
+ "engines": {
19
+ "bun": ">=1.4.0"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "https://github.com/Kayno0o/prunelle",
24
+ "directory": "packages/plugin-auth"
25
+ },
26
+ "peerDependencies": {
27
+ "prunelle": "^0.7.2"
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 ADDED
@@ -0,0 +1,130 @@
1
+ // Zero-dependency Bun-native crypto helpers for @prunellejs/auth.
2
+ // Uses crypto.getRandomValues, Bun.CryptoHasher (SHA-256 / HMAC-SHA256), and Bun.password (Argon2id).
3
+
4
+ import { safeEqual } from 'prunelle/server'
5
+
6
+ export function toBase64Url(bytes: Uint8Array): string {
7
+ return Buffer.from(bytes).toString('base64url')
8
+ }
9
+
10
+ export function fromBase64Url(value: string): Uint8Array {
11
+ return new Uint8Array(Buffer.from(value, 'base64url'))
12
+ }
13
+
14
+ export function randomToken(byteLength = 32): string {
15
+ const bytes = new Uint8Array(byteLength)
16
+ crypto.getRandomValues(bytes)
17
+ return toBase64Url(bytes)
18
+ }
19
+
20
+ export function sha256Hex(value: string): string {
21
+ const hasher = new Bun.CryptoHasher('sha256')
22
+ hasher.update(value)
23
+ return hasher.digest('hex')
24
+ }
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
+
79
+ export function pkceChallenge(verifier: string): string {
80
+ const hasher = new Bun.CryptoHasher('sha256')
81
+ hasher.update(verifier)
82
+ return hasher.digest().toString('base64url')
83
+ }
84
+
85
+
86
+ export function signPayload(secret: string, payload: unknown): string {
87
+ const encoded = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url')
88
+ const mac = new Bun.CryptoHasher('sha256', secret).update(encoded).digest().toString('base64url')
89
+ return `${encoded}.${mac}`
90
+ }
91
+
92
+ export function verifyPayload<T>(secret: string, token: string): T | undefined {
93
+ const dot = token.indexOf('.')
94
+ if (dot <= 0)
95
+ return undefined
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))
100
+ return undefined
101
+ try {
102
+ return JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8')) as T
103
+ }
104
+ catch {
105
+ return undefined
106
+ }
107
+ }
108
+
109
+ export async function hashPassword(password: string): Promise<string> {
110
+ return Bun.password.hash(password, { algorithm: 'argon2id', memoryCost: 19456, timeCost: 2 })
111
+ }
112
+
113
+ // Lazily computed dummy Argon2id hash so unknown-email sign-in spends the same CPU time as a real check.
114
+ let dummyHashPromise: Promise<string> | undefined
115
+ function getDummyHash(): Promise<string> {
116
+ return (dummyHashPromise ??= hashPassword('prunelle-auth-dummy-timing-shield'))
117
+ }
118
+
119
+ export async function verifyPassword(password: string, storedHash: string | undefined): Promise<boolean> {
120
+ if (!storedHash) {
121
+ await Bun.password.verify(password, await getDummyHash())
122
+ return false
123
+ }
124
+ try {
125
+ return await Bun.password.verify(password, storedHash)
126
+ }
127
+ catch {
128
+ return false
129
+ }
130
+ }
@@ -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
+ }