Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off preferSchemaOverJson:off - This tests the standalone Node release tool with a fake HTTP server.
2import * as NodeCrypto from "node:crypto";
3import * as NodeFSP from "node:fs/promises";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6import { describe, expect, it, vi } from "vite-plus/test";
7
8import {
9 createTestFlightClient,
10 makeAppStoreToken,
11 parseTestFlightArgs,
12 parseTestFlightEnv,
13 readTestFlightEnv,
14 validateUploadMetadata,
15 withTemporaryPrivateKey,
16} from "./swift-testflight.ts";
17
18const keys = NodeCrypto.generateKeyPairSync("ec", { namedCurve: "prime256v1" });
19const encodedKey = Buffer.from(keys.privateKey.export({ type: "pkcs8", format: "pem" })).toString(
20 "base64",
21);
22const envSource = `# Synthetic test credentials, never used with Apple.
23T3_SWIFT_ASC_KEY_ID="TESTKEY123"
24T3_SWIFT_ASC_ISSUER_ID=00000000-0000-0000-0000-000000000001
25T3_SWIFT_ASC_PRIVATE_KEY_BASE64="${encodedKey}"
26T3_SWIFT_ASC_APP_ID=12345
27T3_SWIFT_ASC_PUBLIC_GROUP_ID=public
28T3_SWIFT_ASC_INTERNAL_GROUP_ID=internal
29`;
30const { config } = parseTestFlightEnv(envSource);
31const selection = { build: "46", version: "0.1.0" };
32const notes = "Fix attachment imports and keep the keyboard open during dictation.";
33const linkage = (type: string, id: string) => ({ data: { type, id } });
34
35function mockServer(
36 options: {
37 bundleId?: string;
38 groupAppId?: string;
39 buildAppId?: string;
40 buildExists?: boolean;
41 processingState?: string;
42 externalState?: string;
43 reviewState?: string;
44 assigned?: string[];
45 autoNotifyEnabled?: boolean;
46 existingNotes?: string | null;
47 failAfterGroupAssignment?: boolean;
48 approveImmediately?: boolean;
49 sparseBetaRelations?: boolean;
50 } = {},
51) {
52 const state = {
53 externalState: options.externalState ?? "IN_BETA_TESTING",
54 reviewState: options.reviewState,
55 assigned: new Set(options.assigned ?? ["internal", "public"]),
56 autoNotifyEnabled: options.autoNotifyEnabled ?? true,
57 notes: options.existingNotes === undefined ? notes : options.existingNotes,
58 };
59 const writes: { method: string; path: string; body: unknown }[] = [];
60 const fetchMock = vi.fn<typeof fetch>(async (input, init) => {
61 const url = new URL(String(input));
62 const method = init?.method ?? "GET";
63 if (url.origin !== "https://api.appstoreconnect.apple.com") {
64 throw new Error("Unexpected origin");
65 }
66 const path = url.pathname;
67 const detail = {
68 type: "buildBetaDetails",
69 id: "detail-46",
70 attributes: {
71 externalBuildState: state.externalState,
72 internalBuildState: "IN_BETA_TESTING",
73 autoNotifyEnabled: state.autoNotifyEnabled,
74 },
75 };
76 const reviews = state.reviewState
77 ? [
78 {
79 type: "betaAppReviewSubmissions",
80 id: "review-46",
81 attributes: { betaReviewState: state.reviewState },
82 },
83 ]
84 : [];
85 const groupResource = (id: string) => ({
86 type: "betaGroups",
87 id,
88 attributes: {
89 name: id,
90 isInternalGroup: id === "internal",
91 hasAccessToAllBuilds: false,
92 publicLinkEnabled: id === "public",
93 },
94 relationships: { app: linkage("apps", options.groupAppId ?? config.appId) },
95 });
96 if (method === "GET") {
97 if (path === `/v1/apps/${config.appId}`) {
98 return Response.json({
99 data: {
100 type: "apps",
101 id: config.appId,
102 attributes: {
103 name: "T3 Code SwiftUI",
104 bundleId: options.bundleId ?? "com.t3tools.t3code.swiftui",
105 primaryLocale: "en-US",
106 },
107 },
108 });
109 }
110 if (path === "/v1/betaGroups/public" || path === "/v1/betaGroups/internal") {
111 expect(url.searchParams.get("include")).toBe("app");
112 return Response.json({
113 data: groupResource(path.endsWith("public") ? "public" : "internal"),
114 });
115 }
116 if (path === "/v1/builds") {
117 expect(url.searchParams.get("filter[app]")).toBe(config.appId);
118 expect(url.searchParams.get("filter[version]")).toBe("46");
119 expect(url.searchParams.get("filter[preReleaseVersion.version]")).toBe("0.1.0");
120 const build = {
121 type: "builds",
122 id: "build-46",
123 attributes: {
124 version: "46",
125 processingState: options.processingState ?? "VALID",
126 expired: false,
127 buildAudienceType: "APP_STORE_ELIGIBLE",
128 },
129 relationships: {
130 app: url.searchParams.get("include")?.split(",").includes("app")
131 ? linkage("apps", options.buildAppId ?? config.appId)
132 : { links: { related: "/v1/builds/build-46/app" } },
133 preReleaseVersion: linkage("preReleaseVersions", "version-1"),
134 buildBetaDetail: options.sparseBetaRelations
135 ? {}
136 : linkage("buildBetaDetails", "detail-46"),
137 betaAppReviewSubmission: options.sparseBetaRelations
138 ? {}
139 : state.reviewState
140 ? linkage("betaAppReviewSubmissions", "review-46")
141 : { data: null },
142 },
143 };
144 return Response.json({
145 data: options.buildExists === false ? [] : [build],
146 included: [
147 {
148 type: "preReleaseVersions",
149 id: "version-1",
150 attributes: { version: "0.1.0", platform: "IOS" },
151 },
152 ...(options.sparseBetaRelations ? [] : [detail, ...reviews]),
153 ],
154 });
155 }
156 if (path === "/v1/buildBetaDetails" || path === "/v1/betaAppReviewSubmissions") {
157 expect(url.searchParams.get("filter[build]")).toBe("build-46");
158 return Response.json({ data: path === "/v1/buildBetaDetails" ? [detail] : reviews });
159 }
160 if (path === "/v1/betaGroups") {
161 expect(url.searchParams.has("filter[app]")).toBe(false);
162 expect(url.searchParams.get("filter[builds]")).toBe("build-46");
163 return Response.json({ data: [...state.assigned].map(groupResource) });
164 }
165 if (path === "/v1/builds/build-46/betaBuildLocalizations") {
166 return Response.json({
167 data:
168 state.notes === null
169 ? []
170 : [
171 {
172 type: "betaBuildLocalizations",
173 id: "notes-46",
174 attributes: { locale: "en-US", whatsNew: state.notes },
175 },
176 ],
177 });
178 }
179 } else {
180 const body: unknown = JSON.parse(String(init?.body));
181 writes.push({ method, path, body });
182 if (path === "/v1/betaBuildLocalizations" || path === "/v1/betaBuildLocalizations/notes-46") {
183 state.notes = notes;
184 return Response.json({ data: { type: "betaBuildLocalizations", id: "notes-46" } });
185 }
186 if (path === "/v1/buildBetaDetails/detail-46") {
187 state.autoNotifyEnabled = true;
188 return Response.json({ data: { type: "buildBetaDetails", id: "detail-46" } });
189 }
190 if (
191 path === "/v1/betaGroups/public/relationships/builds" ||
192 path === "/v1/betaGroups/internal/relationships/builds"
193 ) {
194 state.assigned.add(path.includes("/public/") ? "public" : "internal");
195 if (options.failAfterGroupAssignment) throw new Error("Lost response after write");
196 return new Response(null, { status: 204 });
197 }
198 if (path === "/v1/betaAppReviewSubmissions") {
199 state.externalState = options.approveImmediately
200 ? "BETA_APPROVED"
201 : "WAITING_FOR_BETA_REVIEW";
202 state.reviewState = options.approveImmediately ? "APPROVED" : "WAITING_FOR_REVIEW";
203 return Response.json(
204 { data: { type: "betaAppReviewSubmissions", id: "review-46" } },
205 { status: 201 },
206 );
207 }
208 if (path === "/v1/buildBetaNotifications") {
209 state.externalState = "IN_BETA_TESTING";
210 return Response.json(
211 { data: { type: "buildBetaNotifications", id: "notification-46" } },
212 { status: 201 },
213 );
214 }
215 }
216 throw new Error(`Unexpected request: ${method} ${path}`);
217 });
218 return {
219 client: createTestFlightClient(config, keys.privateKey, fetchMock),
220 fetchMock,
221 state,
222 writes,
223 };
224}
225
226describe("App Store Connect authentication", () => {
227 it("does not print a token echoed in an API error", async () => {
228 let capturedToken = "";
229 const client = createTestFlightClient(config, keys.privateKey, async (_input, init) => {
230 capturedToken = new Headers(init?.headers).get("Authorization")?.slice(7) ?? "";
231 return Response.json({ errors: [{ detail: `Rejected ${capturedToken}` }] }, { status: 401 });
232 });
233 await expect(client.status(selection)).rejects.toThrow("Rejected [redacted token]");
234 expect(capturedToken).not.toBe("");
235 });
236
237 it("parses a quoted env file and restores the downloaded PEM key", () => {
238 const parsed = parseTestFlightEnv(envSource);
239 expect(parsed.config).toEqual({
240 keyId: "TESTKEY123",
241 issuerId: "00000000-0000-0000-0000-000000000001",
242 appId: "12345",
243 publicGroupId: "public",
244 internalGroupId: "internal",
245 });
246 expect(
247 NodeCrypto.createPublicKey(parsed.privateKey).export({ type: "spki", format: "pem" }),
248 ).toBe(keys.publicKey.export({ type: "spki", format: "pem" }));
249 });
250
251 it("does not export parsed env variables to the process", () => {
252 const before = process.env.T3_SWIFT_ENV_PARSE_TEST_SENTINEL;
253 parseTestFlightEnv(`${envSource}T3_SWIFT_ENV_PARSE_TEST_SENTINEL="local only"\n`);
254 expect(process.env.T3_SWIFT_ENV_PARSE_TEST_SENTINEL).toBe(before);
255 });
256
257 it("requires private permissions on the env file", async () => {
258 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-swift-env-test-"));
259 const path = NodePath.join(directory, ".env.testflight.local");
260 try {
261 await NodeFSP.writeFile(path, envSource, { mode: 0o600 });
262 expect((await readTestFlightEnv(path)).config).toEqual(config);
263 await NodeFSP.chmod(path, 0o644);
264 await expect(readTestFlightEnv(path)).rejects.toThrow("mode 600");
265 } finally {
266 await NodeFSP.rm(directory, { recursive: true, force: true });
267 }
268 });
269
270 it.each([false, true])(
271 "removes the temporary Xcode key after success or failure: %s",
272 async (fail) => {
273 let temporaryPath: string | undefined;
274 const operation = withTemporaryPrivateKey(keys.privateKey, async (path) => {
275 temporaryPath = path;
276 expect((await NodeFSP.stat(path)).mode & 0o777).toBe(0o600);
277 expect((await NodeFSP.stat(NodePath.dirname(path))).mode & 0o777).toBe(0o700);
278 const savedKey = NodeCrypto.createPrivateKey(await NodeFSP.readFile(path));
279 expect(NodeCrypto.createPublicKey(savedKey).export({ type: "spki", format: "pem" })).toBe(
280 keys.publicKey.export({ type: "spki", format: "pem" }),
281 );
282 if (fail) throw new Error("Upload failed");
283 });
284 if (fail) await expect(operation).rejects.toThrow("Upload failed");
285 else await operation;
286 if (!temporaryPath) throw new Error("The upload callback did not run");
287 await expect(NodeFSP.stat(NodePath.dirname(temporaryPath))).rejects.toMatchObject({
288 code: "ENOENT",
289 });
290 },
291 );
292
293 it("signs a ten-minute ES256 token with the API audience and P1363 signature", () => {
294 const token = makeAppStoreToken(config, keys.privateKey, 1_000);
295 const [header, payload, signature] = token.split(".");
296 if (!header || !payload || !signature) throw new Error("Invalid token");
297 expect(JSON.parse(Buffer.from(header, "base64url").toString())).toEqual({
298 alg: "ES256",
299 kid: config.keyId,
300 typ: "JWT",
301 });
302 expect(JSON.parse(Buffer.from(payload, "base64url").toString())).toEqual({
303 iss: config.issuerId,
304 iat: 1_000,
305 exp: 1_600,
306 aud: "appstoreconnect-v1",
307 });
308 expect(Buffer.from(signature, "base64url")).toHaveLength(64);
309 expect(
310 NodeCrypto.verify(
311 "sha256",
312 Buffer.from(`${header}.${payload}`),
313 {
314 key: keys.publicKey,
315 dsaEncoding: "ieee-p1363",
316 },
317 Buffer.from(signature, "base64url"),
318 ),
319 ).toBe(true);
320 });
321
322 it("rejects a key that cannot sign ES256", () => {
323 const wrongKey = NodeCrypto.generateKeyPairSync("ed25519");
324 expect(() => makeAppStoreToken(config, wrongKey.privateKey)).toThrow("P-256 private key");
325 });
326});
327
328describe("SwiftUI TestFlight publication", () => {
329 it.each([
330 { bundleId: "com.t3tools.t3code.swiftui.dev" },
331 { groupAppId: "other-app" },
332 { buildAppId: "other-app" },
333 ])("refuses wrong-app targets before any write: %j", async (options) => {
334 const server = mockServer(options);
335 await expect(server.client.publish(selection, notes)).rejects.toThrow(
336 /Refusing|different app/u,
337 );
338 expect(server.writes).toEqual([]);
339 });
340
341 it("does not duplicate group assignment, review, or notifications for a testing build", async () => {
342 const server = mockServer();
343 const result = await server.client.publish(selection, notes);
344 expect(result.publicTesting).toBe(true);
345 expect(server.writes).toEqual([]);
346 });
347
348 it("sets notes, assigns both groups, and submits once without claiming review is complete", async () => {
349 const server = mockServer({
350 externalState: "READY_FOR_BETA_SUBMISSION",
351 assigned: [],
352 autoNotifyEnabled: false,
353 existingNotes: null,
354 });
355 const result = await server.client.publish(selection, notes);
356 expect(result.publicTesting).toBe(false);
357 expect(result.externalState).toBe("WAITING_FOR_BETA_REVIEW");
358 expect(server.writes.map(({ method, path }) => `${method} ${path}`)).toEqual([
359 "POST /v1/betaBuildLocalizations",
360 "PATCH /v1/buildBetaDetails/detail-46",
361 "POST /v1/betaGroups/internal/relationships/builds",
362 "POST /v1/betaGroups/public/relationships/builds",
363 "POST /v1/betaAppReviewSubmissions",
364 ]);
365 expect(server.writes.at(-1)?.body).toEqual({
366 data: {
367 type: "betaAppReviewSubmissions",
368 relationships: { build: linkage("builds", "build-46") },
369 },
370 });
371 await server.client.publish(selection, notes);
372 expect(server.writes).toHaveLength(5);
373 });
374
375 it("notifies an approved build once and rereads the resulting testing state", async () => {
376 const server = mockServer({ externalState: "BETA_APPROVED", reviewState: "APPROVED" });
377 const result = await server.client.publish(selection, notes);
378 expect(result.publicTesting).toBe(true);
379 expect(server.writes.map((item) => item.path)).toEqual(["/v1/buildBetaNotifications"]);
380 await server.client.publish(selection, notes);
381 expect(server.writes).toHaveLength(1);
382 });
383
384 it("leaves automatic notification alone when a new review immediately becomes approved", async () => {
385 const server = mockServer({
386 externalState: "READY_FOR_BETA_SUBMISSION",
387 approveImmediately: true,
388 });
389 const result = await server.client.publish(selection, notes);
390 expect(result.externalState).toBe("BETA_APPROVED");
391 expect(result.publicTesting).toBe(false);
392 expect(server.writes.map((item) => item.path)).toEqual(["/v1/betaAppReviewSubmissions"]);
393 });
394
395 it("checks missing review linkage before deciding whether a submission exists", async () => {
396 const server = mockServer({
397 externalState: "READY_FOR_BETA_SUBMISSION",
398 reviewState: "WAITING_FOR_REVIEW",
399 sparseBetaRelations: true,
400 });
401 const result = await server.client.publish(selection, notes);
402 expect(result.reviewState).toBe("WAITING_FOR_REVIEW");
403 expect(server.writes).toEqual([]);
404 });
405
406 it.each([
407 { processingState: "PROCESSING" },
408 { externalState: "MISSING_EXPORT_COMPLIANCE" },
409 { externalState: "BETA_REJECTED", reviewState: "REJECTED" },
410 { buildExists: false },
411 ])("fails before writes for a build that is not ready: %j", async (options) => {
412 const server = mockServer(options);
413 await expect(server.client.publish(selection, notes)).rejects.toThrow();
414 expect(server.writes).toEqual([]);
415 });
416
417 it("does not retry a write when the response is lost", async () => {
418 const server = mockServer({ assigned: ["public"], failAfterGroupAssignment: true });
419 await expect(server.client.publish(selection, notes)).rejects.toThrow(
420 "The write was not retried",
421 );
422 expect(server.writes).toHaveLength(1);
423 expect(server.state.assigned.has("internal")).toBe(true);
424 await server.client.publish(selection, notes);
425 expect(server.writes).toHaveLength(1);
426 });
427
428 it("refuses another upload of a build that Apple already has", async () => {
429 const server = mockServer();
430 await expect(server.client.verifyUpload(selection)).rejects.toThrow("already exists");
431 expect(server.writes).toEqual([]);
432 });
433
434 it("verifies app and groups before allowing a new upload", async () => {
435 const server = mockServer({ buildExists: false });
436 await expect(server.client.verifyUpload(selection)).resolves.toBeUndefined();
437 expect(server.writes).toEqual([]);
438 });
439});
440
441describe("release command input", () => {
442 const info = {
443 CFBundleIdentifier: "com.t3tools.t3code.swiftui",
444 DTPlatformName: "iphoneos",
445 CFBundleVersion: "46",
446 CFBundleShortVersionString: "0.1.0",
447 };
448 const exportOptions = {
449 method: "app-store-connect",
450 destination: "upload",
451 manageAppVersionAndBuildNumber: false,
452 };
453
454 it("reads an exact Release build from archive metadata", () => {
455 expect(validateUploadMetadata(info, exportOptions)).toEqual(selection);
456 });
457
458 it.each([
459 { ...info, CFBundleIdentifier: "com.t3tools.t3code.swiftui.dev" },
460 { ...info, DTPlatformName: "iphonesimulator" },
461 ])("rejects a dev or simulator archive", (metadata) => {
462 expect(() => validateUploadMetadata(metadata, exportOptions)).toThrow("Release SwiftUI app");
463 });
464
465 it.each([
466 { ...exportOptions, destination: "export" },
467 { ...exportOptions, manageAppVersionAndBuildNumber: true },
468 { ...exportOptions, testFlightInternalTestingOnly: true },
469 ])("rejects export options that would change or restrict the release", (options) => {
470 expect(() => validateUploadMetadata(info, options)).toThrow();
471 });
472
473 it("requires explicit release notes for publication", () => {
474 expect(() => parseTestFlightArgs(["publish", "--build", "46", "--version", "0.1.0"])).toThrow(
475 "--notes-file",
476 );
477 expect(
478 parseTestFlightArgs([
479 "status",
480 "--build",
481 "46",
482 "--version",
483 "0.1.0",
484 "--env-file",
485 "/tmp/.env.testflight.local",
486 ]),
487 ).toMatchObject({ command: "status", ...selection, envFile: "/tmp/.env.testflight.local" });
488 });
489
490 it("requires supplied export options and reads upload versions only from the archive", () => {
491 expect(
492 parseTestFlightArgs([
493 "upload",
494 "--archive",
495 "/tmp/Test.xcarchive",
496 "--export-options",
497 "/tmp/ExportOptions.plist",
498 ]),
499 ).toMatchObject({
500 command: "upload",
501 archive: "/tmp/Test.xcarchive",
502 exportOptions: "/tmp/ExportOptions.plist",
503 });
504 expect(() =>
505 parseTestFlightArgs([
506 "upload",
507 "--archive",
508 "/tmp/Test.xcarchive",
509 "--export-options",
510 "/tmp/ExportOptions.plist",
511 "--build",
512 "47",
513 ]),
514 ).toThrow("reads the build and version from the archive");
515 });
516});