mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-19 00:03:13 +03:00
feat(updates): serve updates under opencode.ai/update (#47858)
This commit is contained in:
@@ -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')
|
||||
|
||||
|
||||
@@ -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 },
|
||||
})
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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)]),
|
||||
},
|
||||
|
||||
@@ -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:
|
||||
|
||||
|
||||
@@ -39,6 +39,12 @@ const githubKeys = createRemoteJWKSet(new URL("https://token.actions.githubuserc
|
||||
export default {
|
||||
async fetch(request: Request, env: Env, ctx: Pick<ExecutionContext, "waitUntil">): Promise<Response> {
|
||||
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
|
||||
? ""
|
||||
: `<form action="/admin/activate" method="post">
|
||||
: `<form action="${prefix}/admin/activate" method="post">
|
||||
<input type="hidden" name="channel" value="${escape(artifact.channel)}">
|
||||
<input type="hidden" name="name" value="${escape(artifact.name)}">
|
||||
<input type="hidden" name="distribution" value="${escape(artifact.distribution)}">
|
||||
@@ -176,7 +182,7 @@ async function admin(request: Request, env: Env) {
|
||||
<button class="btn" data-size="sm" data-variant="outline" type="submit">Activate</button>
|
||||
</form>`
|
||||
}
|
||||
<form action="/admin/minimum" method="post">
|
||||
<form action="${prefix}/admin/minimum" method="post">
|
||||
<input type="hidden" name="channel" value="${escape(artifact.channel)}">
|
||||
<input type="hidden" name="name" value="${escape(artifact.name)}">
|
||||
<input type="hidden" name="distribution" value="${escape(artifact.distribution)}">
|
||||
@@ -232,8 +238,8 @@ async function admin(request: Request, env: Env) {
|
||||
<footer class="pagination">
|
||||
<p>Page ${currentPage} of ${pages} · ${count?.total ?? 0} builds</p>
|
||||
<nav aria-label="Pagination">
|
||||
${currentPage > 1 ? `<a class="btn" data-size="sm" data-variant="outline" href="/admin?page=${currentPage - 1}">Previous</a>` : ""}
|
||||
${currentPage < pages ? `<a class="btn" data-size="sm" data-variant="outline" href="/admin?page=${currentPage + 1}">Next</a>` : ""}
|
||||
${currentPage > 1 ? `<a class="btn" data-size="sm" data-variant="outline" href="${prefix}/admin?page=${currentPage - 1}">Previous</a>` : ""}
|
||||
${currentPage < pages ? `<a class="btn" data-size="sm" data-variant="outline" href="${prefix}/admin?page=${currentPage + 1}">Next</a>` : ""}
|
||||
</nav>
|
||||
</footer>
|
||||
</article>
|
||||
@@ -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[]) {
|
||||
|
||||
@@ -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": [
|
||||
{
|
||||
|
||||
@@ -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}`,
|
||||
|
||||
Reference in New Issue
Block a user