@prunellejs/auth 0.0.0-stage → 0.5.3

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 ADDED
@@ -0,0 +1,65 @@
1
+ # @prunellejs/auth Reference
2
+
3
+ > Zero-dependency Bun-native authentication: Argon2id passwords, hashed DB sessions, email verification, magic links, OAuth 2.0 + PKCE, route guards, and RGPD helpers.
4
+
5
+ ## Imports
6
+
7
+ - `@prunellejs/auth`: `createAuth`, `memoryAuthStore`, `normalizeEmail`, `toPublicUser`, `safeRedirect` (re-exported from `prunelle/server`), `github`, `discord`, `google`, `oauthProvider`; types `Auth`, `AuthOptions`, `GuardOptions`, `AuthStore`, `AuthUser`, `PublicUser`, `AuthSession`, `OAuthAccount`, `TokenKind`, `VerificationToken`, `UserExport`, `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).
9
+ - `@prunellejs/auth/oauth`: `github`, `discord`, `google`, `oauthProvider`.
10
+
11
+ ## Configuration (`createAuth(options)`)
12
+
13
+ `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
+ - `store`: `AuthStore` (default `memoryAuthStore()`; a production start refuses it and `sqliteAuthStore()` on `:memory:`: use `sqliteAuthStore('./data/auth.sqlite')`).
16
+ - `secret`: string (defaults to `process.env.AUTH_SECRET`; required and ≥32 UTF-8 bytes in `NODE_ENV=production`).
17
+ - `site`: public origin (`https://example.com`, inherits `PrunelleConfig.site`; required off localhost for mailed links & OAuth callbacks).
18
+ - `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). `maxPasswordLength`: default `1024` (chars/UTF-8 bytes, capped before Argon2id). `defaultRole`: `'user'`. `defaultRedirect`: `'/'`.
22
+ - `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).
23
+ - `mailer`: pass a `@prunellejs/mail` `Mailer` directly, or `sendMail(mail: AuthMailPayload)`.
24
+ - `providers`: `[github({ clientId, clientSecret, scopes? }), discord(...), google(...), oauthProvider(...)]`.
25
+ - `trustProxy`: inherits `PrunelleConfig.trustProxy`. `trustedOrigins`: merged with `PrunelleConfig.trustedOrigins`.
26
+ - `rateLimit`: `{ max?, windowMs? } | false` (default 15 a minute, per scope and address and per scope and email, counted in the server's store; a refusal is a `429` with `Retry-After`). `pruneIntervalMs`: default 15 min (`false` disables).
27
+ - RGPD minimization: `storeIp`: `'truncate'` (default, /24 IPv4 and /48 IPv6) | `true` | `false`; `storeUserAgent`: `true` (default) | `false`.
28
+ - `defaultUserFields`: extra columns/fields merged on user creation when extending `AuthUser`.
29
+
30
+ ## Mounted Routes (default `basePath = '/auth'`) & `ctx.locals`
31
+
32
+ - `GET /auth/session` → `{ user, session }`
33
+ - `POST /auth/signup`, `POST /auth/signin`, `POST /auth/signout` (accept form or JSON; redirect or JSON based on `Accept`)
34
+ - `GET /auth/verify-email?token=...` and `GET /auth/magic-link/verify?token=...` (the mailed links) show a no-JS page whose button POSTs the token to the same URL; only that `POST` (form or JSON `{ token }`) consumes it, so mail scanners don't burn links
35
+ - `POST /auth/magic-link` mails the sign-in link; the first claim of an unverified account drops prior password, sessions, and OAuth links
36
+ - `GET /auth/oauth/:provider`, `GET /auth/oauth/:provider/callback`
37
+ - `ctx.locals.user` (`PublicUser | undefined`) and `ctx.locals.session` (`AuthSession | undefined`) — lazily resolved on first read. The session middleware has `scope: 'rendered'`: a prerendered page, built before any visitor, never resolves or renews a session, and stays on Bun's route table.
38
+
39
+ ## Handle Methods (`auth`)
40
+
41
+ - `auth.guard({ redirectTo?, role?, allow? })`: returns a `Middleware` (HTML redirects to `redirectTo?next=...`, JSON gets `401`, wrong role/predicate gets `403`).
42
+ - `auth.getUser(ctx)`, `auth.getSession(ctx)`, `auth.resolve(ctx)`, `auth.createUser(input)`, `auth.createSessionForUser(userId, ctx)`, `auth.signOut(ctx)`, `auth.revokeAllSessions(userId)`, `auth.sendMagicLink(email, origin, redirectTo?)`, `auth.sendVerificationEmail(email, origin, redirectTo?)`.
43
+ - RGPD & maintenance: `auth.listSessions(userId)`, `auth.exportUser(userId)`, `auth.deleteUser(userId)`, `auth.pruneExpired()`, `auth.dispose()`.
44
+
45
+ ## Snippets
46
+
47
+ ```ts
48
+ // src/auth.ts
49
+ import { createAuth, github } from '@prunellejs/auth'
50
+ import { sqliteAuthStore } from '@prunellejs/auth/sqlite'
51
+ import { mail } from './mail'
52
+
53
+ export const auth = createAuth({
54
+ store: sqliteAuthStore('./data/app.sqlite'),
55
+ mailer: mail,
56
+ providers: [github({ clientId: process.env.GITHUB_ID!, clientSecret: process.env.GITHUB_SECRET! })],
57
+ })
58
+ ```
59
+
60
+ ```ts
61
+ // src/routes/app/_middleware.ts
62
+ import { auth } from '../../auth'
63
+
64
+ export default auth.guard({ redirectTo: '/login' })
65
+ ```
package/package.json CHANGED
@@ -1,6 +1,28 @@
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.5.3",
4
+ "description": "Zero-dependency Bun-native auth plugin for Prunelle (Argon2id, hashed sessions, SQLite, magic links, OAuth2 PKCE)",
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
+ },
17
+ "engines": {
18
+ "bun": ">=1.4.0"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "https://github.com/Kayno0o/prunelle",
23
+ "directory": "packages/plugin-auth"
24
+ },
25
+ "peerDependencies": {
26
+ "prunelle": "^0.5.3"
27
+ }
28
+ }
package/src/crypto.ts ADDED
@@ -0,0 +1,73 @@
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 randomToken(byteLength = 32): string {
11
+ const bytes = new Uint8Array(byteLength)
12
+ crypto.getRandomValues(bytes)
13
+ return toBase64Url(bytes)
14
+ }
15
+
16
+ export function sha256Hex(value: string): string {
17
+ const hasher = new Bun.CryptoHasher('sha256')
18
+ hasher.update(value)
19
+ return hasher.digest('hex')
20
+ }
21
+
22
+ export function pkceChallenge(verifier: string): string {
23
+ const hasher = new Bun.CryptoHasher('sha256')
24
+ hasher.update(verifier)
25
+ return hasher.digest().toString('base64url')
26
+ }
27
+
28
+
29
+ export function signPayload(secret: string, payload: unknown): string {
30
+ const encoded = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url')
31
+ const mac = new Bun.CryptoHasher('sha256', secret).update(encoded).digest().toString('base64url')
32
+ return `${encoded}.${mac}`
33
+ }
34
+
35
+ export function verifyPayload<T>(secret: string, token: string): T | undefined {
36
+ const dot = token.indexOf('.')
37
+ if (dot <= 0)
38
+ return undefined
39
+ const encoded = token.slice(0, dot)
40
+ const providedMac = token.slice(dot + 1)
41
+ const expectedMac = new Bun.CryptoHasher('sha256', secret).update(encoded).digest().toString('base64url')
42
+ if (!safeEqual(providedMac, expectedMac))
43
+ return undefined
44
+ try {
45
+ return JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8')) as T
46
+ }
47
+ catch {
48
+ return undefined
49
+ }
50
+ }
51
+
52
+ export async function hashPassword(password: string): Promise<string> {
53
+ return Bun.password.hash(password, { algorithm: 'argon2id', memoryCost: 19456, timeCost: 2 })
54
+ }
55
+
56
+ // Lazily computed dummy Argon2id hash so unknown-email sign-in spends the same CPU time as a real check.
57
+ let dummyHashPromise: Promise<string> | undefined
58
+ function getDummyHash(): Promise<string> {
59
+ return (dummyHashPromise ??= hashPassword('prunelle-auth-dummy-timing-shield'))
60
+ }
61
+
62
+ export async function verifyPassword(password: string, storedHash: string | undefined): Promise<boolean> {
63
+ if (!storedHash) {
64
+ await Bun.password.verify(password, await getDummyHash())
65
+ return false
66
+ }
67
+ try {
68
+ return await Bun.password.verify(password, storedHash)
69
+ }
70
+ catch {
71
+ return false
72
+ }
73
+ }
package/src/http.ts ADDED
@@ -0,0 +1,111 @@
1
+ // Request parsing and client-address helpers shared by the auth routes.
2
+
3
+ import type { RateLimiter, RequestContext, TrustProxy } from 'prunelle/server'
4
+ import { getClientIp, readStringFields, wantsJson } from 'prunelle/server'
5
+ import { normalizeEmail } from './store'
6
+
7
+ export function fail(ctx: RequestContext, status: number, error: string): Response {
8
+ return ctx.json({ ok: false, error }, { status })
9
+ }
10
+
11
+ export function respondAuthError(ctx: RequestContext, status: number, error: string, redirectTo?: string): Response {
12
+ if (wantsJson(ctx.request) || !redirectTo)
13
+ return ctx.json({ ok: false, error }, { status })
14
+ const sep = redirectTo.includes('?') ? '&' : '?'
15
+ return ctx.redirect(`${redirectTo}${sep}error=${encodeURIComponent(error)}`, 303)
16
+ }
17
+
18
+ const ATTR_SPECIALS_RE = /[&"<>]/g
19
+ const ATTR_ENTITIES: Record<string, string> = { '&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;' }
20
+
21
+ /** 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
+ export function linkConfirmPage(copy: { title: string, button: string }, fields: Record<string, string>): Response {
23
+ let inputs = ''
24
+ for (const [name, value] of Object.entries(fields))
25
+ inputs += `<input type="hidden" name="${name}" value="${value.replace(ATTR_SPECIALS_RE, c => ATTR_ENTITIES[c]!)}">`
26
+ 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
+ return new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8' } })
28
+ }
29
+
30
+ export function withNoStore(res: Response): Response {
31
+ if (res.headers.has('cache-control'))
32
+ return res
33
+ try {
34
+ res.headers.set('cache-control', 'no-store')
35
+ return res
36
+ }
37
+ catch {
38
+ const headers = new Headers(res.headers)
39
+ headers.set('cache-control', 'no-store')
40
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
41
+ }
42
+ }
43
+
44
+ export async function parseBody(ctx: RequestContext): Promise<Record<string, string> | Response> {
45
+ try {
46
+ return await readStringFields(ctx.request)
47
+ }
48
+ catch {
49
+ return fail(ctx, 400, 'Invalid request body')
50
+ }
51
+ }
52
+
53
+ export function isValidEmail(email: string): boolean {
54
+ const e = email.trim()
55
+ const at = e.indexOf('@')
56
+ return at > 0 && at === e.lastIndexOf('@') && e.indexOf('.', at + 2) > at + 1 && !/\s/.test(e)
57
+ }
58
+
59
+ export function resolveClientIp(ctx: RequestContext, trustProxy: TrustProxy): string {
60
+ return ctx.ip?.trim() || getClientIp(ctx.request, trustProxy) || 'unknown'
61
+ }
62
+
63
+ export interface AuthLimits {
64
+ /** The 429 to answer when this address is past the limit of `scope`, else `undefined`. */
65
+ limitIp: (ctx: RequestContext, scope: string) => Response | undefined
66
+ /** The same per email, for the forms that send one; nothing is counted without an email. */
67
+ limitEmail: (ctx: RequestContext, scope: string, email: string | undefined) => Response | undefined
68
+ }
69
+
70
+ export function authLimits(limiter: RateLimiter | undefined, getTrustProxy: () => TrustProxy): AuthLimits {
71
+ const limitKey = (ctx: RequestContext, key: string): Response | undefined => {
72
+ const retryAfter = limiter?.hit(key) ?? 0
73
+ if (retryAfter === 0)
74
+ return undefined
75
+ const refused = fail(ctx, 429, 'Too many requests')
76
+ refused.headers.set('retry-after', String(retryAfter))
77
+ return refused
78
+ }
79
+ return {
80
+ limitIp: (ctx, scope) => limitKey(ctx, `${scope}:ip:${resolveClientIp(ctx, getTrustProxy())}`),
81
+ limitEmail(ctx, scope, email) {
82
+ const normalized = normalizeEmail(email ?? '')
83
+ return normalized ? limitKey(ctx, `${scope}:email:${normalized}`) : undefined
84
+ },
85
+ }
86
+ }
87
+
88
+ export function formatSessionIp(ip: string, mode: boolean | 'truncate'): string | undefined {
89
+ if (mode === false || ip === 'unknown')
90
+ return undefined
91
+ if (mode === true)
92
+ return ip
93
+ // Truncate mode: IPv4 -> /24, IPv4-mapped IPv6 -> /120, IPv6 -> /48
94
+ const v4 = /^(\d{1,3}\.\d{1,3}\.\d{1,3})\.\d{1,3}$/.exec(ip)
95
+ if (v4)
96
+ return `${v4[1]}.0`
97
+ const v4Mapped = /^(::ffff:\d{1,3}\.\d{1,3}\.\d{1,3})\.\d{1,3}$/i.exec(ip)
98
+ if (v4Mapped)
99
+ return `${v4Mapped[1]}.0`
100
+ if (ip.includes(':')) {
101
+ const [head = '', tail = ''] = ip.split('::')
102
+ const headParts = head ? head.split(':').filter(Boolean) : []
103
+ const tailParts = ip.includes('::') && tail ? tail.split(':').filter(Boolean) : []
104
+ const full = ip.includes('::')
105
+ ? [...headParts, ...Array.from({ length: Math.max(0, 8 - headParts.length - tailParts.length) }, () => '0'), ...tailParts]
106
+ : headParts
107
+ if (full.length >= 3)
108
+ return `${full.slice(0, 3).join(':')}::`
109
+ }
110
+ return undefined
111
+ }