@cslug/auth 0.0.0-stage → 0.1.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/README.md CHANGED
@@ -1,3 +1,7 @@
1
- # Temporary Holding Version
1
+ # @cslug/auth
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Session and token authentication (`ctx.auth`), password hashing, magic links, API tokens, policies and gates.
4
+ List `AuthProvider` in `bootstrap/providers.ts` and set `config/auth.ts` → `users`.
5
+
6
+ Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md),
7
+ [guide 15](../../guides/15-auth-and-authorization.md).
package/docs/README.md ADDED
@@ -0,0 +1,17 @@
1
+ # @cslug/auth
2
+
3
+ `AuthProvider` binds `Hash`, `Gate`, `Tokens`, `MagicLinks`, adds `authenticate()` to the web and api route groups
4
+ (through `@cslug/http`'s `WEB_MIDDLEWARE` / `API_MIDDLEWARE` tags), and registers the `cslug_access_tokens`
5
+ migration (`@cslug/database`'s `addMigrations`).
6
+
7
+ Per request, `authenticate()` creates `ctx.auth` and loads the user (one primary-key lookup) from a `Bearer`
8
+ token or the session's `auth.id`, so `auth.user()` is synchronous and views can read `useRequest().user`.
9
+
10
+ Security notes:
11
+ - `login()` regenerates the session id (fixation) and the CSRF token.
12
+ - `attempt()` is throttled per email + IP, verifies a dummy hash for unknown emails (no timing oracle), logs
13
+ failures without the password, and rehashes when parameters change.
14
+ - Token secrets are stored as SHA-256 and compared in constant time.
15
+ - Magic-link redirects must be local paths.
16
+
17
+ Testing: `t.actingAs(user)` (from `@cslug/testing`) signs requests in through the session.
package/docs/api.md ADDED
@@ -0,0 +1,15 @@
1
+ # @cslug/auth: API
2
+
3
+ | | |
4
+ |---|---|
5
+ | `ctx.auth` (`Auth`) | `user()`, `userOrNull()`, `check()`, `id`, `guard` (`'web' \| 'token'`), `token`, `login(user)`, `logout()`, `attempt(email, password)`, `can/cannot/authorize(Policy, ability, ...args)` or `(gate, ...args)`, `tokenCan(ability)` |
6
+ | `ctx.user` | The user or null |
7
+ | `Hash` | `make`, `verify`, `needsRehash` (argon2id via `Bun.password`; bcrypt supported) |
8
+ | `Policy` | Base class; methods `(user, ...args) => boolean`, optional `before(user)` |
9
+ | `Gate` | `define(name, (user, ...args) => boolean)` in a provider's `boot()` |
10
+ | `Tokens` | `create(user, { name, abilities?, expiresIn? })` → `{ plainText, token }`, `verify`, `list`, `revoke`, `revokeAll` |
11
+ | `MagicLinks` | `create(user, { redirect?, lifetime? })` → `{ token, expiresAt }`; `consume(token)` → `{ user, redirectTo }` or `MagicLinkError` (400: invalid, expired, used) |
12
+ | Middleware | `authenticate()`, `auth(guard?)`, `guest()`, `ability(...)`, `can(gate)` |
13
+ | `AuthProvider` | Config `auth`: `users`, `fields`, `passwords`, `magicLinks`, `throttle`, `loginRoute`, `home` |
14
+
15
+ Type the user once: `declare module '@cslug/core' { interface AuthUser extends User {} }`.
@@ -0,0 +1,15 @@
1
+ -- up
2
+ create table cslug_access_tokens (
3
+ id uuid primary key,
4
+ user_id text not null,
5
+ name text not null,
6
+ token_hash text not null,
7
+ abilities jsonb not null default '["*"]',
8
+ last_used_at timestamptz,
9
+ expires_at timestamptz,
10
+ created_at timestamptz not null default now()
11
+ );
12
+ create index cslug_access_tokens_user_id_idx on cslug_access_tokens (user_id);
13
+
14
+ -- down
15
+ drop table cslug_access_tokens;
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@cslug/auth",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Session and token guards, password hashing, magic links, policies and gates.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/cslugts/cslug.git",
10
+ "directory": "packages/auth"
11
+ },
12
+ "homepage": "https://github.com/cslugts/cslug/tree/main/packages/auth",
13
+ "keywords": [
14
+ "cslug",
15
+ "bun",
16
+ "framework"
17
+ ],
18
+ "exports": {
19
+ ".": "./src/index.ts"
20
+ },
21
+ "files": [
22
+ "src",
23
+ "docs",
24
+ "stubs",
25
+ "README.md",
26
+ "migrations"
27
+ ],
28
+ "engines": {
29
+ "bun": ">=1.3.14"
30
+ },
31
+ "peerDependencies": {
32
+ "@cslug/core": "0.1.0",
33
+ "@cslug/http": "0.1.0",
34
+ "@cslug/database": "0.1.0"
35
+ },
36
+ "devDependencies": {
37
+ "@cslug/testing": "workspace:*",
38
+ "@cslug/validation": "workspace:*"
39
+ }
40
+ }
package/src/auth.ts ADDED
@@ -0,0 +1,190 @@
1
+ import {
2
+ type AuthUser,
3
+ currentContext,
4
+ ForbiddenError,
5
+ RateLimiter,
6
+ TooManyRequestsError,
7
+ UnauthorizedError,
8
+ } from '@cslug/core'
9
+ import type { HttpContext } from '@cslug/http'
10
+ import { type AuthConfig, field, idOf, type UserSource } from './config'
11
+ import type { Hash } from './hash'
12
+ import { type Abilities, type AbilityArgs, checkPolicy, Gate, type PolicyClass } from './policy'
13
+ import { type AccessToken, type Tokens, tokenCan } from './tokens'
14
+
15
+ /** The session key holding the signed-in user's id. */
16
+ export const SESSION_KEY = 'auth.id'
17
+
18
+ export type AuthDeps = {
19
+ config: AuthConfig
20
+ users: () => Promise<UserSource>
21
+ hash: Hash
22
+ tokens: () => Tokens
23
+ }
24
+
25
+ /**
26
+ * Who is making this request (`ctx.auth`). The `authenticate()` middleware (in the web and api groups) loads the
27
+ * user from the session or a `Bearer` token before the handler runs, so `user()` is synchronous.
28
+ */
29
+ export class Auth {
30
+ private current: AuthUser | null = null
31
+ /** How the user was authenticated: the session (`web`) or an API token (`token`). */
32
+ guard: 'web' | 'token' | undefined
33
+ /** The API token, when the request used one. */
34
+ token: AccessToken | undefined
35
+ loaded = false
36
+
37
+ constructor(
38
+ private readonly ctx: HttpContext,
39
+ private readonly deps: AuthDeps,
40
+ ) {}
41
+
42
+ private get hasSession(): boolean {
43
+ return this.ctx.session.constructor.name !== 'MissingSession'
44
+ }
45
+
46
+ /** Load the user from a Bearer token, else the session (called by `authenticate()`). */
47
+ async load(): Promise<void> {
48
+ this.loaded = true
49
+ const header = this.ctx.request.header('authorization')
50
+ if (header?.startsWith('Bearer ')) {
51
+ const token = await this.deps.tokens().verify(header.slice(7).trim())
52
+ const user = token ? await (await this.deps.users()).find(token.userId) : null
53
+ if (token && user) this.set(user as AuthUser, 'token', token)
54
+ return
55
+ }
56
+ if (!this.hasSession) return
57
+ const id = this.ctx.session.get<string>(SESSION_KEY)
58
+ if (id === undefined) return
59
+ const user = await (await this.deps.users()).find(id)
60
+ if (user) this.set(user as AuthUser, 'web')
61
+ else this.ctx.session.forget(SESSION_KEY) // deleted user
62
+ }
63
+
64
+ private set(user: AuthUser | null, guard?: 'web' | 'token', token?: AccessToken): void {
65
+ this.current = user
66
+ this.guard = user ? guard : undefined
67
+ this.token = token
68
+ const store = currentContext()
69
+ if (store) store.userId = user ? idOf(user) : undefined
70
+ ;(this.ctx as unknown as { user: AuthUser | null }).user = user
71
+ }
72
+
73
+ /** The signed-in user; throws `UnauthorizedError` (401) for guests. */
74
+ user(): AuthUser {
75
+ if (!this.loaded)
76
+ throw new Error(
77
+ 'auth.user() before authentication: add the authenticate() middleware (routes/web.ts and routes/api.ts have it)',
78
+ )
79
+ if (!this.current) throw new UnauthorizedError()
80
+ return this.current
81
+ }
82
+
83
+ /** The user or null. */
84
+ userOrNull(): AuthUser | null {
85
+ return this.current
86
+ }
87
+
88
+ check(): boolean {
89
+ return this.current !== null
90
+ }
91
+
92
+ get id(): string | undefined {
93
+ return this.current ? idOf(this.current) : undefined
94
+ }
95
+
96
+ /** Sign a user in: new session id (no fixation), new CSRF token. */
97
+ async login(user: AuthUser): Promise<void> {
98
+ if (!this.hasSession) throw new Error('auth.login() needs the session (web routes)')
99
+ this.ctx.session.regenerate()
100
+ this.ctx.session.forget('_token')
101
+ this.ctx.session.put(SESSION_KEY, idOf(user))
102
+ this.loaded = true
103
+ this.set(user, 'web')
104
+ }
105
+
106
+ /** Sign out: the session is emptied and gets a new id. */
107
+ async logout(): Promise<void> {
108
+ if (this.hasSession) this.ctx.session.invalidate()
109
+ this.set(null)
110
+ }
111
+
112
+ /**
113
+ * Check an email and password and sign in. Throttled per email and IP (429 when exceeded), constant-time
114
+ * whether or not the email exists, rehashes on login when the hashing parameters changed. Null on failure.
115
+ */
116
+ async attempt(email: string, password: string): Promise<AuthUser | null> {
117
+ const { config, hash } = this.deps
118
+ const limiter = this.ctx.resolve(RateLimiter)
119
+ const key = `login:${email.trim().toLowerCase()}|${this.ctx.request.ip() ?? ''}`
120
+ const hit = await limiter.hit(key, config.throttle ?? '5/min')
121
+ if (!hit.allowed) throw new TooManyRequestsError(hit.retryAfter)
122
+ const emailField = config.fields?.email ?? 'email'
123
+ const passwordField = config.fields?.password ?? 'passwordHash'
124
+ const users = await this.deps.users()
125
+ const user = await users.findBy({ [emailField]: email.trim().toLowerCase() })
126
+ const stored = user ? (field(user, passwordField) as string | null) : null
127
+ // verify against a real hash even when there is no user, so timing does not reveal which emails exist
128
+ const ok = await hash.verify(password, stored ?? (await dummyHash(hash)))
129
+ if (!user || !stored || !ok) {
130
+ this.ctx.log.warn('auth.failed', { email })
131
+ return null
132
+ }
133
+ await limiter.reset(key)
134
+ if (config.passwords?.rehashOnLogin !== false && hash.needsRehash(stored)) {
135
+ const update = (users as unknown as { update?: (id: unknown, v: object) => Promise<unknown> }).update
136
+ if (update) await update.call(users, field(user, 'id'), { [passwordField]: await hash.make(password) })
137
+ }
138
+ await this.login(user as AuthUser)
139
+ return user as AuthUser
140
+ }
141
+
142
+ /** May the user do this? Policies: `can(BookingPolicy, 'pay', booking)`; gates: `can('admin.access')`. Guests: false. */
143
+ async can<P extends object, A extends Abilities<P>>(
144
+ policy: PolicyClass<P>,
145
+ ability: A,
146
+ ...args: AbilityArgs<P, A>
147
+ ): Promise<boolean>
148
+ async can(gate: string, ...args: unknown[]): Promise<boolean>
149
+ async can(target: PolicyClass | string, ...rest: unknown[]): Promise<boolean> {
150
+ if (!this.current) return false
151
+ if (typeof target === 'string') return this.ctx.resolve(Gate).allows(this.current, target, rest)
152
+ const [ability, ...args] = rest as [string, ...unknown[]]
153
+ return checkPolicy(this.ctx.resolve(target as PolicyClass<object>), ability, this.current, args)
154
+ }
155
+
156
+ async cannot<P extends object, A extends Abilities<P>>(
157
+ policy: PolicyClass<P>,
158
+ ability: A,
159
+ ...args: AbilityArgs<P, A>
160
+ ): Promise<boolean>
161
+ async cannot(gate: string, ...args: unknown[]): Promise<boolean>
162
+ async cannot(target: PolicyClass | string, ...rest: unknown[]): Promise<boolean> {
163
+ return !(await (this.can as (t: unknown, ...r: unknown[]) => Promise<boolean>)(target, ...rest))
164
+ }
165
+
166
+ /** Like `can`, but throws: `UnauthorizedError` (401) for guests, `ForbiddenError` (403) otherwise. */
167
+ async authorize<P extends object, A extends Abilities<P>>(
168
+ policy: PolicyClass<P>,
169
+ ability: A,
170
+ ...args: AbilityArgs<P, A>
171
+ ): Promise<void>
172
+ async authorize(gate: string, ...args: unknown[]): Promise<void>
173
+ async authorize(target: PolicyClass | string, ...rest: unknown[]): Promise<void> {
174
+ if (!this.current) throw new UnauthorizedError()
175
+ if (!(await (this.can as (t: unknown, ...r: unknown[]) => Promise<boolean>)(target, ...rest)))
176
+ throw new ForbiddenError()
177
+ }
178
+
179
+ /** For API tokens: does the token allow `ability`? Session users always may (abilities scope tokens only). */
180
+ tokenCan(ability: string): boolean {
181
+ if (!this.current) return false
182
+ return this.guard !== 'token' || (this.token !== undefined && tokenCan(this.token, ability))
183
+ }
184
+ }
185
+
186
+ let dummy: Promise<string> | undefined
187
+ const dummyHash = (hash: Hash) => {
188
+ dummy ??= hash.make(crypto.randomUUID())
189
+ return dummy
190
+ }
package/src/config.ts ADDED
@@ -0,0 +1,39 @@
1
+ import type { Class } from '@cslug/core'
2
+
3
+ /** What auth needs from the users repository (a cslug `Repository` has both). */
4
+ export type UserSource = {
5
+ find(id: unknown): Promise<object | null>
6
+ findBy(where: Record<string, unknown>): Promise<object | null>
7
+ }
8
+
9
+ export type AuthConfig = {
10
+ /** The users repository class, or a lazy import of it (avoids import cycles from config files). */
11
+ users: Class<UserSource> | (() => Promise<Class<UserSource>>)
12
+ /** Field names on the user row. Default `email` and `passwordHash`. */
13
+ fields?: { email?: string; password?: string }
14
+ passwords?: {
15
+ algorithm?: 'argon2id' | 'argon2i' | 'argon2d' | 'bcrypt'
16
+ memoryCost?: number
17
+ timeCost?: number
18
+ cost?: number
19
+ rehashOnLogin?: boolean
20
+ }
21
+ magicLinks?: { lifetime?: string | number; singleUse?: boolean }
22
+ /** Rate limit for `attempt()`, per email + IP. Default `'5/min'`. */
23
+ throttle?: string
24
+ /** Where `auth()` sends guests on HTML requests: a route name or path. Default the `login` route, else `/login`. */
25
+ loginRoute?: string
26
+ /** Where `guest()` sends signed-in users. Default `/`. */
27
+ home?: string
28
+ }
29
+
30
+ export const isClass = (v: unknown): v is Class =>
31
+ typeof v === 'function' && /^class[\s{]/.test(Function.prototype.toString.call(v))
32
+
33
+ /** Field value from a user row, by name. */
34
+ export const field = (user: object, name: string): unknown => (user as Record<string, unknown>)[name]
35
+ export const idOf = (user: object): string => {
36
+ const id = field(user, 'id')
37
+ if (id === undefined || id === null) throw new Error('The user has no id')
38
+ return String(id)
39
+ }
package/src/hash.ts ADDED
@@ -0,0 +1,36 @@
1
+ import type { AuthConfig } from './config'
2
+
3
+ type Options = NonNullable<AuthConfig['passwords']>
4
+
5
+ /** Password hashing through `Bun.password` (argon2id by default). */
6
+ export class Hash {
7
+ constructor(private readonly options: Options = {}) {}
8
+
9
+ private params(): Parameters<typeof Bun.password.hash>[1] {
10
+ const algorithm = this.options.algorithm ?? 'argon2id'
11
+ if (algorithm === 'bcrypt') return { algorithm, cost: this.options.cost ?? 10 }
12
+ return { algorithm, memoryCost: this.options.memoryCost ?? 65536, timeCost: this.options.timeCost ?? 2 }
13
+ }
14
+
15
+ make(plain: string): Promise<string> {
16
+ return Bun.password.hash(plain, this.params())
17
+ }
18
+
19
+ /** Constant-time; false for a malformed hash instead of throwing. */
20
+ async verify(plain: string, hash: string | null | undefined): Promise<boolean> {
21
+ if (!hash) return false
22
+ try {
23
+ return await Bun.password.verify(plain, hash)
24
+ } catch {
25
+ return false
26
+ }
27
+ }
28
+
29
+ /** True when the hash was made with other parameters (verify, then store `make()` again). */
30
+ needsRehash(hash: string): boolean {
31
+ const p = this.params() as { algorithm: string; memoryCost?: number; timeCost?: number; cost?: number }
32
+ if (p.algorithm === 'bcrypt') return !hash.startsWith('$2') || Number(hash.split('$')[2]) !== p.cost
33
+ const m = /^\$(argon2id|argon2i|argon2d)\$v=\d+\$m=(\d+),t=(\d+)/.exec(hash)
34
+ return !m || m[1] !== p.algorithm || Number(m[2]) !== p.memoryCost || Number(m[3]) !== p.timeCost
35
+ }
36
+ }
package/src/index.ts ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @cslug/auth: session and token guards (`ctx.auth`), password hashing, magic links, API tokens, policies and
3
+ * gates, and the `auth()`, `guest()`, `ability()`, `can()` middleware.
4
+ */
5
+ import './types'
6
+
7
+ export { Auth, SESSION_KEY } from './auth'
8
+ export type { AuthConfig, UserSource } from './config'
9
+ export { Hash } from './hash'
10
+ export { isLocalPath, MagicLinkError, MagicLinks } from './magic-links'
11
+ export { ability, auth, authenticate, can, guest } from './middleware'
12
+ export { type Abilities, type AbilityArgs, Gate, Policy } from './policy'
13
+ export { AuthProvider } from './provider'
14
+ export { type AccessToken, Tokens, tokenCan } from './tokens'
@@ -0,0 +1,81 @@
1
+ import { createHmac, timingSafeEqual } from 'node:crypto'
2
+ import { AppError, type AuthUser, type Clock, type Lock, parseDuration } from '@cslug/core'
3
+ import { idOf, type UserSource } from './config'
4
+
5
+ export class MagicLinkError extends AppError {
6
+ constructor(reason: 'invalid' | 'expired' | 'used') {
7
+ super(
8
+ `auth.magic_link_${reason}`,
9
+ reason === 'expired'
10
+ ? 'This sign-in link has expired. Ask for a new one.'
11
+ : reason === 'used'
12
+ ? 'This sign-in link was already used. Ask for a new one.'
13
+ : 'This sign-in link is not valid.',
14
+ { status: 400 },
15
+ )
16
+ }
17
+ }
18
+
19
+ type Payload = { u: string; r?: string; e: number; n: string }
20
+ const b64 = (s: string) => Buffer.from(s).toString('base64url')
21
+
22
+ /**
23
+ * Passwordless sign-in links. The token is signed with APP_KEY and carries the user, the redirect and the
24
+ * expiry; "single use" is an atomic `Lock` on its nonce (Redis with @cslug/redis), so no table is needed.
25
+ */
26
+ export class MagicLinks {
27
+ constructor(
28
+ private readonly key: string,
29
+ private readonly users: () => Promise<UserSource>,
30
+ private readonly lock: Lock,
31
+ private readonly clock: Clock,
32
+ private readonly options: { lifetime?: string | number; singleUse?: boolean } = {},
33
+ ) {
34
+ if (!key) throw new Error('Magic links need APP_KEY (config app.key)')
35
+ }
36
+
37
+ private sign = (data: string) => createHmac('sha256', this.key).update(`magic:${data}`).digest('base64url')
38
+
39
+ /** A token for the user. `redirect` must be a path on this site (`/bookings`). Put it in a URL with `route()`. */
40
+ create(
41
+ user: AuthUser,
42
+ options: { redirect?: string; lifetime?: string | number } = {},
43
+ ): { token: string; expiresAt: Date } {
44
+ if (options.redirect !== undefined && !isLocalPath(options.redirect))
45
+ throw new Error(`Magic link redirect must be a local path, got "${options.redirect}"`)
46
+ const expires = this.clock.now().getTime() + parseDuration(options.lifetime ?? this.options.lifetime ?? '30m')
47
+ const payload: Payload = {
48
+ u: idOf(user),
49
+ e: expires,
50
+ n: crypto.randomUUID(),
51
+ ...(options.redirect ? { r: options.redirect } : {}),
52
+ }
53
+ const data = b64(JSON.stringify(payload))
54
+ return { token: `${data}.${this.sign(data)}`, expiresAt: new Date(expires) }
55
+ }
56
+
57
+ /** The user and where to send them; throws `MagicLinkError` if the token is invalid, expired or used. */
58
+ async consume(token: string): Promise<{ user: AuthUser; redirectTo: string }> {
59
+ const [data, signature] = String(token).split('.')
60
+ if (!data || !signature) throw new MagicLinkError('invalid')
61
+ const a = Buffer.from(signature)
62
+ const b = Buffer.from(this.sign(data))
63
+ if (a.length !== b.length || !timingSafeEqual(a, b)) throw new MagicLinkError('invalid')
64
+ let payload: Payload
65
+ try {
66
+ payload = JSON.parse(Buffer.from(data, 'base64url').toString())
67
+ } catch {
68
+ throw new MagicLinkError('invalid')
69
+ }
70
+ const left = payload.e - this.clock.now().getTime()
71
+ if (left <= 0) throw new MagicLinkError('expired')
72
+ if (this.options.singleUse !== false && !(await this.lock.acquire(`magic-link:${payload.n}`, left)))
73
+ throw new MagicLinkError('used')
74
+ const user = await (await this.users()).find(payload.u)
75
+ if (!user) throw new MagicLinkError('invalid')
76
+ return { user: user as AuthUser, redirectTo: payload.r && isLocalPath(payload.r) ? payload.r : '/' }
77
+ }
78
+ }
79
+
80
+ /** `/bookings?x=1` yes; `//evil.com`, `https://…`, `/\evil` no. */
81
+ export const isLocalPath = (p: string) => p.startsWith('/') && !p.startsWith('//') && !p.startsWith('/\\')
@@ -0,0 +1,76 @@
1
+ import { ForbiddenError, UnauthorizedError } from '@cslug/core'
2
+ import { type HttpContext, type MiddlewareFn, Router, redirect, route } from '@cslug/http'
3
+ import { Auth, type AuthDeps } from './auth'
4
+ import type { AuthConfig } from './config'
5
+
6
+ /** Deps for `Auth`, registered by `AuthProvider`. */
7
+ export const AUTH_DEPS = Symbol.for('cslug.auth.deps')
8
+
9
+ async function ensureAuth(ctx: HttpContext): Promise<Auth> {
10
+ const existing = (ctx as { auth?: Auth }).auth
11
+ if (existing?.loaded) return existing
12
+ const deps = (ctx.app as unknown as Record<symbol, AuthDeps | undefined>)[AUTH_DEPS]
13
+ if (!deps) throw new Error('Auth middleware needs AuthProvider in bootstrap/providers.ts')
14
+ const auth = new Auth(ctx, deps)
15
+ ;(ctx as { auth?: Auth }).auth = auth
16
+ await auth.load()
17
+ return auth
18
+ }
19
+
20
+ /** Load the user (session or Bearer token) into `ctx.auth` / `ctx.user`. In the web and api groups. */
21
+ export const authenticate = (): MiddlewareFn => async (ctx, next) => {
22
+ await ensureAuth(ctx)
23
+ return next()
24
+ }
25
+
26
+ /**
27
+ * Require a signed-in user (optionally through one guard: `auth('token')`). Guests get 401 (JSON), or are sent
28
+ * to the login page with the URL remembered for `redirect().intended()` (HTML).
29
+ */
30
+ export const auth =
31
+ (guard?: 'web' | 'token'): MiddlewareFn =>
32
+ async (ctx, next) => {
33
+ const a = await ensureAuth(ctx)
34
+ if (a.check() && (!guard || a.guard === guard)) return next()
35
+ if (ctx.request.wantsJson() || guard === 'token' || ctx.session.constructor.name === 'MissingSession')
36
+ throw new UnauthorizedError()
37
+ if (ctx.request.method === 'GET') {
38
+ const url = new URL(ctx.request.url)
39
+ ctx.session.put('url.intended', url.pathname + url.search)
40
+ }
41
+ return redirect().to(loginUrl(ctx)).toResponse(ctx)
42
+ }
43
+
44
+ /** Only for guests (login and register pages): signed-in users go to `config('auth.home')`. */
45
+ export const guest = (): MiddlewareFn => async (ctx, next) => {
46
+ const a = await ensureAuth(ctx)
47
+ if (!a.check()) return next()
48
+ return redirect()
49
+ .to(ctx.app.config<string | undefined>('auth.home') ?? '/')
50
+ .toResponse(ctx)
51
+ }
52
+
53
+ /** API token abilities: `ability('quotes:write')`. Session users pass; tokens need every listed ability. */
54
+ export const ability =
55
+ (...abilities: string[]): MiddlewareFn =>
56
+ async (ctx, next) => {
57
+ const a = await ensureAuth(ctx)
58
+ if (!a.check()) throw new UnauthorizedError()
59
+ if (!abilities.every((x) => a.tokenCan(x)))
60
+ throw new ForbiddenError('auth.token_ability', `This token lacks the ability: ${abilities.join(', ')}`)
61
+ return next()
62
+ }
63
+
64
+ /** A gate as middleware: `can('admin.access')`. */
65
+ export const can =
66
+ (gate: string): MiddlewareFn =>
67
+ async (ctx, next) => {
68
+ await (await ensureAuth(ctx)).authorize(gate)
69
+ return next()
70
+ }
71
+
72
+ function loginUrl(ctx: HttpContext): string {
73
+ const target = ctx.app.config<AuthConfig['loginRoute']>('auth.loginRoute') ?? 'login'
74
+ if (target.startsWith('/')) return target
75
+ return ctx.resolve(Router).byName(target) ? route(target) : '/login'
76
+ }
package/src/policy.ts ADDED
@@ -0,0 +1,51 @@
1
+ import type { AuthUser, Class } from '@cslug/core'
2
+
3
+ /**
4
+ * Base of policies: one `@inject()` class per resource whose methods `(user, resource, …) => boolean`. An
5
+ * optional `before(user)` runs first; returning true/false decides, undefined continues. (Not declared here,
6
+ * so no `override` is needed.)
7
+ */
8
+ export abstract class Policy {}
9
+
10
+ type Fn = (user: never, ...args: never[]) => unknown
11
+ /** The ability names of a policy: its methods, except `before`. */
12
+ export type Abilities<P> = Exclude<{ [K in keyof P]: P[K] extends Fn ? K : never }[keyof P], 'before' | 'constructor'> &
13
+ string
14
+ /** The arguments of an ability after the user. */
15
+ export type AbilityArgs<P, A extends keyof P> = P[A] extends (user: never, ...args: infer R) => unknown ? R : never
16
+
17
+ type GateFn = (user: AuthUser, ...args: never[]) => boolean | Promise<boolean>
18
+
19
+ /** Abilities without a resource: `gate.define('admin.access', (user) => user.role === 'admin')`. */
20
+ export class Gate {
21
+ private readonly abilities = new Map<string, GateFn>()
22
+
23
+ define(name: string, check: (user: AuthUser, ...args: never[]) => boolean | Promise<boolean>): this {
24
+ this.abilities.set(name, check)
25
+ return this
26
+ }
27
+
28
+ has(name: string): boolean {
29
+ return this.abilities.has(name)
30
+ }
31
+
32
+ async allows(user: AuthUser, name: string, args: unknown[]): Promise<boolean> {
33
+ const check = this.abilities.get(name)
34
+ if (!check) throw new Error(`No gate named "${name}" (define it with gate.define in a provider's boot())`)
35
+ return (await (check as (u: AuthUser, ...a: unknown[]) => boolean | Promise<boolean>)(user, ...args)) === true
36
+ }
37
+ }
38
+
39
+ /** Run a policy ability for a user: `before`, then the method. Only `true` allows. */
40
+ export async function checkPolicy(policy: object, ability: string, user: AuthUser, args: unknown[]): Promise<boolean> {
41
+ const p = policy as Record<string, (...a: unknown[]) => unknown>
42
+ if (typeof p.before === 'function') {
43
+ const decided = await p.before.call(policy, user, ability, ...args)
44
+ if (decided === true || decided === false) return decided
45
+ }
46
+ const method = p[ability]
47
+ if (typeof method !== 'function') throw new Error(`${policy.constructor.name} has no ability "${ability}"`)
48
+ return (await method.call(policy, user, ...args)) === true
49
+ }
50
+
51
+ export type PolicyClass<P = object> = Class<P>
@@ -0,0 +1,55 @@
1
+ import { join } from 'node:path'
2
+ import { Clock, CslugError, Lock, ServiceProvider, token } from '@cslug/core'
3
+ import { addMigrations } from '@cslug/database'
4
+ import { API_MIDDLEWARE, type MiddlewareFn, WEB_MIDDLEWARE } from '@cslug/http'
5
+ import type { AuthDeps } from './auth'
6
+ import { type AuthConfig, isClass, type UserSource } from './config'
7
+ import { Hash } from './hash'
8
+ import { MagicLinks } from './magic-links'
9
+ import { AUTH_DEPS, authenticate } from './middleware'
10
+ import { Gate } from './policy'
11
+ import { Tokens } from './tokens'
12
+
13
+ const AUTHENTICATE = token<MiddlewareFn>('auth.authenticate')
14
+
15
+ /**
16
+ * Binds `Hash`, `Gate`, `Tokens` and `MagicLinks`, adds `authenticate()` to the web and api groups, and the
17
+ * access-tokens migration. Config: `config/auth.ts`.
18
+ */
19
+ export class AuthProvider extends ServiceProvider {
20
+ register() {
21
+ const configured = this.app.config<AuthConfig | undefined>('auth')
22
+ if (!configured?.users)
23
+ throw new CslugError('auth.no_users', 'config/auth.ts must set `users` (your users repository)')
24
+ const config: AuthConfig = configured
25
+ addMigrations(join(import.meta.dir, '../migrations'))
26
+
27
+ let source: Promise<UserSource> | undefined
28
+ const users = () => {
29
+ source ??= (async () => {
30
+ const Repo = isClass(config.users) ? config.users : await (config.users as () => Promise<typeof config.users>)()
31
+ return this.app.resolve(Repo as never) as UserSource
32
+ })()
33
+ return source
34
+ }
35
+ this.app.singleton(Hash, () => new Hash(config.passwords))
36
+ this.app.singleton(Gate, () => new Gate())
37
+ this.app.singleton(
38
+ MagicLinks,
39
+ (c) =>
40
+ new MagicLinks(
41
+ this.app.config<string>('app.key') ?? '',
42
+ users,
43
+ c.resolve(Lock),
44
+ c.resolve(Clock),
45
+ config.magicLinks,
46
+ ),
47
+ )
48
+ this.app.instance(AUTHENTICATE, authenticate())
49
+ this.app.tag([AUTHENTICATE], WEB_MIDDLEWARE)
50
+ this.app.tag([AUTHENTICATE], API_MIDDLEWARE)
51
+ const deps: AuthDeps = { config, users, hash: undefined as unknown as Hash, tokens: () => this.app.resolve(Tokens) }
52
+ Object.defineProperty(deps, 'hash', { get: () => this.app.resolve(Hash) })
53
+ ;(this.app as unknown as Record<symbol, AuthDeps>)[AUTH_DEPS] = deps
54
+ }
55
+ }
package/src/tokens.ts ADDED
@@ -0,0 +1,86 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto'
2
+ import { type AuthUser, Clock, inject, parseDuration } from '@cslug/core'
3
+ import { Database, sql } from '@cslug/database'
4
+ import { idOf } from './config'
5
+
6
+ export type AccessToken = {
7
+ id: string
8
+ userId: string
9
+ name: string
10
+ abilities: string[]
11
+ lastUsedAt: Date | null
12
+ expiresAt: Date | null
13
+ createdAt: Date
14
+ }
15
+
16
+ const sha256 = (s: string) => createHash('sha256').update(s).digest('hex')
17
+ const secret = () => Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('base64url')
18
+
19
+ /**
20
+ * Opaque API tokens: `<id>.<secret>`, only the SHA-256 of the secret is stored (`cslug_access_tokens`).
21
+ * Scoped by abilities (`['quotes:write']`, `'*'` for all) and optionally expiring.
22
+ */
23
+ @inject(Database, Clock)
24
+ export class Tokens {
25
+ constructor(
26
+ private readonly db: Database,
27
+ private readonly clock: Clock,
28
+ ) {}
29
+
30
+ /** The plain text is returned once; show it to the user then, it cannot be recovered. */
31
+ async create(
32
+ user: AuthUser,
33
+ options: { name: string; abilities?: string[]; expiresIn?: string | number },
34
+ ): Promise<{ plainText: string; token: AccessToken }> {
35
+ const id = Bun.randomUUIDv7()
36
+ const plain = secret()
37
+ const expires =
38
+ options.expiresIn === undefined ? null : new Date(this.clock.now().getTime() + parseDuration(options.expiresIn))
39
+ const row =
40
+ await this.db.one<AccessToken>(sql`insert into cslug_access_tokens (id, user_id, name, token_hash, abilities, expires_at)
41
+ values (${id}, ${idOf(user)}, ${options.name}, ${sha256(plain)}, ${sql.json(options.abilities ?? ['*'])}, ${expires}) returning *`)
42
+ return { plainText: `${id}.${plain}`, token: clean(row) }
43
+ }
44
+
45
+ /** The token for a plain text, if valid and not expired (and marks it used, at most once a minute). */
46
+ async verify(plainText: string): Promise<AccessToken | null> {
47
+ const [id, plain] = plainText.split('.')
48
+ if (!id || !plain || !/^[0-9a-f-]{36}$/.test(id)) return null
49
+ const row = await this.db.maybeOne<AccessToken & { tokenHash: string }>(
50
+ sql`select * from cslug_access_tokens where id = ${id}`,
51
+ )
52
+ if (!row) return null
53
+ const a = Buffer.from(sha256(plain))
54
+ const b = Buffer.from(row.tokenHash)
55
+ if (a.length !== b.length || !timingSafeEqual(a, b)) return null
56
+ const now = this.clock.now()
57
+ if (row.expiresAt && row.expiresAt <= now) return null
58
+ if (!row.lastUsedAt || now.getTime() - row.lastUsedAt.getTime() > 60_000) {
59
+ await this.db.exec(sql`update cslug_access_tokens set last_used_at = ${now} where id = ${id}`)
60
+ }
61
+ return clean(row)
62
+ }
63
+
64
+ list(user: AuthUser): Promise<AccessToken[]> {
65
+ return this.db
66
+ .many<AccessToken>(sql`select * from cslug_access_tokens where user_id = ${idOf(user)} order by created_at desc`)
67
+ .then((rows) => rows.map(clean))
68
+ }
69
+
70
+ async revoke(id: string): Promise<void> {
71
+ await this.db.exec(sql`delete from cslug_access_tokens where id = ${id}`)
72
+ }
73
+
74
+ async revokeAll(user: AuthUser): Promise<void> {
75
+ await this.db.exec(sql`delete from cslug_access_tokens where user_id = ${idOf(user)}`)
76
+ }
77
+ }
78
+
79
+ const clean = (row: AccessToken & { tokenHash?: string }): AccessToken => {
80
+ const { tokenHash: _hash, ...rest } = row
81
+ return rest
82
+ }
83
+
84
+ /** Does a token allow an ability? `*` allows everything; `quotes:*` allows `quotes:write`. */
85
+ export const tokenCan = (token: AccessToken, ability: string): boolean =>
86
+ token.abilities.some((a) => a === '*' || a === ability || (a.endsWith(':*') && ability.startsWith(a.slice(0, -1))))
package/src/types.ts ADDED
@@ -0,0 +1,11 @@
1
+ import type { AuthUser } from '@cslug/core'
2
+ import type { Auth } from './auth'
3
+
4
+ declare module '@cslug/http' {
5
+ interface HttpContext {
6
+ /** Who is making the request (loaded by `authenticate()`, in the web and api groups). */
7
+ auth: Auth
8
+ /** The signed-in user, or null. */
9
+ user: AuthUser | null
10
+ }
11
+ }