diff --git a/docs/src/fragments/commands/build.md b/docs/src/fragments/commands/build.md index 53dbed41ab..ffa76e9143 100644 --- a/docs/src/fragments/commands/build.md +++ b/docs/src/fragments/commands/build.md @@ -6,6 +6,10 @@ # Upload an Android build (APK or AAB) for size analysis sentry build upload ./app-release.apk +# Upload an iOS build (XCArchive directory or IPA) +sentry build upload ./MyApp.xcarchive +sentry build upload ./MyApp.ipa + # Upload with a build configuration and release notes sentry build upload ./app.aab --build-configuration Release --release-notes "Nightly" @@ -27,8 +31,13 @@ sentry build download 1234567890 --json ## Important Notes -- `build upload` supports **Android APK and AAB**. iOS XCArchive/IPA upload is - not yet supported. **Sentry SaaS only.** +- `build upload` supports **Android APK/AAB** and **iOS XCArchive/IPA**. An + XCArchive is a directory; an IPA is converted to an XCArchive layout for + upload. **Sentry SaaS only.** +- iOS caveat: `Assets.car` asset catalogs are **not** parsed into per-asset + images (that required native macOS frameworks), so the server sees the raw + `.car` rather than a per-image breakdown. XCArchive symlinks and Unix file + permissions are preserved. - Multiple paths may be uploaded at once; the command exits non-zero if any build fails to upload. - Git metadata (commit, branch, PR number, repo) is **auto-collected in CI** diff --git a/plugins/sentry-cli/skills/sentry-cli/references/build.md b/plugins/sentry-cli/skills/sentry-cli/references/build.md index 94b6b608a2..2013d17e53 100644 --- a/plugins/sentry-cli/skills/sentry-cli/references/build.md +++ b/plugins/sentry-cli/skills/sentry-cli/references/build.md @@ -43,6 +43,10 @@ Download a build artifact # Upload an Android build (APK or AAB) for size analysis sentry build upload ./app-release.apk +# Upload an iOS build (XCArchive directory or IPA) +sentry build upload ./MyApp.xcarchive +sentry build upload ./MyApp.ipa + # Upload with a build configuration and release notes sentry build upload ./app.aab --build-configuration Release --release-notes "Nightly" diff --git a/src/commands/build/upload.ts b/src/commands/build/upload.ts index 93c8836a62..170a296d9f 100644 --- a/src/commands/build/upload.ts +++ b/src/commands/build/upload.ts @@ -17,8 +17,11 @@ import { } from "../../lib/api/preprod-artifacts.js"; import { detectBuildFormat, + normalizeBuildDirectory, normalizeBuildFile, + normalizeIpa, parsePluginFromPipeline, + validateXcarchiveDirectory, } from "../../lib/build/index.js"; import { collectVcsMetadata, @@ -110,12 +113,15 @@ async function uploadOne( throw new ValidationError(`Path does not exist: ${path}`, "path"); } - // XCArchive is a directory; iOS support is ported separately. + const plugin = parsePluginFromPipeline(ctx.env.SENTRY_PIPELINE); + + // An XCArchive is a directory; validate its structure, then zip it. The + // validation refuses arbitrary directories so a stray `sentry build upload ./` + // can't sweep up source, .git/, or secrets. if (info.isDirectory()) { - throw new ValidationError( - `iOS XCArchive upload is not yet supported: ${path}`, - "path" - ); + validateXcarchiveDirectory(path); + const normalized = await normalizeBuildDirectory(path, plugin); + return await uploadBuild({ org, project, content: normalized, metadata }); } // NOTE: the build is read fully into memory (and normalized into a second @@ -123,23 +129,21 @@ async function uploadOne( // Buffer cap will throw. A follow-up can stream normalization to a temp file // and use the file-based chunk path; the legacy CLI memory-maps instead. const content = await readFile(path); + // detectBuildFormat only classifies files (apk/aab/ipa); XCArchive is a + // directory, handled above. const format = detectBuildFormat(content); - if (format === "ipa" || format === "xcarchive") { + let normalized: Buffer; + if (format === "ipa") { + normalized = normalizeIpa(content, plugin); + } else if (format === "apk" || format === "aab") { + normalized = normalizeBuildFile(path, content, plugin); + } else { throw new ValidationError( - `iOS ${format.toUpperCase()} upload is not yet supported: ${path}`, + `Unsupported build format (expected APK, AAB, IPA, or XCArchive): ${path}`, "path" ); } - if (format !== "apk" && format !== "aab") { - throw new ValidationError( - `Unsupported build format (expected APK or AAB): ${path}`, - "path" - ); - } - - const plugin = parsePluginFromPipeline(ctx.env.SENTRY_PIPELINE); - const normalized = normalizeBuildFile(path, content, plugin); return await uploadBuild({ org, project, content: normalized, metadata }); } @@ -148,13 +152,15 @@ export const uploadCommand = buildCommand({ brief: "Upload builds to a project", fullDescription: "Upload mobile builds to Sentry for preprod size analysis. Each build " + - "is wrapped in a deterministic ZIP and uploaded via the chunk-upload + " + - "assemble protocol.\n\n" + - "Supported formats: Android APK and AAB. (iOS XCArchive/IPA is not yet " + - "supported.) This feature only works with Sentry SaaS.\n\n" + + "is normalized into a deterministic ZIP and uploaded via the " + + "chunk-upload + assemble protocol.\n\n" + + "Supported formats: Android APK/AAB, iOS XCArchive (a directory) and IPA. " + + "Note: iOS Assets.car asset catalogs are not parsed into per-asset " + + "images. This feature only works with Sentry SaaS.\n\n" + "Usage:\n" + " sentry build upload ./app-release.apk\n" + - " sentry build upload ./app.aab --build-configuration Release\n" + + " sentry build upload ./MyApp.xcarchive\n" + + " sentry build upload ./MyApp.ipa --build-configuration Release\n" + " sentry build upload ./app.aab --install-group qa --install-group beta", }, output: { @@ -164,7 +170,7 @@ export const uploadCommand = buildCommand({ positional: { kind: "array", parameter: { - brief: "Path(s) to the build(s) to upload (APK or AAB)", + brief: "Path(s) to the build(s) to upload (APK, AAB, IPA, or XCArchive)", parse: String, placeholder: "path", }, diff --git a/src/lib/build/index.ts b/src/lib/build/index.ts index da43eaf9c3..85359f2e8e 100644 --- a/src/lib/build/index.ts +++ b/src/lib/build/index.ts @@ -17,12 +17,18 @@ * CLI's, so chunks are not deduplicated across the two CLIs — only within this * one, which is what matters for repeated uploads from the same tool. * - * Only Android APK/AAB is handled here; iOS XCArchive/IPA is ported separately. + * Handles Android APK/AAB (file wrappers) and iOS XCArchive (directory) / IPA + * (converted to an XCArchive layout). Unlike the legacy CLI, iOS is not gated to + * Apple Silicon — the only native dependency was `Assets.car` parsing, which is + * intentionally skipped (see `normalizeBuildDirectory`). */ -import { basename } from "node:path"; -import { strToU8, unzipSync, zipSync } from "fflate"; +import { existsSync, readdirSync, statSync } from "node:fs"; +import { lstat, readdir, readFile, readlink } from "node:fs/promises"; +import { basename, join, resolve } from "node:path"; +import { strToU8, unzipSync, type Zippable, zipSync } from "fflate"; import { CLI_VERSION } from "../constants.js"; +import { ValidationError } from "../errors.js"; import { logger } from "../logger.js"; const log = logger.withTag("build.normalize"); @@ -174,3 +180,270 @@ export function normalizeBuildFile( }); return Buffer.from(zipped); } + +/** Deterministic STORE + fixed-mtime options for a normalized ZIP entry. */ +const ENTRY_OPTIONS = { level: 0 as const, mtime: FIXED_MTIME }; + +/** `os` = 3 (Unix) — required for `attrs` to carry Unix mode bits in a ZIP. */ +const ZIP_OS_UNIX = 3; + +/** + * Recursively find `.app` bundle directories under `dir` (does not descend into + * a `.app` once found), mirroring the legacy CLI's `Products/**` + `*.app` glob. + */ +function findAppBundles(dir: string): string[] { + const found: string[] = []; + for (const dirent of readdirSync(dir, { withFileTypes: true })) { + if (!dirent.isDirectory()) { + continue; + } + const full = join(dir, dirent.name); + if (dirent.name.endsWith(".app")) { + found.push(full); + } else { + found.push(...findAppBundles(full)); + } + } + return found; +} + +/** + * Validate that a directory is a real XCArchive before it is zipped and + * uploaded — mirrors the legacy CLI's `validate_xcarchive_directory`. + * + * Guards against accidentally uploading an arbitrary directory (e.g. a project + * root, which would sweep up `.git/`, `node_modules/`, and `.env` secrets). + * Requires a root `Info.plist`, a `Products/` directory, and at least one + * `.app` bundle (each with its own `Info.plist`). + * + * @throws {ValidationError} If the directory is not a valid XCArchive. + */ +export function validateXcarchiveDirectory(dirPath: string): void { + const root = resolve(dirPath); + if (!existsSync(join(root, "Info.plist"))) { + throw new ValidationError( + "Invalid XCArchive: missing Info.plist at the archive root", + "path" + ); + } + const products = join(root, "Products"); + if (!(existsSync(products) && statSync(products).isDirectory())) { + throw new ValidationError( + "Invalid XCArchive: missing Products/ directory", + "path" + ); + } + const apps = findAppBundles(products); + if (apps.length === 0) { + throw new ValidationError( + "Invalid XCArchive: no .app bundles found under Products/", + "path" + ); + } + for (const app of apps) { + if (!existsSync(join(app, "Info.plist"))) { + throw new ValidationError( + `Invalid XCArchive: missing Info.plist in .app bundle: ${basename(app)}`, + "path" + ); + } + } +} + +/** A collected archive entry: its relative path, bytes, and ZIP attrs. */ +type ArchiveEntry = { relPath: string; content: Uint8Array; attrs: number }; + +/** + * Recursively collect an XCArchive's entries, preserving symlinks and Unix + * permissions (via ZIP external attributes) exactly as the legacy CLI does. + * + * A custom walk (rather than the shared file walker) is used because fidelity + * matters here: symlinks are stored as symlink entries (their target string as + * content, `S_IFLNK` in the mode) — NOT followed — so Apple framework/dSYM + * bundles aren't restructured or their binaries duplicated, which would corrupt + * the server's size analysis. Symlinked directories are recorded as links and + * not descended into, matching the Rust `WalkDir` (follow_links = false). + */ +async function collectArchiveEntries(root: string): Promise { + const entries: ArchiveEntry[] = []; + + const walk = async (dir: string, prefix: string): Promise => { + const dirents = await readdir(dir, { withFileTypes: true }); + for (const dirent of dirents) { + const full = join(dir, dirent.name); + const relPath = prefix ? `${prefix}/${dirent.name}` : dirent.name; + + // Check symlink first: a symlink to a directory must be stored as a link, + // not descended into (matching Rust's WalkDir with follow_links = false). + let content: Uint8Array; + if (dirent.isSymbolicLink()) { + content = strToU8(await readlink(full)); + } else if (dirent.isDirectory()) { + await walk(full, relPath); + continue; + } else if (dirent.isFile()) { + content = await readFile(full); + } else { + // Skip sockets, FIFOs, and other special files. + continue; + } + + // Encode the full Unix mode (type + permission bits) into the upper 16 + // bits of the ZIP external attributes so symlinks and exec bits survive. + const { mode } = await lstat(full); + const attrs = ((mode & 0xff_ff) << 16) >>> 0; + entries.push({ relPath, content, attrs }); + } + }; + + await walk(root, ""); + entries.sort((a, b) => (a.relPath < b.relPath ? -1 : a.relPath > b.relPath ? 1 : 0)); + return entries; +} + +/** + * Wrap an XCArchive directory into a deterministic normalized ZIP for upload. + * + * Every file under `dirPath` is stored under `/` + * (STORE, fixed mtime, sorted for byte-stability) alongside a root + * `.sentry-cli-metadata.txt`, mirroring the legacy CLI's `normalize_directory`. + * Symlinks and Unix permissions are preserved (see {@link collectArchiveEntries}); + * validate the directory first with {@link validateXcarchiveDirectory}. + * + * Documented gap: `Assets.car` asset catalogs are not parsed into per-asset + * images (that required native macOS frameworks), so no `ParsedAssets/` tree is + * added — the raw `.car` is uploaded as-is. + * + * The whole directory is read into memory; a very large XCArchive (e.g. with + * dSYMs) could exceed Node's ~2 GiB Buffer cap — streaming is a follow-up. + * + * @param dirPath - Path to the XCArchive directory. + * @param plugin - Optional plugin identity for the metadata file. + * @returns The normalized ZIP bytes. + */ +export async function normalizeBuildDirectory( + dirPath: string, + plugin: PipelinePlugin | null +): Promise { + const root = resolve(dirPath); + const dirName = basename(root); + + const entries: Zippable = {}; + for (const entry of await collectArchiveEntries(root)) { + entries[`${dirName}/${entry.relPath}`] = [ + entry.content, + { level: 0, mtime: FIXED_MTIME, os: ZIP_OS_UNIX, attrs: entry.attrs }, + ]; + } + entries[METADATA_FILENAME] = [ + strToU8(buildMetadataFile(plugin)), + ENTRY_OPTIONS, + ]; + + return Buffer.from(zipSync(entries)); +} + +/** Regex matching an IPA's single `Payload/.app/Info.plist` entry. */ +const IPA_APP_INFO_PLIST = /^Payload\/([^/]+)\.app\/Info\.plist$/; + +/** + * Extract the single app name from an IPA's entry names. + * + * @throws {Error} If the IPA does not contain exactly one `.app`. + */ +export function extractIpaAppName(names: string[]): string { + const appNames = new Set(); + for (const name of names) { + const match = IPA_APP_INFO_PLIST.exec(name); + if (match?.[1]) { + appNames.add(match[1]); + } + } + const appName = appNames.values().next().value; + if (appNames.size !== 1 || appName === undefined) { + throw new Error("IPA did not contain exactly one .app"); + } + return appName; +} + +/** Build the XCArchive `Info.plist` for a converted IPA. */ +function xcarchiveInfoPlist(appName: string): string { + return ` + + + + ApplicationProperties + + ApplicationPath + Applications/${appName}.app + + ArchiveVersion + 1 + +`; +} + +/** + * Convert an IPA into a deterministic normalized XCArchive ZIP for upload. + * + * The IPA (a ZIP of `Payload/.app/…`) is remapped in-memory into an + * XCArchive layout — `archive.xcarchive/Products/Applications/.app/…` plus + * a generated `archive.xcarchive/Info.plist` — and stored (STORE, fixed mtime) + * alongside a root `.sentry-cli-metadata.txt`. Mirrors the legacy CLI's + * `ipa_to_xcarchive` + `normalize_directory`. + * + * @param content - The raw IPA bytes. + * @param plugin - Optional plugin identity for the metadata file. + * @returns The normalized ZIP bytes. + * @throws {Error} If the IPA does not contain exactly one `.app`. + */ +export function normalizeIpa( + content: Uint8Array, + plugin: PipelinePlugin | null +): Buffer { + const ipaEntries = unzipSync(content); + const appName = extractIpaAppName(Object.keys(ipaEntries)); + + const archiveDir = "archive.xcarchive"; + // Only the identified app's entries are included (an IPA should contain + // exactly one `.app`); a stray second bundle is ignored so it can't skew size + // analysis. + const appPrefix = `Payload/${appName}.app/`; + + // Collect (path, bytes) then sort so the output depends only on contents, not + // on the IPA's central-directory order — keeping bytes deterministic for + // chunk dedup across re-uploads (as normalizeBuildDirectory does). + const archiveEntries: Array<[string, Uint8Array]> = []; + for (const [name, bytes] of Object.entries(ipaEntries)) { + // Directory entries (trailing "/") carry no data; skip them. + if (name.endsWith("/") || !name.startsWith(appPrefix)) { + continue; + } + const stripped = name.slice("Payload/".length); + // Skip path-traversal entries (a `..` segment) defensively, matching the + // legacy CLI's `enclosed_name()` guard. + if (stripped.split("/").includes("..")) { + continue; + } + archiveEntries.push([ + `${archiveDir}/Products/Applications/${stripped}`, + bytes, + ]); + } + archiveEntries.push([ + `${archiveDir}/Info.plist`, + strToU8(xcarchiveInfoPlist(appName)), + ]); + archiveEntries.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)); + + const entries: Zippable = {}; + for (const [key, bytes] of archiveEntries) { + entries[key] = [bytes, ENTRY_OPTIONS]; + } + entries[METADATA_FILENAME] = [ + strToU8(buildMetadataFile(plugin)), + ENTRY_OPTIONS, + ]; + + return Buffer.from(zipSync(entries)); +} diff --git a/test/commands/build/upload.test.ts b/test/commands/build/upload.test.ts index ce285c60fe..e1cda398f1 100644 --- a/test/commands/build/upload.test.ts +++ b/test/commands/build/upload.test.ts @@ -178,9 +178,33 @@ describe("build upload", () => { expect(harness.output()).toContain("Unsupported build format"); }); - test("rejects a directory (iOS XCArchive) with a non-zero exit", async () => { - const dir = join(tmpDir, "MyApp.xcarchive"); + /** Write a minimal valid XCArchive directory; returns its path. */ + async function writeXcarchive(name = "MyApp.xcarchive"): Promise { + const dir = join(tmpDir, name); + const app = join(dir, "Products", "Applications", "MyApp.app"); + await mkdir(app, { recursive: true }); + await writeFile(join(dir, "Info.plist"), ""); + await writeFile(join(app, "Info.plist"), ""); + await writeFile(join(app, "MyApp"), "binary"); + return dir; + } + + test("uploads an XCArchive directory", async () => { + const dir = await writeXcarchive(); + const harness = createContext(); + const func = await uploadCommand.loader(); + + await func.call(harness.context, {}, dir); + + expect(uploadSpy).toHaveBeenCalledTimes(1); + expect(harness.exitCode).toBeUndefined(); + expect(harness.output()).toContain("https://sentry.io/artifact/1"); + }); + + test("rejects a directory that is not a valid XCArchive", async () => { + const dir = join(tmpDir, "not-an-archive"); await mkdir(dir); + await writeFile(join(dir, "readme.txt"), "hello"); const harness = createContext(); const func = await uploadCommand.loader(); @@ -188,7 +212,25 @@ describe("build upload", () => { expect(uploadSpy).not.toHaveBeenCalled(); expect(harness.exitCode).toBe(1); - expect(harness.output()).toContain("XCArchive"); + expect(harness.output()).toContain("Invalid XCArchive"); + }); + + test("uploads an IPA (converted to an XCArchive layout)", async () => { + const ipa = join(tmpDir, "MyApp.ipa"); + await writeFile( + ipa, + zipSync({ + "Payload/MyApp.app/Info.plist": strToU8(""), + "Payload/MyApp.app/MyApp": strToU8("binary"), + }) + ); + const harness = createContext(); + const func = await uploadCommand.loader(); + + await func.call(harness.context, {}, ipa); + + expect(uploadSpy).toHaveBeenCalledTimes(1); + expect(harness.exitCode).toBeUndefined(); }); test("uploads the good build but exits non-zero when another fails", async () => { diff --git a/test/lib/build/index.test.ts b/test/lib/build/index.test.ts index 95efa565a9..a9696c5a7a 100644 --- a/test/lib/build/index.test.ts +++ b/test/lib/build/index.test.ts @@ -5,12 +5,25 @@ * APK/AAB" is just a ZIP carrying the marker entry names the detector keys on. */ +import { + mkdirSync, + mkdtempSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { strToU8, unzipSync, zipSync } from "fflate"; -import { describe, expect, test } from "vitest"; +import { afterEach, describe, expect, test } from "vitest"; import { detectBuildFormat, + extractIpaAppName, + normalizeBuildDirectory, normalizeBuildFile, + normalizeIpa, parsePluginFromPipeline, + validateXcarchiveDirectory, } from "../../../src/lib/build/index.js"; function fakeApk(): Uint8Array { @@ -113,3 +126,230 @@ describe("normalizeBuildFile", () => { expect(Buffer.from(a).equals(Buffer.from(b))).toBe(true); }); }); + +describe("normalizeBuildDirectory", () => { + const dirs: string[] = []; + afterEach(() => { + while (dirs.length > 0) { + const d = dirs.pop(); + if (d) { + rmSync(d, { recursive: true, force: true }); + } + } + }); + + function fakeXcarchive(): string { + const base = mkdtempSync(join(tmpdir(), "xc-")); + dirs.push(base); + const xc = join(base, "MyApp.xcarchive"); + mkdirSync(join(xc, "Products", "Applications", "MyApp.app"), { + recursive: true, + }); + writeFileSync(join(xc, "Info.plist"), ""); + writeFileSync( + join(xc, "Products", "Applications", "MyApp.app", "MyApp"), + "binary" + ); + return xc; + } + + test("zips files under the directory basename plus a root metadata file", async () => { + const zip = await normalizeBuildDirectory(fakeXcarchive(), null); + const entries = unzipSync(zip); + expect(Object.keys(entries).sort()).toEqual([ + ".sentry-cli-metadata.txt", + "MyApp.xcarchive/Info.plist", + "MyApp.xcarchive/Products/Applications/MyApp.app/MyApp", + ]); + expect(entries["MyApp.xcarchive/Info.plist"]).toEqual(strToU8("")); + }); + + test("is deterministic (identical tree → identical bytes)", async () => { + const xc = fakeXcarchive(); + const a = await normalizeBuildDirectory(xc, null); + const b = await normalizeBuildDirectory(xc, null); + expect(a.equals(b)).toBe(true); + }); + + // Symlinks require privileges on Windows; the unit suite runs on Linux. + test.skipIf(process.platform === "win32")( + "preserves symlinks as entries (stores the target path, not followed content)", + async () => { + const base = mkdtempSync(join(tmpdir(), "xc-sym-")); + dirs.push(base); + const xc = join(base, "App.xcarchive"); + mkdirSync(xc, { recursive: true }); + writeFileSync(join(xc, "real.txt"), "REAL"); + symlinkSync("real.txt", join(xc, "link.txt")); + + const entries = unzipSync(await normalizeBuildDirectory(xc, null)); + // The symlink entry stores its target path — proof it was NOT followed + // (following would store "REAL", the target's file content). + expect(new TextDecoder().decode(entries["App.xcarchive/link.txt"])).toBe( + "real.txt" + ); + expect(new TextDecoder().decode(entries["App.xcarchive/real.txt"])).toBe( + "REAL" + ); + } + ); +}); + +describe("validateXcarchiveDirectory", () => { + const dirs: string[] = []; + afterEach(() => { + while (dirs.length > 0) { + const d = dirs.pop(); + if (d) { + rmSync(d, { recursive: true, force: true }); + } + } + }); + + function makeArchive(build: (xc: string) => void): string { + const base = mkdtempSync(join(tmpdir(), "xc-val-")); + dirs.push(base); + const xc = join(base, "MyApp.xcarchive"); + mkdirSync(xc, { recursive: true }); + build(xc); + return xc; + } + + test("accepts a valid XCArchive", () => { + const xc = makeArchive((dir) => { + const app = join(dir, "Products", "Applications", "MyApp.app"); + mkdirSync(app, { recursive: true }); + writeFileSync(join(dir, "Info.plist"), ""); + writeFileSync(join(app, "Info.plist"), ""); + }); + expect(() => validateXcarchiveDirectory(xc)).not.toThrow(); + }); + + test("rejects a directory missing the root Info.plist", () => { + const xc = makeArchive((dir) => { + mkdirSync(join(dir, "Products"), { recursive: true }); + }); + expect(() => validateXcarchiveDirectory(xc)).toThrow("Info.plist"); + }); + + test("rejects a directory missing Products/", () => { + const xc = makeArchive((dir) => { + writeFileSync(join(dir, "Info.plist"), ""); + }); + expect(() => validateXcarchiveDirectory(xc)).toThrow("Products/"); + }); + + test("rejects when a .app bundle has no Info.plist", () => { + const xc = makeArchive((dir) => { + writeFileSync(join(dir, "Info.plist"), ""); + mkdirSync(join(dir, "Products", "Applications", "MyApp.app"), { + recursive: true, + }); + }); + expect(() => validateXcarchiveDirectory(xc)).toThrow(".app bundle"); + }); +}); + +describe("extractIpaAppName", () => { + test("returns the single app name", () => { + expect( + extractIpaAppName([ + "Payload/MyApp.app/Info.plist", + "Payload/MyApp.app/MyApp", + ]) + ).toBe("MyApp"); + }); + + test("throws when there is no .app", () => { + expect(() => extractIpaAppName(["readme.txt"])).toThrow("exactly one"); + }); + + test("throws when there are multiple .apps", () => { + expect(() => + extractIpaAppName([ + "Payload/A.app/Info.plist", + "Payload/B.app/Info.plist", + ]) + ).toThrow("exactly one"); + }); +}); + +describe("normalizeIpa", () => { + function fakeIpaBytes(): Uint8Array { + return zipSync({ + "Payload/MyApp.app/Info.plist": strToU8(""), + "Payload/MyApp.app/MyApp": strToU8("binary"), + "Payload/MyApp.app/Assets.car": strToU8("carbytes"), + }); + } + + test("remaps Payload into an XCArchive layout with a generated Info.plist", () => { + const zip = normalizeIpa(fakeIpaBytes(), null); + const entries = unzipSync(zip); + expect(Object.keys(entries).sort()).toEqual([ + ".sentry-cli-metadata.txt", + "archive.xcarchive/Info.plist", + "archive.xcarchive/Products/Applications/MyApp.app/Assets.car", + "archive.xcarchive/Products/Applications/MyApp.app/Info.plist", + "archive.xcarchive/Products/Applications/MyApp.app/MyApp", + ]); + const plist = new TextDecoder().decode( + entries["archive.xcarchive/Info.plist"] + ); + expect(plist).toContain("Applications/MyApp.app"); + // Assets.car is carried through verbatim (not parsed). + expect( + entries["archive.xcarchive/Products/Applications/MyApp.app/Assets.car"] + ).toEqual(strToU8("carbytes")); + }); + + test("remaps nested framework entries under the app", () => { + const ipa = zipSync({ + "Payload/MyApp.app/Info.plist": strToU8(""), + "Payload/MyApp.app/Frameworks/X.framework/X": strToU8("fw"), + }); + const entries = unzipSync(normalizeIpa(ipa, null)); + expect( + entries[ + "archive.xcarchive/Products/Applications/MyApp.app/Frameworks/X.framework/X" + ] + ).toEqual(strToU8("fw")); + }); + + test("includes only the identified app's entries", () => { + const ipa = zipSync({ + "Payload/MyApp.app/Info.plist": strToU8(""), + "Payload/MyApp.app/MyApp": strToU8("bin"), + // A stray second .app (no Info.plist so extractIpaAppName still sees one) + // must not be bundled. + "Payload/Stray.app/junk": strToU8("junk"), + }); + const names = Object.keys(unzipSync(normalizeIpa(ipa, null))); + expect(names.some((n) => n.includes("Stray"))).toBe(false); + expect( + names.includes( + "archive.xcarchive/Products/Applications/MyApp.app/MyApp" + ) + ).toBe(true); + }); + + test("skips path-traversal entries", () => { + const ipa = zipSync({ + "Payload/MyApp.app/Info.plist": strToU8(""), + "Payload/MyApp.app/../../evil": strToU8("x"), + }); + const names = Object.keys(unzipSync(normalizeIpa(ipa, null))); + expect(names.some((n) => n.includes("evil"))).toBe(false); + }); + + test("is deterministic (identical IPA → identical bytes)", () => { + const ipa = fakeIpaBytes(); + expect(normalizeIpa(ipa, null).equals(normalizeIpa(ipa, null))).toBe(true); + }); + + test("throws when the IPA has no single .app", () => { + expect(() => normalizeIpa(zipSync({ "readme.txt": strToU8("x") }), null)).toThrow( + "exactly one" + ); + }); +});