@farthershore/backend 0.3.0 → 0.8.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/README.md CHANGED
@@ -4,6 +4,10 @@ Runtime metering and gateway-verification SDK for builder upstreams. Install one
4
4
  package, set one token (`FS_RUNTIME_TOKEN`), and Farther Shore handles signed
5
5
  gateway-to-upstream request verification plus response-bound usage reporting.
6
6
 
7
+ > **Status: `0.8.0` (lockstep SDK family).** Published at the SAME version as
8
+ > `@farthershore/farthershore-js` and `@farthershore/product` — pin the three
9
+ > together. Pre-1.0: minor bumps may break.
10
+
7
11
  ## Install
8
12
 
9
13
  ```sh
@@ -4,11 +4,17 @@ import { createRequire as __createRequire } from "node:module";const require=__c
4
4
  var FartherShoreError = class extends Error {
5
5
  code;
6
6
  status;
7
- constructor(code, message, status) {
7
+ /** Present only when this error is a self-minted plan-limit deny (rare; the
8
+ * backend usually relays the gateway's descriptor-bearing deny instead). */
9
+ limitDescriptor;
10
+ constructor(code, message, status, limitDescriptor) {
8
11
  super(message);
9
12
  this.name = "FartherShoreError";
10
13
  this.code = code;
11
14
  this.status = status ?? statusForCode(code);
15
+ if (limitDescriptor !== void 0) {
16
+ this.limitDescriptor = limitDescriptor;
17
+ }
12
18
  }
13
19
  };
14
20
  function statusForCode(code) {
package/dist/index.js CHANGED
@@ -184,7 +184,102 @@ var init_reconcile = __esm({
184
184
  }
185
185
  });
186
186
 
187
+ // src/generated/runtime-contract.ts
188
+ var RUNTIME_BODY_HASH_CONTRACT = {
189
+ algorithm: "SHA-256",
190
+ encoding: "hex-lower",
191
+ source: "raw-request-bytes",
192
+ emptyBodyHash: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
193
+ maxBodyBytes: 10485760,
194
+ streamingExemptToken: "STREAM",
195
+ streamingExemptContentTypes: [
196
+ "text/event-stream",
197
+ "application/octet-stream",
198
+ "multipart/form-data"
199
+ ],
200
+ overMaxStatus: 413
201
+ };
202
+ var RUNTIME_ERROR_CODES = {
203
+ missingSignature: "missing_signature",
204
+ malformedSignature: "malformed_signature",
205
+ unknownKeyId: "unknown_key_id",
206
+ jwksUnavailable: "jwks_unavailable",
207
+ badSignature: "bad_signature",
208
+ bodyHashMismatch: "body_hash_mismatch",
209
+ routeMismatch: "route_mismatch",
210
+ clockSkew: "clock_skew",
211
+ expiredSignature: "expired_signature",
212
+ replayedNonce: "replayed_nonce",
213
+ bodyTooLarge: "body_too_large",
214
+ environmentMismatch: "environment_mismatch",
215
+ missingToken: "missing_token",
216
+ invalidToken: "invalid_token"
217
+ };
218
+ var RUNTIME_RESPONSE_METERING_CONTRACT = {
219
+ headers: {
220
+ payload: "x-fs-metering",
221
+ signature: "x-fs-metering-sig",
222
+ token: "x-fs-metering-token"
223
+ },
224
+ token: {
225
+ environmentVariable: "FS_RUNTIME_TOKEN",
226
+ presentation: "x-fs-metering-token",
227
+ storage: "sha256-hash-only"
228
+ },
229
+ signature: {
230
+ algorithm: "HMAC-SHA256",
231
+ encoding: "base64url",
232
+ input: "payload-json",
233
+ secret: "presented-runtime-token"
234
+ },
235
+ payload: {
236
+ method: "string",
237
+ path: "string",
238
+ rawDimsUnits: "Record<string, number>",
239
+ measureContext: "Record<string, unknown>?",
240
+ creditUnitsConsumed: "Record<string, number>?"
241
+ },
242
+ errors: {
243
+ missingToken: "missing_token",
244
+ invalidMeterKey: "invalid_meter_key",
245
+ invalidMeterValue: "invalid_meter_value"
246
+ },
247
+ httpAdapter: {
248
+ input: "Request",
249
+ output: "Response",
250
+ networkCalls: false,
251
+ preserves: ["body", "headers", "status", "statusText"],
252
+ gatewayStripsInternalHeaders: true
253
+ }
254
+ };
255
+
187
256
  // src/runtime-types.ts
257
+ var RUNTIME_ERROR_CODE_TO_ERROR_CODE = {
258
+ // Credential / token presentation faults → UNAUTHORIZED (401).
259
+ [RUNTIME_ERROR_CODES.missingToken]: "UNAUTHORIZED",
260
+ [RUNTIME_ERROR_CODES.invalidToken]: "UNAUTHORIZED",
261
+ // Signature / key faults → UNAUTHORIZED (401, fail-closed verification).
262
+ [RUNTIME_ERROR_CODES.missingSignature]: "UNAUTHORIZED",
263
+ [RUNTIME_ERROR_CODES.malformedSignature]: "UNAUTHORIZED",
264
+ [RUNTIME_ERROR_CODES.unknownKeyId]: "UNAUTHORIZED",
265
+ [RUNTIME_ERROR_CODES.badSignature]: "UNAUTHORIZED",
266
+ [RUNTIME_ERROR_CODES.expiredSignature]: "UNAUTHORIZED",
267
+ // Replay / freshness faults → UNAUTHORIZED (401).
268
+ [RUNTIME_ERROR_CODES.clockSkew]: "UNAUTHORIZED",
269
+ [RUNTIME_ERROR_CODES.replayedNonce]: "UNAUTHORIZED",
270
+ // Request/route binding faults → UNAUTHORIZED (401, fail-closed).
271
+ [RUNTIME_ERROR_CODES.bodyHashMismatch]: "UNAUTHORIZED",
272
+ [RUNTIME_ERROR_CODES.routeMismatch]: "UNAUTHORIZED",
273
+ [RUNTIME_ERROR_CODES.environmentMismatch]: "UNAUTHORIZED",
274
+ // JWKS fetch unavailable — dependency fault (still 401 to the client), but
275
+ // the canonical code keeps the "dependency down" semantic for callers.
276
+ [RUNTIME_ERROR_CODES.jwksUnavailable]: "SERVICE_UNAVAILABLE",
277
+ // The single non-401 (413) — oversized request body.
278
+ [RUNTIME_ERROR_CODES.bodyTooLarge]: "VALIDATION_ERROR"
279
+ };
280
+ function runtimeErrorToErrorCode(code) {
281
+ return RUNTIME_ERROR_CODE_TO_ERROR_CODE[code] ?? "INTERNAL_ERROR";
282
+ }
188
283
  var FS_RUNTIME_TOKEN_ENV = "FS_RUNTIME_TOKEN";
189
284
  var RUNTIME_TOKEN_PREFIXES = {
190
285
  live: "fsrt_live_",
@@ -195,8 +290,11 @@ var RUNTIME_TOKEN_CAPABILITIES = [
195
290
  "metering",
196
291
  "health",
197
292
  "tunnel",
198
- // Mirror of @farthershore/contracts RUNTIME_TOKEN_CAPABILITIES — kept in
199
- // lockstep (golden-vector test). Opt-in capability for reporting route drift.
293
+ // Hand-maintained mirror of @farthershore/contracts RUNTIME_TOKEN_CAPABILITIES
294
+ // (`runtime.ts`). Bound to that source by the SET-EQUALITY + ORDER assertions
295
+ // in `deny-taxonomy-drift.test.ts` (test-only contracts devDep) — NOT by the
296
+ // generated runtime-contract.ts, which mirrors only RUNTIME_ERROR_CODES.
297
+ // `drift_report` is the opt-in capability for reporting route drift.
200
298
  "drift_report"
201
299
  ];
202
300
  var RUNTIME_HEADER_NAMES = {
@@ -346,11 +444,17 @@ var runtimeTokenKind2 = runtimeTokenKind;
346
444
  var FartherShoreError = class extends Error {
347
445
  code;
348
446
  status;
349
- constructor(code, message, status) {
447
+ /** Present only when this error is a self-minted plan-limit deny (rare; the
448
+ * backend usually relays the gateway's descriptor-bearing deny instead). */
449
+ limitDescriptor;
450
+ constructor(code, message, status, limitDescriptor) {
350
451
  super(message);
351
452
  this.name = "FartherShoreError";
352
453
  this.code = code;
353
454
  this.status = status ?? statusForCode(code);
455
+ if (limitDescriptor !== void 0) {
456
+ this.limitDescriptor = limitDescriptor;
457
+ }
354
458
  }
355
459
  };
356
460
  function statusForCode(code) {
@@ -1233,7 +1337,8 @@ function headerGetter(headers) {
1233
1337
 
1234
1338
  // src/core/runtime.ts
1235
1339
  var DEFAULT_CORE_URL = "https://core.farthershore.com";
1236
- var SDK_VERSION = "0.3.0".length > 0 ? "0.3.0" : "0.0.0-dev";
1340
+ var SDK_VERSION = "0.8.0".length > 0 ? "0.8.0" : "0.0.0-dev";
1341
+ var CONTRACTS_FP = "af8995b9467842b6".length > 0 ? "af8995b9467842b6" : "0000000000000000";
1237
1342
  var FartherShore = class {
1238
1343
  bootstrapClient;
1239
1344
  fetchImpl;
@@ -1470,75 +1575,6 @@ function readProcessEnv() {
1470
1575
  return maybeProcess?.env ?? {};
1471
1576
  }
1472
1577
 
1473
- // src/generated/runtime-contract.ts
1474
- var RUNTIME_BODY_HASH_CONTRACT = {
1475
- algorithm: "SHA-256",
1476
- encoding: "hex-lower",
1477
- source: "raw-request-bytes",
1478
- emptyBodyHash: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
1479
- maxBodyBytes: 10485760,
1480
- streamingExemptToken: "STREAM",
1481
- streamingExemptContentTypes: [
1482
- "text/event-stream",
1483
- "application/octet-stream",
1484
- "multipart/form-data"
1485
- ],
1486
- overMaxStatus: 413
1487
- };
1488
- var RUNTIME_ERROR_CODES = {
1489
- missingSignature: "missing_signature",
1490
- malformedSignature: "malformed_signature",
1491
- unknownKeyId: "unknown_key_id",
1492
- jwksUnavailable: "jwks_unavailable",
1493
- badSignature: "bad_signature",
1494
- bodyHashMismatch: "body_hash_mismatch",
1495
- routeMismatch: "route_mismatch",
1496
- clockSkew: "clock_skew",
1497
- expiredSignature: "expired_signature",
1498
- replayedNonce: "replayed_nonce",
1499
- bodyTooLarge: "body_too_large",
1500
- environmentMismatch: "environment_mismatch",
1501
- missingToken: "missing_token",
1502
- invalidToken: "invalid_token"
1503
- };
1504
- var RUNTIME_RESPONSE_METERING_CONTRACT = {
1505
- headers: {
1506
- payload: "x-fs-metering",
1507
- signature: "x-fs-metering-sig",
1508
- token: "x-fs-metering-token"
1509
- },
1510
- token: {
1511
- environmentVariable: "FS_RUNTIME_TOKEN",
1512
- presentation: "x-fs-metering-token",
1513
- storage: "sha256-hash-only"
1514
- },
1515
- signature: {
1516
- algorithm: "HMAC-SHA256",
1517
- encoding: "base64url",
1518
- input: "payload-json",
1519
- secret: "presented-runtime-token"
1520
- },
1521
- payload: {
1522
- method: "string",
1523
- path: "string",
1524
- rawDimsUnits: "Record<string, number>",
1525
- measureContext: "Record<string, unknown>?",
1526
- creditUnitsConsumed: "Record<string, number>?"
1527
- },
1528
- errors: {
1529
- missingToken: "missing_token",
1530
- invalidMeterKey: "invalid_meter_key",
1531
- invalidMeterValue: "invalid_meter_value"
1532
- },
1533
- httpAdapter: {
1534
- input: "Request",
1535
- output: "Response",
1536
- networkCalls: false,
1537
- preserves: ["body", "headers", "status", "statusText"],
1538
- gatewayStripsInternalHeaders: true
1539
- }
1540
- };
1541
-
1542
1578
  // src/adapters/express.ts
1543
1579
  var STREAMING_CONTENT_TYPES = new Set(
1544
1580
  RUNTIME_BODY_HASH_CONTRACT.streamingExemptContentTypes
@@ -1770,6 +1806,7 @@ export {
1770
1806
  REDACTED_TOKEN,
1771
1807
  RUNTIME_CLOCK_SKEW_SECONDS,
1772
1808
  RUNTIME_ERROR_CODES,
1809
+ RUNTIME_ERROR_CODE_TO_ERROR_CODE,
1773
1810
  RUNTIME_HEADER_NAMES,
1774
1811
  RUNTIME_REPLAY_WINDOW_SECONDS,
1775
1812
  RUNTIME_TOKEN_CAPABILITIES,
@@ -1786,6 +1823,7 @@ export {
1786
1823
  initFromEnv2 as initFromEnv,
1787
1824
  nodeSpawn,
1788
1825
  reportHealth,
1826
+ runtimeErrorToErrorCode,
1789
1827
  runtimeTokenKind2 as runtimeTokenKind,
1790
1828
  signCanonicalString2 as signCanonicalString,
1791
1829
  statusForCode,
@@ -1,12 +1,23 @@
1
1
  import type { RuntimeErrorCode } from "../generated/runtime-contract.js";
2
+ import type { LimitDescriptor } from "../runtime-types.js";
2
3
  /**
3
4
  * A verification / runtime failure with a stable, cross-language `code` and the
4
5
  * fail-closed HTTP status the adapter should emit.
6
+ *
7
+ * Optionally carries a {@link LimitDescriptor} (`limitDescriptor`) when the
8
+ * failure is a plan-limit deny the backend chooses to surface itself, so SDKs
9
+ * can render an upgrade affordance from a backend-minted error. This is OPT-IN
10
+ * plumbing — the backend normally RELAYS the gateway's deny (which already
11
+ * carries the descriptor) rather than minting its own, so the field is absent on
12
+ * every verification/runtime failure. Additive; no behavior change.
5
13
  */
6
14
  export declare class FartherShoreError extends Error {
7
15
  readonly code: RuntimeErrorCode;
8
16
  readonly status: number;
9
- constructor(code: RuntimeErrorCode, message: string, status?: number);
17
+ /** Present only when this error is a self-minted plan-limit deny (rare; the
18
+ * backend usually relays the gateway's descriptor-bearing deny instead). */
19
+ readonly limitDescriptor?: LimitDescriptor;
20
+ constructor(code: RuntimeErrorCode, message: string, status?: number, limitDescriptor?: LimitDescriptor);
10
21
  }
11
22
  /**
12
23
  * Map a runtime error code to its fail-closed HTTP status. Oversized bodies are
@@ -41,6 +41,7 @@ export type FartherShoreInitOptions = {
41
41
  instanceId?: string;
42
42
  };
43
43
  export declare const SDK_VERSION: string;
44
+ export declare const CONTRACTS_FP: string;
44
45
  /**
45
46
  * The runtime instance. Lazily bootstraps; holds the JWKS client, nonce cache,
46
47
  * metering buffer, and shutdown hooks.
@@ -13,7 +13,7 @@ export { ShutdownManager, type ShutdownHook } from "./core/shutdown.js";
13
13
  export { CloudflaredSupervisor, nodeSpawn, REDACTED_TOKEN, type SpawnFn, type SpawnedTunnelProcess, type CloudflaredSupervisorOptions, type TunnelState, type TunnelStatus, } from "./core/tunnel.js";
14
14
  export type { FartherShoreTunnelOptions } from "./core/runtime.js";
15
15
  export { createExpressMiddleware, type ExpressMiddleware, type ExpressRequestLike, type ExpressResponseLike, type ExpressNext, type MiddlewareOptions, } from "./adapters/express.js";
16
- export { FS_RUNTIME_TOKEN_ENV, RUNTIME_TOKEN_PREFIXES, RUNTIME_TOKEN_CAPABILITIES, RUNTIME_HEADER_NAMES, RUNTIME_CLOCK_SKEW_SECONDS, RUNTIME_REPLAY_WINDOW_SECONDS, EMPTY_BODY_SHA256, STREAMING_EXEMPT_BODY_HASH, MAX_BODY_BYTES, type RuntimeErrorCode, type RuntimeTokenCapability, type CanonicalSigningInput, type RuntimeBootstrapResponse, type RuntimeMeteringEvent, type RuntimeHealthReport, type TransportMode, } from "./runtime-types.js";
16
+ export { FS_RUNTIME_TOKEN_ENV, RUNTIME_TOKEN_PREFIXES, RUNTIME_TOKEN_CAPABILITIES, RUNTIME_HEADER_NAMES, RUNTIME_CLOCK_SKEW_SECONDS, RUNTIME_REPLAY_WINDOW_SECONDS, EMPTY_BODY_SHA256, STREAMING_EXEMPT_BODY_HASH, MAX_BODY_BYTES, type RuntimeErrorCode, type RuntimeTokenCapability, type CanonicalSigningInput, type RuntimeBootstrapResponse, type RuntimeMeteringEvent, type RuntimeHealthReport, type TransportMode, RUNTIME_ERROR_CODE_TO_ERROR_CODE, runtimeErrorToErrorCode, type LimitDescriptor, type RuntimeMappedErrorCode, } from "./runtime-types.js";
17
17
  export { RUNTIME_ERROR_CODES } from "./generated/runtime-contract.js";
18
18
  export { hashBody, buildCanonicalSigningString, canonicalizeQuery, signCanonicalString, verifyCanonicalSignature, runtimeTokenKind, } from "./runtime-signing.js";
19
19
  export { createUsage, withUsage, MeteringError, METERING_PAYLOAD_HEADER, METERING_SIGNATURE_HEADER, METERING_TOKEN_HEADER, DEFAULT_TOKEN_ENV, type UsageMap, type UsageReporter, type MeteringOptions, } from "./response-metering.js";
@@ -1,4 +1,53 @@
1
+ import type { RuntimeErrorCode } from "./generated/runtime-contract.js";
1
2
  export type { RuntimeErrorCode } from "./generated/runtime-contract.js";
3
+ /**
4
+ * C-1 — the machine-readable limit descriptor on a limit-deny body. A backend
5
+ * that surfaces a plan-limit deny carries this so SDKs can render an upgrade
6
+ * affordance. Structurally identical to the contracts `LimitDescriptor`.
7
+ */
8
+ export interface LimitDescriptor {
9
+ /** Stable identifier for the limit hit — a `limitCode` VALUE
10
+ * (`quota` | `rate_limit` | `credit` | `resource:<name>`), NOT a wire code. */
11
+ limitCode: string;
12
+ /** Metered/resource dimension when known; null otherwise. */
13
+ dimension: string | null;
14
+ /** The cap the subscriber is at when known; null otherwise. */
15
+ currentCapacity: number | null;
16
+ }
17
+ /**
18
+ * C-1 (BE-1) — the RUNTIME field set of the SDK-local {@link LimitDescriptor}
19
+ * mirror. `satisfies Record<keyof LimitDescriptor, true>` makes the compiler
20
+ * reject this if it drifts from the local interface; the drift guard
21
+ * (`deny-taxonomy-drift.test.ts`) then asserts it deep-equals the canonical
22
+ * contracts `LIMIT_DESCRIPTOR_FIELDS` at RUNTIME — so a hand-copy that adds or
23
+ * drops a field fails a test that actually runs. (Contracts-free: this is a
24
+ * plain local constant, never the published-types path to contracts.) */
25
+ export declare const LIMIT_DESCRIPTOR_FIELDS: {
26
+ limitCode: true;
27
+ dimension: true;
28
+ currentCapacity: true;
29
+ };
30
+ /**
31
+ * C-2 — the canonical core `ErrorCode` VALUES this backend can map a
32
+ * `RuntimeErrorCode` onto (the codomain of {@link RUNTIME_ERROR_CODE_TO_ERROR_CODE}).
33
+ * The full core enum lives in the shared platform contracts; the SDK only needs
34
+ * the subset its bridge produces. Each is a verbatim core `ErrorCode` string —
35
+ * the drift guard asserts membership in the canonical enum.
36
+ */
37
+ export type RuntimeMappedErrorCode = "UNAUTHORIZED" | "SERVICE_UNAVAILABLE" | "VALIDATION_ERROR" | "INTERNAL_ERROR";
38
+ /**
39
+ * C-2 — map every canonical {@link RuntimeErrorCode} (wire snake_case value) to
40
+ * the core `ErrorCode` it belongs to. Total over `RuntimeErrorCode` (the
41
+ * `Record<RuntimeErrorCode, …>` type makes a missing key a compile error). A
42
+ * faithful copy of contracts' `RUNTIME_ERROR_CODE_TO_ERROR_CODE`.
43
+ */
44
+ export declare const RUNTIME_ERROR_CODE_TO_ERROR_CODE: Record<RuntimeErrorCode, RuntimeMappedErrorCode>;
45
+ /**
46
+ * C-2 — translate a runtime code into the canonical core `ErrorCode`. Returns
47
+ * `INTERNAL_ERROR` for an unrecognized value (defensive; the map is total over
48
+ * known codes). Mirrors contracts' `runtimeErrorToErrorCode`.
49
+ */
50
+ export declare function runtimeErrorToErrorCode(code: string): RuntimeMappedErrorCode;
2
51
  export declare const FS_RUNTIME_TOKEN_ENV: "FS_RUNTIME_TOKEN";
3
52
  export declare const RUNTIME_TOKEN_PREFIXES: {
4
53
  readonly live: "fsrt_live_";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@farthershore/backend",
3
- "version": "0.3.0",
3
+ "version": "0.8.0",
4
4
  "description": "Farther Shore backend SDK for builder upstreams: signed response usage, fail-closed gateway request verification, health, and lifecycle from FS_RUNTIME_TOKEN",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",