Something went wrong. Try again.
Your thinking partner.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188import { createHash } from "node:crypto";import { spawnSync } from "node:child_process";import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join, resolve } from "node:path";import { releaseVersion } from "./release-version.cjs";
export const MAX_ARTIFACT_BYTES = 50 * 1024 * 1024;const APK = "artifacts/co-release.apk";const COLLECTION = "sh.tangled.repo.artifact";const env = process.env;
function required(name: string): string { const value = env[name]; if (!value) throw new Error(`Missing ${name}. Configure it in Tangled repository secrets.`); return value;}
function run(command: string, args: string[], options: { capture?: boolean } = {}): string { const result = spawnSync(command, args, { encoding: "utf8", stdio: options.capture ? "pipe" : "inherit" }); if (result.status !== 0) throw new Error(`${command} failed (${result.status ?? result.error?.message}).`); return result.stdout?.trim() ?? "";}
export function artifactName(tag: string) { releaseVersion(tag); return `co-${tag}-arm64.apk`;}
// A deterministic, syntactically valid AT Protocol TID makes retries converge// on one record for this repo/tag/filename instead of producing duplicate rows.export function artifactRecordKey(repo: string, tagHash: string, name: string): string { const alphabet = "234567abcdefghijklmnopqrstuvwxyz"; const digest = createHash("sha256").update(`${repo}\0${tagHash}\0${name}`).digest(); let value = digest.readBigUInt64BE() & ((1n << 63n) - 1n); let tid = ""; for (let i = 0; i < 13; i++) { tid = alphabet[Number(value & 31n)] + tid; value >>= 5n; } return tid;}
export function validateArtifactSize(size: number) { if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_ARTIFACT_BYTES) throw new Error("APK must be nonempty and at most 50 MiB for Tangled artifacts.");}
function releaseContext() { const tag = required("TANGLED_REF_NAME"); releaseVersion(tag); if (env.TANGLED_REF_TYPE !== "tag" || env.TANGLED_PIPELINE_KIND !== "push") throw new Error("Publishing requires a version-tag push pipeline."); const ref = `refs/tags/${tag}`; const tagHash = run("git", ["rev-parse", "--verify", `${ref}^{tag}`], { capture: true }); const commit = run("git", ["rev-parse", "--verify", `${ref}^{commit}`], { capture: true }); const head = run("git", ["rev-parse", "HEAD"], { capture: true }); if (commit !== head) throw new Error("Release tag does not point at the checked-out commit."); const repo = required("CO_REPO_DID"); const did = required("CO_OWNER_DID"); if (env.TANGLED_REPO_REPO_DID && env.TANGLED_REPO_REPO_DID !== repo) throw new Error("Pipeline is running for a different repository."); return { tag, tagHash, repo, did, name: artifactName(tag), commit };}
function preflight() { const context = releaseContext(); for (const name of ["ANDROID_KEYSTORE_BASE64", "ANDROID_KEYSTORE_PASSWORD", "ANDROID_KEY_ALIAS", "ATP_APP_PASSWORD", "ATP_IDENTIFIER", "ATP_PDS_URL"]) required(name); const endpoint = new URL(required("ATP_PDS_URL")); if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.search || endpoint.hash) throw new Error("ATP_PDS_URL must be the HTTPS URL of your account's PDS."); console.log(`Release ${context.tag}: ${context.name}`);}
function sign() { const tag = required("CO_RELEASE_TAG"); releaseVersion(tag); const sdk = required("ANDROID_HOME"); const signer = join(sdk, "build-tools", "36.1.0", "apksigner"); if (!existsSync(signer)) throw new Error("Android Build Tools 36.1.0 are required."); const directory = mkdtempSync(join(tmpdir(), "co-signing-")); chmodSync(directory, 0o700); try { const keystore = join(directory, "release.jks"); writeFileSync(keystore, Buffer.from(required("ANDROID_KEYSTORE_BASE64"), "base64"), { mode: 0o600 }); required("ANDROID_KEYSTORE_PASSWORD"); env.ANDROID_KEY_PASSWORD ||= env.ANDROID_KEYSTORE_PASSWORD; const args = ["sign", "--out", join("artifacts", artifactName(tag)), "--v4-signing-enabled", "false"]; if (env.ANDROID_SIGNING_LINEAGE_BASE64) { const oldKey = join(directory, "debug.keystore"); const template = run("tar", ["-tzf", "node_modules/expo/template.tgz"], { capture: true }); const entry = template.split("\n").find(path => path.endsWith("/android/app/debug.keystore")); if (!entry) throw new Error("Expo test keystore missing from template."); const extracted = spawnSync("tar", ["-xOzf", "node_modules/expo/template.tgz", entry]); if (extracted.status !== 0) throw new Error("Could not extract the previous test signing key."); writeFileSync(oldKey, extracted.stdout, { mode: 0o600 }); const lineage = join(directory, "release.lineage"); writeFileSync(lineage, Buffer.from(env.ANDROID_SIGNING_LINEAGE_BASE64, "base64"), { mode: 0o600 }); args.push("--lineage", lineage, "--rotation-min-sdk-version", "28", "--ks", oldKey, "--ks-key-alias", "androiddebugkey", "--ks-pass", "pass:android", "--key-pass", "pass:android", "--next-signer"); } args.push("--ks", keystore, "--ks-key-alias", required("ANDROID_KEY_ALIAS"), "--ks-pass", "env:ANDROID_KEYSTORE_PASSWORD", "--key-pass", "env:ANDROID_KEY_PASSWORD", APK); run(signer, args); const output = join("artifacts", artifactName(tag)); run(signer, ["verify", "--verbose", "--print-certs", output]); validateArtifactSize(statSync(output).size); const sha256 = createHash("sha256").update(readFileSync(output)).digest("hex"); writeFileSync(`${output}.sha256`, `${sha256} ${artifactName(tag)}\n`); console.log(`Signed ${output} (${statSync(output).size} bytes).`); } finally { rmSync(directory, { recursive: true, force: true }); }}
type Fetcher = typeof fetch;export async function publishArtifact(options: { pds: string; identifier: string; password: string; did: string; repo: string; tagHash: string; name: string; bytes: Uint8Array; fetcher?: Fetcher;}) { const { pds, identifier, password, did, repo, tagHash, name, bytes } = options; validateArtifactSize(bytes.byteLength); if (!/^[a-f0-9]{40}$/.test(tagHash)) throw new Error("Expected an annotated Git tag object hash."); const fetcher = options.fetcher ?? fetch; const base = pds.replace(/\/$/, ""); let jwt: string | undefined; async function request(method: string, body?: unknown, query?: Record<string, string>) { const url = `${base}/xrpc/${method}${query ? `?${new URLSearchParams(query)}` : ""}`; const binary = body instanceof Uint8Array; const response = await fetcher(url, { method: body === undefined ? "GET" : "POST", headers: { ...(jwt ? { Authorization: `Bearer ${jwt}` } : {}), ...(body === undefined ? {} : { "Content-Type": binary ? "application/vnd.android.package-archive" : "application/json" }) }, body: body === undefined ? undefined : binary ? body : JSON.stringify(body), signal: AbortSignal.timeout(binary ? 180_000 : 30_000), redirect: "error", }); const data = await response.json() as Record<string, any>; if (!response.ok) { if (method === "com.atproto.repo.getRecord" && data.error === "RecordNotFound") return null; // Do not echo server messages: authentication failures can contain inputs. throw new Error(`${method} failed (HTTP ${response.status}).`); } return data; } const session = await request("com.atproto.server.createSession", { identifier, password }); if (session?.did !== did || typeof session?.accessJwt !== "string") throw new Error("Publishing account does not own this repository."); jwt = session.accessJwt; const rkey = artifactRecordKey(repo, tagHash, name); const recordQuery = { repo: did, collection: COLLECTION, rkey }; const existing = await request("com.atproto.repo.getRecord", undefined, recordQuery); if (existing) { if (existing.value?.repoDid !== repo || existing.value?.name !== name || existing.value?.tag?.$bytes !== Buffer.from(tagHash, "hex").toString("base64").replace(/=+$/, "")) throw new Error("Existing artifact record does not match the release."); return { uri: existing.uri as string, existing: true }; } const uploaded = await request("com.atproto.repo.uploadBlob", bytes); if (!uploaded?.blob?.ref?.$link || uploaded.blob.size !== bytes.byteLength) throw new Error("PDS did not acknowledge the complete APK upload."); const created = await request("com.atproto.repo.createRecord", { ...recordQuery, validate: false, record: { $type: COLLECTION, repoDid: repo, name, tag: { $bytes: Buffer.from(tagHash, "hex").toString("base64").replace(/=+$/, "") }, artifact: uploaded.blob, createdAt: new Date().toISOString() }, }); if (typeof created?.uri !== "string") throw new Error("PDS did not confirm the artifact record."); return { uri: created.uri, existing: false };}
if (import.meta.main) { try { const command = process.argv[2]; if (command === "preflight") preflight(); else if (command === "sign") sign(); else if (command === "publish") { preflight(); const context = releaseContext(); const result = await publishArtifact({ ...context, pds: required("ATP_PDS_URL"), identifier: required("ATP_IDENTIFIER"), password: required("ATP_APP_PASSWORD"), bytes: readFileSync(resolve("artifacts", context.name)), }); console.log(`${result.existing ? "Already published" : "Published"}: ${result.uri}`); } else throw new Error("Usage: bun scripts/android-release.ts preflight|sign|publish"); } catch (error) { console.error(error instanceof Error ? error.message : "Android release failed."); process.exitCode = 1; }}