diff --git a/.agents/skills/mobile-release/SKILL.md b/.agents/skills/mobile-release/SKILL.md index 240a2055f..1f43ae913 100644 --- a/.agents/skills/mobile-release/SKILL.md +++ b/.agents/skills/mobile-release/SKILL.md @@ -40,7 +40,7 @@ The CI release flow is file-driven: ``` 2. If no tag exists, fall back to the last release commit subject: ```bash - git log --format="%H %s" | grep "^[a-f0-9]* release(mobile): Release v" | head -1 | awk '{print $1}' + git log --format="%H %s" | grep -Ei "^[a-f0-9]* release\\(mobile\\): release v" | head -1 | awk '{print $1}' ``` 3. Collect commits since that point: ```bash diff --git a/apps/mobile/app.config.base.ts b/apps/mobile/app.config.base.ts index f6f041f50..7ef8b3211 100644 --- a/apps/mobile/app.config.base.ts +++ b/apps/mobile/app.config.base.ts @@ -16,6 +16,7 @@ const adaptiveIconPath = resolve(__dirname, "./assets/adaptive-icon.png") const splashIconPath = resolve(__dirname, "./assets/splash-icon.png") const isDev = process.env.NODE_ENV === "development" +const semverPattern = /^\d+\.\d+\.\d+$/ const channelNameMap = { development: "development", "ios-simulator": "development", @@ -25,9 +26,40 @@ const channelNameMap = { production: "production", } as Record +export const resolveRuntimeVersion = ({ + isDevelopment, + packageVersion, + otaRuntimeVersionOverride, +}: { + isDevelopment: boolean + packageVersion: string + otaRuntimeVersionOverride?: string | null +}) => { + if (isDevelopment) { + return "0.0.0-dev" + } + + if (otaRuntimeVersionOverride) { + if (!semverPattern.test(otaRuntimeVersionOverride)) { + throw new Error( + `Expected OTA_RUNTIME_VERSION to be a plain x.y.z version, got ${otaRuntimeVersionOverride}`, + ) + } + + return otaRuntimeVersionOverride + } + + return packageVersion +} + export default ({ config }: ConfigContext): ExpoConfig => { const profile = process.env.PROFILE || "production" const channelName = channelNameMap[profile] || channelNameMap.production + const runtimeVersion = resolveRuntimeVersion({ + isDevelopment: isDev, + packageVersion: PKG.version, + otaRuntimeVersionOverride: process.env.OTA_RUNTIME_VERSION ?? null, + }) const result: ExpoConfig = { ...config, @@ -52,7 +84,7 @@ export default ({ config }: ConfigContext): ExpoConfig => { }, checkAutomatically: "NEVER", }, - runtimeVersion: isDev ? "0.0.0-dev" : PKG.version, + runtimeVersion, name: "Folo", slug: "follow", diff --git a/apps/mobile/scripts/app-config.base.test.ts b/apps/mobile/scripts/app-config.base.test.ts new file mode 100644 index 000000000..abd0f94fe --- /dev/null +++ b/apps/mobile/scripts/app-config.base.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from "vitest" + +import { resolveRuntimeVersion } from "../app.config.base" + +describe("resolveRuntimeVersion", () => { + it("keeps the development runtime version stable", () => { + expect( + resolveRuntimeVersion({ + isDevelopment: true, + packageVersion: "0.4.2", + otaRuntimeVersionOverride: "0.4.1", + }), + ).toBe("0.0.0-dev") + }) + + it("uses OTA_RUNTIME_VERSION for OTA exports", () => { + expect( + resolveRuntimeVersion({ + isDevelopment: false, + packageVersion: "0.4.2", + otaRuntimeVersionOverride: "0.4.1", + }), + ).toBe("0.4.1") + }) + + it("rejects invalid OTA runtime versions", () => { + expect(() => + resolveRuntimeVersion({ + isDevelopment: false, + packageVersion: "0.4.2", + otaRuntimeVersionOverride: "0.4", + }), + ).toThrow(/OTA_RUNTIME_VERSION/i) + }) +}) diff --git a/apps/ota/README.md b/apps/ota/README.md index f0bd4b5db..71799909f 100644 --- a/apps/ota/README.md +++ b/apps/ota/README.md @@ -79,6 +79,8 @@ export OTA_GOOD_RELEASE_VERSION="0.4.1" export OTA_GOOD_STORE_VERSION="0.4.1" ``` +Production and development Workers must also provide an `OTA_CODE_SIGNING_PRIVATE_KEY` secret containing the PEM-encoded PKCS#8 private key that matches `apps/mobile/code-signing/certificate.pem`. + ## Manual Verification Commands Trigger a sync and inspect health: diff --git a/apps/ota/src/__tests__/manifest.test.ts b/apps/ota/src/__tests__/manifest.test.ts index e5a4e2a05..650bbdd89 100644 --- a/apps/ota/src/__tests__/manifest.test.ts +++ b/apps/ota/src/__tests__/manifest.test.ts @@ -1,3 +1,5 @@ +import { createVerify, generateKeyPairSync } from "node:crypto" + import { describe, expect, it, vi } from "vitest" import type { Env } from "../env" @@ -172,6 +174,78 @@ describe("/manifest", () => { expect(response.status).toBe(204) }) + + it("signs manifest responses when expo-expect-signature is provided", async () => { + const { privateKey, publicKey } = generateKeyPairSync("rsa", { + modulusLength: 2048, + privateKeyEncoding: { + format: "pem", + type: "pkcs8", + }, + publicKeyEncoding: { + format: "pem", + type: "spki", + }, + }) + const response = await fetchWorker( + "/manifest", + { + headers: { + "expo-platform": "ios", + "expo-runtime-version": "0.4.1", + "expo-expect-signature": 'sig, keyid="main", alg="rsa-v1_5-sha256"', + }, + }, + { + kvEntries: new Map([ + [KV_KEYS.latest("mobile", "production", "0.4.1", "ios"), { releaseVersion: "0.4.2" }], + [KV_KEYS.release("mobile", "0.4.2"), createRelease()], + ]), + otaCodeSigningPrivateKey: privateKey, + }, + ) + + expect(response.status).toBe(200) + + const manifestBody = await response.text() + const signatureHeader = response.headers.get("expo-signature") + + expect(signatureHeader).toContain('keyid="main"') + expect(signatureHeader).toContain('alg="rsa-v1_5-sha256"') + + const signatureMatch = signatureHeader?.match(/sig="([^"]+)"/) + expect(signatureMatch?.[1]).toBeTruthy() + + const verifier = createVerify("RSA-SHA256") + verifier.update(manifestBody, "utf8") + verifier.end() + + expect(verifier.verify(publicKey, signatureMatch![1]!, "base64")).toBe(true) + }) + + it("returns 500 when code signing is requested but the Worker is not configured", async () => { + const response = await fetchWorker( + "/manifest", + { + headers: { + "expo-platform": "ios", + "expo-runtime-version": "0.4.1", + "expo-expect-signature": 'sig, keyid="main", alg="rsa-v1_5-sha256"', + }, + }, + { + kvEntries: new Map([ + [KV_KEYS.latest("mobile", "production", "0.4.1", "ios"), { releaseVersion: "0.4.2" }], + [KV_KEYS.release("mobile", "0.4.2"), createRelease()], + ]), + }, + ) + + expect(response.status).toBe(500) + await expect(response.json()).resolves.toEqual({ + error: "OTA code signing is not configured", + }) + }) }) describe("/assets/*", () => { @@ -279,6 +353,7 @@ async function fetchWorker( headers?: Record } > + otaCodeSigningPrivateKey?: string }, ) { const response = await otaWorker.fetch( @@ -299,6 +374,7 @@ function createEnv(options?: { headers?: Record } > + otaCodeSigningPrivateKey?: string }): Env { return { OTA_KV: createKvNamespace(options?.kvEntries), @@ -308,6 +384,7 @@ function createEnv(options?: { GITHUB_TOKEN: "", OTA_SYNC_TOKEN: "", OTA_SYNC_TOKEN_HEADER: "x-ota-sync-token", + OTA_CODE_SIGNING_PRIVATE_KEY: options?.otaCodeSigningPrivateKey, } } diff --git a/apps/ota/src/env.ts b/apps/ota/src/env.ts index 899fbcdb3..b61ff4c12 100644 --- a/apps/ota/src/env.ts +++ b/apps/ota/src/env.ts @@ -6,4 +6,5 @@ export interface Env { GITHUB_TOKEN: string OTA_SYNC_TOKEN: string OTA_SYNC_TOKEN_HEADER: string + OTA_CODE_SIGNING_PRIVATE_KEY?: string } diff --git a/apps/ota/src/lib/code-signing.ts b/apps/ota/src/lib/code-signing.ts new file mode 100644 index 000000000..105cf9cf3 --- /dev/null +++ b/apps/ota/src/lib/code-signing.ts @@ -0,0 +1,101 @@ +const DEFAULT_CODE_SIGNING_KEY_ID = "main" +const SUPPORTED_CODE_SIGNING_ALG = "rsa-v1_5-sha256" + +let cachedPrivateKeyPem: string | null = null +let cachedPrivateKeyPromise: Promise | null = null + +export class OtaCodeSigningError extends Error { + readonly status: number + + constructor(status: number, message: string) { + super(message) + this.name = "OtaCodeSigningError" + this.status = status + } +} + +export async function createExpoSignatureHeader(input: { + manifestBody: string + expectSignatureHeader: string | undefined + privateKeyPem?: string | null +}) { + if (!input.expectSignatureHeader) { + return null + } + + const signatureRequest = parseExpoExpectSignatureHeader(input.expectSignatureHeader) + if (signatureRequest.keyId !== DEFAULT_CODE_SIGNING_KEY_ID) { + throw new OtaCodeSigningError( + 400, + `Unsupported expo-expect-signature keyid "${signatureRequest.keyId}"`, + ) + } + + if (signatureRequest.alg !== SUPPORTED_CODE_SIGNING_ALG) { + throw new OtaCodeSigningError( + 400, + `Unsupported expo-expect-signature alg "${signatureRequest.alg}"`, + ) + } + + const privateKeyPem = input.privateKeyPem?.trim() + if (!privateKeyPem) { + throw new OtaCodeSigningError(500, "OTA code signing is not configured") + } + + const privateKey = await importPrivateKey(privateKeyPem) + const manifestBuffer = new TextEncoder().encode(input.manifestBody) + const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, manifestBuffer) + + return serializeExpoSignatureHeader({ + sig: Buffer.from(signature).toString("base64"), + keyid: signatureRequest.keyId, + alg: signatureRequest.alg, + }) +} + +function parseExpoExpectSignatureHeader(value: string) { + const keyIdMatch = value.match(/\bkeyid="?([^",]+)"?/i) + const algMatch = value.match(/\balg="?([^",]+)"?/i) + + return { + keyId: keyIdMatch?.[1] ?? DEFAULT_CODE_SIGNING_KEY_ID, + alg: algMatch?.[1] ?? SUPPORTED_CODE_SIGNING_ALG, + } +} + +function serializeExpoSignatureHeader(input: { sig: string; keyid: string; alg: string }) { + return Object.entries(input) + .map(([key, value]) => `${key}=${JSON.stringify(value)}`) + .join(", ") +} + +async function importPrivateKey(privateKeyPem: string) { + if (cachedPrivateKeyPromise && cachedPrivateKeyPem === privateKeyPem) { + return cachedPrivateKeyPromise + } + + cachedPrivateKeyPem = privateKeyPem + cachedPrivateKeyPromise = crypto.subtle.importKey( + "pkcs8", + pemToArrayBuffer(privateKeyPem), + { + name: "RSASSA-PKCS1-v1_5", + hash: "SHA-256", + }, + false, + ["sign"], + ) + + return cachedPrivateKeyPromise +} + +function pemToArrayBuffer(value: string) { + const normalized = value + .replaceAll("-----BEGIN PRIVATE KEY-----", "") + .replaceAll("-----END PRIVATE KEY-----", "") + .replaceAll(/\s+/g, "") + + const buffer = Buffer.from(normalized, "base64") + return Uint8Array.from(buffer).buffer +} diff --git a/apps/ota/src/routes/manifest.ts b/apps/ota/src/routes/manifest.ts index 3870f8358..a1cf55793 100644 --- a/apps/ota/src/routes/manifest.ts +++ b/apps/ota/src/routes/manifest.ts @@ -2,6 +2,7 @@ import { Hono } from "hono" import { z } from "zod" import type { Env } from "../env" +import { createExpoSignatureHeader, OtaCodeSigningError } from "../lib/code-signing" import { KV_KEYS } from "../lib/constants" import { getLatestReleasePointer } from "../lib/kv" import { buildManifest } from "../lib/manifest" @@ -90,19 +91,46 @@ manifestRoute.get("/manifest", async (c) => { return c.body(null, 204) } - return new Response( - JSON.stringify(buildManifest(release, { origin: new URL(c.req.url).origin, platform })), - { - status: 200, - headers: { - "cache-control": "private, max-age=0", - "content-type": "application/expo+json; charset=utf-8", - "expo-protocol-version": "1", - "expo-sfv-version": "0", - vary: "expo-platform, expo-runtime-version, expo-channel-name", - }, - }, + const manifestBody = JSON.stringify( + buildManifest(release, { origin: new URL(c.req.url).origin, platform }), ) + + let expoSignatureHeader: string | null = null + try { + expoSignatureHeader = await createExpoSignatureHeader({ + manifestBody, + expectSignatureHeader: c.req.header("expo-expect-signature"), + privateKeyPem: c.env.OTA_CODE_SIGNING_PRIVATE_KEY, + }) + } catch (error) { + if (error instanceof OtaCodeSigningError) { + return new Response(JSON.stringify({ error: error.message }), { + status: error.status, + headers: { + "content-type": "application/json; charset=utf-8", + }, + }) + } + + throw error + } + + const headers = new Headers({ + "cache-control": "private, max-age=0", + "content-type": "application/expo+json; charset=utf-8", + "expo-protocol-version": "1", + "expo-sfv-version": "0", + vary: "expo-platform, expo-runtime-version, expo-channel-name", + }) + + if (expoSignatureHeader) { + headers.set("expo-signature", expoSignatureHeader) + } + + return new Response(manifestBody, { + status: 200, + headers, + }) }) function parsePlatform(value: string | undefined): OtaPlatform | null {