@broberg/lens-daemon 0.1.60 → 0.1.61

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@broberg/lens-daemon",
3
- "version": "0.1.60",
3
+ "version": "0.1.61",
4
4
  "description": "The Lens module of the cardmem daemon (flows, critic, coverage, capture sessions, the /lens/* routes and the cardmem-lens MCP) as a package. The daemon mounts createLensRouter(deps) + createLensMcpRouter(deps). Bun runtime.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -15,8 +15,8 @@
15
15
  "sharp": "^0.35.5",
16
16
  "turndown": "^7.2.4",
17
17
  "zod": "^3.23.8",
18
- "@broberg/lens-svg": "0.1.1",
19
- "@broberg/lens-engine": "0.14.1"
18
+ "@broberg/lens-engine": "0.14.1",
19
+ "@broberg/lens-svg": "0.1.1"
20
20
  },
21
21
  "devDependencies": {
22
22
  "@happy-dom/global-registrator": "^20.10.6",
@@ -0,0 +1,104 @@
1
+ // F010.17 — a flow sends a request header whose value lives in cardmem's vault, and
2
+ // ONLY to the hosts it names. beacon (F010.5) lets a Lens run past Cloudflare
3
+ // Turnstile on a customer domain with a secret header; the secret must never reach
4
+ // any other host the run touches (a CDN, Cloudflare itself, analytics).
5
+ import type { BrowserContext, Route } from 'playwright';
6
+ import { readSecret } from './secret-fill.ts';
7
+
8
+ export interface FlowHeader { name: string; from: { vault: string }; hosts: string[] }
9
+ export interface ResolvedHeader { name: string; value: string; hosts: Set<string> }
10
+
11
+ const HEADER_NAME = /^[A-Za-z0-9][A-Za-z0-9-]*$/;
12
+ // A bare hostname: no scheme, port, path or wildcard. A listed host is a promise
13
+ // about where the secret goes, so "*.x" or "x:443" is refused rather than guessed at.
14
+ const HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;
15
+
16
+ /** Refused when malformed, never dropped: a dropped header runs the flow without the
17
+ * pass and reports Turnstile as the site failing. */
18
+ export function parseFlowHeaders(input: unknown): FlowHeader[] {
19
+ let h = input;
20
+ if (typeof h === 'string') {
21
+ try {
22
+ h = JSON.parse(h);
23
+ } catch {
24
+ throw new Error('flow.headers was a string but not valid JSON — pass [{name, from: {vault}, hosts: [...]}]');
25
+ }
26
+ }
27
+ if (!Array.isArray(h) || h.length === 0) throw new Error('flow.headers must be a non-empty array of {name, from: {vault: "<secret id>"}, hosts: ["<host>"]}');
28
+ const seen = new Set<string>();
29
+ return h.map((e, i) => {
30
+ const o = e as Record<string, unknown> | null;
31
+ if (!o || typeof o !== 'object' || Array.isArray(o) || Object.keys(o).some((k) => !['name', 'from', 'hosts'].includes(k))) {
32
+ throw new Error(`flow.headers[${i}] must be {name, from: {vault}, hosts} and nothing else`);
33
+ }
34
+ if (typeof o.name !== 'string' || !HEADER_NAME.test(o.name)) throw new Error(`flow.headers[${i}].name must be a header name (letters, digits, dash)`);
35
+ if (seen.has(o.name.toLowerCase())) throw new Error(`flow.headers: "${o.name}" is listed twice`);
36
+ seen.add(o.name.toLowerCase());
37
+ const f = o.from as Record<string, unknown> | null;
38
+ if (!f || typeof f !== 'object' || Array.isArray(f) || Object.keys(f).length !== 1 || typeof f.vault !== 'string' || !f.vault.trim()) {
39
+ throw new Error(`flow.headers[${i}].from must be {vault: "<secret id>"} — a header value only ever comes from the vault`);
40
+ }
41
+ if (!Array.isArray(o.hosts) || o.hosts.length === 0 || !o.hosts.every((x) => typeof x === 'string' && HOST.test(x))) {
42
+ throw new Error(`flow.headers[${i}].hosts must list exact hostnames (e.g. "beacon.broberg.ai") — no scheme, port, path or wildcard`);
43
+ }
44
+ return { name: o.name, from: { vault: f.vault.trim() }, hosts: o.hosts as string[] };
45
+ });
46
+ }
47
+
48
+ /** Read every value once, before the first step. The error names the secret id, never a value. */
49
+ export async function resolveFlowHeaders(headers: FlowHeader[]): Promise<ResolvedHeader[]> {
50
+ const out: ResolvedHeader[] = [];
51
+ for (const h of headers) {
52
+ let value: string;
53
+ try {
54
+ value = await readSecret({ vault: h.from.vault }, undefined);
55
+ } catch (err) {
56
+ const why = err instanceof Error ? err.message.replace(/^fill valueFrom \{vault\}: /, '') : 'error';
57
+ throw new Error(`flow.headers ${h.name}: ${why}`);
58
+ }
59
+ out.push({ name: h.name, value, hosts: new Set(h.hosts) });
60
+ }
61
+ return out;
62
+ }
63
+
64
+ /** The headers this request may carry: only those whose host list holds its EXACT hostname. */
65
+ export function headersFor(url: string, headers: ResolvedHeader[]): Record<string, string> {
66
+ let host: string;
67
+ try {
68
+ host = new URL(url).hostname;
69
+ } catch {
70
+ return {};
71
+ }
72
+ const out: Record<string, string> = {};
73
+ for (const h of headers) if (h.hosts.has(host)) out[h.name] = h.value;
74
+ return out;
75
+ }
76
+
77
+ /**
78
+ * Install on a context. A matching request is fetched with redirects NOT followed and
79
+ * fulfilled with that answer: Playwright carries headers given to continue()/fetch()
80
+ * into every redirect, so a listed host answering 302 → elsewhere would hand the
81
+ * secret to that elsewhere. Unfollowed, the browser makes the redirected request
82
+ * itself, and it comes back through this handler and its host check.
83
+ */
84
+ export async function installFlowHeaders(context: BrowserContext, headers: ResolvedHeader[]): Promise<void> {
85
+ if (headers.length === 0) return;
86
+ await context.route('**/*', async (route: Route) => {
87
+ const req = route.request();
88
+ const extra = headersFor(req.url(), headers);
89
+ if (Object.keys(extra).length === 0) return route.fallback();
90
+ const response = await route.fetch({ headers: { ...req.headers(), ...extra }, maxRedirects: 0 });
91
+ return route.fulfill({ response });
92
+ });
93
+ }
94
+
95
+ /** Wrap a context preparation so the headers go on after it, in every context a run opens. */
96
+ export function withFlowHeaders(
97
+ prepare: ((context: BrowserContext) => Promise<void>) | undefined,
98
+ headers: () => ResolvedHeader[],
99
+ ): ((context: BrowserContext) => Promise<void>) | undefined {
100
+ return async (context) => {
101
+ if (prepare) await prepare(context);
102
+ await installFlowHeaders(context, headers());
103
+ };
104
+ }
package/src/flow.ts CHANGED
@@ -38,6 +38,7 @@ import { fillSecret, getVaultWriter, type VaultReceipt, type VaultTarget } from
38
38
  import { storagePayload, type StorageSeed } from './seed-storage.ts';
39
39
  import { passwordInUrl, type FilledPassword, type PasswordInUrlFinding } from './password-in-url.ts';
40
40
  import { assertTestMailbox, cleanupMail, fillFromMail, httpMailSource, type MailFrom, type MailSource } from './mail-fill.ts';
41
+ import { parseFlowHeaders, resolveFlowHeaders, withFlowHeaders, type FlowHeader, type ResolvedHeader } from './flow-headers.ts';
41
42
  import { approveNumberWithOwner, fillFromOwner, MS_NUMBER_SELECTOR, OWNER_KINDS, OWNER_WAIT_MAX_MS, type OwnerFrom, type OwnerKind } from './owner-fill.ts';
42
43
  import {
43
44
  EDIT_EVENTS,
@@ -220,6 +221,9 @@ export interface Flow {
220
221
  /** F009.141 — a named browser («in <name>:») signs in as its OWN user. Without an
221
222
  * entry it uses the run's auth, as before. */
222
223
  browsers?: Record<string, { auth: AuthConfig }>;
224
+ /** F010.17 — request headers whose value is read from cardmem's vault, sent ONLY to
225
+ * requests whose hostname exactly equals one of `hosts` (every browser of the run). */
226
+ headers?: FlowHeader[];
223
227
  steps: FlowStep[];
224
228
  }
225
229
 
@@ -445,6 +449,8 @@ export interface FlowResult {
445
449
  /** F009.131 — set when auth.persist was asked for: whether the renewed login was
446
450
  * written back to statePath, and why not when it was not. Never a value. */
447
451
  auth_persisted?: { ok: boolean; reason?: string };
452
+ /** F010.17 — the vault headers this run sent and the hosts they were limited to. Never a value. */
453
+ headers?: Array<{ name: string; hosts: string[] }>;
448
454
  /** F010.1 — browsers the daemon reinstalled because their binary was missing. */
449
455
  browser_repaired?: Array<{ engine: string; ms: number }>;
450
456
  /** F010.7 — Chrome code-sign copies Lens removed after this run's browser closed. */
@@ -638,6 +644,7 @@ export function parseFlow(input: unknown): Flow {
638
644
  browsers[name] = { auth: e.auth as AuthConfig };
639
645
  }
640
646
  }
647
+ const headers = f.headers === undefined ? undefined : parseFlowHeaders(f.headers);
641
648
  if (!extension && usesPopup(f.steps as FlowStep[])) {
642
649
  throw new Error('openPopup / in:"popup" need flow.extension — there is no extension loaded to open a popup from');
643
650
  }
@@ -653,6 +660,7 @@ export function parseFlow(input: unknown): Flow {
653
660
  ...(networkShapes ? { network_shapes: networkShapes } : {}),
654
661
  ...(f.passkeys === 'unavailable' || f.passkeys === 'virtual' ? { passkeys: f.passkeys } : {}),
655
662
  ...(browsers ? { browsers } : {}),
663
+ ...(headers ? { headers } : {}),
656
664
  steps: f.steps as FlowStep[],
657
665
  };
658
666
  }
@@ -2887,7 +2895,11 @@ export async function runFlow(flow: Flow, env: AuthEnv, opts: RunFlowOptions = {
2887
2895
  const results: FlowStepResult[] = [];
2888
2896
  const base = flow.base_url.replace(/\/$/, '');
2889
2897
  const from = Math.max(0, opts.from ?? 0);
2890
- const prepare = authPrepare(flow.auth, env);
2898
+ // F010.17 — filled from the vault before the first step; every context the run opens
2899
+ // (default, named browsers, a parallel loop iteration) installs them after its auth.
2900
+ let resolvedHeaders: ResolvedHeader[] = [];
2901
+ const withHeaders = (p: ReturnType<typeof authPrepare>) => (flow.headers ? withFlowHeaders(p, () => resolvedHeaders) : p);
2902
+ const prepare = withHeaders(authPrepare(flow.auth, env));
2891
2903
  // F074.97 — computed ONCE from the flow's own base_url, so every page this run
2892
2904
  // opens (including each parallel loop iteration) seeds the same origin and
2893
2905
  // nothing else. A bad seed throws here, before a browser is launched.
@@ -3034,7 +3046,7 @@ export async function runFlow(flow: Flow, env: AuthEnv, opts: RunFlowOptions = {
3034
3046
  // F009.141 — its own user when the flow names one, else the run's.
3035
3047
  const own = flow.browsers?.[name];
3036
3048
  const closed = withPage(
3037
- { prepareContext: own ? authPrepare(own.auth, env) : prepare, seedStorage, viewport: opts.viewport, engine: opts.engine, locale: opts.locale, timezone: opts.timezone, reducedMotion: opts.reducedMotion },
3049
+ { prepareContext: own ? withHeaders(authPrepare(own.auth, env)) : prepare, seedStorage, viewport: opts.viewport, engine: opts.engine, locale: opts.locale, timezone: opts.timezone, reducedMotion: opts.reducedMotion },
3038
3050
  async (p) => {
3039
3051
  collectFailures(p);
3040
3052
  resolvePage(p);
@@ -3539,6 +3551,26 @@ export async function runFlow(flow: Flow, env: AuthEnv, opts: RunFlowOptions = {
3539
3551
  }
3540
3552
  }
3541
3553
 
3554
+ // F010.17 — read before a browser is launched: a run without the header would meet
3555
+ // Turnstile and report it as the site failing.
3556
+ if (flow.headers) {
3557
+ try {
3558
+ resolvedHeaders = await resolveFlowHeaders(flow.headers);
3559
+ } catch (err) {
3560
+ skipFill(flow.steps, 0, {}, 'skipped — a flow header could not be read from the vault');
3561
+ await prepared?.cleanup();
3562
+ return {
3563
+ name: flow.name,
3564
+ status: 'error',
3565
+ steps: results.sort((a, b) => a.index - b.index),
3566
+ failed_at: 0,
3567
+ reason: err instanceof Error ? err.message : String(err),
3568
+ duration_ms: Date.now() - startedAt,
3569
+ reduced_motion: opts.reducedMotion ?? 'reduce',
3570
+ };
3571
+ }
3572
+ }
3573
+
3542
3574
  try {
3543
3575
  await withPage(
3544
3576
  {
@@ -3588,7 +3620,7 @@ export async function runFlow(flow: Flow, env: AuthEnv, opts: RunFlowOptions = {
3588
3620
  // possibly be authenticated says so instead of producing a confident
3589
3621
  // verdict about a login screen. Only when auth was actually requested:
3590
3622
  // a deliberately anonymous run is not a problem to report.
3591
- if (prepare) {
3623
+ if (flow.auth) {
3592
3624
  try {
3593
3625
  const held = (await context.cookies()).length;
3594
3626
  const applicable = (await context.cookies(base)).length;
@@ -3751,6 +3783,8 @@ export async function runFlow(flow: Flow, env: AuthEnv, opts: RunFlowOptions = {
3751
3783
  // currently-green fleet runs red on the day it ships, and that is its own
3752
3784
  // decision to announce rather than a side effect of this one.
3753
3785
  password_in_url: passwordInUrl(finalUrl, filledPasswords),
3786
+ // F010.17 — which header went where; never its value.
3787
+ ...(flow.headers ? { headers: flow.headers.map((h) => ({ name: h.name, hosts: h.hosts })) } : {}),
3754
3788
  // F074.99 part 1 — the FIRST page that was not listening. Reported on a
3755
3789
  // passing run and never failing it: a plain server-rendered form legitimately
3756
3790
  // has no listener, so a red here would be a regression for every repo that
package/src/mcp.ts CHANGED
@@ -374,6 +374,7 @@ export const TOOLS = [
374
374
  'F255.7 — do not start until the app is serving the build under test. A commit sha waits for THAT build; true waits for any change from the build live at run start. Polls GET /api/health for a `build` field (the fleet contract), from the runner with no-store, requiring 3 consecutive matching reads so a fleet mid-rollout cannot end the wait early. Fails loudly if the app exposes no marker. Use it right after a deploy — otherwise a green run may be verifying the build you just replaced.',
375
375
  },
376
376
  auth: authSchema,
377
+ headers: { type: ['array', 'string'], description: 'F010.17 — [{name, from: {vault: "<secret id>"}, hosts: ["<exact hostname>"]}]: a request header whose value the DAEMON reads from cardmem\'s vault, sent ONLY to requests whose hostname exactly equals a listed host (no subdomains, no wildcards), in every browser of the run. A redirect from a listed host to another host does not carry it. The report lists name + hosts, never the value. A vault read failure ends the run before step 1. Use: a site-owned pass (e.g. beacon\'s Turnstile header) on beacon.broberg.ai + firstcoat.gallery. A service worker\'s own fetches are not covered.' },
377
378
  browsers: {
378
379
  type: 'object',
379
380
  description:
@@ -432,6 +433,7 @@ export const TOOLS = [
432
433
  timezone: timezoneSchema,
433
434
  reduced_motion: reducedMotionSchema,
434
435
  storage: storageSchema,
436
+ headers: { type: ['array', 'string'], description: 'F010.17 — [{name, from: {vault: "<secret id>"}, hosts: ["<exact hostname>"]}]: a request header whose value the DAEMON reads from cardmem\'s vault, sent ONLY to requests whose hostname exactly equals a listed host (no subdomains, no wildcards), in every browser of the run. A redirect from a listed host to another host does not carry it. The report lists name + hosts, never the value. A vault read failure ends the run before step 1. Use: a site-owned pass (e.g. beacon\'s Turnstile header) on beacon.broberg.ai + firstcoat.gallery. A service worker\'s own fetches are not covered.' },
435
437
  browsers: {
436
438
  type: 'object',
437
439
  description:
package/src/service.ts CHANGED
@@ -33,6 +33,7 @@ import {
33
33
  listBaselineVersions,
34
34
  revertBaseline,
35
35
  } from './store.ts';
36
+ import { parseFlowHeaders } from './flow-headers.ts';
36
37
  import { runFlow, parseFlow, parseRunBrowser, compileManuscript, type Flow, type FlowResult, type FlowStepResult } from './flow.ts';
37
38
  // F074.24 — the daemon HOSTS the engine's own runFlow for flat cloud-shape
38
39
  // FlowRequests (one wire-shape, driven via @broberg/lens-client). The engine
@@ -1001,6 +1002,8 @@ export async function lensRunFlow(deps: LensDeps, input: RunFlowInput) {
1001
1002
 
1002
1003
  export interface RunManuscriptInput {
1003
1004
  project: string;
1005
+ /** F010.17 — vault headers limited to named hosts (see Flow.headers). */
1006
+ headers?: unknown;
1004
1007
  /** Markdown manuscript — compiled to a flow then executed. */
1005
1008
  manuscript: string;
1006
1009
  /** F074.36 — an explicit auth block, same shape lens_run_flow takes. The prose
@@ -1063,6 +1066,8 @@ export async function lensRunManuscript(deps: LensDeps, input: RunManuscriptInpu
1063
1066
  flow.browsers = parseFlow({ name: flow.name, base_url: flow.base_url, steps: [{ type: 'goto', path: '/' }], browsers: input.browsers }).browsers;
1064
1067
  }
1065
1068
  resolveBrowserAuths(flow, input.local_path, deps.sandboxRoots);
1069
+ // F010.17 — no header line in the manuscript language either; the call carries it.
1070
+ if (input.headers !== undefined) flow.headers = parseFlowHeaders(input.headers);
1066
1071
  const result = await runFlow(flow, process.env as AuthEnv, {
1067
1072
  engine: input.engine,
1068
1073
  ...resolveLocale(input, manifestLocale(input.local_path, deps.sandboxRoots)),