@gate-forge/witness 0.13.7 → 0.13.9

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.
@@ -154,9 +154,9 @@ import { readFileSync, renameSync, writeFileSync } from 'node:fs';
154
154
  import { join, resolve } from 'node:path';
155
155
  import { ATTESTATION_VERSION, attestationMac, behaviorActionDigestOf, DEFAULT_QUEUE_POLL_INTERVAL_MS, DEFAULT_QUEUE_TERMINAL_TIMEOUT_MS, BehaviorCatalogSchema, BEHAVIOR_CASE_KIND, enumerationDigestOf, interpretObservedPath, pathMatchesShape, recordIdOf, resolveHttpRoute, } from '@gate-forge/core';
156
156
  import { canonicalOf } from '../json.js';
157
- import { DEFAULT_REQUEST_TIMEOUT_MS, HTTP_OBSERVED_KIND, KNOWN_RECORD_KINDS, LOOPBACK_HOSTNAME, OBSERVED_KIND, OBSERVED_EXCHANGES_CAP, PERSISTENCE_KIND, RUN_HEADER, VERIFIER_HEADER, } from '../constants.js';
157
+ import { DEFAULT_REQUEST_TIMEOUT_MS, HTTP_OBSERVED_KIND, KNOWN_RECORD_KINDS, LOOPBACK_HOSTNAME, OBSERVED_EXCHANGES_CAP, OBSERVED_KIND, PERSISTENCE_KIND, RUN_HEADER, DIRECT_CHANNEL, DIRECT_EXCHANGES_CAP, VERIFIER_HEADER, } from '../constants.js';
158
158
  import { PageObserverRegistrationError, registerPageObserver, sweepPageVisits } from './page-observer-registration.js';
159
- import { loadAdapters, makeAdapterContext } from './adapter-registry.js';
159
+ import { AdapterRegistryError, loadAdapters, makeAdapterContext } from './adapter-registry.js';
160
160
  import { AttestationError, assertLoopback, envFingerprintMismatch, probeEnvFingerprint, } from './env-attestation.js';
161
161
  import { hostResolverRules, isLoopbackAddress, pinnedLoopbackIps, pinnedGet } from './loopback-pins.js';
162
162
  import { loadClassifications, toClassificationView } from './classifications.js';
