Skip to content

Commit 3a7b812

Browse files
committed
feat(desktop): support external macOS update installation
1 parent ade4730 commit 3a7b812

7 files changed

Lines changed: 1010 additions & 94 deletions

File tree

Lines changed: 251 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,251 @@
1+
import * as NodeAssert from "node:assert/strict";
2+
import * as NodeChildProcess from "node:child_process";
3+
import * as NodeEvents from "node:events";
4+
import * as NodeFS from "node:fs";
5+
import * as NodeOS from "node:os";
6+
import * as NodePath from "node:path";
7+
import * as NodeURL from "node:url";
8+
9+
export const installerPath = NodeURL.fileURLToPath(
10+
new URL("./install-macos-update.sh", import.meta.url),
11+
);
12+
13+
export function run(command, args, options = {}) {
14+
return NodeChildProcess.spawnSync(command, args, {
15+
encoding: "utf8",
16+
timeout: 7_000,
17+
...options,
18+
});
19+
}
20+
21+
export function isAlive(pid) {
22+
try {
23+
process.kill(pid, 0);
24+
return true;
25+
} catch {
26+
return false;
27+
}
28+
}
29+
30+
function createBundle(base, version, options = {}) {
31+
NodeFS.mkdirSync(NodePath.join(base, "Contents/Resources/nested"), { recursive: true });
32+
NodeFS.writeFileSync(
33+
NodePath.join(base, "Contents/Info.plist"),
34+
`<?xml version="1.0"?><plist version="1.0"><dict><key>CFBundleIdentifier</key><string>${options.id ?? "org.example.fixture"}</string><key>CFBundleShortVersionString</key><string>${version}</string></dict></plist>`,
35+
);
36+
NodeFS.writeFileSync(
37+
NodePath.join(base, "Contents/Resources/app.asar"),
38+
options.integration === false
39+
? "fixture payload"
40+
: "fixture T3CODE_DESKTOP_UPDATE_INSTALLER payload",
41+
);
42+
NodeFS.writeFileSync(
43+
NodePath.join(base, "Contents/Resources/nested/content"),
44+
`payload:${version}\n`,
45+
);
46+
NodeFS.writeFileSync(NodePath.join(base, ".version"), version);
47+
NodeFS.writeFileSync(NodePath.join(base, ".team"), options.team ?? "SYNTHETIC");
48+
if (options.signature !== false)
49+
NodeFS.writeFileSync(NodePath.join(base, ".signature-valid"), "synthetic");
50+
if (options.gatekeeper !== false)
51+
NodeFS.writeFileSync(NodePath.join(base, ".gatekeeper-valid"), "synthetic");
52+
NodeFS.writeFileSync(
53+
NodePath.join(base, "Contents/Resources/executable"),
54+
"#!/bin/sh\nexit 0\n",
55+
{
56+
mode: 0o755,
57+
},
58+
);
59+
NodeFS.symlinkSync("nested/content", NodePath.join(base, "Contents/Resources/content-link"));
60+
}
61+
62+
export function snapshot(base, relative = "") {
63+
const entry = NodePath.join(base, relative);
64+
const stat = NodeFS.lstatSync(entry);
65+
const contents = stat.isSymbolicLink()
66+
? NodeFS.readlinkSync(entry)
67+
: stat.isFile()
68+
? NodeFS.readFileSync(entry).toString("base64")
69+
: "directory";
70+
const entries = [[relative, stat.mode & 0o777, contents]];
71+
if (stat.isDirectory()) {
72+
for (const name of NodeFS.readdirSync(entry).sort()) {
73+
entries.push(...snapshot(base, NodePath.join(relative, name)));
74+
}
75+
}
76+
return entries;
77+
}
78+
79+
export function createFixture(options = {}) {
80+
const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "installer-fixture-"));
81+
const clean = () => NodeFS.rmSync(dir, { recursive: true, force: true });
82+
try {
83+
const bin = NodePath.join(dir, "fake-bin");
84+
NodeFS.mkdirSync(bin);
85+
const app = NodePath.join(dir, "Fixture App.app");
86+
createBundle(app, "1.0.0");
87+
const source = NodePath.join(dir, "release/Fixture App.app");
88+
createBundle(source, options.version ?? "2.0.0", options);
89+
const expected = snapshot(source);
90+
const archive = NodePath.join(dir, "selected.zip");
91+
const archived = run("/usr/bin/ditto", [
92+
"-c",
93+
"-k",
94+
"--sequesterRsrc",
95+
"--keepParent",
96+
source,
97+
archive,
98+
]);
99+
NodeAssert.equal(archived.status, 0, archived.stderr);
100+
const events = NodePath.join(dir, "events");
101+
NodeFS.writeFileSync(events, "");
102+
103+
// Only signature, Gatekeeper and launch boundaries are simulated; these are not signed-app fixtures.
104+
const stubs = {
105+
codesign: `#!/bin/sh
106+
for arg do bundle=$arg; done
107+
if [ "$1" = -dv ]; then printf 'TeamIdentifier=%s\\n' "$(cat "$bundle/.team")" >&2; exit 0; fi
108+
printf 'verify:%s\\n' "$bundle" >> "$FIXTURE_EVENTS"
109+
if [ "$bundle" = "$FIXTURE_APP" ] && [ "$(cat "$bundle/.version")" = 2.0.0 ]; then
110+
if kill -0 "$FIXTURE_PARENT" 2>/dev/null; then
111+
echo postverify-parent-alive >> "$FIXTURE_EVENTS"
112+
else
113+
echo postverify-parent-exited >> "$FIXTURE_EVENTS"
114+
fi
115+
if [ "\${FIXTURE_FAIL_INSTALLED:-0}" = 1 ]; then exit 31; fi
116+
fi
117+
[ -f "$bundle/.signature-valid" ] || exit 32
118+
`,
119+
spctl: `#!/bin/sh
120+
for arg do bundle=$arg; done
121+
printf 'assess:%s\\n' "$bundle" >> "$FIXTURE_EVENTS"
122+
[ -f "$bundle/.gatekeeper-valid" ] || exit 33
123+
`,
124+
open: `#!/bin/sh
125+
printf 'open:%s\\n' "$*" >> "$FIXTURE_EVENTS"
126+
`,
127+
};
128+
for (const [name, contents] of Object.entries(stubs)) {
129+
NodeFS.writeFileSync(NodePath.join(bin, name), contents, { mode: 0o755 });
130+
}
131+
const original = NodeFS.readFileSync(
132+
new URL("./install-macos-update.sh", import.meta.url),
133+
"utf8",
134+
);
135+
const originalPath = "PATH=/usr/bin:/bin:/usr/sbin:/sbin";
136+
NodeAssert.equal(original.split(originalPath).length - 1, 1, "one fixed PATH assignment");
137+
const fixturePath = `PATH='${bin.replaceAll("'", "'\\''")}:/usr/bin:/bin:/usr/sbin:/sbin'`;
138+
const helper = NodePath.join(dir, "installer.sh");
139+
NodeFS.writeFileSync(helper, original.replace(originalPath, fixturePath), { mode: 0o755 });
140+
const env = {
141+
...process.env,
142+
FIXTURE_APP: app,
143+
FIXTURE_EVENTS: events,
144+
FIXTURE_PARENT: "99999999",
145+
};
146+
const prepare = () => run("/bin/sh", [helper, "prepare", archive, app, "2.0.0"], { env });
147+
return { dir, app, archive, expected, helper, env, events, prepare, clean };
148+
} catch (error) {
149+
clean();
150+
throw error;
151+
}
152+
}
153+
154+
export async function startParent() {
155+
const child = NodeChildProcess.spawn(
156+
process.execPath,
157+
["-e", "process.stdin.resume();process.stdin.on('end',()=>process.exit(0));"],
158+
{ stdio: ["pipe", "ignore", "ignore"] },
159+
);
160+
await NodeEvents.once(child, "spawn");
161+
return child;
162+
}
163+
164+
export async function stopParent(child) {
165+
if (child.exitCode === null && child.signalCode === null) {
166+
const exited = NodeEvents.once(child, "exit");
167+
child.stdin.end();
168+
await exited;
169+
}
170+
}
171+
172+
export async function install(fixture, { relaunch = true, failInstalled = false } = {}) {
173+
const parent = await startParent();
174+
let child;
175+
let watchdog;
176+
let stdout = "";
177+
let stderr = "";
178+
try {
179+
const prepared = fixture.prepare();
180+
NodeAssert.equal(prepared.status, 0, prepared.stderr);
181+
const candidate = prepared.stdout.trim();
182+
const stage = NodePath.dirname(candidate);
183+
child = NodeChildProcess.spawn(
184+
"/bin/sh",
185+
[fixture.helper, "install", candidate, fixture.app, String(parent.pid), String(relaunch)],
186+
{
187+
env: {
188+
...fixture.env,
189+
FIXTURE_PARENT: String(parent.pid),
190+
FIXTURE_FAIL_INSTALLED: failInstalled ? "1" : "0",
191+
},
192+
stdio: ["ignore", "pipe", "pipe"],
193+
},
194+
);
195+
const closed = NodeEvents.once(child, "close");
196+
watchdog = setTimeout(() => child.kill("SIGTERM"), 8_000);
197+
child.stdout.on("data", (chunk) => {
198+
stdout += chunk;
199+
});
200+
child.stderr.on("data", (chunk) => {
201+
stderr += chunk;
202+
});
203+
await new Promise((resolve, reject) => {
204+
const timer = setTimeout(
205+
() => reject(new Error("readiness absent while fixture parent lives")),
206+
3_000,
207+
);
208+
const onData = () => {
209+
if (stdout.includes("ready\n")) {
210+
clearTimeout(timer);
211+
child.stdout.off("data", onData);
212+
resolve();
213+
}
214+
};
215+
child.stdout.on("data", onData);
216+
child.once("close", (code) => {
217+
clearTimeout(timer);
218+
if (!stdout.includes("ready\n"))
219+
reject(new Error(`installer exited ${code} before ready: ${stderr}`));
220+
});
221+
});
222+
NodeAssert.equal(isAlive(parent.pid), true, "ready precedes fixture parent exit");
223+
NodeAssert.equal(NodeFS.readFileSync(NodePath.join(fixture.app, ".version"), "utf8"), "1.0.0");
224+
NodeAssert.equal(NodeFS.existsSync(candidate), true, "candidate remains staged at readiness");
225+
NodeAssert.equal(
226+
NodeFS.existsSync(`${fixture.app}.update-lock`),
227+
true,
228+
"ready follows lock acquisition",
229+
);
230+
NodeAssert.equal(NodeFS.readFileSync(fixture.events, "utf8").includes("open:"), false);
231+
await stopParent(parent);
232+
const [status] = await closed;
233+
return {
234+
status,
235+
stdout,
236+
stderr,
237+
stage,
238+
candidate,
239+
log: NodeFS.readFileSync(NodePath.join(stage, "install.log"), "utf8"),
240+
events: NodeFS.readFileSync(fixture.events, "utf8"),
241+
};
242+
} finally {
243+
clearTimeout(watchdog);
244+
await stopParent(parent);
245+
if (child && child.exitCode === null && child.signalCode === null) {
246+
const closed = NodeEvents.once(child, "close");
247+
child.kill("SIGTERM");
248+
await closed;
249+
}
250+
}
251+
}
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
#!/bin/sh
2+
# Keep the publisher's signed bundle intact; never patch or re-sign downloaded apps.
3+
set -eu
4+
PATH=/usr/bin:/bin:/usr/sbin:/sbin
5+
export PATH
6+
7+
fail() { echo "$*" >&2; exit 1; }
8+
team() { codesign -dv "$1" 2>&1 | sed -n 's/^TeamIdentifier=//p'; }
9+
identifier() { /usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$1/Contents/Info.plist"; }
10+
launch() { open --env "T3CODE_DESKTOP_UPDATE_INSTALLER=$0" --env T3CODE_DISABLE_AUTO_UPDATE=false "$app"; }
11+
verify() {
12+
codesign --verify --deep --strict "$1" >&2
13+
[ "$(team "$1")" = "$signer" ] || fail "Update publisher does not match the installed app."
14+
[ "$(identifier "$1")" = "$bundle_id" ] || fail "Update bundle identifier does not match the installed app."
15+
}
16+
17+
[ "$#" -ge 1 ] || fail "Expected prepare or install."
18+
phase=$1; shift
19+
case "$phase" in
20+
prepare)
21+
[ "$#" -eq 3 ] || fail "Expected prepare ARCHIVE APP VERSION."
22+
archive=$1; app=$2; version=$3
23+
case "$app" in /*.app) ;; *) fail "Expected an absolute app bundle path." ;; esac
24+
[ -d "$app" ] && [ ! -L "$app" ] || fail "Invalid app bundle."
25+
codesign --verify --deep --strict "$app" >&2
26+
signer=$(team "$app"); bundle_id=$(identifier "$app")
27+
[ -n "$signer" ] && [ "$signer" != 'not set' ] || fail "Installed app has no signing team."
28+
stage=$(mktemp -d "$(dirname "$app")/.t3-update.XXXXXXXX")
29+
trap 'rm -rf "$stage"' EXIT
30+
trap 'exit 1' HUP INT TERM
31+
ditto -x -k "$archive" "$stage/extracted" >&2
32+
candidate="$stage/extracted/$(basename "$app")"
33+
verify "$candidate"
34+
actual=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$candidate/Contents/Info.plist")
35+
[ "$actual" = "$version" ] || fail "Downloaded update version does not match T3's selected version."
36+
# Stock nightlies would remove this integration on the next restart.
37+
grep -a -q 'T3CODE_DESKTOP_UPDATE_INSTALLER' "$candidate/Contents/Resources/app.asar" ||
38+
fail "Downloaded build lacks external installer support; a signed build containing the patch is required."
39+
spctl --assess --type execute "$candidate" >&2
40+
mv "$candidate" "$stage/candidate.app"
41+
rm -rf "$stage/extracted"
42+
printf '%s\n' "$stage/candidate.app"
43+
trap - EXIT HUP INT TERM
44+
;;
45+
install)
46+
[ "$#" -eq 4 ] || fail "Expected install CANDIDATE APP PARENT_PID RELAUNCH."
47+
candidate=$1; app=$2; parent_pid=$3; relaunch=$4
48+
case "$parent_pid" in ''|*[!0-9]*|0|1) fail "Invalid parent PID." ;; esac
49+
case "$relaunch" in true|false) ;; *) fail "Invalid relaunch value." ;; esac
50+
stage=$(dirname "$candidate")
51+
case "$stage" in "$(dirname "$app")"/.t3-update.*) ;; *) fail "Invalid staging directory." ;; esac
52+
[ "$candidate" = "$stage/candidate.app" ] || fail "Invalid staged app path."
53+
[ -d "$app" ] && [ ! -L "$app" ] && [ ! -L "$stage" ] || fail "Invalid app or staging directory."
54+
signer=$(team "$app"); bundle_id=$(identifier "$app")
55+
[ -n "$signer" ] && [ "$signer" != 'not set' ] || fail "Installed app has no signing team."
56+
verify "$candidate"
57+
shlock -p "$$" -f "$app.update-lock" || fail "Another installation is running."
58+
moved_old=false
59+
rollback() {
60+
status=$?
61+
if [ "$moved_old" = true ]; then
62+
if [ -e "$app" ]; then mv "$app" "$stage/failed.app"; fi
63+
mv "$stage/previous.app" "$app"
64+
fi
65+
if [ "$status" -ne 0 ] && [ "$relaunch" = true ] && ! kill -0 "$parent_pid" 2>/dev/null; then
66+
launch || true
67+
fi
68+
rm -f "$app.update-lock"
69+
exit "$status"
70+
}
71+
trap rollback EXIT
72+
trap 'exit 1' HUP INT TERM
73+
exec 3>&1
74+
exec >> "$stage/install.log" 2>&1
75+
printf 'ready\n' >&3
76+
exec 3>&-
77+
attempts=0
78+
while kill -0 "$parent_pid" 2>/dev/null; do
79+
[ "$attempts" -lt 120 ] || fail "T3 did not exit; update was not installed."
80+
sleep 1
81+
attempts=$((attempts + 1))
82+
done
83+
mv "$app" "$stage/previous.app"
84+
moved_old=true
85+
mv "$candidate" "$app"
86+
verify "$app"
87+
if [ "$relaunch" = true ]; then launch; fi
88+
moved_old=false
89+
printf '%s\n' "$app" > "$stage/installed-app"
90+
# Keep one verified rollback bundle, leaving unrelated backups untouched.
91+
for previous in "$(dirname "$app")"/.t3-update.*; do
92+
[ "$previous" != "$stage" ] || continue
93+
[ ! -L "$previous" ] && [ -f "$previous/installed-app" ] || continue
94+
[ "$(cat "$previous/installed-app")" = "$app" ] || continue
95+
rm -rf "$previous"
96+
done
97+
;;
98+
*) fail "Unknown installer phase: $phase" ;;
99+
esac

0 commit comments

Comments
 (0)