@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,129 @@
1
+ """Snapshot non-ignored source and verify it against local desktop archives."""
2
+ import argparse
3
+ import gzip
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import subprocess
8
+ import tarfile
9
+ import tempfile
10
+ from pathlib import Path
11
+ from zipfile import ZipFile
12
+
13
+ root = Path(__file__).resolve().parents[1]
14
+ dist = root / 'dist'
15
+ version = json.loads((root / 'package.json').read_text())['version']
16
+ snapshot_name = 'open-browser-source-' + version
17
+ snapshot = dist / (snapshot_name + '.tar.gz')
18
+
19
+
20
+ def digest(file):
21
+ checksum = hashlib.sha256()
22
+ for part in iter(lambda: file.read(1024 * 1024), b''):
23
+ checksum.update(part)
24
+ return checksum.hexdigest()
25
+
26
+
27
+ def source_files():
28
+ names = subprocess.check_output(
29
+ ['git', 'ls-files', '--cached', '--others', '--exclude-standard', '-z'], cwd=root
30
+ ).split(b'\0')
31
+ return sorted({os.fsdecode(name) for name in names if name and (root / os.fsdecode(name)).is_file()})
32
+
33
+
34
+ def create_snapshot():
35
+ dist.mkdir(exist_ok=True)
36
+ files = source_files()
37
+ with tempfile.NamedTemporaryFile(dir=dist, delete=False) as raw:
38
+ temp = Path(raw.name)
39
+ try:
40
+ with gzip.GzipFile(filename='', fileobj=raw, mode='wb', mtime=0) as gz:
41
+ with tarfile.open(fileobj=gz, mode='w|', format=tarfile.PAX_FORMAT) as tar:
42
+ for name in files:
43
+ file = root / name
44
+ if file.is_symlink():
45
+ raise ValueError('Review symlink for source snapshot: ' + name)
46
+ info = tarfile.TarInfo(snapshot_name + '/' + name)
47
+ info.mode = 0o755 if os.access(file, os.X_OK) else 0o644
48
+ info.size = file.stat().st_size
49
+ with file.open('rb') as content:
50
+ tar.addfile(info, content)
51
+ raw.close()
52
+ os.replace(temp, snapshot)
53
+ finally:
54
+ temp.unlink(missing_ok=True)
55
+ with snapshot.open('rb') as file:
56
+ checksum = digest(file)
57
+ Path(str(snapshot) + '.sha256').write_text(checksum + ' ' + snapshot.name + '\n')
58
+ print(f'{snapshot.name} {checksum} ({len(files)} source files)')
59
+
60
+
61
+ def packaged_paths(source, mac):
62
+ common = {name: 'app/' + name for name in source if
63
+ (('/' not in name and name.endswith('.mjs')) or name.startswith(('browser-extension/', 'studio/', 'skills/')))
64
+ and not name.endswith('.test.mjs')}
65
+ for name in ('package.json', 'package-lock.json'):
66
+ common[name] = 'app/' + name
67
+ common['Docs/THIRD-PARTY-NOTICES.md'] = 'app/THIRD-PARTY-NOTICES.md'
68
+ if mac:
69
+ common = {name: 'open-browser.app/Contents/Resources/' + location for name, location in common.items()}
70
+ common['desktop/icons/open-browser.icns'] = 'open-browser.app/Contents/Resources/open-browser.icns'
71
+ common['desktop/Info.plist'] = 'open-browser.app/Contents/Info.plist'
72
+ else:
73
+ common['Docs/跨平台试用与发行.md'] = 'README.md'
74
+ common['desktop/smoke-portable.mjs'] = 'verify.mjs'
75
+ return common
76
+
77
+
78
+ def verify():
79
+ with tarfile.open(snapshot) as tar:
80
+ source = {entry.name.removeprefix(snapshot_name + '/'): digest(tar.extractfile(entry))
81
+ for entry in tar if entry.isfile()}
82
+ if set(source) != set(source_files()):
83
+ raise ValueError('Working tree file list has changed since snapshot')
84
+ for name, checksum in source.items():
85
+ with (root / name).open('rb') as file:
86
+ if digest(file) != checksum:
87
+ raise ValueError('Working tree differs from snapshot: ' + name)
88
+ sums = {}
89
+ for name in (snapshot.name, 'open-browser-macos-arm64.zip', 'open-browser-win32-x64.zip', 'open-browser-linux-x64.tar.gz'):
90
+ artifact = dist / name
91
+ with artifact.open('rb') as file:
92
+ sums[name] = digest(file)
93
+ if Path(str(artifact) + '.sha256').read_text().split()[0] != sums[name]:
94
+ raise ValueError('Archive checksum mismatch: ' + name)
95
+ if artifact == snapshot:
96
+ continue
97
+ mac = name.startswith('open-browser-macos-')
98
+ paths = packaged_paths(source, mac)
99
+ if 'win32' in name:
100
+ paths.update({'desktop/icons/open-browser.ico': 'open-browser.ico',
101
+ 'desktop/create-shortcut.ps1': 'create-shortcut.ps1'})
102
+ elif 'linux' in name:
103
+ paths['desktop/install-menu-entry.mjs'] = 'install-menu-entry.mjs'
104
+ prefix = '' if mac else name.split('.')[0] + '/'
105
+ with ZipFile(artifact) if name.endswith('.zip') else tarfile.open(artifact, mode='r|gz') as archive:
106
+ # Read compressed tar in a single linear pass.
107
+ entries = archive.namelist() if isinstance(archive, ZipFile) else archive
108
+ by_entry = {prefix + entry: name for name, entry in paths.items()}
109
+ for entry in entries:
110
+ path = entry if isinstance(entry, str) else entry.name
111
+ if path not in by_entry:
112
+ continue
113
+ src = by_entry.pop(path)
114
+ with archive.open(path) if isinstance(archive, ZipFile) else archive.extractfile(entry) as data:
115
+ if digest(data) != source[src]:
116
+ raise ValueError(f'{artifact.name}: {src} differs')
117
+ if by_entry:
118
+ raise ValueError(f'{artifact.name}: missing {list(by_entry)}')
119
+ print(f'{name}: {len(paths)} packaged source files matched the snapshot')
120
+ (dist / 'SHA256SUMS').write_text(''.join(f'{value} {key}\n' for key, value in sums.items()))
121
+
122
+
123
+ if __name__ == '__main__':
124
+ parser = argparse.ArgumentParser(description=__doc__)
125
+ parser.add_argument('command', choices=['snapshot', 'verify'])
126
+ if parser.parse_args().command == 'snapshot':
127
+ create_snapshot()
128
+ else:
129
+ verify()
@@ -0,0 +1,95 @@
1
+ #!/usr/bin/env python3
2
+ """Apply the macOS Keychain service-name source patch to a staged CfT 159 app.
3
+
4
+ The matching upstream source edit is in patches/chromium-macos-keychain-service.patch.
5
+ Digests are from the official chrome-for-testing-public/159.0.8154.6/mac-{arm64,x64}
6
+ archives. The input and output digests cover the complete, pre-codesign framework.
7
+ """
8
+ import argparse
9
+ import hashlib
10
+ import mmap
11
+ import os
12
+ from pathlib import Path
13
+ import plistlib
14
+ import stat
15
+ import struct
16
+ from tempfile import NamedTemporaryFile
17
+
18
+ VERSION = '159.0.8154.6'
19
+ REVISION = '98a2592026af8d673b9fa83b626ac68bdf4ae78a'
20
+ FRAMEWORK = 'Google Chrome for Testing Framework'
21
+ SOURCE = b'Chromium Safe Storage'
22
+ PRODUCT = b'open-browser Keychain'
23
+ # Mach CPU type -> offset in __TEXT,__const, input hash, branded hash.
24
+ RELEASE = {
25
+ 0x0100000C: (225772584, 'a0a2e8854ce90268f5d9b32210cf53fc0709f4b798b3c3a96964ba3ebce4bc4b',
26
+ 'c9a9477055677cf37ee0872c6c0077a562dfefb7f5315832c1f022aa75a7bc33'),
27
+ 0x01000007: (246160880, 'cdc858707b7fbf3144528c2c2ee4bd7a2d9a107b7964b6069faf84ac0b0ed894',
28
+ '1ac99579ee9459c917d8463140dc3f44cde520e4357bf058584f51b783675ef9'),
29
+ }
30
+
31
+
32
+ def in_readonly_constants(data, offset):
33
+ command = 32 # mach_header_64
34
+ for _ in range(struct.unpack_from('<I', data, 16)[0]):
35
+ kind, length = struct.unpack_from('<II', data, command)
36
+ if kind == 0x19: # LC_SEGMENT_64
37
+ protections, count = struct.unpack_from('<II', data, command + 60)
38
+ for n in range(count):
39
+ section = command + 72 + 80 * n
40
+ name, segment, _, size, start = struct.unpack_from('<16s16sQQI', data, section)
41
+ flags, = struct.unpack_from('<I', data, section + 64)
42
+ if (name.rstrip(b'\0') == b'__const' and segment.rstrip(b'\0') == b'__TEXT'
43
+ and not protections & 2 and not flags & 0x80000400
44
+ and start <= offset and offset + len(SOURCE) < start + size):
45
+ return True
46
+ command += length
47
+ return False
48
+
49
+
50
+ def brand(bundle):
51
+ bundle = bundle.resolve(strict=True)
52
+ with (bundle / 'Contents/Info.plist').open('rb') as stream:
53
+ info = plistlib.load(stream)
54
+ if (bundle.name != 'open-browser.app' or info.get('CFBundleIdentifier') != 'local.open-browser.chromium'
55
+ or info.get('CFBundleShortVersionString') != VERSION
56
+ or info.get('SCMRevision', '').split('-')[0] != REVISION):
57
+ raise ValueError('Expected the staged open-browser Chromium bundle at the pinned upstream revision')
58
+ binary = bundle / 'Contents/Frameworks' / (FRAMEWORK + '.framework') / 'Versions' / VERSION / FRAMEWORK
59
+ if binary.resolve(strict=True) != binary:
60
+ raise ValueError('Expected a regular framework binary inside the staged bundle')
61
+ with binary.open('rb') as source, mmap.mmap(source.fileno(), 0, access=mmap.ACCESS_COPY) as data:
62
+ magic, cpu = struct.unpack_from('<II', data)
63
+ if magic != 0xFEEDFACF or cpu not in RELEASE:
64
+ raise ValueError('Unrecognized framework architecture')
65
+ offset, before, after = RELEASE[cpu]
66
+ digest = hashlib.sha256(data).hexdigest()
67
+ if digest == after:
68
+ return
69
+ if digest != before:
70
+ raise ValueError('Framework SHA-256 differs from the reviewed official release')
71
+ if (len(SOURCE) != len(PRODUCT) or not in_readonly_constants(data, offset)
72
+ or data[offset-1:offset+len(SOURCE)+10] != b'\0' + SOURCE + b'\0Chromium\0'
73
+ or data.find(SOURCE) != offset or data.find(SOURCE, offset + 1) != -1):
74
+ raise ValueError('Unexpected keychain service constant layout')
75
+ data[offset:offset+len(SOURCE)] = PRODUCT
76
+ if hashlib.sha256(data).hexdigest() != after:
77
+ raise ValueError('Unexpected branded framework digest')
78
+ # Publish a fully verified copy atomically, even for hardlinked input.
79
+ with NamedTemporaryFile(dir=binary.parent, prefix='.open-browser-keychain-', delete=False) as temp:
80
+ staged = Path(temp.name)
81
+ try:
82
+ temp.write(data)
83
+ temp.flush()
84
+ os.fchmod(temp.fileno(), stat.S_IMODE(os.fstat(source.fileno()).st_mode))
85
+ os.fsync(temp.fileno())
86
+ os.replace(staged, binary)
87
+ finally:
88
+ if staged.exists():
89
+ staged.unlink()
90
+
91
+
92
+ if __name__ == '__main__':
93
+ parser = argparse.ArgumentParser(description=__doc__)
94
+ parser.add_argument('bundle', type=Path)
95
+ brand(parser.parse_args().bundle)
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env python3
2
+ """Brand the macOS CFT 159 UI resources in a staged app before signing."""
3
+ import argparse
4
+ from pathlib import Path
5
+ import re
6
+ import struct
7
+
8
+
9
+ HEADER = struct.Struct('<IB3xHH')
10
+ ENTRY = struct.Struct('<HI')
11
+ ALIAS = struct.Struct('<HH')
12
+ # Reviewed against the pinned engine's English locale. 961 and 963 are
13
+ # aliased window-title templates. Engine notices and credits have other IDs.
14
+ DISPLAY = {
15
+ 103: 'Google Chrome for Testing',
16
+ 302: 'About &Google Chrome for Testing',
17
+ 801: 'About Chrome for Testing',
18
+ 802: 'Get help with Chrome for Testing',
19
+ 925: 'Chrome for Testing',
20
+ 961: '$1 - Google Chrome for Testing',
21
+ 963: '$1 - Google Chrome for Testing',
22
+ 1153: 'Customize Chrome for Testing',
23
+ }
24
+ PRODUCT = re.compile(
25
+ r'(?:Google\s+)?Chrome(?:\s+for\s+Testing|\s+ya\s+(?:Majaribio|Kujaribia)'
26
+ r'|\s+para testes|\s+för testning|\s+na Pang-test|\s+для тестирования'
27
+ r'|-toetsweergawe|\s+สำหรับการทดสอบ|ን?\s+ለሙከራ)', re.IGNORECASE)
28
+
29
+
30
+ def resources(data):
31
+ version, encoding, count, aliases = HEADER.unpack_from(data)
32
+ if (version, encoding) != (5, 1):
33
+ raise ValueError('Expected a Chromium v5 UTF-8 locale pack')
34
+ start = HEADER.size
35
+ entries = list(ENTRY.iter_unpack(data[start:start + (count + 1) * ENTRY.size]))
36
+ index = start + (count + 1) * ENTRY.size
37
+ if entries[-1] != (0, len(data)) or entries[0][1] != index + aliases * ALIAS.size:
38
+ raise ValueError('Unexpected Chromium resource offsets')
39
+ result = {key: data[offset:entries[i + 1][1]]
40
+ for i, (key, offset) in enumerate(entries[:-1])}
41
+ for key, target in ALIAS.iter_unpack(data[index:entries[0][1]]):
42
+ result[key] = result[entries[target][0]]
43
+ return result
44
+
45
+
46
+ def pack(values):
47
+ entries, aliases, indices = [], [], {}
48
+ for key, value in sorted(values.items()):
49
+ if value in indices:
50
+ aliases.append(ALIAS.pack(key, indices[value]))
51
+ else:
52
+ indices[value] = len(entries)
53
+ entries.append((key, value))
54
+ offset = HEADER.size + (len(entries) + 1) * ENTRY.size + len(aliases) * ALIAS.size
55
+ table = []
56
+ for key, value in entries:
57
+ table.append(ENTRY.pack(key, offset))
58
+ offset += len(value)
59
+ return b''.join([HEADER.pack(5, 1, len(entries), len(aliases)), *table,
60
+ ENTRY.pack(0, offset), *aliases, *(value for _, value in entries)])
61
+
62
+
63
+ def brand(app):
64
+ locations = sorted(app.glob('Contents/Frameworks/*.framework/Versions/[0-9]*/Resources/en.lproj/locale.pak'))
65
+ if not locations:
66
+ raise ValueError(f'Missing Chromium English resources under {app}')
67
+ changed = 0
68
+ for english in locations:
69
+ en = resources(english.read_bytes())
70
+ for key, expected in DISPLAY.items():
71
+ if en.get(key, b'').decode() not in (expected, PRODUCT.sub('open-browser', expected)):
72
+ raise ValueError(f'Chromium English resource {key} changed; review this engine version')
73
+ for path in sorted(english.parent.parent.glob('*.lproj/locale.pak')):
74
+ values = resources(path.read_bytes())
75
+ modified = False
76
+ for key in DISPLAY.keys() & values.keys():
77
+ original = values[key].decode()
78
+ replacement = PRODUCT.sub('open-browser', original)
79
+ if 'open-browser' not in replacement:
80
+ raise ValueError(f'Unrecognized product spelling in {path.parent.name} resource {key}')
81
+ if replacement != original:
82
+ values[key] = replacement.encode()
83
+ modified = True
84
+ if modified:
85
+ path.write_bytes(pack(values))
86
+ changed += 1
87
+ return changed
88
+
89
+
90
+ if __name__ == '__main__':
91
+ parser = argparse.ArgumentParser(description=__doc__)
92
+ parser.add_argument('app', type=Path, help='Path to the staged Chromium .app')
93
+ print(f'Branded {brand(parser.parse_args().app)} Chromium locale packs')
@@ -0,0 +1,24 @@
1
+ """Update the staged browser and its notification helpers before code signing."""
2
+ from pathlib import Path
3
+ import os
4
+ import plistlib
5
+ import shutil
6
+ import sys
7
+
8
+ app = Path(sys.argv[1])
9
+ root = Path(__file__).resolve().parents[1]
10
+ for contents in [app / 'Contents', *app.glob('Contents/Frameworks/*.framework/Versions/[0-9]*/Helpers/*.app/Contents')]:
11
+ path = contents / 'Info.plist'
12
+ with path.open('rb') as file:
13
+ info = plistlib.load(file)
14
+ if 'CFBundleIconFile' in info:
15
+ shutil.copyfile(root / 'desktop/icons/open-browser.icns', contents / 'Resources' / info['CFBundleIconFile'])
16
+ # On macOS 26 IconServices prefers this CFT icon-only catalog even
17
+ # without CFBundleIconName, masking the replacement ICNS.
18
+ (contents / 'Resources/Assets.car').unlink(missing_ok=True)
19
+ info.pop('CFBundleIconName', None)
20
+ path.write_bytes(plistlib.dumps(info))
21
+ # ditto preserves the upstream bundle date, which IconServices caches.
22
+ os.utime(contents.parent, None)
23
+ for image in app.glob('Contents/Frameworks/*.framework/Versions/[0-9]*/Resources/product_logo_32.png'):
24
+ shutil.copyfile(root / 'browser-extension/icons/open-browser-32.png', image)
@@ -0,0 +1,48 @@
1
+ import { cp, mkdtemp, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
2
+ import { createHash } from 'node:crypto';
3
+ import path from 'node:path';
4
+ import { Data, Resource, NtExecutable, NtExecutableResource } from 'resedit';
5
+
6
+ // The pinned CFT build carries the Explorer icon in the executable and the
7
+ // native window icon in chrome.dll. Both files in this distribution are unsigned.
8
+ const iconFile = new URL('./icons/open-browser.ico', import.meta.url);
9
+
10
+ export async function brandWindowsIcons(engine) {
11
+ const ico = await readFile(iconFile);
12
+ const images = Data.IconFile.from(ico).icons.map(frame => frame.data);
13
+ for (const [name, id] of [['chrome.exe', 'IDR_MAINFRAME'], ['chrome.dll', 101]]) {
14
+ const file = path.join(engine, name);
15
+ const pe = NtExecutable.from(await readFile(file));
16
+ const resources = NtExecutableResource.from(pe);
17
+ if (!resources.entries.some(e => e.type === 14 && e.id === id && e.lang === 1033))
18
+ throw new Error('Missing Chromium application icon in ' + name);
19
+ Resource.IconGroupEntry.replaceIconsForResource(resources.entries, id, 1033, images);
20
+ resources.outputResource(pe);
21
+ await writeFile(file, Buffer.from(pe.generate()));
22
+ }
23
+ }
24
+
25
+ // Publish a branded sibling of Playwright's cache without modifying its downloads.
26
+ // Only fully written directories are visible to concurrent or repeat installs.
27
+ export async function installWindowsIcons(executable) {
28
+ const source = path.dirname(executable);
29
+ const digest = createHash('sha256').update(await readFile(iconFile)).digest('hex').slice(0, 16);
30
+ const target = source + '-open-browser-' + digest;
31
+ const binary = path.join(target, path.basename(executable));
32
+ async function installed() {
33
+ try { return (await stat(binary)).isFile(); }
34
+ catch (e) { if (e.code === 'ENOENT') return false; throw e; }
35
+ }
36
+ if (await installed()) return binary;
37
+ const staging = await mkdtemp(source + '-open-browser-build-');
38
+ try {
39
+ await cp(source, staging, { recursive: true });
40
+ await brandWindowsIcons(staging);
41
+ try { await rename(staging, target); }
42
+ catch (e) {
43
+ if (!['EEXIST', 'ENOTEMPTY', 'EPERM', 'EACCES'].includes(e.code) ||
44
+ !(await installed())) throw e;
45
+ }
46
+ return binary;
47
+ } finally { await rm(staging, { force: true, recursive: true }); }
48
+ }
@@ -0,0 +1,96 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { copyFile, mkdir, mkdtemp, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { copyApplication } from './package-assets.mjs';
7
+ import { engineExecutable } from '../runtime.mjs';
8
+ import { signBundle, signingIdentity, verifyUpgrade } from './sign.mjs';
9
+
10
+ const root = fileURLToPath(new URL('../', import.meta.url));
11
+ const sums = {
12
+ arm64: 'e7131995759b61a0170b646010d2ad35a5d37b4cb0d471f3e8317eac6f742f3d',
13
+ x64: 'c53383238206b9ae4db23c5d8a63645e2e753bec8ab51a49cc81939aa64e9422',
14
+ };
15
+ if (process.platform !== 'darwin' || !sums[process.arch]) throw new Error('macOS arm64 or x64 required');
16
+ const identity = signingIdentity();
17
+ await engineExecutable();
18
+ const out = path.join(root, 'dist');
19
+ const cache = path.join(root, '.open-browser', 'build-cache');
20
+ await mkdir(out, { recursive: true });
21
+ await mkdir(cache, { recursive: true });
22
+ const filename = 'node-v22.23.5-darwin-' + process.arch + '.tar.gz';
23
+ const archive = path.join(cache, filename);
24
+ const checksum = async p => createHash('sha256').update(await readFile(p)).digest('hex');
25
+ if ((await checksum(archive).catch(() => '')) !== sums[process.arch]) {
26
+ const temp = archive + '.' + process.pid;
27
+ execFileSync('curl', ['--fail', '--location', '--retry', '2', '--output', temp,
28
+ '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');
30
+ await rename(temp, archive);
31
+ }
32
+
33
+ const staging = await mkdtemp(path.join(out, '.open-browser-build-'));
34
+ const bundle = path.join(staging, 'open-browser.app');
35
+ const contents = path.join(bundle, 'Contents');
36
+ const resources = path.join(contents, 'Resources');
37
+ const app = path.join(resources, 'app');
38
+ const copyTree = (a, b) => execFileSync('ditto', ['--noqtn', '--noextattr', a, b]);
39
+ try {
40
+ await mkdir(path.join(contents, 'MacOS'), { recursive: true });
41
+ await mkdir(app, { recursive: true });
42
+ const node = path.join(resources, 'node');
43
+ await mkdir(node);
44
+ const prefix = filename.slice(0, -7);
45
+ execFileSync('tar', ['-xzf', archive, '-C', node, '--strip-components', '1',
46
+ prefix + '/bin/node', prefix + '/LICENSE']);
47
+ await copyFile(path.join(root, 'desktop/Info.plist'), path.join(contents, 'Info.plist'));
48
+ execFileSync('xcrun', ['clang', '-fobjc-arc', '-O2', '-framework', 'AppKit', '-framework', 'CoreGraphics',
49
+ path.join(root, 'desktop/Launcher.m'), path.join(root, 'desktop/OBControlBar.m'),
50
+ '-o', path.join(contents, 'MacOS/open-browser')], { stdio: 'inherit' });
51
+ await copyFile(path.join(root, 'desktop/icons/open-browser.icns'), path.join(resources, 'open-browser.icns'));
52
+ await copyApplication(app);
53
+ const engine = path.join(app, '.open-browser', 'engine');
54
+ await mkdir(engine, { recursive: true });
55
+ const sourceEngine = path.join(root, '.open-browser', 'engine');
56
+ 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));
59
+ // Brand the packaged browser, which owns the visible window and Dock entry.
60
+ const originalBinary = path.join(engine, executable);
61
+ const originalBundle = path.resolve(path.dirname(originalBinary), '../..');
62
+ const browserBundle = path.join(path.dirname(originalBundle), 'open-browser.app');
63
+ await rename(originalBundle, browserBundle);
64
+ const binary = path.join(browserBundle, 'Contents/MacOS/open-browser');
65
+ await rename(path.join(path.dirname(binary), path.basename(originalBinary)), binary);
66
+ const plist = path.join(browserBundle, 'Contents/Info.plist');
67
+ for (const key of ['CFBundleName', 'CFBundleDisplayName', 'CFBundleExecutable'])
68
+ execFileSync('plutil', ['-replace', key, '-string', 'open-browser', plist]);
69
+ execFileSync('plutil', ['-replace', 'CFBundleIdentifier', '-string', 'local.open-browser.chromium', plist]);
70
+ execFileSync('python3', [path.join(root, 'desktop/brand-locales.py'), browserBundle], { stdio: 'inherit' });
71
+ execFileSync('python3', [path.join(root, 'desktop/brand-keychain.py'), browserBundle], { stdio: 'inherit' });
72
+ execFileSync('python3', [path.join(root, 'desktop/brand-macos-icons.py'), browserBundle], { stdio: 'inherit' });
73
+ signBundle(browserBundle, identity, true);
74
+ 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';
76
+ await writeFile(path.join(engine, manifest), JSON.stringify({ executable: path.relative(engine, binary), profileVersion: 2 }) + '\n');
77
+ signBundle(bundle, identity);
78
+ const target = path.join(out, 'open-browser.app');
79
+ const priorEngine = path.join(target, 'Contents/Resources/app/.open-browser/engine');
80
+ const entries = await readdir(priorEngine).catch(e => { if (e.code === 'ENOENT') return []; throw e; });
81
+ for (const entry of entries.filter(name => /^engine-.*-darwin-(arm64|x64)\.json$/.test(name))) {
82
+ const prior = JSON.parse(await readFile(path.join(priorEngine, entry), 'utf8'));
83
+ if (prior.profileVersion !== 2) continue;
84
+ const previousBrowser = path.resolve(priorEngine, prior.executable, '../../..');
85
+ if (!previousBrowser.startsWith(priorEngine + path.sep) || path.basename(previousBrowser) !== 'open-browser.app')
86
+ throw new Error('旧版本 Chromium 路径无效。');
87
+ verifyUpgrade(previousBrowser, browserBundle);
88
+ }
89
+ const old = path.join(staging, 'previous.app');
90
+ try { await rename(target, old); } catch (e) { if (e.code !== 'ENOENT') throw e; }
91
+ try { await rename(bundle, target); }
92
+ catch (e) { await rename(old, target).catch(() => {}); throw e; }
93
+ console.log(target);
94
+ } finally {
95
+ await rm(staging, { recursive: true, force: true });
96
+ }
@@ -0,0 +1,95 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { createReadStream } from 'node:fs';
4
+ import { chmod, copyFile, mkdir, mkdtemp, readFile, rename, rm, writeFile } from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { copyApplication, root } from './package-assets.mjs';
7
+
8
+ const platforms = {
9
+ 'linux-x64': { chrome: 'linux64', executable: 'chrome', node: 'linux-x64.tar.xz',
10
+ nodeHash: 'cdeb8670a0c81f51b4dc4ac61919f9b1ad917b304bf8221eb939570663d240f8',
11
+ chromeHash: '370601106c1b5619aae5f06f7a3fdc60836486135934779461e2a208d777f596' },
12
+ 'win32-x64': { chrome: 'win64', executable: 'chrome.exe', node: 'win-x64.zip',
13
+ nodeHash: '4a191082e9706866830379d577d2cc8a50c776fcd9436a8d061b063ed0d9a0e3',
14
+ chromeHash: '3e2514fddb71f6727e2079369e03a6a4e105adcb28f05a6bfd875b782bddc431' },
15
+ };
16
+ const platform = process.argv[2] || process.platform + '-' + process.arch;
17
+ const spec = platforms[platform];
18
+ if (!spec) throw new Error('Use node desktop/build-portable.mjs linux-x64 or win32-x64');
19
+ const chromeVersion = '159.0.8154.6';
20
+ const nodeVersion = '22.23.5';
21
+ const info = JSON.parse(await readFile(path.join(root, 'node_modules/playwright-core/browsers.json'), 'utf8')).browsers.find(b => b.name === 'chromium');
22
+ if (info.browserVersion !== chromeVersion) throw new Error('Refresh the pinned Chrome archive version and SHA-256.');
23
+ const playwright = JSON.parse(await readFile(path.join(root, 'node_modules/playwright-core/package.json'), 'utf8'));
24
+ const cache = path.join(root, '.open-browser', 'build-cache', 'portable');
25
+ const output = path.join(root, 'dist');
26
+ await mkdir(cache, { recursive: true });
27
+ await mkdir(output, { recursive: true });
28
+ const python = process.platform === 'win32' ? 'python' : 'python3';
29
+ const pythonArchive = (...args) => execFileSync(python, [path.join(root, 'desktop/portable-archive.py'), ...args], { stdio: 'inherit' });
30
+
31
+ async function digest(file) {
32
+ const hash = createHash('sha256');
33
+ for await (const chunk of createReadStream(file)) hash.update(chunk);
34
+ return hash.digest('hex');
35
+ }
36
+ async function cached(name, url, sum) {
37
+ const file = path.join(cache, name);
38
+ if (await digest(file).catch(() => '') === sum) return file;
39
+ const tmp = file + '.' + randomUUID();
40
+ try {
41
+ execFileSync(process.platform === 'win32' ? 'curl.exe' : 'curl', ['--fail', '--location', '--retry', '2', '--output', tmp, url], { stdio: 'inherit' });
42
+ if (await digest(tmp) !== sum) throw new Error('SHA-256 mismatch: ' + name);
43
+ await rename(tmp, file);
44
+ return file;
45
+ } finally { await rm(tmp, { force: true }); }
46
+ }
47
+ const nodeName = 'node-v' + nodeVersion + '-' + spec.node;
48
+ const nodeArchive = await cached(nodeName, 'https://nodejs.org/dist/v' + nodeVersion + '/' + nodeName, spec.nodeHash);
49
+ const chromeArchive = await cached('chrome-' + spec.chrome + '-' + chromeVersion + '.zip',
50
+ 'https://cdn.playwright.dev/builds/cft/' + chromeVersion + '/' + spec.chrome + '/chrome-' + spec.chrome + '.zip', spec.chromeHash);
51
+ const staging = await mkdtemp(path.join(output, '.open-browser-portable-'));
52
+ const folder = 'open-browser-' + platform;
53
+ const bundle = path.join(staging, folder), app = path.join(bundle, 'app'), node = path.join(bundle, 'node');
54
+ const windows = platform === 'win32-x64';
55
+ try {
56
+ await copyApplication(app);
57
+ await mkdir(node);
58
+ if (windows) {
59
+ pythonArchive('extract', nodeArchive, staging);
60
+ const upstream = path.join(staging, 'node-v' + nodeVersion + '-win-x64');
61
+ for (const file of ['node.exe', 'LICENSE']) await copyFile(path.join(upstream, file), path.join(node, file));
62
+ } else {
63
+ const prefix = 'node-v' + nodeVersion + '-linux-x64';
64
+ execFileSync('tar', ['-xf', nodeArchive, '-C', node, '--strip-components', '1', prefix + '/bin/node', prefix + '/LICENSE']);
65
+ }
66
+ const engine = path.join(app, '.open-browser', 'engine');
67
+ const build = 'chromium-' + info.revision;
68
+ await mkdir(path.join(engine, build), { recursive: true });
69
+ pythonArchive('extract', chromeArchive, path.join(engine, build));
70
+ const executable = [build, 'chrome-' + spec.chrome, spec.executable].join('/');
71
+ await writeFile(path.join(engine, 'engine-' + playwright.version + '-' + platform + '.json'), JSON.stringify({ executable }) + '\n');
72
+ if (windows) {
73
+ const { brandWindowsIcons } = await import('./brand-windows-icons.mjs');
74
+ await brandWindowsIcons(path.dirname(path.join(engine, executable)));
75
+ await copyFile(path.join(root, 'desktop/icons/open-browser.ico'), path.join(bundle, 'open-browser.ico'));
76
+ await copyFile(path.join(root, 'desktop/create-shortcut.ps1'), path.join(bundle, 'create-shortcut.ps1'));
77
+ await writeFile(path.join(bundle, 'open-browser.cmd'), '@echo off\r\n"%~dp0node\\node.exe" "%~dp0app\\service.mjs" --chromium %*\r\n');
78
+ } else {
79
+ await copyFile(path.join(root, 'desktop/install-menu-entry.mjs'), path.join(bundle, 'install-menu-entry.mjs'));
80
+ await copyFile(path.join(app, 'browser-extension/icons/open-browser-48.png'),
81
+ path.join(engine, build, 'chrome-' + spec.chrome, 'product_logo_48.png'));
82
+ const launcher = path.join(bundle, 'open-browser');
83
+ await writeFile(launcher, '#!/bin/sh\nset -eu\nbase=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)\nexec "$base/node/bin/node" "$base/app/service.mjs" --chromium "$@"\n');
84
+ await chmod(launcher, 0o755);
85
+ }
86
+ await copyFile(path.join(root, 'Docs/跨平台试用与发行.md'), path.join(bundle, 'README.md'));
87
+ await copyFile(path.join(root, 'desktop/smoke-portable.mjs'), path.join(bundle, 'verify.mjs'));
88
+ const name = folder + (windows ? '.zip' : '.tar.gz'), archive = path.join(staging, name);
89
+ if (windows) pythonArchive('pack', bundle, archive);
90
+ else execFileSync('tar', ['--no-xattrs', '-czf', archive, '-C', staging, folder], { env: { ...process.env, COPYFILE_DISABLE: '1' } });
91
+ const hash = await digest(archive);
92
+ await rename(archive, path.join(output, name));
93
+ await writeFile(path.join(output, name + '.sha256'), hash + ' ' + name + '\n');
94
+ console.log(path.join(output, name), hash);
95
+ } finally { await rm(staging, { recursive: true, force: true }); }
@@ -0,0 +1,5 @@
1
+ if (process.platform === 'darwin') {
2
+ await import('./build-macos.mjs');
3
+ } else {
4
+ await import('./build-portable.mjs');
5
+ }
@@ -0,0 +1,9 @@
1
+ $ErrorActionPreference = 'Stop'
2
+ $desktop = [Environment]::GetFolderPath('DesktopDirectory')
3
+ $link = (New-Object -ComObject WScript.Shell).CreateShortcut((Join-Path $desktop 'open-browser.lnk'))
4
+ $link.TargetPath = Join-Path $PSScriptRoot 'node\node.exe'
5
+ $link.Arguments = '"' + (Join-Path $PSScriptRoot 'app\service.mjs') + '" --chromium'
6
+ $link.WorkingDirectory = $PSScriptRoot
7
+ $link.IconLocation = (Join-Path $PSScriptRoot 'open-browser.ico') + ',0'
8
+ $link.WindowStyle = 7
9
+ $link.Save()
@@ -0,0 +1,39 @@
1
+ """Regenerate checked-in desktop and extension icons on macOS from the README artwork."""
2
+ from pathlib import Path
3
+ from tempfile import TemporaryDirectory
4
+ import struct
5
+ import subprocess
6
+
7
+ root = Path(__file__).resolve().parents[1]
8
+ source = root / 'Docs/assets/open-browser-logo.png'
9
+ desktop = root / 'desktop/icons'
10
+ extension = root / 'browser-extension/icons'
11
+ for directory in (desktop, extension):
12
+ directory.mkdir(exist_ok=True)
13
+
14
+
15
+ def resize(image, size, destination):
16
+ subprocess.run(['sips', '-Z', str(size), str(image), '--out', str(destination)],
17
+ check=True, stdout=subprocess.DEVNULL)
18
+
19
+
20
+ with TemporaryDirectory() as temp:
21
+ iconset = Path(temp) / 'open-browser.iconset'
22
+ iconset.mkdir()
23
+ for size in (16, 32, 128, 256, 512):
24
+ for scale, suffix in ((1, ''), (2, '@2x')):
25
+ resize(source, size * scale, iconset / f'icon_{size}x{size}{suffix}.png')
26
+ subprocess.run(['iconutil', '-c', 'icns', str(iconset), '-o', str(desktop / 'open-browser.icns')], check=True)
27
+
28
+ sizes = (16, 32, 48, 128, 256)
29
+ entries, images = [], []
30
+ offset = 6 + 16 * len(sizes)
31
+ for size in sizes:
32
+ png = (extension if size <= 128 else Path(temp)) / f'open-browser-{size}.png'
33
+ resize(source, size, png)
34
+ data = png.read_bytes()
35
+ entries.append(struct.pack('<BBBBHHII', size % 256, size % 256, 0, 0, 1, 32, len(data), offset))
36
+ images.append(data)
37
+ offset += len(data)
38
+ (desktop / 'open-browser.ico').write_bytes(struct.pack('<HHH', 0, 1, len(sizes)) + b''.join(entries + images))
39
+ resize(root / 'Docs/assets/open-browser-wordmark.png', 576, extension / 'open-browser-wordmark.png')
Binary file
Binary file