@gate-forge/witness 0.14.0 → 0.15.1
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/adapter/contract-suite.d.ts.map +1 -1
- package/dist/adapter/contract-suite.js +2 -8
- package/dist/adapter/contract-suite.js.map +1 -1
- package/dist/client/witness-client.d.ts +1 -6
- package/dist/client/witness-client.d.ts.map +1 -1
- package/dist/client/witness-client.js +0 -7
- package/dist/client/witness-client.js.map +1 -1
- package/dist/constants.d.ts +14 -12
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +14 -12
- package/dist/constants.js.map +1 -1
- package/dist/witness/bin.d.ts.map +1 -1
- package/dist/witness/bin.js +48 -1
- package/dist/witness/bin.js.map +1 -1
- package/dist/witness/server.d.ts.map +1 -1
- package/dist/witness/server.js +257 -123
- package/dist/witness/server.js.map +1 -1
- package/dist/witness/types.d.ts +42 -36
- package/dist/witness/types.d.ts.map +1 -1
- package/package.json +3 -3
package/dist/witness/server.js
CHANGED
|
@@ -152,9 +152,9 @@ import { createHash, randomUUID } from 'node:crypto';
|
|
|
152
152
|
import { lookup } from 'node:dns/promises';
|
|
153
153
|
import { readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
154
154
|
import { join, resolve } from 'node:path';
|
|
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';
|
|
155
|
+
import { ATTESTATION_VERSION, attestationMac, behaviorActionDigestOf, DEFAULT_QUEUE_POLL_INTERVAL_MS, DEFAULT_QUEUE_TERMINAL_TIMEOUT_MS, BehaviorCatalogSchema, BEHAVIOR_CASE_KIND, enumerationDigestOf, httpExchangeKind, interpretObservedPath, pathMatchesShape, recordIdOf, resolveHttpRoute, } from '@gate-forge/core';
|
|
156
156
|
import { canonicalOf } from '../json.js';
|
|
157
|
-
import { DEFAULT_REQUEST_TIMEOUT_MS, HTTP_EXCHANGES_KIND, HTTP_OBSERVED_KIND, HTTP_OPENAPI_KIND, KNOWN_RECORD_KINDS, LOOPBACK_HOSTNAME, OBSERVED_EXCHANGES_CAP, OBSERVED_KIND, PERSISTENCE_KIND, RUN_HEADER,
|
|
157
|
+
import { DEFAULT_REQUEST_TIMEOUT_MS, HTTP_EXCHANGES_KIND, HTTP_OBSERVED_KIND, HTTP_OPENAPI_KIND, KNOWN_RECORD_KINDS, LOOPBACK_HOSTNAME, OBSERVED_EXCHANGES_CAP, OBSERVED_KIND, PERSISTENCE_KIND, RUN_HEADER, VERIFIER_HEADER, } from '../constants.js';
|
|
158
158
|
import { PageObserverRegistrationError, registerPageObserver, sweepPageVisits } from './page-observer-registration.js';
|
|
159
159
|
import { AdapterRegistryError, loadAdapters, makeAdapterContext } from './adapter-registry.js';
|
|
160
160
|
import { AttestationError, assertLoopback, envFingerprintMismatch, probeEnvFingerprint, } from './env-attestation.js';
|
|
@@ -172,7 +172,8 @@ import { BEHAVIOR_BODY_LIMIT_BYTES, BehaviorDriverError, driveBehaviorRequest }
|
|
|
172
172
|
import { OBSERVE_CHANNEL, OBSERVED_E2E_TEST_KIND, SERVER_CHANNEL, SERVER_E2E_TEST_KIND } from '../constants.js';
|
|
173
173
|
import { QueueObserverError } from '../queue/observer.js';
|
|
174
174
|
import { driveTaskDelivery, TaskDriverError } from './task.js';
|
|
175
|
-
|
|
175
|
+
/** Supervisor JSON bodies (expected-set, behavior catalog, run context). */
|
|
176
|
+
const MAX_BODY_BYTES = 8 * 1024 * 1024;
|
|
176
177
|
const OBLIGATION_ID_PATTERN = /^[^:]+:.+$/;
|
|
177
178
|
/**
|
|
178
179
|
* Bounded response snapshot the observation proxy keeps per forwarded
|
|
@@ -507,19 +508,21 @@ async function closeProxyListeners(servers) {
|
|
|
507
508
|
})));
|
|
508
509
|
}
|
|
509
510
|
/**
|
|
510
|
-
* Starts one loopback reverse proxy forwarding to
|
|
511
|
-
*
|
|
512
|
-
*
|
|
513
|
-
*
|
|
514
|
-
*
|
|
511
|
+
* Starts one loopback reverse proxy forwarding to ONE attested app origin.
|
|
512
|
+
* `sessionId` names the session the port belongs to (null = the shared
|
|
513
|
+
* unattributed proxy): every exchange completing on this port is recorded
|
|
514
|
+
* as an engine observation stamped with that session id and the
|
|
515
|
+
* witness-monotonic completion tick.
|
|
515
516
|
*
|
|
516
|
-
* The proxy listens on EVERY loopback address
|
|
517
|
-
* resolved to, all on ONE port: a browser tries every resolved
|
|
518
|
-
*
|
|
519
|
-
*
|
|
517
|
+
* The proxy listens on EVERY loopback address that origin's hostname
|
|
518
|
+
* resolved to, all on ONE port: a browser tries every resolved address,
|
|
519
|
+
* but a Node-only client (Playwright's APIRequestContext) connects to the
|
|
520
|
+
* single address its resolver picks. A session with several declared app
|
|
521
|
+
* origins gets one of these per origin, all attributed to the SAME session.
|
|
520
522
|
*
|
|
521
523
|
* Args:
|
|
522
524
|
* state: running witness state.
|
|
525
|
+
* origin: the attested app origin this proxy fronts.
|
|
523
526
|
* sessionId: owning session id, or null for the shared proxy.
|
|
524
527
|
*
|
|
525
528
|
* Returns:
|
|
@@ -528,8 +531,8 @@ async function closeProxyListeners(servers) {
|
|
|
528
531
|
* Throws:
|
|
529
532
|
* Error: when the proxy fails to bind.
|
|
530
533
|
*/
|
|
531
|
-
async function startObservedProxy(state, sessionId, chaosSession) {
|
|
532
|
-
const proxyTargetUrl = new URL(
|
|
534
|
+
async function startObservedProxy(state, origin, sessionId, chaosSession) {
|
|
535
|
+
const proxyTargetUrl = new URL(origin.baseUrl);
|
|
533
536
|
// One scheduler per proxy port: a session's `k` and its recorded
|
|
534
537
|
// schedule are its own, so two tests in one run can never shift each
|
|
535
538
|
// other's timing. `chaosSession` is the supervisor-issued test id
|
|
@@ -567,7 +570,29 @@ async function startObservedProxy(state, sessionId, chaosSession) {
|
|
|
567
570
|
}
|
|
568
571
|
if (collectionRoutes.size === 0)
|
|
569
572
|
return null;
|
|
570
|
-
|
|
573
|
+
let matched = null;
|
|
574
|
+
for (const [route, candidate] of collectionRoutes) {
|
|
575
|
+
const separator = route.indexOf(' ');
|
|
576
|
+
if (route.slice(0, separator) !== method)
|
|
577
|
+
continue;
|
|
578
|
+
if (matchObserveTemplate(path, route.slice(separator + 1)) === null)
|
|
579
|
+
continue;
|
|
580
|
+
if (matched === null) {
|
|
581
|
+
matched = candidate;
|
|
582
|
+
continue;
|
|
583
|
+
}
|
|
584
|
+
const agrees = matched.shape !== null &&
|
|
585
|
+
candidate.shape !== null &&
|
|
586
|
+
(matched.shape.rowsKey ?? null) === (candidate.shape.rowsKey ?? null) &&
|
|
587
|
+
matched.shape.idKey === candidate.shape.idKey;
|
|
588
|
+
if (!agrees) {
|
|
589
|
+
return {
|
|
590
|
+
shape: null,
|
|
591
|
+
declarations: [...matched.declarations, ...candidate.declarations],
|
|
592
|
+
};
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
return matched;
|
|
571
596
|
};
|
|
572
597
|
// One request handler shared by EVERY listener of this
|
|
573
598
|
// proxy: each loopback address gets its own Server
|
|
@@ -795,9 +820,8 @@ async function startObservedProxy(state, sessionId, chaosSession) {
|
|
|
795
820
|
forward.end();
|
|
796
821
|
});
|
|
797
822
|
};
|
|
798
|
-
// ONE port for every loopback address
|
|
823
|
+
// ONE port for every loopback address THIS ORIGIN's hostname
|
|
799
824
|
// resolves to: the first listener asks the OS for a free
|
|
800
|
-
// port and the rest share it. A browser tries every
|
|
801
825
|
// resolved address, but a Node-only client (Playwright's
|
|
802
826
|
// APIRequestContext) connects to the single address its
|
|
803
827
|
// resolver picks, so every loopback address must answer
|
|
@@ -809,7 +833,7 @@ async function startObservedProxy(state, sessionId, chaosSession) {
|
|
|
809
833
|
const servers = [];
|
|
810
834
|
let port = 0;
|
|
811
835
|
try {
|
|
812
|
-
for (const bindHost of
|
|
836
|
+
for (const bindHost of origin.bindHosts) {
|
|
813
837
|
const server = createServer(proxyHandler);
|
|
814
838
|
await new Promise((resolveListen, rejectListen) => {
|
|
815
839
|
server.once('error', rejectListen);
|
|
@@ -831,7 +855,7 @@ async function startObservedProxy(state, sessionId, chaosSession) {
|
|
|
831
855
|
await closeProxyListeners(servers);
|
|
832
856
|
if (attempt === PROXY_BIND_ATTEMPTS ||
|
|
833
857
|
error?.code !== 'EADDRINUSE') {
|
|
834
|
-
throw new WitnessStartupError(`observation proxy failed to bind '${
|
|
858
|
+
throw new WitnessStartupError(`observation proxy failed to bind '${origin.host}': ${error instanceof Error ? error.message : String(error)}`);
|
|
835
859
|
}
|
|
836
860
|
// EADDRINUSE on a later address: another process took
|
|
837
861
|
// the port between assignment and this bind. Retry on
|
|
@@ -839,21 +863,28 @@ async function startObservedProxy(state, sessionId, chaosSession) {
|
|
|
839
863
|
}
|
|
840
864
|
}
|
|
841
865
|
// Unreachable: every attempt returns or throws above.
|
|
842
|
-
throw new WitnessStartupError(`observation proxy failed to bind '${
|
|
866
|
+
throw new WitnessStartupError(`observation proxy failed to bind '${origin.host}'`);
|
|
843
867
|
}
|
|
844
868
|
/**
|
|
845
|
-
* The base URL of a started observation proxy: the HOSTNAME
|
|
869
|
+
* The base URL of a started observation proxy: the ORIGIN's HOSTNAME
|
|
846
870
|
* (never an IP, so Host headers stay exactly as the suite
|
|
847
871
|
* addresses them) plus the one port every listener shares.
|
|
848
872
|
*/
|
|
849
|
-
function proxyUrlOf(
|
|
850
|
-
return `http://${formatHost(
|
|
873
|
+
function proxyUrlOf(origin, proxy) {
|
|
874
|
+
return `http://${formatHost(origin.host)}:${proxy.port}`;
|
|
851
875
|
}
|
|
852
876
|
/**
|
|
853
|
-
* Starts the DEDICATED
|
|
854
|
-
*
|
|
855
|
-
* the
|
|
856
|
-
*
|
|
877
|
+
* Starts the session's DEDICATED observation-proxy ports (plan Phase 1),
|
|
878
|
+
* one per attested app origin, and stores them on the session. Only called
|
|
879
|
+
* when the run wires an observation proxy; the worker's browser uses these
|
|
880
|
+
* origins for the whole test, so all of its traffic — on the primary app
|
|
881
|
+
* AND on every declared additional origin, absolute paths included — is
|
|
882
|
+
* attributed to this one session.
|
|
883
|
+
*
|
|
884
|
+
* A declared origin that fails to bind closes the ports already opened for
|
|
885
|
+
* this session first: a half-attributed session (one origin witnessed, one
|
|
886
|
+
* origin silently absent) is exactly the state this feature exists to
|
|
887
|
+
* remove, so the session opens with none or with all of them.
|
|
857
888
|
*
|
|
858
889
|
* Args:
|
|
859
890
|
* state: running witness state.
|
|
@@ -865,17 +896,44 @@ async function startSessionProxy(state, session) {
|
|
|
865
896
|
session.proxyUrl = null;
|
|
866
897
|
return;
|
|
867
898
|
}
|
|
868
|
-
const
|
|
869
|
-
|
|
870
|
-
|
|
899
|
+
const [primary, ...additional] = state.proxyOrigins;
|
|
900
|
+
if (primary === undefined) {
|
|
901
|
+
session.proxyUrl = null;
|
|
902
|
+
return;
|
|
903
|
+
}
|
|
904
|
+
// The primary proxy and every additional origin's proxy are retained on
|
|
905
|
+
// the session so sealing closes every listener, not only the primary.
|
|
906
|
+
try {
|
|
907
|
+
const primaryProxy = await startObservedProxy(state, primary, session.sessionId, session.testId);
|
|
908
|
+
session.proxyServer = primaryProxy;
|
|
909
|
+
session.proxyUrl = proxyUrlOf(primary, primaryProxy);
|
|
910
|
+
for (const origin of additional) {
|
|
911
|
+
const proxy = await startObservedProxy(state, origin, session.sessionId, session.testId);
|
|
912
|
+
session.additionalProxyServers.push(proxy);
|
|
913
|
+
session.additionalProxyUrls.push({ appOrigin: origin.appOrigin, proxyUrl: proxyUrlOf(origin, proxy) });
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
catch (error) {
|
|
917
|
+
// Half-attributed is worse than unattributed: close every listener
|
|
918
|
+
// this session opened (its own primary included) and open no session
|
|
919
|
+
// at all, so the caller sees the bind failure rather than a session
|
|
920
|
+
// whose declared origins are only partly witnessed.
|
|
921
|
+
await stopSessionProxy(session);
|
|
922
|
+
session.proxyUrl = null;
|
|
923
|
+
throw error;
|
|
924
|
+
}
|
|
871
925
|
}
|
|
872
926
|
/** Closes one session's dedicated proxy listeners (sealed = channel gone). */
|
|
873
927
|
async function stopSessionProxy(session) {
|
|
874
|
-
const
|
|
928
|
+
const servers = [
|
|
929
|
+
...(session.proxyServer?.servers ?? []),
|
|
930
|
+
...session.additionalProxyServers.flatMap((proxy) => proxy.servers),
|
|
931
|
+
];
|
|
875
932
|
session.proxyServer = null;
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
933
|
+
session.additionalProxyServers.length = 0;
|
|
934
|
+
session.additionalProxyUrls.length = 0;
|
|
935
|
+
if (servers.length > 0)
|
|
936
|
+
await closeProxyListeners(servers);
|
|
879
937
|
}
|
|
880
938
|
/** Detaches the independent browser observer when its test session ends. */
|
|
881
939
|
async function stopPageObserver(state, sessionId) {
|
|
@@ -894,8 +952,8 @@ function sealPageObservationRecords(state, sessionId, outcome) {
|
|
|
894
952
|
}
|
|
895
953
|
/**
|
|
896
954
|
* Issues the session's ONE claim-free `http.exchanges` record (0.14
|
|
897
|
-
* WP2): the
|
|
898
|
-
*
|
|
955
|
+
* WP2): the transport snapshot including assets (watermark, dedup, cap,
|
|
956
|
+
* `truncated`), bound to the
|
|
899
957
|
* SESSION identity instead of an obligation so no claim can ever select
|
|
900
958
|
* it. Only a session that sealed as PASSED retains its exchanges — the
|
|
901
959
|
* same non-passing rule {@link sealPageObservationRecords} applies to
|
|
@@ -937,8 +995,8 @@ function readBody(req) {
|
|
|
937
995
|
req.on('data', (chunk) => {
|
|
938
996
|
raw += chunk;
|
|
939
997
|
if (raw.length > MAX_BODY_BYTES) {
|
|
940
|
-
|
|
941
|
-
|
|
998
|
+
req.pause();
|
|
999
|
+
rejectBody(new HttpError(413, 'request body too large'));
|
|
942
1000
|
}
|
|
943
1001
|
});
|
|
944
1002
|
req.on('end', () => {
|
|
@@ -984,6 +1042,35 @@ async function enginePageFor(state, sessionId) {
|
|
|
984
1042
|
}
|
|
985
1043
|
return manager.pageFor(sessionId);
|
|
986
1044
|
}
|
|
1045
|
+
/**
|
|
1046
|
+
* The loopback addresses one app origin's observation proxy may bind.
|
|
1047
|
+
*
|
|
1048
|
+
* An app hostname can resolve to SEVERAL loopback addresses (`localhost`
|
|
1049
|
+
* commonly answers ::1 and the IPv4 loopback): a browser tries every one,
|
|
1050
|
+
* but a Node-only client connects to the single address its resolver picks.
|
|
1051
|
+
* Fail closed on any non-loopback answer, and serve every loopback address.
|
|
1052
|
+
*
|
|
1053
|
+
* Args:
|
|
1054
|
+
* baseUrl: the origin's base URL (attested here, never forwarded off loopback).
|
|
1055
|
+
* hostname: its logical hostname, with any IPv6 brackets stripped.
|
|
1056
|
+
* role: what is being attested, for the refusal message.
|
|
1057
|
+
*
|
|
1058
|
+
* Returns:
|
|
1059
|
+
* string[]: the resolved loopback addresses, deduplicated.
|
|
1060
|
+
*
|
|
1061
|
+
* Raises:
|
|
1062
|
+
* AttestationError: when the origin is not loopback or resolves to any
|
|
1063
|
+
* non-loopback address.
|
|
1064
|
+
*/
|
|
1065
|
+
async function resolveProxyBindHosts(baseUrl, hostname, role) {
|
|
1066
|
+
await assertLoopback(baseUrl, role);
|
|
1067
|
+
const resolved = await lookup(hostname, { all: true });
|
|
1068
|
+
const addresses = resolved.map((record) => record.address);
|
|
1069
|
+
if (addresses.length === 0 || !addresses.every(isLoopbackAddress)) {
|
|
1070
|
+
throw new AttestationError(`${role} hostname '${hostname}' resolved to a non-loopback bind address`);
|
|
1071
|
+
}
|
|
1072
|
+
return [...new Set(addresses)];
|
|
1073
|
+
}
|
|
987
1074
|
/**
|
|
988
1075
|
* Starts the witness service.
|
|
989
1076
|
*
|
|
@@ -1059,25 +1146,39 @@ export async function startWitness(options) {
|
|
|
1059
1146
|
}
|
|
1060
1147
|
}
|
|
1061
1148
|
// Keep the browser-facing logical hostname and the control host separate.
|
|
1062
|
-
// Resolve the proxy bind addresses once, and never bind a
|
|
1149
|
+
// Resolve the proxy bind addresses once per app origin, and never bind a
|
|
1150
|
+
// non-loopback result.
|
|
1063
1151
|
const proxyHostname = options.proxyTarget ? new URL(options.proxyTarget).hostname : null;
|
|
1064
1152
|
const proxyHost = proxyHostname === null
|
|
1065
1153
|
? options.host ?? LOOPBACK_HOSTNAME
|
|
1066
1154
|
: proxyHostname.replace(/^\[|\]$/g, '');
|
|
1067
1155
|
let proxyBindHosts = proxyHostname === null ? [proxyHost] : [];
|
|
1068
1156
|
if (proxyHostname !== null) {
|
|
1069
|
-
await
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1157
|
+
proxyBindHosts = await resolveProxyBindHosts(options.proxyTarget, proxyHost, 'observation proxy target');
|
|
1158
|
+
}
|
|
1159
|
+
// Declared ADDITIONAL app origins (0.15.0, `.gateforge.yml`
|
|
1160
|
+
// `additionalAppOrigins`, resolved by the CLI): each is attested with the
|
|
1161
|
+
// SAME loopback discipline as the primary target, because it is a second
|
|
1162
|
+
// upstream the witness will forward browser traffic to. A non-loopback or
|
|
1163
|
+
// mixed-resolution origin refuses startup HERE, before any request
|
|
1164
|
+
// surface exists for it.
|
|
1165
|
+
const proxyOrigins = [];
|
|
1166
|
+
if (proxyHostname !== null) {
|
|
1167
|
+
proxyOrigins.push({
|
|
1168
|
+
appOrigin: new URL(options.proxyTarget).origin,
|
|
1169
|
+
baseUrl: options.proxyTarget,
|
|
1170
|
+
host: proxyHost,
|
|
1171
|
+
bindHosts: proxyBindHosts,
|
|
1172
|
+
});
|
|
1173
|
+
}
|
|
1174
|
+
for (const declared of options.additionalAppOrigins ?? []) {
|
|
1175
|
+
const hostname = new URL(declared).hostname.replace(/^\[|\]$/g, '');
|
|
1176
|
+
proxyOrigins.push({
|
|
1177
|
+
appOrigin: new URL(declared).origin,
|
|
1178
|
+
baseUrl: declared,
|
|
1179
|
+
host: hostname,
|
|
1180
|
+
bindHosts: await resolveProxyBindHosts(declared, hostname, 'declared additional app origin'),
|
|
1181
|
+
});
|
|
1081
1182
|
}
|
|
1082
1183
|
const state = {
|
|
1083
1184
|
options: {
|
|
@@ -1094,6 +1195,7 @@ export async function startWitness(options) {
|
|
|
1094
1195
|
adapters,
|
|
1095
1196
|
proxyHost,
|
|
1096
1197
|
proxyBindHosts,
|
|
1198
|
+
proxyOrigins,
|
|
1097
1199
|
classifications,
|
|
1098
1200
|
ledger: new Map(),
|
|
1099
1201
|
preObservations: new Map(),
|
|
@@ -1174,8 +1276,12 @@ export async function startWitness(options) {
|
|
|
1174
1276
|
// by URL rewriting.
|
|
1175
1277
|
let proxyUrl = null;
|
|
1176
1278
|
if (typeof state.options.proxyTarget === 'string' && state.options.proxyTarget.length > 0) {
|
|
1177
|
-
|
|
1178
|
-
|
|
1279
|
+
const sharedOrigin = state.proxyOrigins[0];
|
|
1280
|
+
if (sharedOrigin === undefined) {
|
|
1281
|
+
throw new WitnessStartupError('observation proxy target resolved to no proxy origin');
|
|
1282
|
+
}
|
|
1283
|
+
state.proxyServer = await startObservedProxy(state, sharedOrigin, null, SHARED_PROXY_CHAOS_SESSION);
|
|
1284
|
+
proxyUrl = proxyUrlOf(sharedOrigin, state.proxyServer);
|
|
1179
1285
|
}
|
|
1180
1286
|
// DNS binding (loopback-pins): the startup asserts above pinned every
|
|
1181
1287
|
// operator-provided hostname to its approved loopback IPs. Hand the
|
|
@@ -1915,10 +2021,6 @@ async function handleRequest(state, req, res) {
|
|
|
1915
2021
|
await handleSessionPageOrigins(state, res, (await readBody(req)));
|
|
1916
2022
|
return;
|
|
1917
2023
|
}
|
|
1918
|
-
if (req.method === 'POST' && path === '/sessions/direct-exchanges') {
|
|
1919
|
-
await handleSessionDirectExchanges(state, res, (await readBody(req)));
|
|
1920
|
-
return;
|
|
1921
|
-
}
|
|
1922
2024
|
if (req.method === 'POST' && path === '/sessions/page-observer') {
|
|
1923
2025
|
const body = (await readBody(req));
|
|
1924
2026
|
try {
|
|
@@ -3078,12 +3180,13 @@ async function handleSessionOpen(state, res, body) {
|
|
|
3078
3180
|
sealedTick: null,
|
|
3079
3181
|
outcome: null,
|
|
3080
3182
|
intervals: new Map(),
|
|
3081
|
-
// Filled below: the session's DEDICATED observation-proxy
|
|
3183
|
+
// Filled below: the session's DEDICATED observation-proxy ports, one
|
|
3184
|
+
// per attested app origin this run declares.
|
|
3082
3185
|
proxyUrl: null,
|
|
3186
|
+
additionalProxyUrls: [],
|
|
3187
|
+
additionalProxyServers: [],
|
|
3083
3188
|
proxyServer: null,
|
|
3084
3189
|
claims,
|
|
3085
|
-
directExchanges: [],
|
|
3086
|
-
directRecordsIssued: new Set(),
|
|
3087
3190
|
// The registered expected-set identity this session was minted for
|
|
3088
3191
|
// (enforcement-review fix 2b); null when no expected set is bound.
|
|
3089
3192
|
registered: registered !== null
|
|
@@ -3135,6 +3238,7 @@ function sessionView(state, session) {
|
|
|
3135
3238
|
workerIndex: session.workerIndex,
|
|
3136
3239
|
openedTick: session.openedTick,
|
|
3137
3240
|
proxyUrl: session.proxyUrl,
|
|
3241
|
+
additionalProxyUrls: session.additionalProxyUrls.map((entry) => ({ ...entry })),
|
|
3138
3242
|
claims: [...session.claims],
|
|
3139
3243
|
};
|
|
3140
3244
|
}
|
|
@@ -3314,38 +3418,6 @@ async function handleSessionPageOrigins(state, res, body) {
|
|
|
3314
3418
|
});
|
|
3315
3419
|
sendJson(res, 200, { recorded: true });
|
|
3316
3420
|
}
|
|
3317
|
-
/** Stores bounded, deduplicated direct API exchanges on their session. */
|
|
3318
|
-
async function handleSessionDirectExchanges(state, res, body) {
|
|
3319
|
-
if (!isPlainObject(body))
|
|
3320
|
-
throw new HttpError(400, 'direct exchange report body must be an object');
|
|
3321
|
-
const session = requireOpenSession(state, body);
|
|
3322
|
-
const reported = body['exchanges'];
|
|
3323
|
-
if (!Array.isArray(reported) || reported.length === 0) {
|
|
3324
|
-
throw new HttpError(400, 'direct exchange report requires at least one exchange');
|
|
3325
|
-
}
|
|
3326
|
-
const exchanges = reported.map((item) => {
|
|
3327
|
-
if (!isPlainObject(item) ||
|
|
3328
|
-
typeof item['method'] !== 'string' ||
|
|
3329
|
-
!/^[A-Z]+$/.test(item['method']) ||
|
|
3330
|
-
typeof item['url'] !== 'string' ||
|
|
3331
|
-
item['url'].length === 0 ||
|
|
3332
|
-
typeof item['status'] !== 'number' ||
|
|
3333
|
-
!Number.isInteger(item['status']) ||
|
|
3334
|
-
item['status'] < 100 ||
|
|
3335
|
-
item['status'] > 599) {
|
|
3336
|
-
throw new HttpError(400, 'each direct exchange must have an uppercase method, URL, and HTTP status');
|
|
3337
|
-
}
|
|
3338
|
-
return { method: item['method'], url: item['url'], status: item['status'] };
|
|
3339
|
-
});
|
|
3340
|
-
for (const exchange of exchanges) {
|
|
3341
|
-
if (session.directExchanges.some((prior) => prior.method === exchange.method && prior.url === exchange.url && prior.status === exchange.status))
|
|
3342
|
-
continue;
|
|
3343
|
-
if (session.directExchanges.length >= DIRECT_EXCHANGES_CAP)
|
|
3344
|
-
break;
|
|
3345
|
-
session.directExchanges.push(exchange);
|
|
3346
|
-
}
|
|
3347
|
-
sendJson(res, 200, { recorded: true, kept: session.directExchanges.length });
|
|
3348
|
-
}
|
|
3349
3421
|
/**
|
|
3350
3422
|
* One reported origin, parsed and reduced to its origin form. A value
|
|
3351
3423
|
* that is not an absolute http(s) URL is refused rather than repaired:
|
|
@@ -4018,6 +4090,29 @@ async function takePreObservation(state, session, resourceId, entityId) {
|
|
|
4018
4090
|
session.activity += 1;
|
|
4019
4091
|
return { observationId, observed: ids.length };
|
|
4020
4092
|
}
|
|
4093
|
+
/**
|
|
4094
|
+
* Whether the ledger holds TEST evidence: any issued record other than
|
|
4095
|
+
* the single run-level OpenAPI metadata record (kind `http.openapi`,
|
|
4096
|
+
* testId `run`) that binding a response-shape run seals. That record is
|
|
4097
|
+
* run metadata sealed at bind time — BEFORE the supervisor drain
|
|
4098
|
+
* registers its PRE-run declarations — so the PRE-run gates must not
|
|
4099
|
+
* treat it as "the run already happened". Any other record (exchanges,
|
|
4100
|
+
* observations, persistence, claims) is real test evidence and counts.
|
|
4101
|
+
*
|
|
4102
|
+
* Args:
|
|
4103
|
+
* state: running witness state.
|
|
4104
|
+
*
|
|
4105
|
+
* Returns:
|
|
4106
|
+
* boolean: true when the ledger holds at least one non-metadata record.
|
|
4107
|
+
*/
|
|
4108
|
+
function hasTestEvidenceRecord(state) {
|
|
4109
|
+
for (const record of state.ledger.values()) {
|
|
4110
|
+
if (record.kind === HTTP_OPENAPI_KIND && record.testId === 'run')
|
|
4111
|
+
continue;
|
|
4112
|
+
return true;
|
|
4113
|
+
}
|
|
4114
|
+
return false;
|
|
4115
|
+
}
|
|
4021
4116
|
/**
|
|
4022
4117
|
* `POST /runs/server-e2e-declarations` — SUPERVISOR ONLY (verifier key;
|
|
4023
4118
|
* the same authority as `POST /runs/expected-set`): registers the
|
|
@@ -4060,7 +4155,7 @@ async function handleServerE2eDeclarations(state, res, verifier, body) {
|
|
|
4060
4155
|
});
|
|
4061
4156
|
return;
|
|
4062
4157
|
}
|
|
4063
|
-
if (state
|
|
4158
|
+
if (hasTestEvidenceRecord(state) || state.sessions.size > 0 || state.serverPreObservations.size > 0) {
|
|
4064
4159
|
sendJson(res, 409, {
|
|
4065
4160
|
error: 'witness already issued evidence or holds open sessions; server-e2e declarations must be ' +
|
|
4066
4161
|
'registered BEFORE the run — start a fresh witness for a new invocation',
|
|
@@ -4111,7 +4206,7 @@ async function handleObserveDeclarations(state, res, verifier, body) {
|
|
|
4111
4206
|
});
|
|
4112
4207
|
return;
|
|
4113
4208
|
}
|
|
4114
|
-
if (state
|
|
4209
|
+
if (hasTestEvidenceRecord(state) || state.sessions.size > 0) {
|
|
4115
4210
|
sendJson(res, 409, {
|
|
4116
4211
|
error: 'witness already issued evidence or holds open sessions; observe declarations must be ' +
|
|
4117
4212
|
'registered BEFORE the run — start a fresh witness for a new invocation',
|
|
@@ -4256,7 +4351,7 @@ async function observeListEntities(adapterName, adapter, ctx) {
|
|
|
4256
4351
|
function matchObserveTemplate(observedPath, template) {
|
|
4257
4352
|
const segments = template.split('/').filter((segment) => segment.length > 0);
|
|
4258
4353
|
const idIndex = segments.indexOf('{id}');
|
|
4259
|
-
const canonical = segments.map((segment) => (segment === '{id}' ? '{}' : segment)).join('/');
|
|
4354
|
+
const canonical = segments.map((segment) => (segment === '{id}' || segment.startsWith(':') ? '{}' : segment)).join('/');
|
|
4260
4355
|
if (!pathMatchesShape(observedPath, canonical.startsWith('/') ? canonical : `/${canonical}`)) {
|
|
4261
4356
|
return null;
|
|
4262
4357
|
}
|
|
@@ -4531,9 +4626,10 @@ function attributeCreatedEntity(state, binding, exchange, fresh) {
|
|
|
4531
4626
|
* stays blocking through verdicts, which is the honest outcome).
|
|
4532
4627
|
*
|
|
4533
4628
|
* Per obligation (`<resourceId>:persistence:<op>`):
|
|
4534
|
-
* -
|
|
4535
|
-
*
|
|
4536
|
-
*
|
|
4629
|
+
* - exactly one 2xx session exchange must match the binding for
|
|
4630
|
+
* create/update/delete; reads may match repeated exchanges only when
|
|
4631
|
+
* each resolves to the same entity, consuming every matching exchange
|
|
4632
|
+
* single-use (zero → missing-traffic note; disagreement → ambiguity);
|
|
4537
4633
|
* - create attributes its id to the response the witness proxied,
|
|
4538
4634
|
* verified against the after-list (a concurrent observed create
|
|
4539
4635
|
* named by its OWN response is not ambiguity; a new entity no
|
|
@@ -4582,18 +4678,7 @@ async function handleObserveFinalize(state, res, verifier, body) {
|
|
|
4582
4678
|
// transport record carries. Persistence-vs-persistence consumption is
|
|
4583
4679
|
// untouched: it still matches against the LIVE log, so one exchange
|
|
4584
4680
|
// can never credit two persistence claims.
|
|
4585
|
-
|
|
4586
|
-
for (const claimId of session.claims) {
|
|
4587
|
-
if (session.directRecordsIssued.has(claimId))
|
|
4588
|
-
continue;
|
|
4589
|
-
issueRecord(state, claimId, HTTP_OBSERVED_KIND, session.testId, {
|
|
4590
|
-
channel: DIRECT_CHANNEL,
|
|
4591
|
-
exchanges: session.directExchanges.map((exchange) => ({ ...exchange })),
|
|
4592
|
-
}, 'engine-observed');
|
|
4593
|
-
session.directRecordsIssued.add(claimId);
|
|
4594
|
-
}
|
|
4595
|
-
}
|
|
4596
|
-
const transport = transportSnapshot(state, session);
|
|
4681
|
+
const transport = transportSnapshot(state, session, false);
|
|
4597
4682
|
const claims = session.claims.filter((claim) => state.observeDeclarations?.has(claim));
|
|
4598
4683
|
for (const claimId of claims) {
|
|
4599
4684
|
const outcome = await finalizeObserveClaim(state, session, claimId, transport);
|
|
@@ -4637,7 +4722,7 @@ function zeroTrafficCause(state, session) {
|
|
|
4637
4722
|
const reported = pageOriginNote(state, session);
|
|
4638
4723
|
return reported === '' ? FIXTURE_PAGE_CAUSE : reported;
|
|
4639
4724
|
}
|
|
4640
|
-
function transportSnapshot(state, session) {
|
|
4725
|
+
function transportSnapshot(state, session, includeAssets = true) {
|
|
4641
4726
|
const watermark = state.runContext === null ? 0 : state.observedSeqAtBind;
|
|
4642
4727
|
// key -> position in `exchanges`, so a repeat can upgrade its shape in place.
|
|
4643
4728
|
const seen = new Map();
|
|
@@ -4646,6 +4731,8 @@ function transportSnapshot(state, session) {
|
|
|
4646
4731
|
for (const exchange of state.observed) {
|
|
4647
4732
|
if (exchange.sessionId !== session.sessionId || exchange.seq <= watermark)
|
|
4648
4733
|
continue;
|
|
4734
|
+
if (!includeAssets && httpExchangeKind(exchange.fetchDest) === 'asset')
|
|
4735
|
+
continue;
|
|
4649
4736
|
const key = `${exchange.method} ${exchange.path} ${String(exchange.status)} ${exchange.initiator ?? 'page'} ${exchange.fetchDest ?? ''} ${exchange.resourceType ?? ''}`;
|
|
4650
4737
|
const at = seen.get(key);
|
|
4651
4738
|
if (at !== undefined) {
|
|
@@ -4678,13 +4765,15 @@ function transportSnapshot(state, session) {
|
|
|
4678
4765
|
* Applies the SAME snapshot discipline `transportSnapshot` enforces —
|
|
4679
4766
|
* dedup by `(method, url, status)`, cap at {@link OBSERVED_EXCHANGES_CAP}
|
|
4680
4767
|
* with `truncated: true` past the cap — to an already-captured exchange
|
|
4681
|
-
* list
|
|
4768
|
+
* list. Ledger callers retain assets; Observe callers must exclude them.
|
|
4682
4769
|
*/
|
|
4683
|
-
function cappedExchangeSnapshot(exchanges) {
|
|
4770
|
+
function cappedExchangeSnapshot(exchanges, includeAssets = true) {
|
|
4684
4771
|
const seen = Object.create(null);
|
|
4685
4772
|
const kept = [];
|
|
4686
4773
|
let truncated = false;
|
|
4687
4774
|
for (const exchange of exchanges) {
|
|
4775
|
+
if (!includeAssets && httpExchangeKind(exchange.fetchDest) === 'asset')
|
|
4776
|
+
continue;
|
|
4688
4777
|
const key = `${exchange.method} ${exchange.url} ${String(exchange.status)} ${exchange.fetchDest ?? ''} ${exchange.resourceType ?? ''}`;
|
|
4689
4778
|
if (key in seen)
|
|
4690
4779
|
continue;
|
|
@@ -4770,11 +4859,53 @@ async function finalizeObserveClaim(state, session, claimId, transport) {
|
|
|
4770
4859
|
`proxy — drive traffic through the session proxy prefix before claiming the obligation; ` +
|
|
4771
4860
|
zeroTrafficCause(state, session));
|
|
4772
4861
|
}
|
|
4862
|
+
let exchangesToConsume = [];
|
|
4773
4863
|
if (matches.length > 1) {
|
|
4774
|
-
|
|
4775
|
-
|
|
4864
|
+
if (operation !== 'read') {
|
|
4865
|
+
return note(`${String(matches.length)} matching ${binding.method} ${binding.path} exchanges — ambiguous, ` +
|
|
4866
|
+
'refusing to pick one (seed through untracked channels so the mutation stands alone)');
|
|
4867
|
+
}
|
|
4868
|
+
const resolved = new Set();
|
|
4869
|
+
if (binding.collection === undefined) {
|
|
4870
|
+
for (const match of matches) {
|
|
4871
|
+
if (match.id === null) {
|
|
4872
|
+
return note('the observe binding carries no {id} segment for a non-create operation');
|
|
4873
|
+
}
|
|
4874
|
+
const key = beforeKeyForSegment(snapshot.before, match.id);
|
|
4875
|
+
if (key === null) {
|
|
4876
|
+
return note(`entity '${match.id}' was not in the session-open snapshot — observe binds {id} ` +
|
|
4877
|
+
'against witness-held before-state, never against suite-declared ids');
|
|
4878
|
+
}
|
|
4879
|
+
resolved.add(key);
|
|
4880
|
+
}
|
|
4881
|
+
if (resolved.size > 1)
|
|
4882
|
+
return note(`${resolved.size} distinct entity ids among repeated read exchanges — ambiguous`);
|
|
4883
|
+
}
|
|
4884
|
+
else {
|
|
4885
|
+
for (const match of matches) {
|
|
4886
|
+
const rows = match.exchange.collectionRows;
|
|
4887
|
+
if (match.exchange.collectionConflict !== undefined || rows === undefined || rows.error !== null ||
|
|
4888
|
+
rows.rowsKey !== (binding.collection.rowsKey ?? null) || rows.idKey !== binding.collection.idKey) {
|
|
4889
|
+
return note(`${matches.length} repeated collection read exchanges could not all resolve to the same entity — ambiguous`);
|
|
4890
|
+
}
|
|
4891
|
+
const held = Object.create(null);
|
|
4892
|
+
for (const id of rows.ids) {
|
|
4893
|
+
const key = beforeKeyForSegment(snapshot.before, String(id));
|
|
4894
|
+
if (key !== null)
|
|
4895
|
+
held[key] = true;
|
|
4896
|
+
}
|
|
4897
|
+
const returned = Object.keys(held).sort(compareStrings);
|
|
4898
|
+
if (returned.length === 0) {
|
|
4899
|
+
return note(`${matches.length} repeated collection read exchanges could not all resolve to the same entity — ambiguous`);
|
|
4900
|
+
}
|
|
4901
|
+
resolved.add(returned[0]);
|
|
4902
|
+
}
|
|
4903
|
+
if (resolved.size > 1)
|
|
4904
|
+
return note(`${resolved.size} distinct entities among repeated collection reads — ambiguous`);
|
|
4905
|
+
}
|
|
4906
|
+
exchangesToConsume = matches.map((match) => match.exchange);
|
|
4776
4907
|
}
|
|
4777
|
-
const matched = matches[
|
|
4908
|
+
const matched = matches[matches.length - 1];
|
|
4778
4909
|
// Resolve the entity id: create attributes the entity to the response
|
|
4779
4910
|
// the witness proxied (verified against the witness's own after-list,
|
|
4780
4911
|
// so a concurrent observed create cannot make it ambiguous);
|
|
@@ -4810,8 +4941,8 @@ async function finalizeObserveClaim(state, session, claimId, transport) {
|
|
|
4810
4941
|
// such row names nothing to prove — both are typed notes.
|
|
4811
4942
|
const conflict = matched.exchange.collectionConflict;
|
|
4812
4943
|
if (conflict !== undefined) {
|
|
4813
|
-
return note(`this session claims more than one read on ${binding.method} ${binding.path} and
|
|
4814
|
-
`
|
|
4944
|
+
return note(`this session claims more than one read on ${binding.method} ${binding.path} and declares DIFFERENT ` +
|
|
4945
|
+
`collection shapes (different declared collection shapes: ${conflict.join(' vs ')}) — the witness parses that response for ` +
|
|
4815
4946
|
'neither of them, so no record is issued');
|
|
4816
4947
|
}
|
|
4817
4948
|
const rows = matched.exchange.collectionRows;
|
|
@@ -4901,10 +5032,13 @@ async function finalizeObserveClaim(state, session, claimId, transport) {
|
|
|
4901
5032
|
// origin, witnessed trust; the suite-driven-browser distinction rides
|
|
4902
5033
|
// `channel: 'observe'`, which the grader keys off explicitly.
|
|
4903
5034
|
const issued = issueRecord(state, claimId, OBSERVED_KIND, session.testId, payload, 'engine-observed');
|
|
4904
|
-
// Single-use:
|
|
4905
|
-
const
|
|
4906
|
-
|
|
4907
|
-
state.observed.
|
|
5035
|
+
// Single-use: agreeing repeated read exchanges are consumed together.
|
|
5036
|
+
const consumedExchanges = exchangesToConsume.length === 0 ? [matched.exchange] : exchangesToConsume;
|
|
5037
|
+
for (const exchange of consumedExchanges) {
|
|
5038
|
+
const consumed = state.observed.indexOf(exchange);
|
|
5039
|
+
if (consumed !== -1)
|
|
5040
|
+
state.observed.splice(consumed, 1);
|
|
5041
|
+
}
|
|
4908
5042
|
session.activity += 1;
|
|
4909
5043
|
return {
|
|
4910
5044
|
record: { obligationId: claimId, recordId: issued.recordId, operation, entityId: read.entityId },
|
|
@@ -5440,7 +5574,7 @@ async function handleRunContext(state, res, verifier, body) {
|
|
|
5440
5574
|
});
|
|
5441
5575
|
return;
|
|
5442
5576
|
}
|
|
5443
|
-
if (state
|
|
5577
|
+
if (hasTestEvidenceRecord(state) ||
|
|
5444
5578
|
state.observed.length > 0 ||
|
|
5445
5579
|
state.preObservations.size > 0 ||
|
|
5446
5580
|
state.serverPreObservations.size > 0 ||
|