@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
package/src/index.ts ADDED
@@ -0,0 +1,79 @@
1
+ export { PlaywrightBrowserHost } from './host.js'
2
+ export type { PlaywrightBrowserHostOptions } from './host.js'
3
+ export {
4
+ detectBrowserEnvironment,
5
+ isWsl,
6
+ nodeBrowserProbes,
7
+ runnableBrowserPlan,
8
+ wslInteropAvailable,
9
+ wslInteropSocket,
10
+ wslNetworkingMode,
11
+ } from './detect.js'
12
+ export {
13
+ DEFAULT_WSL_MOUNT_ROOT,
14
+ findWslInteropSocket,
15
+ listWslInteropSockets,
16
+ parseNetworkingModeOutput,
17
+ parseWslConfigNetworkingMode,
18
+ parseWslMountRoot,
19
+ windowsPathToWsl,
20
+ wslPathToWindows,
21
+ } from './wsl.js'
22
+ export type { WslInteropSocket, WslNetworkingMode } from './wsl.js'
23
+ export {
24
+ WindowsBridgeError,
25
+ bridgeArguments,
26
+ encodePowerShellCommand,
27
+ parseDevToolsActivePort,
28
+ } from './windows-bridge.js'
29
+ export type { WindowsBridgeParams, WindowsBridgeReady } from './windows-bridge.js'
30
+ export type {
31
+ BrowserEngineSetting,
32
+ BrowserEnginePlan,
33
+ BrowserEnvironmentProbes,
34
+ BrowserHeadlessSetting,
35
+ BrowserHostPlatform,
36
+ BrowserRunMode,
37
+ DetectBrowserEnvironmentOptions,
38
+ LocalBrowserPlan,
39
+ WindowsCdpBrowserPlan,
40
+ } from './detect.js'
41
+ export {
42
+ BrowserHumanRequiredError,
43
+ BrowserOriginMismatchError,
44
+ BrowserOutcomeUnknownError,
45
+ BrowserSiteDeniedError,
46
+ BrowserStaleRefError,
47
+ BrowserUnavailableError,
48
+ ProfileBusyError,
49
+ } from './errors.js'
50
+ export {
51
+ BrowserSitePolicy,
52
+ BrowserSitePolicyError,
53
+ DEFAULT_BROWSER_SITE_RULES,
54
+ } from './policy.js'
55
+ export type { BrowserLandingVerdict, BrowserSiteLevel, BrowserSiteRules } from './policy.js'
56
+ export {
57
+ CAPTCHA_FRAME_HOSTS,
58
+ SIGN_IN_ADDRESSES,
59
+ classifyHumanRequired,
60
+ isBotBlockTitle,
61
+ isCaptchaFrame,
62
+ isCredentialField,
63
+ isSignInAddress,
64
+ } from './classifier.js'
65
+ export type {
66
+ BrowserFieldFacts,
67
+ BrowserHumanClassifierOptions,
68
+ BrowserPageSignals,
69
+ } from './classifier.js'
70
+ export {
71
+ BROWSER_PROFILE_NAME,
72
+ BrowserLeaseStore,
73
+ BrowserProfileError,
74
+ BrowserProfileStore,
75
+ DEFAULT_BROWSER_PROFILE,
76
+ processAlive,
77
+ } from './profiles.js'
78
+ export type { BrowserLease, BrowserLeaseRecord, BrowserProfileDescriptor } from './profiles.js'
79
+ export { PLAYWRIGHT_CORE_VERSION } from './snapshot.js'
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Functions the host runs inside the page. Each is serialised by Playwright
3
+ * and must not close over anything in this module.
4
+ *
5
+ * They run in the page's main world, so a hostile page can lie to them. They
6
+ * are hygiene — counting password boxes, dropping text nobody can see — not a
7
+ * boundary: the boundary is the gate, the origin check, the refusal to type
8
+ * into a credential field (checked again right before typing), and the
9
+ * untrusted envelope around everything the page says.
10
+ */
11
+
12
+ /** Visible password and one-time-code fields on the page. */
13
+ export interface FieldCounts {
14
+ readonly passwordFields: number
15
+ readonly oneTimeCodeFields: number
16
+ }
17
+
18
+ // The body of this function is serialised; keep it self-contained.
19
+ export function countCredentialFields(): FieldCounts {
20
+ const oneTime =
21
+ /(?:^|[^a-z])(?:otp|totp|2fa|mfa|one[-_ ]?time[-_ ]?(?:code|password)|verification[-_ ]?code|passcode|security[-_ ]?code|auth(?:entication)?[-_ ]?code)(?:[^a-z]|$)/i
22
+ const visible = (el: Element): boolean => {
23
+ const rect = el.getBoundingClientRect()
24
+ if (rect.width < 2 || rect.height < 2) return false
25
+ const style = getComputedStyle(el)
26
+ return style.visibility !== 'hidden' && style.display !== 'none' && Number(style.opacity) > 0
27
+ }
28
+ let passwordFields = 0
29
+ let oneTimeCodeFields = 0
30
+ for (const input of Array.from(document.querySelectorAll('input'))) {
31
+ if (!visible(input)) continue
32
+ const autocomplete = (input.getAttribute('autocomplete') ?? '').toLowerCase()
33
+ if (input.type === 'password' || /\bcurrent-password\b/.test(autocomplete)) {
34
+ passwordFields += 1
35
+ continue
36
+ }
37
+ const label = [input.name, input.id, input.getAttribute('aria-label') ?? ''].join(' ')
38
+ if (/\bone-time-code\b/.test(autocomplete) || oneTime.test(label)) oneTimeCodeFields += 1
39
+ }
40
+ return { passwordFields, oneTimeCodeFields }
41
+ }
42
+
43
+ /** What {@link fieldFacts} returns: the facts `isCredentialField` reads. */
44
+ export interface ElementFieldFacts {
45
+ readonly tag: string
46
+ readonly type: string
47
+ readonly autocomplete: string
48
+ readonly name: string
49
+ readonly id: string
50
+ readonly label: string
51
+ /** `checkbox`, `radio`, `select`, `file`, or `text`. */
52
+ readonly kind: 'checkbox' | 'radio' | 'select' | 'file' | 'text'
53
+ }
54
+
55
+ // Serialised; keep it self-contained.
56
+ export function fieldFacts(el: Element): ElementFieldFacts {
57
+ const tag = el.tagName.toLowerCase()
58
+ const input = el as HTMLInputElement
59
+ const type = tag === 'input' ? (input.type || 'text').toLowerCase() : ''
60
+ const labels =
61
+ 'labels' in input && input.labels
62
+ ? Array.from(input.labels)
63
+ .map((l) => l.textContent ?? '')
64
+ .join(' ')
65
+ : ''
66
+ const label = [el.getAttribute('aria-label') ?? '', el.getAttribute('placeholder') ?? '', labels]
67
+ .join(' ')
68
+ .trim()
69
+ const role = el.getAttribute('role') ?? ''
70
+ const kind: ElementFieldFacts['kind'] =
71
+ type === 'checkbox' || role === 'checkbox' || role === 'switch'
72
+ ? 'checkbox'
73
+ : type === 'radio' || role === 'radio'
74
+ ? 'radio'
75
+ : tag === 'select'
76
+ ? 'select'
77
+ : type === 'file'
78
+ ? 'file'
79
+ : 'text'
80
+ return {
81
+ tag,
82
+ type,
83
+ autocomplete: el.getAttribute('autocomplete') ?? '',
84
+ name: el.getAttribute('name') ?? '',
85
+ id: el.id ?? '',
86
+ label,
87
+ kind,
88
+ }
89
+ }
90
+
91
+ // Serialised; keep it self-contained.
92
+ export function focusedFieldFacts(): ElementFieldFacts | null {
93
+ let el: Element | null = document.activeElement
94
+ while (el?.shadowRoot?.activeElement) el = el.shadowRoot.activeElement
95
+ if (!el || el === document.body) return null
96
+ const tag = el.tagName.toLowerCase()
97
+ const input = el as HTMLInputElement
98
+ const type = tag === 'input' ? (input.type || 'text').toLowerCase() : ''
99
+ return {
100
+ tag,
101
+ type,
102
+ autocomplete: el.getAttribute('autocomplete') ?? '',
103
+ name: el.getAttribute('name') ?? '',
104
+ id: el.id ?? '',
105
+ label: [el.getAttribute('aria-label') ?? '', el.getAttribute('placeholder') ?? ''].join(' '),
106
+ kind: 'text',
107
+ }
108
+ }
109
+
110
+ /** A rectangle in viewport CSS pixels, as `getBoundingClientRect` reports it. */
111
+ export interface Rect {
112
+ readonly x: number
113
+ readonly y: number
114
+ readonly width: number
115
+ readonly height: number
116
+ }
117
+
118
+ /** {@link invisibleBoxes}' answer: the boxes and the page's scroll offset. */
119
+ export interface InvisibleBoxes {
120
+ readonly scrollX: number
121
+ readonly scrollY: number
122
+ readonly boxes: readonly Rect[]
123
+ }
124
+
125
+ /**
126
+ * Boxes of elements that are in the accessibility tree but that no one can
127
+ * see: fully transparent (themselves or through an ancestor), text too small
128
+ * to read, or text drawn in a transparent colour. Hidden-text prompt
129
+ * injection lives here; `aria-hidden`, `display: none` and `visibility:
130
+ * hidden` are already out of the tree.
131
+ */
132
+ // Serialised; keep it self-contained.
133
+ export function invisibleBoxes(limit: number): InvisibleBoxes {
134
+ const out: Rect[] = []
135
+ const push = (el: Element): void => {
136
+ const r = el.getBoundingClientRect()
137
+ out.push({ x: r.x, y: r.y, width: r.width, height: r.height })
138
+ }
139
+ const walk = (el: Element, hiddenAbove: boolean): void => {
140
+ if (out.length >= limit) return
141
+ const style = getComputedStyle(el)
142
+ const fontSize = Number.parseFloat(style.fontSize)
143
+ const transparentText = /rgba\([^)]*,\s*0\)$/.test(style.color) || style.color === 'transparent'
144
+ const hidden =
145
+ hiddenAbove ||
146
+ Number(style.opacity) === 0 ||
147
+ (Number.isFinite(fontSize) && fontSize < 2) ||
148
+ transparentText
149
+ if (hidden) push(el)
150
+ for (const child of Array.from(el.children)) walk(child, hidden && !transparentText)
151
+ }
152
+ if (document.body) walk(document.body, false)
153
+ return { scrollX: window.scrollX, scrollY: window.scrollY, boxes: out }
154
+ }
package/src/policy.ts ADDED
@@ -0,0 +1,190 @@
1
+ import { canonicalizeBrowserSitePattern, canonicalizeBrowserUrl } from '@namzu/sdk'
2
+
3
+ /**
4
+ * What a site may be used for.
5
+ *
6
+ * - `deny`: not opened, not acted on; a page that lands there is cleared.
7
+ * - `read`: opened and read without asking; never acted on.
8
+ * - `ask`: opening and acting are for the gate to review; the host lets a
9
+ * call through (it was approved to reach the host) but a redirect or popup
10
+ * that lands there unasked is cleared.
11
+ * - `act`: opened, read and acted on without asking.
12
+ */
13
+ export type BrowserSiteLevel = 'deny' | 'read' | 'ask' | 'act'
14
+
15
+ /** Site key (`https://github.com`, `https://*.example.com`, `http://localhost:*`, `*`) to level. */
16
+ export type BrowserSiteRules = Readonly<Record<string, BrowserSiteLevel>>
17
+
18
+ /** The rules a host applies when its caller gives none. */
19
+ export const DEFAULT_BROWSER_SITE_RULES: BrowserSiteRules = { '*': 'ask' }
20
+
21
+ const LEVELS: readonly BrowserSiteLevel[] = ['deny', 'read', 'ask', 'act']
22
+
23
+ interface CompiledRule {
24
+ readonly key: string
25
+ readonly level: BrowserSiteLevel
26
+ readonly scheme: string
27
+ /** Exact host, or the suffix after `*.`. */
28
+ readonly host: string
29
+ readonly wildcardHost: boolean
30
+ /** `*`, an explicit port, or '' for the scheme's default port. */
31
+ readonly port: string
32
+ }
33
+
34
+ export class BrowserSitePolicyError extends Error {
35
+ override readonly name = 'BrowserSitePolicyError'
36
+ }
37
+
38
+ /** A landing the policy refused, and why, in the host's words. */
39
+ export interface BrowserLandingVerdict {
40
+ readonly allowed: boolean
41
+ /** Canonical origin, `about:blank`, or the scheme for a non-web address. */
42
+ readonly origin: string
43
+ readonly reason?: string
44
+ }
45
+
46
+ function compile(key: string, level: BrowserSiteLevel): CompiledRule {
47
+ if (!LEVELS.includes(level)) {
48
+ throw new BrowserSitePolicyError(
49
+ `site rule "${key}" has level "${String(level)}"; use deny, read, ask or act`,
50
+ )
51
+ }
52
+ const verdict = canonicalizeBrowserSitePattern(key)
53
+ if (!verdict.ok) throw new BrowserSitePolicyError(`site rule "${key}": ${verdict.reason}`)
54
+ const match = /^(https?):\/\/(\*\.)?([^:]+)(?::(\*|\d+))?$/.exec(verdict.pattern)
55
+ if (!match) throw new BrowserSitePolicyError(`site rule "${key}" could not be read`)
56
+ return {
57
+ key: verdict.pattern,
58
+ level,
59
+ scheme: match[1] ?? '',
60
+ host: match[3] ?? '',
61
+ wildcardHost: match[2] !== undefined,
62
+ port: match[4] ?? '',
63
+ }
64
+ }
65
+
66
+ function matches(rule: CompiledRule, url: URL): boolean {
67
+ if (url.protocol !== `${rule.scheme}:`) return false
68
+ if (rule.port !== '*' && url.port !== rule.port) return false
69
+ const host = url.hostname
70
+ if (rule.wildcardHost) return host.endsWith(`.${rule.host}`)
71
+ return host === rule.host
72
+ }
73
+
74
+ /** Higher is more specific: exact host over wildcard, longer suffix first, exact port over `*`. */
75
+ function specificity(rule: CompiledRule): number {
76
+ return (rule.wildcardHost ? 0 : 1_000_000) + rule.host.length * 10 + (rule.port === '*' ? 0 : 1)
77
+ }
78
+
79
+ /**
80
+ * The host-side site policy: the check after the fact.
81
+ *
82
+ * The gate decides whether a call may run; this decides whether the page the
83
+ * browser actually ended up on may stay loaded, and whether the live page may
84
+ * be acted on. A navigation the gate approved can redirect, a click can open
85
+ * a popup, and a script can move the tab — none of which the gate saw.
86
+ *
87
+ * Matching: every `deny` that matches wins; otherwise the most specific
88
+ * matching key; otherwise `*`; otherwise `ask`.
89
+ */
90
+ export class BrowserSitePolicy {
91
+ private readonly rules: readonly CompiledRule[]
92
+ private readonly fallback: BrowserSiteLevel
93
+ private readonly approved = new Set<string>()
94
+
95
+ constructor(sites: BrowserSiteRules = DEFAULT_BROWSER_SITE_RULES) {
96
+ const rules: CompiledRule[] = []
97
+ let fallback: BrowserSiteLevel = 'ask'
98
+ for (const [key, level] of Object.entries(sites)) {
99
+ if (key.trim() === '*') {
100
+ if (!LEVELS.includes(level)) {
101
+ throw new BrowserSitePolicyError(
102
+ `site rule "*" has level "${String(level)}"; use deny, read, ask or act`,
103
+ )
104
+ }
105
+ fallback = level
106
+ continue
107
+ }
108
+ rules.push(compile(key, level))
109
+ }
110
+ this.rules = rules.sort((a, b) => specificity(b) - specificity(a))
111
+ this.fallback = fallback
112
+ }
113
+
114
+ /** The level of a canonical origin (`https://github.com`). */
115
+ levelOf(origin: string): BrowserSiteLevel {
116
+ let url: URL
117
+ try {
118
+ url = new URL(origin)
119
+ } catch {
120
+ return 'deny'
121
+ }
122
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return 'deny'
123
+ const hits = this.rules.filter((rule) => matches(rule, url))
124
+ if (hits.some((rule) => rule.level === 'deny')) return 'deny'
125
+ return hits[0]?.level ?? this.fallback
126
+ }
127
+
128
+ /**
129
+ * Record that the caller asked to open `origin`. A call that reached the
130
+ * host passed the gate, so the page it names may stay loaded even when
131
+ * its level alone would need a review.
132
+ */
133
+ approve(origin: string): void {
134
+ this.approved.add(origin)
135
+ }
136
+
137
+ isApproved(origin: string): boolean {
138
+ return this.approved.has(origin)
139
+ }
140
+
141
+ /** May the host act on a page at `origin`? `ask` and `act`: the gate has had its say. */
142
+ canAct(origin: string): boolean {
143
+ const level = this.levelOf(origin)
144
+ return level === 'ask' || level === 'act'
145
+ }
146
+
147
+ /**
148
+ * May a page that a navigation, redirect or popup landed on stay loaded?
149
+ * `about:blank`, an origin at `read` or `act`, or one the caller asked to
150
+ * open this session; never a `deny`, never a non-web scheme, never a cloud
151
+ * metadata address.
152
+ */
153
+ landing(rawUrl: string): BrowserLandingVerdict {
154
+ if (rawUrl === 'about:blank' || rawUrl === '') return { allowed: true, origin: 'about:blank' }
155
+ let parsed: URL
156
+ try {
157
+ parsed = new URL(rawUrl)
158
+ } catch {
159
+ return { allowed: false, origin: 'unknown', reason: 'the address could not be read' }
160
+ }
161
+ if (parsed.protocol === 'about:') {
162
+ return parsed.href === 'about:blank' || parsed.href === 'about:srcdoc'
163
+ ? { allowed: true, origin: 'about:blank' }
164
+ : { allowed: false, origin: 'about', reason: `${parsed.href} is not a web page` }
165
+ }
166
+ // A blob: document belongs to the page that made it; the origin inside decides.
167
+ const inner = parsed.protocol === 'blob:' ? parsed.pathname : rawUrl
168
+ const verdict = canonicalizeBrowserUrl(inner)
169
+ if (!verdict.ok) {
170
+ return {
171
+ allowed: false,
172
+ origin: parsed.protocol.replace(/:$/, ''),
173
+ reason: verdict.reason,
174
+ }
175
+ }
176
+ const origin = verdict.origin
177
+ const level = this.levelOf(origin)
178
+ if (level === 'deny') {
179
+ return { allowed: false, origin, reason: `${origin} is denied by the site rules` }
180
+ }
181
+ if (level === 'read' || level === 'act' || this.approved.has(origin)) {
182
+ return { allowed: true, origin }
183
+ }
184
+ return {
185
+ allowed: false,
186
+ origin,
187
+ reason: `${origin} was not asked for and the site rules need approval to open it`,
188
+ }
189
+ }
190
+ }