@coffre/core 0.15.0 → 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 (70) hide show
  1. package/README.md +1 -1
  2. package/dist/{access-CgQTlUMz.js → access-CF8UG59J.js} +70 -95
  3. package/dist/{access-DqLJjnLM.d.ts → access-ERdGGHG7.d.ts} +45 -64
  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 +3 -1018
  9. package/dist/identity.js +885 -623
  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 +27 -4
  16. package/dist/mcp.js +31 -10
  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 -12
  21. package/dist/schemas.js +16 -14
  22. package/dist/{types-Cp3lB_-W.js → types-DwTO_b4H.js} +17 -5
  23. package/dist/vault.d.ts +1771 -1419
  24. package/dist/vault.js +96 -302
  25. package/dist/{workloads-D049JH0M.d.ts → workloads-CW2dK4AW.d.ts} +1 -9
  26. package/dist/workloads.d.ts +2 -2
  27. package/dist/workloads.js +1 -9
  28. package/package.json +7 -7
  29. package/src/access.ts +63 -95
  30. package/src/changes/access.ts +140 -0
  31. package/src/changes/freezes.ts +40 -0
  32. package/src/changes/mcp.ts +150 -0
  33. package/src/changes/places.ts +219 -0
  34. package/src/changes/secrets.ts +235 -0
  35. package/src/changes/signin.ts +197 -0
  36. package/src/changes/workloads.ts +166 -0
  37. package/src/context.ts +18 -2
  38. package/src/envelope.ts +35 -12
  39. package/src/identity/auth.ts +11 -3
  40. package/src/identity/aws.ts +62 -0
  41. package/src/identity/github-app.ts +45 -24
  42. package/src/identity/index.ts +3 -2
  43. package/src/identity/{profile-rules.ts → profiles.ts} +1 -9
  44. package/src/identity/proofs.ts +306 -0
  45. package/src/identity/signin/config.ts +1 -1
  46. package/src/identity/tokens.ts +10 -3
  47. package/src/identity/verifier.ts +73 -14
  48. package/src/identity/workload-token.ts +4 -0
  49. package/src/identity/workloads.ts +0 -11
  50. package/src/kek/aws-kms.ts +18 -13
  51. package/src/kek/check.ts +16 -46
  52. package/src/kek/index.ts +2 -2
  53. package/src/kek/types.ts +15 -3
  54. package/src/log/index.ts +7 -0
  55. package/src/{audit → log}/tiles.ts +18 -49
  56. package/src/{audit → log}/tree.ts +2 -2
  57. package/src/mcp.ts +36 -9
  58. package/src/schemas.ts +15 -12
  59. package/src/vault.ts +251 -1150
  60. package/dist/merkle.d.ts +0 -456
  61. package/dist/merkle.js +0 -964
  62. package/src/answers.ts +0 -209
  63. package/src/audit/leaf.ts +0 -81
  64. package/src/audit/merkle.ts +0 -13
  65. package/src/audit/note.ts +0 -187
  66. package/src/audit/pair.ts +0 -86
  67. package/src/audit/verify.ts +0 -393
  68. package/src/audit/witness.ts +0 -50
  69. package/src/checkpoint.ts +0 -22
  70. package/src/identity/run-proof.ts +0 -159
package/dist/identity.js CHANGED
@@ -1,8 +1,8 @@
1
- import { BEARER_PROFILES, BindingInvalid, CREDENTIAL_NAME, EVENT_EXPOSURE, EXCHANGED_CREDENTIAL_MS, EXCHANGE_SKEW_SECONDS, GITHUB_EVENTS, GITHUB_ISSUER, GITLAB_ISSUER, GITLAB_PIPELINE_SOURCES, GOOGLE_ISSUER, KEY_NAMING_PROFILES, MAX_BINDINGS, MAX_CLAIMS, MAX_CLAIM_BYTES, MAX_ISSUER_BYTES, MAX_READ_KEYS, MAX_READ_PLACES, MAX_SOURCES, OIDC_PROFILES, POLICY_DEFAULTS, POLICY_FIELDS, PROFILE_URNS, REPEATING_PROFILES, REQUIRED_CLAIMS, SESSION_MS, WORKLOAD_PROFILES, WORKLOAD_SIGN_IN_PATH, addressWithin, canonicalClaims, checkBinding, checkFetchUrl, checkPolicy, claimAt, claimValues, defaultIssuer, differingClaims, freezeTarget, fullRef, githubEventsAt, githubReusable, githubWorkflow, gitlabProject, isBearerProfile, parseAddress, parseCidr, policyText, workflowRef } from "./workloads.js";
1
+ import { BEARER_PROFILES, BindingInvalid, CREDENTIAL_NAME, EVENT_EXPOSURE, GITHUB_EVENTS, GITHUB_ISSUER, GITLAB_ISSUER, GITLAB_PIPELINE_SOURCES, GOOGLE_ISSUER, KEY_NAMING_PROFILES, MAX_BINDINGS, MAX_CLAIMS, MAX_CLAIM_BYTES, MAX_ISSUER_BYTES, MAX_READ_KEYS, MAX_READ_PLACES, MAX_SOURCES, OIDC_PROFILES, POLICY_DEFAULTS, POLICY_FIELDS, PROFILE_URNS, REPEATING_PROFILES, REQUIRED_CLAIMS, WORKLOAD_PROFILES, addressWithin, canonicalClaims, checkBinding, checkFetchUrl, checkPolicy, claimAt, claimValues, defaultIssuer, differingClaims, freezeTarget, fullRef, githubEventsAt, githubReusable, githubWorkflow, gitlabProject, isBearerProfile, parseAddress, parseCidr, policyText, workflowRef } from "./workloads.js";
2
2
  import { createCipheriv, createDecipheriv, createHash, hkdfSync, randomBytes } from "node:crypto";
3
3
  import * as oauth from "oauth4webapi";
4
+ import { compactVerify, createLocalJWKSet, decodeProtectedHeader, errors, importJWK, jwtVerify } from "jose";
4
5
  import { MAX_PROOF_LENGTH, MAX_PROOF_LENGTH as MAX_PROOF_LENGTH$1, MAX_SIGNED_HEADERS, MAX_SIGNED_HEADERS as MAX_SIGNED_HEADERS$1, METHOD_TOKEN, UNSIGNED_HEADERS, canonicalHtu, canonicalHtu as canonicalHtu$1, canonicalRequest, fetchMethod, fetchMethod as fetchMethod$1, fromBase64url, requestDigest, sentTarget, sentTarget as sentTarget$1, thumbprint, thumbprint as thumbprint$1, tokenDigest } from "@coffre/client/dpop";
5
- import { createLocalJWKSet, createRemoteJWKSet, errors, importJWK, jwtVerify } from "jose";
6
6
  //#region src/identity/github-app.ts
7
7
  /** GitHub could not be asked, or refused the app: the message says which, for a person, and carries no credential. */
8
8
  var GitHubAppUnavailable = class extends Error {
@@ -49,18 +49,28 @@ var GitHubApp = class {
49
49
  clientSecret: this.#clientSecret
50
50
  };
51
51
  }
52
- /** Every repository of every account the app is installed on, as many as `MAX_LISTING_REQUESTS` reach. */
53
- async repositories() {
52
+ /**
53
+ * Every repository of every account the app is installed on, as many as
54
+ * `MAX_LISTING_REQUESTS` reach. `signal` ends every request still going
55
+ * when it aborts, and the listing with `GitHubAppUnavailable`: the caller's
56
+ * deadline for the whole of it, beside each request's own.
57
+ */
58
+ async repositories(options = {}) {
59
+ const failed = new AbortController();
60
+ const signal = options.signal === void 0 ? failed.signal : AbortSignal.any([options.signal, failed.signal]);
54
61
  const budget = { left: 40 };
55
- this.#app ??= await this.#appInfo(budget);
56
- const { installations, more } = await this.#installations(budget);
62
+ this.#app ??= await this.#appInfo(budget, signal);
63
+ const { installations, more } = await this.#installations(budget, signal);
57
64
  let truncated = more;
58
65
  /** An installation's repositories, its first page paid from `own`, and the rest from what the listing has left. */
59
66
  const list = async (installation, own) => {
60
67
  const repositories = [];
61
68
  try {
62
69
  for (let page = 1;; page++) {
63
- const body = record(await this.#asInstallation(installation.id, `/installation/repositories?per_page=${PAGE}&page=${page}`, { budget: own }));
70
+ const body = record(await this.#asInstallation(installation.id, `/installation/repositories?per_page=${PAGE}&page=${page}`, {
71
+ budget: own,
72
+ signal
73
+ }));
64
74
  const items = Array.isArray(body.repositories) ? body.repositories : [];
65
75
  repositories.push(...items.flatMap((item) => repository(item) ?? []));
66
76
  const total = typeof body.total_count === "number" ? body.total_count : 0;
@@ -92,7 +102,14 @@ var GitHubApp = class {
92
102
  break;
93
103
  }
94
104
  rest = rest.slice(wave.length);
95
- listed.push(...await Promise.all(wave.map(({ installation, own }) => list(installation, own))));
105
+ const failures = [];
106
+ const pages = await Promise.all(wave.map(({ installation, own }) => list(installation, own).catch((error) => {
107
+ failures.push(error);
108
+ failed.abort();
109
+ return [];
110
+ })));
111
+ if (failures.length > 0) throw failures[0];
112
+ listed.push(...pages);
96
113
  for (const { own } of wave) budget.left += own.left;
97
114
  }
98
115
  const byId = new Map(listed.flat().map((each) => [each.repositoryId, each]));
@@ -103,14 +120,24 @@ var GitHubApp = class {
103
120
  truncated
104
121
  };
105
122
  }
106
- /** `owner/name`'s IDs, when the app is installed on it; null when it is not, its installation is suspended, or GitHub knows no such repository. */
107
- async repository(fullName) {
108
- const { id, suspended_at: suspended } = record(await this.#asApp(`/repos/${fullName}/installation`, { missing: true }));
123
+ /** `owner/name`'s IDs, when the app is installed on it; null when it is not, its installation is suspended, or GitHub knows no such repository. `signal` as for `repositories`. */
124
+ async repository(fullName, options = {}) {
125
+ const { signal } = options;
126
+ const { id, suspended_at: suspended } = record(await this.#asApp(`/repos/${fullName}/installation`, {
127
+ missing: true,
128
+ signal
129
+ }));
109
130
  if (typeof id !== "number" || suspended !== null && suspended !== void 0) return null;
110
- return repository(await this.#asInstallation(id, `/repos/${fullName}`, { missing: true }));
131
+ return repository(await this.#asInstallation(id, `/repos/${fullName}`, {
132
+ missing: true,
133
+ signal
134
+ }));
111
135
  }
112
- async #appInfo(budget) {
113
- const app = record(await this.#asApp("/app", { budget }));
136
+ async #appInfo(budget, signal) {
137
+ const app = record(await this.#asApp("/app", {
138
+ budget,
139
+ signal
140
+ }));
114
141
  if (typeof app.name !== "string" || typeof app.html_url !== "string") throw new GitHubAppUnavailable("GitHub answered /app without the app");
115
142
  return {
116
143
  name: app.name,
@@ -118,8 +145,11 @@ var GitHubApp = class {
118
145
  };
119
146
  }
120
147
  /** The installations not suspended, of the first page: `more` when there may be others. */
121
- async #installations(budget) {
122
- const answer = await this.#asApp(`/app/installations?per_page=${PAGE}`, { budget });
148
+ async #installations(budget, signal) {
149
+ const answer = await this.#asApp(`/app/installations?per_page=${PAGE}`, {
150
+ budget,
151
+ signal
152
+ });
123
153
  const items = Array.isArray(answer) ? answer : [];
124
154
  return {
125
155
  installations: items.flatMap((item) => {
@@ -144,7 +174,7 @@ var GitHubApp = class {
144
174
  async #asInstallation(id, path, options = {}) {
145
175
  const kept = this.#kept(id);
146
176
  const fresh = kept === null;
147
- const token = kept ?? await this.#issueToken(id, options.budget);
177
+ const token = kept ?? await this.#issueToken(id, options);
148
178
  const answer = await this.#call(path, {
149
179
  method: "GET",
150
180
  token,
@@ -154,7 +184,7 @@ var GitHubApp = class {
154
184
  if (answer !== REFUSED) return answer;
155
185
  return this.#call(path, {
156
186
  method: "GET",
157
- token: await this.#issueToken(id, options.budget),
187
+ token: await this.#issueToken(id, options),
158
188
  ...options
159
189
  });
160
190
  }
@@ -164,12 +194,13 @@ var GitHubApp = class {
164
194
  return kept !== void 0 && kept.expiresAt - 3e5 > this.#now() ? kept.token : null;
165
195
  }
166
196
  /** https://docs.github.com/en/rest/apps/apps#create-an-installation-access-token-for-an-app */
167
- async #issueToken(id, budget) {
197
+ async #issueToken(id, { budget, signal }) {
168
198
  this.#tokens.delete(id);
169
199
  const answer = record(await this.#call(`/app/installations/${id}/access_tokens`, {
170
200
  method: "POST",
171
201
  token: await this.#jwt(),
172
- budget
202
+ budget,
203
+ signal
173
204
  }));
174
205
  const expiresAt = typeof answer.expires_at === "string" ? Date.parse(answer.expires_at) : NaN;
175
206
  if (typeof answer.token !== "string" || !Number.isFinite(expiresAt)) throw new GitHubAppUnavailable("GitHub issued no installation token");
