@broberg/lens-daemon 0.1.53 → 0.1.56

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.53",
3
+ "version": "0.1.56",
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-engine": "0.14.1",
19
- "@broberg/lens-svg": "0.1.1"
18
+ "@broberg/lens-svg": "0.1.1",
19
+ "@broberg/lens-engine": "0.14.1"
20
20
  },
21
21
  "devDependencies": {
22
22
  "@happy-dom/global-registrator": "^20.10.6",
package/src/flow.ts CHANGED
@@ -26,7 +26,8 @@ import {
26
26
  import { takeBrowserRepairs, withPage, type LensEngine, type RunBrowser } from './browser.ts';
27
27
  import { takeChromeClonesRemoved } from './chrome-clones.ts';
28
28
  import { collectNetworkShapes, type NetworkShapesOptions, type NetworkShapesReport } from './network-shapes.ts';
29
- import { passkeysUnavailableInPage } from './passkeys.ts';
29
+ import { passkeysUnavailableInPage, virtualPasskeys, VIRTUAL_PASSKEYS_NEED_CHROMIUM } from './passkeys.ts';
30
+ import { redactInspect } from './inspect-redact.ts';
30
31
  import { deadline, defaultPopupOf, prepareExtension, seedExtensionStorage, SIMULATED_ACCESS_NOTE } from './extension-flow.ts';
31
32
  import { authPrepare, fetchMintJson, persistStorageState, persistTarget, type AuthConfig, type AuthEnv } from './auth/index.ts';
32
33
  import { takeShot, settleForShot } from './capture.ts';
@@ -207,8 +208,11 @@ export interface Flow {
207
208
  * fetch/xhr request + response bodies and WebSocket frames. */
208
209
  network_shapes?: true | NetworkShapesOptions;
209
210
  /** F010.10 — "unavailable": the page sees a browser without passkeys, so a site
210
- * that offers passkey first falls back to a code or the password. */
211
- passkeys?: 'unavailable';
211
+ * that offers passkey first falls back to a code or the password.
212
+ * F010.13 — "virtual": the browser holds a virtual authenticator that creates and
213
+ * uses passkeys by itself (no dialog), on every page of the run incl. popups.
214
+ * The passkey lives only for the run. Chromium only. */
215
+ passkeys?: 'unavailable' | 'virtual';
212
216
  steps: FlowStep[];
213
217
  }
214
218
 
@@ -596,8 +600,8 @@ export function parseFlow(input: unknown): Flow {
596
600
  throw new Error('flow.network_shapes must be true or {hosts?: ["<host>"], reveal?: ["<key>"]}');
597
601
  }
598
602
  }
599
- if (f.passkeys !== undefined && f.passkeys !== 'unavailable') {
600
- throw new Error('flow.passkeys must be "unavailable" (or left out)');
603
+ if (f.passkeys !== undefined && f.passkeys !== 'unavailable' && f.passkeys !== 'virtual') {
604
+ throw new Error('flow.passkeys must be "unavailable" or "virtual" (or left out)');
601
605
  }
602
606
  if (!extension && usesPopup(f.steps as FlowStep[])) {
603
607
  throw new Error('openPopup / in:"popup" need flow.extension — there is no extension loaded to open a popup from');
@@ -612,7 +616,7 @@ export function parseFlow(input: unknown): Flow {
612
616
  ...(extension ? { extension } : {}),
613
617
  ...(browser ? { browser } : {}),
614
618
  ...(networkShapes ? { network_shapes: networkShapes } : {}),
615
- ...(f.passkeys === 'unavailable' ? { passkeys: 'unavailable' as const } : {}),
619
+ ...(f.passkeys === 'unavailable' || f.passkeys === 'virtual' ? { passkeys: f.passkeys } : {}),
616
620
  steps: f.steps as FlowStep[],
617
621
  };
618
622
  }
@@ -3085,7 +3089,8 @@ export async function runFlow(flow: Flow, env: AuthEnv, opts: RunFlowOptions = {
3085
3089
  ? await expectRequest(step, vars)
3086
3090
  : await execStep(sp, step, base, vars, opts.critic ?? 'off', opts.localPath, sink, filledPasswords, notListening, opts.secretRoot, mailCtx);
3087
3091
  const obj = out !== null && !Buffer.isBuffer(out) && typeof out === 'object' ? out : null;
3088
- const inspect = obj && '__inspect' in obj ? (obj as { __inspect: string }).__inspect : null;
3092
+ // F010.14 — never a password in the report, whatever the page keeps in its attributes.
3093
+ const inspect = obj && '__inspect' in obj ? redactInspect((obj as { __inspect: string }).__inspect, filledPasswords) : null;
3089
3094
  const via = obj && '__via' in obj ? (obj as { __via: string }).__via : null;
3090
3095
  // F074.30 — a waitForBuild step KNOWS the live sha; it wins over the
3091
3096
  // best-effort read taken before driving.
@@ -3394,6 +3399,22 @@ export async function runFlow(flow: Flow, env: AuthEnv, opts: RunFlowOptions = {
3394
3399
  }
3395
3400
  };
3396
3401
 
3402
+ // F010.13 — refused before a browser is launched: another engine has no CDP
3403
+ // WebAuthn, and a run without the authenticator would look like the site failing.
3404
+ if (flow.passkeys === 'virtual' && opts.engine && opts.engine !== 'chromium') {
3405
+ skipFill(flow.steps, 0, {}, 'skipped — passkeys:"virtual" cannot run on this engine');
3406
+ await prepared?.cleanup();
3407
+ return {
3408
+ name: flow.name,
3409
+ status: 'error',
3410
+ steps: results.sort((a, b) => a.index - b.index),
3411
+ failed_at: 0,
3412
+ reason: `${VIRTUAL_PASSKEYS_NEED_CHROMIUM} (engine: ${opts.engine})`,
3413
+ duration_ms: Date.now() - startedAt,
3414
+ reduced_motion: opts.reducedMotion ?? 'reduce',
3415
+ };
3416
+ }
3417
+
3397
3418
  // F255.7 — gate the WHOLE run on the build under test actually serving, BEFORE a browser
3398
3419
  // is even launched. A flow that verifies the previous build is the most expensive kind of
3399
3420
  // green: it exercises real behaviour, so nothing in the report looks wrong.
@@ -3436,6 +3457,13 @@ export async function runFlow(flow: Flow, env: AuthEnv, opts: RunFlowOptions = {
3436
3457
  videoPage = page;
3437
3458
  if (flow.network_shapes) shapesRef.c = collectNetworkShapes(context, flow.network_shapes === true ? {} : flow.network_shapes);
3438
3459
  if (flow.passkeys === 'unavailable') await context.addInitScript(passkeysUnavailableInPage);
3460
+ if (flow.passkeys === 'virtual') {
3461
+ const vp = await virtualPasskeys(context);
3462
+ await vp.attach(page);
3463
+ context.on('page', (p) => {
3464
+ vp.attach(p).catch((e: unknown) => console.error(`[lens/flow] ${flow.name}: no virtual authenticator on an opened page: ${e instanceof Error ? e.message : String(e)}`));
3465
+ });
3466
+ }
3439
3467
  collectFailures(page);
3440
3468
  watchRequests(context);
3441
3469
  watchDownloads(context);
@@ -0,0 +1,55 @@
1
+ // lens F010.14 — an inspect report never carries a password.
2
+ //
3
+ // jam (#44821, run 13f7f1b5): Google keeps what was typed into its password field in
4
+ // the attribute data-initial-value, and `inspect` copied the field's outerHTML into
5
+ // the run report — the owner's Google password stood there in plain text. A password
6
+ // input masks itself on screen; its attributes do not.
7
+ //
8
+ // Applied to every inspect result before it reaches the report, on the server, so it
9
+ // holds for both forms (the anchor dump and `html:true`) whatever the page does:
10
+ // 1. a password-like <input> loses its value and every data-* attribute but
11
+ // data-testid (the anchor an author needs);
12
+ // 2. an <input> tag the 400-char cut left unterminated is treated the same — its
13
+ // type may be the part that was cut away;
14
+ // 3. every value Lens itself typed from a secret (vault / file, or a typed password)
15
+ // is replaced wherever it appears, whatever attribute or text holds it.
16
+ import type { FilledPassword } from './password-in-url.ts';
17
+
18
+ export const REDACTED = '[redacted]';
19
+
20
+ const SECRET_INPUT = /\btype\s*=\s*"password"|\bautocomplete\s*=\s*"[^"]*(?:password|one-time-code)[^"]*"/i;
21
+ const VALUE_ATTRS = /\s(?:value|data-(?!testid\b)[\w.:-]+)\s*=\s*"[^"]*"?/gi;
22
+
23
+ function scrubHtml(html: string): string {
24
+ return html.replace(/<input\b[^>]*(?:>|$)/gi, (tag) =>
25
+ SECRET_INPUT.test(tag) || !tag.endsWith('>') ? tag.replace(VALUE_ATTRS, '') : tag,
26
+ );
27
+ }
28
+
29
+ export function redactInspect(raw: string, filled: readonly FilledPassword[]): string {
30
+ let out = raw;
31
+ try {
32
+ const dump = JSON.parse(raw) as Record<string, unknown>;
33
+ if (dump && typeof dump === 'object' && ('inputs' in dump || 'clickables' in dump)) {
34
+ for (const key of ['inputs', 'clickables'] as const) {
35
+ const list = dump[key];
36
+ if (!Array.isArray(list)) continue;
37
+ for (const e of list as Array<{ html?: unknown }>) if (typeof e.html === 'string') e.html = scrubHtml(e.html);
38
+ }
39
+ out = JSON.stringify(dump);
40
+ } else out = scrubHtml(raw);
41
+ } catch {
42
+ out = scrubHtml(raw);
43
+ }
44
+ for (const { value } of filled) {
45
+ if (value.length < 4) continue; // a 1–3 character value would blank half the page
46
+ // The same secret in every spelling a report can hold it: raw, as the browser
47
+ // serialises it into an attribute (& → &amp; — measured: a password with & was
48
+ // missed), and each of those inside a JSON string.
49
+ const html = value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/\u00a0/g, '&nbsp;');
50
+ for (const form of new Set([value, html, JSON.stringify(value).slice(1, -1), JSON.stringify(html).slice(1, -1)])) {
51
+ out = out.split(form).join(REDACTED);
52
+ }
53
+ }
54
+ return out;
55
+ }
package/src/mcp.ts CHANGED
@@ -380,6 +380,12 @@ export const TOOLS = [
380
380
  description:
381
381
  'F009.133 — true or {hosts?:["<host>"], reveal?:["<key>"]}: record the SHAPE (keys, types, string lengths — never a value) of every fetch/xhr call to the page\'s own host (+ hosts): method, path, query keys, status, request-body and response-body shape (JSON, Google )]}\' chunks, SSE, form, SignalR), plus every WebSocket frame. Other hosts are only counted. reveal keeps the value of those named keys (e.g. "rpcids", "target"). The report lands as an artifact; findings.network_shapes carries counts + url.',
382
382
  },
383
+ passkeys: {
384
+ type: 'string',
385
+ enum: ['unavailable', 'virtual'],
386
+ description:
387
+ 'F010.10 "unavailable": the page sees a browser WITHOUT passkeys (create/get with publicKey reject NotAllowedError at once), so a site that offers passkey first falls back to a code or the password. F010.13 "virtual": the browser holds a virtual authenticator (CDP WebAuthn, ctap2, resident key, user verification) that creates and uses passkeys by itself, no dialog, on every page of the run incl. windows the page opens; a sign-up that offers only «Create with passkey» can then be driven end to end. The passkey lives only for the run. Chromium only (another engine is refused). Serve local test pages as localhost, not an IP: an IP is not a valid passkey RP ID.',
388
+ },
383
389
  extension: {
384
390
  type: 'object',
385
391
  required: ['path'],
package/src/passkeys.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { BrowserContext, CDPSession, Page } from 'playwright';
2
+
1
3
  // F010.10 — a flow can say «this browser has no passkeys».
2
4
  //
3
5
  // A passkey request opens a system dialog a Lens browser cannot answer, so a site
@@ -24,3 +26,75 @@ export function passkeysUnavailableInPage(): void {
24
26
  pkc.isConditionalMediationAvailable = () => Promise.resolve(false);
25
27
  }
26
28
  }
29
+
30
+ // F010.13 — a flow can hold a test passkey.
31
+ //
32
+ // jam-F001.66 needs a brand-new BID account per run, and id.broberg.ai/create
33
+ // offers only «Create with passkey» (Lens run e8a0396e). This gives the run a CDP
34
+ // virtual authenticator, so the site's create()/get() are answered by the browser
35
+ // itself — no dialog, no human. The passkey lives only for the run.
36
+ //
37
+ // A virtual authenticator belongs to ONE page. Every page of the context gets its
38
+ // own, seeded with the passkeys made so far, and a passkey made on any page is
39
+ // copied to the others at once — so a sign-in that moves into a popup (or back)
40
+ // still finds it. Chromium only: CDP WebAuthn does not exist elsewhere.
41
+ type Cred = { credentialId: string };
42
+
43
+ const AUTHENTICATOR = {
44
+ protocol: 'ctap2',
45
+ transport: 'internal',
46
+ hasResidentKey: true,
47
+ hasUserVerification: true,
48
+ isUserVerified: true,
49
+ automaticPresenceSimulation: true,
50
+ } as const;
51
+
52
+ export const VIRTUAL_PASSKEYS_NEED_CHROMIUM = 'passkeys:"virtual" needs Chromium (CDP WebAuthn) — this engine has no virtual authenticator';
53
+
54
+ // A window the page opens can ask for a passkey before its authenticator is attached
55
+ // (measured: NotSupportedError in the popup test). So the page's passkey calls wait
56
+ // until Lens says THIS page has one — at most 5 s, then the browser answers as is.
57
+ // Self-contained, like passkeysUnavailableInPage.
58
+ export function waitForAuthenticatorInPage(): void {
59
+ const creds = navigator.credentials as CredentialsContainer | undefined;
60
+ const ready = (globalThis as unknown as { __lensPasskeyReady?: () => Promise<boolean> }).__lensPasskeyReady;
61
+ if (!creds || !ready) return;
62
+ const until = async () => {
63
+ for (let i = 0; i < 50 && !(await ready()); i++) await new Promise((r) => setTimeout(r, 100));
64
+ };
65
+ const get = creds.get.bind(creds);
66
+ const create = creds.create.bind(creds);
67
+ creds.get = async (o?: CredentialRequestOptions) => { if (o && 'publicKey' in o) await until(); return get(o); };
68
+ creds.create = async (o?: CredentialCreationOptions) => { if (o && 'publicKey' in o) await until(); return create(o); };
69
+ }
70
+
71
+ export async function virtualPasskeys(context: BrowserContext): Promise<{ attach: (page: Page) => Promise<void> }> {
72
+ const creds = new Map<string, Cred>();
73
+ const live: Array<{ cdp: CDPSession; id: string; page: Page }> = [];
74
+ const ready = new Set<Page>();
75
+ await context.exposeBinding('__lensPasskeyReady', ({ page }) => ready.has(page));
76
+ await context.addInitScript(waitForAuthenticatorInPage);
77
+ const attach = async (page: Page): Promise<void> => {
78
+ let cdp: CDPSession;
79
+ try {
80
+ cdp = await context.newCDPSession(page);
81
+ } catch (err) {
82
+ throw new Error(`${VIRTUAL_PASSKEYS_NEED_CHROMIUM} (${err instanceof Error ? err.message : String(err)})`);
83
+ }
84
+ await cdp.send('WebAuthn.enable', { enableUI: false });
85
+ const { authenticatorId: id } = await cdp.send('WebAuthn.addVirtualAuthenticator', { options: AUTHENTICATOR });
86
+ for (const credential of creds.values()) await cdp.send('WebAuthn.addCredential', { authenticatorId: id, credential: credential as never });
87
+ cdp.on('WebAuthn.credentialAdded', ({ credential }) => {
88
+ creds.set(credential.credentialId, credential);
89
+ for (const o of live) {
90
+ if (o.id === id || o.page.isClosed()) continue;
91
+ o.cdp.send('WebAuthn.addCredential', { authenticatorId: o.id, credential }).catch((e: unknown) =>
92
+ console.error(`[lens/passkeys] copying a new passkey to another page failed: ${e instanceof Error ? e.message : String(e)}`));
93
+ }
94
+ });
95
+ cdp.on('WebAuthn.credentialAsserted', ({ credential }) => creds.set(credential.credentialId, credential));
96
+ live.push({ cdp, id, page });
97
+ ready.add(page);
98
+ };
99
+ return { attach };
100
+ }