@broberg/lens-daemon 0.1.66 → 0.1.67
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 +1 -1
- package/src/flow.ts +13 -5
- package/src/http.ts +8 -3
- package/src/mcp.ts +1 -1
- package/src/profile-watch.ts +17 -6
- package/src/sign-in.ts +79 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@broberg/lens-daemon",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.67",
|
|
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",
|
package/src/flow.ts
CHANGED
|
@@ -170,7 +170,9 @@ export type FlowStep =
|
|
|
170
170
|
| { type: 'capture'; testid: string; as: string; from?: 'text' | 'value'; label?: string; timeout?: number }
|
|
171
171
|
/** F010.15 — the value goes straight into cardmem's vault; the run only ever holds its receipt. */
|
|
172
172
|
| { type: 'capture'; testid: string; to: 'vault'; vault: VaultTarget; label?: string; timeout?: number }
|
|
173
|
-
|
|
173
|
+
// F010.9 — `selector` (css) instead of `testid`, for a third-party page with no testids
|
|
174
|
+
// (a login page whose next screen depends on the account).
|
|
175
|
+
| { type: 'conditional'; testid?: string; selector?: string; present: boolean; steps: FlowStep[]; label?: string; timeout?: number }
|
|
174
176
|
| { type: 'loop'; data: Array<Record<string, unknown>>; steps: FlowStep[]; label?: string; parallel?: number }
|
|
175
177
|
// F009.125 — open the loaded extension's popup as its own page in the SAME browser,
|
|
176
178
|
// then put the page under test back in front so the extension sees it as the active
|
|
@@ -815,7 +817,7 @@ export const STEP_FIELDS: Record<string, string[]> = {
|
|
|
815
817
|
uploadSelector: ['selector', 'path', 'frame'],
|
|
816
818
|
autocomplete: ['testid', 'value', 'option', 'pickText', 'pickIndex'],
|
|
817
819
|
capture: ['testid', 'as', 'from', 'to', 'vault'],
|
|
818
|
-
conditional: ['testid', 'present', 'steps'],
|
|
820
|
+
conditional: ['testid', 'selector', 'present', 'steps'],
|
|
819
821
|
loop: ['data', 'steps', 'parallel'],
|
|
820
822
|
openPopup: ['path'],
|
|
821
823
|
waitForPopup: [],
|
|
@@ -1004,7 +1006,13 @@ function validateAndNormalizeSteps(steps: unknown[], depth = 0, inParallel = fal
|
|
|
1004
1006
|
// race eventually resolved, not on the element it was asked about.
|
|
1005
1007
|
// Staying testid-only keeps it on `page.locator(sel(testid))`, which is a
|
|
1006
1008
|
// plain locator this verb times itself (see the settle window below).
|
|
1007
|
-
const testidOnly = ['expectAbsent', 'drag', 'autocomplete', 'capture', '
|
|
1009
|
+
const testidOnly = ['expectAbsent', 'drag', 'autocomplete', 'capture', 'uploadFile'];
|
|
1010
|
+
if (s.type === 'conditional') {
|
|
1011
|
+
const c = s as { testid?: unknown; selector?: unknown };
|
|
1012
|
+
if ((typeof c.testid === 'string') === (typeof c.selector === 'string' && !!(c.selector as string).trim())) {
|
|
1013
|
+
throw new Error('conditional step requires exactly one of a string testid or a css selector');
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1008
1016
|
if (testidOnly.includes(s.type) && typeof (s as { testid?: unknown }).testid !== 'string') {
|
|
1009
1017
|
throw new Error(`${s.type} step requires a string testid`);
|
|
1010
1018
|
}
|
|
@@ -1760,7 +1768,7 @@ function describe(step: FlowStep): string {
|
|
|
1760
1768
|
case 'press': return `press ${step.key}${step.testid ? ` @${step.testid}` : ''}`;
|
|
1761
1769
|
case 'autocomplete': return `autocomplete ${step.testid} → ${step.pickText !== undefined ? `"${step.pickText}"` : `#${step.pickIndex}`}`;
|
|
1762
1770
|
case 'capture': return 'to' in step ? `capture ${step.testid} → vault ${step.vault.project}/${step.vault.name}` : `capture ${step.testid} → {{${step.as}}}`;
|
|
1763
|
-
case 'conditional': return `${step.present ? 'if' : 'unless'} [${step.testid}]`;
|
|
1771
|
+
case 'conditional': return `${step.present ? 'if' : 'unless'} ${step.selector ?? `[${step.testid}]`}`;
|
|
1764
1772
|
case 'loop': return 'loop';
|
|
1765
1773
|
case 'openPopup': return `openPopup ${step.path ?? '(manifest popup)'}`;
|
|
1766
1774
|
case 'waitForPopup': return 'waitForPopup';
|
|
@@ -3129,7 +3137,7 @@ export async function runFlow(flow: Flow, env: AuthEnv, opts: RunFlowOptions = {
|
|
|
3129
3137
|
const probe = step.timeout ?? 2000;
|
|
3130
3138
|
let visible = false;
|
|
3131
3139
|
try {
|
|
3132
|
-
await page.locator(sel(step.testid)).first().waitFor({ state: 'visible', timeout: probe });
|
|
3140
|
+
await page.locator(step.selector ?? sel(step.testid!)).first().waitFor({ state: 'visible', timeout: probe });
|
|
3133
3141
|
visible = true;
|
|
3134
3142
|
} catch {
|
|
3135
3143
|
// anchor not present within the probe window → treated as absent
|
package/src/http.ts
CHANGED
|
@@ -36,7 +36,8 @@ 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';
|
|
39
|
+
import { checkProfile, flowLooker, listProfiles, setProbe, setProfileNotifier, setProfileRenewer, startProfileWatch } from './profile-watch.ts';
|
|
40
|
+
import { signIn } from './sign-in.ts';
|
|
40
41
|
|
|
41
42
|
/** F010.3 — the cardmem project Lens's own mail to the owner is filed under. */
|
|
42
43
|
const LENS_CARDMEM_PROJECT = '01a12d2d-868b-76b7-a316-b32f71fe5415';
|
|
@@ -70,16 +71,17 @@ export function createLensRouter(deps: LensDeps): Hono {
|
|
|
70
71
|
});
|
|
71
72
|
// F010.3 — an expired login is told to the owner once, through cardmem's own mail
|
|
72
73
|
// to him (the recipient is fixed; nothing else can be addressed).
|
|
73
|
-
setProfileNotifier(async ({ profile, url, reason }) => {
|
|
74
|
+
setProfileNotifier(async ({ profile, url, reason, renewing }) => {
|
|
74
75
|
const cloud = deps.cloud?.();
|
|
75
76
|
if (!cloud) throw new Error('not signed in to cardmem');
|
|
76
77
|
const r = await cloud.callTool<{ sent?: boolean; skipped?: boolean }>('cardmem_mail_owner', {
|
|
77
78
|
project_id: LENS_CARDMEM_PROJECT,
|
|
78
79
|
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\
|
|
80
|
+
markdown: `Lens' gemte login i profilen **${profile}** er ikke længere logget ind (tjekket mod ${url}${reason ? ` — ${reason}` : ''}).\n\n${renewing ? 'Lens logger profilen ind igen nu. Beder sitet om en kode fra din Authenticator, kommer spørgsmålet i ARS. Det er det eneste, du skal gøre.' : 'Lens kan ikke selv logge denne profil ind endnu, fordi der ikke findes en login-opskrift til sitet. Du skal ikke gøre noget i et browservindue.'} Kørsler, der bruger profilen, vil fejle på login, indtil den er fornyet. Du får kun denne ene besked, indtil profilen er logget ind igen.`,
|
|
80
81
|
});
|
|
81
82
|
if (!r?.sent) throw new Error(r?.skipped ? 'the mailer held it back (skipped)' : 'cardmem did not confirm the mail was sent');
|
|
82
83
|
});
|
|
84
|
+
setProfileRenewer((profile, recipe) => signIn(profile, recipe));
|
|
83
85
|
if (process.env.NODE_ENV !== 'test') startProfileWatch(flowLooker);
|
|
84
86
|
// lens F001.5 — the routes that used to be registered one by one in the
|
|
85
87
|
// daemon's index.ts. First, so their specific paths win as they did there.
|
|
@@ -118,6 +120,9 @@ export function createLensRouter(deps: LensDeps): Hono {
|
|
|
118
120
|
};
|
|
119
121
|
r.post('/profiles/:name/probe', profileRoute((name, body) => ({ probe: setProbe(name, body) })));
|
|
120
122
|
r.post('/profiles/:name/check', profileRoute(async (name) => ({ result: await checkProfile(name, flowLooker) })));
|
|
123
|
+
// F010.9 — sign a kept profile in by itself: password from the vault, an
|
|
124
|
+
// authenticator code from the owner in ARS. {recipe: "<name>"}.
|
|
125
|
+
r.post('/profiles/:name/sign-in', profileRoute(async (name, body) => ({ result: await signIn(name, String((body as { recipe?: unknown }).recipe ?? '')) })));
|
|
121
126
|
r.post('/capture', handle((body) => lensCapture(deps, body as Parameters<typeof lensCapture>[1])));
|
|
122
127
|
r.post('/verify', handle((body) => lensVerify(deps, body as Parameters<typeof lensVerify>[1])));
|
|
123
128
|
// F074.63 — the export verb beside capture. Same pipeline, one terminal call
|
package/src/mcp.ts
CHANGED
|
@@ -33,7 +33,7 @@ const browserSchema = {
|
|
|
33
33
|
type: 'object',
|
|
34
34
|
required: ['channel'],
|
|
35
35
|
description:
|
|
36
|
-
'F009.136 — run in this browser BUILD with its own user-data dir. {channel:"chrome", profile:"<name>"} = the installed Google Chrome with the kept profile ~/.lens/profiles/<name>, de-flagged (no automation bar, no navigator.webdriver, no HeadlessChrome in the user agent). Use it for Google sign-ins (YouTube Studio, Postmaster Tools, Chrome Web Store), which refuse Playwright\'s Chromium ("this browser may not be secure").
|
|
36
|
+
'F009.136 — run in this browser BUILD with its own user-data dir. {channel:"chrome", profile:"<name>"} = the installed Google Chrome with the kept profile ~/.lens/profiles/<name>, de-flagged (no automation bar, no navigator.webdriver, no HeadlessChrome in the user agent). Use it for Google sign-ins (YouTube Studio, Postmaster Tools, Chrome Web Store), which refuse Playwright\'s Chromium ("this browser may not be secure"). Sign a profile in with POST /lens/profiles/<name>/sign-in {recipe} (F010.9): Lens walks the site\'s own login with the password from cardmem\'s vault and asks the owner ONLY for an authenticator code, in ARS — never a login window for the owner. Then reuse the profile in any run and from any project. GET /lens/profiles shows each profile\'s last signed-in check (F010.3). A profile remembers its build: using it with the other channel is refused. One run per profile at a time. visible:true opens a window instead of headless. Not with extension.',
|
|
37
37
|
properties: {
|
|
38
38
|
channel: { type: 'string', enum: ['chrome', 'chromium'] },
|
|
39
39
|
profile: { type: 'string', description: '1-40 chars a-z 0-9 -. Omit for a fresh temp profile.' },
|
package/src/profile-watch.ts
CHANGED
|
@@ -9,7 +9,8 @@ import { listProfileNames, profileChannel, profileDir } from './profiles.ts';
|
|
|
9
9
|
import { runFlow, type Flow } from './flow.ts';
|
|
10
10
|
|
|
11
11
|
export type SignedIn = { selector: string } | { url_excludes: string };
|
|
12
|
-
|
|
12
|
+
/** F010.9 — `recipe` names the sign-in recipe that can renew this profile. */
|
|
13
|
+
export interface Probe { url: string; signed_in: SignedIn; recipe?: string }
|
|
13
14
|
export type ProbeStateName = 'signed_in' | 'signed_out' | 'unknown';
|
|
14
15
|
export interface ProbeState { state: ProbeStateName; checked_at: string; reason?: string; notified_at?: string }
|
|
15
16
|
|
|
@@ -20,8 +21,8 @@ const STATE = '.lens-probe-state.json';
|
|
|
20
21
|
* would report "signed in" forever. */
|
|
21
22
|
export function parseProbe(input: unknown): Probe {
|
|
22
23
|
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}}');
|
|
24
|
+
if (!o || typeof o !== 'object' || Array.isArray(o) || Object.keys(o).some((k) => k !== 'url' && k !== 'signed_in' && k !== 'recipe')) {
|
|
25
|
+
throw new Error('probe must be {url, signed_in: {selector} | {url_excludes}, recipe?}');
|
|
25
26
|
}
|
|
26
27
|
// https only, except a loopback page (tests, a local app) — a probe never sends a login over plain http.
|
|
27
28
|
if (typeof o.url !== 'string' || !(/^https:\/\//.test(o.url) || /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?\//.test(o.url))) {
|
|
@@ -32,7 +33,8 @@ export function parseProbe(input: unknown): Probe {
|
|
|
32
33
|
if (keys.length !== 1 || (keys[0] !== 'selector' && keys[0] !== 'url_excludes') || typeof s![keys[0]] !== 'string' || !(s![keys[0]] as string).trim()) {
|
|
33
34
|
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
|
}
|
|
35
|
-
|
|
36
|
+
if (o.recipe !== undefined && (typeof o.recipe !== 'string' || !/^[a-z0-9][a-z0-9-]{0,59}$/.test(o.recipe))) throw new Error('probe.recipe must be a recipe name');
|
|
37
|
+
return { url: o.url, signed_in: { [keys[0]!]: (s![keys[0]!] as string).trim() } as SignedIn, ...(typeof o.recipe === 'string' ? { recipe: o.recipe } : {}) };
|
|
36
38
|
}
|
|
37
39
|
|
|
38
40
|
const readJson = <T>(path: string): T | null => {
|
|
@@ -61,9 +63,14 @@ export function listProfiles() {
|
|
|
61
63
|
/** One look at the profile. Injected so the check itself is testable without the
|
|
62
64
|
* timer, and so it reuses runFlow (claim, build marker, launch) instead of a copy. */
|
|
63
65
|
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>;
|
|
66
|
+
export type Notifier = (msg: { profile: string; url: string; reason?: string; renewing?: boolean }) => Promise<void>;
|
|
65
67
|
|
|
66
68
|
let notifier: Notifier | null = null;
|
|
69
|
+
/** F010.9 — what renews a profile whose probe names a recipe. Installed by the daemon. */
|
|
70
|
+
let renewer: ((profile: string, recipe: string) => Promise<unknown>) | null = null;
|
|
71
|
+
export function setProfileRenewer(fn: ((profile: string, recipe: string) => Promise<unknown>) | null): void {
|
|
72
|
+
renewer = fn;
|
|
73
|
+
}
|
|
67
74
|
export function setProfileNotifier(fn: Notifier | null): void {
|
|
68
75
|
notifier = fn;
|
|
69
76
|
}
|
|
@@ -89,8 +96,12 @@ export async function checkProfile(name: string, look: Looker, now: () => Date =
|
|
|
89
96
|
if (told) next.notified_at = told;
|
|
90
97
|
if (res.state === 'signed_out' && !told && notifier) {
|
|
91
98
|
try {
|
|
92
|
-
|
|
99
|
+
const renewing = !!(probe.recipe && renewer);
|
|
100
|
+
await notifier({ profile: name, url: probe.url, ...(res.reason ? { reason: res.reason } : {}), ...(renewing ? { renewing } : {}) });
|
|
93
101
|
next.notified_at = checked_at;
|
|
102
|
+
// Once per transition, like the mail: started, not awaited — the sign-in claims
|
|
103
|
+
// the profile and waits on ARS, and this check must not hold the timer meanwhile.
|
|
104
|
+
if (renewing) void renewer!(name, probe.recipe!).catch((err) => console.warn(`[lens/profiles] renewing ${name} failed:`, err instanceof Error ? err.message : err));
|
|
94
105
|
} catch (err) {
|
|
95
106
|
// Not stamped: the next check tries again rather than believing he was told.
|
|
96
107
|
next.reason = `${res.reason ?? 'signed out'} · owner not told: ${err instanceof Error ? err.message.slice(0, 120) : 'error'}`;
|
package/src/sign-in.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// F010.9 — Lens signs a kept profile in by itself. A recipe is DATA: the flow steps
|
|
2
|
+
// that walk a site's own login page, plus the probe that says it worked (F010.3's).
|
|
3
|
+
// Where each value comes from is the owner's rule (D-dbaedd, D-9f3294, 26 Oct):
|
|
4
|
+
// the account name → the recipe (not a secret)
|
|
5
|
+
// the password → cardmem's vault, by secret id
|
|
6
|
+
// an authenticator code → the owner, through ARS — the ONLY thing he types
|
|
7
|
+
// a mailed code → the test mailbox (F009.137), never the owner
|
|
8
|
+
// Steps a page may or may not show (a challenge screen) are `conditional` on a css
|
|
9
|
+
// selector, so one recipe covers «already past this screen» and «asked for it».
|
|
10
|
+
import { runFlow, type Flow } from './flow.ts';
|
|
11
|
+
import { checkProfile, flowLooker, readProbe, setProbe, type Looker, type Probe } from './profile-watch.ts';
|
|
12
|
+
import { profileChannel } from './profiles.ts';
|
|
13
|
+
|
|
14
|
+
export interface SignInRecipe {
|
|
15
|
+
/** Shown in the owner's ARS question and in errors. */
|
|
16
|
+
site: string;
|
|
17
|
+
base_url: string;
|
|
18
|
+
steps: Flow['steps'];
|
|
19
|
+
probe: Probe;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const WAIT = 15_000;
|
|
23
|
+
|
|
24
|
+
/** Google account sign-in. `account` is the address; `passwordSecret` its vault id. */
|
|
25
|
+
const google = (account: string, passwordSecret: string): SignInRecipe => ({
|
|
26
|
+
site: 'Google',
|
|
27
|
+
base_url: 'https://accounts.google.com',
|
|
28
|
+
steps: [
|
|
29
|
+
{ type: 'goto', path: '/ServiceLogin?continue=https%3A%2F%2Fmyaccount.google.com%2F' },
|
|
30
|
+
{ type: 'conditional', selector: 'input[type=email]', present: true, timeout: WAIT, steps: [
|
|
31
|
+
{ type: 'fill', target: { css: 'input[type=email]' }, value: account },
|
|
32
|
+
{ type: 'click', target: { css: '#identifierNext' } },
|
|
33
|
+
] },
|
|
34
|
+
{ type: 'conditional', selector: 'input[type=password][name=Passwd]', present: true, timeout: WAIT, steps: [
|
|
35
|
+
{ type: 'fill', target: { css: 'input[type=password][name=Passwd]' }, valueFrom: { vault: passwordSecret } },
|
|
36
|
+
{ type: 'click', target: { css: '#passwordNext' } },
|
|
37
|
+
] },
|
|
38
|
+
// Google's authenticator challenge. A phone prompt or any other challenge leaves
|
|
39
|
+
// this skipped and the probe reports signed_out with where it stopped.
|
|
40
|
+
{ type: 'conditional', selector: 'input[name=totpPin]', present: true, timeout: WAIT, steps: [
|
|
41
|
+
{ type: 'fill', target: { css: 'input[name=totpPin]' }, valueFrom: { owner: { question: `Google (${account}): koden fra Google Authenticator`, kind: 'code' } } },
|
|
42
|
+
{ type: 'click', target: { css: '#totpNext' } },
|
|
43
|
+
] },
|
|
44
|
+
] as Flow['steps'],
|
|
45
|
+
probe: { url: 'https://myaccount.google.com/', signed_in: { url_excludes: '/account/about' } },
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
/** The recipes this daemon knows, by name. Adding a site = adding an entry here. */
|
|
49
|
+
export const RECIPES: Record<string, SignInRecipe> = {
|
|
50
|
+
'google-webhouse-developer': google('webhouse.developer@gmail.com', '019f6a86-d74a-7f2b-972b-f18d5be38bfa'),
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export function recipeFor(name: string): SignInRecipe {
|
|
54
|
+
const r = RECIPES[name];
|
|
55
|
+
if (!r) throw new Error(`no sign-in recipe "${name}" — known: ${Object.keys(RECIPES).join(', ') || 'none'}`);
|
|
56
|
+
return r;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Sign `profile` in with `recipeName`, then look. The profile's probe becomes the
|
|
60
|
+
* recipe's, with the recipe named on it, so F010.3 can renew it next time. */
|
|
61
|
+
export async function signIn(
|
|
62
|
+
profile: string,
|
|
63
|
+
recipeName: string,
|
|
64
|
+
run: typeof runFlow = runFlow,
|
|
65
|
+
look: Looker = flowLooker,
|
|
66
|
+
): Promise<{ state: string; reason?: string; failed_step?: string }> {
|
|
67
|
+
const recipe = recipeFor(recipeName);
|
|
68
|
+
const channel = profileChannel(profile);
|
|
69
|
+
if (!channel) throw new Error(`browser profile "${profile}" has never been used — open it once in a run first`);
|
|
70
|
+
const r = await run({ name: `sign-in:${profile}`, base_url: recipe.base_url, mutates: true, browser: { channel, profile }, steps: recipe.steps }, process.env as never, {});
|
|
71
|
+
const failed = r.status !== 'pass' ? r.steps.find((s) => s.status === 'fail') : undefined;
|
|
72
|
+
if (!readProbe(profile)?.recipe) setProbe(profile, { ...recipe.probe, recipe: recipeName });
|
|
73
|
+
const state = await checkProfile(profile, look);
|
|
74
|
+
return {
|
|
75
|
+
state: state.state,
|
|
76
|
+
...(failed ? { failed_step: `${failed.label}: ${String(failed.detail ?? r.reason ?? '').slice(0, 200)}` } : {}),
|
|
77
|
+
...(state.reason ? { reason: state.reason } : {}),
|
|
78
|
+
};
|
|
79
|
+
}
|