@devries-cameron20 / t3code-1 / commits / 7681605d73
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): t3 update installs from the policy's update mirror (#29911)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 3, 2026 at 11:11 UTC 7681605d7375cfa25e72ca48db56bb76e2025f7e
9 files changed +345 -56
apps/server/src/cli/update.test.ts
+75 -5
@@ -18,7 +18,13 @@ import * as BootService from "../cloud/bootService.ts";
18 import { prunePinnedRuntimes } from "../cloud/pinnedRuntime.ts";
19 import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
20 import * as ProcessRunner from "../processRunner.ts";
21 -import { repointLauncher, resolveLauncherPath, resolveNewestVersion, runUpdate } from "./update.ts";
21 +import {
22 + repointLauncher,
23 + resolveLauncherPath,
24 + resolveMirrorVersion,
25 + resolveNewestVersion,
26 + runUpdate,
27 +} from "./update.ts";
28
29 // lsof listing one process, so prune sees a process list in which no runtime is running.
30 const unrelatedLsof = ProcessRunner.ProcessRunner.of({
@@ -60,10 +66,59 @@ it.effect("authenticates each release page until the requested channel is found"
66 }),
67 );
68
69 +it.effect("reads the newest version from the update feed file a mirror publishes", () =>
70 + Effect.gen(function* () {
71 + const requested: string[] = [];
72 + const mirror = {
73 + organization: "Example Corp",
74 + feedUrl: "https://updates.example.com/t3code/?token=abc",
75 + };
76 + const resolve = (
77 + channel: "stable" | "nightly" | "preview",
78 + platform: NodeJS.Platform,
79 + arch: string,
80 + feed: string,
81 + ) =>
82 + resolveMirrorVersion(mirror, channel).pipe(
83 + Effect.map((version): string => version),
84 + Effect.catchTags({ CliUpdateError: (error) => Effect.succeed(`error: ${error.reason}`) }),
85 + Effect.provideService(HostProcess.Platform, platform),
86 + Effect.provideService(HostProcess.Architecture, arch),
87 + Effect.provideService(
88 + HttpClient.HttpClient,
89 + HttpClient.make((request) => {
90 + requested.push(request.url);
91 + return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(feed)));
92 + }),
93 + ),
94 + );
95 +
96 + assert.equal(
97 + yield* resolve("stable", "darwin", "arm64", "version: 1.4.0\nfiles: []\n"),
98 + "1.4.0",
99 + );
100 + assert.equal(
101 + yield* resolve("nightly", "linux", "arm64", "version: '1.5.0-nightly.20261101.2'\n"),
102 + "1.5.0-nightly.20261101.2",
103 + );
104 + assert.deepStrictEqual(requested, [
105 + "https://updates.example.com/t3code/latest-mac.yml?token=abc",
106 + "https://updates.example.com/t3code/nightly-linux-arm64.yml?token=abc",
107 + ]);
108 + // A feed for the wrong track is not trusted to mean the requested one.
109 + assert.include(
110 + yield* resolve("stable", "win32", "x64", "version: 1.5.0-nightly.20261101.2\n"),
111 + "Could not read latest.yml from Example Corp's update mirror.",
112 + );
113 + assert.include(yield* resolve("preview", "win32", "x64", ""), "has no preview builds");
114 + }),
115 +);
116 +
117 it.layer(NodeServices.layer)("t3 update under a managed policy", (it) => {
118 const runWithPolicy = (
119 updates: ManagedUpdatesPolicy,
120 input: { readonly channel?: "stable" | "nightly"; readonly requestedVersion?: string } = {},
121 + httpClient = HttpClient.make(() => Effect.die("unexpected release lookup")),
122 ) =>
123 runUpdate({
124 baseDir: "/unused",
@@ -85,10 +140,7 @@ it.layer(NodeServices.layer)("t3 update under a managed policy", (it) => {
140 // Refusals happen before the update touches the network, the service, or a process.
141 Layer.mock(BootService.BootService, {}),
142 Layer.mock(ProcessRunner.ProcessRunner, {}),
88 - Layer.succeed(
89 - HttpClient.HttpClient,
90 - HttpClient.make(() => Effect.die("unexpected release lookup")),
91 - ),
143 + Layer.succeed(HttpClient.HttpClient, httpClient),
144 ),
145 ),
146 );
@@ -118,6 +170,24 @@ it.layer(NodeServices.layer)("t3 update under a managed policy", (it) => {
170 }
171 }),
172 );
173 +
174 + it.effect("looks for updates on the policy's mirror, never the public releases", () =>
175 + Effect.gen(function* () {
176 + const requested: string[] = [];
177 + const error = yield* runWithPolicy(
178 + { mode: "auto", feedUrl: "https://updates.example.com/t3code" },
179 + { channel: "stable" },
180 + HttpClient.make((request) => {
181 + requested.push(new URL(request.url).origin);
182 + return Effect.succeed(
183 + HttpClientResponse.fromWeb(request, new Response("", { status: 404 })),
184 + );
185 + }),
186 + );
187 + assert.include(error.message, "from Example Corp's update mirror");
188 + assert.deepStrictEqual(requested, ["https://updates.example.com"]);
189 + }),
190 + );
191 });
192
193 it.layer(NodeServices.layer)("t3 update launcher", (it) => {
apps/server/src/cli/update.ts
+62 -16
@@ -5,6 +5,8 @@ import {
5 cliReleaseIndexPageUrl,
6 cliReleaseChannelOf,
7 newestCliReleaseVersion,
8 + releaseAssetUrl,
9 + updateFeedFileName,
10 type CliReleaseChannel,
11 } from "@t3tools/shared/cliRelease";
12 import * as Console from "effect/Console";
@@ -24,6 +26,7 @@ import {
26 ensurePinnedRuntimeInstalled,
27 launcherOwnsVersionsDir,
28 pinnedRuntimeCommand,
29 + isUnpublishedRelease,
30 PinnedRuntimeInstallError,
31 pinnedRuntimePaths,
32 pinnedRuntimeVersionsDir,
@@ -33,7 +36,7 @@ import {
36 } from "../cloud/pinnedRuntime.ts";
37 import { compareExactServiceVersions, isExactServiceVersion } from "../cloud/serviceProtocol.ts";
38 import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
36 -import { managedUpdateRefusal } from "../policy/managedUpdates.ts";
39 +import { managedUpdateMirror, managedUpdateRefusal } from "../policy/managedUpdates.ts";
40 import * as ProcessRunner from "../processRunner.ts";
41 import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
42 import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
@@ -94,6 +97,47 @@ export const resolveNewestVersion = Effect.fn("cli.update.resolve_newest")(funct
97 return yield* new CliUpdateError({ reason: `No published ${channel} release was found.` });
98 });
99
100 +/** The version an update mirror's feed file for this platform offers on `channel`. */
101 +export const resolveMirrorVersion = Effect.fn("cli.update.resolve_mirror")(function* (
102 + mirror: { readonly organization: string; readonly feedUrl: string },
103 + channel: CliReleaseChannel,
104 +) {
105 + if (channel === "preview") {
106 + return yield* new CliUpdateError({
107 + reason: `${mirror.organization}'s update mirror has no preview builds.`,
108 + });
109 + }
110 + const httpClient = yield* HttpClient.HttpClient;
111 + const fileName = updateFeedFileName(
112 + channel === "nightly" ? "nightly" : "latest",
113 + yield* HostProcess.Platform,
114 + yield* HostProcess.Architecture,
115 + );
116 + const url = releaseAssetUrl(mirror.feedUrl, fileName);
117 + // Not the URL, whose query can hold the mirror's access token.
118 + const unreadable = new CliUpdateError({
119 + reason: `Could not read ${fileName} from ${mirror.organization}'s update mirror.`,
120 + });
121 + const body = yield* httpClient.get(url).pipe(
122 + Effect.flatMap(HttpClientResponse.filterStatusOk),
123 + Effect.flatMap((response) => response.text),
124 + Effect.mapError(() => unreadable),
125 + Effect.timeoutOrElse({
126 + duration: RELEASE_INDEX_TIMEOUT,
127 + orElse: () => Effect.fail(unreadable),
128 + }),
129 + );
130 + const version = /^version:\s*["']?([^"'\s]+)/m.exec(body)?.[1];
131 + if (
132 + version === undefined ||
133 + !isExactServiceVersion(version) ||
134 + cliReleaseChannelOf(version) !== channel
135 + ) {
136 + return yield* unreadable;
137 + }
138 + return version;
139 +});
140 +
141 /**
142 * Only a launcher that already points into this home's `runtime/versions` tree is touched; a
143 * plain copy of the executable, or a launcher for some other install, is left alone. It is
@@ -320,6 +364,7 @@ export const runUpdate = Effect.fn("cli.update.run")(function* (input: {
364 const httpClient = yield* HttpClient.HttpClient;
365 const service = yield* BootService.BootService;
366 const policy = yield* ManagedPolicy.ManagedPolicy;
367 + const mirror = managedUpdateMirror(policy.document);
368
369 const currentVersion = packageJson.version;
370 const channel = input.channel ?? cliReleaseChannelOf(currentVersion);
@@ -338,9 +383,11 @@ export const runUpdate = Effect.fn("cli.update.run")(function* (input: {
383 const progress = createUpdateProgress();
384 progress.status("Checking for updates...");
385 const targetVersion = yield* (
341 - input.requestedVersion === undefined
342 - ? resolveNewestVersion(channel)
343 - : Effect.succeed(input.requestedVersion)
386 + input.requestedVersion !== undefined
387 + ? Effect.succeed(input.requestedVersion)
388 + : mirror === undefined
389 + ? resolveNewestVersion(channel)
390 + : resolveMirrorVersion(mirror, channel)
391 ).pipe(Effect.ensuring(Effect.sync(progress.finish)));
392 const targetChannel = cliReleaseChannelOf(targetVersion);
393
@@ -455,7 +502,8 @@ export const runUpdate = Effect.fn("cli.update.run")(function* (input: {
502 httpClient,
503 platform,
504 arch,
458 - releaseBaseUrl: environment[CLI_RELEASE_BASE_URL_ENV]?.trim() || undefined,
505 + releaseBaseUrl: mirror?.feedUrl ?? (environment[CLI_RELEASE_BASE_URL_ENV]?.trim() || undefined),
506 + requirePublishedRelease: mirror !== undefined,
507 validate: (paths) =>
508 runner
509 .run({
@@ -481,17 +529,15 @@ export const runUpdate = Effect.fn("cli.update.run")(function* (input: {
529 ),
530 }).pipe(
531 Effect.ensuring(Effect.sync(progress.finish)),
484 - Effect.catchIf(
485 - (error): error is PinnedRuntimeInstallError =>
486 - error._tag === "PinnedRuntimeInstallError" &&
487 - error.step.startsWith("downloading the t3 release checksums") &&
488 - String(error.cause).includes("404"),
489 - () =>
490 - Effect.fail(
491 - new CliUpdateError({
492 - reason: `No release archive was published for t3@${targetVersion}.`,
493 - }),
494 - ),
532 + Effect.catchIf(isUnpublishedRelease, () =>
533 + Effect.fail(
534 + new CliUpdateError({
535 + reason:
536 + mirror === undefined
537 + ? `No release archive was published for t3@${targetVersion}.`
538 + : `${mirror.organization}'s update mirror has no t3@${targetVersion} for this machine.`,
539 + }),
540 + ),
541 ),
542 );
543
apps/server/src/cloud/pinnedRuntime.test.ts
+72 -1
@@ -16,6 +16,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
16 import * as ProcessRunner from "../processRunner.ts";
17 import {
18 ensurePinnedRuntimeInstalled,
19 + isUnpublishedRelease,
20 pinnedRuntimeCommand,
21 pinnedRuntimePaths,
22 PinnedRuntimeInstallError,
@@ -39,7 +40,7 @@ const validChecksums = archiveHex(archiveBytes).pipe(
40 const releaseHttpClient = (checksums: string, requests: string[] = []) =>
41 HttpClient.make((request) => {
42 requests.push(request.url);
42 - const body = request.url.endsWith("/SHA256SUMS") ? checksums : archiveBytes;
43 + const body = new URL(request.url).pathname.endsWith("/SHA256SUMS") ? checksums : archiveBytes;
44 return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(body)));
45 });
46 const extractingRunner = (fs: FileSystem.FileSystem, path: Path.Path, commands: string[] = []) =>
@@ -155,6 +156,40 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
156 }),
157 );
158
159 + it.effect("reports a release that lists an archive it does not serve as unpublished", () =>
160 + Effect.gen(function* () {
161 + const fs = yield* FileSystem.FileSystem;
162 + const path = yield* Path.Path;
163 + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-archive-missing-" });
164 + const checksums = yield* validChecksums;
165 + const failsWith = (status: number) =>
166 + ensurePinnedRuntimeInstalled({
167 + baseDir,
168 + version,
169 + fs,
170 + path,
171 + platform: "linux",
172 + arch: "x64",
173 + httpClient: HttpClient.make((request) =>
174 + Effect.succeed(
175 + HttpClientResponse.fromWeb(
176 + request,
177 + request.url.endsWith("/SHA256SUMS")
178 + ? new Response(checksums)
179 + : new Response("", { status }),
180 + ),
181 + ),
182 + ),
183 + // "404" in the mirror's path must not read a server error as a missing release.
184 + releaseBaseUrl: "https://updates.example.com/404/t3code",
185 + runner: extractingRunner(fs, path),
186 + validate: () => Effect.die("must not validate a missing archive"),
187 + }).pipe(Effect.flip);
188 + assert.isTrue(isUnpublishedRelease(yield* failsWith(404)));
189 + assert.isFalse(isUnpublishedRelease(yield* failsWith(500)));
190 + }),
191 + );
192 +
193 it.effect("refuses an archive whose checksum does not match the release", () =>
194 Effect.gen(function* () {
195 const fs = yield* FileSystem.FileSystem;
@@ -267,6 +302,42 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
302 }),
303 );
304
305 + it.effect("reuses a cached runtime under a mirror only while the mirror lists it", () =>
306 + Effect.gen(function* () {
307 + const fs = yield* FileSystem.FileSystem;
308 + const path = yield* Path.Path;
309 + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-mirror-" });
310 + const cached = pinnedRuntimePaths(path, baseDir, version, "linux");
311 + yield* fs.makeDirectory(path.dirname(cached.entryPath), { recursive: true });
312 + yield* fs.writeFileString(cached.entryPath, "#!/bin/sh\n");
313 + yield* fs.writeFileString(cached.sentinelPath, `${version}\n`);
314 + const install = (checksums: string, requests: string[]) =>
315 + ensurePinnedRuntimeInstalled({
316 + baseDir,
317 + version,
318 + fs,
319 + path,
320 + platform: "linux",
321 + arch: "x64",
322 + httpClient: releaseHttpClient(checksums, requests),
323 + // A signed mirror URL keeps its query on every file it serves.
324 + releaseBaseUrl: "https://updates.example.com/t3code/?token=abc",
325 + requirePublishedRelease: true,
326 + runner: extractingRunner(fs, path),
327 + validate: () => Effect.void,
328 + });
329 +
330 + const withdrawn = yield* install("", []).pipe(Effect.flip);
331 + assert.include(withdrawn.message, `finding ${archiveName} in the t3 release checksums`);
332 + const requests: string[] = [];
333 + assert.equal((yield* install(yield* validChecksums, requests)).entryPath, cached.entryPath);
334 + // Listed, so the cached runtime is used without downloading it again.
335 + assert.deepEqual(requests, [
336 + `https://updates.example.com/t3code/v${version}/SHA256SUMS?token=abc`,
337 + ]);
338 + }),
339 + );
340 +
341 it.effect("preserves a completed runtime when validation fails", () =>
342 Effect.gen(function* () {
343 const fs = yield* FileSystem.FileSystem;
apps/server/src/cloud/pinnedRuntime.ts
+50 -21
@@ -9,14 +9,15 @@ import * as Schema from "effect/Schema";
9 import * as Option from "effect/Option";
10 import * as Stream from "effect/Stream";
11 import * as Semaphore from "effect/Semaphore";
12 -import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
12 +import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
13
14 import {
15 CLI_RELEASE_CHECKSUMS_FILE,
16 cliArchiveFileName,
17 cliArchivePlatformKey,
18 cliArchiveTarCommand,
19 - cliReleaseDownloadBaseUrl,
19 + cliReleaseAssetUrl,
20 + type CliArchivePlatformKey,
21 parseChecksums,
22 } from "@t3tools/shared/cliRelease";
23
@@ -111,6 +112,8 @@ interface PinnedRuntimeInstallInput {
112 readonly arch: string;
113 readonly httpClient: HttpClient.HttpClient;
114 readonly releaseBaseUrl?: string | undefined;
115 + /** Reuse a cached runtime only while the release source still lists it, as a policy mirror does. */
116 + readonly requirePublishedRelease?: boolean;
117 readonly onProgress?: (progress: PinnedRuntimeProgress) => void;
118 }
119
@@ -178,28 +181,11 @@ const installFromArchive = Effect.fn("cloud.pinned_runtime.install_archive")(fun
181 });
182 }
183 const httpClient = input.httpClient;
181 - const baseUrl = cliReleaseDownloadBaseUrl(input.version, input.releaseBaseUrl);
182 - const fileName = cliArchiveFileName(input.version, platformKey);
183 -
184 input.onProgress?.({ stage: "download", received: 0, total: undefined });
185 - const checksums = parseChecksums(
186 - new TextDecoder().decode(
187 - yield* fetchReleaseAsset(
188 - httpClient,
189 - `${baseUrl}/${CLI_RELEASE_CHECKSUMS_FILE}`,
190 - "downloading the t3 release checksums",
191 - ),
192 - ),
193 - );
194 - const expected = checksums.get(fileName);
195 - if (expected === undefined) {
196 - return yield* new PinnedRuntimeInstallError({
197 - step: `finding ${fileName} in the t3 release checksums`,
198 - });
199 - }
185 + const { fileName, expected } = yield* publishedArchive(input, platformKey);
186 const archive = yield* fetchReleaseAsset(
187 httpClient,
202 - `${baseUrl}/${fileName}`,
188 + cliReleaseAssetUrl(input.version, fileName, input.releaseBaseUrl),
189 "downloading the t3 release archive",
190 input.onProgress,
191 );
@@ -248,6 +234,40 @@ const installFromArchive = Effect.fn("cloud.pinned_runtime.install_archive")(fun
234 yield* fs.remove(archivePath, { force: true }).pipe(Effect.ignore);
235 });
236
237 +/** The release's archive for this machine and its checksum; fails when the release lists none. */
238 +const publishedArchive = Effect.fn("cloud.pinned_runtime.published_archive")(function* (
239 + input: PinnedRuntimeInstallInput,
240 + platformKey: CliArchivePlatformKey,
241 +) {
242 + const fileName = cliArchiveFileName(input.version, platformKey);
243 + const checksums = parseChecksums(
244 + new TextDecoder().decode(
245 + yield* fetchReleaseAsset(
246 + input.httpClient,
247 + cliReleaseAssetUrl(input.version, CLI_RELEASE_CHECKSUMS_FILE, input.releaseBaseUrl),
248 + "downloading the t3 release checksums",
249 + ),
250 + ),
251 + );
252 + const expected = checksums.get(fileName);
253 + if (expected === undefined) {
254 + return yield* new PinnedRuntimeInstallError({
255 + step: `finding ${fileName} in the t3 release checksums`,
256 + });
257 + }
258 + return { fileName, expected };
259 +});
260 +
261 +const isPinnedRuntimeInstallError = Schema.is(PinnedRuntimeInstallError);
262 +
263 +/** Whether an install failed because the release source does not publish the version for this machine. */
264 +export const isUnpublishedRelease = (error: unknown): error is PinnedRuntimeInstallError =>
265 + isPinnedRuntimeInstallError(error) &&
266 + (error.step.startsWith("finding ") ||
267 + (error.step.startsWith("downloading the t3 release") &&
268 + HttpClientError.isHttpClientError(error.cause) &&
269 + error.cause.response?.status === 404));
270 +
271 const installPinnedRuntime = Effect.fn("cloud.pinned_runtime.ensure_installed")(function* (
272 input: PinnedRuntimeInstallInput,
273 ) {
@@ -265,6 +285,15 @@ const installPinnedRuntime = Effect.fn("cloud.pinned_runtime.ensure_installed")(
285 const alreadyPinned =
286 entryExists && Option.isSome(sentinel) && sentinel.value.trim() === input.version;
287 if (alreadyPinned) {
288 + if (input.requirePublishedRelease === true) {
289 + const platformKey = cliArchivePlatformKey(input.platform, input.arch);
290 + if (platformKey === undefined) {
291 + return yield* new PinnedRuntimeInstallError({
292 + step: `selecting a t3 release archive for ${input.platform}-${input.arch}`,
293 + });
294 + }
295 + yield* publishedArchive(input, platformKey);
296 + }
297 input.onProgress?.({ stage: "cached" });
298 yield* input.validate(paths);
299 return paths;
apps/server/src/cloud/selfUpdate.test.ts
+24 -5
@@ -36,9 +36,10 @@ interface HarnessOptions {
36 }
37
38 const archiveBytes = new TextEncoder().encode("not really a tarball");
39 -const releaseHttpClient = (order: string[], beforeDownload?: Effect.Effect<void>) =>
39 +const releaseHttpClient = (order: string[], urls: string[], beforeDownload?: Effect.Effect<void>) =>
40 HttpClient.make((request) =>
41 Effect.gen(function* () {
42 + urls.push(request.url);
43 if (request.url.endsWith("/SHA256SUMS")) {
44 const digest = yield* Effect.promise(() => crypto.subtle.digest("SHA-256", archiveBytes));
45 const hex = Array.from(new Uint8Array(digest), (byte) =>
@@ -62,6 +63,7 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
63 const path = yield* Path.Path;
64 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-self-update-test-" });
65 const order: string[] = [];
66 + const urls: string[] = [];
67 const runner = ProcessRunner.ProcessRunner.of({
68 run: (input) =>
69 Effect.gen(function* () {
@@ -141,7 +143,10 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
143 run: () => Effect.die("unexpected desktop app update run"),
144 },
145 ),
144 - Effect.provideService(HttpClient.HttpClient, releaseHttpClient(order, options.beforeDownload)),
146 + Effect.provideService(
147 + HttpClient.HttpClient,
148 + releaseHttpClient(order, urls, options.beforeDownload),
149 + ),
150 Effect.provideService(HostProcess.Platform, "linux"),
151 Effect.provideService(HostProcess.Architecture, "x64"),
152 Effect.provide(
@@ -151,7 +156,7 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
156 ),
157 ),
158 );
154 - return { selfUpdate, order };
159 + return { selfUpdate, order, urls };
160 });
161
162 it.layer(NodeServices.layer)("server self update", (it) => {
@@ -198,11 +203,17 @@ it.layer(NodeServices.layer)("server self update", (it) => {
203
204 it.effect("lets a user start an update, but only to stable without nightly", () =>
205 Effect.gen(function* () {
201 - const { selfUpdate, order } = yield* makeHarness({
206 + const { selfUpdate, order, urls } = yield* makeHarness({
207 policy: {
208 schemaVersion: 1,
209 organization: "Example Corp",
205 - limits: { updates: { mode: "auto", allowNightly: false } },
210 + limits: {
211 + updates: {
212 + mode: "auto",
213 + allowNightly: false,
214 + feedUrl: "https://updates.example.com/t3code/",
215 + },
216 + },
217 },
218 });
219 expect(
@@ -210,7 +221,15 @@ it.layer(NodeServices.layer)("server self update", (it) => {
221 .reason,
222 ).toBe("Example Corp manages T3 Code updates. Only stable releases can be installed.");
223 expect(order).toEqual([]);
224 + // The mirror lists only 1.1.0's archive.
225 + expect((yield* selfUpdate.update({ targetVersion: "1.2.0" }).pipe(Effect.flip)).reason).toBe(
226 + "Example Corp's update mirror has no t3@1.2.0 for this machine.",
227 + );
228 expect((yield* selfUpdate.update({ targetVersion: "1.1.0" })).updateId).toBe("launcher-id");
229 + // The release comes from the policy's mirror, not GitHub.
230 + expect(urls.length).toBeGreaterThan(0);
231 + for (const url of urls)
232 + expect(url).toMatch(/^https:\/\/updates\.example\.com\/t3code\/v1\.[12]\.0\//);
233 }),
234 );
235
apps/server/src/cloud/selfUpdate.ts
+13 -5
@@ -31,10 +31,11 @@ import * as ServerConfig from "../config.ts";
31 import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
32 import { databaseMigrationHead } from "../persistence/databaseMigrationHead.ts";
33 import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
34 -import { managedUpdateRefusal } from "../policy/managedUpdates.ts";
34 +import { managedUpdateMirror, managedUpdateRefusal } from "../policy/managedUpdates.ts";
35 import * as ProcessRunner from "../processRunner.ts";
36 import {
37 ensurePinnedRuntimeInstalled,
38 + isUnpublishedRelease,
39 pinnedRuntimeCommand,
40 PinnedRuntimeInstallError,
41 pinnedRuntimePaths,
@@ -132,9 +133,10 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () {
133 const platform = yield* HostProcess.Platform;
134 const arch = yield* HostProcess.Architecture;
135 const httpClient = yield* HttpClient.HttpClient;
135 - const releaseBaseUrl = Option.getOrUndefined(
136 - yield* Config.String(CLI_RELEASE_BASE_URL_ENV).pipe(Config.option),
137 - );
136 + const mirror = managedUpdateMirror(policy.document);
137 + const releaseBaseUrl =
138 + mirror?.feedUrl ??
139 + Option.getOrUndefined(yield* Config.String(CLI_RELEASE_BASE_URL_ENV).pipe(Config.option));
140 const inFlight = yield* Ref.make(false);
141
142 yield* pruneRuntimesOnStart({ baseDir: serverConfig.baseDir, managed: launcher.managed }).pipe(
@@ -209,6 +211,7 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () {
211 platform,
212 arch,
213 releaseBaseUrl,
214 + requirePublishedRelease: mirror !== undefined,
215 validate: (runtime) =>
216 runner
217 .run({
@@ -282,7 +285,12 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () {
285 Effect.mapError((error) =>
286 error._tag === "PinnedRuntimePreflightBlockedError"
287 ? failWith(error.reason, error)
285 - : failWith(`Could not prepare t3@${targetVersion}.`, error),
288 + : mirror !== undefined && isUnpublishedRelease(error)
289 + ? failWith(
290 + `${mirror.organization}'s update mirror has no t3@${targetVersion} for this machine.`,
291 + error,
292 + )
293 + : failWith(`Could not prepare t3@${targetVersion}.`, error),
294 ),
295 );
296
apps/server/src/policy/managedUpdates.ts
+11
@@ -5,6 +5,17 @@ import {
5 } from "@t3tools/contracts";
6 import type { CliReleaseChannel } from "@t3tools/shared/cliRelease";
7
8 +/**
9 + * The update mirror the policy sends updates to, or `undefined` for the public releases. It wins
10 + * over the environment, which a user can set.
11 + */
12 +export function managedUpdateMirror(document: ManagedPolicyDocument | undefined) {
13 + const feedUrl = document?.limits?.updates?.feedUrl;
14 + return feedUrl === undefined || document === undefined
15 + ? undefined
16 + : { organization: document.organization, feedUrl };
17 +}
18 +
19 /**
20 * Why the managed policy refuses an update a user or maintainer asked for, or `undefined` when it
21 * allows it. The server never updates on its own, so `auto` allows every explicit request.
docs/user/managed-policy.md
+7 -3
@@ -250,9 +250,13 @@ starts the binary you set.
250
251 - `mode`: `auto` keeps the normal update flow. `off` stops T3 Code from checking for updates, for
252 machines that get T3 Code through device management.
253 -- `feedUrl`: the desktop app updates from your own mirror of the release feed instead of GitHub.
254 - Publish only the versions you have approved. The `t3` command-line server updates through npm,
255 - so pin it with your package tooling.
253 +- `feedUrl`: T3 Code updates from your own mirror instead of GitHub: the desktop app, `t3 update`,
254 + and updates started from another device. Publish only the versions you have approved, laid out
255 + as on a GitHub release. The release's update files (`latest.yml`, `latest-mac.yml`,
256 + `latest-linux.yml`, `latest-linux-arm64.yml`, and their `nightly` versions if you allow nightly)
257 + and the desktop installers they list go at the URL's root. The release's `t3-*` archives and
258 + `SHA256SUMS` go under `v<version>/`. A `t3` run through `npx` comes from npm, so pin it with your
259 + package tooling.
260 - `allowNightly: false`: the nightly channel is unavailable.
261
262 ## What a policy does not cover
packages/shared/src/cliRelease.ts
+31
@@ -50,6 +50,22 @@ export function cliReleaseDownloadBaseUrl(
50 return `${(baseUrl?.trim() || CLI_RELEASE_DEFAULT_BASE_URL).replace(/\/+$/, "")}/v${version}`;
51 }
52
53 +/** `segments` added to `baseUrl`'s path, keeping its query, such as a signed mirror URL's token. */
54 +export function releaseAssetUrl(baseUrl: string, ...segments: ReadonlyArray<string>): string {
55 + const url = new URL(baseUrl);
56 + url.pathname = [url.pathname.replace(/\/+$/, ""), ...segments.map(encodeURIComponent)].join("/");
57 + return url.toString();
58 +}
59 +
60 +/** A file of release `version`, from `baseUrl` laid out as GitHub's release downloads. */
61 +export function cliReleaseAssetUrl(
62 + version: string,
63 + fileName: string,
64 + baseUrl: string | undefined = CLI_RELEASE_DEFAULT_BASE_URL,
65 +): string {
66 + return releaseAssetUrl(baseUrl?.trim() || CLI_RELEASE_DEFAULT_BASE_URL, `v${version}`, fileName);
67 +}
68 +
69 export function parseChecksums(text: string): ReadonlyMap<string, string> {
70 const checksums = new Map<string, string>();
71 for (const line of text.split(/\r?\n/)) {
@@ -86,6 +102,21 @@ export function desktopUpdateChannelOf(version: string): "latest" | "nightly" {
102 return cliReleaseChannelOf(version) === "nightly" ? "nightly" : "latest";
103 }
104
105 +/**
106 + * The update feed file a desktop app on this platform reads, which an update mirror publishes at
107 + * its root beside the release's CLI archives.
108 + */
109 +export function updateFeedFileName(
110 + channel: "latest" | "nightly",
111 + platform: NodeJS.Platform,
112 + arch: string,
113 +): string {
114 + if (platform === "darwin") return `${channel}-mac.yml`;
115 + if (platform === "linux")
116 + return arch === "arm64" ? `${channel}-linux-arm64.yml` : `${channel}-linux.yml`;
117 + return `${channel}.yml`;
118 +}
119 +
120 /** Whether a track switch may install `found` after its database check cleared `checked`: any build
121 * on the switch's track at least as new, since later releases only add migrations. */
122 export function acceptsTrackSwitchRelease(