@farthershore/backend 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.
@@ -218,7 +218,9 @@ var RUNTIME_ERROR_CODES = {
218
218
  environmentMismatch: "environment_mismatch",
219
219
  missingToken: "missing_token",
220
220
  invalidToken: "invalid_token",
221
- contextUnverified: "context_unverified"
221
+ contextUnverified: "context_unverified",
222
+ memberSubjectRequired: "member_subject_required",
223
+ serviceSubjectRequired: "service_subject_required"
222
224
  };
223
225
  var RUNTIME_RESPONSE_METERING_CONTRACT = {
224
226
  headers: {
@@ -282,7 +284,10 @@ var RUNTIME_ERROR_CODE_TO_ERROR_CODE = {
282
284
  // the canonical code keeps the "dependency down" semantic for callers.
283
285
  [RUNTIME_ERROR_CODES.jwksUnavailable]: "SERVICE_UNAVAILABLE",
284
286
  // The single non-401 (413) — oversized request body.
285
- [RUNTIME_ERROR_CODES.bodyTooLarge]: "VALIDATION_ERROR"
287
+ [RUNTIME_ERROR_CODES.bodyTooLarge]: "VALIDATION_ERROR",
288
+ // Consumer-principal wave — route subject-requirement faults → FORBIDDEN (403).
289
+ [RUNTIME_ERROR_CODES.memberSubjectRequired]: "FORBIDDEN",
290
+ [RUNTIME_ERROR_CODES.serviceSubjectRequired]: "FORBIDDEN"
286
291
  };
287
292
  var FS_RUNTIME_TOKEN_ENV = "FS_RUNTIME_TOKEN";
288
293
  var RUNTIME_TOKEN_PREFIXES = {
@@ -300,10 +305,6 @@ var RUNTIME_HEADER_NAMES = {
300
305
  policyVersion: "x-fs-policy-version",
301
306
  bodyHash: "x-fs-body-hash"
302
307
  };
303
- var RUNTIME_IDENTITY_HEADER_NAMES = {
304
- permissions: "x-fs-permissions",
305
- roles: "x-fs-roles"
306
- };
307
308
  var RUNTIME_CLOCK_SKEW_SECONDS = 5;
308
309
  var RUNTIME_REPLAY_WINDOW_SECONDS = 300;
309
310
  var EMPTY_BODY_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
@@ -349,31 +350,16 @@ var CANONICAL_SIGNING_FIELDS = [
349
350
  "business-id",
350
351
  "backend-id",
351
352
  "route-id",
352
- "policy-version"
353
+ "policy-version",
354
+ // Consumer-principal wave (D3) — the trailing identity-context binding line.
355
+ // MUST stay last so pre-binding verifiers that stop at `policy-version`
356
+ // fail loud on a bound request rather than silently accepting a prefix.
357
+ "context-hash"
353
358
  ];
354
359
  var CANONICAL_FIELD_SEPARATOR = "\n";
355
360
  var CANONICAL_KV_SEPARATOR = ":";
356
361
  function canonicalizeQuery(query) {
357
- const raw = query.startsWith("?") ? query.slice(1) : query;
358
- if (raw === "")
359
- return "";
360
- const pairs = raw.split("&").filter((p) => p.length > 0);
361
- pairs.sort((a, b) => {
362
- const [an, ...arest] = a.split("=");
363
- const [bn, ...brest] = b.split("=");
364
- if (an < bn)
365
- return -1;
366
- if (an > bn)
367
- return 1;
368
- const av = arest.join("=");
369
- const bv = brest.join("=");
370
- if (av < bv)
371
- return -1;
372
- if (av > bv)
373
- return 1;
374
- return 0;
375
- });
376
- return pairs.join("&");
362
+ return query;
377
363
  }
378
364
  function buildCanonicalSigningString(input) {
379
365
  const values = {
@@ -386,10 +372,14 @@ function buildCanonicalSigningString(input) {
386
372
  "business-id": input.businessId,
387
373
  "backend-id": input.backendId,
388
374
  "route-id": input.routeId,
389
- "policy-version": input.policyVersion
375
+ "policy-version": input.policyVersion,
376
+ "context-hash": input.contextHash
390
377
  };
391
378
  return CANONICAL_SIGNING_FIELDS.map((field) => `${field}${CANONICAL_KV_SEPARATOR}${values[field]}`).join(CANONICAL_FIELD_SEPARATOR);
392
379
  }
380
+ function hashContextToken(token) {
381
+ return hashBody(new TextEncoder().encode(token ?? ""));
382
+ }
393
383
  var ED25519_ALGORITHM = "Ed25519";
394
384
  async function importEd25519PrivateKey(jwk) {
395
385
  return crypto.subtle.importKey("jwk", { ...jwk, alg: void 0 }, { name: ED25519_ALGORITHM }, false, ["sign"]);
@@ -431,6 +421,7 @@ function base64UrlDecode(value) {
431
421
  // src/runtime-signing.ts
432
422
  var hashBody2 = hashBody;
433
423
  var buildCanonicalSigningString2 = buildCanonicalSigningString;
424
+ var hashContextToken2 = hashContextToken;
434
425
  var signCanonicalString2 = signCanonicalString;
435
426
  var verifyCanonicalSignature2 = verifyCanonicalSignature;
436
427
  var runtimeTokenKind2 = runtimeTokenKind;
@@ -611,7 +602,10 @@ async function makeSignedRequest(spec = {}) {
611
602
  businessId: spec.businessId ?? "biz_test",
612
603
  backendId: spec.backendId ?? "be_test",
613
604
  routeId: spec.routeId ?? "route_test",
614
- policyVersion: spec.policyVersion ?? "pv_1"
605
+ policyVersion: spec.policyVersion ?? "pv_1",
606
+ // Consumer-principal wave (D3): bind the X-Fs-Context hash into the
607
+ // canonical string (empty context → SHA-256 of the empty string).
608
+ contextHash: await hashContextToken2(spec.contextToken)
615
609
  };
616
610
  const canonical = buildCanonicalSigningString2(claim);
617
611
  const signature = await signCanonicalString2(canonical, privateJwk);
@@ -624,7 +618,8 @@ async function makeSignedRequest(spec = {}) {
624
618
  [RUNTIME_HEADER_NAMES.backendId]: claim.backendId,
625
619
  [RUNTIME_HEADER_NAMES.routeId]: claim.routeId,
626
620
  [RUNTIME_HEADER_NAMES.policyVersion]: claim.policyVersion,
627
- [RUNTIME_HEADER_NAMES.bodyHash]: claim.bodyHash
621
+ [RUNTIME_HEADER_NAMES.bodyHash]: claim.bodyHash,
622
+ ...spec.contextToken ? { "x-fs-context": spec.contextToken } : {}
628
623
  };
629
624
  return {
630
625
  input: { method, path, query, body, streamingExempt },
@@ -663,7 +658,7 @@ function base64urlEncodeJson(value) {
663
658
  }
664
659
  async function signContextToken(claim, secret = TEST_CONTEXT_SECRET, kid = TEST_CONTEXT_KID) {
665
660
  const header = base64urlEncodeJson({ alg: "HS256", typ: "JWT", kid });
666
- const payload = base64urlEncodeJson({ cv: 1, ...claim });
661
+ const payload = base64urlEncodeJson({ ...claim });
667
662
  const signingInput = `${header}.${payload}`;
668
663
  const key2 = await crypto.subtle.importKey(
669
664
  "raw",
@@ -743,12 +738,15 @@ function mergeHeaders(initHeaders, signedHeaders) {
743
738
  return headers;
744
739
  }
745
740
  function buildContextClaim(persona, businessId) {
741
+ const memberId = persona.actor?.id ?? `user_${persona.name}`;
746
742
  return {
747
- orgId: persona.orgId ?? "org_dev",
748
- actor: persona.actor ?? { type: "user", id: `user_${persona.name}` },
749
- // Business binding: the retained signed-context productId claim MUST equal
750
- // the signed request businessId or verifyRequest rejects it as tamper evidence.
751
- productId: businessId,
743
+ cv: 2,
744
+ sub: memberId,
745
+ subjectKind: "member",
746
+ org: persona.orgId ?? "org_dev",
747
+ // Business binding: the signed-context businessId claim MUST equal the
748
+ // signed request businessId or verifyRequest rejects it as tamper evidence.
749
+ businessId,
752
750
  compiledPlanId: persona.compiledPlanId ?? "plan_dev",
753
751
  subscriptionId: persona.subscriptionId ?? "sub_dev",
754
752
  subscriberId: persona.subscriberId ?? "subscriber_dev",
@@ -770,6 +768,11 @@ function createPersonaClient(ctx) {
770
768
  }
771
769
  async function buildHeaders(persona, spec) {
772
770
  const method = normalizeMethod(spec.method);
771
+ const contextToken = persona.anonymous ? void 0 : await signContextToken(
772
+ buildContextClaim(persona, ctx.businessId),
773
+ ctx.contextSecret,
774
+ ctx.contextKid
775
+ );
773
776
  const signed = await makeSignedRequest({
774
777
  method,
775
778
  path: spec.path ?? "/",
@@ -781,19 +784,11 @@ function createPersonaClient(ctx) {
781
784
  routeId: spec.routeId ?? "",
782
785
  privateJwk: ctx.keys.privateJwk,
783
786
  kid: ctx.keys.kid,
787
+ ...contextToken ? { contextToken } : {},
784
788
  ...spec.requestId ? { requestId: spec.requestId } : {},
785
789
  ...spec.timestamp !== void 0 ? { timestamp: spec.timestamp } : {}
786
790
  });
787
- const headers = { ...signed.headers };
788
- if (!persona.anonymous) {
789
- const claim = buildContextClaim(persona, ctx.businessId);
790
- headers["x-fs-context"] = await signContextToken(
791
- claim,
792
- ctx.contextSecret,
793
- ctx.contextKid
794
- );
795
- }
796
- return headers;
791
+ return { ...signed.headers };
797
792
  }
798
793
  function asPersona(name) {
799
794
  const persona = resolve(name);
@@ -1422,8 +1417,8 @@ function resolveEndpoint2(endpoint, coreUrl) {
1422
1417
  }
1423
1418
 
1424
1419
  // src/core/nonceCache.ts
1425
- var DEFAULT_MAX_ENTRIES = 1e5;
1426
- var DEFAULT_TTL_MS = 6e5;
1420
+ var DEFAULT_MAX_ENTRIES = 25e4;
1421
+ var DEFAULT_TTL_MS = (RUNTIME_REPLAY_WINDOW_SECONDS + RUNTIME_CLOCK_SKEW_SECONDS) * 1e3;
1427
1422
  var NonceCache = class {
1428
1423
  maxEntries;
1429
1424
  ttlMs;
@@ -1447,7 +1442,7 @@ var NonceCache = class {
1447
1442
  this.seen.delete(id);
1448
1443
  }
1449
1444
  this.evictExpired(at);
1450
- this.evictOverflow();
1445
+ if (this.seen.size >= this.maxEntries) return true;
1451
1446
  this.seen.set(id, at);
1452
1447
  return false;
1453
1448
  }
@@ -1461,13 +1456,6 @@ var NonceCache = class {
1461
1456
  this.seen.delete(id);
1462
1457
  }
1463
1458
  }
1464
- evictOverflow() {
1465
- while (this.seen.size >= this.maxEntries) {
1466
- const oldest = this.seen.keys().next().value;
1467
- if (oldest === void 0) break;
1468
- this.seen.delete(oldest);
1469
- }
1470
- }
1471
1459
  };
1472
1460
 
1473
1461
  // src/core/shutdown.ts
@@ -1802,47 +1790,82 @@ function resolvePackageBinary(require2, pkg, manifestPath) {
1802
1790
  return `${root}${sep}${normalized}`;
1803
1791
  }
1804
1792
 
1805
- // src/core/permissions.ts
1806
- var WILDCARD = "*";
1807
- var FartherShorePermissionError = class extends Error {
1808
- code = "permission_denied";
1809
- status = 403;
1810
- /** The permission key that was required but not held. */
1811
- requiredPermission;
1812
- constructor(requiredPermission, message) {
1813
- super(message ?? `missing required permission: ${requiredPermission}`);
1814
- this.name = "FartherShorePermissionError";
1815
- this.requiredPermission = requiredPermission;
1816
- }
1817
- };
1818
- function parsePermissionHeader(raw) {
1819
- if (raw === null || raw === void 0) return void 0;
1820
- return raw.split(",").map((p) => p.trim()).filter((p) => p.length > 0);
1793
+ // ../contracts/dist/authz/principal.js
1794
+ var SUBJECT_KINDS = ["member", "service"];
1795
+ function isSubjectKind(value) {
1796
+ return typeof value === "string" && SUBJECT_KINDS.includes(value);
1821
1797
  }
1822
- function permissionSatisfies(required, granted) {
1823
- if (granted === void 0) return true;
1824
- if (granted.includes(WILDCARD)) return true;
1825
- if (granted.includes(required)) return true;
1826
- const idx = required.indexOf(":");
1827
- if (idx > 0 && idx < required.length - 1) {
1828
- const subject = required.slice(0, idx);
1829
- if (granted.includes(`${subject}:${WILDCARD}`)) return true;
1830
- }
1831
- return false;
1798
+ function isNonEmptyTrimmed(value) {
1799
+ return typeof value === "string" && value.trim().length > 0;
1832
1800
  }
1833
- function hasPermission(ctx, key2) {
1834
- if (ctx.permissions === void 0) {
1835
- return ctx.signedContext !== void 0;
1836
- }
1837
- return permissionSatisfies(key2, ctx.permissions);
1801
+ function normalizeIdentityId(value) {
1802
+ return value.trim();
1838
1803
  }
1839
- function requirePermission(ctx, key2) {
1840
- if (!hasPermission(ctx, key2)) {
1841
- throw new FartherShorePermissionError(key2);
1804
+ function isNonEmptyStringArray(value) {
1805
+ return Array.isArray(value) && value.every((item) => isNonEmptyTrimmed(item));
1806
+ }
1807
+ function principalFromContextClaims(claims) {
1808
+ if (typeof claims !== "object" || claims === null)
1809
+ return null;
1810
+ const { sub, org: orgId, businessId, subjectKind } = claims;
1811
+ if (!isNonEmptyTrimmed(sub) || !isNonEmptyTrimmed(orgId) || !isNonEmptyTrimmed(businessId)) {
1812
+ return null;
1842
1813
  }
1814
+ if (!isSubjectKind(subjectKind))
1815
+ return null;
1816
+ if (claims.permissions !== void 0 && !isNonEmptyStringArray(claims.permissions)) {
1817
+ return null;
1818
+ }
1819
+ if (claims.roles !== void 0 && !isNonEmptyStringArray(claims.roles)) {
1820
+ return null;
1821
+ }
1822
+ const clientId = claims.client_id;
1823
+ const actSub = claims.act?.sub;
1824
+ if (isNonEmptyTrimmed(clientId) && isNonEmptyTrimmed(actSub) && normalizeIdentityId(clientId) !== normalizeIdentityId(actSub)) {
1825
+ return null;
1826
+ }
1827
+ const org = { id: normalizeIdentityId(orgId) };
1828
+ if (subjectKind === "service") {
1829
+ const explicitServiceAccountId = claims.serviceAccountId;
1830
+ if (isNonEmptyTrimmed(explicitServiceAccountId) && normalizeIdentityId(explicitServiceAccountId) !== normalizeIdentityId(sub)) {
1831
+ return null;
1832
+ }
1833
+ const serviceAccountId = normalizeIdentityId(explicitServiceAccountId ?? sub);
1834
+ const keyIdSource = clientId ?? actSub ?? sub;
1835
+ if (!isNonEmptyTrimmed(serviceAccountId) || !isNonEmptyTrimmed(keyIdSource)) {
1836
+ return null;
1837
+ }
1838
+ return {
1839
+ org,
1840
+ subject: {
1841
+ kind: "service",
1842
+ serviceAccountId,
1843
+ keyId: normalizeIdentityId(keyIdSource)
1844
+ }
1845
+ };
1846
+ }
1847
+ const memberId = normalizeIdentityId(sub);
1848
+ const act = claims.act;
1849
+ if (act !== void 0 && act !== null) {
1850
+ if (typeof act !== "object" || !isNonEmptyTrimmed(act.sub))
1851
+ return null;
1852
+ return {
1853
+ org,
1854
+ subject: {
1855
+ kind: "member",
1856
+ memberId,
1857
+ via: "api_key",
1858
+ keyId: normalizeIdentityId(act.sub)
1859
+ }
1860
+ };
1861
+ }
1862
+ return { org, subject: { kind: "member", memberId, via: "session" } };
1843
1863
  }
1844
1864
 
1845
1865
  // src/core/verifyContext.ts
1866
+ function principalFromContextClaims2(claims) {
1867
+ return principalFromContextClaims(claims);
1868
+ }
1846
1869
  var EXPECTED_JWT_ALG = "HS256";
1847
1870
  function base64urlDecode(value) {
1848
1871
  const padded = value.replace(/-/g, "+").replace(/_/g, "/");
@@ -1882,6 +1905,7 @@ async function verifyContext(token, secrets) {
1882
1905
  }
1883
1906
  let verified = false;
1884
1907
  for (const secret of secrets) {
1908
+ if (secret.trim().length === 0) continue;
1885
1909
  try {
1886
1910
  const key2 = await importHmacKey(secret);
1887
1911
  if (await crypto.subtle.verify(
@@ -1897,11 +1921,20 @@ async function verifyContext(token, secrets) {
1897
1921
  }
1898
1922
  }
1899
1923
  if (!verified) return null;
1924
+ return parseContextPayload(payload);
1925
+ }
1926
+ function decodeContextClaims(token) {
1927
+ const parts = token.split(".");
1928
+ if (parts.length !== 3) return null;
1929
+ return parseContextPayload(parts[1]);
1930
+ }
1931
+ function parseContextPayload(payload) {
1900
1932
  try {
1901
1933
  const parsed = JSON.parse(
1902
1934
  new TextDecoder().decode(base64urlDecode(payload))
1903
1935
  );
1904
1936
  if (typeof parsed !== "object" || parsed === null) return null;
1937
+ if (parsed.cv !== 2) return null;
1905
1938
  return parsed;
1906
1939
  } catch {
1907
1940
  return null;
@@ -1910,7 +1943,7 @@ async function verifyContext(token, secrets) {
1910
1943
  function contextRequiredError(reason) {
1911
1944
  return new FartherShoreError(
1912
1945
  "context_unverified",
1913
- `X-Fs-Context ${reason} (contextVerification is "required")`
1946
+ `X-Fs-Context ${reason} \u2014 signed context is required whenever context secrets are configured`
1914
1947
  );
1915
1948
  }
1916
1949
 
@@ -1986,6 +2019,7 @@ async function verifyRequest(input, deps) {
1986
2019
  "signed route-id is not served by this backend"
1987
2020
  );
1988
2021
  }
2022
+ const contextToken = h("x-fs-context") ?? null;
1989
2023
  const canonicalInput = {
1990
2024
  method: input.method,
1991
2025
  path: input.path,
@@ -1996,7 +2030,13 @@ async function verifyRequest(input, deps) {
1996
2030
  businessId: signedBusinessId,
1997
2031
  backendId: signedBackendId,
1998
2032
  routeId: signedRouteId,
1999
- policyVersion
2033
+ policyVersion,
2034
+ // Consumer-principal wave (D3): bind the presented X-Fs-Context hash into
2035
+ // the canonical string in exact lockstep with the gateway signer. A missing
2036
+ // context hashes the empty string, so an identity-less request still
2037
+ // verifies (it is rejected later by the fail-closed context gate when
2038
+ // secrets exist).
2039
+ contextHash: await hashContextToken2(contextToken)
2000
2040
  };
2001
2041
  const canonical = buildCanonicalSigningString2(canonicalInput);
2002
2042
  const publicJwk = await deps.jwks.getKey(kid);
@@ -2015,44 +2055,28 @@ async function verifyRequest(input, deps) {
2015
2055
  "Ed25519 signature verification failed"
2016
2056
  );
2017
2057
  }
2018
- if (deps.nonceCache.checkAndRemember(requestId)) {
2058
+ if (await deps.nonceCache.checkAndRemember(requestId)) {
2019
2059
  throw new FartherShoreError(
2020
2060
  "replayed_nonce",
2021
2061
  "x-fs-request-id has already been seen (replay)"
2022
2062
  );
2023
2063
  }
2024
- let permissions;
2025
- let roles;
2026
- let signedContext = null;
2027
- const contextSecrets = deps.contextSecrets ?? [];
2028
- const hasContextKeyring = contextSecrets.length > 0;
2029
- if (hasContextKeyring) {
2030
- const token = h("x-fs-context");
2031
- if (token) {
2032
- signedContext = await verifyContext(token, contextSecrets);
2033
- if (signedContext === null && deps.contextVerification === "required") {
2034
- throw contextRequiredError("failed verification");
2035
- }
2036
- if (signedContext && signedContext.productId !== signedBusinessId) {
2037
- throw new FartherShoreError(
2038
- "context_unverified",
2039
- "X-Fs-Context was minted for a different business than the signed request"
2040
- );
2041
- }
2042
- } else if (deps.contextVerification === "required") {
2043
- throw contextRequiredError("header is missing");
2044
- }
2045
- } else if (deps.contextVerification === "required") {
2046
- throw contextRequiredError("keyring is empty");
2047
- }
2064
+ const signedContext = await resolveSignedContext(
2065
+ contextToken,
2066
+ deps.contextSecrets ?? [],
2067
+ signedBusinessId
2068
+ );
2069
+ const permissions = signedContext?.permissions;
2070
+ const roles = signedContext?.roles;
2071
+ let principal;
2048
2072
  if (signedContext) {
2049
- permissions = signedContext.permissions;
2050
- roles = signedContext.roles;
2051
- } else {
2052
- permissions = parsePermissionHeader(
2053
- h(RUNTIME_IDENTITY_HEADER_NAMES.permissions)
2054
- );
2055
- roles = parsePermissionHeader(h(RUNTIME_IDENTITY_HEADER_NAMES.roles));
2073
+ const derived = principalFromContextClaims2(signedContext);
2074
+ if (derived === null) {
2075
+ throw contextRequiredError(
2076
+ "carried an invalid or incomplete consumer principal"
2077
+ );
2078
+ }
2079
+ principal = derived;
2056
2080
  }
2057
2081
  return {
2058
2082
  requestId,
@@ -2062,11 +2086,32 @@ async function verifyRequest(input, deps) {
2062
2086
  policyVersion,
2063
2087
  timestamp,
2064
2088
  bodyHash: computedBodyHash,
2089
+ ...principal ? { principal } : {},
2065
2090
  ...permissions !== void 0 ? { permissions } : {},
2066
2091
  ...roles !== void 0 ? { roles } : {},
2067
2092
  ...signedContext ? { signedContext } : {}
2068
2093
  };
2069
2094
  }
2095
+ async function resolveSignedContext(contextToken, contextSecrets, signedBusinessId) {
2096
+ if (!contextToken) return null;
2097
+ const signedContext = decodeContextClaims(contextToken);
2098
+ if (signedContext === null) {
2099
+ throw contextRequiredError("payload could not be parsed as a cv=2 claim");
2100
+ }
2101
+ if (contextSecrets.length > 0) {
2102
+ const hmacVerified = await verifyContext(contextToken, contextSecrets);
2103
+ if (hmacVerified === null) {
2104
+ throw contextRequiredError("failed HS256 verification");
2105
+ }
2106
+ }
2107
+ if (signedContext.businessId !== signedBusinessId) {
2108
+ throw new FartherShoreError(
2109
+ "context_unverified",
2110
+ "X-Fs-Context was minted for a different business than the signed request"
2111
+ );
2112
+ }
2113
+ return signedContext;
2114
+ }
2070
2115
  async function computeBodyHash(input) {
2071
2116
  if (input.streamingExempt) return STREAMING_EXEMPT_BODY_HASH;
2072
2117
  const body = input.body;
@@ -2099,8 +2144,8 @@ function headerGetter(headers) {
2099
2144
 
2100
2145
  // src/core/runtime.ts
2101
2146
  var DEFAULT_CORE_URL = "https://core.farthershore.com";
2102
- var SDK_VERSION = "0.15.0".length > 0 ? "0.15.0" : "0.0.0-dev";
2103
- var CONTRACTS_FP = "4b6a36b4cb1f0b68".length > 0 ? "4b6a36b4cb1f0b68" : "0000000000000000";
2147
+ var SDK_VERSION = "0.16.0".length > 0 ? "0.16.0" : "0.0.0-dev";
2148
+ var CONTRACTS_FP = "c3961d4ea07ff178".length > 0 ? "c3961d4ea07ff178" : "0000000000000000";
2104
2149
  var FartherShore = class {
2105
2150
  bootstrapClient;
2106
2151
  fetchImpl;
@@ -2110,11 +2155,9 @@ var FartherShore = class {
2110
2155
  coreUrl;
2111
2156
  instanceId;
2112
2157
  tunnelOptions;
2113
- /** FAR-723 HS256 secret(s) for verifying the signed X-Fs-Context claim. */
2158
+ /** OPTIONAL HS256 secret(s) defense-in-depth over the cv=2 X-Fs-Context. */
2114
2159
  contextSecrets;
2115
- /** FAR-723 — "preferred" (fallback to unsigned) | "required" (fail-closed). */
2116
- contextVerification;
2117
- nonceCache = new NonceCache();
2160
+ nonceCache;
2118
2161
  shutdownManager = new ShutdownManager();
2119
2162
  jwks = null;
2120
2163
  meteringClient = null;
@@ -2132,8 +2175,8 @@ var FartherShore = class {
2132
2175
  this.meteringEnabledOverride = options.metering?.enabled ?? true;
2133
2176
  this.tunnelOptions = options.tunnel ?? {};
2134
2177
  this.instanceId = options.instanceId;
2178
+ this.nonceCache = options.nonceStore ?? new NonceCache();
2135
2179
  this.contextSecrets = options.contextSecrets ?? parseContextSecrets(env.FS_CONTEXT_SECRETS);
2136
- this.contextVerification = options.contextVerification ?? (env.FS_CONTEXT_VERIFICATION === "required" ? "required" : "preferred");
2137
2180
  this.bootstrapClient = new BootstrapClient({
2138
2181
  runtimeToken,
2139
2182
  coreUrl,
@@ -2258,12 +2301,10 @@ var FartherShore = class {
2258
2301
  knownRouteIds,
2259
2302
  clockSkewSeconds: config.verification.clockSkewSeconds,
2260
2303
  replayWindowSeconds: config.verification.replayWindowSeconds,
2261
- // FAR-723 a VERIFIED signed X-Fs-Context is the preferred (or
2262
- // required) identity source. Required mode must also fail closed when the
2263
- // keyring is empty; preferred mode preserves the transitional unsigned
2264
- // fallback until the backend-v* publish gate removes it.
2265
- contextSecrets: this.contextSecrets,
2266
- contextVerification: this.contextVerification
2304
+ // Consumer-principal wave (D3): OPTIONAL defense-in-depth. The principal
2305
+ // is derived from the Ed25519-vouched X-Fs-Context regardless; when these
2306
+ // secrets are set a presented token must ALSO pass HS256.
2307
+ contextSecrets: this.contextSecrets
2267
2308
  });
2268
2309
  return {
2269
2310
  ...context,
@@ -2390,6 +2431,40 @@ function parseContextSecrets(raw) {
2390
2431
  return raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
2391
2432
  }
2392
2433
 
2434
+ // src/core/permissions.ts
2435
+ var WILDCARD = "*";
2436
+ var FartherShorePermissionError = class extends Error {
2437
+ code = "permission_denied";
2438
+ status = 403;
2439
+ /** The permission key that was required but not held. */
2440
+ requiredPermission;
2441
+ constructor(requiredPermission, message) {
2442
+ super(message ?? `missing required permission: ${requiredPermission}`);
2443
+ this.name = "FartherShorePermissionError";
2444
+ this.requiredPermission = requiredPermission;
2445
+ }
2446
+ };
2447
+ function permissionSatisfies(required, granted) {
2448
+ if (granted === void 0) return true;
2449
+ if (granted.includes(WILDCARD)) return true;
2450
+ if (granted.includes(required)) return true;
2451
+ const idx = required.indexOf(":");
2452
+ if (idx > 0 && idx < required.length - 1) {
2453
+ const subject = required.slice(0, idx);
2454
+ if (granted.includes(`${subject}:${WILDCARD}`)) return true;
2455
+ }
2456
+ return false;
2457
+ }
2458
+ function hasPermission(ctx, key2) {
2459
+ if (ctx.permissions === void 0) return false;
2460
+ return permissionSatisfies(key2, ctx.permissions);
2461
+ }
2462
+ function requirePermission(ctx, key2) {
2463
+ if (!hasPermission(ctx, key2)) {
2464
+ throw new FartherShorePermissionError(key2);
2465
+ }
2466
+ }
2467
+
2393
2468
  // src/adapters/express.ts
2394
2469
  var STREAMING_CONTENT_TYPES = new Set(
2395
2470
  RUNTIME_BODY_HASH_CONTRACT.streamingExemptContentTypes
@@ -2401,7 +2476,9 @@ function createExpressMiddleware(fs, options = {}) {
2401
2476
  }
2402
2477
  async function runMiddleware(fs, options, req, res, next) {
2403
2478
  try {
2404
- if (!options.always && !await fs.verificationRequired()) {
2479
+ const strict = options.always ?? true;
2480
+ if (!strict && !await fs.verificationRequired()) {
2481
+ stripFartherShoreHeaders(req);
2405
2482
  next();
2406
2483
  return;
2407
2484
  }
@@ -2418,6 +2495,7 @@ async function runMiddleware(fs, options, req, res, next) {
2418
2495
  streamingExempt
2419
2496
  });
2420
2497
  req.fartherShore = ctx;
2498
+ stripFartherShoreHeaders(req);
2421
2499
  next();
2422
2500
  } catch (error) {
2423
2501
  fail(res, error);
@@ -2430,6 +2508,51 @@ function fail(res, error) {
2430
2508
  }
2431
2509
  res.status(401).json({ error: "bad_signature" });
2432
2510
  }
2511
+ function stripFartherShoreHeaders(req) {
2512
+ const headers = req.headers;
2513
+ for (const name of Object.keys(headers)) {
2514
+ if (name.toLowerCase().startsWith("x-fs-")) {
2515
+ delete headers[name];
2516
+ }
2517
+ }
2518
+ const withRaw = req;
2519
+ const raw = withRaw.rawHeaders;
2520
+ if (Array.isArray(raw)) {
2521
+ const cleaned = [];
2522
+ for (let i = 0; i < raw.length; i += 2) {
2523
+ const key2 = raw[i];
2524
+ const value = raw[i + 1];
2525
+ if (typeof key2 !== "string" || value === void 0) continue;
2526
+ if (key2.toLowerCase().startsWith("x-fs-")) continue;
2527
+ cleaned.push(key2, value);
2528
+ }
2529
+ withRaw.rawHeaders = cleaned;
2530
+ }
2531
+ }
2532
+ function createExpressHandler(handler) {
2533
+ return (req, res, next) => {
2534
+ const ctx = req.fartherShore;
2535
+ if (!ctx) {
2536
+ res.status(401).json({ error: "context_unverified" });
2537
+ return;
2538
+ }
2539
+ if (!ctx.principal) {
2540
+ res.status(401).json({ error: "principal_required" });
2541
+ return;
2542
+ }
2543
+ const verified = ctx;
2544
+ void Promise.resolve().then(
2545
+ () => handler(verified, req, res, next)
2546
+ ).catch((error) => failHandler(res, next, error));
2547
+ };
2548
+ }
2549
+ function failHandler(res, next, error) {
2550
+ if (error instanceof FartherShoreError || error instanceof FartherShorePermissionError) {
2551
+ res.status(error.status).json({ error: error.code });
2552
+ return;
2553
+ }
2554
+ next(error);
2555
+ }
2433
2556
  function splitUrl(req) {
2434
2557
  const raw = req.originalUrl ?? req.url ?? req.path ?? "/";
2435
2558
  const qIndex = raw.indexOf("?");
@@ -2692,8 +2815,9 @@ function createDevRuntime(options) {
2692
2815
  runtimeToken: keys.runtimeToken,
2693
2816
  coreUrl: DEV_CORE_URL,
2694
2817
  fetchImpl: gateway.fetchImpl,
2818
+ // Consumer-principal wave (D3): signed cv=2 context is fail-closed whenever
2819
+ // contextSecrets are set — no per-mode verification toggle.
2695
2820
  contextSecrets: [keys.contextSecret],
2696
- contextVerification: mode === "simulated" ? "required" : "preferred",
2697
2821
  env: {}
2698
2822
  });
2699
2823
  const tracedAuthz = {
@@ -2719,7 +2843,8 @@ function createDevRuntime(options) {
2719
2843
  });
2720
2844
  }
2721
2845
  function middleware(mwOptions) {
2722
- const inner = createExpressMiddleware(fs, mwOptions);
2846
+ const resolved = mode === "passthrough" ? { always: false, ...mwOptions } : mwOptions ?? {};
2847
+ const inner = createExpressMiddleware(fs, resolved);
2723
2848
  return (req, res, next) => {
2724
2849
  const requestId = headerValue2(req.headers, "x-fs-request-id") ?? "unknown";
2725
2850
  const { path } = splitUrl2(req);
@@ -2758,6 +2883,7 @@ function createDevRuntime(options) {
2758
2883
  };
2759
2884
  }
2760
2885
  fs.middleware = middleware;
2886
+ fs.handler = createExpressHandler;
2761
2887
  const devRuntime = {
2762
2888
  fs,
2763
2889
  asPersona: (name) => personaClient.asPersona(name),