@coffre/core 0.14.7 → 0.16.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.
Files changed (56) hide show
  1. package/README.md +1 -1
  2. package/dist/{access-BrdZKp1d.js → access-CF8UG59J.js} +70 -8
  3. package/dist/{access-qkMZa-6Z.d.ts → access-ERdGGHG7.d.ts} +45 -3
  4. package/dist/access.d.ts +2 -2
  5. package/dist/access.js +2 -2
  6. package/dist/envelope.d.ts +28 -9
  7. package/dist/envelope.js +25 -8
  8. package/dist/identity.d.ts +2 -917
  9. package/dist/identity.js +1036 -525
  10. package/dist/index-DuG9p3GH.d.ts +1233 -0
  11. package/dist/kek.d.ts +10 -16
  12. package/dist/kek.js +26 -41
  13. package/dist/log.d.ts +114 -0
  14. package/dist/log.js +291 -0
  15. package/dist/mcp.d.ts +25 -1
  16. package/dist/mcp.js +29 -4
  17. package/dist/recipe-BgJpmJum.d.ts +128 -0
  18. package/dist/recipe.d.ts +2 -127
  19. package/dist/{registry-D7X-x202.d.ts → registry-B7_LUDsJ.d.ts} +30 -5
  20. package/dist/schemas.d.ts +14 -4
  21. package/dist/schemas.js +16 -4
  22. package/dist/{types-Cp3lB_-W.js → types-DwTO_b4H.js} +17 -5
  23. package/dist/vault.d.ts +1800 -299
  24. package/dist/vault.js +99 -32
  25. package/package.json +8 -3
  26. package/src/access.ts +63 -8
  27. package/src/changes/access.ts +140 -0
  28. package/src/changes/freezes.ts +40 -0
  29. package/src/changes/mcp.ts +150 -0
  30. package/src/changes/places.ts +219 -0
  31. package/src/changes/secrets.ts +235 -0
  32. package/src/changes/signin.ts +197 -0
  33. package/src/changes/workloads.ts +166 -0
  34. package/src/context.ts +18 -2
  35. package/src/envelope.ts +35 -12
  36. package/src/identity/auth.ts +11 -3
  37. package/src/identity/aws.ts +62 -0
  38. package/src/identity/github-app.ts +45 -24
  39. package/src/identity/index.ts +3 -0
  40. package/src/identity/profiles.ts +139 -0
  41. package/src/identity/proofs.ts +306 -0
  42. package/src/identity/signin/config.ts +1 -1
  43. package/src/identity/tokens.ts +10 -3
  44. package/src/identity/verifier.ts +73 -14
  45. package/src/identity/workload-token.ts +4 -0
  46. package/src/kek/aws-kms.ts +18 -13
  47. package/src/kek/check.ts +16 -46
  48. package/src/kek/index.ts +2 -2
  49. package/src/kek/types.ts +15 -3
  50. package/src/log/index.ts +7 -0
  51. package/src/log/tiles.ts +166 -0
  52. package/src/log/tree.ts +163 -0
  53. package/src/mcp.ts +34 -3
  54. package/src/schemas.ts +16 -2
  55. package/src/vault.ts +308 -276
  56. package/src/checkpoint.ts +0 -22
