@coffre/core 0.10.2 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/identity.js CHANGED
@@ -1,6 +1,7 @@
1
- import { BindingInvalid, EVENT_EXPOSURE, GITHUB_EVENTS, GITHUB_ISSUER, GITLAB_ISSUER, GITLAB_PIPELINE_SOURCES, MAX_BINDINGS, MAX_CLAIMS, MAX_CLAIM_BYTES, MAX_ISSUER_BYTES, REQUIRED_CLAIMS, WORKLOAD_PROFILES, canonicalClaims, checkBinding, checkFetchUrl, claimAt, claimValues, defaultIssuer, differingClaims, fullRef, githubEventsAt, githubReusable, githubWorkflow, gitlabProject, 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 { 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";
4
5
  import { createLocalJWKSet, createRemoteJWKSet, errors, importJWK, jwtVerify } from "jose";
5
6
  //#region src/identity/github-app.ts
6
7
  /** GitHub could not be asked, or refused the app: the message says which, for a person, and carries no credential. */
@@ -848,10 +849,15 @@ function workloadsConfig(options, publicUrl) {
848
849
  const app = options.github;
849
850
  if (app !== void 0 && !(app instanceof GitHubApp)) throw new Error("workloads.github is the deployment's GitHub App: githubApp({ appId, privateKey })");
850
851
  if (app !== void 0 && app.apiUrl !== "https://api.github.com" && !isLoopback(new URL(app.apiUrl))) throw new Error("workloads.github is for github.com: GitHub Enterprise Server is not supported yet; sign in with its app, and leave workloads.github out");
852
+ for (const flag of ["useOnly", "noReads"]) if (options[flag] !== void 0 && typeof options[flag] !== "boolean") throw new Error(`workloads.${flag} is true or false`);
853
+ if (options.alert !== void 0 && typeof options.alert !== "function") throw new Error("workloads.alert is a function, given each alert");
851
854
  return {
852
855
  allowLoopback: loopback,
853
856
  limits: options.limits,
854
- github: app ?? null
857
+ github: app ?? null,
858
+ useOnly: options.useOnly === true,
859
+ noReads: options.noReads === true,
860
+ alert: options.alert ?? null
855
861
  };
856
862
  }
857
863
  /** A deployment's own provider is checked like coffre's: it is only typed, not trusted. */
@@ -937,6 +943,322 @@ function toSignin(options) {
937
943
  };
938
944
  }
939
945
  //#endregion
946
+ //#region src/identity/constraints.ts
947
+ /**
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
960
+ */
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";
968
+ }
969
+ };
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
+ /**
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`.
1000
+ */
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));
1024
+ }
1025
+ /**
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.
1030
+ */
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());
1046
+ }
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
940
1262
  //#region src/identity/signin/sealed.ts
941
1263
  const IV_BYTES = 12;
942
1264
  const VERSION = "v1";
