@sitepong/fastnode 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +148 -0
  2. package/dist/actions/index.cjs +964 -137
  3. package/dist/actions/index.cjs.map +1 -1
  4. package/dist/actions/index.mjs +964 -137
  5. package/dist/actions/index.mjs.map +1 -1
  6. package/dist/cert/index.cjs +40 -0
  7. package/dist/cert/index.cjs.map +1 -1
  8. package/dist/cert/index.d.cts +3 -3
  9. package/dist/cert/index.d.ts +3 -3
  10. package/dist/cert/index.mjs +37 -1
  11. package/dist/cert/index.mjs.map +1 -1
  12. package/dist/{cert-BmJGtYtb.d.cts → cert-6m1R8UeW.d.cts} +1 -1
  13. package/dist/{cert-owkOFNW8.d.ts → cert-DtYDJBjG.d.ts} +1 -1
  14. package/dist/cli/index.cjs +964 -137
  15. package/dist/cli/index.cjs.map +1 -1
  16. package/dist/cli/index.d.cts +1 -1
  17. package/dist/cli/index.d.ts +1 -1
  18. package/dist/cli/index.mjs +964 -137
  19. package/dist/cli/index.mjs.map +1 -1
  20. package/dist/client/index.cjs +730 -109
  21. package/dist/client/index.cjs.map +1 -1
  22. package/dist/client/index.d.cts +1 -1
  23. package/dist/client/index.d.ts +1 -1
  24. package/dist/client/index.mjs +726 -110
  25. package/dist/client/index.mjs.map +1 -1
  26. package/dist/deliver/index.d.cts +2 -2
  27. package/dist/deliver/index.d.ts +2 -2
  28. package/dist/index-AD8QXY1T.d.cts +158 -0
  29. package/dist/{index-DfCUVJX1.d.cts → index-BW8wQUGC.d.cts} +1 -1
  30. package/dist/{index-EcVvViW8.d.cts → index-BWK-T2-S.d.cts} +1 -1
  31. package/dist/{index-B0yhu_LZ.d.ts → index-BpiEBPVd.d.ts} +1 -1
  32. package/dist/index-CCs5irG7.d.cts +61 -0
  33. package/dist/{index-B9yXicrQ.d.ts → index-CLsvyTkh.d.ts} +1 -1
  34. package/dist/{index-BLubSlgK.d.cts → index-CMH_GpN9.d.cts} +358 -2
  35. package/dist/index-CQKpbHZt.d.ts +61 -0
  36. package/dist/{index-BQJIJlK7.d.cts → index-CQd4bo3G.d.cts} +3 -3
  37. package/dist/{index-CWNLnSOL.d.cts → index-CdYdwxpQ.d.cts} +1 -1
  38. package/dist/{index-BFdNOmPJ.d.cts → index-Ce-WMV7c.d.cts} +1 -1
  39. package/dist/{index-TfXqwuac.d.ts → index-CojSGJ7m.d.ts} +1 -1
  40. package/dist/{index-1Vu2cRQ2.d.ts → index-CsFIp7OO.d.ts} +1 -1
  41. package/dist/{index-D1Izm7qt.d.ts → index-D2z7RiAM.d.ts} +358 -2
  42. package/dist/index-D82CmjMP.d.ts +158 -0
  43. package/dist/{index-BN0ubxjZ.d.ts → index-DZaPkUnC.d.ts} +3 -3
  44. package/dist/{index-D5eihzwM.d.cts → index-KCB2q1-8.d.cts} +1 -1
  45. package/dist/{index-A5MimeQk.d.ts → index-Kq3rbG0u.d.ts} +1 -1
  46. package/dist/index.cjs +1322 -138
  47. package/dist/index.cjs.map +1 -1
  48. package/dist/index.d.cts +199 -10
  49. package/dist/index.d.ts +199 -10
  50. package/dist/index.mjs +1319 -139
  51. package/dist/index.mjs.map +1 -1
  52. package/dist/lane/index.cjs +964 -137
  53. package/dist/lane/index.cjs.map +1 -1
  54. package/dist/lane/index.mjs +964 -137
  55. package/dist/lane/index.mjs.map +1 -1
  56. package/dist/match/index.d.cts +4 -4
  57. package/dist/match/index.d.ts +4 -4
  58. package/dist/pem/index.d.cts +2 -2
  59. package/dist/pem/index.d.ts +2 -2
  60. package/dist/pilot/index.cjs +190 -12
  61. package/dist/pilot/index.cjs.map +1 -1
  62. package/dist/pilot/index.d.cts +2 -2
  63. package/dist/pilot/index.d.ts +2 -2
  64. package/dist/pilot/index.mjs +186 -14
  65. package/dist/pilot/index.mjs.map +1 -1
  66. package/dist/precheck/index.d.cts +2 -2
  67. package/dist/precheck/index.d.ts +2 -2
  68. package/dist/produce/index.d.cts +2 -2
  69. package/dist/produce/index.d.ts +2 -2
  70. package/dist/sigh/index.d.cts +2 -2
  71. package/dist/sigh/index.d.ts +2 -2
  72. package/package.json +3 -1
  73. package/dist/index-DfirmFbC.d.ts +0 -32
  74. package/dist/index-DkvinY7_.d.ts +0 -54
  75. package/dist/index-HRiaaX-Q.d.cts +0 -54
  76. package/dist/index-lt819Jgj.d.cts +0 -32
@@ -184,8 +184,8 @@ async function revokeExpiredCertificates(options) {
184
184
  return count;
185
185
  }
