@cslug/auth 0.0.0-stage → 0.2.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 +6 -2
- package/docs/README.md +17 -0
- package/docs/api.md +18 -0
- package/migrations/00000000_000100_cslug_access_tokens.sql +15 -0
- package/package.json +38 -4
- package/src/auth.ts +190 -0
- package/src/config.ts +43 -0
- package/src/hash.ts +36 -0
- package/src/index.ts +14 -0
- package/src/magic-links.ts +81 -0
- package/src/middleware.ts +74 -0
- package/src/policy.ts +64 -0
- package/src/provider.ts +62 -0
- package/src/tokens.ts +86 -0
- package/src/types.ts +11 -0
package/README.md
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @cslug/auth
|
|
2
2
|
|
|
3
|
-
|
|
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,18 @@
|
|
|
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
|
+
| `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) |
|
|
12
|
+
| `Tokens` | `create(user, { name, abilities?, expiresIn? })` → `{ plainText, token }`, `verify`, `list`, `revoke`, `revokeAll` |
|
|
13
|
+
| `MagicLinks` | `create(user, { redirect?, lifetime? })` → `{ token, expiresAt }`; `consume(token)` → `{ user, redirectTo }` or `MagicLinkError` (400: invalid, expired, used) |
|
|
14
|
+
| Middleware | `authenticate()`, `auth(guard?)`, `guest()`, `ability(...)`, `can(gate)` |
|
|
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) |
|
|
17
|
+
|
|
18
|
+
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.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.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.2.0",
|
|
33
|
+
"@cslug/http": "0.2.0",
|
|
34
|
+
"@cslug/database": "0.2.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.available
|
|
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.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 } = this.deps
|
|
118
|
+
const hash = this.deps.hash()
|
|
119
|
+
const limiter = this.ctx.resolve(RateLimiter)
|
|
120
|
+
const key = `login:${email.trim().toLowerCase()}|${this.ctx.request.ip() ?? ''}`
|
|
121
|
+
const hit = await limiter.hit(key, config.throttle ?? '5/min')
|
|
122
|
+
if (!hit.allowed) throw new TooManyRequestsError(hit.retryAfter)
|
|
123
|
+
const emailField = config.fields?.email ?? 'email'
|
|
124
|
+
const passwordField = config.fields?.password ?? 'passwordHash'
|
|
125
|
+
const users = await this.deps.users()
|
|
126
|
+
const user = await users.findBy({ [emailField]: email.trim().toLowerCase() })
|
|
127
|
+
const stored = user ? (field(user, passwordField) as string | null) : null
|
|
128
|
+
// verify against a real hash even when there is no user, so timing does not reveal which emails exist
|
|
129
|
+
const ok = await hash.verify(password, stored ?? (await dummyHash(hash)))
|
|
130
|
+
if (!user || !stored || !ok) {
|
|
131
|
+
this.ctx.log.warn('auth.failed', { email })
|
|
132
|
+
return null
|
|
133
|
+
}
|
|
134
|
+
await limiter.reset(key)
|
|
135
|
+
if (config.passwords?.rehashOnLogin !== false && hash.needsRehash(stored)) {
|
|
136
|
+
await users.update?.(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,43 @@
|
|
|
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
|
+
/** Used to store a rehashed password on login; without it the old hash stays. */
|
|
8
|
+
update?(id: unknown, values: object): Promise<unknown>
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export type AuthConfig = {
|
|
12
|
+
/** The users repository class, or a lazy import of it (avoids import cycles from config files). */
|
|
13
|
+
users: Class<UserSource> | (() => Promise<Class<UserSource>>)
|
|
14
|
+
/** Field names on the user row. Default `email` and `passwordHash`. */
|
|
15
|
+
fields?: { email?: string; password?: string }
|
|
16
|
+
passwords?: {
|
|
17
|
+
algorithm?: 'argon2id' | 'argon2i' | 'argon2d' | 'bcrypt'
|
|
18
|
+
memoryCost?: number
|
|
19
|
+
timeCost?: number
|
|
20
|
+
cost?: number
|
|
21
|
+
rehashOnLogin?: boolean
|
|
22
|
+
}
|
|
23
|
+
magicLinks?: { lifetime?: string | number; singleUse?: boolean }
|
|
24
|
+
/** Rate limit for `attempt()`, per email + IP. Default `'5/min'`. */
|
|
25
|
+
throttle?: string
|
|
26
|
+
/** Where `auth()` sends guests on HTML requests: a route name or path. Default the `login` route, else `/login`. */
|
|
27
|
+
loginRoute?: string
|
|
28
|
+
/** Where `guest()` sends signed-in users. Default `/`. */
|
|
29
|
+
home?: string
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** True for a `class` (not a lazy-import function): `config.users` accepts both. */
|
|
33
|
+
export const isClass = (v: unknown): v is Class =>
|
|
34
|
+
typeof v === 'function' && /^class[\s{]/.test(Function.prototype.toString.call(v))
|
|
35
|
+
|
|
36
|
+
/** Field value from a user row, by name. */
|
|
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. */
|
|
39
|
+
export const idOf = (user: object): string => {
|
|
40
|
+
const id = field(user, 'id')
|
|
41
|
+
if (id === undefined || id === null) throw new Error('The user has no id')
|
|
42
|
+
return String(id)
|
|
43
|
+
}
|
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, gate, Policy } from './policy'
|
|
13
|
+
export { AuthProvider, userSource } 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,74 @@
|
|
|
1
|
+
import { ForbiddenError, token, 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 = token<AuthDeps>('cslug.auth.deps')
|
|
8
|
+
|
|
9
|
+
async function ensureAuth(ctx: HttpContext): Promise<Auth> {
|
|
10
|
+
const existing = ctx.auth as Auth | undefined // unset until this middleware runs
|
|
11
|
+
if (existing?.loaded) return existing
|
|
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
|
|
15
|
+
await auth.load()
|
|
16
|
+
return auth
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Load the user (session or Bearer token) into `ctx.auth` / `ctx.user`. In the web and api groups. */
|
|
20
|
+
export const authenticate = (): MiddlewareFn => async (ctx, next) => {
|
|
21
|
+
await ensureAuth(ctx)
|
|
22
|
+
return next()
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Require a signed-in user (optionally through one guard: `auth('token')`). Guests get 401 (JSON), or are sent
|
|
27
|
+
* to the login page with the URL remembered for `redirect().intended()` (HTML).
|
|
28
|
+
*/
|
|
29
|
+
export const auth =
|
|
30
|
+
(guard?: 'web' | 'token'): MiddlewareFn =>
|
|
31
|
+
async (ctx, next) => {
|
|
32
|
+
const a = await ensureAuth(ctx)
|
|
33
|
+
if (a.check() && (!guard || a.guard === guard)) return next()
|
|
34
|
+
if (ctx.request.wantsJson() || guard === 'token' || !ctx.session.available) throw new UnauthorizedError()
|
|
35
|
+
if (ctx.request.method === 'GET') {
|
|
36
|
+
const url = new URL(ctx.request.url)
|
|
37
|
+
ctx.session.put('url.intended', url.pathname + url.search)
|
|
38
|
+
}
|
|
39
|
+
return redirect().to(loginUrl(ctx)).toResponse(ctx)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Only for guests (login and register pages): signed-in users go to `config('auth.home')`. */
|
|
43
|
+
export const guest = (): MiddlewareFn => async (ctx, next) => {
|
|
44
|
+
const a = await ensureAuth(ctx)
|
|
45
|
+
if (!a.check()) return next()
|
|
46
|
+
return redirect()
|
|
47
|
+
.to(ctx.app.config<string | undefined>('auth.home') ?? '/')
|
|
48
|
+
.toResponse(ctx)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** API token abilities: `ability('quotes:write')`. Session users pass; tokens need every listed ability. */
|
|
52
|
+
export const ability =
|
|
53
|
+
(...abilities: string[]): MiddlewareFn =>
|
|
54
|
+
async (ctx, next) => {
|
|
55
|
+
const a = await ensureAuth(ctx)
|
|
56
|
+
if (!a.check()) throw new UnauthorizedError()
|
|
57
|
+
if (!abilities.every((x) => a.tokenCan(x)))
|
|
58
|
+
throw new ForbiddenError('auth.token_ability', `This token lacks the ability: ${abilities.join(', ')}`)
|
|
59
|
+
return next()
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** A gate as middleware: `can('admin.access')`. */
|
|
63
|
+
export const can =
|
|
64
|
+
(gate: string): MiddlewareFn =>
|
|
65
|
+
async (ctx, next) => {
|
|
66
|
+
await (await ensureAuth(ctx)).authorize(gate)
|
|
67
|
+
return next()
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function loginUrl(ctx: HttpContext): string {
|
|
71
|
+
const target = ctx.app.config<AuthConfig['loginRoute']>('auth.loginRoute') ?? 'login'
|
|
72
|
+
if (target.startsWith('/')) return target
|
|
73
|
+
return ctx.resolve(Router).byName(target) ? route(target) : '/login'
|
|
74
|
+
}
|
package/src/policy.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { type AuthUser, type Class, resolve } 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
|
+
/**
|
|
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
|
+
|
|
52
|
+
/** Run a policy ability for a user: `before`, then the method. Only `true` allows. */
|
|
53
|
+
export async function checkPolicy(policy: object, ability: string, user: AuthUser, args: unknown[]): Promise<boolean> {
|
|
54
|
+
const p = policy as Record<string, (...a: unknown[]) => unknown>
|
|
55
|
+
if (typeof p.before === 'function') {
|
|
56
|
+
const decided = await p.before.call(policy, user, ability, ...args)
|
|
57
|
+
if (decided === true || decided === false) return decided
|
|
58
|
+
}
|
|
59
|
+
const method = p[ability]
|
|
60
|
+
if (typeof method !== 'function') throw new Error(`${policy.constructor.name} has no ability "${ability}"`)
|
|
61
|
+
return (await method.call(policy, user, ...args)) === true
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export type PolicyClass<P = object> = Class<P>
|
package/src/provider.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { join } from 'node:path'
|
|
2
|
+
import { type Application, 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 AuthConfig, isClass, type UserSource } from './config'
|
|
6
|
+
import { Hash } from './hash'
|
|
7
|
+
import { MagicLinks } from './magic-links'
|
|
8
|
+
import { AUTH_DEPS, authenticate } from './middleware'
|
|
9
|
+
import { Gate } from './policy'
|
|
10
|
+
import { Tokens } from './tokens'
|
|
11
|
+
|
|
12
|
+
const AUTHENTICATE = token<MiddlewareFn>('auth.authenticate')
|
|
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
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Binds `Hash`, `Gate`, `Tokens` and `MagicLinks`, adds `authenticate()` to the web and api groups, and the
|
|
24
|
+
* access-tokens migration. Config: `config/auth.ts`.
|
|
25
|
+
*/
|
|
26
|
+
export class AuthProvider extends ServiceProvider {
|
|
27
|
+
register() {
|
|
28
|
+
const configured = this.app.config<AuthConfig | undefined>('auth')
|
|
29
|
+
if (!configured?.users)
|
|
30
|
+
throw new CslugError('auth.no_users', 'config/auth.ts must set `users` (your users repository)')
|
|
31
|
+
const config: AuthConfig = configured
|
|
32
|
+
addMigrations(join(import.meta.dir, '../migrations'))
|
|
33
|
+
|
|
34
|
+
let source: Promise<UserSource> | undefined
|
|
35
|
+
const users = () => {
|
|
36
|
+
source ??= userSource(this.app)
|
|
37
|
+
return source
|
|
38
|
+
}
|
|
39
|
+
this.app.singleton(Hash, () => new Hash(config.passwords))
|
|
40
|
+
this.app.singleton(Gate, () => new Gate())
|
|
41
|
+
this.app.singleton(
|
|
42
|
+
MagicLinks,
|
|
43
|
+
(c) =>
|
|
44
|
+
new MagicLinks(
|
|
45
|
+
this.app.config<string>('app.key') ?? '',
|
|
46
|
+
users,
|
|
47
|
+
c.resolve(Lock),
|
|
48
|
+
c.resolve(Clock),
|
|
49
|
+
config.magicLinks,
|
|
50
|
+
),
|
|
51
|
+
)
|
|
52
|
+
this.app.instance(AUTHENTICATE, authenticate())
|
|
53
|
+
this.app.tag([AUTHENTICATE], WEB_MIDDLEWARE)
|
|
54
|
+
this.app.tag([AUTHENTICATE], API_MIDDLEWARE)
|
|
55
|
+
this.app.instance(AUTH_DEPS, {
|
|
56
|
+
config,
|
|
57
|
+
users,
|
|
58
|
+
hash: () => this.app.resolve(Hash),
|
|
59
|
+
tokens: () => this.app.resolve(Tokens),
|
|
60
|
+
})
|
|
61
|
+
}
|
|
62
|
+
}
|
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
|
+
}
|