@@ -203,7 +234,8 @@ var GitHubApp = class {
203
234
  * `SPENT` when none is left. A 404 is null where `missing` allows it; a
204
235
  * 401 is `REFUSED` where `refused` asks, for a token to be issued again;
205
236
  * any other answer than a 2xx says GitHub's status and the path, and a
206
- * redirect is never followed.
237
+ * redirect is never followed. It ends at its own deadline, or at the
238
+ * caller's `signal`, whichever comes first.
207
239
  */
208
240
  async #call(path, request) {
209
241
  if (request.budget !== void 0 && !spend(request.budget)) throw SPENT;
@@ -212,7 +244,7 @@ var GitHubApp = class {
212
244
  response = await this.#fetch(`${this.apiUrl}${path}`, {
213
245
  method: request.method,
214
246
  redirect: "manual",
215
- signal: AbortSignal.timeout(DEADLINE_MS),
247
+ signal: request.signal === void 0 ? AbortSignal.timeout(DEADLINE_MS) : AbortSignal.any([AbortSignal.timeout(DEADLINE_MS), request.signal]),
216
248
  headers: {
217
249
  accept: "application/vnd.github+json",
218
250
  authorization: `Bearer ${request.token}`,
@@ -221,7 +253,7 @@ var GitHubApp = class {
221
253
  }
222
254
  });
223
255
  } catch (cause) {
224
- throw new GitHubAppUnavailable("GitHub could not be reached", { cause });
256
+ throw new GitHubAppUnavailable(request.signal?.aborted === true ? "GitHub did not answer in time" : "GitHub could not be reached", { cause });
225
257
  }
226
258
  if (response.ok) try {
227
259
  return await response.json();
@@ -892,9 +924,14 @@ function checkAudience(audience) {
892
924
  /**
893
925
  * Cloudflare Access in front of coffre: every request carries Access's
894
926
  * signed assertion, checked against the team's keys and the application's
895
- * AUD tag.
927
+ * AUD tag. A browser's first request signs its person in to a session of
928
+ * coffre's, which every later one shows beside the assertion; the CLI and
929
+ * machines are not served behind Access yet.
896
930
  *
897
931
  * cloudflareAccess({ teamDomain: 'acme.cloudflareaccess.com', audience: env.ACCESS_AUD })
932
+ *
933
+ * `browserSessionHours`: the longest that session lasts, 12 hours unless
934
+ * set, at most a week. Access's own session is the one people see.
898
935
  */
899
936
  function cloudflareAccess(options) {
900
937
  const domain = options.teamDomain.trim();
@@ -907,7 +944,8 @@ function cloudflareAccess(options) {
907
944
  issuer,
908
945
  jwksUrl: `${issuer}/cdn-cgi/access/certs`,
909
946
  audience: checkAudience(options.audience.trim())
910
- }
947
+ },
948
+ browserSessionHours: lifetime(options.browserSessionHours, "browserSessionHours", 12, 168)
911
949
  };
912
950
  return { resolve: () => config };
913
951
  }
@@ -943,473 +981,161 @@ function toSignin(options) {
943
981
  };
944
982
  }
945
983
  //#endregion
946
- //#region src/identity/constraints.ts
984
+ //#region src/identity/profiles.ts
985
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
986
+ /** A Kubernetes namespace (a DNS label) and service account (a DNS subdomain), as its tokens' `sub` names them. */
987
+ 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])?)$/;
988
+ /** A Google service account's unique ID: digits, 21 of them today. */
989
+ const GOOGLE_ID = /^[1-9]\d{0,31}$/;
990
+ const AZURE_V1 = /^https:\/\/sts\.windows\.net\/([0-9a-f-]{36})\/$/;
991
+ const AZURE_V2 = /^https:\/\/login\.microsoftonline\.com\/([0-9a-f-]{36})\/v2\.0$/;
992
+ const FLY_ISSUER = /^https:\/\/oidc\.fly\.io\/[a-z0-9][a-z0-9-]{0,62}$/;
947
993
  /**
948
- * A `narrow` child's limits (docs/design/workload-access.md, section 8.4):
949
- * the places, credentials, methods and path prefixes it may reach, each
950
- * left out for no limit of its own. A child holds the intersection of what
951
- * it asked and what its parent holds, computed when it is made and stored
952
- * under its row's MAC, and every operation it asks for is checked against
953
- * them by `constraintsAllow`, on the URL the proxy is about to send.
954
- *
955
- * parent { credentials: ['stripe', 'openai'] } child asks { credentials: ['stripe'], paths: ['/v1/refunds'] }
956
- * child { credentials: ['stripe'], paths: ['/v1/refunds'] }
957
- * POST https://api.stripe.com/v1/refunds/re_1 allowed
958
- * POST https://api.stripe.com/v1/refunds/%2e%2e/charges refused: it is /v1/charges once parsed
959
- * POST https://api.stripe.com/v1/refundsX refused: a prefix matches whole segments
994
+ * Fly's IDs are digits in its documentation's tokens, unchecked live: kept
995
+ * loose, which fails closed, since a token's `org_id` and `app_id` are IDs
996
+ * and a binding naming a name matches none.
960
997
  */
961
- /** The most entries in each list. */
962
- const MAX_CONSTRAINTS = 32;
963
- /** A constraint that does not parse, said so the caller can fix it. */
964
- var ConstraintsInvalid = class extends Error {
965
- constructor(message) {
966
- super(message);
967
- this.name = "ConstraintsInvalid";
998
+ const FLY_ID = /^[A-Za-z0-9_-]{1,64}$/;
999
+ const VERCEL_ISSUER = /^https:\/\/oidc\.vercel\.com(\/[a-z0-9][a-z0-9-]{0,62})?$/;
1000
+ const VERCEL_OWNER = /^(team_)?[A-Za-z0-9]{8,64}$/;
1001
+ const VERCEL_PROJECT = /^prj_[A-Za-z0-9]{8,64}$/;
1002
+ /** `production`, `preview`, `development`, or a custom environment's slug. */
1003
+ const VERCEL_ENVIRONMENT = /^[a-z0-9][a-z0-9-]{0,63}$/;
1004
+ const AWS_ACCOUNT = /^\d{12}$/;
1005
+ /** A role's unique ID: `AROA`, then its own characters. */
1006
+ const AWS_ROLE_ID = /^AROA[A-Z0-9]{8,124}$/;
1007
+ function shaped(claims, name, pattern, what) {
1008
+ if (!pattern.test(claims[name])) throw new BindingInvalid(`${name} is ${what}`);
1009
+ }
1010
+ const none = () => null;
1011
+ const PROFILE_RULES = {
1012
+ kubernetes: {
1013
+ binding({ claims }) {
1014
+ const sub = SERVICE_ACCOUNT_SUB.exec(claims.sub);
1015
+ if (sub === null) throw new BindingInvalid("sub is the service account's, system:serviceaccount:<namespace>:<name>");
1016
+ 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}'");
1017
+ for (const [name, value] of [["kubernetes.io.namespace", sub[1]], ["kubernetes.io.serviceaccount.name", sub[3]]]) if (claims[name] !== void 0 && claims[name] !== value) throw new BindingInvalid(`${name} is ${value}, as its sub says`);
1018
+ },
1019
+ token(claims) {
1020
+ const sub = SERVICE_ACCOUNT_SUB.exec(String(claims.sub));
1021
+ if (sub === null) return "the token's sub is no service account's";
1022
+ const namespace = claimAt(claims, "kubernetes.io.namespace");
1023
+ const name = claimAt(claims, "kubernetes.io.serviceaccount.name");
1024
+ return namespace === sub[1] && name === sub[3] ? null : "the token names another service account under kubernetes.io than its sub";
1025
+ }
1026
+ },
1027
+ gcp: {
1028
+ binding({ claims }) {
1029
+ 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)'");
1030
+ },
1031
+ token: none
1032
+ },
1033
+ azure: {
1034
+ binding({ issuer, claims }, policy) {
1035
+ const tenant = AZURE_V1.exec(issuer)?.[1] ?? AZURE_V2.exec(issuer)?.[1];
1036
+ if (tenant === void 0 || !UUID.test(tenant)) 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");
1037
+ shaped(claims, "tid", UUID, "the tenant's ID");
1038
+ if (claims.tid !== tenant) throw new BindingInvalid("tid is the tenant its issuer names");
1039
+ shaped(claims, "oid", UUID, "the managed identity's object ID (its principal ID): az identity show --query principalId");
1040
+ if (AZURE_V2.test(issuer) && !UUID.test(policy.audience ?? "")) 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");
1041
+ },
1042
+ token(claims, binding) {
1043
+ const version = AZURE_V1.test(binding.issuer) ? "1.0" : "2.0";
1044
+ return claims.ver === version ? null : `the token is of version ${JSON.stringify(claims.ver ?? null)}, and its binding's issuer issues ${version}`;
1045
+ }
1046
+ },
1047
+ fly: {
1048
+ binding({ issuer, claims }) {
1049
+ if (!FLY_ISSUER.test(issuer)) throw new BindingInvalid("a fly binding's issuer is https://oidc.fly.io/<organization>, by its slug");
1050
+ shaped(claims, "org_id", FLY_ID, "the organization's ID, as its tokens' org_id says it");
1051
+ shaped(claims, "app_id", FLY_ID, "the app's ID, as its tokens' app_id says it");
1052
+ },
1053
+ token: none
1054
+ },
1055
+ vercel: {
1056
+ binding({ issuer, claims }) {
1057
+ 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)");
1058
+ shaped(claims, "owner_id", VERCEL_OWNER, "the team's ID, team_…, as .vercel/project.json's orgId says it");
1059
+ shaped(claims, "project_id", VERCEL_PROJECT, "the project's ID, prj_…, as .vercel/project.json's projectId says it");
1060
+ shaped(claims, "environment", VERCEL_ENVIRONMENT, "production, preview, development or a custom environment's slug");
1061
+ },
1062
+ token: none
1063
+ },
1064
+ aws: {
1065
+ binding({ claims }) {
1066
+ const extra = Object.keys(claims).filter((name) => name !== "account" && name !== "role_id");
1067
+ if (extra.length > 0) throw new BindingInvalid(`an aws binding names its role's account and role_id alone, not ${extra.join(", ")}`);
1068
+ shaped(claims, "account", AWS_ACCOUNT, "the account's 12 digits");
1069
+ 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");
1070
+ },
1071
+ token: none
968
1072
  }
969
1073
  };
