@cslug/auth 0.1.0 → 0.3.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/docs/api.md CHANGED
@@ -7,9 +7,12 @@
7
7
  | `Hash` | `make`, `verify`, `needsRehash` (argon2id via `Bun.password`; bcrypt supported) |
8
8
  | `Policy` | Base class; methods `(user, ...args) => boolean`, optional `before(user)` |
9
9
  | `Gate` | `define(name, (user, ...args) => boolean)` in a provider's `boot()` |
10
+ | `gate` | Static shortcut for the current app's `Gate`: `gate.define(…)`, `gate.has(name)`, `gate.allows(user, name, ...args)` |
11
+ | `userSource(app)` | The users repository of `config/auth.ts` (used by the guards and by `t.auth` in tests) |
10
12
  | `Tokens` | `create(user, { name, abilities?, expiresIn? })` → `{ plainText, token }`, `verify`, `list`, `revoke`, `revokeAll` |
11
13
  | `MagicLinks` | `create(user, { redirect?, lifetime? })` → `{ token, expiresAt }`; `consume(token)` → `{ user, redirectTo }` or `MagicLinkError` (400: invalid, expired, used) |
12
14
  | Middleware | `authenticate()`, `auth(guard?)`, `guest()`, `ability(...)`, `can(gate)` |
13
15
  | `AuthProvider` | Config `auth`: `users`, `fields`, `passwords`, `magicLinks`, `throttle`, `loginRoute`, `home` |
16
+ | `UserSource` | What `users` must provide: `find(id)`, `findBy(where)`, and optionally `update(id, values)` (stores a rehashed password on login; a database repository has it) |
14
17
 
15
18
  Type the user once: `declare module '@cslug/core' { interface AuthUser extends User {} }`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cslug/auth",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Session and token guards, password hashing, magic links, policies and gates.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -29,9 +29,9 @@
29
29
  "bun": ">=1.3.14"
30
30
  },
31
31
  "peerDependencies": {
32
- "@cslug/core": "0.1.0",
33
- "@cslug/http": "0.1.0",
34
- "@cslug/database": "0.1.0"
32
+ "@cslug/core": "0.3.0",
33
+ "@cslug/http": "0.3.0",
34
+ "@cslug/database": "0.3.0"
35
35
  },
36
36
  "devDependencies": {
37
37
  "@cslug/testing": "workspace:*",
package/src/auth.ts CHANGED
@@ -18,7 +18,7 @@ export const SESSION_KEY = 'auth.id'
18
18
  export type AuthDeps = {
19
19
  config: AuthConfig
20
20
  users: () => Promise<UserSource>
21
- hash: Hash
21
+ hash: () => Hash
22
22
  tokens: () => Tokens
23
23
  }
24
24
 
@@ -40,7 +40,7 @@ export class Auth {
40
40
  ) {}
41
41
 
42
42
  private get hasSession(): boolean {
43
- return this.ctx.session.constructor.name !== 'MissingSession'
43
+ return this.ctx.session.available
44
44
  }
45
45
 
46
46
  /** Load the user from a Bearer token, else the session (called by `authenticate()`). */
@@ -67,7 +67,7 @@ export class Auth {
67
67
  this.token = token
68
68
  const store = currentContext()
69
69
  if (store) store.userId = user ? idOf(user) : undefined
70
- ;(this.ctx as unknown as { user: AuthUser | null }).user = user
70
+ this.ctx.user = user
71
71
  }
72
72
 
73
73
  /** The signed-in user; throws `UnauthorizedError` (401) for guests. */
@@ -114,7 +114,8 @@ export class Auth {
114
114
  * whether or not the email exists, rehashes on login when the hashing parameters changed. Null on failure.
115
115
  */
116
116
  async attempt(email: string, password: string): Promise<AuthUser | null> {
117
- const { config, hash } = this.deps
117
+ const { config } = this.deps
118
+ const hash = this.deps.hash()
118
119
  const limiter = this.ctx.resolve(RateLimiter)
119
120
  const key = `login:${email.trim().toLowerCase()}|${this.ctx.request.ip() ?? ''}`
120
121
  const hit = await limiter.hit(key, config.throttle ?? '5/min')
@@ -132,8 +133,7 @@ export class Auth {
132
133
  }
133
134
  await limiter.reset(key)
134
135
  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) })
