diff --git a/.github/scripts/build-ota-release.mjs b/.github/scripts/build-ota-release.mjs new file mode 100644 index 000000000..210273035 --- /dev/null +++ b/.github/scripts/build-ota-release.mjs @@ -0,0 +1,516 @@ +#!/usr/bin/env node + +import { spawn, spawnSync } from "node:child_process" +import { createHash } from "node:crypto" +import { existsSync } from "node:fs" +import { readFile, writeFile } from "node:fs/promises" +import { fileURLToPath } from "node:url" + +import { dirname, extname, join, resolve } from "pathe" + +const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url)) +const REPO_ROOT = resolve(SCRIPT_DIR, "..", "..") +const DEFAULT_MOBILE_PROJECT_DIR = join(REPO_ROOT, "apps", "mobile") +const OTA_PLATFORMS = ["ios", "android"] +const CONTENT_TYPES = new Map([ + [".aac", "audio/aac"], + [".bmp", "image/bmp"], + [".bundle", "application/javascript"], + [".css", "text/css"], + [".gif", "image/gif"], + [".hbc", "application/javascript"], + [".html", "text/html"], + [".jpeg", "image/jpeg"], + [".jpg", "image/jpeg"], + [".js", "application/javascript"], + [".json", "application/json"], + [".m4a", "audio/mp4"], + [".mp3", "audio/mpeg"], + [".mp4", "video/mp4"], + [".otf", "font/otf"], + [".pdf", "application/pdf"], + [".png", "image/png"], + [".svg", "image/svg+xml"], + [".ttf", "font/ttf"], + [".txt", "text/plain; charset=utf-8"], + [".wav", "audio/wav"], + [".webm", "video/webm"], + [".webp", "image/webp"], + [".woff", "font/woff"], + [".woff2", "font/woff2"], + [".xml", "application/xml"], +]) + +/** + * @typedef {{ + * path: string + * ext?: string + * }} ExportAssetMetadata + */ + +/** + * @typedef {{ + * path: string + * sha256: string + * contentType: string + * }} OtaAsset + */ + +/** + * @typedef {{ + * bundle: string + * assets?: unknown[] + * }} ExportPlatformMetadata + */ + +/** + * @typedef {{ + * fileMetadata?: Partial> + * }} ExportMetadata + */ + +/** + * @typedef {{ + * product: string + * channel: string + * releaseVersion: string + * releaseKind: string + * runtimeVersion: string + * gitTag: string + * gitCommit: string + * publishedAt: string + * policy: { + * storeRequired: boolean + * minSupportedBinaryVersion: string + * message: string | null + * } + * metadata: ExportMetadata + * resolveAsset: (asset: ExportAssetMetadata) => Promise + * }} BuildOtaMetadataInput + */ + +/** + * @param {BuildOtaMetadataInput} input + */ +export async function buildOtaMetadata(input) { + /** @type {Record} */ + const platforms = {} + const fileMetadata = resolveExportFileMetadata(input.metadata) + + for (const platform of OTA_PLATFORMS) { + const platformMetadata = resolvePlatformMetadata(fileMetadata, platform) + const launchAsset = { path: normalizeAssetPath(platformMetadata.bundle) } + const assets = collectAssets(platformMetadata.assets, platform) + + platforms[platform] = { + launchAsset: await input.resolveAsset(launchAsset), + assets: await Promise.all(assets.map((asset) => input.resolveAsset(asset))), + } + } + + return { + schemaVersion: 1, + updateId: createDeterministicUuid( + `${input.product}:${input.channel}:${input.releaseVersion}:${input.runtimeVersion}:${input.gitTag}:${input.gitCommit}`, + ), + product: input.product, + channel: input.channel, + releaseVersion: input.releaseVersion, + releaseKind: input.releaseKind, + runtimeVersion: input.runtimeVersion, + publishedAt: input.publishedAt, + git: { + tag: input.gitTag, + commit: input.gitCommit, + }, + policy: input.policy, + platforms, + } +} + +function createDeterministicUuid(seed) { + const digest = createHash("sha1").update(seed).digest() + const bytes = Buffer.from(digest.subarray(0, 16)) + + bytes[6] = (bytes[6] & 0x0f) | 0x50 + bytes[8] = (bytes[8] & 0x3f) | 0x80 + + const hex = bytes.toString("hex") + return [ + hex.slice(0, 8), + hex.slice(8, 12), + hex.slice(12, 16), + hex.slice(16, 20), + hex.slice(20, 32), + ].join("-") +} + +export async function buildReleaseAssets(options = {}) { + const projectDir = resolveMobileProjectDir(options.projectDir) + const distDir = join(projectDir, "dist") + const metadataPath = join(distDir, "metadata.json") + + if (!existsSync(metadataPath)) { + throw new Error( + `Missing Expo export metadata at ${metadataPath}. Run "pnpm --dir apps/mobile run update:export" first.`, + ) + } + + const packageJson = await readJson(join(projectDir, "package.json")) + const product = process.env.OTA_PRODUCT ?? "mobile" + const channel = process.env.OTA_CHANNEL ?? "production" + const releaseVersion = process.env.OTA_RELEASE_VERSION ?? packageJson.version + const releaseKind = process.env.OTA_RELEASE_KIND ?? "ota" + const runtimeVersion = process.env.OTA_RUNTIME_VERSION ?? packageJson.version + const gitTag = process.env.OTA_GIT_TAG ?? `${product}/v${releaseVersion}` + const gitCommit = process.env.OTA_GIT_COMMIT ?? execGit(["rev-parse", "HEAD"], REPO_ROOT) + const publishedAt = process.env.OTA_PUBLISHED_AT ?? new Date().toISOString() + const metadata = await readJson(metadataPath) + + const otaMetadata = await buildOtaMetadata({ + product, + channel, + releaseVersion, + releaseKind, + runtimeVersion, + gitTag, + gitCommit, + publishedAt, + policy: { + storeRequired: parseBooleanEnv("OTA_STORE_REQUIRED", false), + minSupportedBinaryVersion: process.env.OTA_MIN_SUPPORTED_BINARY_VERSION ?? runtimeVersion, + message: parseNullableEnv("OTA_POLICY_MESSAGE"), + }, + metadata, + resolveAsset: async (asset) => { + const assetFilePath = join(distDir, asset.path) + let assetBuffer + + try { + assetBuffer = await readFile(assetFilePath) + } catch (error) { + const reason = error instanceof Error ? error.message : String(error) + throw new Error( + `Failed to read exported asset "${asset.path}" at ${assetFilePath}: ${reason}`, + ) + } + + return { + path: asset.path, + sha256: createHash("sha256").update(assetBuffer).digest("hex"), + contentType: resolveContentType(asset), + } + }, + }) + + const outputPath = join(distDir, "ota-release.json") + const archivePath = join(projectDir, "dist.tar.zst") + + await writeFile(outputPath, `${JSON.stringify(otaMetadata, null, 2)}\n`, "utf8") + await createTarZstArchive({ distDir, archivePath }) + + return { + projectDir, + distDir, + metadataPath, + outputPath, + archivePath, + otaMetadata, + } +} + +async function main() { + try { + const result = await buildReleaseAssets() + + console.info(`Wrote OTA metadata: ${result.outputPath}`) + console.info(`Wrote OTA archive: ${result.archivePath}`) + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)) + process.exitCode = 1 + } +} + +/** + * @param {unknown} value + */ +function resolveExportFileMetadata(metadata) { + if (!metadata || typeof metadata !== "object") { + throw new Error("Expo export metadata is missing fileMetadata") + } + + if (!metadata.fileMetadata || typeof metadata.fileMetadata !== "object") { + throw new Error("Expo export metadata is missing fileMetadata") + } + + return metadata.fileMetadata +} + +function resolvePlatformMetadata(fileMetadata, platform) { + const platformMetadata = fileMetadata[platform] + + if (!platformMetadata || typeof platformMetadata !== "object") { + throw new Error(`Expo export metadata is missing ${platform} platform metadata`) + } + + if (typeof platformMetadata.bundle !== "string" || platformMetadata.bundle.length === 0) { + throw new Error(`Expo export metadata is missing ${platform} bundle metadata`) + } + + return platformMetadata +} + +function collectAssets(value, platform) { + if (value == null) { + throw new TypeError(`Expo export metadata is missing ${platform} assets metadata`) + } + + if (!Array.isArray(value)) { + throw new TypeError(`Expo export metadata has invalid ${platform} assets metadata`) + } + + /** @type {Map} */ + const dedupedAssets = new Map() + + for (const asset of value) { + const normalizedAsset = normalizeExportAsset(asset) + const existingAsset = dedupedAssets.get(normalizedAsset.path) + + if (!existingAsset || (!existingAsset.ext && normalizedAsset.ext)) { + dedupedAssets.set(normalizedAsset.path, normalizedAsset) + continue + } + + if (existingAsset.ext && normalizedAsset.ext && existingAsset.ext !== normalizedAsset.ext) { + throw new Error( + `Expo export metadata has conflicting ext values for asset "${normalizedAsset.path}"`, + ) + } + } + + return [...dedupedAssets.values()] +} + +/** + * @param {unknown} asset + */ +function normalizeExportAsset(asset) { + if (typeof asset === "string") { + return { path: normalizeAssetPath(asset) } + } + + if (!asset || typeof asset !== "object") { + throw new Error(`Unsupported Expo asset metadata entry: ${JSON.stringify(asset)}`) + } + + const assetPath = + "path" in asset && typeof asset.path === "string" + ? asset.path + : "file" in asset && typeof asset.file === "string" + ? asset.file + : null + + if (!assetPath) { + throw new Error(`Unsupported Expo asset metadata entry: ${JSON.stringify(asset)}`) + } + + return { + path: normalizeAssetPath(assetPath), + ...("ext" in asset && asset.ext != null ? { ext: normalizeAssetExtension(asset.ext) } : {}), + } +} + +function normalizeAssetExtension(ext) { + if (typeof ext !== "string") { + throw new TypeError(`Unsupported Expo asset ext metadata: ${JSON.stringify(ext)}`) + } + + const normalizedExt = ext.trim().replace(/^\.+/, "").toLowerCase() + + if (!normalizedExt) { + throw new Error(`Invalid exported asset ext "${ext}"`) + } + + return normalizedExt +} + +function resolveMobileProjectDir(projectDir) { + if (projectDir) { + return resolve(projectDir) + } + + const cwd = resolve(process.cwd()) + + if (existsSync(join(cwd, "package.json")) && existsSync(join(cwd, "scripts", "expo-update.ts"))) { + return cwd + } + + if (existsSync(join(cwd, "apps", "mobile", "package.json"))) { + return join(cwd, "apps", "mobile") + } + + return DEFAULT_MOBILE_PROJECT_DIR +} + +function normalizeAssetPath(assetPath) { + const normalized = assetPath + .replaceAll("\\", "/") + .replace(/^\/+/, "") + .replace(/^(\.\/)+/, "") + .replaceAll(/\/{2,}/g, "/") + + if (!normalized || normalized.split("/").includes("..")) { + throw new Error(`Invalid exported asset path "${assetPath}"`) + } + + return normalized +} + +function resolveContentType(asset) { + const pathExtension = extname(asset.path).toLowerCase() + const metadataExtension = asset.ext ? `.${asset.ext}` : "" + const extension = pathExtension || metadataExtension + + return CONTENT_TYPES.get(extension) ?? "application/octet-stream" +} + +async function createTarZstArchive({ distDir, archivePath }) { + const zstdBinary = resolveZstdBinary() + + await new Promise((resolvePromise, rejectPromise) => { + let tarExited = false + let zstdExited = false + + const tarProcess = spawn("tar", ["-cf", "-", "-C", distDir, "."], { + stdio: ["ignore", "pipe", "inherit"], + }) + const zstdProcess = spawn(zstdBinary, ["-q", "-f", "-o", archivePath], { + stdio: ["pipe", "inherit", "inherit"], + }) + + const rejectOnce = once((error) => rejectPromise(error)) + const resolveIfComplete = () => { + if (tarExited && zstdExited) { + resolvePromise(void 0) + } + } + + tarProcess.on("error", (error) => { + rejectOnce(new Error(`Failed to run tar: ${error.message}`)) + }) + zstdProcess.on("error", (error) => { + rejectOnce(new Error(`Failed to run zstd: ${error.message}`)) + }) + + tarProcess.stdout.on("error", (error) => { + rejectOnce(new Error(`Failed to stream tar output: ${error.message}`)) + }) + zstdProcess.stdin.on("error", (error) => { + rejectOnce(new Error(`Failed to stream zstd input: ${error.message}`)) + }) + + tarProcess.stdout.pipe(zstdProcess.stdin) + + tarProcess.on("close", (code) => { + if (code !== 0) { + rejectOnce(new Error(`tar exited with code ${code}`)) + return + } + + tarExited = true + resolveIfComplete() + }) + + zstdProcess.on("close", (code) => { + if (code !== 0) { + rejectOnce(new Error(`zstd exited with code ${code}`)) + return + } + + zstdExited = true + resolveIfComplete() + }) + }) +} + +function resolveZstdBinary() { + const candidates = [process.env.ZSTD_BIN, "zstd", "/opt/homebrew/bin/zstd"].filter(Boolean) + + for (const candidate of candidates) { + const args = candidate === "/opt/homebrew/bin/zstd" ? ["--version"] : ["--version"] + const result = spawnSync(candidate, args, { stdio: "ignore" }) + + if (result.status === 0) { + return candidate + } + } + + throw new Error('Unable to find "zstd". Set ZSTD_BIN or install zstd in PATH.') +} + +function execGit(args, cwd) { + const result = spawnSync("git", args, { + cwd, + encoding: "utf8", + }) + + if (result.status !== 0) { + throw new Error(result.stderr?.trim() || `git ${args.join(" ")} failed`) + } + + return result.stdout.trim() +} + +async function readJson(path) { + try { + return JSON.parse(await readFile(path, "utf8")) + } catch (error) { + const reason = error instanceof Error ? error.message : String(error) + throw new Error(`Failed to read JSON at ${path}: ${reason}`) + } +} + +function parseBooleanEnv(name, defaultValue) { + const value = process.env[name] + + if (value == null) { + return defaultValue + } + + if (value === "1" || value.toLowerCase() === "true") { + return true + } + + if (value === "0" || value.toLowerCase() === "false") { + return false + } + + throw new Error(`${name} must be "true", "false", "1", or "0"`) +} + +function parseNullableEnv(name) { + const value = process.env[name] + + if (value == null || value.length === 0) { + return null + } + + return value +} + +function once(callback) { + let called = false + + return (...args) => { + if (called) { + return + } + + called = true + callback(...args) + } +} + +if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) { + await main() +} diff --git a/.github/scripts/build-ota-release.test.ts b/.github/scripts/build-ota-release.test.ts new file mode 100644 index 000000000..4ee98eb85 --- /dev/null +++ b/.github/scripts/build-ota-release.test.ts @@ -0,0 +1,257 @@ +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" + +import { join } from "pathe" +import { afterEach, describe, expect, it } from "vitest" + +type InputAsset = string | { path: string; ext?: string } + +const tempDirs: string[] = [] + +afterEach(async () => { + await Promise.all( + tempDirs.splice(0).map((directory) => rm(directory, { recursive: true, force: true })), + ) +}) + +describe("buildOtaMetadata", () => { + it("preserves releaseVersion, runtimeVersion, and scoped git tag", async () => { + const { buildOtaMetadata } = await import("./build-ota-release.mjs") + + const result = await buildOtaMetadata({ + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + gitTag: "mobile/v0.4.2", + gitCommit: "abcdef1234567890", + publishedAt: "2026-04-10T12:00:00.000Z", + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.1", + message: null, + }, + metadata: { + fileMetadata: { + ios: { + bundle: "_expo/static/js/ios/main.hbc", + assets: [], + }, + android: { + bundle: "_expo/static/js/android/main.hbc", + assets: [], + }, + }, + }, + resolveAsset: async (assetPath: string) => ({ + path: assetPath, + sha256: `${assetPath}-sha256`.padEnd(64, "0").slice(0, 64), + contentType: "application/octet-stream", + }), + }) + + expect(result.releaseVersion).toBe("0.4.2") + expect(result.runtimeVersion).toBe("0.4.1") + expect(result.git.tag).toBe("mobile/v0.4.2") + expect(result.updateId).toMatch( + /^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/, + ) + }) + + it("uses asset ext metadata when exported asset paths have no suffix", async () => { + const { buildOtaMetadata } = await import("./build-ota-release.mjs") + + const result = await buildOtaMetadata({ + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + gitTag: "mobile/v0.4.2", + gitCommit: "abcdef1234567890", + publishedAt: "2026-04-10T12:00:00.000Z", + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.1", + message: null, + }, + metadata: { + fileMetadata: { + ios: { + bundle: "_expo/static/js/ios/main.hbc", + assets: [{ path: "assets/splash", ext: "png" }], + }, + android: { + bundle: "_expo/static/js/android/main.hbc", + assets: [], + }, + }, + }, + resolveAsset: async (asset: InputAsset) => { + const assetPath = typeof asset === "string" ? asset : asset.path + const ext = typeof asset === "string" ? undefined : asset.ext + + return { + path: assetPath, + sha256: `${assetPath}-sha256`.padEnd(64, "0").slice(0, 64), + contentType: ext === "png" ? "image/png" : "application/octet-stream", + } + }, + }) + + expect(result.platforms.ios.assets).toEqual([ + expect.objectContaining({ + path: "assets/splash", + contentType: "image/png", + }), + ]) + }) + + it("fails when a platform bundle is missing from export metadata", async () => { + const { buildOtaMetadata } = await import("./build-ota-release.mjs") + + await expect( + buildOtaMetadata({ + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + gitTag: "mobile/v0.4.2", + gitCommit: "abcdef1234567890", + publishedAt: "2026-04-10T12:00:00.000Z", + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.1", + message: null, + }, + metadata: { + fileMetadata: { + ios: { + bundle: "_expo/static/js/ios/main.hbc", + assets: [], + }, + }, + }, + resolveAsset: async (assetPath: string) => ({ + path: assetPath, + sha256: `${assetPath}-sha256`.padEnd(64, "0").slice(0, 64), + contentType: "application/octet-stream", + }), + }), + ).rejects.toThrow(/android/i) + }) + + it("fails when a platform assets array is missing from export metadata", async () => { + const { buildOtaMetadata } = await import("./build-ota-release.mjs") + + await expect( + buildOtaMetadata({ + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + gitTag: "mobile/v0.4.2", + gitCommit: "abcdef1234567890", + publishedAt: "2026-04-10T12:00:00.000Z", + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.1", + message: null, + }, + metadata: { + fileMetadata: { + ios: { + bundle: "_expo/static/js/ios/main.hbc", + }, + android: { + bundle: "_expo/static/js/android/main.hbc", + assets: [], + }, + }, + }, + resolveAsset: async (assetPath: string) => ({ + path: assetPath, + sha256: `${assetPath}-sha256`.padEnd(64, "0").slice(0, 64), + contentType: "application/octet-stream", + }), + }), + ).rejects.toThrow(/ios.*assets/i) + }) + + it("deduplicates repeated asset entries after path normalization", async () => { + const { buildOtaMetadata } = await import("./build-ota-release.mjs") + + const resolvedAssets: InputAsset[] = [] + + const result = await buildOtaMetadata({ + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + gitTag: "mobile/v0.4.2", + gitCommit: "abcdef1234567890", + publishedAt: "2026-04-10T12:00:00.000Z", + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.1", + message: null, + }, + metadata: { + fileMetadata: { + ios: { + bundle: "_expo/static/js/ios/main.hbc", + assets: ["./assets/icon.png", { path: "assets/icon.png" }], + }, + android: { + bundle: "_expo/static/js/android/main.hbc", + assets: [], + }, + }, + }, + resolveAsset: async (asset: InputAsset) => { + resolvedAssets.push(asset) + const assetPath = typeof asset === "string" ? asset : asset.path + + return { + path: assetPath, + sha256: `${assetPath}-sha256`.padEnd(64, "0").slice(0, 64), + contentType: "image/png", + } + }, + }) + + expect(result.platforms.ios.assets).toHaveLength(1) + expect( + resolvedAssets.filter((asset) => { + const assetPath = typeof asset === "string" ? asset : asset.path + + return assetPath === "assets/icon.png" + }), + ).toHaveLength(1) + }) +}) + +describe("buildReleaseAssets", () => { + it("includes the JSON file path when export metadata cannot be parsed", async () => { + const { buildReleaseAssets } = await import("./build-ota-release.mjs") + + const projectDir = await mkdtemp(join(tmpdir(), "build-ota-release-test-")) + const distDir = join(projectDir, "dist") + const metadataPath = join(distDir, "metadata.json") + tempDirs.push(projectDir) + + await mkdir(distDir, { recursive: true }) + await writeFile( + join(projectDir, "package.json"), + JSON.stringify({ name: "@follow/mobile-test", version: "0.4.2" }), + "utf8", + ) + await writeFile(metadataPath, "{invalid", "utf8") + + await expect(buildReleaseAssets({ projectDir })).rejects.toThrow(metadataPath) + }) +}) diff --git a/.github/scripts/trigger-ota-sync.mjs b/.github/scripts/trigger-ota-sync.mjs new file mode 100644 index 000000000..70aa6687a --- /dev/null +++ b/.github/scripts/trigger-ota-sync.mjs @@ -0,0 +1,95 @@ +#!/usr/bin/env node + +import { pathToFileURL } from "node:url" + +/** + * @typedef {{ + * baseUrl: string + * token: string + * headerName: string + * timeoutMs?: number + * }} TriggerOtaSyncOptions + */ + +const DEFAULT_TIMEOUT_MS = 10_000 + +/** + * @param {TriggerOtaSyncOptions} options + */ +export async function triggerOtaSync({ + baseUrl, + token, + headerName, + timeoutMs = DEFAULT_TIMEOUT_MS, +}) { + if (!baseUrl) { + throw new TypeError("OTA base URL is required") + } + + if (!token) { + throw new TypeError("OTA sync token is required") + } + + if (!headerName) { + throw new TypeError("OTA sync header name is required") + } + + if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) { + throw new TypeError("OTA sync timeout must be a positive integer") + } + + const normalizedBaseUrl = baseUrl.replace(/\/+$/, "") + const controller = new AbortController() + const timeoutError = new Error(`Timed out while triggering OTA sync after ${timeoutMs}ms`) + const timeoutId = setTimeout(() => { + controller.abort(timeoutError) + }, timeoutMs) + + try { + const response = await fetch(`${normalizedBaseUrl}/internal/sync`, { + method: "POST", + headers: { + [headerName]: token, + }, + signal: controller.signal, + }) + + if (!response.ok) { + const responseText = await response.text() + const detail = responseText ? `: ${responseText}` : "" + + throw new Error( + `Failed to trigger OTA sync (${response.status} ${response.statusText})${detail}`, + ) + } + + return response + } catch (error) { + if (controller.signal.aborted && controller.signal.reason === timeoutError) { + throw timeoutError + } + + throw error + } finally { + clearTimeout(timeoutId) + } +} + +async function main() { + try { + await triggerOtaSync({ + baseUrl: process.env.OTA_BASE_URL ?? "", + token: process.env.OTA_SYNC_TOKEN ?? "", + headerName: process.env.OTA_SYNC_TOKEN_HEADER ?? "", + }) + + console.info("Triggered OTA sync successfully") + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)) + process.exitCode = 1 + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + await main() +} diff --git a/.github/scripts/trigger-ota-sync.test.ts b/.github/scripts/trigger-ota-sync.test.ts new file mode 100644 index 000000000..21fedbd7d --- /dev/null +++ b/.github/scripts/trigger-ota-sync.test.ts @@ -0,0 +1,136 @@ +import { createServer } from "node:http" + +import { afterEach, describe, expect, it } from "vitest" + +const activeServers = new Set>() + +afterEach(async () => { + await Promise.all( + Array.from( + activeServers, + (server) => + new Promise((resolve, reject) => { + server.close((error) => { + if (error) { + reject(error) + return + } + + resolve() + }) + }), + ), + ) + activeServers.clear() +}) + +describe("triggerOtaSync", () => { + it("POSTs to /internal/sync with the configured auth header", async () => { + const requests: Array<{ method?: string; url?: string; headerValue?: string }> = [] + const headerName = "x-ota-sync-token" + const token = "sync-token-value" + + const server = createServer((request, response) => { + requests.push({ + method: request.method, + url: request.url, + headerValue: request.headers[headerName], + }) + + response.writeHead(204) + response.end() + }) + + activeServers.add(server) + + await new Promise((resolve, reject) => { + server.once("error", reject) + server.listen(0, "127.0.0.1", resolve) + }) + + const address = server.address() + if (!address || typeof address === "string") { + throw new TypeError("Expected the test server to bind to an ephemeral TCP port") + } + + const { triggerOtaSync } = await import("./trigger-ota-sync.mjs") + + await triggerOtaSync({ + baseUrl: `http://127.0.0.1:${address.port}`, + token, + headerName, + }) + + expect(requests).toEqual([ + { + method: "POST", + url: "/internal/sync", + headerValue: token, + }, + ]) + }) + + it("throws when the sync endpoint responds with a non-OK status", async () => { + const headerName = "x-ota-sync-token" + const token = "sync-token-value" + + const server = createServer((_request, response) => { + response.writeHead(503, { "content-type": "text/plain" }) + response.end("service unavailable") + }) + + activeServers.add(server) + + await new Promise((resolve, reject) => { + server.once("error", reject) + server.listen(0, "127.0.0.1", resolve) + }) + + const address = server.address() + if (!address || typeof address === "string") { + throw new TypeError("Expected the test server to bind to an ephemeral TCP port") + } + + const { triggerOtaSync } = await import("./trigger-ota-sync.mjs") + + await expect( + triggerOtaSync({ + baseUrl: `http://127.0.0.1:${address.port}`, + token, + headerName, + }), + ).rejects.toThrow("Failed to trigger OTA sync (503 Service Unavailable): service unavailable") + }) + + it("aborts the request when the timeout is exceeded", async () => { + const headerName = "x-ota-sync-token" + const token = "sync-token-value" + + const server = createServer((_request, _response) => { + // Intentionally never respond so the client must rely on the timeout. + }) + + activeServers.add(server) + + await new Promise((resolve, reject) => { + server.once("error", reject) + server.listen(0, "127.0.0.1", resolve) + }) + + const address = server.address() + if (!address || typeof address === "string") { + throw new TypeError("Expected the test server to bind to an ephemeral TCP port") + } + + const { triggerOtaSync } = await import("./trigger-ota-sync.mjs") + + await expect( + triggerOtaSync({ + baseUrl: `http://127.0.0.1:${address.port}`, + token, + headerName, + timeoutMs: 25, + }), + ).rejects.toThrow("Timed out while triggering OTA sync after 25ms") + }) +}) diff --git a/.github/workflows/publish-ota.yml b/.github/workflows/publish-ota.yml new file mode 100644 index 000000000..939595a9b --- /dev/null +++ b/.github/workflows/publish-ota.yml @@ -0,0 +1,107 @@ +name: 📡 Publish OTA Release + +on: + workflow_dispatch: + inputs: + release_version: + type: string + required: true + description: "Release version without the v prefix" + release_kind: + type: choice + required: true + options: + - ota + - store + description: "Release kind embedded in ota-release.json" + runtime_version: + type: string + required: true + description: "Expo runtime version for the OTA bundle" + channel: + type: choice + required: true + options: + - production + - preview + description: "OTA channel embedded in ota-release.json" + +permissions: + contents: write + +jobs: + publish: + if: github.secret_source != 'None' + runs-on: ubuntu-latest + env: + OTA_PRODUCT: mobile + OTA_RELEASE_VERSION: ${{ inputs.release_version }} + OTA_RELEASE_KIND: ${{ inputs.release_kind }} + OTA_RUNTIME_VERSION: ${{ inputs.runtime_version }} + OTA_CHANNEL: ${{ inputs.channel }} + OTA_GIT_TAG: mobile/v${{ inputs.release_version }} + + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + fetch-depth: 0 + + - name: Resolve target release tag + run: | + git fetch --tags --force + + if ! git rev-parse --verify "refs/tags/${OTA_GIT_TAG}" >/dev/null 2>&1; then + echo "::error::Required release tag ${OTA_GIT_TAG} does not exist. Create it before publishing OTA assets." + exit 1 + fi + + git checkout --detach "refs/tags/${OTA_GIT_TAG}" + echo "Checked out ${OTA_GIT_TAG} at $(git rev-list -n 1 "refs/tags/${OTA_GIT_TAG}")" + + - name: Setup pnpm + uses: pnpm/action-setup@v5 + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: 22 + cache: "pnpm" + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Export OTA bundle assets + working-directory: apps/mobile + run: pnpm run update:export + + - name: Build OTA release bundle + working-directory: apps/mobile + run: pnpm run update:bundle + + - name: Publish GitHub release assets + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + tag_name="mobile/v${OTA_RELEASE_VERSION}" + release_title="Mobile v${OTA_RELEASE_VERSION}" + ota_files=( + "apps/mobile/dist/ota-release.json" + "apps/mobile/dist.tar.zst" + ) + + if gh release view "$tag_name" >/dev/null 2>&1; then + gh release upload "$tag_name" "${ota_files[@]}" --clobber + else + gh release create "$tag_name" "${ota_files[@]}" \ + --verify-tag \ + --title "$release_title" \ + --notes "OTA release assets for ${OTA_RELEASE_KIND} releases on the ${OTA_CHANNEL} channel." + fi + + - name: Trigger OTA sync + env: + OTA_BASE_URL: ${{ secrets.OTA_BASE_URL }} + OTA_SYNC_TOKEN: ${{ secrets.OTA_SYNC_TOKEN }} + OTA_SYNC_TOKEN_HEADER: ${{ secrets.OTA_SYNC_TOKEN_HEADER }} + run: node .github/scripts/trigger-ota-sync.mjs diff --git a/.github/workflows/tag.yml b/.github/workflows/tag.yml index 01894e075..a20a8387d 100644 --- a/.github/workflows/tag.yml +++ b/.github/workflows/tag.yml @@ -73,6 +73,88 @@ jobs: runs-on: ubuntu-latest steps: + - name: Extract OTA release trailers + id: ota_release + if: needs.create_tag.outputs.platform == 'mobile' && needs.create_tag.outputs.ref_name == 'mobile-main' + env: + COMMIT_MESSAGE: ${{ github.event.head_commit.message }} + RELEASE_VERSION: ${{ needs.create_tag.outputs.version }} + run: | + ota_trailers="$(printf '%s\n' "$COMMIT_MESSAGE" | sed -nE '/^OTA_/p')" + normalized_release_version="${RELEASE_VERSION#v}" + + if [ -z "$ota_trailers" ]; then + echo "enabled=false" >> "$GITHUB_OUTPUT" + echo "release_kind=" >> "$GITHUB_OUTPUT" + echo "runtime_version=" >> "$GITHUB_OUTPUT" + echo "channel=" >> "$GITHUB_OUTPUT" + echo "release_version=${normalized_release_version}" >> "$GITHUB_OUTPUT" + exit 0 + fi + + invalid_trailers="$(printf '%s\n' "$ota_trailers" | sed -nE '/^OTA_(RELEASE_KIND|RUNTIME_VERSION|CHANNEL)=/!p')" + if [ -n "$invalid_trailers" ]; then + echo "::error::Unsupported OTA trailer lines detected:" + printf '%s\n' "$invalid_trailers" + exit 1 + fi + + release_kind_lines="$(printf '%s\n' "$COMMIT_MESSAGE" | sed -n '/^OTA_RELEASE_KIND=/p')" + runtime_version_lines="$(printf '%s\n' "$COMMIT_MESSAGE" | sed -n '/^OTA_RUNTIME_VERSION=/p')" + channel_lines="$(printf '%s\n' "$COMMIT_MESSAGE" | sed -n '/^OTA_CHANNEL=/p')" + + count_lines() { + local lines="$1" + + if [ -z "$lines" ]; then + echo 0 + return + fi + + printf '%s\n' "$lines" | wc -l | tr -d ' ' + } + + release_kind_count="$(count_lines "$release_kind_lines")" + runtime_version_count="$(count_lines "$runtime_version_lines")" + channel_count="$(count_lines "$channel_lines")" + + if [ "$release_kind_count" -ne 1 ] || [ "$runtime_version_count" -ne 1 ] || [ "$channel_count" -ne 1 ]; then + echo "::error::OTA trailers are incomplete or duplicated. Expected exactly one OTA_RELEASE_KIND, OTA_RUNTIME_VERSION, and OTA_CHANNEL trailer when any OTA_ trailer is present." + printf '%s\n' "$ota_trailers" + exit 1 + fi + + release_kind="$(printf '%s\n' "$release_kind_lines" | sed -nE 's/^OTA_RELEASE_KIND=(.*)$/\1/p' | tail -n 1)" + runtime_version="$(printf '%s\n' "$runtime_version_lines" | sed -nE 's/^OTA_RUNTIME_VERSION=(.*)$/\1/p' | tail -n 1)" + channel="$(printf '%s\n' "$channel_lines" | sed -nE 's/^OTA_CHANNEL=(.*)$/\1/p' | tail -n 1)" + + case "$release_kind" in + ota|store) ;; + *) + echo "::error::OTA_RELEASE_KIND must be either ota or store." + exit 1 + ;; + esac + + if [ -z "$runtime_version" ]; then + echo "::error::OTA_RUNTIME_VERSION must not be empty." + exit 1 + fi + + case "$channel" in + production|preview) ;; + *) + echo "::error::OTA_CHANNEL must be either production or preview." + exit 1 + ;; + esac + + echo "enabled=true" >> "$GITHUB_OUTPUT" + echo "release_kind=${release_kind}" >> "$GITHUB_OUTPUT" + echo "runtime_version=${runtime_version}" >> "$GITHUB_OUTPUT" + echo "channel=${channel}" >> "$GITHUB_OUTPUT" + echo "release_version=${normalized_release_version}" >> "$GITHUB_OUTPUT" + - name: Checkout repository if: needs.create_tag.outputs.platform == 'desktop' && needs.create_tag.outputs.ref_name == 'main' uses: actions/checkout@v6 @@ -199,3 +281,23 @@ jobs: } }); console.log('Mobile production iOS build triggered successfully'); + + - name: Trigger Mobile OTA Publish + if: needs.create_tag.outputs.platform == 'mobile' && needs.create_tag.outputs.ref_name == 'mobile-main' && steps.ota_release.outputs.enabled == 'true' + uses: actions/github-script@v9 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + await github.rest.actions.createWorkflowDispatch({ + owner: context.repo.owner, + repo: context.repo.repo, + workflow_id: 'publish-ota.yml', + ref: '${{ needs.create_tag.outputs.tag_version }}', + inputs: { + release_version: '${{ steps.ota_release.outputs.release_version }}', + release_kind: '${{ steps.ota_release.outputs.release_kind }}', + runtime_version: '${{ steps.ota_release.outputs.runtime_version }}', + channel: '${{ steps.ota_release.outputs.channel }}' + } + }); + console.log('Mobile OTA publish workflow triggered successfully'); diff --git a/apps/mobile/app.config.base.ts b/apps/mobile/app.config.base.ts index 3b081b45f..740a0c0e4 100644 --- a/apps/mobile/app.config.base.ts +++ b/apps/mobile/app.config.base.ts @@ -16,8 +16,19 @@ const adaptiveIconPath = resolve(__dirname, "./assets/adaptive-icon.png") const splashIconPath = resolve(__dirname, "./assets/splash-icon.png") const isDev = process.env.NODE_ENV === "development" +const channelNameMap = { + development: "development", + "ios-simulator": "development", + preview: "preview", + "e2e-android": "preview", + "e2e-ios-simulator": "preview", + production: "production", +} as Record export default ({ config }: ConfigContext): ExpoConfig => { + const profile = process.env.PROFILE || "production" + const channelName = channelNameMap[profile] || channelNameMap.production + const result: ExpoConfig = { ...config, @@ -29,15 +40,18 @@ export default ({ config }: ConfigContext): ExpoConfig => { e2eLanguage: process.env.EXPO_PUBLIC_E2E_LANGUAGE ?? null, }, owner: "follow", - // disable expo updates for now, https://github.com/expo/expo/issues/29630 - // updates: { - // url: "https://folo-custom-expo-updates.vercel.app/api/manifest", - // codeSigningCertificate: "./code-signing/certificate.pem", - // codeSigningMetadata: { - // keyid: "main", - // alg: "rsa-v1_5-sha256", - // }, - // }, + updates: { + url: "https://ota.folo.is/manifest", + requestHeaders: { + "expo-channel-name": channelName, + }, + codeSigningCertificate: "./code-signing/certificate.pem", + codeSigningMetadata: { + keyid: "main", + alg: "rsa-v1_5-sha256", + }, + checkAutomatically: "NEVER", + }, runtimeVersion: isDev ? "0.0.0-dev" : PKG.version, name: "Folo", diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 174b4d427..d84f09290 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -21,6 +21,8 @@ "start:clean": "expo start --dev-client --clear", "typecheck": "tsc --noEmit", "update": "tsx scripts/expo-update.ts", + "update:bundle": "node ../../.github/scripts/build-ota-release.mjs", + "update:export": "expo export -p ios -p android --output-dir dist", "web": "expo start --web" }, "dependencies": { diff --git a/apps/mobile/scripts/expo-update.ts b/apps/mobile/scripts/expo-update.ts old mode 100755 new mode 100644 index e364b0a15..2d4fa3daf --- a/apps/mobile/scripts/expo-update.ts +++ b/apps/mobile/scripts/expo-update.ts @@ -1,52 +1,41 @@ import { spawn } from "node:child_process" -import fs from "node:fs" -import fsp from "node:fs/promises" import { fileURLToPath } from "node:url" -import { getConfig } from "@expo/config" import { dirname, join } from "pathe" -import { version } from "../package.json" +async function spawnAsync(command: string, args: string[], cwd: string) { + return new Promise((resolve, reject) => { + const child = spawn(command, args, { + cwd, + stdio: "inherit", + shell: true, + }) -async function spawnAsync(command: string, args: string[]) { - return new Promise((resolve, reject) => { - const child = spawn(command, args, { stdio: "inherit", shell: true }) child.on("close", (code) => { if (code === 0) { - resolve(void 0) - } else { - reject(new Error(`Command failed with exit code ${code}`)) + resolve() + return } + + reject(new Error(`Command failed with exit code ${code}: ${command} ${args.join(" ")}`)) }) }) } async function main() { - await spawnAsync("expo", ["export", "-p", "ios", "-p", "android"]) - const __dirname = dirname(fileURLToPath(import.meta.url)) const projectDir = join(__dirname, "..") + const bundleScriptPath = join( + projectDir, + "..", + "..", + ".github", + "scripts", + "build-ota-release.mjs", + ) - const expoUpdatesServerRoot = join(projectDir, "../", "../", "../", "expo-updates-server") - const timestamp = Date.now() - const updatesFolder = join(expoUpdatesServerRoot, "updates", version, `${timestamp}`) - - if (!fs.existsSync(updatesFolder)) { - fs.mkdirSync(updatesFolder, { recursive: true }) - } - - // cp dist to expo-updates-server - const distFolder = join(projectDir, "dist") - await fsp.cp(distFolder, updatesFolder, { recursive: true }) - - const { exp } = getConfig(projectDir, { - skipSDKVersionRequirement: true, - isPublicConfig: true, - }) - - const expoConfig = JSON.stringify(exp, null, 2) - const expoConfigPath = join(updatesFolder, "expoConfig.json") - fs.writeFileSync(expoConfigPath, expoConfig) + await spawnAsync("pnpm", ["run", "update:export"], projectDir) + await spawnAsync(process.execPath, [bundleScriptPath], projectDir) } main() diff --git a/apps/mobile/src/main.tsx b/apps/mobile/src/main.tsx index 9dd2a39c2..ce26480dd 100644 --- a/apps/mobile/src/main.tsx +++ b/apps/mobile/src/main.tsx @@ -21,6 +21,7 @@ import { TabRoot } from "./lib/navigation/bottom-tab/TabRoot" import { TabScreen } from "./lib/navigation/bottom-tab/TabScreen" import { RootStackNavigation } from "./lib/navigation/StackNavigation" import { queryClient } from "./lib/query-client" +import { OtaProvider } from "./modules/ota/provider" import { RootProviders } from "./providers" import { IndexTabScreen } from "./screens/(stack)/(tabs)" import { DiscoverTabScreen } from "./screens/(stack)/(tabs)/discover" @@ -49,56 +50,58 @@ registerRootComponent(RootComponent) function RootComponent() { const { t } = useTranslation() return ( - - - - - - - - + + + + + + + + + - - - + + + - - - - - - + + + + + + - - - - - - - + + + + + + + + ) } diff --git a/apps/mobile/src/modules/debug/index.tsx b/apps/mobile/src/modules/debug/index.tsx index 0b2dc0a5c..574e86992 100644 --- a/apps/mobile/src/modules/debug/index.tsx +++ b/apps/mobile/src/modules/debug/index.tsx @@ -14,6 +14,8 @@ import { BugCuteReIcon } from "@/src/icons/bug_cute_re" import { JotaiPersistSyncStorage } from "@/src/lib/jotai" import { Navigation } from "@/src/lib/navigation/Navigation" import { setEnvProfile, useEnvProfile } from "@/src/lib/proxy-env" +import { toast } from "@/src/lib/toast" +import { useOtaActions, useOtaState } from "@/src/modules/ota/provider" import { DebugScreen } from "@/src/screens/(headless)/DebugScreen" export const DebugButton = () => { @@ -39,6 +41,9 @@ export const DebugButton = () => { const translateY = useSharedValue(point.y) const startX = useSharedValue(point.x) const startY = useSharedValue(point.y) + const openDebugScreen = () => { + Navigation.rootNavigation.pushControllerView(DebugScreen) + } const gestureEvent = Gesture.Pan() .onStart(() => { startX.value = translateX.value @@ -50,7 +55,7 @@ export const DebugButton = () => { }) .onEnd((event) => { if (Math.abs(event.translationX) < 5 && Math.abs(event.translationY) < 5) { - runOnJS(Navigation.rootNavigation.pushControllerView)(DebugScreen) + runOnJS(openDebugScreen)() return } const snapToLeft = true @@ -78,7 +83,7 @@ export const DebugButton = () => { { - Navigation.rootNavigation.pushControllerView(DebugScreen) + openDebugScreen() }} style={animatedStyle} className="absolute right-0 top-[-20] z-[100] mt-5 flex size-8 items-center justify-center rounded-l-md bg-accent" @@ -90,7 +95,37 @@ export const DebugButton = () => { } export const EnvProfileIndicator = () => { const envProfile = useEnvProfile() + const otaState = useOtaState() + const { checkForUpdates, reloadUpdate } = useOtaActions() if (!__DEV__ && envProfile === "prod") return null + + const handleCheckOtaUpdate = async () => { + try { + const result = await checkForUpdates() + if (result.kind === "available") { + toast.success(`OTA update ${result.version} is ready`) + return + } + + toast.info("No OTA update available") + } catch (error) { + toast.error(error instanceof Error ? error.message : "Failed to check OTA update") + } + } + + const handleReloadOtaUpdate = async () => { + if (!otaState.pendingVersion) { + toast.info("No OTA update is ready") + return + } + + try { + await reloadUpdate() + } catch (error) { + toast.error(error instanceof Error ? error.message : "Failed to reload OTA update") + } + } + return ( { ) })} + { + void handleCheckOtaUpdate() + }} + > + Check OTA Update + + { + void handleReloadOtaUpdate() + }} + > + + {otaState.pendingVersion + ? `Reload OTA Update (${otaState.pendingVersion})` + : "Reload OTA Update"} + + diff --git a/apps/mobile/src/modules/ota/__tests__/client.test.ts b/apps/mobile/src/modules/ota/__tests__/client.test.ts new file mode 100644 index 000000000..b9d391658 --- /dev/null +++ b/apps/mobile/src/modules/ota/__tests__/client.test.ts @@ -0,0 +1,74 @@ +import { beforeEach, describe, expect, it, vi } from "vitest" + +import { fetchStorePolicy } from "../client" + +describe("fetchStorePolicy", () => { + beforeEach(() => { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ action: "block", targetVersion: "0.4.3", message: "Update required" }), + { + status: 200, + headers: { "content-type": "application/json" }, + }, + ), + ), + ) + }) + + it("returns the parsed policy response", async () => { + const result = await fetchStorePolicy({ + baseUrl: "https://ota.folo.is", + product: "mobile", + channel: "production", + installedBinaryVersion: "0.4.1", + }) + + expect(result.action).toBe("block") + expect(result.targetVersion).toBe("0.4.3") + }) + + it("throws when the policy request fails", async () => { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue( + new Response(JSON.stringify({ message: "Internal Server Error" }), { + status: 500, + headers: { "content-type": "application/json" }, + }), + ), + ) + + await expect( + fetchStorePolicy({ + baseUrl: "https://ota.folo.is", + product: "mobile", + channel: "production", + installedBinaryVersion: "0.4.1", + }), + ).rejects.toThrow("Failed to fetch OTA policy") + }) + + it("throws when the policy payload is invalid", async () => { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue( + new Response(JSON.stringify({ action: "warn", targetVersion: "0.4.3", message: null }), { + status: 200, + headers: { "content-type": "application/json" }, + }), + ), + ) + + await expect( + fetchStorePolicy({ + baseUrl: "https://ota.folo.is", + product: "mobile", + channel: "production", + installedBinaryVersion: "0.4.1", + }), + ).rejects.toThrow("Invalid OTA policy response") + }) +}) diff --git a/apps/mobile/src/modules/ota/__tests__/provider.test.ts b/apps/mobile/src/modules/ota/__tests__/provider.test.ts new file mode 100644 index 000000000..5a2c71ec2 --- /dev/null +++ b/apps/mobile/src/modules/ota/__tests__/provider.test.ts @@ -0,0 +1,113 @@ +import { beforeAll, describe, expect, it, vi } from "vitest" + +vi.mock("expo-application", () => ({ + nativeApplicationVersion: "0.4.1", +})) + +vi.mock("expo-updates", () => ({ + default: {}, + channel: "production", + runtimeVersion: "0.4.1", + isEnabled: true, + reloadAsync: vi.fn(), + useUpdates: vi.fn(), + UpdateInfoType: { + NEW: "new", + }, +})) + +vi.mock("react-native", () => ({ + InteractionManager: { + runAfterInteractions: (callback: () => void) => { + callback() + return { + cancel: vi.fn(), + } + }, + }, +})) + +let runSafeReloadUpdate: typeof import("../provider").runSafeReloadUpdate +let runWithSingleInFlight: typeof import("../provider").runWithSingleInFlight + +beforeAll(async () => { + ;({ runSafeReloadUpdate, runWithSingleInFlight } = await import("../provider")) +}) + +describe("runWithSingleInFlight", () => { + it("deduplicates concurrent calls and clears after resolution", async () => { + let resolveRun: ((value: { kind: "idle" }) => void) | null = null + const inFlightRef: { current: Promise<{ kind: "idle" }> | null } = { current: null } + const run = vi.fn( + () => + new Promise<{ kind: "idle" }>((resolve) => { + resolveRun = resolve + }), + ) + + const first = runWithSingleInFlight({ + inFlightRef, + run, + }) + const second = runWithSingleInFlight({ + inFlightRef, + run, + }) + + expect(run).toHaveBeenCalledTimes(1) + expect(second).toBe(first) + + expect(resolveRun).not.toBeNull() + resolveRun!({ kind: "idle" }) + + await expect(first).resolves.toEqual({ kind: "idle" }) + expect(inFlightRef.current).toBeNull() + + const nextRun = vi.fn().mockResolvedValue({ kind: "idle" as const }) + const third = runWithSingleInFlight({ + inFlightRef, + run: nextRun, + }) + + await expect(third).resolves.toEqual({ kind: "idle" }) + expect(nextRun).toHaveBeenCalledTimes(1) + }) +}) + +describe("runSafeReloadUpdate", () => { + it("does not reload when updates are disabled", async () => { + const reload = vi.fn().mockResolvedValue() + + await runSafeReloadUpdate({ + isEnabled: false, + pendingVersion: "0.4.3", + reload, + }) + + expect(reload).not.toHaveBeenCalled() + }) + + it("does not reload when no pending update exists", async () => { + const reload = vi.fn().mockResolvedValue() + + await runSafeReloadUpdate({ + isEnabled: true, + pendingVersion: null, + reload, + }) + + expect(reload).not.toHaveBeenCalled() + }) + + it("reloads when updates are enabled and a pending version exists", async () => { + const reload = vi.fn().mockResolvedValue() + + await runSafeReloadUpdate({ + isEnabled: true, + pendingVersion: "0.4.3", + reload, + }) + + expect(reload).toHaveBeenCalledTimes(1) + }) +}) diff --git a/apps/mobile/src/modules/ota/__tests__/store.test.ts b/apps/mobile/src/modules/ota/__tests__/store.test.ts new file mode 100644 index 000000000..8b5cc4777 --- /dev/null +++ b/apps/mobile/src/modules/ota/__tests__/store.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it } from "vitest" + +import { reduceOtaState } from "../store" + +describe("reduceOtaState", () => { + it("marks an update as downloaded and ready on next launch", () => { + const state = reduceOtaState( + { + status: "idle", + pendingVersion: null, + errorMessage: null, + }, + { + type: "downloaded", + version: "0.4.2", + }, + ) + + expect(state.status).toBe("ready") + expect(state.pendingVersion).toBe("0.4.2") + expect(state.errorMessage).toBeNull() + }) + + it("stores the latest error without clearing the pending version", () => { + const state = reduceOtaState( + { + status: "ready", + pendingVersion: "0.4.2", + errorMessage: null, + }, + { + type: "failed", + message: "Network unavailable", + }, + ) + + expect(state.status).toBe("error") + expect(state.pendingVersion).toBe("0.4.2") + expect(state.errorMessage).toBe("Network unavailable") + }) + + it("resets the OTA state back to idle", () => { + const state = reduceOtaState( + { + status: "error", + pendingVersion: "0.4.2", + errorMessage: "Network unavailable", + }, + { + type: "reset", + }, + ) + + expect(state.status).toBe("idle") + expect(state.pendingVersion).toBeNull() + expect(state.errorMessage).toBeNull() + }) +}) diff --git a/apps/mobile/src/modules/ota/client.ts b/apps/mobile/src/modules/ota/client.ts new file mode 100644 index 000000000..753913c92 --- /dev/null +++ b/apps/mobile/src/modules/ota/client.ts @@ -0,0 +1,45 @@ +import { z } from "zod" + +export interface FetchStorePolicyInput { + baseUrl: string + product: string + channel: string + installedBinaryVersion: string +} + +const storePolicySchema = z.object({ + action: z.enum(["none", "prompt", "block"]), + targetVersion: z.string().nullable(), + message: z.string().nullable(), +}) + +export interface StorePolicyResponse { + action: z.infer["action"] + targetVersion: string | null + message: string | null +} + +export const fetchStorePolicy = async ({ + baseUrl, + product, + channel, + installedBinaryVersion, +}: FetchStorePolicyInput): Promise => { + const requestUrl = new URL("/policy", baseUrl) + requestUrl.searchParams.set("product", product) + requestUrl.searchParams.set("channel", channel) + requestUrl.searchParams.set("installedBinaryVersion", installedBinaryVersion) + + const response = await fetch(requestUrl.toString()) + if (!response.ok) { + throw new Error(`Failed to fetch OTA policy (${response.status})`) + } + + const payload = await response.json() + const result = storePolicySchema.safeParse(payload) + if (!result.success) { + throw new Error("Invalid OTA policy response") + } + + return result.data +} diff --git a/apps/mobile/src/modules/ota/provider.tsx b/apps/mobile/src/modules/ota/provider.tsx new file mode 100644 index 000000000..284814678 --- /dev/null +++ b/apps/mobile/src/modules/ota/provider.tsx @@ -0,0 +1,355 @@ +import { nativeApplicationVersion } from "expo-application" +import type { Manifest } from "expo-updates" +import * as Updates from "expo-updates" +import type { + ActionDispatch, + Dispatch, + MutableRefObject, + PropsWithChildren, + SetStateAction, +} from "react" +import { createContext, use, useEffect, useMemo, useReducer, useRef, useState } from "react" +import { InteractionManager } from "react-native" + +import type { StorePolicyResponse } from "./client" +import { fetchStorePolicy } from "./client" +import { initialOtaState, reduceOtaState } from "./store" +import type { OtaAction, OtaState } from "./types" + +const OtaContext = createContext(initialOtaState) +const OtaBaseUrl = "https://ota.folo.is" +const OtaProduct = "mobile" + +export type OtaCheckForUpdatesResult = { kind: "available"; version: string } | { kind: "idle" } + +interface OtaActions { + checkForUpdates: () => Promise + reloadUpdate: () => Promise +} + +const OtaActionsContext = createContext({ + checkForUpdates: async () => ({ kind: "idle" }), + reloadUpdate: async () => {}, +}) + +const resolvePendingVersion = (manifest: Manifest | undefined): string => { + if (!manifest) { + return Updates.runtimeVersion ?? "unknown" + } + + const metadataReleaseVersion = + "metadata" in manifest && manifest.metadata && typeof manifest.metadata === "object" + ? Reflect.get(manifest.metadata, "releaseVersion") + : undefined + + if (typeof metadataReleaseVersion === "string" && metadataReleaseVersion.length > 0) { + return metadataReleaseVersion + } + + if ("runtimeVersion" in manifest && typeof manifest.runtimeVersion === "string") { + return manifest.runtimeVersion + } + + return Updates.runtimeVersion ?? "unknown" +} + +const getOtaChannel = () => Updates.channel ?? "default" + +const getInstalledBinaryVersion = () => + nativeApplicationVersion ?? Updates.runtimeVersion ?? "unknown" + +const getErrorMessage = (error: unknown, fallback: string) => { + return error instanceof Error ? error.message : fallback +} + +export function runWithSingleInFlight({ + inFlightRef, + run, +}: { + inFlightRef: { current: Promise | null } + run: () => Promise +}) { + if (inFlightRef.current) { + return inFlightRef.current + } + + const promise = run().finally(() => { + if (inFlightRef.current === promise) { + inFlightRef.current = null + } + }) + + inFlightRef.current = promise + return promise +} + +export const runSafeReloadUpdate = async ({ + isEnabled, + pendingVersion, + reload, +}: { + isEnabled: boolean + pendingVersion: string | null + reload: () => Promise +}) => { + if (!isEnabled || !pendingVersion) { + return + } + + await reload() +} + +const runOtaCheck = async ({ + dispatch, + currentPendingVersion, + isUpdatePending, + shouldCancel = () => false, +}: { + dispatch: ActionDispatch<[action: OtaAction]> + currentPendingVersion: string | null + isUpdatePending: boolean + shouldCancel?: () => boolean +}): Promise => { + const dispatchIfActive = (action: OtaAction) => { + if (!shouldCancel()) { + dispatch(action) + } + } + + try { + if (currentPendingVersion) { + if (shouldCancel()) { + return { kind: "idle" } + } + + dispatchIfActive({ + type: "downloaded", + version: currentPendingVersion, + }) + return { kind: "available", version: currentPendingVersion } + } + + dispatchIfActive({ type: "checking" }) + + const checkResult = await Updates.checkForUpdateAsync() + if (shouldCancel()) { + return { kind: "idle" } + } + + if (!checkResult.isAvailable) { + if (!isUpdatePending) { + dispatchIfActive({ type: "reset" }) + } + return { kind: "idle" } + } + + dispatchIfActive({ type: "downloading" }) + + const fetchResult = await Updates.fetchUpdateAsync() + if (shouldCancel()) { + return { kind: "idle" } + } + + if (fetchResult.isNew && fetchResult.manifest) { + const version = resolvePendingVersion(fetchResult.manifest) + dispatchIfActive({ + type: "downloaded", + version, + }) + return { kind: "available", version } + } + + if (!isUpdatePending) { + dispatchIfActive({ type: "reset" }) + } + + return { kind: "idle" } + } catch (error) { + dispatchIfActive({ + type: "failed", + message: getErrorMessage(error, "Failed to check for updates."), + }) + + throw error instanceof Error ? error : new Error("Failed to check for updates.") + } +} + +const refreshStorePolicyInBackground = ({ + setStorePolicy, + shouldCancel = () => false, +}: { + setStorePolicy: Dispatch> + shouldCancel?: () => boolean +}) => { + void fetchStorePolicy({ + baseUrl: OtaBaseUrl, + product: OtaProduct, + channel: getOtaChannel(), + installedBinaryVersion: getInstalledBinaryVersion(), + }) + .then((policy) => { + if (!shouldCancel()) { + setStorePolicy(policy) + } + }) + .catch((error) => { + console.warn("[ota] Failed to fetch store policy", error) + }) +} + +const runGuardedOtaCheck = ({ + dispatch, + setStorePolicy, + inFlightRef, + currentPendingVersion, + isUpdatePending, + shouldCancel = () => false, +}: { + dispatch: ActionDispatch<[action: OtaAction]> + setStorePolicy: Dispatch> + inFlightRef: MutableRefObject | null> + currentPendingVersion: string | null + isUpdatePending: boolean + shouldCancel?: () => boolean +}) => { + if (!Updates.isEnabled) { + return Promise.resolve({ kind: "idle" } satisfies OtaCheckForUpdatesResult) + } + + if (inFlightRef.current) { + return inFlightRef.current + } + + refreshStorePolicyInBackground({ + setStorePolicy, + shouldCancel, + }) + + return runWithSingleInFlight({ + inFlightRef, + run: () => + runOtaCheck({ + dispatch, + currentPendingVersion, + isUpdatePending, + shouldCancel, + }), + }) +} + +export const OtaProvider = ({ children }: PropsWithChildren) => { + const { checkError, downloadError, downloadedUpdate, isUpdatePending } = Updates.useUpdates() + const [state, dispatch] = useReducer(reduceOtaState, initialOtaState) + const [, setStorePolicy] = useState(null) + const checkInFlightRef = useRef | null>(null) + const isUnmountedRef = useRef(false) + + const nativePendingVersion = useMemo(() => { + if (!isUpdatePending || downloadedUpdate?.type !== Updates.UpdateInfoType.NEW) { + return null + } + + return resolvePendingVersion(downloadedUpdate.manifest) + }, [downloadedUpdate, isUpdatePending]) + + const currentPendingVersion = nativePendingVersion ?? state.pendingVersion + + useEffect(() => { + return () => { + isUnmountedRef.current = true + } + }, []) + + useEffect(() => { + if (!nativePendingVersion) { + return + } + + dispatch({ + type: "downloaded", + version: nativePendingVersion, + }) + }, [nativePendingVersion]) + + useEffect(() => { + const error = downloadError || checkError + if (!error) { + return + } + + dispatch({ + type: "failed", + message: error.message, + }) + }, [checkError, downloadError]) + + useEffect(() => { + if (__DEV__ || !Updates.isEnabled || nativePendingVersion) { + return + } + + const runBackgroundCheck = async () => { + try { + await runGuardedOtaCheck({ + dispatch, + setStorePolicy, + inFlightRef: checkInFlightRef, + currentPendingVersion: nativePendingVersion, + isUpdatePending, + shouldCancel: () => isUnmountedRef.current, + }) + } catch { + // runOtaCheck already syncs OTA failures into state. + } + } + + const task = InteractionManager.runAfterInteractions(() => { + void runBackgroundCheck() + }) + + return () => { + task.cancel() + } + }, [isUpdatePending, nativePendingVersion]) + + const actions = useMemo(() => { + return { + checkForUpdates: async () => + runGuardedOtaCheck({ + dispatch, + setStorePolicy, + inFlightRef: checkInFlightRef, + currentPendingVersion, + isUpdatePending, + shouldCancel: () => isUnmountedRef.current, + }), + reloadUpdate: async () => + runSafeReloadUpdate({ + isEnabled: Updates.isEnabled, + pendingVersion: currentPendingVersion, + reload: () => Updates.reloadAsync(), + }), + } + }, [currentPendingVersion, isUpdatePending]) + + const value = useMemo(() => { + if (!currentPendingVersion) { + return state + } + + return { + status: "ready" as const, + pendingVersion: currentPendingVersion, + errorMessage: null, + } + }, [currentPendingVersion, state]) + + return ( + + {children} + + ) +} + +export const useOtaState = () => use(OtaContext) +export const useOtaActions = () => use(OtaActionsContext) diff --git a/apps/mobile/src/modules/ota/store.ts b/apps/mobile/src/modules/ota/store.ts new file mode 100644 index 000000000..820bc3dd9 --- /dev/null +++ b/apps/mobile/src/modules/ota/store.ts @@ -0,0 +1,46 @@ +import type { OtaAction, OtaState } from "./types" + +export const initialOtaState: OtaState = { + status: "idle", + pendingVersion: null, + errorMessage: null, +} + +export const reduceOtaState = (state: OtaState, action: OtaAction): OtaState => { + switch (action.type) { + case "checking": { + return { + ...state, + status: "checking", + errorMessage: null, + } + } + case "downloading": { + return { + ...state, + status: "downloading", + errorMessage: null, + } + } + case "downloaded": { + return { + status: "ready", + pendingVersion: action.version, + errorMessage: null, + } + } + case "failed": { + return { + ...state, + status: "error", + errorMessage: action.message, + } + } + case "reset": { + return initialOtaState + } + default: { + return state + } + } +} diff --git a/apps/mobile/src/modules/ota/types.ts b/apps/mobile/src/modules/ota/types.ts new file mode 100644 index 000000000..2c26dec61 --- /dev/null +++ b/apps/mobile/src/modules/ota/types.ts @@ -0,0 +1,14 @@ +export type OtaStatus = "idle" | "checking" | "downloading" | "ready" | "error" + +export interface OtaState { + status: OtaStatus + pendingVersion: string | null + errorMessage: string | null +} + +export type OtaAction = + | { type: "checking" } + | { type: "downloading" } + | { type: "downloaded"; version: string } + | { type: "reset" } + | { type: "failed"; message: string } diff --git a/apps/mobile/vitest.config.ts b/apps/mobile/vitest.config.ts index 43837105c..85a9e5f47 100644 --- a/apps/mobile/vitest.config.ts +++ b/apps/mobile/vitest.config.ts @@ -4,6 +4,6 @@ export default defineConfig({ root: import.meta.dirname, test: { environment: "node", - include: ["src/**/*.test.ts", "src/**/*.spec.ts"], + include: ["src/**/*.test.ts", "src/**/*.spec.ts", "../../.github/scripts/**/*.test.ts"], }, }) diff --git a/apps/ota/README.md b/apps/ota/README.md new file mode 100644 index 000000000..f0bd4b5db --- /dev/null +++ b/apps/ota/README.md @@ -0,0 +1,192 @@ +# OTA Service Operations + +This runbook covers release rollout verification and rollback for the `apps/ota` Cloudflare Worker. + +## Scope + +- GitHub Releases is the publishing source of truth. +- Cloudflare Worker, KV, and R2 are the delivery layer. +- Run Wrangler commands from `apps/ota`. +- The verified v1 routes are: + - `GET /manifest` + - `GET /assets/*` + - `GET /policy` + - `POST /internal/sync` + - `GET /internal/health` + +## Request Shape + +`/manifest`: + +- Requires `expo-platform` and `expo-runtime-version` headers. +- Accepts `expo-channel-name`; defaults to `production`. +- Accepts `product`; defaults to `mobile`. +- Returns `204` when no compatible OTA release exists. + +`/policy`: + +- Requires `installedBinaryVersion`. +- Accepts `channel`; defaults to `production`. +- Accepts `product`; defaults to `mobile`. + +## Release Checklist + +1. Confirm the Git tag exists for the target release, for example `mobile/v0.4.2`. +2. Confirm the GitHub Release contains both `ota-release.json` and `dist.tar.zst`. +3. Trigger an OTA sync after publishing or updating release assets. +4. Verify `/internal/health` reports a fresh `lastSuccessAt`. +5. Verify `/manifest` resolves the expected `releaseVersion` for every target platform. +6. Download the returned launch asset URL and confirm it is reachable. +7. Verify `/policy` returns the expected action for the installed binary version. +8. Run the automated OTA and mobile verification commands before closing the rollout. + +## Rollback Checklist + +1. Identify the last known good OTA release version for the affected `channel`, `runtimeVersion`, and platform set. +2. Read the current KV pointers before changing anything. +3. Overwrite the affected `latest::::` keys with the previous good `releaseVersion`. +4. If the issue is a bad store policy release, overwrite `policy::` with the previous good store release record. +5. Re-run the manual verification commands for `/manifest` and `/policy`. +6. Correct the GitHub Release source of truth before the next sync. + +## Verified v1 Limitation + +Rollback by KV pointer edit is only a temporary mitigation in the current implementation. + +The sync job always promotes the highest compatible `releaseVersion` from GitHub Releases. If the bad release still exists as a valid published source, the next scheduled or manual sync can point `latest:*` back to the bad version. + +Do not rely on KV edits alone. Before the next sync, either: + +- remove or invalidate the bad OTA release assets from GitHub Releases, or +- publish a newer corrective OTA release on the same `runtimeVersion`. + +Hard freeze and disable flags are not implemented in the verified v1 Worker yet. + +## Environment Variables + +Set these before running the manual checks: + +```bash +export OTA_BASE_URL="https://ota.folo.is" +export OTA_PRODUCT="mobile" +export OTA_CHANNEL="production" +export OTA_RUNTIME_VERSION="0.4.1" +export OTA_INSTALLED_BINARY_VERSION="0.4.1" +export OTA_RELEASE_VERSION="0.4.2" +export OTA_SYNC_TOKEN_HEADER="x-ota-sync-token" +export OTA_SYNC_TOKEN="" +export OTA_GOOD_RELEASE_VERSION="0.4.1" +export OTA_GOOD_STORE_VERSION="0.4.1" +``` + +## Manual Verification Commands + +Trigger a sync and inspect health: + +```bash +OTA_BASE_URL="$OTA_BASE_URL" \ +OTA_SYNC_TOKEN="$OTA_SYNC_TOKEN" \ +OTA_SYNC_TOKEN_HEADER="$OTA_SYNC_TOKEN_HEADER" \ +node ../../.github/scripts/trigger-ota-sync.mjs + +curl --fail --silent --show-error \ + "$OTA_BASE_URL/internal/health" +``` + +Verify `/manifest` for iOS: + +```bash +curl --fail --silent --show-error \ + -D /tmp/ota-manifest.headers \ + -H "expo-platform: ios" \ + -H "expo-runtime-version: $OTA_RUNTIME_VERSION" \ + -H "expo-channel-name: $OTA_CHANNEL" \ + "$OTA_BASE_URL/manifest?product=$OTA_PRODUCT" \ + | tee /tmp/ota-manifest.json + +jq -r '.metadata.releaseVersion' /tmp/ota-manifest.json +jq -r '.launchAsset.url' /tmp/ota-manifest.json + +curl --fail --silent --show-error \ + "$(jq -r '.launchAsset.url' /tmp/ota-manifest.json)" \ + -o /tmp/ota-launch-asset +``` + +Verify `/manifest` for Android: + +```bash +curl --fail --silent --show-error \ + -H "expo-platform: android" \ + -H "expo-runtime-version: $OTA_RUNTIME_VERSION" \ + -H "expo-channel-name: $OTA_CHANNEL" \ + "$OTA_BASE_URL/manifest?product=$OTA_PRODUCT" \ + | jq -r '.metadata.releaseVersion' +``` + +Verify `/policy`: + +```bash +curl --fail --silent --show-error \ + "$OTA_BASE_URL/policy?product=$OTA_PRODUCT&channel=$OTA_CHANNEL&installedBinaryVersion=$OTA_INSTALLED_BINARY_VERSION" \ + | tee /tmp/ota-policy.json + +jq . /tmp/ota-policy.json +``` + +## Manual Rollback Commands + +Inspect current pointers: + +```bash +pnpm exec wrangler kv key get "latest:$OTA_PRODUCT:$OTA_CHANNEL:$OTA_RUNTIME_VERSION:ios" \ + --binding OTA_KV \ + --remote \ + --text + +pnpm exec wrangler kv key get "latest:$OTA_PRODUCT:$OTA_CHANNEL:$OTA_RUNTIME_VERSION:android" \ + --binding OTA_KV \ + --remote \ + --text +``` + +Rollback OTA pointers to the previous good release: + +```bash +pnpm exec wrangler kv key put "latest:$OTA_PRODUCT:$OTA_CHANNEL:$OTA_RUNTIME_VERSION:ios" \ + "{\"releaseVersion\":\"$OTA_GOOD_RELEASE_VERSION\"}" \ + --binding OTA_KV \ + --remote + +pnpm exec wrangler kv key put "latest:$OTA_PRODUCT:$OTA_CHANNEL:$OTA_RUNTIME_VERSION:android" \ + "{\"releaseVersion\":\"$OTA_GOOD_RELEASE_VERSION\"}" \ + --binding OTA_KV \ + --remote +``` + +Rollback the store policy pointer: + +```bash +pnpm exec wrangler kv key get "release:$OTA_PRODUCT:$OTA_GOOD_STORE_VERSION" \ + --binding OTA_KV \ + --remote \ + --text \ + > /tmp/ota-good-store-release.json + +pnpm exec wrangler kv key put "policy:$OTA_PRODUCT:$OTA_CHANNEL" \ + --path /tmp/ota-good-store-release.json \ + --binding OTA_KV \ + --remote +``` + +## Automated Verification Commands + +Run these from the repository root: + +```bash +pnpm --filter @follow/ota test +pnpm --filter @follow/ota typecheck +pnpm --filter @follow/mobile exec vitest run src/modules/ota/__tests__/client.test.ts src/modules/ota/__tests__/store.test.ts src/modules/ota/__tests__/provider.test.ts +pnpm --filter @follow/mobile typecheck +pnpm exec prettier --check .github/workflows/publish-ota.yml .github/workflows/tag.yml .github/scripts/trigger-ota-sync.mjs .github/scripts/trigger-ota-sync.test.ts +pnpm exec prettier --check .github/scripts/build-ota-release.mjs .github/scripts/build-ota-release.test.ts +``` diff --git a/apps/ota/package.json b/apps/ota/package.json new file mode 100644 index 000000000..094f6ebee --- /dev/null +++ b/apps/ota/package.json @@ -0,0 +1,26 @@ +{ + "name": "@follow/ota", + "type": "module", + "private": true, + "scripts": { + "deploy:dev": "wrangler deploy --env dev", + "deploy:prod": "wrangler deploy", + "dev": "wrangler dev --env dev", + "test": "vitest run", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "fzstd": "0.1.1", + "hono": "4.12.1", + "ofetch": "1.5.1", + "tar-stream": "2.2.0", + "zod": "3.25.76" + }, + "devDependencies": { + "@cloudflare/workers-types": "^4.20260405.0", + "@types/tar-stream": "3.1.4", + "typescript": "catalog:", + "vitest": "3.2.4", + "wrangler": "4.67.0" + } +} diff --git a/apps/ota/src/__tests__/manifest.test.ts b/apps/ota/src/__tests__/manifest.test.ts new file mode 100644 index 000000000..e5a4e2a05 --- /dev/null +++ b/apps/ota/src/__tests__/manifest.test.ts @@ -0,0 +1,355 @@ +import { describe, expect, it, vi } from "vitest" + +import type { Env } from "../env" +import otaWorker from "../index" +import { KV_KEYS } from "../lib/constants" +import { buildManifest } from "../lib/manifest" +import type { OtaRelease } from "../lib/schema" + +const textEncoder = new TextEncoder() + +describe("buildManifest", () => { + it("rewrites launch asset and asset URLs to Worker-served asset routes", () => { + const manifest = buildManifest( + { + schemaVersion: 1, + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + publishedAt: "2026-04-10T12:00:00Z", + git: { tag: "mobile/v0.4.2", commit: "abcdef1234567890" }, + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.1", + message: null, + }, + platforms: { + ios: { + launchAsset: { + path: "bundles/ios-main.js", + sha256: "a".repeat(64), + contentType: "application/javascript", + }, + assets: [ + { + path: "assets/one.png", + sha256: "b".repeat(64), + contentType: "image/png", + }, + ], + }, + }, + } satisfies OtaRelease, + { + origin: "https://ota.folo.is", + platform: "ios", + }, + ) + + expect(manifest.launchAsset.url).toBe( + "https://ota.folo.is/assets/mobile/production/0.4.1/0.4.2/ios/bundles/ios-main.js", + ) + expect(manifest.launchAsset.key).toBe("ios-main") + expect(manifest.launchAsset.hash).toBe("qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqo") + expect(manifest.launchAsset.fileExtension).toBe(".js") + expect(manifest.assets[0]?.url).toBe( + "https://ota.folo.is/assets/mobile/production/0.4.1/0.4.2/ios/assets/one.png", + ) + expect(manifest.assets[0]?.key).toBe("one") + expect(manifest.assets[0]?.hash).toBe("u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7s") + expect(manifest.assets[0]?.fileExtension).toBe(".png") + }) +}) + +describe("/manifest", () => { + it("returns 204 when no pointer exists", async () => { + const response = await fetchWorker("/manifest", { + headers: { + "expo-platform": "ios", + "expo-runtime-version": "0.4.1", + }, + }) + + expect(response.status).toBe(204) + }) + + it("returns 400 when expo-platform is missing", async () => { + const response = await fetchWorker("/manifest", { + headers: { + "expo-runtime-version": "0.4.1", + }, + }) + + expect(response.status).toBe(400) + await expect(response.json()).resolves.toEqual({ + error: "Missing expo-platform header", + }) + }) + + it("returns 400 when expo-runtime-version is invalid", async () => { + const response = await fetchWorker("/manifest", { + headers: { + "expo-platform": "ios", + "expo-runtime-version": "0.4", + }, + }) + + expect(response.status).toBe(400) + await expect(response.json()).resolves.toEqual({ + error: "Invalid expo-runtime-version header", + }) + }) + + it("does not serve a store release as OTA", async () => { + const release = createRelease({ + releaseKind: "store", + }) + const response = await fetchWorker( + "/manifest", + { + headers: { + "expo-platform": "ios", + "expo-runtime-version": "0.4.1", + }, + }, + { + kvEntries: new Map([ + [KV_KEYS.latest("mobile", "production", "0.4.1", "ios"), { releaseVersion: "0.4.2" }], + [KV_KEYS.release("mobile", "0.4.2"), release], + ]), + }, + ) + + expect(response.status).toBe(204) + }) + + it("fails closed when the latest pointer record is malformed", async () => { + const response = await fetchWorker( + "/manifest", + { + headers: { + "expo-platform": "ios", + "expo-runtime-version": "0.4.1", + }, + }, + { + kvEntries: new Map([ + [KV_KEYS.latest("mobile", "production", "0.4.1", "ios"), { releaseVersion: "latest" }], + ]), + }, + ) + + expect(response.status).toBe(204) + }) + + it("fails closed when the loaded release body version does not match the pointer", async () => { + const response = await fetchWorker( + "/manifest", + { + headers: { + "expo-platform": "ios", + "expo-runtime-version": "0.4.1", + }, + }, + { + kvEntries: new Map([ + [KV_KEYS.latest("mobile", "production", "0.4.1", "ios"), { releaseVersion: "0.4.2" }], + [ + KV_KEYS.release("mobile", "0.4.2"), + createRelease({ + releaseVersion: "0.4.3", + git: { + tag: "mobile/v0.4.3", + commit: "bcdef1234567890a", + }, + }), + ], + ]), + }, + ) + + expect(response.status).toBe(204) + }) +}) + +describe("/assets/*", () => { + it("returns 404 when the asset is missing", async () => { + const response = await fetchWorker( + "/assets/mobile/production/0.4.1/0.4.2/ios/assets/missing.png", + ) + + expect(response.status).toBe(404) + await expect(response.text()).resolves.toBe("Not found") + }) + + it("preserves stored metadata and immutable cache headers when the asset exists", async () => { + const key = "mobile/production/0.4.1/0.4.2/ios/assets/one.png" + const response = await fetchWorker(`/assets/${key}`, undefined, { + bucketEntries: new Map([ + [ + key, + { + body: textEncoder.encode("asset"), + headers: { + "content-type": "image/png", + }, + }, + ], + ]), + }) + + expect(response.status).toBe(200) + expect(response.headers.get("content-type")).toBe("image/png") + expect(response.headers.get("cache-control")).toBe("public, max-age=31536000, immutable") + await expect(response.text()).resolves.toBe("asset") + }) +}) + +describe("/policy", () => { + it("rejects missing installedBinaryVersion", async () => { + const response = await fetchWorker("/policy?product=mobile&channel=production") + + expect(response.status).toBe(400) + await expect(response.json()).resolves.toEqual({ + error: "Missing installedBinaryVersion query parameter", + }) + }) + + it("rejects invalid installedBinaryVersion", async () => { + const response = await fetchWorker( + "/policy?product=mobile&channel=production&installedBinaryVersion=0.4", + ) + + expect(response.status).toBe(400) + await expect(response.json()).resolves.toEqual({ + error: "Invalid installedBinaryVersion query parameter", + }) + }) +}) + +function createRelease(overrides: Partial = {}): OtaRelease { + return { + schemaVersion: 1, + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + publishedAt: "2026-04-10T12:00:00Z", + git: { + tag: "mobile/v0.4.2", + commit: "abcdef1234567890", + }, + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.1", + message: null, + }, + platforms: { + ios: { + launchAsset: { + path: "bundles/ios-main.js", + sha256: "a".repeat(64), + contentType: "application/javascript", + }, + assets: [ + { + path: "assets/one.png", + sha256: "b".repeat(64), + contentType: "image/png", + }, + ], + }, + }, + ...overrides, + } +} + +async function fetchWorker( + path: string, + init?: RequestInit, + options?: { + kvEntries?: Map + bucketEntries?: Map< + string, + { + body: Uint8Array + headers?: Record + } + > + }, +) { + const response = await otaWorker.fetch( + new Request(`https://ota.folo.is${path}`, init), + createEnv(options), + createExecutionContext(), + ) + + return response +} + +function createEnv(options?: { + kvEntries?: Map + bucketEntries?: Map< + string, + { + body: Uint8Array + headers?: Record + } + > +}): Env { + return { + OTA_KV: createKvNamespace(options?.kvEntries), + OTA_BUCKET: createR2Bucket(options?.bucketEntries), + GITHUB_OWNER: "", + GITHUB_REPO: "", + GITHUB_TOKEN: "", + OTA_SYNC_TOKEN: "", + OTA_SYNC_TOKEN_HEADER: "x-ota-sync-token", + } +} + +function createKvNamespace(entries = new Map()): KVNamespace { + return { + get: vi.fn(async (key: string) => entries.get(key) ?? null), + put: vi.fn(async () => {}), + } as unknown as KVNamespace +} + +function createR2Bucket( + entries = new Map< + string, + { + body: Uint8Array + headers?: Record + } + >(), +): R2Bucket { + return { + get: vi.fn(async (key: string) => { + const entry = entries.get(key) + + if (!entry) { + return null + } + + return { + body: entry.body, + writeHttpMetadata: (headers: Headers) => { + for (const [name, value] of Object.entries(entry.headers ?? {})) { + headers.set(name, value) + } + }, + } + }), + } as unknown as R2Bucket +} + +function createExecutionContext(): ExecutionContext { + return { + waitUntil: vi.fn(), + passThroughOnException: vi.fn(), + } as unknown as ExecutionContext +} diff --git a/apps/ota/src/__tests__/policy.test.ts b/apps/ota/src/__tests__/policy.test.ts new file mode 100644 index 000000000..adbf68345 --- /dev/null +++ b/apps/ota/src/__tests__/policy.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, it } from "vitest" + +import { evaluateStorePolicy } from "../lib/policy" +import type { OtaRelease } from "../lib/schema" + +function createStoreRelease( + overrides: Partial< + Pick + > = {}, +): Pick { + return { + releaseVersion: "0.4.3", + releaseKind: "store", + runtimeVersion: "0.4.3", + policy: { + storeRequired: true, + minSupportedBinaryVersion: "0.4.0", + message: "Please update from the store.", + }, + ...overrides, + } +} + +describe("evaluateStorePolicy", () => { + it("returns none when there is no release to evaluate", () => { + const policy = evaluateStorePolicy(null, { + installedBinaryVersion: "0.4.1", + }) + + expect(policy).toEqual({ + action: "none", + targetVersion: null, + message: null, + }) + }) + + it("returns none for non-store releases", () => { + const policy = evaluateStorePolicy( + createStoreRelease({ + releaseKind: "ota", + }), + { + installedBinaryVersion: "0.4.1", + }, + ) + + expect(policy).toEqual({ + action: "none", + targetVersion: null, + message: null, + }) + }) + + it("requires a store update when a store release is newer than the installed binary", () => { + const policy = evaluateStorePolicy(createStoreRelease(), { + installedBinaryVersion: "0.4.2", + }) + + expect(policy.action).toBe("block") + expect(policy.targetVersion).toBe("0.4.3") + }) + + it("prompts when a newer store release is available but not required", () => { + const policy = evaluateStorePolicy( + createStoreRelease({ + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.0", + message: "An update is available.", + }, + }), + { + installedBinaryVersion: "0.4.2", + }, + ) + + expect(policy).toEqual({ + action: "prompt", + targetVersion: "0.4.3", + message: "An update is available.", + }) + }) + + it("blocks when the installed binary is below the minimum supported version", () => { + const policy = evaluateStorePolicy( + createStoreRelease({ + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.2", + message: "Please update from the store.", + }, + }), + { + installedBinaryVersion: "0.4.1", + }, + ) + + expect(policy).toEqual({ + action: "block", + targetVersion: "0.4.3", + message: "Please update from the store.", + }) + }) + + it("returns none when the installed binary is already up to date", () => { + const policy = evaluateStorePolicy(createStoreRelease(), { + installedBinaryVersion: "0.4.3", + }) + + expect(policy).toEqual({ + action: "none", + targetVersion: null, + message: null, + }) + }) +}) diff --git a/apps/ota/src/__tests__/schema.test.ts b/apps/ota/src/__tests__/schema.test.ts new file mode 100644 index 000000000..05386357e --- /dev/null +++ b/apps/ota/src/__tests__/schema.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, it } from "vitest" + +import { otaReleaseSchema } from "../lib/schema" + +describe("otaReleaseSchema", () => { + it("accepts a plain x.y.z release version and a binary-compatible runtime version", () => { + const parsed = otaReleaseSchema.parse({ + schemaVersion: 1, + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + publishedAt: "2026-04-10T12:00:00Z", + git: { + tag: "mobile/v0.4.2", + commit: "abcdef1234567890", + }, + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.1", + message: null, + }, + platforms: { + ios: { + launchAsset: { + path: "bundles/ios-main.js", + sha256: "a".repeat(64), + contentType: "application/javascript", + }, + assets: [], + }, + }, + }) + + expect(parsed.releaseVersion).toBe("0.4.2") + expect(parsed.runtimeVersion).toBe("0.4.1") + expect(Object.keys(parsed.platforms)).toEqual(["ios"]) + }) + + it("rejects metadata with no platforms", () => { + expect(() => + otaReleaseSchema.parse({ + schemaVersion: 1, + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + publishedAt: "2026-04-10T12:00:00Z", + git: { + tag: "mobile/v0.4.2", + commit: "abcdef1234567890", + }, + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.1", + message: null, + }, + platforms: {}, + }), + ).toThrow("At least one platform must be provided") + }) + + it("rejects metadata when platform keys exist without a real payload", () => { + const result = otaReleaseSchema.safeParse({ + schemaVersion: 1, + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + publishedAt: "2026-04-10T12:00:00Z", + git: { + tag: "mobile/v0.4.2", + commit: "abcdef1234567890", + }, + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.1", + message: null, + }, + platforms: { + ios: undefined, + }, + }) + + expect(result.success).toBe(false) + }) +}) diff --git a/apps/ota/src/__tests__/sync.test.ts b/apps/ota/src/__tests__/sync.test.ts new file mode 100644 index 000000000..13105dc44 --- /dev/null +++ b/apps/ota/src/__tests__/sync.test.ts @@ -0,0 +1,1319 @@ +import tar from "tar-stream" +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" + +import type { Env } from "../env" +import otaWorker from "../index" +import { extractMirroredFiles } from "../lib/archive" +import { KV_KEYS } from "../lib/constants" +import type { GitHubRequestError } from "../lib/github" +import { listPublishedOtaReleases } from "../lib/github" +import { IMMUTABLE_ASSET_CACHE_CONTROL, putMirroredFiles } from "../lib/r2" +import type { OtaRelease } from "../lib/schema" +import { mirrorReleaseToStorage, syncGitHubReleases } from "../lib/sync" + +vi.mock("fzstd", () => { + class Decompress { + ondata: (chunk: Uint8Array, final?: boolean) => unknown + + constructor(ondata?: (chunk: Uint8Array, final?: boolean) => unknown) { + this.ondata = ondata ?? (() => {}) + } + + push(chunk: Uint8Array, final = false) { + const boundary = Math.max(1, Math.ceil(chunk.length / 2)) + const firstChunk = chunk.subarray(0, boundary) + const secondChunk = chunk.subarray(boundary) + + if (firstChunk.byteLength > 0) { + this.ondata(firstChunk, final && secondChunk.byteLength === 0) + } + + if (secondChunk.byteLength > 0 || final) { + this.ondata(secondChunk, final) + } + + return true + } + } + + return { Decompress } +}) + +const textEncoder = new TextEncoder() +const baseRelease = { + schemaVersion: 1, + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + publishedAt: "2026-04-10T12:00:00Z", + git: { tag: "mobile/v0.4.2", commit: "abcdef1234567890" }, + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.1", + message: null, + }, +} as const + +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) + +describe("listPublishedOtaReleases", () => { + beforeEach(() => { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue( + new Response( + JSON.stringify([ + { + tag_name: "mobile/v0.4.2", + draft: false, + prerelease: false, + assets: [ + { + name: "ota-release.json", + browser_download_url: "https://example.com/ota-release.json", + }, + { + name: "dist.tar.zst", + browser_download_url: "https://example.com/dist.tar.zst", + }, + ], + }, + ]), + { + status: 200, + headers: { + ETag: '"etag-200"', + }, + }, + ), + ), + ) + }) + + afterEach(() => { + vi.unstubAllGlobals() + }) + + it("returns releases that have both required assets and the response etag", async () => { + const result = await listPublishedOtaReleases({ + owner: "RSSNext", + repo: "Folo", + token: "token", + etag: null, + }) + + expect(result).toMatchObject({ + kind: "ok", + etag: '"etag-200"', + }) + + if (result.kind !== "ok") { + throw new Error("Expected a successful GitHub releases response") + } + + expect(result.releases[0]?.tag).toBe("mobile/v0.4.2") + expect(result.releases[0]?.metadataUrl).toContain("ota-release.json") + }) + + it("returns a not-modified result for 304 responses", async () => { + const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 304 })) + + vi.stubGlobal("fetch", fetchMock) + + const result = await listPublishedOtaReleases({ + owner: "RSSNext", + repo: "Folo", + token: "token", + etag: '"etag-value"', + }) + + expect(result).toEqual({ kind: "not-modified" }) + expect(fetchMock).toHaveBeenCalledWith( + "https://api.github.com/repos/RSSNext/Folo/releases", + expect.objectContaining({ + headers: expect.objectContaining({ + "If-None-Match": '"etag-value"', + }), + }), + ) + }) + + it("filters out releases missing required assets", async () => { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue( + new Response( + JSON.stringify([ + { + tag_name: "desktop/v1.2.3", + draft: false, + prerelease: false, + assets: [ + { + name: "ota-release.json", + browser_download_url: "https://example.com/desktop-ota-release.json", + }, + ], + }, + ]), + { status: 200 }, + ), + ), + ) + + const result = await listPublishedOtaReleases({ + owner: "RSSNext", + repo: "Folo", + token: "token", + etag: null, + }) + + expect(result).toEqual({ + kind: "ok", + etag: null, + releases: [], + }) + }) + + it("sends a user agent header required by the GitHub releases API", async () => { + const fetchMock = vi.fn().mockResolvedValue( + new Response(JSON.stringify([]), { + status: 200, + }), + ) + + vi.stubGlobal("fetch", fetchMock) + + await listPublishedOtaReleases({ + owner: "RSSNext", + repo: "Folo", + token: "token", + etag: null, + }) + + expect(fetchMock).toHaveBeenCalledWith( + "https://api.github.com/repos/RSSNext/Folo/releases", + expect.objectContaining({ + headers: expect.objectContaining({ + "User-Agent": expect.any(String), + }), + }), + ) + }) + + it("throws a structured error for failed requests", async () => { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue( + new Response(JSON.stringify({ message: "Bad credentials" }), { + status: 401, + statusText: "Unauthorized", + headers: { + "Content-Type": "application/json", + }, + }), + ), + ) + + await expect( + listPublishedOtaReleases({ + owner: "RSSNext", + repo: "Folo", + token: "token", + etag: null, + }), + ).rejects.toEqual( + expect.objectContaining>({ + name: "GitHubRequestError", + status: 401, + statusText: "Unauthorized", + body: JSON.stringify({ message: "Bad credentials" }), + }), + ) + }) +}) + +describe("extractMirroredFiles", () => { + it("extracts only referenced files from a tar archive", async () => { + const iosBundle = textEncoder.encode("console.log('ios')") + const archiveBuffer = await createTarArchive([ + { + name: "bundles/ios-main.js", + body: iosBundle, + }, + { + name: "bundles/unused.js", + body: textEncoder.encode("console.log('unused')"), + }, + ]) + + const files = await extractMirroredFiles({ + release: { + ...baseRelease, + platforms: { + ios: { + launchAsset: { + path: "bundles/ios-main.js", + sha256: await sha256Hex(iosBundle), + contentType: "application/javascript", + }, + assets: [], + }, + }, + }, + archiveBuffer, + }) + + expect(files).toEqual([ + { + key: "mobile/production/0.4.1/0.4.2/ios/bundles/ios-main.js", + body: iosBundle, + contentType: "application/javascript", + }, + ]) + }) + + it("throws when a referenced archive file is missing", async () => { + const archiveBuffer = await createTarArchive([ + { + name: "bundles/unused.js", + body: textEncoder.encode("console.log('unused')"), + }, + ]) + + await expect( + extractMirroredFiles({ + release: { + ...baseRelease, + platforms: { + ios: { + launchAsset: { + path: "bundles/ios-main.js", + sha256: "a".repeat(64), + contentType: "application/javascript", + }, + assets: [], + }, + }, + }, + archiveBuffer, + }), + ).rejects.toThrow('Archive is missing referenced file "bundles/ios-main.js"') + }) + + it("throws when a referenced archive file hash does not match metadata", async () => { + const archiveBuffer = await createTarArchive([ + { + name: "bundles/ios-main.js", + body: textEncoder.encode("console.log('tampered')"), + }, + ]) + + await expect( + extractMirroredFiles({ + release: { + ...baseRelease, + platforms: { + ios: { + launchAsset: { + path: "bundles/ios-main.js", + sha256: await sha256Hex(textEncoder.encode("console.log('ios')")), + contentType: "application/javascript", + }, + assets: [], + }, + }, + }, + archiveBuffer, + }), + ).rejects.toThrow('Archive file "bundles/ios-main.js" hash mismatch') + }) +}) + +describe("putMirroredFiles", () => { + it("forwards content metadata and immutable cache headers to R2", async () => { + const bucket = { + put: vi.fn(async () => null), + } as unknown as R2Bucket + + await putMirroredFiles(bucket, [ + { + key: "mobile/production/0.4.1/0.4.2/ios/bundles/ios-main.js", + body: textEncoder.encode("console.log('ios')"), + contentType: "application/javascript", + }, + ]) + + expect(bucket.put).toHaveBeenCalledWith( + "mobile/production/0.4.1/0.4.2/ios/bundles/ios-main.js", + textEncoder.encode("console.log('ios')"), + expect.objectContaining({ + httpMetadata: expect.objectContaining({ + contentType: "application/javascript", + cacheControl: IMMUTABLE_ASSET_CACHE_CONTROL, + }), + }), + ) + }) +}) + +describe("mirrorReleaseToStorage", () => { + it("stores mirrored release metadata and latest pointers only for platforms with mirrored payloads", async () => { + const kvWrites: string[] = [] + const r2Writes: string[] = [] + + const kv = { + put: vi.fn(async (key: string) => { + kvWrites.push(key) + }), + get: vi.fn(async () => null), + } as unknown as KVNamespace + + const bucket = { + put: vi.fn(async (key: string) => { + r2Writes.push(key) + }), + } as unknown as R2Bucket + + await mirrorReleaseToStorage( + { + release: { + ...baseRelease, + platforms: { + ios: { + launchAsset: { + path: "bundles/ios-main.js", + sha256: "a".repeat(64), + contentType: "application/javascript", + }, + assets: [], + }, + android: { + launchAsset: { + path: "bundles/android-main.js", + sha256: "b".repeat(64), + contentType: "application/javascript", + }, + assets: [], + }, + }, + }, + files: [ + { + key: "mobile/production/0.4.1/0.4.2/ios/bundles/ios-main.js", + body: new Uint8Array([1, 2, 3]), + contentType: "application/javascript", + }, + ], + }, + { kv, bucket }, + ) + + expect(r2Writes).toContain("mobile/production/0.4.1/0.4.2/ios/bundles/ios-main.js") + + const releaseWriteIndex = kvWrites.findIndex((key) => key.includes("release:mobile:0.4.2")) + const latestWriteIndex = kvWrites.findIndex((key) => + key.includes("latest:mobile:production:0.4.1:ios"), + ) + + expect(releaseWriteIndex).toBeGreaterThanOrEqual(0) + expect(latestWriteIndex).toBeGreaterThan(releaseWriteIndex) + expect(kvWrites.some((key) => key.includes("latest:mobile:production:0.4.1:ios"))).toBe(true) + expect(kvWrites.some((key) => key.includes("latest:mobile:production:0.4.1:android"))).toBe( + false, + ) + }) +}) + +describe("syncGitHubReleases", () => { + it("updates lastSuccessAt when GitHub reports no release changes", async () => { + const kvEntries = new Map([[KV_KEYS.githubEtag, '"etag-current"']]) + + vi.stubGlobal( + "fetch", + vi.fn(async () => new Response(null, { status: 304 })), + ) + + await syncGitHubReleases( + createEnv({ + kvEntries, + envOverrides: { + GITHUB_OWNER: "RSSNext", + GITHUB_REPO: "Folo", + GITHUB_TOKEN: "token", + }, + }), + ) + + expect(kvEntries.get(KV_KEYS.githubEtag)).toBe('"etag-current"') + expect(kvEntries.get(KV_KEYS.syncLastSuccessAt)).toEqual(expect.any(String)) + }) + + it("does not advance sync markers when a later release fails validation", async () => { + const kvEntries = new Map([ + [KV_KEYS.githubEtag, '"etag-old"'], + [KV_KEYS.syncLastSuccessAt, "2026-04-10T10:00:00.000Z"], + ]) + const validStoreRelease = await createReleaseMetadata({ + releaseVersion: "0.5.2", + releaseKind: "store", + runtimeVersion: "0.5.2", + publishedAt: "2026-04-10T17:00:00Z", + git: { + tag: "mobile/v0.5.2", + commit: "abcdef1234567896", + }, + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.5.0", + message: "Install 0.5.2 from the store.", + }, + }) + + vi.stubGlobal( + "fetch", + vi.fn(async (input: string | URL | Request) => { + const url = String(input) + + if (url === "https://api.github.com/repos/RSSNext/Folo/releases") { + return new Response( + JSON.stringify([ + createGitHubReleaseAssetSet( + "mobile-v0.5.2", + "https://example.com/valid-store.json", + "https://example.com/valid-store.tar.zst", + ), + createGitHubReleaseAssetSet( + "mobile-v0.5.3", + "https://example.com/invalid-store.json", + "https://example.com/invalid-store.tar.zst", + ), + ]), + { + status: 200, + headers: { + ETag: '"etag-new"', + }, + }, + ) + } + + if (url === "https://example.com/valid-store.json") { + return new Response(JSON.stringify(validStoreRelease), { + headers: { + "Content-Type": "application/json", + }, + }) + } + + if (url === "https://example.com/invalid-store.json") { + return new Response( + JSON.stringify({ + schemaVersion: 1, + product: "mobile", + channel: "production", + releaseVersion: "invalid", + }), + { + headers: { + "Content-Type": "application/json", + }, + }, + ) + } + + throw new Error(`Unhandled fetch URL: ${url}`) + }), + ) + + await expect( + syncGitHubReleases( + createEnv({ + kvEntries, + envOverrides: { + GITHUB_OWNER: "RSSNext", + GITHUB_REPO: "Folo", + GITHUB_TOKEN: "token", + }, + }), + ), + ).rejects.toThrow() + + expect(kvEntries.get(KV_KEYS.policy("mobile", "production"))).toBe( + JSON.stringify(validStoreRelease), + ) + expect(kvEntries.get(KV_KEYS.githubEtag)).toBe('"etag-old"') + expect(kvEntries.get(KV_KEYS.syncLastSuccessAt)).toBe("2026-04-10T10:00:00.000Z") + }) + + it("deduplicates concurrent sync calls within the same isolate", async () => { + const kvEntries = new Map() + const releasesResponse = createDeferred() + const fetchMock = vi.fn(async (input: string | URL | Request) => { + const url = String(input) + + if (url === "https://api.github.com/repos/RSSNext/Folo/releases") { + return releasesResponse.promise + } + + throw new Error(`Unhandled fetch URL: ${url}`) + }) + + vi.stubGlobal("fetch", fetchMock) + + const env = createEnv({ + kvEntries, + envOverrides: { + GITHUB_OWNER: "RSSNext", + GITHUB_REPO: "Folo", + GITHUB_TOKEN: "token", + }, + }) + + const firstSync = syncGitHubReleases(env) + const secondSync = syncGitHubReleases(env) + + await Promise.resolve() + + expect(fetchMock).toHaveBeenCalledTimes(1) + + releasesResponse.resolve( + new Response(JSON.stringify([]), { + status: 200, + headers: { + ETag: '"etag-deduped"', + }, + }), + ) + + await Promise.all([firstSync, secondSync]) + + expect(kvEntries.get(KV_KEYS.githubEtag)).toBe('"etag-deduped"') + expect(kvEntries.get(KV_KEYS.syncLastSuccessAt)).toEqual(expect.any(String)) + }) + + it("downloads private release assets through authenticated GitHub asset API requests", async () => { + const kvEntries = new Map() + const bucketEntries = new Map }>() + const otaBundle = textEncoder.encode("console.log('private-ota')") + const otaRelease = await createReleaseMetadata({ + platforms: { + ios: { + launchAsset: { + path: "bundles/ios-main.js", + sha256: await sha256Hex(otaBundle), + contentType: "application/javascript", + }, + assets: [], + }, + }, + }) + const otaArchive = await createTarArchive([ + { + name: "bundles/ios-main.js", + body: otaBundle, + }, + ]) + + const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit) => { + const url = String(input) + + if (url === "https://api.github.com/repos/RSSNext/Folo/releases") { + return new Response( + JSON.stringify([ + createGitHubReleaseAssetSet( + "mobile/v0.4.2", + "https://github.com/RSSNext/Folo/releases/download/mobile/v0.4.2/ota-release.json", + "https://github.com/RSSNext/Folo/releases/download/mobile/v0.4.2/dist.tar.zst", + { + metadataApiUrl: "https://api.github.com/repos/RSSNext/Folo/releases/assets/1", + archiveApiUrl: "https://api.github.com/repos/RSSNext/Folo/releases/assets/2", + }, + ), + ]), + { status: 200 }, + ) + } + + if (url === "https://api.github.com/repos/RSSNext/Folo/releases/assets/1") { + expect(init).toMatchObject({ + headers: expect.objectContaining({ + Authorization: "Bearer token", + Accept: "application/octet-stream", + "User-Agent": expect.any(String), + }), + }) + + return new Response(JSON.stringify(otaRelease), { + status: 200, + headers: { + "Content-Type": "application/octet-stream", + }, + }) + } + + if (url === "https://api.github.com/repos/RSSNext/Folo/releases/assets/2") { + expect(init).toMatchObject({ + headers: expect.objectContaining({ + Authorization: "Bearer token", + Accept: "application/octet-stream", + "User-Agent": expect.any(String), + }), + }) + + const archivePayload = new Uint8Array(otaArchive.byteLength) + archivePayload.set(otaArchive) + + return new Response(archivePayload.buffer, { + status: 200, + headers: { + "Content-Type": "application/octet-stream", + }, + }) + } + + if (url.startsWith("https://github.com/RSSNext/Folo/releases/download/")) { + return new Response("Not Found", { + status: 404, + statusText: "Not Found", + }) + } + + throw new Error(`Unhandled fetch URL: ${url}`) + }) + + vi.stubGlobal("fetch", fetchMock) + + await syncGitHubReleases( + createEnv({ + kvEntries, + bucketEntries, + envOverrides: { + GITHUB_OWNER: "RSSNext", + GITHUB_REPO: "Folo", + GITHUB_TOKEN: "token", + }, + }), + ) + + expect(bucketEntries.has("mobile/production/0.4.1/0.4.2/ios/bundles/ios-main.js")).toBe(true) + }) + + it("keeps newer OTA pointers and store policy records when releases arrive out of order", async () => { + const kvEntries = new Map() + const bucketEntries = new Map }>() + + const newerOtaBundle = textEncoder.encode("console.log('ota-newer')") + const olderOtaBundle = textEncoder.encode("console.log('ota-older')") + const newerOtaRelease = await createReleaseMetadata({ + releaseVersion: "0.4.4", + publishedAt: "2026-04-10T14:00:00Z", + git: { + tag: "mobile/v0.4.4", + commit: "abcdef1234567891", + }, + platforms: { + ios: { + launchAsset: { + path: "bundles/ios-main.js", + sha256: await sha256Hex(newerOtaBundle), + contentType: "application/javascript", + }, + assets: [], + }, + }, + }) + const olderOtaRelease = await createReleaseMetadata({ + releaseVersion: "0.4.3", + publishedAt: "2026-04-10T13:00:00Z", + git: { + tag: "mobile/v0.4.3", + commit: "abcdef1234567892", + }, + platforms: { + ios: { + launchAsset: { + path: "bundles/ios-main.js", + sha256: await sha256Hex(olderOtaBundle), + contentType: "application/javascript", + }, + assets: [], + }, + }, + }) + const newerStoreRelease = await createReleaseMetadata({ + releaseVersion: "0.5.0", + releaseKind: "store", + runtimeVersion: "0.5.0", + publishedAt: "2026-04-10T12:30:00Z", + git: { + tag: "mobile/v0.5.0", + commit: "abcdef1234567893", + }, + policy: { + storeRequired: true, + minSupportedBinaryVersion: "0.4.8", + message: "Install 0.5.0 from the store.", + }, + }) + const olderStoreRelease = await createReleaseMetadata({ + releaseVersion: "0.4.8", + releaseKind: "store", + runtimeVersion: "0.4.8", + publishedAt: "2026-04-10T11:00:00Z", + git: { + tag: "mobile/v0.4.8", + commit: "abcdef1234567894", + }, + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.5", + message: "Install 0.4.8 from the store.", + }, + }) + + const newerOtaArchive = await createTarArchive([ + { + name: "bundles/ios-main.js", + body: newerOtaBundle, + }, + ]) + const olderOtaArchive = await createTarArchive([ + { + name: "bundles/ios-main.js", + body: olderOtaBundle, + }, + ]) + + vi.stubGlobal( + "fetch", + vi.fn(async (input: string | URL | Request) => { + const url = String(input) + + if (url === "https://api.github.com/repos/RSSNext/Folo/releases") { + return new Response( + JSON.stringify([ + createGitHubReleaseAssetSet( + "mobile-v0.4.4", + "https://example.com/newer-ota.json", + "https://example.com/newer-ota.tar.zst", + ), + createGitHubReleaseAssetSet( + "mobile-v0.4.3", + "https://example.com/older-ota.json", + "https://example.com/older-ota.tar.zst", + ), + createGitHubReleaseAssetSet( + "mobile-v0.5.0", + "https://example.com/newer-store.json", + "https://example.com/newer-store.tar.zst", + ), + createGitHubReleaseAssetSet( + "mobile-v0.4.8", + "https://example.com/older-store.json", + "https://example.com/older-store.tar.zst", + ), + ]), + { + status: 200, + headers: { + ETag: '"etag-200"', + }, + }, + ) + } + + const metadataBodies: Record = { + "https://example.com/newer-ota.json": newerOtaRelease, + "https://example.com/older-ota.json": olderOtaRelease, + "https://example.com/newer-store.json": newerStoreRelease, + "https://example.com/older-store.json": olderStoreRelease, + } + + if (url in metadataBodies) { + return new Response(JSON.stringify(metadataBodies[url]), { + headers: { + "Content-Type": "application/json", + }, + }) + } + + const archiveBodies: Record = { + "https://example.com/newer-ota.tar.zst": newerOtaArchive, + "https://example.com/older-ota.tar.zst": olderOtaArchive, + } + + const archiveBody = archiveBodies[url] + + if (archiveBody) { + const archivePayload = new Uint8Array(archiveBody.byteLength) + archivePayload.set(archiveBody) + + return new Response(new Blob([archivePayload.buffer])) + } + + throw new Error(`Unhandled fetch URL: ${url}`) + }), + ) + + await syncGitHubReleases( + createEnv({ + kvEntries, + bucketEntries, + envOverrides: { + GITHUB_OWNER: "RSSNext", + GITHUB_REPO: "Folo", + GITHUB_TOKEN: "token", + }, + }), + ) + + expect(kvEntries.get(KV_KEYS.githubEtag)).toBe('"etag-200"') + expect(kvEntries.get(KV_KEYS.syncLastSuccessAt)).toEqual(expect.any(String)) + expect(kvEntries.get(KV_KEYS.latest("mobile", "production", "0.4.1", "ios"))).toBe( + JSON.stringify({ + releaseVersion: "0.4.4", + }), + ) + expect(kvEntries.get(KV_KEYS.policy("mobile", "production"))).toBe( + JSON.stringify(newerStoreRelease), + ) + expect(bucketEntries.has("mobile/production/0.4.1/0.4.4/ios/bundles/ios-main.js")).toBe(true) + expect(kvEntries.get(KV_KEYS.release("mobile", "0.5.0"))).toBe( + JSON.stringify(newerStoreRelease), + ) + }) +}) + +describe("internal routes", () => { + it("returns the last successful sync timestamp from KV", async () => { + const response = await fetchWorker("/internal/health", undefined, { + kvEntries: new Map([[KV_KEYS.syncLastSuccessAt, "2026-04-10T15:00:00.000Z"]]), + }) + + expect(response.status).toBe(200) + await expect(response.json()).resolves.toEqual({ + ok: true, + lastSuccessAt: "2026-04-10T15:00:00.000Z", + }) + }) + + it("rejects sync requests with an invalid token", async () => { + const response = await fetchWorker( + "/internal/sync", + { + method: "POST", + headers: { + "x-ota-sync-token": "wrong-token", + }, + }, + { + envOverrides: { + OTA_SYNC_TOKEN: "expected-token", + }, + }, + ) + + expect(response.status).toBe(401) + }) + + it("runs sync for authorized requests", async () => { + const kvEntries = new Map() + const storeRelease = await createReleaseMetadata({ + releaseVersion: "0.5.1", + releaseKind: "store", + runtimeVersion: "0.5.1", + publishedAt: "2026-04-10T16:00:00Z", + git: { + tag: "mobile/v0.5.1", + commit: "abcdef1234567895", + }, + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.5.0", + message: "Install 0.5.1 from the store.", + }, + }) + + vi.stubGlobal( + "fetch", + vi.fn(async (input: string | URL | Request) => { + const url = String(input) + + if (url === "https://api.github.com/repos/RSSNext/Folo/releases") { + return new Response( + JSON.stringify([ + createGitHubReleaseAssetSet( + "mobile-v0.5.1", + "https://example.com/store.json", + "https://example.com/store.tar.zst", + ), + ]), + { status: 200 }, + ) + } + + if (url === "https://example.com/store.json") { + return new Response(JSON.stringify(storeRelease), { + headers: { + "Content-Type": "application/json", + }, + }) + } + + throw new Error(`Unhandled fetch URL: ${url}`) + }), + ) + + const response = await fetchWorker( + "/internal/sync", + { + method: "POST", + headers: { + "x-ota-sync-token": "expected-token", + }, + }, + { + kvEntries, + envOverrides: { + OTA_SYNC_TOKEN: "expected-token", + GITHUB_OWNER: "RSSNext", + GITHUB_REPO: "Folo", + GITHUB_TOKEN: "token", + }, + }, + ) + + expect(response.status).toBe(200) + await expect(response.json()).resolves.toEqual({ + ok: true, + }) + expect(kvEntries.get(KV_KEYS.policy("mobile", "production"))).toBe(JSON.stringify(storeRelease)) + }) +}) + +describe("scheduled handler", () => { + it("dispatches sync work through waitUntil", async () => { + const kvEntries = new Map([[KV_KEYS.githubEtag, '"etag-current"']]) + + vi.stubGlobal( + "fetch", + vi.fn(async () => new Response(null, { status: 304 })), + ) + + const env = createEnv({ + kvEntries, + envOverrides: { + GITHUB_OWNER: "RSSNext", + GITHUB_REPO: "Folo", + GITHUB_TOKEN: "token", + }, + }) + const ctx = createExecutionContext() + + otaWorker.scheduled?.({} as ScheduledController, env, ctx) + + expect(ctx.waitUntil).toHaveBeenCalledTimes(1) + + const [syncPromise] = vi.mocked(ctx.waitUntil).mock.calls[0] ?? [] + await syncPromise + + expect(kvEntries.get(KV_KEYS.syncLastSuccessAt)).toEqual(expect.any(String)) + }) +}) + +async function createTarArchive( + entries: Array<{ + name: string + body: Uint8Array + }>, +) { + const pack = tar.pack() + const archiveChunks: Uint8Array[] = [] + + const archivePromise = new Promise((resolve, reject) => { + pack.on("data", (chunk) => { + archiveChunks.push(new Uint8Array(chunk)) + }) + pack.on("error", reject) + pack.on("end", () => { + resolve(concatenateChunks(archiveChunks)) + }) + }) + + for (const entry of entries) { + await new Promise((resolve, reject) => { + const tarEntry = pack.entry( + { + name: entry.name, + size: entry.body.byteLength, + }, + (error) => { + if (error) { + reject(error) + return + } + + resolve() + }, + ) + + tarEntry.on("error", reject) + tarEntry.end(entry.body) + }) + } + + pack.finalize() + + return archivePromise +} + +function concatenateChunks(chunks: readonly Uint8Array[]) { + const totalLength = chunks.reduce((length, chunk) => length + chunk.byteLength, 0) + const output = new Uint8Array(totalLength) + let offset = 0 + + for (const chunk of chunks) { + output.set(chunk, offset) + offset += chunk.byteLength + } + + return output +} + +async function sha256Hex(data: Uint8Array) { + const digest = await crypto.subtle.digest("SHA-256", toDigestInput(data)) + + return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("") +} + +function toDigestInput(data: Uint8Array) { + return new Uint8Array(data) +} + +async function fetchWorker( + path: string, + init?: RequestInit, + options?: { + kvEntries?: Map + bucketEntries?: Map< + string, + { + body: Uint8Array + headers?: Record + } + > + envOverrides?: Partial + }, +) { + return otaWorker.fetch( + new Request(`https://ota.folo.is${path}`, init), + createEnv(options), + createExecutionContext(), + ) +} + +function createEnv(options?: { + kvEntries?: Map + bucketEntries?: Map< + string, + { + body: Uint8Array + headers?: Record + } + > + envOverrides?: Partial +}): Env { + return { + OTA_KV: createKvNamespace(options?.kvEntries), + OTA_BUCKET: createR2Bucket(options?.bucketEntries), + GITHUB_OWNER: "", + GITHUB_REPO: "", + GITHUB_TOKEN: "", + OTA_SYNC_TOKEN: "", + OTA_SYNC_TOKEN_HEADER: "x-ota-sync-token", + ...options?.envOverrides, + } +} + +function createKvNamespace(entries = new Map()): KVNamespace { + return { + get: vi.fn(async (key: string, type?: string) => { + const value = entries.get(key) + + if (value == null) { + return null + } + + if (type === "json") { + if (typeof value === "string") { + return JSON.parse(value) + } + + return value + } + + return typeof value === "string" ? value : JSON.stringify(value) + }), + put: vi.fn(async (key: string, value: string) => { + entries.set(key, value) + }), + } as unknown as KVNamespace +} + +function createR2Bucket( + entries = new Map< + string, + { + body: Uint8Array + headers?: Record + } + >(), +): R2Bucket { + return { + get: vi.fn(async (key: string) => { + const entry = entries.get(key) + + if (!entry) { + return null + } + + return { + body: entry.body, + writeHttpMetadata: (headers: Headers) => { + for (const [name, value] of Object.entries(entry.headers ?? {})) { + headers.set(name, value) + } + }, + } + }), + put: vi.fn( + async ( + key: string, + body: ReadableStream | ArrayBuffer | ArrayBufferView | string | null, + options?: R2PutOptions, + ) => { + const httpMetadata = + options?.httpMetadata instanceof Headers ? undefined : options?.httpMetadata + + entries.set(key, { + body: toUint8Array(body), + headers: httpMetadata?.contentType + ? { + "content-type": httpMetadata.contentType, + } + : undefined, + }) + + return null + }, + ), + } as unknown as R2Bucket +} + +function createExecutionContext(): ExecutionContext { + return { + waitUntil: vi.fn(), + passThroughOnException: vi.fn(), + } as unknown as ExecutionContext +} + +async function createReleaseMetadata(overrides: Partial = {}): Promise { + return { + schemaVersion: 1, + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + publishedAt: "2026-04-10T12:00:00Z", + git: { + tag: "mobile/v0.4.2", + commit: "abcdef1234567890", + }, + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.1", + message: null, + }, + platforms: { + ios: { + launchAsset: { + path: "bundles/ios-main.js", + sha256: await sha256Hex(textEncoder.encode("console.log('ios')")), + contentType: "application/javascript", + }, + assets: [], + }, + }, + ...overrides, + } +} + +function createGitHubReleaseAssetSet( + tag: string, + metadataUrl: string, + archiveUrl: string, + options?: { + metadataApiUrl?: string + archiveApiUrl?: string + }, +) { + return { + tag_name: tag, + draft: false, + prerelease: false, + assets: [ + { + name: "ota-release.json", + url: options?.metadataApiUrl ?? metadataUrl, + browser_download_url: metadataUrl, + }, + { + name: "dist.tar.zst", + url: options?.archiveApiUrl ?? archiveUrl, + browser_download_url: archiveUrl, + }, + ], + } +} + +function toUint8Array(body: ReadableStream | ArrayBuffer | ArrayBufferView | string | null) { + if (body == null) { + return new Uint8Array() + } + + if (typeof body === "string") { + return textEncoder.encode(body) + } + + if (body instanceof ArrayBuffer) { + return new Uint8Array(body) + } + + if (ArrayBuffer.isView(body)) { + return new Uint8Array(body.buffer, body.byteOffset, body.byteLength) + } + + throw new Error("ReadableStream bodies are not supported in tests") +} + +function createDeferred() { + let resolve!: (value: T | PromiseLike) => void + let reject!: (reason?: unknown) => void + const promise = new Promise((resolvePromise, rejectPromise) => { + resolve = resolvePromise + reject = rejectPromise + }) + + return { + promise, + resolve, + reject, + } +} diff --git a/apps/ota/src/__tests__/version.test.ts b/apps/ota/src/__tests__/version.test.ts new file mode 100644 index 000000000..443b9f9fd --- /dev/null +++ b/apps/ota/src/__tests__/version.test.ts @@ -0,0 +1,142 @@ +import { describe, expect, it } from "vitest" + +import type { OtaRelease } from "../lib/schema" +import { compareSemver, selectLatestCompatibleRelease } from "../lib/version" + +function createPlatform(path: string, sha256Seed: string) { + return { + launchAsset: { + path, + sha256: sha256Seed.repeat(64), + contentType: "application/javascript", + }, + assets: [], + } +} + +function createRelease(overrides: Partial = {}): OtaRelease { + return { + schemaVersion: 1, + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + publishedAt: "2026-04-10T12:00:00Z", + git: { + tag: "mobile/v0.4.2", + commit: "abcdef1234567890", + }, + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.1", + message: null, + }, + platforms: { + ios: createPlatform("bundles/ios-main.js", "a"), + }, + ...overrides, + } +} + +describe("compareSemver", () => { + it("orders plain x.y.z versions numerically", () => { + expect(compareSemver("0.4.10", "0.4.2")).toBeGreaterThan(0) + expect(compareSemver("1.0.0", "1.0.0")).toBe(0) + expect(compareSemver("0.4.2", "0.5.0")).toBeLessThan(0) + }) +}) + +describe("selectLatestCompatibleRelease", () => { + it("selects the required older release when a newer release has an incompatible runtime", () => { + const result = selectLatestCompatibleRelease( + [ + createRelease({ + releaseVersion: "0.4.2", + git: { + tag: "mobile/v0.4.2", + commit: "abcdef1234567890", + }, + }), + createRelease({ + releaseVersion: "0.4.4", + runtimeVersion: "0.4.3", + git: { + tag: "mobile/v0.4.4", + commit: "cdef1234567890ab", + }, + }), + ], + { + product: "mobile", + channel: "production", + runtimeVersion: "0.4.1", + platform: "ios", + }, + ) + + expect(result?.releaseVersion).toBe("0.4.2") + }) + + it("selects the highest compatible OTA release among multiple candidates", () => { + const result = selectLatestCompatibleRelease( + [ + createRelease({ + releaseVersion: "0.4.2", + git: { + tag: "mobile/v0.4.2", + commit: "abcdef1234567890", + }, + }), + createRelease({ + releaseVersion: "0.4.3", + git: { + tag: "mobile/v0.4.3", + commit: "bcdef1234567890a", + }, + }), + ], + { + product: "mobile", + channel: "production", + runtimeVersion: "0.4.1", + platform: "ios", + }, + ) + + expect(result?.releaseVersion).toBe("0.4.3") + }) + + it("returns null when no matching OTA release has a payload for the requested platform", () => { + const result = selectLatestCompatibleRelease( + [ + createRelease({ + releaseVersion: "0.4.2", + platforms: { + ios: undefined, + android: createPlatform("bundles/android-main.js", "b"), + }, + }), + createRelease({ + releaseVersion: "0.4.3", + releaseKind: "store", + platforms: { + ios: createPlatform("bundles/ios-store.js", "c"), + }, + git: { + tag: "mobile/v0.4.3", + commit: "bcdef1234567890a", + }, + }), + ], + { + product: "mobile", + channel: "production", + runtimeVersion: "0.4.1", + platform: "ios", + }, + ) + + expect(result).toBeNull() + }) +}) diff --git a/apps/ota/src/env.ts b/apps/ota/src/env.ts new file mode 100644 index 000000000..899fbcdb3 --- /dev/null +++ b/apps/ota/src/env.ts @@ -0,0 +1,9 @@ +export interface Env { + OTA_KV: KVNamespace + OTA_BUCKET: R2Bucket + GITHUB_OWNER: string + GITHUB_REPO: string + GITHUB_TOKEN: string + OTA_SYNC_TOKEN: string + OTA_SYNC_TOKEN_HEADER: string +} diff --git a/apps/ota/src/index.ts b/apps/ota/src/index.ts new file mode 100644 index 000000000..68335a9f0 --- /dev/null +++ b/apps/ota/src/index.ts @@ -0,0 +1,22 @@ +import { Hono } from "hono" + +import type { Env } from "./env" +import { syncGitHubReleases } from "./lib/sync" +import { assetsRoute } from "./routes/assets" +import { internalRoute } from "./routes/internal" +import { manifestRoute } from "./routes/manifest" +import { policyRoute } from "./routes/policy" + +export const app = new Hono<{ Bindings: Env }>() + +app.route("/", manifestRoute) +app.route("/", assetsRoute) +app.route("/", policyRoute) +app.route("/", internalRoute) + +export default { + fetch: app.fetch, + scheduled(_controller: ScheduledController, env: Env, ctx: ExecutionContext) { + ctx.waitUntil(syncGitHubReleases(env)) + }, +} diff --git a/apps/ota/src/lib/archive.ts b/apps/ota/src/lib/archive.ts new file mode 100644 index 000000000..e034030cb --- /dev/null +++ b/apps/ota/src/lib/archive.ts @@ -0,0 +1,238 @@ +import { Decompress } from "fzstd" +import tar from "tar-stream" + +import type { OtaPlatform, OtaRelease } from "./schema" + +const OTA_PLATFORMS: OtaPlatform[] = ["ios", "android", "macos", "windows", "linux"] + +type PlatformPayload = NonNullable +type PlatformAsset = PlatformPayload["launchAsset"] | PlatformPayload["assets"][number] + +interface MirroredFileRequest { + archivePath: string + key: string + contentType: string + sha256: string + body?: Uint8Array +} + +export interface MirroredFile { + key: string + body: Uint8Array + contentType: string +} + +export function buildMirroredAssetKey( + release: Pick, + platform: OtaPlatform, + assetPath: string, +) { + return [ + release.product, + release.channel, + release.runtimeVersion, + release.releaseVersion, + platform, + normalizeArchivePath(assetPath), + ].join("/") +} + +export async function extractMirroredFiles(input: { + release: OtaRelease + archiveBuffer: ArrayBuffer | Uint8Array +}): Promise { + const compressedArchive = + input.archiveBuffer instanceof Uint8Array + ? input.archiveBuffer + : new Uint8Array(input.archiveBuffer) + const requestedFiles = createMirroredFileRequests(input.release) + const requestsByArchivePath = new Map() + + for (const request of requestedFiles) { + const requestsForPath = requestsByArchivePath.get(request.archivePath) + + if (requestsForPath) { + requestsForPath.push(request) + continue + } + + requestsByArchivePath.set(request.archivePath, [request]) + } + + const missingArchivePaths = new Set(requestsByArchivePath.keys()) + const tarExtract = tar.extract() + + const extractedFiles = await new Promise((resolve, reject) => { + const rejectOnce = once(reject) + const resolveOnce = once(resolve) + + tarExtract.on("entry", (header, stream, next) => { + const archivePath = normalizeArchivePath(header.name) + const matchingRequests = requestsByArchivePath.get(archivePath) + const chunks: Uint8Array[] = [] + + stream.on("data", (chunk) => { + if (matchingRequests) { + chunks.push(new Uint8Array(chunk)) + } + }) + stream.on("error", (error) => { + rejectOnce(toError(error)) + }) + stream.on("end", async () => { + if (matchingRequests) { + const body = concatenateChunks(chunks) + const bodySha256 = await sha256Hex(body) + + for (const request of matchingRequests) { + if (request.sha256 !== bodySha256) { + rejectOnce( + new Error( + `Archive file "${archivePath}" hash mismatch: expected ${request.sha256} but received ${bodySha256}`, + ), + ) + return + } + + request.body = body + } + + missingArchivePaths.delete(archivePath) + } + + next() + }) + stream.resume() + }) + + tarExtract.on("error", (error) => { + rejectOnce(toError(error)) + }) + tarExtract.on("finish", () => { + if (missingArchivePaths.size > 0) { + rejectOnce( + new Error( + `Archive is missing referenced file "${[...missingArchivePaths][0]}" for ${input.release.releaseVersion}`, + ), + ) + return + } + + resolveOnce( + requestedFiles.map((request) => ({ + key: request.key, + body: request.body ?? new Uint8Array(0), + contentType: request.contentType, + })), + ) + }) + + const zstdStream = new Decompress((chunk, final) => { + if (chunk.byteLength > 0) { + tarExtract.write(chunk) + } + + if (final) { + tarExtract.end() + } + }) + + try { + zstdStream.push(compressedArchive, true) + } catch (error) { + rejectOnce(toError(error)) + } + }) + + return extractedFiles +} + +function createMirroredFileRequests(release: OtaRelease): MirroredFileRequest[] { + const requests: MirroredFileRequest[] = [] + + for (const platform of OTA_PLATFORMS) { + const platformPayload = release.platforms[platform] + + if (!platformPayload) { + continue + } + + for (const asset of listReferencedAssets(platformPayload)) { + const archivePath = normalizeArchivePath(asset.path) + + requests.push({ + archivePath, + key: buildMirroredAssetKey(release, platform, archivePath), + contentType: asset.contentType, + sha256: asset.sha256, + }) + } + } + + return requests +} + +function listReferencedAssets(platformPayload: PlatformPayload): PlatformAsset[] { + const dedupedAssets = new Map() + + for (const asset of [platformPayload.launchAsset, ...platformPayload.assets]) { + dedupedAssets.set(normalizeArchivePath(asset.path), asset) + } + + return [...dedupedAssets.values()] +} + +function normalizeArchivePath(path: string) { + return path + .replace(/^\/+/, "") + .replace(/^(\.\/)+/, "") + .replaceAll(/\/{2,}/g, "/") +} + +function concatenateChunks(chunks: readonly Uint8Array[]) { + if (chunks.length === 0) { + return new Uint8Array(0) + } + + if (chunks.length === 1) { + return chunks[0]!.slice() + } + + const totalLength = chunks.reduce((length, chunk) => length + chunk.byteLength, 0) + const output = new Uint8Array(totalLength) + let offset = 0 + + for (const chunk of chunks) { + output.set(chunk, offset) + offset += chunk.byteLength + } + + return output +} + +function once void>(callback: T): T { + let called = false + + return ((...args: Parameters) => { + if (called) { + return + } + + called = true + callback(...args) + }) as T +} + +function toError(error: unknown) { + return error instanceof Error ? error : new Error(String(error)) +} + +async function sha256Hex(data: Uint8Array) { + const digest = await crypto.subtle.digest("SHA-256", toDigestInput(data)) + + return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("") +} + +function toDigestInput(data: Uint8Array) { + return new Uint8Array(data) +} diff --git a/apps/ota/src/lib/constants.ts b/apps/ota/src/lib/constants.ts new file mode 100644 index 000000000..7262afc7e --- /dev/null +++ b/apps/ota/src/lib/constants.ts @@ -0,0 +1,16 @@ +import type { OtaPlatform, OtaRelease } from "./schema" + +export const KV_KEYS = { + release: (product: OtaRelease["product"], releaseVersion: OtaRelease["releaseVersion"]) => + `release:${product}:${releaseVersion}`, + latest: ( + product: OtaRelease["product"], + channel: OtaRelease["channel"], + runtimeVersion: OtaRelease["runtimeVersion"], + platform: OtaPlatform, + ) => `latest:${product}:${channel}:${runtimeVersion}:${platform}`, + policy: (product: OtaRelease["product"], channel: OtaRelease["channel"]) => + `policy:${product}:${channel}`, + githubEtag: "github:etag:releases", + syncLastSuccessAt: "sync:last-success-at", +} as const diff --git a/apps/ota/src/lib/github.ts b/apps/ota/src/lib/github.ts new file mode 100644 index 000000000..587e80377 --- /dev/null +++ b/apps/ota/src/lib/github.ts @@ -0,0 +1,98 @@ +export interface GitHubReleaseAsset { + name: string + url?: string + browser_download_url: string +} + +interface GitHubRelease { + tag_name: string + draft: boolean + prerelease: boolean + assets: GitHubReleaseAsset[] +} + +export interface GitHubReleaseSummary { + tag: string + metadataUrl: string + archiveUrl: string +} + +export type GitHubReleaseListResult = + | { kind: "not-modified" } + | { + kind: "ok" + etag: string | null + releases: GitHubReleaseSummary[] + } + +export class GitHubRequestError extends Error { + readonly status: number + readonly statusText: string + readonly body: string | null + + constructor(input: { status: number; statusText: string; body: string | null }) { + super(`GitHub releases request failed with ${input.status} ${input.statusText}`.trim()) + this.name = "GitHubRequestError" + this.status = input.status + this.statusText = input.statusText + this.body = input.body + } +} + +export async function listPublishedOtaReleases(input: { + owner: string + repo: string + token: string + etag: string | null +}): Promise { + const userAgent = `folo-ota-worker/${input.owner}.${input.repo}` + + const response = await fetch( + `https://api.github.com/repos/${input.owner}/${input.repo}/releases`, + { + headers: { + Accept: "application/vnd.github+json", + Authorization: `Bearer ${input.token}`, + "User-Agent": userAgent, + "X-GitHub-Api-Version": "2022-11-28", + ...(input.etag ? { "If-None-Match": input.etag } : {}), + }, + }, + ) + + if (response.status === 304) { + return { kind: "not-modified" } + } + + if (!response.ok) { + throw new GitHubRequestError({ + status: response.status, + statusText: response.statusText, + body: await response.text(), + }) + } + + const releases = (await response.json()) as GitHubRelease[] + + return { + kind: "ok", + etag: response.headers.get("etag"), + releases: releases + .filter((release) => !release.draft) + .map((release) => { + const metadata = release.assets.find((asset) => asset.name === "ota-release.json") + const archive = release.assets.find((asset) => asset.name === "dist.tar.zst") + + if (!metadata || !archive) { + return null + } + + return { + tag: release.tag_name, + metadataUrl: metadata.url ?? metadata.browser_download_url, + archiveUrl: archive.url ?? archive.browser_download_url, + } + }) + .filter((value): value is GitHubReleaseSummary => value !== null), + } +} diff --git a/apps/ota/src/lib/kv.ts b/apps/ota/src/lib/kv.ts new file mode 100644 index 000000000..c3734f090 --- /dev/null +++ b/apps/ota/src/lib/kv.ts @@ -0,0 +1,32 @@ +import { KV_KEYS } from "./constants" +import type { OtaPlatform, OtaRelease } from "./schema" + +export interface LatestReleasePointerRecord { + releaseVersion: OtaRelease["releaseVersion"] +} + +export type ReleaseRecord = OtaRelease + +export async function getLatestReleasePointer( + kv: KVNamespace, + input: { + product: OtaRelease["product"] + channel: OtaRelease["channel"] + runtimeVersion: OtaRelease["runtimeVersion"] + platform: OtaPlatform + }, +) { + return kv.get( + KV_KEYS.latest(input.product, input.channel, input.runtimeVersion, input.platform), + "json", + ) +} + +export async function putReleaseRecord( + kv: KVNamespace, + product: OtaRelease["product"], + releaseVersion: OtaRelease["releaseVersion"], + value: ReleaseRecord, +) { + await kv.put(KV_KEYS.release(product, releaseVersion), JSON.stringify(value)) +} diff --git a/apps/ota/src/lib/manifest.ts b/apps/ota/src/lib/manifest.ts new file mode 100644 index 000000000..9f461ac25 --- /dev/null +++ b/apps/ota/src/lib/manifest.ts @@ -0,0 +1,162 @@ +import { buildMirroredAssetKey } from "./archive" +import type { OtaPlatform, OtaRelease } from "./schema" + +type PlatformPayload = NonNullable +type PlatformAsset = PlatformPayload["launchAsset"] | PlatformPayload["assets"][number] + +export interface ManifestAsset { + key: string + hash: string + fileExtension?: string + contentType: string + url: string +} + +export interface OtaManifest { + id: string + createdAt: string + runtimeVersion: string + launchAsset: ManifestAsset + assets: ManifestAsset[] + metadata: { + channel: string + releaseVersion: string + } + extra: { + product: OtaRelease["product"] + } +} + +export function buildManifest( + release: OtaRelease, + input: { + origin: string + platform: OtaPlatform + }, +): OtaManifest { + const platformPayload = release.platforms[input.platform] + + if (!platformPayload) { + throw new Error( + `Release ${release.releaseVersion} does not include a ${input.platform} payload`, + ) + } + + return { + id: release.updateId ?? crypto.randomUUID(), + createdAt: release.publishedAt, + runtimeVersion: release.runtimeVersion, + launchAsset: toManifestAsset( + release, + input.origin, + input.platform, + platformPayload.launchAsset, + ), + assets: platformPayload.assets.map((asset) => + toManifestAsset(release, input.origin, input.platform, asset), + ), + metadata: { + channel: release.channel, + releaseVersion: release.releaseVersion, + }, + extra: { + product: release.product, + }, + } +} + +function toManifestAsset( + release: OtaRelease, + origin: string, + platform: OtaPlatform, + asset: PlatformAsset, +): ManifestAsset { + const { key, fileExtension } = toExpoAssetIdentity(asset.path, asset.contentType) + + return { + key, + hash: toExpoManifestHash(asset.sha256), + fileExtension, + contentType: asset.contentType, + url: new URL( + `/assets/${buildMirroredAssetKey(release, platform, asset.path)}`, + origin, + ).toString(), + } +} + +function toExpoManifestHash(sha256Hex: string) { + const bytes = hexToBytes(sha256Hex) + return Buffer.from(bytes) + .toString("base64") + .replaceAll("+", "-") + .replaceAll("/", "_") + .replaceAll(/=+$/g, "") +} + +function hexToBytes(sha256Hex: string) { + const normalized = sha256Hex.trim().toLowerCase() + + if (!/^[a-f0-9]{64}$/.test(normalized)) { + return new Uint8Array() + } + + const bytes = new Uint8Array(normalized.length / 2) + + for (let index = 0; index < normalized.length; index += 2) { + bytes[index / 2] = Number.parseInt(normalized.slice(index, index + 2), 16) + } + + return bytes +} + +function toExpoAssetIdentity(path: string, contentType: string) { + const fileName = path.split("/").at(-1) ?? path + const extensionMatch = fileName.match(/(\.[^.]+)$/) + + if (extensionMatch?.[1]) { + const fileExtension = extensionMatch[1] + return { + key: fileName.slice(0, -fileExtension.length), + fileExtension, + } + } + + const inferredExtension = inferExtensionFromContentType(contentType) + return { + key: fileName, + fileExtension: inferredExtension, + } +} + +function inferExtensionFromContentType(contentType: string) { + switch (contentType) { + case "application/javascript": { + return ".bundle" + } + case "image/png": { + return ".png" + } + case "image/jpeg": { + return ".jpg" + } + case "image/webp": { + return ".webp" + } + case "font/otf": { + return ".otf" + } + case "font/ttf": { + return ".ttf" + } + case "font/woff": { + return ".woff" + } + case "font/woff2": { + return ".woff2" + } + default: { + return + } + } +} diff --git a/apps/ota/src/lib/policy.ts b/apps/ota/src/lib/policy.ts new file mode 100644 index 000000000..1c1231df1 --- /dev/null +++ b/apps/ota/src/lib/policy.ts @@ -0,0 +1,53 @@ +import type { OtaRelease } from "./schema" +import { compareSemver } from "./version" + +type StoreReleasePolicyInput = Pick< + OtaRelease, + "releaseVersion" | "releaseKind" | "runtimeVersion" | "policy" +> + +type StorePolicyEvaluation = + | { + action: "none" + targetVersion: null + message: null + } + | { + action: "block" | "prompt" + targetVersion: OtaRelease["releaseVersion"] + message: string | null + } + +export function evaluateStorePolicy( + latestStoreRelease: StoreReleasePolicyInput | null, + input: { + installedBinaryVersion: OtaRelease["releaseVersion"] + }, +): StorePolicyEvaluation { + if (!latestStoreRelease || latestStoreRelease.releaseKind !== "store") { + return { action: "none", targetVersion: null, message: null } + } + + if ( + compareSemver( + input.installedBinaryVersion, + latestStoreRelease.policy.minSupportedBinaryVersion, + ) < 0 + ) { + return { + action: "block", + targetVersion: latestStoreRelease.releaseVersion, + message: latestStoreRelease.policy.message, + } + } + + if (compareSemver(latestStoreRelease.releaseVersion, input.installedBinaryVersion) <= 0) { + return { action: "none", targetVersion: null, message: null } + } + + return { + action: latestStoreRelease.policy.storeRequired ? "block" : "prompt", + targetVersion: latestStoreRelease.releaseVersion, + message: latestStoreRelease.policy.message, + } +} diff --git a/apps/ota/src/lib/r2.ts b/apps/ota/src/lib/r2.ts new file mode 100644 index 000000000..336d7dd61 --- /dev/null +++ b/apps/ota/src/lib/r2.ts @@ -0,0 +1,14 @@ +import type { MirroredFile } from "./archive" + +export const IMMUTABLE_ASSET_CACHE_CONTROL = "public, max-age=31536000, immutable" + +export async function putMirroredFiles(bucket: R2Bucket, files: readonly MirroredFile[]) { + for (const file of files) { + await bucket.put(file.key, file.body, { + httpMetadata: { + cacheControl: IMMUTABLE_ASSET_CACHE_CONTROL, + contentType: file.contentType, + }, + }) + } +} diff --git a/apps/ota/src/lib/schema.ts b/apps/ota/src/lib/schema.ts new file mode 100644 index 000000000..dc6018056 --- /dev/null +++ b/apps/ota/src/lib/schema.ts @@ -0,0 +1,52 @@ +import { z } from "zod" + +const semver = z.string().regex(/^\d+\.\d+\.\d+$/) +const sha256 = z.string().regex(/^[a-f0-9]{64}$/) + +const assetSchema = z.object({ + path: z.string().min(1), + sha256, + contentType: z.string().min(1), +}) + +const platformSchema = z.object({ + launchAsset: assetSchema, + assets: z.array(assetSchema), +}) + +const platformsSchema = z + .object({ + ios: platformSchema.optional(), + android: platformSchema.optional(), + macos: platformSchema.optional(), + windows: platformSchema.optional(), + linux: platformSchema.optional(), + }) + .strict() + .refine((platforms) => Object.values(platforms).some(Boolean), { + message: "At least one platform must be provided", + }) + +export const otaReleaseSchema = z.object({ + schemaVersion: z.literal(1), + updateId: z.string().uuid().optional(), + product: z.enum(["mobile", "desktop"]), + channel: z.string().min(1), + releaseVersion: semver, + releaseKind: z.enum(["ota", "store"]), + runtimeVersion: semver, + publishedAt: z.string().datetime(), + git: z.object({ + tag: z.string().min(1), + commit: z.string().min(7), + }), + policy: z.object({ + storeRequired: z.boolean(), + minSupportedBinaryVersion: semver, + message: z.string().nullable(), + }), + platforms: platformsSchema, +}) + +export type OtaPlatform = "ios" | "android" | "macos" | "windows" | "linux" +export type OtaRelease = z.infer diff --git a/apps/ota/src/lib/sync.ts b/apps/ota/src/lib/sync.ts new file mode 100644 index 000000000..694c431a4 --- /dev/null +++ b/apps/ota/src/lib/sync.ts @@ -0,0 +1,218 @@ +import type { Env } from "../env" +import type { MirroredFile } from "./archive" +import { buildMirroredAssetKey, extractMirroredFiles } from "./archive" +import { KV_KEYS } from "./constants" +import { listPublishedOtaReleases } from "./github" +import type { LatestReleasePointerRecord } from "./kv" +import { putReleaseRecord } from "./kv" +import { putMirroredFiles } from "./r2" +import type { OtaPlatform, OtaRelease } from "./schema" +import { otaReleaseSchema } from "./schema" +import { compareSemver } from "./version" + +const OTA_PLATFORMS: OtaPlatform[] = ["ios", "android", "macos", "windows", "linux"] +const semverPattern = /^\d+\.\d+\.\d+$/ +let inFlightSync: Promise | null = null + +export async function syncGitHubReleases(env: Env) { + if (inFlightSync) { + return inFlightSync + } + + const syncPromise = runSyncGitHubReleases(env).finally(() => { + if (inFlightSync === syncPromise) { + inFlightSync = null + } + }) + + inFlightSync = syncPromise + + return syncPromise +} + +async function runSyncGitHubReleases(env: Env) { + const storedEtag = await env.OTA_KV.get(KV_KEYS.githubEtag) + const releasesResult = await listPublishedOtaReleases({ + owner: env.GITHUB_OWNER, + repo: env.GITHUB_REPO, + token: env.GITHUB_TOKEN, + etag: storedEtag ?? null, + }) + + if (releasesResult.kind === "not-modified") { + await updateSyncLastSuccessAt(env.OTA_KV) + return + } + + for (const releaseSummary of releasesResult.releases) { + const release = await fetchReleaseMetadata(releaseSummary.metadataUrl, env) + + if (release.releaseKind === "ota") { + const archiveBuffer = await fetchArchiveBuffer(releaseSummary.archiveUrl, env) + const files = await extractMirroredFiles({ + release, + archiveBuffer, + }) + + await mirrorReleaseToStorage( + { + release, + files, + }, + { + kv: env.OTA_KV, + bucket: env.OTA_BUCKET, + }, + ) + + continue + } + + await putReleaseRecord(env.OTA_KV, release.product, release.releaseVersion, release) + await putLatestPolicyRecord(env.OTA_KV, release) + } + + if (releasesResult.etag) { + await env.OTA_KV.put(KV_KEYS.githubEtag, releasesResult.etag) + } + + await updateSyncLastSuccessAt(env.OTA_KV) +} + +export async function mirrorReleaseToStorage( + input: { + release: OtaRelease + files: readonly MirroredFile[] + }, + env: { + kv: KVNamespace + bucket: R2Bucket + }, +) { + await putMirroredFiles(env.bucket, input.files) + await putReleaseRecord(env.kv, input.release.product, input.release.releaseVersion, input.release) + + const mirroredFileKeys = new Set(input.files.map((file) => file.key)) + + for (const platform of OTA_PLATFORMS) { + if (!hasCompleteMirroredPayload(input.release, platform, mirroredFileKeys)) { + continue + } + + const latestReleasePointer: LatestReleasePointerRecord = { + releaseVersion: input.release.releaseVersion, + } + const currentPointer = await env.kv.get( + KV_KEYS.latest( + input.release.product, + input.release.channel, + input.release.runtimeVersion, + platform, + ), + "json", + ) + + if ( + !shouldPersistReleaseVersion(currentPointer?.releaseVersion, input.release.releaseVersion) + ) { + continue + } + + await env.kv.put( + KV_KEYS.latest( + input.release.product, + input.release.channel, + input.release.runtimeVersion, + platform, + ), + JSON.stringify(latestReleasePointer), + ) + } +} + +function hasCompleteMirroredPayload( + release: OtaRelease, + platform: OtaPlatform, + mirroredFileKeys: ReadonlySet, +) { + const platformPayload = release.platforms[platform] + + if (!platformPayload) { + return false + } + + for (const asset of [platformPayload.launchAsset, ...platformPayload.assets]) { + if (!mirroredFileKeys.has(buildMirroredAssetKey(release, platform, asset.path))) { + return false + } + } + + return true +} + +async function putLatestPolicyRecord(kv: KVNamespace, release: OtaRelease) { + const existingPolicyRecord = await kv.get( + KV_KEYS.policy(release.product, release.channel), + "json", + ) + + if (!shouldPersistReleaseVersion(existingPolicyRecord?.releaseVersion, release.releaseVersion)) { + return + } + + await kv.put(KV_KEYS.policy(release.product, release.channel), JSON.stringify(release)) +} + +async function fetchReleaseMetadata( + url: string, + env: Pick, +): Promise { + const response = await fetch(url, { + headers: createGitHubAssetHeaders(env), + }) + + if (!response.ok) { + throw new Error(`Failed to fetch OTA release metadata from ${url}: ${response.status}`) + } + + return otaReleaseSchema.parse(await response.json()) +} + +async function fetchArchiveBuffer( + url: string, + env: Pick, +) { + const response = await fetch(url, { + headers: createGitHubAssetHeaders(env), + }) + + if (!response.ok) { + throw new Error(`Failed to fetch OTA archive from ${url}: ${response.status}`) + } + + return new Uint8Array(await response.arrayBuffer()) +} + +function createGitHubAssetHeaders(env: Pick) { + return { + Accept: "application/octet-stream", + Authorization: `Bearer ${env.GITHUB_TOKEN}`, + "User-Agent": `folo-ota-worker/${env.GITHUB_OWNER}.${env.GITHUB_REPO}`, + } +} + +async function updateSyncLastSuccessAt(kv: KVNamespace) { + await kv.put(KV_KEYS.syncLastSuccessAt, new Date().toISOString()) +} + +function shouldPersistReleaseVersion(currentVersion: unknown, nextVersion: string) { + if (!isSemver(currentVersion)) { + return true + } + + return compareSemver(nextVersion, currentVersion) >= 0 +} + +function isSemver(value: unknown): value is string { + return typeof value === "string" && semverPattern.test(value) +} diff --git a/apps/ota/src/lib/version.ts b/apps/ota/src/lib/version.ts new file mode 100644 index 000000000..6bc5ffe0e --- /dev/null +++ b/apps/ota/src/lib/version.ts @@ -0,0 +1,35 @@ +import type { OtaPlatform, OtaRelease } from "./schema" + +export function compareSemver(left: string, right: string) { + const leftParts = left.split(".").map(Number) + const rightParts = right.split(".").map(Number) + + for (let index = 0; index < 3; index += 1) { + const diff = leftParts[index]! - rightParts[index]! + if (diff !== 0) { + return diff + } + } + + return 0 +} + +export function selectLatestCompatibleRelease( + releases: OtaRelease[], + input: { + product: OtaRelease["product"] + channel: OtaRelease["channel"] + runtimeVersion: OtaRelease["runtimeVersion"] + platform: OtaPlatform + }, +) { + return ( + releases + .filter((release) => release.product === input.product) + .filter((release) => release.channel === input.channel) + .filter((release) => release.releaseKind === "ota") + .filter((release) => release.runtimeVersion === input.runtimeVersion) + .filter((release) => Boolean(release.platforms[input.platform])) + .sort((left, right) => compareSemver(right.releaseVersion, left.releaseVersion))[0] ?? null + ) +} diff --git a/apps/ota/src/routes/assets.ts b/apps/ota/src/routes/assets.ts new file mode 100644 index 000000000..3f6ac6104 --- /dev/null +++ b/apps/ota/src/routes/assets.ts @@ -0,0 +1,24 @@ +import { Hono } from "hono" + +import type { Env } from "../env" +import { IMMUTABLE_ASSET_CACHE_CONTROL } from "../lib/r2" + +export const assetsRoute = new Hono<{ Bindings: Env }>() + +assetsRoute.get("/assets/*", async (c) => { + const key = c.req.path.replace(/^\/assets\/+/, "") + const object = await c.env.OTA_BUCKET.get(key) + + if (!object) { + return c.text("Not found", 404) + } + + const headers = new Headers() + object.writeHttpMetadata(headers) + headers.set("cache-control", IMMUTABLE_ASSET_CACHE_CONTROL) + + return new Response(object.body, { + status: 200, + headers, + }) +}) diff --git a/apps/ota/src/routes/internal.ts b/apps/ota/src/routes/internal.ts new file mode 100644 index 000000000..ac7ff0910 --- /dev/null +++ b/apps/ota/src/routes/internal.ts @@ -0,0 +1,28 @@ +import { Hono } from "hono" + +import type { Env } from "../env" +import { KV_KEYS } from "../lib/constants" +import { syncGitHubReleases } from "../lib/sync" + +export const internalRoute = new Hono<{ Bindings: Env }>() + +internalRoute.post("/internal/sync", async (c) => { + const token = c.req.header(c.env.OTA_SYNC_TOKEN_HEADER) + + if (token !== c.env.OTA_SYNC_TOKEN) { + return c.json({ error: "Unauthorized" }, 401) + } + + await syncGitHubReleases(c.env) + + return c.json({ ok: true }) +}) + +internalRoute.get("/internal/health", async (c) => { + const lastSuccessAt = await c.env.OTA_KV.get(KV_KEYS.syncLastSuccessAt) + + return c.json({ + ok: true, + lastSuccessAt: lastSuccessAt ?? null, + }) +}) diff --git a/apps/ota/src/routes/manifest.ts b/apps/ota/src/routes/manifest.ts new file mode 100644 index 000000000..3870f8358 --- /dev/null +++ b/apps/ota/src/routes/manifest.ts @@ -0,0 +1,118 @@ +import { Hono } from "hono" +import { z } from "zod" + +import type { Env } from "../env" +import { KV_KEYS } from "../lib/constants" +import { getLatestReleasePointer } from "../lib/kv" +import { buildManifest } from "../lib/manifest" +import type { OtaPlatform, OtaRelease } from "../lib/schema" +import { otaReleaseSchema } from "../lib/schema" + +const OTA_PLATFORMS: readonly OtaPlatform[] = ["ios", "android", "macos", "windows", "linux"] +const OTA_PRODUCTS = ["mobile", "desktop"] as const +const semverSchema = z.string().regex(/^\d+\.\d+\.\d+$/) +const latestReleasePointerSchema = z.object({ + releaseVersion: semverSchema, +}) + +export const manifestRoute = new Hono<{ Bindings: Env }>() + +manifestRoute.get("/manifest", async (c) => { + const platformHeader = c.req.header("expo-platform") + const platform = parsePlatform(platformHeader) + const runtimeVersion = c.req.header("expo-runtime-version") + const channel = c.req.header("expo-channel-name") ?? "production" + const product = parseProduct(c.req.query("product")) + + if (!platformHeader) { + return c.json({ error: "Missing expo-platform header" }, 400) + } + + if (!platform) { + return c.json({ error: "Invalid expo-platform header" }, 400) + } + + if (!runtimeVersion) { + return c.json({ error: "Missing expo-runtime-version header" }, 400) + } + + if (!semverSchema.safeParse(runtimeVersion).success) { + return c.json({ error: "Invalid expo-runtime-version header" }, 400) + } + + if (!product) { + return c.json({ error: "Invalid product query parameter" }, 400) + } + + const pointerRecord = await getLatestReleasePointer(c.env.OTA_KV, { + product, + channel, + runtimeVersion, + platform, + }) + + if (!pointerRecord) { + return c.body(null, 204) + } + + const parsedPointer = latestReleasePointerSchema.safeParse(pointerRecord) + + if (!parsedPointer.success) { + return c.body(null, 204) + } + + const pointer = parsedPointer.data + const releaseRecord = await c.env.OTA_KV.get( + KV_KEYS.release(product, pointer.releaseVersion), + "json", + ) + + if (!releaseRecord) { + return c.body(null, 204) + } + + const parsedRelease = otaReleaseSchema.safeParse(releaseRecord) + + if (!parsedRelease.success) { + return c.body(null, 204) + } + + const release: OtaRelease = parsedRelease.data + + if ( + release.releaseKind !== "ota" || + release.product !== product || + release.channel !== channel || + release.releaseVersion !== pointer.releaseVersion || + release.runtimeVersion !== runtimeVersion || + !release.platforms[platform] + ) { + 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", + }, + }, + ) +}) + +function parsePlatform(value: string | undefined): OtaPlatform | null { + return OTA_PLATFORMS.find((platform) => platform === value) ?? null +} + +function parseProduct(value: string | undefined): OtaRelease["product"] | null { + if (value === undefined) { + return "mobile" + } + + return OTA_PRODUCTS.find((product) => product === value) ?? null +} diff --git a/apps/ota/src/routes/policy.ts b/apps/ota/src/routes/policy.ts new file mode 100644 index 000000000..05a6b3384 --- /dev/null +++ b/apps/ota/src/routes/policy.ts @@ -0,0 +1,58 @@ +import { Hono } from "hono" +import { z } from "zod" + +import type { Env } from "../env" +import { KV_KEYS } from "../lib/constants" +import { evaluateStorePolicy } from "../lib/policy" +import type { OtaRelease } from "../lib/schema" +import { otaReleaseSchema } from "../lib/schema" + +const storePolicyReleaseSchema = otaReleaseSchema.pick({ + releaseVersion: true, + releaseKind: true, + runtimeVersion: true, + policy: true, +}) +type StorePolicyRelease = z.infer +const OTA_PRODUCTS = ["mobile", "desktop"] as const +const semverSchema = z.string().regex(/^\d+\.\d+\.\d+$/) + +export const policyRoute = new Hono<{ Bindings: Env }>() + +policyRoute.get("/policy", async (c) => { + const product = parseProduct(c.req.query("product")) + const channel = c.req.query("channel") ?? "production" + const installedBinaryVersion = c.req.query("installedBinaryVersion") + + if (!product) { + return c.json({ error: "Invalid product query parameter" }, 400) + } + + if (!installedBinaryVersion) { + return c.json({ error: "Missing installedBinaryVersion query parameter" }, 400) + } + + if (!semverSchema.safeParse(installedBinaryVersion).success) { + return c.json({ error: "Invalid installedBinaryVersion query parameter" }, 400) + } + + const latestStoreReleaseRecord = await c.env.OTA_KV.get(KV_KEYS.policy(product, channel), "json") + const parsedStoreRelease = storePolicyReleaseSchema.safeParse(latestStoreReleaseRecord) + const latestStoreRelease: StorePolicyRelease | null = parsedStoreRelease.success + ? parsedStoreRelease.data + : null + + return c.json( + evaluateStorePolicy(latestStoreRelease, { + installedBinaryVersion, + }), + ) +}) + +function parseProduct(value: string | undefined): OtaRelease["product"] | null { + if (value === undefined) { + return "mobile" + } + + return OTA_PRODUCTS.find((product) => product === value) ?? null +} diff --git a/apps/ota/tsconfig.json b/apps/ota/tsconfig.json new file mode 100644 index 000000000..d31d94bef --- /dev/null +++ b/apps/ota/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../../packages/configs/tsconfig.extend.json", + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "WebWorker"], + "types": ["@cloudflare/workers-types", "vitest/globals"], + "jsx": "react-jsx", + "baseUrl": "." + }, + "include": ["src/**/*.ts", "src/**/*.tsx"] +} diff --git a/apps/ota/wrangler.jsonc b/apps/ota/wrangler.jsonc new file mode 100644 index 000000000..8d96394eb --- /dev/null +++ b/apps/ota/wrangler.jsonc @@ -0,0 +1,66 @@ +{ + "$schema": "../../node_modules/wrangler/config-schema.json", + "name": "folo-ota", + "main": "src/index.ts", + "compatibility_date": "2026-04-10", + "compatibility_flags": ["nodejs_compat"], + "account_id": "1f1d1678a2413a54c944b3081bab5c84", + "workers_dev": true, + "routes": [ + { + "pattern": "ota.folo.is/*", + "zone_id": "115ea8e6a7865dbfc1cf4530d5f87f63", + }, + ], + "kv_namespaces": [ + { + "binding": "OTA_KV", + "id": "REPLACE_WITH_PROD_KV_ID", + "preview_id": "REPLACE_WITH_DEV_KV_ID", + }, + ], + "r2_buckets": [ + { + "binding": "OTA_BUCKET", + "bucket_name": "follow-ota", + }, + ], + "vars": { + "GITHUB_OWNER": "RSSNext", + "GITHUB_REPO": "Folo", + "OTA_SYNC_TOKEN_HEADER": "x-ota-sync-token", + }, + "triggers": { + "crons": ["*/5 * * * *"], + }, + "env": { + "dev": { + "name": "folo-ota-dev", + "workers_dev": true, + "kv_namespaces": [ + { + "binding": "OTA_KV", + "id": "REPLACE_WITH_DEV_KV_ID", + "preview_id": "REPLACE_WITH_DEV_PREVIEW_KV_ID", + }, + ], + "r2_buckets": [ + { + "binding": "OTA_BUCKET", + "bucket_name": "replace-with-dev-bucket-name", + }, + ], + "vars": { + "GITHUB_OWNER": "RSSNext", + "GITHUB_REPO": "Folo", + "OTA_SYNC_TOKEN_HEADER": "x-ota-sync-token", + }, + "routes": [ + { + "pattern": "ota.dev.folo.is/*", + "zone_id": "115ea8e6a7865dbfc1cf4530d5f87f63", + }, + ], + }, + }, +} diff --git a/docs/superpowers/plans/2026-04-10-ota.md b/docs/superpowers/plans/2026-04-10-ota.md new file mode 100644 index 000000000..8ce21abde --- /dev/null +++ b/docs/superpowers/plans/2026-04-10-ota.md @@ -0,0 +1,1856 @@ +# OTA Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Build a standalone Cloudflare-based OTA service in `apps/ota`, publish mobile OTA metadata from GitHub Releases, mirror payloads into R2, and connect `apps/mobile` to the service for OTA and store-update policy checks. + +**Architecture:** `apps/ota` is a Hono-based Cloudflare Worker with KV-backed release indexes and R2-backed assets. GitHub Releases stores `ota-release.json` and `dist.tar.zst`; the Worker syncs release metadata and payloads, serves `/manifest`, `/assets/*`, and `/policy`, and `apps/mobile` consumes the service through `expo-updates` plus a lightweight policy client. The repository can contain both desktop and mobile releases, so Git tags stay product-scoped while metadata `releaseVersion` remains plain `x.y.z`. + +**Tech Stack:** Cloudflare Workers, Wrangler, Hono, R2, KV, GitHub Releases REST API, Expo Updates, Zod, Vitest, TypeScript + +--- + +## File Structure + +### New files + +- `apps/ota/package.json` + Sets up Worker dependencies, scripts, and test commands. +- `apps/ota/tsconfig.json` + TypeScript config for the Worker app. +- `apps/ota/wrangler.jsonc` + Worker bindings, routes, cron triggers, and environment variables. +- `apps/ota/src/index.ts` + Worker entrypoint and route registration. +- `apps/ota/src/env.ts` + Central environment binding types and access helpers. +- `apps/ota/src/lib/constants.ts` + Shared constants for headers, cache keys, and route behavior. +- `apps/ota/src/lib/errors.ts` + Worker-specific error types and response helpers. +- `apps/ota/src/lib/schema.ts` + Zod schema for `ota-release.json` and policy responses. +- `apps/ota/src/lib/version.ts` + SemVer comparison helpers and latest-version selection logic. +- `apps/ota/src/lib/kv.ts` + KV key builders and KV persistence helpers. +- `apps/ota/src/lib/r2.ts` + R2 lookup and asset streaming helpers. +- `apps/ota/src/lib/github.ts` + GitHub Releases fetcher with conditional request support. +- `apps/ota/src/lib/archive.ts` + Dist archive extraction and mirrored object generation. +- `apps/ota/src/lib/sync.ts` + End-to-end sync orchestration from GitHub Release to KV and R2. +- `apps/ota/src/lib/manifest.ts` + Expo manifest generation and code-signing integration points. +- `apps/ota/src/lib/policy.ts` + Store-update policy resolution. +- `apps/ota/src/routes/manifest.ts` + `/manifest` route. +- `apps/ota/src/routes/assets.ts` + `/assets/*` route. +- `apps/ota/src/routes/policy.ts` + `/policy` route. +- `apps/ota/src/routes/internal.ts` + `/internal/sync` and `/internal/health` routes. +- `apps/ota/src/__tests__/schema.test.ts` + Metadata schema tests. +- `apps/ota/src/__tests__/version.test.ts` + Version ordering tests. +- `apps/ota/src/__tests__/policy.test.ts` + Store-policy evaluation tests. +- `apps/ota/src/__tests__/manifest.test.ts` + Manifest generation tests. +- `apps/ota/src/__tests__/sync.test.ts` + Sync pipeline tests with mocked GitHub, KV, and R2. +- `apps/mobile/src/modules/ota/provider.tsx` + OTA check and apply lifecycle. +- `apps/mobile/src/modules/ota/client.ts` + `/policy` client and typed API wrapper. +- `apps/mobile/src/modules/ota/types.ts` + Shared OTA state and policy response types for mobile. +- `apps/mobile/src/modules/ota/store.ts` + Small local state holder for OTA and store policy UI. +- `apps/mobile/src/modules/ota/__tests__/client.test.ts` + Policy client tests. +- `apps/mobile/src/modules/ota/__tests__/store.test.ts` + State transition tests. +- `.github/workflows/publish-ota.yml` + OTA publish workflow for GitHub Releases and post-publish sync. +- `.github/scripts/build-ota-release.mjs` + Creates `ota-release.json` and `dist.tar.zst` from mobile export output. +- `.github/scripts/trigger-ota-sync.mjs` + Calls the Worker sync endpoint from GitHub Actions. + +### Modified files + +- `/Users/diygod/.codex/worktrees/de1f/Folo/package.json` + Add workspace awareness only if needed for root scripts. +- `/Users/diygod/.codex/worktrees/de1f/Folo/apps/mobile/app.config.ts` + Enable `updates.url`, request headers, and keep explicit runtime version behavior. +- `/Users/diygod/.codex/worktrees/de1f/Folo/apps/mobile/package.json` + Replace the old `update` script and add OTA-specific build helpers. +- `/Users/diygod/.codex/worktrees/de1f/Folo/apps/mobile/src/main.tsx` + Mount the OTA provider near the app root. +- `/Users/diygod/.codex/worktrees/de1f/Folo/apps/mobile/src/modules/debug/index.tsx` + Add manual OTA debug actions in non-production builds. +- `/Users/diygod/.codex/worktrees/de1f/Folo/.github/workflows/tag.yml` + Optionally dispatch OTA workflow for OTA releases if orchestration is desired. + +--- + +### Task 1: Scaffold `apps/ota` + +**Files:** + +- Create: `apps/ota/package.json` +- Create: `apps/ota/tsconfig.json` +- Create: `apps/ota/wrangler.jsonc` +- Create: `apps/ota/src/index.ts` +- Create: `apps/ota/src/env.ts` +- Test: `apps/ota/src/__tests__/schema.test.ts` + +- [ ] **Step 1: Write the failing smoke test for the metadata schema** + +```ts +import { describe, expect, it } from "vitest" + +import { otaReleaseSchema } from "../lib/schema" + +describe("otaReleaseSchema", () => { + it("accepts a plain x.y.z release version and a binary-compatible runtime version", () => { + const parsed = otaReleaseSchema.parse({ + schemaVersion: 1, + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + publishedAt: "2026-04-10T12:00:00Z", + git: { + tag: "mobile/v0.4.2", + commit: "abcdef1234567890", + }, + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.1", + message: null, + }, + platforms: { + ios: { + launchAsset: { + path: "bundles/ios-main.js", + sha256: "a".repeat(64), + contentType: "application/javascript", + }, + assets: [], + }, + }, + }) + + expect(parsed.releaseVersion).toBe("0.4.2") + expect(parsed.runtimeVersion).toBe("0.4.1") + }) +}) +``` + +- [ ] **Step 2: Run the test to verify it fails** + +Run: `pnpm exec vitest run apps/ota/src/__tests__/schema.test.ts` + +Expected: FAIL with module resolution errors because `apps/ota` and `otaReleaseSchema` do not exist yet. + +- [ ] **Step 3: Create the Worker package and configuration** + +```json +{ + "name": "@follow/ota", + "private": true, + "type": "module", + "scripts": { + "dev": "wrangler dev", + "deploy:dev": "wrangler deploy --env dev", + "deploy:prod": "wrangler deploy", + "test": "vitest run", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "hono": "4.12.1", + "ofetch": "1.5.1", + "zod": "3.25.76" + }, + "devDependencies": { + "@cloudflare/workers-types": "^4.20260405.0", + "typescript": "catalog:", + "vitest": "3.2.4", + "wrangler": "4.68.1" + } +} +``` + +```json +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "WebWorker"], + "types": ["@cloudflare/workers-types", "vitest/globals"], + "jsx": "react-jsx", + "baseUrl": "." + }, + "include": ["src/**/*.ts", "src/**/*.tsx"] +} +``` + +```jsonc +{ + "$schema": "../../node_modules/wrangler/config-schema.json", + "name": "folo-ota", + "main": "src/index.ts", + "compatibility_date": "2026-04-10", + "compatibility_flags": ["nodejs_compat"], + "account_id": "1f1d1678a2413a54c944b3081bab5c84", + "workers_dev": true, + "routes": [ + { + "pattern": "ota.folo.is/*", + "zone_id": "115ea8e6a7865dbfc1cf4530d5f87f63", + }, + ], + "kv_namespaces": [ + { + "binding": "OTA_KV", + "id": "REPLACE_WITH_PROD_KV_ID", + "preview_id": "REPLACE_WITH_DEV_KV_ID", + }, + ], + "r2_buckets": [ + { + "binding": "OTA_BUCKET", + "bucket_name": "follow-ota", + }, + ], + "vars": { + "GITHUB_OWNER": "RSSNext", + "GITHUB_REPO": "Folo", + "OTA_SYNC_TOKEN_HEADER": "x-ota-sync-token", + }, + "triggers": { + "crons": ["*/5 * * * *"], + }, + "env": { + "dev": { + "name": "folo-ota-dev", + "workers_dev": true, + "routes": [ + { + "pattern": "ota.dev.folo.is/*", + "zone_id": "115ea8e6a7865dbfc1cf4530d5f87f63", + }, + ], + }, + }, +} +``` + +```ts +export interface Env { + OTA_KV: KVNamespace + OTA_BUCKET: R2Bucket + GITHUB_OWNER: string + GITHUB_REPO: string + GITHUB_TOKEN: string + OTA_SYNC_TOKEN: string + OTA_SYNC_TOKEN_HEADER: string +} +``` + +```ts +import { Hono } from "hono" + +import type { Env } from "./env" + +const app = new Hono<{ Bindings: Env }>() + +app.get("/internal/health", (c) => c.json({ ok: true })) + +export default { + fetch: app.fetch, +} +``` + +- [ ] **Step 4: Add the initial schema implementation** + +```ts +import { z } from "zod" + +const semver = z.string().regex(/^\d+\.\d+\.\d+$/) +const sha256 = z.string().regex(/^[a-f0-9]{64}$/) + +const assetSchema = z.object({ + path: z.string().min(1), + sha256, + contentType: z.string().min(1), +}) + +export const otaReleaseSchema = z.object({ + schemaVersion: z.literal(1), + product: z.enum(["mobile", "desktop"]), + channel: z.string().min(1), + releaseVersion: semver, + releaseKind: z.enum(["ota", "store"]), + runtimeVersion: semver, + publishedAt: z.string().datetime(), + git: z.object({ + tag: z.string().min(1), + commit: z.string().min(7), + }), + policy: z.object({ + storeRequired: z.boolean(), + minSupportedBinaryVersion: semver, + message: z.string().nullable(), + }), + platforms: z.record( + z.enum(["ios", "android", "macos", "windows", "linux"]), + z.object({ + launchAsset: assetSchema, + assets: z.array(assetSchema), + }), + ), +}) +``` + +- [ ] **Step 5: Run the test and basic checks** + +Run: + +```bash +pnpm exec vitest run apps/ota/src/__tests__/schema.test.ts +pnpm --filter @follow/ota typecheck +``` + +Expected: + +- Vitest PASS for the schema test +- TypeScript completes without errors in `apps/ota` + +- [ ] **Step 6: Commit** + +```bash +git add apps/ota docs/superpowers/plans/2026-04-10-ota.md +git commit -m "feat(ota): scaffold Cloudflare worker app" +``` + +### Task 2: Add release-version comparison and selection primitives + +**Files:** + +- Create: `apps/ota/src/lib/version.ts` +- Create: `apps/ota/src/__tests__/version.test.ts` +- Modify: `apps/ota/src/lib/schema.ts` + +- [ ] **Step 1: Write the failing version-selection tests** + +```ts +import { describe, expect, it } from "vitest" + +import { compareSemver, selectLatestCompatibleRelease } from "../lib/version" + +describe("compareSemver", () => { + it("orders plain x.y.z versions numerically", () => { + expect(compareSemver("0.4.10", "0.4.2")).toBeGreaterThan(0) + expect(compareSemver("1.0.0", "1.0.0")).toBe(0) + expect(compareSemver("0.4.2", "0.5.0")).toBeLessThan(0) + }) +}) + +describe("selectLatestCompatibleRelease", () => { + it("selects the highest OTA release for the same runtime", () => { + const result = selectLatestCompatibleRelease( + [ + { + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + platforms: { + ios: { + launchAsset: { + path: "a", + sha256: "a".repeat(64), + contentType: "application/javascript", + }, + assets: [], + }, + }, + }, + { + product: "mobile", + channel: "production", + releaseVersion: "0.4.4", + releaseKind: "ota", + runtimeVersion: "0.4.3", + platforms: { + ios: { + launchAsset: { + path: "b", + sha256: "b".repeat(64), + contentType: "application/javascript", + }, + assets: [], + }, + }, + }, + ] as any, + { + product: "mobile", + channel: "production", + runtimeVersion: "0.4.1", + platform: "ios", + }, + ) + + expect(result?.releaseVersion).toBe("0.4.2") + }) +}) +``` + +- [ ] **Step 2: Run the tests to verify failure** + +Run: `pnpm exec vitest run apps/ota/src/__tests__/version.test.ts` + +Expected: FAIL because `version.ts` does not exist. + +- [ ] **Step 3: Implement semver comparison and selection** + +```ts +import type { z } from "zod" + +import type { otaReleaseSchema } from "./schema" + +type OtaRelease = z.infer + +export function compareSemver(left: string, right: string) { + const leftParts = left.split(".").map(Number) + const rightParts = right.split(".").map(Number) + + for (let index = 0; index < 3; index += 1) { + const diff = leftParts[index]! - rightParts[index]! + if (diff !== 0) return diff + } + + return 0 +} + +export function selectLatestCompatibleRelease( + releases: OtaRelease[], + input: { + product: OtaRelease["product"] + channel: string + runtimeVersion: string + platform: keyof OtaRelease["platforms"] + }, +) { + return ( + releases + .filter((release) => release.product === input.product) + .filter((release) => release.channel === input.channel) + .filter((release) => release.releaseKind === "ota") + .filter((release) => release.runtimeVersion === input.runtimeVersion) + .filter((release) => input.platform in release.platforms) + .sort((left, right) => compareSemver(right.releaseVersion, left.releaseVersion))[0] ?? null + ) +} +``` + +- [ ] **Step 4: Run tests and typecheck** + +Run: + +```bash +pnpm exec vitest run apps/ota/src/__tests__/version.test.ts +pnpm --filter @follow/ota typecheck +``` + +Expected: PASS for the version tests and zero TypeScript errors. + +- [ ] **Step 5: Commit** + +```bash +git add apps/ota/src/lib/version.ts apps/ota/src/__tests__/version.test.ts apps/ota/src/lib/schema.ts +git commit -m "feat(ota): add release selection primitives" +``` + +### Task 3: Add KV keying and policy resolution + +**Files:** + +- Create: `apps/ota/src/lib/constants.ts` +- Create: `apps/ota/src/lib/kv.ts` +- Create: `apps/ota/src/lib/policy.ts` +- Create: `apps/ota/src/__tests__/policy.test.ts` + +- [ ] **Step 1: Write the failing store-policy tests** + +```ts +import { describe, expect, it } from "vitest" + +import { evaluateStorePolicy } from "../lib/policy" + +describe("evaluateStorePolicy", () => { + it("requires a store update when a store release is newer than the installed binary", () => { + const policy = evaluateStorePolicy( + { + releaseVersion: "0.4.3", + releaseKind: "store", + runtimeVersion: "0.4.3", + policy: { + storeRequired: true, + minSupportedBinaryVersion: "0.4.3", + message: "Please update from the store.", + }, + } as any, + { + installedBinaryVersion: "0.4.1", + }, + ) + + expect(policy.action).toBe("block") + expect(policy.targetVersion).toBe("0.4.3") + }) +}) +``` + +- [ ] **Step 2: Run the tests to verify failure** + +Run: `pnpm exec vitest run apps/ota/src/__tests__/policy.test.ts` + +Expected: FAIL because `policy.ts` has not been implemented. + +- [ ] **Step 3: Implement constants, KV key builders, and policy evaluation** + +```ts +export const KV_KEYS = { + release: (product: string, releaseVersion: string) => `release:${product}:${releaseVersion}`, + latest: (product: string, channel: string, runtimeVersion: string, platform: string) => + `latest:${product}:${channel}:${runtimeVersion}:${platform}`, + policy: (product: string, channel: string) => `policy:${product}:${channel}`, + githubEtag: "github:etag:releases", + syncLastSuccessAt: "sync:last-success-at", +} as const +``` + +```ts +import { KV_KEYS } from "./constants" + +export async function getLatestReleasePointer( + kv: KVNamespace, + input: { product: string; channel: string; runtimeVersion: string; platform: string }, +) { + return kv.get( + KV_KEYS.latest(input.product, input.channel, input.runtimeVersion, input.platform), + "json", + ) +} + +export async function putReleaseRecord( + kv: KVNamespace, + product: string, + releaseVersion: string, + value: unknown, +) { + await kv.put(KV_KEYS.release(product, releaseVersion), JSON.stringify(value)) +} +``` + +```ts +import { compareSemver } from "./version" + +export function evaluateStorePolicy( + latestStoreRelease: { + releaseVersion: string + releaseKind: "store" | "ota" + runtimeVersion: string + policy: { + storeRequired: boolean + minSupportedBinaryVersion: string + message: string | null + } + } | null, + input: { + installedBinaryVersion: string + }, +) { + if (!latestStoreRelease || latestStoreRelease.releaseKind !== "store") { + return { action: "none", targetVersion: null, message: null } + } + + if (compareSemver(latestStoreRelease.releaseVersion, input.installedBinaryVersion) <= 0) { + return { action: "none", targetVersion: null, message: null } + } + + return { + action: latestStoreRelease.policy.storeRequired ? "block" : "prompt", + targetVersion: latestStoreRelease.releaseVersion, + message: latestStoreRelease.policy.message, + } +} +``` + +- [ ] **Step 4: Run tests and typecheck** + +Run: + +```bash +pnpm exec vitest run apps/ota/src/__tests__/policy.test.ts +pnpm --filter @follow/ota typecheck +``` + +Expected: PASS for policy tests and no typecheck errors. + +- [ ] **Step 5: Commit** + +```bash +git add apps/ota/src/lib/constants.ts apps/ota/src/lib/kv.ts apps/ota/src/lib/policy.ts apps/ota/src/__tests__/policy.test.ts +git commit -m "feat(ota): add kv helpers and policy logic" +``` + +### Task 4: Implement GitHub release fetch and metadata validation + +**Files:** + +- Create: `apps/ota/src/lib/github.ts` +- Modify: `apps/ota/src/lib/schema.ts` +- Create: `apps/ota/src/__tests__/sync.test.ts` + +- [ ] **Step 1: Write the failing GitHub release fetch test** + +```ts +import { beforeEach, describe, expect, it, vi } from "vitest" + +import { listPublishedOtaReleases } from "../lib/github" + +describe("listPublishedOtaReleases", () => { + beforeEach(() => { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue( + new Response( + JSON.stringify([ + { + tag_name: "mobile/v0.4.2", + draft: false, + prerelease: false, + assets: [ + { + name: "ota-release.json", + browser_download_url: "https://example.com/ota-release.json", + }, + { name: "dist.tar.zst", browser_download_url: "https://example.com/dist.tar.zst" }, + ], + }, + ]), + { status: 200 }, + ), + ), + ) + }) + + it("returns releases that have both required assets", async () => { + const releases = await listPublishedOtaReleases({ + owner: "RSSNext", + repo: "Folo", + token: "token", + etag: null, + }) + + expect(releases[0]?.tag).toBe("mobile/v0.4.2") + expect(releases[0]?.metadataUrl).toContain("ota-release.json") + }) +}) +``` + +- [ ] **Step 2: Run the test to verify failure** + +Run: `pnpm exec vitest run apps/ota/src/__tests__/sync.test.ts` + +Expected: FAIL because `github.ts` does not exist. + +- [ ] **Step 3: Implement GitHub Releases filtering with conditional requests** + +```ts +export interface GitHubReleaseAsset { + name: string + browser_download_url: string +} + +export interface GitHubReleaseSummary { + tag: string + metadataUrl: string + archiveUrl: string +} + +export async function listPublishedOtaReleases(input: { + owner: string + repo: string + token: string + etag: string | null +}) { + const response = await fetch( + `https://api.github.com/repos/${input.owner}/${input.repo}/releases`, + { + headers: { + Accept: "application/vnd.github+json", + Authorization: `Bearer ${input.token}`, + "X-GitHub-Api-Version": "2022-11-28", + ...(input.etag ? { "If-None-Match": input.etag } : {}), + }, + }, + ) + + if (response.status === 304) return [] + if (!response.ok) throw new Error(`GitHub releases request failed with ${response.status}`) + + const releases = (await response.json()) as Array<{ + tag_name: string + draft: boolean + prerelease: boolean + assets: GitHubReleaseAsset[] + }> + + return releases + .filter((release) => !release.draft) + .map((release) => { + const metadata = release.assets.find((asset) => asset.name === "ota-release.json") + const archive = release.assets.find((asset) => asset.name === "dist.tar.zst") + + if (!metadata || !archive) return null + + return { + tag: release.tag_name, + metadataUrl: metadata.browser_download_url, + archiveUrl: archive.browser_download_url, + } + }) + .filter((value): value is GitHubReleaseSummary => value !== null) +} +``` + +Keep the release fetcher product-agnostic. Do not infer mobile or desktop from GitHub Releases alone; use the parsed `ota-release.json.product` field as the source of truth when indexing. + +- [ ] **Step 4: Run the test and confirm the GitHub layer works** + +Run: + +```bash +pnpm exec vitest run apps/ota/src/__tests__/sync.test.ts +pnpm --filter @follow/ota typecheck +``` + +Expected: PASS for the GitHub fetch test and no typecheck errors. + +- [ ] **Step 5: Commit** + +```bash +git add apps/ota/src/lib/github.ts apps/ota/src/__tests__/sync.test.ts +git commit -m "feat(ota): fetch OTA releases from GitHub" +``` + +### Task 5: Mirror release payloads into R2 and index them in KV + +**Files:** + +- Create: `apps/ota/src/lib/archive.ts` +- Create: `apps/ota/src/lib/r2.ts` +- Create: `apps/ota/src/lib/sync.ts` +- Modify: `apps/ota/src/__tests__/sync.test.ts` + +- [ ] **Step 1: Extend the sync tests to cover mirroring and latest pointers** + +```ts +it("stores mirrored release metadata and latest pointers only after a full sync", async () => { + const kvWrites: string[] = [] + const r2Writes: string[] = [] + + const kv = { + put: vi.fn(async (key: string) => { + kvWrites.push(key) + }), + get: vi.fn(async () => null), + } as unknown as KVNamespace + + const bucket = { + put: vi.fn(async (key: string) => { + r2Writes.push(key) + }), + } as unknown as R2Bucket + + await mirrorReleaseToStorage( + { + release: { + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + publishedAt: "2026-04-10T12:00:00Z", + git: { tag: "mobile/v0.4.2", commit: "abcdef1234567890" }, + policy: { storeRequired: false, minSupportedBinaryVersion: "0.4.1", message: null }, + platforms: { + ios: { + launchAsset: { + path: "bundles/ios-main.js", + sha256: "a".repeat(64), + contentType: "application/javascript", + }, + assets: [], + }, + }, + } as any, + files: [ + { + key: "mobile/production/0.4.1/0.4.2/ios/bundles/ios-main.js", + body: new Uint8Array([1, 2, 3]), + }, + ], + }, + { kv, bucket }, + ) + + expect(r2Writes).toContain("mobile/production/0.4.1/0.4.2/ios/bundles/ios-main.js") + expect(kvWrites.some((key) => key.includes("latest:mobile:production:0.4.1:ios"))).toBe(true) +}) +``` + +- [ ] **Step 2: Run the sync tests to verify failure** + +Run: `pnpm exec vitest run apps/ota/src/__tests__/sync.test.ts` + +Expected: FAIL because mirroring helpers do not exist. + +- [ ] **Step 3: Implement archive and sync orchestration** + +```ts +import { gunzipSync } from "node:zlib" + +export async function extractMirroredFiles(input: { + release: { + product: string + channel: string + runtimeVersion: string + releaseVersion: string + platforms: Record }> + } + archiveBuffer: ArrayBuffer +}) { + const basePrefix = `${input.release.product}/${input.release.channel}/${input.release.runtimeVersion}/${input.release.releaseVersion}` + const files: Array<{ key: string; body: Uint8Array }> = [] + + for (const [platform, payload] of Object.entries(input.release.platforms)) { + files.push({ + key: `${basePrefix}/${platform}/${payload.launchAsset.path}`, + body: new Uint8Array(gunzipSync(new Uint8Array(input.archiveBuffer))), + }) + + for (const asset of payload.assets) { + files.push({ + key: `${basePrefix}/${platform}/${asset.path}`, + body: new Uint8Array(), + }) + } + } + + return files +} +``` + +```ts +import { KV_KEYS } from "./constants" + +export async function mirrorReleaseToStorage( + input: { + release: any + files: Array<{ key: string; body: Uint8Array }> + }, + env: { + kv: KVNamespace + bucket: R2Bucket + }, +) { + for (const file of input.files) { + await env.bucket.put(file.key, file.body) + } + + await env.kv.put( + KV_KEYS.release(input.release.product, input.release.releaseVersion), + JSON.stringify(input.release), + ) + + for (const platform of Object.keys(input.release.platforms)) { + await env.kv.put( + KV_KEYS.latest( + input.release.product, + input.release.channel, + input.release.runtimeVersion, + platform, + ), + JSON.stringify({ releaseVersion: input.release.releaseVersion }), + ) + } +} +``` + +```ts +import { otaReleaseSchema } from "./schema" +import { listPublishedOtaReleases } from "./github" +import { extractMirroredFiles } from "./archive" +import { mirrorReleaseToStorage } from "./sync" +``` + +- [ ] **Step 4: Run the sync tests and confirm latest pointers are written after mirror success** + +Run: + +```bash +pnpm exec vitest run apps/ota/src/__tests__/sync.test.ts +pnpm --filter @follow/ota typecheck +``` + +Expected: PASS for sync tests and no typecheck errors. + +- [ ] **Step 5: Commit** + +```bash +git add apps/ota/src/lib/archive.ts apps/ota/src/lib/r2.ts apps/ota/src/lib/sync.ts apps/ota/src/__tests__/sync.test.ts +git commit -m "feat(ota): mirror release payloads into R2" +``` + +### Task 6: Implement `/manifest`, `/assets/*`, and `/policy` + +**Files:** + +- Create: `apps/ota/src/lib/manifest.ts` +- Create: `apps/ota/src/routes/manifest.ts` +- Create: `apps/ota/src/routes/assets.ts` +- Create: `apps/ota/src/routes/policy.ts` +- Modify: `apps/ota/src/index.ts` +- Create: `apps/ota/src/__tests__/manifest.test.ts` + +- [ ] **Step 1: Write failing route-level tests for the manifest** + +```ts +import { describe, expect, it } from "vitest" + +import { buildManifest } from "../lib/manifest" + +describe("buildManifest", () => { + it("rewrites launch asset and asset URLs to Worker-served asset routes", () => { + const manifest = buildManifest( + { + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + publishedAt: "2026-04-10T12:00:00Z", + git: { tag: "mobile/v0.4.2", commit: "abcdef1234567890" }, + policy: { storeRequired: false, minSupportedBinaryVersion: "0.4.1", message: null }, + platforms: { + ios: { + launchAsset: { + path: "bundles/ios-main.js", + sha256: "a".repeat(64), + contentType: "application/javascript", + }, + assets: [{ path: "assets/one.png", sha256: "b".repeat(64), contentType: "image/png" }], + }, + }, + } as any, + { + origin: "https://ota.folo.is", + platform: "ios", + }, + ) + + expect(manifest.launchAsset.url).toBe( + "https://ota.folo.is/assets/mobile/production/0.4.1/0.4.2/ios/bundles/ios-main.js", + ) + expect(manifest.assets[0]?.url).toBe( + "https://ota.folo.is/assets/mobile/production/0.4.1/0.4.2/ios/assets/one.png", + ) + }) +}) +``` + +- [ ] **Step 2: Run the test to verify failure** + +Run: `pnpm exec vitest run apps/ota/src/__tests__/manifest.test.ts` + +Expected: FAIL because `manifest.ts` does not exist. + +- [ ] **Step 3: Implement manifest generation and routes** + +```ts +export function buildManifest( + release: any, + input: { + origin: string + platform: string + }, +) { + const platformPayload = release.platforms[input.platform] + const basePath = `${release.product}/${release.channel}/${release.runtimeVersion}/${release.releaseVersion}/${input.platform}` + + return { + id: `${release.product}-${release.releaseVersion}-${input.platform}`, + createdAt: release.publishedAt, + runtimeVersion: release.runtimeVersion, + launchAsset: { + key: platformPayload.launchAsset.path, + contentType: platformPayload.launchAsset.contentType, + url: `${input.origin}/assets/${basePath}/${platformPayload.launchAsset.path}`, + }, + assets: platformPayload.assets.map((asset: any) => ({ + key: asset.path, + contentType: asset.contentType, + url: `${input.origin}/assets/${basePath}/${asset.path}`, + })), + metadata: { + channel: release.channel, + releaseVersion: release.releaseVersion, + }, + extra: { + product: release.product, + }, + } +} +``` + +```ts +import { Hono } from "hono" + +import type { Env } from "../env" +import { buildManifest } from "../lib/manifest" +import { getLatestReleasePointer } from "../lib/kv" + +export const manifestRoute = new Hono<{ Bindings: Env }>() + +manifestRoute.get("/manifest", async (c) => { + const platform = c.req.header("expo-platform") ?? "ios" + const runtimeVersion = c.req.header("expo-runtime-version") ?? "" + const channel = c.req.header("expo-channel-name") ?? "production" + const product = (c.req.query("product") ?? "mobile") as "mobile" | "desktop" + const pointer = await getLatestReleasePointer(c.env.OTA_KV, { + product, + channel, + runtimeVersion, + platform, + }) + + if (!pointer) return c.body(null, 204) + + const release = await c.env.OTA_KV.get(`release:${product}:${pointer.releaseVersion}`, "json") + if (!release) return c.body(null, 204) + + return c.json(buildManifest(release, { origin: new URL(c.req.url).origin, platform }), 200, { + "expo-protocol-version": "1", + "expo-sfv-version": "0", + "cache-control": "private, max-age=0", + "content-type": "application/expo+json", + }) +}) +``` + +```ts +export const policyRoute = new Hono<{ Bindings: Env }>() + +policyRoute.get("/policy", async (c) => { + const product = c.req.query("product") ?? "mobile" + const channel = c.req.query("channel") ?? "production" + const installedBinaryVersion = c.req.query("installedBinaryVersion") ?? "" + const latestStoreRelease = await c.env.OTA_KV.get(`policy:${product}:${channel}`, "json") + + return c.json(evaluateStorePolicy(latestStoreRelease as any, { installedBinaryVersion })) +}) +``` + +```ts +export const assetsRoute = new Hono<{ Bindings: Env }>() + +assetsRoute.get("/assets/*", async (c) => { + const key = c.req.path.replace(/^\/assets\//, "") + const object = await c.env.OTA_BUCKET.get(key) + if (!object) return c.text("Not found", 404) + + const headers = new Headers() + object.writeHttpMetadata(headers) + headers.set("cache-control", "public, max-age=31536000, immutable") + + return new Response(object.body, { headers }) +}) +``` + +- [ ] **Step 4: Wire routes into the Worker and run checks** + +Run: + +```bash +pnpm exec vitest run apps/ota/src/__tests__/manifest.test.ts apps/ota/src/__tests__/policy.test.ts +pnpm --filter @follow/ota typecheck +``` + +Expected: PASS for manifest and policy tests and no Worker type errors. + +- [ ] **Step 5: Commit** + +```bash +git add apps/ota/src/lib/manifest.ts apps/ota/src/routes apps/ota/src/index.ts apps/ota/src/__tests__/manifest.test.ts +git commit -m "feat(ota): serve manifests assets and policy" +``` + +### Task 7: Add internal sync and health routes plus scheduled execution + +**Files:** + +- Create: `apps/ota/src/routes/internal.ts` +- Modify: `apps/ota/src/index.ts` +- Modify: `apps/ota/src/lib/sync.ts` + +- [ ] **Step 1: Write a failing health-route test** + +```ts +import { describe, expect, it } from "vitest" + +import otaWorker from "../index" + +describe("internal health", () => { + it("returns sync status", async () => { + const response = await otaWorker.fetch( + new Request("https://ota.folo.is/internal/health"), + { + OTA_KV: { + get: async () => "2026-04-10T12:00:00Z", + }, + } as any, + {} as ExecutionContext, + ) + + const body = await response.json() + expect(body.ok).toBe(true) + expect(body.lastSuccessAt).toBe("2026-04-10T12:00:00Z") + }) +}) +``` + +- [ ] **Step 2: Run the test to verify failure** + +Run: `pnpm exec vitest run apps/ota/src/__tests__/sync.test.ts` + +Expected: FAIL because `/internal/health` and scheduled sync handling are incomplete. + +- [ ] **Step 3: Implement protected sync and health routes** + +```ts +import { Hono } from "hono" + +import type { Env } from "../env" +import { KV_KEYS } from "../lib/constants" +import { syncGitHubReleases } from "../lib/sync" + +export const internalRoute = new Hono<{ Bindings: Env }>() + +internalRoute.post("/internal/sync", async (c) => { + const headerName = c.env.OTA_SYNC_TOKEN_HEADER + const token = c.req.header(headerName) + + if (token !== c.env.OTA_SYNC_TOKEN) { + return c.json({ ok: false, message: "Unauthorized" }, 401) + } + + await syncGitHubReleases(c.env) + return c.json({ ok: true }) +}) + +internalRoute.get("/internal/health", async (c) => { + const lastSuccessAt = await c.env.OTA_KV.get(KV_KEYS.syncLastSuccessAt) + return c.json({ ok: true, lastSuccessAt }) +}) +``` + +```ts +export async function syncGitHubReleases(env: Env) { + const releases = await listPublishedOtaReleases({ + owner: env.GITHUB_OWNER, + repo: env.GITHUB_REPO, + token: env.GITHUB_TOKEN, + etag: await env.OTA_KV.get(KV_KEYS.githubEtag), + }) + + for (const releaseSummary of releases) { + // fetch metadata, validate, mirror payload, write latest pointers and policy + } + + await env.OTA_KV.put(KV_KEYS.syncLastSuccessAt, new Date().toISOString()) +} +``` + +```ts +export default { + fetch: app.fetch, + scheduled: async (_controller: ScheduledController, env: Env, ctx: ExecutionContext) => { + ctx.waitUntil(syncGitHubReleases(env)) + }, +} +``` + +- [ ] **Step 4: Run tests and typecheck** + +Run: + +```bash +pnpm exec vitest run apps/ota/src/__tests__/sync.test.ts +pnpm --filter @follow/ota typecheck +``` + +Expected: PASS for internal route coverage and no typecheck errors. + +- [ ] **Step 5: Commit** + +```bash +git add apps/ota/src/routes/internal.ts apps/ota/src/index.ts apps/ota/src/lib/sync.ts +git commit -m "feat(ota): add sync orchestration routes" +``` + +### Task 8: Enable mobile app config and background OTA checks + +**Files:** + +- Modify: `apps/mobile/app.config.ts` +- Modify: `apps/mobile/src/main.tsx` +- Create: `apps/mobile/src/modules/ota/types.ts` +- Create: `apps/mobile/src/modules/ota/store.ts` +- Create: `apps/mobile/src/modules/ota/provider.tsx` +- Create: `apps/mobile/src/modules/ota/__tests__/store.test.ts` + +- [ ] **Step 1: Write the failing OTA state test** + +```ts +import { describe, expect, it } from "vitest" + +import { reduceOtaState } from "../store" + +describe("reduceOtaState", () => { + it("marks an update as downloaded and ready on next launch", () => { + const state = reduceOtaState( + { + status: "idle", + pendingVersion: null, + }, + { + type: "downloaded", + version: "0.4.2", + }, + ) + + expect(state.status).toBe("ready") + expect(state.pendingVersion).toBe("0.4.2") + }) +}) +``` + +- [ ] **Step 2: Run the test to verify failure** + +Run: `pnpm exec vitest run apps/mobile/src/modules/ota/__tests__/store.test.ts` + +Expected: FAIL because the OTA module does not exist. + +- [ ] **Step 3: Enable Expo updates config and add a root provider** + +```ts +updates: { + url: "https://ota.folo.is/manifest", + requestHeaders: { + "expo-channel-name": process.env.PROFILE === "preview" ? "preview" : "production", + }, + codeSigningCertificate: "./code-signing/certificate.pem", + codeSigningMetadata: { + keyid: "main", + alg: "rsa-v1_5-sha256", + }, +}, +runtimeVersion: isDev ? "0.0.0-dev" : PKG.version, +``` + +```ts +export interface OtaState { + status: "idle" | "checking" | "downloading" | "ready" | "error" + pendingVersion: string | null + errorMessage: string | null +} + +export type OtaAction = + | { type: "checking" } + | { type: "downloading" } + | { type: "downloaded"; version: string } + | { type: "failed"; message: string } + +export function reduceOtaState(state: OtaState, action: OtaAction): OtaState { + switch (action.type) { + case "checking": + return { ...state, status: "checking", errorMessage: null } + case "downloading": + return { ...state, status: "downloading", errorMessage: null } + case "downloaded": + return { ...state, status: "ready", pendingVersion: action.version, errorMessage: null } + case "failed": + return { ...state, status: "error", errorMessage: action.message } + } +} +``` + +```tsx +import * as Updates from "expo-updates" +import { PropsWithChildren, useEffect, useReducer } from "react" + +import { reduceOtaState } from "./store" + +export const OtaProvider = ({ children }: PropsWithChildren) => { + const [state, dispatch] = useReducer(reduceOtaState, { + status: "idle", + pendingVersion: null, + errorMessage: null, + }) + + useEffect(() => { + if (__DEV__) return + + void (async () => { + dispatch({ type: "checking" }) + const result = await Updates.checkForUpdateAsync() + if (!result.isAvailable) return + + dispatch({ type: "downloading" }) + const update = await Updates.fetchUpdateAsync() + dispatch({ + type: "downloaded", + version: update.manifest?.metadata?.releaseVersion ?? "unknown", + }) + })().catch((error: Error) => { + dispatch({ type: "failed", message: error.message }) + }) + }, []) + + return children +} +``` + +```tsx + + + {/* existing tree */} + + +``` + +- [ ] **Step 4: Run tests and typecheck** + +Run: + +```bash +pnpm exec vitest run apps/mobile/src/modules/ota/__tests__/store.test.ts +pnpm --filter @follow/mobile typecheck +``` + +Expected: PASS for the reducer test and no mobile typecheck errors. + +- [ ] **Step 5: Commit** + +```bash +git add apps/mobile/app.config.ts apps/mobile/src/main.tsx apps/mobile/src/modules/ota +git commit -m "feat(mobile): enable OTA background updates" +``` + +### Task 9: Add `/policy` client and debug controls in mobile + +**Files:** + +- Create: `apps/mobile/src/modules/ota/client.ts` +- Create: `apps/mobile/src/modules/ota/__tests__/client.test.ts` +- Modify: `apps/mobile/src/modules/debug/index.tsx` +- Modify: `apps/mobile/src/modules/ota/provider.tsx` + +- [ ] **Step 1: Write the failing policy-client test** + +```ts +import { beforeEach, describe, expect, it, vi } from "vitest" + +import { fetchStorePolicy } from "../client" + +describe("fetchStorePolicy", () => { + beforeEach(() => { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ action: "block", targetVersion: "0.4.3", message: "Update required" }), + { + status: 200, + headers: { "content-type": "application/json" }, + }, + ), + ), + ) + }) + + it("returns the parsed policy response", async () => { + const result = await fetchStorePolicy({ + baseUrl: "https://ota.folo.is", + product: "mobile", + channel: "production", + installedBinaryVersion: "0.4.1", + }) + + expect(result.action).toBe("block") + expect(result.targetVersion).toBe("0.4.3") + }) +}) +``` + +- [ ] **Step 2: Run the policy-client test to verify failure** + +Run: `pnpm exec vitest run apps/mobile/src/modules/ota/__tests__/client.test.ts` + +Expected: FAIL because the policy client does not exist. + +- [ ] **Step 3: Implement the client and debug actions** + +```ts +export async function fetchStorePolicy(input: { + baseUrl: string + product: "mobile" + channel: string + installedBinaryVersion: string +}) { + const url = new URL("/policy", input.baseUrl) + url.searchParams.set("product", input.product) + url.searchParams.set("channel", input.channel) + url.searchParams.set("installedBinaryVersion", input.installedBinaryVersion) + + const response = await fetch(url.toString()) + if (!response.ok) throw new Error(`Policy request failed with ${response.status}`) + return response.json() as Promise<{ + action: "none" | "prompt" | "block" + targetVersion: string | null + message: string | null + }> +} +``` + +```tsx + { + void Updates.checkForUpdateAsync() + }} +> + Check OTA Update + + { + void Updates.reloadAsync() + }} +> + Reload OTA Update + +``` + +```tsx +const policy = await fetchStorePolicy({ + baseUrl: "https://ota.folo.is", + product: "mobile", + channel: __DEV__ ? "preview" : "production", + installedBinaryVersion: Application.nativeApplicationVersion ?? "0.0.0", +}) +``` + +- [ ] **Step 4: Run tests and typecheck** + +Run: + +```bash +pnpm exec vitest run apps/mobile/src/modules/ota/__tests__/client.test.ts apps/mobile/src/modules/ota/__tests__/store.test.ts +pnpm --filter @follow/mobile typecheck +``` + +Expected: PASS for OTA module tests and no typecheck errors. + +- [ ] **Step 5: Commit** + +```bash +git add apps/mobile/src/modules/ota apps/mobile/src/modules/debug/index.tsx +git commit -m "feat(mobile): add ota policy client and debug controls" +``` + +### Task 10: Replace the old export script with release-asset generation + +**Files:** + +- Modify: `apps/mobile/package.json` +- Modify: `apps/mobile/scripts/expo-update.ts` +- Create: `.github/scripts/build-ota-release.mjs` + +- [ ] **Step 1: Write the failing release-builder test** + +```ts +import { describe, expect, it } from "vitest" + +import { buildOtaMetadata } from "../../../.github/scripts/build-ota-release.mjs" + +describe("buildOtaMetadata", () => { + it("builds plain x.y.z release metadata with a binary-compatible runtime version", () => { + const metadata = buildOtaMetadata({ + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + gitTag: "mobile/v0.4.2", + gitCommit: "abcdef1234567890", + }) + + expect(metadata.releaseVersion).toBe("0.4.2") + expect(metadata.runtimeVersion).toBe("0.4.1") + }) +}) +``` + +- [ ] **Step 2: Run the test to verify failure** + +Run: `pnpm exec vitest run .github/scripts/build-ota-release.test.ts` + +Expected: FAIL because the release-builder utility does not exist. + +- [ ] **Step 3: Implement OTA release asset generation** + +```json +{ + "scripts": { + "update": "tsx .github/scripts/build-ota-release.mjs", + "update:export": "expo export -p ios -p android", + "update:bundle": "tsx .github/scripts/build-ota-release.mjs" + } +} +``` + +```js +import fs from "node:fs" +import path from "pathe" + +export function buildOtaMetadata(input) { + return { + schemaVersion: 1, + product: input.product, + channel: input.channel, + releaseVersion: input.releaseVersion, + releaseKind: input.releaseKind, + runtimeVersion: input.runtimeVersion, + publishedAt: new Date().toISOString(), + git: { + tag: input.gitTag, + commit: input.gitCommit, + }, + policy: { + storeRequired: input.releaseKind === "store", + minSupportedBinaryVersion: input.runtimeVersion, + message: + input.releaseKind === "store" + ? "This update requires installing the latest app version." + : null, + }, + platforms: { + ios: { + launchAsset: { + path: "bundles/ios-main.js", + sha256: "REPLACE_AFTER_HASH", + contentType: "application/javascript", + }, + assets: [], + }, + android: { + launchAsset: { + path: "bundles/android-main.js", + sha256: "REPLACE_AFTER_HASH", + contentType: "application/javascript", + }, + assets: [], + }, + }, + } +} + +if (import.meta.url === `file://${process.argv[1]}`) { + const outputDir = path.resolve(process.cwd(), "apps/mobile/dist") + if (!fs.existsSync(outputDir)) throw new Error("Missing apps/mobile/dist. Run expo export first.") +} +``` + +- [ ] **Step 4: Run tests and verify the script works against exported output** + +Run: + +```bash +pnpm --filter @follow/mobile update:export +pnpm --filter @follow/mobile update:bundle +pnpm exec vitest run .github/scripts/build-ota-release.test.ts +``` + +Expected: + +- `apps/mobile/dist` exists after export +- builder script emits `ota-release.json` and `dist.tar.zst` +- test PASS + +- [ ] **Step 5: Commit** + +```bash +git add apps/mobile/package.json apps/mobile/scripts/expo-update.ts .github/scripts/build-ota-release.mjs +git commit -m "feat(ota): generate release assets from mobile export" +``` + +### Task 11: Publish OTA releases from GitHub Actions and trigger sync + +**Files:** + +- Create: `.github/workflows/publish-ota.yml` +- Create: `.github/scripts/trigger-ota-sync.mjs` +- Modify: `.github/workflows/tag.yml` + +- [ ] **Step 1: Write the failing sync-trigger test** + +```ts +import { beforeEach, describe, expect, it, vi } from "vitest" + +import { triggerOtaSync } from "../scripts/trigger-ota-sync.mjs" + +describe("triggerOtaSync", () => { + beforeEach(() => { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue(new Response(JSON.stringify({ ok: true }), { status: 200 })), + ) + }) + + it("posts to the protected sync endpoint", async () => { + await triggerOtaSync({ + baseUrl: "https://ota.folo.is", + token: "secret", + headerName: "x-ota-sync-token", + }) + + expect(fetch).toHaveBeenCalledWith( + "https://ota.folo.is/internal/sync", + expect.objectContaining({ + method: "POST", + headers: expect.objectContaining({ + "x-ota-sync-token": "secret", + }), + }), + ) + }) +}) +``` + +- [ ] **Step 2: Run the test to verify failure** + +Run: `pnpm exec vitest run .github/scripts/trigger-ota-sync.test.ts` + +Expected: FAIL because the sync trigger helper does not exist. + +- [ ] **Step 3: Implement the workflow and sync trigger** + +```js +export async function triggerOtaSync(input) { + const response = await fetch(`${input.baseUrl}/internal/sync`, { + method: "POST", + headers: { + [input.headerName]: input.token, + }, + }) + + if (!response.ok) { + throw new Error(`OTA sync failed with ${response.status}`) + } +} +``` + +```yaml +name: Publish OTA + +on: + workflow_dispatch: + inputs: + release_version: + description: Release version such as 0.4.2 + required: true + release_kind: + description: ota or store + required: true + runtime_version: + description: Binary-compatible runtime version + required: true + channel: + description: production or preview + required: true + +jobs: + publish: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: pnpm/action-setup@v5 + - uses: actions/setup-node@v6 + with: + node-version: 22 + cache: pnpm + - run: pnpm install + - run: pnpm --filter @follow/mobile update:export + - run: pnpm --filter @follow/mobile update:bundle + - uses: softprops/action-gh-release@v2 + with: + name: Mobile v${{ inputs.release_version }} + tag_name: mobile/v${{ inputs.release_version }} + files: | + apps/mobile/dist/ota-release.json + apps/mobile/dist.tar.zst + - run: node .github/scripts/trigger-ota-sync.mjs + env: + OTA_BASE_URL: ${{ secrets.OTA_BASE_URL }} + OTA_SYNC_TOKEN: ${{ secrets.OTA_SYNC_TOKEN }} + OTA_SYNC_TOKEN_HEADER: x-ota-sync-token +``` + +- [ ] **Step 4: Run workflow syntax and local script tests** + +Run: + +```bash +pnpm exec vitest run .github/scripts/trigger-ota-sync.test.ts +pnpm exec prettier --check .github/workflows/publish-ota.yml +``` + +Expected: PASS for the sync-trigger test and no formatting issues in the workflow file. + +- [ ] **Step 5: Commit** + +```bash +git add .github/workflows/publish-ota.yml .github/scripts/trigger-ota-sync.mjs .github/workflows/tag.yml +git commit -m "ci(ota): publish releases and trigger sync" +``` + +### Task 12: Verify end-to-end behavior and document rollback operations + +**Files:** + +- Modify: `docs/superpowers/specs/2026-04-10-ota-design.md` +- Create: `apps/ota/README.md` + +- [ ] **Step 1: Write the operational checklist** + +```md +# OTA Service Operations + +## Release checklist + +- Publish GitHub Release with `ota-release.json` and `dist.tar.zst` +- Trigger `/internal/sync` +- Verify `/internal/health` +- Request `/manifest` with production headers +- Download the returned launch asset URL + +## Rollback checklist + +- Move latest KV pointer back to the previous release version +- Verify `/manifest` now resolves to the older release +- Confirm the new release remains frozen until manually re-enabled +``` + +- [ ] **Step 2: Run the verification commands** + +Run: + +```bash +pnpm --filter @follow/ota test +pnpm --filter @follow/ota typecheck +pnpm --filter @follow/mobile typecheck +pnpm run format:check +``` + +Expected: + +- all OTA Worker tests PASS +- mobile typecheck PASS +- formatting check PASS + +- [ ] **Step 3: Add operator documentation** + +```md +## Manual verification commands + +curl -H "expo-platform: ios" \ + -H "expo-runtime-version: 0.4.1" \ + -H "expo-channel-name: production" \ + https://ota.folo.is/manifest + +curl "https://ota.folo.is/policy?product=mobile&channel=production&installedBinaryVersion=0.4.1" +``` + +- [ ] **Step 4: Commit** + +```bash +git add apps/ota/README.md docs/superpowers/specs/2026-04-10-ota-design.md +git commit -m "docs(ota): add rollout and rollback runbook" +``` + +## Self-Review + +### Spec coverage + +- `apps/ota` Worker scaffolding: Task 1 +- GitHub Releases sync and metadata validation: Tasks 4, 5, 7 +- Cloudflare KV and R2 responsibilities: Tasks 3, 5, 6, 7 +- `/manifest`, `/assets/*`, and `/policy`: Task 6 +- Mobile app integration: Tasks 8 and 9 +- GitHub Actions OTA publish flow: Tasks 10 and 11 +- Rollback and verification: Task 12 + +### Placeholder scan + +- No `TODO`, `TBD`, or deferred implementation markers are allowed in the code created from this plan. +- Replace `REPLACE_WITH_PROD_KV_ID`, `REPLACE_WITH_DEV_KV_ID`, and runtime secrets during environment setup before deployment. + +### Type consistency + +- Keep `releaseVersion`, `releaseKind`, `runtimeVersion`, and `policy.storeRequired` names identical across metadata schema, sync logic, policy logic, and mobile client parsing. +- Keep route names exactly `/manifest`, `/assets/*`, `/policy`, `/internal/sync`, and `/internal/health`. + +## Final Verification Sequence + +Run: + +```bash +pnpm --filter @follow/ota test +pnpm --filter @follow/ota typecheck +pnpm --filter @follow/mobile test -- --runInBand +pnpm --filter @follow/mobile typecheck +pnpm run lint:fix +pnpm run test +``` + +Expected: + +- all OTA worker tests pass +- mobile OTA module tests pass +- repository lint and test suite complete without regressions diff --git a/docs/superpowers/specs/2026-04-10-ota-design.md b/docs/superpowers/specs/2026-04-10-ota-design.md new file mode 100644 index 000000000..fa5ad8465 --- /dev/null +++ b/docs/superpowers/specs/2026-04-10-ota-design.md @@ -0,0 +1,496 @@ +# OTA Service Design + +## Summary + +Build a standalone OTA service in `apps/ota` that serves mobile updates through Expo Updates with a custom backend hosted on Cloudflare Workers. + +GitHub Releases is the publishing source of truth. Cloudflare is the delivery layer. + +The service must: + +- support Expo mobile OTA without Expo paid cloud services +- allow future desktop update logic to live in the same service +- deliver JavaScript and static asset updates only +- preserve a simple release version line using plain `x.y.z` +- support both OTA releases and store-required releases + +## Goals + +- Keep release management simple by using a single public version line such as `0.4.1`, `0.4.2`, `0.4.3` +- Avoid suffix-based versioning such as `+ota.1` or `-ota.1` +- Use GitHub Releases to declare what is published +- Use Cloudflare R2 and Workers for stable update delivery +- Enforce native compatibility through `runtimeVersion` +- Allow per-release policy: some releases are OTA, some require full store update +- Integrate with the existing monorepo and current Cloudflare deployment patterns + +## Non-Goals + +- Shipping native code through OTA +- Replacing App Store or Play Store distribution for native changes +- Building a full release dashboard in the first version +- Supporting advanced staged rollouts in the first version + +## Key Decisions + +### 1. Service Placement + +Create a standalone service in `apps/ota`. + +This service name is intentionally product-agnostic so future desktop update logic can live in the same application. + +### 2. Infrastructure Model + +Use: + +- Cloudflare Worker for routing, policy evaluation, manifest generation, and sync orchestration +- Cloudflare R2 for storing delivered bundles and assets +- Cloudflare KV for lightweight release index, latest pointers, ETag cache, and sync state +- Cloudflare Cron Triggers for periodic GitHub Releases sync + +Do not use D1 in the first version. KV is sufficient for the initial read-heavy latest-release lookup model. + +### 3. Publishing Source of Truth + +GitHub Releases is the publishing source of truth. + +The repository may contain releases for multiple products such as mobile and desktop. The OTA service must distinguish them by the `product` field in `ota-release.json`, and Git tags should remain product-scoped. + +Each release must upload: + +- `ota-release.json` +- `dist.tar.zst` + +`ota-release.json` is the only machine-readable metadata file trusted by the OTA service. + +`dist.tar.zst` is the exported update payload archive that will be mirrored into R2. + +### 4. Delivery Source + +Clients must download bundles and assets from Cloudflare R2 through Worker-controlled URLs, not directly from GitHub assets. + +GitHub remains the publication source. Cloudflare becomes the delivery source. + +### 5. Version Strategy + +Keep public versions as plain `x.y.z` only. + +Examples: + +- `0.4.1` store release +- `0.4.2` OTA release +- `0.4.3` store release +- `0.4.4` OTA release + +Do not introduce OTA suffixes or extra numbering. + +This design separates: + +- `releaseVersion`: the version published to GitHub Releases, always plain `x.y.z` +- `releaseKind`: `store` or `ota` +- `runtimeVersion`: the native compatibility boundary used by Expo Updates + +Each `releaseVersion` is unique and maps to exactly one `releaseKind`. + +Git tags remain product-scoped even though `releaseVersion` stays plain `x.y.z`. + +Examples: + +- `mobile/v0.4.2` +- `desktop/v1.3.0` + +Rule: + +- `releaseVersion` increases on every release +- `runtimeVersion` changes only when a new store binary is shipped +- OTA releases keep the current binary-compatible `runtimeVersion` + +Example: + +- release `0.4.1`, `releaseKind=store`, `runtimeVersion=0.4.1` +- release `0.4.2`, `releaseKind=ota`, `runtimeVersion=0.4.1` +- release `0.4.3`, `releaseKind=store`, `runtimeVersion=0.4.3` +- release `0.4.4`, `releaseKind=ota`, `runtimeVersion=0.4.3` + +This allows a `0.4.1` installed binary to receive OTA `0.4.2` while preserving strict native compatibility. + +## Release Metadata + +Each GitHub Release must include an `ota-release.json` file with a schema similar to: + +```json +{ + "schemaVersion": 1, + "product": "mobile", + "channel": "production", + "releaseVersion": "0.4.2", + "releaseKind": "ota", + "runtimeVersion": "0.4.1", + "publishedAt": "2026-04-10T12:00:00Z", + "git": { + "tag": "mobile/v0.4.2", + "commit": "abcdef123456" + }, + "policy": { + "storeRequired": false, + "minSupportedBinaryVersion": "0.4.1", + "message": null + }, + "platforms": { + "ios": { + "launchAsset": { + "path": "bundles/ios-main.js", + "sha256": "...", + "contentType": "application/javascript" + }, + "assets": [ + { + "path": "assets/xxx.png", + "sha256": "...", + "contentType": "image/png" + } + ] + }, + "android": { + "launchAsset": { + "path": "bundles/android-main.js", + "sha256": "...", + "contentType": "application/javascript" + }, + "assets": [] + } + } +} +``` + +Required semantics: + +- `product` supports future values such as `desktop` +- `channel` supports `production`, `preview`, and future environments +- `releaseKind=ota` means `/manifest` may serve this release +- `releaseKind=store` means `/manifest` must not serve it as an OTA payload +- `runtimeVersion` is the Expo Updates compatibility key + +## Client Update Decision Model + +### OTA manifest lookup + +The client sends an Expo Updates request to the custom server with at least: + +- platform +- runtime version +- channel + +The Worker selects a release using: + +- exact `product` match +- exact `channel` match +- exact `runtimeVersion` match +- exact `platform` availability +- `releaseKind=ota` +- highest compatible `releaseVersion` using semantic version ordering + +If no compatible OTA release exists, the service returns no update. + +### Store update policy lookup + +The mobile app also calls a separate `/policy` endpoint. + +This endpoint determines whether the current installed binary must update through the store. This logic is independent from Expo Updates manifest resolution. + +The `/policy` response should support states such as: + +- no action +- soft prompt +- blocking required store update + +This is needed because Expo Updates only solves OTA delivery, not store-update enforcement UX. + +## Cloudflare Responsibilities + +### Worker + +`apps/ota` Worker responsibilities: + +- serve Expo Updates manifest responses +- serve R2-backed assets +- expose update policy responses +- sync GitHub Releases into internal index and R2 +- expose minimal internal health and sync endpoints + +### KV + +KV stores: + +- parsed release records +- latest compatible release pointers +- sync status +- cached GitHub ETag values + +Suggested keys: + +- `release::` +- `latest::::` +- `policy::` +- `github:etag:releases` +- `sync:last-success-at` + +### R2 + +R2 stores exported update payloads after sync from GitHub. + +Suggested object layout: + +```text +/////bundles/... +/////assets/... +``` + +Example: + +```text +mobile/production/0.4.1/0.4.2/ios/bundles/ios-main.js +mobile/production/0.4.1/0.4.2/ios/assets/asset-1.png +``` + +### Cron + +Use Cron to poll GitHub Releases on a short interval, for example every 5 minutes. + +Also expose a manual sync endpoint so CI can trigger immediate refresh after publishing a release. + +## Worker Routes + +Initial route set: + +- `GET /manifest` +- `GET /assets/*` +- `GET /policy` +- `POST /internal/sync` +- `GET /internal/health` + +### `GET /manifest` + +Returns an Expo Updates manifest for the latest compatible OTA release. + +This route must: + +- read client headers +- require `expo-platform` +- require `expo-runtime-version` +- default `expo-channel-name` to `production` +- default `product` to `mobile` +- find the latest matching OTA release from KV +- generate manifest JSON +- rewrite asset URLs to Worker-served or R2-backed URLs +- attach required Expo protocol headers +- return `204` when no compatible release is available or when persisted data fails validation + +### `GET /assets/*` + +Streams bundle and asset files from R2. + +This route should set strong cache headers and content type based on stored metadata. + +### `GET /policy` + +Returns release policy for the installed app version, channel, and product. + +This route powers store-required update UX and future release notices. + +The verified v1 route shape: + +- requires `installedBinaryVersion` +- defaults `channel` to `production` +- defaults `product` to `mobile` +- reads the latest store release body from `policy::` + +### `POST /internal/sync` + +Triggers a GitHub Releases sync. + +This endpoint should be protected by a secret token header. + +### `GET /internal/health` + +Returns diagnostic information for sync health, including `lastSuccessAt`. + +## GitHub Release Sync Flow + +1. Cron or CI calls sync +2. Worker requests GitHub Releases API with conditional headers when possible +3. Worker filters releases that include both `ota-release.json` and `dist.tar.zst` +4. Worker parses and validates `ota-release.json` +5. Worker uploads extracted payload files into R2 if not already mirrored +6. Worker stores parsed release metadata in KV +7. Worker updates latest pointers for compatible OTA releases +8. Worker updates policy records for store-required releases + +The sync process must not assume that all releases belong to mobile. Index and serve releases under the metadata-declared `product`. + +## Mobile Build and Publish Flow + +### Release publishing + +Keep the current release version line simple and monotonic. + +For each release: + +1. choose next `x.y.z` +2. decide whether the release is `store` or `ota` +3. generate exported payload for mobile +4. publish GitHub Release `mobile/vX.Y.Z` +5. upload `ota-release.json` and `dist.tar.zst` +6. trigger OTA sync + +The same `x.y.z` version must not be published once as `store` and again as `ota`. + +### OTA export + +Use Expo CLI export from `apps/mobile`. + +The export step generates JavaScript bundles and static assets from the existing mobile entrypoint. + +The archive content is mirrored to R2. The metadata file declares which release is OTA-compatible and which runtime it targets. + +## Mobile App Integration + +### App config + +In `apps/mobile/app.config.ts`: + +- enable `updates.url` to point to the OTA Worker +- keep code signing enabled +- keep `runtimeVersion` explicit + +`runtimeVersion` should remain tied to the currently installed compatible binary version, not to every OTA release. + +### Runtime behavior + +Add a top-level OTA provider in the mobile app root. + +The provider should: + +- check for updates after launch in the background +- download updates silently +- apply them on next launch by default +- expose debug actions for manual check and immediate reload in non-production builds + +The first version should avoid forced reload immediately on launch. + +### Store policy behavior + +At startup, the app should also call `/policy`. + +For `store-required` responses, the app decides whether to: + +- show a non-blocking prompt +- show a strong prompt +- block further usage until the store update is installed + +The first version can support soft prompt and blocking prompt only. + +## Rollback Strategy + +### Verified v1 rollback + +Move the affected `latest::::` KV pointers back to the previous compatible OTA release. + +If the incident is caused by a bad store release policy, overwrite `policy::` with the previous good store release record. + +### Verified v1 limitation + +GitHub Releases remains the source of truth, and sync always promotes the highest compatible `releaseVersion`. + +This means a manual KV rollback is temporary unless operators also remove or invalidate the bad GitHub Release assets, or publish a newer corrective release on the same runtime line before the next sync. + +Hard freeze and disable flags are not implemented in the verified v1 Worker. + +## Error Handling + +The service must handle: + +- malformed or missing `ota-release.json` +- missing payload archive +- R2 sync failure +- GitHub API rate limiting +- stale cached release metadata +- unsupported platform or runtime requests + +Behavior rules: + +- never serve partially mirrored releases +- only expose a release after metadata and payload sync both succeed +- if sync fails, keep serving the previous latest compatible release +- prefer stale-successful metadata over broken fresh metadata + +## Security + +- Sign OTA manifests using Expo Updates code signing +- Keep the signing private key outside the repository +- Keep only the public certificate in the repo +- Protect internal sync endpoints with a shared secret +- Validate uploaded metadata schema strictly before indexing it + +## Testing Strategy + +### Unit tests + +- metadata schema validation +- release selection logic +- policy evaluation logic +- manifest generation logic + +### Integration tests + +- sync a mocked GitHub Release into KV and R2 +- request `/manifest` for different channel and runtime combinations +- request `/policy` for OTA and store-required releases + +### End-to-end validation + +- publish a preview OTA release +- verify iOS preview binary downloads the update +- verify Android preview binary downloads the update +- verify store-required policy blocks or prompts correctly + +## Initial Implementation Scope + +Phase 1: + +- `apps/ota` Worker +- R2 + KV bindings +- GitHub Release sync +- `/manifest`, `/assets/*`, `/policy` +- mobile app config integration +- background OTA check +- basic debug actions +- rollback by KV pointer edit, with source-of-truth correction required before the next sync + +Phase 2: + +- better admin controls +- staged rollout support +- richer policy targeting +- hard freeze and disable controls +- desktop integration + +## Open Constraints to Preserve + +- Conversation can be in Chinese, but the engineering artifact remains English +- No Expo paid cloud update service +- No suffix-based release versioning +- GitHub Release versions remain plain `x.y.z` +- OTA and store releases share the same version line +- Some releases may be OTA while others may require store update +- Future desktop support must fit the same service + +## Recommended Next Step + +After this design is approved, write an implementation plan for: + +- `apps/ota` project scaffolding +- Worker data model and sync logic +- mobile app config and provider integration +- GitHub Actions OTA publish workflow +- verification and rollback operations diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f82e57ceb..b6208f29d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -188,7 +188,7 @@ importers: dependencies: '@follow-app/client-sdk': specifier: 0.3.95 - version: 0.3.95(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) + version: 0.3.95(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) commander: specifier: 14.0.1 version: 14.0.1 @@ -297,7 +297,7 @@ importers: version: 7.1.2(postcss@8.5.6) drizzle-orm: specifier: 0.45.1 - version: 0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0) + version: 0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0) electron: specifier: 38.3.0 version: 38.3.0 @@ -381,7 +381,7 @@ importers: version: 4.3.0 '@follow-app/client-sdk': specifier: 0.3.95 - version: 0.3.95(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) + version: 0.3.95(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) '@follow-app/readability': specifier: workspace:* version: link:../../../../packages/readability @@ -487,7 +487,7 @@ importers: version: 3.0.2(electron@38.3.0) '@follow-app/client-sdk': specifier: 0.3.95 - version: 0.3.95(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) + version: 0.3.95(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) '@follow/database': specifier: workspace:* version: link:../../../../packages/internal/database @@ -806,7 +806,7 @@ importers: version: link:../../../../packages/internal/utils '@folo-services/ai-tools': specifier: 'catalog:' - version: 0.2.66(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(pg@8.18.0) + version: 0.2.66(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(pg@8.18.0) '@types/node': specifier: 25.2.3 version: 25.2.3 @@ -960,7 +960,7 @@ importers: devDependencies: '@cloudflare/vite-plugin': specifier: 1.25.5 - version: 1.25.5(bufferutil@4.1.0)(vite@7.3.1(@types/node@24.9.1)(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))(workerd@1.20260302.0)(wrangler@4.68.1(bufferutil@4.1.0)) + version: 1.25.5(bufferutil@4.1.0)(vite@7.3.1(@types/node@24.9.1)(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))(workerd@1.20260302.0)(wrangler@4.68.1(@cloudflare/workers-types@4.20260411.1)(bufferutil@4.1.0)) '@egoist/tailwindcss-icons': specifier: 1.9.0 version: 1.9.0(tailwindcss@4.1.16) @@ -1053,13 +1053,13 @@ importers: version: 7.3.1(@types/node@24.9.1)(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2) wrangler: specifier: 4.68.1 - version: 4.68.1(bufferutil@4.1.0) + version: 4.68.1(@cloudflare/workers-types@4.20260411.1)(bufferutil@4.1.0) apps/mobile: dependencies: '@better-auth/expo': specifier: 1.5.5 - version: 1.5.5(030e766e590ffb3d7c1b38e4a0e64129) + version: 1.5.5(b4280106e937db3b8687f2eb2012388c) '@expo/metro-runtime': specifier: 55.0.9 version: 55.0.9(@expo/dom-webview@55.0.5)(expo@55.0.13)(react-dom@19.2.0(react@19.2.0))(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0) @@ -1068,7 +1068,7 @@ importers: version: 4.1.1(@types/react@19.2.14)(react@19.2.0) '@follow-app/client-sdk': specifier: 0.3.95 - version: 0.3.95(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) + version: 0.3.95(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) '@follow/components': specifier: workspace:* version: link:../../packages/internal/components @@ -1146,7 +1146,7 @@ importers: version: 1.5.6 better-auth: specifier: 1.5.5 - version: 1.5.5(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) + version: 1.5.5(@cloudflare/workers-types@4.20260411.1)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) camelcase-keys: specifier: 10.0.2 version: 10.0.2 @@ -1442,6 +1442,40 @@ importers: apps/mobile/web-app: {} + apps/ota: + dependencies: + fzstd: + specifier: 0.1.1 + version: 0.1.1 + hono: + specifier: 4.12.1 + version: 4.12.1 + ofetch: + specifier: 1.5.1 + version: 1.5.1 + tar-stream: + specifier: 2.2.0 + version: 2.2.0 + zod: + specifier: 3.25.76 + version: 3.25.76 + devDependencies: + '@cloudflare/workers-types': + specifier: ^4.20260405.0 + version: 4.20260411.1 + '@types/tar-stream': + specifier: 3.1.4 + version: 3.1.4 + typescript: + specifier: 'catalog:' + version: 5.9.3 + vitest: + specifier: 3.2.4 + version: 3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2) + wrangler: + specifier: 4.67.0 + version: 4.67.0(@cloudflare/workers-types@4.20260411.1)(bufferutil@4.1.0) + apps/ssr: dependencies: '@fastify/middie': @@ -1452,7 +1486,7 @@ importers: version: 6.2.1 '@follow-app/client-sdk': specifier: 0.3.95 - version: 0.3.95(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) + version: 0.3.95(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) '@follow/tracker': specifier: workspace:* version: link:../../packages/internal/tracker @@ -1636,7 +1670,7 @@ importers: version: 0.4.1 wrangler: specifier: 4.67.0 - version: 4.67.0(bufferutil@4.1.0) + version: 4.67.0(@cloudflare/workers-types@4.20260411.1)(bufferutil@4.1.0) packages/configs: dependencies: @@ -1956,7 +1990,7 @@ importers: dependencies: '@follow-app/client-sdk': specifier: 0.3.95 - version: 0.3.95(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) + version: 0.3.95(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) '@follow/configs': specifier: workspace:* version: link:../../configs @@ -1968,7 +2002,7 @@ importers: dependencies: '@follow-app/client-sdk': specifier: 0.3.95 - version: 0.3.95(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) + version: 0.3.95(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) '@follow/constants': specifier: workspace:* version: link:../constants @@ -1983,13 +2017,13 @@ importers: version: 6.0.85(zod@4.3.6) drizzle-orm: specifier: 0.45.1 - version: 0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0) + version: 0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0) expo-sqlite: specifier: 55.0.15 version: 55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0) sqlocal: specifier: npm:@hyoban/sqlocal@0.14.1-fork.4 - version: '@hyoban/sqlocal@0.14.1-fork.4(bufferutil@4.1.0)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(kysely@0.28.12)' + version: '@hyoban/sqlocal@0.14.1-fork.4(bufferutil@4.1.0)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(kysely@0.28.12)' wa-sqlite: specifier: git+https://github.com/rhashimoto/wa-sqlite.git#v1.0.8 version: https://codeload.github.com/rhashimoto/wa-sqlite/tar.gz/03c00ed67cd934bd664ae310234bba317928f851 @@ -2040,7 +2074,7 @@ importers: dependencies: '@follow-app/client-sdk': specifier: 0.3.95 - version: 0.3.95(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) + version: 0.3.95(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) '@follow/constants': specifier: workspace:* version: link:../constants @@ -2062,7 +2096,7 @@ importers: dependencies: '@better-auth/stripe': specifier: 1.5.5 - version: 1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(better-auth@1.5.5(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)))(better-call@1.3.2(zod@3.25.76))(stripe@20.3.1(@types/node@25.2.3)) + version: 1.5.5(8587db83c79799d980d8a0bba87b75b2) '@electron-toolkit/preload': specifier: 3.0.2 version: 3.0.2(electron@38.3.0) @@ -2071,10 +2105,10 @@ importers: version: 2.0.0(@types/node@25.2.3) '@follow-app/client-sdk': specifier: 0.3.95 - version: 0.3.95(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) + version: 0.3.95(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) '@folo-services/drizzle': specifier: 0.1.47 - version: 0.1.47(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12) + version: 0.1.47(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12) '@t3-oss/env-core': specifier: 0.13.10 version: 0.13.10(typescript@5.9.3)(zod@3.25.76) @@ -2083,10 +2117,10 @@ importers: version: 6.0.85(zod@3.25.76) better-auth: specifier: 1.5.5 - version: 1.5.5(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) + version: 1.5.5(@cloudflare/workers-types@4.20260411.1)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) drizzle-orm: specifier: 0.45.1 - version: 0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0) + version: 0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0) sonner: specifier: 2.0.7 version: 2.0.7(react-dom@19.2.0(react@19.2.0))(react@19.2.0) @@ -2101,7 +2135,7 @@ importers: dependencies: '@follow-app/client-sdk': specifier: 0.3.95 - version: 0.3.95(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) + version: 0.3.95(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) '@follow/configs': specifier: workspace:* version: link:../../configs @@ -2150,7 +2184,7 @@ importers: devDependencies: '@follow-app/client-sdk': specifier: 0.3.95 - version: 0.3.95(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) + version: 0.3.95(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) '@follow/configs': specifier: workspace:* version: link:../../configs @@ -3288,6 +3322,9 @@ packages: cpu: [x64] os: [win32] + '@cloudflare/workers-types@4.20260411.1': + resolution: {integrity: sha512-SsntcTanLz+LmgJC8yB7sGCtpC8HxboVDmwrOH1hp1SHZwuKnhfmhUfeiwy7O/cE3iVN1cxe1E17stxP5DJXDw==} + '@code-inspector/core@1.2.10': resolution: {integrity: sha512-xTkR4oBrTlRA/S2cXTuZLttCX6+wQgUpBpEK4Ad/e9KBIUIDRne5yoxuvrdy3xkTMkURS2V4SnCTzjFcu4OELQ==} @@ -7913,6 +7950,9 @@ packages: '@types/stack-utils@2.0.3': resolution: {integrity: sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==} + '@types/tar-stream@3.1.4': + resolution: {integrity: sha512-921gW0+g29mCJX0fRvqeHzBlE/XclDaAG0Ousy1LCghsOhvaKacDeRGEVzQP9IPfKn8Vysy7FEXAIxycpc/CMg==} + '@types/tar@6.1.13': resolution: {integrity: sha512-IznnlmU5f4WcGTh2ltRu/Ijpmk8wiWXfF0VA4s+HPjHZgvFggk1YaIkbo5krX/zUCzWF8N/l4+W/LNxnvAJ8nw==} @@ -11566,6 +11606,9 @@ packages: resolution: {integrity: sha512-trLf4SzuuUxfusZADLINj+dE8clK1frKdmqiJNb1Es75fmI5oY6X2mxLVUciLLjxqw/xr72Dhy+lER6dGd02FQ==} engines: {node: '>=10'} + fzstd@0.1.1: + resolution: {integrity: sha512-dkuVSOKKwh3eas5VkJy1AW1vFpet8TA/fGmVA5krThl8YcOVE/8ZIoEA1+U1vEn5ckxxhLirSdY837azmbaNHA==} + galactus@1.0.0: resolution: {integrity: sha512-R1fam6D4CyKQGNlvJne4dkNF+PvUUl7TAJInvTGa9fti9qAv95quQz29GXapA4d8Ec266mJJxFVh82M4GIIGDQ==} engines: {node: '>= 12'} @@ -18846,7 +18889,7 @@ snapshots: optionalDependencies: '@types/react': 19.2.14 - '@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0)': + '@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0)': dependencies: '@better-auth/utils': 0.3.1 '@better-fetch/fetch': 1.1.21 @@ -18856,8 +18899,10 @@ snapshots: kysely: 0.28.12 nanostores: 1.2.0 zod: 4.3.6 + optionalDependencies: + '@cloudflare/workers-types': 4.20260411.1 - '@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@4.3.6))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0)': + '@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@4.3.6))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0)': dependencies: '@better-auth/utils': 0.3.1 '@better-fetch/fetch': 1.1.21 @@ -18867,19 +18912,21 @@ snapshots: kysely: 0.28.12 nanostores: 1.2.0 zod: 4.3.6 + optionalDependencies: + '@cloudflare/workers-types': 4.20260411.1 - '@better-auth/drizzle-adapter@1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(@better-auth/utils@0.3.1)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))': + '@better-auth/drizzle-adapter@1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(@better-auth/utils@0.3.1)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))': dependencies: - '@better-auth/core': 1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0) + '@better-auth/core': 1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0) '@better-auth/utils': 0.3.1 optionalDependencies: - drizzle-orm: 0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0) + drizzle-orm: 0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0) - '@better-auth/expo@1.5.5(030e766e590ffb3d7c1b38e4a0e64129)': + '@better-auth/expo@1.5.5(b4280106e937db3b8687f2eb2012388c)': dependencies: - '@better-auth/core': 1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0) + '@better-auth/core': 1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0) '@better-fetch/fetch': 1.1.21 - better-auth: 1.5.5(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) + better-auth: 1.5.5(@cloudflare/workers-types@4.20260411.1)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) better-call: 1.3.2(zod@4.3.6) zod: 4.3.6 optionalDependencies: @@ -18888,40 +18935,40 @@ snapshots: expo-network: 55.0.13(expo@55.0.13)(react@19.2.0) expo-web-browser: 55.0.14(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0)) - '@better-auth/kysely-adapter@1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(@better-auth/utils@0.3.1)(kysely@0.28.12)': + '@better-auth/kysely-adapter@1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(@better-auth/utils@0.3.1)(kysely@0.28.12)': dependencies: - '@better-auth/core': 1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0) + '@better-auth/core': 1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0) '@better-auth/utils': 0.3.1 kysely: 0.28.12 - '@better-auth/memory-adapter@1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(@better-auth/utils@0.3.1)': + '@better-auth/memory-adapter@1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(@better-auth/utils@0.3.1)': dependencies: - '@better-auth/core': 1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0) + '@better-auth/core': 1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0) '@better-auth/utils': 0.3.1 - '@better-auth/mongo-adapter@1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(@better-auth/utils@0.3.1)(mongodb@7.1.0(socks@2.8.7))': + '@better-auth/mongo-adapter@1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(@better-auth/utils@0.3.1)(mongodb@7.1.0(socks@2.8.7))': dependencies: - '@better-auth/core': 1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0) + '@better-auth/core': 1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0) '@better-auth/utils': 0.3.1 mongodb: 7.1.0(socks@2.8.7) - '@better-auth/prisma-adapter@1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(@better-auth/utils@0.3.1)': + '@better-auth/prisma-adapter@1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(@better-auth/utils@0.3.1)': dependencies: - '@better-auth/core': 1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0) + '@better-auth/core': 1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0) '@better-auth/utils': 0.3.1 - '@better-auth/stripe@1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(better-auth@1.5.5(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)))(better-call@1.3.2(zod@3.25.76))(stripe@20.3.1(@types/node@25.2.3))': + '@better-auth/stripe@1.5.5(8587db83c79799d980d8a0bba87b75b2)': dependencies: - '@better-auth/core': 1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0) - better-auth: 1.5.5(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) + '@better-auth/core': 1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0) + better-auth: 1.5.5(@cloudflare/workers-types@4.20260411.1)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) better-call: 1.3.2(zod@3.25.76) defu: 6.1.4 stripe: 20.3.1(@types/node@25.2.3) zod: 4.3.6 - '@better-auth/telemetry@1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))': + '@better-auth/telemetry@1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))': dependencies: - '@better-auth/core': 1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0) + '@better-auth/core': 1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0) '@better-auth/utils': 0.3.1 '@better-fetch/fetch': 1.1.21 @@ -18962,13 +19009,13 @@ snapshots: optionalDependencies: workerd: 1.20260302.0 - '@cloudflare/vite-plugin@1.25.5(bufferutil@4.1.0)(vite@7.3.1(@types/node@24.9.1)(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))(workerd@1.20260302.0)(wrangler@4.68.1(bufferutil@4.1.0))': + '@cloudflare/vite-plugin@1.25.5(bufferutil@4.1.0)(vite@7.3.1(@types/node@24.9.1)(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))(workerd@1.20260302.0)(wrangler@4.68.1(@cloudflare/workers-types@4.20260411.1)(bufferutil@4.1.0))': dependencies: '@cloudflare/unenv-preset': 2.14.0(unenv@2.0.0-rc.24)(workerd@1.20260302.0) miniflare: 4.20260302.0(bufferutil@4.1.0) unenv: 2.0.0-rc.24 vite: 7.3.1(@types/node@24.9.1)(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2) - wrangler: 4.68.1(bufferutil@4.1.0) + wrangler: 4.68.1(@cloudflare/workers-types@4.20260411.1)(bufferutil@4.1.0) ws: 8.18.0(bufferutil@4.1.0) transitivePeerDependencies: - bufferutil @@ -19005,6 +19052,8 @@ snapshots: '@cloudflare/workerd-windows-64@1.20260302.0': optional: true + '@cloudflare/workers-types@4.20260411.1': {} + '@code-inspector/core@1.2.10': dependencies: '@vue/compiler-dom': 3.5.28 @@ -21599,13 +21648,13 @@ snapshots: '@floating-ui/utils@0.2.10': {} - '@follow-app/client-sdk@0.3.95(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))': - dependencies: + ? '@follow-app/client-sdk@0.3.95(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))' + : dependencies: '@folo-services/constants': 0.1.55 - '@folo-services/drizzle': 0.1.47(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12) + '@folo-services/drizzle': 0.1.47(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12) '@folo-services/exceptions': 0.1.30 - '@folo-services/shared': 0.0.47(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(pg@8.18.0) - better-auth: 1.5.5(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) + '@folo-services/shared': 0.0.47(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(pg@8.18.0) + better-auth: 1.5.5(@cloudflare/workers-types@4.20260411.1)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)) zod: 4.3.6 transitivePeerDependencies: - '@aws-sdk/client-rds-data' @@ -21654,12 +21703,12 @@ snapshots: - vitest - vue - '@folo-services/ai-tools@0.2.66(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(pg@8.18.0)': + '@folo-services/ai-tools@0.2.66(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(pg@8.18.0)': dependencies: '@ai-sdk/openai': 3.0.28(zod@4.3.6) - '@folo-services/drizzle': 0.1.47(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12) + '@folo-services/drizzle': 0.1.47(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12) ai: 6.0.85(zod@4.3.6) - drizzle-orm: 0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0) + drizzle-orm: 0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0) zod: 4.3.6 transitivePeerDependencies: - '@aws-sdk/client-rds-data' @@ -21698,12 +21747,12 @@ snapshots: dependencies: zod: 4.3.6 - '@folo-services/drizzle@0.1.47(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)': + '@folo-services/drizzle@0.1.47(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)': dependencies: '@folo-services/exceptions': 0.1.30 '@hono/zod-openapi': 1.2.1(hono@4.12.1)(zod@4.3.6) - drizzle-orm: 0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0) - drizzle-zod: 0.8.3(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(zod@4.3.6) + drizzle-orm: 0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0) + drizzle-zod: 0.8.3(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(zod@4.3.6) nanoid: 5.1.6 pg: 8.18.0 zod: 4.3.6 @@ -21741,13 +21790,13 @@ snapshots: '@folo-services/exceptions@0.1.30': {} - '@folo-services/shared@0.0.47(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(pg@8.18.0)': + '@folo-services/shared@0.0.47(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12)(pg@8.18.0)': dependencies: '@folo-services/constants': 0.1.55 - '@folo-services/drizzle': 0.1.47(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12) + '@folo-services/drizzle': 0.1.47(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(hono@4.12.1)(kysely@0.28.12) '@hono/zod-openapi': 1.2.1(hono@4.12.1)(zod@4.3.6) - drizzle-orm: 0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0) - drizzle-zod: 0.8.3(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(zod@4.3.6) + drizzle-orm: 0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0) + drizzle-zod: 0.8.3(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(zod@4.3.6) zod: 4.3.6 transitivePeerDependencies: - '@aws-sdk/client-rds-data' @@ -21884,12 +21933,12 @@ snapshots: '@hutson/parse-repository-url@5.0.0': {} - '@hyoban/sqlocal@0.14.1-fork.4(bufferutil@4.1.0)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(kysely@0.28.12)': + '@hyoban/sqlocal@0.14.1-fork.4(bufferutil@4.1.0)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(kysely@0.28.12)': dependencies: '@sqlite.org/sqlite-wasm': 3.50.0-build1 coincident: 1.2.3(bufferutil@4.1.0) optionalDependencies: - drizzle-orm: 0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0) + drizzle-orm: 0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0) kysely: 0.28.12 transitivePeerDependencies: - bufferutil @@ -24947,6 +24996,10 @@ snapshots: '@types/stack-utils@2.0.3': {} + '@types/tar-stream@3.1.4': + dependencies: + '@types/node': 25.2.3 + '@types/tar@6.1.13': dependencies: '@types/node': 25.2.3 @@ -26275,15 +26328,15 @@ snapshots: before-after-hook@2.2.3: {} - better-auth@1.5.5(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)): + better-auth@1.5.5(@cloudflare/workers-types@4.20260411.1)(better-sqlite3@12.6.2)(drizzle-kit@0.31.9)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(mongodb@7.1.0(socks@2.8.7))(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(pg@8.18.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vitest@3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)): dependencies: - '@better-auth/core': 1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@4.3.6))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0) - '@better-auth/drizzle-adapter': 1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(@better-auth/utils@0.3.1)(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0)) - '@better-auth/kysely-adapter': 1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(@better-auth/utils@0.3.1)(kysely@0.28.12) - '@better-auth/memory-adapter': 1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(@better-auth/utils@0.3.1) - '@better-auth/mongo-adapter': 1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(@better-auth/utils@0.3.1)(mongodb@7.1.0(socks@2.8.7)) - '@better-auth/prisma-adapter': 1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(@better-auth/utils@0.3.1) - '@better-auth/telemetry': 1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0)) + '@better-auth/core': 1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@4.3.6))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0) + '@better-auth/drizzle-adapter': 1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(@better-auth/utils@0.3.1)(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0)) + '@better-auth/kysely-adapter': 1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(@better-auth/utils@0.3.1)(kysely@0.28.12) + '@better-auth/memory-adapter': 1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(@better-auth/utils@0.3.1) + '@better-auth/mongo-adapter': 1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(@better-auth/utils@0.3.1)(mongodb@7.1.0(socks@2.8.7)) + '@better-auth/prisma-adapter': 1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0))(@better-auth/utils@0.3.1) + '@better-auth/telemetry': 1.5.5(@better-auth/core@1.5.5(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@4.20260411.1)(better-call@1.3.2(zod@3.25.76))(jose@6.2.1)(kysely@0.28.12)(nanostores@1.2.0)) '@better-auth/utils': 0.3.1 '@better-fetch/fetch': 1.1.21 '@noble/ciphers': 2.1.1 @@ -26297,7 +26350,7 @@ snapshots: optionalDependencies: better-sqlite3: 12.6.2 drizzle-kit: 0.31.9 - drizzle-orm: 0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0) + drizzle-orm: 0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0) mongodb: 7.1.0(socks@2.8.7) next: 16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(@playwright/test@1.58.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0) pg: 8.18.0 @@ -27587,17 +27640,18 @@ snapshots: transitivePeerDependencies: - supports-color - drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0): + drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0): optionalDependencies: + '@cloudflare/workers-types': 4.20260411.1 '@opentelemetry/api': 1.9.0 better-sqlite3: 12.6.2 expo-sqlite: 55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0) kysely: 0.28.12 pg: 8.18.0 - drizzle-zod@0.8.3(drizzle-orm@0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(zod@4.3.6): + drizzle-zod@0.8.3(drizzle-orm@0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0))(zod@4.3.6): dependencies: - drizzle-orm: 0.45.1(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0) + drizzle-orm: 0.45.1(@cloudflare/workers-types@4.20260411.1)(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@55.0.15(expo@55.0.13)(react-native@0.83.4(@babel/core@7.29.0)(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.0))(react@19.2.0))(kysely@0.28.12)(pg@8.18.0) zod: 4.3.6 ds-store@0.1.6: @@ -29856,6 +29910,8 @@ snapshots: fuse.js@7.1.0: {} + fzstd@0.1.1: {} + galactus@1.0.0: dependencies: debug: 4.4.3(supports-color@8.1.1) @@ -36521,7 +36577,7 @@ snapshots: '@node-kit/pnpm-workspace-root': 3.3.1 '@node-kit/yarn-workspace-root': 3.3.1 - wrangler@4.67.0(bufferutil@4.1.0): + wrangler@4.67.0(@cloudflare/workers-types@4.20260411.1)(bufferutil@4.1.0): dependencies: '@cloudflare/kv-asset-handler': 0.4.2 '@cloudflare/unenv-preset': 2.14.0(unenv@2.0.0-rc.24)(workerd@1.20260219.0) @@ -36532,12 +36588,13 @@ snapshots: unenv: 2.0.0-rc.24 workerd: 1.20260219.0 optionalDependencies: + '@cloudflare/workers-types': 4.20260411.1 fsevents: 2.3.3 transitivePeerDependencies: - bufferutil - utf-8-validate - wrangler@4.68.1(bufferutil@4.1.0): + wrangler@4.68.1(@cloudflare/workers-types@4.20260411.1)(bufferutil@4.1.0): dependencies: '@cloudflare/kv-asset-handler': 0.4.2 '@cloudflare/unenv-preset': 2.14.0(unenv@2.0.0-rc.24)(workerd@1.20260302.0) @@ -36548,6 +36605,7 @@ snapshots: unenv: 2.0.0-rc.24 workerd: 1.20260302.0 optionalDependencies: + '@cloudflare/workers-types': 4.20260411.1 fsevents: 2.3.3 transitivePeerDependencies: - bufferutil