970
- const PLACE = /^[a-z0-9][a-z0-9-]{0,62}\/[a-z0-9][a-z0-9-]{0,62}(@me)?$/;
971
- /** A path segment as a constraint names one: no escape, no `;`, no dot segment. */
972
- const SEGMENT = /^[A-Za-z0-9\-_~!$&'()*+,=:@.]+$/;
973
- /**
974
- * What a path may not hold for a constrained session, since an upstream
975
- * might read a segment otherwise than coffre: an escaped `.`, `/` or `\`,
976
- * a `%25` (double encoding), or a `;`, raw or escaped
977
- * (`/v1/refunds/..;/charges` and `/v1/refunds/..%3b/charges` are
978
- * `/v1/charges` to Tomcat).
979
- */
980
- const AMBIGUOUS = /%2e|%2f|%5c|%25|%3b|;/i;
981
- function list(value, what, valid) {
982
- if (value === void 0) return void 0;
983
- if (!Array.isArray(value) || value.length > 32 || value.some((item) => typeof item !== "string" || !valid(item))) throw new ConstraintsInvalid(`${what} lists at most 32 of them`);
984
- return [...new Set(value)].sort();
985
- }
986
- function isPrefix(path) {
987
- if (path === "/") return true;
988
- if (!path.startsWith("/") || path.endsWith("/")) return false;
989
- return path.slice(1).split("/").every((segment) => SEGMENT.test(segment) && segment !== "." && segment !== "..");
990
- }
991
- /** Whether `path` is `prefix` or below it, by whole segments. */
992
- function under(path, prefix) {
993
- return prefix === "/" || path === prefix || path.startsWith(`${prefix}/`);
994
- }
995
1074
  /**
996
- * Constraints as a child asks for them, checked and canonical: each list
997
- * sorted, without duplicates; methods as Fetch sends them; prefixes absolute,
998
- * with no trailing slash, escape, `;` or dot segment, and none under
999
- * another, which it would add nothing to. Throws `ConstraintsInvalid`.
1075
+ * The audiences a token of a binding may name, the first the one its SDK
1076
+ * asks for: the session's key, `<publicUrl>#jkt=<thumbprint>`, for the
1077
+ * platforms whose caller picks the audience, and `?jkt=` for one that
1078
+ * refuses a `#` in it (section 4.2); the exact audience of a platform that
1079
+ * fixes it; this instance's URL for every other.
1000
1080
  */
1001
- function checkConstraints(input) {
1002
- if (typeof input !== "object" || input === null || Array.isArray(input)) throw new ConstraintsInvalid("constraints are an object");
1003
- const { places, credentials, methods, paths, ...rest } = input;
1004
- if (Object.keys(rest).length > 0) throw new ConstraintsInvalid(`constraints hold places, credentials, methods and paths, not ${Object.keys(rest).join(", ")}`);
1005
- const checked = {};
1006
- const placeList = list(places, "places", (place) => PLACE.test(place));
1007
- const credentialList = list(credentials, "credentials", (name) => CREDENTIAL_NAME.test(name));
1008
- const methodList = list(Array.isArray(methods) ? methods.map((method) => typeof method === "string" && METHOD_TOKEN.test(method) ? fetchMethod$1(method) : method) : methods, "methods", (method) => METHOD_TOKEN.test(method));
1009
- const pathList = list(paths, "paths", isPrefix);
1010
- if (placeList !== void 0) checked.places = placeList;
1011
- if (credentialList !== void 0) checked.credentials = credentialList;
1012
- if (methodList !== void 0) checked.methods = methodList;
1013
- if (pathList !== void 0) checked.paths = outermost(pathList);
1014
- return checked;
1015
- }
1016
- /** The prefixes no other one is above. */
1017
- function outermost(paths) {
1018
- return paths.filter((path) => !paths.some((other) => other !== path && under(path, other)));
1019
- }
1020
- function both(a, b) {
1021
- if (a === void 0) return b;
1022
- if (b === void 0) return a;
1023
- return a.filter((item) => b.includes(item));
1081
+ function expectedAudiences(profile, policy, expected) {
1082
+ if (KEY_NAMING_PROFILES.includes(profile) || policy.keyAudience === true) return [`${expected.publicUrl}#jkt=${expected.jkt}`, `${expected.publicUrl}?jkt=${expected.jkt}`];
1083
+ return [policy.audience ?? expected.publicUrl];
1024
1084
  }
1085
+ //#endregion
1086
+ //#region src/identity/workload-token.ts
1025
1087
  /**
1026
- * What a child holds: what it asked within what its parent holds, list by
1027
- * list, and for paths each prefix of one side that is under one of the
1028
- * other's. A parent with none is a root, which only its scope bounds. Never
1029
- * wider than either: whatever `intersect(a, b)` allows, `a` and `b` allow.
1088
+ * An ID token a CI platform signed for a run, as the exchange checks it
1089
+ * (docs/design/oidc.md, section 3). The checks run in this order; each
1090
+ * refusal says which, as a reason a CI user can act on.
1030
1091
  */
1031
- function intersect(parent, child) {
1032
- if (parent === null) return child;
1033
- const result = {};
1034
- const places = both(parent.places, child.places);
1035
- const credentials = both(parent.credentials, child.credentials);
1036
- const methods = both(parent.methods, child.methods);
1037
- if (places !== void 0) result.places = places;
1038
- if (credentials !== void 0) result.credentials = credentials;
1039
- if (methods !== void 0) result.methods = methods;
1040
- if (parent.paths === void 0 || child.paths === void 0) {
1041
- const paths = parent.paths ?? child.paths;
1042
- if (paths !== void 0) result.paths = paths;
1043
- } else {
1044
- const kept = [...child.paths.filter((path) => parent.paths.some((prefix) => under(path, prefix))), ...parent.paths.filter((path) => child.paths.some((prefix) => under(path, prefix)))];
1045
- result.paths = outermost([...new Set(kept)].sort());
1092
+ /** A compact JWS is three base64url parts; the whole token at most this long. */
1093
+ const MAX_TOKEN_BYTES = 8192;
1094
+ /** Each side of every time check. */
1095
+ const CLOCK_TOLERANCE_SECONDS = 30;
1096
+ /** The oldest token accepted, by its `iat`: tokens handed to a job at its start fit, day-old ones do not. */
1097
+ const MAX_TOKEN_AGE_SECONDS = 3600;
1098
+ /** RS256 and ES256 (P-256), as for Access assertions: never `none`, never HS*. */
1099
+ const WORKLOAD_ALGORITHMS = ["RS256", "ES256"];
1100
+ var WorkloadTokenRefused = class extends Error {
1101
+ reason;
1102
+ constructor(reason, message) {
1103
+ super(message);
1104
+ this.name = "WorkloadTokenRefused";
1105
+ this.reason = reason;
1046
1106
  }
1047
- return result;
1048
- }
1049
- /** The constraints as a row's `constraints` column and its MAC hold them: `checkConstraints`'s keys in order. */
1050
- function constraintsText(constraints) {
1051
- const { places, credentials, methods, paths } = constraints;
1052
- return JSON.stringify({
1053
- places,
1054
- credentials,
1055
- methods,
1056
- paths
1057
- });
1058
- }
1059
- /**
1060
- * Whether one operation is within the constraints: its place and credential
1061
- * named, and, for one that sends a request upstream, its method and the
1062
- * path of the URL it is about to send, as the WHATWG parser resolved it.
1063
- * An operation with no request to check (`sign`, `verify`, `mint`, the
1064
- * tunnel) is refused wherever methods or paths are limited: a constraint
1065
- * that cannot be checked refuses.
1066
- */
1067
- function constraintsAllow(constraints, operation) {
1068
- if (constraints === null) return true;
1069
- if (constraints.places !== void 0 && !constraints.places.includes(operation.place)) return false;
1070
- if (constraints.credentials !== void 0 && !constraints.credentials.includes(operation.credential)) return false;
1071
- if (constraints.methods === void 0 && constraints.paths === void 0) return true;
1072
- if (operation.request === void 0) return false;
1073
- if (constraints.methods !== void 0 && !(METHOD_TOKEN.test(operation.request.method) && constraints.methods.includes(fetchMethod$1(operation.request.method)))) return false;
1074
- if (constraints.paths === void 0) return true;
1075
- let path;
1076
- try {
1077
- path = new URL(String(operation.request.url)).pathname;
1078
- } catch {
1079
- return false;
1080
- }
1081
- if (AMBIGUOUS.test(path)) return false;
1082
- return constraints.paths.some((prefix) => under(path, prefix));
1083
- }
1084
- //#endregion
1085
- //#region src/identity/dpop.ts
1086
- /**
1087
- * Checking a workload's proof (docs/design/workload-access.md, section
1088
- * 5.1): the verifying half of `@coffre/client/dpop`, whose canonicalization
1089
- * it runs, so both sides agree on every byte. Cheapest first:
1090
- *
1091
- * 1. shape at most 2 KiB, `typ` exactly `dpop+jwt`, `alg` exactly `ES256`
1092
- * 2. the key `jwk` exactly `kty`, `crv`, `x` and `y`, a point on P-256
1093
- * 3. claims `jti` 16 bytes, `iat` an integer, `hdr` at most 32 names, none unsigned
1094
- * (`parseProof`, no I/O)
1095
- * 4. the session row, from the token's hash: the server's, between the two
1096
- * 5. key and signature the thumbprint is the row's `jkt`, then ES256
1097
- * 6. what was signed `htm`, `htu`, `ath`, `req`, then `iat` within ±300 s
1098
- * (`verifyProof`)
1099
- * 7. the gate's nonce and `jti`: the server's again (`Gate`)
1100
- *
1101
- * Each claim the caller expects (`ath` with a token, `hdr` and `req` with a
1102
- * request's content) must be there, and one it does not expect must not.
1103
- * Two signatures of one payload, `(r, s)` and `(r, n − s)`, both verify:
1104
- * they carry one `jti`, which the gate takes once.
1105
- */
1106
- /** How far a proof's `iat` may be from now: the nonce, not the clock, is what makes a proof fresh. */
1107
- const PROOF_SKEW_SECONDS = 300;
1108
- const refuse = (reason, message) => ({
1109
- ok: false,
1110
- reason,
1111
- message
1112
- });
1113
- const DECODER = new TextDecoder("utf-8", { fatal: true });
1114
- const ENCODER = new TextEncoder();
1115
- const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9a-z-]+$/;
1116
- const CLAIMS = /* @__PURE__ */ new Set([
1117
- "jti",
1118
- "htm",
1119
- "htu",
1120
- "iat",
1121
- "ath",
1122
- "nonce",
1123
- "hdr",
1124
- "req"
1125
- ]);
1126
- /** A part of the proof as a JSON object, or null for anything else. */
1127
- function jsonPart(part) {
1128
- const bytes = fromBase64url(part);
1129
- if (bytes === null) return null;
1130
- try {
1131
- const value = JSON.parse(DECODER.decode(bytes));
1132
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
1133
- } catch {
1134
- return null;
1135
- }
1136
- }
1137
- function exactly(value, keys) {
1138
- return Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
1139
- }
1140
- const isDigest = (value) => typeof value === "string" && fromBase64url(value)?.length === 32;
1141
- /** Steps 1 to 3: the proof's shape, its key's and its claims', with no I/O. */
1142
- function parseProof(proof) {
1143
- if (proof.length > MAX_PROOF_LENGTH$1) return refuse("malformed", `a proof is at most ${MAX_PROOF_LENGTH$1} characters`);
1144
- const parts = proof.split(".");
1145
- if (parts.length !== 3) return refuse("malformed", "a proof is a compact JWS: three parts");
1146
- const [headerPart, payloadPart, signaturePart] = parts;
1147
- const header = jsonPart(headerPart);
1148
- if (header === null || !exactly(header, [
1149
- "typ",
1150
- "alg",
1151
- "jwk"
1152
- ]) || header.typ !== "dpop+jwt" || header.alg !== "ES256") return refuse("malformed", "a proof's header is exactly { typ: \"dpop+jwt\", alg: \"ES256\", jwk }");
1153
- const jwk = header.jwk;
1154
- if (typeof jwk !== "object" || jwk === null || Array.isArray(jwk) || !exactly(jwk, [
1155
- "kty",
1156
- "crv",
1157
- "x",
1158
- "y"
1159
- ]) || jwk.kty !== "EC" || jwk.crv !== "P-256" || !isCoordinate(jwk.x) || !isCoordinate(jwk.y)) return refuse("key", "a proof's key is a P-256 public key: exactly kty, crv, x and y");
1160
- const signature = fromBase64url(signaturePart);
1161
- if (signature === null || signature.length !== 64) return refuse("malformed", "an ES256 signature is 64 bytes, r then s");
1162
- const claims = jsonPart(payloadPart);
1163
- if (claims === null || Object.keys(claims).some((name) => !CLAIMS.has(name))) return refuse("malformed", "a proof's claims are jti, htm, htu, iat, and ath, nonce, hdr, req where they apply");
1164
- if (typeof claims.jti !== "string" || fromBase64url(claims.jti)?.length !== 16) return refuse("malformed", "jti is 16 random bytes, in base64url");
1165
- if (typeof claims.htm !== "string" || !METHOD_TOKEN.test(claims.htm)) return refuse("malformed", "htm is the request's method");
1166
- if (typeof claims.htu !== "string") return refuse("malformed", "htu is the request's URL");
1167
- if (!Number.isSafeInteger(claims.iat)) return refuse("malformed", "iat is an integer, in seconds");
1168
- if (claims.ath !== void 0 && !isDigest(claims.ath)) return refuse("malformed", "ath is a SHA-256, in base64url");
1169
- if (claims.nonce !== void 0 && (typeof claims.nonce !== "string" || !/^[\x21-\x7e]{1,128}$/.test(claims.nonce))) return refuse("malformed", "nonce is the one coffre gave");
1170
- if (claims.hdr === void 0 !== (claims.req === void 0)) return refuse("malformed", "hdr and req come together");
1171
- let hdr = null;
1172
- if (claims.hdr !== void 0) {
1173
- if (typeof claims.hdr !== "string" || !isDigest(claims.req)) return refuse("malformed", "hdr names headers, and req is a SHA-256");
1174
- hdr = claims.hdr === "" ? [] : claims.hdr.split(" ");
1175
- if (hdr.length > MAX_SIGNED_HEADERS$1) return refuse("malformed", `a proof signs at most ${MAX_SIGNED_HEADERS$1} headers`);
1176
- if (hdr.some((name) => !HEADER_NAME.test(name) || UNSIGNED_HEADERS.has(name)) || new Set(hdr).size !== hdr.length) return refuse("malformed", "hdr names each header once, in lower case, and none the transport or the request to coffre owns");
1177
- }
1178
- return {
1179
- ok: true,
1180
- jwk,
1181
- claims,
1182
- hdr,
1183
- signingInput: `${headerPart}.${payloadPart}`,
1184
- signature
1185
- };
1186
- }
1187
- function isCoordinate(value) {
1188
- return typeof value === "string" && fromBase64url(value)?.length === 32;
1189
- }
1190
- /**
1191
- * Steps 5 and 6: the proof against its request, `parseProof`'s first when
1192
- * given a string. Nothing here reads a store, so the gate (step 7) still
1193
- * decides whether this `jti` was seen.
1194
- */
1195
- async function verifyProof(proof, expect) {
1196
- const parsed = typeof proof === "string" ? parseProof(proof) : proof;
1197
- if (!parsed.ok) return parsed;
1198
- const { jwk, claims, hdr } = parsed;
1199
- const jkt = await thumbprint$1(jwk);
1200
- if (expect.jkt !== void 0 && jkt !== expect.jkt) return refuse("jkt", "the proof is signed by another key than the session's");
1201
- let key;
1202
- try {
1203
- key = await crypto.subtle.importKey("jwk", {
1204
- kty: jwk.kty,
1205
- crv: jwk.crv,
1206
- x: jwk.x,
1207
- y: jwk.y
1208
- }, {
1209
- name: "ECDSA",
1210
- namedCurve: "P-256"
1211
- }, false, ["verify"]);
1212
- } catch {
1213
- return refuse("key", "the proof's key is no point on P-256");
1214
- }
1215
- if (!await crypto.subtle.verify({
1216
- name: "ECDSA",
1217
- hash: "SHA-256"
1218
- }, key, parsed.signature, ENCODER.encode(parsed.signingInput))) return refuse("signature", "the proof's signature does not verify");
1219
- if (claims.htm !== fetchMethod$1(expect.method)) return refuse("htm", "the proof signs another method");
1220
- let htu;
1221
- try {
1222
- htu = canonicalHtu$1(expect.url);
1223
- } catch {
1224
- return refuse("htu", "the request's URL cannot be signed");
1225
- }
1226
- if (claims.htu !== htu) return refuse("htu", "the proof signs another URL");
1227
- if (expect.token === void 0 !== (claims.ath === void 0)) return refuse("ath", expect.token === void 0 ? "this proof signs no token" : "the proof signs no token: ath");
1228
- if (expect.token !== void 0 && claims.ath !== await tokenDigest(expect.token)) return refuse("ath", "the proof signs another token");
1229
- if (expect.content === void 0 !== (hdr === null)) return refuse("req", expect.content === void 0 ? "this proof signs no request content" : "the proof signs no request content: hdr and req");
1230
- if (expect.content !== void 0) {
1231
- const headers = [];
1232
- for (const name of hdr) {
1233
- const value = expect.content.headers.get(name);
1234
- if (value === null) return refuse("req", `the proof signs a header the request lacks: ${name}`);
1235
- headers.push([name, value]);
1236
- }
1237
- let digest;
1238
- try {
1239
- digest = await requestDigest({
1240
- ...sentTarget$1(expect.url),
1241
- headers,
1242
- body: expect.content.body
1243
- });
1244
- } catch {
1245
- return refuse("req", "the request cannot be signed: a line break in its path, query or headers");
1246
- }
1247
- if (claims.req !== digest) return refuse("req", "the proof signs another path as sent, query, header or body");
1248
- }
1249
- const skew = expect.skewSeconds ?? 300;
1250
- const now = Math.floor((expect.now ?? Date.now()) / 1e3);
1251
- if (Math.abs(now - claims.iat) > skew) return refuse("iat", `the proof was made more than ${skew} seconds from now`);
1252
- return {
1253
- ok: true,
1254
- jkt,
1255
- jti: claims.jti,
1256
- nonce: claims.nonce ?? null,
1257
- iat: claims.iat,
1258
- hdr
1259
- };
1260
- }
1261
- //#endregion
1262
- //#region src/identity/profile-rules.ts
1263
- const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
1264
- /** A Kubernetes namespace (a DNS label) and service account (a DNS subdomain), as its tokens' `sub` names them. */
1265
- 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])?)$/;
1266
- /** A Google service account's unique ID: digits, 21 of them today. */
1267
- const GOOGLE_ID = /^[1-9]\d{0,31}$/;
1268
- const AZURE_V1 = /^https:\/\/sts\.windows\.net\/([0-9a-f-]{36})\/$/;
1269
- const AZURE_V2 = /^https:\/\/login\.microsoftonline\.com\/([0-9a-f-]{36})\/v2\.0$/;
1270
- const FLY_ISSUER = /^https:\/\/oidc\.fly\.io\/[a-z0-9][a-z0-9-]{0,62}$/;
1271
- /**
1272
- * Fly's IDs are digits in its documentation's tokens, unchecked live: kept
1273
- * loose, which fails closed, since a token's `org_id` and `app_id` are IDs
1274
- * and a binding naming a name matches none.
1275
- */
1276
- const FLY_ID = /^[A-Za-z0-9_-]{1,64}$/;
1277
- const VERCEL_ISSUER = /^https:\/\/oidc\.vercel\.com(\/[a-z0-9][a-z0-9-]{0,62})?$/;
1278
- const VERCEL_OWNER = /^(team_)?[A-Za-z0-9]{8,64}$/;
1279
- const VERCEL_PROJECT = /^prj_[A-Za-z0-9]{8,64}$/;
1280
- /** `production`, `preview`, `development`, or a custom environment's slug. */
1281
- const VERCEL_ENVIRONMENT = /^[a-z0-9][a-z0-9-]{0,63}$/;
1282
- const AWS_ACCOUNT = /^\d{12}$/;
1283
- /** A role's unique ID: `AROA`, then its own characters. */
1284
- const AWS_ROLE_ID = /^AROA[A-Z0-9]{8,124}$/;
1285
- function shaped(claims, name, pattern, what) {
1286
- if (!pattern.test(claims[name])) throw new BindingInvalid(`${name} is ${what}`);
1287
- }
1288
- const none = () => null;
1289
- const PROFILE_RULES = {
1290
- kubernetes: {
1291
- binding({ claims }) {
1292
- const sub = SERVICE_ACCOUNT_SUB.exec(claims.sub);
1293
- if (sub === null) throw new BindingInvalid("sub is the service account's, system:serviceaccount:<namespace>:<name>");
1294
- 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}'");
1295
- for (const [name, value] of [["kubernetes.io.namespace", sub[1]], ["kubernetes.io.serviceaccount.name", sub[3]]]) if (claims[name] !== void 0 && claims[name] !== value) throw new BindingInvalid(`${name} is ${value}, as its sub says`);
1296
- },
1297
- token(claims) {
1298
- const sub = SERVICE_ACCOUNT_SUB.exec(String(claims.sub));
1299
- if (sub === null) return "the token's sub is no service account's";
1300
- const namespace = claimAt(claims, "kubernetes.io.namespace");
1301
- const name = claimAt(claims, "kubernetes.io.serviceaccount.name");
1302
- return namespace === sub[1] && name === sub[3] ? null : "the token names another service account under kubernetes.io than its sub";
1303
- }
1304
- },
1305
- gcp: {
1306
- binding({ claims }) {
1307
- 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)'");
1308
- },
1309
- token: none
1310
- },
1311
- azure: {
1312
- binding({ issuer, claims }, policy) {
1313
- const tenant = AZURE_V1.exec(issuer)?.[1] ?? AZURE_V2.exec(issuer)?.[1];
1314
- if (tenant === void 0 || !UUID.test(tenant)) 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");
1315
- shaped(claims, "tid", UUID, "the tenant's ID");
1316
- if (claims.tid !== tenant) throw new BindingInvalid("tid is the tenant its issuer names");
1317
- shaped(claims, "oid", UUID, "the managed identity's object ID (its principal ID): az identity show --query principalId");
1318
- if (AZURE_V2.test(issuer) && !UUID.test(policy.audience ?? "")) 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");
1319
- },
1320
- token(claims, binding) {
1321
- const version = AZURE_V1.test(binding.issuer) ? "1.0" : "2.0";
1322
- return claims.ver === version ? null : `the token is of version ${JSON.stringify(claims.ver ?? null)}, and its binding's issuer issues ${version}`;
1323
- }
1324
- },
1325
- fly: {
1326
- binding({ issuer, claims }) {
1327
- if (!FLY_ISSUER.test(issuer)) throw new BindingInvalid("a fly binding's issuer is https://oidc.fly.io/<organization>, by its slug");
1328
- shaped(claims, "org_id", FLY_ID, "the organization's ID, as its tokens' org_id says it");
1329
- shaped(claims, "app_id", FLY_ID, "the app's ID, as its tokens' app_id says it");
1330
- },
1331
- token: none
1332
- },
1333
- vercel: {
1334
- binding({ issuer, claims }) {
1335
- 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)");
1336
- shaped(claims, "owner_id", VERCEL_OWNER, "the team's ID, team_…, as .vercel/project.json's orgId says it");
1337
- shaped(claims, "project_id", VERCEL_PROJECT, "the project's ID, prj_…, as .vercel/project.json's projectId says it");
1338
- shaped(claims, "environment", VERCEL_ENVIRONMENT, "production, preview, development or a custom environment's slug");
1339
- },
1340
- token: none
1341
- },
1342
- aws: {
1343
- binding({ claims }) {
1344
- const extra = Object.keys(claims).filter((name) => name !== "account" && name !== "role_id");
1345
- if (extra.length > 0) throw new BindingInvalid(`an aws binding names its role's account and role_id alone, not ${extra.join(", ")}`);
1346
- shaped(claims, "account", AWS_ACCOUNT, "the account's 12 digits");
1347
- 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");
1348
- },
1349
- token: none
1350
- }
1351
- };
1352
- /**
1353
- * The audiences a token of a binding may name, the first the one its SDK
1354
- * asks for: the session's key, `<publicUrl>#jkt=<thumbprint>`, for the
1355
- * platforms whose caller picks the audience, and `?jkt=` for one that
1356
- * refuses a `#` in it (section 4.2); the exact audience of a platform that
1357
- * fixes it; this instance's URL for every other.
1358
- */
1359
- function expectedAudiences(profile, policy, expected) {
1360
- if (KEY_NAMING_PROFILES.includes(profile) || policy.keyAudience === true) return [`${expected.publicUrl}#jkt=${expected.jkt}`, `${expected.publicUrl}?jkt=${expected.jkt}`];
1361
- return [policy.audience ?? expected.publicUrl];
1362
- }
1363
- //#endregion
1364
- //#region src/identity/workload-token.ts
1365
- /**
1366
- * An ID token a CI platform signed for a run, as the exchange checks it
1367
- * (docs/design/oidc.md, section 3). The checks run in this order; each
1368
- * refusal says which, as a reason a CI user can act on.
1369
- */
1370
- /** A compact JWS is three base64url parts; the whole token at most this long. */
1371
- const MAX_TOKEN_BYTES = 8192;
1372
- /** Each side of every time check. */
1373
- const CLOCK_TOLERANCE_SECONDS = 30;
1374
- /** The oldest token accepted, by its `iat`: tokens handed to a job at its start fit, day-old ones do not. */
1375
- const MAX_TOKEN_AGE_SECONDS = 3600;
1376
- /** RS256 and ES256 (P-256), as for Access assertions: never `none`, never HS*. */
1377
- const WORKLOAD_ALGORITHMS = ["RS256", "ES256"];
1378
- var WorkloadTokenRefused = class extends Error {
1379
- reason;
1380
- constructor(reason, message) {
1381
- super(message);
1382
- this.name = "WorkloadTokenRefused";
1383
- this.reason = reason;
1384
- }
1385
- };
1386
- const PART = /^[A-Za-z0-9_-]+$/;
1387
- /** A token's parts and claims, checked for shape and types only. Throws `WorkloadTokenRefused('malformed')`. */
1388
- function decodeWorkloadToken(token) {
1389
- const malformed = (why) => new WorkloadTokenRefused("malformed", `the token ${why}`);
1390
- if (typeof token !== "string" || token.length === 0) throw malformed("is empty");
1391
- if (token.length > 8192) throw malformed(`is longer than ${MAX_TOKEN_BYTES} bytes`);
1392
- const parts = token.split(".");
1393
- if (parts.length !== 3 || !parts.every((part) => PART.test(part))) throw malformed("is not a compact JWS");
1394
- const json = (part) => {
1395
- let value;
1396
- try {
1397
- value = JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
1398
- } catch {
1399
- throw malformed("has a part that is not JSON");
1400
- }
1401
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw malformed("has a part that is not an object");
1402
- return value;
1403
- };
1404
- const [header, claims] = [json(parts[0]), json(parts[1])];
1405
- for (const name of ["iss", "sub"]) if (typeof claims[name] !== "string" || claims[name] === "") throw malformed(`has no ${name}, as a nonempty string`);
1406
- for (const name of ["exp", "iat"]) if (typeof claims[name] !== "number" || !Number.isFinite(claims[name])) throw malformed(`has no ${name}, as a finite number`);
1407
- if (claims.nbf !== void 0 && (typeof claims.nbf !== "number" || !Number.isFinite(claims.nbf))) throw malformed("has an nbf that is not a finite number");
1408
- return {
1409
- header,
1410
- claims,
1411
- signingInputHash: createHash("sha256").update(`${parts[0]}.${parts[1]}`, "ascii").digest()
1412
- };
1107
+ };
1108
+ const PART = /^[A-Za-z0-9_-]+$/;
1109
+ /** A token's parts and claims, checked for shape and types only. Throws `WorkloadTokenRefused('malformed')`. */
1110
+ function decodeWorkloadToken(token) {
1111
+ const malformed = (why) => new WorkloadTokenRefused("malformed", `the token ${why}`);
1112
+ if (typeof token !== "string" || token.length === 0) throw malformed("is empty");
1113
+ if (token.length > 8192) throw malformed(`is longer than ${MAX_TOKEN_BYTES} bytes`);
1114
+ const parts = token.split(".");
1115
+ if (parts.length !== 3 || !parts.every((part) => PART.test(part))) throw malformed("is not a compact JWS");
1116
+ const json = (part) => {
1117
+ let value;
1118
+ try {
1119
+ value = JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
1120
+ } catch {
1121
+ throw malformed("has a part that is not JSON");
1122
+ }
1123
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw malformed("has a part that is not an object");
1124
+ return value;
1125
+ };
1126
+ const [header, claims] = [json(parts[0]), json(parts[1])];
1127
+ if (header.crit !== void 0) throw malformed("names a critical header extension");
1128
+ for (const name of ["iss", "sub"]) {
1129
+ if (typeof claims[name] !== "string" || claims[name] === "") throw malformed(`has no ${name}, as a nonempty string`);
1130
+ if (/[\0\p{Cs}]/u.test(claims[name])) throw malformed(`has an ${name} with a NUL or a lone surrogate`);
1131
+ }
1132
+ for (const name of ["exp", "iat"]) if (typeof claims[name] !== "number" || !Number.isFinite(claims[name])) throw malformed(`has no ${name}, as a finite number`);
1133
+ if (claims.nbf !== void 0 && (typeof claims.nbf !== "number" || !Number.isFinite(claims.nbf))) throw malformed("has an nbf that is not a finite number");
1134
+ return {
1135
+ header,
1136
+ claims,
1137
+ signingInputHash: createHash("sha256").update(`${parts[0]}.${parts[1]}`, "ascii").digest()
1138
+ };
1413
1139
  }
