@broberg/lens-daemon 0.1.77 → 0.1.80

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.77",
3
+ "version": "0.1.80",
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",
@@ -10,15 +10,17 @@
10
10
  "@modelcontextprotocol/sdk": "^1.0.4",
11
11
  "@mozilla/readability": "^0.6.0",
12
12
  "hono": "^4.6.14",
13
+ "imapflow": "1.7.8",
14
+ "mailparser": "3.15.0",
13
15
  "pixelmatch": "^6.0.0",
14
16
  "playwright": "1.61.1",
15
17
  "pngjs": "^7.0.0",
16
18
  "sharp": "^0.35.5",
17
19
  "turndown": "^7.2.4",
18
20
  "zod": "^3.23.8",
19
- "@broberg/lens-engine": "0.14.1",
20
21
  "@broberg/lens-measure": "0.1.7",
21
- "@broberg/lens-svg": "0.1.1"
22
+ "@broberg/lens-svg": "0.1.1",
23
+ "@broberg/lens-engine": "0.14.1"
22
24
  },
23
25
  "devDependencies": {
24
26
  "@happy-dom/global-registrator": "^20.10.6",
package/src/code-boxes.ts CHANGED
@@ -1,19 +1,45 @@
1
1
  // F010.11 — a one-time code field split into one box per character (Microsoft's
2
2
  // «Enter your code»). Shared by fill-from-owner and fill-from-mail: the code is
3
3
  // typed key by key from the first box and the page's own auto-advance moves focus.
4
+ // F009.143 — also the variant whose FIRST box takes the whole code (maxlength =
5
+ // code length, autocomplete=one-time-code) and spreads it (vn-leker's login), and
6
+ // a flow anchored on the GROUP's testid rather than on one of its inputs.
4
7
  import type { Locator } from 'playwright';
5
8
 
9
+ /** The input a code is typed into: the anchor itself, or — when the anchor is a
10
+ * wrapper such as the boxes' group — the first visible input inside it. */
11
+ export async function codeInput(loc: Locator): Promise<Locator> {
12
+ const tag = await loc.evaluate((el) => el.tagName).catch(() => '');
13
+ if (tag === 'INPUT' || tag === 'TEXTAREA') return loc;
14
+ const inner = loc.locator('input:not([type=hidden])');
15
+ return (await inner.count()) > 0 ? inner.first() : loc;
16
+ }
17
+
18
+ /** True when `el` is one box of a split code field: either a one-character box,
19
+ * or a wider box whose siblings in its group are all one-character boxes. */
6
20
  export async function isOneCharBox(loc: Locator): Promise<boolean> {
7
- return loc.evaluate((el) => (el as HTMLInputElement).maxLength === 1).catch(() => false);
21
+ return loc
22
+ .evaluate((el) => {
23
+ const input = el as HTMLInputElement;
24
+ if (input.maxLength === 1) return true;
25
+ let group: Element | null = el.parentElement;
26
+ while (group && group.querySelectorAll('input').length < 2 && group.parentElement) group = group.parentElement;
27
+ const others = [...(group?.querySelectorAll('input') ?? [])].filter((i) => i !== el) as HTMLInputElement[];
28
+ return others.length > 0 && others.every((i) => i.maxLength === 1);
29
+ })
30
+ .catch(() => false);
8
31
  }
9
32
 
10
- /** The joined value of the one-character boxes around `el`. */
33
+ /** The joined value of the code boxes around `el`. */
11
34
  function joinedBoxes(el: Element): string {
12
35
  let group: Element | null = el.parentElement;
13
36
  while (group && group.querySelectorAll('input').length < 2 && group.parentElement) group = group.parentElement;
14
- return [...(group?.querySelectorAll('input') ?? [])]
15
- .filter((i) => (i as HTMLInputElement).maxLength === 1)
16
- .map((i) => (i as HTMLInputElement).value)
37
+ const inputs = [...(group?.querySelectorAll('input') ?? [])] as HTMLInputElement[];
38
+ // A box wider than one character belongs to the code only when it is the one
39
+ // we typed into (F009.143); any other wide input in the group is not a box.
40
+ return inputs
41
+ .filter((i) => i.maxLength === 1 || i === el)
42
+ .map((i) => i.value)
17
43
  .join('');
18
44
  }
19
45
 
@@ -21,10 +47,15 @@ function joinedBoxes(el: Element): string {
21
47
  * starts the error message; the value itself is never in it. */
22
48
  export async function typeIntoBoxes(loc: Locator, value: string, failure: string, timeout: number): Promise<void> {
23
49
  await loc.focus({ timeout });
50
+ // Hold the box itself, not the locator: when the last digit submits and the
51
+ // page navigates, a locator would wait for a box that no longer exists until
52
+ // it times out; a handle fails at once with «context destroyed».
53
+ const box = await loc.elementHandle({ timeout });
24
54
  await loc.pressSequentially(value, { timeout });
25
55
  let got: string;
26
56
  try {
27
- got = await loc.evaluate(joinedBoxes);
57
+ if (!box) throw new Error('detached');
58
+ got = await box.evaluate(joinedBoxes);
28
59
  } catch (err) {
29
60
  // The last digit often submits the form; the page leaving is the code landing.
30
61
  if (/Execution context was destroyed|Cannot find context|has been closed|detached/i.test(err instanceof Error ? err.message : String(err))) return;
package/src/flow.ts CHANGED
@@ -37,7 +37,8 @@ import { fillAndVerify } from './fill.ts';
37
37
  import { fillSecret, getVaultWriter, type VaultReceipt, type VaultTarget } from './secret-fill.ts';
38
38
  import { storagePayload, type StorageSeed } from './seed-storage.ts';
39
39
  import { passwordInUrl, type FilledPassword, type PasswordInUrlFinding } from './password-in-url.ts';
40
- import { assertTestMailbox, cleanupMail, fillFromMail, httpMailSource, type MailFrom, type MailSource } from './mail-fill.ts';
40
+ import { assertTestMailbox, cleanupMail, fillFromMail, type MailFrom, type MailSource } from './mail-fill.ts';
41
+ import { routedMailSource } from './gmail-mail-source.ts';
41
42
  import { profileSignedOut } from './profile-watch.ts';
42
43
  import { parseFlowHeaders, resolveFlowHeaders, withFlowHeaders, type FlowHeader, type ResolvedHeader } from './flow-headers.ts';
43
44
  import { approveNumberWithOwner, fillFromOwner, MS_NUMBER_SELECTOR, OWNER_KINDS, OWNER_WAIT_MAX_MS, type OwnerFrom, type OwnerKind } from './owner-fill.ts';
@@ -3440,7 +3441,7 @@ export async function runFlow(flow: Flow, env: AuthEnv, opts: RunFlowOptions = {
3440
3441
  let networkShapesReport: NetworkShapesReport | undefined;
3441
3442
  const persistPath = persistTarget(flow.auth);
3442
3443
  // F009.137 — every mail a step consumes is removed when the run ends, pass or fail.
3443
- const mailCtx = { source: opts.mailSource ?? httpMailSource(), consumed: [] as Array<{ to: string; id: string }> };
3444
+ const mailCtx = { source: opts.mailSource ?? routedMailSource(), consumed: [] as Array<{ to: string; id: string }> };
3444
3445
  let mailReport: FlowResult['mail'];
3445
3446
  const finishMail = async () => {
3446
3447
  if (mailCtx.consumed.length && !mailReport) mailReport = await cleanupMail(mailCtx.consumed, mailCtx.source);
@@ -0,0 +1,153 @@
1
+ // F009.144 — Lens reads the mail codes of the FLEET TEST USER, webhouse.developer@gmail.com
2
+ // (owner 24/11, decision D-2d545d). mail-mcp cannot read that Gmail account (403), so
3
+ // this source reads it over IMAP with the account's app password, which the DAEMON
4
+ // fetches from cardmem's vault by secret id. Fenced to that one address; every other
5
+ // test mailbox still goes through mail-mcp (routedMailSource).
6
+ //
7
+ // The password, a mail body and a code never reach a report, a step detail or an error.
8
+ import { ImapFlow } from 'imapflow';
9
+ import { simpleParser } from 'mailparser';
10
+ import { httpMailSource, mailboxOf, type Mail, type MailSource } from './mail-fill.ts';
11
+ import { getVaultReader } from './secret-fill.ts';
12
+
13
+ export const GMAIL_TEST_USER = 'webhouse.developer@gmail.com';
14
+ /** Global Vault: «webhouse.developer@gmail.com — app-kodeord». */
15
+ export const GMAIL_TEST_USER_VAULT_ID = '01a16e28-663d-774e-87cd-fb4a151b4499';
16
+ const POLL_MS = 3_000;
17
+
18
+ /** A raw message as the mailbox holds it. */
19
+ export interface RawMessage { uid: number; internalDate: number; source: Buffer }
20
+
21
+ /** The narrow door to the mailbox — the real one is IMAP, tests pass a fake. */
22
+ export interface GmailPort {
23
+ /** Messages in INBOX whose internal date is on/after `since` (the server filters by
24
+ * day; the caller filters by the exact time). */
25
+ listSince(since: Date): Promise<RawMessage[]>;
26
+ moveToTrash(uid: number): Promise<void>;
27
+ close(): Promise<void>;
28
+ }
29
+ export type GmailConnect = () => Promise<GmailPort>;
30
+
31
+ /** Gmail ignores dots in the local part and treats googlemail.com as gmail.com. */
32
+ export function sameGmailAddress(a: string, b: string): boolean {
33
+ const norm = (s: string) => {
34
+ const [local = '', domain = ''] = mailboxOf(s).split('@');
35
+ const d = domain === 'googlemail.com' ? 'gmail.com' : domain;
36
+ return `${d === 'gmail.com' ? local.replace(/\./g, '') : local}@${d}`;
37
+ };
38
+ return norm(a) === norm(b);
39
+ }
40
+
41
+ async function toMail(m: RawMessage): Promise<{ mail: Mail; recipients: string[] }> {
42
+ const p = await simpleParser(m.source);
43
+ const list = (v: unknown) => (Array.isArray(v) ? v : v ? [v] : []) as Array<{ value: Array<{ address?: string }>; text?: string }>;
44
+ const recipients = [...list(p.to), ...list(p.cc)].flatMap((g) => g.value.map((x) => x.address ?? '')).filter(Boolean);
45
+ const text = p.text ?? (typeof p.html === 'string' ? p.html.replace(/<[^>]+>/g, ' ') : '');
46
+ return {
47
+ recipients,
48
+ mail: {
49
+ id: String(m.uid),
50
+ from: p.from?.text ?? '',
51
+ to: list(p.to).map((g) => g.text ?? '').join(', '),
52
+ subject: p.subject ?? '',
53
+ receivedAt: m.internalDate,
54
+ text,
55
+ },
56
+ };
57
+ }
58
+
59
+ /** The real port: imap.gmail.com over TLS, password from the vault. */
60
+ export function imapGmailConnect(env: Record<string, string | undefined> = process.env): GmailConnect {
61
+ return async () => {
62
+ const reader = getVaultReader();
63
+ if (!reader) throw new Error(`fill from mail (${GMAIL_TEST_USER}): this daemon is not signed in to cardmem, so it cannot read the Gmail app password from the vault`);
64
+ const secretId = env.LENS_GMAIL_SECRET_ID ?? GMAIL_TEST_USER_VAULT_ID;
65
+ let pass: string;
66
+ try {
67
+ pass = (await reader(secretId)).replace(/\s+/g, '');
68
+ } catch (err) {
69
+ throw new Error(`fill from mail (${GMAIL_TEST_USER}): could not read the Gmail app password (vault secret ${secretId}): ${err instanceof Error ? err.message.split('\n')[0]!.slice(0, 160) : 'error'}`);
70
+ }
71
+ if (!pass) throw new Error(`fill from mail (${GMAIL_TEST_USER}): vault secret ${secretId} is empty`);
72
+ const client = new ImapFlow({ host: 'imap.gmail.com', port: 993, secure: true, auth: { user: GMAIL_TEST_USER, pass }, logger: false });
73
+ try {
74
+ await client.connect();
75
+ } catch (err) {
76
+ const e = err as { authenticationFailed?: boolean; responseText?: string; message?: string };
77
+ const why = e.authenticationFailed ? 'Gmail refused the app password (authentication failed)' : (e.responseText ?? e.message ?? 'connect failed').replaceAll(pass, '***');
78
+ throw new Error(`fill from mail (${GMAIL_TEST_USER}): IMAP login failed — ${why.slice(0, 200)}`);
79
+ }
80
+ const lock = await client.getMailboxLock('INBOX');
81
+ return {
82
+ async listSince(since) {
83
+ await client.noop();
84
+ const uids = await client.search({ since }, { uid: true });
85
+ if (!uids || uids.length === 0) return [];
86
+ const out: RawMessage[] = [];
87
+ for await (const m of client.fetch(uids, { uid: true, internalDate: true, source: true }, { uid: true })) {
88
+ if (m.source) out.push({ uid: m.uid, internalDate: new Date(m.internalDate ?? 0).getTime(), source: m.source });
89
+ }
90
+ return out;
91
+ },
92
+ async moveToTrash(uid) {
93
+ const boxes = await client.list();
94
+ const trash = boxes.find((b) => b.specialUse === '\\Trash')?.path ?? '[Gmail]/Trash';
95
+ await client.messageMove(String(uid), trash, { uid: true });
96
+ },
97
+ async close() {
98
+ lock.release();
99
+ await client.logout().catch(() => client.close());
100
+ },
101
+ };
102
+ };
103
+ }
104
+
105
+ /** mail-mcp's contract over the Gmail test user's inbox. */
106
+ export function gmailMailSource(connect: GmailConnect = imapGmailConnect(), sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)), now = Date.now): MailSource {
107
+ return {
108
+ async wait(q) {
109
+ const re = new RegExp(q.codePattern);
110
+ const until = now() + q.timeoutSeconds * 1000;
111
+ const port = await connect();
112
+ try {
113
+ for (;;) {
114
+ const raws = await port.listSince(new Date(q.since));
115
+ const matches: Mail[] = [];
116
+ for (const raw of raws) {
117
+ if (raw.internalDate < q.since) continue;
118
+ const { mail, recipients } = await toMail(raw);
119
+ if (!recipients.some((r) => sameGmailAddress(r, q.to))) continue;
120
+ if (q.subject && !mail.subject.toLowerCase().includes(q.subject.toLowerCase())) continue;
121
+ if (!re.test(`${mail.subject}\n${mail.text}`)) continue;
122
+ matches.push(mail);
123
+ }
124
+ if (matches.length) {
125
+ const newest = matches.sort((a, b) => b.receivedAt - a.receivedAt)[0]!;
126
+ return { found: true, code: null, mail: newest };
127
+ }
128
+ if (now() >= until) return { found: false };
129
+ await sleep(Math.min(POLL_MS, Math.max(0, until - now())));
130
+ }
131
+ } finally {
132
+ await port.close();
133
+ }
134
+ },
135
+ async remove(q) {
136
+ const port = await connect();
137
+ try {
138
+ await port.moveToTrash(Number(q.id));
139
+ } finally {
140
+ await port.close();
141
+ }
142
+ },
143
+ };
144
+ }
145
+
146
+ /** The fleet test user's Gmail goes to IMAP; every other test mailbox to mail-mcp. */
147
+ export function routedMailSource(gmail: MailSource = gmailMailSource(), other: MailSource = httpMailSource()): MailSource {
148
+ const pick = (to: string) => (sameGmailAddress(to, GMAIL_TEST_USER) ? gmail : other);
149
+ return {
150
+ wait: (q) => pick(q.to).wait(q),
151
+ remove: (q) => pick(q.to).remove(q),
152
+ };
153
+ }
package/src/mail-fill.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  // spent by then, and hiding it would mean not photographing the form at all.
11
11
  import type { Locator } from 'playwright';
12
12
  import { fillAndVerify } from './fill.ts';
13
- import { isOneCharBox, typeIntoBoxes } from './code-boxes.ts';
13
+ import { codeInput, isOneCharBox, typeIntoBoxes } from './code-boxes.ts';
14
14
 
15
15
  export interface MailFrom {
16
16
  to: string;
@@ -113,12 +113,13 @@ export async function fillFromMail(
113
113
  ): Promise<void> {
114
114
  const { code, id } = await waitForMailCode(mf, since, source);
115
115
  consumed.push({ to: mailboxOf(mf.to), id });
116
- if (code.length > 1 && (await isOneCharBox(loc))) {
117
- await typeIntoBoxes(loc, code, `fill from mail did not land: expected a ${code.length}-character code`, timeout);
116
+ const input = await codeInput(loc);
117
+ if (code.length > 1 && (await isOneCharBox(input))) {
118
+ await typeIntoBoxes(input, code, `fill from mail did not land: expected a ${code.length}-character code`, timeout);
118
119
  return;
119
120
  }
120
121
  try {
121
- await fillAndVerify(loc, code, timeout);
122
+ await fillAndVerify(input, code, timeout);
122
123
  } catch {
123
124
  throw new Error(`fill from mail did not land: expected a ${code.length}-character code in the field (value withheld)`);
124
125
  }
package/src/owner-fill.ts CHANGED
@@ -13,7 +13,7 @@ import { homedir } from 'node:os';
13
13
  import { join } from 'node:path';
14
14
  import type { Locator } from 'playwright';
15
15
  import { fillAndVerify } from './fill.ts';
16
- import { isOneCharBox, typeIntoBoxes } from './code-boxes.ts';
16
+ import { codeInput, isOneCharBox, typeIntoBoxes } from './code-boxes.ts';
17
17
 
18
18
  export type OwnerKind = 'code' | 'password' | 'text';
19
19
 
@@ -90,12 +90,13 @@ export async function fillFromOwner(loc: Locator, of: OwnerFrom, fillTimeout: nu
90
90
  if (!res.answer) throw new Error('fill from owner: ARS answered with an empty value');
91
91
  // F010.11 — a code field split into one box per character (Microsoft's «Enter your
92
92
  // code»): type it key by key from the first box and let the page advance.
93
- if (res.answer.length > 1 && (await isOneCharBox(loc))) {
94
- await typeIntoBoxes(loc, res.answer, `fill from owner did not land: expected a ${res.answer.length}-character ${kind}`, fillTimeout);
93
+ const input = await codeInput(loc);
94
+ if (res.answer.length > 1 && (await isOneCharBox(input))) {
95
+ await typeIntoBoxes(input, res.answer, `fill from owner did not land: expected a ${res.answer.length}-character ${kind}`, fillTimeout);
95
96
  return;
96
97
  }
97
98
  try {
98
- await fillAndVerify(loc, res.answer, fillTimeout);
99
+ await fillAndVerify(input, res.answer, fillTimeout);
99
100
  } catch {
100
101
  throw new Error(`fill from owner did not land: expected a ${res.answer.length}-character ${kind} in the field (value withheld)`);
101
102
  }
@@ -18,6 +18,10 @@ let vaultReader: VaultReader | null = null;
18
18
  export function setVaultReader(fn: VaultReader | null): void {
19
19
  vaultReader = fn;
20
20
  }
21
+ /** F009.144 — the Gmail test-user mail source reads its app password the same way. */
22
+ export function getVaultReader(): VaultReader | null {
23
+ return vaultReader;
24
+ }
21
25
 
22
26
  // F010.15 — the other direction: a value READ off the page (a new API key a provider
23
27
  // console shows once) is stored in cardmem's vault by the DAEMON, with its own