Something went wrong. Try again.
Your thinking partner.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147import { createHash } from "node:crypto";import { spawnSync } from "node:child_process";import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { homedir, tmpdir } from "node:os";import { join, resolve } from "node:path";import { artifactName, publishArtifact, validateArtifactSize } from "./android-release";import { releaseVersion } from "./release-version.cjs";
const REMOTE = "git@tangled.sh:cameron.stream/co";const REPO = "did:plc:e65ouwqnsfswdkm23wbojfaz";const OWNER = "did:plc:gfrmhdmjvxn2sjedzboeudef";const PDS = "https://enoki.us-east.host.bsky.network";const HELP = `Usage: bun run release:android v0.1.6 [--build-only | --publish-only]
Default: build and sign locally, push an annotated tag, publish the APK to Tangled.--build-only: save a signed APK without creating a tag or publishing.--publish-only: publish the saved APK for this version and commit without rebuilding.
Requires a clean checkout, Bun, Android Studio, and the existing private signingcredentials in ~/.config/co/android-release/secrets.json (or CO_SIGNING_SECRETS_FILE).Publishing prompts privately for an AT Protocol app password if ATP_APP_PASSWORDis not set. It is not saved. No Expo login or hosted runner is needed.`;
export function parseReleaseArgs(args: string[]) { if (args.length === 1 && ["--help", "-h"].includes(args[0]!)) return null; const [tag, mode] = args; if (!tag || args.length > 2 || (mode && !["--build-only", "--publish-only"].includes(mode))) throw new Error(HELP); releaseVersion(tag); return { tag, buildOnly: mode === "--build-only", publishOnly: mode === "--publish-only" };}
export function verifySavedArtifact(manifest: unknown, tag: string, commit: string, bytes: Uint8Array) { validateArtifactSize(bytes.byteLength); const saved = manifest as { tag?: string; commit?: string; sha256?: string } | null; const sha256 = createHash("sha256").update(bytes).digest("hex"); if (!saved || saved.tag !== tag || saved.commit !== commit || saved.sha256 !== sha256) throw new Error("Saved APK does not match this version and commit. Run --build-only again.");}
function command(program: string, args: string[], cwd: string, env = process.env, capture = false) { const result = spawnSync(program, args, { cwd, env, encoding: "utf8", stdio: capture ? "pipe" : "inherit" }); if (result.status !== 0) throw new Error(`${program} failed (${result.status ?? result.error?.message}).`); return result.stdout?.trim() ?? "";}
async function main() { const options = parseReleaseArgs(process.argv.slice(2)); if (!options) { console.log(HELP); return; } const { tag, buildOnly, publishOnly } = options; const root = resolve(import.meta.dir, ".."); const git = (...args: string[]) => command("git", args, root, process.env, true); if (git("status", "--porcelain")) throw new Error("Commit or stash your changes before releasing; only committed source is built."); const commit = git("rev-parse", "HEAD"); const ref = `refs/tags/${tag}`; const hasTag = !!git("tag", "--list", tag); if (hasTag) { git("rev-parse", "--verify", `${ref}^{tag}`); if (git("rev-parse", `${ref}^{commit}`) !== commit) throw new Error("This version already tags another commit. Choose a new version or check out that tag."); } if (!buildOnly) { const remoteTag = git("ls-remote", "--tags", REMOTE, ref).split(/\s/)[0]; if (remoteTag && (!hasTag || remoteTag !== git("rev-parse", ref))) throw new Error("This version already exists on Tangled. Fetch its tag or choose a new version."); }
const sdk = process.env.ANDROID_HOME || join(homedir(), "Library/Android/sdk"); const java = process.env.JAVA_HOME || "/Applications/Android Studio.app/Contents/jbr/Contents/Home"; const signer = join(sdk, "build-tools/36.1.0/apksigner"); if (!existsSync(signer) || !existsSync(join(java, "bin/java"))) throw new Error("Install Android Studio and SDK Build Tools 36.1.0, or set ANDROID_HOME and JAVA_HOME."); // Publishing credentials never enter dependency installers, tests, or the build. const buildEnv = { ...process.env, ANDROID_HOME: sdk, JAVA_HOME: java, CO_RELEASE_TAG: tag, CO_ANDROID_ARCHITECTURES: "arm64-v8a" }; delete buildEnv.ATP_APP_PASSWORD; for (const name of Object.keys(buildEnv)) if (name.startsWith("ANDROID_KEY") || name === "ANDROID_SIGNING_LINEAGE_BASE64") delete buildEnv[name]; const apk = join(root, "artifacts", artifactName(tag)); const manifestPath = `${apk}.json`;
if (!publishOnly) { const secretPath = process.env.CO_SIGNING_SECRETS_FILE || join(homedir(), ".config/co/android-release/secrets.json"); if (!existsSync(secretPath)) throw new Error(`Signing credentials missing: ${secretPath}`); const secrets = JSON.parse(readFileSync(secretPath, "utf8")) as Record<string, string>; const signingEnv = { ...buildEnv }; for (const name of ["ANDROID_KEYSTORE_BASE64", "ANDROID_KEYSTORE_PASSWORD", "ANDROID_KEY_ALIAS", "ANDROID_KEY_PASSWORD", "ANDROID_SIGNING_LINEAGE_BASE64"]) { if (typeof secrets[name] === "string") signingEnv[name] = secrets[name]; if (name !== "ANDROID_KEY_PASSWORD" && !signingEnv[name]) throw new Error(`Signing credentials missing ${name}.`); } const temporary = mkdtempSync(join(tmpdir(), "co-android-release-")); const checkout = join(temporary, "source"); let added = false; try { command("git", ["worktree", "add", "--detach", checkout, commit], root); added = true; console.log(`Building ${tag} from ${commit.slice(0, 12)} in an isolated worktree.`); const run = (program: string, args: string[]) => command(program, args, checkout, buildEnv); run("bun", ["install", "--frozen-lockfile"]); run("bun", ["test", "src", "scripts/android-release.test.ts", "scripts/release-android-local.test.ts"]); run("bun", ["run", "typecheck"]); run("bun", ["run", "lint"]); run("bash", ["scripts/build-android-apk.sh"]); command("bun", ["scripts/android-release.ts", "sign"], checkout, signingEnv); mkdirSync(join(root, "artifacts"), { recursive: true }); copyFileSync(join(checkout, "artifacts", artifactName(tag)), apk); copyFileSync(join(checkout, "artifacts", `${artifactName(tag)}.sha256`), `${apk}.sha256`); writeFileSync(manifestPath, JSON.stringify({ tag, commit, sha256: createHash("sha256").update(readFileSync(apk)).digest("hex") }, null, 2) + "\n"); } finally { if (added) command("git", ["worktree", "remove", "--force", checkout], root); rmSync(temporary, { recursive: true, force: true }); } }
if (!existsSync(apk) || !existsSync(manifestPath)) throw new Error("No saved release. Run --build-only first."); const bytes = readFileSync(apk); verifySavedArtifact(JSON.parse(readFileSync(manifestPath, "utf8")), tag, commit, bytes); command(signer, ["verify", "--verbose", apk], root, buildEnv); console.log(`APK ready: ${apk}`); if (buildOnly) return;
let password = process.env.ATP_APP_PASSWORD; if (!password) { if (!process.stdin.isTTY) throw new Error(`Publishing needs ATP_APP_PASSWORD or an interactive terminal. Your APK is saved. Run: bun run release:android ${tag} --publish-only`); const prompt = spawnSync("bash", ["-c", 'IFS= read -r -s -p "AT Protocol app password (hidden): " co_password; printf "\\n" >&2; printf "%s" "$co_password"'], { stdio: ["inherit", "pipe", "inherit"], encoding: "utf8" }); if (prompt.status !== 0 || !prompt.stdout) throw new Error("No publishing password entered. Your APK is saved."); password = prompt.stdout; } // A concurrent checkout/edit must not change what the release tag names. if (git("rev-parse", "HEAD") !== commit || git("status", "--porcelain")) throw new Error("Checkout changed during the build. Restore the original commit before publishing the saved APK."); if (!hasTag) command("git", ["tag", "-a", tag, commit, "-m", `Co ${tag.slice(1)}`], root); const tagHash = git("rev-parse", "--verify", `${ref}^{tag}`); if (git("rev-parse", `${ref}^{commit}`) !== commit) throw new Error("Release tag changed during the build."); command("git", ["push", REMOTE, `${ref}:${ref}`], root); const result = await publishArtifact({ pds: PDS, identifier: "cameron.stream", password, did: OWNER, repo: REPO, tagHash, name: artifactName(tag), bytes }); console.log(`${result.existing ? "Already published" : "Published"}: ${result.uri}`); console.log("Download: https://tangled.org/cameron.stream/co/tags");}
if (import.meta.main) main().catch(error => { console.error(error instanceof Error ? error.message : "Local Android release failed."); process.exitCode = 1;});