@@ -977,8 +1299,9 @@ function seal(key, value, ttlSeconds, now = Date.now()) {
977
1299
  /** The sealed value, or null when it is malformed, forged, tampered with or expired. */
978
1300
  function unseal(key, sealed, now = Date.now()) {
979
1301
  if (!sealed?.startsWith(`${VERSION}.`)) return null;
980
- const raw = Buffer.from(sealed.slice(3), "base64url");
981
- if (raw.length <= 28) return null;
1302
+ const body = sealed.slice(3);
1303
+ const raw = Buffer.from(body, "base64url");
1304
+ if (raw.length <= 28 || raw.toString("base64url") !== body) return null;
982
1305
  try {
983
1306
  const decipher = createDecipheriv("aes-256-gcm", key, raw.subarray(0, IV_BYTES));
984
1307
  decipher.setAAD(Buffer.from(VERSION));
@@ -998,9 +1321,11 @@ const PREFIX = {
998
1321
  cli: "coffre_cli_",
999
1322
  service: "coffre_svc_",
1000
1323
  personal: "coffre_pat_",
1001
- handle: "coffre_use_"
1324
+ handle: "coffre_use_",
1325
+ workload: "coffre_wl_",
1326
+ enrollment: "coffre_enr_"
1002
1327
  };
1003
- const TOKEN = /^coffre_(web|cli|svc|pat|use)_[A-Za-z0-9_-]{43}$/;
1328
+ const TOKEN = /^coffre_(web|cli|svc|pat|use|wl|enr)_[A-Za-z0-9_-]{43}$/;
1004
1329
  function generateToken(kind) {
1005
1330
  return PREFIX[kind] + randomBytes(32).toString("base64url");
1006
1331
  }
@@ -1047,8 +1372,8 @@ function asNonEmptyString(value) {
1047
1372
  /**
1048
1373
  * Verifies Cloudflare Access JWTs.
1049
1374
  *
1050
- * Signature and claim verification for the TanStack request boundary. The
1051
- * boundary also rejects `x-middleware-subrequest` before calling this verifier.
1375
+ * Signature and claim verification of the token Access sends with each
1376
+ * request.
1052
1377
  */
1053
1378
  var AccessIdentityVerifier = class {
1054
1379
  #config;
@@ -1157,7 +1482,10 @@ function decodeWorkloadToken(token) {
1157
1482
  * the issuer exactly; `exp`, `nbf` and `iat` within the tolerance, `iat` at
1158
1483
  * most an hour old; and the audience, this instance's public URL alone.
1159
1484
  * With `maxLifetime`, in seconds, a token whose `exp` is further than that
1160
- * from its `iat` is refused too. Returns the verified claims.
1485
+ * from its `iat` is refused too. With `maxAge: null`, its `iat` may be any
1486
+ * age, and its own `exp` alone ends it: a token its platform hands out
1487
+ * again for hours, a managed identity's (docs/design/workload-access.md,
1488
+ * section 4.2). Returns the verified claims.
1161
1489
  */
1162
1490
  async function verifyWorkloadToken(token, keys, expected) {
1163
1491
  const options = {
@@ -1179,7 +1507,7 @@ async function verifyWorkloadToken(token, keys, expected) {
1179
1507
  if (!(error instanceof errors.JWKSMultipleMatchingKeys)) throw refusalOf(error);
1180
1508
  payload = await anyKey(token, error, options);
1181
1509
  }
1182
- const issued = issuedRefusal(payload.iat, expected.now.getTime() / 1e3);
1510
+ const issued = issuedRefusal(payload.iat, expected.now.getTime() / 1e3, expected.maxAge === null ? Infinity : MAX_TOKEN_AGE_SECONDS);
1183
1511
  if (issued !== null) throw issued;
1184
1512
  if (expected.maxLifetime !== void 0 && payload.exp - payload.iat > expected.maxLifetime) throw new WorkloadTokenRefused("too_long", `the token lives longer than ${expected.maxLifetime / 60} minutes, from its iat to its exp: ask for a shorter one`);
1185
1513
  const { aud } = payload;
@@ -1188,12 +1516,12 @@ async function verifyWorkloadToken(token, keys, expected) {
1188
1516
  }
1189
1517
  /**
1190
1518
  * Why a token issued at `iat` may not be exchanged at `now`, both in
1191
- * seconds, or null: issued an hour ago at most, exactly, and no further
1192
- * ahead than the clock tolerance. Verification and the exchange's commit
1193
- * both ask it.
1519
+ * seconds, or null: issued `maxAge` seconds ago at most, an hour unless
1520
+ * said, exactly, and no further ahead than the clock tolerance.
1521
+ * Verification and the exchange's commit both ask it.
1194
1522
  */
1195
- function issuedRefusal(iat, now) {
1196
- if (now - iat > 3600) return new WorkloadTokenRefused("too_old", `the token was issued more than ${MAX_TOKEN_AGE_SECONDS / 60} minutes ago`);
1523
+ function issuedRefusal(iat, now, maxAge = MAX_TOKEN_AGE_SECONDS) {
1524
+ if (now - iat > maxAge) return new WorkloadTokenRefused("too_old", `the token was issued more than ${maxAge / 60} minutes ago`);
1197
1525
  if (iat - now > 30) return new WorkloadTokenRefused("too_old", "the token says it was issued in the future");
1198
1526
  return null;
1199
1527
  }
@@ -1306,7 +1634,7 @@ async function uploadedKeys(value) {
1306
1634
  keys.push(key);
1307
1635
  }
1308
1636
  if (keys.length === 0) throw new KeysInvalid("the key set holds no key that signs");
1309
- const sorted = keys.map((key) => [`${thumbprint(key)} ${JSON.stringify(key)}`, key]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
1637
+ const sorted = keys.map((key) => [`${thumbprint$2(key)} ${JSON.stringify(key)}`, key]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
1310
1638
  const jwks = JSON.stringify({ keys: sorted.map(([, key]) => key) });
1311
1639
  return {
1312
1640
  jwks,
@@ -1319,11 +1647,11 @@ function keySummaries(jwks) {
1319
1647
  return JSON.parse(jwks).keys.map((key) => ({
1320
1648
  kid: key.kid ?? null,
1321
1649
  alg: key.kty === "RSA" ? "RS256" : "ES256",
1322
- thumbprint: thumbprint(key)
1650
+ thumbprint: thumbprint$2(key)
1323
1651
  }));
1324
1652
  }
1325
1653
  /** A key's RFC 7638 thumbprint: the SHA-256 of its required members alone, in lexicographic order. */
1326
- function thumbprint(key) {
1654
+ function thumbprint$2(key) {
1327
1655
  const required = key.kty === "RSA" ? {
1328
1656
  e: key.e,
1329
1657
  kty: key.kty,
@@ -1357,4 +1685,4 @@ function kidAndUse(jwk) {
1357
1685
  };
1358
1686
  }
1359
1687
  //#endregion
1360
- export { ACCESS_JWT_HEADER, AccessIdentityVerifier, BindingInvalid, CLOCK_TOLERANCE_SECONDS, EVENT_EXPOSURE, GITHUB_EVENTS, GITHUB_ISSUER, GITLAB_ISSUER, GITLAB_PIPELINE_SOURCES, GitHubApp, GitHubAppUnavailable, GitHubSigninProvider, KeysInvalid, MAX_BINDINGS, MAX_CLAIMS, MAX_CLAIM_BYTES, MAX_ISSUER_BYTES, MAX_KEYS, MAX_LISTING_REQUESTS, MAX_TOKEN_AGE_SECONDS, MAX_TOKEN_BYTES, OidcSigninProvider, REQUIRED_CLAIMS, SigninError, TOKEN_MARGIN_MS, WORKLOAD_ALGORITHMS, WORKLOAD_PROFILES, WorkloadTokenRefused, canonicalClaims, checkBinding, checkFetchUrl, claimAt, claimValues, cloudflareAccess, decodeWorkloadToken, defaultIssuer, defineSignin, deriveKey, differingClaims, fullRef, generateToken, github, githubApp, githubEventsAt, githubReusable, githubWorkflow, gitlabProject, google, hashToken, isCoffreToken, issuedRefusal, keySummaries, microsoft, oidc, pkcs8Of, publicOrigin, seal, signin, toPrincipal, tokenHint, tokenKind, unseal, uploadedKeys, verifyWorkloadToken, workflowRef };
1688
+ export { ACCESS_JWT_HEADER, AccessIdentityVerifier, BEARER_PROFILES, BindingInvalid, 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_SIGNED_HEADERS, MAX_SOURCES, MAX_TOKEN_AGE_SECONDS, MAX_TOKEN_BYTES, OIDC_PROFILES, OidcSigninProvider, POLICY_DEFAULTS, POLICY_FIELDS, PROFILE_URNS, PROOF_SKEW_SECONDS, REPEATING_PROFILES, REQUIRED_CLAIMS, SigninError, TOKEN_MARGIN_MS, WORKLOAD_ALGORITHMS, WORKLOAD_PROFILES, WorkloadTokenRefused, addressWithin, canonicalClaims, canonicalHtu, canonicalRequest, checkBinding, checkConstraints, checkFetchUrl, checkPolicy, claimAt, claimValues, cloudflareAccess, constraintsAllow, constraintsText, decodeWorkloadToken, defaultIssuer, defineSignin, deriveKey, differingClaims, 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, seal, sentTarget, signin, thumbprint, toPrincipal, tokenHint, tokenKind, unseal, uploadedKeys, verifyProof, verifyWorkloadToken, workflowRef };
package/dist/kek.js CHANGED
@@ -112,7 +112,7 @@ var LocalKekProvider = class LocalKekProvider {
112
112
  }
113
113
  async unwrap(wrapped, ctx, operation) {
114
114
  checkOperation(operation);
115
- if (wrapped.kekProvider !== this.provider || wrapped.kekId !== this.keyId) throw new KekBadClaimError(`wrapped DEK is for ${wrapped.kekProvider}:${wrapped.kekId}, not ${this.provider}:${this.keyId}`);
115
+ if (wrapped.kekProvider !== this.provider || wrapped.kekId !== this.keyId || wrapped.kekVersion !== this.keyVersion) throw new KekBadClaimError(`wrapped DEK is for ${wrapped.kekProvider}:${wrapped.kekId} version ${wrapped.kekVersion}, not ${this.provider}:${this.keyId} version ${this.keyVersion}`);
116
116
  if (wrapped.bytes.length !== 60) throw new KekBadClaimError("wrapped DEK has the wrong length");
117
117
  const iv = wrapped.bytes.subarray(0, IV_BYTES);
118
118
  const tag = wrapped.bytes.subarray(IV_BYTES, 28);
package/dist/schemas.d.ts CHANGED
@@ -39,11 +39,11 @@ export declare const principalType: z.ZodEnum<{
39
39
  }>;
40
40
  export declare const principalId: z.ZodString;
41
41
  export declare const instanceRole: z.ZodEnum<{
42
- developer: "developer";
43
- auditor: "auditor";
44
- owner: "owner";
45
42
  member: "member";
43
+ auditor: "auditor";
44
+ developer: "developer";
46
45
  admin: "admin";
46
+ owner: "owner";
47
47
  }>;
48
48
  /** A project role's id: one coffre ships, or one an Owner made (`ROLE_ID`). Which the instance defines, its policy says. */
49
49
  export declare const roleId: z.ZodString;
package/dist/schemas.js CHANGED
@@ -1,4 +1,4 @@
1
- import { m as ROLE_ID, s as INSTANCE_ROLE_NAMES } from "./access-Dl13x6mB.js";
1
+ import { m as ROLE_ID, s as INSTANCE_ROLE_NAMES } from "./access-CembYDiI.js";
2
2
  import { PROJECT_PAGES } from "./pages.js";
3
3
  import { z } from "zod";
4
4
  //#region src/schemas.ts
package/dist/vault.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { D as RoleDefinition, E as Role, O as Scope, S as Policy, j as ServiceSetting, m as InstanceRole, r as CredentialScope, u as GrantPlace } from "./access-CF4noOjL.js";
1
+ import { A as Scope, N as ServiceSetting, O as Role, d as GrantPlace, g as InstanceRole, i as CredentialScope, k as RoleDefinition, n as CallerKind, w as Policy } from "./access-CU3xEOLH.js";
2
2
  //#region src/access-fault.d.ts
3
3
  /**
4
4
  * Why the vault's members and grants do not follow from its log, as facts
@@ -111,7 +111,10 @@ export interface Vault {
111
111
  * It needs a write grant, not a read one, since the key never leaves the
112
112
  * vault. A new version is never less sensitive than the one it is made
113
113
  * from, or than its secret's newest: a value is made looser only by
114
- * being written again (`invalid`).
114
+ * being written again (`invalid`). Except one: a key's current sensitive
115
+ * value made a secret, in place, by an Owner of its project, or of the
116
+ * whole instance, on no credential's scope (`ownsProject`; `not_allowed`
117
+ * for anyone else), its entry saying `was: 'sensitive'`.
115
118
  */
116
119
  rewrap(input: RewrapInput): Promise<Outcome<Wrapped>>;
117
120
  /**
@@ -195,7 +198,8 @@ export interface Vault {
195
198
  * Member;
196
199
  * - environments of one project protected, by whoever manages its
197
200
  * environments, before their rows exist too (a fork's); or
198
- * unprotected, by an Owner of the whole instance.
201
+ * unprotected, by an Owner of the project or of the whole instance
202
+ * (`ownsProject`), as far as that project protected them.
199
203
  * The policy after it, and the newest `policy.change`, which it is as of:
200
204
  * the change's own, when it changed anything.
201
205
  */
@@ -297,6 +301,21 @@ export type RefusalCode =
297
301
  * credential proxy, and service accounts read it.
298
302
  */
299
303
  'sensitive' |
304
+ /**
305
+ * A service account asked for a sensitive value to be handed back on a
306
+ * credential no Owner of its project issued (`readsSensitive`, R32): it
307
+ * reads every other value there, and that one once an Owner issues it a
308
+ * token or binding.
309
+ */
310
+ 'not_owner_issued' |
311
+ /**
312
+ * A workload asked for a value its credential does not list where the
313
+ * value is held (`useOnly`) for anything but the proxy's use: to read
314
+ * it, compare a guess with it or copy it, or to make a reference to it.
315
+ * It uses that value through coffre, and never holds it, nor moves it
316
+ * where it would.
317
+ */
318
+ 'use_only' |
300
319
  /**
301
320
  * The project or environment was deleted for good: nothing under it is
302
321
  * opened or wrapped again, whatever grant would cover it.
@@ -428,13 +447,24 @@ type Correlation = {
428
447
  credentialId?: string | null;
429
448
  };
430
449
  /**
431
- * The scope of the credential the request came in on, a service token's or
432
- * a trust binding's: unlike the correlation, the vault decides on it, and
433
- * its principal holds nothing past it (`allows`). Null, or left out, for a
450
+ * The credential the request came in on, which the vault decides on, unlike
451
+ * the correlation.
452
+ *
453
+ * `credentialScope` is a service token's or a trust binding's scope: its
454
+ * principal holds nothing past it (`allows`). Null, or left out, for a
434
455
  * session's, which carries all its member holds.
456
+ *
457
+ * `caller` is what kind of credential it is (`CallerKind`): a person's, on
458
+ * a `user:` principal; a bearer's or a workload's, on a `token:` one. A
459
+ * workload's comes with its scope, or the vault refuses the call outright,
460
+ * and is handed back only the values the scope lists where each is held
461
+ * (`useOnly`, docs/design/workload-access.md, section 6.1): any other is
462
+ * refused `use_only`. An app older than 0.11 says none, and has no
463
+ * workloads: the vault, deployed first, decides for it as before.
435
464
  */
436
465
  export type Through = {
437
466
  credentialScope?: CredentialScope | null;
467
+ caller: CallerKind;
438
468
  };
439
469
  export type UnwrapInput = Correlation & Through & {
440
470
  principal: string;
@@ -709,4 +739,4 @@ export type LogVerification = {
709
739
  fault?: AccessFault;
710
740
  };
711
741
  //#endregion
712
- export type { AccessFault, FaultGrant, FaultNames };
742
+ export type { AccessFault, CallerKind, FaultGrant, FaultNames };