turno-browser 0.2.0 → 0.4.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.
Files changed (121) hide show
  1. package/CHANGELOG.md +228 -0
  2. package/README.md +205 -16
  3. package/dist/act-model.d.ts +85 -0
  4. package/dist/act-model.js +116 -0
  5. package/dist/act.d.ts +37 -0
  6. package/dist/act.js +599 -0
  7. package/dist/api.d.ts +96 -0
  8. package/dist/api.js +88 -0
  9. package/dist/argv.d.ts +55 -3
  10. package/dist/argv.js +190 -10
  11. package/dist/batch.d.ts +19 -0
  12. package/dist/batch.js +148 -0
  13. package/dist/bench.d.ts +1 -1
  14. package/dist/bench.js +21 -5
  15. package/dist/bin/mcp.js +108 -12
  16. package/dist/captcha.d.ts +77 -0
  17. package/dist/captcha.js +333 -0
  18. package/dist/cdp-relay.d.ts +20 -0
  19. package/dist/cdp-relay.js +101 -0
  20. package/dist/chrome-features.d.ts +23 -0
  21. package/dist/chrome-features.js +44 -0
  22. package/dist/detectors.d.ts +11 -0
  23. package/dist/detectors.js +46 -4
  24. package/dist/diagnose.d.ts +45 -0
  25. package/dist/diagnose.js +326 -0
  26. package/dist/doctor.d.ts +85 -0
  27. package/dist/doctor.js +556 -0
  28. package/dist/engine-attach.d.ts +27 -0
  29. package/dist/engine-attach.js +165 -0
  30. package/dist/engine-camoufox.d.ts +32 -0
  31. package/dist/engine-camoufox.js +270 -0
  32. package/dist/engine-lightpanda.d.ts +72 -0
  33. package/dist/engine-lightpanda.js +292 -0
  34. package/dist/engine.d.ts +119 -0
  35. package/dist/engine.js +355 -0
  36. package/dist/flows.d.ts +127 -0
  37. package/dist/flows.js +294 -0
  38. package/dist/governor.d.ts +119 -0
  39. package/dist/governor.js +325 -0
  40. package/dist/health.d.ts +60 -0
  41. package/dist/health.js +86 -0
  42. package/dist/host.d.ts +95 -0
  43. package/dist/host.js +1181 -0
  44. package/dist/human-input.d.ts +84 -0
  45. package/dist/human-input.js +443 -0
  46. package/dist/humanize.d.ts +123 -0
  47. package/dist/humanize.js +241 -0
  48. package/dist/identities.d.ts +23 -10
  49. package/dist/identities.js +45 -37
  50. package/dist/idle-timer.d.ts +12 -0
  51. package/dist/idle-timer.js +25 -0
  52. package/dist/ids.d.ts +9 -0
  53. package/dist/ids.js +34 -0
  54. package/dist/index.d.ts +21 -6
  55. package/dist/index.js +19 -18
  56. package/dist/lifecycle.d.ts +99 -0
  57. package/dist/lifecycle.js +172 -0
  58. package/dist/live-client.d.ts +22 -0
  59. package/dist/live-client.js +93 -0
  60. package/dist/live-page.d.ts +11 -0
  61. package/dist/live-page.js +143 -0
  62. package/dist/live-server.d.ts +173 -0
  63. package/dist/live-server.js +640 -0
  64. package/dist/live.d.ts +120 -0
  65. package/dist/live.js +203 -0
  66. package/dist/login-tool.d.ts +45 -0
  67. package/dist/login-tool.js +233 -0
  68. package/dist/login.d.ts +8 -3
  69. package/dist/login.js +65 -26
  70. package/dist/network-chrome.d.ts +74 -0
  71. package/dist/network-chrome.js +178 -0
  72. package/dist/network.d.ts +125 -0
  73. package/dist/network.js +263 -0
  74. package/dist/opt-in-settings.d.ts +69 -0
  75. package/dist/opt-in-settings.js +151 -0
  76. package/dist/patchright.d.ts +4 -2
  77. package/dist/patchright.js +4 -2
  78. package/dist/recorder.d.ts +88 -0
  79. package/dist/recorder.js +538 -0
  80. package/dist/recordings.d.ts +116 -0
  81. package/dist/recordings.js +474 -0
  82. package/dist/redact.d.ts +34 -0
  83. package/dist/redact.js +135 -0
  84. package/dist/replay.d.ts +20 -0
  85. package/dist/replay.js +382 -0
  86. package/dist/reputation.d.ts +89 -0
  87. package/dist/reputation.js +203 -0
  88. package/dist/resources.d.ts +76 -0
  89. package/dist/resources.js +341 -0
  90. package/dist/runtime-lock.d.ts +59 -0
  91. package/dist/runtime-lock.js +131 -0
  92. package/dist/sealed.d.ts +8 -0
  93. package/dist/sealed.js +96 -0
  94. package/dist/session-export.d.ts +67 -0
  95. package/dist/session-export.js +194 -0
  96. package/dist/session.d.ts +20 -0
  97. package/dist/session.js +30 -0
  98. package/dist/settings.d.ts +246 -0
  99. package/dist/settings.js +530 -0
  100. package/dist/sharing.d.ts +96 -0
  101. package/dist/sharing.js +269 -0
  102. package/dist/snippet.d.ts +8 -0
  103. package/dist/snippet.js +22 -0
  104. package/dist/tab-locks.d.ts +63 -0
  105. package/dist/tab-locks.js +179 -0
  106. package/dist/tools.d.ts +111 -0
  107. package/dist/tools.js +59 -0
  108. package/dist/totp.d.ts +32 -0
  109. package/dist/totp.js +82 -0
  110. package/dist/tuning.d.ts +76 -0
  111. package/dist/tuning.js +69 -0
  112. package/dist/units.d.ts +8 -0
  113. package/dist/units.js +20 -0
  114. package/dist/upstream.d.ts +243 -0
  115. package/dist/upstream.js +46 -0
  116. package/dist/vault.d.ts +91 -0
  117. package/dist/vault.js +273 -0
  118. package/npm-shrinkwrap.json +1074 -3
  119. package/package.json +5 -4
  120. package/dist/paths.d.ts +0 -17
  121. package/dist/paths.js +0 -17
