@gate-forge/pack-playwright 0.13.10 → 0.15.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.
Files changed (90) hide show
  1. package/dist/discovery/config-locations.d.ts +4 -0
  2. package/dist/discovery/config-locations.d.ts.map +1 -1
  3. package/dist/discovery/config-locations.js +9 -0
  4. package/dist/discovery/config-locations.js.map +1 -1
  5. package/dist/discovery/cypress-runner-adapter.d.ts +1 -1
  6. package/dist/discovery/cypress-runner-adapter.d.ts.map +1 -1
  7. package/dist/discovery/cypress-runner-adapter.js +9 -7
  8. package/dist/discovery/cypress-runner-adapter.js.map +1 -1
  9. package/dist/discovery/discover.d.ts +10 -0
  10. package/dist/discovery/discover.d.ts.map +1 -1
  11. package/dist/discovery/discover.js +123 -6
  12. package/dist/discovery/discover.js.map +1 -1
  13. package/dist/discovery/index.d.ts +1 -1
  14. package/dist/discovery/index.d.ts.map +1 -1
  15. package/dist/discovery/index.js +1 -1
  16. package/dist/discovery/index.js.map +1 -1
  17. package/dist/discovery/playwright-runner-adapter.d.ts.map +1 -1
  18. package/dist/discovery/playwright-runner-adapter.js +4 -1
  19. package/dist/discovery/playwright-runner-adapter.js.map +1 -1
  20. package/dist/discovery/prepare-barrier.d.ts +2 -1
  21. package/dist/discovery/prepare-barrier.d.ts.map +1 -1
  22. package/dist/discovery/prepare-barrier.js +2 -1
  23. package/dist/discovery/prepare-barrier.js.map +1 -1
  24. package/dist/discovery/pytest-runner-adapter.d.ts.map +1 -1
  25. package/dist/discovery/pytest-runner-adapter.js +11 -14
  26. package/dist/discovery/pytest-runner-adapter.js.map +1 -1
  27. package/dist/discovery/reconcile.d.ts +7 -7
  28. package/dist/discovery/reconcile.d.ts.map +1 -1
  29. package/dist/discovery/reconcile.js +36 -29
  30. package/dist/discovery/reconcile.js.map +1 -1
  31. package/dist/discovery/runner-config-paths.d.ts.map +1 -1
  32. package/dist/discovery/runner-config-paths.js +3 -4
  33. package/dist/discovery/runner-config-paths.js.map +1 -1
  34. package/dist/discovery/runner-env.d.ts +12 -0
  35. package/dist/discovery/runner-env.d.ts.map +1 -1
  36. package/dist/discovery/runner-env.js +36 -2
  37. package/dist/discovery/runner-env.js.map +1 -1
  38. package/dist/discovery/runner-file-scope.d.ts.map +1 -1
  39. package/dist/discovery/runner-file-scope.js +8 -0
  40. package/dist/discovery/runner-file-scope.js.map +1 -1
  41. package/dist/discovery/supervised-run.d.ts +11 -1
  42. package/dist/discovery/supervised-run.d.ts.map +1 -1
  43. package/dist/discovery/supervised-run.js +32 -12
  44. package/dist/discovery/supervised-run.js.map +1 -1
  45. package/dist/discovery/vitest-runner-adapter.d.ts +8 -1
  46. package/dist/discovery/vitest-runner-adapter.d.ts.map +1 -1
  47. package/dist/discovery/vitest-runner-adapter.js +28 -21
  48. package/dist/discovery/vitest-runner-adapter.js.map +1 -1
  49. package/dist/fixture/api-request.d.ts +11 -18
  50. package/dist/fixture/api-request.d.ts.map +1 -1
  51. package/dist/fixture/api-request.js +91 -32
  52. package/dist/fixture/api-request.js.map +1 -1
  53. package/dist/fixture/auto-session-env.d.ts +3 -0
  54. package/dist/fixture/auto-session-env.d.ts.map +1 -0
  55. package/dist/fixture/auto-session-env.js +7 -0
  56. package/dist/fixture/auto-session-env.js.map +1 -0
  57. package/dist/fixture/auto-session-loader.mjs +20 -0
  58. package/dist/fixture/auto-session-playwright-wrapper.mjs +6 -0
  59. package/dist/fixture/auto-session-root.cjs +14 -0
  60. package/dist/fixture/auto-session-wrapper.cjs +8 -0
  61. package/dist/fixture/auto-session-wrapper.mjs +6 -0
  62. package/dist/fixture/auto-session.cjs +36 -0
  63. package/dist/fixture/fixture.d.ts +45 -34
  64. package/dist/fixture/fixture.d.ts.map +1 -1
  65. package/dist/fixture/fixture.js +362 -245
  66. package/dist/fixture/fixture.js.map +1 -1
  67. package/dist/index.d.ts +2 -1
  68. package/dist/index.d.ts.map +1 -1
  69. package/dist/index.js +2 -1
  70. package/dist/index.js.map +1 -1
  71. package/dist/reporter/reporter.cjs +4 -0
  72. package/dist/reporter/reporter.cjs.map +1 -1
  73. package/dist/reporter/reporter.d.ts +8 -0
  74. package/dist/reporter/reporter.d.ts.map +1 -1
  75. package/dist/reporter/reporter.js +40 -0
  76. package/dist/reporter/reporter.js.map +1 -1
  77. package/dist/supervisor/drain.d.ts.map +1 -1
  78. package/dist/supervisor/drain.js +27 -0
  79. package/dist/supervisor/drain.js.map +1 -1
  80. package/dist/supervisor/spool.d.ts +5 -0
  81. package/dist/supervisor/spool.d.ts.map +1 -1
  82. package/dist/supervisor/spool.js +20 -1
  83. package/dist/supervisor/spool.js.map +1 -1
  84. package/dist/vitest/index.d.ts.map +1 -1
  85. package/dist/vitest/index.js +2 -1
  86. package/dist/vitest/index.js.map +1 -1
  87. package/dist/vitest/reporter.d.ts.map +1 -1
  88. package/dist/vitest/reporter.js +2 -1
  89. package/dist/vitest/reporter.js.map +1 -1
  90. package/package.json +4 -4
