@broberg/lens-daemon 0.1.62 → 0.1.65

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.62",
3
+ "version": "0.1.65",
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,9 +15,9 @@
15
15
  "sharp": "^0.35.5",
16
16
  "turndown": "^7.2.4",
17
17
  "zod": "^3.23.8",
18
- "@broberg/lens-measure": "0.1.0",
19
18
  "@broberg/lens-engine": "0.14.1",
20
- "@broberg/lens-svg": "0.1.1"
19
+ "@broberg/lens-svg": "0.1.1",
20
+ "@broberg/lens-measure": "0.1.2"
21
21
  },
22
22
  "devDependencies": {
23
23
  "@happy-dom/global-registrator": "^20.10.6",
@@ -150,25 +150,46 @@ type Installer = (names: string[]) => Promise<{ ok: boolean; error?: string }>;
150
150
 
151
151
  const INSTALL_TIMEOUT_MS = 10 * 60_000;
152
152
 
153
- const spawnInstaller: Installer = (names) =>
154
- new Promise((resolve) => {
155
- let cliPath: string;
156
- try {
157
- cliPath = resolvePlaywrightCli();
158
- } catch (err) {
159
- resolve({ ok: false, error: `cannot resolve playwright CLI: ${err instanceof Error ? err.message : String(err)}` });
160
- return;
161
- }
162
- console.log(`[lens] browser missing — installing ${names.join(', ')} via ${cliPath} …`);
163
- const child = spawn(process.execPath, [cliPath, 'install', ...names], { stdio: 'inherit', env: process.env });
153
+ /** F010.18 — the installer's own reason, not just its exit code: «exited 1» sent
154
+ * components to ask for a repair of WebKit on a macOS Playwright does not support.
155
+ * Output still reaches the daemon log; the last ERROR line also reaches the run. */
156
+ export function runInstallProcess(cmd: string, args: string[], timeoutMs = INSTALL_TIMEOUT_MS): Promise<{ ok: boolean; error?: string }> {
157
+ return new Promise((resolve) => {
158
+ const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'], env: process.env });
159
+ const tail: string[] = [];
160
+ const keep = (chunk: Buffer, to: NodeJS.WriteStream) => {
161
+ to.write(chunk);
162
+ for (const line of chunk.toString('utf8').split(/\r?\n/)) if (line.trim()) tail.push(line.trim());
163
+ if (tail.length > 40) tail.splice(0, tail.length - 40);
164
+ };
165
+ child.stdout.on('data', (c: Buffer) => keep(c, process.stdout));
166
+ child.stderr.on('data', (c: Buffer) => keep(c, process.stderr));
167
+ const why = () => [...tail].reverse().find((l) => /error/i.test(l)) ?? tail[tail.length - 1];
164
168
  // A download that stalls must not hold every run waiting on it forever.
165
169
  const timer = setTimeout(() => {
166
170
  child.kill('SIGKILL');
167
- resolve({ ok: false, error: `playwright install did not finish within ${INSTALL_TIMEOUT_MS / 60_000} min` });
168
- }, INSTALL_TIMEOUT_MS);
171
+ resolve({ ok: false, error: `playwright install did not finish within ${timeoutMs / 60_000} min` });
172
+ }, timeoutMs);
169
173
  child.on('error', (err) => { clearTimeout(timer); resolve({ ok: false, error: err.message }); });
170
- child.on('exit', (code) => { clearTimeout(timer); resolve(code === 0 ? { ok: true } : { ok: false, error: `playwright install exited ${code}` }); });
174
+ child.on('close', (code) => {
175
+ clearTimeout(timer);
176
+ if (code === 0) return resolve({ ok: true });
177
+ const reason = why();
178
+ resolve({ ok: false, error: `playwright install exited ${code}${reason ? `: ${reason.slice(0, 200)}` : ''}` });
179
+ });
171
180
  });
181
+ }
182
+
183
+ const spawnInstaller: Installer = (names) => {
184
+ let cliPath: string;
185
+ try {
186
+ cliPath = resolvePlaywrightCli();
187
+ } catch (err) {
188
+ return Promise.resolve({ ok: false, error: `cannot resolve playwright CLI: ${err instanceof Error ? err.message : String(err)}` });
189
+ }
190
+ console.log(`[lens] browser missing — installing ${names.join(', ')} via ${cliPath} …`);
191
+ return runInstallProcess(process.execPath, [cliPath, 'install', ...names]);
192
+ };
172
193
 
173
194
  let installer: Installer = spawnInstaller;
174
195
  /** Test seam: replace the installer (null restores the real one). */
package/src/flow-store.ts CHANGED
@@ -189,6 +189,8 @@ export async function recordFlowRun(
189
189
  ...(result.mail ? { mail: result.mail } : {}),
190
190
  ...(result.browser_repaired ? { browser_repaired: result.browser_repaired } : {}),
191
191
  ...(result.chrome_clones_removed ? { chrome_clones_removed: result.chrome_clones_removed } : {}),
192
+ // F010.3 — the profile's login was last seen expired.
193
+ ...(result.profile_signed_out ? { profile_signed_out: result.profile_signed_out } : {}),
192
194
  }),
