@adrouter/agent 0.1.0-beta.10
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 +182 -0
- package/README.md +34 -0
- package/bin/adrouter-agent.mjs +9 -0
- package/lib/cli.mjs +50 -0
- package/lib/installer.mjs +629 -0
- package/lib/manifest.mjs +153 -0
- package/package.json +42 -0
- package/release-manifest.json +57 -0
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,34 @@
|
|
|
1
|
+
# `@adrouter/agent`
|
|
2
|
+
|
|
3
|
+
This dependency-free package installs and launches the matching AdRouter Agent
|
|
4
|
+
portable application from the canonical GitHub release. The desktop binaries
|
|
5
|
+
are not duplicated in the npm tarball.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install --global @adrouter/agent@beta
|
|
9
|
+
adrouter-agent doctor --json
|
|
10
|
+
adrouter-agent
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Supported targets are macOS 12+ arm64/x64, Ubuntu Desktop 24.04 LTS x64, and
|
|
14
|
+
Windows 11 x64 with Node.js 22.19 or newer. The launcher accepts no alternate
|
|
15
|
+
download URL or checksum. It validates the embedded schema-3 manifest, bounded
|
|
16
|
+
download, SHA-256 digest, archive paths, executable, managed receipt, and
|
|
17
|
+
staged-update rollback before activation.
|
|
18
|
+
|
|
19
|
+
macOS is ad-hoc signed but not notarized. Linux and Windows portable beta
|
|
20
|
+
artifacts are unsigned. Run `adrouter-agent doctor --json` for the platform
|
|
21
|
+
install path, artifact key, verification result, sandbox readiness, and static
|
|
22
|
+
setup guidance. The launcher never disables host security or auto-elevates.
|
|
23
|
+
|
|
24
|
+
Commands:
|
|
25
|
+
|
|
26
|
+
- `adrouter-agent` or `adrouter-agent launch`: install if needed, then launch.
|
|
27
|
+
- `adrouter-agent install`: install and verify without launching.
|
|
28
|
+
- `adrouter-agent doctor --json`: report installation, integrity, and sandbox
|
|
29
|
+
status without credentials.
|
|
30
|
+
- `adrouter-agent --version`: print the package/release version without a
|
|
31
|
+
network request.
|
|
32
|
+
|
|
33
|
+
See the repository's platform-setup guide for Ubuntu dependencies, Windows
|
|
34
|
+
one-time sandbox provisioning, and staging bearer-token onboarding.
|
|
@@ -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, selectArtifact } 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, { artifact: selectArtifact(manifest) });
|
|
50
|
+
}
|
|
@@ -0,0 +1,629 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import {
|
|
4
|
+
access,
|
|
5
|
+
constants as fsConstants,
|
|
6
|
+
lstat,
|
|
7
|
+
mkdir,
|
|
8
|
+
mkdtemp,
|
|
9
|
+
open,
|
|
10
|
+
readdir,
|
|
11
|
+
readFile,
|
|
12
|
+
readlink,
|
|
13
|
+
realpath,
|
|
14
|
+
rename,
|
|
15
|
+
rm,
|
|
16
|
+
} from 'node:fs/promises';
|
|
17
|
+
import { homedir } from 'node:os';
|
|
18
|
+
import { basename, join, posix, relative, sep } from 'node:path';
|
|
19
|
+
import { promisify } from 'node:util';
|
|
20
|
+
import { selectArtifact } from './manifest.mjs';
|
|
21
|
+
|
|
22
|
+
const execFileAsync = promisify(execFile);
|
|
23
|
+
const RECEIPT_OWNER = '@adrouter/agent';
|
|
24
|
+
const MAX_DOWNLOAD_BYTES = 512 * 1024 * 1024;
|
|
25
|
+
const MAX_REDIRECTS = 5;
|
|
26
|
+
const WINDOWS_SANDBOX_SETUP = 'npx @anthropic-ai/sandbox-runtime@0.0.65 windows-install';
|
|
27
|
+
const MAC_WARNING =
|
|
28
|
+
'This credential-free beta is not Developer ID signed or notarized. If macOS blocks it, open System Settings > Privacy & Security and choose Open Anyway.';
|
|
29
|
+
const PORTABLE_WARNING =
|
|
30
|
+
'This portable beta is unsigned. Install only from the canonical release and retain checksum verification.';
|
|
31
|
+
const ALLOWED_HOSTS = new Set([
|
|
32
|
+
'github.com',
|
|
33
|
+
'objects.githubusercontent.com',
|
|
34
|
+
'release-assets.githubusercontent.com',
|
|
35
|
+
]);
|
|
36
|
+
|
|
37
|
+
export function assertSupportedPlatform(platform = process.platform, arch = process.arch) {
|
|
38
|
+
selectArtifact(
|
|
39
|
+
{
|
|
40
|
+
artifacts: [{ key: 'darwin-universal' }, { key: 'linux-x64' }, { key: 'win32-x64' }],
|
|
41
|
+
},
|
|
42
|
+
platform,
|
|
43
|
+
arch
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function assertSupportedMacOsVersion(version) {
|
|
48
|
+
const major = Number.parseInt(String(version).split('.')[0] ?? '', 10);
|
|
49
|
+
if (!Number.isSafeInteger(major) || major < 12) {
|
|
50
|
+
throw new Error(`Unsupported macOS version ${version}; macOS 12 or newer is required.`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function assertNonRoot(uid = process.getuid?.()) {
|
|
55
|
+
if (uid === 0) {
|
|
56
|
+
throw new Error(
|
|
57
|
+
'Do not run adrouter-agent with sudo or as root; install it as the logged-in user.'
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function assertAllowedDownloadUrl(input) {
|
|
63
|
+
const url = input instanceof URL ? input : new URL(input);
|
|
64
|
+
if (url.protocol !== 'https:' || !ALLOWED_HOSTS.has(url.hostname)) {
|
|
65
|
+
throw new Error(`Refusing non-canonical download URL: ${url.origin}`);
|
|
66
|
+
}
|
|
67
|
+
if (url.username || url.password || url.port) {
|
|
68
|
+
throw new Error('Refusing a download URL containing credentials or a non-default port.');
|
|
69
|
+
}
|
|
70
|
+
return url;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function assertSafeArchiveEntries(entries, archiveRoot = 'AdRouter Agent.app') {
|
|
74
|
+
if (!Array.isArray(entries) || entries.length === 0) {
|
|
75
|
+
throw new Error('The release ZIP is empty.');
|
|
76
|
+
}
|
|
77
|
+
for (const entry of entries) {
|
|
78
|
+
if (
|
|
79
|
+
typeof entry !== 'string' ||
|
|
80
|
+
entry.includes('\0') ||
|
|
81
|
+
entry.startsWith('/') ||
|
|
82
|
+
/^[A-Za-z]:/.test(entry) ||
|
|
83
|
+
entry.startsWith('\\') ||
|
|
84
|
+
entry.split(/[\\/]/).includes('..')
|
|
85
|
+
) {
|
|
86
|
+
throw new Error(`Unsafe ZIP entry: ${JSON.stringify(entry)}`);
|
|
87
|
+
}
|
|
88
|
+
const normalized = entry.replaceAll('\\', '/').replace(/\/$/, '');
|
|
89
|
+
if (!normalized || normalized.split('/').some((segment) => segment === '' || segment === '.')) {
|
|
90
|
+
throw new Error(`Unsafe ZIP entry: ${JSON.stringify(entry)}`);
|
|
91
|
+
}
|
|
92
|
+
if (
|
|
93
|
+
archiveRoot !== '.' &&
|
|
94
|
+
normalized !== archiveRoot &&
|
|
95
|
+
!normalized.startsWith(`${archiveRoot}/`)
|
|
96
|
+
) {
|
|
97
|
+
throw new Error(`Unexpected ZIP layout entry: ${entry}`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function assertSafeArchiveSymlink(entry, target, archiveRoot = 'AdRouter Agent.app') {
|
|
103
|
+
assertSafeArchiveEntries([entry], archiveRoot);
|
|
104
|
+
if (
|
|
105
|
+
typeof target !== 'string' ||
|
|
106
|
+
target.length === 0 ||
|
|
107
|
+
target.includes('\0') ||
|
|
108
|
+
target.startsWith('/') ||
|
|
109
|
+
target.startsWith('\\') ||
|
|
110
|
+
target.includes('\\')
|
|
111
|
+
) {
|
|
112
|
+
throw new Error(`Unsafe ZIP symbolic link target: ${JSON.stringify(target)}`);
|
|
113
|
+
}
|
|
114
|
+
const root = archiveRoot === '.' ? '/_archive' : `/${archiveRoot}`;
|
|
115
|
+
const relativeEntry =
|
|
116
|
+
archiveRoot === '.'
|
|
117
|
+
? entry.split(String.fromCodePoint(92)).join('/')
|
|
118
|
+
: entry
|
|
119
|
+
.split(String.fromCodePoint(92))
|
|
120
|
+
.join('/')
|
|
121
|
+
.slice(archiveRoot.length + 1);
|
|
122
|
+
const resolved = posix.resolve(root, posix.dirname(relativeEntry), target);
|
|
123
|
+
if (resolved !== root && !resolved.startsWith(`${root}/`)) {
|
|
124
|
+
throw new Error(`ZIP symbolic link escapes ${archiveRoot}: ${entry} -> ${target}`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function releasePaths(
|
|
129
|
+
_manifest,
|
|
130
|
+
homeDirectory = homedir(),
|
|
131
|
+
platform = process.platform,
|
|
132
|
+
options = {}
|
|
133
|
+
) {
|
|
134
|
+
if (platform === 'darwin') {
|
|
135
|
+
const applicationsDirectory = join(homeDirectory, 'Applications');
|
|
136
|
+
const supportDirectory = join(
|
|
137
|
+
homeDirectory,
|
|
138
|
+
'Library',
|
|
139
|
+
'Application Support',
|
|
140
|
+
'adrouter-agent-launcher'
|
|
141
|
+
);
|
|
142
|
+
return {
|
|
143
|
+
applicationsDirectory,
|
|
144
|
+
supportDirectory,
|
|
145
|
+
appPath: join(applicationsDirectory, 'AdRouter Agent.app'),
|
|
146
|
+
receiptPath: join(supportDirectory, 'receipt.json'),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
if (platform === 'linux') {
|
|
150
|
+
const dataDirectory =
|
|
151
|
+
options.xdgDataHome ?? process.env.XDG_DATA_HOME ?? join(homeDirectory, '.local', 'share');
|
|
152
|
+
const applicationsDirectory = join(dataDirectory, 'adrouter-agent');
|
|
153
|
+
const supportDirectory = join(dataDirectory, 'adrouter-agent-launcher');
|
|
154
|
+
return {
|
|
155
|
+
applicationsDirectory,
|
|
156
|
+
supportDirectory,
|
|
157
|
+
appPath: join(applicationsDirectory, 'app'),
|
|
158
|
+
receiptPath: join(supportDirectory, 'receipt.json'),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
const localAppData =
|
|
162
|
+
options.localAppData ?? process.env.LOCALAPPDATA ?? join(homeDirectory, 'AppData', 'Local');
|
|
163
|
+
const applicationsDirectory = join(localAppData, 'Programs');
|
|
164
|
+
const supportDirectory = join(localAppData, 'adrouter-agent-launcher');
|
|
165
|
+
return {
|
|
166
|
+
applicationsDirectory,
|
|
167
|
+
supportDirectory,
|
|
168
|
+
appPath: join(applicationsDirectory, 'AdRouter Agent'),
|
|
169
|
+
receiptPath: join(supportDirectory, 'receipt.json'),
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async function exists(path) {
|
|
174
|
+
try {
|
|
175
|
+
await access(path);
|
|
176
|
+
return true;
|
|
177
|
+
} catch {
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function execute(file, args, options = {}) {
|
|
183
|
+
return execFileAsync(file, args, {
|
|
184
|
+
encoding: 'utf8',
|
|
185
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
186
|
+
...options,
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async function plistValue(appPath, key, executeImpl) {
|
|
191
|
+
const plist = join(appPath, 'Contents', 'Info.plist');
|
|
192
|
+
const { stdout } = await executeImpl('/usr/libexec/PlistBuddy', ['-c', `Print :${key}`, plist]);
|
|
193
|
+
return stdout.trim();
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async function verifyMacApp(appPath, manifest, executeImpl) {
|
|
197
|
+
await executeImpl('/usr/bin/codesign', ['--verify', '--deep', '--strict', appPath]);
|
|
198
|
+
const signatureResult = await executeImpl('/usr/bin/codesign', ['-dv', '--verbose=4', appPath]);
|
|
199
|
+
const signatureDetails = `${signatureResult.stdout ?? ''}${signatureResult.stderr ?? ''}`;
|
|
200
|
+
if (
|
|
201
|
+
!signatureDetails.includes('Signature=adhoc') ||
|
|
202
|
+
!signatureDetails.includes('TeamIdentifier=not set')
|
|
203
|
+
) {
|
|
204
|
+
throw new Error('The application is not the expected credential-free ad-hoc build.');
|
|
205
|
+
}
|
|
206
|
+
if (
|
|
207
|
+
(await plistValue(appPath, 'CFBundleIdentifier', executeImpl)) !== manifest.bundleIdentifier
|
|
208
|
+
) {
|
|
209
|
+
throw new Error('The installed app bundle identifier does not match the release manifest.');
|
|
210
|
+
}
|
|
211
|
+
if (
|
|
212
|
+
(await plistValue(appPath, 'CFBundleShortVersionString', executeImpl)) !==
|
|
213
|
+
manifest.bundleShortVersion
|
|
214
|
+
) {
|
|
215
|
+
throw new Error('The installed app short bundle version does not match the release manifest.');
|
|
216
|
+
}
|
|
217
|
+
if ((await plistValue(appPath, 'CFBundleVersion', executeImpl)) !== manifest.bundleVersion) {
|
|
218
|
+
throw new Error('The installed app build version does not match the release manifest.');
|
|
219
|
+
}
|
|
220
|
+
const executable = join(appPath, 'Contents', 'MacOS', 'AdRouter Agent');
|
|
221
|
+
const { stdout: architectures } = await executeImpl('/usr/bin/lipo', ['-archs', executable]);
|
|
222
|
+
if (!architectures.includes('arm64') || !architectures.includes('x86_64')) {
|
|
223
|
+
throw new Error('The installed app is not a universal arm64+x86_64 build.');
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async function verifyPortableApp(appPath, artifact) {
|
|
228
|
+
const executable = join(appPath, ...artifact.executablePath.split('/'));
|
|
229
|
+
const stat = await lstat(executable);
|
|
230
|
+
if (!stat.isFile() || stat.isSymbolicLink()) {
|
|
231
|
+
throw new Error('The portable application executable is missing or unsafe.');
|
|
232
|
+
}
|
|
233
|
+
if (artifact.platform === 'linux') await access(executable, fsConstants.X_OK);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
async function verifyApp(appPath, manifest, artifact, executeImpl = execute) {
|
|
237
|
+
if (artifact.verificationMode === 'macos-adhoc') {
|
|
238
|
+
await verifyMacApp(appPath, manifest, executeImpl);
|
|
239
|
+
} else {
|
|
240
|
+
await verifyPortableApp(appPath, artifact);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async function assessGatekeeper(appPath, executeImpl = execute) {
|
|
245
|
+
try {
|
|
246
|
+
await executeImpl('/usr/sbin/spctl', ['--assess', '--type', 'execute', appPath]);
|
|
247
|
+
return 'accepted';
|
|
248
|
+
} catch (error) {
|
|
249
|
+
if (error && typeof error === 'object' && error.code === 'ENOENT') return 'unavailable';
|
|
250
|
+
return 'rejected';
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async function verifyExtractedTree(root, appPath, archiveRoot) {
|
|
255
|
+
const canonicalRoot = `${await realpath(root)}${sep}`;
|
|
256
|
+
async function visit(path) {
|
|
257
|
+
const stat = await lstat(path);
|
|
258
|
+
if (stat.isSymbolicLink()) {
|
|
259
|
+
const entry = relative(root, path).split(sep).join('/');
|
|
260
|
+
assertSafeArchiveSymlink(entry, await readlink(path), archiveRoot);
|
|
261
|
+
}
|
|
262
|
+
const canonical = await realpath(path);
|
|
263
|
+
if (canonical !== canonicalRoot.slice(0, -1) && !canonical.startsWith(canonicalRoot)) {
|
|
264
|
+
throw new Error('Release archive escaped its extraction directory.');
|
|
265
|
+
}
|
|
266
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) return;
|
|
267
|
+
for (const entry of await readdir(path)) await visit(join(path, entry));
|
|
268
|
+
}
|
|
269
|
+
const topLevel = await readdir(root);
|
|
270
|
+
if (archiveRoot === '.' && topLevel.length === 0) {
|
|
271
|
+
throw new Error('Release archive is empty after extraction.');
|
|
272
|
+
}
|
|
273
|
+
if (archiveRoot !== '.' && (topLevel.length !== 1 || topLevel[0] !== archiveRoot)) {
|
|
274
|
+
throw new Error(`Release archive must contain exactly ${archiveRoot}.`);
|
|
275
|
+
}
|
|
276
|
+
await visit(appPath);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
async function download(manifest, artifact, destination, fetchImpl = fetch) {
|
|
280
|
+
let current = assertAllowedDownloadUrl(artifact.assetUrl);
|
|
281
|
+
for (let redirect = 0; redirect <= MAX_REDIRECTS; redirect += 1) {
|
|
282
|
+
const response = await fetchImpl(current, {
|
|
283
|
+
redirect: 'manual',
|
|
284
|
+
headers: { 'user-agent': `@adrouter/agent/${manifest.releaseVersion}` },
|
|
285
|
+
signal: AbortSignal.timeout(5 * 60 * 1000),
|
|
286
|
+
});
|
|
287
|
+
if ([301, 302, 303, 307, 308].includes(response.status)) {
|
|
288
|
+
const location = response.headers.get('location');
|
|
289
|
+
if (!location) throw new Error('Download redirect did not include a Location header.');
|
|
290
|
+
current = assertAllowedDownloadUrl(new URL(location, current));
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
if (!response.ok || !response.body) {
|
|
294
|
+
throw new Error(`Release download failed with HTTP ${response.status}.`);
|
|
295
|
+
}
|
|
296
|
+
const contentLength = response.headers.get('content-length');
|
|
297
|
+
const declaredSize = contentLength === null ? null : Number(contentLength);
|
|
298
|
+
if (
|
|
299
|
+
declaredSize !== null &&
|
|
300
|
+
(!Number.isSafeInteger(declaredSize) || declaredSize < 0 || declaredSize > MAX_DOWNLOAD_BYTES)
|
|
301
|
+
) {
|
|
302
|
+
throw new Error('Release download exceeds the maximum permitted size.');
|
|
303
|
+
}
|
|
304
|
+
const handle = await open(destination, 'wx', 0o600);
|
|
305
|
+
let received = 0;
|
|
306
|
+
const digest = createHash('sha256');
|
|
307
|
+
const reader = response.body.getReader();
|
|
308
|
+
try {
|
|
309
|
+
while (true) {
|
|
310
|
+
const { done, value: chunk } = await reader.read();
|
|
311
|
+
if (done) break;
|
|
312
|
+
received += chunk.byteLength;
|
|
313
|
+
if (received > MAX_DOWNLOAD_BYTES) {
|
|
314
|
+
throw new Error('Release download exceeds the maximum permitted size.');
|
|
315
|
+
}
|
|
316
|
+
digest.update(chunk);
|
|
317
|
+
await handle.write(chunk);
|
|
318
|
+
}
|
|
319
|
+
} finally {
|
|
320
|
+
reader.releaseLock();
|
|
321
|
+
await handle.close();
|
|
322
|
+
}
|
|
323
|
+
if (declaredSize !== null && received !== declaredSize) {
|
|
324
|
+
throw new Error('Release download ended before the declared content length.');
|
|
325
|
+
}
|
|
326
|
+
const actual = digest.digest('hex');
|
|
327
|
+
if (actual !== artifact.sha256) throw new Error('Release ZIP checksum verification failed.');
|
|
328
|
+
return { bytes: received, sha256: actual, finalUrl: current.href };
|
|
329
|
+
}
|
|
330
|
+
throw new Error('Release download exceeded the redirect limit.');
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
async function archiveEntries(zipPath, artifact, executeImpl = execute) {
|
|
334
|
+
if (artifact.platform === 'win32') {
|
|
335
|
+
const script =
|
|
336
|
+
'& { param([string]$zipPath) ' +
|
|
337
|
+
'Add-Type -AssemblyName System.IO.Compression.FileSystem; ' +
|
|
338
|
+
'$z=[IO.Compression.ZipFile]::OpenRead($zipPath); ' +
|
|
339
|
+
'try {$z.Entries.FullName} finally {$z.Dispose()} }';
|
|
340
|
+
const { stdout } = await executeImpl('powershell.exe', [
|
|
341
|
+
'-NoProfile',
|
|
342
|
+
'-NonInteractive',
|
|
343
|
+
'-Command',
|
|
344
|
+
script,
|
|
345
|
+
zipPath,
|
|
346
|
+
]);
|
|
347
|
+
const entries = stdout.split(/\r?\n/).filter(Boolean);
|
|
348
|
+
assertSafeArchiveEntries(entries, artifact.archiveRoot);
|
|
349
|
+
return entries;
|
|
350
|
+
}
|
|
351
|
+
const { stdout } = await executeImpl('/usr/bin/unzip', ['-Z1', zipPath]);
|
|
352
|
+
const entries = stdout.split('\n').filter(Boolean);
|
|
353
|
+
assertSafeArchiveEntries(entries, artifact.archiveRoot);
|
|
354
|
+
const { stdout: listing } = await executeImpl('/usr/bin/zipinfo', ['-l', zipPath]);
|
|
355
|
+
for (const line of listing.split('\n').filter((value) => /^l[rwx-]{9}\s/.test(value))) {
|
|
356
|
+
const match = line.match(/^l[rwx-]{9}\s+\S+\s+\S+\s+\d+\s+\S+\s+\d+\s+\S+\s+\S+\s+\S+\s+(.+)$/);
|
|
357
|
+
if (!match) throw new Error('Unable to validate a ZIP symbolic link entry.');
|
|
358
|
+
const entry = match[1];
|
|
359
|
+
const { stdout: target } = await executeImpl('/usr/bin/unzip', ['-p', zipPath, entry]);
|
|
360
|
+
assertSafeArchiveSymlink(entry, target, artifact.archiveRoot);
|
|
361
|
+
}
|
|
362
|
+
return entries;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
async function extractArchive(archive, extracted, artifact, executeImpl) {
|
|
366
|
+
if (artifact.platform === 'darwin') {
|
|
367
|
+
await executeImpl('/usr/bin/ditto', ['-x', '-k', archive, extracted]);
|
|
368
|
+
} else if (artifact.platform === 'linux') {
|
|
369
|
+
await executeImpl('/usr/bin/unzip', ['-q', archive, '-d', extracted]);
|
|
370
|
+
} else {
|
|
371
|
+
const script =
|
|
372
|
+
'& { param([string]$archive, [string]$destination) ' +
|
|
373
|
+
'Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }';
|
|
374
|
+
await executeImpl('powershell.exe', [
|
|
375
|
+
'-NoProfile',
|
|
376
|
+
'-NonInteractive',
|
|
377
|
+
'-Command',
|
|
378
|
+
script,
|
|
379
|
+
archive,
|
|
380
|
+
extracted,
|
|
381
|
+
]);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
async function readReceipt(receiptPath, appPath, platform) {
|
|
386
|
+
try {
|
|
387
|
+
const receipt = JSON.parse(await readFile(receiptPath, 'utf8'));
|
|
388
|
+
const current = receipt.schema === 3;
|
|
389
|
+
const legacyMac = platform === 'darwin' && receipt.schema === 2;
|
|
390
|
+
const owned =
|
|
391
|
+
(current || legacyMac) &&
|
|
392
|
+
receipt.owner === RECEIPT_OWNER &&
|
|
393
|
+
receipt.applicationPath === appPath;
|
|
394
|
+
return { receipt, owned, legacyMac };
|
|
395
|
+
} catch {
|
|
396
|
+
return { receipt: null, owned: false, legacyMac: false };
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function receiptMatchesManifest(receipt, manifest, artifact) {
|
|
401
|
+
return (
|
|
402
|
+
receipt?.releaseVersion === manifest.releaseVersion &&
|
|
403
|
+
receipt?.sha256 === artifact.sha256 &&
|
|
404
|
+
receipt?.releaseTag === manifest.releaseTag &&
|
|
405
|
+
(receipt.schema === 2 || receipt.artifactKey === artifact.key)
|
|
406
|
+
);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
async function appIsRunning(appPath, artifact, executeImpl = execute) {
|
|
410
|
+
const executable = join(appPath, ...artifact.executablePath.split('/'));
|
|
411
|
+
if (artifact.platform === 'win32') return false;
|
|
412
|
+
const { stdout } = await executeImpl('/bin/ps', ['-axo', 'command=']);
|
|
413
|
+
return stdout
|
|
414
|
+
.split('\n')
|
|
415
|
+
.map((line) => line.trim())
|
|
416
|
+
.some((line) => line === executable || line.startsWith(`${executable} `));
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function sandboxReport(platform, override) {
|
|
420
|
+
if (override) return override;
|
|
421
|
+
if (platform === 'win32') {
|
|
422
|
+
return {
|
|
423
|
+
status: 'setup-required',
|
|
424
|
+
detail: 'Run the one-time elevated Windows sandbox setup before command tools are enabled.',
|
|
425
|
+
setupCommands: [WINDOWS_SANDBOX_SETUP],
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
if (platform === 'linux') {
|
|
429
|
+
return {
|
|
430
|
+
status: 'setup-required',
|
|
431
|
+
detail: 'Verify Bubblewrap, socat, ripgrep, and the Ubuntu AppArmor userns profile.',
|
|
432
|
+
setupCommands: ['sudo apt-get install bubblewrap socat ripgrep'],
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
return {
|
|
436
|
+
status: 'ready',
|
|
437
|
+
detail: 'Seatbelt command sandboxing is built into macOS.',
|
|
438
|
+
setupCommands: [],
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
export async function inspectInstallation(manifest, options = {}) {
|
|
443
|
+
const platform = options.platform ?? process.platform;
|
|
444
|
+
const architecture = options.arch ?? process.arch;
|
|
445
|
+
const artifact = selectArtifact(manifest, platform, architecture);
|
|
446
|
+
const paths = releasePaths(manifest, options.homeDirectory, platform, options);
|
|
447
|
+
const report = {
|
|
448
|
+
schema: 3,
|
|
449
|
+
distributionMode: manifest.distributionMode,
|
|
450
|
+
platform,
|
|
451
|
+
architecture,
|
|
452
|
+
artifactKey: artifact.key,
|
|
453
|
+
verificationMode: artifact.verificationMode,
|
|
454
|
+
operatingSystemVersion: null,
|
|
455
|
+
supported: false,
|
|
456
|
+
releaseVersion: manifest.releaseVersion,
|
|
457
|
+
releaseTag: manifest.releaseTag,
|
|
458
|
+
applicationPath: paths.appPath,
|
|
459
|
+
installed: false,
|
|
460
|
+
receiptMatches: false,
|
|
461
|
+
bundleIntegrity: false,
|
|
462
|
+
signatureType: 'missing',
|
|
463
|
+
gatekeeperAssessment: platform === 'darwin' ? 'unavailable' : 'not-applicable',
|
|
464
|
+
sandbox: sandboxReport(platform, options.sandbox),
|
|
465
|
+
authenticationInspection: 'application-only',
|
|
466
|
+
authenticationState: 'unknown',
|
|
467
|
+
storageClassification: 'unknown',
|
|
468
|
+
signedRequestSupport: false,
|
|
469
|
+
refreshHealth: 'unknown',
|
|
470
|
+
pendingEnrollment: 'unknown',
|
|
471
|
+
originClass: 'unknown',
|
|
472
|
+
reconnectNeed: 'unknown',
|
|
473
|
+
warning: platform === 'darwin' ? MAC_WARNING : PORTABLE_WARNING,
|
|
474
|
+
};
|
|
475
|
+
try {
|
|
476
|
+
assertSupportedPlatform(platform, architecture);
|
|
477
|
+
if (platform === 'darwin') {
|
|
478
|
+
const versionResult =
|
|
479
|
+
options.macOsVersion === undefined
|
|
480
|
+
? await (options.executeImpl ?? execute)('/usr/bin/sw_vers', ['-productVersion'])
|
|
481
|
+
: { stdout: options.macOsVersion };
|
|
482
|
+
report.operatingSystemVersion = versionResult.stdout.trim();
|
|
483
|
+
assertSupportedMacOsVersion(report.operatingSystemVersion);
|
|
484
|
+
}
|
|
485
|
+
report.supported = true;
|
|
486
|
+
} catch (error) {
|
|
487
|
+
report.error = error instanceof Error ? error.message : String(error);
|
|
488
|
+
return report;
|
|
489
|
+
}
|
|
490
|
+
report.installed = await exists(paths.appPath);
|
|
491
|
+
if (!report.installed) return report;
|
|
492
|
+
const receiptStatus = await readReceipt(paths.receiptPath, paths.appPath, platform);
|
|
493
|
+
report.receiptMatches =
|
|
494
|
+
receiptStatus.owned && receiptMatchesManifest(receiptStatus.receipt, manifest, artifact);
|
|
495
|
+
try {
|
|
496
|
+
await verifyApp(paths.appPath, manifest, artifact, options.executeImpl);
|
|
497
|
+
report.bundleIntegrity = true;
|
|
498
|
+
report.signedRequestSupport = true;
|
|
499
|
+
report.signatureType = platform === 'darwin' ? 'adhoc' : 'unsigned-portable';
|
|
500
|
+
} catch (error) {
|
|
501
|
+
report.signatureType = 'invalid';
|
|
502
|
+
report.error = error instanceof Error ? error.message : String(error);
|
|
503
|
+
}
|
|
504
|
+
if (platform === 'darwin') {
|
|
505
|
+
report.gatekeeperAssessment = await assessGatekeeper(paths.appPath, options.executeImpl);
|
|
506
|
+
if (report.gatekeeperAssessment === 'accepted') report.warning = null;
|
|
507
|
+
}
|
|
508
|
+
return report;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
export async function install(manifest, options = {}) {
|
|
512
|
+
const platform = options.platform ?? process.platform;
|
|
513
|
+
const architecture = options.arch ?? process.arch;
|
|
514
|
+
const artifact = selectArtifact(manifest, platform, architecture);
|
|
515
|
+
assertNonRoot(options.uid ?? process.getuid?.());
|
|
516
|
+
const paths = releasePaths(manifest, options.homeDirectory, platform, options);
|
|
517
|
+
const executeImpl = options.executeImpl ?? execute;
|
|
518
|
+
const existing = await inspectInstallation(manifest, options);
|
|
519
|
+
if (!existing.supported)
|
|
520
|
+
throw new Error(existing.error ?? 'This operating system is not supported.');
|
|
521
|
+
const receiptStatus = await readReceipt(paths.receiptPath, paths.appPath, platform);
|
|
522
|
+
if (existing.installed && existing.receiptMatches && existing.bundleIntegrity) {
|
|
523
|
+
if (receiptStatus.legacyMac) {
|
|
524
|
+
await (options.writeReceiptImpl ?? writeReceipt)(paths.receiptPath, {
|
|
525
|
+
...receiptStatus.receipt,
|
|
526
|
+
schema: 3,
|
|
527
|
+
distributionMode: manifest.distributionMode,
|
|
528
|
+
artifactKey: artifact.key,
|
|
529
|
+
migratedAt: new Date().toISOString(),
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
return paths.appPath;
|
|
533
|
+
}
|
|
534
|
+
if (existing.installed && !receiptStatus.owned) {
|
|
535
|
+
throw new Error(
|
|
536
|
+
`${paths.appPath} already exists and is not managed by @adrouter/agent; move or remove it before installing.`
|
|
537
|
+
);
|
|
538
|
+
}
|
|
539
|
+
if (existing.installed && (await appIsRunning(paths.appPath, artifact, executeImpl))) {
|
|
540
|
+
throw new Error('Quit AdRouter Agent before installing or updating it.');
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
await mkdir(paths.applicationsDirectory, { recursive: true, mode: 0o755 });
|
|
544
|
+
await mkdir(paths.supportDirectory, { recursive: true, mode: 0o700 });
|
|
545
|
+
const staging = await mkdtemp(join(paths.applicationsDirectory, '.adrouter-agent-staging-'));
|
|
546
|
+
const archive = join(staging, basename(artifact.assetName));
|
|
547
|
+
const extracted = join(staging, 'extracted');
|
|
548
|
+
const stagedApp =
|
|
549
|
+
artifact.archiveRoot === '.' ? extracted : join(extracted, artifact.archiveRoot);
|
|
550
|
+
const backupPath = join(
|
|
551
|
+
paths.applicationsDirectory,
|
|
552
|
+
`.adrouter-agent-backup-${process.pid}-${Date.now()}`
|
|
553
|
+
);
|
|
554
|
+
let backedUp = false;
|
|
555
|
+
let activated = false;
|
|
556
|
+
try {
|
|
557
|
+
const receipt = await download(manifest, artifact, archive, options.fetchImpl);
|
|
558
|
+
await archiveEntries(archive, artifact, executeImpl);
|
|
559
|
+
await mkdir(extracted, { mode: 0o700 });
|
|
560
|
+
await extractArchive(archive, extracted, artifact, executeImpl);
|
|
561
|
+
await verifyExtractedTree(extracted, stagedApp, artifact.archiveRoot);
|
|
562
|
+
await verifyApp(stagedApp, manifest, artifact, executeImpl);
|
|
563
|
+
if (existing.installed) {
|
|
564
|
+
await rename(paths.appPath, backupPath);
|
|
565
|
+
backedUp = true;
|
|
566
|
+
}
|
|
567
|
+
await rename(stagedApp, paths.appPath);
|
|
568
|
+
activated = true;
|
|
569
|
+
await (options.writeReceiptImpl ?? writeReceipt)(paths.receiptPath, {
|
|
570
|
+
schema: 3,
|
|
571
|
+
owner: RECEIPT_OWNER,
|
|
572
|
+
distributionMode: manifest.distributionMode,
|
|
573
|
+
artifactKey: artifact.key,
|
|
574
|
+
releaseVersion: manifest.releaseVersion,
|
|
575
|
+
releaseTag: manifest.releaseTag,
|
|
576
|
+
sha256: receipt.sha256,
|
|
577
|
+
bytes: receipt.bytes,
|
|
578
|
+
finalUrl: receipt.finalUrl,
|
|
579
|
+
applicationPath: paths.appPath,
|
|
580
|
+
installedAt: new Date().toISOString(),
|
|
581
|
+
});
|
|
582
|
+
if (backedUp) await rm(backupPath, { recursive: true, force: true });
|
|
583
|
+
return paths.appPath;
|
|
584
|
+
} catch (error) {
|
|
585
|
+
if (activated) await rm(paths.appPath, { recursive: true, force: true });
|
|
586
|
+
if (backedUp && (await exists(backupPath))) await rename(backupPath, paths.appPath);
|
|
587
|
+
throw error;
|
|
588
|
+
} finally {
|
|
589
|
+
await rm(staging, { recursive: true, force: true });
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
async function writeReceipt(path, receipt) {
|
|
594
|
+
const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;
|
|
595
|
+
try {
|
|
596
|
+
const handle = await open(temporary, 'wx', 0o600);
|
|
597
|
+
try {
|
|
598
|
+
await handle.writeFile(`${JSON.stringify(receipt, null, 2)}\n`, 'utf8');
|
|
599
|
+
} finally {
|
|
600
|
+
await handle.close();
|
|
601
|
+
}
|
|
602
|
+
await rename(temporary, path);
|
|
603
|
+
} catch (error) {
|
|
604
|
+
await rm(temporary, { force: true });
|
|
605
|
+
throw error;
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
export async function launch(appPath, options = {}) {
|
|
610
|
+
const platform = options.platform ?? process.platform;
|
|
611
|
+
const artifact = options.artifact ?? {
|
|
612
|
+
executablePath:
|
|
613
|
+
platform === 'darwin'
|
|
614
|
+
? 'Contents/MacOS/AdRouter Agent'
|
|
615
|
+
: platform === 'win32'
|
|
616
|
+
? 'AdRouter Agent.exe'
|
|
617
|
+
: 'AdRouter Agent',
|
|
618
|
+
};
|
|
619
|
+
const spawnImpl = options.spawnImpl ?? spawn;
|
|
620
|
+
const executable =
|
|
621
|
+
platform === 'darwin' ? '/usr/bin/open' : join(appPath, ...artifact.executablePath.split('/'));
|
|
622
|
+
const args = platform === 'darwin' ? [appPath] : [];
|
|
623
|
+
await new Promise((resolvePromise, reject) => {
|
|
624
|
+
const child = spawnImpl(executable, args, { detached: true, stdio: 'ignore' });
|
|
625
|
+
child.once('error', reject);
|
|
626
|
+
child.once('spawn', resolvePromise);
|
|
627
|
+
child.unref();
|
|
628
|
+
});
|
|
629
|
+
}
|
package/lib/manifest.mjs
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
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
|
+
const ARTIFACTS = Object.freeze({
|
|
6
|
+
'darwin-universal': {
|
|
7
|
+
platform: 'darwin',
|
|
8
|
+
architectures: ['arm64', 'x64'],
|
|
9
|
+
archiveRoot: 'AdRouter Agent.app',
|
|
10
|
+
executablePath: 'Contents/MacOS/AdRouter Agent',
|
|
11
|
+
verificationMode: 'macos-adhoc',
|
|
12
|
+
suffix: 'darwin-universal',
|
|
13
|
+
},
|
|
14
|
+
'linux-x64': {
|
|
15
|
+
platform: 'linux',
|
|
16
|
+
architectures: ['x64'],
|
|
17
|
+
archiveRoot: 'AdRouter Agent-linux-x64',
|
|
18
|
+
executablePath: 'AdRouter Agent',
|
|
19
|
+
verificationMode: 'portable-checksum',
|
|
20
|
+
suffix: 'linux-x64',
|
|
21
|
+
},
|
|
22
|
+
'win32-x64': {
|
|
23
|
+
platform: 'win32',
|
|
24
|
+
architectures: ['x64'],
|
|
25
|
+
archiveRoot: '.',
|
|
26
|
+
executablePath: 'AdRouter Agent.exe',
|
|
27
|
+
verificationMode: 'portable-checksum',
|
|
28
|
+
suffix: 'win32-x64',
|
|
29
|
+
},
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
export function artifactKey(platform = process.platform, arch = process.arch) {
|
|
33
|
+
if (platform === 'darwin' && (arch === 'arm64' || arch === 'x64')) {
|
|
34
|
+
return 'darwin-universal';
|
|
35
|
+
}
|
|
36
|
+
if (platform === 'linux' && arch === 'x64') return 'linux-x64';
|
|
37
|
+
if (platform === 'win32' && arch === 'x64') return 'win32-x64';
|
|
38
|
+
throw new Error(`Unsupported operating system/architecture combination: ${platform}/${arch}.`);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function selectArtifact(manifest, platform = process.platform, arch = process.arch) {
|
|
42
|
+
const key = artifactKey(platform, arch);
|
|
43
|
+
const artifact = manifest.artifacts.find((candidate) => candidate.key === key);
|
|
44
|
+
if (!artifact) throw new Error(`The release manifest does not contain ${key}.`);
|
|
45
|
+
return artifact;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function validateManifest(value) {
|
|
49
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
50
|
+
throw new Error('The embedded release manifest is not an object.');
|
|
51
|
+
}
|
|
52
|
+
for (const key of [
|
|
53
|
+
'releaseVersion',
|
|
54
|
+
'releaseTag',
|
|
55
|
+
'repository',
|
|
56
|
+
'distributionMode',
|
|
57
|
+
'bundleIdentifier',
|
|
58
|
+
'bundleShortVersion',
|
|
59
|
+
'bundleVersion',
|
|
60
|
+
]) {
|
|
61
|
+
if (typeof value[key] !== 'string' || value[key].length === 0) {
|
|
62
|
+
throw new Error(`The embedded release manifest has an invalid ${key}.`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (value.schema !== 3) throw new Error('Unsupported release manifest schema.');
|
|
66
|
+
if (value.distributionMode !== 'credential-free-portable') {
|
|
67
|
+
throw new Error('The embedded release distribution mode is not supported.');
|
|
68
|
+
}
|
|
69
|
+
if (!VERSION_PATTERN.test(value.releaseVersion)) {
|
|
70
|
+
throw new Error('The embedded release version is not a supported SemVer.');
|
|
71
|
+
}
|
|
72
|
+
if (value.releaseTag !== `v${value.releaseVersion}`) {
|
|
73
|
+
throw new Error('The embedded release tag does not match the version.');
|
|
74
|
+
}
|
|
75
|
+
if (value.repository !== 'adrouter/adrouterAgent') {
|
|
76
|
+
throw new Error('The embedded repository is not canonical.');
|
|
77
|
+
}
|
|
78
|
+
if (value.bundleIdentifier !== 'com.adrouter.agent') {
|
|
79
|
+
throw new Error('The embedded bundle identifier is not canonical.');
|
|
80
|
+
}
|
|
81
|
+
if (!/^\d+\.\d+\.\d+$/.test(value.bundleShortVersion)) {
|
|
82
|
+
throw new Error('The embedded short bundle version is invalid.');
|
|
83
|
+
}
|
|
84
|
+
if (!/^\d+(?:\.\d+){0,2}$/.test(value.bundleVersion)) {
|
|
85
|
+
throw new Error('The embedded numeric bundle version is invalid.');
|
|
86
|
+
}
|
|
87
|
+
if (
|
|
88
|
+
value.authentication?.fixture !== 'tests/fixtures/platform-auth-v1.json' ||
|
|
89
|
+
value.authentication?.fixtureSha256 !==
|
|
90
|
+
'93a8ec8d4eba38f9165179aa0cdfe3316f8134a882bd0426bd83339af55d17f8' ||
|
|
91
|
+
value.authentication?.acceptanceAsset !== 'authentication-acceptance.json'
|
|
92
|
+
) {
|
|
93
|
+
throw new Error('The embedded platform authentication metadata is not canonical.');
|
|
94
|
+
}
|
|
95
|
+
if (!Array.isArray(value.artifacts) || value.artifacts.length !== 3) {
|
|
96
|
+
throw new Error('The embedded release manifest must contain exactly three artifacts.');
|
|
97
|
+
}
|
|
98
|
+
const seen = new Set();
|
|
99
|
+
for (const artifact of value.artifacts) {
|
|
100
|
+
const expected = ARTIFACTS[artifact?.key];
|
|
101
|
+
if (!expected || seen.has(artifact.key)) {
|
|
102
|
+
throw new Error(
|
|
103
|
+
`The embedded release manifest has an invalid artifact key: ${artifact?.key}.`
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
seen.add(artifact.key);
|
|
107
|
+
for (const field of [
|
|
108
|
+
'platform',
|
|
109
|
+
'assetName',
|
|
110
|
+
'assetUrl',
|
|
111
|
+
'sha256',
|
|
112
|
+
'archiveRoot',
|
|
113
|
+
'executablePath',
|
|
114
|
+
'verificationMode',
|
|
115
|
+
]) {
|
|
116
|
+
if (typeof artifact[field] !== 'string' || artifact[field].length === 0) {
|
|
117
|
+
throw new Error(`Artifact ${artifact.key} has an invalid ${field}.`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (
|
|
121
|
+
artifact.platform !== expected.platform ||
|
|
122
|
+
JSON.stringify(artifact.architectures) !== JSON.stringify(expected.architectures) ||
|
|
123
|
+
artifact.archiveRoot !== expected.archiveRoot ||
|
|
124
|
+
artifact.executablePath !== expected.executablePath ||
|
|
125
|
+
artifact.verificationMode !== expected.verificationMode
|
|
126
|
+
) {
|
|
127
|
+
throw new Error(`Artifact ${artifact.key} does not match its canonical target metadata.`);
|
|
128
|
+
}
|
|
129
|
+
const expectedName = `AdRouter-Agent-${value.releaseVersion}-${expected.suffix}.zip`;
|
|
130
|
+
if (artifact.assetName !== expectedName) {
|
|
131
|
+
throw new Error(`Artifact ${artifact.key} has a non-canonical asset name.`);
|
|
132
|
+
}
|
|
133
|
+
const expectedUrl =
|
|
134
|
+
`https://github.com/${value.repository}/releases/download/` +
|
|
135
|
+
`${value.releaseTag}/${expectedName}`;
|
|
136
|
+
if (artifact.assetUrl !== expectedUrl) {
|
|
137
|
+
throw new Error(`Artifact ${artifact.key} has a non-canonical asset URL.`);
|
|
138
|
+
}
|
|
139
|
+
if (!SHA256_PATTERN.test(artifact.sha256)) {
|
|
140
|
+
throw new Error(`Artifact ${artifact.key} checksum is not a SHA-256 digest.`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return Object.freeze({
|
|
144
|
+
...value,
|
|
145
|
+
authentication: Object.freeze({ ...value.authentication }),
|
|
146
|
+
artifacts: Object.freeze(value.artifacts.map((artifact) => Object.freeze({ ...artifact }))),
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export async function readManifest(url = new URL('../release-manifest.json', import.meta.url)) {
|
|
151
|
+
const text = await readFile(url, 'utf8');
|
|
152
|
+
return validateManifest(JSON.parse(text));
|
|
153
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@adrouter/agent",
|
|
3
|
+
"version": "0.1.0-beta.10",
|
|
4
|
+
"description": "Verified installer and launcher for the AdRouter Agent desktop 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
|
+
"linux",
|
|
23
|
+
"win32"
|
|
24
|
+
],
|
|
25
|
+
"cpu": [
|
|
26
|
+
"arm64",
|
|
27
|
+
"x64"
|
|
28
|
+
],
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "git+https://github.com/adrouter/adrouterAgent.git",
|
|
32
|
+
"directory": "packages/agent-launcher"
|
|
33
|
+
},
|
|
34
|
+
"bugs": {
|
|
35
|
+
"url": "https://github.com/adrouter/adrouterAgent/issues"
|
|
36
|
+
},
|
|
37
|
+
"homepage": "https://github.com/adrouter/adrouterAgent#readme",
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public",
|
|
40
|
+
"provenance": true
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schema": 3,
|
|
3
|
+
"distributionMode": "credential-free-portable",
|
|
4
|
+
"releaseVersion": "0.1.0-beta.10",
|
|
5
|
+
"releaseTag": "v0.1.0-beta.10",
|
|
6
|
+
"repository": "adrouter/adrouterAgent",
|
|
7
|
+
"bundleIdentifier": "com.adrouter.agent",
|
|
8
|
+
"bundleShortVersion": "0.1.0",
|
|
9
|
+
"bundleVersion": "10010",
|
|
10
|
+
"authentication": {
|
|
11
|
+
"fixture": "tests/fixtures/platform-auth-v1.json",
|
|
12
|
+
"fixtureSha256": "93a8ec8d4eba38f9165179aa0cdfe3316f8134a882bd0426bd83339af55d17f8",
|
|
13
|
+
"acceptanceAsset": "authentication-acceptance.json"
|
|
14
|
+
},
|
|
15
|
+
"artifacts": [
|
|
16
|
+
{
|
|
17
|
+
"key": "darwin-universal",
|
|
18
|
+
"platform": "darwin",
|
|
19
|
+
"architectures": [
|
|
20
|
+
"arm64",
|
|
21
|
+
"x64"
|
|
22
|
+
],
|
|
23
|
+
"archiveRoot": "AdRouter Agent.app",
|
|
24
|
+
"executablePath": "Contents/MacOS/AdRouter Agent",
|
|
25
|
+
"verificationMode": "macos-adhoc",
|
|
26
|
+
"assetName": "AdRouter-Agent-0.1.0-beta.10-darwin-universal.zip",
|
|
27
|
+
"assetUrl": "https://github.com/adrouter/adrouterAgent/releases/download/v0.1.0-beta.10/AdRouter-Agent-0.1.0-beta.10-darwin-universal.zip",
|
|
28
|
+
"sha256": "8509e4817b21a83efa6d26f312cdfb2e14788e7897f43931f118bb8d5228e33b"
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
"key": "linux-x64",
|
|
32
|
+
"platform": "linux",
|
|
33
|
+
"architectures": [
|
|
34
|
+
"x64"
|
|
35
|
+
],
|
|
36
|
+
"archiveRoot": "AdRouter Agent-linux-x64",
|
|
37
|
+
"executablePath": "AdRouter Agent",
|
|
38
|
+
"verificationMode": "portable-checksum",
|
|
39
|
+
"assetName": "AdRouter-Agent-0.1.0-beta.10-linux-x64.zip",
|
|
40
|
+
"assetUrl": "https://github.com/adrouter/adrouterAgent/releases/download/v0.1.0-beta.10/AdRouter-Agent-0.1.0-beta.10-linux-x64.zip",
|
|
41
|
+
"sha256": "5ac61e2fd757f584762291c7fe65bf0c9edda4e650dd5e7c972a7dc7cadbd332"
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
"key": "win32-x64",
|
|
45
|
+
"platform": "win32",
|
|
46
|
+
"architectures": [
|
|
47
|
+
"x64"
|
|
48
|
+
],
|
|
49
|
+
"archiveRoot": ".",
|
|
50
|
+
"executablePath": "AdRouter Agent.exe",
|
|
51
|
+
"verificationMode": "portable-checksum",
|
|
52
|
+
"assetName": "AdRouter-Agent-0.1.0-beta.10-win32-x64.zip",
|
|
53
|
+
"assetUrl": "https://github.com/adrouter/adrouterAgent/releases/download/v0.1.0-beta.10/AdRouter-Agent-0.1.0-beta.10-win32-x64.zip",
|
|
54
|
+
"sha256": "7fd83263aa2272b4585acd7a69b95f1e9f09f8e7bbde13b76f7dabc89916aa27"
|
|
55
|
+
}
|
|
56
|
+
]
|
|
57
|
+
}
|