@@ -10,14 +10,13 @@
10
10
  * API. Tests that use engine-driven UI must extend this runner with a
11
11
  * declarative `surface` descriptor (`test.extend({ surface })`) — the
12
12
  * pack carries no application-specific selectors. Tests must
13
- * import `{ test, expect }` FROM A RUNNER EXTENDED LIKE THIS — importing
14
- * raw `playwright/test` bypasses the fixture and produces claims with no
15
- * records (the engine grades the obligation `missing`; GF-24).
13
+ * import `{ test, expect }` FROM A RUNNER EXTENDED LIKE THIS. Witnessed
14
+ * runs automatically redirect consumer `@playwright/test` and `playwright/test`
15
+ * imports here too; an uninstrumented test produces no browser records.
16
16
  *
17
- * API requests made directly from test code are never E2E evidence. The
18
- * `request` fixture, owned `page.request`/`context.request`, and exported
19
- * `request` factory all go directly to the app; only browser page traffic
20
- * rides the session proxy.
17
+ * API requests made from test code are never E2E evidence. Test-owned
18
+ * `request` contexts ride the session proxy with a test-code marker for
19
+ * the HTTP ledger; owned `page.request`/`context.request` stay direct.
21
20
  */
22
21
  import { chromium, firefox, webkit, request as playwrightRequest } from 'playwright';
23
22
  import { createServer as createTcpServer } from 'node:net';
@@ -26,7 +25,7 @@ import { expect, test as base } from './consumer-runner.js';
26
25
  import { setTimeout as delay } from 'node:timers/promises';
27
26
  import { ENV_WITNESS_URL } from '../constants.js';
28
27
  import { createEvidence, } from './evidence.js';
29
- import { wrapDirectRequestContext } from './api-request.js';
28
+ import { wrapRequestContext } from './api-request.js';
30
29
  import { WitnessClient } from './witness-client.js';
31
30
  const browserDebuggingPorts = new WeakMap();
32
31
  const unavailableInitiatorBrowsers = new Set();
@@ -84,14 +83,17 @@ function projectBaseURL(testInfo) {
84
83
  const baseURL = testInfo.project.use['baseURL'];
85
84
  return typeof baseURL === 'string' && baseURL !== '' ? baseURL : undefined;
86
85
  }