193
195
  };
194
196
 
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 { profileSignedOut } from './profile-watch.ts';
41
42
  import { parseFlowHeaders, resolveFlowHeaders, withFlowHeaders, type FlowHeader, type ResolvedHeader } from './flow-headers.ts';
42
43
  import { approveNumberWithOwner, fillFromOwner, MS_NUMBER_SELECTOR, OWNER_KINDS, OWNER_WAIT_MAX_MS, type OwnerFrom, type OwnerKind } from './owner-fill.ts';
43
44
  import {
@@ -449,6 +450,8 @@ export interface FlowResult {
449
450
  /** F009.131 — set when auth.persist was asked for: whether the renewed login was
450
451
  * written back to statePath, and why not when it was not. Never a value. */
451
452
  auth_persisted?: { ok: boolean; reason?: string };
453
+ /** F010.3 — the kept profile this run used was last checked signed_out. */
454
+ profile_signed_out?: { profile: string; checked_at: string };
452
455
  /** F010.17 — the vault headers this run sent and the hosts they were limited to. Never a value. */
453
456
  headers?: Array<{ name: string; hosts: string[] }>;
454
457
  /** F010.1 — browsers the daemon reinstalled because their binary was missing. */
@@ -3785,6 +3788,8 @@ export async function runFlow(flow: Flow, env: AuthEnv, opts: RunFlowOptions = {
3785
3788
  password_in_url: passwordInUrl(finalUrl, filledPasswords),
3786
3789
  // F010.17 — which header went where; never its value.
3787
3790
  ...(flow.headers ? { headers: flow.headers.map((h) => ({ name: h.name, hosts: h.hosts })) } : {}),
3791
+ // F010.3 — a red run on an expired login says so, instead of looking like the app.
3792
+ ...(() => { const so = profileSignedOut(flow.browser?.profile); return so ? { profile_signed_out: so } : {}; })(),
3788
3793
  // F074.99 part 1 — the FIRST page that was not listening. Reported on a
3789
3794
  // passing run and never failing it: a plain server-rendered form legitimately
3790
3795
  // has no listener, so a red here would be a regression for every repo that
package/src/http.ts CHANGED
@@ -36,6 +36,10 @@ import { backfillFromDisk } from './artifact-backfill.ts';
36
36
  import { artifactContentType } from './storage.ts';
37
37
  import { localRequestGuard } from './local-guard.ts';
38
38
  import { measureRequest, MeasureBodyError } from './measure-local.ts';
39
+ import { checkProfile, flowLooker, listProfiles, setProbe, setProfileNotifier, startProfileWatch } from './profile-watch.ts';
40
+
41
+ /** F010.3 — the cardmem project Lens's own mail to the owner is filed under. */
42
+ const LENS_CARDMEM_PROJECT = '01a12d2d-868b-76b7-a316-b32f71fe5415';
39
43
 
40
44
  export function createLensRouter(deps: LensDeps): Hono {
41
45
  const r = new Hono();
@@ -64,6 +68,19 @@ export function createLensRouter(deps: LensDeps): Hono {
64
68
  if (typeof r?.id !== 'string' || !r.id) throw new Error('cardmem did not return a secret id — nothing confirmed stored');
65
69
  return { secret_id: r.id, name: typeof r.name === 'string' ? r.name : t.name, preview: typeof r.preview === 'string' ? r.preview : '' };
66
70
  });
71
+ // F010.3 — an expired login is told to the owner once, through cardmem's own mail
72
+ // to him (the recipient is fixed; nothing else can be addressed).
73
+ setProfileNotifier(async ({ profile, url, reason }) => {
74
+ const cloud = deps.cloud?.();
75
+ if (!cloud) throw new Error('not signed in to cardmem');
76
+ const r = await cloud.callTool<{ sent?: boolean; skipped?: boolean }>('cardmem_mail_owner', {
77
+ project_id: LENS_CARDMEM_PROJECT,
78
+ subject: `Lens: login i browserprofilen «${profile}» er udløbet`,
79
+ markdown: `Lens' gemte login i profilen **${profile}** er ikke længere logget ind (tjekket mod ${url}${reason ? ` — ${reason}` : ''}).\n\nKørsler, der bruger profilen, vil fejle på login, indtil den er fornyet. Lens kan ikke selv logge profilen ind igen endnu (det kommer med F010.9), og du skal ikke gøre noget i et browservindue: når fornyelsen findes, beder Lens om koden i ARS. Du får kun denne ene besked, indtil profilen er logget ind igen.`,
80
+ });
81
+ if (!r?.sent) throw new Error(r?.skipped ? 'the mailer held it back (skipped)' : 'cardmem did not confirm the mail was sent');
82
+ });
83
+ if (process.env.NODE_ENV !== 'test') startProfileWatch(flowLooker);
67
84
  // lens F001.5 — the routes that used to be registered one by one in the
68
85
  // daemon's index.ts. First, so their specific paths win as they did there.
69
86
  registerDaemonRoutes(r, deps);
@@ -89,6 +106,18 @@ export function createLensRouter(deps: LensDeps): Hono {
89
106
  return c.json({ error: err instanceof Error ? err.message : 'measure failed' }, err instanceof MeasureBodyError ? 400 : 502);
90
107
  }
91
108
  });
109
+ // F010.3 — kept profiles and their login probes.
110
+ r.get('/profiles', (c) => c.json({ ok: true, profiles: listProfiles() }));
111
+ const profileRoute = (fn: (name: string, body: unknown) => Promise<unknown> | unknown) => async (c: import('hono').Context) => {
112
+ const body = await c.req.json().catch(() => ({}));
113
+ try {
114
+ return c.json({ ok: true, ...((await fn(c.req.param('name') ?? '', body)) as object) });
115
+ } catch (err) {
116
+ return c.json({ ok: false, error: err instanceof Error ? err.message : String(err) }, 400);
117
+ }
118
+ };
119
+ r.post('/profiles/:name/probe', profileRoute((name, body) => ({ probe: setProbe(name, body) })));
120
+ r.post('/profiles/:name/check', profileRoute(async (name) => ({ result: await checkProfile(name, flowLooker) })));
92
121
  r.post('/capture', handle((body) => lensCapture(deps, body as Parameters<typeof lensCapture>[1])));
93
122
  r.post('/verify', handle((body) => lensVerify(deps, body as Parameters<typeof lensVerify>[1])));
94
123
  // F074.63 — the export verb beside capture. Same pipeline, one terminal call
@@ -0,0 +1,148 @@
1
+ // F010.3 — a login that expires is noticed before a run needs it. Each kept profile
2
+ // (F009.132/136) can carry a probe: a URL and how to tell "signed in" there. The
3
+ // daemon checks every probed profile on a timer, read-only (goto + look, never a
4
+ // click or a fill), and tells the owner ONCE when a profile goes from signed in to
5
+ // signed out. A run on a profile whose last check was signed_out says so.
6
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ import { listProfileNames, profileChannel, profileDir } from './profiles.ts';
9
+ import { runFlow, type Flow } from './flow.ts';
10
+
11
+ export type SignedIn = { selector: string } | { url_excludes: string };
12
+ export interface Probe { url: string; signed_in: SignedIn }
13
+ export type ProbeStateName = 'signed_in' | 'signed_out' | 'unknown';
14
+ export interface ProbeState { state: ProbeStateName; checked_at: string; reason?: string; notified_at?: string }
15
+
16
+ const PROBE = '.lens-probe.json';
17
+ const STATE = '.lens-probe-state.json';
18
+
19
+ /** Refused when malformed, never dropped: a probe that silently checks nothing
20
+ * would report "signed in" forever. */
21
+ export function parseProbe(input: unknown): Probe {
22
+ const o = input as Record<string, unknown> | null;
23
+ if (!o || typeof o !== 'object' || Array.isArray(o) || Object.keys(o).some((k) => k !== 'url' && k !== 'signed_in')) {
24
+ throw new Error('probe must be {url, signed_in: {selector} | {url_excludes}}');
25
+ }
26
+ // https only, except a loopback page (tests, a local app) — a probe never sends a login over plain http.
27
+ if (typeof o.url !== 'string' || !(/^https:\/\//.test(o.url) || /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?\//.test(o.url))) {
28
+ throw new Error('probe.url must be an https URL (or http on localhost)');
29
+ }
30
+ const s = o.signed_in as Record<string, unknown> | null;
31
+ const keys = s && typeof s === 'object' && !Array.isArray(s) ? Object.keys(s) : [];
32
+ if (keys.length !== 1 || (keys[0] !== 'selector' && keys[0] !== 'url_excludes') || typeof s![keys[0]] !== 'string' || !(s![keys[0]] as string).trim()) {
33
+ throw new Error('probe.signed_in must be exactly one of {selector: "<css present when signed in>"} or {url_excludes: "<part of the login url>"}');
34
+ }
35
+ return { url: o.url, signed_in: { [keys[0]!]: (s![keys[0]!] as string).trim() } as SignedIn };
36
+ }
37
+
38
+ const readJson = <T>(path: string): T | null => {
39
+ if (!existsSync(path)) return null;
40
+ try {
41
+ return JSON.parse(readFileSync(path, 'utf8')) as T;
42
+ } catch {
43
+ return null;
44
+ }
45
+ };
46
+
47
+ export function setProbe(name: string, input: unknown): Probe {
48
+ const probe = parseProbe(input);
49
+ if (!profileChannel(name)) throw new Error(`browser profile "${name}" has never been used — there is no login in it to watch`);
50
+ writeFileSync(join(profileDir(name), PROBE), JSON.stringify(probe, null, 2), { mode: 0o600 });
51
+ return probe;
52
+ }
53
+
54
+ export const readProbe = (name: string) => readJson<Probe>(join(profileDir(name), PROBE));
55
+ export const readProbeState = (name: string) => readJson<ProbeState>(join(profileDir(name), STATE));
56
+
57
+ export function listProfiles() {
58
+ return listProfileNames().map((name) => ({ name, channel: profileChannel(name), probe: readProbe(name), last: readProbeState(name) }));
59
+ }
60
+
61
+ /** One look at the profile. Injected so the check itself is testable without the
62
+ * timer, and so it reuses runFlow (claim, build marker, launch) instead of a copy. */
63
+ export type Looker = (name: string, probe: Probe) => Promise<{ state: ProbeStateName; reason?: string }>;
64
+ export type Notifier = (msg: { profile: string; url: string; reason?: string }) => Promise<void>;
65
+
66
+ let notifier: Notifier | null = null;
67
+ export function setProfileNotifier(fn: Notifier | null): void {
68
+ notifier = fn;
69
+ }
70
+
71
+ /** Check one profile and persist the result. The owner hears it on the TRANSITION
72
+ * to signed_out only — a profile that stays signed out is silent, and a recovery
73
+ * followed by a new expiry is a new transition. `unknown` (in use, browser error)
74
+ * never notifies and never resets the memory of an earlier signed_out. */
75
+ export async function checkProfile(name: string, look: Looker, now: () => Date = () => new Date()): Promise<ProbeState> {
76
+ const probe = readProbe(name);
77
+ if (!probe) throw new Error(`browser profile "${name}" has no probe — set one with POST /lens/profiles/${name}/probe`);
78
+ const prev = readProbeState(name);
79
+ let res: { state: ProbeStateName; reason?: string };
80
+ try {
81
+ res = await look(name, probe);
82
+ } catch (err) {
83
+ res = { state: 'unknown', reason: err instanceof Error ? err.message.split('\n')[0]!.slice(0, 200) : String(err) };
84
+ }
85
+ const checked_at = now().toISOString();
86
+ const next: ProbeState = { state: res.state, checked_at, ...(res.reason ? { reason: res.reason } : {}) };
87
+ // The memory of «he has been told» survives until the profile is seen signed in again.
88
+ const told = res.state !== 'signed_in' && prev?.state !== 'signed_in' ? prev?.notified_at : undefined;
89
+ if (told) next.notified_at = told;
90
+ if (res.state === 'signed_out' && !told && notifier) {
91
+ try {
92
+ await notifier({ profile: name, url: probe.url, ...(res.reason ? { reason: res.reason } : {}) });
93
+ next.notified_at = checked_at;
94
+ } catch (err) {
95
+ // Not stamped: the next check tries again rather than believing he was told.
96
+ next.reason = `${res.reason ?? 'signed out'} · owner not told: ${err instanceof Error ? err.message.slice(0, 120) : 'error'}`;
97
+ }
98
+ }
99
+ writeFileSync(join(profileDir(name), STATE), JSON.stringify(next, null, 2), { mode: 0o600 });
100
+ return next;
101
+ }
102
+
103
+ /** Every probed profile, one after another (one browser at a time on this host). */
104
+ export async function checkAllProfiles(look: Looker): Promise<Array<{ name: string } & ProbeState>> {
105
+ const out = [];
106
+ for (const p of listProfiles()) if (p.probe) out.push({ name: p.name, ...(await checkProfile(p.name, look)) });
107
+ return out;
108
+ }
109
+
110
+ let timer: { first: ReturnType<typeof setTimeout>; every: ReturnType<typeof setInterval> } | null = null;
111
+ /** The daemon's own clock: the profiles live on this machine only, so nothing remote
112
+ * can reach them. Started once per process; unref'd so it never holds the process up. */
113
+ export function startProfileWatch(look: Looker, opts: { firstMs?: number; everyMs?: number } = {}): void {
114
+ if (timer) return;
115
+ const run = () => void checkAllProfiles(look).catch((err) => console.warn('[lens/profiles] watch failed:', err instanceof Error ? err.message : err));
116
+ const first = setTimeout(run, opts.firstMs ?? 2 * 60_000);
117
+ const every = setInterval(run, opts.everyMs ?? 6 * 60 * 60_000);
118
+ first.unref?.();
119
+ every.unref?.();
120
+ timer = { first, every };
121
+ }
122
+
123
+ /** The real look: a two-step flow in the profile's own build — goto, then read the
124
+ * marker. Through runFlow, so the profile claim, the build check and the launch are
125
+ * the ones every run uses. A profile held by a run answers "unknown", not "out". */
126
+ export const flowLooker: Looker = async (name, probe) => {
127
+ const channel = profileChannel(name);
128
+ if (!channel) return { state: 'unknown', reason: 'profile never used' };
129
+ const u = new URL(probe.url);
130
+ const steps: Flow['steps'] = [{ type: 'goto', path: `${u.pathname}${u.search}` }];
131
+ if ('selector' in probe.signed_in) {
132
+ steps.push({ type: 'assert', js: `!!document.querySelector(${JSON.stringify(probe.signed_in.selector)})`, timeout: 8000 });
133
+ }
134
+ const r = await runFlow({ name: `profile-probe:${name}`, base_url: u.origin, mutates: false, browser: { channel, profile: name }, steps }, process.env as never, {});
135
+ if (r.status === 'error' || r.steps[0]?.status !== 'pass') return { state: 'unknown', reason: (r.reason ?? 'the page did not load').slice(0, 200) };
136
+ if ('url_excludes' in probe.signed_in) {
137
+ const at = r.final_url ?? '';
138
+ return at.includes(probe.signed_in.url_excludes) ? { state: 'signed_out', reason: `landed on ${at}` } : { state: 'signed_in' };
139
+ }
140
+ return r.status === 'pass' ? { state: 'signed_in' } : { state: 'signed_out', reason: `${probe.signed_in.selector} not on the page (${r.final_url ?? probe.url})` };
141
+ };
142
+
143
+ /** F010.3 — for a run: the profile's last check, when it said signed_out. */
144
+ export function profileSignedOut(name: string | undefined): { profile: string; checked_at: string } | null {
145
+ if (!name) return null;
146
+ const st = readProbeState(name);
147
+ return st?.state === 'signed_out' ? { profile: name, checked_at: st.checked_at } : null;
148
+ }
package/src/profiles.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  // browser that holds it, so a login only survives if it happens in, and is reused
3
3
  // from, ONE profile of ONE browser build. The profile lives on the daemon host.
4
4
  import { execFileSync } from 'node:child_process';
5
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
5
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
6
6
  import { homedir } from 'node:os';
7
7
  import { join } from 'node:path';
8
8
 
@@ -10,6 +10,21 @@ import { join } from 'node:path';
10
10
  const profileRoot = () => process.env.LENS_PROFILE_ROOT || join(homedir(), '.lens', 'profiles');
11
11
  const NAME = /^[a-z0-9][a-z0-9-]{0,39}$/;
12
12
 
13
+ /** F010.3 — the kept profiles on this host: every valid name with a directory. */
14
+ export function listProfileNames(): string[] {
15
+ const root = profileRoot();
16
+ if (!existsSync(root)) return [];
17
+ return readdirSync(root, { withFileTypes: true }).filter((d) => d.isDirectory() && NAME.test(d.name)).map((d) => d.name).sort();
18
+ }
19
+
20
+ /** F010.3 — the build a profile is bound to, or null when it was never used. */
21
+ export function profileChannel(name: string): ProfileChannel | null {
22
+ const marker = join(profileDir(name), MARKER);
23
+ if (!existsSync(marker)) return null;
24
+ const v = readFileSync(marker, 'utf8').trim();
25
+ return v === 'chrome' || v === 'chromium' ? v : null;
26
+ }
27
+
13
28
  /** The profile's user-data dir. The name is checked because it becomes a path. */
14
29
  export function profileDir(name: string): string {
15
30
  if (typeof name !== 'string' || !NAME.test(name)) {