@prunellejs/auth 0.6.0 → 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 +21 -0
- package/llms.txt +15 -9
- package/package.json +2 -2
- package/src/account.ts +101 -0
- package/src/form-messages.ts +58 -0
- package/src/http.ts +77 -26
- package/src/index.ts +114 -50
- package/src/links.ts +43 -39
- package/src/oauth-routes.ts +21 -24
- package/src/org-routes.ts +1 -1
- package/src/orgs.ts +17 -0
- package/src/passkeys.ts +5 -9
- package/src/routes.ts +97 -82
- package/src/session-cookie.ts +55 -0
- package/src/session.ts +45 -42
- package/src/sqlite.ts +89 -38
- package/src/store.ts +48 -19
- package/src/totp-routes.ts +11 -5
- package/src/totp.ts +8 -12
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
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
|
|
5
5
|
## Imports
|
|
6
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).
|
|
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
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
11
|
|
|
@@ -14,25 +14,30 @@
|
|
|
14
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
15
|
|
|
16
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.
|
|
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
18
|
- `site`: public origin (`https://example.com`, inherits `PrunelleConfig.site`; required off localhost for mailed links, OAuth callbacks, and WebAuthn origin/rpId defaults).
|
|
19
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
|
-
- `
|
|
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).
|
|
22
23
|
- `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
|
+
- `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.
|
|
24
27
|
- `mailer`: pass a `@prunellejs/mail` `Mailer` directly, or `sendMail(mail: AuthMailPayload)` (handles `kind: 'magic-link' | 'verify-email' | 'reset-password' | 'org-invite'`).
|
|
25
28
|
- `providers`: `[github({ clientId, clientSecret, scopes? }), discord(...), google(...), oauthProvider(...)]`.
|
|
26
29
|
- `totp`: `{ issuer?, verifyPath? }`. `twoFactorRedirect`: custom redirect target for HTML form sign-ins when 2FA is required (default `${basePath}/totp/verify`).
|
|
27
30
|
- `passkeys`: `{ rpId?, rpName?, origin?, userVerification? }` (WebAuthn L2 ES256 / RS256 / EdDSA, zero npm deps).
|
|
28
31
|
- `trustProxy`: inherits `PrunelleConfig.trustProxy`. `trustedOrigins`: merged with `PrunelleConfig.trustedOrigins`.
|
|
29
|
-
- `rateLimit`: `{ max?, windowMs? } | false` (default 15 a minute
|
|
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).
|
|
30
33
|
- RGPD minimization: `storeIp`: `'truncate'` (default, /24 IPv4 and /48 IPv6) | `true` | `false`; `storeUserAgent`: `true` (default) | `false`.
|
|
31
34
|
- `defaultUserFields`: extra columns/fields merged on user creation when extending `AuthUser`.
|
|
32
35
|
|
|
33
36
|
## Mounted Routes (default `basePath = '/auth'`) & `ctx.locals`
|
|
34
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.
|
|
35
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.
|
|
36
41
|
- TOTP 2FA (works without JS via HTML forms or JSON):
|
|
37
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 }`.
|
|
38
43
|
- `POST /auth/totp/setup` (authenticated) → creates pending enrollment `{ secret, otpauthUrl }`.
|
|
@@ -49,15 +54,16 @@
|
|
|
49
54
|
- `POST /auth/orgs/invite` (authenticated `'owner'`/`'admin'`, `{ orgId | org | slug, email, role? }`) → mails one-time invite link (`kind: 'org-invite'`).
|
|
50
55
|
- `GET /auth/orgs/invite/accept?token=...` (no-JS confirm page) & `POST /auth/orgs/invite/accept` (authenticated; verifies user email matches invite).
|
|
51
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}`.
|
|
52
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 })`.
|
|
53
59
|
|
|
54
60
|
## Handle Methods (`auth`)
|
|
55
61
|
|
|
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?)`.
|
|
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?)`.
|
|
57
63
|
- TOTP: `auth.setupTotp(userId, opts?)`, `auth.confirmTotp(userId, code)`, `auth.verifyTotp(userId, code)`, `auth.disableTotp(userId, code)`, `auth.regenerateRecoveryCodes(userId)`.
|
|
58
64
|
- Passkeys: `auth.listPasskeys(userId)`, `auth.deletePasskey(userId, credentialId)`.
|
|
59
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)`.
|
|
60
|
-
- RGPD & maintenance: `auth.listSessions(userId)`, `auth.exportUser(userId)` (includes `user`, `sessions`, `oauthAccounts`, `totp` status/remaining recovery count without secrets, `passkeys` metadata, `organizations`,
|
|
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`.
|
|
61
67
|
|
|
62
68
|
## Snippets
|
|
63
69
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/auth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Zero-dependency Bun-native auth plugin for Prunelle (Argon2id, hashed sessions, SQLite, magic links, OAuth2 PKCE, TOTP 2FA, Passkeys, Organizations)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -24,6 +24,6 @@
|
|
|
24
24
|
"directory": "packages/plugin-auth"
|
|
25
25
|
},
|
|
26
26
|
"peerDependencies": {
|
|
27
|
-
"prunelle": "^0.
|
|
27
|
+
"prunelle": "^0.7.0"
|
|
28
28
|
}
|
|
29
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
|
+
}
|
|
@@ -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,19 +1,42 @@
|
|
|
1
1
|
// Request parsing and client-address helpers shared by the auth routes.
|
|
2
2
|
|
|
3
3
|
import type { PluginRouteOptions, ServerPluginAPI } from 'prunelle/config'
|
|
4
|
-
import type { RateLimiter, RequestContext, TrustProxy } from 'prunelle/server'
|
|
5
|
-
import {
|
|
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'
|
|
6
8
|
import { normalizeEmail } from './store'
|
|
7
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
|
+
|
|
8
15
|
export function fail(ctx: RequestContext, status: number, error: string): Response {
|
|
9
16
|
return ctx.json({ ok: false, error }, { status })
|
|
10
17
|
}
|
|
11
18
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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
|
|
17
40
|
}
|
|
18
41
|
|
|
19
42
|
const ATTR_SPECIALS_RE = /[&"<>]/g
|
|
@@ -73,7 +96,7 @@ export async function parseJsonBody(ctx: RequestContext): Promise<Record<string,
|
|
|
73
96
|
export type AuthRouteRegistrar = (
|
|
74
97
|
method: 'GET' | 'POST',
|
|
75
98
|
path: string,
|
|
76
|
-
routeCfg: { limit?: string,
|
|
99
|
+
routeCfg: { limit?: string, mailLimit?: string, readBody?: boolean },
|
|
77
100
|
handler: (ctx: RequestContext, body: Record<string, string>) => Response | Promise<Response>,
|
|
78
101
|
) => void
|
|
79
102
|
|
|
@@ -97,8 +120,8 @@ export function createAuthRouteRegistrar(
|
|
|
97
120
|
return withNoStore(parsed)
|
|
98
121
|
body = parsed
|
|
99
122
|
}
|
|
100
|
-
if (routeCfg.
|
|
101
|
-
const limited = limits.
|
|
123
|
+
if (routeCfg.mailLimit !== undefined) {
|
|
124
|
+
const limited = limits.limitMail(ctx, routeCfg.mailLimit, body.email)
|
|
102
125
|
if (limited)
|
|
103
126
|
return withNoStore(limited)
|
|
104
127
|
}
|
|
@@ -107,10 +130,13 @@ export function createAuthRouteRegistrar(
|
|
|
107
130
|
}
|
|
108
131
|
}
|
|
109
132
|
|
|
133
|
+
// Whitespace, and the characters that split or wrap an address list.
|
|
134
|
+
const EMAIL_FORBIDDEN_RE = /[\s,;<>]/
|
|
135
|
+
|
|
110
136
|
export function isValidEmail(email: string): boolean {
|
|
111
137
|
const e = email.trim()
|
|
112
138
|
const at = e.indexOf('@')
|
|
113
|
-
return at > 0 && at === e.lastIndexOf('@') && e.indexOf('.', at + 2) > at + 1 &&
|
|
139
|
+
return at > 0 && at === e.lastIndexOf('@') && e.indexOf('.', at + 2) > at + 1 && !EMAIL_FORBIDDEN_RE.test(e)
|
|
114
140
|
}
|
|
115
141
|
|
|
116
142
|
export function resolveClientIp(ctx: RequestContext, trustProxy: TrustProxy): string {
|
|
@@ -120,24 +146,49 @@ export function resolveClientIp(ctx: RequestContext, trustProxy: TrustProxy): st
|
|
|
120
146
|
export interface AuthLimits {
|
|
121
147
|
/** The 429 to answer when this address is past the limit of `scope`, else `undefined`. */
|
|
122
148
|
limitIp: (ctx: RequestContext, scope: string) => Response | undefined
|
|
123
|
-
/** The same per email, for the forms that
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
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 }),
|
|
135
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 {
|
|
136
182
|
return {
|
|
137
|
-
limitIp: (ctx, scope) =>
|
|
138
|
-
|
|
183
|
+
limitIp: (ctx, scope) => tooMany(ctx, limiters?.attempts.hit(`${scope}:ip:${rateLimitAddress(resolveClientIp(ctx, getTrustProxy()))}`) ?? 0),
|
|
184
|
+
limitMail(ctx, scope, email) {
|
|
139
185
|
const normalized = normalizeEmail(email ?? '')
|
|
140
|
-
return normalized ?
|
|
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}`)
|
|
141
192
|
},
|
|
142
193
|
}
|
|
143
194
|
}
|