87
- async function attachInitiatorTracking(page, appBaseURL) {
86
+ async function attachInitiatorTracking(page, appOrigins) {
88
87
  const session = await page.context().newCDPSession(page);
89
88
  const pending = new Map();
90
89
  // Route callbacks that arrived before their CDP event, oldest first.
91
90
  const waiting = new Map();
92
- const appOriginPrefix = `${new URL(appBaseURL).origin}/`;
91
+ // EVERY app origin this session routes, not just the primary one: an
92
+ // unclassified request on a declared second app would otherwise be
93
+ // graded `unknown` and lose the test-code marking it must keep.
94
+ const appOriginPrefixes = appOrigins.map((origin) => `${origin.origin}/`);
93
95
  session.on('Network.requestWillBeSent', (event) => {
94
- if (!event.request.url.startsWith(appOriginPrefix))
96
+ if (!appOriginPrefixes.some((prefix) => event.request.url.startsWith(prefix)))
95
97
  return;
96
98
  let deepest = event.initiator?.stack;
97
99
  while (deepest?.parent !== undefined)
@@ -143,58 +145,115 @@ async function attachInitiatorTracking(page, appBaseURL) {
143
145
  };
144
146
  }
145
147
  /**
146
- * Routes browser requests for the configured app origin through the
147
- * supervisor-issued session proxy, preserving the app URL and path.
148
+ * Routes browser requests for every CONFIGURED app origin through the
149
+ * supervisor-issued session proxy of that origin, preserving the app URL
150
+ * and path.
148
151
  *
149
- * Every OTHER origin the page requests is continued untouched — that is
150
- * what a third-party asset needs. When such an origin is on the app's
151
- * own host (or loopback) it is also a silent ORIGIN MISMATCH: the page
152
- * is talking to an app origin Gateforge never configured, so nothing it
153
- * fetches can reach the session proxy. `onUnroutedOrigin` reports those
154
- * origins so the witness's zero-traffic note can name the real cause
155
- * (plan 0.9.2 item F). It is diagnostic text: no record, no verdict.
152
+ * A run may declare more than one app origin (`.gateforge.yml`
153
+ * `additionalAppOrigins`): a consumer whose tests drive a platform admin
154
+ * console beside the tenant app loads both, and traffic on the second one
155
+ * used to pass unwitnessed — the test passed and earned nothing. Each
156
+ * origin rewrites onto ITS OWN session proxy, and both land on the same
157
+ * session, so attribution and claims are unchanged.
158
+ *
159
+ * Every OTHER origin the page requests is passed to remaining routes
160
+ * untouched, preserving the consumer's handlers for third-party assets.
161
+ * When an origin is on a routed app's own host (or loopback) it is also a
162
+ * silent ORIGIN MISMATCH: the page is talking to an app origin Gateforge
163
+ * never configured, so nothing it fetches can reach the session proxy.
164
+ * `onUnroutedOrigin` reports those origins so the witness's zero-traffic
165
+ * note can name the real cause (plan 0.9.2 item F). It is diagnostic text:
166
+ * no record, no verdict.
156
167
  *
157
168
  * Args:
158
169
  * page: Playwright page used by the current test.
159
- * appBaseURL: shared observation-proxy origin from the operator.
160
- * sessionProxyURL: dedicated observation-proxy origin for this test.
170
+ * appBaseURL: the primary app origin from the operator.
171
+ * sessionProxyURL: that origin's dedicated session-proxy origin.
161
172
  * onUnroutedOrigin: optional sink for unrouted same-host origins.
173
+ * initiatorForRequest: optional UI-vs-test-code classifier.
174
+ * additionalProxies: the DECLARED further origins and their proxies
175
+ * (from the session credential), when the run declares any.
162
176
  */
163
- export async function routePageThroughSessionProxy(page, appBaseURL, sessionProxyURL, onUnroutedOrigin, initiatorForRequest) {
164
- const appOrigin = new URL(appBaseURL);
165
- const sessionOrigin = new URL(sessionProxyURL);
166
- if (appOrigin.protocol !== 'http:' ||
167
- sessionOrigin.protocol !== appOrigin.protocol ||
168
- sessionOrigin.hostname !== appOrigin.hostname) {
169
- throw new Error('Gateforge session proxy and app base must share the same loopback HTTP host');
170
- }
171
- if (appOrigin.origin === sessionOrigin.origin)
177
+ export async function routePageThroughSessionProxy(page, appBaseURL, sessionProxyURL, onUnroutedOrigin, initiatorForRequest, additionalProxies = []) {
178
+ const routes = sessionProxyRoutes(appBaseURL, sessionProxyURL, additionalProxies);
179
+ if (routes.length === 0)
172
180
  return;
173
- await page.route('**/*', async (route) => {
181
+ await page.route('**/*', sessionProxyRoute(routes, onUnroutedOrigin, initiatorForRequest));
182
+ }
183
+ /**
184
+ * The session's app-origin routing table: one entry per origin that
185
+ * actually needs a rewrite, validated exactly as the single-origin case
186
+ * always was (same loopback HTTP host, or no rewrite at all).
187
+ *
188
+ * Args:
189
+ * appBaseURL: the primary app origin from the operator, or null when the
190
+ * suite configured none.
191
+ * sessionProxyURL: that origin's dedicated session-proxy origin, or null
192
+ * when this session has no primary proxy (nothing to rewrite).
193
+ * additionalProxies: the declared further origins and their proxies.
194
+ *
195
+ * Returns:
196
+ * SessionProxyRoute[]: the entries to rewrite, primary first.
197
+ *
198
+ * Raises:
199
+ * Error: when a session proxy does not share its app origin's loopback
200
+ * HTTP host — the proxy would answer with the wrong `Host`.
201
+ */
202
+ function sessionProxyRoutes(appBaseURL, sessionProxyURL, additionalProxies) {
203
+ const candidates = [
204
+ ...(appBaseURL !== null && sessionProxyURL !== null ? [{ appOrigin: appBaseURL, proxyUrl: sessionProxyURL }] : []),
205
+ ...additionalProxies,
206
+ ];
207
+ const routes = [];
208
+ const seen = new Set();
209
+ for (const candidate of candidates) {
210
+ const appOrigin = new URL(candidate.appOrigin);
211
+ const sessionOrigin = new URL(candidate.proxyUrl);
212
+ if (appOrigin.protocol !== 'http:' ||
213
+ sessionOrigin.protocol !== appOrigin.protocol ||
214
+ sessionOrigin.hostname !== appOrigin.hostname) {
215
+ throw new Error('Gateforge session proxy and app base must share the same loopback HTTP host');
216
+ }
217
+ if (appOrigin.origin === sessionOrigin.origin || seen.has(appOrigin.origin))
218
+ continue;
219
+ seen.add(appOrigin.origin);
220
+ routes.push({ appOrigin, sessionOrigin });
221
+ }
222
+ return routes;
223
+ }
224
+ function sessionProxyRoute(routes, onUnroutedOrigin, initiatorForRequest) {
225
+ return async (route) => {
174
226
  const requestURL = new URL(route.request().url());
175
- if (requestURL.origin !== appOrigin.origin) {
176
- if (onUnroutedOrigin !== undefined && isAppHostOrigin(requestURL, appOrigin)) {
227
+ const routed = routes.find((entry) => requestURL.origin === entry.appOrigin.origin);
228
+ if (routed === undefined) {
229
+ if (onUnroutedOrigin !== undefined && isAppHostOrigin(requestURL, routes)) {
177
230
  onUnroutedOrigin(requestURL.origin);
178
231
  }
179
- await route.continue();
232
+ await route.fallback();
180
233
  return;
181
234
  }
182
235
  const originalURL = requestURL.href;
183
- requestURL.host = sessionOrigin.host;
236
+ requestURL.host = routed.sessionOrigin.host;
184
237
  const initiator = await initiatorForRequest?.(route.request().method(), originalURL);
185
- const headers = initiator === 'test-code'
186
- ? { ...route.request().headers(), 'x-gateforge-initiator': 'test-code' }
187
- : undefined;
188
- await route.continue({ url: requestURL.href, ...(headers === undefined ? {} : { headers }) });
189
- });
238
+ const headers = {
239
+ ...route.request().headers(),
240
+ 'x-gateforge-resource-type': route.request().resourceType(),
241
+ };
242
+ if (initiator === 'test-code')
243
+ headers['x-gateforge-initiator'] = 'test-code';
244
+ // Yield to consumer context routes while carrying the session rewrite.
245
+ // continue() would skip their stubs and change the test's response.
246
+ await route.fallback({ url: requestURL.href, headers });
247
+ };
190
248
  }
191
249
  /**
192
- * Whether an unrouted origin is a plausible app origin at all: the app
193
- * base's own host, or loopback (where every local deployment lives). A
194
- * CDN or an analytics host is not a mismatch and is never reported.
250
+ * Whether an unrouted origin is a plausible app origin at all: the host of
251
+ * an origin this session DOES route, or loopback (where every local
252
+ * deployment lives). A CDN or an analytics host is not a mismatch and is
253
+ * never reported.
195
254
  */
196
- function isAppHostOrigin(url, appOrigin) {
197
- return url.hostname === appOrigin.hostname || isLoopbackHostname(url.hostname);
255
+ function isAppHostOrigin(url, routes) {
256
+ return routes.some((entry) => url.hostname === entry.appOrigin.hostname) || isLoopbackHostname(url.hostname);
198
257
  }
199
258
  /** Loopback in the three forms a browser URL can carry it. */
200
259
  function isLoopbackHostname(hostname) {
@@ -208,20 +267,23 @@ const UNROUTED_ORIGIN_CAP = 5;
208
267
  * Args:
209
268
  * witness: the session's witness client.
210
269
  * session: the session the report belongs to (its own, never another's).
211
- * appBaseURL: the base URL the fixture routes — the origin the page
212
- * was supposed to load.
270
+ * appBaseURL: the primary base URL the fixture routes.
271
+ * additionalAppOrigins: the run's DECLARED further app origins. They are
272
+ * routed too, so a report naming one would be the fixture accusing
273
+ * itself of a mismatch it does not have.
213
274
  *
214
275
  * Returns:
215
276
  * UnroutedOriginReporter: the bounded, non-blocking reporter.
216
277
  */
217
278
  export function createUnroutedOriginReporter(options) {
218
279
  const appBaseUrl = new URL(options.appBaseURL).origin;
280
+ const routedOrigins = [appBaseUrl, ...(options.additionalAppOrigins ?? []).map((url) => new URL(url).origin)];
219
281
  const origins = [];
220
282
  const inFlight = new Set();
221
283
  return {
222
284
  origins,
223
285
  report(origin) {
224
- if (origin === appBaseUrl || origins.includes(origin))
286
+ if (routedOrigins.includes(origin) || origins.includes(origin))
225
287
  return;
226
288
  if (origins.length >= UNROUTED_ORIGIN_CAP)
227
289
  return;
@@ -245,47 +307,6 @@ export function createUnroutedOriginReporter(options) {
245
307
  },
246
308
  };
247
309
  }
248
- const directExchangeReporters = new Map();
249
- function directExchangeReporterFor(testInfo) {
250
- const existing = directExchangeReporters.get(testInfo.testId);
251
- if (existing !== undefined)
252
- return existing;
253
- const inFlight = new Set();
254
- const witness = new WitnessClient();
255
- const reporter = {
256
- report(exchange) {
257
- const sent = (async () => {
258
- const session = await resolveSessionBounded(witness, testInfo.testId, testInfo.workerIndex, 5_000);
259
- if (session === null)
260
- return;
261
- await witness.reportSessionDirectExchanges({
262
- sessionId: session.sessionId,
263
- sessionToken: session.sessionToken,
264
- exchanges: [exchange],
265
- });
266
- })().catch(() => undefined);
267
- inFlight.add(sent);
268
- void sent.then(() => inFlight.delete(sent));
269
- },
270
- async settled() {
271
- while (inFlight.size > 0)
272
- await Promise.all([...inFlight]);
273
- },
274
- };
275
- directExchangeReporters.set(testInfo.testId, reporter);
276
- return reporter;
277
- }
278
- async function settleDirectExchangeReports(testInfo) {
279
- const reporter = directExchangeReporters.get(testInfo.testId);
280
- if (reporter === undefined)
281
- return;
282
- try {
283
- await reporter.settled();
284
- }
285
- finally {
286
- directExchangeReporters.delete(testInfo.testId);
287
- }
288
- }
289
310
  /**
290
311
  * The runner the evidence fixtures extend. Page observation needs a
291
312
  * Chromium debugging port, so only then does it replace Playwright's
@@ -325,141 +346,250 @@ const browserRunner = process.env['GATEFORGE_PAGE_OBSERVATION_ENABLED'] === '1'
325
346
  * was wired.
326
347
  */
327
348
  const extended = browserRunner.extend({
328
- directApiReports: [async ({}, use, testInfo) => {
349
+ browserPages: [async ({ browser, browserName }, use, testInfo) => {
329
350
  if (!process.env[ENV_WITNESS_URL]) {
330
351
  await use(undefined);
331
352
  return;
332
353
  }
333
- directExchangeReporterFor(testInfo);
334
- try {
335
- await use(undefined);
354
+ const appBaseURL = process.env['GATEFORGE_APP_BASE_URL']?.trim();
355
+ const witness = new WitnessClient();
356
+ const session = await resolveSessionBounded(witness, testInfo.testId, testInfo.workerIndex, 5_000);
357
+ if (session === null) {
358
+ throw new Error(`No supervisor-issued witness session for ${testInfo.testId}.`);
336
359
  }
337
- finally {
338
- await settleDirectExchangeReports(testInfo);
360
+ // The auto fixture also runs for tests that never create a context or
361
+ // page. Require app routing configuration only at those browser edges.
362
+ //
363
+ // The routing table is built from the SESSION CREDENTIAL, never from a
364
+ // suite-side variable: which origins exist is controller-held (the
365
+ // owner's `.gateforge.yml` declaration, resolved by the CLI into the
366
+ // witness's per-session proxies), so a test process cannot widen its
367
+ // own routing by setting an environment variable.
368
+ const additionalProxies = session.additionalProxyUrls ?? [];
369
+ const appOrigins = appBaseURL === undefined
370
+ ? null
371
+ : [new URL(appBaseURL), ...additionalProxies.map((entry) => new URL(entry.appOrigin))];
372
+ const appOriginPrefixes = appOrigins === null ? null : appOrigins.map((origin) => `${origin.origin}/`);
373
+ const routes = sessionProxyRoutes(appBaseURL ?? null, session.proxyUrl, additionalProxies);
374
+ let pageObserverRegistered = false;
375
+ const debuggingPort = browserDebuggingPorts.get(browser);
376
+ // Authority cutover (0.13): the request carries ONLY session
377
+ // credentials + the debugging port. Grading configuration is
378
+ // controller-held (supervisor-registered page-observation context);
379
+ // a registration the witness refuses (tampered session, unbound
380
+ // context) is surfaced and never retried from suite-side state.
381
+ if (debuggingPort !== undefined && process.env['GATEFORGE_PAGE_OBSERVATION_ENABLED'] === '1') {
382
+ try {
383
+ await witness.registerPageObserver({
384
+ sessionId: session.sessionId,
385
+ sessionToken: session.sessionToken,
386
+ testId: session.testId,
387
+ debuggingPort,
388
+ });
389
+ pageObserverRegistered = true;
390
+ }
391
+ catch (error) {
392
+ const detail = error instanceof Error ? error.message : String(error);
393
+ if (detail.startsWith('PAGE_OBSERVATION_TAMPER_RISK')) {
394
+ // The WITNESS refused this session's records from the
395
+ // controller context (its decision is not env-mutable here);
396
+ // surface it and continue — the page obligations stay
397
+ // unproven, never satisfied by a tampered session.
398
+ console.error(detail);
399
+ }
400
+ else {
401
+ throw error;
402
+ }
403
+ }
339
404
  }
340
- }, { auto: true }],
341
- page: async ({ page, browser, browserName }, use, testInfo) => {
342
- if (!process.env[ENV_WITNESS_URL]) {
343
- await use(page);
344
- return;
345
- }
346
- const appBaseURL = process.env['GATEFORGE_APP_BASE_URL']?.trim();
347
- if (!appBaseURL) {
348
- throw new Error('GATEFORGE_APP_BASE_URL is required for witnessed browser traffic.');
349
- }
350
- const witness = new WitnessClient();
351
- const session = await resolveSessionBounded(witness, testInfo.testId, testInfo.workerIndex, 5_000);
352
- if (session === null) {
353
- throw new Error(`No supervisor-issued witness session for ${testInfo.testId}.`);
354
- }
355
- let pageObserverRegistered = false;
356
- const debuggingPort = browserDebuggingPorts.get(browser);
357
- // Authority cutover (0.13): the request carries ONLY session
358
- // credentials + the debugging port. Grading configuration is
359
- // controller-held (supervisor-registered page-observation context);
360
- // a registration the witness refuses (tampered session, unbound
361
- // context) is surfaced and never retried from suite-side state.
362
- if (debuggingPort !== undefined && process.env['GATEFORGE_PAGE_OBSERVATION_ENABLED'] === '1') {
363
- try {
364
- await witness.registerPageObserver({
405
+ const flushPageObserver = async () => {
406
+ if (!pageObserverRegistered)
407
+ return;
408
+ await flushPageObserverEvidence(witness, {
365
409
  sessionId: session.sessionId,
366
410
  sessionToken: session.sessionToken,
367
411
  testId: session.testId,
368
- debuggingPort,
369
412
  });
370
- pageObserverRegistered = true;
371
- }
372
- catch (error) {
373
- const detail = error instanceof Error ? error.message : String(error);
374
- if (detail.startsWith('PAGE_OBSERVATION_TAMPER_RISK')) {
375
- // The WITNESS refused this session's records from the
376
- // controller context (its decision is not env-mutable here);
377
- // surface it and continue — the page obligations stay
378
- // unproven, never satisfied by a tampered session.
379
- console.error(detail);
413
+ };
414
+ const reporter = appBaseURL
415
+ ? createUnroutedOriginReporter({
416
+ witness,
417
+ session,
418
+ appBaseURL,
419
+ additionalAppOrigins: additionalProxies.map((entry) => entry.appOrigin),
420
+ })
421
+ : null;
422
+ const initialPopupRoute = routes.length === 0 || reporter === null
423
+ ? null
424
+ : sessionProxyRoute(routes, reporter.report);
425
+ const pages = new Map();
426
+ const tracking = new Map();
427
+ const pageClosers = new Map();
428
+ const pageRoutes = new Map();
429
+ const contexts = new Map();
430
+ let active = true;
431
+ const preparePage = (page) => {
432
+ if (!appBaseURL || appOrigins === null || reporter === null) {
433
+ throw new Error('GATEFORGE_APP_BASE_URL is required for witnessed browser traffic.');
380
434
  }
381
- else {
382
- throw error;
435
+ const existing = pages.get(page);
436
+ if (existing !== undefined)
437
+ return existing;
438
+ const close = page.close;
439
+ pageClosers.set(page, close);
440
+ page.close = async (...args) => {
441
+ await pages.get(page);
442
+ await flushPageObserver();
443
+ await close.apply(page, args);
444
+ };
445
+ const ready = (async () => {
446
+ let initiator;
447
+ if (browserName === 'chromium') {
448
+ initiator = await attachInitiatorTracking(page, appOrigins ?? []);
449
+ tracking.set(page, initiator);
450
+ }
451
+ else if (!unavailableInitiatorBrowsers.has(browserName)) {
452
+ unavailableInitiatorBrowsers.add(browserName);
453
+ console.warn(`initiator check unavailable for ${browserName}; requests started by test code cannot be told apart`);
454
+ }
455
+ if (routes.length > 0) {
456
+ const handler = sessionProxyRoute(routes, reporter.report, initiator?.classify);
457
+ pageRoutes.set(page, handler);
458
+ await page.route('**/*', handler);
459
+ }
460
+ })();
461
+ pages.set(page, ready);
462
+ // Event-created pages have no awaiting caller. Retain the rejection
463
+ // for teardown while preventing an unhandled-rejection process exit.
464
+ void ready.catch(() => undefined);
465
+ return ready;
466
+ };
467
+ const prepareContext = async (context) => {
468
+ if (appOriginPrefixes === null) {
469
+ throw new Error('GATEFORGE_APP_BASE_URL is required for witnessed browser traffic.');
383
470
  }
384
- }
385
- }
386
- const flushPageObserver = async () => {
387
- if (!pageObserverRegistered)
388
- return;
389
- await flushPageObserverEvidence(witness, {
390
- sessionId: session.sessionId,
391
- sessionToken: session.sessionToken,
392
- testId: session.testId,
393
- });
394
- };
395
- let initiatorTracking;
396
- if (browserName === 'chromium') {
397
- initiatorTracking = await attachInitiatorTracking(page, appBaseURL);
398
- }
399
- else if (!unavailableInitiatorBrowsers.has(browserName)) {
400
- unavailableInitiatorBrowsers.add(browserName);
401
- console.warn(`initiator check unavailable for ${browserName}; requests started by test code cannot be told apart`);
402
- }
403
- if (session.proxyUrl !== null) {
404
- const sessionProxyUrl = session.proxyUrl;
405
- const reporter = createUnroutedOriginReporter({ witness, session, appBaseURL });
406
- await routePageThroughSessionProxy(page, appBaseURL, sessionProxyUrl, reporter.report, initiatorTracking?.classify);
407
- // Do not wrap page/context.request: Playwright's Route.fetch uses
408
- // the context request internally to forward browser traffic here.
471
+ if (contexts.has(context))
472
+ return;
473
+ const newPage = context.newPage;
474
+ const contextRoute = context.route;
475
+ const contextClose = context.close;
476
+ const listener = (page) => { if (active)
477
+ void preparePage(page); };
478
+ // Playwright cannot page-route a popup's initial navigation. A
479
+ // context guard catches only requests that missed the page route;
480
+ // normal page routes rewrite first and fall through untouched here.
481
+ const popupRoute = async (route) => {
482
+ if (!active || initialPopupRoute === null || route.request().serviceWorker() !== null || !(appOriginPrefixes ?? []).some((prefix) => route.request().url().startsWith(prefix))) {
483
+ await route.fallback();
484
+ return;
485
+ }
486
+ // Initial popup requests can arrive before their frame exists.
487
+ // There is no CDP page to classify yet; subsequent requests use
488
+ // the event-installed page route and its initiator tracking.
489
+ await initialPopupRoute(route);
490
+ };
491
+ contexts.set(context, { newPage, route: contextRoute, close: contextClose, listener, popupRoute });
492
+ context.close = async (...args) => {
493
+ // A popup can finish loading before its asynchronous CDP setup.
494
+ // Complete that setup before the consumer destroys the context.
495
+ await Promise.all(context.pages().map(preparePage));
496
+ await flushPageObserver();
497
+ await contextClose.apply(context, args);
498
+ };
499
+ context.newPage = async (...args) => {
500
+ const page = await newPage.apply(context, args);
501
+ if (active)
502
+ await preparePage(page);
503
+ return page;
504
+ };
505
+ context.on('page', listener);
506
+ if (session.proxyUrl !== null) {
507
+ await contextRoute.call(context, '**/*', popupRoute);
508
+ context.route = async (...args) => {
509
+ await contextRoute.apply(context, args);
510
+ if (active) {
511
+ // Keep the initial-popup guard ahead of newly added context
512
+ // routes; fallback still passes the rewritten URL to them.
513
+ await context.unroute('**/*', popupRoute);
514
+ await contextRoute.call(context, '**/*', popupRoute);
515
+ }
516
+ };
517
+ }
518
+ await Promise.all(context.pages().map(preparePage));
519
+ };
520
+ const newContext = browser.newContext;
521
+ const newPage = browser.newPage;
522
+ browser.newContext = async (...args) => {
523
+ const context = await newContext.apply(browser, args);
524
+ if (active)
525
+ await prepareContext(context);
526
+ return context;
527
+ };
528
+ // Browser.newPage delegates internally to newContext in the pinned
529
+ // runner, but also await page readiness explicitly at its public edge.
530
+ browser.newPage = async (...args) => {
531
+ const page = await newPage.apply(browser, args);
532
+ if (active) {
533
+ await prepareContext(page.context());
534
+ await preparePage(page);
535
+ }
536
+ return page;
537
+ };
409
538
  try {
410
- await use(page);
539
+ await Promise.all(browser.contexts().map(prepareContext));
540
+ await use(undefined);
411
541
  }
412
542
  finally {
543
+ active = false;
544
+ browser.newContext = newContext;
545
+ browser.newPage = newPage;
546
+ for (const [context, hooks] of contexts) {
547
+ context.newPage = hooks.newPage;
548
+ context.route = hooks.route;
549
+ context.close = hooks.close;
550
+ context.off('page', hooks.listener);
551
+ }
552
+ for (const [page, close] of pageClosers)
553
+ page.close = close;
413
554
  try {
414
- await reporter.settled();
555
+ await Promise.all(pages.values());
556
+ await reporter?.settled();
557
+ await flushPageObserver();
415
558
  }
416
559
  finally {
417
- try {
418
- await flushPageObserver();
560
+ for (const [page, handler] of pageRoutes) {
561
+ if (!page.isClosed())
562
+ await page.unroute('**/*', handler);
563
+ }
564
+ for (const [context, hooks] of contexts) {
565
+ if (browser.contexts().includes(context))
566
+ await context.unroute('**/*', hooks.popupRoute);
419
567
  }
420
- finally {
421
- await initiatorTracking?.session.detach();
568
+ for (const [page, initiator] of tracking) {
569
+ if (!page.isClosed())
570
+ await initiator.session.detach();
422
571
  }
423
572
  }
424
573
  }
425
- return;
426
- }
427
- try {
428
- await use(page);
429
- }
430
- finally {
431
- try {
432
- await flushPageObserver();
433
- }
434
- finally {
435
- await initiatorTracking?.session.detach();
436
- }
437
- }
438
- },
574
+ }, { auto: Boolean(process.env[ENV_WITNESS_URL]) }],
439
575
  request: async ({ request }, use, testInfo) => {
440
576
  if (!process.env[ENV_WITNESS_URL]) {
441
577
  await use(request);
442
578
  return;
443
579
  }
444
- const appBaseURL = process.env['GATEFORGE_APP_BASE_URL']?.trim();
445
- if (!appBaseURL) {
446
- throw new Error('GATEFORGE_APP_BASE_URL is required for witnessed API traffic.');
447
- }
580
+ const appBaseURL = process.env['GATEFORGE_APP_BASE_URL']?.trim() || projectBaseURL(testInfo);
448
581
  const witness = new WitnessClient();
449
582
  const session = await resolveSessionBounded(witness, testInfo.testId, testInfo.workerIndex, 5_000);
450
583
  if (session === null) {
451
584
  throw new Error(`No supervisor-issued witness session for ${testInfo.testId}.`);
452
585
  }
453
- const directReporter = directExchangeReporterFor(testInfo);
454
- try {
455
- await use(wrapDirectRequestContext(request, {
456
- ...(projectBaseURL(testInfo) === undefined ? {} : { baseURL: projectBaseURL(testInfo) }),
457
- onExchange: (exchange) => directReporter.report(exchange),
458
- }));
459
- }
460
- finally {
461
- await directReporter.settled();
462
- }
586
+ if (session.proxyUrl === null)
587
+ throw new Error(`No session proxy for ${testInfo.testId}.`);
588
+ await use(wrapRequestContext(request, {
589
+ ...(projectBaseURL(testInfo) === undefined ? {} : { baseURL: projectBaseURL(testInfo) }),
590
+ ...(appBaseURL === undefined ? {} : { appBaseURL }),
591
+ sessionProxyUrl: async () => session.proxyUrl,
592
+ }));
463
593
  },
464
594
  surface: async ({}, use) => {
465
595
  await use(undefined);
@@ -535,71 +665,58 @@ function trackedHook(callback) {
535
665
  export const test = withHookTracking(extended);
536
666
  export { expect }; // re-exported so tests never need `playwright/test`
537
667
  /**
538
- * The module-scope `request` of `@gate-forge/pack-playwright/fixture`.
539
- * `newContext(options)` creates a normal Playwright API context with the
540
- * supplied options and never rehosts its calls onto the session proxy.
541
- * App-origin calls made in a test body are reported as direct-API
542
- * diagnostics only; they can never satisfy an E2E claim. Calls made at
543
- * module scope have no owning test and are not reported.
544
- *
545
- * In worker hooks, calls go straight to the app and remain uncredited;
546
- * the first test's session may already be open, but that does not make
547
- * hook traffic test-body evidence.
668
+ * Test-created standalone API contexts use the CURRENT test's session.
669
+ * base.info() throwing detects module/global scope; workerHookDepth detects
670
+ * beforeAll/afterAll even when Playwright already exposes the first test.
671
+ * Contexts created there remain native/direct and never acquire attribution.
548
672
  */
549
673
  export const request = {
550
674
  async newContext(options = {}) {
551
675
  if (!process.env[ENV_WITNESS_URL])
552
676
  return await playwrightRequest.newContext(options);
553
- const appBaseURL = process.env['GATEFORGE_APP_BASE_URL']?.trim();
554
- if (appBaseURL === undefined || appBaseURL === '')
555
- return await playwrightRequest.newContext(options);
556
- const directContext = async (testInfo) => {
557
- // Calls go to the app directly. The project's own base URL rides
558
- // along when the caller gave none, so relative setup calls retain
559
- // the suite's configured resolution.
560
- const fallbackBaseURL = options.baseURL ?? (testInfo === undefined ? undefined : projectBaseURL(testInfo));
561
- const context = await playwrightRequest.newContext(fallbackBaseURL === undefined ? options : { ...options, baseURL: fallbackBaseURL });
562
- return wrapDirectRequestContext(context, {
563
- ...(fallbackBaseURL === undefined ? {} : { baseURL: fallbackBaseURL }),
564
- onExchange: (exchange) => {
565
- let owner = testInfo;
566
- if (owner === undefined) {
567
- try {
568
- owner = base.info();
569
- }
570
- catch {
571
- return;
572
- }
573
- }
574
- directExchangeReporterFor(owner).report(exchange);
575
- },
576
- });
577
- };
578
677
  let testInfo;
579
678
  try {
580
679
  testInfo = base.info();
581
680
  }
582
681
  catch {
583
- // Module scope: no test owns this context.
584
- return await directContext();
585
- }
586
- if (workerHookDepth > 0) {
587
- // A worker hook: setup traffic, never credited — even though the
588
- // first test's session may already be open here.
589
- return await directContext(testInfo);
682
+ return await playwrightRequest.newContext(options);
590
683
  }
684
+ const baseURL = options.baseURL ?? projectBaseURL(testInfo);
685
+ const contextOptions = baseURL === undefined ? options : { ...options, baseURL };
686
+ if (workerHookDepth > 0)
687
+ return await playwrightRequest.newContext(contextOptions);
688
+ const appBaseURL = process.env['GATEFORGE_APP_BASE_URL']?.trim() || projectBaseURL(testInfo);
591
689
  const witness = new WitnessClient();
592
- // Inside a test body the supervisor has already opened (or is
593
- // opening) this test's session: wait the same bound the
594
- // fixtures use. A missing session must NOT fall back to a
595
- // direct context here — that would silently bypass the
596
- // witness for in-test traffic (only module scope and worker
597
- // hooks are setup traffic, which stays uncredited by design).
598
- const session = await resolveSessionBounded(witness, testInfo.testId, testInfo.workerIndex, 5_000);
599
- if (session === null) {
600
- throw new Error(`No supervisor-issued witness session for ${testInfo.testId}.`);
690
+ let owner = testInfo;
691
+ let session = await resolveSessionBounded(witness, owner.testId, owner.workerIndex, 5_000);
692
+ if (session === null || session.proxyUrl === null) {
693
+ throw new Error(`No supervisor-issued witness session proxy for ${owner.testId}.`);
601
694
  }
602
- return await directContext(testInfo);
695
+ const context = await playwrightRequest.newContext(contextOptions);
696
+ return wrapRequestContext(context, {
697
+ ...(baseURL === undefined ? {} : { baseURL }),
698
+ ...(appBaseURL === undefined ? {} : { appBaseURL }),
699
+ ...(options.maxRedirects === undefined ? {} : { maxRedirects: options.maxRedirects }),
700
+ sessionProxyUrl: async () => {
701
+ let current;
702
+ try {
703
+ current = base.info();
704
+ }
705
+ catch {
706
+ return null;
707
+ }
708
+ if (workerHookDepth > 0)
709
+ return null;
710
+ if (current !== owner) {
711
+ owner = current;
712
+ session = await resolveSessionBounded(witness, owner.testId, owner.workerIndex, 5_000);
713
+ }
714
+ if (session === null || session.proxyUrl === null) {
715
+ throw new Error(`No supervisor-issued witness session proxy for ${owner.testId}.`);
716
+ }
717
+ return session.proxyUrl;
718
+ },
719
+ });
603
720
  },
604
721
  };
605
722
  //# sourceMappingURL=fixture.js.map