@fabrika/auth-core 0.3.3 → 0.4.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/package.json +1 -1
- package/src/app-environment.ts +44 -0
- package/src/canonical-path.ts +66 -0
- package/src/contract-canonical.ts +189 -0
- package/src/contract.ts +504 -0
- package/src/endpoint-digest.ts +141 -0
- package/src/endpoints.ts +292 -0
- package/src/framework-variables.ts +114 -0
- package/src/index.ts +14 -1
- package/src/installation-endpoint.ts +61 -0
- package/src/locale.ts +35 -0
- package/src/mail.ts +198 -0
- package/src/membership.ts +384 -0
- package/src/oauth.ts +50 -0
- package/src/path-segment.ts +9 -0
- package/src/requirement.ts +58 -0
- package/src/rpc.ts +22 -8
- package/src/sha256.ts +125 -0
- package/src/token.ts +255 -9
- package/src/types.ts +123 -43
- package/src/wire.ts +48 -0
- package/src/gates.ts +0 -29
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { APP_CALLER_PREFIX, CONNECT_PREFIX, type EndpointRequirement } from './contract'
|
|
2
|
+
import { type AuthenticatedRequirement, OAUTH_CALLER, type TokenCaller } from './installation-endpoint'
|
|
3
|
+
import { permits } from './permissions'
|
|
4
|
+
import type { AccessTokenClaims } from './token'
|
|
5
|
+
import type { PermissionEntry } from './types'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Whether a token's permissions meet an endpoint's requirement. This is authorization, not a gate: it reads only the
|
|
9
|
+
* token. `member` is any permission of this application; an action is that action in some scope, global included.
|
|
10
|
+
* The access form narrows it to one scope afterwards, against the application's own data. The `app` form is the
|
|
11
|
+
* action held as a global grant, so an entry scoped to any value does not meet it. `authenticated`, which only an
|
|
12
|
+
* installation row carries, needs no permission.
|
|
13
|
+
*/
|
|
14
|
+
export function satisfies(requirement: EndpointRequirement | AuthenticatedRequirement, perms: readonly PermissionEntry[]): boolean {
|
|
15
|
+
if (requirement.kind === 'authenticated') {
|
|
16
|
+
return true
|
|
17
|
+
}
|
|
18
|
+
if (requirement.kind === 'member') {
|
|
19
|
+
return perms.length > 0
|
|
20
|
+
}
|
|
21
|
+
if (requirement.access.form === 'app') {
|
|
22
|
+
return perms.some((entry) => permits([entry], requirement.action))
|
|
23
|
+
}
|
|
24
|
+
return perms.some((entry) => permits([entry], requirement.action, entry.scope ?? undefined))
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The caller kind a verified token presents: a `user` principal is `human`, a `service` principal is `machine`, a
|
|
29
|
+
* connector key of application `<id>` is `app:<id>`, and a token bound to no principal is a share link. An OAuth
|
|
30
|
+
* resource token is `oauth`, which only an installation row admits. A job or webhook token is no caller: `null` is
|
|
31
|
+
* refused by every endpoint.
|
|
32
|
+
*/
|
|
33
|
+
export function callerOf(claims: AccessTokenClaims): TokenCaller | null {
|
|
34
|
+
if (claims.oauth !== undefined) {
|
|
35
|
+
return OAUTH_CALLER
|
|
36
|
+
}
|
|
37
|
+
switch (claims.ptype) {
|
|
38
|
+
case 'user':
|
|
39
|
+
return 'human'
|
|
40
|
+
case 'service':
|
|
41
|
+
return 'machine'
|
|
42
|
+
case 'app':
|
|
43
|
+
return claims.workload === undefined ? null : `app:${claims.workload}`
|
|
44
|
+
case 'job':
|
|
45
|
+
case 'webhook':
|
|
46
|
+
return null
|
|
47
|
+
case undefined:
|
|
48
|
+
return 'link'
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Whether a caller may be admitted at an endpoint path. A connector caller `app:<id>` reaches only an export's paths
|
|
54
|
+
* (ADR-0022 "Principal kinds"); every other caller is not limited by the path.
|
|
55
|
+
*/
|
|
56
|
+
export function callerAdmittedAt(caller: TokenCaller, path: string): boolean {
|
|
57
|
+
return !caller.startsWith(APP_CALLER_PREFIX) || path.startsWith(`${CONNECT_PREFIX}/`)
|
|
58
|
+
}
|
package/src/rpc.ts
CHANGED
|
@@ -30,7 +30,8 @@ export interface MintTokenInput {
|
|
|
30
30
|
export type MintTokenResult =
|
|
31
31
|
/** `expiresAt` (unix seconds) lets the SDK refresh ahead of expiry. */
|
|
32
32
|
| { ok: true; token: string; expiresAt: number }
|
|
33
|
-
|
|
33
|
+
/** `token_too_large`: the principal holds more than fits in one header; a decided refusal, never a login bounce. */
|
|
34
|
+
| { ok: false; reason: 'no_session' | 'invalid_session' | 'unknown_principal' | 'disabled' | 'token_too_large' }
|
|
34
35
|
|
|
35
36
|
// ── propustka-native key auth (mint an access token from an opaque `px_` credential) ──
|
|
36
37
|
//
|
|
@@ -50,7 +51,7 @@ export interface MintFromKeyInput {
|
|
|
50
51
|
|
|
51
52
|
export type MintFromKeyResult =
|
|
52
53
|
| { ok: true; token: string; expiresAt: number }
|
|
53
|
-
| { ok: false; reason: 'invalid_key' | 'unknown_principal' | 'disabled' }
|
|
54
|
+
| { ok: false; reason: 'invalid_key' | 'unknown_principal' | 'disabled' | 'token_too_large' }
|
|
54
55
|
|
|
55
56
|
// ── Session handoff (ADR-0022, ADR-0023) ──────────────────────────────────────
|
|
56
57
|
//
|
|
@@ -171,10 +172,17 @@ export interface IssueKeyInput {
|
|
|
171
172
|
/** Inline grants — the frozen set (standalone) and/or a downscope restriction (bound). */
|
|
172
173
|
permissions?: KeyGrant[]
|
|
173
174
|
label?: string
|
|
174
|
-
/** Absolute credential expiry (unix seconds)
|
|
175
|
-
expiresAt
|
|
175
|
+
/** Absolute credential expiry (unix seconds), after now and at most `MAX_KEY_LIFETIME_SECONDS` ahead. */
|
|
176
|
+
expiresAt: number
|
|
176
177
|
}
|
|
177
178
|
|
|
179
|
+
/**
|
|
180
|
+
* The longest a `px_` credential `issueKey` writes may live, in every mode. A key is a standing copy
|
|
181
|
+
* of authority that outlives any token it was issued from, so it must end; 30 days is also the
|
|
182
|
+
* builder's device-authorized key lifetime.
|
|
183
|
+
*/
|
|
184
|
+
export const MAX_KEY_LIFETIME_SECONDS = 30 * 24 * 60 * 60
|
|
185
|
+
|
|
178
186
|
export type IssueKeyResult =
|
|
179
187
|
/**
|
|
180
188
|
* Plaintext `px_` token returned ONCE; `id` is the credential's stable handle (revoke). `principalId`
|
|
@@ -198,7 +206,11 @@ export interface ResolvedPrincipal {
|
|
|
198
206
|
}
|
|
199
207
|
|
|
200
208
|
export interface AuditInput {
|
|
201
|
-
|
|
209
|
+
/**
|
|
210
|
+
* The caller's verified access token — the one the proxy injected. IAM verifies it and records
|
|
211
|
+
* the app it was minted for; there is no `app` field, so a caller cannot name another app.
|
|
212
|
+
*/
|
|
213
|
+
credential: string
|
|
202
214
|
requestId: string
|
|
203
215
|
/** NULL for an anonymous-credential event (a share link has no principal). */
|
|
204
216
|
principalId: string | null
|
|
@@ -288,7 +300,8 @@ export interface IamRpc {
|
|
|
288
300
|
mintFromKey(input: MintFromKeyInput): Promise<MintFromKeyResult>
|
|
289
301
|
/**
|
|
290
302
|
* Mint an opaque, stored, revocable `px_` credential (API key / share link). Delegated: the issuer
|
|
291
|
-
* is resolved from the forwarded credentials and may only grant what it holds
|
|
303
|
+
* is resolved from the forwarded credentials and may only grant what it holds, only exact actions of the
|
|
304
|
+
* app's catalog, and only with an expiry inside `MAX_KEY_LIFETIME_SECONDS`. Returns the
|
|
292
305
|
* plaintext token ONCE; `id` is the durable handle for revoke.
|
|
293
306
|
*/
|
|
294
307
|
issueKey(input: IssueKeyInput): Promise<IssueKeyResult>
|
|
@@ -307,8 +320,9 @@ export interface IamRpc {
|
|
|
307
320
|
listPrincipals(input: ListPrincipalsInput): Promise<ListPrincipalsResult>
|
|
308
321
|
/**
|
|
309
322
|
* Revoke a previously-issued opaque `px_` credential (an API key / share link) by id. The caller
|
|
310
|
-
* is resolved from the forwarded Access credentials and authorized: the
|
|
311
|
-
*
|
|
323
|
+
* is resolved from the forwarded Access credentials and authorized: the credential must be bound to
|
|
324
|
+
* the caller's verified app (any other is `not_found`); then the original issuer may always revoke,
|
|
325
|
+
* and otherwise, for an anonymous credential, the caller must hold every granted action (an
|
|
312
326
|
* admin / app-wide operator). Idempotent — revoking an already-revoked credential returns
|
|
313
327
|
* `{ ok: true, revoked: false }`. An unknown id returns `{ ok: false, reason: 'not_found' }`.
|
|
314
328
|
*/
|
package/src/sha256.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// SHA-256 (FIPS 180-4), synchronous. WebCrypto's `digest` is asynchronous, and the digests of a contract are checked
|
|
2
|
+
// where nothing may wait: a zod refinement of the proxy manifest and the application's synchronous `boot`.
|
|
3
|
+
|
|
4
|
+
const ROUND_CONSTANTS = new Uint32Array([
|
|
5
|
+
0x428a2f98,
|
|
6
|
+
0x71374491,
|
|
7
|
+
0xb5c0fbcf,
|
|
8
|
+
0xe9b5dba5,
|
|
9
|
+
0x3956c25b,
|
|
10
|
+
0x59f111f1,
|
|
11
|
+
0x923f82a4,
|
|
12
|
+
0xab1c5ed5,
|
|
13
|
+
0xd807aa98,
|
|
14
|
+
0x12835b01,
|
|
15
|
+
0x243185be,
|
|
16
|
+
0x550c7dc3,
|
|
17
|
+
0x72be5d74,
|
|
18
|
+
0x80deb1fe,
|
|
19
|
+
0x9bdc06a7,
|
|
20
|
+
0xc19bf174,
|
|
21
|
+
0xe49b69c1,
|
|
22
|
+
0xefbe4786,
|
|
23
|
+
0x0fc19dc6,
|
|
24
|
+
0x240ca1cc,
|
|
25
|
+
0x2de92c6f,
|
|
26
|
+
0x4a7484aa,
|
|
27
|
+
0x5cb0a9dc,
|
|
28
|
+
0x76f988da,
|
|
29
|
+
0x983e5152,
|
|
30
|
+
0xa831c66d,
|
|
31
|
+
0xb00327c8,
|
|
32
|
+
0xbf597fc7,
|
|
33
|
+
0xc6e00bf3,
|
|
34
|
+
0xd5a79147,
|
|
35
|
+
0x06ca6351,
|
|
36
|
+
0x14292967,
|
|
37
|
+
0x27b70a85,
|
|
38
|
+
0x2e1b2138,
|
|
39
|
+
0x4d2c6dfc,
|
|
40
|
+
0x53380d13,
|
|
41
|
+
0x650a7354,
|
|
42
|
+
0x766a0abb,
|
|
43
|
+
0x81c2c92e,
|
|
44
|
+
0x92722c85,
|
|
45
|
+
0xa2bfe8a1,
|
|
46
|
+
0xa81a664b,
|
|
47
|
+
0xc24b8b70,
|
|
48
|
+
0xc76c51a3,
|
|
49
|
+
0xd192e819,
|
|
50
|
+
0xd6990624,
|
|
51
|
+
0xf40e3585,
|
|
52
|
+
0x106aa070,
|
|
53
|
+
0x19a4c116,
|
|
54
|
+
0x1e376c08,
|
|
55
|
+
0x2748774c,
|
|
56
|
+
0x34b0bcb5,
|
|
57
|
+
0x391c0cb3,
|
|
58
|
+
0x4ed8aa4a,
|
|
59
|
+
0x5b9cca4f,
|
|
60
|
+
0x682e6ff3,
|
|
61
|
+
0x748f82ee,
|
|
62
|
+
0x78a5636f,
|
|
63
|
+
0x84c87814,
|
|
64
|
+
0x8cc70208,
|
|
65
|
+
0x90befffa,
|
|
66
|
+
0xa4506ceb,
|
|
67
|
+
0xbef9a3f7,
|
|
68
|
+
0xc67178f2,
|
|
69
|
+
])
|
|
70
|
+
|
|
71
|
+
const INITIAL_HASH = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]
|
|
72
|
+
|
|
73
|
+
function rotateRight(value: number, bits: number): number {
|
|
74
|
+
return (value >>> bits) | (value << (32 - bits))
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The SHA-256 of `text`'s UTF-8 bytes, as 64 lower-case hex digits. */
|
|
78
|
+
export function sha256Hex(text: string): string {
|
|
79
|
+
const bytes = new TextEncoder().encode(text)
|
|
80
|
+
// The message, a 0x80 byte, zero padding and the 64-bit bit length fill whole 64-byte blocks.
|
|
81
|
+
const padded = new Uint8Array(Math.ceil((bytes.length + 9) / 64) * 64)
|
|
82
|
+
padded.set(bytes)
|
|
83
|
+
padded[bytes.length] = 0x80
|
|
84
|
+
const view = new DataView(padded.buffer)
|
|
85
|
+
const bitLength = bytes.length * 8
|
|
86
|
+
view.setUint32(padded.length - 8, Math.floor(bitLength / 0x1_0000_0000))
|
|
87
|
+
view.setUint32(padded.length - 4, bitLength >>> 0)
|
|
88
|
+
|
|
89
|
+
const hash = new Uint32Array(INITIAL_HASH)
|
|
90
|
+
const schedule = new Uint32Array(64)
|
|
91
|
+
for (let offset = 0; offset < padded.length; offset += 64) {
|
|
92
|
+
for (let index = 0; index < 16; index++) {
|
|
93
|
+
schedule[index] = view.getUint32(offset + index * 4)
|
|
94
|
+
}
|
|
95
|
+
for (let index = 16; index < 64; index++) {
|
|
96
|
+
const early = schedule[index - 15] ?? 0
|
|
97
|
+
const late = schedule[index - 2] ?? 0
|
|
98
|
+
const sigma0 = rotateRight(early, 7) ^ rotateRight(early, 18) ^ (early >>> 3)
|
|
99
|
+
const sigma1 = rotateRight(late, 17) ^ rotateRight(late, 19) ^ (late >>> 10)
|
|
100
|
+
schedule[index] = (schedule[index - 16] ?? 0) + sigma0 + (schedule[index - 7] ?? 0) + sigma1
|
|
101
|
+
}
|
|
102
|
+
let [a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0] = hash
|
|
103
|
+
for (let index = 0; index < 64; index++) {
|
|
104
|
+
const sum1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25)
|
|
105
|
+
const choice = (e & f) ^ (~e & g)
|
|
106
|
+
const first = (h + sum1 + choice + (ROUND_CONSTANTS[index] ?? 0) + (schedule[index] ?? 0)) >>> 0
|
|
107
|
+
const sum0 = rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22)
|
|
108
|
+
const majority = (a & b) ^ (a & c) ^ (b & c)
|
|
109
|
+
const second = (sum0 + majority) >>> 0
|
|
110
|
+
h = g
|
|
111
|
+
g = f
|
|
112
|
+
f = e
|
|
113
|
+
e = (d + first) >>> 0
|
|
114
|
+
d = c
|
|
115
|
+
c = b
|
|
116
|
+
b = a
|
|
117
|
+
a = (first + second) >>> 0
|
|
118
|
+
}
|
|
119
|
+
const round = [a, b, c, d, e, f, g, h]
|
|
120
|
+
for (const [index, value] of round.entries()) {
|
|
121
|
+
hash[index] = (hash[index] ?? 0) + value
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return Array.from(hash, (word) => word.toString(16).padStart(8, '0')).join('')
|
|
125
|
+
}
|
package/src/token.ts
CHANGED
|
@@ -23,8 +23,10 @@
|
|
|
23
23
|
*/
|
|
24
24
|
|
|
25
25
|
import { numberField, prop, stringField } from './json'
|
|
26
|
+
import { isNormalizedMailbox } from './membership'
|
|
27
|
+
import { isCimdClientId, isOAuthResourceUri, parseOAuthScopes } from './oauth'
|
|
26
28
|
import type { ResolvedPrincipal } from './rpc'
|
|
27
|
-
import type
|
|
29
|
+
import { isWorkloadKind, type PermissionEntry, type PermissionSource, type Scope, type TokenPrincipalType } from './types'
|
|
28
30
|
|
|
29
31
|
// ── Names & knobs on the wire (both sides agree) ───────────────────────────────
|
|
30
32
|
|
|
@@ -47,8 +49,16 @@ export const SESSION_COOKIE = `${FABRIKA_COOKIE_PREFIX}session`
|
|
|
47
49
|
/** Prefix marking a propustka opaque credential (API key / share link), e.g. `Bearer px_<random>`. */
|
|
48
50
|
export const API_KEY_PREFIX = 'px_'
|
|
49
51
|
|
|
52
|
+
/**
|
|
53
|
+
* Where a job or a webhook exchanges its own `px_` key for an access token at IAM's public origin: `POST` with the key
|
|
54
|
+
* as the bearer and `{ app }` as the body. IAM answers `MintFromKeyResult`, and only for a workload key of that app.
|
|
55
|
+
*/
|
|
56
|
+
export const WORKLOAD_TOKEN_PATH = '/auth/workload/token'
|
|
57
|
+
|
|
50
58
|
/** Signing algorithm propustka issues with and the SDK verifies (ECDSA P-256 — compact, ubiquitous). */
|
|
51
59
|
export const TOKEN_ALG = 'ES256'
|
|
60
|
+
/** JWT `typ` of an OAuth resource access token (RFC 9068). Native app tokens carry no `typ`. */
|
|
61
|
+
export const RESOURCE_ACCESS_TOKEN_TYP = 'at+jwt'
|
|
52
62
|
|
|
53
63
|
/** Default per-app access-token lifetime. Revocation/role changes take effect within this. */
|
|
54
64
|
export const DEFAULT_TOKEN_TTL_SECONDS = 300
|
|
@@ -58,6 +68,14 @@ export const DEFAULT_TOKEN_TTL_SECONDS = 300
|
|
|
58
68
|
*/
|
|
59
69
|
export const TOKEN_REFRESH_SKEW_SECONDS = 30
|
|
60
70
|
|
|
71
|
+
/**
|
|
72
|
+
* The largest access token IAM signs, in bytes (a JWT is ASCII). The proxy forwards it as one header,
|
|
73
|
+
* and Bun's server, the application's runtime on Zerops, refuses a request whose headers exceed 16 KiB
|
|
74
|
+
* in total; 8 KiB leaves the rest for the request's own headers and cookies. Caddy (1 MiB) and
|
|
75
|
+
* Cloudflare (128 KiB) allow more.
|
|
76
|
+
*/
|
|
77
|
+
export const MAX_ACCESS_TOKEN_BYTES = 8192
|
|
78
|
+
|
|
61
79
|
// ── Claim shape (one, no discriminator) ────────────────────────────────────────
|
|
62
80
|
|
|
63
81
|
/**
|
|
@@ -79,11 +97,66 @@ export interface AccessTokenClaims {
|
|
|
79
97
|
/** Resolved/effective permissions; `can(action, scope?)` = `permits(perms, action, scope)`. */
|
|
80
98
|
perms: PermissionEntry[]
|
|
81
99
|
/** Present only when the token is bound to a principal (`sub` is that principal). */
|
|
82
|
-
ptype?:
|
|
100
|
+
ptype?: TokenPrincipalType
|
|
101
|
+
/**
|
|
102
|
+
* Present exactly when `ptype` is a workload kind: the job's or the webhook's name, or for `app` the id of the
|
|
103
|
+
* consuming application, which the proxy admits as the caller `app:<id>`.
|
|
104
|
+
*/
|
|
105
|
+
workload?: string
|
|
83
106
|
/** Audit actor label — the principal's label, or the credential label, or null (anonymous). */
|
|
84
107
|
label: string | null
|
|
108
|
+
/**
|
|
109
|
+
* Only on a user token: the mailbox IAM recorded for the principal (`principals.email`, `normalizeEmailIdentity`).
|
|
110
|
+
* The signature authenticates that IAM recorded it, not that the person controls it. A user's `label` is that
|
|
111
|
+
* address as it was spelled, never a substitute for it.
|
|
112
|
+
*/
|
|
113
|
+
email?: string
|
|
114
|
+
/**
|
|
115
|
+
* Present only on a principal token IAM minted from a signed-in session (`mintToken`). A token minted from a `px_`
|
|
116
|
+
* key carries what the key's own grants narrow, so a check that resolves the person's permissions requires this.
|
|
117
|
+
*/
|
|
118
|
+
session?: true
|
|
119
|
+
/** Present only on an OAuth resource token (`aud` is then a resource URI, not an app id). */
|
|
120
|
+
oauth?: OAuthTokenClaims
|
|
121
|
+
/** Present only on a share-link token, which has no `ptype`: `sub` is then the link key's id. */
|
|
122
|
+
link?: LinkTokenClaims
|
|
85
123
|
}
|
|
86
124
|
|
|
125
|
+
/** What a share-link token adds: the link mount that issued the key and the chain the key is bound to. */
|
|
126
|
+
export interface LinkTokenClaims {
|
|
127
|
+
mount: string
|
|
128
|
+
/** The bound object first, then each value containing it, outward. */
|
|
129
|
+
chain: Scope[]
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The principal kind of a token (ADR-0022 rule 3): a user or a service principal, a workload, or a share link. Null
|
|
134
|
+
* for an anonymous credential that is not a link, which no contract mount admits.
|
|
135
|
+
*/
|
|
136
|
+
export type PrincipalKind = TokenPrincipalType | 'link'
|
|
137
|
+
|
|
138
|
+
export function principalKind(claims: AccessTokenClaims): PrincipalKind | null {
|
|
139
|
+
if (claims.ptype !== undefined) return claims.ptype
|
|
140
|
+
return claims.link === undefined ? null : 'link'
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** What an OAuth resource token adds: the signed app coordinate and the grant it was minted from. */
|
|
144
|
+
export interface OAuthTokenClaims {
|
|
145
|
+
/** The app whose permissions `perms` are; `aud` names the resource URI instead. */
|
|
146
|
+
app: string
|
|
147
|
+
/** CIMD URL of the MCP client the user consented to. */
|
|
148
|
+
clientId: string
|
|
149
|
+
/** Consented scopes; `perms` is already narrowed by them. */
|
|
150
|
+
scopes: string[]
|
|
151
|
+
/** IAM's OAuth grant id — revoking it stops refresh. */
|
|
152
|
+
grantId: string
|
|
153
|
+
/** Unique token id, fresh on every mint. */
|
|
154
|
+
tokenId: string
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Which tokens a verifier accepts: native app tokens, or OAuth tokens minted for one resource of one app. */
|
|
158
|
+
export type TokenAudienceProfile = { kind: 'app'; app: string } | { kind: 'resource'; app: string; resource: string }
|
|
159
|
+
|
|
87
160
|
// ── Public JWKS (the SDK fetches this once, then verifies tokens locally) ───────
|
|
88
161
|
//
|
|
89
162
|
// Transport is the IAM service binding (`getJwks()` RPC), NOT a public HTTPS URL: app↔IAM is
|
|
@@ -117,12 +190,66 @@ export interface AccessTokenParams {
|
|
|
117
190
|
/** Subject id (becomes `sub`) — a principal id when `type` is given, else a credential id. */
|
|
118
191
|
subject: string
|
|
119
192
|
/** Principal type — omit for an anonymous credential (share link). */
|
|
120
|
-
type?:
|
|
193
|
+
type?: TokenPrincipalType
|
|
194
|
+
/** The workload's name; required with a workload `type`, refused with any other. */
|
|
195
|
+
workload?: string
|
|
121
196
|
/** Audit actor label, or null for an unlabeled anonymous token. */
|
|
122
197
|
label: string | null
|
|
198
|
+
/** A user principal's normalized mailbox; refused with any other `type`. */
|
|
199
|
+
email?: string
|
|
200
|
+
/** Minted from a signed-in session; refused on a token without `type` or of a workload. */
|
|
201
|
+
session?: true
|
|
202
|
+
permissions: PermissionEntry[]
|
|
203
|
+
issuedAt: number
|
|
204
|
+
expiresAt: number
|
|
205
|
+
/** A share-link key's mount and chain; only on a token without `type`. */
|
|
206
|
+
link?: LinkTokenClaims
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export interface ResourceAccessTokenParams {
|
|
210
|
+
iss: string
|
|
211
|
+
app: string
|
|
212
|
+
resource: string
|
|
213
|
+
subject: string
|
|
214
|
+
label: string | null
|
|
123
215
|
permissions: PermissionEntry[]
|
|
124
216
|
issuedAt: number
|
|
125
217
|
expiresAt: number
|
|
218
|
+
clientId: string
|
|
219
|
+
scopes: string[]
|
|
220
|
+
grantId: string
|
|
221
|
+
tokenId: string
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Assemble an OAuth resource access token. Always a user principal. The wire carries the standard
|
|
226
|
+
* `client_id`/`scope`/`jti` claims plus Fabrika's `app` and `grant`; the caller signs with
|
|
227
|
+
* `typ: RESOURCE_ACCESS_TOKEN_TYP`.
|
|
228
|
+
*/
|
|
229
|
+
export function buildResourceAccessClaims(params: ResourceAccessTokenParams): Record<string, unknown> {
|
|
230
|
+
const payload = {
|
|
231
|
+
iss: params.iss,
|
|
232
|
+
aud: params.resource,
|
|
233
|
+
sub: params.subject,
|
|
234
|
+
iat: params.issuedAt,
|
|
235
|
+
exp: params.expiresAt,
|
|
236
|
+
perms: params.permissions,
|
|
237
|
+
ptype: 'user',
|
|
238
|
+
label: params.label,
|
|
239
|
+
app: params.app,
|
|
240
|
+
client_id: params.clientId,
|
|
241
|
+
scope: params.scopes.join(' '),
|
|
242
|
+
grant: params.grantId,
|
|
243
|
+
jti: params.tokenId,
|
|
244
|
+
}
|
|
245
|
+
if (parseAccessClaims(payload)?.oauth === undefined) throw new Error('Invalid resource access token claims')
|
|
246
|
+
return payload
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** A token is accepted only by the profile it was minted for: an app token never passes as a resource token, and vice versa. */
|
|
250
|
+
export function matchesTokenAudience(claims: AccessTokenClaims, profile: TokenAudienceProfile): boolean {
|
|
251
|
+
if (profile.kind === 'app') return claims.oauth === undefined && claims.aud === profile.app
|
|
252
|
+
return claims.oauth !== undefined && claims.aud === profile.resource && claims.oauth.app === profile.app
|
|
126
253
|
}
|
|
127
254
|
|
|
128
255
|
/** Assemble the claim object for an access token. Pure — the caller signs the result. */
|
|
@@ -139,6 +266,26 @@ export function buildAccessClaims(params: AccessTokenParams): AccessTokenClaims
|
|
|
139
266
|
if (params.type !== undefined) {
|
|
140
267
|
claims.ptype = params.type
|
|
141
268
|
}
|
|
269
|
+
if (isWorkloadKind(params.type) !== (params.workload !== undefined) || (params.workload !== undefined && !isWorkloadName(params.workload))) {
|
|
270
|
+
throw new Error('A workload token names its workload, and only a workload token does')
|
|
271
|
+
}
|
|
272
|
+
if (params.workload !== undefined) {
|
|
273
|
+
claims.workload = params.workload
|
|
274
|
+
}
|
|
275
|
+
if (params.email !== undefined) {
|
|
276
|
+
if (params.type !== 'user' || !isNormalizedMailbox(params.email)) {
|
|
277
|
+
throw new Error('Only a user token carries a mailbox, and only a normalized one')
|
|
278
|
+
}
|
|
279
|
+
claims.email = params.email
|
|
280
|
+
}
|
|
281
|
+
if (params.session !== undefined) {
|
|
282
|
+
if (params.type === undefined || isWorkloadKind(params.type)) throw new Error("Only a person's or a service's token is minted from a session")
|
|
283
|
+
claims.session = params.session
|
|
284
|
+
}
|
|
285
|
+
if (params.link !== undefined) {
|
|
286
|
+
if (params.type !== undefined) throw new Error('A share-link token has no principal type')
|
|
287
|
+
claims.link = { mount: params.link.mount, chain: params.link.chain.map((scope) => ({ type: scope.type, value: scope.value })) }
|
|
288
|
+
}
|
|
142
289
|
return claims
|
|
143
290
|
}
|
|
144
291
|
|
|
@@ -164,20 +311,119 @@ export function parseAccessClaims(payload: unknown): AccessTokenClaims | null {
|
|
|
164
311
|
if (perms === null || label === undefined || ptype === undefined) {
|
|
165
312
|
return null
|
|
166
313
|
}
|
|
314
|
+
const oauth = parseOAuthClaims(payload)
|
|
315
|
+
if (oauth === undefined || (oauth !== null && (ptype !== 'user' || !isOAuthResourceUri(aud)))) {
|
|
316
|
+
return null
|
|
317
|
+
}
|
|
318
|
+
const link = parseLinkClaims(prop(payload, 'link'))
|
|
319
|
+
if (link === undefined || (link !== null && (ptype !== null || oauth !== null))) {
|
|
320
|
+
return null
|
|
321
|
+
}
|
|
322
|
+
const workload = parseWorkload(prop(payload, 'workload'), ptype)
|
|
323
|
+
if (workload === undefined) {
|
|
324
|
+
return null
|
|
325
|
+
}
|
|
326
|
+
const email = parseEmail(prop(payload, 'email'), ptype)
|
|
327
|
+
if (email === undefined) {
|
|
328
|
+
return null
|
|
329
|
+
}
|
|
330
|
+
const session = prop(payload, 'session')
|
|
331
|
+
if (session !== undefined && (session !== true || ptype === null || isWorkloadKind(ptype) || oauth !== null)) {
|
|
332
|
+
return null
|
|
333
|
+
}
|
|
167
334
|
const claims: AccessTokenClaims = { iss, aud, sub, iat, exp, perms, label }
|
|
168
335
|
if (ptype !== null) {
|
|
169
336
|
claims.ptype = ptype
|
|
170
337
|
}
|
|
338
|
+
if (workload !== null) {
|
|
339
|
+
claims.workload = workload
|
|
340
|
+
}
|
|
341
|
+
if (email !== null) {
|
|
342
|
+
claims.email = email
|
|
343
|
+
}
|
|
344
|
+
if (session === true) {
|
|
345
|
+
claims.session = true
|
|
346
|
+
}
|
|
347
|
+
if (oauth !== null) {
|
|
348
|
+
claims.oauth = oauth
|
|
349
|
+
}
|
|
350
|
+
if (link !== null) {
|
|
351
|
+
claims.link = link
|
|
352
|
+
}
|
|
171
353
|
return claims
|
|
172
354
|
}
|
|
173
355
|
|
|
356
|
+
/** A job, webhook or mount name, or an application id. */
|
|
357
|
+
const WORKLOAD_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/
|
|
358
|
+
|
|
359
|
+
function isWorkloadName(value: string): boolean {
|
|
360
|
+
return WORKLOAD_NAME.test(value)
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** A workload kind requires its name and every other kind refuses one: the name → the name, none → null, else undefined. */
|
|
364
|
+
function parseWorkload(value: unknown, ptype: TokenPrincipalType | null): string | null | undefined {
|
|
365
|
+
if (!isWorkloadKind(ptype)) {
|
|
366
|
+
return value === undefined ? null : undefined
|
|
367
|
+
}
|
|
368
|
+
return typeof value === 'string' && isWorkloadName(value) ? value : undefined
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** Absent → null; a normalized mailbox on a user token → it; anything else → undefined. */
|
|
372
|
+
function parseEmail(value: unknown, ptype: TokenPrincipalType | null): string | null | undefined {
|
|
373
|
+
if (value === undefined) {
|
|
374
|
+
return null
|
|
375
|
+
}
|
|
376
|
+
return ptype === 'user' && typeof value === 'string' && isNormalizedMailbox(value) ? value : undefined
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** Absent → null; a mount and a non-empty chain → the claims; anything else → undefined. */
|
|
380
|
+
function parseLinkClaims(value: unknown): LinkTokenClaims | null | undefined {
|
|
381
|
+
if (value === undefined) {
|
|
382
|
+
return null
|
|
383
|
+
}
|
|
384
|
+
const mount = stringField(value, 'mount')
|
|
385
|
+
const rawChain = prop(value, 'chain')
|
|
386
|
+
if (mount === undefined || mount === '' || !Array.isArray(rawChain) || rawChain.length === 0) {
|
|
387
|
+
return undefined
|
|
388
|
+
}
|
|
389
|
+
const chain: Scope[] = []
|
|
390
|
+
for (const item of rawChain) {
|
|
391
|
+
const scope = parseScope(item)
|
|
392
|
+
if (scope === null || scope === undefined) {
|
|
393
|
+
return undefined
|
|
394
|
+
}
|
|
395
|
+
chain.push(scope)
|
|
396
|
+
}
|
|
397
|
+
return { mount, chain }
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** Absent OAuth claims → null; complete and valid → the claims; partial or malformed → undefined. */
|
|
401
|
+
function parseOAuthClaims(payload: unknown): OAuthTokenClaims | null | undefined {
|
|
402
|
+
const app = prop(payload, 'app')
|
|
403
|
+
const clientId = prop(payload, 'client_id')
|
|
404
|
+
const scope = prop(payload, 'scope')
|
|
405
|
+
const grantId = prop(payload, 'grant')
|
|
406
|
+
const tokenId = prop(payload, 'jti')
|
|
407
|
+
if (app === undefined && clientId === undefined && scope === undefined && grantId === undefined && tokenId === undefined) {
|
|
408
|
+
return null
|
|
409
|
+
}
|
|
410
|
+
const scopes = typeof scope === 'string' ? parseOAuthScopes(scope.split(' ')) : null
|
|
411
|
+
if (
|
|
412
|
+
typeof app !== 'string' || app === '' || !isCimdClientId(clientId) || scopes === null || typeof grantId !== 'string' || grantId === ''
|
|
413
|
+
|| typeof tokenId !== 'string' || tokenId === ''
|
|
414
|
+
) {
|
|
415
|
+
return undefined
|
|
416
|
+
}
|
|
417
|
+
return { app, clientId, scopes, grantId, tokenId }
|
|
418
|
+
}
|
|
419
|
+
|
|
174
420
|
/**
|
|
175
421
|
* Map a verified PRINCIPAL-bound access token into the `ResolvedPrincipal` the existing
|
|
176
|
-
* `AuthContext` consumes. Returns null for an anonymous token (no `ptype`)
|
|
177
|
-
* the
|
|
422
|
+
* `AuthContext` consumes. Returns null for an anonymous token (no `ptype`) and for a workload token,
|
|
423
|
+
* which no `AuthContext` represents — the caller handles both separately.
|
|
178
424
|
*/
|
|
179
425
|
export function accessClaimsToResolved(claims: AccessTokenClaims, requestId: string): ResolvedPrincipal | null {
|
|
180
|
-
if (claims.ptype === undefined) {
|
|
426
|
+
if (claims.ptype === undefined || isWorkloadKind(claims.ptype)) {
|
|
181
427
|
return null
|
|
182
428
|
}
|
|
183
429
|
return {
|
|
@@ -191,12 +437,12 @@ export function accessClaimsToResolved(claims: AccessTokenClaims, requestId: str
|
|
|
191
437
|
|
|
192
438
|
// ── Structural parsers (no `as`) ───────────────────────────────────────────────
|
|
193
439
|
|
|
194
|
-
/** Read `ptype`: a valid principal
|
|
195
|
-
function parseOptionalPrincipalType(value: unknown):
|
|
440
|
+
/** Read `ptype`: a valid principal kind, explicit-absent (→ null), or malformed or unknown (→ undefined). */
|
|
441
|
+
function parseOptionalPrincipalType(value: unknown): TokenPrincipalType | null | undefined {
|
|
196
442
|
if (value === undefined || value === null) {
|
|
197
443
|
return null
|
|
198
444
|
}
|
|
199
|
-
return value === 'user' || value === 'service' ? value : undefined
|
|
445
|
+
return value === 'user' || value === 'service' || isWorkloadKind(value) ? value : undefined
|
|
200
446
|
}
|
|
201
447
|
|
|
202
448
|
/** Accept a string or explicit-null/absent (→ null); reject any other type (→ undefined). */
|