@namzu/browser 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.
Files changed (74) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/LICENSE.md +110 -0
  3. package/README.md +149 -0
  4. package/dist/classifier.d.ts +70 -0
  5. package/dist/classifier.d.ts.map +1 -0
  6. package/dist/classifier.js +147 -0
  7. package/dist/classifier.js.map +1 -0
  8. package/dist/detect.d.ts +126 -0
  9. package/dist/detect.d.ts.map +1 -0
  10. package/dist/detect.js +282 -0
  11. package/dist/detect.js.map +1 -0
  12. package/dist/errors.d.ts +64 -0
  13. package/dist/errors.d.ts.map +1 -0
  14. package/dist/errors.js +99 -0
  15. package/dist/errors.js.map +1 -0
  16. package/dist/host.d.ts +167 -0
  17. package/dist/host.d.ts.map +1 -0
  18. package/dist/host.js +1024 -0
  19. package/dist/host.js.map +1 -0
  20. package/dist/index.d.ts +17 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +10 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/page-scripts.d.ts +51 -0
  25. package/dist/page-scripts.d.ts.map +1 -0
  26. package/dist/page-scripts.js +123 -0
  27. package/dist/page-scripts.js.map +1 -0
  28. package/dist/policy.d.ts +61 -0
  29. package/dist/policy.d.ts.map +1 -0
  30. package/dist/policy.js +150 -0
  31. package/dist/policy.js.map +1 -0
  32. package/dist/profiles.d.ts +107 -0
  33. package/dist/profiles.d.ts.map +1 -0
  34. package/dist/profiles.js +312 -0
  35. package/dist/profiles.js.map +1 -0
  36. package/dist/relay.d.ts +27 -0
  37. package/dist/relay.d.ts.map +1 -0
  38. package/dist/relay.js +69 -0
  39. package/dist/relay.js.map +1 -0
  40. package/dist/snapshot.d.ts +101 -0
  41. package/dist/snapshot.d.ts.map +1 -0
  42. package/dist/snapshot.js +265 -0
  43. package/dist/snapshot.js.map +1 -0
  44. package/dist/windows-bridge-script.d.ts +29 -0
  45. package/dist/windows-bridge-script.d.ts.map +1 -0
  46. package/dist/windows-bridge-script.js +161 -0
  47. package/dist/windows-bridge-script.js.map +1 -0
  48. package/dist/windows-bridge.d.ts +120 -0
  49. package/dist/windows-bridge.d.ts.map +1 -0
  50. package/dist/windows-bridge.js +267 -0
  51. package/dist/windows-bridge.js.map +1 -0
  52. package/dist/windows-engine.d.ts +55 -0
  53. package/dist/windows-engine.d.ts.map +1 -0
  54. package/dist/windows-engine.js +154 -0
  55. package/dist/windows-engine.js.map +1 -0
  56. package/dist/wsl.d.ts +52 -0
  57. package/dist/wsl.d.ts.map +1 -0
  58. package/dist/wsl.js +134 -0
  59. package/dist/wsl.js.map +1 -0
  60. package/package.json +74 -0
  61. package/src/classifier.ts +191 -0
  62. package/src/detect.ts +432 -0
  63. package/src/errors.ts +121 -0
  64. package/src/host.ts +1217 -0
  65. package/src/index.ts +79 -0
  66. package/src/page-scripts.ts +154 -0
  67. package/src/policy.ts +190 -0
  68. package/src/profiles.ts +373 -0
  69. package/src/relay.ts +101 -0
  70. package/src/snapshot.ts +317 -0
  71. package/src/windows-bridge-script.ts +160 -0
  72. package/src/windows-bridge.ts +358 -0
  73. package/src/windows-engine.ts +208 -0
  74. package/src/wsl.ts +155 -0