1414
1140
  /**
1415
1141
  * Verify a token under an issuer's keys: the signature by jose, with the
@@ -1620,152 +1346,629 @@ function kidAndUse(jwk) {
1620
1346
  };
1621
1347
  }
1622
1348
  //#endregion
1623
- //#region src/identity/run-proof.ts
1349
+ //#region src/identity/proofs.ts
1350
+ /** 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. */
1351
+ const CARRIED = "sha256:";
1352
+ /** A token's claims and the hash of what was signed, or `malformed`. */
1353
+ function readIdToken(token) {
1354
+ try {
1355
+ return decodeWorkloadToken(token);
1356
+ } catch (error) {
1357
+ if (error instanceof WorkloadTokenRefused) return { refused: "malformed" };
1358
+ throw error;
1359
+ }
1360
+ }
1361
+ /** 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. */
1362
+ function policyOf(binding) {
1363
+ if (binding.policy === null) return null;
1364
+ try {
1365
+ const policy = JSON.parse(binding.policy);
1366
+ return typeof policy === "object" && policy !== null && !Array.isArray(policy) ? policy : void 0;
1367
+ } catch {
1368
+ return;
1369
+ }
1370
+ }
1371
+ /** 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. */
1372
+ function issues(binding, wanted) {
1373
+ return (wanted === "run" ? BEARER_PROFILES : OIDC_PROFILES).includes(binding.profile) && (wanted === "run" ? binding.policy === null : policyOf(binding) != null);
1374
+ }
1375
+ /** The audience a token names, alone; null for none, or several. */
1376
+ function soleAudience(aud) {
1377
+ if (typeof aud === "string") return aud;
1378
+ return Array.isArray(aud) && aud.length === 1 && typeof aud[0] === "string" ? aud[0] : null;
1379
+ }
1380
+ /**
1381
+ * The audiences a binding takes: this instance's URL for a CI run's; for a
1382
+ * session's, its policy's, the session's key or its profile's
1383
+ * (`expectedAudiences`). None for one whose policy does not read.
1384
+ */
1385
+ function audiencesOf(binding, publicUrl, wanted) {
1386
+ const policy = policyOf(binding);
1387
+ if (wanted.kind === "run") return policy === null ? [publicUrl] : [];
1388
+ return policy == null ? [] : expectedAudiences(binding.profile, policy, {
1389
+ publicUrl,
1390
+ jkt: wanted.jkt
1391
+ });
1392
+ }
1393
+ /**
1394
+ * Which audience a token is held to, and the bindings that take it: the
1395
+ * token's own if some binding takes it, otherwise the instance's, 0.14's
1396
+ * rule. A token none takes is refused `audience` once its times are checked.
1397
+ */
1398
+ function audienceTried(aud, bindings, publicUrl, wanted) {
1399
+ const named = soleAudience(aud);
1400
+ const audience = named !== null && bindings.some((binding) => audiencesOf(binding, publicUrl, wanted).includes(named)) ? named : publicUrl;
1401
+ return {
1402
+ audience,
1403
+ taking: bindings.filter((binding) => audiencesOf(binding, publicUrl, wanted).includes(audience))
1404
+ };
1405
+ }
1406
+ /**
1407
+ * A token's times on the vault's clock, `now` in milliseconds, each within
1408
+ * the clock tolerance, as 0.14 held them: not before its `nbf`, to jose's
1409
+ * whole second; before its `exp`, to the millisecond, as 0.14's exchange
1410
+ * checked it again; issued `maxAge` seconds ago at most (an hour,
1411
+ * or any age for a token its platform hands out again), and, where a binding
1412
+ * carries its keys, living `maxLifetime` seconds at most.
1413
+ */
1414
+ function timesRefusal(claims, now, { maxAge = MAX_TOKEN_AGE_SECONDS, maxLifetime = null } = {}) {
1415
+ const seconds = Math.floor(now / 1e3);
1416
+ if (typeof claims.nbf === "number" && claims.nbf > seconds + 30) return "too_old";
1417
+ if (claims.exp <= now / 1e3 - 30) return "expired";
1418
+ if (issuedRefusal(claims.iat, now / 1e3, maxAge ?? Infinity) !== null) return "too_old";
1419
+ if (maxLifetime !== null && claims.exp - claims.iat > maxLifetime) return "too_old";
1420
+ return null;
1421
+ }
1422
+ /** The oldest of `bindings` whose every claim the token carries (`differingClaims`), in the order the bindings' index reads them. */
1423
+ function oldestMatching(bindings, claims) {
1424
+ return [...bindings].sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)).find((binding) => {
1425
+ let expected;
1426
+ try {
1427
+ expected = JSON.parse(binding.claims);
1428
+ } catch {
1429
+ return false;
1430
+ }
1431
+ return typeof expected === "object" && expected !== null && !Array.isArray(expected) && differingClaims(binding.profile, expected, claims).length === 0;
1432
+ }) ?? null;
1433
+ }
1434
+ /** Why a token its binding matched still breaks its profile's own rule (`PROFILE_RULES`: Azure's version, Kubernetes' subject), or null. */
1435
+ function profileRefusal(binding, policy, claims) {
1436
+ const rule = PROFILE_RULES[binding.profile];
1437
+ if (rule === void 0) return null;
1438
+ return rule.token(claims, {
1439
+ issuer: binding.issuer,
1440
+ claims: JSON.parse(binding.claims),
1441
+ policy
1442
+ }) === null ? null : "malformed";
1443
+ }
1444
+ /**
1445
+ * Whether a proof is spent once it is traded, by the SHA-256 of what was
1446
+ * signed: a CI run's token always; a session's token unless it names the
1447
+ * session's key, which works for no other, or its platform hands the same
1448
+ * one out again (`REPEATING_PROFILES`), which spending would refuse.
1449
+ */
1450
+ function spends(binding, policy, wanted) {
1451
+ if (wanted === "run") return true;
1452
+ return policy?.keyAudience !== true && !REPEATING_PROFILES.includes(binding.profile);
1453
+ }
1454
+ /**
1455
+ * A session's hard end, in milliseconds: the earliest of its binding's
1456
+ * `sessionHours` after `at`, where its profile has them (24 unless said),
1457
+ * and, unless the token names the session's key, the token's own `exp`, so
1458
+ * that a copy of it buys no more than the platform's lifetime. `exp` is in
1459
+ * seconds, null for a proof that is no token. A session whose end is not
1460
+ * after `at` is refused `expired`.
1461
+ */
1462
+ function hardEnd(binding, policy, at, exp) {
1463
+ const hours = (POLICY_FIELDS[binding.profile] ?? []).includes("sessionHours") ? policy.sessionHours ?? POLICY_DEFAULTS.sessionHours : null;
1464
+ const ends = [hours === null ? null : at + hours * 36e5, policy.keyAudience === true || exp === null ? null : exp * 1e3].filter((end) => end !== null);
1465
+ return Math.min(...ends.length === 0 ? [at + POLICY_DEFAULTS.sessionHours * 36e5] : ends);
1466
+ }
1467
+ /**
1468
+ * Why a session is refused at its sign-in, from its binding's policy and the
1469
+ * request's address: the deployment lets no binding list reads (`noReads`)
1470
+ * and this one does, or it names its sources and the request came from
1471
+ * outside them, or from nowhere the app could tell. Both are `no_match`, as
1472
+ * the design's refusals have it; 0.14 answered the second `source`.
1473
+ */
1474
+ function sessionRefusal(policy, ip, { noReads }) {
1475
+ if (noReads && policy.reads !== void 0) return "no_match";
1476
+ if (policy.sources !== void 0 && (ip === null || !addressWithin(ip, policy.sources))) return "no_match";
1477
+ return null;
1478
+ }
1479
+ /**
1480
+ * An ID token whose signature verified under `under`, held to the
1481
+ * service's live bindings, in 0.14's order:
1482
+ *
1483
+ * 1. of the bindings that issue what it is traded for (`issues`), those
1484
+ * on its issuer under the keys it was verified under;
1485
+ * 2. the audience tried, and the bindings that take it (`audienceTried`);
1486
+ * 3. its times (`timesRefusal`): any age for a token its platform hands
1487
+ * out again, where a binding that takes it is of such a platform, and
1488
+ * an hour's lifetime at most under keys a binding carries;
1489
+ * 4. that audience, the token's own, alone;
1490
+ * 5. the oldest whose claims match (`oldestMatching`);
1491
+ * 6. an hour's age after all, if the binding that matched is of a
1492
+ * platform that hands out no token twice;
1493
+ * 7. its profile's own rule (`profileRefusal`).
1494
+ *
1495
+ * `bindings` are the sealed rows the read found: a decision that picks the
1496
+ * oldest of several refuses before this if any row it read is not the
1497
+ * vault's, since one passed over would let a later one answer.
1498
+ */
1499
+ function matchIdToken(token, bindings, { under, publicUrl, wanted, now }) {
1500
+ const { claims } = token;
1501
+ const candidates = bindings.filter((binding) => issues(binding, wanted.kind) && binding.issuer === under.issuer && binding.jwksUri === under.jwksUri && claims.iss === under.issuer);
1502
+ if (candidates.length === 0) return { refused: "no_match" };
1503
+ const { audience, taking } = audienceTried(claims.aud, candidates, publicUrl, wanted);
1504
+ const repeats = taking.some((binding) => REPEATING_PROFILES.includes(binding.profile));
1505
+ const times = timesRefusal(claims, now, {
1506
+ maxAge: repeats ? null : MAX_TOKEN_AGE_SECONDS,
1507
+ maxLifetime: under.jwksUri.startsWith("sha256:") ? MAX_TOKEN_AGE_SECONDS : null
1508
+ });
1509
+ if (times !== null) return { refused: times };
1510
+ if (soleAudience(claims.aud) !== audience || taking.length === 0) return { refused: "audience" };
1511
+ const binding = oldestMatching(taking, claims);
1512
+ if (binding === null) return { refused: "no_match" };
1513
+ const policy = policyOf(binding);
1514
+ if (repeats && !REPEATING_PROFILES.includes(binding.profile) && issuedRefusal(claims.iat, now / 1e3) !== null) return { refused: "too_old" };
1515
+ if (policy !== null && profileRefusal(binding, policy, claims) !== null) return { refused: "malformed" };
1516
+ return {
1517
+ binding,
1518
+ policy,
1519
+ claims,
1520
+ spends: spends(binding, policy, wanted.kind) ? token.signingInputHash : null
1521
+ };
1522
+ }
1523
+ /**
1524
+ * Whether a token's signature verifies under keys a binding carries, a JWKS
1525
+ * as its row holds it: null if it does, `unknown_signer` when the set lacks
1526
+ * the key the token names, and `malformed` for any other failure, a
1527
+ * signature that does not verify under it included. The algorithms are
1528
+ * fixed, and nothing is taken from the header but `alg` and `kid`; a set
1529
+ * with several keys the header could name tries each. A token that does
1530
+ * not read as one (`readIdToken`), an unencoded payload's included, is
1531
+ * `malformed` before any key is tried. It checks no claim: the times and
1532
+ * the audience are `matchIdToken`'s.
1533
+ */
1534
+ async function signatureRefusal(token, jwks) {
1535
+ if ("refused" in readIdToken(token)) return "malformed";
1536
+ let keys;
1537
+ try {
1538
+ keys = JSON.parse(jwks);
1539
+ } catch {
1540
+ return "malformed";
1541
+ }
1542
+ const options = { algorithms: [...WORKLOAD_ALGORITHMS] };
1543
+ try {
1544
+ await compactVerify(token, createLocalJWKSet(keys), options);
1545
+ return null;
1546
+ } catch (error) {
1547
+ if (error instanceof errors.JWKSNoMatchingKey) return "unknown_signer";
1548
+ if (!(error instanceof errors.JWKSMultipleMatchingKeys)) return "malformed";
1549
+ for await (const key of error) try {
1550
+ await compactVerify(token, key, options);
1551
+ return null;
1552
+ } catch {}
1553
+ return "malformed";
1554
+ }
1555
+ }
1556
+ /**
1557
+ * The claims of the run a credential was issued for, as its issuer stated
1558
+ * them: those that say which run, each bounded, in the exchange's entry and
1559
+ * the credential's row, so that a read leads back to its run. What the
1560
+ * issuer says, not proof of which run sent the request.
1561
+ */
1562
+ const RUN_CLAIMS = [
1563
+ "sub",
1564
+ "jti",
1565
+ "actor",
1566
+ "event_name",
1567
+ "ref",
1568
+ "base_ref",
1569
+ "head_ref",
1570
+ "sha",
1571
+ "repository",
1572
+ "repository_id",
1573
+ "run_id",
1574
+ "run_attempt",
1575
+ "workflow_ref",
1576
+ "job_workflow_ref",
1577
+ "job_workflow_sha",
1578
+ "environment",
1579
+ "project_path",
1580
+ "project_id",
1581
+ "namespace_id",
1582
+ "pipeline_id",
1583
+ "pipeline_source",
1584
+ "job_id",
1585
+ "kubernetes.io.pod.name"
1586
+ ];
1587
+ const MAX_RUN_CLAIM = 256;
1588
+ /** The run's claims, as the issuer stated them: each a string of 256 characters at most, or a finite number. */
1589
+ function runClaims(claims) {
1590
+ const run = {};
1591
+ for (const name of RUN_CLAIMS) {
1592
+ const value = claimAt(claims, name);
1593
+ if (typeof value === "string") run[name] = value.slice(0, 256);
1594
+ else if (typeof value === "number" && Number.isFinite(value)) run[name] = value;
1595
+ }
1596
+ return run;
1597
+ }
1598
+ //#endregion
1599
+ //#region src/identity/aws.ts
1600
+ const ACCOUNT = /^\d{12}$/;
1601
+ const ASSUMED_ROLE = /^arn:aws:sts::(\d{12}):assumed-role\/([\w+=,.@-]{1,64})\/([\w+=,.@-]{2,64})$/;
1602
+ const ROLE_SESSION = /^(AROA[A-Z0-9]{8,124}):([\w+=,.@-]{2,64})$/;
1603
+ /**
1604
+ * The role a caller's identity is a session of, or why none: an account's
1605
+ * root, a federated user and an IAM user are `no_match`, since each means a
1606
+ * long-lived key on disk, which a workload does not hold, and so is any
1607
+ * other partition than `aws`. An answer whose account, ARN and user ID
1608
+ * disagree is no answer STS gives: `malformed` (0.14's server took it as
1609
+ * STS unavailable).
1610
+ */
1611
+ function assumedRole(identity) {
1612
+ if (!ACCOUNT.test(identity.account)) return { refused: "malformed" };
1613
+ const role = ASSUMED_ROLE.exec(identity.arn);
1614
+ const session = ROLE_SESSION.exec(identity.userId);
1615
+ if (role === null || session === null) return { refused: "no_match" };
1616
+ if (role[1] !== identity.account || session[2] !== role[3]) return { refused: "malformed" };
1617
+ return {
1618
+ account: identity.account,
1619
+ roleId: session[1],
1620
+ arn: identity.arn,
1621
+ role: role[2],
1622
+ session: role[3]
1623
+ };
1624
+ }
1625
+ /** The claims an `aws` binding matches, as the proof makes them. */
1626
+ function awsClaims(identity) {
1627
+ return {
1628
+ account: identity.account,
1629
+ role_id: identity.roleId
1630
+ };
1631
+ }
1632
+ /**
1633
+ * STS's answer held to a service's bindings: the oldest `aws` binding with
1634
+ * a policy that names its role's account and unique ID, and the claims the
1635
+ * session's entry gives, the role's ARN and session name with them. The
1636
+ * request named the session's key and this instance under its signature,
1637
+ * so nothing is spent, and nothing but its binding's hours ends the
1638
+ * session early.
1639
+ */
1640
+ function matchAwsAnswer(answer, bindings) {
1641
+ const candidates = bindings.filter((binding) => binding.profile === "aws" && binding.issuer === PROFILE_URNS.aws && policyOf(binding) != null);
1642
+ if (candidates.length === 0) return { refused: "no_match" };
1643
+ const identity = assumedRole(answer);
1644
+ if ("refused" in identity) return identity;
1645
+ const binding = oldestMatching(candidates, awsClaims(identity));
1646
+ if (binding === null) return { refused: "no_match" };
1647
+ return {
1648
+ binding,
1649
+ claims: {
1650
+ ...awsClaims(identity),
1651
+ arn: identity.arn,
1652
+ session: identity.session
1653
+ }
1654
+ };
1655
+ }
1656
+ //#endregion
1657
+ //#region src/identity/constraints.ts
1658
+ /**
1659
+ * A `narrow` child's limits (docs/design/workload-access.md, section 8.4):
1660
+ * the places, credentials, methods and path prefixes it may reach, each
1661
+ * left out for no limit of its own. A child holds the intersection of what
1662
+ * it asked and what its parent holds, computed when it is made and stored
1663
+ * under its row's MAC, and every operation it asks for is checked against
1664
+ * them by `constraintsAllow`, on the URL the proxy is about to send.
1665
+ *
1666
+ * parent { credentials: ['stripe', 'openai'] } child asks { credentials: ['stripe'], paths: ['/v1/refunds'] }
1667
+ * child { credentials: ['stripe'], paths: ['/v1/refunds'] }
1668
+ * POST https://api.stripe.com/v1/refunds/re_1 allowed
1669
+ * POST https://api.stripe.com/v1/refunds/%2e%2e/charges refused: it is /v1/charges once parsed
1670
+ * POST https://api.stripe.com/v1/refundsX refused: a prefix matches whole segments
1671
+ */
1672
+ /** The most entries in each list. */
1673
+ const MAX_CONSTRAINTS = 32;
1674
+ /** A constraint that does not parse, said so the caller can fix it. */
1675
+ var ConstraintsInvalid = class extends Error {
1676
+ constructor(message) {
1677
+ super(message);
1678
+ this.name = "ConstraintsInvalid";
1679
+ }
1680
+ };
1681
+ const PLACE = /^[a-z0-9][a-z0-9-]{0,62}\/[a-z0-9][a-z0-9-]{0,62}(@me)?$/;
1682
+ /** A path segment as a constraint names one: no escape, no `;`, no dot segment. */
1683
+ const SEGMENT = /^[A-Za-z0-9\-_~!$&'()*+,=:@.]+$/;
1684
+ /**
1685
+ * What a path may not hold for a constrained session, since an upstream
1686
+ * might read a segment otherwise than coffre: an escaped `.`, `/` or `\`,
1687
+ * a `%25` (double encoding), or a `;`, raw or escaped
1688
+ * (`/v1/refunds/..;/charges` and `/v1/refunds/..%3b/charges` are
1689
+ * `/v1/charges` to Tomcat).
1690
+ */
1691
+ const AMBIGUOUS = /%2e|%2f|%5c|%25|%3b|;/i;
1692
+ function list(value, what, valid) {
1693
+ if (value === void 0) return void 0;
1694
+ if (!Array.isArray(value) || value.length > 32 || value.some((item) => typeof item !== "string" || !valid(item))) throw new ConstraintsInvalid(`${what} lists at most 32 of them`);
1695
+ return [...new Set(value)].sort();
1696
+ }
1697
+ function isPrefix(path) {
1698
+ if (path === "/") return true;
1699
+ if (!path.startsWith("/") || path.endsWith("/")) return false;
1700
+ return path.slice(1).split("/").every((segment) => SEGMENT.test(segment) && segment !== "." && segment !== "..");
1701
+ }
1702
+ /** Whether `path` is `prefix` or below it, by whole segments. */
1703
+ function under(path, prefix) {
1704
+ return prefix === "/" || path === prefix || path.startsWith(`${prefix}/`);
1705
+ }
1706
+ /**
1707
+ * Constraints as a child asks for them, checked and canonical: each list
1708
+ * sorted, without duplicates; methods as Fetch sends them; prefixes absolute,
1709
+ * with no trailing slash, escape, `;` or dot segment, and none under
1710
+ * another, which it would add nothing to. Throws `ConstraintsInvalid`.
1711
+ */
1712
+ function checkConstraints(input) {
1713
+ if (typeof input !== "object" || input === null || Array.isArray(input)) throw new ConstraintsInvalid("constraints are an object");
1714
+ const { places, credentials, methods, paths, ...rest } = input;
1715
+ if (Object.keys(rest).length > 0) throw new ConstraintsInvalid(`constraints hold places, credentials, methods and paths, not ${Object.keys(rest).join(", ")}`);
1716
+ const checked = {};
1717
+ const placeList = list(places, "places", (place) => PLACE.test(place));
1718
+ const credentialList = list(credentials, "credentials", (name) => CREDENTIAL_NAME.test(name));
1719
+ const methodList = list(Array.isArray(methods) ? methods.map((method) => typeof method === "string" && METHOD_TOKEN.test(method) ? fetchMethod$1(method) : method) : methods, "methods", (method) => METHOD_TOKEN.test(method));
1720
+ const pathList = list(paths, "paths", isPrefix);
1721
+ if (placeList !== void 0) checked.places = placeList;
1722
+ if (credentialList !== void 0) checked.credentials = credentialList;
1723
+ if (methodList !== void 0) checked.methods = methodList;
1724
+ if (pathList !== void 0) checked.paths = outermost(pathList);
1725
+ return checked;
1726
+ }
1727
+ /** The prefixes no other one is above. */
1728
+ function outermost(paths) {
1729
+ return paths.filter((path) => !paths.some((other) => other !== path && under(path, other)));
1730
+ }
1731
+ function both(a, b) {
1732
+ if (a === void 0) return b;
1733
+ if (b === void 0) return a;
1734
+ return a.filter((item) => b.includes(item));
1735
+ }
1736
+ /**
1737
+ * What a child holds: what it asked within what its parent holds, list by
1738
+ * list, and for paths each prefix of one side that is under one of the
1739
+ * other's. A parent with none is a root, which only its scope bounds. Never
1740
+ * wider than either: whatever `intersect(a, b)` allows, `a` and `b` allow.
1741
+ */
1742
+ function intersect(parent, child) {
1743
+ if (parent === null) return child;
1744
+ const result = {};
1745
+ const places = both(parent.places, child.places);
1746
+ const credentials = both(parent.credentials, child.credentials);
1747
+ const methods = both(parent.methods, child.methods);
1748
+ if (places !== void 0) result.places = places;
1749
+ if (credentials !== void 0) result.credentials = credentials;
1750
+ if (methods !== void 0) result.methods = methods;
1751
+ if (parent.paths === void 0 || child.paths === void 0) {
1752
+ const paths = parent.paths ?? child.paths;
1753
+ if (paths !== void 0) result.paths = paths;
1754
+ } else {
1755
+ const kept = [...child.paths.filter((path) => parent.paths.some((prefix) => under(path, prefix))), ...parent.paths.filter((path) => child.paths.some((prefix) => under(path, prefix)))];
1756
+ result.paths = outermost([...new Set(kept)].sort());
1757
+ }
1758
+ return result;
1759
+ }
1760
+ /** The constraints as a row's `constraints` column and its MAC hold them: `checkConstraints`'s keys in order. */
1761
+ function constraintsText(constraints) {
1762
+ const { places, credentials, methods, paths } = constraints;
1763
+ return JSON.stringify({
1764
+ places,
1765
+ credentials,
1766
+ methods,
1767
+ paths
1768
+ });
1769
+ }
1770
+ /**
1771
+ * Whether one operation is within the constraints: its place and credential
1772
+ * named, and, for one that sends a request upstream, its method and the
1773
+ * path of the URL it is about to send, as the WHATWG parser resolved it.
1774
+ * An operation with no request to check (`sign`, `verify`, `mint`, the
1775
+ * tunnel) is refused wherever methods or paths are limited: a constraint
1776
+ * that cannot be checked refuses.
1777
+ */
1778
+ function constraintsAllow(constraints, operation) {
1779
+ if (constraints === null) return true;
1780
+ if (constraints.places !== void 0 && !constraints.places.includes(operation.place)) return false;
1781
+ if (constraints.credentials !== void 0 && !constraints.credentials.includes(operation.credential)) return false;
1782
+ if (constraints.methods === void 0 && constraints.paths === void 0) return true;
1783
+ if (operation.request === void 0) return false;
1784
+ if (constraints.methods !== void 0 && !(METHOD_TOKEN.test(operation.request.method) && constraints.methods.includes(fetchMethod$1(operation.request.method)))) return false;
1785
+ if (constraints.paths === void 0) return true;
1786
+ let path;
1787
+ try {
1788
+ path = new URL(String(operation.request.url)).pathname;
1789
+ } catch {
1790
+ return false;
1791
+ }
1792
+ if (AMBIGUOUS.test(path)) return false;
1793
+ return constraints.paths.some((prefix) => under(path, prefix));
1794
+ }
1795
+ //#endregion
1796
+ //#region src/identity/dpop.ts
1624
1797
  /**
1625
- * The claims of the run a credential was issued for, as the issuer
1626
- * asserted them: in the sign-in's record, so that a read leads back to its
1627
- * run. What the issuer says, not proof of which run sent the request.
1798
+ * Checking a workload's proof (docs/design/workload-access.md, section
1799
+ * 5.1): the verifying half of `@coffre/client/dpop`, whose canonicalization
1800
+ * it runs, so both sides agree on every byte. Cheapest first:
1801
+ *
1802
+ * 1. shape at most 2 KiB, `typ` exactly `dpop+jwt`, `alg` exactly `ES256`
1803
+ * 2. the key `jwk` exactly `kty`, `crv`, `x` and `y`, a point on P-256
1804
+ * 3. claims `jti` 16 bytes, `iat` an integer, `hdr` at most 32 names, none unsigned
1805
+ * (`parseProof`, no I/O)
1806
+ * 4. the session row, from the token's hash: the server's, between the two
1807
+ * 5. key and signature the thumbprint is the row's `jkt`, then ES256
1808
+ * 6. what was signed `htm`, `htu`, `ath`, `req`, then `iat` within ±300 s
1809
+ * (`verifyProof`)
1810
+ * 7. the gate's nonce and `jti`: the server's again (`Gate`)
1811
+ *
1812
+ * Each claim the caller expects (`ath` with a token, `hdr` and `req` with a
1813
+ * request's content) must be there, and one it does not expect must not.
1814
+ * Two signatures of one payload, `(r, s)` and `(r, n − s)`, both verify:
1815
+ * they carry one `jti`, which the gate takes once.
1628
1816
  */
1629
- const RUN_CLAIMS = [
1630
- "sub",
1817
+ /** How far a proof's `iat` may be from now: the nonce, not the clock, is what makes a proof fresh. */
1818
+ const PROOF_SKEW_SECONDS = 300;
1819
+ const refuse = (reason, message) => ({
1820
+ ok: false,
1821
+ reason,
1822
+ message
1823
+ });
1824
+ const DECODER = new TextDecoder("utf-8", { fatal: true });
1825
+ const ENCODER = new TextEncoder();
1826
+ const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9a-z-]+$/;
1827
+ const CLAIMS = /* @__PURE__ */ new Set([
1631
1828
  "jti",
1632
- "actor",
1633
- "event_name",
1634
- "ref",
1635
- "base_ref",
1636
- "head_ref",
1637
- "sha",
1638
- "repository",
1639
- "repository_id",
1640
- "run_id",
1641
- "run_attempt",
1642
- "workflow_ref",
1643
- "job_workflow_ref",
1644
- "job_workflow_sha",
1645
- "environment",
1646
- "project_path",
1647
- "project_id",
1648
- "namespace_id",
1649
- "pipeline_id",
1650
- "pipeline_source",
1651
- "job_id",
1652
- "kubernetes.io.pod.name"
1653
- ];
1654
- const MAX_RUN_CLAIM = 256;
1655
- /** A binding's `jwks_uri` when it carries its issuer's keys: the SHA-256 of those keys (`UploadedKeys`), where a fetched set's URL would be. */
1656
- const UPLOADED_KEYS = "sha256:";
1657
- /** The run's claims, as the issuer stated them: those that say which run, each bounded. */
1658
- function runClaims(claims) {
1659
- const run = {};
1660
- for (const name of RUN_CLAIMS) {
1661
- const value = claimAt(claims, name);
1662
- if (typeof value === "string") run[name] = value.slice(0, MAX_RUN_CLAIM);
1663
- else if (typeof value === "number" && Number.isFinite(value)) run[name] = value;
1829
+ "htm",
1830
+ "htu",
1831
+ "iat",
1832
+ "ath",
1833
+ "nonce",
1834
+ "hdr",
1835
+ "req"
1836
+ ]);
1837
+ /** A part of the proof as a JSON object, or null for anything else. */
1838
+ function jsonPart(part) {
1839
+ const bytes = fromBase64url(part);
1840
+ if (bytes === null) return null;
1841
+ try {
1842
+ const value = JSON.parse(DECODER.decode(bytes));
1843
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
1844
+ } catch {
1845
+ return null;
1664
1846
  }
1665
- return run;
1666
1847
  }
1667
- /** A token's one audience, or null for none or several: a token for several parties is no single party's. */
1668
- function soleAudience(aud) {
1669
- if (typeof aud === "string") return aud;
1670
- return Array.isArray(aud) && aud.length === 1 && typeof aud[0] === "string" ? aud[0] : null;
1848
+ function exactly(value, keys) {
1849
+ return Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
1671
1850
  }
1672
- /** Why a run's proof buys nothing, as the app's refusals say it (`ExchangeReason`), with the key a refused token named. */
1673
- var RunProofRefused = class extends Error {
1674
- reason;
1675
- kid;
1676
- constructor(reason, message, kid = null) {
1677
- super(message);
1678
- this.name = "RunProofRefused";
1679
- this.reason = reason;
1680
- this.kid = kid;
1851
+ const isDigest = (value) => typeof value === "string" && fromBase64url(value)?.length === 32;
1852
+ /** Steps 1 to 3: the proof's shape, its key's and its claims', with no I/O. */
1853
+ function parseProof(proof) {
1854
+ if (proof.length > MAX_PROOF_LENGTH$1) return refuse("malformed", `a proof is at most ${MAX_PROOF_LENGTH$1} characters`);
1855
+ const parts = proof.split(".");
1856
+ if (parts.length !== 3) return refuse("malformed", "a proof is a compact JWS: three parts");
1857
+ const [headerPart, payloadPart, signaturePart] = parts;
1858
+ const header = jsonPart(headerPart);
1859
+ if (header === null || !exactly(header, [
1860
+ "typ",
1861
+ "alg",
1862
+ "jwk"
1863
+ ]) || header.typ !== "dpop+jwt" || header.alg !== "ES256") return refuse("malformed", "a proof's header is exactly { typ: \"dpop+jwt\", alg: \"ES256\", jwk }");
1864
+ const jwk = header.jwk;
1865
+ if (typeof jwk !== "object" || jwk === null || Array.isArray(jwk) || !exactly(jwk, [
1866
+ "kty",
1867
+ "crv",
1868
+ "x",
1869
+ "y"
1870
+ ]) || jwk.kty !== "EC" || jwk.crv !== "P-256" || !isCoordinate(jwk.x) || !isCoordinate(jwk.y)) return refuse("key", "a proof's key is a P-256 public key: exactly kty, crv, x and y");
1871
+ const signature = fromBase64url(signaturePart);
1872
+ if (signature === null || signature.length !== 64) return refuse("malformed", "an ES256 signature is 64 bytes, r then s");
1873
+ const claims = jsonPart(payloadPart);
1874
+ if (claims === null || Object.keys(claims).some((name) => !CLAIMS.has(name))) return refuse("malformed", "a proof's claims are jti, htm, htu, iat, and ath, nonce, hdr, req where they apply");
1875
+ if (typeof claims.jti !== "string" || fromBase64url(claims.jti)?.length !== 16) return refuse("malformed", "jti is 16 random bytes, in base64url");
1876
+ if (typeof claims.htm !== "string" || !METHOD_TOKEN.test(claims.htm)) return refuse("malformed", "htm is the request's method");
1877
+ if (typeof claims.htu !== "string") return refuse("malformed", "htu is the request's URL");
1878
+ if (!Number.isSafeInteger(claims.iat)) return refuse("malformed", "iat is an integer, in seconds");
1879
+ if (claims.ath !== void 0 && !isDigest(claims.ath)) return refuse("malformed", "ath is a SHA-256, in base64url");
1880
+ if (claims.nonce !== void 0 && (typeof claims.nonce !== "string" || !/^[\x21-\x7e]{1,128}$/.test(claims.nonce))) return refuse("malformed", "nonce is the one coffre gave");
1881
+ if (claims.hdr === void 0 !== (claims.req === void 0)) return refuse("malformed", "hdr and req come together");
1882
+ let hdr = null;
1883
+ if (claims.hdr !== void 0) {
1884
+ if (typeof claims.hdr !== "string" || !isDigest(claims.req)) return refuse("malformed", "hdr names headers, and req is a SHA-256");
1885
+ hdr = claims.hdr === "" ? [] : claims.hdr.split(" ");
1886
+ if (hdr.length > MAX_SIGNED_HEADERS$1) return refuse("malformed", `a proof signs at most ${MAX_SIGNED_HEADERS$1} headers`);
1887
+ if (hdr.some((name) => !HEADER_NAME.test(name) || UNSIGNED_HEADERS.has(name)) || new Set(hdr).size !== hdr.length) return refuse("malformed", "hdr names each header once, in lower case, and none the transport or the request to coffre owns");
1681
1888
  }
1682
- };
1683
- /** A token's `kid`, at most 64 characters, for a refusal and the alert it raises; the token is unverified. */
1684
- function shownKid(header) {
1685
- return typeof header.kid === "string" ? header.kid.slice(0, 64) : null;
1889
+ return {
1890
+ ok: true,
1891
+ jwk,
1892
+ claims,
1893
+ hdr,
1894
+ signingInput: `${headerPart}.${payloadPart}`,
1895
+ signature
1896
+ };
1897
+ }
1898
+ function isCoordinate(value) {
1899
+ return typeof value === "string" && fromBase64url(value)?.length === 32;
1686
1900
  }
1687
1901
  /**
1688
- * Verify a CI run's or a workload's ID token against one binding, sealed
1689
- * (D148), whose keys were uploaded with it: the vault's own check, which
1690
- * no app can steer, and which asks no one. The binding's keys, held to the
1691
- * digest its seal covers (a key they lack is refused, never looked for),
1692
- * its issuer, its audience (the instance it was made on, or, for a
1693
- * platform whose caller names the session's key, that key: `jkt`, from the
1694
- * DPoP proof the vault verified, never from the app), the token's times,
1695
- * the binding's claims and its profile's rules. Throws `RunProofRefused`.
1902
+ * Steps 5 and 6: the proof against its request, `parseProof`'s first when
1903
+ * given a string. Nothing here reads a store, so the gate (step 7) still
1904
+ * decides whether this `jti` was seen.
1696
1905
  */
1697
- async function verifyRunToken(token, binding, context) {
1698
- let decoded;
1906
+ async function verifyProof(proof, expect) {
1907
+ const parsed = typeof proof === "string" ? parseProof(proof) : proof;
1908
+ if (!parsed.ok) return parsed;
1909
+ const { jwk, claims, hdr } = parsed;
1910
+ const jkt = await thumbprint$1(jwk);
1911
+ if (expect.jkt !== void 0 && jkt !== expect.jkt) return refuse("jkt", "the proof is signed by another key than the session's");
1912
+ let key;
1699
1913
  try {
1700
- decoded = decodeWorkloadToken(token);
1701
- } catch (error) {
1702
- throw refusedBy(error);
1914
+ key = await crypto.subtle.importKey("jwk", {
1915
+ kty: jwk.kty,
1916
+ crv: jwk.crv,
1917
+ x: jwk.x,
1918
+ y: jwk.y
1919
+ }, {
1920
+ name: "ECDSA",
1921
+ namedCurve: "P-256"
1922
+ }, false, ["verify"]);
1923
+ } catch {
1924
+ return refuse("key", "the proof's key is no point on P-256");
1703
1925
  }
1704
- const { claims: unverified, header } = decoded;
1705
- if (unverified.iss !== binding.issuer) throw new RunProofRefused("no_match", `the token is from ${unverified.iss}, which this binding does not trust`);
1706
- const policy = binding.policy === null ? null : JSON.parse(binding.policy);
1707
- if (context.workload === null !== (policy === null)) throw new RunProofRefused("no_match", "a CI run signs in through a binding with no policy, a workload through one with");
1708
- const accepted = context.workload === null ? [binding.origin] : expectedAudiences(binding.profile, policy, {
1709
- publicUrl: binding.origin,
1710
- jkt: context.workload.jkt
1711
- });
1712
- const named = soleAudience(unverified.aud);
1713
- const audience = named !== null && accepted.includes(named) ? named : accepted[0];
1714
- const repeating = context.workload !== null && REPEATING_PROFILES.includes(binding.profile);
1715
- const expected = {
1716
- issuer: binding.issuer,
1717
- audience,
1718
- now: context.now,
1719
- ...repeating ? { maxAge: null } : {}
1720
- };
1721
- let claims;
1926
+ if (!await crypto.subtle.verify({
1927
+ name: "ECDSA",
1928
+ hash: "SHA-256"
1929
+ }, key, parsed.signature, ENCODER.encode(parsed.signingInput))) return refuse("signature", "the proof's signature does not verify");
1930
+ if (claims.htm !== fetchMethod$1(expect.method)) return refuse("htm", "the proof signs another method");
1931
+ let htu;
1722
1932
  try {
1723
- const uploaded = await uploadedKeys(JSON.parse(binding.jwks));
1724
- if (`sha256:${uploaded.digest}` !== binding.jwksUri) throw new RunProofRefused("keys", "the keys are not those the binding was made with");
1725
- claims = await verifyWorkloadToken(token, JSON.parse(uploaded.jwks), {
1726
- ...expected,
1727
- maxLifetime: MAX_TOKEN_AGE_SECONDS
1728
- });
1729
- } catch (error) {
1730
- if (error instanceof RunProofRefused) throw error;
1731
- if (error instanceof WorkloadTokenRefused && error.reason === "unknown_key") throw new RunProofRefused("unknown_key", error.message, shownKid(header));
1732
- throw refusedBy(error);
1733
- }
1734
- const differ = differingClaims(binding.profile, JSON.parse(binding.claims), claims);
1735
- if (differ.length > 0) throw new RunProofRefused("no_match", `the binding does not trust these claims: ${differ.join(", ")} differ`);
1736
- if (context.workload !== null) {
1737
- const ruled = PROFILE_RULES[binding.profile]?.token(claims, {
1738
- issuer: binding.issuer,
1739
- claims: JSON.parse(binding.claims),
1740
- policy
1741
- }) ?? null;
1742
- if (ruled !== null) throw new RunProofRefused("no_match", ruled);
1933
+ htu = canonicalHtu$1(expect.url);
1934
+ } catch {
1935
+ return refuse("htu", "the request's URL cannot be signed");
1743
1936
  }
1744
- const run = runClaims(claims);
1745
- if (context.workload === null) {
1746
- const validUntil = Math.floor(Math.min((decoded.claims.exp + 30) * 1e3, (decoded.claims.iat + MAX_TOKEN_AGE_SECONDS) * 1e3));
1747
- return {
1748
- claims,
1749
- run,
1750
- spent: decoded.signingInputHash,
1751
- validUntil,
1752
- notAfter: null
1753
- };
1937
+ if (claims.htu !== htu) return refuse("htu", "the proof signs another URL");
1938
+ if (expect.token === void 0 !== (claims.ath === void 0)) return refuse("ath", expect.token === void 0 ? "this proof signs no token" : "the proof signs no token: ath");
1939
+ if (expect.token !== void 0 && claims.ath !== await tokenDigest(expect.token)) return refuse("ath", "the proof signs another token");
1940
+ if (expect.content === void 0 !== (hdr === null)) return refuse("req", expect.content === void 0 ? "this proof signs no request content" : "the proof signs no request content: hdr and req");
1941
+ if (expect.content !== void 0) {
1942
+ const headers = [];
1943
+ for (const name of hdr) {
1944
+ const value = expect.content.headers.get(name);
1945
+ if (value === null) return refuse("req", `the proof signs a header the request lacks: ${name}`);
1946
+ headers.push([name, value]);
1947
+ }
1948
+ let digest;
1949
+ try {
1950
+ digest = await requestDigest({
1951
+ ...sentTarget$1(expect.url),
1952
+ headers,
1953
+ body: expect.content.body
1954
+ });
1955
+ } catch {
1956
+ return refuse("req", "the request cannot be signed: a line break in its path, query or headers");
1957
+ }
1958
+ if (claims.req !== digest) return refuse("req", "the proof signs another path as sent, query, header or body");
1754
1959
  }
1755
- const namesKey = policy.keyAudience === true;
1960
+ const skew = expect.skewSeconds ?? 300;
1961
+ const now = Math.floor((expect.now ?? Date.now()) / 1e3);
1962
+ if (Math.abs(now - claims.iat) > skew) return refuse("iat", `the proof was made more than ${skew} seconds from now`);
1756
1963
  return {
1757
- claims,
1758
- run,
1759
- spent: namesKey || repeating ? null : decoded.signingInputHash,
1760
- validUntil: null,
1761
- notAfter: namesKey ? null : decoded.claims.exp * 1e3
1964
+ ok: true,
1965
+ jkt,
1966
+ jti: claims.jti,
1967
+ nonce: claims.nonce ?? null,
1968
+ iat: claims.iat,
1969
+ hdr
1762
1970
  };
1763
1971
  }
1764
- function refusedBy(error) {
1765
- if (error instanceof WorkloadTokenRefused) return new RunProofRefused(error.reason, error.message);
1766
- if (error instanceof RunProofRefused) return error;
1767
- return new RunProofRefused("malformed", error?.message ?? "the token is not one coffre reads");
1768
- }
1769
1972
  //#endregion
1770
1973
  //#region src/identity/signin/sealed.ts
1771
1974
  const IV_BYTES = 12;
@@ -1831,9 +2034,11 @@ const PREFIX = {
1831
2034
  personal: "coffre_pat_",
1832
2035
  handle: "coffre_use_",
1833
2036
  workload: "coffre_wl_",
1834
- enrollment: "coffre_enr_"
2037
+ enrollment: "coffre_enr_",
2038
+ mcp: "coffre_mcp_",
2039
+ "mcp-refresh": "coffre_mcr_"
1835
2040
  };
1836
- const TOKEN = /^coffre_(web|cli|svc|pat|use|wl|enr)_[A-Za-z0-9_-]{43}$/;
2041
+ const TOKEN = /^coffre_(web|cli|svc|pat|use|wl|enr|mcp|mcr)_[A-Za-z0-9_-]{43}$/;
1837
2042
  function generateToken(kind) {
1838
2043
  return PREFIX[kind] + randomBytes(32).toString("base64url");
1839
2044
  }
@@ -1874,34 +2079,91 @@ const ACCESS_JWT_HEADER = "cf-access-jwt-assertion";
1874
2079
  * defaults to permitting whatever the key supports; we do not rely on that.
1875
2080
  */
1876
2081
  const ALLOWED_ALGORITHMS = ["RS256", "ES256"];
2082
+ /** How long a key set is used before it is fetched again, and the least time between two fetches an unknown key asks for. */
2083
+ const KEYS_MAX_AGE_MS = 6e5;
2084
+ const REFETCH_COOLDOWN_MS = 3e4;
1877
2085
  function asNonEmptyString(value) {
1878
2086
  return typeof value === "string" && value.length > 0 ? value : null;
1879
2087
  }
2088
+ /** 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. */
2089
+ var AccessKeysUnavailable = class extends Error {
2090
+ constructor(message, options) {
2091
+ super(message, options);
2092
+ this.name = "AccessKeysUnavailable";
2093
+ }
2094
+ };
2095
+ async function fetchJson(url) {
2096
+ const response = await fetch(url, {
2097
+ redirect: "manual",
2098
+ signal: AbortSignal.timeout(5e3),
2099
+ headers: { accept: "application/json" }
2100
+ });
2101
+ if (response.status !== 200) {
2102
+ await response.body?.cancel();
2103
+ throw new Error(`${url.href} answered ${response.status}`);
2104
+ }
2105
+ return response.json();
2106
+ }
1880
2107
  /**
1881
2108
  * Verifies Cloudflare Access JWTs.
1882
2109
  *
1883
2110
  * Signature and claim verification of the token Access sends with each
1884
- * request.
2111
+ * request. The team's keys are fetched when first needed, used for ten
2112
+ * minutes, and fetched again sooner for a key they lack, at most every 30
2113
+ * seconds. The verifier lives as long as its configuration (an isolate's,
2114
+ * on Workers) and keeps settled values only, never a fetch in flight
2115
+ * (AGENTS.md, "What an isolate keeps"): concurrent requests that find no
2116
+ * key set each fetch their own, and the last to land is kept. The 30
2117
+ * seconds count from the last refresh started, landed or not, and are
2118
+ * taken before it starts: of a burst of assertions naming a key the set
2119
+ * lacks, one fetches, and the others are refused as the key unknown.
1885
2120
  */
1886
2121
  var AccessIdentityVerifier = class {
1887
2122
  #config;
1888
- #jwks;
1889
- constructor(config) {
2123
+ #url;
2124
+ #json;
2125
+ #now;
2126
+ #keys = null;
2127
+ /** When a refresh for an unknown key last started: a number, settled the moment it starts. */
2128
+ #refreshed = Number.NEGATIVE_INFINITY;
2129
+ constructor(config, io = {}) {
1890
2130
  this.#config = config;
1891
- this.#jwks = createRemoteJWKSet(new URL(config.jwksUrl), {
1892
- cooldownDuration: 3e4,
1893
- cacheMaxAge: 6e5
1894
- });
2131
+ this.#url = new URL(config.jwksUrl);
2132
+ this.#json = io.json ?? fetchJson;
2133
+ this.#now = io.now ?? Date.now;
1895
2134
  }
1896
2135
  async verify(token) {
1897
2136
  if (typeof token !== "string" || token.length === 0) throw new Error("missing or empty Access token");
1898
- const { payload } = await jwtVerify(token, this.#jwks, {
2137
+ const { alg } = decodeProtectedHeader(token);
2138
+ if (!ALLOWED_ALGORITHMS.includes(alg)) throw new errors.JOSEAlgNotAllowed(`"alg" (Algorithm) Header Parameter value not allowed`);
2139
+ const options = {
1899
2140
  issuer: this.#config.issuer,
1900
2141
  audience: this.#config.audience,
1901
2142
  algorithms: [...ALLOWED_ALGORITHMS],
1902
2143
  clockTolerance: this.#config.clockToleranceSeconds ?? 0
1903
- });
1904
- return toPrincipal(payload);
2144
+ };
2145
+ let keys = this.#keys;
2146
+ if (keys === null || this.#now() - keys.at >= KEYS_MAX_AGE_MS) keys = await this.#fetch();
2147
+ try {
2148
+ return toPrincipal((await jwtVerify(token, keys.set, options)).payload);
2149
+ } catch (error) {
2150
+ const now = this.#now();
2151
+ if (!(error instanceof errors.JWKSNoMatchingKey) || now - Math.max(keys.at, this.#refreshed) < REFETCH_COOLDOWN_MS) throw error;
2152
+ this.#refreshed = now;
2153
+ }
2154
+ return toPrincipal((await jwtVerify(token, (await this.#fetch()).set, options)).payload);
2155
+ }
2156
+ async #fetch() {
2157
+ let set;
2158
+ try {
2159
+ set = createLocalJWKSet(await this.#json(this.#url));
2160
+ } catch (error) {
2161
+ throw new AccessKeysUnavailable(`Cloudflare Access's keys could not be fetched from ${this.#url.href}`, { cause: error });
2162
+ }
2163
+ return this.#keys = {
2164
+ set,
2165
+ at: this.#now()
2166
+ };
1905
2167
  }
1906
2168
  };
1907
2169
  /**
@@ -1934,4 +2196,4 @@ function toPrincipal(claims) {
1934
2196
  throw new Error("token verified but carries no usable identity: expected common_name (service) or sub+email (user)");
1935
2197
  }
1936
2198
  //#endregion
1937
- export { ACCESS_JWT_HEADER, AccessIdentityVerifier, BEARER_PROFILES, BindingInvalid, CLOCK_TOLERANCE_SECONDS, CREDENTIAL_NAME, ConstraintsInvalid, EVENT_EXPOSURE, EXCHANGED_CREDENTIAL_MS, EXCHANGE_SKEW_SECONDS, GITHUB_EVENTS, GITHUB_ISSUER, GITLAB_ISSUER, GITLAB_PIPELINE_SOURCES, GOOGLE_ISSUER, GitHubApp, GitHubAppUnavailable, GitHubSigninProvider, KEY_NAMING_PROFILES, KeysInvalid, MAX_BINDINGS, MAX_CLAIMS, MAX_CLAIM_BYTES, MAX_CONSTRAINTS, MAX_ISSUER_BYTES, MAX_KEYS, MAX_LISTING_REQUESTS, MAX_PROOF_LENGTH, MAX_READ_KEYS, MAX_READ_PLACES, MAX_SIGNED_HEADERS, MAX_SOURCES, MAX_TOKEN_AGE_SECONDS, MAX_TOKEN_BYTES, OIDC_PROFILES, OidcSigninProvider, POLICY_DEFAULTS, POLICY_FIELDS, PROFILE_RULES, PROFILE_URNS, PROOF_SKEW_SECONDS, REPEATING_PROFILES, REQUIRED_CLAIMS, RUN_CLAIMS, RunProofRefused, SESSION_MS, SigninError, TOKEN_MARGIN_MS, UPLOADED_KEYS, WORKLOAD_ALGORITHMS, WORKLOAD_PROFILES, WORKLOAD_SIGN_IN_PATH, WorkloadTokenRefused, addressWithin, canonicalClaims, canonicalHtu, canonicalRequest, checkBinding, checkConstraints, checkFetchUrl, checkPolicy, claimAt, claimValues, cloudflareAccess, constraintsAllow, constraintsText, decodeWorkloadToken, defaultIssuer, defineSignin, deriveKey, differingClaims, expectedAudiences, fetchMethod, freezeTarget, fullRef, generateToken, github, githubApp, githubEventsAt, githubReusable, githubWorkflow, gitlabProject, google, hashToken, intersect, isBearerProfile, isCoffreToken, issuedRefusal, keySummaries, microsoft, oidc, parseAddress, parseCidr, parseProof, pkcs8Of, policyText, publicOrigin, runClaims, seal, sentTarget, signin, soleAudience, thumbprint, toPrincipal, tokenHint, tokenKind, unseal, uploadedKeys, verifyProof, verifyRunToken, verifyWorkloadToken, workflowRef };
2199
+ export { ACCESS_JWT_HEADER, AccessIdentityVerifier, AccessKeysUnavailable, BEARER_PROFILES, BindingInvalid, CARRIED, CLOCK_TOLERANCE_SECONDS, CREDENTIAL_NAME, ConstraintsInvalid, EVENT_EXPOSURE, GITHUB_EVENTS, GITHUB_ISSUER, GITLAB_ISSUER, GITLAB_PIPELINE_SOURCES, GOOGLE_ISSUER, GitHubApp, GitHubAppUnavailable, GitHubSigninProvider, KEY_NAMING_PROFILES, KeysInvalid, MAX_BINDINGS, MAX_CLAIMS, MAX_CLAIM_BYTES, MAX_CONSTRAINTS, MAX_ISSUER_BYTES, MAX_KEYS, MAX_LISTING_REQUESTS, MAX_PROOF_LENGTH, MAX_READ_KEYS, MAX_READ_PLACES, MAX_RUN_CLAIM, MAX_SIGNED_HEADERS, MAX_SOURCES, MAX_TOKEN_AGE_SECONDS, MAX_TOKEN_BYTES, OIDC_PROFILES, OidcSigninProvider, POLICY_DEFAULTS, POLICY_FIELDS, PROFILE_RULES, PROFILE_URNS, PROOF_SKEW_SECONDS, REPEATING_PROFILES, REQUIRED_CLAIMS, RUN_CLAIMS, SigninError, TOKEN_MARGIN_MS, WORKLOAD_ALGORITHMS, WORKLOAD_PROFILES, WorkloadTokenRefused, addressWithin, assumedRole, audienceTried, audiencesOf, awsClaims, canonicalClaims, canonicalHtu, canonicalRequest, checkBinding, checkConstraints, checkFetchUrl, checkPolicy, claimAt, claimValues, cloudflareAccess, constraintsAllow, constraintsText, decodeWorkloadToken, defaultIssuer, defineSignin, deriveKey, differingClaims, expectedAudiences, fetchMethod, freezeTarget, fullRef, generateToken, github, githubApp, githubEventsAt, githubReusable, githubWorkflow, gitlabProject, google, hardEnd, hashToken, intersect, isBearerProfile, isCoffreToken, issuedRefusal, issues, keySummaries, lifetime, matchAwsAnswer, matchIdToken, microsoft, oidc, oldestMatching, parseAddress, parseCidr, parseProof, pkcs8Of, policyOf, policyText, profileRefusal, publicOrigin, readIdToken, runClaims, seal, sentTarget, sessionRefusal, signatureRefusal, signin, soleAudience, spends, thumbprint, timesRefusal, toPrincipal, tokenHint, tokenKind, unseal, uploadedKeys, verifyProof, verifyWorkloadToken, workflowRef };