136
+ await users.update?.(field(user, 'id'), { [passwordField]: await hash.make(password) })
137
137
  }
138
138
  await this.login(user as AuthUser)
139
139
  return user as AuthUser
package/src/config.ts CHANGED
@@ -4,6 +4,8 @@ import type { Class } from '@cslug/core'
4
4
  export type UserSource = {
5
5
  find(id: unknown): Promise<object | null>
6
6
  findBy(where: Record<string, unknown>): Promise<object | null>
7
+ /** Used to store a rehashed password on login; without it the old hash stays. */
8
+ update?(id: unknown, values: object): Promise<unknown>
7
9
  }
8
10
 
9
11
  export type AuthConfig = {
@@ -27,11 +29,13 @@ export type AuthConfig = {
27
29
  home?: string
28
30
  }
29
31
 
32
+ /** True for a `class` (not a lazy-import function): `config.users` accepts both. */
30
33
  export const isClass = (v: unknown): v is Class =>
31
34
  typeof v === 'function' && /^class[\s{]/.test(Function.prototype.toString.call(v))
32
35
 
33
36
  /** Field value from a user row, by name. */
34
37
  export const field = (user: object, name: string): unknown => (user as Record<string, unknown>)[name]
38
+ /** The user's `id` as a string; throws when the row has none. */
35
39
  export const idOf = (user: object): string => {
36
40
  const id = field(user, 'id')
37
41
  if (id === undefined || id === null) throw new Error('The user has no id')
package/src/index.ts CHANGED
@@ -9,6 +9,6 @@ export type { AuthConfig, UserSource } from './config'
9
9
  export { Hash } from './hash'
10
10
  export { isLocalPath, MagicLinkError, MagicLinks } from './magic-links'
11
11
  export { ability, auth, authenticate, can, guest } from './middleware'
12
- export { type Abilities, type AbilityArgs, Gate, Policy } from './policy'
13
- export { AuthProvider } from './provider'
12
+ export { type Abilities, type AbilityArgs, Gate, gate, Policy } from './policy'
13
+ export { AuthProvider, userSource } from './provider'
14
14
  export { type AccessToken, Tokens, tokenCan } from './tokens'
package/src/middleware.ts CHANGED
@@ -1,18 +1,17 @@
1
- import { ForbiddenError, UnauthorizedError } from '@cslug/core'
1
+ import { ForbiddenError, token, UnauthorizedError } from '@cslug/core'
2
2
  import { type HttpContext, type MiddlewareFn, Router, redirect, route } from '@cslug/http'
3
3
  import { Auth, type AuthDeps } from './auth'
4
4
  import type { AuthConfig } from './config'
5
5
 
6
6
  /** Deps for `Auth`, registered by `AuthProvider`. */
7
- export const AUTH_DEPS = Symbol.for('cslug.auth.deps')
7
+ export const AUTH_DEPS = token<AuthDeps>('cslug.auth.deps')
8
8
 
9
9
  async function ensureAuth(ctx: HttpContext): Promise<Auth> {
10
- const existing = (ctx as { auth?: Auth }).auth
10
+ const existing = ctx.auth as Auth | undefined // unset until this middleware runs
11
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
12
+ if (!ctx.app.has(AUTH_DEPS)) throw new Error('Auth middleware needs AuthProvider in bootstrap/providers.ts')
13
+ const auth = new Auth(ctx, ctx.app.resolve(AUTH_DEPS))
14
+ ctx.auth = auth
16
15
  await auth.load()
17
16
  return auth
18
17
  }
@@ -32,8 +31,7 @@ export const auth =
32
31
  async (ctx, next) => {
33
32
  const a = await ensureAuth(ctx)
34
33
  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()
34
+ if (ctx.request.wantsJson() || guard === 'token' || !ctx.session.available) throw new UnauthorizedError()
37
35
  if (ctx.request.method === 'GET') {
38
36
  const url = new URL(ctx.request.url)
39
37
  ctx.session.put('url.intended', url.pathname + url.search)
package/src/policy.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { AuthUser, Class } from '@cslug/core'
1
+ import { type AuthUser, type Class, resolve } from '@cslug/core'
2
2
 
3
3
  /**
4
4
  * Base of policies: one `@inject()` class per resource whose methods `(user, resource, …) => boolean`. An
@@ -36,6 +36,19 @@ export class Gate {
36
36
  }
37
37
  }
38
38
 
39
+ /**
40
+ * The current app's `Gate` (a static shortcut, D9): `gate.define('admin.access', (user) => user.role === 'admin')` in
41
+ * a provider's `boot()`. Same as `resolve(Gate).define(…)`.
42
+ */
43
+ export const gate = {
44
+ define(name: string, check: (user: AuthUser, ...args: never[]) => boolean | Promise<boolean>): Gate {
45
+ return resolve(Gate).define(name, check)
46
+ },
47
+ has: (name: string): boolean => resolve(Gate).has(name),
48
+ allows: (user: AuthUser, name: string, ...args: unknown[]): Promise<boolean> =>
49
+ resolve(Gate).allows(user, name, args),
50
+ }
51
+
39
52
  /** Run a policy ability for a user: `before`, then the method. Only `true` allows. */
40
53
  export async function checkPolicy(policy: object, ability: string, user: AuthUser, args: unknown[]): Promise<boolean> {
41
54
  const p = policy as Record<string, (...a: unknown[]) => unknown>
package/src/provider.ts CHANGED
@@ -1,8 +1,7 @@
1
1
  import { join } from 'node:path'
2
- import { Clock, CslugError, Lock, ServiceProvider, token } from '@cslug/core'
2
+ import { type Application, Clock, CslugError, Lock, ServiceProvider, token } from '@cslug/core'
3
3
  import { addMigrations } from '@cslug/database'
4
4
  import { API_MIDDLEWARE, type MiddlewareFn, WEB_MIDDLEWARE } from '@cslug/http'
5
- import type { AuthDeps } from './auth'
6
5
  import { type AuthConfig, isClass, type UserSource } from './config'
7
6
  import { Hash } from './hash'
8
7
  import { MagicLinks } from './magic-links'
@@ -12,6 +11,14 @@ import { Tokens } from './tokens'
12
11
 
13
12
  const AUTHENTICATE = token<MiddlewareFn>('auth.authenticate')
14
13
 
14
+ /** The users repository of `config/auth.ts` (`users`: a class, or a function importing it lazily). */
15
+ export async function userSource(app: Application): Promise<UserSource> {
16
+ const users = app.config<AuthConfig | undefined>('auth')?.users
17
+ if (!users) throw new CslugError('auth.no_users', 'config/auth.ts must set `users` (your users repository)')
18
+ const Repo = isClass(users) ? users : await (users as () => Promise<typeof users>)()
19
+ return app.resolve(Repo as never) as UserSource
20
+ }
21
+
15
22
  /**
16
23
  * Binds `Hash`, `Gate`, `Tokens` and `MagicLinks`, adds `authenticate()` to the web and api groups, and the
17
24
  * access-tokens migration. Config: `config/auth.ts`.
@@ -26,10 +33,7 @@ export class AuthProvider extends ServiceProvider {
26
33
 
27
34
  let source: Promise<UserSource> | undefined
28
35
  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
- })()
36
+ source ??= userSource(this.app)
33
37
  return source
34
38
  }
35
39
  this.app.singleton(Hash, () => new Hash(config.passwords))
@@ -48,8 +52,11 @@ export class AuthProvider extends ServiceProvider {
48
52
  this.app.instance(AUTHENTICATE, authenticate())
49
53
  this.app.tag([AUTHENTICATE], WEB_MIDDLEWARE)
50
54
  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
55
+ this.app.instance(AUTH_DEPS, {
56
+ config,
57
+ users,
58
+ hash: () => this.app.resolve(Hash),
59
+ tokens: () => this.app.resolve(Tokens),
60
+ })
54
61
  }
55
62
  }