blindfill 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,402 @@
1
+ import {
2
+ BlindfillError,
3
+ SessionPolicy,
4
+ WebActuator,
5
+ assertLoopbackEndpoint,
6
+ configDir,
7
+ getProvider,
8
+ inferProviderId,
9
+ mkdirPrivate,
10
+ parseEgoEndpoint,
11
+ readPrivateFile,
12
+ redactEndpoint,
13
+ resolveEndpoint,
14
+ stateDir,
15
+ strictJson,
16
+ validateRules,
17
+ windowsPathsPrivate
18
+ } from "./chunk-V4KGRR36.js";
19
+
20
+ // src/harden.ts
21
+ delete process.env.DEBUG;
22
+ delete process.env.PWDEBUG;
23
+
24
+ // src/actuators/web/session.ts
25
+ import { spawn } from "child_process";
26
+ import { randomBytes } from "crypto";
27
+ import {
28
+ closeSync,
29
+ existsSync,
30
+ lstatSync,
31
+ mkdtempSync,
32
+ openSync,
33
+ readFileSync,
34
+ renameSync,
35
+ rmSync,
36
+ statSync,
37
+ writeFileSync
38
+ } from "fs";
39
+ import { join } from "path";
40
+ import { tmpdir } from "os";
41
+ import { chromium } from "playwright-core";
42
+ var file = () => join(stateDir(), "session.json");
43
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
44
+ function assertPrivateDir(dir) {
45
+ const st = lstatSync(dir);
46
+ const ok = process.platform === "win32" ? st.isDirectory() && windowsPathsPrivate([dir]) : st.isDirectory() && st.uid === process.getuid?.() && (st.mode & 63) === 0;
47
+ if (!ok)
48
+ throw new BlindfillError(
49
+ "POLICY",
50
+ "the blindfill state directory must be a directory (not a symlink) private to you (mode 0700; on Windows only you, SYSTEM and Administrators in its ACL)"
51
+ );
52
+ }
53
+ function readSession() {
54
+ try {
55
+ return JSON.parse(readFileSync(file(), "utf8"));
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+ function loadSession() {
61
+ if (existsSync(stateDir())) assertPrivateDir(stateDir());
62
+ return readSession();
63
+ }
64
+ function withLock(dir, fn) {
65
+ const lock = join(dir, "session.lock");
66
+ const deadline = Date.now() + 5e3;
67
+ for (; ; ) {
68
+ try {
69
+ closeSync(openSync(lock, "wx", 384));
70
+ break;
71
+ } catch (e) {
72
+ if (e.code !== "EEXIST") throw e;
73
+ try {
74
+ if (Date.now() - statSync(lock).mtimeMs > 1e4) rmSync(lock, { force: true });
75
+ } catch {
76
+ }
77
+ if (Date.now() > deadline)
78
+ throw new BlindfillError("ACTUATOR", "session state is locked by another blindfill process");
79
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
80
+ }
81
+ }
82
+ try {
83
+ return fn();
84
+ } finally {
85
+ rmSync(lock, { force: true });
86
+ }
87
+ }
88
+ function saveSession(s) {
89
+ const dir = stateDir();
90
+ mkdirPrivate(dir);
91
+ assertPrivateDir(dir);
92
+ withLock(dir, () => {
93
+ const cur = readSession();
94
+ const same = cur && cur.cdp === s.cdp && cur.endpointFile === s.endpointFile && (cur.browser ?? "chromium-cdp") === (s.browser ?? "chromium-cdp");
95
+ const policy = same ? {
96
+ ...s.policy,
97
+ locked: !!cur.policy?.locked || s.policy.locked,
98
+ filled: [.../* @__PURE__ */ new Set([...cur.policy?.filled ?? [], ...s.policy.filled])]
99
+ } : s.policy;
100
+ const tmp = join(dir, `.session.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
101
+ try {
102
+ writeFileSync(tmp, JSON.stringify({ ...s, policy }), { mode: 384, flag: "wx" });
103
+ renameSync(tmp, file());
104
+ } finally {
105
+ rmSync(tmp, { force: true });
106
+ }
107
+ });
108
+ }
109
+ async function startSession(opts = {}) {
110
+ const existing = loadSession();
111
+ if (existing?.owned && existing.pid && alive(existing.pid))
112
+ throw new BlindfillError("POLICY", "a session is already running; run `blindfill session stop` first");
113
+ const exe = opts.executablePath ?? process.env.BLINDFILL_CHROMIUM ?? chromium.executablePath();
114
+ if (!existsSync(exe))
115
+ throw new BlindfillError("ACTUATOR", "Chromium not found. Run: npx playwright-core install chromium");
116
+ const dir = mkdtempSync(join(tmpdir(), "blindfill-profile-"));
117
+ const args = [
118
+ "--remote-debugging-port=0",
119
+ "--remote-debugging-address=127.0.0.1",
120
+ `--user-data-dir=${dir}`,
121
+ "--no-first-run",
122
+ "--no-default-browser-check",
123
+ "--disable-extensions",
124
+ ...opts.headless ?? true ? ["--headless=new"] : [],
125
+ ...process.env.BLINDFILL_NO_SANDBOX === "1" ? ["--no-sandbox"] : [],
126
+ "about:blank"
127
+ ];
128
+ const child = spawn(exe, args, { detached: true, stdio: "ignore" });
129
+ child.unref();
130
+ let port = 0;
131
+ for (let i = 0; i < 100 && !port; i++) {
132
+ await sleep(150);
133
+ try {
134
+ port = Number(readFileSync(join(dir, "DevToolsActivePort"), "utf8").split("\n")[0]);
135
+ } catch {
136
+ }
137
+ }
138
+ if (!port) {
139
+ try {
140
+ process.kill(child.pid, "SIGKILL");
141
+ } catch {
142
+ }
143
+ rmSync(dir, { recursive: true, force: true });
144
+ throw new BlindfillError("ACTUATOR", "Chromium did not expose a debugging port");
145
+ }
146
+ const s = {
147
+ cdp: `http://127.0.0.1:${port}`,
148
+ owned: true,
149
+ pid: child.pid,
150
+ userDataDir: dir,
151
+ browser: "chromium-cdp",
152
+ headless: opts.headless ?? true,
153
+ policy: { locked: false, filled: [] }
154
+ };
155
+ saveSession(s);
156
+ return s;
157
+ }
158
+ function alive(pid) {
159
+ try {
160
+ process.kill(pid, 0);
161
+ return true;
162
+ } catch {
163
+ return false;
164
+ }
165
+ }
166
+ function explicitSession(opts) {
167
+ const endpoint = opts.endpoint ?? opts.cdp;
168
+ if (!endpoint && !opts.endpointFile) return null;
169
+ const ep = resolveEndpoint({ endpoint, endpointFile: opts.endpointFile });
170
+ const browser = opts.browser ?? inferProviderId(ep);
171
+ if (browser === "ego-cli") parseEgoEndpoint(ep);
172
+ else assertLoopbackEndpoint(ep);
173
+ return {
174
+ cdp: endpoint ?? "",
175
+ endpointFile: opts.endpointFile,
176
+ browser,
177
+ playwrightModule: opts.playwrightModule,
178
+ owned: false,
179
+ policy: { locked: false, filled: [] }
180
+ };
181
+ }
182
+ async function attach(opts = {}) {
183
+ let s = loadSession();
184
+ const ex = explicitSession(opts);
185
+ if (ex) {
186
+ const same = s && s.cdp === ex.cdp && s.endpointFile === ex.endpointFile && (s.browser ?? "chromium-cdp") === ex.browser;
187
+ if (!same) s = ex;
188
+ else if (s && opts.browser) s.browser = opts.browser;
189
+ }
190
+ if (!s)
191
+ throw new BlindfillError(
192
+ "ACTUATOR",
193
+ "no browser session: run `blindfill session start`, `blindfill session attach --endpoint <url>` or pass --endpoint"
194
+ );
195
+ const session = s;
196
+ const provider = getProvider(session.browser ?? "chromium-cdp");
197
+ if (!provider.attachable)
198
+ throw new BlindfillError("ACTUATOR", `provider ${provider.id} cannot be attached from a saved session`);
199
+ const policy = new SessionPolicy(session.policy);
200
+ const actuator = await WebActuator.fromProvider(
201
+ provider.id,
202
+ {
203
+ endpoint: session.cdp || void 0,
204
+ endpointFile: session.endpointFile,
205
+ urlIncludes: opts.urlIncludes,
206
+ pageIndex: opts.pageIndex,
207
+ playwrightModule: opts.playwrightModule ?? session.playwrightModule
208
+ },
209
+ policy
210
+ );
211
+ const persist = () => saveSession({ ...session, policy: policy.snapshot() });
212
+ return { actuator, session, persist };
213
+ }
214
+ async function attachSession(opts) {
215
+ const ex = explicitSession(opts);
216
+ if (!ex)
217
+ throw new BlindfillError(
218
+ "POLICY",
219
+ "usage: blindfill session attach --endpoint <url> | --endpoint-file <json>"
220
+ );
221
+ const existing = loadSession();
222
+ if (existing?.owned && existing.pid && alive(existing.pid))
223
+ throw new BlindfillError(
224
+ "POLICY",
225
+ "a blindfill-owned session is running; run `blindfill session stop` first"
226
+ );
227
+ saveSession(ex);
228
+ let actuator;
229
+ try {
230
+ ({ actuator } = await attach(opts));
231
+ const pages = actuator.page.context().pages().map((p, index) => ({ index, origin: safeOrigin(p.url()) }));
232
+ return {
233
+ browser: ex.browser,
234
+ endpoint: redactEndpoint(
235
+ resolveEndpoint({ endpoint: ex.cdp || void 0, endpointFile: ex.endpointFile })
236
+ ),
237
+ capabilities: actuator.capabilities,
238
+ pages
239
+ };
240
+ } catch (e) {
241
+ rmSync(file(), { force: true });
242
+ throw e;
243
+ } finally {
244
+ await actuator?.close();
245
+ }
246
+ }
247
+ function safeOrigin(url) {
248
+ try {
249
+ const u = new URL(url);
250
+ return /^https?:$/.test(u.protocol) ? u.origin : u.protocol;
251
+ } catch {
252
+ return "";
253
+ }
254
+ }
255
+ async function stopSession() {
256
+ const s = loadSession();
257
+ if (!s) return { stopped: false, killed: false };
258
+ let killed = false;
259
+ if (s.owned && s.pid && alive(s.pid)) {
260
+ try {
261
+ process.kill(s.pid, "SIGTERM");
262
+ for (let i = 0; i < 30 && alive(s.pid); i++) await sleep(100);
263
+ if (alive(s.pid)) process.kill(s.pid, "SIGKILL");
264
+ killed = true;
265
+ } catch {
266
+ }
267
+ }
268
+ if (s.userDataDir) {
269
+ await sleep(200);
270
+ rmSync(s.userDataDir, { recursive: true, force: true });
271
+ }
272
+ rmSync(file(), { force: true });
273
+ return { stopped: true, killed };
274
+ }
275
+
276
+ // src/profiles.ts
277
+ import { createHash } from "crypto";
278
+ import { closeSync as closeSync2, constants, fsyncSync, lstatSync as lstatSync2, openSync as openSync2, writeSync } from "fs";
279
+ import { join as join2 } from "path";
280
+ var ALIAS = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;
281
+ var FIELD = /^[a-z][a-z0-9_.]{0,63}$/;
282
+ var bad = (why) => {
283
+ throw new BlindfillError("POLICY", `invalid profile: ${why}`);
284
+ };
285
+ function profilesDir() {
286
+ return join2(configDir(), "profiles");
287
+ }
288
+ function canonical(v) {
289
+ if (Array.isArray(v)) return `[${v.map(canonical).join(",")}]`;
290
+ if (v && typeof v === "object")
291
+ return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}`;
292
+ return JSON.stringify(v);
293
+ }
294
+ function validateProfile(raw, name = "profile") {
295
+ if (!ALIAS.test(name)) bad("name must be [A-Za-z0-9][A-Za-z0-9_-]{0,63}");
296
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) bad("expected an object");
297
+ const o = raw;
298
+ for (const k of Object.keys(o))
299
+ if (!["version", "item", "item_name", "web"].includes(k)) bad(`unknown key "${k}"`);
300
+ if (o.version !== 1) bad("version must be 1");
301
+ if (typeof o.item !== "string" || !/^[A-Za-z0-9-]{1,64}$/.test(o.item))
302
+ bad("item must be a backend item id");
303
+ if (o.item_name !== void 0 && (typeof o.item_name !== "string" || !o.item_name || o.item_name.length > 200))
304
+ bad("item_name");
305
+ const w = o.web;
306
+ if (!w || typeof w !== "object") return bad("missing web target");
307
+ for (const k of Object.keys(w))
308
+ if (!["origin", "rule", "fields", "submit"].includes(k)) bad(`unknown web key "${k}"`);
309
+ let origin;
310
+ try {
311
+ const u = new URL(String(w.origin));
312
+ if (!/^https?:$/.test(u.protocol) || u.username || u.password || u.search || u.hash || !["", "/"].includes(u.pathname))
313
+ throw new Error();
314
+ origin = u.origin;
315
+ } catch {
316
+ return bad("web.origin must be a bare http(s) origin");
317
+ }
318
+ if (w.submit !== void 0 && typeof w.submit !== "boolean") bad("web.submit must be boolean");
319
+ let rule;
320
+ if (typeof w.rule === "string") {
321
+ if (!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(w.rule)) bad("web.rule id");
322
+ rule = w.rule;
323
+ } else {
324
+ const [r] = validateRules([w.rule]);
325
+ if ((r.mode ?? "login") !== "login") bad("a profile rule must be a login rule");
326
+ rule = r;
327
+ }
328
+ let fields;
329
+ if (w.fields !== void 0) {
330
+ if (!Array.isArray(w.fields) || !w.fields.length || w.fields.length > 16 || w.fields.some((f) => typeof f !== "string" || !FIELD.test(f)) || new Set(w.fields).size !== w.fields.length)
331
+ bad("web.fields must be a unique list of field names");
332
+ fields = w.fields;
333
+ }
334
+ const doc = {
335
+ version: 1,
336
+ item: o.item,
337
+ ...o.item_name !== void 0 ? { item_name: o.item_name } : {},
338
+ web: { origin, rule, ...fields ? { fields } : {}, submit: w.submit === true }
339
+ };
340
+ if (JSON.stringify(doc).length > 65536) bad("too large");
341
+ return { name, doc, revision: createHash("sha256").update(canonical(doc)).digest("hex") };
342
+ }
343
+ function loadProfile(name, dir = profilesDir()) {
344
+ if (!ALIAS.test(name)) throw new BlindfillError("POLICY", "invalid profile name");
345
+ let text;
346
+ try {
347
+ text = readPrivateFile(dir, `${name}.json`);
348
+ } catch (e) {
349
+ if (e instanceof BlindfillError && e.message === "file not found")
350
+ throw new BlindfillError("NOT_FOUND", "profile not found");
351
+ throw e;
352
+ }
353
+ return validateProfile(strictJson(text), name);
354
+ }
355
+ function assertRevision(p, revision) {
356
+ if (revision !== void 0 && revision !== p.revision)
357
+ throw new BlindfillError(
358
+ "POLICY",
359
+ "profile_revision_mismatch: the recipe changed since it was reviewed; re-validate it"
360
+ );
361
+ }
362
+ function createProfile(name, doc, dir = profilesDir()) {
363
+ const profile = validateProfile(doc, name);
364
+ mkdirPrivate(dir);
365
+ const st = lstatSync2(dir);
366
+ if (!st.isDirectory() || st.isSymbolicLink() || (process.platform === "win32" ? !windowsPathsPrivate([dir]) : process.getuid && st.uid !== process.getuid() || st.mode & 63))
367
+ throw new BlindfillError(
368
+ "POLICY",
369
+ "profiles directory must be a private (0700; on Windows owner-only ACL) directory owned by you"
370
+ );
371
+ const path = join2(dir, `${name}.json`);
372
+ let fd;
373
+ try {
374
+ fd = openSync2(
375
+ path,
376
+ constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,
377
+ 384
378
+ );
379
+ } catch (e) {
380
+ if (e.code === "EEXIST")
381
+ throw new BlindfillError("POLICY", "a profile with that name already exists (never overwritten)");
382
+ throw new BlindfillError("POLICY", "cannot create the profile file");
383
+ }
384
+ try {
385
+ writeSync(fd, JSON.stringify(profile.doc, null, 2) + "\n");
386
+ fsyncSync(fd);
387
+ } finally {
388
+ closeSync2(fd);
389
+ }
390
+ return { path, profile };
391
+ }
392
+
393
+ export {
394
+ loadSession,
395
+ startSession,
396
+ attach,
397
+ attachSession,
398
+ stopSession,
399
+ loadProfile,
400
+ assertRevision,
401
+ createProfile
402
+ };