@seekskyworld/open-browser 0.1.0 → 0.3.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 (68) hide show
  1. package/Docs/open-browser-api.d.ts +32 -10
  2. 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 +51 -3
  3. package/README.md +14 -5
  4. package/README.zh-CN.md +16 -5
  5. package/access-registry.mjs +13 -3
  6. package/action-execution.mjs +60 -24
  7. package/api-contract.mjs +19 -7
  8. package/browser-extension/manifest.json +1 -4
  9. package/browser-extension/newtab.css +6 -0
  10. package/browser-extension/newtab.js +54 -2
  11. package/browser-extension/phase-labels.js +1 -1
  12. package/browser-extension/popup.css +1 -1
  13. package/browser-extension/popup.html +16 -4
  14. package/browser-extension/popup.js +122 -21
  15. package/browser-extension/tab-action.js +4 -2
  16. package/browser-extension/worker.js +102 -9
  17. package/build-profile.mjs +23 -0
  18. package/capability-matrix.mjs +4 -4
  19. package/chromium-host.mjs +81 -25
  20. package/chromium-shell.mjs +78 -49
  21. package/cli.mjs +63 -5
  22. package/contract-validation.mjs +1 -1
  23. package/desktop/Info.plist +2 -2
  24. package/desktop/OBControlBar.m +7 -3
  25. package/desktop/WorkspacePanel.m +4 -2
  26. package/desktop/brand-keychain.py +20 -4
  27. package/desktop/build-macos.mjs +31 -12
  28. package/desktop/build-managed-input.mjs +37 -0
  29. package/desktop/build-profile.mjs +6 -0
  30. package/desktop/build.mjs +8 -0
  31. package/desktop/macos-entitlements.plist +12 -0
  32. package/desktop/notarize-macos.mjs +189 -0
  33. package/desktop/package-macos.mjs +54 -0
  34. package/desktop/patches/chromium-managed-input.patch +144 -0
  35. package/desktop/sign.mjs +63 -4
  36. package/desktop/start-profile.mjs +5 -0
  37. package/desktop/start.mjs +25 -3
  38. package/desktop/verify-macos-release.mjs +69 -0
  39. package/desktop/verify-version.mjs +22 -2
  40. package/diagnostics.mjs +9 -0
  41. package/engine-service.mjs +244 -29
  42. package/managed-input.mjs +155 -0
  43. package/mcp-http.mjs +84 -0
  44. package/mcp-server.mjs +57 -0
  45. package/mcp.mjs +3 -40
  46. package/package.json +24 -3
  47. package/page-activity.mjs +97 -29
  48. package/page-observation.mjs +44 -3
  49. package/paths.mjs +5 -3
  50. package/receipt-store.mjs +24 -7
  51. package/runtime.mjs +10 -1
  52. package/sdk.mjs +53 -26
  53. package/service.mjs +45 -10
  54. package/skill-links.mjs +144 -0
  55. package/skills/open-browser/SKILL.md +8 -76
  56. package/skills/open-browser/references/macos.md +3 -0
  57. package/skills/open-browser/references/operations.md +59 -0
  58. package/skills/open-browser/references/recovery.md +36 -0
  59. package/skills/open-browser/references/windows.md +3 -0
  60. package/skills/open-browser/scripts/bootstrap.mjs +112 -45
  61. package/skills/open-browser/scripts/guide.mjs +17 -0
  62. package/studio/studio.js +2 -2
  63. package/tab-adoption.mjs +83 -0
  64. package/tab-recovery.mjs +100 -0
  65. package/uploads.mjs +4 -4
  66. package/visual-page.mjs +17 -7
  67. package/workspace-lifecycle.mjs +92 -8
  68. package/workspace-state.mjs +65 -12
package/cli.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { writeFile } from 'node:fs/promises';
3
+ import { createInterface } from 'node:readline';
3
4
  import { socketPath, adminTokenPath } from './paths.mjs';
4
5
  import { localRequest, agentMethods, OpenBrowserClient, OpenBrowserError } from './sdk.mjs';
5
6
 
@@ -13,6 +14,9 @@ const help = `open-browser <method> [< params.json]
13
14
  printf '%s\\n' '{"workspaceId":"WORKSPACE_ID","pageId":"PAGE_ID"}' | open-browser observe
14
15
  printf '%s\\n' '{"workspaceId":"WORKSPACE_ID","operationId":"finish-UNIQUE-ID","keepPageIds":[]}' | open-browser finishWorkspace
15
16
 
17
+ open-browser --json <method> # stdout 返回 {result} 或 {error},失败保留非零退出码
18
+ open-browser session # 每行读取 {"id":1,"method":"observe","params":{...}},直到 stdin 关闭
19
+
16
20
  echo '{"name":"网页检查","agentName":"研究助手"}' | node cli.mjs createWorkspace
17
21
  echo '{"url":"https://example.org","name":"网页检查"}' | node cli.mjs open
18
22
  node cli.mjs listWorkspaces
@@ -23,6 +27,7 @@ const help = `open-browser <method> [< params.json]
23
27
  需要完整参数契约时运行:node cli.mjs --schema
24
28
  本机管理命令:admin.pair、admin.list、admin.grant、admin.revoke、admin.revokeClient、admin.clearHistory、admin.scheduler、admin.setPixelPermission。
25
29
  凭据在可信的本地控制台设置;使用 fillCredential 和 credentialRef 填写登录字段。
