@seekskyworld/open-browser 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.
Files changed (109) hide show
  1. package/CONTRIBUTING.md +15 -0
  2. package/Docs/Agent/346/265/217/350/247/210/345/231/250/346/200/273/344/275/223/346/236/266/346/236/204.md +58 -0
  3. package/Docs/THIRD-PARTY-NOTICES.md +12 -0
  4. package/Docs/open-browser-api.d.ts +273 -0
  5. package/Docs/open-browser/344/273/273/345/212/241/350/257/204/346/265/213/346/214/207/345/215/227.md +59 -0
  6. package/Docs/open-browser/351/232/220/347/247/201/344/270/216/345/274/200/346/272/220/345/256/241/350/256/241.md +37 -0
  7. package/Docs//346/216/247/345/210/266/345/217/260/345/210/206/347/273/204/344/270/216/346/216/245/347/256/241/346/226/271/346/241/210.md +31 -0
  8. package/Docs//350/267/250/345/271/263/345/217/260/350/257/225/347/224/250/344/270/216/345/217/221/350/241/214.md +36 -0
  9. package/LICENSE +200 -0
  10. package/README.md +150 -2
  11. package/README.zh-CN.md +155 -0
  12. package/SECURITY.md +9 -0
  13. package/access-registry.mjs +151 -0
  14. package/action-execution.mjs +374 -0
  15. package/activity-notifier.mjs +34 -0
  16. package/api-contract.mjs +122 -0
  17. package/browser-extension/icons/open-browser-128.png +0 -0
  18. package/browser-extension/icons/open-browser-16.png +0 -0
  19. package/browser-extension/icons/open-browser-32.png +0 -0
  20. package/browser-extension/icons/open-browser-48.png +0 -0
  21. package/browser-extension/icons/open-browser-wordmark.png +0 -0
  22. package/browser-extension/manifest.json +38 -0
  23. package/browser-extension/newtab.css +20 -0
  24. package/browser-extension/newtab.html +19 -0
  25. package/browser-extension/newtab.js +123 -0
  26. package/browser-extension/phase-labels.js +9 -0
  27. package/browser-extension/popup.css +19 -0
  28. package/browser-extension/popup.html +46 -0
  29. package/browser-extension/popup.js +324 -0
  30. package/browser-extension/tab-action.js +137 -0
  31. package/browser-extension/worker.js +188 -0
  32. package/browser-extension/workspace-title.js +15 -0
  33. package/capability-matrix.mjs +21 -0
  34. package/chromium-host.mjs +149 -0
  35. package/chromium-shell.mjs +150 -0
  36. package/cli.mjs +83 -0
  37. package/contract-validation.mjs +27 -0
  38. package/control.mjs +107 -0
  39. package/desktop/Info.plist +13 -0
  40. package/desktop/Launcher.m +117 -0
  41. package/desktop/OBControlBar.h +7 -0
  42. package/desktop/OBControlBar.m +213 -0
  43. package/desktop/OBPageView.h +6 -0
  44. package/desktop/OBPageView.m +348 -0
  45. package/desktop/WorkspacePanel.h +16 -0
  46. package/desktop/WorkspacePanel.m +915 -0
  47. package/desktop/archive-release.py +129 -0
  48. package/desktop/brand-keychain.py +95 -0
  49. package/desktop/brand-locales.py +93 -0
  50. package/desktop/brand-macos-icons.py +24 -0
  51. package/desktop/brand-windows-icons.mjs +48 -0
  52. package/desktop/build-macos.mjs +96 -0
  53. package/desktop/build-portable.mjs +95 -0
  54. package/desktop/build.mjs +5 -0
  55. package/desktop/create-shortcut.ps1 +9 -0
  56. package/desktop/generate-icons.py +39 -0
  57. package/desktop/icons/open-browser.icns +0 -0
  58. package/desktop/icons/open-browser.ico +0 -0
  59. package/desktop/install-menu-entry.mjs +24 -0
  60. package/desktop/package-assets.mjs +34 -0
  61. package/desktop/patches/chromium-macos-keychain-service.patch +18 -0
  62. package/desktop/portable-archive.py +22 -0
  63. package/desktop/sign.mjs +33 -0
  64. package/desktop/smoke-portable.mjs +65 -0
  65. package/desktop/start.mjs +12 -0
  66. package/desktop/verify-upgrade.mjs +74 -0
  67. package/desktop/verify-version.mjs +12 -0
  68. package/desktop-page.mjs +211 -0
  69. package/diagnostics.mjs +28 -0
  70. package/downloads.mjs +110 -0
  71. package/engine-service.mjs +1002 -0
  72. package/hosted/README.md +74 -0
  73. package/hosted/cli.mjs +17 -0
  74. package/hosted/directory.mjs +261 -0
  75. package/hosted/init.mjs +37 -0
  76. package/hosted/server.mjs +129 -0
  77. package/managed-popup.mjs +54 -0
  78. package/mcp.mjs +43 -0
  79. package/network-policy.mjs +107 -0
  80. package/output-store.mjs +96 -0
  81. package/package.json +57 -4
  82. package/page-activity.mjs +121 -0
  83. package/page-dialogs.mjs +53 -0
  84. package/page-observation.mjs +280 -0
  85. package/paths.mjs +20 -0
  86. package/privacy-config.mjs +95 -0
  87. package/receipt-store.mjs +191 -0
  88. package/runtime.mjs +44 -0
  89. package/scheduler.mjs +70 -0
  90. package/sdk.mjs +176 -0
  91. package/service.mjs +271 -0
  92. package/site-workflow.mjs +115 -0
  93. package/skills/open-browser/SKILL.md +86 -0
  94. package/skills/open-browser/scripts/bootstrap.mjs +134 -0
  95. package/skills/open-browser/scripts/open-browser +21 -0
  96. package/skills/open-browser/scripts/open-browser.cmd +9 -0
  97. package/skills/open-browser/workflows/login-export.json +10 -0
  98. package/skills/open-browser/workflows/upload-verify.json +8 -0
  99. package/studio/demo-site.mjs +111 -0
  100. package/studio/demo.css +1 -0
  101. package/studio/index.html +66 -0
  102. package/studio/index.mjs +57 -0
  103. package/studio/native-demo.mjs +124 -0
  104. package/studio/studio.css +119 -0
  105. package/studio/studio.js +438 -0
  106. package/uploads.mjs +63 -0
  107. package/visual-page.mjs +306 -0
  108. package/workspace-lifecycle.mjs +170 -0
  109. package/workspace-state.mjs +95 -0