@@ -0,0 +1,139 @@
1
+ import { BindingInvalid, claimAt, KEY_NAMING_PROFILES, type BindingClaims, type BindingPolicy, type CheckedBinding, type WorkloadProfile } from './workloads.ts';
2
+
3
+ /**
4
+ * What each platform's binding and tokens must say beyond the claims a
5
+ * binding names (docs/design/workload-access.md, section 4.2). Core holds
6
+ * the rules every profile shares: the required claims, the issuers that
7
+ * force a profile, the policy's fields. These are each platform's own:
8
+ * the shape of the IDs it issues, which issuer goes with which, and what a
9
+ * token of it says that its binding cannot.
10
+ *
11
+ * A binding names IDs the platform never reuses, so each is checked for
12
+ * the shape the platform gives it: a name in its place is refused, since a
13
+ * name can be taken again after its owner is gone.
14
+ */
15
+ export type ProfileRules = {
16
+ /** At binding time, after `checkBinding` and `checkPolicy`. Throws `BindingInvalid`. */
17
+ binding(binding: CheckedBinding, policy: BindingPolicy): void;
18
+ /** At the exchange, once the token verified and matched its binding's claims: why it is still refused, or null. */
19
+ token(claims: Record<string, unknown>, binding: { issuer: string; claims: BindingClaims; policy: BindingPolicy }): string | null;
20
+ };
21
+
22
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
23
+ /** A Kubernetes namespace (a DNS label) and service account (a DNS subdomain), as its tokens' `sub` names them. */
24
+ const SERVICE_ACCOUNT_SUB = /^system:serviceaccount:([a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?):([a-z0-9]([-a-z0-9.]{0,251}[a-z0-9])?)$/;
25
+ /** A Google service account's unique ID: digits, 21 of them today. */
26
+ const GOOGLE_ID = /^[1-9]\d{0,31}$/;
27
+ const AZURE_V1 = /^https:\/\/sts\.windows\.net\/([0-9a-f-]{36})\/$/;
28
+ const AZURE_V2 = /^https:\/\/login\.microsoftonline\.com\/([0-9a-f-]{36})\/v2\.0$/;
29
+ const FLY_ISSUER = /^https:\/\/oidc\.fly\.io\/[a-z0-9][a-z0-9-]{0,62}$/;
30
+ /**
31
+ * Fly's IDs are digits in its documentation's tokens, unchecked live: kept
32
+ * loose, which fails closed, since a token's `org_id` and `app_id` are IDs
33
+ * and a binding naming a name matches none.
34
+ */
35
+ const FLY_ID = /^[A-Za-z0-9_-]{1,64}$/;
36
+ const VERCEL_ISSUER = /^https:\/\/oidc\.vercel\.com(\/[a-z0-9][a-z0-9-]{0,62})?$/;
37
+ const VERCEL_OWNER = /^(team_)?[A-Za-z0-9]{8,64}$/;
38
+ const VERCEL_PROJECT = /^prj_[A-Za-z0-9]{8,64}$/;
39
+ /** `production`, `preview`, `development`, or a custom environment's slug. */
40
+ const VERCEL_ENVIRONMENT = /^[a-z0-9][a-z0-9-]{0,63}$/;
41
+ const AWS_ACCOUNT = /^\d{12}$/;
42
+ /** A role's unique ID: `AROA`, then its own characters. */
43
+ const AWS_ROLE_ID = /^AROA[A-Z0-9]{8,124}$/;
44
+
45
+ function shaped(claims: BindingClaims, name: string, pattern: RegExp, what: string): void {
46
+ if (!pattern.test(claims[name] as string)) throw new BindingInvalid(`${name} is ${what}`);
47
+ }
48
+
49
+ const none = () => null;
50
+
51
+ export const PROFILE_RULES: { readonly [P in WorkloadProfile]?: ProfileRules } = {
52
+ kubernetes: {
53
+ binding({ claims }) {
54
+ const sub = SERVICE_ACCOUNT_SUB.exec(claims.sub as string);
55
+ if (sub === null) throw new BindingInvalid('sub is the service account\'s, system:serviceaccount:<namespace>:<name>');
56
+ shaped(claims, 'kubernetes.io.serviceaccount.uid', UUID, "the service account's UID, which a service account made again under the same name does not keep: kubectl get serviceaccount <name> -o jsonpath='{.metadata.uid}'");
57
+ // Narrowing claims that name the same account again must agree with sub, or the binding would match nothing.
58
+ for (const [name, value] of [['kubernetes.io.namespace', sub[1]], ['kubernetes.io.serviceaccount.name', sub[3]]] as const) {
59
+ if (claims[name] !== undefined && claims[name] !== value) throw new BindingInvalid(`${name} is ${value}, as its sub says`);
60
+ }
61
+ },
62
+ // The cluster says the same account twice, in sub and under kubernetes.io; a token where they differ is no cluster's.
63
+ token(claims) {
64
+ const sub = SERVICE_ACCOUNT_SUB.exec(String(claims.sub));
65
+ if (sub === null) return 'the token\'s sub is no service account\'s';
66
+ const namespace = claimAt(claims, 'kubernetes.io.namespace');
67
+ const name = claimAt(claims, 'kubernetes.io.serviceaccount.name');
68
+ return namespace === sub[1] && name === sub[3] ? null : 'the token names another service account under kubernetes.io than its sub';
69
+ },
70
+ },
71
+ gcp: {
72
+ binding({ claims }) {
73
+ shaped(claims, 'sub', GOOGLE_ID, "the service account's unique ID, its digits, which a service account made again under the same email does not keep: gcloud iam service-accounts describe <email> --format='value(uniqueId)'");
74
+ },
75
+ token: none,
76
+ },
77
+ azure: {
78
+ binding({ issuer, claims }, policy) {
79
+ const tenant = AZURE_V1.exec(issuer)?.[1] ?? AZURE_V2.exec(issuer)?.[1];
80
+ if (tenant === undefined || !UUID.test(tenant)) {
81
+ throw new BindingInvalid('an azure binding\'s issuer is https://sts.windows.net/<tenant>/ (v1 tokens) or https://login.microsoftonline.com/<tenant>/v2.0 (v2), by the tenant\'s ID');
82
+ }
83
+ shaped(claims, 'tid', UUID, "the tenant's ID");
84
+ if (claims.tid !== tenant) throw new BindingInvalid('tid is the tenant its issuer names');
85
+ shaped(claims, 'oid', UUID, "the managed identity's object ID (its principal ID): az identity show --query principalId");
86
+ // A v1 token's aud is the resource as asked for, its App ID URI or client ID; a v2 token's is always the API's client ID.
87
+ if (AZURE_V2.test(issuer) && !UUID.test(policy.audience ?? '')) {
88
+ throw new BindingInvalid("a v2 token's audience is the API's application (client) ID, a GUID, never its App ID URI: Entra puts no other in a v2 token");
89
+ }
90
+ },
91
+ // The issuer says which token version Entra issues, and each version names its own issuer: a token that disagrees is not what was bound.
92
+ token(claims, binding) {
93
+ const version = AZURE_V1.test(binding.issuer) ? '1.0' : '2.0';
94
+ return claims.ver === version ? null : `the token is of version ${JSON.stringify(claims.ver ?? null)}, and its binding's issuer issues ${version}`;
95
+ },
96
+ },
97
+ fly: {
98
+ binding({ issuer, claims }) {
99
+ if (!FLY_ISSUER.test(issuer)) throw new BindingInvalid('a fly binding\'s issuer is https://oidc.fly.io/<organization>, by its slug');
100
+ shaped(claims, 'org_id', FLY_ID, "the organization's ID, as its tokens' org_id says it");
101
+ shaped(claims, 'app_id', FLY_ID, "the app's ID, as its tokens' app_id says it");
102
+ },
103
+ token: none,
104
+ },
105
+ vercel: {
106
+ binding({ issuer, claims }) {
107
+ if (!VERCEL_ISSUER.test(issuer)) throw new BindingInvalid('a vercel binding\'s issuer is https://oidc.vercel.com/<team> (team mode) or https://oidc.vercel.com (global mode)');
108
+ shaped(claims, 'owner_id', VERCEL_OWNER, "the team's ID, team_…, as .vercel/project.json's orgId says it");
109
+ shaped(claims, 'project_id', VERCEL_PROJECT, "the project's ID, prj_…, as .vercel/project.json's projectId says it");
110
+ shaped(claims, 'environment', VERCEL_ENVIRONMENT, 'production, preview, development or a custom environment\'s slug');
111
+ },
112
+ token: none,
113
+ },
114
+ aws: {
115
+ binding({ claims }) {
116
+ // Its proof says the account and the role, and nothing else a binding could narrow by.
117
+ const extra = Object.keys(claims).filter((name) => name !== 'account' && name !== 'role_id');
118
+ if (extra.length > 0) throw new BindingInvalid(`an aws binding names its role's account and role_id alone, not ${extra.join(', ')}`);
119
+ shaped(claims, 'account', AWS_ACCOUNT, 'the account\'s 12 digits');
120
+ shaped(claims, 'role_id', AWS_ROLE_ID, "the role's unique ID, AROA…, which a role made again under the same name does not keep: aws iam get-role --role-name <name> --query Role.RoleId");
121
+ },
122
+ // Its proof is no token: workloads/aws.ts checks it.
123
+ token: none,
124
+ },
125
+ };
126
+
127
+ /**
128
+ * The audiences a token of a binding may name, the first the one its SDK
129
+ * asks for: the session's key, `<publicUrl>#jkt=<thumbprint>`, for the
130
+ * platforms whose caller picks the audience, and `?jkt=` for one that
131
+ * refuses a `#` in it (section 4.2); the exact audience of a platform that
132
+ * fixes it; this instance's URL for every other.
133
+ */
134
+ export function expectedAudiences(profile: WorkloadProfile, policy: BindingPolicy, expected: { publicUrl: string; jkt: string }): string[] {
135
+ if (KEY_NAMING_PROFILES.includes(profile) || policy.keyAudience === true) {
136
+ return [`${expected.publicUrl}#jkt=${expected.jkt}`, `${expected.publicUrl}?jkt=${expected.jkt}`];
137
+ }
138
+ return [policy.audience ?? expected.publicUrl];
139
+ }
@@ -0,0 +1,306 @@
1
+ import { compactVerify, createLocalJWKSet, errors, type JSONWebKeySet } from 'jose';
2
+
3
+ import { expectedAudiences, PROFILE_RULES } from './profiles.ts';
4
+ import { CLOCK_TOLERANCE_SECONDS, decodeWorkloadToken, issuedRefusal, MAX_TOKEN_AGE_SECONDS, WORKLOAD_ALGORITHMS, WorkloadTokenRefused, type DecodedToken } from './workload-token.ts';
5
+ import {
6
+ addressWithin, BEARER_PROFILES, claimAt, differingClaims, OIDC_PROFILES, POLICY_DEFAULTS, POLICY_FIELDS, REPEATING_PROFILES,
7
+ type BindingClaims, type BindingPolicy, type WorkloadProfile,
8
+ } from './workloads.ts';
9
+
10
+ /**
11
+ * A platform's proof held to a service's bindings (docs/design/0.16.md, "A
12
+ * workload signing in"). The app verifies a token's signature, or asks AWS,
13
+ * since only it reaches the platform; everything else read the binding's
14
+ * row, which only the vault can trust. So the vault decides it, on its own
15
+ * rows and its own clock, with these functions: rows and claims in, a
16
+ * binding or a refusal's word out. No I/O, and no clock but the one passed
17
+ * in, in milliseconds.
18
+ *
19
+ * Example: Ada's `deploy` service has two GitHub bindings on
20
+ * `token.actions.githubusercontent.com`, one for `main` made in March and
21
+ * one for every branch made in May. A run on `main` matches both; the
22
+ * March one, the oldest, issues its credential, with the scope its maker
23
+ * gave it. A run on `feature/x` matches May's alone.
24
+ */
25
+
26
+ /**
27
+ * Why a proof is refused, in the vault's words. `no_match`: no binding of
28
+ * the service takes it. `audience`, `expired`, `too_old`, `malformed`: the
29
+ * token is not for this instance or this key, is past its time, or breaks
30
+ * its profile's rule. `unknown_signer`: a binding carries its keys, and they
31
+ * lack the one the token names.
32
+ */
33
+ export type ExchangeRefusal = 'no_match' | 'audience' | 'expired' | 'too_old' | 'malformed' | 'unknown_signer';
34
+ export type ExchangeRefused = { refused: ExchangeRefusal };
35
+
36
+ /** A trust binding as a decision reads it: the columns of its row that say what it takes. */
37
+ export type ProofBinding = {
38
+ id: string;
39
+ profile: string;
40
+ issuer: string;
41
+ /** Where its issuer's keys are fetched from, or `sha256:<hex>` of those it carries (`CARRIED`). */
42
+ jwksUri: string;
43
+ /** The keys it carries, a JWKS as JSON: null when they are fetched. */
44
+ jwks: string | null;
45
+ /** JSON, sorted by claim name (`canonicalClaims`). */
46
+ claims: string;
47
+ /** Canonical JSON (`policyText`): null on a binding that issues a CI run's token, which no session is made from. */
48
+ policy: string | null;
49
+ createdAt: Date;
50
+ };
51
+
52
+ /** A binding's `jwks_uri` when it carries its issuer's keys: the SHA-256 of those keys, where a fetched set's URL would be. */
53
+ export const CARRIED = 'sha256:';
54
+
55
+ /**
56
+ * The keys a token was verified under, as the app says: its issuer, and
57
+ * their address, the URL it fetched them from. For a binding that carries
58
+ * its keys the address is theirs, `sha256:<hex>`, and the vault verifies the
59
+ * signature itself (`signatureRefusal`).
60
+ */
61
+ export type VerifiedUnder = { issuer: string; jwksUri: string };
62
+
63
+ /**
64
+ * What a proof is traded for: a CI run's five-minute token (`run`), from a
65
+ * binding with no policy, or a workload's session bound to a key
66
+ * (`session`), from one with a policy.
67
+ */
68
+ export type ProofFor = { kind: 'run' } | { kind: 'session'; jkt: string };
69
+
70
+ /** A token's claims and the hash of what was signed, or `malformed`. */
71
+ export function readIdToken(token: string): DecodedToken | ExchangeRefused {
72
+ try {
73
+ return decodeWorkloadToken(token);
74
+ } catch (error) {
75
+ if (error instanceof WorkloadTokenRefused) return { refused: 'malformed' };
76
+ throw error;
77
+ }
78
+ }
79
+
80
+ /** A binding's policy as its row holds it: null for none, undefined for one that does not read as a policy, which takes nothing. */
81
+ export function policyOf(binding: Pick<ProofBinding, 'policy'>): BindingPolicy | null | undefined {
82
+ if (binding.policy === null) return null;
83
+ try {
84
+ const policy: unknown = JSON.parse(binding.policy);
85
+ return typeof policy === 'object' && policy !== null && !Array.isArray(policy) ? (policy as BindingPolicy) : undefined;
86
+ } catch {
87
+ return undefined;
88
+ }
89
+ }
90
+
91
+ /** Whether a binding issues what a proof is traded for: a CI run's token from a bearer profile with no policy, a session from an ID-token profile with one. */
92
+ export function issues(binding: Pick<ProofBinding, 'profile' | 'policy'>, wanted: ProofFor['kind']): boolean {
93
+ const profiles: readonly string[] = wanted === 'run' ? BEARER_PROFILES : OIDC_PROFILES;
94
+ return profiles.includes(binding.profile) && (wanted === 'run' ? binding.policy === null : policyOf(binding) != null);
95
+ }
96
+
97
+ /** The audience a token names, alone; null for none, or several. */
98
+ export function soleAudience(aud: unknown): string | null {
99
+ if (typeof aud === 'string') return aud;
100
+ return Array.isArray(aud) && aud.length === 1 && typeof aud[0] === 'string' ? aud[0] : null;
101
+ }
102
+
103
+ /**
104
+ * The audiences a binding takes: this instance's URL for a CI run's; for a
105
+ * session's, its policy's, the session's key or its profile's
106
+ * (`expectedAudiences`). None for one whose policy does not read.
107
+ */
108
+ export function audiencesOf(binding: Pick<ProofBinding, 'profile' | 'policy'>, publicUrl: string, wanted: ProofFor): string[] {
109
+ const policy = policyOf(binding);
110
+ if (wanted.kind === 'run') return policy === null ? [publicUrl] : [];
111
+ return policy == null ? [] : expectedAudiences(binding.profile as WorkloadProfile, policy, { publicUrl, jkt: wanted.jkt });
112
+ }
113
+
114
+ /**
115
+ * Which audience a token is held to, and the bindings that take it: the
116
+ * token's own if some binding takes it, otherwise the instance's, 0.14's
117
+ * rule. A token none takes is refused `audience` once its times are checked.
118
+ */
119
+ export function audienceTried<B extends ProofBinding>(aud: unknown, bindings: readonly B[], publicUrl: string, wanted: ProofFor): { audience: string; taking: B[] } {
120
+ const named = soleAudience(aud);
121
+ const audience = named !== null && bindings.some((binding) => audiencesOf(binding, publicUrl, wanted).includes(named)) ? named : publicUrl;
122
+ return { audience, taking: bindings.filter((binding) => audiencesOf(binding, publicUrl, wanted).includes(audience)) };
123
+ }
124
+
125
+ /**
126
+ * A token's times on the vault's clock, `now` in milliseconds, each within
127
+ * the clock tolerance, as 0.14 held them: not before its `nbf`, to jose's
128
+ * whole second; before its `exp`, to the millisecond, as 0.14's exchange
129
+ * checked it again; issued `maxAge` seconds ago at most (an hour,
130
+ * or any age for a token its platform hands out again), and, where a binding
131
+ * carries its keys, living `maxLifetime` seconds at most.
132
+ */
133
+ export function timesRefusal(claims: DecodedToken['claims'], now: number, { maxAge = MAX_TOKEN_AGE_SECONDS, maxLifetime = null }: { maxAge?: number | null; maxLifetime?: number | null } = {}): ExchangeRefusal | null {
134
+ const seconds = Math.floor(now / 1000);
135
+ // 0.14's `not_yet_valid` and `too_long` are `too_old` here, as a token issued in the future already was: past its time.
136
+ if (typeof claims.nbf === 'number' && claims.nbf > seconds + CLOCK_TOLERANCE_SECONDS) return 'too_old';
137
+ if (claims.exp <= now / 1000 - CLOCK_TOLERANCE_SECONDS) return 'expired';
138
+ if (issuedRefusal(claims.iat, now / 1000, maxAge ?? Infinity) !== null) return 'too_old';
139
+ if (maxLifetime !== null && claims.exp - claims.iat > maxLifetime) return 'too_old';
140
+ return null;
141
+ }
142
+
143
+ /** The oldest of `bindings` whose every claim the token carries (`differingClaims`), in the order the bindings' index reads them. */
144
+ export function oldestMatching<B extends Pick<ProofBinding, 'id' | 'profile' | 'claims' | 'createdAt'>>(bindings: readonly B[], claims: Record<string, unknown>): B | null {
145
+ const ordered = [...bindings].sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
146
+ return ordered.find((binding) => {
147
+ let expected: unknown;
148
+ try {
149
+ expected = JSON.parse(binding.claims);
150
+ } catch {
151
+ return false;
152
+ }
153
+ return typeof expected === 'object' && expected !== null && !Array.isArray(expected) && differingClaims(binding.profile as WorkloadProfile, expected as BindingClaims, claims).length === 0;
154
+ }) ?? null;
155
+ }
156
+
157
+ /** Why a token its binding matched still breaks its profile's own rule (`PROFILE_RULES`: Azure's version, Kubernetes' subject), or null. */
158
+ export function profileRefusal(binding: Pick<ProofBinding, 'profile' | 'issuer' | 'claims'>, policy: BindingPolicy, claims: Record<string, unknown>): 'malformed' | null {
159
+ const rule = PROFILE_RULES[binding.profile as WorkloadProfile];
160
+ if (rule === undefined) return null;
161
+ return rule.token(claims, { issuer: binding.issuer, claims: JSON.parse(binding.claims) as BindingClaims, policy }) === null ? null : 'malformed';
162
+ }
163
+
164
+ /**
165
+ * Whether a proof is spent once it is traded, by the SHA-256 of what was
166
+ * signed: a CI run's token always; a session's token unless it names the
167
+ * session's key, which works for no other, or its platform hands the same
168
+ * one out again (`REPEATING_PROFILES`), which spending would refuse.
169
+ */
170
+ export function spends(binding: Pick<ProofBinding, 'profile'>, policy: BindingPolicy | null, wanted: ProofFor['kind']): boolean {
171
+ if (wanted === 'run') return true;
172
+ return policy?.keyAudience !== true && !REPEATING_PROFILES.includes(binding.profile as WorkloadProfile);
173
+ }
174
+
175
+ /**
176
+ * A session's hard end, in milliseconds: the earliest of its binding's
177
+ * `sessionHours` after `at`, where its profile has them (24 unless said),
178
+ * and, unless the token names the session's key, the token's own `exp`, so
179
+ * that a copy of it buys no more than the platform's lifetime. `exp` is in
180
+ * seconds, null for a proof that is no token. A session whose end is not
181
+ * after `at` is refused `expired`.
182
+ */
183
+ export function hardEnd(binding: Pick<ProofBinding, 'profile'>, policy: BindingPolicy, at: number, exp: number | null): number {
184
+ const fields = POLICY_FIELDS[binding.profile as WorkloadProfile] ?? [];
185
+ const hours = fields.includes('sessionHours') ? (policy.sessionHours ?? POLICY_DEFAULTS.sessionHours) : null;
186
+ const ends = [hours === null ? null : at + hours * 3_600_000, policy.keyAudience === true || exp === null ? null : exp * 1000].filter((end): end is number => end !== null);
187
+ return Math.min(...(ends.length === 0 ? [at + POLICY_DEFAULTS.sessionHours * 3_600_000] : ends));
188
+ }
189
+
190
+ /**
191
+ * Why a session is refused at its sign-in, from its binding's policy and the
192
+ * request's address: the deployment lets no binding list reads (`noReads`)
193
+ * and this one does, or it names its sources and the request came from
194
+ * outside them, or from nowhere the app could tell. Both are `no_match`, as
195
+ * the design's refusals have it; 0.14 answered the second `source`.
196
+ */
197
+ export function sessionRefusal(policy: BindingPolicy, ip: string | null, { noReads }: { noReads: boolean }): 'no_match' | null {
198
+ if (noReads && policy.reads !== undefined) return 'no_match';
199
+ if (policy.sources !== undefined && (ip === null || !addressWithin(ip, policy.sources))) return 'no_match';
200
+ return null;
201
+ }
202
+
203
+ /** An ID token held to a service's bindings: the binding it is traded at, its claims and policy, and the hash it spends, if any. */
204
+ export type IdTokenMatch<B extends ProofBinding> = { binding: B; policy: BindingPolicy | null; claims: DecodedToken['claims']; spends: Buffer | null };
205
+
206
+ /**
207
+ * An ID token whose signature verified under `under`, held to the
208
+ * service's live bindings, in 0.14's order:
209
+ *
210
+ * 1. of the bindings that issue what it is traded for (`issues`), those
211
+ * on its issuer under the keys it was verified under;
212
+ * 2. the audience tried, and the bindings that take it (`audienceTried`);
213
+ * 3. its times (`timesRefusal`): any age for a token its platform hands
214
+ * out again, where a binding that takes it is of such a platform, and
215
+ * an hour's lifetime at most under keys a binding carries;
216
+ * 4. that audience, the token's own, alone;
217
+ * 5. the oldest whose claims match (`oldestMatching`);
218
+ * 6. an hour's age after all, if the binding that matched is of a
219
+ * platform that hands out no token twice;
220
+ * 7. its profile's own rule (`profileRefusal`).
221
+ *
222
+ * `bindings` are the sealed rows the read found: a decision that picks the
223
+ * oldest of several refuses before this if any row it read is not the
224
+ * vault's, since one passed over would let a later one answer.
225
+ */
226
+ export function matchIdToken<B extends ProofBinding>(token: DecodedToken, bindings: readonly B[], { under, publicUrl, wanted, now }: { under: VerifiedUnder; publicUrl: string; wanted: ProofFor; now: number }): IdTokenMatch<B> | ExchangeRefused {
227
+ const { claims } = token;
228
+ const candidates = bindings.filter((binding) => issues(binding, wanted.kind) && binding.issuer === under.issuer && binding.jwksUri === under.jwksUri && claims.iss === under.issuer);
229
+ if (candidates.length === 0) return { refused: 'no_match' };
230
+ const { audience, taking } = audienceTried(claims.aud, candidates, publicUrl, wanted);
231
+ const repeats = taking.some((binding) => REPEATING_PROFILES.includes(binding.profile as WorkloadProfile));
232
+ // Keys a binding carries: no issuer to ask whether a token still stands, so none lives past the hour.
233
+ const times = timesRefusal(claims, now, { maxAge: repeats ? null : MAX_TOKEN_AGE_SECONDS, maxLifetime: under.jwksUri.startsWith(CARRIED) ? MAX_TOKEN_AGE_SECONDS : null });
234
+ if (times !== null) return { refused: times };
235
+ if (soleAudience(claims.aud) !== audience || taking.length === 0) return { refused: 'audience' };
236
+ const binding = oldestMatching(taking, claims);
237
+ if (binding === null) return { refused: 'no_match' };
238
+ const policy = policyOf(binding)!;
239
+ // A token its platform hands out again is as old as the platform's cache; one of another platform beside it is an hour old at most.
240
+ if (repeats && !REPEATING_PROFILES.includes(binding.profile as WorkloadProfile) && issuedRefusal(claims.iat, now / 1000) !== null) return { refused: 'too_old' };
241
+ if (policy !== null && profileRefusal(binding, policy, claims) !== null) return { refused: 'malformed' };
242
+ return { binding, policy, claims, spends: spends(binding, policy, wanted.kind) ? token.signingInputHash : null };
243
+ }
244
+
245
+ /**
246
+ * Whether a token's signature verifies under keys a binding carries, a JWKS
247
+ * as its row holds it: null if it does, `unknown_signer` when the set lacks
248
+ * the key the token names, and `malformed` for any other failure, a
249
+ * signature that does not verify under it included. The algorithms are
250
+ * fixed, and nothing is taken from the header but `alg` and `kid`; a set
251
+ * with several keys the header could name tries each. A token that does
252
+ * not read as one (`readIdToken`), an unencoded payload's included, is
253
+ * `malformed` before any key is tried. It checks no claim: the times and
254
+ * the audience are `matchIdToken`'s.
255
+ */
256
+ export async function signatureRefusal(token: string, jwks: string): Promise<'unknown_signer' | 'malformed' | null> {
257
+ if ('refused' in readIdToken(token)) return 'malformed';
258
+ let keys: JSONWebKeySet;
259
+ try {
260
+ keys = JSON.parse(jwks) as JSONWebKeySet;
261
+ } catch {
262
+ return 'malformed';
263
+ }
264
+ const options = { algorithms: [...WORKLOAD_ALGORITHMS] };
265
+ try {
266
+ await compactVerify(token, createLocalJWKSet(keys), options);
267
+ return null;
268
+ } catch (error) {
269
+ if (error instanceof errors.JWKSNoMatchingKey) return 'unknown_signer';
270
+ if (!(error instanceof errors.JWKSMultipleMatchingKeys)) return 'malformed';
271
+ for await (const key of error) {
272
+ try {
273
+ await compactVerify(token, key, options);
274
+ return null;
275
+ } catch {
276
+ // The next key the header could name.
277
+ }
278
+ }
279
+ return 'malformed';
280
+ }
281
+ }
282
+
283
+ /**
284
+ * The claims of the run a credential was issued for, as its issuer stated
285
+ * them: those that say which run, each bounded, in the exchange's entry and
286
+ * the credential's row, so that a read leads back to its run. What the
287
+ * issuer says, not proof of which run sent the request.
288
+ */
289
+ export const RUN_CLAIMS = [
290
+ 'sub', 'jti', 'actor', 'event_name', 'ref', 'base_ref', 'head_ref', 'sha', 'repository', 'repository_id', 'run_id', 'run_attempt',
291
+ 'workflow_ref', 'job_workflow_ref', 'job_workflow_sha', 'environment',
292
+ 'project_path', 'project_id', 'namespace_id', 'pipeline_id', 'pipeline_source', 'job_id',
293
+ 'kubernetes.io.pod.name',
294
+ ] as const;
295
+ export const MAX_RUN_CLAIM = 256;
296
+
297
+ /** The run's claims, as the issuer stated them: each a string of 256 characters at most, or a finite number. */
298
+ export function runClaims(claims: Record<string, unknown>): Record<string, string | number> {
299
+ const run: Record<string, string | number> = {};
300
+ for (const name of RUN_CLAIMS) {
301
+ const value = claimAt(claims, name);
302
+ if (typeof value === 'string') run[name] = value.slice(0, MAX_RUN_CLAIM);
303
+ else if (typeof value === 'number' && Number.isFinite(value)) run[name] = value;
304
+ }
305
+ return run;
306
+ }
@@ -474,7 +474,7 @@ function checkProvider(provider: SigninProvider): void {
474
474
  }
475
475
  }
