@prunellejs/auth 0.0.0-stage → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/llms.txt +89 -0
- package/package.json +27 -4
- package/src/crypto.ts +130 -0
- package/src/http.ts +168 -0
- package/src/index.ts +566 -0
- package/src/links.ts +150 -0
- package/src/oauth-routes.ts +255 -0
- package/src/oauth.ts +155 -0
- package/src/org-routes.ts +216 -0
- package/src/orgs.ts +386 -0
- package/src/passkey-client.ts +207 -0
- package/src/passkey-routes.ts +210 -0
- package/src/passkeys.ts +425 -0
- package/src/routes.ts +294 -0
- package/src/session.ts +380 -0
- package/src/sqlite-ext.ts +516 -0
- package/src/sqlite.ts +351 -0
- package/src/store-ext.ts +425 -0
- package/src/store.ts +310 -0
- package/src/totp-routes.ts +138 -0
- package/src/totp.ts +338 -0
- package/src/webauthn-crypto.ts +284 -0
- package/README.md +0 -3
package/llms.txt
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
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`, `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`, `OAuthProvider`, `OAuthPresetConfig`, `OAuthProfile`, `RateLimitOptions`.
|
|
8
|
+
- `@prunellejs/auth/sqlite`: `sqliteAuthStore(dbOrPath?: string | Database)` (returns `AuthStore & { readonly db: Database }`, uses `bun:sqlite` in WAL mode; 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`). 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'`). Short-lived signed cookies use `${cookieName}_oauth`, `${cookieName}_2fa`, and `${cookieName}_webauthn`.
|
|
21
|
+
- `sessionTtlSeconds` (default 30 days), `renewalIntervalSeconds` (sliding renewal), `tokenTtlSeconds` (default 15 min), `orgInviteTtlSeconds` (default 7 days).
|
|
22
|
+
- `minPasswordLength`: default `12` (CNIL guidance). `maxPasswordLength`: default `1024` (chars/UTF-8 bytes, capped before Argon2id). `defaultRole`: `'user'`. `defaultRedirect`: `'/'`.
|
|
23
|
+
- `requireEmailVerification`: default `true` (signup sends verification link and returns `202` without opening a session; signin refuses unverified users with `403`; unverified OAuth callbacks require email verification and do not open a session or persist an unverified link).
|
|
24
|
+
- `mailer`: pass a `@prunellejs/mail` `Mailer` directly, or `sendMail(mail: AuthMailPayload)` (handles `kind: 'magic-link' | 'verify-email' | 'reset-password' | 'org-invite'`).
|
|
25
|
+
- `providers`: `[github({ clientId, clientSecret, scopes? }), discord(...), google(...), oauthProvider(...)]`.
|
|
26
|
+
- `totp`: `{ issuer?, verifyPath? }`. `twoFactorRedirect`: custom redirect target for HTML form sign-ins when 2FA is required (default `${basePath}/totp/verify`).
|
|
27
|
+
- `passkeys`: `{ rpId?, rpName?, origin?, userVerification? }` (WebAuthn L2 ES256 / RS256 / EdDSA, zero npm deps).
|
|
28
|
+
- `trustProxy`: inherits `PrunelleConfig.trustProxy`. `trustedOrigins`: merged with `PrunelleConfig.trustedOrigins`.
|
|
29
|
+
- `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).
|
|
30
|
+
- RGPD minimization: `storeIp`: `'truncate'` (default, /24 IPv4 and /48 IPv6) | `true` | `false`; `storeUserAgent`: `true` (default) | `false`.
|
|
31
|
+
- `defaultUserFields`: extra columns/fields merged on user creation when extending `AuthUser`.
|
|
32
|
+
|
|
33
|
+
## Mounted Routes (default `basePath = '/auth'`) & `ctx.locals`
|
|
34
|
+
|
|
35
|
+
- 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`.
|
|
36
|
+
- TOTP 2FA (works without JS via HTML forms or JSON):
|
|
37
|
+
- 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 }`.
|
|
38
|
+
- `POST /auth/totp/setup` (authenticated) → creates pending enrollment `{ secret, otpauthUrl }`.
|
|
39
|
+
- `POST /auth/totp/confirm` (authenticated, `code`) → enables TOTP and returns 10 single-use recovery codes (`XXXX-XXXX`).
|
|
40
|
+
- `GET /auth/totp/verify` & `POST /auth/totp/verify` (pending 2FA cookie, `code` = 6-digit TOTP or recovery code) → clears pending cookie and opens session.
|
|
41
|
+
- `POST /auth/totp/disable` (authenticated, `code` = TOTP or recovery code) → disables TOTP and deletes recovery codes.
|
|
42
|
+
- Passkeys (WebAuthn L2, passwordless sign-in & 2FA):
|
|
43
|
+
- `POST /auth/passkeys/register/options` & `POST /auth/passkeys/register/verify` (authenticated).
|
|
44
|
+
- `POST /auth/passkeys/login/options` & `POST /auth/passkeys/login/verify` (public, discoverable or with optional `email` hint).
|
|
45
|
+
- `POST /auth/passkeys/2fa/options` & `POST /auth/passkeys/2fa/verify` (pending 2FA cookie; completes 2FA when user has registered passkeys).
|
|
46
|
+
- `GET /auth/passkeys` & `POST /auth/passkeys/delete` (authenticated, own passkeys only).
|
|
47
|
+
- Organizations (HTML form POST or JSON):
|
|
48
|
+
- `POST /auth/orgs` (authenticated, `{ name, slug? }`) → creates org with caller as `'owner'`.
|
|
49
|
+
- `POST /auth/orgs/invite` (authenticated `'owner'`/`'admin'`, `{ orgId | org | slug, email, role? }`) → mails one-time invite link (`kind: 'org-invite'`).
|
|
50
|
+
- `GET /auth/orgs/invite/accept?token=...` (no-JS confirm page) & `POST /auth/orgs/invite/accept` (authenticated; verifies user email matches invite).
|
|
51
|
+
- `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'`).
|
|
52
|
+
- `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 })`.
|
|
53
|
+
|
|
54
|
+
## Handle Methods (`auth`)
|
|
55
|
+
|
|
56
|
+
- 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.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?)`.
|
|
57
|
+
- TOTP: `auth.setupTotp(userId, opts?)`, `auth.confirmTotp(userId, code)`, `auth.verifyTotp(userId, code)`, `auth.disableTotp(userId, code)`, `auth.regenerateRecoveryCodes(userId)`.
|
|
58
|
+
- Passkeys: `auth.listPasskeys(userId)`, `auth.deletePasskey(userId, credentialId)`.
|
|
59
|
+
- 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)`.
|
|
60
|
+
- RGPD & maintenance: `auth.listSessions(userId)`, `auth.exportUser(userId)` (includes `user`, `sessions`, `oauthAccounts`, `totp` status/remaining recovery count without secrets, `passkeys` metadata, `organizations`, and pending `invitations`), `auth.deleteUser(userId)` (cascades sessions, OAuth links, tokens, TOTP, recovery codes, passkeys, org memberships, and pending invitations), `auth.pruneExpired()`, `auth.dispose()`.
|
|
61
|
+
|
|
62
|
+
## Snippets
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
// src/auth.ts
|
|
66
|
+
import { createAuth, github } from '@prunellejs/auth'
|
|
67
|
+
import { sqliteAuthStore } from '@prunellejs/auth/sqlite'
|
|
68
|
+
import { mail } from './mail'
|
|
69
|
+
|
|
70
|
+
export const auth = createAuth({
|
|
71
|
+
store: sqliteAuthStore('./data/app.sqlite'),
|
|
72
|
+
mailer: mail,
|
|
73
|
+
totp: { issuer: 'Acme' },
|
|
74
|
+
passkeys: { rpName: 'Acme' },
|
|
75
|
+
providers: [github({ clientId: process.env.GITHUB_ID!, clientSecret: process.env.GITHUB_SECRET! })],
|
|
76
|
+
})
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
// src/routes/org/[org]/settings/_middleware.ts
|
|
81
|
+
import { auth } from '../../../../auth'
|
|
82
|
+
|
|
83
|
+
export default auth.guard({ redirectTo: '/login', org: true, role: ['owner', 'admin'] })
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
// Browser island (ships passkey client code ONLY where imported)
|
|
88
|
+
import { isPasskeySupported, registerPasskey, signInWithPasskey } from '@prunellejs/auth/passkey'
|
|
89
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/auth",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.6.0",
|
|
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.6.0"
|
|
28
|
+
}
|
|
29
|
+
}
|
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
|
+
}
|
package/src/http.ts
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// Request parsing and client-address helpers shared by the auth routes.
|
|
2
|
+
|
|
3
|
+
import type { PluginRouteOptions, ServerPluginAPI } from 'prunelle/config'
|
|
4
|
+
import type { RateLimiter, RequestContext, TrustProxy } from 'prunelle/server'
|
|
5
|
+
import { getClientIp, readStringFields, wantsJson } from 'prunelle/server'
|
|
6
|
+
import { normalizeEmail } from './store'
|
|
7
|
+
|
|
8
|
+
export function fail(ctx: RequestContext, status: number, error: string): Response {
|
|
9
|
+
return ctx.json({ ok: false, error }, { status })
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function respondAuthError(ctx: RequestContext, status: number, error: string, redirectTo?: string): Response {
|
|
13
|
+
if (wantsJson(ctx.request) || !redirectTo)
|
|
14
|
+
return ctx.json({ ok: false, error }, { status })
|
|
15
|
+
const sep = redirectTo.includes('?') ? '&' : '?'
|
|
16
|
+
return ctx.redirect(`${redirectTo}${sep}error=${encodeURIComponent(error)}`, 303)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const ATTR_SPECIALS_RE = /[&"<>]/g
|
|
20
|
+
const ATTR_ENTITIES: Record<string, string> = { '&': '&', '"': '"', '<': '<', '>': '>' }
|
|
21
|
+
|
|
22
|
+
export function escapeHtml(value: string): string {
|
|
23
|
+
return value.replace(ATTR_SPECIALS_RE, c => ATTR_ENTITIES[c]!)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** 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. */
|
|
27
|
+
export function linkConfirmPage(copy: { title: string, button: string }, fields: Record<string, string>): Response {
|
|
28
|
+
let inputs = ''
|
|
29
|
+
for (const [name, value] of Object.entries(fields))
|
|
30
|
+
inputs += `<input type="hidden" name="${name}" value="${escapeHtml(value)}">`
|
|
31
|
+
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>`
|
|
32
|
+
return new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8' } })
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function withNoStore(res: Response): Response {
|
|
36
|
+
if (res.headers.has('cache-control'))
|
|
37
|
+
return res
|
|
38
|
+
try {
|
|
39
|
+
res.headers.set('cache-control', 'no-store')
|
|
40
|
+
return res
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
const headers = new Headers(res.headers)
|
|
44
|
+
headers.set('cache-control', 'no-store')
|
|
45
|
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function parseBody(ctx: RequestContext): Promise<Record<string, string> | Response> {
|
|
50
|
+
try {
|
|
51
|
+
return await readStringFields(ctx.request)
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return fail(ctx, 400, 'Invalid request body')
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function parseJsonBody(ctx: RequestContext): Promise<Record<string, unknown> | Response> {
|
|
59
|
+
try {
|
|
60
|
+
const raw = await ctx.request.text()
|
|
61
|
+
if (!raw.trim())
|
|
62
|
+
return {}
|
|
63
|
+
const parsed: unknown = JSON.parse(raw)
|
|
64
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
65
|
+
return fail(ctx, 400, 'Invalid JSON body')
|
|
66
|
+
return parsed as Record<string, unknown>
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return fail(ctx, 400, 'Invalid JSON body')
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export type AuthRouteRegistrar = (
|
|
74
|
+
method: 'GET' | 'POST',
|
|
75
|
+
path: string,
|
|
76
|
+
routeCfg: { limit?: string, emailLimit?: string, readBody?: boolean },
|
|
77
|
+
handler: (ctx: RequestContext, body: Record<string, string>) => Response | Promise<Response>,
|
|
78
|
+
) => void
|
|
79
|
+
|
|
80
|
+
export function createAuthRouteRegistrar(
|
|
81
|
+
api: ServerPluginAPI,
|
|
82
|
+
basePath: string,
|
|
83
|
+
authRouteOpts: PluginRouteOptions,
|
|
84
|
+
limits: AuthLimits,
|
|
85
|
+
): AuthRouteRegistrar {
|
|
86
|
+
return (method, path, routeCfg, handler) => {
|
|
87
|
+
api.route(method, `${basePath}${path}`, async (ctx) => {
|
|
88
|
+
if (routeCfg.limit !== undefined) {
|
|
89
|
+
const limited = limits.limitIp(ctx, routeCfg.limit)
|
|
90
|
+
if (limited)
|
|
91
|
+
return withNoStore(limited)
|
|
92
|
+
}
|
|
93
|
+
let body: Record<string, string> = {}
|
|
94
|
+
if (routeCfg.readBody) {
|
|
95
|
+
const parsed = await parseBody(ctx)
|
|
96
|
+
if (parsed instanceof Response)
|
|
97
|
+
return withNoStore(parsed)
|
|
98
|
+
body = parsed
|
|
99
|
+
}
|
|
100
|
+
if (routeCfg.emailLimit !== undefined) {
|
|
101
|
+
const limited = limits.limitEmail(ctx, routeCfg.emailLimit, body.email)
|
|
102
|
+
if (limited)
|
|
103
|
+
return withNoStore(limited)
|
|
104
|
+
}
|
|
105
|
+
return withNoStore(await handler(ctx, body))
|
|
106
|
+
}, method === 'POST' ? authRouteOpts : undefined)
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function isValidEmail(email: string): boolean {
|
|
111
|
+
const e = email.trim()
|
|
112
|
+
const at = e.indexOf('@')
|
|
113
|
+
return at > 0 && at === e.lastIndexOf('@') && e.indexOf('.', at + 2) > at + 1 && !/\s/.test(e)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function resolveClientIp(ctx: RequestContext, trustProxy: TrustProxy): string {
|
|
117
|
+
return ctx.ip?.trim() || getClientIp(ctx.request, trustProxy) || 'unknown'
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export interface AuthLimits {
|
|
121
|
+
/** The 429 to answer when this address is past the limit of `scope`, else `undefined`. */
|
|
122
|
+
limitIp: (ctx: RequestContext, scope: string) => Response | undefined
|
|
123
|
+
/** The same per email, for the forms that send one; nothing is counted without an email. */
|
|
124
|
+
limitEmail: (ctx: RequestContext, scope: string, email: string | undefined) => Response | undefined
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function authLimits(limiter: RateLimiter | undefined, getTrustProxy: () => TrustProxy): AuthLimits {
|
|
128
|
+
const limitKey = (ctx: RequestContext, key: string): Response | undefined => {
|
|
129
|
+
const retryAfter = limiter?.hit(key) ?? 0
|
|
130
|
+
if (retryAfter === 0)
|
|
131
|
+
return undefined
|
|
132
|
+
const refused = fail(ctx, 429, 'Too many requests')
|
|
133
|
+
refused.headers.set('retry-after', String(retryAfter))
|
|
134
|
+
return refused
|
|
135
|
+
}
|
|
136
|
+
return {
|
|
137
|
+
limitIp: (ctx, scope) => limitKey(ctx, `${scope}:ip:${resolveClientIp(ctx, getTrustProxy())}`),
|
|
138
|
+
limitEmail(ctx, scope, email) {
|
|
139
|
+
const normalized = normalizeEmail(email ?? '')
|
|
140
|
+
return normalized ? limitKey(ctx, `${scope}:email:${normalized}`) : undefined
|
|
141
|
+
},
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function formatSessionIp(ip: string, mode: boolean | 'truncate'): string | undefined {
|
|
146
|
+
if (mode === false || ip === 'unknown')
|
|
147
|
+
return undefined
|
|
148
|
+
if (mode === true)
|
|
149
|
+
return ip
|
|
150
|
+
// Truncate mode: IPv4 -> /24, IPv4-mapped IPv6 -> /120, IPv6 -> /48
|
|
151
|
+
const v4 = /^(\d{1,3}\.\d{1,3}\.\d{1,3})\.\d{1,3}$/.exec(ip)
|
|
152
|
+
if (v4)
|
|
153
|
+
return `${v4[1]}.0`
|
|
154
|
+
const v4Mapped = /^(::ffff:\d{1,3}\.\d{1,3}\.\d{1,3})\.\d{1,3}$/i.exec(ip)
|
|
155
|
+
if (v4Mapped)
|
|
156
|
+
return `${v4Mapped[1]}.0`
|
|
157
|
+
if (ip.includes(':')) {
|
|
158
|
+
const [head = '', tail = ''] = ip.split('::')
|
|
159
|
+
const headParts = head ? head.split(':').filter(Boolean) : []
|
|
160
|
+
const tailParts = ip.includes('::') && tail ? tail.split(':').filter(Boolean) : []
|
|
161
|
+
const full = ip.includes('::')
|
|
162
|
+
? [...headParts, ...Array.from({ length: Math.max(0, 8 - headParts.length - tailParts.length) }, () => '0'), ...tailParts]
|
|
163
|
+
: headParts
|
|
164
|
+
if (full.length >= 3)
|
|
165
|
+
return `${full.slice(0, 3).join(':')}::`
|
|
166
|
+
}
|
|
167
|
+
return undefined
|
|
168
|
+
}
|