@@ -581,6 +581,7 @@ async function startObservedProxy(state, sessionId, chaosSession) {
581
581
  // claims. With no declared mount path the URL is forwarded and
582
582
  // recorded byte-identical to today.
583
583
  const forwardUrl = stripMountPath(req.url ?? '/', state.options.mountPath);
584
+ const testCodeInitiated = req.headers['x-gateforge-initiator'] === 'test-code';
584
585
  // In-flight accounting (plan §11.4): a proxy exchange that starts
585
586
  // before `/run-context` binds must refuse the bind — otherwise
586
587
  // traffic from an older invocation could be signed under the new
@@ -684,6 +685,7 @@ async function startObservedProxy(state, sessionId, chaosSession) {
684
685
  requestContentType: contentTypeOf(req.headers['content-type']),
685
686
  sessionId,
686
687
  tick: (state.tick += 1),
688
+ ...(testCodeInitiated ? { initiator: 'test-code' } : {}),
687
689
  ...(collectionShape !== null
688
690
  ? {
689
691
  collectionRows: parseCollectionRows(Buffer.concat(collectionSnapshot), responseContentType, totalBytes > COLLECTION_BODY_MAX_BYTES, totalBytes, collectionShape),
@@ -709,13 +711,15 @@ async function startObservedProxy(state, sessionId, chaosSession) {
709
711
  res.writeHead(status, upstream.headers);
710
712
  upstream.pipe(res);
711
713
  };
714
+ const forwardHeaders = { ...req.headers, host: proxyTargetUrl.host };
715
+ delete forwardHeaders['x-gateforge-initiator'];
712
716
  const forward = request({
713
717
  protocol: proxyTargetUrl.protocol,
714
718
  hostname: proxyTargetUrl.hostname,
715
719
  port: proxyTargetUrl.port,
716
720
  method: req.method,
717
721
  path: forwardUrl,
718
- headers: { ...req.headers, host: proxyTargetUrl.host },
722
+ headers: forwardHeaders,
719
723
  agent: false,
720
724
  }, (upstream) => {
721
725
  // Chaos holds a response back by PAUSING the upstream stream:
@@ -943,8 +947,27 @@ export async function startWitness(options) {
943
947
  const classificationsPath = options.classificationsPath === null || options.classificationsPath === undefined
944
948
  ? null
945
949
  : resolve(cwd, options.classificationsPath);
946
- const adapters = adaptersDir === null ? new Map() : await loadAdapters(adaptersDir);
947
950
  const classifications = loadClassifications(classificationsPath);
951
+ const adapterDeleteStates = new Map();
952
+ for (const classification of Object.values(classifications)) {
953
+ if (classification.evidenceAdapter === undefined)
954
+ continue;
955
+ const state = adapterDeleteStates.get(classification.evidenceAdapter) ?? { disabled: false, enabled: false };
956
+ if (classification.lifecycle.delete)
957
+ state.enabled = true;
958
+ else
959
+ state.disabled = true;
960
+ adapterDeleteStates.set(classification.evidenceAdapter, state);
961
+ }
962
+ for (const [adapter, state] of adapterDeleteStates) {
963
+ if (state.disabled && state.enabled) {
964
+ throw new AdapterRegistryError(`adapter '${adapter}' is shared by resources with conflicting delete lifecycle rules`);
965
+ }
966
+ }
967
+ const deleteDisabledAdapters = new Set([...adapterDeleteStates].filter(([, state]) => state.disabled).map(([adapter]) => adapter));
968
+ const adapters = adaptersDir === null
969
+ ? new Map()
970
+ : await loadAdapters(adaptersDir, { deleteDisabledAdapters });
948
971
  const targetBaseUrl = options.targetBaseUrl ?? null;
949
972
  // The mount prefix declares how the browser-facing deployment mounts
950
973
  // the backend for the OBSERVATION PROXY; it is meaningless without one.
@@ -1802,6 +1825,10 @@ async function handleRequest(state, req, res) {
1802
1825
  await handleSessionPageOrigins(state, res, (await readBody(req)));
1803
1826
  return;
1804
1827
  }
1828
+ if (req.method === 'POST' && path === '/sessions/direct-exchanges') {
1829
+ await handleSessionDirectExchanges(state, res, (await readBody(req)));
1830
+ return;
1831
+ }
1805
1832
  if (req.method === 'POST' && path === '/sessions/page-observer') {
1806
1833
  const body = (await readBody(req));
1807
1834
  try {
@@ -2965,6 +2992,8 @@ async function handleSessionOpen(state, res, body) {
2965
2992
  proxyUrl: null,
2966
2993
  proxyServer: null,
2967
2994
  claims,
2995
+ directExchanges: [],
2996
+ directRecordsIssued: new Set(),
2968
2997
  // The registered expected-set identity this session was minted for
2969
2998
  // (enforcement-review fix 2b); null when no expected set is bound.
2970
2999
  registered: registered !== null
@@ -3193,6 +3222,38 @@ async function handleSessionPageOrigins(state, res, body) {
3193
3222
  });
3194
3223
  sendJson(res, 200, { recorded: true });
3195
3224
  }
3225
+ /** Stores bounded, deduplicated direct API exchanges on their session. */
3226
+ async function handleSessionDirectExchanges(state, res, body) {
3227
+ if (!isPlainObject(body))
3228
+ throw new HttpError(400, 'direct exchange report body must be an object');
3229
+ const session = requireOpenSession(state, body);
3230
+ const reported = body['exchanges'];
3231
+ if (!Array.isArray(reported) || reported.length === 0) {
3232
+ throw new HttpError(400, 'direct exchange report requires at least one exchange');
3233
+ }
3234
+ const exchanges = reported.map((item) => {
3235
+ if (!isPlainObject(item) ||
3236
+ typeof item['method'] !== 'string' ||
3237
+ !/^[A-Z]+$/.test(item['method']) ||
3238
+ typeof item['url'] !== 'string' ||
3239
+ item['url'].length === 0 ||
3240
+ typeof item['status'] !== 'number' ||
3241
+ !Number.isInteger(item['status']) ||
3242
+ item['status'] < 100 ||
3243
+ item['status'] > 599) {
3244
+ throw new HttpError(400, 'each direct exchange must have an uppercase method, URL, and HTTP status');
3245
+ }
3246
+ return { method: item['method'], url: item['url'], status: item['status'] };
3247
+ });
3248
+ for (const exchange of exchanges) {
3249
+ if (session.directExchanges.some((prior) => prior.method === exchange.method && prior.url === exchange.url && prior.status === exchange.status))
3250
+ continue;
3251
+ if (session.directExchanges.length >= DIRECT_EXCHANGES_CAP)
3252
+ break;
3253
+ session.directExchanges.push(exchange);
3254
+ }
3255
+ sendJson(res, 200, { recorded: true, kept: session.directExchanges.length });
3256
+ }
3196
3257
  /**
3197
3258
  * One reported origin, parsed and reduced to its origin form. A value
3198
3259
  * that is not an absolute http(s) URL is refused rather than repaired:
@@ -4429,6 +4490,17 @@ async function handleObserveFinalize(state, res, verifier, body) {
4429
4490
  // transport record carries. Persistence-vs-persistence consumption is
4430
4491
  // untouched: it still matches against the LIVE log, so one exchange
4431
4492
  // can never credit two persistence claims.
4493
+ if (session.directExchanges.length > 0) {
4494
+ for (const claimId of session.claims) {
4495
+ if (session.directRecordsIssued.has(claimId))
4496
+ continue;
4497
+ issueRecord(state, claimId, HTTP_OBSERVED_KIND, session.testId, {
4498
+ channel: DIRECT_CHANNEL,
4499
+ exchanges: session.directExchanges.map((exchange) => ({ ...exchange })),
4500
+ }, 'engine-observed');
4501
+ session.directRecordsIssued.add(claimId);
4502
+ }
4503
+ }
4432
4504
  const transport = transportSnapshot(state, session);
4433
4505
  const claims = session.claims.filter((claim) => state.observeDeclarations?.has(claim));
4434
4506
  for (const claimId of claims) {
@@ -4481,7 +4553,7 @@ function transportSnapshot(state, session) {
4481
4553
  for (const exchange of state.observed) {
4482
4554
  if (exchange.sessionId !== session.sessionId || exchange.seq <= watermark)
4483
4555
  continue;
4484
- const key = `${exchange.method} ${exchange.path} ${String(exchange.status)}`;
4556
+ const key = `${exchange.method} ${exchange.path} ${String(exchange.status)} ${exchange.initiator ?? 'page'}`;
4485
4557
  if (key in seen)
4486
4558
  continue;
4487
4559
  seen[key] = true;
@@ -4489,7 +4561,12 @@ function transportSnapshot(state, session) {
4489
4561
  truncated = true;
4490
4562
  continue;
4491
4563
  }
4492
- exchanges.push({ method: exchange.method, url: exchange.path, status: exchange.status });
4564
+ exchanges.push({
4565
+ method: exchange.method,
4566
+ url: exchange.path,
4567
+ status: exchange.status,
4568
+ ...(exchange.initiator === 'test-code' ? { initiator: exchange.initiator } : {}),
4569
+ });
4493
4570
  }
4494
4571
  return { exchanges, truncated };
4495
4572
  }
@@ -4543,6 +4620,8 @@ async function finalizeObserveClaim(state, session, claimId, transport) {
4543
4620
  for (const exchange of state.observed) {
4544
4621
  if (exchange.sessionId !== session.sessionId || exchange.seq <= watermark)
4545
4622
  continue;
4623
+ if (exchange.initiator === 'test-code')
4624
+ continue;
4546
4625
  if (exchange.method !== binding.method)
4547
4626
  continue;
4548
4627
  if (exchange.status < 200 || exchange.status > 299)