476
476
 
477
- function lifetime(value: number | undefined, name: string, fallback: number, max: number): number {
477
+ export function lifetime(value: number | undefined, name: string, fallback: number, max: number): number {
478
478
  if (value === undefined) return fallback;
479
479
  if (!Number.isFinite(value) || value <= 0 || value > max) {
480
480
  throw new Error(`${name} must be a number above 0 and at most ${max}`);
@@ -21,8 +21,13 @@ import { createHash, randomBytes } from 'node:crypto';
21
21
  */
22
22
  export type CredentialKind = 'browser' | 'cli' | 'service' | 'personal' | 'handle' | 'workload';
23
23
 
24
- /** What a token's prefix says it is: a credential, or an enrollment code. */
25
- export type TokenKind = CredentialKind | 'enrollment';
24
+ /**
25
+ * What a token's prefix says it is: a credential, an enrollment code, or
26
+ * an MCP client's tokens: an access token, good at `/mcp` alone, and the
27
+ * refresh token it gets the next one with, good at the token endpoint alone
28
+ * (docs/design/0.16.md, "MCP connections").
29
+ */
30
+ export type TokenKind = CredentialKind | 'enrollment' | 'mcp' | 'mcp-refresh';
26
31
 
27
32
  const PREFIX: Record<TokenKind, string> = {
28
33
  browser: 'coffre_web_',
@@ -32,9 +37,11 @@ const PREFIX: Record<TokenKind, string> = {
32
37
  handle: 'coffre_use_',
33
38
  workload: 'coffre_wl_',
34
39
  enrollment: 'coffre_enr_',
40
+ mcp: 'coffre_mcp_',
41
+ 'mcp-refresh': 'coffre_mcr_',
35
42
  };
36
43
 
37
- const TOKEN = /^coffre_(web|cli|svc|pat|use|wl|enr)_[A-Za-z0-9_-]{43}$/;
44
+ const TOKEN = /^coffre_(web|cli|svc|pat|use|wl|enr|mcp|mcr)_[A-Za-z0-9_-]{43}$/;
38
45
 
39
46
  export function generateToken(kind: TokenKind): string {
40
47
  return PREFIX[kind] + randomBytes(32).toString('base64url');
@@ -1,4 +1,4 @@
1
- import { createRemoteJWKSet, jwtVerify, type JWTPayload } from 'jose';
1
+ import { createLocalJWKSet, decodeProtectedHeader, errors, jwtVerify, type JSONWebKeySet, type JWTPayload } from 'jose';
2
2
  import type { AccessVerifierConfig, IdentityVerifier, Principal } from './types.ts';
3
3
 
4
4
  export type { AccessVerifierConfig };
@@ -12,6 +12,10 @@ export type { AccessVerifierConfig };
12
12
  */
13
13
  const ALLOWED_ALGORITHMS = ['RS256', 'ES256'] as const;
14
14
 
15
+ /** How long a key set is used before it is fetched again, and the least time between two fetches an unknown key asks for. */
16
+ const KEYS_MAX_AGE_MS = 10 * 60_000;
17
+ const REFETCH_COOLDOWN_MS = 30_000;
18
+
15
19
  type AccessClaims = JWTPayload & {
16
20
  email?: unknown;
17
21
  common_name?: unknown;
@@ -21,39 +25,94 @@ function asNonEmptyString(value: unknown): string | null {
21
25
  return typeof value === 'string' && value.length > 0 ? value : null;
22
26
  }
23
27
 
28
+ /** The team's keys could not be fetched, or are no key set: no assertion can be checked, which is not the caller's fault. */
29
+ export class AccessKeysUnavailable extends Error {
30
+ constructor(message: string, options?: { cause?: unknown }) {
31
+ super(message, options);
32
+ this.name = 'AccessKeysUnavailable';
33
+ }
34
+ }
35
+
36
+ /** How the verifier fetches the team's key set, and what time it is. */
37
+ export type AccessVerifierIo = {
38
+ /** GET a JSON document; throws when it cannot. The global `fetch` unless given. */
39
+ json?: (url: URL) => Promise<unknown>;
40
+ now?: () => number;
41
+ };
42
+
43
+ async function fetchJson(url: URL): Promise<unknown> {
44
+ const response = await fetch(url, { redirect: 'manual', signal: AbortSignal.timeout(5_000), headers: { accept: 'application/json' } });
45
+ if (response.status !== 200) {
46
+ await response.body?.cancel();
47
+ throw new Error(`${url.href} answered ${response.status}`);
48
+ }
49
+ return response.json();
50
+ }
51
+
24
52
  /**
25
53
  * Verifies Cloudflare Access JWTs.
26
54
  *
27
55
  * Signature and claim verification of the token Access sends with each
28
- * request.
56
+ * request. The team's keys are fetched when first needed, used for ten
57
+ * minutes, and fetched again sooner for a key they lack, at most every 30
58
+ * seconds. The verifier lives as long as its configuration (an isolate's,
59
+ * on Workers) and keeps settled values only, never a fetch in flight
60
+ * (AGENTS.md, "What an isolate keeps"): concurrent requests that find no
61
+ * key set each fetch their own, and the last to land is kept. The 30
62
+ * seconds count from the last refresh started, landed or not, and are
63
+ * taken before it starts: of a burst of assertions naming a key the set
64
+ * lacks, one fetches, and the others are refused as the key unknown.
29
65
  */
30
66
  export class AccessIdentityVerifier implements IdentityVerifier {
31
67
  readonly #config: AccessVerifierConfig;
32
- readonly #jwks: ReturnType<typeof createRemoteJWKSet>;
68
+ readonly #url: URL;
69
+ readonly #json: (url: URL) => Promise<unknown>;
70
+ readonly #now: () => number;
71
+ #keys: { set: ReturnType<typeof createLocalJWKSet>; at: number } | null = null;
72
+ /** When a refresh for an unknown key last started: a number, settled the moment it starts. */
73
+ #refreshed = Number.NEGATIVE_INFINITY;
33
74
 
34
- constructor(config: AccessVerifierConfig) {
75
+ constructor(config: AccessVerifierConfig, io: AccessVerifierIo = {}) {
35
76
  this.#config = config;
36
- // jose handles JWKS fetching, caching and rotation-driven refetch. Not
37
- // something to hand-roll.
38
- this.#jwks = createRemoteJWKSet(new URL(config.jwksUrl), {
39
- cooldownDuration: 30_000,
40
- cacheMaxAge: 600_000,
41
- });
77
+ this.#url = new URL(config.jwksUrl);
78
+ this.#json = io.json ?? fetchJson;
79
+ this.#now = io.now ?? Date.now;
42
80
  }
43
81
 
44
82
  async verify(token: string): Promise<Principal> {
45
83
  if (typeof token !== 'string' || token.length === 0) {
46
84
  throw new Error('missing or empty Access token');
47
85
  }
48
-
49
- const { payload } = await jwtVerify<AccessClaims>(token, this.#jwks, {
86
+ // Malformed, or signed with an algorithm we never take: refused before anything is fetched for it.
87
+ const { alg } = decodeProtectedHeader(token);
88
+ if (!(ALLOWED_ALGORITHMS as readonly unknown[]).includes(alg)) throw new errors.JOSEAlgNotAllowed(`"alg" (Algorithm) Header Parameter value not allowed`);
89
+ const options = {
50
90
  issuer: this.#config.issuer,
51
91
  audience: this.#config.audience,
52
92
  algorithms: [...ALLOWED_ALGORITHMS],
53
93
  clockTolerance: this.#config.clockToleranceSeconds ?? 0,
54
- });
94
+ };
95
+ let keys = this.#keys;
96
+ if (keys === null || this.#now() - keys.at >= KEYS_MAX_AGE_MS) keys = await this.#fetch();
97
+ try {
98
+ return toPrincipal((await jwtVerify<AccessClaims>(token, keys.set, options)).payload);
99
+ } catch (error) {
100
+ // A key the set lacks may be one Access rotated in since: asked again, once, past the cooldown.
101
+ const now = this.#now();
102
+ if (!(error instanceof errors.JWKSNoMatchingKey) || now - Math.max(keys.at, this.#refreshed) < REFETCH_COOLDOWN_MS) throw error;
103
+ this.#refreshed = now;
104
+ }
105
+ return toPrincipal((await jwtVerify<AccessClaims>(token, (await this.#fetch()).set, options)).payload);
106
+ }
55
107
 
56
- return toPrincipal(payload);
108
+ async #fetch(): Promise<{ set: ReturnType<typeof createLocalJWKSet>; at: number }> {
109
+ let set: ReturnType<typeof createLocalJWKSet>;
110
+ try {
111
+ set = createLocalJWKSet((await this.#json(this.#url)) as JSONWebKeySet);
112
+ } catch (error) {
113
+ throw new AccessKeysUnavailable(`Cloudflare Access's keys could not be fetched from ${this.#url.href}`, { cause: error });
114
+ }
115
+ return (this.#keys = { set, at: this.#now() });
57
116
  }
58
117
  }
59
118
 
@@ -79,8 +79,12 @@ export function decodeWorkloadToken(token: string): DecodedToken {
79
79
  return value as Record<string, unknown>;
80
80
  };
81
81
  const [header, claims] = [json(parts[0]!), json(parts[1]!)];
82
+ // An extension the signer requires to be understood, `b64: false`'s unencoded payload above all, is one this reader does not: it reads `alg` and `kid` alone.
83
+ if (header.crit !== undefined) throw malformed('names a critical header extension');
82
84
  for (const name of ['iss', 'sub'] as const) {
83
85
  if (typeof claims[name] !== 'string' || claims[name] === '') throw malformed(`has no ${name}, as a nonempty string`);
86
+ // A database stores no NUL, and UTF-8 no lone surrogate: a claim with one could match nothing, and is no text.
87
+ if (/[\0\p{Cs}]/u.test(claims[name])) throw malformed(`has an ${name} with a NUL or a lone surrogate`);
84
88
  }
85
89
  for (const name of ['exp', 'iat'] as const) {
86
90
  if (typeof claims[name] !== 'number' || !Number.isFinite(claims[name])) throw malformed(`has no ${name}, as a finite number`);