@@ -0,0 +1,280 @@
1
+ export function inspectDocument(options = {}) {
2
+ const textOnly = options === true || options.textOnly;
3
+ if (options.origins && (!options.origins.includes(self.origin) || !options.origins.includes(location.origin))) return null;
4
+ const excluded = '[aria-hidden="true" i],[inert],[data-open-browser-private]';
5
+ // closest() stops at a shadow boundary. Walk the composed ancestry so a
6
+ // private or inert host also protects its projected and shadow children.
7
+ function composedMatch(el, selector) {
8
+ for(let node=el;node;node=node.assignedSlot || node.parentElement || node.getRootNode().host)
9
+ if(node.matches(selector)) return true;
10
+ return false;
11
+ }
12
+ const visible = node => node.checkVisibility({visibilityProperty:true,opacityProperty:true}) &&
13
+ node.getClientRects().length>0 && !composedMatch(node,excluded);
14
+ const disabled = node => node.matches(':disabled') || composedMatch(node,'[aria-disabled="true" i]');
15
+ const region = options.region;
16
+ function intersects(el) {
17
+ if(!region) return true;
18
+ const r=el.getBoundingClientRect();
19
+ return r.right>region.x && r.left<region.x+region.width && r.bottom>region.y && r.top<region.y+region.height;
20
+ }
21
+ function* walk(root,mask) {
22
+ const stack=[document.createTreeWalker(root,mask | NodeFilter.SHOW_ELEMENT)];
23
+ while(stack.length) {
24
+ const node=stack.at(-1).nextNode();
25
+ if(!node) {stack.pop();continue;}
26
+ if(node.shadowRoot) stack.push(document.createTreeWalker(node.shadowRoot,mask | NodeFilter.SHOW_ELEMENT));
27
+ yield node;
28
+ }
29
+ }
30
+ function textWindow(root,limit,offset=0,scoped=false) {
31
+ let content='',position=0;
32
+ const protectedText='script,style,noscript,input,textarea,select,[contenteditable]';
33
+ for(const node of walk(root,NodeFilter.SHOW_TEXT)) {
34
+ if(node.nodeType!==Node.TEXT_NODE) continue;
35
+ const el=node.parentElement || node.getRootNode().host;
36
+ if(!el || !visible(el) || composedMatch(el,protectedText) || (scoped && !intersects(el))) continue;
37
+ const value=node.textContent.trim();
38
+ if(!value) continue;
39
+ const piece=(position?' ':'')+value;
40
+ const start=Math.max(0,offset-position);
41
+ position+=piece.length;
42
+ if(start<piece.length) content+=piece.slice(start,start+limit+1-content.length);
43
+ if(content.length>limit) break;
44
+ }
45
+ return {text:content.slice(0,limit),more:content.length>limit};
46
+ }
47
+ const visibleText=(root,limit)=>textWindow(root,limit).text;
48
+ // Native top-layer dialogs follow paint order, which can differ from DOM order.
49
+ const modalSelector='dialog:modal,[role="dialog"][aria-modal="true"],[role="alertdialog"][aria-modal="true"]';
50
+ const dialogs=[...document.querySelectorAll(modalSelector)];
51
+ for(let focused=document.activeElement;focused?.shadowRoot?.activeElement;) {
52
+ const root=focused.shadowRoot;
53
+ dialogs.push(...root.querySelectorAll(modalSelector));
54
+ focused=root.activeElement;
55
+ }
56
+ const painted=dialogs.filter(el=>el.checkVisibility({visibilityProperty:true,opacityProperty:true}) && el.getClientRects().length);
57
+ const front=painted.findLast(el=>{
58
+ const r=el.getBoundingClientRect();
59
+ const hit=el.getRootNode().elementFromPoint(r.x+r.width/2,r.y+r.height/2);
60
+ return hit && (el===hit || el.contains(hit));
61
+ }) ?? painted.at(-1);
62
+ if(options.foregroundTarget) {
63
+ if(!front) return true;
64
+ for(let node=options.foregroundTarget;node;node=node.assignedSlot || node.parentElement || node.getRootNode().host)
65
+ if(node===front) return true;
66
+ return false;
67
+ }
68
+ let foreground;
69
+ if(front && visible(front)) {
70
+ const label=(front.getAttribute('aria-labelledby') || '').split(/\s+/)
71
+ .map(id=>front.getRootNode().getElementById(id)).filter(el=>el && visible(el))
72
+ .map(el=>visibleText(el,160)).join(' ');
73
+ const {x,y,width,height}=front.getBoundingClientRect();
74
+ foreground={role:front.getAttribute('role') || 'dialog',name:(label || front.getAttribute('aria-label') || '').slice(0,160),
75
+ bounds:{x,y,width,height}};
76
+ }
77
+ const nodes=[],details=[];
78
+ function stateOf(el) {
79
+ const state = {};
80
+ for (const key of ['checked', 'pressed', 'expanded', 'selected']) {
81
+ const raw = el.getAttribute('aria-' + key);
82
+ if (raw === 'true' || raw === 'false') state[key] = raw === 'true';
83
+ else if (raw === 'mixed' && (key === 'checked' || key === 'pressed')) state[key] = raw;
84
+ }
85
+ if (el.matches('input[type="checkbox"],input[type="radio"]'))
86
+ state.checked = el.indeterminate && el.type === 'checkbox' ? 'mixed' : el.checked;
87
+ return state;
88
+ }
89
+ const selector='[role="checkbox"],[role="radio"],[role="switch"],[role="tab"],[role="option"],a[href],button,input,textarea,select,label,[role="button"],[role="link"],[contenteditable="true"]';
90
+ const offset=options.elementOffset===undefined?0:options.elementOffset;
91
+ const limit=options.limit??180;
92
+ let seen=0,moreControls=false;
93
+ const locator=options.locator;
94
+ const candidates=[];
95
+ let matchCount=0;
96
+ function semanticScope(el, wanted) {
97
+ for(let parent=el.parentElement || el.getRootNode().host; parent;
98
+ parent=parent.assignedSlot || parent.parentElement || parent.getRootNode().host) {
99
+ const role=parent.getAttribute('role') || {section:'region',tr:'row',fieldset:'group',form:'form',dialog:'dialog'}[parent.localName];
100
+ if(!['region','row','group','form','dialog','listitem','article'].includes(role)) continue;
101
+ const labelled=(parent.getAttribute('aria-labelledby') || '').split(/\s+/).filter(Boolean)
102
+ .map(id=>parent.getRootNode().getElementById(id)).filter(node=>node && visible(node))
103
+ .map(node=>visibleText(node,160)).join(' ');
104
+ const name=(labelled || parent.getAttribute('aria-label') || visibleText(parent,160)).slice(0,160);
105
+ if(!wanted || (role===wanted.role && name===wanted.name)) return {role,name};
106
+ }
107
+ }
108
+ function add(el,detail) {
109
+ if(locator) {
110
+ if(detail.role!==locator.role || detail.name!==locator.name) return;
111
+ const within=semanticScope(el,locator.within);
112
+ if(locator.within && !within) return;
113
+ matchCount++;
114
+ if(candidates.length<8) candidates.push({role:detail.role,name:detail.name,...(within && {within})});
115
+ if(matchCount===1) {nodes.push(el);details.push(detail);}
116
+ if(matchCount===2) {nodes.length=0;details.length=0;}
117
+ return;
118
+ }
119
+ if(options.name && !detail.name.toLowerCase().includes(options.name.toLowerCase())) return;
120
+ if(seen++<offset) return;
121
+ if(nodes.length===limit) {moreControls=true;return;}
122
+ nodes.push(el);details.push(detail);
123
+ }
124
+ for(const el of textOnly || offset===null ? [] : walk(front || document,NodeFilter.SHOW_ELEMENT)) {
125
+ if(moreControls) break;
126
+ if(!el.matches(selector) || !intersects(el)) continue;
127
+ if (!visible(el) || disabled(el) || el.matches('input[type="hidden"]')) continue;
128
+ if (el instanceof HTMLLabelElement && !el.matches('[role="button"],[role="link"],[contenteditable="true"]')) {
129
+ // Chromium dispatches the native activation through the visible label.
130
+ // Keep the ref on the control when the control already has a target.
131
+ const control = el.control;
132
+ if (!control || composedMatch(control,excluded) || disabled(control) || visible(control) ||
133
+ !control.matches('input[type="checkbox"],input[type="radio"]')) continue;
134
+ const name = visibleText(el, 160);
135
+ if (name) add(el,{role:'label',name,...stateOf(control)});
136
+ continue;
137
+ }
138
+ const type = el.type || '';
139
+ let role = el.getAttribute('role') || 'textbox';
140
+ if (el.matches('a,[role="link"]')) role = 'link';
141
+ else if (el.matches('button,[role="button"],input[type="submit"],input[type="button"]')) role = 'button';
142
+ else if (el.matches('select')) role = 'combobox';
143
+ else if (['checkbox', 'radio'].includes(type)) role = type;
144
+ const labels = Array.from(el.labels || []).filter(visible).map(label => visibleText(label, 160)).join(' ');
145
+ const caption = ['button', 'link'].includes(role) ? visibleText(el, 160) : '';
146
+ const submitText = el.matches('input[type="submit"],input[type="button"]') ? el.value : '';
147
+ let referenced = '';
148
+ for (const id of (el.getAttribute('aria-labelledby') || '').match(/\S+/g) || []) {
149
+ const label = el.getRootNode().getElementById(id);
150
+ if (!label || !visible(label)) continue;
151
+ const part = visibleText(label, 160 - referenced.length);
152
+ if (part) referenced += (referenced ? ' ' : '') + part;
153
+ if (referenced.length >= 160) break;
154
+ }
155
+ const name = referenced || el.getAttribute('aria-label') || labels || caption || submitText
156
+ || el.getAttribute('placeholder') || el.getAttribute('name') || role;
157
+ const choices = role === 'combobox' ? Array.from(el.options).slice(0, 64)
158
+ .map(option => ({ label: option.label.slice(0, 160), value: option.value.slice(0, 256) })) : undefined;
159
+ add(el,{ role, name: name.trim().slice(0,160), ...stateOf(el), ...(choices && {options:choices}) });
160
+ }
161
+ const textOffset=options.textOffset===undefined?0:options.textOffset;
162
+ const textLimit=options.textLimit??8000,padding=options.padding??0;
163
+ const start=Math.max(0,(textOffset??0)-padding);
164
+ const skip=(textOffset??0)-start;
165
+ const window=locator || options.name || textOffset===null ? {text:'',more:false} :
166
+ textWindow(front || document.body || document.documentElement,textLimit+skip+padding,start,true);
167
+ const text=window.text.slice(skip,skip+textLimit);
168
+ const more=window.more || window.text.length>skip+textLimit;
169
+ const textWindowInfo=padding ? {padded:window.text,skip,length:text.length} : undefined;
170
+ if (options.origins && textOnly) return {origin:self.origin,text,textWindowInfo};
171
+ if (textOnly) return text;
172
+ const next=moreControls || more ? {elementOffset:moreControls?offset+nodes.length:null,textOffset:more?textOffset+text.length:null} : null;
173
+ if (options.expectedNode) return nodes.length===1 && nodes[0]===options.expectedNode;
174
+ const match=locator ? {status:matchCount===1?'unique':matchCount?'ambiguous':'missing',count:matchCount,candidates} : undefined;
175
+ const summary={text,details,next,origin:self.origin,textWindowInfo,foreground,...(match && {match})};
176
+ if (options.summaryOnly) return summary;
177
+ if (!options.previousNodes) return {nodes,summary};
178
+ // Match the DOM objects themselves. Reordering or duplicate labels cannot
179
+ // redirect an old ref to a replacement element.
180
+ const previous = new Map(options.previousNodes.map((node, index) => [node, index]));
181
+ const freshNodes = {};
182
+ const previousIndices = nodes.map((node, index) => {
183
+ if (previous.has(node)) return previous.get(node);
184
+ freshNodes[index] = node;
185
+ return -1;
186
+ });
187
+ return { nodes, freshNodes, summary:{...summary,previousIndices} };
188
+ }
189
+
190
+ // Only delegated readers use this path. Owners retain Playwright element handles for actions.
191
+ export async function readDocumentSummary(tab, origins, options = {}) {
192
+ if (!tab.summarySession) tab.summarySession = await tab.page.context().newCDPSession(tab.page);
193
+ const session = tab.summarySession;
194
+ const allowed = JSON.stringify(origins);
195
+ const expression = `(${allowed}.includes(self.origin) && ${allowed}.includes(location.origin)) ? (${inspectDocument})(${JSON.stringify(options)}).summary : null`;
196
+ for (let attempt = 0; attempt < 2; attempt++) {
197
+ if (!tab.summaryContext || tab.summaryContext.documentId !== tab.documentId) {
198
+ const documentId = tab.documentId;
199
+ const {frameTree} = await session.send('Page.getFrameTree');
200
+ const {executionContextId} = await session.send('Page.createIsolatedWorld', {
201
+ frameId: frameTree.frame.id, worldName: 'open-browser-observer',
202
+ });
203
+ tab.summaryContext = { documentId, executionContextId };
204
+ }
205
+ let response;
206
+ try {
207
+ response = await session.send('Runtime.evaluate', {
208
+ contextId: tab.summaryContext.executionContextId, expression, returnByValue: true,
209
+ });
210
+ } catch (error) {
211
+ // A renderer may invalidate the world before its navigation event reaches the service.
212
+ if (attempt || !/context/i.test(error.message)) throw error;
213
+ tab.summaryContext = undefined;
214
+ continue;
215
+ }
216
+ if (response.exceptionDetails) throw new Error('observation_failed');
217
+ if (!response.result.value) throw Object.assign(new Error('origin_denied'), {code:'origin_denied'});
218
+ return response.result.value;
219
+ }
220
+ }
221
+
222
+ export async function frameAllowed(frame,origins) {
223
+ for(let child=frame; child.parentFrame(); child=child.parentFrame()) {
224
+ const url=URL.parse(child.url());
225
+ if(child.isDetached() || !url || !['http:','https:'].includes(url.protocol) ||
226
+ url.username || url.password || !origins.has(url.origin)) return false;
227
+ const owner=await child.frameElement();
228
+ try {
229
+ if(!await child.parentFrame().evaluate(inspectDocument,{foregroundTarget:owner})) return false;
230
+ const sandbox=await owner.getAttribute('sandbox');
231
+ if(sandbox!==null && !sandbox.split(/\s+/).includes('allow-same-origin')) return false;
232
+ if(!await owner.evaluate(node=>{
233
+ if(!node.checkVisibility({visibilityProperty:true,opacityProperty:true}) || !node.getClientRects().length) return false;
234
+ for(let el=node;el;el=el.assignedSlot || el.parentElement || el.getRootNode().host)
235
+ if(el.matches('[inert],[aria-hidden="true" i],[data-open-browser-private]')) return false;
236
+ return true;
237
+ })) return false;
238
+ } finally { await owner.dispose().catch(()=>{}); }
239
+ }
240
+ return true;
241
+ }
242
+
243
+ export async function observeFrames(page, origins, redact, padding=0) {
244
+ const frames = [];
245
+ let remaining = 8000;
246
+ // Direct visible child frames only. A blank or opaque sandbox has no
247
+ // explicit HTTP(S) origin. No cross-frame action handles leave this helper.
248
+ for (const frame of page.mainFrame().childFrames().slice(0, 16)) {
249
+ if (!remaining || !origins.has(URL.parse(frame.url())?.origin)) continue;
250
+ try {
251
+ if (!(await frameAllowed(frame,origins))) continue;
252
+ const data=await frame.evaluate(inspectDocument,{textOnly:true,origins:[...origins],textLimit:remaining,padding});
253
+ if (data && origins.has(data.origin) && URL.parse(frame.url())?.origin === data.origin) {
254
+ const text = redact(data.text,data.textWindowInfo);
255
+ frames.push({ origin: data.origin, text });
256
+ remaining -= data.text.length;
257
+ }
258
+ } catch (error) {
259
+ if (!frame.isDetached() && !/context was destroyed|navigat/i.test(error.message)) throw error;
260
+ }
261
+ }
262
+ return frames;
263
+ }
264
+
265
+ export function observationDelta(before, after) {
266
+ const removed = before.elements.map(({role, name}) => ({role, name}));
267
+ const added = [];
268
+ for (const {role, name} of after.elements) {
269
+ const index = removed.findIndex(item => item.role === role && item.name === name);
270
+ if (index < 0) added.push({role, name});
271
+ else removed.splice(index, 1);
272
+ }
273
+ const textChanged = before.text !== after.text;
274
+ const oldByRef = new Map(before.elements.map(item => [item.ref, item]));
275
+ const changed = after.elements.filter(item => {
276
+ const old = oldByRef.get(item.ref);
277
+ return old && ['checked','pressed','expanded','selected'].some(key => item[key] !== old[key]);
278
+ });
279
+ return { ...(changed.length && {changed}), textChanged, ...(textChanged && { text: after.text }), added, removed };
280
+ }
package/paths.mjs ADDED
@@ -0,0 +1,20 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { homedir } from 'node:os';
3
+ import path from 'node:path';
4
+
5
+ export const profileId = process.env.OPEN_BROWSER_PROFILE || 'default';
6
+ const base = path.resolve(process.env.OPEN_BROWSER_STATE_DIR || path.join(homedir(), '.open-browser'));
7
+
8
+ export function pathsForProfile(id) {
9
+ if (typeof id !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,47}$/.test(id)) throw new Error('invalid_profile');
10
+ const stateDir = id === 'default' ? base : path.join(base, 'profiles', id);
11
+ const instance = createHash('sha256').update(stateDir).digest('hex').slice(0, 16);
12
+ const socketFile = path.join(stateDir, 'open-browser.sock');
13
+ const socketPath = process.platform === 'win32'
14
+ ? '\\\\.\\pipe\\open-browser-' + instance
15
+ : Buffer.byteLength(socketFile) < 100 ? socketFile : path.join('/tmp', 'open-browser-' + process.getuid() + '-' + instance + '.sock');
16
+ return {stateDir, socketPath, tokenPath:path.join(stateDir, 'open-browser.token')};
17
+ }
18
+
19
+ export const {stateDir, socketPath, tokenPath} = pathsForProfile(profileId);
20
+ export const adminTokenPath = path.join(stateDir, 'open-browser-admin.token');
@@ -0,0 +1,95 @@
1
+ // Privacy defaults are deliberately local-first. Page traffic is still
2
+ // governed by network-policy.mjs and the user's explicit target origins.
3
+ const serviceFeatures = [
4
+ 'AutofillServerCommunication',
5
+ 'OptimizationHints',
6
+ 'MediaRouter',
7
+ 'Translate',
8
+ 'CertificateTransparencyComponentUpdater',
9
+ 'InterestFeedContentSuggestions',
10
+ 'Reporting',
11
+ 'NetworkTimeServiceQuery',
12
+ 'Topics',
13
+ 'Fledge',
14
+ 'NewTabPage',
15
+ 'Signin',
16
+ 'AccountConsistency',
17
+ ].join(',');
18
+
19
+ const strictArgs = Object.freeze([
20
+ '--disable-background-networking',
21
+ '--disable-component-update',
22
+ '--disable-domain-reliability',
23
+ '--disable-default-apps',
24
+ '--disable-breakpad',
25
+ '--disable-crash-reporter',
26
+ '--disable-sync',
27
+ '--disable-account-consistency',
28
+ '--disable-signin-promo',
29
+ '--disable-search-engine-choice-screen',
30
+ '--disable-network-time',
31
+ '--disable-variations',
32
+ '--no-first-run',
33
+ '--no-default-browser-check',
34
+ '--no-pings',
35
+ `--disable-features=${serviceFeatures}`,
36
+ ]);
37
+
38
+ export function privacyProfile() {
39
+ return process.env.OPEN_BROWSER_PRIVACY_PROFILE?.trim().toLowerCase() || 'strict';
40
+ }
41
+
42
+ export function chromiumPrivacyArgs() {
43
+ // A deliberate opt-in exists for compatibility testing with Chromium
44
+ // services. The shipped default remains strict and has no telemetry path.
45
+ return privacyProfile() === 'compatibility' ? [] : [...strictArgs];
46
+ }
47
+
48
+ export function privacyCapabilities() {
49
+ const profile = privacyProfile();
50
+ return {
51
+ profile,
52
+ telemetry: 'disabled',
53
+ chromiumServices: profile === 'compatibility' ? 'compatibility' : 'reduced',
54
+ taskNetwork: 'explicit-origins',
55
+ diagnostics: 'redacted',
56
+ credentials: 'memory-scoped',
57
+ };
58
+ }
59
+
60
+ const secretKey = '(?:password|passwd|passcode|token|secret|api[_-]?key|access[_-]?token|refresh[_-]?token|authorization|auth|session(?:id)?|sid|cookie|csrf|xsrf|otp|pin|code|signature|credential|private[_-]?key)';
61
+ const keyValue = new RegExp(`(\\b${secretKey}\\b\\s*(?:=|:|->)\\s*)([^\\s,;&]+)`, 'giu');
62
+ const bearer = /\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+\/-]{8,}\b/giu;
63
+ const jwt = /\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/gu;
64
+
65
+ function redactUrl(value) {
66
+ let url;
67
+ try { url = new URL(value); } catch { return value; }
68
+ if (!['http:', 'https:'].includes(url.protocol)) return value;
69
+ for (const key of url.searchParams.keys()) {
70
+ if (new RegExp(`^${secretKey}$`, 'iu').test(key)) url.searchParams.set(key, '[redacted]');
71
+ }
72
+ // Fragments are client-side state and frequently contain OAuth tokens.
73
+ url.hash = '';
74
+ return url.href;
75
+ }
76
+
77
+ export function redactSensitiveText(value, knownSecrets = []) {
78
+ if (typeof value !== 'string' || !value) return value;
79
+ let text = value;
80
+ for (const secret of knownSecrets) {
81
+ if (typeof secret === 'string' && secret.length) text = text.replaceAll(secret, '[redacted]');
82
+ }
83
+ text = text.replace(/https?:\/\/[^\s<>"']+/giu, redactUrl);
84
+ text = text.replace(keyValue, '$1[redacted]');
85
+ text = text.replace(bearer, '[redacted authorization]');
86
+ text = text.replace(jwt, '[redacted token]');
87
+ return text;
88
+ }
89
+
90
+ export const privacyDocumentation = Object.freeze({
91
+ defaultProfile: 'strict',
92
+ optInProfile: 'compatibility',
93
+ optInVariable: 'OPEN_BROWSER_PRIVACY_PROFILE=compatibility',
94
+ outbound: 'Chromium background services are reduced by default. Task navigation still requires explicit origins.',
95
+ });
@@ -0,0 +1,191 @@
1
+ // The service owns its local socket exclusively before opening this journal.
2
+ import {EventEmitter} from 'node:events';
3
+ import { operationDiagnostic } from './diagnostics.mjs';
4
+ import { chmodSync } from 'node:fs';
5
+ import { DatabaseSync } from 'node:sqlite';
6
+
7
+ const retentionMs = 7 * 24 * 3600_000;
8
+
9
+ export function durableReceipt(receipt) {
10
+ const {operationId, pageId, state, phase, totalSteps, stepKind, completedSteps, error, keptPageIds, closedPageIds, fillOutcome} = receipt;
11
+ return { operationId, ...(pageId && {pageId}), state, ...(phase && {phase}), ...(totalSteps !== undefined && {totalSteps}),
12
+ ...(stepKind && {stepKind}), completedSteps, ...(error && {error}),
13
+ ...(fillOutcome && {fillOutcome}),
14
+ ...(receipt.navigation && {navigation:receipt.navigation}),
15
+ ...(keptPageIds && {keptPageIds: [...keptPageIds]}), ...(closedPageIds && {closedPageIds: [...closedPageIds]}) };
16
+ }
17
+
18
+ export class ReceiptStore {
19
+ constructor(path = ':memory:', actor = () => undefined) {
20
+ this.actor = actor;
21
+ this.notifications = new EventEmitter();
22
+ this.waiting = 0;
23
+ this.db = new DatabaseSync(path);
24
+ if (path !== ':memory:') chmodSync(path, 0o600);
25
+ this.db.exec(`PRAGMA synchronous=FULL;
26
+ CREATE TABLE IF NOT EXISTS receipts (
27
+ owner TEXT, workspace TEXT, operation TEXT, digest TEXT NOT NULL, data TEXT NOT NULL,
28
+ inflight INTEGER NOT NULL, expires INTEGER NOT NULL, PRIMARY KEY(owner,workspace,operation));
29
+ CREATE TABLE IF NOT EXISTS recovery_objects (
30
+ owner TEXT NOT NULL, workspace TEXT NOT NULL, kind TEXT NOT NULL, id TEXT NOT NULL, expires INTEGER NOT NULL,
31
+ PRIMARY KEY(owner,workspace,kind,id));
32
+ CREATE INDEX IF NOT EXISTS recovery_expiry ON recovery_objects(expires);
33
+ CREATE INDEX IF NOT EXISTS receipt_expiry ON receipts(expires);
34
+ CREATE TABLE IF NOT EXISTS events (
35
+ sequence INTEGER PRIMARY KEY AUTOINCREMENT, owner TEXT, workspace TEXT, kind TEXT, state TEXT,
36
+ operationId TEXT, completedSteps INTEGER, expires INTEGER, actorId TEXT, pixelWidth INTEGER, pixelHeight INTEGER);
37
+ CREATE INDEX IF NOT EXISTS event_feed ON events(owner,workspace,sequence);
38
+ CREATE INDEX IF NOT EXISTS event_expiry ON events(expires);`);
39
+ this.sweep = this.db.prepare('DELETE FROM receipts WHERE expires <= ?');
40
+ this.sweepRecovery = this.db.prepare('DELETE FROM recovery_objects WHERE expires<=?');
41
+ this.sweepRecovery.run(Date.now());
42
+ this.sweep.run(Date.now());
43
+ this.sweepEvents = this.db.prepare('DELETE FROM events WHERE expires<=?');
44
+ this.sweepEvents.run(Date.now());
45
+ const columns = new Set(this.db.prepare('PRAGMA table_info(events)').all().map(field=>field.name));
46
+ for(const [name,type] of [['actorId','TEXT'],['pixelWidth','INTEGER'],['pixelHeight','INTEGER'],['pageId','TEXT'],['resourceId','TEXT']])
47
+ if(!columns.has(name)) this.db.exec(`ALTER TABLE events ADD COLUMN ${name} ${type}`);
48
+ this.appendEvent = this.db.prepare('INSERT INTO events(owner,workspace,kind,state,operationId,completedSteps,expires,actorId,pixelWidth,pixelHeight,pageId,resourceId) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)');
49
+ this.nextSweep = Date.now() + 60_000;
50
+ this.read = this.db.prepare('SELECT digest,data FROM receipts WHERE owner=? AND workspace=? AND operation=? AND expires>?');
51
+ this.write = this.db.prepare(`INSERT INTO receipts VALUES (?,?,?,?,?,?,?)
52
+ ON CONFLICT(owner,workspace,operation) DO UPDATE SET data=excluded.data,inflight=excluded.inflight,expires=excluded.expires
53
+ WHERE receipts.digest=excluded.digest`);
54
+ for (const row of this.db.prepare('SELECT * FROM receipts WHERE json_extract(data,\'$.state\') IN (\'queued\',\'running\')').all()) {
55
+ const receipt = JSON.parse(row.data);
56
+ receipt.state = row.inflight ? 'outcome_unknown' : 'cancelled';
57
+ receipt.phase = receipt.state;
58
+ receipt.error = row.inflight ? 'inspect_before_retry' : 'service_restarted';
59
+ this.save(row.owner, row.workspace, row.digest, receipt);
60
+ }
61
+ }
62
+
63
+ remember(owner, workspace, kind, id) {
64
+ this.db.prepare('INSERT OR REPLACE INTO recovery_objects VALUES (?,?,?,?,?)')
65
+ .run(owner, workspace, kind, id, Date.now() + retentionMs);
66
+ }
67
+
68
+ recoveryObjects(owner, workspace, after = 0, limit = 50) {
69
+ if (!Number.isSafeInteger(after) || after < 0) throw Object.assign(new Error('invalid_params'), {code:'invalid_params'});
70
+ // ReceiptStore.list has already validated the common limit.
71
+ const rows = this.db.prepare('SELECT rowid,kind,id FROM recovery_objects WHERE owner=? AND workspace=? AND expires>? AND rowid>? ORDER BY rowid LIMIT ?')
72
+ .all(owner, workspace, Date.now(), after, limit + 1);
73
+ return {records:rows.slice(0,limit), nextObjectCursor:rows.length > limit ? rows[limit-1].rowid : null};
74
+ }
75
+
76
+ get(owner, workspace, id) {
77
+ if (typeof workspace !== 'string' || typeof id !== 'string') return null;
78
+ const row = this.read.get(owner, workspace, id, Date.now());
79
+ return row ? { digest: row.digest, receipt: JSON.parse(row.data) } : null;
80
+ }
81
+
82
+ list(owner, workspace, after = 0, limit = 50) {
83
+ if (typeof workspace !== 'string' || !Number.isSafeInteger(after) || after < 0 ||
84
+ !Number.isInteger(limit) || limit < 1 || limit > 100)
85
+ throw Object.assign(new Error('invalid_params'), {code:'invalid_params'});
86
+ const rows = this.db.prepare('SELECT rowid,data FROM receipts WHERE owner=? AND workspace=? AND rowid>? AND expires>? ORDER BY rowid LIMIT ?')
87
+ .all(owner, workspace, after, Date.now(), limit + 1);
88
+ return { operations: rows.slice(0, limit).map(row => JSON.parse(row.data)),
89
+ nextCursor: rows.length > limit ? rows[limit - 1].rowid : null };
90
+ }
91
+
92
+ save(owner, workspace, digest, receipt, inflight = false) {
93
+ const now = Date.now();
94
+ if (now >= this.nextSweep) {
95
+ this.sweepRecovery.run(now);
96
+ this.sweep.run(now);
97
+ this.sweepEvents.run(now);
98
+ this.nextSweep = now + 60_000;
99
+ }
100
+ this.db.exec('BEGIN IMMEDIATE');
101
+ try {
102
+ const result = this.write.run(owner, workspace, receipt.operationId, digest,
103
+ JSON.stringify(durableReceipt(receipt)), Number(inflight), now + retentionMs);
104
+ if (!result.changes) throw Object.assign(new Error('operation_id_conflict'), {code:'operation_id_conflict'});
105
+ this.event(owner, workspace, inflight ? 'dispatch' : 'operation', receipt.state, receipt.operationId, receipt.completedSteps);
106
+ this.db.exec('COMMIT');
107
+ } catch (error) { this.db.exec('ROLLBACK'); throw error; }
108
+ }
109
+
110
+ event(owner, workspace, kind, state, operation = null, steps = null, size = {}) {
111
+ this.appendEvent.run(owner, workspace, kind, state, operation, steps, Date.now() + retentionMs, this.actor() || owner,
112
+ size.pixelWidth ?? null, size.pixelHeight ?? null, size.pageId ?? null,size.resourceId ?? null);
113
+ if (size.resourceId) this.notifications.emit(workspace);
114
+
115
+ }
116
+
117
+ events(owner, workspace, after = 0, limit = 50) {
118
+ if (typeof workspace !== 'string' || !Number.isSafeInteger(after) || after < 0 ||
119
+ !Number.isInteger(limit) || limit < 1 || limit > 100)
120
+ throw Object.assign(new Error('invalid_params'), {code:'invalid_params'});
121
+ const rows = this.db.prepare('SELECT sequence,kind,state,operationId,completedSteps,actorId,pixelWidth,pixelHeight,pageId,resourceId FROM events WHERE owner=? AND workspace=? AND sequence>? AND expires>? ORDER BY sequence LIMIT ?')
122
+ .all(owner, workspace, after, Date.now(), limit);
123
+ return { events: rows.map(row => Object.fromEntries(Object.entries(row).filter(([,value]) => value !== null))),
124
+ nextCursor: rows.at(-1)?.sequence ?? after };
125
+ }
126
+
127
+ cursor(owner,workspace) {
128
+ return {nextCursor:this.db.prepare('SELECT COALESCE(MAX(sequence),0) AS cursor FROM events WHERE owner=? AND workspace=?')
129
+ .get(owner,workspace).cursor};
130
+ }
131
+
132
+ waitForEvent(owner,{workspaceId,pageId,operationId,kind,after,timeoutMs=5000}) {
133
+ if (!Number.isSafeInteger(after) || after<0 || !Number.isSafeInteger(timeoutMs) || timeoutMs<1 || timeoutMs>10000 ||
134
+ !['dialog','popup','download'].includes(kind) || typeof pageId!=='string' ||
135
+ (operationId!==undefined && typeof operationId!=='string'))
136
+ throw Object.assign(new Error('invalid_params'),{code:'invalid_params'});
137
+ const sql=`SELECT sequence,kind,state,pageId,resourceId,operationId FROM events
138
+ WHERE owner=? AND workspace=? AND pageId=? AND kind=? AND sequence>? AND expires>?
139
+ AND (? IS NULL OR operationId=?) ORDER BY sequence LIMIT 1`;
140
+ const query=this.db.prepare(sql);
141
+ const read=()=>{
142
+ const row=query.get(owner,workspaceId,pageId,kind,after,Date.now(),operationId??null,operationId??null);
143
+ if (row?.operationId===null) delete row.operationId;
144
+ return row && {event:row,nextCursor:row.sequence};
145
+ };
146
+ const first=read();
147
+ if (first) return first;
148
+ if (this.waiting>=128 || this.notifications.listenerCount(workspaceId)>=8)
149
+ throw Object.assign(new Error('queue_full'),{code:'queue_full'});
150
+ return new Promise(resolve=>{
151
+ const done=result=>{
152
+ clearTimeout(timer);
153
+ this.notifications.off(workspaceId,changed);
154
+ this.waiting--;
155
+ resolve(result || {event:null,nextCursor:after});
156
+ };
157
+ const changed=()=>{
158
+ if (this.closing) return done();
159
+ const event=read();
160
+ if (event) done(event);
161
+ };
162
+ this.waiting++;
163
+ const timer=setTimeout(done,timeoutMs);
164
+ this.notifications.on(workspaceId,changed);
165
+ });
166
+ }
167
+
168
+ diagnose(owner, workspace, operationId) {
169
+ const record = this.get(owner, workspace, operationId);
170
+ if (!record) throw Object.assign(new Error('operation_not_found'), {code:'operation_not_found'});
171
+ const dispatched = this.db.prepare("SELECT 1 FROM events WHERE owner=? AND workspace=? AND operationId=? AND kind='dispatch' AND expires>? LIMIT 1")
172
+ .get(owner, workspace, operationId, Date.now());
173
+ return operationDiagnostic(record.receipt, Boolean(dispatched));
174
+ }
175
+
176
+ clear(workspace) {
177
+ this.db.exec('BEGIN IMMEDIATE');
178
+ try {
179
+ this.db.prepare('DELETE FROM recovery_objects WHERE workspace=?').run(workspace);
180
+ this.db.prepare('DELETE FROM receipts WHERE workspace=?').run(workspace);
181
+ this.db.prepare('DELETE FROM events WHERE workspace=?').run(workspace);
182
+ this.db.exec('COMMIT');
183
+ } catch (error) { this.db.exec('ROLLBACK'); throw error; }
184
+ }
185
+
186
+ close() {
187
+ this.closing=true;
188
+ for (const workspace of this.notifications.eventNames()) this.notifications.emit(workspace);
189
+ this.db.close();
190
+ }
191
+ }
package/runtime.mjs ADDED
@@ -0,0 +1,44 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { readFile, realpath, rename, writeFile } from 'node:fs/promises';
4
+ import { createRequire } from 'node:module';
5
+ import path from 'node:path';
6
+ import { fileURLToPath, pathToFileURL } from 'node:url';
7
+
8
+ const require = createRequire(import.meta.url);
9
+ const version = require('playwright-core/package.json').version;
10
+ const engineDir = fileURLToPath(new URL('./.open-browser/engine/', import.meta.url));
11
+ const manifest = path.join(engineDir, `engine-${version}-${process.platform}-${process.arch}.json`);
12
+
13
+ export async function engineExecutable() {
14
+ try {
15
+ const entry = JSON.parse(await readFile(manifest, 'utf8'));
16
+ const executable = await realpath(path.join(engineDir, entry.executable));
17
+ const relative = path.relative(await realpath(engineDir), executable);
18
+ if (!relative || relative.startsWith('..' + path.sep) || path.isAbsolute(relative))
19
+ throw new Error('Invalid engine path');
20
+ return executable;
21
+ } catch {
22
+ throw new Error('open-browser engine unavailable. Run npm run browser:install.');
23
+ }
24
+ }
25
+
26
+ async function install() {
27
+ process.env.PLAYWRIGHT_BROWSERS_PATH = engineDir;
28
+ const cli = path.join(path.dirname(require.resolve('playwright-core/package.json')), 'cli.js');
29
+ execFileSync(process.execPath, [cli, 'install', 'chromium', '--no-shell'], { stdio: 'inherit' });
30
+ const { chromium } = await import('playwright-core');
31
+ let binary = await realpath(chromium.executablePath());
32
+ if (process.platform === 'win32') {
33
+ const { installWindowsIcons } = await import('./desktop/brand-windows-icons.mjs');
34
+ binary = await installWindowsIcons(binary);
35
+ }
36
+ const executable = path.relative(engineDir, binary);
37
+ const temp = manifest + '.' + randomUUID();
38
+ await writeFile(temp, JSON.stringify({ executable }) + '\n', { flag: 'wx' });
39
+ await rename(temp, manifest);
40
+ }
41
+
42
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
43
+ await install();
44
+ }