186
186
  async function importToKeychain(certData, keychainPath, keychainPassword) {
187
- const { tmpdir: tmpdir7 } = await import('os');
188
- const tempCertPath = join(tmpdir7(), `fastnode-cert-${Date.now()}.cer`);
187
+ const { tmpdir: tmpdir8 } = await import('os');
188
+ const tempCertPath = join(tmpdir8(), `fastnode-cert-${Date.now()}.cer`);
189
189
  await writeFile(tempCertPath, certData);
190
190
  try {
191
191
  const args = [
@@ -1617,14 +1617,14 @@ var init_building = __esm({
1617
1617
  name: "clean_build_artifacts",
1618
1618
  description: "Remove build artifacts (IPA, dSYM, etc.)",
1619
1619
  async run(params, ctx) {
1620
- const { rm: rm2 } = await import('fs/promises');
1620
+ const { rm: rm4 } = await import('fs/promises');
1621
1621
  const paths = [
1622
1622
  ctx.get("IPA_OUTPUT_PATH"),
1623
1623
  ctx.get("PKG_OUTPUT_PATH"),
1624
1624
  ctx.get("DSYM_OUTPUT_PATH")
1625
1625
  ].filter(Boolean);
1626
1626
  for (const p of paths) {
1627
- await rm2(p, { force: true }).catch(() => {
1627
+ await rm4(p, { force: true }).catch(() => {
1628
1628
  });
1629
1629
  }
1630
1630
  return { cleaned: paths };
@@ -1783,9 +1783,9 @@ Please accept the agreement at https://developer.apple.com/account before contin
1783
1783
  throw new Error(msg);
1784
1784
  }
1785
1785
  }
1786
- async function loginWithAppleId(config) {
1787
- const log = config.onLog ?? console.log;
1788
- const promptFn = config.onPrompt ?? defaultPrompt;
1786
+ async function beginLogin(config) {
1787
+ const log = config.onLog ?? (() => {
1788
+ });
1789
1789
  log("Fetching Apple service key...");
1790
1790
  const serviceKey = await fetchServiceKey();
1791
1791
  const initRes = await fetch(`${AUTH_BASE}/signin?widgetKey=${serviceKey}`, {
@@ -1802,27 +1802,94 @@ async function loginWithAppleId(config) {
1802
1802
  const cookieStr = Object.entries(initCookies).map(([k, v]) => k.startsWith("DES") ? `${k}="${v}"` : `${k}=${v}`).join("; ");
1803
1803
  log("Starting SIRP Apple ID login...");
1804
1804
  const response = await doSirp(config.email, config.password, serviceKey, cookieStr, hashcash);
1805
- const session = {
1805
+ const baseState = {
1806
1806
  cookies: { ...initCookies, ...response.cookies },
1807
1807
  sessionId: response.sessionId,
1808
1808
  scnt: response.scnt,
1809
1809
  serviceKey,
1810
- userEmail: config.email,
1811
- pendingAgreements: []
1810
+ userEmail: config.email
1812
1811
  };
1813
1812
  if (response.status === 403) {
1814
1813
  throw new Error(`Invalid username and password combination. Used '${config.email}' as the username.`);
1815
- } else if (response.status === 200) {
1816
- log("Login successful.");
1817
- await fetchOlympusSession(session);
1818
- } else if (response.status === 409) {
1819
- await handleTwoStepOrFactor(session, log, promptFn);
1820
- await fetchOlympusSession(session);
1821
- } else if (response.status === 412) {
1814
+ }
1815
+ if (response.status === 412) {
1822
1816
  throw new Error("Need to acknowledge Apple's Apple ID and Privacy statement. Please manually log into https://appleid.apple.com.");
1817
+ }
1818
+ if (response.status === 200) {
1819
+ log("Login successful (no 2FA).");
1820
+ const session = { ...baseState, pendingAgreements: [] };
1821
+ await finalizeSession(session, log);
1822
+ return { kind: "logged_in", session };
1823
+ }
1824
+ if (response.status === 409) {
1825
+ log("2FA required, fetching challenge...");
1826
+ const challenge = await fetchTwoFactorChallenge(baseState);
1827
+ return { kind: "needs_2fa", pending: baseState, challenge };
1828
+ }
1829
+ throw new Error(`Unexpected login response (${response.status}): ${JSON.stringify(response.body).slice(0, 500)}`);
1830
+ }
1831
+ async function fetchTwoFactorChallenge(pending) {
1832
+ const r = await fetch(`${AUTH_BASE}`, { headers: buildAuthHeadersFromPending(pending) });
1833
+ const body = await r.json();
1834
+ const trustedPhoneNumbers = (body.trustedPhoneNumbers ?? []).map((p) => ({
1835
+ id: p.id,
1836
+ numberWithDialCode: p.numberWithDialCode,
1837
+ pushMode: p.pushMode
1838
+ }));
1839
+ const phoneOnly = body.noTrustedDevices === true;
1840
+ const codeLength = body.securityCode?.length ?? 6;
1841
+ return {
1842
+ kind: phoneOnly ? "phone_only" : "device",
1843
+ codeLength,
1844
+ trustedPhoneNumbers
1845
+ };
1846
+ }
1847
+ async function requestSmsCode(input) {
1848
+ await fetch(`${AUTH_BASE}/verify/phone`, {
1849
+ method: "PUT",
1850
+ headers: { ...buildAuthHeadersFromPending(input.pending), "Content-Type": "application/json" },
1851
+ body: JSON.stringify({ phoneNumber: { id: input.phoneId }, mode: input.mode ?? "sms" })
1852
+ });
1853
+ }
1854
+ async function submitTwoFactorCode(input) {
1855
+ const log = input.onLog ?? (() => {
1856
+ });
1857
+ let path;
1858
+ let body;
1859
+ if (input.source === "device") {
1860
+ path = `${AUTH_BASE}/verify/trusteddevice/securitycode`;
1861
+ body = JSON.stringify({ securityCode: { code: input.code } });
1823
1862
  } else {
1824
- throw new Error(`Unexpected login response (${response.status}): ${JSON.stringify(response.body).slice(0, 500)}`);
1863
+ if (input.phoneId == null) throw new Error("phoneId is required when source='phone'");
1864
+ path = `${AUTH_BASE}/verify/phone/securitycode`;
1865
+ body = JSON.stringify({
1866
+ securityCode: { code: input.code },
1867
+ phoneNumber: { id: input.phoneId },
1868
+ mode: input.mode ?? "sms"
1869
+ });
1825
1870
  }
1871
+ log("Submitting 2FA code...");
1872
+ const verifyRes = await fetch(path, {
1873
+ method: "POST",
1874
+ headers: { ...buildAuthHeadersFromPending(input.pending), "Content-Type": "application/json" },
1875
+ body
1876
+ });
1877
+ if (!verifyRes.ok) {
1878
+ const err = await verifyRes.json().catch(() => ({}));
1879
+ const msgs = (err?.service_errors ?? err?.serviceErrors ?? []).map((e) => e.message).filter(Boolean);
1880
+ throw new Error(msgs.join("; ") || `Verification failed (${verifyRes.status})`);
1881
+ }
1882
+ const session = {
1883
+ ...input.pending,
1884
+ cookies: { ...input.pending.cookies, ...parseCookies(verifyRes.headers) },
1885
+ pendingAgreements: []
1886
+ };
1887
+ await trustSession(session);
1888
+ await finalizeSession(session, log);
1889
+ return session;
1890
+ }
1891
+ async function finalizeSession(session, log) {
1892
+ await fetchOlympusSession(session);
1826
1893
  const agreements = await fetchContractMessages(session);
1827
1894
  if (agreements.length > 0) {
1828
1895
  for (const msg of agreements) {
@@ -1831,7 +1898,53 @@ async function loginWithAppleId(config) {
1831
1898
  }
1832
1899
  session.pendingAgreements = agreements;
1833
1900
  log(`Logged in as ${session.userEmail}`);
1834
- return session;
1901
+ }
1902
+ async function loginWithAppleId(config) {
1903
+ const log = config.onLog ?? console.log;
1904
+ const promptFn = config.onPrompt ?? defaultPrompt;
1905
+ const result = await beginLogin({ email: config.email, password: config.password, onLog: log });
1906
+ if (result.kind === "logged_in") return result.session;
1907
+ const { pending, challenge } = result;
1908
+ const phones = challenge.trustedPhoneNumbers;
1909
+ if (challenge.kind === "device") {
1910
+ log("Two-factor Authentication (6 digit code) is enabled for this account");
1911
+ log("(Input 'sms' to escape this prompt and select a trusted phone number to send the code as a text message)");
1912
+ const input = await promptFn(`Please enter the ${challenge.codeLength} digit code: `);
1913
+ if (input.toLowerCase() === "sms") {
1914
+ log("Please select a trusted phone number:");
1915
+ for (let i = 0; i < phones.length; i++) log(` ${i + 1}. ${phones[i].numberWithDialCode}`);
1916
+ const choice2 = await promptFn("Enter number: ");
1917
+ const phone2 = phones[Math.max(0, parseInt(choice2, 10) - 1)] ?? phones[0];
1918
+ await requestSmsCode({ pending, phoneId: phone2.id, mode: phone2.pushMode });
1919
+ log(`Code sent to ${phone2.numberWithDialCode}`);
1920
+ const code2 = await promptFn(`Please enter the ${challenge.codeLength} digit code: `);
1921
+ return submitTwoFactorCode({ pending, code: code2, source: "phone", phoneId: phone2.id, mode: phone2.pushMode ?? "sms", onLog: log });
1922
+ }
1923
+ return submitTwoFactorCode({ pending, code: input, source: "device", onLog: log });
1924
+ }
1925
+ log("Two-factor Authentication (6 digit code) is enabled for this account");
1926
+ if (phones.length === 1) {
1927
+ const phone2 = phones[0];
1928
+ log(`Code automatically sent to ${phone2.numberWithDialCode}`);
1929
+ const code2 = await promptFn(`Please enter the ${challenge.codeLength} digit code: `);
1930
+ return submitTwoFactorCode({ pending, code: code2, source: "phone", phoneId: phone2.id, mode: phone2.pushMode ?? "sms", onLog: log });
1931
+ }
1932
+ log("Please select a trusted phone number:");
1933
+ for (let i = 0; i < phones.length; i++) log(` ${i + 1}. ${phones[i].numberWithDialCode}`);
1934
+ const choice = await promptFn("Enter number: ");
1935
+ const phone = phones[Math.max(0, parseInt(choice, 10) - 1)] ?? phones[0];
1936
+ await requestSmsCode({ pending, phoneId: phone.id, mode: phone.pushMode });
1937
+ log(`Code sent to ${phone.numberWithDialCode}`);
1938
+ const code = await promptFn(`Please enter the ${challenge.codeLength} digit code: `);
1939
+ return submitTwoFactorCode({ pending, code, source: "phone", phoneId: phone.id, mode: phone.pushMode ?? "sms", onLog: log });
1940
+ }
1941
+ function buildAuthHeadersFromPending(pending) {
1942
+ const h = { "X-Apple-Widget-Key": pending.serviceKey, Accept: "application/json" };
1943
+ if (pending.sessionId) h["X-Apple-Id-Session-Id"] = pending.sessionId;
1944
+ if (pending.scnt) h["scnt"] = pending.scnt;
1945
+ const c = Object.entries(pending.cookies).map(([k, v]) => `${k}=${v}`).join("; ");
1946
+ if (c) h["Cookie"] = c;
1947
+ return h;
1835
1948
  }
1836
1949
  async function doSirp(user, password, serviceKey, cookieStr, hashcash) {
1837
1950
  const client = new SRPClient(2048);
@@ -1887,99 +2000,6 @@ async function doSirp(user, password, serviceKey, cookieStr, hashcash) {
1887
2000
  scnt: completeRes.headers.get("scnt") ?? ""
1888
2001
  };
1889
2002
  }
1890
- async function handleTwoStepOrFactor(session, log, promptFn) {
1891
- const r = await fetch(`${AUTH_BASE}`, { headers: buildAuthHeaders(session) });
1892
- const body = await r.json();
1893
- if (body.trustedDevices?.length > 0) {
1894
- await handleTwoStep(session, body, log, promptFn);
1895
- } else if (body.trustedPhoneNumbers?.length > 0) {
1896
- await handleTwoFactor(session, body, log, promptFn);
1897
- } else {
1898
- throw new Error("2FA required but no trusted devices or phone numbers found.");
1899
- }
1900
- }
1901
- async function handleTwoFactor(session, authBody, log, promptFn) {
1902
- log("Two-factor Authentication (6 digit code) is enabled for this account");
1903
- const codeLength = authBody.securityCode?.length ?? 6;
1904
- const phones = authBody.trustedPhoneNumbers ?? [];
1905
- const noTrusted = authBody.noTrustedDevices === true;
1906
- let codeType;
1907
- let reqBody;
1908
- if (noTrusted && phones.length === 1) {
1909
- const phone = phones[0];
1910
- log(`Code automatically sent to ${phone.numberWithDialCode}`);
1911
- const code = await promptFn(`Please enter the ${codeLength} digit code you received at ${phone.numberWithDialCode}: `);
1912
- codeType = "phone";
1913
- reqBody = JSON.stringify({ securityCode: { code }, phoneNumber: { id: phone.id }, mode: phone.pushMode ?? "sms" });
1914
- } else if (noTrusted) {
1915
- const phone = await choosePhone(phones, log, promptFn);
1916
- await requestPhoneCode(session, phone);
1917
- log(`Successfully requested text message to ${phone.numberWithDialCode}`);
1918
- const code = await promptFn(`Please enter the ${codeLength} digit code: `);
1919
- codeType = "phone";
1920
- reqBody = JSON.stringify({ securityCode: { code }, phoneNumber: { id: phone.id }, mode: phone.pushMode ?? "sms" });
1921
- } else {
1922
- log("(Input 'sms' to escape this prompt and select a trusted phone number to send the code as a text message)");
1923
- const input = await promptFn(`Please enter the ${codeLength} digit code: `);
1924
- if (input.toLowerCase() === "sms") {
1925
- const phone = await choosePhone(phones, log, promptFn);
1926
- await requestPhoneCode(session, phone);
1927
- const code = await promptFn(`Please enter the ${codeLength} digit code sent to ${phone.numberWithDialCode}: `);
1928
- codeType = "phone";
1929
- reqBody = JSON.stringify({ securityCode: { code }, phoneNumber: { id: phone.id }, mode: phone.pushMode ?? "sms" });
1930
- } else {
1931
- codeType = "trusteddevice";
1932
- reqBody = JSON.stringify({ securityCode: { code: input } });
1933
- }
1934
- }
1935
- log("Requesting session...");
1936
- const verifyRes = await fetch(`${AUTH_BASE}/verify/${codeType}/securitycode`, {
1937
- method: "POST",
1938
- headers: { ...buildAuthHeaders(session), "Content-Type": "application/json" },
1939
- body: reqBody
1940
- });
1941
- if (!verifyRes.ok) {
1942
- const err = await verifyRes.json().catch(() => ({}));
1943
- const msgs = (err?.service_errors ?? err?.serviceErrors ?? []).map((e) => e.message).filter(Boolean);
1944
- throw new Error(msgs.join("; ") || `Verification failed (${verifyRes.status})`);
1945
- }
1946
- Object.assign(session.cookies, parseCookies(verifyRes.headers));
1947
- await trustSession(session);
1948
- }
1949
- async function handleTwoStep(session, authBody, log, promptFn) {
1950
- log("Two-step Verification (4 digit code) is enabled for this account");
1951
- const devices = authBody.trustedDevices ?? [];
1952
- log("Please select a trusted device:");
1953
- for (let i = 0; i < devices.length; i++) {
1954
- log(` ${i + 1}. ${devices[i].name} ${devices[i].modelName ?? "SMS"} (${devices[i].id})`);
1955
- }
1956
- const choice = await promptFn("Enter device number: ");
1957
- const device = devices[Math.max(0, parseInt(choice, 10) - 1)] ?? devices[0];
1958
- await fetch(`${AUTH_BASE}/verify/device/${device.id}/securitycode`, { method: "PUT", headers: buildAuthHeaders(session) });
1959
- log("Successfully requested notification");
1960
- const code = await promptFn("Please enter the 4 digit code: ");
1961
- const verifyRes = await fetch(`${AUTH_BASE}/verify/phone/securitycode`, {
1962
- method: "POST",
1963
- headers: { ...buildAuthHeaders(session), "Content-Type": "application/json" },
1964
- body: JSON.stringify({ phoneNumber: { id: device.id }, securityCode: { code }, mode: "sms" })
1965
- });
1966
- if (!verifyRes.ok) throw new Error("Incorrect verification code.");
1967
- Object.assign(session.cookies, parseCookies(verifyRes.headers));
1968
- await trustSession(session);
1969
- }
1970
- async function choosePhone(phones, log, promptFn) {
1971
- log("Please select a trusted phone number:");
1972
- for (let i = 0; i < phones.length; i++) log(` ${i + 1}. ${phones[i].numberWithDialCode}`);
1973
- const choice = await promptFn("Enter number: ");
1974
- return phones[Math.max(0, parseInt(choice, 10) - 1)] ?? phones[0];
1975
- }
1976
- async function requestPhoneCode(session, phone) {
1977
- await fetch(`${AUTH_BASE}/verify/phone`, {
1978
- method: "PUT",
1979
- headers: { ...buildAuthHeaders(session), "Content-Type": "application/json" },
1980
- body: JSON.stringify({ phoneNumber: { id: phone.id }, mode: phone.pushMode ?? "sms" })
1981
- });
1982
- }
1983
2003
  async function trustSession(session) {
1984
2004
  const r = await fetch(`${AUTH_BASE}/2sv/trust`, { headers: buildAuthHeaders(session) });
1985
2005
  Object.assign(session.cookies, parseCookies(r.headers));
@@ -2271,23 +2291,13 @@ var init_request = __esm({
2271
2291
  };
2272
2292
  }
2273
2293
  });
2274
-
2275
- // src/pilot/index.ts
2276
- var pilot_exports = {};
2277
- __export(pilot_exports, {
2278
- distributeToGroups: () => distributeToGroups,
2279
- expireBuild: () => expireBuild,
2280
- setChangelog: () => setChangelog,
2281
- uploadToTestFlight: () => uploadToTestFlight,
2282
- waitForProcessing: () => waitForProcessing
2283
- });
2284
- async function uploadToTestFlight(options) {
2294
+ async function uploadWithAltool(options) {
2285
2295
  if (!existsSync(options.ipaPath)) {
2286
2296
  throw new Error(`File not found: ${options.ipaPath}`);
2287
2297
  }
2288
2298
  const platform = options.platform ?? "ios";
2289
2299
  const timeout = options.timeout ?? 18e5;
2290
- const keyDir = await mkdtemp(join(tmpdir(), "fastnode-key-"));
2300
+ const keyDir = await mkdtemp(join(tmpdir(), "fastnode-altool-"));
2291
2301
  const keyPath = join(keyDir, `AuthKey_${options.apiKeyId}.p8`);
2292
2302
  await writeFile(keyPath, options.apiPrivateKey);
2293
2303
  return new Promise((resolve4) => {
@@ -2311,24 +2321,228 @@ async function uploadToTestFlight(options) {
2311
2321
  const timer = setTimeout(() => {
2312
2322
  child.kill("SIGTERM");
2313
2323
  }, timeout);
2314
- child.stdout.on("data", (data) => {
2324
+ const onData = (data) => {
2315
2325
  const chunk = data.toString();
2316
2326
  output += chunk;
2317
2327
  options.onOutput?.(chunk);
2328
+ };
2329
+ child.stdout.on("data", onData);
2330
+ child.stderr.on("data", onData);
2331
+ child.on("close", async (code) => {
2332
+ clearTimeout(timer);
2333
+ await unlink(keyPath).catch(() => {
2334
+ });
2335
+ await rm(keyDir, { recursive: true, force: true }).catch(() => {
2336
+ });
2337
+ resolve4({ success: code === 0, output, backend: "altool" });
2318
2338
  });
2319
- child.stderr.on("data", (data) => {
2339
+ });
2340
+ }
2341
+ var init_upload_altool = __esm({
2342
+ "src/pilot/upload-altool.ts"() {
2343
+ }
2344
+ });
2345
+ async function resolveTransporter() {
2346
+ const override = process.env.ITMSTRANSPORTER_BIN;
2347
+ if (override) {
2348
+ if (!existsSync(override)) {
2349
+ throw new Error(
2350
+ `ITMSTRANSPORTER_BIN is set to "${override}" but that path does not exist.`
2351
+ );
2352
+ }
2353
+ return override;
2354
+ }
2355
+ const candidates = process.platform === "darwin" ? [
2356
+ // Xcode 15+: Transporter.app bundled with Xcode
2357
+ "/Applications/Xcode.app/Contents/SharedFrameworks/ContentDeliveryServices.framework/Versions/A/itms/bin/iTMSTransporter",
2358
+ // Standalone Transporter.app from the Mac App Store
2359
+ "/Applications/Transporter.app/Contents/itms/bin/iTMSTransporter"
2360
+ ] : [
2361
+ "/usr/local/itms/bin/iTMSTransporter",
2362
+ "/opt/itms/bin/iTMSTransporter",
2363
+ "/usr/local/bin/iTMSTransporter"
2364
+ ];
2365
+ for (const path of candidates) {
2366
+ if (existsSync(path)) return path;
2367
+ }
2368
+ throw new Error(
2369
+ [
2370
+ "iTMSTransporter not found.",
2371
+ "",
2372
+ "Install options:",
2373
+ process.platform === "darwin" ? " - Install Xcode (includes Transporter)" : " - Download Apple's standalone iTMSTransporter package for Linux",
2374
+ " - Or set ITMSTRANSPORTER_BIN to the absolute path of the binary",
2375
+ "",
2376
+ `Searched: ${candidates.join(", ")}`
2377
+ ].join("\n")
2378
+ );
2379
+ }
2380
+ async function verifyJava() {
2381
+ return new Promise((resolve4, reject) => {
2382
+ const child = spawn("java", ["-version"], { stdio: ["ignore", "pipe", "pipe"] });
2383
+ let stderr = "";
2384
+ child.stderr.on("data", (d) => {
2385
+ stderr += d.toString();
2386
+ });
2387
+ child.on("error", (err) => {
2388
+ reject(
2389
+ new Error(
2390
+ `java not found on PATH (${err.message}). Install Java 17 LTS and ensure it is on PATH.`
2391
+ )
2392
+ );
2393
+ });
2394
+ child.on("close", (code) => {
2395
+ if (code !== 0) {
2396
+ reject(new Error(`java -version exited ${code}: ${stderr}`));
2397
+ return;
2398
+ }
2399
+ const match = stderr.match(/version "([^"]+)"/);
2400
+ resolve4({ version: match?.[1] ?? "unknown" });
2401
+ });
2402
+ });
2403
+ }
2404
+ var init_transporter_install = __esm({
2405
+ "src/pilot/transporter-install.ts"() {
2406
+ }
2407
+ });
2408
+ async function uploadWithTransporter(options) {
2409
+ if (!existsSync(options.ipaPath)) {
2410
+ throw new Error(`File not found: ${options.ipaPath}`);
2411
+ }
2412
+ await verifyJava();
2413
+ const transporterBin = await resolveTransporter();
2414
+ const platform = options.platform ?? "ios";
2415
+ const timeout = options.timeout ?? 18e5;
2416
+ const keyDir = await mkdtemp(join(tmpdir(), "fastnode-itms-"));
2417
+ const keyPath = join(keyDir, `AuthKey_${options.apiKeyId}.p8`);
2418
+ await writeFile(keyPath, options.apiPrivateKey);
2419
+ return new Promise((resolve4) => {
2420
+ const args = [
2421
+ "-m",
2422
+ "upload",
2423
+ "-assetFile",
2424
+ options.ipaPath,
2425
+ "-apiKey",
2426
+ options.apiKeyId,
2427
+ "-apiIssuer",
2428
+ options.apiIssuerId,
2429
+ // WONoPause prevents the JVM from waiting on stdin in non-TTY
2430
+ // environments (CI, LaunchAgent) where it would hang forever.
2431
+ "-WONoPause",
2432
+ "true"
2433
+ ];
2434
+ if (platform !== "ios") {
2435
+ args.push("-bundleType", platform);
2436
+ }
2437
+ const child = spawn(transporterBin, args, {
2438
+ env: {
2439
+ ...process.env,
2440
+ API_PRIVATE_KEYS_DIR: keyDir
2441
+ },
2442
+ stdio: ["ignore", "pipe", "pipe"]
2443
+ });
2444
+ let output = "";
2445
+ const timer = setTimeout(() => {
2446
+ child.kill("SIGTERM");
2447
+ }, timeout);
2448
+ const onData = (data) => {
2320
2449
  const chunk = data.toString();
2321
2450
  output += chunk;
2322
2451
  options.onOutput?.(chunk);
2323
- });
2452
+ };
2453
+ child.stdout.on("data", onData);
2454
+ child.stderr.on("data", onData);
2324
2455
  child.on("close", async (code) => {
2325
2456
  clearTimeout(timer);
2326
- await unlink(keyPath).catch(() => {
2457
+ await rm(keyDir, { recursive: true, force: true }).catch(() => {
2458
+ });
2459
+ resolve4({ success: code === 0, output, backend: "transporter" });
2460
+ });
2461
+ child.on("error", async (err) => {
2462
+ clearTimeout(timer);
2463
+ await rm(keyDir, { recursive: true, force: true }).catch(() => {
2464
+ });
2465
+ resolve4({
2466
+ success: false,
2467
+ output: output + `
2468
+ Process error: ${err.message}`,
2469
+ backend: "transporter"
2327
2470
  });
2328
- resolve4({ success: code === 0, output });
2329
2471
  });
2330
2472
  });
2331
2473
  }
2474
+ var init_upload_transporter = __esm({
2475
+ "src/pilot/upload-transporter.ts"() {
2476
+ init_transporter_install();
2477
+ }
2478
+ });
2479
+
2480
+ // src/pilot/classify.ts
2481
+ function classifyUploadError(output) {
2482
+ for (const { pattern, kind } of RULES) {
2483
+ if (pattern.test(output)) return kind;
2484
+ }
2485
+ return null;
2486
+ }
2487
+ function isTransientUploadError(output) {
2488
+ return classifyUploadError(output) !== null;
2489
+ }
2490
+ var RULES;
2491
+ var init_classify = __esm({
2492
+ "src/pilot/classify.ts"() {
2493
+ RULES = [
2494
+ // Apple's finalize-upload call returning 5xx — the most common transient
2495
+ // failure we see in practice. Example:
2496
+ // "CHANGE UPLOAD STATE TO COMPLETE (UPLOADING ASSET DESCRIPTION):
2497
+ // received status code 500; internal server error."
2498
+ { pattern: /CHANGE UPLOAD STATE TO COMPLETE/i, kind: "finalize_failed" },
2499
+ // Generic 5xx from ASC backend services
2500
+ { pattern: /status code 5\d\d/i, kind: "apple_5xx" },
2501
+ { pattern: /internal server error/i, kind: "apple_5xx" },
2502
+ { pattern: /Service Unavailable/i, kind: "apple_5xx" },
2503
+ { pattern: /Bad Gateway/i, kind: "apple_5xx" },
2504
+ // Network-level interruptions during the upload body transfer
2505
+ { pattern: /Connection reset/i, kind: "connection_reset" },
2506
+ { pattern: /SocketException/i, kind: "connection_reset" },
2507
+ { pattern: /Broken pipe/i, kind: "connection_reset" },
2508
+ // Timeouts — distinct from resets because the other side may have
2509
+ // actually processed the request, so dedupe logic may matter.
2510
+ { pattern: /Read timed out/i, kind: "network_timeout" },
2511
+ { pattern: /SocketTimeoutException/i, kind: "network_timeout" },
2512
+ { pattern: /Operation timed out/i, kind: "network_timeout" },
2513
+ // JVM-internal errors from iTMSTransporter (OOM, thread interruption, etc.)
2514
+ { pattern: /java\.lang\.OutOfMemoryError/i, kind: "transporter_jvm_error" },
2515
+ { pattern: /EOFException/i, kind: "transporter_jvm_error" }
2516
+ ];
2517
+ }
2518
+ });
2519
+
2520
+ // src/pilot/index.ts
2521
+ var pilot_exports = {};
2522
+ __export(pilot_exports, {
2523
+ classifyUploadError: () => classifyUploadError,
2524
+ distributeToGroups: () => distributeToGroups,
2525
+ expireBuild: () => expireBuild,
2526
+ isTransientUploadError: () => isTransientUploadError,
2527
+ resolveTransporter: () => resolveTransporter,
2528
+ setChangelog: () => setChangelog,
2529
+ uploadToTestFlight: () => uploadToTestFlight,
2530
+ uploadWithAltool: () => uploadWithAltool,
2531
+ uploadWithTransporter: () => uploadWithTransporter,
2532
+ verifyJava: () => verifyJava,
2533
+ waitForProcessing: () => waitForProcessing
2534
+ });
2535
+ async function uploadToTestFlight(options) {
2536
+ const backend = selectBackend(options.backend ?? "auto");
2537
+ if (backend === "altool") {
2538
+ return uploadWithAltool(options);
2539
+ }
2540
+ return uploadWithTransporter(options);
2541
+ }
2542
+ function selectBackend(pref) {
2543
+ if (pref !== "auto") return pref;
2544
+ return process.platform === "darwin" ? "altool" : "transporter";
2545
+ }
2332
2546
  async function waitForProcessing(client, params) {
2333
2547
  const timeout = params.timeout ?? 18e5;
2334
2548
  const pollInterval = params.pollInterval ?? 3e4;
@@ -2449,6 +2663,12 @@ function sleep2(ms) {
2449
2663
  var init_pilot = __esm({
2450
2664
  "src/pilot/index.ts"() {
2451
2665
  init_request();
2666
+ init_upload_altool();
2667
+ init_upload_transporter();
2668
+ init_upload_altool();
2669
+ init_upload_transporter();
2670
+ init_classify();
2671
+ init_transporter_install();
2452
2672
  }
2453
2673
  });
2454
2674
  async function loadMetadata(metadataPath) {
@@ -2536,9 +2756,9 @@ var init_metadata = __esm({
2536
2756
  // src/xcode/upload.ts
2537
2757
  var upload_exports = {};
2538
2758
  __export(upload_exports, {
2539
- uploadWithAltool: () => uploadWithAltool
2759
+ uploadWithAltool: () => uploadWithAltool2
2540
2760
  });
2541
- async function uploadWithAltool(options) {
2761
+ async function uploadWithAltool2(options) {
2542
2762
  requireMacOS("altool upload");
2543
2763
  let keyDir;
2544
2764
  if (options.apiPrivateKey && !options.apiKeyPath) {
@@ -2647,8 +2867,8 @@ async function uploadToAppStore(options) {
2647
2867
  if (!options.skipBinaryUpload) {
2648
2868
  const binaryPath = options.ipaPath ?? options.pkgPath;
2649
2869
  if (binaryPath && options.apiKeyId && options.apiIssuerId) {
2650
- const { uploadWithAltool: uploadWithAltool2 } = await Promise.resolve().then(() => (init_upload(), upload_exports));
2651
- await uploadWithAltool2({
2870
+ const { uploadWithAltool: uploadWithAltool3 } = await Promise.resolve().then(() => (init_upload(), upload_exports));
2871
+ await uploadWithAltool3({
2652
2872
  filePath: binaryPath,
2653
2873
  apiKeyId: options.apiKeyId,
2654
2874
  apiIssuerId: options.apiIssuerId,
@@ -3434,8 +3654,8 @@ async function captureScreenshots(options) {
3434
3654
  const outputDir = options.outputDirectory ?? join(process.cwd(), "screenshots");
3435
3655
  const retries = options.numberOfRetries ?? 1;
3436
3656
  if (options.clearPreviousScreenshots && existsSync(outputDir)) {
3437
- const { rm: rm2 } = await import('fs/promises');
3438
- await rm2(outputDir, { recursive: true, force: true });
3657
+ const { rm: rm4 } = await import('fs/promises');
3658
+ await rm4(outputDir, { recursive: true, force: true });
3439
3659
  }
3440
3660
  mkdirSync(outputDir, { recursive: true });
3441
3661
  const screenshots = {};
@@ -6142,6 +6362,264 @@ var init_portal = __esm({
6142
6362
  async init() {
6143
6363
  await this.post("account/listTeams.action", {});
6144
6364
  }
6365
+ /**
6366
+ * JSON POST — different content type than the standard form-encoded
6367
+ * `post()`. Used by the App Store Connect API key endpoints
6368
+ * (`account/auth/key/v2/create`), which Spaceship discovered take a
6369
+ * JSON body even though every other portal mutation is form-encoded.
6370
+ *
6371
+ * Like the form-encoded `post()`, this also runs the response through
6372
+ * `checkPortalResponse` — Apple returns HTTP 200 even for errors and
6373
+ * encodes the error in `resultCode`/`userString` fields, so a raw
6374
+ * status check would silently miss real failures.
6375
+ */
6376
+ async postJson(path, body) {
6377
+ const headers = {
6378
+ Cookie: this.cookieStr,
6379
+ "Content-Type": "application/json",
6380
+ Accept: "application/json"
6381
+ };
6382
+ if (this.csrf) {
6383
+ headers["csrf"] = this.csrf;
6384
+ headers["csrf_ts"] = this.csrfTs;
6385
+ }
6386
+ console.log(`[portal] POST(json) ${path}`);
6387
+ const res = await fetch(`${PORTAL_BASE}/${path}`, {
6388
+ method: "POST",
6389
+ headers,
6390
+ body: JSON.stringify(body)
6391
+ });
6392
+ if (res.headers.get("csrf")) {
6393
+ this.csrf = res.headers.get("csrf");
6394
+ this.csrfTs = res.headers.get("csrf_ts") ?? "";
6395
+ }
6396
+ for (const raw of res.headers.getSetCookie?.() ?? []) {
6397
+ const m = raw.match(/^([^=]+)=([^;]*)/);
6398
+ if (m && !this.cookieStr.includes(m[1] + "=")) this.cookieStr += "; " + m[1] + "=" + m[2];
6399
+ }
6400
+ const text = await res.text();
6401
+ let data = null;
6402
+ try {
6403
+ data = text ? JSON.parse(text) : null;
6404
+ } catch {
6405
+ }
6406
+ console.log(`[portal] POST(json) ${path} \u2192 ${res.status} ${text.slice(0, 400)}`);
6407
+ checkPortalResponse(data, this.session);
6408
+ return { status: res.status, body: data, rawText: text };
6409
+ }
6410
+ /**
6411
+ * GET helper for the portal endpoints that take query parameters
6412
+ * (currently just `account/auth/key/download`). Returns the raw text
6413
+ * since download endpoints can return PEMs or JSON depending on Apple's
6414
+ * mood — caller decides how to parse.
6415
+ */
6416
+ async getRaw(path, params = {}) {
6417
+ const url = new URL(`${PORTAL_BASE}/${path}`);
6418
+ for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
6419
+ const headers = {
6420
+ Cookie: this.cookieStr,
6421
+ Accept: "application/json, text/plain, application/x-pem-file, */*"
6422
+ };
6423
+ if (this.csrf) {
6424
+ headers["csrf"] = this.csrf;
6425
+ headers["csrf_ts"] = this.csrfTs;
6426
+ }
6427
+ console.log(`[portal] GET ${url.pathname}${url.search}`);
6428
+ const res = await fetch(url.toString(), { headers });
6429
+ for (const raw of res.headers.getSetCookie?.() ?? []) {
6430
+ const m = raw.match(/^([^=]+)=([^;]*)/);
6431
+ if (m && !this.cookieStr.includes(m[1] + "=")) this.cookieStr += "; " + m[1] + "=" + m[2];
6432
+ }
6433
+ const text = await res.text();
6434
+ const contentType = res.headers.get("content-type") ?? "";
6435
+ console.log(`[portal] GET ${url.pathname} \u2192 ${res.status} ${contentType} ${text.length}b`);
6436
+ return { status: res.status, rawText: text, contentType };
6437
+ }
6438
+ // ── App Store Connect API Keys (.p8) ────────────────────────────────────
6439
+ /**
6440
+ * Create an App Store Connect API key via the developer portal's
6441
+ * `account/auth/key/v2/create` endpoint. Reverse-engineered from the
6442
+ * _current_ @expo/apple-utils npm package (v2.1.21), which is what
6443
+ * EAS CLI uses to manage Apple credentials in production.
6444
+ *
6445
+ * This differs from older published reverse-engineering guides:
6446
+ * • URL uses the `/v2/create` suffix (Apple kept it)
6447
+ * • Field is `serviceConfigurations`, shape is an object keyed by
6448
+ * service id (NOT `serviceConfigurationsRequests: [...]` array)
6449
+ * • Body REQUIRES `scope: "team"`
6450
+ * • Needs a scope-specific CSRF warmup via the `keys` endpoint
6451
+ * before the create call (EAS's `ensureCSRFAsync("keys", …)`)
6452
+ *
6453
+ * For an App Store Connect API key (PUBLIC_API, used by altool for
6454
+ * TestFlight uploads), `serviceConfigurations` is an empty object `{}`.
6455
+ * For an APNs auth key, it's `{ "U27F4V844T": [] }`. For MusicKit:
6456
+ * `{ "6A7HVUVQ3M": [musicId] }`, etc.
6457
+ *
6458
+ * Apple's name validator rejects parentheses, brackets, and most
6459
+ * punctuation — sanitize to alphanumeric + space + dash + underscore
6460
+ * + period and collapse whitespace.
6461
+ */
6462
+ async createApiKey(rawName, serviceConfigurations = {}) {
6463
+ const name = rawName.replace(/[^A-Za-z0-9 _\-.]/g, " ").replace(/\s+/g, " ").trim().slice(0, 50);
6464
+ if (!name) throw new Error("createApiKey: name is empty after sanitization");
6465
+ try {
6466
+ await this.listApiKeys();
6467
+ } catch {
6468
+ }
6469
+ const body = {
6470
+ teamId: this.teamId,
6471
+ name,
6472
+ serviceConfigurations,
6473
+ scope: "team"
6474
+ };
6475
+ const result = await this.postJson("account/auth/key/v2/create", body);
6476
+ const created = result.body?.keys?.[0] ?? result.body?.key ?? result.body?.data ?? result.body;
6477
+ const keyId = created?.keyId ?? created?.id ?? created?.kid ?? created?.attributes?.kid;
6478
+ if (!keyId) {
6479
+ throw new Error(`createApiKey: no key id in response. Body: ${result.rawText.slice(0, 400)}`);
6480
+ }
6481
+ return { keyId, raw: created };
6482
+ }
6483
+ /**
6484
+ * Fetch a single API key by id via `account/auth/key/get`. Reverse-
6485
+ * engineered from Spaceship's `get_key`. Returns the raw key record so
6486
+ * the caller can extract whatever fields it needs (e.g. issuerId).
6487
+ *
6488
+ * Form-encoded POST — same shape as every other PortalClient mutation
6489
+ * except the JSON `create` endpoint.
6490
+ */
6491
+ async getApiKey(keyId) {
6492
+ const data = await this.post("account/auth/key/get", {
6493
+ teamId: this.teamId,
6494
+ keyId
6495
+ });
6496
+ return data?.keys?.[0] ?? data?.key ?? data?.data ?? data;
6497
+ }
6498
+ /**
6499
+ * Revoke an existing key. Form-encoded POST per Spaceship's
6500
+ * `revoke_key!`. Used for cleaning up orphan keys created during
6501
+ * failed wizard runs.
6502
+ */
6503
+ async revokeApiKey(keyId) {
6504
+ await this.post("account/auth/key/revoke", {
6505
+ teamId: this.teamId,
6506
+ keyId
6507
+ });
6508
+ }
6509
+ // ── APNs Authentication Keys (.p8) ──────────────────────────────────────
6510
+ /** Apple's hardcoded service id for APNs auth keys (from Spaceship). */
6511
+ static APNS_SERVICE_ID = "U27F4V844T";
6512
+ /**
6513
+ * Create an APNs Authentication Key (.p8) via the developer portal.
6514
+ *
6515
+ * Apple requires BOTH `serviceConfigurations` (the map) AND
6516
+ * `serviceConfigurationsRequests` (the array of full config objects)
6517
+ * in the v2/create body. Just sending the map alone results in
6518
+ * "No value was provided for the parameter 'serviceConfigurations'".
6519
+ *
6520
+ * The exact body comes from @expo/apple-utils v2.1.21 — both fields
6521
+ * are produced by separate functions (`d` for the map, `h` for the
6522
+ * array) and merged into the create payload.
6523
+ */
6524
+ async createApnsAuthKey(rawName) {
6525
+ const name = rawName.replace(/[^A-Za-z0-9 _\-.]/g, " ").replace(/\s+/g, " ").trim().slice(0, 50);
6526
+ if (!name) throw new Error("createApnsAuthKey: name is empty after sanitization");
6527
+ try {
6528
+ await this.listApiKeys();
6529
+ } catch {
6530
+ }
6531
+ const body = {
6532
+ teamId: this.teamId,
6533
+ name,
6534
+ serviceConfigurations: {
6535
+ [_PortalClient.APNS_SERVICE_ID]: []
6536
+ },
6537
+ serviceConfigurationsRequests: [
6538
+ {
6539
+ isNew: true,
6540
+ serviceId: _PortalClient.APNS_SERVICE_ID,
6541
+ identifiers: {},
6542
+ environment: "all",
6543
+ scope: "team"
6544
+ }
6545
+ ],
6546
+ scope: "team"
6547
+ };
6548
+ const result = await this.postJson("account/auth/key/v2/create", body);
6549
+ const created = result.body?.keys?.[0];
6550
+ if (!created?.keyId) {
6551
+ throw new Error(`createApnsAuthKey: no key id in response. Body: ${result.rawText.slice(0, 400)}`);
6552
+ }
6553
+ const pem = await this.downloadApiKey(created.keyId);
6554
+ return { keyId: created.keyId, pem, raw: created };
6555
+ }
6556
+ /**
6557
+ * Find existing APNs auth keys in the team. Used by the wizard to
6558
+ * detect "you already have one" cases and offer to reuse rather than
6559
+ * proliferate keys.
6560
+ */
6561
+ async listApnsAuthKeys() {
6562
+ const list = await this.listApiKeys();
6563
+ return (list.keys ?? []).filter(
6564
+ (k) => (k.services ?? []).some((s) => s.id === _PortalClient.APNS_SERVICE_ID || /apns/i.test(s.name ?? ""))
6565
+ ).map((k) => ({
6566
+ keyId: k.keyId,
6567
+ keyName: k.keyName,
6568
+ canDownload: Boolean(k.canDownload)
6569
+ }));
6570
+ }
6571
+ /**
6572
+ * Download an existing App Store Connect API key as PEM. Spaceship's
6573
+ * `download_key` endpoint — GET with teamId + keyId in query string.
6574
+ * Returns the raw .p8 PEM text. Apple shows the .p8 exactly once
6575
+ * (after creation), so call this immediately after createApiKey.
6576
+ */
6577
+ async downloadApiKey(keyId) {
6578
+ const { status, rawText, contentType } = await this.getRaw("account/auth/key/download", {
6579
+ teamId: this.teamId,
6580
+ keyId
6581
+ });
6582
+ if (status !== 200) {
6583
+ throw new Error(`downloadApiKey failed (${status}): ${rawText.slice(0, 200)}`);
6584
+ }
6585
+ if (rawText.includes("BEGIN PRIVATE KEY")) return rawText;
6586
+ if (contentType.includes("json")) {
6587
+ try {
6588
+ const parsed = JSON.parse(rawText);
6589
+ const candidates = [
6590
+ parsed?.privateKey,
6591
+ parsed?.key?.privateKey,
6592
+ parsed?.keys?.[0]?.privateKey,
6593
+ parsed?.data?.attributes?.privateKey,
6594
+ parsed?.value
6595
+ ];
6596
+ for (const c of candidates) {
6597
+ if (typeof c === "string" && c.includes("BEGIN PRIVATE KEY")) return c;
6598
+ }
6599
+ } catch {
6600
+ }
6601
+ }
6602
+ throw new Error(`downloadApiKey returned no PEM. Content-Type=${contentType} body=${rawText.slice(0, 300)}`);
6603
+ }
6604
+ /**
6605
+ * List existing API keys via the portal. Used to discover the team's
6606
+ * issuer id — every key in the team shares the same issuer id, and
6607
+ * altool needs it alongside the key id and .p8 file.
6608
+ *
6609
+ * Form-encoded POST (NOT JSON), with pagination params, per Spaceship's
6610
+ * `list_keys` method. JSON returned 415 from this endpoint.
6611
+ */
6612
+ async listApiKeys() {
6613
+ const data = await this.post("account/auth/key/list", {
6614
+ teamId: this.teamId,
6615
+ pageNumber: "1",
6616
+ pageSize: "500",
6617
+ sort: "name=asc"
6618
+ });
6619
+ const keys = data?.keys ?? [];
6620
+ const issuerId = data?.issuerId ?? data?.issuer ?? data?.team?.issuerId ?? keys[0]?.issuerId ?? keys[0]?.issuer;
6621
+ return { keys, issuerId };
6622
+ }
6145
6623
  async post(path, params) {
6146
6624
  const body = new URLSearchParams();
6147
6625
  for (const [k, v] of Object.entries(params)) {
@@ -6209,6 +6687,31 @@ var init_portal = __esm({
6209
6687
  async deleteAppId(appIdId) {
6210
6688
  await this.post("account/ios/identifiers/deleteAppId.action", { teamId: this.teamId, appIdId });
6211
6689
  }
6690
+ /**
6691
+ * Toggle a capability (a.k.a. "service") on a bundle ID. Mirrors
6692
+ * Spaceship::Portal's `update_service` — the legacy portal endpoint
6693
+ * still works and is the only session-cookie-authenticated way to flip
6694
+ * capabilities like Push Notifications and Sign in with Apple from
6695
+ * outside the Apple Developer web UI.
6696
+ *
6697
+ * Common service codes (from Spaceship portal/portal_client.rb):
6698
+ * push → push notifications
6699
+ * APG3427HIY → Sign in with Apple
6700
+ * IAD53UNK2F → in-app purchase
6701
+ * homeKit → HomeKit
6702
+ * healthKit → HealthKit
6703
+ *
6704
+ * @param featureType Apple's internal capability key (string code or short name)
6705
+ * @param enabled true → turn on, false → turn off
6706
+ */
6707
+ async setBundleCapability(params) {
6708
+ await this.post("account/ios/identifiers/updateAppService.action", {
6709
+ teamId: this.teamId,
6710
+ displayId: params.appIdId,
6711
+ featureType: params.featureType,
6712
+ featureValue: params.enabled ? "on" : "off"
6713
+ });
6714
+ }
6212
6715
  // ── Certificates ───────────────────────────────────────────────────────
6213
6716
  async listCertificates(types) {
6214
6717
  const iosTypes = types ?? [
@@ -6226,12 +6729,21 @@ var init_portal = __esm({
6226
6729
  return data.certRequests ?? [];
6227
6730
  }
6228
6731
  async listPushCertificates() {
6732
+ const types = Array.from(
6733
+ /* @__PURE__ */ new Set([
6734
+ _PortalClient.CERT_TYPES.IOS_PRODUCTION_PUSH,
6735
+ _PortalClient.CERT_TYPES.IOS_DEVELOPMENT_PUSH,
6736
+ // Legacy push codes from OLDER_IOS_CERTIFICATE_TYPES
6737
+ "3BQKVH9I2X",
6738
+ "BKLRAVXMGM"
6739
+ ])
6740
+ );
6229
6741
  const data = await this.post("account/ios/certificate/listCertRequests.action", {
6230
6742
  teamId: this.teamId,
6231
6743
  pageSize: "500",
6232
6744
  pageNumber: "1",
6233
6745
  sort: "certRequestStatusCode=asc",
6234
- types: [_PortalClient.CERT_TYPES.IOS_PRODUCTION_PUSH, _PortalClient.CERT_TYPES.IOS_DEVELOPMENT_PUSH].join(",")
6746
+ types: types.join(",")
6235
6747
  });
6236
6748
  return data.certRequests ?? [];
6237
6749
  }
@@ -6373,18 +6885,332 @@ var init_portal = __esm({
6373
6885
  }
6374
6886
  });
6375
6887
 
6888
+ // src/client/iris.ts
6889
+ var IRIS_BASE, IrisClient, IrisAuthError;
6890
+ var init_iris = __esm({
6891
+ "src/client/iris.ts"() {
6892
+ IRIS_BASE = "https://appstoreconnect.apple.com/iris/v1";
6893
+ IrisClient = class {
6894
+ constructor(session) {
6895
+ this.session = session;
6896
+ this.cookieStr = Object.entries(session.cookies).map(([k, v]) => `${k}=${v}`).join("; ");
6897
+ }
6898
+ session;
6899
+ cookieStr;
6900
+ buildHeaders() {
6901
+ return {
6902
+ Cookie: this.cookieStr,
6903
+ Accept: "application/vnd.api+json, application/json, text/plain, */*",
6904
+ "Content-Type": "application/vnd.api+json",
6905
+ "X-Requested-With": "XMLHttpRequest",
6906
+ // Mimic the App Store Connect web UI's user agent
6907
+ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15"
6908
+ };
6909
+ }
6910
+ /**
6911
+ * Issue a request and absorb any new cookies (Apple rotates session
6912
+ * cookies on a lot of iris calls).
6913
+ */
6914
+ async request(method, path, body) {
6915
+ const headers = this.buildHeaders();
6916
+ if (process.env.FASTNODE_DEBUG) {
6917
+ console.log(`[iris] ${method} ${path}${body ? ` body=${JSON.stringify(body).slice(0, 200)}` : ""}`);
6918
+ }
6919
+ const res = await fetch(`${IRIS_BASE}${path}`, {
6920
+ method,
6921
+ headers,
6922
+ body: body ? JSON.stringify(body) : void 0
6923
+ });
6924
+ for (const raw of res.headers.getSetCookie?.() ?? []) {
6925
+ const m = raw.match(/^([^=]+)=([^;]*)/);
6926
+ if (m) {
6927
+ this.session.cookies[m[1]] = m[2];
6928
+ }
6929
+ }
6930
+ this.cookieStr = Object.entries(this.session.cookies).map(([k, v]) => `${k}=${v}`).join("; ");
6931
+ const text = await res.text();
6932
+ let parsed = null;
6933
+ try {
6934
+ parsed = text ? JSON.parse(text) : null;
6935
+ } catch {
6936
+ }
6937
+ if (process.env.FASTNODE_DEBUG) {
6938
+ console.log(`[iris] \u2192 ${res.status} ${text.slice(0, 300)}`);
6939
+ }
6940
+ return { status: res.status, body: parsed, rawText: text };
6941
+ }
6942
+ /**
6943
+ * List existing API keys. Used both as a sanity check (the user has
6944
+ * permission) and to discover the team's issuer id (which is the same
6945
+ * for every key in the team and is needed by altool).
6946
+ *
6947
+ * Important: Apple's iris endpoint rejects most query parameters with
6948
+ * `PARAMETER_ERROR.INVALID`. Call with no params and let the API return
6949
+ * its default page.
6950
+ */
6951
+ async listApiKeys() {
6952
+ const { status, body, rawText } = await this.request("GET", "/apiKeys");
6953
+ if (status === 403) {
6954
+ throw new IrisAuthError(
6955
+ "You don't have permission to manage App Store Connect API keys (this requires the Account Holder or Admin role)."
6956
+ );
6957
+ }
6958
+ if (status >= 400 || !body) {
6959
+ throw new Error(`iris listApiKeys failed (${status}): ${rawText.slice(0, 200)}`);
6960
+ }
6961
+ const issuerId = body?.meta?.issuerId ?? body?.data?.[0]?.attributes?.issuerId;
6962
+ const keys = (body.data ?? []).map((d) => ({
6963
+ id: d.id,
6964
+ kid: d.attributes?.kid ?? d.id,
6965
+ nickname: d.attributes?.nickname ?? "",
6966
+ issuerId: d.attributes?.issuerId ?? issuerId,
6967
+ roles: d.attributes?.roles ?? [],
6968
+ allAppsVisible: d.attributes?.allAppsVisible ?? true
6969
+ }));
6970
+ return { keys, issuerId };
6971
+ }
6972
+ /**
6973
+ * Create a new API key. Apple returns the .p8 PEM exactly once in the
6974
+ * create response — capture it immediately or the key is dead weight.
6975
+ *
6976
+ * `keyType` is required by Apple's iris API:
6977
+ * • PUBLIC_API — the standard team-wide API key (what TestFlight uploads need)
6978
+ * • MARKETING_API — for App Analytics access only
6979
+ */
6980
+ async createApiKey(input) {
6981
+ const requestBody = {
6982
+ data: {
6983
+ type: "apiKeys",
6984
+ attributes: {
6985
+ nickname: input.nickname,
6986
+ roles: input.roles ?? ["APP_MANAGER"],
6987
+ allAppsVisible: input.allAppsVisible ?? true,
6988
+ keyType: input.keyType ?? "PUBLIC_API"
6989
+ }
6990
+ }
6991
+ };
6992
+ console.log("[iris] createApiKey request:", JSON.stringify(requestBody));
6993
+ const { status, body, rawText } = await this.request("POST", "/apiKeys", requestBody);
6994
+ console.log(`[iris] createApiKey response: ${status} ${rawText.slice(0, 800)}`);
6995
+ if (status === 403) {
6996
+ throw new IrisAuthError(
6997
+ "You don't have permission to create App Store Connect API keys (this requires the Account Holder or Admin role)."
6998
+ );
6999
+ }
7000
+ if (status >= 400 || !body) {
7001
+ const msg = body?.errors?.[0]?.detail ?? body?.errors?.[0]?.title ?? rawText.slice(0, 300) ?? `iris createApiKey failed (${status})`;
7002
+ throw new Error(msg);
7003
+ }
7004
+ const data = body.data ?? body;
7005
+ if (!data?.id) {
7006
+ throw new Error(`iris createApiKey returned no key id. Raw response: ${rawText.slice(0, 400)}`);
7007
+ }
7008
+ const key = {
7009
+ id: data.id,
7010
+ kid: data.attributes?.kid ?? data.id,
7011
+ nickname: data.attributes?.nickname ?? input.nickname,
7012
+ privateKey: data.attributes?.privateKey,
7013
+ issuerId: data.attributes?.issuerId,
7014
+ roles: data.attributes?.roles ?? input.roles ?? ["APP_MANAGER"],
7015
+ allAppsVisible: data.attributes?.allAppsVisible ?? true
7016
+ };
7017
+ return key;
7018
+ }
7019
+ /**
7020
+ * Fetch the .p8 PEM AND the team's issuer id for a previously-created
7021
+ * ASC API key. Both come back in a single request via:
7022
+ *
7023
+ * GET /iris/v1/apiKeys/{id}?fields[apiKeys]=privateKey&include=provider
7024
+ *
7025
+ * Sparse fieldset requesting ONLY `privateKey` is the magic that makes
7026
+ * Apple actually include the (base64-encoded) PEM in the response —
7027
+ * the default view returns `privateKey: null`. The `include=provider`
7028
+ * pulls the team's contentProvider record into `included[]`, and its
7029
+ * `id` field IS the issuer id altool needs (a UUID like
7030
+ * `cfadaf94-44ca-4c2c-8fa6-ecc28d3c7d0d`).
7031
+ *
7032
+ * Reverse-engineered from @expo/apple-utils v2.1.21 (the package that
7033
+ * powers EAS CLI), specifically the `ApiKey.downloadAsync` method
7034
+ * combined with `ApiKey.infoAsync` reading `provider?.id`.
7035
+ *
7036
+ * Returns `{ pem, issuerId }`, or `null` if Apple won't return the
7037
+ * private key (typically because the key was already downloaded once).
7038
+ */
7039
+ async fetchApiKeyPrivateKey(keyId) {
7040
+ try {
7041
+ const url = `${IRIS_BASE}/apiKeys/${keyId}?fields%5BapiKeys%5D=privateKey&include=provider`;
7042
+ const res = await fetch(url, {
7043
+ headers: {
7044
+ ...this.buildHeaders(),
7045
+ Accept: "application/vnd.api+json, application/json, text/plain, */*"
7046
+ }
7047
+ });
7048
+ const text = await res.text();
7049
+ console.log(`[iris] fetchApiKeyPrivateKey \u2192 ${res.status} (${text.length} bytes)`);
7050
+ if (res.status !== 200) {
7051
+ console.log(`[iris] err: ${text.slice(0, 300)}`);
7052
+ return null;
7053
+ }
7054
+ const body = JSON.parse(text);
7055
+ const encoded = body?.data?.attributes?.privateKey;
7056
+ if (typeof encoded !== "string" || encoded.length === 0) {
7057
+ console.log(`[iris] no privateKey in response`);
7058
+ return null;
7059
+ }
7060
+ const pem = Buffer.from(encoded, "base64").toString("utf-8");
7061
+ if (!pem.includes("BEGIN PRIVATE KEY")) {
7062
+ console.log(`[iris] decoded body didn't contain PEM marker`);
7063
+ return null;
7064
+ }
7065
+ const provider = (body?.included ?? []).find((i) => i.type === "contentProviders");
7066
+ const issuerId = provider?.id;
7067
+ console.log(`[iris] \u2713 PEM ${pem.length} bytes, issuerId=${issuerId ?? "(missing)"}`);
7068
+ return { pem, issuerId };
7069
+ } catch (err) {
7070
+ console.log(`[iris] fetchApiKeyPrivateKey error: ${err.message}`);
7071
+ return null;
7072
+ }
7073
+ }
7074
+ /**
7075
+ * @deprecated Kept as a fallback probe for debugging. The real path
7076
+ * is the sparse fieldset above — everything in this brute-force list
7077
+ * returned 404 during testing. Left here so we can re-verify if Apple
7078
+ * changes anything.
7079
+ */
7080
+ async fetchApiKeyPrivateKeyBruteForce(keyId) {
7081
+ const attempts = [
7082
+ // Sparse fieldsets — JSON-API spec lets us request specific attributes.
7083
+ // Apple may exclude privateKey by default and return it only when asked.
7084
+ { kind: "GET", path: `/apiKeys/${keyId}?fields[apiKeys]=privateKey,kid,issuerId,nickname,roles` },
7085
+ { kind: "GET", path: `/apiKeys/${keyId}?include=privateKey` },
7086
+ { kind: "GET", path: `/apiKeys/${keyId}?fields[apiKeys]=privateKey` },
7087
+ // Custom Accept headers — maybe Apple negotiates content type
7088
+ { kind: "GET", path: `/apiKeys/${keyId}`, accept: "application/x-pem-file" },
7089
+ { kind: "GET", path: `/apiKeys/${keyId}`, accept: "application/octet-stream" },
7090
+ { kind: "GET", path: `/apiKeys/${keyId}/p8`, accept: "application/x-pem-file" },
7091
+ // POST variants — Apple sometimes uses POST to mint a download token
7092
+ { kind: "POST", path: `/apiKeys/${keyId}/secrets`, body: {} },
7093
+ { kind: "POST", path: `/apiKeys/${keyId}/regenerate`, body: {} },
7094
+ { kind: "POST", path: `/apiKeys/${keyId}/p8`, body: {} },
7095
+ // Bare GET (last) — confirms canonical fields, in case my parser missed any
7096
+ { kind: "GET", path: `/apiKeys/${keyId}` },
7097
+ // Different host — the legacy developer.apple.com user-and-access namespace
7098
+ { kind: "ABSOLUTE", url: `https://appstoreconnect.apple.com/api/v1/apiKeys/${keyId}/p8` },
7099
+ { kind: "ABSOLUTE", url: `https://appstoreconnect.apple.com/access/api/keys/${keyId}/download` }
7100
+ ];
7101
+ for (const attempt of attempts) {
7102
+ try {
7103
+ let result;
7104
+ if (attempt.kind === "GET") {
7105
+ result = await this.requestWithHeaders("GET", attempt.path, void 0, {
7106
+ ...attempt.accept ? { Accept: attempt.accept } : {}
7107
+ });
7108
+ console.log(`[iris] fetchApiKeyPrivateKey GET ${attempt.path}${attempt.accept ? ` accept=${attempt.accept}` : ""} \u2192 ${result.status} (${result.rawText.length} bytes)`);
7109
+ } else if (attempt.kind === "POST") {
7110
+ result = await this.request("POST", attempt.path, attempt.body);
7111
+ console.log(`[iris] fetchApiKeyPrivateKey POST ${attempt.path} \u2192 ${result.status} (${result.rawText.length} bytes)`);
7112
+ } else {
7113
+ result = await this.requestAbsolute("GET", attempt.url);
7114
+ console.log(`[iris] fetchApiKeyPrivateKey GET ${attempt.url} \u2192 ${result.status} (${result.rawText.length} bytes)`);
7115
+ }
7116
+ if (result.status === 200) {
7117
+ console.log(`[iris] body: ${result.rawText.slice(0, 1500)}`);
7118
+ }
7119
+ if (result.status !== 200) continue;
7120
+ if (result.rawText && result.rawText.includes("BEGIN PRIVATE KEY")) {
7121
+ console.log(`[iris] \u2713 found PEM (plain text response)`);
7122
+ return result.rawText;
7123
+ }
7124
+ if (result.body) {
7125
+ const candidates = [
7126
+ result.body?.data?.attributes?.privateKey,
7127
+ result.body?.data?.attributes?.p8,
7128
+ result.body?.data?.attributes?.privateKeyContent,
7129
+ result.body?.data?.attributes?.kpem,
7130
+ result.body?.data?.attributes?.secret,
7131
+ result.body?.data?.attributes?.keyContent,
7132
+ result.body?.privateKey,
7133
+ result.body?.p8,
7134
+ result.body?.value,
7135
+ result.body?.secret
7136
+ ];
7137
+ for (const c of candidates) {
7138
+ if (typeof c === "string" && c.includes("BEGIN PRIVATE KEY")) {
7139
+ console.log(`[iris] \u2713 found PEM in JSON response`);
7140
+ return c;
7141
+ }
7142
+ }
7143
+ }
7144
+ } catch (err) {
7145
+ console.log(`[iris] fetchApiKeyPrivateKey attempt failed: ${err.message}`);
7146
+ }
7147
+ }
7148
+ console.log(`[iris] fetchApiKeyPrivateKey: no working download path for key ${keyId}`);
7149
+ return null;
7150
+ }
7151
+ /** Internal: like request() but lets us override headers. */
7152
+ async requestWithHeaders(method, path, body, extraHeaders = {}) {
7153
+ const headers = { ...this.buildHeaders(), ...extraHeaders };
7154
+ const res = await fetch(`${IRIS_BASE}${path}`, {
7155
+ method,
7156
+ headers,
7157
+ body: body ? JSON.stringify(body) : void 0
7158
+ });
7159
+ for (const raw of res.headers.getSetCookie?.() ?? []) {
7160
+ const m = raw.match(/^([^=]+)=([^;]*)/);
7161
+ if (m) this.session.cookies[m[1]] = m[2];
7162
+ }
7163
+ this.cookieStr = Object.entries(this.session.cookies).map(([k, v]) => `${k}=${v}`).join("; ");
7164
+ const text = await res.text();
7165
+ let parsed = null;
7166
+ try {
7167
+ parsed = text ? JSON.parse(text) : null;
7168
+ } catch {
7169
+ }
7170
+ return { status: res.status, body: parsed, rawText: text };
7171
+ }
7172
+ /** Internal: fetch an absolute URL with the session cookies. */
7173
+ async requestAbsolute(method, url) {
7174
+ const headers = this.buildHeaders();
7175
+ const res = await fetch(url, { method, headers });
7176
+ const text = await res.text();
7177
+ let parsed = null;
7178
+ try {
7179
+ parsed = text ? JSON.parse(text) : null;
7180
+ } catch {
7181
+ }
7182
+ return { status: res.status, body: parsed, rawText: text };
7183
+ }
7184
+ async deleteApiKey(keyId) {
7185
+ await this.request("DELETE", `/apiKeys/${keyId}`);
7186
+ }
7187
+ };
7188
+ IrisAuthError = class extends Error {
7189
+ constructor(message) {
7190
+ super(message);
7191
+ this.name = "IrisAuthError";
7192
+ }
7193
+ };
7194
+ }
7195
+ });
7196
+
6376
7197
  // src/client/index.ts
6377
7198
  var client_exports = {};
6378
7199
  __export(client_exports, {
6379
7200
  AppStoreConnectClient: () => AppStoreConnectClient,
6380
7201
  AppStoreConnectError: () => AppStoreConnectError,
7202
+ IrisAuthError: () => IrisAuthError,
7203
+ IrisClient: () => IrisClient,
6381
7204
  PortalClient: () => PortalClient,
6382
7205
  ProgramLicenseAgreementError: () => ProgramLicenseAgreementError,
6383
7206
  RateLimitError: () => RateLimitError,
6384
7207
  RequestClient: () => RequestClient,
6385
7208
  TokenManager: () => TokenManager,
7209
+ beginLogin: () => beginLogin,
6386
7210
  checkPortalResponse: () => checkPortalResponse,
6387
- loginWithAppleId: () => loginWithAppleId
7211
+ loginWithAppleId: () => loginWithAppleId,
7212
+ requestSmsCode: () => requestSmsCode,
7213
+ submitTwoFactorCode: () => submitTwoFactorCode
6388
7214
  });
6389
7215
  var AppStoreConnectClient;
6390
7216
  var init_client = __esm({
@@ -6429,6 +7255,7 @@ var init_client = __esm({
6429
7255
  init_request();
6430
7256
  init_apple_session();
6431
7257
  init_portal();
7258
+ init_iris();
6432
7259
  AppStoreConnectClient = class {
6433
7260
  http;
6434
7261
  certificates;