@prunellejs/auth 0.1.1 → 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 +46 -22
- package/package.json +5 -4
- package/src/crypto.ts +57 -0
- package/src/http.ts +58 -1
- package/src/index.ts +206 -192
- package/src/links.ts +150 -0
- package/src/oauth-routes.ts +103 -41
- 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 +93 -68
- package/src/session.ts +113 -63
- package/src/sqlite-ext.ts +516 -0
- package/src/sqlite.ts +53 -39
- package/src/store-ext.ts +425 -0
- package/src/store.ts +73 -30
- package/src/totp-routes.ts +138 -0
- package/src/totp.ts +338 -0
- package/src/webauthn-crypto.ts +284 -0
package/llms.txt
CHANGED
|
@@ -1,27 +1,30 @@
|
|
|
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,
|
|
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`), `
|
|
8
|
-
- `@prunellejs/auth/sqlite`: `sqliteAuthStore(dbOrPath?: string | Database)` (returns `AuthStore & { readonly db: Database }`, uses `bun:sqlite` in WAL mode).
|
|
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
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
|
|
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).
|
|
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'`). 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'`).
|
|
24
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).
|
|
25
28
|
- `trustProxy`: inherits `PrunelleConfig.trustProxy`. `trustedOrigins`: merged with `PrunelleConfig.trustedOrigins`.
|
|
26
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).
|
|
27
30
|
- RGPD minimization: `storeIp`: `'truncate'` (default, /24 IPv4 and /48 IPv6) | `true` | `false`; `storeUserAgent`: `true` (default) | `false`.
|
|
@@ -29,18 +32,32 @@
|
|
|
29
32
|
|
|
30
33
|
## Mounted Routes (default `basePath = '/auth'`) & `ctx.locals`
|
|
31
34
|
|
|
32
|
-
- `GET /auth/session`
|
|
33
|
-
-
|
|
34
|
-
-
|
|
35
|
-
- `POST /auth/
|
|
36
|
-
- `
|
|
37
|
-
- `
|
|
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 })`.
|
|
38
53
|
|
|
39
54
|
## Handle Methods (`auth`)
|
|
40
55
|
|
|
41
|
-
- `auth.guard({ redirectTo?, role?, allow? })
|
|
42
|
-
- `auth.
|
|
43
|
-
-
|
|
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()`.
|
|
44
61
|
|
|
45
62
|
## Snippets
|
|
46
63
|
|
|
@@ -53,13 +70,20 @@ import { mail } from './mail'
|
|
|
53
70
|
export const auth = createAuth({
|
|
54
71
|
store: sqliteAuthStore('./data/app.sqlite'),
|
|
55
72
|
mailer: mail,
|
|
73
|
+
totp: { issuer: 'Acme' },
|
|
74
|
+
passkeys: { rpName: 'Acme' },
|
|
56
75
|
providers: [github({ clientId: process.env.GITHUB_ID!, clientSecret: process.env.GITHUB_SECRET! })],
|
|
57
76
|
})
|
|
58
77
|
```
|
|
59
78
|
|
|
60
79
|
```ts
|
|
61
|
-
// src/routes/
|
|
62
|
-
import { auth } from '
|
|
80
|
+
// src/routes/org/[org]/settings/_middleware.ts
|
|
81
|
+
import { auth } from '../../../../auth'
|
|
63
82
|
|
|
64
|
-
export default auth.guard({ redirectTo: '/login' })
|
|
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'
|
|
65
89
|
```
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/auth",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Zero-dependency Bun-native auth plugin for Prunelle (Argon2id, hashed sessions, SQLite, magic links, OAuth2 PKCE)",
|
|
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
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.
|
|
27
|
+
"prunelle": "^0.6.0"
|
|
27
28
|
}
|
|
28
29
|
}
|
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)
|
package/src/http.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Request parsing and client-address helpers shared by the auth routes.
|
|
2
2
|
|
|
3
|
+
import type { PluginRouteOptions, ServerPluginAPI } from 'prunelle/config'
|
|
3
4
|
import type { RateLimiter, RequestContext, TrustProxy } from 'prunelle/server'
|
|
4
5
|
import { getClientIp, readStringFields, wantsJson } from 'prunelle/server'
|
|
5
6
|
import { normalizeEmail } from './store'
|
|
@@ -18,11 +19,15 @@ export function respondAuthError(ctx: RequestContext, status: number, error: str
|
|
|
18
19
|
const ATTR_SPECIALS_RE = /[&"<>]/g
|
|
19
20
|
const ATTR_ENTITIES: Record<string, string> = { '&': '&', '"': '"', '<': '<', '>': '>' }
|
|
20
21
|
|
|
22
|
+
export function escapeHtml(value: string): string {
|
|
23
|
+
return value.replace(ATTR_SPECIALS_RE, c => ATTR_ENTITIES[c]!)
|
|
24
|
+
}
|
|
25
|
+
|
|
21
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. */
|
|
22
27
|
export function linkConfirmPage(copy: { title: string, button: string }, fields: Record<string, string>): Response {
|
|
23
28
|
let inputs = ''
|
|
24
29
|
for (const [name, value] of Object.entries(fields))
|
|
25
|
-
inputs += `<input type="hidden" name="${name}" value="${value
|
|
30
|
+
inputs += `<input type="hidden" name="${name}" value="${escapeHtml(value)}">`
|
|
26
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>`
|
|
27
32
|
return new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8' } })
|
|
28
33
|
}
|
|
@@ -50,6 +55,58 @@ export async function parseBody(ctx: RequestContext): Promise<Record<string, str
|
|
|
50
55
|
}
|
|
51
56
|
}
|
|
52
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
|
+
|
|
53
110
|
export function isValidEmail(email: string): boolean {
|
|
54
111
|
const e = email.trim()
|
|
55
112
|
const at = e.indexOf('@')
|