@broberg/lens-daemon 0.1.78 → 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.78",
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/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
+ }
@@ -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