@@ -0,0 +1,373 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import {
3
+ chmodSync,
4
+ lstatSync,
5
+ mkdirSync,
6
+ readFileSync,
7
+ readdirSync,
8
+ renameSync,
9
+ rmSync,
10
+ writeFileSync,
11
+ } from 'node:fs'
12
+ import { join } from 'node:path'
13
+ import { ProfileBusyError } from './errors.js'
14
+ import { DEFAULT_WSL_MOUNT_ROOT, windowsPathToWsl } from './wsl.js'
15
+
16
+ /**
17
+ * Browser profiles and the leases on them, under `NAMZU_HOME/browser`:
18
+ *
19
+ * ```text
20
+ * browser/
21
+ * profiles/<name>.json the descriptor
22
+ * profiles/<name>/ the browser's user data directory (0700)
23
+ * leases/<name>/<pid>-<session>.json
24
+ * ```
25
+ *
26
+ * A profile of the Windows engine (WSL driving the Windows browser) keeps its
27
+ * user data on the Windows side, under
28
+ * `%LOCALAPPDATA%\namzu\browser\profiles\<name>`; only the descriptor is
29
+ * here, and its `userDataDir` is that Windows path.
30
+ *
31
+ * A profile is where a site's sign-in lives: the operator signs in once in
32
+ * a visible window, and every later run reuses the cookies. Every directory
33
+ * here is created 0700, because what is inside is as good as a password.
34
+ */
35
+
36
+ /** Profile names: lowercase words joined by single hyphens. */
37
+ export const BROWSER_PROFILE_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
38
+
39
+ export const DEFAULT_BROWSER_PROFILE = 'default'
40
+
41
+ export interface BrowserProfileDescriptor {
42
+ readonly v: 1
43
+ readonly name: string
44
+ /** The engine whose browser owns the user data directory. */
45
+ readonly engine: 'local' | 'windows-cdp'
46
+ /** The browser's user data directory, in the engine's own path syntax. */
47
+ readonly userDataDir: string
48
+ /** `chrome`, `msedge` or `chromium`. */
49
+ readonly browser: string
50
+ readonly createdAt: string
51
+ readonly lastLoginAt?: string
52
+ }
53
+
54
+ export class BrowserProfileError extends Error {
55
+ override readonly name = 'BrowserProfileError'
56
+ }
57
+
58
+ function assertName(name: string): void {
59
+ if (name.length > 64 || !BROWSER_PROFILE_NAME.test(name)) {
60
+ throw new BrowserProfileError(
61
+ `"${name}" is not a profile name: use lowercase letters, digits and single hyphens, at most 64 characters.`,
62
+ )
63
+ }
64
+ }
65
+
66
+ function ensurePrivateDir(path: string): void {
67
+ mkdirSync(path, { recursive: true, mode: 0o700 })
68
+ const stat = lstatSync(path)
69
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
70
+ throw new BrowserProfileError(`${path} is not a real directory.`)
71
+ }
72
+ if (process.platform !== 'win32' && (stat.mode & 0o077) !== 0) chmodSync(path, 0o700)
73
+ }
74
+
75
+ function writeJsonAtomic(path: string, value: unknown): void {
76
+ const temp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`
77
+ writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 })
78
+ renameSync(temp, path)
79
+ }
80
+
81
+ function isDescriptor(value: unknown, name: string): value is BrowserProfileDescriptor {
82
+ if (typeof value !== 'object' || value === null) return false
83
+ const v = value as Record<string, unknown>
84
+ return (
85
+ v.v === 1 &&
86
+ v.name === name &&
87
+ (v.engine === 'local' || v.engine === 'windows-cdp') &&
88
+ typeof v.userDataDir === 'string' &&
89
+ typeof v.browser === 'string' &&
90
+ typeof v.createdAt === 'string'
91
+ )
92
+ }
93
+
94
+ export class BrowserProfileStore {
95
+ readonly root: string
96
+
97
+ /** `home` is `NAMZU_HOME`. */
98
+ constructor(readonly home: string) {
99
+ this.root = join(home, 'browser', 'profiles')
100
+ }
101
+
102
+ /** Where a local engine keeps this profile's user data. */
103
+ localUserDataDir(name: string): string {
104
+ assertName(name)
105
+ return join(this.root, name)
106
+ }
107
+
108
+ get(name: string): BrowserProfileDescriptor | undefined {
109
+ assertName(name)
110
+ let text: string
111
+ try {
112
+ text = readFileSync(join(this.root, `${name}.json`), 'utf8')
113
+ } catch {
114
+ return undefined
115
+ }
116
+ let parsed: unknown
117
+ try {
118
+ parsed = JSON.parse(text)
119
+ } catch {
120
+ throw new BrowserProfileError(`The descriptor of browser profile "${name}" is not JSON.`)
121
+ }
122
+ if (!isDescriptor(parsed, name)) {
123
+ throw new BrowserProfileError(`The descriptor of browser profile "${name}" is not readable.`)
124
+ }
125
+ return parsed
126
+ }
127
+
128
+ list(): BrowserProfileDescriptor[] {
129
+ let entries: string[]
130
+ try {
131
+ entries = readdirSync(this.root)
132
+ } catch {
133
+ return []
134
+ }
135
+ const out: BrowserProfileDescriptor[] = []
136
+ for (const entry of entries.sort()) {
137
+ if (!entry.endsWith('.json')) continue
138
+ const name = entry.slice(0, -'.json'.length)
139
+ if (!BROWSER_PROFILE_NAME.test(name)) continue
140
+ try {
141
+ const descriptor = this.get(name)
142
+ if (descriptor) out.push(descriptor)
143
+ } catch {
144
+ // An unreadable descriptor is skipped in a listing; `get` reports it.
145
+ }
146
+ }
147
+ return out
148
+ }
149
+
150
+ /**
151
+ * The profile's descriptor, created with a 0700 local user data directory
152
+ * when it does not exist yet.
153
+ */
154
+ ensureLocal(name: string, browser: string, now: Date = new Date()): BrowserProfileDescriptor {
155
+ const existing = this.get(name)
156
+ if (existing) {
157
+ if (existing.engine !== 'local') {
158
+ throw new BrowserProfileError(
159
+ `Browser profile "${name}" belongs to the ${existing.engine} engine, not this local browser. Use another profile name.`,
160
+ )
161
+ }
162
+ ensurePrivateDir(existing.userDataDir)
163
+ return existing
164
+ }
165
+ ensurePrivateDir(join(this.home, 'browser'))
166
+ ensurePrivateDir(this.root)
167
+ const userDataDir = this.localUserDataDir(name)
168
+ ensurePrivateDir(userDataDir)
169
+ const descriptor: BrowserProfileDescriptor = {
170
+ v: 1,
171
+ name,
172
+ engine: 'local',
173
+ userDataDir,
174
+ browser,
175
+ createdAt: now.toISOString(),
176
+ }
177
+ writeJsonAtomic(join(this.root, `${name}.json`), descriptor)
178
+ return descriptor
179
+ }
180
+
181
+ /**
182
+ * The descriptor of a Windows-engine profile whose user data directory the
183
+ * bridge reported, created when it does not exist yet.
184
+ */
185
+ ensureWindows(
186
+ name: string,
187
+ browser: string,
188
+ userDataDir: string,
189
+ now: Date = new Date(),
190
+ ): BrowserProfileDescriptor {
191
+ const existing = this.get(name)
192
+ if (existing) {
193
+ if (existing.engine !== 'windows-cdp') {
194
+ throw new BrowserProfileError(
195
+ `Browser profile "${name}" belongs to the ${existing.engine} engine, not the Windows browser. Use another profile name.`,
196
+ )
197
+ }
198
+ if (existing.userDataDir === userDataDir) return existing
199
+ const moved = { ...existing, userDataDir }
200
+ writeJsonAtomic(join(this.root, `${name}.json`), moved)
201
+ return moved
202
+ }
203
+ ensurePrivateDir(join(this.home, 'browser'))
204
+ ensurePrivateDir(this.root)
205
+ const descriptor: BrowserProfileDescriptor = {
206
+ v: 1,
207
+ name,
208
+ engine: 'windows-cdp',
209
+ userDataDir,
210
+ browser,
211
+ createdAt: now.toISOString(),
212
+ }
213
+ writeJsonAtomic(join(this.root, `${name}.json`), descriptor)
214
+ return descriptor
215
+ }
216
+
217
+ /** Record a completed sign-in. */
218
+ markLogin(name: string, now: Date = new Date()): BrowserProfileDescriptor {
219
+ const existing = this.get(name)
220
+ if (!existing) throw new BrowserProfileError(`There is no browser profile "${name}".`)
221
+ const next = { ...existing, lastLoginAt: now.toISOString() }
222
+ writeJsonAtomic(join(this.root, `${name}.json`), next)
223
+ return next
224
+ }
225
+
226
+ /**
227
+ * Delete the descriptor and the profile's user data: a local profile's
228
+ * directory, or a Windows-engine profile's through the drive mount
229
+ * (`mountRoot`, `/mnt/` by default), and only when that directory is a
230
+ * namzu profile directory (`…\namzu\browser\profiles\<name>`). Refused
231
+ * while any live process holds a lease on it.
232
+ */
233
+ remove(
234
+ name: string,
235
+ leases: BrowserLeaseStore = new BrowserLeaseStore(this.home),
236
+ options: { mountRoot?: string } = {},
237
+ ): boolean {
238
+ const existing = this.get(name)
239
+ if (!existing) return false
240
+ const holders = leases.holders(name)
241
+ if (holders.length > 0) throw new ProfileBusyError(name, holders)
242
+ if (existing.engine === 'local') {
243
+ rmSync(existing.userDataDir, { recursive: true, force: true })
244
+ } else {
245
+ const suffix = `\\namzu\\browser\\profiles\\${name}`
246
+ const local = existing.userDataDir.toLowerCase().endsWith(suffix)
247
+ ? windowsPathToWsl(existing.userDataDir, options.mountRoot ?? DEFAULT_WSL_MOUNT_ROOT)
248
+ : undefined
249
+ if (local) rmSync(local, { recursive: true, force: true })
250
+ }
251
+ rmSync(join(this.root, `${name}.json`), { force: true })
252
+ return true
253
+ }
254
+ }
255
+
256
+ // ---------------------------------------------------------------------------
257
+ // Leases
258
+ // ---------------------------------------------------------------------------
259
+
260
+ export interface BrowserLeaseRecord {
261
+ readonly v: 1
262
+ readonly profile: string
263
+ readonly pid: number
264
+ readonly session: string
265
+ readonly acquiredAt: string
266
+ }
267
+
268
+ /** A held lease. `release` returns whether it was the last live one on the profile. */
269
+ export interface BrowserLease {
270
+ readonly profile: string
271
+ readonly id: string
272
+ release(): { last: boolean }
273
+ }
274
+
275
+ /** Is `pid` a live process? A process we may not signal is alive. */
276
+ export function processAlive(pid: number): boolean {
277
+ if (!Number.isInteger(pid) || pid <= 0) return false
278
+ try {
279
+ process.kill(pid, 0)
280
+ return true
281
+ } catch (error) {
282
+ return (error as NodeJS.ErrnoException).code === 'EPERM'
283
+ }
284
+ }
285
+
286
+ const SESSION_ID = /^[A-Za-z0-9_-]{1,64}$/
287
+
288
+ export class BrowserLeaseStore {
289
+ readonly root: string
290
+
291
+ constructor(
292
+ readonly home: string,
293
+ private readonly alive: (pid: number) => boolean = processAlive,
294
+ ) {
295
+ this.root = join(home, 'browser', 'leases')
296
+ }
297
+
298
+ private dir(profile: string): string {
299
+ assertName(profile)
300
+ return join(this.root, profile)
301
+ }
302
+
303
+ /** Live leases on `profile`, as `<pid>-<session>`. Stale ones are removed on the way. */
304
+ holders(profile: string): string[] {
305
+ const dir = this.dir(profile)
306
+ let entries: string[]
307
+ try {
308
+ entries = readdirSync(dir)
309
+ } catch {
310
+ return []
311
+ }
312
+ const live: string[] = []
313
+ for (const entry of entries.sort()) {
314
+ const match = /^(\d+)-([A-Za-z0-9_-]+)\.json$/.exec(entry)
315
+ if (!match) continue
316
+ if (this.alive(Number(match[1]))) live.push(`${match[1]}-${match[2]}`)
317
+ else rmSync(join(dir, entry), { force: true })
318
+ }
319
+ return live
320
+ }
321
+
322
+ /**
323
+ * Take a lease for this process and `session`. With `exclusive`, any live
324
+ * lease by another holder — another process, or another session of this
325
+ * one — is a {@link ProfileBusyError}: a local profile directory can be
326
+ * open in one browser at a time.
327
+ */
328
+ acquire(
329
+ profile: string,
330
+ session: string,
331
+ options: { exclusive?: boolean; pid?: number; now?: Date } = {},
332
+ ): BrowserLease {
333
+ if (!SESSION_ID.test(session)) {
334
+ throw new BrowserProfileError(`"${session}" is not a usable session id for a lease.`)
335
+ }
336
+ const pid = options.pid ?? process.pid
337
+ const id = `${pid}-${session}`
338
+ const dir = this.dir(profile)
339
+ ensurePrivateDir(join(this.home, 'browser'))
340
+ ensurePrivateDir(this.root)
341
+ ensurePrivateDir(dir)
342
+ const record: BrowserLeaseRecord = {
343
+ v: 1,
344
+ profile,
345
+ pid,
346
+ session,
347
+ acquiredAt: (options.now ?? new Date()).toISOString(),
348
+ }
349
+ const path = join(dir, `${id}.json`)
350
+ writeJsonAtomic(path, record)
351
+ // Written first, checked second: two processes racing both see each
352
+ // other and both refuse, rather than both seeing nothing.
353
+ if (options.exclusive) {
354
+ const others = this.holders(profile).filter((holder) => holder !== id)
355
+ if (others.length > 0) {
356
+ rmSync(path, { force: true })
357
+ throw new ProfileBusyError(profile, others)
358
+ }
359
+ }
360
+ let released = false
361
+ return {
362
+ profile,
363
+ id,
364
+ release: () => {
365
+ if (!released) {
366
+ released = true
367
+ rmSync(path, { force: true })
368
+ }
369
+ return { last: this.holders(profile).length === 0 }
370
+ },
371
+ }
372
+ }
373
+ }
package/src/relay.ts ADDED
@@ -0,0 +1,101 @@
1
+ import { randomBytes, timingSafeEqual } from 'node:crypto'
2
+ import { type IncomingMessage, type Server, createServer } from 'node:http'
3
+ import type { AddressInfo } from 'node:net'
4
+ import type { Duplex } from 'node:stream'
5
+ import { type WebSocket, WebSocketServer } from 'ws'
6
+
7
+ /**
8
+ * A WebSocket endpoint on WSL's `127.0.0.1` that Playwright's
9
+ * `connectOverCDP` can use, relaying every message to and from the bridge.
10
+ *
11
+ * The listening port is visible to every process in the distro, so the
12
+ * endpoint lives at a path of 32 random bytes (hex), a request anywhere else
13
+ * is answered 404 before any WebSocket is made, a request carrying an
14
+ * `Origin` header (every browser page's WebSocket does) is refused, and only
15
+ * one client is served at a time.
16
+ */
17
+
18
+ /** The bridge side of a relay. */
19
+ export interface CdpRelayPeer {
20
+ /** Send one CDP message to the browser. */
21
+ send(message: Buffer | string): boolean
22
+ /** Called with every CDP message from the browser. Replaces any earlier listener. */
23
+ onMessage(listener: (message: Buffer) => void): void
24
+ }
25
+
26
+ export interface CdpRelay {
27
+ /** `ws://127.0.0.1:<port>/<token>`. */
28
+ readonly url: string
29
+ /** Stop listening and drop the client. */
30
+ close(): Promise<void>
31
+ }
32
+
33
+ /** Largest message relayed: a full-page screenshot of a very long page, base64. */
34
+ const MAX_MESSAGE_BYTES = 512 * 1024 * 1024
35
+
36
+ function reject(socket: Duplex, status: number, text: string): void {
37
+ socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`)
38
+ socket.destroy()
39
+ }
40
+
41
+ function samePath(actual: string, expected: string): boolean {
42
+ const a = Buffer.from(actual)
43
+ const b = Buffer.from(expected)
44
+ return a.length === b.length && timingSafeEqual(a, b)
45
+ }
46
+
47
+ export async function startCdpRelay(
48
+ peer: CdpRelayPeer,
49
+ options: { token?: string } = {},
50
+ ): Promise<CdpRelay> {
51
+ const token = options.token ?? randomBytes(32).toString('hex')
52
+ const path = `/${token}`
53
+ const server: Server = createServer((_request, response) => {
54
+ response.writeHead(404, { Connection: 'close' }).end()
55
+ })
56
+ const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_MESSAGE_BYTES })
57
+ let client: WebSocket | undefined
58
+
59
+ peer.onMessage((message) => {
60
+ if (client && client.readyState === client.OPEN) client.send(message, { binary: false })
61
+ })
62
+
63
+ server.on('upgrade', (request: IncomingMessage, socket: Duplex, head: Buffer) => {
64
+ if (!samePath(request.url ?? '', path)) return reject(socket, 404, 'Not Found')
65
+ if (request.headers.origin !== undefined) return reject(socket, 403, 'Forbidden')
66
+ if (client) return reject(socket, 409, 'Conflict')
67
+ wss.handleUpgrade(request, socket, head, (ws) => {
68
+ client = ws
69
+ ws.on('message', (data: Buffer | ArrayBuffer | Buffer[]) => {
70
+ const buffer = Array.isArray(data)
71
+ ? Buffer.concat(data)
72
+ : Buffer.isBuffer(data)
73
+ ? data
74
+ : Buffer.from(data)
75
+ peer.send(buffer)
76
+ })
77
+ ws.on('close', () => {
78
+ if (client === ws) client = undefined
79
+ })
80
+ ws.on('error', () => ws.terminate())
81
+ })
82
+ })
83
+
84
+ await new Promise<void>((resolve, rejectListen) => {
85
+ server.once('error', rejectListen)
86
+ server.listen(0, '127.0.0.1', () => {
87
+ server.off('error', rejectListen)
88
+ resolve()
89
+ })
90
+ })
91
+ const { port } = server.address() as AddressInfo
92
+ return {
93
+ url: `ws://127.0.0.1:${port}${path}`,
94
+ close: async () => {
95
+ client?.terminate()
96
+ client = undefined
97
+ wss.close()
98
+ await new Promise<void>((resolve) => server.close(() => resolve()))
99
+ },
100
+ }
101
+ }