diff --git a/install b/install index 4e7d5a334f8..26d62ee2d2f 100755 --- a/install +++ b/install @@ -167,7 +167,7 @@ else package_scope="@opencode" if [ -z "$requested_version" ]; then - metadata=$(curl -fsSL https://update.opencode.ai/api/beta/cli/npm || true) + metadata=$(curl -fsSL https://opencode.ai/update/api/beta/cli/npm || true) specific_version=$(echo "$metadata" | sed -n 's/.*"version":"\([^"]*\)".*/\1/p') package=$(echo "$metadata" | sed -n 's/.*"package":"\([^"]*\)".*/\1/p') diff --git a/packages/cli/script/publish-aur.ts b/packages/cli/script/publish-aur.ts index 913cddbe4e3..ea51c017da5 100644 --- a/packages/cli/script/publish-aur.ts +++ b/packages/cli/script/publish-aur.ts @@ -4,6 +4,7 @@ import { $ } from "bun" import { mkdir, rm } from "node:fs/promises" import path from "node:path" import { fileURLToPath } from "node:url" +import { UpdateArtifact } from "../../../script/update-artifact" if (Script.channel !== "beta" && Script.channel !== "latest") { throw new Error("AUR publishing requires the beta or latest channel") @@ -15,19 +16,10 @@ if (!(beta ? /^\d+\.\d+\.\d+-beta[.-]\d+(?:\.\d+)?$/ : /^\d+\.\d+\.\d+$/).test(S throw new Error(`Expected a ${Script.channel} release version`) } -const response = await fetch(`https://update.opencode.ai/api/${Script.channel}/cli/npm`) -if (!response.ok) throw new Error(`Failed to resolve the ${Script.channel} release: ${response.status}`) -const release: { version: string; metadata?: { package?: string } } = await response.json() -if (release.version !== Script.version) throw new Error(`The active ${Script.channel} release is ${release.version}`) -if (release.metadata?.package !== "@opencode/cli" && release.metadata?.package !== "@opencode-ai/cli") { - throw new Error("The release did not identify a supported CLI package") -} - const dir = fileURLToPath(new URL("..", import.meta.url)) const outdir = path.join(dir, "dist", `aur-${name}`) const dryRun = process.argv.includes("--dry-run") const pkgver = Script.version.replaceAll("-", ".") -const scope = release.metadata.package.slice(0, -"/cli".length) const license = Bun.file(path.join(dir, "..", "..", "LICENSE")) await rm(outdir, { recursive: true, force: true }) @@ -43,12 +35,13 @@ const sources = await Promise.all( { arch: "x86_64", target: "linux-x64-baseline" }, { arch: "aarch64", target: "linux-arm64" }, ].map(async (item) => { + const directory = path.join(dir, "dist", `cli-${item.target}`) + const pkg: { name: string; version: string } = await Bun.file(path.join(directory, "package.json")).json() + if (pkg.version !== Script.version) throw new Error(`Unexpected version for ${pkg.name}: ${pkg.version}`) + const archive = Bun.file(path.join(directory, `${pkg.name.replace("@", "").replace("/", "-")}-${pkg.version}.tgz`)) const filename = `${name}-${pkgver}-${item.arch}.tgz` - const url = `https://registry.npmjs.org/${scope}/cli-${item.target}/-/cli-${item.target}-${Script.version}.tgz` - await $`curl --fail --location --retry 5 --retry-all-errors --output ${path.join(outdir, filename)} ${url}` - const sha256 = new Bun.CryptoHasher("sha256") - .update(await Bun.file(path.join(outdir, filename)).arrayBuffer()) - .digest("hex") + const url = `https://registry.npmjs.org/${pkg.name}/-/${pkg.name.split("/").at(-1)}-${pkg.version}.tgz` + const sha256 = new Bun.CryptoHasher("sha256").update(await archive.arrayBuffer()).digest("hex") return [`source_${item.arch}=('${filename}::${url}')`, `sha256sums_${item.arch}=('${sha256}')`].join("\n") }), ) @@ -86,9 +79,14 @@ console.log(`Prepared ${name} ${pkgver} in ${outdir}`) if (dryRun) process.exit(0) await $`git add PKGBUILD .SRCINFO LICENSE`.cwd(outdir) -if ((await $`git diff --cached --quiet`.cwd(outdir).nothrow()).exitCode === 0) { - console.log("AUR package is already up to date") - process.exit(0) +if ((await $`git diff --cached --quiet`.cwd(outdir).nothrow()).exitCode !== 0) { + await $`git commit -m ${`chore: update ${name} to ${pkgver}`}`.cwd(outdir) + await $`git push origin master`.cwd(outdir) } -await $`git commit -m ${`chore: update ${name} to ${pkgver}`}`.cwd(outdir) -await $`git push origin master`.cwd(outdir) +await UpdateArtifact.publish({ + channel: Script.channel, + name: "cli", + distribution: "aur", + version: Script.version, + metadata: { package: name }, +}) diff --git a/packages/cli/script/publish.ts b/packages/cli/script/publish.ts index 7bd46db8790..85dc3091a5b 100755 --- a/packages/cli/script/publish.ts +++ b/packages/cli/script/publish.ts @@ -18,10 +18,9 @@ async function publish(dir: string, name: string, version: string) { if (process.platform !== "win32") await $`chmod -R 755 .`.cwd(dir) const exists = !dryRun && (await published(name, version)) if (exists) console.log(`already published ${name}@${version}`) - if (!exists) { - await $`bun pm pack`.cwd(dir) - if (!dryRun) await $`npm publish *.tgz --access public --tag ${Script.channel}`.cwd(dir) - } + // Keep local tarballs available to downstream publishers when retrying a release. + await $`bun pm pack`.cwd(dir) + if (!exists && !dryRun) await $`npm publish *.tgz --access public --tag ${Script.channel}`.cwd(dir) } async function publishDistribution(input: { diff --git a/packages/cli/src/services/updater.ts b/packages/cli/src/services/updater.ts index d7a6de0b37b..b9b6e2c2c7b 100644 --- a/packages/cli/src/services/updater.ts +++ b/packages/cli/src/services/updater.ts @@ -123,7 +123,7 @@ const make = Effect.gen(function* () { const response = yield* Effect.tryPromise({ try: (signal) => fetch( - `https://update.opencode.ai/api/${encodeURIComponent(channel)}/${encodeURIComponent(OPENCODE_ARTIFACT)}/npm?current=${encodeURIComponent(OPENCODE_VERSION)}`, + `https://opencode.ai/update/api/${encodeURIComponent(channel)}/${encodeURIComponent(OPENCODE_ARTIFACT)}/npm?current=${encodeURIComponent(OPENCODE_VERSION)}`, { signal: AbortSignal.any([signal, AbortSignal.timeout(10_000)]), }, diff --git a/packages/updates/README.md b/packages/updates/README.md index 7e205db484e..ecf6ad00f39 100644 --- a/packages/updates/README.md +++ b/packages/updates/README.md @@ -3,11 +3,14 @@ The updates Worker serves all selected artifacts for a channel. ```sh -curl 'https://update.opencode.ai/api/latest' -curl 'https://update.opencode.ai/api/latest/cli' -curl 'https://update.opencode.ai/api/latest/cli/npm' +curl 'https://opencode.ai/update/api/latest' +curl 'https://opencode.ai/update/api/latest/cli' +curl 'https://opencode.ai/update/api/latest/cli/npm' ``` +The same Worker also serves the original `https://update.opencode.ai` hostname without +the `/update` prefix. Admin forms, pagination, and redirects preserve the request's mount. + ## Minimum releases Each channel/name/distribution can mark one retained artifact as `minimum`, independently @@ -35,13 +38,14 @@ Choose a minimum that older clients can install and that can itself consume the release. For the CLI package migration, retain a package-aware release published as `@opencode-ai/cli` as the minimum before activating releases under `@opencode/cli`. -The `/admin*` route must be protected by a Cloudflare Access self-hosted application. Configure the application with: +Both admin mounts must be protected by the same Cloudflare Access self-hosted application: -- Public hostname: `update.opencode.ai` -- Path: `admin*` +- Public hostname/path: `update.opencode.ai/admin*` +- Public hostname/path: `opencode.ai/update/admin*` - Policy: allow the OpenCode team identity group -The Worker has `workers_dev` and preview URLs disabled so the custom hostname is its only public entry point. +Configure Access before deploying the new Worker route. The Worker has `workers_dev` +and preview URLs disabled; it is exposed through its custom hostname and the `/update` routes. ## Request logging @@ -49,7 +53,8 @@ Every request reaching the Worker emits an unsampled event at request start to t Cloudflare lake stream through the `EVENTS` Pipelines binding. Events use `source: "update"`, `type: "request"`, an ISO `timestamp`, and a `payload` containing the method, path, `useragent`, `ip` (from Cloudflare's `CF-Connecting-IP` header), -country, and Cloudflare colo. Query strings, request bodies, cookies, and authorization +country, and Cloudflare colo. The path is normalized without `/update` so both mounts +share the existing analytics paths. Query strings, request bodies, cookies, and authorization headers are not included. Response status and duration are not recorded. Delivery runs in `waitUntil` without delaying the response. Delivery failures are @@ -63,7 +68,11 @@ has a single public deployment. ## Publishing -GitHub Actions publishes artifacts through `POST /api/publish` using a short-lived OIDC token with audience `https://update.opencode.ai`. The Worker accepts only tokens signed by GitHub for repository ID `975734319`, owner ID `66570915`, and `.github/workflows/publish.yml` on configured publishing refs. +GitHub Actions publishes artifacts through `POST https://opencode.ai/update/api/publish` +using a short-lived OIDC token with audience `https://update.opencode.ai`. The original +hostname and token audience remain supported. The Worker accepts only tokens signed by +GitHub for repository ID `975734319`, owner ID `66570915`, and `.github/workflows/publish.yml` +on configured publishing refs. Apply migrations and deploy from this directory: diff --git a/packages/updates/src/index.ts b/packages/updates/src/index.ts index 2eb239fbc90..68047a727c8 100644 --- a/packages/updates/src/index.ts +++ b/packages/updates/src/index.ts @@ -39,6 +39,12 @@ const githubKeys = createRemoteJWKSet(new URL("https://token.actions.githubuserc export default { async fetch(request: Request, env: Env, ctx: Pick): Promise { const url = new URL(request.url) + // The legacy hostname only exposes /admin, covered by its existing Access policy. + const prefix = + url.hostname !== "update.opencode.ai" && (url.pathname === "/update" || url.pathname.startsWith("/update/")) + ? "/update" + : "" + const pathname = url.pathname.slice(prefix.length) || "/" ctx.waitUntil( env.EVENTS.send([ { @@ -47,7 +53,7 @@ export default { timestamp: new Date().toISOString(), payload: { method: request.method, - path: url.pathname, + path: pathname, useragent: request.headers.get("user-agent"), ip: request.headers.get("cf-connecting-ip"), cf_country: request.cf?.country, @@ -57,14 +63,14 @@ export default { ]).catch(() => console.error("Failed to send update request event to the data lake")), ) - if (url.pathname === "/") return json({ service: "opencode-updates" }) - if (url.pathname === "/admin" && request.method === "GET") return admin(request, env) - if (url.pathname === "/admin/activate" && request.method === "POST") return markArtifact(request, env, "active") - if (url.pathname === "/admin/minimum" && request.method === "POST") return markArtifact(request, env, "minimum") - if (url.pathname === "/api/publish" && request.method === "POST") return publishArtifact(request, env) + if (pathname === "/") return json({ service: "opencode-updates" }) + if (pathname === "/admin" && request.method === "GET") return admin(request, env, prefix) + if (pathname === "/admin/activate" && request.method === "POST") return markArtifact(request, env, "active", prefix) + if (pathname === "/admin/minimum" && request.method === "POST") return markArtifact(request, env, "minimum", prefix) + if (pathname === "/api/publish" && request.method === "POST") return publishArtifact(request, env) if (request.method !== "GET") return new Response("Method not allowed", { status: 405 }) - const [root, ...path] = url.pathname.split("/").filter(Boolean) + const [root, ...path] = pathname.split("/").filter(Boolean) if (root !== "api" || path.length < 1 || path.length > 3 || !path.every(validIdentifier)) { return new Response("Not found", { status: 404 }) } @@ -143,7 +149,7 @@ function releaseVersion(input: string) { ) } -async function admin(request: Request, env: Env) { +async function admin(request: Request, env: Env, prefix: string) { const url = new URL(request.url) const requestedPage = Number.parseInt(url.searchParams.get("page") ?? "1", 10) const page = Number.isSafeInteger(requestedPage) && requestedPage > 0 ? requestedPage : 1 @@ -168,7 +174,7 @@ async function admin(request: Request, env: Env) { ${ artifact.active ? "" - : `
+ : ` @@ -176,7 +182,7 @@ async function admin(request: Request, env: Env) {
` } -
+ @@ -232,8 +238,8 @@ async function admin(request: Request, env: Env) { @@ -270,7 +276,7 @@ async function publishArtifact(request: Request, env: Env) { return json({ published: true }) } -async function markArtifact(request: Request, env: Env, flag: "active" | "minimum") { +async function markArtifact(request: Request, env: Env, flag: "active" | "minimum", prefix: string) { const invalid = validMutation(request) if (invalid) return invalid const form = await request.formData() @@ -303,7 +309,7 @@ async function markArtifact(request: Request, env: Env, flag: "active" | "minimu `UPDATE artifact SET ${flag} = ?, time_updated = ? WHERE channel = ? AND name = ? AND distribution = ? AND version = ?`, ).bind(enabled, Date.now(), key.channel, key.name, key.distribution, key.version), ]) - return Response.redirect(new URL("/admin", request.url), 303) + return Response.redirect(new URL(`${prefix}/admin`, request.url), 303) } function activate(db: D1Database, artifacts: ArtifactInput[]) { diff --git a/packages/updates/wrangler.jsonc b/packages/updates/wrangler.jsonc index 5f8249470f8..14be746d241 100644 --- a/packages/updates/wrangler.jsonc +++ b/packages/updates/wrangler.jsonc @@ -17,6 +17,14 @@ "pattern": "update.opencode.ai", "custom_domain": true, }, + { + "pattern": "opencode.ai/update", + "zone_name": "opencode.ai", + }, + { + "pattern": "opencode.ai/update/*", + "zone_name": "opencode.ai", + }, ], "d1_databases": [ { diff --git a/script/update-artifact.ts b/script/update-artifact.ts index a8aac1c3a14..6e51d5f9dc9 100644 --- a/script/update-artifact.ts +++ b/script/update-artifact.ts @@ -32,7 +32,7 @@ export namespace UpdateArtifact { throw new Error("GitHub OIDC response did not include a token") for (const attempt of [0, 1, 2]) { - const response = await fetch("https://update.opencode.ai/api/publish", { + const response = await fetch("https://opencode.ai/update/api/publish", { method: "POST", headers: { Authorization: `Bearer ${token.value}`,