@@ -0,0 +1,241 @@
1
+ /**
2
+ * Human-like input, the planning half: where the pointer goes and when, how long a key or a
3
+ * button stays down, how a scroll breaks into wheel notches. Pure functions of a seeded random
4
+ * source, so a test with a seed gets the same plan every run; `human-input.ts` plays a plan on a
5
+ * page.
6
+ *
7
+ * Levels (identity.json `humanize.level`, off by default):
8
+ *
9
+ * - `off`: Playwright's own input, as before: one `mousemove` to the exact center of the target,
10
+ * button down and up at once, text inserted in one go.
11
+ * - `light`: the pointer travels a curve from where it last was to a point inside the target, at
12
+ * a steady pace with small timing jitter; the button stays down for tens of milliseconds;
13
+ * short text is typed key by key with per-key delays.
14
+ * - `full`: `light` plus a duration that grows with distance and shrinks with target size
15
+ * (Fitts' law), a slow-fast-slow speed profile, overshoot and correction on long moves, a
16
+ * short pause to read a page the first time it is acted on, longer pauses between words, and
17
+ * scrolling to an element out of view in wheel notches instead of one jump.
18
+ * - `adaptive`: `light`, and `full` on a site after the identity met a challenge page there (the
19
+ * reputation log, or this session).
20
+ *
21
+ * The numbers come from published measurements: a mouse move to a 20 px target 630 px away takes
22
+ * a person about 750-850 ms; the average typist types 52 words a minute (about 230 ms a
23
+ * character, the fast ones about 100 ms); a button press lasts tens of milliseconds to about 150.
24
+ * Typing faster than a few milliseconds a key is physically impossible, so long text is pasted
25
+ * instead (`MAX_TYPED`), like a person pasting it.
26
+ */
27
+ export const HUMANIZE_LEVELS = ["off", "light", "full", "adaptive"];
28
+ /** Text longer than this is pasted (Playwright's `fill`), not typed. */
29
+ export const MAX_TYPED = 80;
30
+ /** A seeded source of random numbers (mulberry32): small, fast and the same on every platform. */
31
+ export class Rng {
32
+ state;
33
+ constructor(seed) {
34
+ this.state = seed >>> 0;
35
+ }
36
+ /** A number in [0, 1). */
37
+ next() {
38
+ this.state = (this.state + 0x6d2b79f5) >>> 0;
39
+ let t = this.state;
40
+ t = Math.imul(t ^ (t >>> 15), t | 1);
41
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
42
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
43
+ }
44
+ range(min, max) {
45
+ return min + (max - min) * this.next();
46
+ }
47
+ chance(p) {
48
+ return this.next() < p;
49
+ }
50
+ /** A normal draw (Box-Muller), clamped to [min, max]. */
51
+ normal(mean, sd, min = Number.NEGATIVE_INFINITY, max = Number.POSITIVE_INFINITY) {
52
+ const u = 1 - this.next();
53
+ const v = this.next();
54
+ const z = Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
55
+ return Math.min(max, Math.max(min, mean + sd * z));
56
+ }
57
+ }
58
+ /** A 32-bit FNV-1a hash, for a seed from a name. */
59
+ export function hashSeed(text) {
60
+ let h = 0x811c9dc5;
61
+ for (let i = 0; i < text.length; i++) {
62
+ h ^= text.charCodeAt(i);
63
+ h = Math.imul(h, 0x01000193);
64
+ }
65
+ return h >>> 0;
66
+ }
67
+ export function personaFor(seed) {
68
+ const rng = new Rng(seed ^ 0x9e3779b9);
69
+ return {
70
+ speed: Number(rng.range(0.85, 1.2).toFixed(3)),
71
+ keyMs: Math.round(rng.range(120, 190)),
72
+ bend: rng.chance(0.5) ? 1 : -1,
73
+ };
74
+ }
75
+ const STEP_MS = 16;
76
+ function bezier(p0, p1, p2, p3, t) {
77
+ const u = 1 - t;
78
+ const a = u * u * u;
79
+ const b = 3 * u * u * t;
80
+ const c = 3 * u * t * t;
81
+ const d = t * t * t;
82
+ return { x: a * p0.x + b * p1.x + c * p2.x + d * p3.x, y: a * p0.y + b * p1.y + c * p2.y + d * p3.y };
83
+ }
84
+ /** Minimum-jerk position profile: slow start, fast middle, slow end. */
85
+ const minimumJerk = (t) => t * t * t * (10 - 15 * t + 6 * t * t);
86
+ /** How long a move takes at each level, before the persona's speed. */
87
+ export function moveDuration(distance, targetWidth, level, rng) {
88
+ if (distance < 1)
89
+ return 0;
90
+ if (level === "light")
91
+ return Math.min(420, Math.max(90, 80 + 0.2 * distance)) * rng.range(0.85, 1.15);
92
+ // Fitts' law, T = a + b log2(D / W + 1), with a and b in the range measured for a mouse.
93
+ const bits = Math.log2(distance / Math.max(8, targetWidth) + 1);
94
+ return (110 + 140 * bits) * rng.range(0.9, 1.15);
95
+ }
96
+ /**
97
+ * A curve from `from` to `to`: a cubic Bezier whose control points bend to one side. The bend is
98
+ * what a wrist pivoting makes: the path strays about a tenth to a sixth of the distance from the
99
+ * straight line, so it is some 3 to 9% longer than that line (a path within 1% of it, as an
100
+ * earlier version drew, reads as a straight line).
101
+ */
102
+ function curve(from, to, duration, level, rng, persona) {
103
+ const dx = to.x - from.x;
104
+ const dy = to.y - from.y;
105
+ const distance = Math.hypot(dx, dy);
106
+ if (distance < 1 || duration <= 0)
107
+ return [{ x: to.x, y: to.y, wait: 0 }];
108
+ const nx = -dy / distance;
109
+ const ny = dx / distance;
110
+ const spread = Math.min(180, distance * (level === "full" ? 0.34 : 0.3));
111
+ const side = rng.chance(0.75) ? persona.bend : -persona.bend;
112
+ const c1 = rng.range(0.15, 0.45);
113
+ const c2 = rng.range(0.55, 0.85);
114
+ // Both control points on the same side: one smooth arc, never an S.
115
+ const h1 = rng.range(0.55, 1) * spread;
116
+ const h2 = rng.range(0.25, 0.75) * spread;
117
+ const p1 = { x: from.x + dx * c1 + nx * side * h1, y: from.y + dy * c1 + ny * side * h1 };
118
+ const p2 = { x: from.x + dx * c2 + nx * side * h2, y: from.y + dy * c2 + ny * side * h2 };
119
+ const count = Math.max(4, Math.round(duration / STEP_MS));
120
+ const steps = [];
121
+ for (let i = 1; i <= count; i++) {
122
+ const t = i / count;
123
+ const p = bezier(from, p1, p2, to, level === "full" ? minimumJerk(t) : t);
124
+ // A little hand tremor on the way, never on the last point.
125
+ const jitter = level === "full" && i < count ? 0.6 : 0;
126
+ steps.push({
127
+ x: p.x + (jitter ? rng.normal(0, jitter) : 0),
128
+ y: p.y + (jitter ? rng.normal(0, jitter) : 0),
129
+ wait: (duration / count) * rng.range(0.8, 1.2),
130
+ });
131
+ }
132
+ return steps;
133
+ }
134
+ /**
135
+ * The pointer path from `from` to `to` (which ends exactly on `to`), with the wait before each
136
+ * position. `targetWidth` is the smaller side of the target, for Fitts' law.
137
+ */
138
+ export function planMove(from, to, targetWidth, level, rng, persona) {
139
+ const distance = Math.hypot(to.x - from.x, to.y - from.y);
140
+ if (distance < 1)
141
+ return [];
142
+ const duration = moveDuration(distance, targetWidth, level, rng) / persona.speed;
143
+ if (level === "full" && distance > 250 && rng.chance(0.7)) {
144
+ // Overshoot: the fast first movement lands past the target, a short second one corrects.
145
+ const ux = (to.x - from.x) / distance;
146
+ const uy = (to.y - from.y) / distance;
147
+ const past = Math.min(40, distance * rng.range(0.03, 0.07));
148
+ const sideways = rng.normal(0, past / 3);
149
+ const over = { x: to.x + ux * past - uy * sideways, y: to.y + uy * past + ux * sideways };
150
+ const first = curve(from, over, duration * 0.85, level, rng, persona);
151
+ const back = curve(over, to, rng.range(90, 170) / persona.speed, "light", rng, persona);
152
+ const [start, ...rest] = back;
153
+ if (start)
154
+ start.wait += rng.range(40, 110); // the eye sees the miss before the hand corrects
155
+ return [...first, ...(start ? [start] : []), ...rest];
156
+ }
157
+ return curve(from, to, duration, level, rng, persona);
158
+ }
159
+ /**
160
+ * A point inside the box: near the middle, never the exact center and never on the edge (a
161
+ * person aims at the visible middle of a button, and lands a few pixels off).
162
+ */
163
+ export function pickPoint(box, rng) {
164
+ const fx = rng.normal(0.5, 0.12, 0.2, 0.8);
165
+ const fy = rng.normal(0.5, 0.12, 0.25, 0.75);
166
+ return { x: box.x + box.width * fx, y: box.y + box.height * fy };
167
+ }
168
+ export function clickTiming(level, rng) {
169
+ if (level === "light")
170
+ return { beforePress: rng.range(10, 50), press: rng.range(40, 90) };
171
+ return { beforePress: rng.range(60, 200), press: rng.normal(90, 25, 45, 170) };
172
+ }
173
+ /** A pause to look at a page acted on for the first time (`full` only). */
174
+ export function readingPause(rng) {
175
+ return rng.range(250, 800);
176
+ }
177
+ /** How long a key stays down, in ms. */
178
+ export function keyHold(level, rng) {
179
+ return level === "light" ? rng.range(30, 70) : rng.normal(75, 20, 35, 140);
180
+ }
181
+ /**
182
+ * The wait before each character of `text` (the first one included: the hand moves to the
183
+ * keyboard), in ms. `light`: the persona's pace with jitter. `full`: a skewed draw around the
184
+ * pace, faster inside a word than across a space, longer after punctuation, and now and then a
185
+ * pause to think.
186
+ */
187
+ export function keyDelays(text, level, rng, persona) {
188
+ const chars = [...text];
189
+ const out = [];
190
+ for (let i = 0; i < chars.length; i++) {
191
+ const prev = i ? chars[i - 1] : "";
192
+ if (level === "light") {
193
+ out.push(persona.keyMs * rng.range(0.6, 1.3) * 0.8);
194
+ continue;
195
+ }
196
+ // A log-normal draw: most keys near the pace, a long tail of slower ones.
197
+ let wait = persona.keyMs * Math.exp(rng.normal(-0.1, 0.35, -1, 1.2));
198
+ if (prev === " ")
199
+ wait += rng.range(40, 160);
200
+ else if (/[.,;:!?]/.test(prev))
201
+ wait += rng.range(120, 300);
202
+ if (i === 0)
203
+ wait += rng.range(80, 200);
204
+ else if (rng.chance(0.03))
205
+ wait += rng.range(300, 800);
206
+ out.push(wait);
207
+ }
208
+ return out;
209
+ }
210
+ /**
211
+ * A scroll of (dx, dy) in wheel notches of about 100 px, in short bursts with a pause between
212
+ * them, the way a mouse wheel turns (`full`). The notches add up to exactly (dx, dy).
213
+ */
214
+ export function planWheel(dx, dy, rng) {
215
+ const total = Math.max(Math.abs(dx), Math.abs(dy));
216
+ if (total === 0)
217
+ return [];
218
+ const count = Math.max(1, Math.round(total / 100));
219
+ const out = [];
220
+ let burst = Math.round(rng.range(2, 6));
221
+ let sentX = 0;
222
+ let sentY = 0;
223
+ for (let i = 1; i <= count; i++) {
224
+ const x = Math.round((dx * i) / count) - sentX;
225
+ const y = Math.round((dy * i) / count) - sentY;
226
+ sentX += x;
227
+ sentY += y;
228
+ let wait = rng.range(25, 70);
229
+ if (--burst === 0) {
230
+ wait += rng.range(120, 350);
231
+ burst = Math.round(rng.range(2, 6));
232
+ }
233
+ out.push({ dx: x, dy: y, wait: i === 1 ? rng.range(20, 60) : wait });
234
+ }
235
+ return out;
236
+ }
237
+ /** The total time of a plan, in ms. */
238
+ export function planTime(steps) {
239
+ return steps.reduce((sum, s) => sum + s.wait, 0);
240
+ }
241
+ //# sourceMappingURL=humanize.js.map
@@ -1,9 +1,11 @@
1
- export declare class IdentityError extends Error {
2
- constructor(message: string);
3
- }
4
- export declare function isValidIdentityId(id: string): boolean;
5
- export declare function assertIdentityId(id: string): void;
6
- export declare function identityDir(id: string, env?: NodeJS.ProcessEnv): string;
1
+ import { IdentityError, assertIdentityId, identityDir, identityStateDir, isValidIdentityId } from "./ids.js";
2
+ import { type SettingsPatch } from "./settings.js";
3
+ export { IdentityError, assertIdentityId, identityDir, identityStateDir, isValidIdentityId };
4
+ /**
5
+ * A browser identity is a persistent Chrome user data dir (cookies, local storage, saved
6
+ * logins) under `<data>/browser/identities/<id>`. One identity maps to one mcpd server
7
+ * (`browser-<id>`), so a site login done once by hand is reused by every session.
8
+ */
7
9
  export interface IdentityInfo {
8
10
  id: string;
9
11
  dir: string;
@@ -12,14 +14,25 @@ export interface IdentityInfo {
12
14
  }
13
15
  export declare function identityExists(id: string, env?: NodeJS.ProcessEnv): boolean;
14
16
  export declare function listIdentities(env?: NodeJS.ProcessEnv): IdentityInfo[];
15
- /** Create the identity dir (mode 700). Returns its info; adding an existing identity is a no-op. */
16
- export declare function addIdentity(id: string, env?: NodeJS.ProcessEnv): IdentityInfo;
17
- /** Delete the identity and everything in its profile. Refuses while Chrome holds it. */
17
+ /**
18
+ * Create the identity dir (mode 700) and return its info. A new identity also gets its
19
+ * identity.json, pinned to the system time zone plus the settings given, so it keeps the same
20
+ * zone and languages from then on. Adding an existing identity changes nothing,
21
+ * unless settings are given: then they are written to its identity.json.
22
+ */
23
+ export declare function addIdentity(id: string, env?: NodeJS.ProcessEnv, settings?: SettingsPatch, now?: Date): IdentityInfo;
24
+ /**
25
+ * Delete the identity: its profile, its identity.json and what turno wrote for it (runtime
26
+ * state, health, reputation log). Refuses while Chrome holds it, and while its vault still has
27
+ * credentials (their secret store items would be left behind; `vaultClear` removes them first).
28
+ */
18
29
  export declare function removeIdentity(id: string, env?: NodeJS.ProcessEnv): void;
19
30
  /**
20
31
  * Chrome writes `SingletonLock` as a symlink whose target is `<hostname>-<pid>`.
21
32
  * Returns the PID, or undefined when the target does not have that shape.
22
33
  */
23
34
  export declare function parseSingletonLock(target: string): number | undefined;
24
- /** True when the identity's Chrome profile is locked by a live process. */
35
+ /** Who holds the identity right now (its runtime lock), as a message; undefined when nobody does. */
36
+ export declare function inUseBy(id: string, env?: NodeJS.ProcessEnv): string | undefined;
37
+ /** True when a live process holds the identity's runtime lock or its Chrome profile. */
25
38
  export declare function isInUse(id: string, env?: NodeJS.ProcessEnv): boolean;
@@ -1,30 +1,13 @@
1
1
  import { existsSync, mkdirSync, readdirSync, readlinkSync, rmSync, statSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { paths } from "./paths.js";
4
- /**
5
- * A browser identity is a persistent Chrome user data dir (cookies, local storage, saved
6
- * logins) under `<data>/browser/identities/<id>`. One identity maps to one mcpd server
7
- * (`browser-<id>`), so a site login done once by hand is reused by every session.
8
- */
9
- const IDENTITY_ID = /^[a-z0-9][a-z0-9_-]*$/;
10
- export class IdentityError extends Error {
11
- constructor(message) {
12
- super(message);
13
- this.name = "IdentityError";
14
- }
15
- }
16
- export function isValidIdentityId(id) {
17
- return IDENTITY_ID.test(id) && id.length <= 64;
18
- }
19
- export function assertIdentityId(id) {
20
- if (!isValidIdentityId(id)) {
21
- throw new IdentityError(`invalid identity "${id}": use lowercase letters, digits, "-" and "_", starting with a letter or digit`);
22
- }
23
- }
24
- export function identityDir(id, env = process.env) {
25
- assertIdentityId(id);
26
- return join(paths(env).identitiesDir, id);
27
- }
3
+ import { browserPaths as paths } from "turno-core/paths";
4
+ import { pidAlive } from "turno-core/process";
5
+ import { IdentityError, assertIdentityId, identityDir, identityStateDir, isValidIdentityId } from "./ids.js";
6
+ import { removeFlows } from "./flows.js";
7
+ import { inUseMessage, readRuntimeLock, runtimeLockAlive } from "./runtime-lock.js";
8
+ import { identitySettingsPath, systemTimezone, writeIdentitySettings } from "./settings.js";
9
+ import { vaultHasSites, vaultPath } from "./vault.js";
10
+ export { IdentityError, assertIdentityId, identityDir, identityStateDir, isValidIdentityId };
28
11
  export function identityExists(id, env = process.env) {
29
12
  const dir = identityDir(id, env);
30
13
  return existsSync(dir) && statSync(dir).isDirectory();
@@ -44,20 +27,47 @@ export function listIdentities(env = process.env) {
44
27
  }
45
28
  return names.sort().map((id) => ({ id, dir: join(root, id), inUse: isInUse(id, env) }));
46
29
  }
47
- /** Create the identity dir (mode 700). Returns its info; adding an existing identity is a no-op. */
48
- export function addIdentity(id, env = process.env) {
30
+ /**
31
+ * Create the identity dir (mode 700) and return its info. A new identity also gets its
32
+ * identity.json, pinned to the system time zone plus the settings given, so it keeps the same
33
+ * zone and languages from then on. Adding an existing identity changes nothing,
34
+ * unless settings are given: then they are written to its identity.json.
35
+ */
36
+ export function addIdentity(id, env = process.env, settings = {}, now = new Date()) {
49
37
  const dir = identityDir(id, env);
38
+ const created = !existsSync(dir);
39
+ const given = Object.values(settings).some((v) => v !== undefined);
40
+ if (created && !existsSync(identitySettingsPath(id, env))) {
41
+ // Validate before creating anything, so a bad setting leaves no half-made identity.
42
+ writeIdentitySettings(id, { timezone: systemTimezone(), ...settings }, env, now);
43
+ }
44
+ else if (given) {
45
+ writeIdentitySettings(id, settings, env, now);
46
+ }
50
47
  mkdirSync(dir, { recursive: true, mode: 0o700 });
51
48
  return { id, dir, inUse: isInUse(id, env) };
52
49
  }
53
- /** Delete the identity and everything in its profile. Refuses while Chrome holds it. */
50
+ /**
51
+ * Delete the identity: its profile, its identity.json and what turno wrote for it (runtime
52
+ * state, health, reputation log). Refuses while Chrome holds it, and while its vault still has
53
+ * credentials (their secret store items would be left behind; `vaultClear` removes them first).
54
+ */
54
55
  export function removeIdentity(id, env = process.env) {
55
56
  const dir = identityDir(id, env);
56
57
  if (!existsSync(dir))
57
58
  throw new IdentityError(`identity "${id}" does not exist`);
59
+ const holder = inUseBy(id, env);
60
+ if (holder)
61
+ throw new IdentityError(`${holder} Remove it after that.`);
58
62
  if (isInUse(id, env))
59
63
  throw new IdentityError(`identity "${id}" is in use by a running Chrome; close it first`);
64
+ if (vaultHasSites(id, env))
65
+ throw new IdentityError(`identity "${id}" still has vault credentials; remove them first (turno browser remove does)`);
60
66
  rmSync(dir, { recursive: true, force: true });
67
+ rmSync(vaultPath(id, env), { force: true });
68
+ rmSync(identitySettingsPath(id, env), { force: true });
69
+ rmSync(identityStateDir(id, env), { recursive: true, force: true });
70
+ removeFlows(id, env);
61
71
  }
62
72
  /**
63
73
  * Chrome writes `SingletonLock` as a symlink whose target is `<hostname>-<pid>`.
@@ -70,17 +80,15 @@ export function parseSingletonLock(target) {
70
80
  const pid = Number(m[1]);
71
81
  return Number.isSafeInteger(pid) && pid > 0 ? pid : undefined;
72
82
  }
73
- function pidAlive(pid) {
74
- try {
75
- process.kill(pid, 0);
76
- return true;
77
- }
78
- catch (err) {
79
- return err.code === "EPERM";
80
- }
83
+ /** Who holds the identity right now (its runtime lock), as a message; undefined when nobody does. */
84
+ export function inUseBy(id, env = process.env) {
85
+ const lock = readRuntimeLock(id, env);
86
+ return lock && runtimeLockAlive(lock) ? inUseMessage(id, lock) : undefined;
81
87
  }
82
- /** True when the identity's Chrome profile is locked by a live process. */
88
+ /** True when a live process holds the identity's runtime lock or its Chrome profile. */
83
89
  export function isInUse(id, env = process.env) {
90
+ if (inUseBy(id, env))
91
+ return true;
84
92
  let target;
85
93
  try {
86
94
  target = readlinkSync(join(identityDir(id, env), "SingletonLock"));
@@ -0,0 +1,12 @@
1
+ import type { IdleTimerLike, McpConfig } from "./upstream.js";
2
+ /** Upstream's `IdleTimer`: every tool call restarts the countdown. */
3
+ export declare class IdleTimer implements IdleTimerLike {
4
+ private readonly ms;
5
+ private readonly onIdle;
6
+ private timer;
7
+ constructor(ms: number, onIdle: () => void);
8
+ poke(): void;
9
+ dispose(): void;
10
+ }
11
+ /** The idle limit of a browser turno starts or attaches to: the config's, else upstream's headless default. */
12
+ export declare function idleMs(config: McpConfig): number | undefined;
@@ -0,0 +1,25 @@
1
+ /** Upstream's default idle limit for a headless browser it owns (`defaultIdleTimeout`). */
2
+ const HEADLESS_IDLE_MS = 60 * 60 * 1000;
3
+ /** Upstream's `IdleTimer`: every tool call restarts the countdown. */
4
+ export class IdleTimer {
5
+ ms;
6
+ onIdle;
7
+ timer;
8
+ constructor(ms, onIdle) {
9
+ this.ms = ms;
10
+ this.onIdle = onIdle;
11
+ }
12
+ poke() {
13
+ this.dispose();
14
+ this.timer = setTimeout(this.onIdle, this.ms);
15
+ }
16
+ dispose() {
17
+ clearTimeout(this.timer);
18
+ this.timer = undefined;
19
+ }
20
+ }
21
+ /** The idle limit of a browser turno starts or attaches to: the config's, else upstream's headless default. */
22
+ export function idleMs(config) {
23
+ return config.timeouts?.idle ?? (config.browser.launchOptions.headless ? HEADLESS_IDLE_MS : undefined);
24
+ }
25
+ //# sourceMappingURL=idle-timer.js.map
package/dist/ids.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ export declare class IdentityError extends Error {
2
+ constructor(message: string);
3
+ }
4
+ export declare function isValidIdentityId(id: string): boolean;
5
+ export declare function assertIdentityId(id: string): void;
6
+ /** The identity's Chrome profile (user data dir). */
7
+ export declare function identityDir(id: string, env?: NodeJS.ProcessEnv): string;
8
+ /** What turno-browser writes for the identity while it runs, outside the Chrome profile. */
9
+ export declare function identityStateDir(id: string, env?: NodeJS.ProcessEnv): string;
package/dist/ids.js ADDED
@@ -0,0 +1,34 @@
1
+ import { join } from "node:path";
2
+ import { browserPaths as paths } from "turno-core/paths";
3
+ /**
4
+ * Identity ids and where each identity lives. A browser identity is a persistent Chrome user
5
+ * data dir under `<data>/browser/identities/<id>`, its settings in `<id>.json` next to it, and
6
+ * what turno-browser writes while it runs (generated config, runtime lock, session health,
7
+ * reputation log) under `<state>/browser/identities/<id>`.
8
+ */
9
+ const IDENTITY_ID = /^[a-z0-9][a-z0-9_-]*$/;
10
+ export class IdentityError extends Error {
11
+ constructor(message) {
12
+ super(message);
13
+ this.name = "IdentityError";
14
+ }
15
+ }
16
+ export function isValidIdentityId(id) {
17
+ return IDENTITY_ID.test(id) && id.length <= 64;
18
+ }
19
+ export function assertIdentityId(id) {
20
+ if (!isValidIdentityId(id)) {
21
+ throw new IdentityError(`invalid identity "${id}": use lowercase letters, digits, "-" and "_", starting with a letter or digit`);
22
+ }
23
+ }
24
+ /** The identity's Chrome profile (user data dir). */
25
+ export function identityDir(id, env = process.env) {
26
+ assertIdentityId(id);
27
+ return join(paths(env).identitiesDir, id);
28
+ }
29
+ /** What turno-browser writes for the identity while it runs, outside the Chrome profile. */
30
+ export function identityStateDir(id, env = process.env) {
31
+ assertIdentityId(id);
32
+ return join(paths(env).identityStateDir, id);
33
+ }
34
+ //# sourceMappingURL=ids.js.map
package/dist/index.d.ts CHANGED
@@ -1,11 +1,26 @@
1
- export { IdentityError, type IdentityInfo, addIdentity, assertIdentityId, identityDir, identityExists, isInUse, isValidIdentityId, listIdentities, parseSingletonLock, removeIdentity, } from "./identities.js";
2
- export { type BuiltArgv, buildArgv, extractIdentity } from "./argv.js";
1
+ export { API_VERSION, type ApiVersion, type BrowserApi, api } from "./api.js";
2
+ export { SESSION_CAPABILITY, SESSION_ENDED_METHOD, SESSION_META_KEY } from "./session.js";
3
+ export { manifestSnippet } from "./snippet.js";
4
+ export { IdentityError, type IdentityInfo, addIdentity, assertIdentityId, identityDir, identityExists, identityStateDir, inUseBy, isInUse, isValidIdentityId, listIdentities, parseSingletonLock, removeIdentity, } from "./identities.js";
5
+ export { type HealthCheck, IDENTITY_FORMAT_VERSION, type IdentitySettings, type LiveSettings, type RecordSettings, type SettingsPatch, type TabLockSettings, checkIdentitySettings, identitySettingsPath, readIdentitySettings, systemTimezone, writeIdentitySettings, } from "./settings.js";
6
+ export { IdentityInUseError, type RuntimeLock, readRuntimeLock, runtimeLockAlive, runtimeLockPath, } from "./runtime-lock.js";
7
+ export { type HealthRecord, readHealth } from "./health.js";
8
+ export { type ChallengeEvent, type IdentityReputation, type SiteSummary, readChallenges, reputationReport, } from "./reputation.js";
9
+ export { type ChromeInfo, type DoctorCheck, type DoctorOptions, type DoctorReport, type ServedIdentity, findChrome, runDoctor, } from "./doctor.js";
10
+ export { type BuiltArgv, type PlaywrightMcpConfig, buildArgv, extractIdentity } from "./argv.js";
3
11
  export { type BenchOptions, type BenchReport, DETECTORS, ENGINES, ENGINE_ALIASES, type EngineName, type EngineReport, type TargetResult, defaultEngines, engineId, formatBenchTable, runBench, unavailableReason, } from "./bench.js";
4
- export { CHALLENGE_MARKERS, detectChallenge, parseRebrowser, parseSannysoft } from "./detectors.js";
12
+ export { CHALLENGE_MARKERS, type ChallengeKind, classifyChallenge, detectChallenge, parseRebrowser, parseSannysoft, } from "./detectors.js";
5
13
  export { type LoginOptions, loginIdentity } from "./login.js";
14
+ export { LiveError, liveLink, livePause, liveResume, liveStatus } from "./live-client.js";
15
+ export type { LiveStatus } from "./live-server.js";
16
+ export { type TotpParams, TotpError, parseTotpSecret, totp } from "./totp.js";
17
+ export { SealError } from "./sealed.js";
18
+ export { type ExportOptions, type ImportOptions, type SessionSummary, exportSession, importSession, readSessionExport, } from "./session-export.js";
19
+ export { type SubmitPolicy, type VaultAddInput, VaultError, type VaultInfo, type VaultSite, vaultAdd, vaultClear, vaultList, vaultPath, vaultRemove, vaultSetSubmit, } from "./vault.js";
20
+ export { type Flow, FlowError, type FlowLocator, type FlowParam, type FlowStep, type FlowSummary, type FlowTarget, type ParamRef, flowsDir, listFlows, readFlow, removeFlow, } from "./flows.js";
21
+ export { type ReplayOptions, replayFlow } from "./replay.js";
22
+ export { type RecordingSummary, listRecordings, openTraceViewer, recordingsDir, traceViewerCommand, } from "./recordings.js";
6
23
  export { mcpEntryPath } from "./patchright.js";
7
- export { paths } from "./paths.js";
24
+ export { browserPaths as paths } from "turno-core/paths";
8
25
  /** Absolute path of the `turno-browser-mcp` executable script of this install. */
9
26
  export declare function mcpBinPath(): string;
10
- /** The mcp.toml block that serves one identity through mcpd (one session at a time). */
11
- export declare function manifestSnippet(id: string): string;
package/dist/index.js CHANGED
@@ -1,28 +1,29 @@
1
1
  import { fileURLToPath } from "node:url";
2
- import { assertIdentityId } from "./identities.js";
3
- export { IdentityError, addIdentity, assertIdentityId, identityDir, identityExists, isInUse, isValidIdentityId, listIdentities, parseSingletonLock, removeIdentity, } from "./identities.js";
2
+ export { API_VERSION, api } from "./api.js";
3
+ export { SESSION_CAPABILITY, SESSION_ENDED_METHOD, SESSION_META_KEY } from "./session.js";
4
+ export { manifestSnippet } from "./snippet.js";
5
+ export { IdentityError, addIdentity, assertIdentityId, identityDir, identityExists, identityStateDir, inUseBy, isInUse, isValidIdentityId, listIdentities, parseSingletonLock, removeIdentity, } from "./identities.js";
6
+ export { IDENTITY_FORMAT_VERSION, checkIdentitySettings, identitySettingsPath, readIdentitySettings, systemTimezone, writeIdentitySettings, } from "./settings.js";
7
+ export { IdentityInUseError, readRuntimeLock, runtimeLockAlive, runtimeLockPath, } from "./runtime-lock.js";
8
+ export { readHealth } from "./health.js";
9
+ export { readChallenges, reputationReport, } from "./reputation.js";
10
+ export { findChrome, runDoctor, } from "./doctor.js";
4
11
  export { buildArgv, extractIdentity } from "./argv.js";
5
12
  export { DETECTORS, ENGINES, ENGINE_ALIASES, defaultEngines, engineId, formatBenchTable, runBench, unavailableReason, } from "./bench.js";
6
- export { CHALLENGE_MARKERS, detectChallenge, parseRebrowser, parseSannysoft } from "./detectors.js";
13
+ export { CHALLENGE_MARKERS, classifyChallenge, detectChallenge, parseRebrowser, parseSannysoft, } from "./detectors.js";
7
14
  export { loginIdentity } from "./login.js";
15
+ export { LiveError, liveLink, livePause, liveResume, liveStatus } from "./live-client.js";
16
+ export { TotpError, parseTotpSecret, totp } from "./totp.js";
17
+ export { SealError } from "./sealed.js";
18
+ export { exportSession, importSession, readSessionExport, } from "./session-export.js";
19
+ export { VaultError, vaultAdd, vaultClear, vaultList, vaultPath, vaultRemove, vaultSetSubmit, } from "./vault.js";
20
+ export { FlowError, flowsDir, listFlows, readFlow, removeFlow, } from "./flows.js";
21
+ export { replayFlow } from "./replay.js";
22
+ export { listRecordings, openTraceViewer, recordingsDir, traceViewerCommand, } from "./recordings.js";
8
23
  export { mcpEntryPath } from "./patchright.js";
9
- export { paths } from "./paths.js";
24
+ export { browserPaths as paths } from "turno-core/paths";
10
25
  /** Absolute path of the `turno-browser-mcp` executable script of this install. */
11
26
  export function mcpBinPath() {
12
27
  return fileURLToPath(new URL("./bin/mcp.js", import.meta.url));
13
28
  }
14
- /** The mcp.toml block that serves one identity through mcpd (one session at a time). */
15
- export function manifestSnippet(id) {
16
- assertIdentityId(id);
17
- return [
18
- `[server.browser-${id}]`,
19
- `command = "turno-browser-mcp"`,
20
- `args = ["--identity", "${id}"]`,
21
- `scope = "shared"`,
22
- `exclusive = true`,
23
- `lease = "10m"`,
24
- `idle = "30m"`,
25
- "",
26
- ].join("\n");
27
- }
28
29
  //# sourceMappingURL=index.js.map