@fabrika/auth-core 0.0.1
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/package.json +28 -0
- package/src/environment.ts +78 -0
- package/src/gates.ts +29 -0
- package/src/ids.ts +91 -0
- package/src/index.ts +9 -0
- package/src/json.ts +25 -0
- package/src/permissions.ts +108 -0
- package/src/rpc.ts +327 -0
- package/src/token.ts +253 -0
- package/src/types.ts +124 -0
- package/src/wire.ts +30 -0
package/package.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@fabrika/auth-core",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/contember/fabrika-platform.git",
|
|
8
|
+
"directory": "packages/auth-core"
|
|
9
|
+
},
|
|
10
|
+
"publishConfig": {
|
|
11
|
+
"access": "public"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"src",
|
|
15
|
+
"!src/**/__tests__/**"
|
|
16
|
+
],
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"bun": "./src/index.ts",
|
|
20
|
+
"types": "./src/index.ts",
|
|
21
|
+
"default": "./src/index.ts"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"typecheck": "tsc --noEmit",
|
|
26
|
+
"test": "bun test"
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The environment NAME, and the one rule that keeps it honest.
|
|
3
|
+
*
|
|
4
|
+
* `local` is not a label. It is the switch every Access-plane bypass is gated on — IAM's
|
|
5
|
+
* `localDevLogin` (`iam/src/services.ts`), its ephemeral signing key (`iam/src/signing.ts`) and its
|
|
6
|
+
* credential-less caller path (`iam/src/auth.ts`) all fire on exactly this string. A live installation
|
|
7
|
+
* carrying it is one added branch away from turning them on, which is what `fabrika-test` was measured
|
|
8
|
+
* doing on 2026-08-05 (backlog 59). So a composition that can SEE it is not local REFUSES the name,
|
|
9
|
+
* on the same reasoning as `readProxyEnv` and `buildOidc`: refusing to boot beats booting
|
|
10
|
+
* misconfigured.
|
|
11
|
+
*
|
|
12
|
+
* What "can see it" means is the whole design, and shared code does not go looking for a signal. The
|
|
13
|
+
* COMPOSITION ROOT states the fact, the way it names the client-address header
|
|
14
|
+
* (`iam/src/client-address.ts`), and the fact it states is the PUBLIC ORIGIN this service serves on.
|
|
15
|
+
* That value is the one thing here that cannot be wrong quietly: it is the `iss` of every minted
|
|
16
|
+
* token, the host a `__Host-` cookie belongs to, and the address a browser is sent back to. A service
|
|
17
|
+
* answering on a public name is not a laptop, whatever `ENVIRONMENT` says — and no local composition
|
|
18
|
+
* in this repository has one (`local-stack/compose.yaml` serves `*.fabrika.localhost`, the Cloudflare
|
|
19
|
+
* local build serves `http://localhost:18191`).
|
|
20
|
+
*
|
|
21
|
+
* Two non-answers are supported and are never a guess: naming NO origin means this composition cannot
|
|
22
|
+
* see its own public address, and an origin that is not a parseable absolute URL is not evidence
|
|
23
|
+
* either — a typo there already breaks sign-in, and turning it into a second, different failure buys
|
|
24
|
+
* nothing.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
/** The environment name every bypass is gated on. Compared literally; there is no other spelling. */
|
|
28
|
+
export const LOCAL_ENVIRONMENT = 'local'
|
|
29
|
+
|
|
30
|
+
export class EnvironmentNameError extends Error {
|
|
31
|
+
constructor(publicOrigin: string) {
|
|
32
|
+
super(
|
|
33
|
+
`ENVIRONMENT=${LOCAL_ENVIRONMENT} is refused: this service serves ${publicOrigin}, which is not a loopback address. `
|
|
34
|
+
+ 'Name the environment this installation actually is.',
|
|
35
|
+
)
|
|
36
|
+
this.name = 'EnvironmentNameError'
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Loopback per RFC 6761 §6.3 — `localhost` and every name under `.localhost` always resolve to the
|
|
42
|
+
* loopback interface — plus the literal loopback addresses. Deliberately nothing else: a LAN address
|
|
43
|
+
* or an internal DNS name is still a name another machine reaches this service at.
|
|
44
|
+
*/
|
|
45
|
+
export function isLoopbackHost(hostname: string): boolean {
|
|
46
|
+
const host = hostname.toLowerCase()
|
|
47
|
+
if (host === 'localhost' || host.endsWith('.localhost')) {
|
|
48
|
+
return true
|
|
49
|
+
}
|
|
50
|
+
// `URL.hostname` keeps the brackets on an IPv6 literal; accept both spellings.
|
|
51
|
+
if (host === '::1' || host === '[::1]') {
|
|
52
|
+
return true
|
|
53
|
+
}
|
|
54
|
+
return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Validate a composition's declared environment name against the public origin it serves on, and
|
|
59
|
+
* return the name. Throws `EnvironmentNameError` only for the one contradiction it can prove.
|
|
60
|
+
*
|
|
61
|
+
* @param declared the raw `ENVIRONMENT` value
|
|
62
|
+
* @param publicOrigin this composition's own public origin, or `undefined` when it has none to state
|
|
63
|
+
*/
|
|
64
|
+
export function readEnvironmentName(declared: string, publicOrigin: string | undefined): string {
|
|
65
|
+
if (declared !== LOCAL_ENVIRONMENT || publicOrigin === undefined || publicOrigin.trim() === '') {
|
|
66
|
+
return declared
|
|
67
|
+
}
|
|
68
|
+
let hostname: string
|
|
69
|
+
try {
|
|
70
|
+
hostname = new URL(publicOrigin).hostname
|
|
71
|
+
} catch {
|
|
72
|
+
return declared
|
|
73
|
+
}
|
|
74
|
+
if (hostname === '' || isLoopbackHost(hostname)) {
|
|
75
|
+
return declared
|
|
76
|
+
}
|
|
77
|
+
throw new EnvironmentNameError(publicOrigin)
|
|
78
|
+
}
|
package/src/gates.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { AppGates, GateRule } from './types'
|
|
2
|
+
|
|
3
|
+
/** A gate rule with its path glob precompiled. */
|
|
4
|
+
export interface CompiledGate {
|
|
5
|
+
readonly rule: GateRule
|
|
6
|
+
matches(pathname: string): boolean
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** Precompile an app's gate rules while preserving declaration order. */
|
|
10
|
+
export function compileGates(gates: AppGates): CompiledGate[] {
|
|
11
|
+
return gates.rules.map((rule) => {
|
|
12
|
+
const regex = globToRegExp(rule.path)
|
|
13
|
+
return { rule, matches: (pathname: string) => regex.test(pathname) }
|
|
14
|
+
})
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Return matching rules in declaration order. */
|
|
18
|
+
export function applicableGates(compiled: readonly CompiledGate[], pathname: string): CompiledGate[] {
|
|
19
|
+
return compiled.filter((gate) => gate.matches(pathname))
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Glob where `*` crosses path separators; all other characters are literal. */
|
|
23
|
+
function globToRegExp(pattern: string): RegExp {
|
|
24
|
+
return new RegExp(`^${pattern.split('*').map(escapeRegExp).join('.*')}$`)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function escapeRegExp(literal: string): string {
|
|
28
|
+
return literal.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
29
|
+
}
|
package/src/ids.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generate a UUIDv7 (RFC 9562): time-sortable, 128 bits, monotonic WITHIN a millisecond as well as
|
|
3
|
+
* across one — `audit_events` is listed `ORDER BY id DESC` with an `id < ?` keyset cursor, and a
|
|
4
|
+
* request that writes two audit rows writes them inside the same millisecond routinely.
|
|
5
|
+
*
|
|
6
|
+
* Layout, with §6.2's "fixed bit-length dedicated counter" monotonic variant:
|
|
7
|
+
* - bytes 0..5 : 48-bit big-endian Unix-millis timestamp
|
|
8
|
+
* - byte 6 : version nibble `7` in the high 4 bits, the high 4 bits of a 12-bit counter below
|
|
9
|
+
* - byte 7 : the low 8 bits of that counter (bytes 6..7 low bits are `rand_a`)
|
|
10
|
+
* - byte 8 : RFC 4122 variant bits `10` in the high 2 bits, random in the low 6
|
|
11
|
+
* - bytes 9..15 : random (`crypto.getRandomValues`)
|
|
12
|
+
*
|
|
13
|
+
* That leaves **62 random bits per id** — down from the 74 of the unguarded Method 0 this used to be
|
|
14
|
+
* — plus 8 fresh random bits seeding the counter at each new millisecond.
|
|
15
|
+
*
|
|
16
|
+
* The counter is re-seeded from 8 random bits (the top 4 left zero, the RFC's rollover guard, so at
|
|
17
|
+
* least 3840 ids per millisecond are guaranteed) whenever the millisecond advances, and incremented
|
|
18
|
+
* otherwise. Because the timestamp occupies the most-significant bytes and the counter the bytes
|
|
19
|
+
* right after it, ids sort lexicographically in mint order — strictly, not just at millisecond
|
|
20
|
+
* granularity.
|
|
21
|
+
*
|
|
22
|
+
* Two clock hazards are handled explicitly rather than by wrapping:
|
|
23
|
+
* - counter exhausted inside one millisecond → borrow one millisecond from the future (RFC 9562
|
|
24
|
+
* §6.2) and re-seed; the borrowed time is repaid as soon as the wall clock catches up.
|
|
25
|
+
* - clock jumps BACKWARDS → keep the last effective millisecond and keep counting, so the sequence
|
|
26
|
+
* never repeats and never decreases.
|
|
27
|
+
*
|
|
28
|
+
* The counter is per GENERATOR — one process, one Worker isolate. Two ids minted in the same
|
|
29
|
+
* millisecond by two isolates tie only if their independently seeded counters collide (~1/256), and
|
|
30
|
+
* the 62 random bits break that; within one isolate the order is exact. That is the whole promise:
|
|
31
|
+
* strictly increasing per generator, chronological to the millisecond across generators.
|
|
32
|
+
*
|
|
33
|
+
* No dependency, by design — `@fabrika/control` and `@fabrika/platform-node` carry deliberate copies
|
|
34
|
+
* of this same algorithm because neither may depend on this package (see the note in each).
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
/** `rand_a` is 12 bits, all of it counter. */
|
|
38
|
+
const COUNTER_MAX = 0xfff
|
|
39
|
+
/** Seed from 8 random bits only — the leading 4 stay zero so a millisecond has room to count. */
|
|
40
|
+
const COUNTER_SEED_MASK = 0xff
|
|
41
|
+
|
|
42
|
+
/** Effective millisecond of the last id. NEVER decreases; a backwards clock is absorbed here. */
|
|
43
|
+
let lastMillis = -1
|
|
44
|
+
let counter = 0
|
|
45
|
+
|
|
46
|
+
export function uuidv7(): string {
|
|
47
|
+
const bytes = new Uint8Array(16)
|
|
48
|
+
|
|
49
|
+
// Fill bytes 6..15 with randomness; the timestamp, version, variant and counter overwrite the
|
|
50
|
+
// fields they own below.
|
|
51
|
+
const random = new Uint8Array(10)
|
|
52
|
+
crypto.getRandomValues(random)
|
|
53
|
+
bytes.set(random, 6)
|
|
54
|
+
|
|
55
|
+
// Byte 7 is read as the counter seed BEFORE the counter overwrites it, so the seed costs no extra
|
|
56
|
+
// randomness.
|
|
57
|
+
const seed = bytes[7]! & COUNTER_SEED_MASK
|
|
58
|
+
const millis = Date.now()
|
|
59
|
+
if (millis > lastMillis) {
|
|
60
|
+
lastMillis = millis
|
|
61
|
+
counter = seed
|
|
62
|
+
} else if (counter < COUNTER_MAX) {
|
|
63
|
+
// Same millisecond, or a clock that went backwards: hold the effective timestamp, count on.
|
|
64
|
+
counter += 1
|
|
65
|
+
} else {
|
|
66
|
+
// Exhausted — borrow a millisecond from the future rather than wrap back under the last id.
|
|
67
|
+
lastMillis += 1
|
|
68
|
+
counter = seed
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// 48-bit big-endian Unix-millis timestamp in the first 6 bytes. It fits in 48 bits (well under
|
|
72
|
+
// 2^53), so the high bits are zero.
|
|
73
|
+
bytes[0] = Math.floor(lastMillis / 0x10000000000) & 0xff
|
|
74
|
+
bytes[1] = Math.floor(lastMillis / 0x100000000) & 0xff
|
|
75
|
+
bytes[2] = Math.floor(lastMillis / 0x1000000) & 0xff
|
|
76
|
+
bytes[3] = Math.floor(lastMillis / 0x10000) & 0xff
|
|
77
|
+
bytes[4] = Math.floor(lastMillis / 0x100) & 0xff
|
|
78
|
+
bytes[5] = lastMillis & 0xff
|
|
79
|
+
|
|
80
|
+
// Version: high nibble of byte 6 = 0b0111 (7); the counter takes the 12 bits of `rand_a` below it.
|
|
81
|
+
bytes[6] = 0x70 | (counter >>> 8)
|
|
82
|
+
bytes[7] = counter & 0xff
|
|
83
|
+
// Variant: high two bits of byte 8 = 0b10.
|
|
84
|
+
bytes[8] = (bytes[8]! & 0x3f) | 0x80
|
|
85
|
+
|
|
86
|
+
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0'))
|
|
87
|
+
|
|
88
|
+
return `${hex[0]}${hex[1]}${hex[2]}${hex[3]}-${hex[4]}${hex[5]}-${hex[6]}${hex[7]}-${hex[8]}${hex[9]}-${hex[10]}${hex[11]}${hex[12]}${hex[13]}${
|
|
89
|
+
hex[14]
|
|
90
|
+
}${hex[15]}`
|
|
91
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// @fabrika/auth-core — pure logic, types, and wire names shared across auth components and apps.
|
|
2
|
+
export * from './environment'
|
|
3
|
+
export * from './gates'
|
|
4
|
+
export * from './ids'
|
|
5
|
+
export * from './permissions'
|
|
6
|
+
export * from './rpc'
|
|
7
|
+
export * from './token'
|
|
8
|
+
export * from './types'
|
|
9
|
+
export * from './wire'
|
package/src/json.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tiny structural readers for untrusted JSON — here, a verified-but-loosely-typed JWT
|
|
3
|
+
* payload (jose returns `JWTPayload`, an index signature of `unknown`). They let `token.ts`
|
|
4
|
+
* narrow claims without `as` casts: read a field, check its runtime type, proceed. Mirrors the
|
|
5
|
+
* worker's own `json.ts`; kept here so the token-claim parser can live in `@fabrika/auth-core`
|
|
6
|
+
* (the contract both the Worker and the SDK must agree on) with no cross-package import.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** Read a property off an unknown value (undefined when absent / not an object). */
|
|
10
|
+
export function prop(value: unknown, key: string): unknown {
|
|
11
|
+
if (typeof value !== 'object' || value === null) {
|
|
12
|
+
return undefined
|
|
13
|
+
}
|
|
14
|
+
return Object.hasOwn(value, key) ? Reflect.get(value, key) : undefined
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function stringField(value: unknown, key: string): string | undefined {
|
|
18
|
+
const v = prop(value, key)
|
|
19
|
+
return typeof v === 'string' ? v : undefined
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function numberField(value: unknown, key: string): number | undefined {
|
|
23
|
+
const v = prop(value, key)
|
|
24
|
+
return typeof v === 'number' && Number.isFinite(v) ? v : undefined
|
|
25
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import type { PermissionEntry, Scope } from './types'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Wildcard action matching. The pattern is one of:
|
|
5
|
+
* - '*' — matches every action
|
|
6
|
+
* - 'prefix.*' — matches the `prefix` namespace and anything nested under it
|
|
7
|
+
* (e.g. 'project.*' matches 'project.read' and 'project.settings.update',
|
|
8
|
+
* but NOT 'projects.read' — the boundary is the dot)
|
|
9
|
+
* - exact — matches only that exact action string
|
|
10
|
+
*
|
|
11
|
+
* Examples:
|
|
12
|
+
* matchAction('*', 'x.y') === true
|
|
13
|
+
* matchAction('project.*', 'project.read') === true
|
|
14
|
+
* matchAction('project.*', 'project.settings.update') === true
|
|
15
|
+
* matchAction('project.read', 'project.read') === true
|
|
16
|
+
* matchAction('project.read', 'project.write') === false
|
|
17
|
+
* matchAction('project.*', 'projects.read') === false
|
|
18
|
+
*/
|
|
19
|
+
export function matchAction(pattern: string, action: string): boolean {
|
|
20
|
+
if (pattern === '*') {
|
|
21
|
+
return true
|
|
22
|
+
}
|
|
23
|
+
if (pattern.endsWith('.*')) {
|
|
24
|
+
// Drop the trailing '*' (keep the dot) so 'project.*' yields 'project.' —
|
|
25
|
+
// the action must start with that prefix, which enforces the dot boundary.
|
|
26
|
+
const prefix = pattern.slice(0, -1)
|
|
27
|
+
return action.startsWith(prefix)
|
|
28
|
+
}
|
|
29
|
+
return pattern === action
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Does `entries` grant `action` at the given scope? Mirrors `can()` semantics exactly:
|
|
34
|
+
* - scope === undefined → scope-less: ONLY entries with scope === null satisfy (global perms only).
|
|
35
|
+
* - scope === <Scope> → entries with scope === null OR an entry scoped to the SAME
|
|
36
|
+
* (type, value) pair satisfy.
|
|
37
|
+
*
|
|
38
|
+
* Within the satisfying entries, the entry's `action` is matched against the requested
|
|
39
|
+
* `action` using `matchAction` (so a wildcard entry like 'project.*' grants 'project.read').
|
|
40
|
+
*/
|
|
41
|
+
export function permits(entries: PermissionEntry[], action: string, scope?: Scope): boolean {
|
|
42
|
+
for (const entry of entries) {
|
|
43
|
+
const scopeOk = entry.scope === null
|
|
44
|
+
|| (scope !== undefined && entry.scope.type === scope.type && entry.scope.value === scope.value)
|
|
45
|
+
if (scopeOk && matchAction(entry.action, action)) {
|
|
46
|
+
return true
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return false
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The set of scope values `entries` grant `action` on within a single `dimension`
|
|
54
|
+
* (scope type) — the resolution behind `scopedTo()`, shared so the real SDK context and
|
|
55
|
+
* any fake/test context agree exactly:
|
|
56
|
+
* - `null` → unrestricted: a matching GLOBAL entry (scope === null) exists, so the
|
|
57
|
+
* principal holds the action everywhere (e.g. an admin / app-wide grant);
|
|
58
|
+
* - non-empty → exactly the scope values of the matching entries scoped to `dimension`;
|
|
59
|
+
* - `[]` → no matching entry: no scoped access at all within `dimension`.
|
|
60
|
+
* A matching global entry short-circuits to `null` (it dominates any scoped entries).
|
|
61
|
+
* Entries scoped to a DIFFERENT dimension are ignored (they say nothing about `dimension`).
|
|
62
|
+
*/
|
|
63
|
+
export function scopedValues(entries: PermissionEntry[], action: string, dimension: string): string[] | null {
|
|
64
|
+
const values: string[] = []
|
|
65
|
+
const seen = new Set<string>()
|
|
66
|
+
for (const entry of entries) {
|
|
67
|
+
if (!matchAction(entry.action, action)) {
|
|
68
|
+
continue
|
|
69
|
+
}
|
|
70
|
+
if (entry.scope === null) {
|
|
71
|
+
return null
|
|
72
|
+
}
|
|
73
|
+
// A grant in another dimension neither restricts nor widens this one — skip it.
|
|
74
|
+
if (entry.scope.type !== dimension) {
|
|
75
|
+
continue
|
|
76
|
+
}
|
|
77
|
+
if (!seen.has(entry.scope.value)) {
|
|
78
|
+
seen.add(entry.scope.value)
|
|
79
|
+
values.push(entry.scope.value)
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return values
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Validate a role/policy/inline action PATTERN against an app's action `catalog`.
|
|
87
|
+
* The catalog holds concrete action strings the app actually exposes (no wildcards).
|
|
88
|
+
* - '*' → always valid (the universal wildcard).
|
|
89
|
+
* - exact match → valid iff the catalog contains the pattern verbatim.
|
|
90
|
+
* - 'prefix.*' → valid iff some catalog action starts with `prefix.` (i.e. the
|
|
91
|
+
* namespace is non-empty), so we never grant a wildcard over nothing.
|
|
92
|
+
* - otherwise → invalid.
|
|
93
|
+
*/
|
|
94
|
+
export function isActionAllowed(pattern: string, catalog: readonly string[]): boolean {
|
|
95
|
+
if (pattern === '*') {
|
|
96
|
+
return true
|
|
97
|
+
}
|
|
98
|
+
if (catalog.includes(pattern)) {
|
|
99
|
+
return true
|
|
100
|
+
}
|
|
101
|
+
if (pattern.endsWith('.*')) {
|
|
102
|
+
// Keep the dot ('prefix.*' -> 'prefix.') so the namespace boundary is enforced and
|
|
103
|
+
// the wildcard only validates when the app exposes at least one action under it.
|
|
104
|
+
const prefix = pattern.slice(0, -1)
|
|
105
|
+
return catalog.some((entry) => entry.startsWith(prefix))
|
|
106
|
+
}
|
|
107
|
+
return false
|
|
108
|
+
}
|
package/src/rpc.ts
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
import type { Jwks } from './token'
|
|
2
|
+
import type { PermissionEntry, PrincipalType, Scope } from './types'
|
|
3
|
+
|
|
4
|
+
// ── propustka-native session auth (mint a per-app permission token from an SSO session) ──
|
|
5
|
+
//
|
|
6
|
+
// The SDK middleware presents the browser's opaque SSO session cookie; the Worker validates it,
|
|
7
|
+
// resolves the principal's permissions FOR THE CALLING APP, and signs a short-lived per-app
|
|
8
|
+
// permission token. The SDK then verifies that token LOCALLY (via `getJwks`) on every request —
|
|
9
|
+
// no per-request round-trip. `app` is self-asserted, but it is harmless: permissions are resolved
|
|
10
|
+
// server-side per app and the token's `aud` binds it to that app (a token minted for app X is
|
|
11
|
+
// rejected by any other app), so an app can only ever obtain its OWN permissions.
|
|
12
|
+
|
|
13
|
+
export interface MintTokenInput {
|
|
14
|
+
/** The app requesting a permission token (the SDK bakes this into its constructor). */
|
|
15
|
+
app: string
|
|
16
|
+
/** The opaque session cookie value (`__Host-px_session`); null when the browser has no session. */
|
|
17
|
+
session: string | null
|
|
18
|
+
requestId: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export type MintTokenResult =
|
|
22
|
+
/** `expiresAt` (unix seconds) lets the SDK refresh ahead of expiry. */
|
|
23
|
+
| { ok: true; token: string; expiresAt: number }
|
|
24
|
+
| { ok: false; reason: 'no_session' | 'invalid_session' | 'unknown_principal' | 'disabled' }
|
|
25
|
+
|
|
26
|
+
// ── propustka-native key auth (mint an access token from an opaque `px_` credential) ──
|
|
27
|
+
//
|
|
28
|
+
// The other front over the same resolve→sign core as `mintToken`: the SDK presents an opaque
|
|
29
|
+
// credential (an API key as a bearer, or a share-link path token) and the Worker resolves its
|
|
30
|
+
// EFFECTIVE permissions (principal-bound → live; anonymous → frozen inline grants) and signs an
|
|
31
|
+
// access token the SDK then verifies locally. `app` is self-asserted but harmless — the token's
|
|
32
|
+
// `aud` binds it and permissions are resolved server-side per app.
|
|
33
|
+
|
|
34
|
+
export interface MintFromKeyInput {
|
|
35
|
+
/** The app requesting the token (the SDK bakes this into its constructor). */
|
|
36
|
+
app: string
|
|
37
|
+
/** The opaque `px_` credential (bearer / path token). */
|
|
38
|
+
key: string
|
|
39
|
+
requestId: string
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export type MintFromKeyResult =
|
|
43
|
+
| { ok: true; token: string; expiresAt: number }
|
|
44
|
+
| { ok: false; reason: 'invalid_key' | 'unknown_principal' | 'disabled' }
|
|
45
|
+
|
|
46
|
+
// ── Session handoff (ADR-0021, ADR-0023) ──────────────────────────────────────
|
|
47
|
+
//
|
|
48
|
+
// The ONE way a browser that authenticated at IAM ends up authenticated at an app, whether or not the
|
|
49
|
+
// two share a domain: no cookie of IAM's is ever readable from an app's host. IAM issues a single-use
|
|
50
|
+
// code bound to (session, app, return URL); the proxy in front of the app redeems it and sets the
|
|
51
|
+
// returned APP SESSION as a host-only cookie on the app's own host. Everything after that is the
|
|
52
|
+
// ordinary `mintToken` path.
|
|
53
|
+
//
|
|
54
|
+
// The redemption yields a SESSION, not just an access token, and that is the point: an access token
|
|
55
|
+
// lives `DEFAULT_TOKEN_TTL_SECONDS`, so a browser holding only one would be redirected on every
|
|
56
|
+
// expiry — and a redirect turns an in-flight POST into a bodyless GET. The proxy re-mints from the
|
|
57
|
+
// app's own session, server-side.
|
|
58
|
+
//
|
|
59
|
+
// This lives on the PROXY surface (`/auth/mint/*`, gated by its own key), not on `IamRpc`. That is
|
|
60
|
+
// ADR-0007's least-privilege split: the proxy is the only publicly-routed component and holds a key
|
|
61
|
+
// scoped to the handful of calls it needs.
|
|
62
|
+
|
|
63
|
+
export interface ExchangeAuthCodeInput {
|
|
64
|
+
/** The app redeeming the code. A code issued for another app is refused. */
|
|
65
|
+
app: string
|
|
66
|
+
/** The single-use code, as it arrived in the callback query. */
|
|
67
|
+
code: string
|
|
68
|
+
/** Browser-held proof for the S256 challenge integrity-bound into the code. */
|
|
69
|
+
verifier: string
|
|
70
|
+
requestId: string
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export type ExchangeAuthCodeResult =
|
|
74
|
+
/**
|
|
75
|
+
* `session` is the opaque APP session the proxy sets as a host-only cookie; `returnUrl` is where
|
|
76
|
+
* the browser goes next and is carried server-side so a caller cannot redirect it elsewhere.
|
|
77
|
+
* `expiresAt` is the session's absolute expiry, for the cookie's `Max-Age`.
|
|
78
|
+
*/
|
|
79
|
+
| { ok: true; session: string; returnUrl: string; expiresAt: number }
|
|
80
|
+
/** Every failure is terminal — a code is single-use, so there is nothing to retry. */
|
|
81
|
+
| { ok: false; reason: 'invalid_code' | 'expired_code' | 'wrong_app' | 'invalid_verifier' | 'unknown_principal' | 'disabled' }
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Redemption, as a contract of its own rather than a method on `IamRpc`. Only the proxy calls it, and
|
|
85
|
+
* `IamRpc` is held by every SDK consumer — folding it in would hand the ability to convert a code
|
|
86
|
+
* into a session to everything that holds the management key.
|
|
87
|
+
*/
|
|
88
|
+
export interface IamHandoffRpc {
|
|
89
|
+
exchangeAuthCode(input: ExchangeAuthCodeInput): Promise<ExchangeAuthCodeResult>
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Where the proxy answers the handoff, on every app host it fronts. Reserved: an app route at this
|
|
94
|
+
* path is shadowed by the proxy and never reaches the upstream, so it is deliberately namespaced.
|
|
95
|
+
*/
|
|
96
|
+
export const AUTH_CALLBACK_PATH = '/__fabrika/auth/callback'
|
|
97
|
+
|
|
98
|
+
/** Query parameter carrying the single-use code on the callback. */
|
|
99
|
+
export const AUTH_CODE_PARAM = 'code'
|
|
100
|
+
|
|
101
|
+
/** Public nonce that selects the app-host handoff cookie on the callback. */
|
|
102
|
+
export const AUTH_HANDOFF_STATE_PARAM = 'state'
|
|
103
|
+
|
|
104
|
+
/** S256 challenge sent to IAM when the proxy starts a handoff. */
|
|
105
|
+
export const AUTH_HANDOFF_CHALLENGE_PARAM = 'code_challenge'
|
|
106
|
+
|
|
107
|
+
/** Dynamic app-host cookie prefix; the public state suffix permits concurrent login tabs. */
|
|
108
|
+
export const HANDOFF_COOKIE_PREFIX = '__Host-px_handoff_'
|
|
109
|
+
|
|
110
|
+
/** A login attempt may wait at IAM or an upstream IdP before the code itself is issued. */
|
|
111
|
+
export const HANDOFF_COOKIE_TTL_SECONDS = 10 * 60
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* How long a code may be held before redemption. Seconds, not minutes: it travels in one redirect
|
|
115
|
+
* and is redeemed by the next request, so anything longer is only a larger replay window.
|
|
116
|
+
*/
|
|
117
|
+
export const AUTH_CODE_TTL_SECONDS = 120
|
|
118
|
+
|
|
119
|
+
// ── Issuing credentials (issueKey) and passthrough tokens (issueJwt) ──────────────
|
|
120
|
+
//
|
|
121
|
+
// `issueKey` mints an opaque, stored, revocable `px_` credential; `issueJwt` signs a stateless
|
|
122
|
+
// passthrough access token (audit-only, TTL-bounded, not revocable). Both are DELEGATED: the issuer
|
|
123
|
+
// is resolved server-side from the forwarded credentials and may only grant what it itself holds.
|
|
124
|
+
|
|
125
|
+
/** One grant on a `px_` credential / passthrough token — an action pattern + optional scope. */
|
|
126
|
+
export interface KeyGrant {
|
|
127
|
+
action: string
|
|
128
|
+
/** Omitted/null = global (the issuer must hold the action globally). */
|
|
129
|
+
scope?: Scope | null
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Create a NEW service (machine) principal and bind the key to it — the folded `issueServiceToken`.
|
|
134
|
+
* The issuer must hold every `permissions` action on `scope` (the same delegation rule as a grant).
|
|
135
|
+
*/
|
|
136
|
+
export interface IssueKeyServiceSpec {
|
|
137
|
+
/** Display label for the new service principal + the credential. */
|
|
138
|
+
label: string
|
|
139
|
+
/** Inline action patterns granted to the new service principal; delegation-checked on `scope`. */
|
|
140
|
+
permissions: string[]
|
|
141
|
+
/** Scope the grant + the delegation check apply to; omitted/null → global. */
|
|
142
|
+
scope?: Scope | null
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export interface IssueKeyInput {
|
|
146
|
+
app: string
|
|
147
|
+
/**
|
|
148
|
+
* The propustka-native credential the ISSUER is resolved from server-side (never self-asserted):
|
|
149
|
+
* a `px_token` access JWT (verified against propustka's signing keys) or a `px_` key. Null = absent.
|
|
150
|
+
*/
|
|
151
|
+
credential: string | null
|
|
152
|
+
requestId: string
|
|
153
|
+
/**
|
|
154
|
+
* Create a NEW machine principal and bind the key to it (the folded `issueServiceToken`). When set,
|
|
155
|
+
* `principalId` / `permissions` (the bind / standalone modes) are ignored.
|
|
156
|
+
*/
|
|
157
|
+
service?: IssueKeyServiceSpec
|
|
158
|
+
/**
|
|
159
|
+
* Bind to a principal (the credential then carries that principal's LIVE perms; inline
|
|
160
|
+
* `permissions` downscope it). v1: only the issuer's OWN id. Omit for a standalone credential.
|
|
161
|
+
*/
|
|
162
|
+
principalId?: string
|
|
163
|
+
/** Inline grants — the frozen set (standalone) and/or a downscope restriction (bound). */
|
|
164
|
+
permissions?: KeyGrant[]
|
|
165
|
+
label?: string
|
|
166
|
+
/** Absolute credential expiry (unix seconds); NULL = no expiry. */
|
|
167
|
+
expiresAt?: number
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export type IssueKeyResult =
|
|
171
|
+
/**
|
|
172
|
+
* Plaintext `px_` token returned ONCE; `id` is the credential's stable handle (revoke). `principalId`
|
|
173
|
+
* is present when the key is bound to a principal (a `service` create or a self-bind), absent for a
|
|
174
|
+
* standalone (anonymous) credential.
|
|
175
|
+
*/
|
|
176
|
+
| { ok: true; token: string; id: string; principalId?: string }
|
|
177
|
+
| { ok: false; reason: 'missing_token' | 'invalid_token' | 'unknown_principal' | 'disabled' | 'not_allowed' }
|
|
178
|
+
|
|
179
|
+
export interface IssueJwtInput {
|
|
180
|
+
app: string
|
|
181
|
+
/** The propustka-native credential the ISSUER is resolved from (px_token / px_ key); null = absent. */
|
|
182
|
+
credential: string | null
|
|
183
|
+
requestId: string
|
|
184
|
+
/** Inline grants the passthrough token carries (frozen at issue). */
|
|
185
|
+
permissions: KeyGrant[]
|
|
186
|
+
label?: string
|
|
187
|
+
/** Requested lifetime (seconds); capped by the server. Defaults to the standard token TTL. */
|
|
188
|
+
ttl?: number
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export type IssueJwtResult =
|
|
192
|
+
/** The signed passthrough token returned ONCE; `id` is its audit reference (no DB row to revoke). */
|
|
193
|
+
| { ok: true; token: string; expiresAt: number; id: string }
|
|
194
|
+
| { ok: false; reason: 'missing_token' | 'invalid_token' | 'unknown_principal' | 'disabled' | 'not_allowed' }
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* A resolved caller identity + its frozen permission snapshot. Produced by `accessClaimsToResolved`
|
|
198
|
+
* from a verified access token (`token.ts`); consumed where a principal's resolved perms are needed
|
|
199
|
+
* as a plain serializable value.
|
|
200
|
+
*/
|
|
201
|
+
export interface ResolvedPrincipal {
|
|
202
|
+
id: string
|
|
203
|
+
type: PrincipalType
|
|
204
|
+
label: string
|
|
205
|
+
permissions: PermissionEntry[]
|
|
206
|
+
requestId: string
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export interface AuditInput {
|
|
210
|
+
app: string
|
|
211
|
+
requestId: string
|
|
212
|
+
/** NULL for an anonymous-credential event (a share link / passthrough JWT has no principal). */
|
|
213
|
+
principalId: string | null
|
|
214
|
+
/** Snapshot — survives principal deletion (the credential/token label for anonymous events). */
|
|
215
|
+
principalLabel: string
|
|
216
|
+
/** Set for an anonymous-credential event — the issuing credential / passthrough-token id. */
|
|
217
|
+
credentialId?: string
|
|
218
|
+
action: string
|
|
219
|
+
resourceType: string
|
|
220
|
+
resourceId?: string
|
|
221
|
+
diff?: unknown
|
|
222
|
+
metadata?: unknown
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export interface RevokeKeyInput {
|
|
226
|
+
app: string
|
|
227
|
+
/** The propustka-native credential the CALLER (authorizer) is resolved from; null = absent. */
|
|
228
|
+
credential: string | null
|
|
229
|
+
requestId: string
|
|
230
|
+
/** The credential id (the `id` returned by `issueKey`), NOT the plaintext `px_` token. */
|
|
231
|
+
id: string
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export type RevokeKeyResult =
|
|
235
|
+
/** `revoked` is false when the credential was already revoked (idempotent). */
|
|
236
|
+
| { ok: true; revoked: boolean }
|
|
237
|
+
| { ok: false; reason: 'missing_token' | 'invalid_token' | 'unknown_principal' | 'disabled' | 'not_allowed' | 'not_found' }
|
|
238
|
+
|
|
239
|
+
// ── List principals (the app's people directory) ───────────────────────────────
|
|
240
|
+
//
|
|
241
|
+
// A read-only enumeration of the USER principals who can access an app — its people
|
|
242
|
+
// directory. Apps consume it for things propustka isn't the authority on but needs the
|
|
243
|
+
// roster for: an assignee picker, an actor/owner label list. The caller is resolved from
|
|
244
|
+
// the forwarded Access credentials and the listed app is the aud-VERIFIED app — an operator
|
|
245
|
+
// can only enumerate the roster of an app it itself authenticates to (never a self-asserted
|
|
246
|
+
// app), so there is no cross-app leak. Services are excluded (machines aren't assignable
|
|
247
|
+
// people); each item carries `disabled` so the consumer can grey-out/hide deactivated users.
|
|
248
|
+
|
|
249
|
+
export interface ListPrincipalsInput {
|
|
250
|
+
/** Self-asserted caller app id; superseded by the credential's aud on a valid `px_token`. */
|
|
251
|
+
app: string
|
|
252
|
+
/** The propustka-native credential the CALLER is resolved from (px_token / px_ key); null = absent. */
|
|
253
|
+
credential: string | null
|
|
254
|
+
requestId: string
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export interface PrincipalListItem {
|
|
258
|
+
/** IAM principal id (UUIDv7) — stable, safe to store on domain rows (assignee/actor). */
|
|
259
|
+
id: string
|
|
260
|
+
type: PrincipalType
|
|
261
|
+
/** Human-readable: the user's email. */
|
|
262
|
+
label: string
|
|
263
|
+
/** The user's email (users always have one; null only defensively). */
|
|
264
|
+
email: string | null
|
|
265
|
+
/** True when the principal is soft-disabled (kept listable so labels still resolve). */
|
|
266
|
+
disabled: boolean
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export type ListPrincipalsResult =
|
|
270
|
+
| { ok: true; principals: PrincipalListItem[] }
|
|
271
|
+
/** `not_allowed` when the caller has no verified app / no permission on it (a zero-grant user). */
|
|
272
|
+
| { ok: false; reason: 'missing_token' | 'invalid_token' | 'unknown_principal' | 'disabled' | 'not_allowed' }
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* The RPC contract. The Worker's `WorkerEntrypoint` `implements IamRpc`; the SDK types its
|
|
276
|
+
* binding as `Service<IamRpc>` (so the SDK never imports the Worker). Methods return plain
|
|
277
|
+
* serializable objects (RPC-friendly).
|
|
278
|
+
*/
|
|
279
|
+
export interface IamRpc {
|
|
280
|
+
/**
|
|
281
|
+
* Mint a short-lived, per-app permission token from the browser's SSO session — the
|
|
282
|
+
* propustka-native auth path. The SDK middleware calls this only when its cached permission
|
|
283
|
+
* token is missing/near-expiry (≈ once per TTL), NOT per request: every other request verifies
|
|
284
|
+
* the cached token locally against `getJwks`.
|
|
285
|
+
*/
|
|
286
|
+
mintToken(input: MintTokenInput): Promise<MintTokenResult>
|
|
287
|
+
/**
|
|
288
|
+
* Mint a per-app access token from an opaque `px_` credential (API key / share link) — the other
|
|
289
|
+
* front over the same resolve→sign core as `mintToken`. Called by the SDK middleware once per TTL
|
|
290
|
+
* when a request carries a `px_` bearer/path credential; every other request verifies the cached
|
|
291
|
+
* token locally. Fails closed (`invalid_key`/`unknown_principal`/`disabled`).
|
|
292
|
+
*/
|
|
293
|
+
mintFromKey(input: MintFromKeyInput): Promise<MintFromKeyResult>
|
|
294
|
+
/**
|
|
295
|
+
* Mint an opaque, stored, revocable `px_` credential (API key / share link). Delegated: the issuer
|
|
296
|
+
* is resolved from the forwarded credentials and may only grant what it holds. Returns the
|
|
297
|
+
* plaintext token ONCE; `id` is the durable handle for revoke.
|
|
298
|
+
*/
|
|
299
|
+
issueKey(input: IssueKeyInput): Promise<IssueKeyResult>
|
|
300
|
+
/**
|
|
301
|
+
* Sign a stateless passthrough access token (audit-only, TTL-bounded, NOT revocable). Delegated
|
|
302
|
+
* like `issueKey`. The caller carries the returned JWT directly; apps verify it locally with no
|
|
303
|
+
* propustka round-trip.
|
|
304
|
+
*/
|
|
305
|
+
issueJwt(input: IssueJwtInput): Promise<IssueJwtResult>
|
|
306
|
+
/**
|
|
307
|
+
* The public signing key set. The SDK fetches it ONCE per isolate (cached) over the binding —
|
|
308
|
+
* which never traverses the Access edge — then verifies every permission token locally.
|
|
309
|
+
*/
|
|
310
|
+
getJwks(): Promise<Jwks>
|
|
311
|
+
audit(event: AuditInput): Promise<void>
|
|
312
|
+
/**
|
|
313
|
+
* List the USER principals who can access the caller's app (its people directory). The caller
|
|
314
|
+
* is resolved from the forwarded Access credentials and the app is the aud-VERIFIED app — so an
|
|
315
|
+
* operator only ever sees its own app's roster. Authorized for any member that holds at least
|
|
316
|
+
* one permission on the app; a zero-grant authenticated user gets `not_allowed`. Read-only.
|
|
317
|
+
*/
|
|
318
|
+
listPrincipals(input: ListPrincipalsInput): Promise<ListPrincipalsResult>
|
|
319
|
+
/**
|
|
320
|
+
* Revoke a previously-issued opaque `px_` credential (an API key / share link) by id. The caller
|
|
321
|
+
* is resolved from the forwarded Access credentials and authorized: the original issuer may always
|
|
322
|
+
* revoke; otherwise, for an anonymous credential, the caller must hold every granted action (an
|
|
323
|
+
* admin / app-wide operator). Idempotent — revoking an already-revoked credential returns
|
|
324
|
+
* `{ ok: true, revoked: false }`. An unknown id returns `{ ok: false, reason: 'not_found' }`.
|
|
325
|
+
*/
|
|
326
|
+
revokeKey(input: RevokeKeyInput): Promise<RevokeKeyResult>
|
|
327
|
+
}
|
package/src/token.ts
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The propustka-issued token contract — the SECOND thing (after `IamRpc`) that must not drift
|
|
3
|
+
* between the Worker and the SDK.
|
|
4
|
+
*
|
|
5
|
+
* Background: today a request is authorized by the Worker resolving a Cloudflare Access JWT on
|
|
6
|
+
* every call over RPC (the CF token carries only identity, so authz needs a round-trip). When
|
|
7
|
+
* propustka issues its OWN token it can embed the already-resolved permission set, and the SDK
|
|
8
|
+
* authorizes LOCALLY — no per-request round-trip. This module is the wire shape of that token:
|
|
9
|
+
*
|
|
10
|
+
* - the Worker BUILDS claims here and signs them (`buildAccessClaims`);
|
|
11
|
+
* - the SDK verifies the signature with jose, then PARSES the payload back into typed claims
|
|
12
|
+
* here (`parseAccessClaims`) — structurally, so it reads them without an `as` cast — and maps a
|
|
13
|
+
* principal-bound token into the `ResolvedPrincipal` the existing `AuthContext` consumes.
|
|
14
|
+
*
|
|
15
|
+
* ONE shape, no `kind` discriminator — the optional `ptype` carries the distinction. Every token carries
|
|
16
|
+
* `perms: PermissionEntry[]` (authorized via `permits` — scopes + wildcards) and an OPTIONAL
|
|
17
|
+
* principal (`ptype`): present means the token is bound to a user/service principal; absent means an
|
|
18
|
+
* anonymous credential (a share link / standalone JWT), whose `perms` are narrow scoped entries and
|
|
19
|
+
* whose audit actor is `label`. `sub` is the subject id either way — a principal id when bound, else
|
|
20
|
+
* the issuing credential/token id.
|
|
21
|
+
*
|
|
22
|
+
* Pure: no jose, no I/O. Signing/verifying (key material) stays in the packages that own it.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { numberField, prop, stringField } from './json'
|
|
26
|
+
import type { ResolvedPrincipal } from './rpc'
|
|
27
|
+
import type { PermissionEntry, PermissionSource, PrincipalType, Scope } from './types'
|
|
28
|
+
|
|
29
|
+
// ── Names & knobs on the wire (both sides agree) ───────────────────────────────
|
|
30
|
+
|
|
31
|
+
/** Namespace reserved for browser credentials owned by IAM and the Fabrika proxy. */
|
|
32
|
+
export const FABRIKA_COOKIE_PREFIX = '__Host-px_'
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Long-lived opaque session id, HOST-ONLY on whichever host wrote it — IAM's own at login, an app's
|
|
36
|
+
* own after the proxy redeems a handoff code
|
|
37
|
+
* ([ADR-0023](../../../docs/decisions/0023-one-session-per-host.md)). Same name, different host,
|
|
38
|
+
* different `sessions` row.
|
|
39
|
+
*
|
|
40
|
+
* `__Host-` is a browser-enforced restatement of that: the prefix makes the browser refuse the cookie
|
|
41
|
+
* unless it carries `Secure`, omits `Domain` and uses `Path=/`, so a sibling host under a shared
|
|
42
|
+
* registrable domain cannot plant a second cookie of this name that the real host would then send
|
|
43
|
+
* alongside its own. Measured, not assumed: Chromium accepts it over plain HTTP on `*.localhost`,
|
|
44
|
+
* because those origins are potentially trustworthy.
|
|
45
|
+
*/
|
|
46
|
+
export const SESSION_COOKIE = `${FABRIKA_COOKIE_PREFIX}session`
|
|
47
|
+
/** Prefix marking a propustka opaque credential (API key / share link), e.g. `Bearer px_<random>`. */
|
|
48
|
+
export const API_KEY_PREFIX = 'px_'
|
|
49
|
+
|
|
50
|
+
/** Signing algorithm propustka issues with and the SDK verifies (ECDSA P-256 — compact, ubiquitous). */
|
|
51
|
+
export const TOKEN_ALG = 'ES256'
|
|
52
|
+
|
|
53
|
+
/** Default per-app access-token lifetime. Revocation/role changes take effect within this. */
|
|
54
|
+
export const DEFAULT_TOKEN_TTL_SECONDS = 300
|
|
55
|
+
/**
|
|
56
|
+
* Hard cap on a `issueJwt` passthrough token's lifetime. A passthrough JWT is NOT revocable (no
|
|
57
|
+
* stored row), so its TTL is its whole security window — bounded here (24 h) regardless of request.
|
|
58
|
+
*/
|
|
59
|
+
export const MAX_PASSTHROUGH_TTL_SECONDS = 24 * 60 * 60
|
|
60
|
+
/**
|
|
61
|
+
* The SDK refreshes an access token this many seconds BEFORE it expires, so a request never rides a
|
|
62
|
+
* token that expires mid-flight. Must be < the token TTL.
|
|
63
|
+
*/
|
|
64
|
+
export const TOKEN_REFRESH_SKEW_SECONDS = 30
|
|
65
|
+
|
|
66
|
+
// ── Claim shape (one, no discriminator) ────────────────────────────────────────
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The propustka access token. `perms` is always present (matched via `permits`); `ptype` is present
|
|
70
|
+
* only when `sub` is a principal. `label` is the audit actor — the principal's label when bound, the
|
|
71
|
+
* credential/jwt label otherwise (or null).
|
|
72
|
+
*/
|
|
73
|
+
export interface AccessTokenClaims {
|
|
74
|
+
/** Issuer — propustka's own origin (e.g. `https://propustka.example.com`). */
|
|
75
|
+
iss: string
|
|
76
|
+
/** The app id this token is scoped to. The SDK REJECTS a token whose `aud` is not its app. */
|
|
77
|
+
aud: string
|
|
78
|
+
/** Subject id: a principal id when `ptype` is set, else the issuing credential/token id. */
|
|
79
|
+
sub: string
|
|
80
|
+
/** Issued-at (unix seconds). */
|
|
81
|
+
iat: number
|
|
82
|
+
/** Expiry (unix seconds). */
|
|
83
|
+
exp: number
|
|
84
|
+
/** Resolved/effective permissions; `can(action, scope?)` = `permits(perms, action, scope)`. */
|
|
85
|
+
perms: PermissionEntry[]
|
|
86
|
+
/** Present only when the token is bound to a principal (`sub` is that principal). */
|
|
87
|
+
ptype?: PrincipalType
|
|
88
|
+
/** Audit actor label — the principal's label, or the credential/jwt label, or null (anonymous). */
|
|
89
|
+
label: string | null
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// ── Public JWKS (the SDK fetches this once, then verifies tokens locally) ───────
|
|
93
|
+
//
|
|
94
|
+
// Transport is the IAM service binding (`getJwks()` RPC), NOT a public HTTPS URL: app↔IAM is
|
|
95
|
+
// RPC over the binding, which never traverses the Access edge — so the SDK reaches the key set
|
|
96
|
+
// even while propustka's own hostname is still gated by Cloudflare Access. The Worker also
|
|
97
|
+
// serves the standard `/.well-known/jwks.json`, for when Access is gone. Both emit this shape.
|
|
98
|
+
|
|
99
|
+
/** A published public signing key (EC P-256 / ES256). A jose-compatible JWK subset. */
|
|
100
|
+
export interface PublicJwk {
|
|
101
|
+
kty: string
|
|
102
|
+
crv?: string
|
|
103
|
+
x?: string
|
|
104
|
+
y?: string
|
|
105
|
+
kid?: string
|
|
106
|
+
alg?: string
|
|
107
|
+
use?: string
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The public key set the SDK feeds to a local JWKS verifier. */
|
|
111
|
+
export interface Jwks {
|
|
112
|
+
keys: PublicJwk[]
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// ── Build (Worker side, pre-sign) ──────────────────────────────────────────────
|
|
116
|
+
|
|
117
|
+
export interface AccessTokenParams {
|
|
118
|
+
/** Issuer (propustka origin). */
|
|
119
|
+
iss: string
|
|
120
|
+
/** App id this token is for (becomes `aud`). */
|
|
121
|
+
app: string
|
|
122
|
+
/** Subject id (becomes `sub`) — a principal id when `type` is given, else a credential/token id. */
|
|
123
|
+
subject: string
|
|
124
|
+
/** Principal type — omit for an anonymous credential (share link / standalone JWT). */
|
|
125
|
+
type?: PrincipalType
|
|
126
|
+
/** Audit actor label, or null for an unlabeled anonymous token. */
|
|
127
|
+
label: string | null
|
|
128
|
+
permissions: PermissionEntry[]
|
|
129
|
+
issuedAt: number
|
|
130
|
+
expiresAt: number
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Assemble the claim object for an access token. Pure — the caller signs the result. */
|
|
134
|
+
export function buildAccessClaims(params: AccessTokenParams): AccessTokenClaims {
|
|
135
|
+
const claims: AccessTokenClaims = {
|
|
136
|
+
iss: params.iss,
|
|
137
|
+
aud: params.app,
|
|
138
|
+
sub: params.subject,
|
|
139
|
+
iat: params.issuedAt,
|
|
140
|
+
exp: params.expiresAt,
|
|
141
|
+
perms: params.permissions,
|
|
142
|
+
label: params.label,
|
|
143
|
+
}
|
|
144
|
+
if (params.type !== undefined) {
|
|
145
|
+
claims.ptype = params.type
|
|
146
|
+
}
|
|
147
|
+
return claims
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// ── Parse (SDK side, post-verify) ──────────────────────────────────────────────
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Narrow a verified JWT payload into typed access-token claims WITHOUT trusting its shape. jose has
|
|
154
|
+
* already checked the signature, `exp`, and `aud`; this validates the custom claims structurally so
|
|
155
|
+
* the SDK reads them without an `as` cast. Returns null on any malformed claim shape.
|
|
156
|
+
*/
|
|
157
|
+
export function parseAccessClaims(payload: unknown): AccessTokenClaims | null {
|
|
158
|
+
const iss = stringField(payload, 'iss')
|
|
159
|
+
const aud = stringField(payload, 'aud')
|
|
160
|
+
const sub = stringField(payload, 'sub')
|
|
161
|
+
const iat = numberField(payload, 'iat')
|
|
162
|
+
const exp = numberField(payload, 'exp')
|
|
163
|
+
const perms = parsePermissionEntries(prop(payload, 'perms'))
|
|
164
|
+
const label = parseNullableString(prop(payload, 'label'))
|
|
165
|
+
const ptype = parseOptionalPrincipalType(prop(payload, 'ptype'))
|
|
166
|
+
if (iss === undefined || aud === undefined || sub === undefined || iat === undefined || exp === undefined) {
|
|
167
|
+
return null
|
|
168
|
+
}
|
|
169
|
+
if (perms === null || label === undefined || ptype === undefined) {
|
|
170
|
+
return null
|
|
171
|
+
}
|
|
172
|
+
const claims: AccessTokenClaims = { iss, aud, sub, iat, exp, perms, label }
|
|
173
|
+
if (ptype !== null) {
|
|
174
|
+
claims.ptype = ptype
|
|
175
|
+
}
|
|
176
|
+
return claims
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Map a verified PRINCIPAL-bound access token into the `ResolvedPrincipal` the existing
|
|
181
|
+
* `AuthContext` consumes. Returns null for an anonymous token (no `ptype`) — the caller handles
|
|
182
|
+
* the anonymous case separately.
|
|
183
|
+
*/
|
|
184
|
+
export function accessClaimsToResolved(claims: AccessTokenClaims, requestId: string): ResolvedPrincipal | null {
|
|
185
|
+
if (claims.ptype === undefined) {
|
|
186
|
+
return null
|
|
187
|
+
}
|
|
188
|
+
return {
|
|
189
|
+
id: claims.sub,
|
|
190
|
+
type: claims.ptype,
|
|
191
|
+
label: claims.label ?? claims.sub,
|
|
192
|
+
permissions: claims.perms,
|
|
193
|
+
requestId,
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// ── Structural parsers (no `as`) ───────────────────────────────────────────────
|
|
198
|
+
|
|
199
|
+
/** Read `ptype`: a valid principal type, explicit-absent (→ null), or malformed (→ undefined). */
|
|
200
|
+
function parseOptionalPrincipalType(value: unknown): PrincipalType | null | undefined {
|
|
201
|
+
if (value === undefined || value === null) {
|
|
202
|
+
return null
|
|
203
|
+
}
|
|
204
|
+
return value === 'user' || value === 'service' ? value : undefined
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Accept a string or explicit-null/absent (→ null); reject any other type (→ undefined). */
|
|
208
|
+
function parseNullableString(value: unknown): string | null | undefined {
|
|
209
|
+
if (value === null || value === undefined) {
|
|
210
|
+
return null
|
|
211
|
+
}
|
|
212
|
+
return typeof value === 'string' ? value : undefined
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function parseScope(value: unknown): Scope | null | undefined {
|
|
216
|
+
if (value === null) {
|
|
217
|
+
return null
|
|
218
|
+
}
|
|
219
|
+
const type = stringField(value, 'type')
|
|
220
|
+
const scopeValue = stringField(value, 'value')
|
|
221
|
+
if (type === undefined || scopeValue === undefined) {
|
|
222
|
+
return undefined
|
|
223
|
+
}
|
|
224
|
+
return { type, value: scopeValue }
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Validate `source` against the union — our own token, but read without `as`. */
|
|
228
|
+
function parseSource(value: unknown): PermissionSource | null {
|
|
229
|
+
if (value === 'grant' || value === 'bootstrap') {
|
|
230
|
+
return value
|
|
231
|
+
}
|
|
232
|
+
if (typeof value === 'string' && value.startsWith('group:')) {
|
|
233
|
+
return `group:${value.slice('group:'.length)}`
|
|
234
|
+
}
|
|
235
|
+
return null
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function parsePermissionEntries(value: unknown): PermissionEntry[] | null {
|
|
239
|
+
if (!Array.isArray(value)) {
|
|
240
|
+
return null
|
|
241
|
+
}
|
|
242
|
+
const out: PermissionEntry[] = []
|
|
243
|
+
for (const item of value) {
|
|
244
|
+
const action = stringField(item, 'action')
|
|
245
|
+
const scope = parseScope(prop(item, 'scope'))
|
|
246
|
+
const source = parseSource(prop(item, 'source'))
|
|
247
|
+
if (action === undefined || scope === undefined || source === null) {
|
|
248
|
+
return null
|
|
249
|
+
}
|
|
250
|
+
out.push({ action, scope, source })
|
|
251
|
+
}
|
|
252
|
+
return out
|
|
253
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
export type PrincipalType = 'user' | 'service'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Where a resolved permission entry came from. Used for debuggability in the admin UI
|
|
5
|
+
* ("why does this user have this permission?"); `can()`/`scopedTo()` ignore it.
|
|
6
|
+
* - 'grant' — explicit `grants` row
|
|
7
|
+
* - 'bootstrap' — IAM_BOOTSTRAP_ADMINS env match (resolution-time only)
|
|
8
|
+
* - `group:${groupRef}` — IdP group → role mapping (the `<org>/<team>` ref)
|
|
9
|
+
*/
|
|
10
|
+
export type PermissionSource = 'grant' | 'bootstrap' | `group:${string}`
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* A flat, app-owned scope coordinate — one dimension (`type`) and an opaque value.
|
|
14
|
+
* Dimensions are INDEPENDENT: there is NO hierarchy/containment between them.
|
|
15
|
+
* `value` is an opaque app-owned string; core never validates it.
|
|
16
|
+
*/
|
|
17
|
+
export interface Scope {
|
|
18
|
+
type: string
|
|
19
|
+
value: string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface PermissionEntry {
|
|
23
|
+
action: string
|
|
24
|
+
/** null = global / all scopes */
|
|
25
|
+
scope: Scope | null
|
|
26
|
+
source: PermissionSource
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Domain event apps emit. Only the app knows what changed.
|
|
31
|
+
*
|
|
32
|
+
* IMPORTANT: `diff`/`metadata` may carry sensitive values (settings can hold secrets).
|
|
33
|
+
* The app MUST redact secret material before passing them — audit storage is verbatim
|
|
34
|
+
* and long-lived; the IAM Worker stores what it receives as-is.
|
|
35
|
+
*/
|
|
36
|
+
export interface DomainEvent {
|
|
37
|
+
action: string
|
|
38
|
+
resourceType: string
|
|
39
|
+
resourceId?: string
|
|
40
|
+
diff?: unknown
|
|
41
|
+
metadata?: unknown
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface RoleDef {
|
|
45
|
+
name: string
|
|
46
|
+
description?: string
|
|
47
|
+
permissions: string[]
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** One scope dimension an app exposes (flat, independent). */
|
|
51
|
+
export interface AppScopeDef {
|
|
52
|
+
type: string
|
|
53
|
+
label?: string
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** One action in an app's catalog (used for validation + admin UI discovery). */
|
|
57
|
+
export interface AppActionDef {
|
|
58
|
+
action: string
|
|
59
|
+
description?: string
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** An app's full authz vocabulary, declared in the app's code, reconciled into Propustka. */
|
|
63
|
+
export interface AppSchema {
|
|
64
|
+
scopes: AppScopeDef[]
|
|
65
|
+
actions: AppActionDef[]
|
|
66
|
+
/** role_key -> def; these are origin='app' roles. */
|
|
67
|
+
roles: Record<string, RoleDef>
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// ── Per-path access gates (the propustka-native front door, enforced by the proxy) ──
|
|
71
|
+
//
|
|
72
|
+
// Replaces the deleted Cloudflare-Access edge model (AppAccess/AccessAppDecl/AccessRule). There is
|
|
73
|
+
// no IAM reconcile for these: gate rules are deployed verbatim in the proxy manifest, and the proxy
|
|
74
|
+
// decides WHICH credential KIND a path requires. Three kinds mirror the three old edge decisions:
|
|
75
|
+
// - public → no credential (the old `bypass`/everyone carve-out)
|
|
76
|
+
// - service → a machine `px_` key or passthrough JWT (the old `non_identity`/service-token gate)
|
|
77
|
+
// - human → a logged-in human via `px_session`/`px_token` (the old `allow`-by-audience gate)
|
|
78
|
+
// WHO is an admitted human stays centrally owned by propustka (decided at `/auth/callback`, the
|
|
79
|
+
// admission allowlist), exactly as the old central edge audience did — a `human` gate only asserts
|
|
80
|
+
// "a resolved user principal exists". Auth-surface paths (`/auth/*`, `/.well-known/jwks.json`) live
|
|
81
|
+
// on PROPUSTKA's host, not the app's, so apps never declare them.
|
|
82
|
+
|
|
83
|
+
/** Where a propustka credential (a `px_` key or a passthrough JWT) rides on a request. */
|
|
84
|
+
export interface CredentialLocation {
|
|
85
|
+
/** Transport carrying the credential. */
|
|
86
|
+
in: 'header' | 'query' | 'cookie'
|
|
87
|
+
/** Header / query-param / cookie name. A header value may be bare or `Bearer <token>`. */
|
|
88
|
+
name: string
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** What a matched path requires. The discriminant `kind` mirrors the three old edge decisions. */
|
|
92
|
+
export type GateKind =
|
|
93
|
+
/** Anyone — no credential. Terminal; resolves to an ANONYMOUS AuthContext (`principal: null`). */
|
|
94
|
+
| { kind: 'public' }
|
|
95
|
+
/**
|
|
96
|
+
* A machine `px_` key or a passthrough JWT — a bearer (default `Authorization: Bearer`) or the
|
|
97
|
+
* declared `credential` location. ABSENT → falls through to the next matching rule; PRESENT but
|
|
98
|
+
* invalid → fail closed (no fall-through).
|
|
99
|
+
*/
|
|
100
|
+
| { kind: 'service'; credential?: CredentialLocation }
|
|
101
|
+
/** A logged-in human (a `user` principal via the `px_session`/`px_token` cookies). */
|
|
102
|
+
| { kind: 'human' }
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* One per-path gate rule. The array order on `AppGates.rules` is the PRECEDENCE: the first rule whose
|
|
106
|
+
* `path` matches AND whose required credential is present is enforced. A matching rule whose credential
|
|
107
|
+
* is ABSENT falls through to the next matching rule; a request matching NO rule is denied (fail-closed).
|
|
108
|
+
* `path` is a glob where `*` matches any run of chars (e.g. `/api/v1/*`); anchored.
|
|
109
|
+
*/
|
|
110
|
+
export type GateRule = { path: string } & GateKind
|
|
111
|
+
|
|
112
|
+
/** An app's full per-path gate declaration, enforced by the Fabrika proxy. */
|
|
113
|
+
export interface AppGates {
|
|
114
|
+
rules: GateRule[]
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* App-aware role lookup. The worker layers a built-in cross-app source (admin) over a
|
|
119
|
+
* per-app DB source. `app` is the calling app id; null = cross-app/built-in only.
|
|
120
|
+
*/
|
|
121
|
+
export interface RoleSource {
|
|
122
|
+
getRole(app: string | null, key: string): RoleDef | undefined
|
|
123
|
+
listRoles(app: string | null): Record<string, RoleDef>
|
|
124
|
+
}
|
package/src/wire.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** Header carrying the proxy-verified access token to the upstream app. */
|
|
2
|
+
export const PROXY_TOKEN_HEADER = 'X-Fabrika-Token'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Header carrying the CLIENT COORDINATE the enforcement point observed — the only address an inner
|
|
6
|
+
* hop may key an abuse limit on.
|
|
7
|
+
*
|
|
8
|
+
* Owned exactly like `PROXY_TOKEN_HEADER`: the edge deletes a caller-supplied one and writes its own,
|
|
9
|
+
* so an upstream reading it is reading the edge and never the caller. It is deliberately NOT
|
|
10
|
+
* `X-Forwarded-For` — that name means "whatever the chain appended", and a value whose
|
|
11
|
+
* trustworthiness depends on where you are standing is exactly the key backlog 21 and 49 twice
|
|
12
|
+
* refused to build on ([sprint](../../../docs/archive/sprint-2026-08-05-auth-track-closeout.md)).
|
|
13
|
+
*
|
|
14
|
+
* Where a composition cannot observe the client the header is simply ABSENT, and the upstream then
|
|
15
|
+
* has no per-client bucket — today's behaviour — rather than a spoofable one.
|
|
16
|
+
*/
|
|
17
|
+
export const CLIENT_ADDRESS_HEADER = 'X-Fabrika-Client-Ip'
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The other names a client address travels under, deleted at ingress so `CLIENT_ADDRESS_HEADER` is the
|
|
21
|
+
* only one an upstream can read.
|
|
22
|
+
*
|
|
23
|
+
* Two reasons, and both matter. `X-Forwarded-For` is caller-writable on BOTH compositions — Caddy
|
|
24
|
+
* keeps a client-supplied prefix once the peer is trusted, and Cloudflare appends to whatever the
|
|
25
|
+
* caller sent — so a downstream reading it reads the caller. `CF-Connecting-IP` is genuinely
|
|
26
|
+
* trustworthy on Cloudflare's edge and a caller's invention anywhere else, which is worse: an app that
|
|
27
|
+
* reads it works on one cloud and silently keys on a forgery on the other. Deleting both leaves one
|
|
28
|
+
* header with one meaning everywhere, supplied only by the enforcement point.
|
|
29
|
+
*/
|
|
30
|
+
export const UNTRUSTED_FORWARD_HEADERS: readonly string[] = ['X-Forwarded-For', 'CF-Connecting-IP']
|