30
+ open-browser skill # 输出与当前包版本匹配的 Skill 指南
26
31
  `;
27
32
 
28
33
  async function readParams() {
@@ -40,13 +45,60 @@ async function readParams() {
40
45
  catch { throw new OpenBrowserError('INVALID_JSON', '标准输入必须是 JSON 对象。'); }
41
46
  }
42
47
 
48
+ async function sessionMain() {
49
+ const api = new OpenBrowserClient({ fallbackName: 'CLI session' });
50
+ const input = createInterface({ input: process.stdin, crlfDelay: Infinity });
51
+ let tail = Promise.resolve();
52
+ const send = frame => process.stdout.write(JSON.stringify(frame) + '\n');
53
+ input.on('line', line => {
54
+ tail = tail.then(async () => {
55
+ let frame;
56
+ try { frame = JSON.parse(line); } catch { send({ id: null, error: { code: 'INVALID_JSON', message: '每行必须是 JSON 请求。' } }); return; }
57
+ const id = frame?.id;
58
+ if (!(typeof id === 'string' || Number.isSafeInteger(id)) || typeof frame?.method !== 'string' || !frame.method ||
59
+ (frame.params !== undefined && (!frame.params || typeof frame.params !== 'object' || Array.isArray(frame.params)))) {
60
+ send({ id: id ?? null, error: { code: 'INVALID_PARAMS', message: 'session 请求需要 id、method 和对象 params。' } });
61
+ return;
62
+ }
63
+ try {
64
+ const result = await api.call(frame.method, frame.params ?? {});
65
+ send({ id, result: result ?? null });
66
+ } catch (error) {
67
+ send({ id, error: { code: error.code ?? 'CLI_ERROR', message: error.message,
68
+ ...(error.nextAction ? { nextAction: error.nextAction } : {}) } });
69
+ }
70
+ });
71
+ });
72
+ await new Promise(resolve => input.once('close', resolve));
73
+ await tail;
74
+ api.close();
75
+ }
76
+
77
+ const jsonMode = process.argv[2] === '--json';
78
+ function writeResult(result) {
79
+ process.stdout.write(JSON.stringify(jsonMode ? {result:result ?? null} : result) + '\n');
80
+ }
81
+
43
82
  async function main() {
44
- const [method, ...extra] = process.argv.slice(2);
83
+ const [method, ...extra] = process.argv.slice(jsonMode ? 3 : 2);
84
+ if (jsonMode && !agentMethods.includes(method) && !method?.startsWith('admin.'))
85
+ throw new OpenBrowserError('UNKNOWN_METHOD','--json 需要一个 API 方法名。');
86
+ if (method === 'session') {
87
+ if (extra.length) throw new OpenBrowserError('INVALID_PARAMS', 'session 不接受额外参数。');
88
+ await sessionMain();
89
+ return;
90
+ }
45
91
  if (method === '--schema') {
46
92
  const { tools } = await import('./api-contract.mjs');
47
93
  process.stdout.write(JSON.stringify(tools, null, 2) + '\n');
48
94
  return;
49
95
  }
96
+ if (method === 'skill') {
97
+ if (extra.length) throw new OpenBrowserError('INVALID_PARAMS', 'skill 不接受额外参数。');
98
+ const { readSkillGuide } = await import('./skills/open-browser/scripts/guide.mjs');
99
+ process.stdout.write(await readSkillGuide());
100
+ return;
101
+ }
50
102
  if (!method || method === '--help' || method === '-h') {
51
103
  process.stdout.write(help);
52
104
  return;
@@ -61,21 +113,27 @@ async function main() {
61
113
  const result = await admin(method.slice(6),args);
62
114
  if (method === 'admin.pair') {
63
115
  try { await writeFile(tokenFile,result.token + '\n',{flag:'wx',mode:0o600}); }
64
- catch (error) { await admin('revokeClient',{principalId:result.principalId}); throw error; }
116
+ catch (error) {
117
+ try { await admin('revokeClient', {principalId:result.principalId}); }
118
+ catch {
119
+ throw new OpenBrowserError('PAIR_CLEANUP_FAILED', `令牌文件写入失败,请用 admin.revokeClient 核对并撤销 ${result.principalId}。`);
120
+ }
121
+ throw error;
122
+ }
65
123
  delete result.token;
66
124
  }
67
- process.stdout.write(JSON.stringify(result) + '\n');
125
+ writeResult(result);
68
126
  return;
69
127
  }
70
128
  if (!agentMethods.includes(method)) throw new OpenBrowserError('UNKNOWN_METHOD', '未知的方法,请用 --help 查看命令。');
71
129
  const api = new OpenBrowserClient({ fallbackName: 'CLI' });
72
130
  const params = await readParams();
73
131
  const result = method === 'capabilities' ? await api.capabilities() : await api.call(method, params);
74
- process.stdout.write(JSON.stringify(result) + '\n');
132
+ writeResult(result);
75
133
  }
76
134
 
77
135
  main().catch(error => {
78
- process.stderr.write(JSON.stringify({ error: {
136
+ (jsonMode ? process.stdout : process.stderr).write(JSON.stringify({ error: {
79
137
  code: error.code ?? 'CLI_ERROR', message: error.message,
80
138
  ...(error.nextAction ? { nextAction: error.nextAction } : {}),
81
139
  } }) + '\n');
@@ -7,7 +7,7 @@ const schemas = new Map(tools.map(tool => [tool.name,tool.inputSchema]));
7
7
  // Older callers spread a returned page or workspace handle into a subsequent request.
8
8
  // Strip only the known read-only handle fields before checking that request.
9
9
  const viewFields = new Set(['agentName','name','mode','pages','controlGeneration','activity','blockedOrigins','pageId','origin','title','profile','profileId','profileAlias',
10
- 'openedByOperationId','openerPageId','documentId','pendingDialogs']);
10
+ 'pageAvailability','readyForAgent','nextAction','scope','accountAlias','ownership','syncState','syncRevision','lastSyncedAt','security','openedByOperationId','openerPageId','documentId','pendingDialogs']);
11
11
 
12
12
  export function checkAgentRequest(method, params) {
13
13
  const schema = schemas.get(method);
@@ -7,7 +7,7 @@
7
7
  <key>CFBundleExecutable</key><string>open-browser</string>
8
8
  <key>CFBundlePackageType</key><string>APPL</string>
9
9
  <key>CFBundleIconFile</key><string>open-browser.icns</string>
10
- <key>CFBundleVersion</key><string>1</string>
11
- <key>CFBundleShortVersionString</key><string>0.1.0</string>
10
+ <key>CFBundleVersion</key><string>2</string>
11
+ <key>CFBundleShortVersionString</key><string>0.3.0</string>
12
12
  <key>NSHighResolutionCapable</key><true/>
13
13
  </dict></plist>
@@ -130,9 +130,12 @@ static NSString *Text(id value) { return [value isKindOfClass:NSString.class] ?
130
130
 
131
131
  - (BOOL)frontMatches:(CGRect)bounds {
132
132
  NSRunningApplication *front = NSWorkspace.sharedWorkspace.frontmostApplication;
133
- if (![front.bundleIdentifier isEqual:@"local.open-browser.chromium"] || front.hidden) return NO;
133
+ BOOL dev = [NSBundle.mainBundle.bundleIdentifier isEqual:@"local.open-browser.desktop-dev"];
134
+ NSString *engineID = dev ? @"local.open-browser-dev.chromium" : @"local.open-browser.chromium";
135
+ if (![front.bundleIdentifier isEqual:engineID] || front.hidden) return NO;
134
136
  NSString *path = front.executableURL.URLByResolvingSymlinksInPath.path;
135
- return [path hasPrefix:self.rootPrefix] && [path hasSuffix:@"/open-browser.app/Contents/MacOS/open-browser"] &&
137
+ NSString *suffix = dev ? @"/open-browser-dev.app/Contents/MacOS/open-browser" : @"/open-browser.app/Contents/MacOS/open-browser";
138
+ return [path hasPrefix:self.rootPrefix] && [path hasSuffix:suffix] &&
136
139
  IsChildOfService(front.processIdentifier, self.servicePID) && FrontWindowMatches(front.processIdentifier, bounds);
137
140
  }
138
141
 
@@ -177,10 +180,11 @@ static NSString *Text(id value) { return [value isKindOfClass:NSString.class] ?
177
180
  if (![self.pending isEqual:binding]) self.pending = nil;
178
181
  BOOL human = [bar[@"mode"] isEqual:@"human"], transferring = [bar[@"mode"] isEqual:@"transferring"];
179
182
  NSDictionary *states = @{@"actionability":@"检查目标", @"dispatching":@"正在派发", @"waiting":@"等待页面", @"verifying":@"核对结果", @"dispatched":@"已派发", @"running":@"执行中", @"queued":@"已排队", @"idle":@"待命", @"completed":@"已完成",
180
- @"needs_credential":@"等待凭据", @"failed":@"失败", @"cancelled":@"已取消", @"outcome_unknown":@"待核实"};
183
+ @"needs_credential":@"等待凭据", @"needs_human_verification":@"需要人工验证", @"failed":@"失败", @"cancelled":@"已取消", @"outcome_unknown":@"待核实"};
181
184
  self.agent.stringValue = Text(bar[@"agentName"]).length ? bar[@"agentName"] : @"Agent";
182
185
  self.agent.toolTip = self.agent.stringValue;
183
186
  self.status.stringValue = transferring ? @"交接中" : human ? @"人工控制" : states[Text(bar[@"phase"])] ?: @"待命";
187
+ self.button.bezelColor = !human && !transferring && [bar[@"inputBlocked"] boolValue] ? NSColor.systemOrangeColor : nil;
184
188
  self.button.title = human ? @"交回 Agent" : @"人工接管";
185
189
  self.delivery.enabled = !transferring;
186
190
  self.button.enabled = !transferring && !self.pending;
@@ -49,7 +49,7 @@ static NSString *Operation(NSDictionary *op) {
49
49
  static NSInteger Group(NSDictionary *workspace) {
50
50
  NSDictionary *activity = workspace[@"activity"];
51
51
  if (![workspace[@"mode"] isEqual:@"agent"]) return 2;
52
- if ([activity[@"needsCredential"] boolValue] || [@[@"failed", @"outcome_unknown", @"needs_credential"] containsObject:String(activity[@"phase"])]) return 0;
52
+ if ([activity[@"needsCredential"] boolValue] || [activity[@"needsVisualPermission"] boolValue] || [@[@"failed", @"outcome_unknown", @"needs_credential", @"needs_visual_permission"] containsObject:String(activity[@"phase"])]) return 0;
53
53
  if (Map(activity[@"current"]) || [activity[@"queued"] integerValue] || [@[@"queued", @"running"] containsObject:String(activity[@"phase"])]) return 1;
54
54
  return 3;
55
55
  }
@@ -58,12 +58,14 @@ static NSString *Status(NSDictionary *workspace) {
58
58
  if ([workspace[@"mode"] isEqual:@"human"]) return @"用户控制 · Agent 已暂停";
59
59
  if ([workspace[@"mode"] isEqual:@"transferring"]) return @"正在交接控制权";
60
60
  NSDictionary *activity = workspace[@"activity"];
61
+ if ([activity[@"needsHumanVerification"] boolValue]) return @"需要人工验证";
61
62
  if ([activity[@"needsCredential"] boolValue]) return @"等待补充凭据";
63
+ if ([activity[@"needsVisualPermission"] boolValue]) return @"需要授权截图";
62
64
  NSString *current = Operation(Map(activity[@"current"]));
63
65
  if (current.length) return current;
64
66
  NSDictionary *phase = @{@"running":@"执行中", @"actionability":@"检查目标", @"dispatching":@"正在派发",
65
67
  @"waiting":@"等待页面", @"verifying":@"核对结果", @"queued":@"排队中", @"completed":@"已完成", @"failed":@"执行失败",
66
- @"outcome_unknown":@"结果待核对", @"cancelled":@"已取消", @"needs_credential":@"等待补充凭据"};
68
+ @"outcome_unknown":@"结果待核对", @"cancelled":@"已取消", @"needs_credential":@"等待补充凭据", @"needs_human_verification":@"需要人工验证", @"needs_visual_permission":@"需要授权截图"};
67
69
  return phase[String(activity[@"phase"])] ?: @"等待指令";
68
70
  }
69
71
 
@@ -19,7 +19,10 @@ VERSION = '159.0.8154.6'
19
19
  REVISION = '98a2592026af8d673b9fa83b626ac68bdf4ae78a'
20
20
  FRAMEWORK = 'Google Chrome for Testing Framework'
21
21
  SOURCE = b'Chromium Safe Storage'
22
- PRODUCT = b'open-browser Keychain'
22
+ DEV = os.environ.get('OPEN_BROWSER_BUILD_PROFILE', '').strip().lower() == 'dev'
23
+ STABLE_PRODUCT = b'open-browser Keychain'
24
+ PRODUCT = b'open-browser Dev Safe' if DEV else STABLE_PRODUCT
25
+ EXPECTED_BUNDLE = 'local.open-browser-dev.chromium' if DEV else 'local.open-browser.chromium'
23
26
  # Mach CPU type -> offset in __TEXT,__const, input hash, branded hash.
24
27
  RELEASE = {
25
28
  0x0100000C: (225772584, 'a0a2e8854ce90268f5d9b32210cf53fc0709f4b798b3c3a96964ba3ebce4bc4b',
@@ -47,11 +50,24 @@ def in_readonly_constants(data, offset):
47
50
  return False
48
51
 
49
52
 
53
+ def matches_branded_digest(data, offset, stable_digest):
54
+ # Dev differs from the pinned Stable output at exactly this constant.
55
+ end = offset + len(PRODUCT)
56
+ if data[offset:end] != PRODUCT:
57
+ return False
58
+ view = memoryview(data)
59
+ digest = hashlib.sha256(view[:offset])
60
+ digest.update(STABLE_PRODUCT)
61
+ digest.update(view[end:])
62
+ return digest.hexdigest() == stable_digest
63
+
64
+
50
65
  def brand(bundle):
51
66
  bundle = bundle.resolve(strict=True)
52
67
  with (bundle / 'Contents/Info.plist').open('rb') as stream:
53
68
  info = plistlib.load(stream)
54
- if (bundle.name != 'open-browser.app' or info.get('CFBundleIdentifier') != 'local.open-browser.chromium'
69
+ expected_name = 'open-browser-dev.app' if DEV else 'open-browser.app'
70
+ if (bundle.name != expected_name or info.get('CFBundleIdentifier') != EXPECTED_BUNDLE
55
71
  or info.get('CFBundleShortVersionString') != VERSION
56
72
  or info.get('SCMRevision', '').split('-')[0] != REVISION):
57
73
  raise ValueError('Expected the staged open-browser Chromium bundle at the pinned upstream revision')
@@ -64,7 +80,7 @@ def brand(bundle):
64
80
  raise ValueError('Unrecognized framework architecture')
65
81
  offset, before, after = RELEASE[cpu]
66
82
  digest = hashlib.sha256(data).hexdigest()
67
- if digest == after:
83
+ if matches_branded_digest(data, offset, after):
68
84
  return
69
85
  if digest != before:
70
86
  raise ValueError('Framework SHA-256 differs from the reviewed official release')
@@ -73,7 +89,7 @@ def brand(bundle):
73
89
  or data.find(SOURCE) != offset or data.find(SOURCE, offset + 1) != -1):
74
90
  raise ValueError('Unexpected keychain service constant layout')
75
91
  data[offset:offset+len(SOURCE)] = PRODUCT
76
- if hashlib.sha256(data).hexdigest() != after:
92
+ if not matches_branded_digest(data, offset, after):
77
93
  raise ValueError('Unexpected branded framework digest')
78
94
  # Publish a fully verified copy atomically, even for hardlinked input.
79
95
  with NamedTemporaryFile(dir=binary.parent, prefix='.open-browser-keychain-', delete=False) as temp:
@@ -6,27 +6,35 @@ import { fileURLToPath } from 'node:url';
6
6
  import { copyApplication } from './package-assets.mjs';
7
7
  import { engineExecutable } from '../runtime.mjs';
8
8
  import { signBundle, signingIdentity, verifyUpgrade } from './sign.mjs';
9
+ import { isDevelopmentBuild } from '../build-profile.mjs';
9
10
 
10
11
  const root = fileURLToPath(new URL('../', import.meta.url));
12
+ const archOption = process.argv.findIndex(value => value === '--arch');
13
+ const requestedArch = archOption >= 0 ? process.argv[archOption + 1] : process.env.OPEN_BROWSER_TARGET_ARCH || process.arch;
14
+ const compilerArch = requestedArch === 'x64' ? 'x86_64' : requestedArch;
11
15
  const sums = {
12
16
  arm64: 'e7131995759b61a0170b646010d2ad35a5d37b4cb0d471f3e8317eac6f742f3d',
13
17
  x64: 'c53383238206b9ae4db23c5d8a63645e2e753bec8ab51a49cc81939aa64e9422',
14
18
  };
15
- if (process.platform !== 'darwin' || !sums[process.arch]) throw new Error('macOS arm64 or x64 required');
19
+ if (process.platform !== 'darwin' || !sums[requestedArch]) throw new Error('macOS 构建目标架构必须是 arm64 或 x64。');
20
+ if (archOption >= 0 && !requestedArch) throw new Error('--arch 需要 arm64 或 x64。');
21
+ if (requestedArch !== process.arch)
22
+ throw new Error(`当前 Node 是 ${process.arch},不能伪造 ${requestedArch} 架构构建。请在对应架构的 macOS、Rosetta 下的 x64 Node,或 x64 CI runner 上运行。`);
23
+ process.env.OPEN_BROWSER_TARGET_ARCH = requestedArch;
16
24
  const identity = signingIdentity();
17
25
  await engineExecutable();
18
26
  const out = path.join(root, 'dist');
19
27
  const cache = path.join(root, '.open-browser', 'build-cache');
20
28
  await mkdir(out, { recursive: true });
21
29
  await mkdir(cache, { recursive: true });
22
- const filename = 'node-v22.23.5-darwin-' + process.arch + '.tar.gz';
30
+ const filename = 'node-v22.23.5-darwin-' + requestedArch + '.tar.gz';
23
31
  const archive = path.join(cache, filename);
24
32
  const checksum = async p => createHash('sha256').update(await readFile(p)).digest('hex');
25
- if ((await checksum(archive).catch(() => '')) !== sums[process.arch]) {
33
+ if ((await checksum(archive).catch(() => '')) !== sums[requestedArch]) {
26
34
  const temp = archive + '.' + process.pid;
27
35
  execFileSync('curl', ['--fail', '--location', '--retry', '2', '--output', temp,
28
36
  'https://nodejs.org/dist/v22.23.5/' + filename], { stdio: 'inherit' });
29
- if (await checksum(temp) !== sums[process.arch]) throw new Error('Node archive integrity check failed');
37
+ if (await checksum(temp) !== sums[requestedArch]) throw new Error('Node archive integrity check failed');
30
38
  await rename(temp, archive);
31
39
  }
32
40
 
@@ -45,44 +53,55 @@ try {
45
53
  execFileSync('tar', ['-xzf', archive, '-C', node, '--strip-components', '1',
46
54
  prefix + '/bin/node', prefix + '/LICENSE']);
47
55
  await copyFile(path.join(root, 'desktop/Info.plist'), path.join(contents, 'Info.plist'));
48
- execFileSync('xcrun', ['clang', '-fobjc-arc', '-O2', '-framework', 'AppKit', '-framework', 'CoreGraphics',
56
+ if (isDevelopmentBuild) {
57
+ const outerInfo = path.join(contents, 'Info.plist');
58
+ execFileSync('plutil', ['-replace', 'CFBundleIdentifier', '-string', 'local.open-browser.desktop-dev', outerInfo]);
59
+ execFileSync('plutil', ['-replace', 'CFBundleName', '-string', 'open-browser Dev', outerInfo]);
60
+ execFileSync('plutil', ['-replace', 'CFBundleDisplayName', '-string', 'open-browser Dev', outerInfo]);
61
+ }
62
+ execFileSync('xcrun', ['clang', '-arch', compilerArch, '-fobjc-arc', '-O2', '-framework', 'AppKit', '-framework', 'CoreGraphics',
49
63
  path.join(root, 'desktop/Launcher.m'), path.join(root, 'desktop/OBControlBar.m'),
50
64
  '-o', path.join(contents, 'MacOS/open-browser')], { stdio: 'inherit' });
51
65
  await copyFile(path.join(root, 'desktop/icons/open-browser.icns'), path.join(resources, 'open-browser.icns'));
52
66
  await copyApplication(app);
67
+ await writeFile(path.join(app, '.open-browser-build-profile'), (isDevelopmentBuild ? 'dev' : 'stable') + '\n');
53
68
  const engine = path.join(app, '.open-browser', 'engine');
54
69
  await mkdir(engine, { recursive: true });
55
70
  const sourceEngine = path.join(root, '.open-browser', 'engine');
56
71
  const executable = path.relative(sourceEngine, await engineExecutable());
57
- const build = executable.split(path.sep)[0];
58
- copyTree(path.join(sourceEngine, build), path.join(engine, build));
72
+ const platformDirectory = path.dirname(path.resolve(sourceEngine, executable, '../../..'));
73
+ const packagedDirectory = path.join(engine,path.relative(sourceEngine,platformDirectory));
74
+ await mkdir(path.dirname(packagedDirectory),{recursive:true});
75
+ copyTree(platformDirectory,packagedDirectory);
59
76
  // Brand the packaged browser, which owns the visible window and Dock entry.
60
77
  const originalBinary = path.join(engine, executable);
61
78
  const originalBundle = path.resolve(path.dirname(originalBinary), '../..');
62
- const browserBundle = path.join(path.dirname(originalBundle), 'open-browser.app');
79
+ const browserName = isDevelopmentBuild ? 'open-browser-dev.app' : 'open-browser.app';
80
+ const browserBundle = path.join(path.dirname(originalBundle), browserName);
63
81
  await rename(originalBundle, browserBundle);
64
82
  const binary = path.join(browserBundle, 'Contents/MacOS/open-browser');
65
83
  await rename(path.join(path.dirname(binary), path.basename(originalBinary)), binary);
66
84
  const plist = path.join(browserBundle, 'Contents/Info.plist');
67
85
  for (const key of ['CFBundleName', 'CFBundleDisplayName', 'CFBundleExecutable'])
68
86
  execFileSync('plutil', ['-replace', key, '-string', 'open-browser', plist]);
69
- execFileSync('plutil', ['-replace', 'CFBundleIdentifier', '-string', 'local.open-browser.chromium', plist]);
87
+ execFileSync('plutil', ['-replace', 'CFBundleIdentifier', '-string', isDevelopmentBuild ? 'local.open-browser-dev.chromium' : 'local.open-browser.chromium', plist]);
70
88
  execFileSync('python3', [path.join(root, 'desktop/brand-locales.py'), browserBundle], { stdio: 'inherit' });
71
89
  execFileSync('python3', [path.join(root, 'desktop/brand-keychain.py'), browserBundle], { stdio: 'inherit' });
72
90
  execFileSync('python3', [path.join(root, 'desktop/brand-macos-icons.py'), browserBundle], { stdio: 'inherit' });
73
91
  signBundle(browserBundle, identity, true);
74
92
  const packageInfo = JSON.parse(await readFile(path.join(root, 'node_modules/playwright-core/package.json'), 'utf8'));
75
- const manifest = 'engine-' + packageInfo.version + '-' + process.platform + '-' + process.arch + '.json';
93
+ const manifest = 'engine-' + packageInfo.version + '-' + process.platform + '-' + requestedArch + '.json';
76
94
  await writeFile(path.join(engine, manifest), JSON.stringify({ executable: path.relative(engine, binary), profileVersion: 2 }) + '\n');
77
95
  signBundle(bundle, identity);
78
- const target = path.join(out, 'open-browser.app');
96
+ const outputName = isDevelopmentBuild ? 'open-browser-dev.app' : requestedArch === 'arm64' ? 'open-browser.app' : 'open-browser-x64.app';
97
+ const target = path.join(out, outputName);
79
98
  const priorEngine = path.join(target, 'Contents/Resources/app/.open-browser/engine');
80
99
  const entries = await readdir(priorEngine).catch(e => { if (e.code === 'ENOENT') return []; throw e; });
81
100
  for (const entry of entries.filter(name => /^engine-.*-darwin-(arm64|x64)\.json$/.test(name))) {
82
101
  const prior = JSON.parse(await readFile(path.join(priorEngine, entry), 'utf8'));
83
102
  if (prior.profileVersion !== 2) continue;
84
103
  const previousBrowser = path.resolve(priorEngine, prior.executable, '../../..');
85
- if (!previousBrowser.startsWith(priorEngine + path.sep) || path.basename(previousBrowser) !== 'open-browser.app')
104
+ if (!previousBrowser.startsWith(priorEngine + path.sep) || !['open-browser.app', 'open-browser-x64.app', 'open-browser-dev.app'].includes(path.basename(previousBrowser)))
86
105
  throw new Error('旧版本 Chromium 路径无效。');
87
106
  verifyUpgrade(previousBrowser, browserBundle);
88
107
  }
@@ -0,0 +1,37 @@
1
+ // Build the Dev engine in an already synced Chromium checkout on its native OS.
2
+ import { execFileSync } from 'node:child_process';
3
+ import { existsSync, realpathSync } from 'node:fs';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+
7
+ const revision = '98a2592026af8d673b9fa83b626ac68bdf4ae78a';
8
+ const patch = fileURLToPath(new URL('./patches/chromium-managed-input.patch', import.meta.url));
9
+ const arg = process.argv[2];
10
+ if (!arg || process.argv.length !== 3) throw Error('Usage: node desktop/build-managed-input.mjs <chromium-src>');
11
+ const src = realpathSync(arg);
12
+ const run = (file, args, options = {}) => execFileSync(file, args, {cwd:src, stdio:'inherit', ...options});
13
+ const head = run('git', ['rev-parse', 'HEAD'], {stdio:'pipe', encoding:'utf8'}).trim();
14
+ if (head !== revision) throw Error('Input guard requires Chromium revision ' + revision);
15
+ try { run('git', ['apply', '--reverse', '--check', patch], {stdio:'pipe'}); }
16
+ catch {
17
+ run('git', ['apply', '--check', patch]);
18
+ run('git', ['apply', patch]);
19
+ }
20
+ const out = 'out/OpenBrowserInput';
21
+ const args = 'is_debug=false is_component_build=false symbol_level=0';
22
+ const windows = process.platform === 'win32';
23
+ // On Windows depot_tools ships GN as a batch wrapper. Pass only fixed arguments
24
+ // through cmd.exe, with the checkout supplied as cwd.
25
+ if (windows) {
26
+ run('cmd.exe', ['/d', '/c', 'gn gen out/OpenBrowserInput "--args=' + args + '"']);
27
+ run('cmd.exe', ['/d', '/c', 'autoninja -C out/OpenBrowserInput chrome content_browsertests']);
28
+ } else {
29
+ run('gn', ['gen', out, '--args=' + args]);
30
+ run('autoninja', ['-C', out, 'chrome', 'content_browsertests']);
31
+ }
32
+ const tests = path.join(src, out, windows ? 'content_browsertests.exe' : 'content_browsertests');
33
+ run(tests, ['--gtest_filter=SyntheticMouseEventTest.OpenBrowserInputGuard']);
34
+ const engine = path.join(src, out, windows ? 'chrome.exe' : process.platform === 'darwin'
35
+ ? 'Chromium.app/Contents/MacOS/Chromium' : 'chrome');
36
+ if (!existsSync(engine)) throw Error('Chromium build did not produce ' + engine);
37
+ console.log('Dev engine for OPEN_BROWSER_DEV_CHROMIUM:', engine);
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ const [profile, ...args] = process.argv.slice(2);
3
+ if (!['dev', 'stable'].includes(profile)) throw new Error('usage: build-profile.mjs <dev|stable> [build arguments]');
4
+ process.env.OPEN_BROWSER_BUILD_PROFILE = profile;
5
+ process.argv = [process.argv[0], process.argv[1], ...args];
6
+ await import('./build.mjs');
package/desktop/build.mjs CHANGED
@@ -1,3 +1,11 @@
1
+ const profileIndex = process.argv.findIndex(value => value === '--profile');
2
+ if (profileIndex >= 0) {
3
+ const profile = process.argv[profileIndex + 1];
4
+ if (!['dev', 'stable'].includes(profile)) throw new Error('--profile must be dev or stable');
5
+ process.env.OPEN_BROWSER_BUILD_PROFILE = profile;
6
+ }
7
+ const archIndex = process.argv.findIndex(value => value === '--arch');
8
+ if (archIndex >= 0) process.env.OPEN_BROWSER_TARGET_ARCH = process.argv[archIndex + 1];
1
9
  if (process.platform === 'darwin') {
2
10
  await import('./build-macos.mjs');
3
11
  } else {
@@ -0,0 +1,12 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>com.apple.security.cs.allow-jit</key>
6
+ <true/>
7
+ <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
8
+ <true/>
9
+ <key>com.apple.security.cs.disable-library-validation</key>
10
+ <true/>
11
+ </dict>
12
+ </plist>
@@ -0,0 +1,189 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { access, mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { signingIdentity } from './sign.mjs';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ const root = fileURLToPath(new URL('../', import.meta.url));
9
+ const defaultApp = path.join(root, 'dist', 'open-browser.app');
10
+
11
+ function usage() {
12
+ console.log(`用法:node desktop/notarize-macos.mjs [app-path] [--zip zip-path] [--dmg dmg-path]
13
+
14
+ 提交并公证 macOS 应用,固化票据后生成可上传的 GitHub ZIP 和可选 DMG。
15
+ 凭据优先使用 OPEN_BROWSER_NOTARY_PROFILE,其次使用 App Store Connect API Key,
16
+ 最后使用 Apple ID 加应用专用密码。凭据只从环境变量或本机钥匙串读取。`);
17
+ }
18
+
19
+ function parseArgs(argv) {
20
+ let app = process.env.OPEN_BROWSER_APP_PATH || defaultApp;
21
+ let zip = process.env.OPEN_BROWSER_NOTARY_ZIP;
22
+ let dmg = process.env.OPEN_BROWSER_NOTARY_DMG;
23
+ for (let index = 0; index < argv.length; index += 1) {
24
+ const value = argv[index];
25
+ if (value === '--help' || value === '-h') return { help: true };
26
+ if (value === '--zip') {
27
+ zip = argv[++index];
28
+ if (!zip) throw new Error('--zip 需要文件路径。');
29
+ continue;
30
+ }
31
+ if (value === '--dmg') {
32
+ dmg = argv[++index];
33
+ if (!dmg) throw new Error('--dmg 需要文件路径。');
34
+ continue;
35
+ }
36
+ if (value.startsWith('--')) throw new Error('未知参数:' + value);
37
+ if (app !== defaultApp && app !== process.env.OPEN_BROWSER_APP_PATH)
38
+ throw new Error('只能指定一个应用路径。');
39
+ app = value;
40
+ }
41
+ const appArch = app.endsWith('-x64.app') ? 'x64' : app.endsWith('-arm64.app') ? 'arm64' : process.arch;
42
+ if (!zip) zip = path.join(path.dirname(app), `open-browser-macos-${appArch}.zip`);
43
+ return {
44
+ app: path.resolve(app),
45
+ zip: path.resolve(zip),
46
+ dmg: dmg ? path.resolve(dmg) : undefined,
47
+ help: false,
48
+ };
49
+ }
50
+
51
+ function run(command, args, options = {}) {
52
+ return execFileSync(command, args, { stdio: 'inherit', ...options });
53
+ }
54
+
55
+ function commandPath(name, fallback) {
56
+ try {
57
+ return execFileSync('/usr/bin/xcrun', ['--find', name], { encoding: 'utf8' }).trim();
58
+ } catch {
59
+ return fallback;
60
+ }
61
+ }
62
+
63
+ async function requirePath(target, label) {
64
+ try {
65
+ await access(target);
66
+ } catch {
67
+ throw new Error(`${label}不存在:${target}`);
68
+ }
69
+ }
70
+
71
+ function notaryCredentials() {
72
+ const profile = process.env.OPEN_BROWSER_NOTARY_PROFILE;
73
+ const key = process.env.OPEN_BROWSER_NOTARY_KEY || process.env.APPLE_API_KEY_PATH;
74
+ const keyId = process.env.OPEN_BROWSER_NOTARY_KEY_ID || process.env.APPLE_API_KEY;
75
+ const issuer = process.env.OPEN_BROWSER_NOTARY_ISSUER || process.env.APPLE_API_ISSUER;
76
+ const appleId = process.env.OPEN_BROWSER_NOTARY_APPLE_ID || process.env.APPLE_ID;
77
+ const teamId = process.env.OPEN_BROWSER_NOTARY_TEAM_ID || process.env.APPLE_TEAM_ID;
78
+ const password = process.env.OPEN_BROWSER_NOTARY_PASSWORD || process.env.APPLE_PASSWORD;
79
+
80
+ const apiKeyFields = [key, keyId, issuer].filter(Boolean).length;
81
+ const hasApiKey = Boolean(key || keyId || issuer);
82
+ const hasAppleId = Boolean(appleId || password);
83
+ if (profile && (hasApiKey || hasAppleId || teamId))
84
+ throw new Error('OPEN_BROWSER_NOTARY_PROFILE 不能和其他凭据模式同时设置。');
85
+ if (hasApiKey && hasAppleId)
86
+ throw new Error('API Key 和 Apple ID 公证凭据不能混用。');
87
+ if (profile) return ['--keychain-profile', profile];
88
+ if (hasApiKey) {
89
+ if (!key || !keyId) throw new Error('API Key 模式需要 OPEN_BROWSER_NOTARY_KEY 和 OPEN_BROWSER_NOTARY_KEY_ID。');
90
+ if (!issuer && apiKeyFields === 3) throw new Error('团队 API Key 模式需要 OPEN_BROWSER_NOTARY_ISSUER。');
91
+ const args = ['--key', key, '--key-id', keyId];
92
+ if (issuer) args.push('--issuer', issuer);
93
+ return args;
94
+ }
95
+ if (!appleId && !teamId && !password) {
96
+ throw new Error('缺少公证凭据。优先设置 OPEN_BROWSER_NOTARY_PROFILE,或提供 API Key,' +
97
+ '或设置 OPEN_BROWSER_NOTARY_APPLE_ID、OPEN_BROWSER_NOTARY_TEAM_ID 和应用专用密码。');
98
+ }
99
+ if (!appleId || !teamId) throw new Error('Apple ID 模式需要 OPEN_BROWSER_NOTARY_APPLE_ID 和 OPEN_BROWSER_NOTARY_TEAM_ID。');
100
+ let resolvedPassword = password;
101
+ if (!resolvedPassword) {
102
+ const service = process.env.OPEN_BROWSER_NOTARY_PASSWORD_SERVICE || 'open-browser-notary';
103
+ try {
104
+ resolvedPassword = execFileSync('/usr/bin/security', [
105
+ 'find-generic-password', '-a', appleId, '-s', service, '-w'
106
+ ], { encoding: 'utf8' }).trim();
107
+ } catch {
108
+ throw new Error(`未找到 Apple ID 应用专用密码。请将密码保存到钥匙串服务 ${service},或设置 OPEN_BROWSER_NOTARY_PASSWORD。`);
109
+ }
110
+ }
111
+ if (!resolvedPassword) throw new Error('Apple ID 应用专用密码为空。');
112
+ return ['--apple-id', appleId, '--team-id', teamId, '--password', resolvedPassword];
113
+ }
114
+
115
+ async function sha256(file) {
116
+ return createHash('sha256').update(await readFile(file)).digest('hex');
117
+ }
118
+
119
+ async function main() {
120
+ const parsed = parseArgs(process.argv.slice(2));
121
+ if (parsed.help) {
122
+ usage();
123
+ return;
124
+ }
125
+ if (process.platform !== 'darwin') throw new Error('macOS 公证只能在 macOS 构建机执行。');
126
+ await requirePath(parsed.app, '应用');
127
+ if (!parsed.app.endsWith('.app')) throw new Error('公证输入必须是 .app 应用包。');
128
+ await requirePath('/usr/bin/codesign', 'codesign');
129
+ await requirePath('/usr/bin/xcrun', 'xcrun');
130
+
131
+ const notarytool = commandPath('notarytool', '/usr/bin/xcrun');
132
+ const stapler = commandPath('stapler', '/usr/bin/xcrun');
133
+ const spctl = commandPath('spctl', '/usr/sbin/spctl');
134
+ run('/usr/bin/codesign', ['--verify', '--strict', '--deep', '--verbose=2', parsed.app]);
135
+
136
+ run('/usr/bin/ditto', ['-c', '-k', '--keepParent', '--sequesterRsrc', parsed.app, parsed.zip]);
137
+ const credentials = notaryCredentials();
138
+ function submitAndStaple(archive, target) {
139
+ const prefix = notarytool === '/usr/bin/xcrun' ? ['notarytool'] : [];
140
+ const args = [...prefix, 'submit', archive, '--wait', '--output-format', 'json', ...credentials];
141
+ if (process.env.OPEN_BROWSER_NOTARY_S3_ACCELERATION === '0') args.push('--no-s3-acceleration');
142
+ let result;
143
+ try {
144
+ result = JSON.parse(execFileSync(notarytool, args, { encoding: 'utf8', stdio:['ignore','pipe','pipe'] }));
145
+ } catch {
146
+ throw new Error('Apple 公证提交失败:' + path.basename(archive));
147
+ }
148
+ console.log(path.basename(archive), result.id, result.status);
149
+ if (result.status !== 'Accepted') throw new Error('Apple 未接受这次公证提交。');
150
+ const staplePrefix = stapler === '/usr/bin/xcrun' ? ['stapler'] : [];
151
+ run(stapler, [...staplePrefix, 'staple', target]);
152
+ run(stapler, [...staplePrefix, 'validate', target]);
153
+ }
154
+ submitAndStaple(parsed.zip, parsed.app);
155
+ run(spctl, ['--assess', '--type', 'execute', '--verbose=4', parsed.app]);
156
+
157
+ // The first archive is the notarization input. Recreate it after stapling so
158
+ // the GitHub download contains the ticket and passes offline Gatekeeper checks.
159
+ run('/usr/bin/ditto', ['-c', '-k', '--keepParent', '--sequesterRsrc', parsed.app, parsed.zip]);
160
+ const digest = await sha256(parsed.zip);
161
+ await writeFile(parsed.zip + '.sha256', `${digest} ${path.basename(parsed.zip)}\n`);
162
+ if (parsed.dmg) {
163
+ const staging = await mkdtemp(path.join(root, 'dist', '.open-browser-notary-dmg-'));
164
+ const volume = path.join(staging, `open-browser ${path.basename(parsed.app, '.app')}`);
165
+ try {
166
+ await mkdir(volume, { recursive: true });
167
+ run('/usr/bin/ditto', [parsed.app, path.join(volume, path.basename(parsed.app))]);
168
+ run('/bin/ln', ['-s', '/Applications', path.join(volume, 'Applications')]);
169
+ run('/usr/bin/hdiutil', [
170
+ 'create', '-volname', `open-browser ${path.basename(parsed.app, '.app')}`,
171
+ '-srcfolder', volume, '-ov', '-format', 'UDZO', parsed.dmg,
172
+ ]);
173
+ run('/usr/bin/codesign', ['--sign', signingIdentity(), '--timestamp', parsed.dmg]);
174
+ submitAndStaple(parsed.dmg, parsed.dmg);
175
+ run(spctl, ['--assess', '--type', 'open', '--context', 'context:primary-signature', '--verbose=4', parsed.dmg]);
176
+ const dmgDigest = await sha256(parsed.dmg);
177
+ await writeFile(parsed.dmg + '.sha256', `${dmgDigest} ${path.basename(parsed.dmg)}\n`);
178
+ console.log(`${parsed.dmg}\nSHA-256 ${dmgDigest}`);
179
+ } finally {
180
+ await rm(staging, { recursive: true, force: true });
181
+ }
182
+ }
183
+ console.log(`${parsed.zip}\nSHA-256 ${digest}`);
184
+ }
185
+
186
+ main().catch(error => {
187
+ console.error(error instanceof Error ? error.message : error);
188
+ process.exitCode = 1;
189
+ });