@adrouter/agent 0.1.0-beta.2

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.
package/LICENSE ADDED
@@ -0,0 +1,182 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the
13
+ copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other
16
+ entities that control, are controlled by, or are under common control with
17
+ that entity. For the purposes of this definition, "control" means (i) the
18
+ power, direct or indirect, to cause the direction or management of such
19
+ entity, whether by contract or otherwise, or (ii) ownership of fifty percent
20
+ (50%) or more of the outstanding shares, or (iii) beneficial ownership of
21
+ such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
24
+ permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation source, and
28
+ configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical transformation
31
+ or translation of a Source form, including but not limited to compiled object
32
+ code, generated documentation, and conversions to other media types.
33
+
34
+ "Work" shall mean the work of authorship, whether in Source or Object form,
35
+ made available under the License, as indicated by a copyright notice that is
36
+ included in or attached to the work.
37
+
38
+ "Derivative Works" shall mean any work, whether in Source or Object form,
39
+ that is based on (or derived from) the Work and for which the editorial
40
+ revisions, annotations, elaborations, or other modifications represent, as a
41
+ whole, an original work of authorship. For the purposes of this License,
42
+ Derivative Works shall not include works that remain separable from, or merely
43
+ link (or bind by name) to the interfaces of, the Work and Derivative Works
44
+ thereof.
45
+
46
+ "Contribution" shall mean any work of authorship, including the original
47
+ version of the Work and any modifications or additions to that Work or
48
+ Derivative Works thereof, that is intentionally submitted to Licensor for
49
+ inclusion in the Work by the copyright owner or by an individual or Legal
50
+ Entity authorized to submit on behalf of the copyright owner. For the purposes
51
+ of this definition, "submitted" means any form of electronic, verbal, or
52
+ written communication sent to the Licensor or its representatives, including
53
+ but not limited to communication on electronic mailing lists, source code
54
+ control systems, and issue tracking systems that are managed by, or on behalf
55
+ of, the Licensor for the purpose of discussing and improving the Work, but
56
+ excluding communication that is conspicuously marked or otherwise designated
57
+ in writing by the copyright owner as "Not a Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any individual or Legal Entity on
60
+ behalf of whom a Contribution has been received by Licensor and subsequently
61
+ incorporated within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
64
+ License, each Contributor hereby grants to You a perpetual, worldwide,
65
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
66
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
67
+ sublicense, and distribute the Work and such Derivative Works in Source or
68
+ Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of this
71
+ License, each Contributor hereby grants to You a perpetual, worldwide,
72
+ non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this
73
+ section) patent license to make, have made, use, offer to sell, sell, import,
74
+ and otherwise transfer the Work, where such license applies only to those
75
+ patent claims licensable by such Contributor that are necessarily infringed by
76
+ their Contribution(s) alone or by combination of their Contribution(s) with
77
+ the Work to which such Contribution(s) was submitted. If You institute patent
78
+ litigation against any entity (including a cross-claim or counterclaim in a
79
+ lawsuit) alleging that the Work or a Contribution incorporated within the Work
80
+ constitutes direct or contributory patent infringement, then any patent
81
+ licenses granted to You under this License for that Work shall terminate as of
82
+ the date such litigation is filed.
83
+
84
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
85
+ Derivative Works thereof in any medium, with or without modifications, and in
86
+ Source or Object form, provided that You meet the following conditions:
87
+
88
+ (a) You must give any other recipients of the Work or Derivative Works a copy
89
+ of this License; and
90
+
91
+ (b) You must cause any modified files to carry prominent notices stating that
92
+ You changed the files; and
93
+
94
+ (c) You must retain, in the Source form of any Derivative Works that You
95
+ distribute, all copyright, patent, trademark, and attribution notices from the
96
+ Source form of the Work, excluding those notices that do not pertain to any
97
+ part of the Derivative Works; and
98
+
99
+ (d) If the Work includes a "NOTICE" text file as part of its distribution,
100
+ then any Derivative Works that You distribute must include a readable copy of
101
+ the attribution notices contained within such NOTICE file, excluding those
102
+ notices that do not pertain to any part of the Derivative Works, in at least
103
+ one of the following places: within a NOTICE text file distributed as part of
104
+ the Derivative Works; within the Source form or documentation, if provided
105
+ along with the Derivative Works; or, within a display generated by the
106
+ Derivative Works, if and wherever such third-party notices normally appear.
107
+ The contents of the NOTICE file are for informational purposes only and do not
108
+ modify the License. You may add Your own attribution notices within Derivative
109
+ Works that You distribute, alongside or as an addendum to the NOTICE text from
110
+ the Work, provided that such additional attribution notices cannot be
111
+ construed as modifying the License.
112
+
113
+ You may add Your own copyright statement to Your modifications and may provide
114
+ additional or different license terms and conditions for use, reproduction,
115
+ or distribution of Your modifications, or for any such Derivative Works as a
116
+ whole, provided Your use, reproduction, and distribution of the Work otherwise
117
+ complies with the conditions stated in this License.
118
+
119
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
120
+ Contribution intentionally submitted for inclusion in the Work by You to the
121
+ Licensor shall be under the terms and conditions of this License, without any
122
+ additional terms or conditions. Notwithstanding the above, nothing herein
123
+ shall supersede or modify the terms of any separate license agreement you may
124
+ have executed with Licensor regarding such Contributions.
125
+
126
+ 6. Trademarks. This License does not grant permission to use the trade names,
127
+ trademarks, service marks, or product names of the Licensor, except as required
128
+ for reasonable and customary use in describing the origin of the Work and
129
+ reproducing the content of the NOTICE file.
130
+
131
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
132
+ writing, Licensor provides the Work (and each Contributor provides its
133
+ Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
134
+ KIND, either express or implied, including, without limitation, any warranties
135
+ or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
136
+ PARTICULAR PURPOSE. You are solely responsible for determining the
137
+ appropriateness of using or redistributing the Work and assume any risks
138
+ associated with Your exercise of permissions under this License.
139
+
140
+ 8. Limitation of Liability. In no event and under no legal theory, whether in
141
+ tort (including negligence), contract, or otherwise, unless required by
142
+ applicable law (such as deliberate and grossly negligent acts) or agreed to in
143
+ writing, shall any Contributor be liable to You for damages, including any
144
+ direct, indirect, special, incidental, or consequential damages of any
145
+ character arising as a result of this License or out of the use or inability to
146
+ use the Work (including but not limited to damages for loss of goodwill, work
147
+ stoppage, computer failure or malfunction, or any and all other commercial
148
+ damages or losses), even if such Contributor has been advised of the
149
+ possibility of such damages.
150
+
151
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work
152
+ or Derivative Works thereof, You may choose to offer, and charge a fee for,
153
+ acceptance of support, warranty, indemnity, or other liability obligations
154
+ and/or rights consistent with this License. However, in accepting such
155
+ obligations, You may act only on Your own behalf and on Your sole
156
+ responsibility, not on behalf of any other Contributor, and only if You agree
157
+ to indemnify, defend, and hold each Contributor harmless for any liability
158
+ incurred by, or claims asserted against, such Contributor by reason of your
159
+ accepting any such warranty or additional liability.
160
+
161
+ END OF TERMS AND CONDITIONS
162
+
163
+ APPENDIX: How to apply the Apache License to your work.
164
+
165
+ To apply the Apache License to your work, attach the following boilerplate
166
+ notice, with the fields enclosed by brackets "[]" replaced with your own
167
+ identifying information. (Don't include the brackets!) The text should be
168
+ enclosed in the appropriate comment syntax for the file format. We also
169
+ recommend that a file or class name and description of purpose be included on
170
+ the same "printed page" as the copyright notice for easier identification
171
+ within third-party archives.
172
+
173
+ Copyright 2026 AdRouter Agent contributors
174
+
175
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
176
+ this file except in compliance with the License. You may obtain a copy of the
177
+ License at http://www.apache.org/licenses/LICENSE-2.0.
178
+
179
+ Unless required by applicable law or agreed to in writing, software distributed
180
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
181
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
182
+ specific language governing permissions and limitations under the License.
package/README.md ADDED
@@ -0,0 +1,35 @@
1
+ # `@adrouter/agent`
2
+
3
+ This dependency-free package installs and launches the credential-free,
4
+ ad-hoc-signed universal macOS application from the matching
5
+ [AdRouter Agent GitHub release](https://github.com/adrouter/adrouterAgent/releases).
6
+ The desktop application is not duplicated in the npm tarball.
7
+
8
+ ```bash
9
+ npm install --global @adrouter/agent@beta
10
+ adrouter-agent doctor --json
11
+ adrouter-agent
12
+ ```
13
+
14
+ The launcher supports macOS 12 or newer, Apple Silicon and Intel, and Node.js
15
+ 22.19.0 or newer. It accepts no alternate download URL or checksum. Downloads
16
+ are bounded, checked against the release manifest embedded in this package,
17
+ and installed as the real application at `~/Applications/AdRouter Agent.app`
18
+ after archive, bundle identity, universal architecture, and ad-hoc `codesign`
19
+ integrity checks.
20
+
21
+ This beta is not Developer ID signed or notarized. If macOS blocks the first
22
+ launch, open **System Settings → Privacy & Security** and choose **Open Anyway**.
23
+ The launcher never removes quarantine metadata or changes Gatekeeper settings.
24
+
25
+ Commands:
26
+
27
+ - `adrouter-agent` or `adrouter-agent launch`: install if needed, then launch.
28
+ - `adrouter-agent install`: install and verify without launching.
29
+ - `adrouter-agent doctor --json`: report platform, installation receipt,
30
+ bundle integrity, ad-hoc signature, and diagnostic Gatekeeper status.
31
+ - `adrouter-agent --version`: print the package/release version without a
32
+ network request.
33
+
34
+ See the [repository security policy](https://github.com/adrouter/adrouterAgent/blob/main/SECURITY.md)
35
+ before reporting a vulnerability.
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { runCli } from '../lib/cli.mjs';
4
+
5
+ runCli(process.argv.slice(2)).catch((error) => {
6
+ const message = error instanceof Error ? error.message : String(error);
7
+ process.stderr.write(`adrouter-agent: ${message}\n`);
8
+ process.exitCode = 1;
9
+ });
package/lib/cli.mjs ADDED
@@ -0,0 +1,50 @@
1
+ import { inspectInstallation, install, launch } from './installer.mjs';
2
+ import { readManifest } from './manifest.mjs';
3
+
4
+ const USAGE = `Usage: adrouter-agent [launch|install|doctor [--json]|--version]
5
+
6
+ launch Install if needed, then launch (default)
7
+ install Download, verify, and cache without launching
8
+ doctor Report installation and security status
9
+ --version Print the release version without downloading
10
+ `;
11
+
12
+ export async function runCli(args, io = process) {
13
+ const manifest = await readManifest();
14
+ if (args.includes('--version') || args.includes('-v')) {
15
+ io.stdout.write(`${manifest.releaseVersion}\n`);
16
+ return;
17
+ }
18
+ if (args.includes('--help') || args.includes('-h')) {
19
+ io.stdout.write(USAGE);
20
+ return;
21
+ }
22
+ const positional = args.filter((argument) => !argument.startsWith('-'));
23
+ const command = positional[0] ?? 'launch';
24
+ const unknownOptions = args.filter(
25
+ (argument) => argument.startsWith('-') && argument !== '--json'
26
+ );
27
+ if (unknownOptions.length > 0 || positional.length > 1) throw new Error(USAGE.trim());
28
+
29
+ if (command === 'doctor') {
30
+ const report = await inspectInstallation(manifest);
31
+ if (args.includes('--json')) io.stdout.write(`${JSON.stringify(report)}\n`);
32
+ else {
33
+ for (const [key, value] of Object.entries(report)) io.stdout.write(`${key}: ${value}\n`);
34
+ }
35
+ return;
36
+ }
37
+ if (args.includes('--json')) throw new Error('--json is supported only by doctor.');
38
+ if (command === 'install') {
39
+ const appPath = await install(manifest);
40
+ io.stdout.write(`Installed and verified ${appPath}\n`);
41
+ const report = await inspectInstallation(manifest);
42
+ if (report.warning) io.stderr.write(`Warning: ${report.warning}\n`);
43
+ return;
44
+ }
45
+ if (command !== 'launch') throw new Error(`Unknown command ${command}.\n${USAGE}`);
46
+ const appPath = await install(manifest);
47
+ const report = await inspectInstallation(manifest);
48
+ if (report.warning) io.stderr.write(`Warning: ${report.warning}\n`);
49
+ await launch(appPath);
50
+ }
@@ -0,0 +1,437 @@
1
+ import { execFile, spawn } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import {
4
+ access,
5
+ lstat,
6
+ mkdir,
7
+ mkdtemp,
8
+ open,
9
+ readdir,
10
+ readFile,
11
+ realpath,
12
+ rename,
13
+ rm,
14
+ } from 'node:fs/promises';
15
+ import { homedir } from 'node:os';
16
+ import { basename, join, sep } from 'node:path';
17
+ import { promisify } from 'node:util';
18
+
19
+ const execFileAsync = promisify(execFile);
20
+ const APP_NAME = 'AdRouter Agent.app';
21
+ const EXECUTABLE_NAME = 'AdRouter Agent';
22
+ const RECEIPT_OWNER = '@adrouter/agent';
23
+ const MAX_DOWNLOAD_BYTES = 512 * 1024 * 1024;
24
+ const MAX_REDIRECTS = 5;
25
+ const GATEKEEPER_WARNING =
26
+ 'This credential-free beta is not Developer ID signed or notarized. If macOS blocks it, open System Settings > Privacy & Security and choose Open Anyway.';
27
+ const ALLOWED_HOSTS = new Set([
28
+ 'github.com',
29
+ 'objects.githubusercontent.com',
30
+ 'release-assets.githubusercontent.com',
31
+ ]);
32
+
33
+ export function assertSupportedPlatform(platform = process.platform, arch = process.arch) {
34
+ if (platform !== 'darwin') {
35
+ throw new Error(`Unsupported platform ${platform}; AdRouter Agent requires macOS 12 or newer.`);
36
+ }
37
+ if (arch !== 'arm64' && arch !== 'x64') {
38
+ throw new Error(`Unsupported macOS architecture ${arch}; expected arm64 or x64.`);
39
+ }
40
+ }
41
+
42
+ export function assertSupportedMacOsVersion(version) {
43
+ const major = Number.parseInt(String(version).split('.')[0] ?? '', 10);
44
+ if (!Number.isSafeInteger(major) || major < 12) {
45
+ throw new Error(`Unsupported macOS version ${version}; macOS 12 or newer is required.`);
46
+ }
47
+ }
48
+
49
+ export function assertNonRoot(uid = process.getuid?.()) {
50
+ if (uid === 0) {
51
+ throw new Error('Do not run adrouter-agent with sudo; install it as the logged-in macOS user.');
52
+ }
53
+ }
54
+
55
+ export function assertAllowedDownloadUrl(input) {
56
+ const url = input instanceof URL ? input : new URL(input);
57
+ if (url.protocol !== 'https:' || !ALLOWED_HOSTS.has(url.hostname)) {
58
+ throw new Error(`Refusing non-canonical download URL: ${url.origin}`);
59
+ }
60
+ if (url.username || url.password || url.port) {
61
+ throw new Error('Refusing a download URL containing credentials or a non-default port.');
62
+ }
63
+ return url;
64
+ }
65
+
66
+ export function assertSafeArchiveEntries(entries) {
67
+ if (!Array.isArray(entries) || entries.length === 0) {
68
+ throw new Error('The release ZIP is empty.');
69
+ }
70
+ for (const entry of entries) {
71
+ if (
72
+ typeof entry !== 'string' ||
73
+ entry.includes('\0') ||
74
+ entry.startsWith('/') ||
75
+ entry.startsWith('\\') ||
76
+ entry.split(/[\\/]/).includes('..')
77
+ ) {
78
+ throw new Error(`Unsafe ZIP entry: ${JSON.stringify(entry)}`);
79
+ }
80
+ if (entry !== APP_NAME && !entry.startsWith(`${APP_NAME}/`)) {
81
+ throw new Error(`Unexpected ZIP layout entry: ${entry}`);
82
+ }
83
+ }
84
+ }
85
+
86
+ export function releasePaths(_manifest, homeDirectory = homedir()) {
87
+ const applicationsDirectory = join(homeDirectory, 'Applications');
88
+ const supportDirectory = join(
89
+ homeDirectory,
90
+ 'Library',
91
+ 'Application Support',
92
+ 'adrouter-agent-launcher'
93
+ );
94
+ return {
95
+ applicationsDirectory,
96
+ supportDirectory,
97
+ appPath: join(applicationsDirectory, APP_NAME),
98
+ receiptPath: join(supportDirectory, 'receipt.json'),
99
+ };
100
+ }
101
+
102
+ async function exists(path) {
103
+ try {
104
+ await access(path);
105
+ return true;
106
+ } catch {
107
+ return false;
108
+ }
109
+ }
110
+
111
+ async function execute(file, args, options = {}) {
112
+ return execFileAsync(file, args, {
113
+ encoding: 'utf8',
114
+ maxBuffer: 16 * 1024 * 1024,
115
+ ...options,
116
+ });
117
+ }
118
+
119
+ async function plistValue(appPath, key, executeImpl) {
120
+ const plist = join(appPath, 'Contents', 'Info.plist');
121
+ const { stdout } = await executeImpl('/usr/libexec/PlistBuddy', ['-c', `Print :${key}`, plist]);
122
+ return stdout.trim();
123
+ }
124
+
125
+ async function verifyApp(appPath, manifest, executeImpl = execute) {
126
+ await executeImpl('/usr/bin/codesign', ['--verify', '--deep', '--strict', appPath]);
127
+ const signatureResult = await executeImpl('/usr/bin/codesign', ['-dv', '--verbose=4', appPath]);
128
+ const signatureDetails = `${signatureResult.stdout ?? ''}${signatureResult.stderr ?? ''}`;
129
+ if (
130
+ !signatureDetails.includes('Signature=adhoc') ||
131
+ !signatureDetails.includes('TeamIdentifier=not set')
132
+ ) {
133
+ throw new Error('The application is not the expected credential-free ad-hoc build.');
134
+ }
135
+
136
+ const bundleIdentifier = await plistValue(appPath, 'CFBundleIdentifier', executeImpl);
137
+ const shortVersion = await plistValue(appPath, 'CFBundleShortVersionString', executeImpl);
138
+ const buildVersion = await plistValue(appPath, 'CFBundleVersion', executeImpl);
139
+ if (bundleIdentifier !== manifest.bundleIdentifier) {
140
+ throw new Error('The installed app bundle identifier does not match the release manifest.');
141
+ }
142
+ if (shortVersion !== manifest.bundleShortVersion) {
143
+ throw new Error('The installed app short bundle version does not match the release manifest.');
144
+ }
145
+ if (buildVersion !== manifest.bundleVersion) {
146
+ throw new Error('The installed app build version does not match the release manifest.');
147
+ }
148
+
149
+ const executable = join(appPath, 'Contents', 'MacOS', EXECUTABLE_NAME);
150
+ const { stdout: architectures } = await executeImpl('/usr/bin/lipo', ['-archs', executable]);
151
+ if (!architectures.includes('arm64') || !architectures.includes('x86_64')) {
152
+ throw new Error('The installed app is not a universal arm64+x86_64 build.');
153
+ }
154
+ }
155
+
156
+ async function assessGatekeeper(appPath, executeImpl = execute) {
157
+ try {
158
+ await executeImpl('/usr/sbin/spctl', ['--assess', '--type', 'execute', appPath]);
159
+ return 'accepted';
160
+ } catch (error) {
161
+ if (error && typeof error === 'object' && error.code === 'ENOENT') return 'unavailable';
162
+ return 'rejected';
163
+ }
164
+ }
165
+
166
+ async function verifyExtractedTree(root, appPath) {
167
+ const canonicalRoot = `${await realpath(root)}${sep}`;
168
+ async function visit(path) {
169
+ const stat = await lstat(path);
170
+ if (stat.isSymbolicLink()) throw new Error(`Release archive contains a symbolic link: ${path}`);
171
+ const canonical = await realpath(path);
172
+ if (canonical !== canonicalRoot.slice(0, -1) && !canonical.startsWith(canonicalRoot)) {
173
+ throw new Error('Release archive escaped its extraction directory.');
174
+ }
175
+ if (!stat.isDirectory()) return;
176
+ for (const entry of await readdir(path)) await visit(join(path, entry));
177
+ }
178
+ const topLevel = await readdir(root);
179
+ if (topLevel.length !== 1 || topLevel[0] !== APP_NAME) {
180
+ throw new Error('Release archive must contain exactly AdRouter Agent.app.');
181
+ }
182
+ await visit(appPath);
183
+ }
184
+
185
+ async function download(manifest, destination, fetchImpl = fetch) {
186
+ let current = assertAllowedDownloadUrl(manifest.assetUrl);
187
+ for (let redirect = 0; redirect <= MAX_REDIRECTS; redirect += 1) {
188
+ const response = await fetchImpl(current, {
189
+ redirect: 'manual',
190
+ headers: { 'user-agent': `@adrouter/agent/${manifest.releaseVersion}` },
191
+ signal: AbortSignal.timeout(5 * 60 * 1000),
192
+ });
193
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
194
+ const location = response.headers.get('location');
195
+ if (!location) throw new Error('Download redirect did not include a Location header.');
196
+ current = assertAllowedDownloadUrl(new URL(location, current));
197
+ continue;
198
+ }
199
+ if (!response.ok || !response.body) {
200
+ throw new Error(`Release download failed with HTTP ${response.status}.`);
201
+ }
202
+ const contentLength = response.headers.get('content-length');
203
+ const declaredSize = contentLength === null ? null : Number(contentLength);
204
+ if (
205
+ declaredSize !== null &&
206
+ (!Number.isSafeInteger(declaredSize) || declaredSize < 0 || declaredSize > MAX_DOWNLOAD_BYTES)
207
+ ) {
208
+ throw new Error('Release download exceeds the maximum permitted size.');
209
+ }
210
+ const handle = await open(destination, 'wx', 0o600);
211
+ let received = 0;
212
+ const digest = createHash('sha256');
213
+ const reader = response.body.getReader();
214
+ try {
215
+ while (true) {
216
+ const { done, value: chunk } = await reader.read();
217
+ if (done) break;
218
+ received += chunk.byteLength;
219
+ if (received > MAX_DOWNLOAD_BYTES) {
220
+ throw new Error('Release download exceeds the maximum permitted size.');
221
+ }
222
+ digest.update(chunk);
223
+ await handle.write(chunk);
224
+ }
225
+ } finally {
226
+ reader.releaseLock();
227
+ await handle.close();
228
+ }
229
+ if (declaredSize !== null && received !== declaredSize) {
230
+ throw new Error('Release download ended before the declared content length.');
231
+ }
232
+ const actual = digest.digest('hex');
233
+ if (actual !== manifest.sha256) throw new Error('Release ZIP checksum verification failed.');
234
+ return { bytes: received, sha256: actual, finalUrl: current.href };
235
+ }
236
+ throw new Error('Release download exceeded the redirect limit.');
237
+ }
238
+
239
+ async function archiveEntries(zipPath, executeImpl = execute) {
240
+ const { stdout } = await executeImpl('/usr/bin/unzip', ['-Z1', zipPath]);
241
+ const entries = stdout.split('\n').filter(Boolean);
242
+ assertSafeArchiveEntries(entries);
243
+ const { stdout: listing } = await executeImpl('/usr/bin/zipinfo', ['-l', zipPath]);
244
+ if (listing.split('\n').some((line) => /^l[rwx-]{9}\s/.test(line))) {
245
+ throw new Error('Release ZIP contains symbolic links.');
246
+ }
247
+ return entries;
248
+ }
249
+
250
+ async function readReceipt(receiptPath, appPath) {
251
+ try {
252
+ const receipt = JSON.parse(await readFile(receiptPath, 'utf8'));
253
+ const owned =
254
+ receipt.schema === 2 &&
255
+ receipt.owner === RECEIPT_OWNER &&
256
+ receipt.applicationPath === appPath;
257
+ return { receipt, owned };
258
+ } catch {
259
+ return { receipt: null, owned: false };
260
+ }
261
+ }
262
+
263
+ function receiptMatchesManifest(receipt, manifest) {
264
+ return (
265
+ receipt?.releaseVersion === manifest.releaseVersion &&
266
+ receipt?.sha256 === manifest.sha256 &&
267
+ receipt?.releaseTag === manifest.releaseTag
268
+ );
269
+ }
270
+
271
+ async function appIsRunning(appPath, executeImpl = execute) {
272
+ const executable = join(appPath, 'Contents', 'MacOS', EXECUTABLE_NAME);
273
+ const { stdout } = await executeImpl('/bin/ps', ['-axo', 'command=']);
274
+ return stdout
275
+ .split('\n')
276
+ .map((line) => line.trim())
277
+ .some((line) => line === executable || line.startsWith(`${executable} `));
278
+ }
279
+
280
+ export async function inspectInstallation(manifest, options = {}) {
281
+ const paths = releasePaths(manifest, options.homeDirectory);
282
+ const report = {
283
+ schema: 2,
284
+ distributionMode: manifest.distributionMode,
285
+ platform: options.platform ?? process.platform,
286
+ architecture: options.arch ?? process.arch,
287
+ macOsVersion: null,
288
+ supported: false,
289
+ releaseVersion: manifest.releaseVersion,
290
+ releaseTag: manifest.releaseTag,
291
+ applicationPath: paths.appPath,
292
+ installed: false,
293
+ receiptMatches: false,
294
+ bundleIntegrity: false,
295
+ signatureType: 'missing',
296
+ gatekeeperAssessment: 'unavailable',
297
+ warning: GATEKEEPER_WARNING,
298
+ };
299
+ try {
300
+ assertSupportedPlatform(report.platform, report.architecture);
301
+ const versionResult =
302
+ options.macOsVersion === undefined
303
+ ? await (options.executeImpl ?? execute)('/usr/bin/sw_vers', ['-productVersion'])
304
+ : { stdout: options.macOsVersion };
305
+ report.macOsVersion = versionResult.stdout.trim();
306
+ assertSupportedMacOsVersion(report.macOsVersion);
307
+ report.supported = true;
308
+ } catch (error) {
309
+ report.error = error instanceof Error ? error.message : String(error);
310
+ return report;
311
+ }
312
+
313
+ report.installed = await exists(paths.appPath);
314
+ if (!report.installed) return report;
315
+ const receiptStatus = await readReceipt(paths.receiptPath, paths.appPath);
316
+ report.receiptMatches =
317
+ receiptStatus.owned && receiptMatchesManifest(receiptStatus.receipt, manifest);
318
+ try {
319
+ await verifyApp(paths.appPath, manifest, options.executeImpl);
320
+ report.bundleIntegrity = true;
321
+ report.signatureType = 'adhoc';
322
+ } catch (error) {
323
+ report.signatureType = 'invalid';
324
+ report.error = error instanceof Error ? error.message : String(error);
325
+ }
326
+ report.gatekeeperAssessment = await assessGatekeeper(paths.appPath, options.executeImpl);
327
+ if (report.gatekeeperAssessment === 'accepted') report.warning = null;
328
+ return report;
329
+ }
330
+
331
+ export async function install(manifest, options = {}) {
332
+ assertSupportedPlatform(options.platform ?? process.platform, options.arch ?? process.arch);
333
+ assertNonRoot(options.uid ?? process.getuid?.());
334
+ const paths = releasePaths(manifest, options.homeDirectory);
335
+ const executeImpl = options.executeImpl ?? execute;
336
+ const existing = await inspectInstallation(manifest, options);
337
+ if (!existing.supported) {
338
+ throw new Error(existing.error ?? 'This Mac is not supported.');
339
+ }
340
+ if (
341
+ existing.installed &&
342
+ existing.receiptMatches &&
343
+ existing.bundleIntegrity &&
344
+ existing.signatureType === 'adhoc'
345
+ ) {
346
+ return paths.appPath;
347
+ }
348
+
349
+ const receiptStatus = await readReceipt(paths.receiptPath, paths.appPath);
350
+ if (existing.installed && !receiptStatus.owned) {
351
+ throw new Error(
352
+ `${paths.appPath} already exists and is not managed by @adrouter/agent; move or remove it before installing.`
353
+ );
354
+ }
355
+ if (existing.installed && (await appIsRunning(paths.appPath, executeImpl))) {
356
+ throw new Error('Quit AdRouter Agent before installing or updating it.');
357
+ }
358
+
359
+ await mkdir(paths.applicationsDirectory, { recursive: true, mode: 0o755 });
360
+ await mkdir(paths.supportDirectory, { recursive: true, mode: 0o700 });
361
+ const staging = await mkdtemp(join(paths.applicationsDirectory, '.adrouter-agent-staging-'));
362
+ const archive = join(staging, basename(manifest.assetName));
363
+ const extracted = join(staging, 'extracted');
364
+ const stagedApp = join(extracted, APP_NAME);
365
+ const backupPath = join(
366
+ paths.applicationsDirectory,
367
+ `.AdRouter Agent.app.backup-${process.pid}-${Date.now()}`
368
+ );
369
+ let backedUp = false;
370
+ let activated = false;
371
+ try {
372
+ const receipt = await download(manifest, archive, options.fetchImpl);
373
+ await archiveEntries(archive, executeImpl);
374
+ await mkdir(extracted, { mode: 0o700 });
375
+ await executeImpl('/usr/bin/ditto', ['-x', '-k', archive, extracted]);
376
+ await verifyExtractedTree(extracted, stagedApp);
377
+ await verifyApp(stagedApp, manifest, executeImpl);
378
+
379
+ if (existing.installed) {
380
+ await rename(paths.appPath, backupPath);
381
+ backedUp = true;
382
+ }
383
+ await rename(stagedApp, paths.appPath);
384
+ activated = true;
385
+ await (options.writeReceiptImpl ?? writeReceipt)(paths.receiptPath, {
386
+ schema: 2,
387
+ owner: RECEIPT_OWNER,
388
+ distributionMode: manifest.distributionMode,
389
+ releaseVersion: manifest.releaseVersion,
390
+ releaseTag: manifest.releaseTag,
391
+ sha256: receipt.sha256,
392
+ bytes: receipt.bytes,
393
+ finalUrl: receipt.finalUrl,
394
+ applicationPath: paths.appPath,
395
+ installedAt: new Date().toISOString(),
396
+ });
397
+ if (backedUp) await rm(backupPath, { recursive: true, force: true });
398
+ return paths.appPath;
399
+ } catch (error) {
400
+ if (activated) await rm(paths.appPath, { recursive: true, force: true });
401
+ if (backedUp && (await exists(backupPath))) await rename(backupPath, paths.appPath);
402
+ throw error;
403
+ } finally {
404
+ await rm(staging, { recursive: true, force: true });
405
+ }
406
+ }
407
+
408
+ async function writeReceipt(path, receipt) {
409
+ const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;
410
+ try {
411
+ const handle = await open(temporary, 'wx', 0o600);
412
+ try {
413
+ await handle.writeFile(`${JSON.stringify(receipt, null, 2)}\n`, 'utf8');
414
+ } finally {
415
+ await handle.close();
416
+ }
417
+ await rename(temporary, path);
418
+ } catch (error) {
419
+ await rm(temporary, { force: true });
420
+ throw error;
421
+ }
422
+ }
423
+
424
+ export async function launch(appPath, spawnImpl = spawn) {
425
+ await new Promise((resolvePromise, reject) => {
426
+ const child = spawnImpl('/usr/bin/open', [appPath], {
427
+ detached: true,
428
+ stdio: 'ignore',
429
+ });
430
+ child.once('error', reject);
431
+ child.once('exit', (code) => {
432
+ if (code === 0) resolvePromise();
433
+ else reject(new Error(`macOS open failed with exit code ${code}.`));
434
+ });
435
+ child.unref();
436
+ });
437
+ }
@@ -0,0 +1,67 @@
1
+ import { readFile } from 'node:fs/promises';
2
+
3
+ const SHA256_PATTERN = /^[a-f0-9]{64}$/;
4
+ const VERSION_PATTERN = /^\d+\.\d+\.\d+-beta\.\d+$/;
5
+
6
+ export function validateManifest(value) {
7
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
8
+ throw new Error('The embedded release manifest is not an object.');
9
+ }
10
+ const requiredStrings = [
11
+ 'releaseVersion',
12
+ 'releaseTag',
13
+ 'assetName',
14
+ 'assetUrl',
15
+ 'sha256',
16
+ 'repository',
17
+ 'distributionMode',
18
+ 'bundleIdentifier',
19
+ 'bundleShortVersion',
20
+ 'bundleVersion',
21
+ ];
22
+ for (const key of requiredStrings) {
23
+ if (typeof value[key] !== 'string' || value[key].length === 0) {
24
+ throw new Error(`The embedded release manifest has an invalid ${key}.`);
25
+ }
26
+ }
27
+ if (value.schema !== 2) throw new Error('Unsupported release manifest schema.');
28
+ if (value.distributionMode !== 'credential-free-adhoc') {
29
+ throw new Error('The embedded release distribution mode is not supported.');
30
+ }
31
+ if (!VERSION_PATTERN.test(value.releaseVersion)) {
32
+ throw new Error('The embedded release version is not a beta SemVer.');
33
+ }
34
+ if (value.releaseTag !== `v${value.releaseVersion}`) {
35
+ throw new Error('The embedded release tag does not match the version.');
36
+ }
37
+ if (value.repository !== 'adrouter/adrouterAgent') {
38
+ throw new Error('The embedded repository is not canonical.');
39
+ }
40
+ if (value.bundleIdentifier !== 'com.adrouter.agent') {
41
+ throw new Error('The embedded bundle identifier is not canonical.');
42
+ }
43
+ if (value.assetName !== `AdRouter-Agent-${value.releaseVersion}-universal.zip`) {
44
+ throw new Error('The embedded release asset name is not canonical.');
45
+ }
46
+ const expectedUrl =
47
+ `https://github.com/${value.repository}/releases/download/` +
48
+ `${value.releaseTag}/${value.assetName}`;
49
+ if (value.assetUrl !== expectedUrl) {
50
+ throw new Error('The embedded release asset URL is not canonical.');
51
+ }
52
+ if (!SHA256_PATTERN.test(value.sha256)) {
53
+ throw new Error('The embedded release checksum is not a SHA-256 digest.');
54
+ }
55
+ if (!/^\d+\.\d+\.\d+$/.test(value.bundleShortVersion)) {
56
+ throw new Error('The embedded short bundle version is invalid.');
57
+ }
58
+ if (!/^\d+(?:\.\d+){0,2}$/.test(value.bundleVersion)) {
59
+ throw new Error('The embedded numeric bundle version is invalid.');
60
+ }
61
+ return Object.freeze({ ...value });
62
+ }
63
+
64
+ export async function readManifest(url = new URL('../release-manifest.json', import.meta.url)) {
65
+ const text = await readFile(url, 'utf8');
66
+ return validateManifest(JSON.parse(text));
67
+ }
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@adrouter/agent",
3
+ "version": "0.1.0-beta.2",
4
+ "description": "Verified installer and launcher for the AdRouter Agent macOS application.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "bin": {
8
+ "adrouter-agent": "bin/adrouter-agent.mjs"
9
+ },
10
+ "files": [
11
+ "bin/",
12
+ "lib/",
13
+ "LICENSE",
14
+ "README.md",
15
+ "release-manifest.json"
16
+ ],
17
+ "engines": {
18
+ "node": ">=22.19.0"
19
+ },
20
+ "os": [
21
+ "darwin"
22
+ ],
23
+ "cpu": [
24
+ "arm64",
25
+ "x64"
26
+ ],
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/adrouter/adrouterAgent.git",
30
+ "directory": "packages/agent-launcher"
31
+ },
32
+ "bugs": {
33
+ "url": "https://github.com/adrouter/adrouterAgent/issues"
34
+ },
35
+ "homepage": "https://github.com/adrouter/adrouterAgent#readme",
36
+ "publishConfig": {
37
+ "access": "public",
38
+ "provenance": true
39
+ }
40
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "schema": 2,
3
+ "distributionMode": "credential-free-adhoc",
4
+ "releaseVersion": "0.1.0-beta.2",
5
+ "releaseTag": "v0.1.0-beta.2",
6
+ "assetName": "AdRouter-Agent-0.1.0-beta.2-universal.zip",
7
+ "assetUrl": "https://github.com/adrouter/adrouterAgent/releases/download/v0.1.0-beta.2/AdRouter-Agent-0.1.0-beta.2-universal.zip",
8
+ "sha256": "51bc43a700e06ced94ad6e64d281ee7f6f20ae092a3a8b2e6effa39bea52df8a",
9
+ "repository": "adrouter/adrouterAgent",
10
+ "bundleIdentifier": "com.adrouter.agent",
11
+ "bundleShortVersion": "0.1.0",
12
+ "bundleVersion": "10002"
13
+ }