@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
@@ -153,8 +153,8 @@ async function revokeExpiredCertificates(options) {
153
153
  return count;
154
154
  }
155
155
  async function importToKeychain(certData, keychainPath, keychainPassword) {
156
- const { tmpdir: tmpdir7 } = await import('os');
157
- const tempCertPath = join(tmpdir7(), `fastnode-cert-${Date.now()}.cer`);
156
+ const { tmpdir: tmpdir8 } = await import('os');
157
+ const tempCertPath = join(tmpdir8(), `fastnode-cert-${Date.now()}.cer`);
158
158
  await writeFile(tempCertPath, certData);
159
159
  try {
160
160
  const args = [
@@ -1586,14 +1586,14 @@ var init_building = __esm({
1586
1586
  name: "clean_build_artifacts",
1587
1587
  description: "Remove build artifacts (IPA, dSYM, etc.)",
1588
1588
  async run(params, ctx) {
1589
- const { rm: rm2 } = await import('fs/promises');
1589
+ const { rm: rm4 } = await import('fs/promises');
1590
1590
  const paths = [
1591
1591
  ctx.get("IPA_OUTPUT_PATH"),
1592
1592
  ctx.get("PKG_OUTPUT_PATH"),
1593
1593
  ctx.get("DSYM_OUTPUT_PATH")
1594
1594
  ].filter(Boolean);
1595
1595
  for (const p of paths) {
1596
- await rm2(p, { force: true }).catch(() => {
1596
+ await rm4(p, { force: true }).catch(() => {
1597
1597
  });
1598
1598
  }
1599
1599
  return { cleaned: paths };
@@ -1752,9 +1752,9 @@ Please accept the agreement at https://developer.apple.com/account before contin
1752
1752
  throw new Error(msg);
1753
1753
  }
1754
1754
  }
1755
- async function loginWithAppleId(config) {
1756
- const log = config.onLog ?? console.log;
1757
- const promptFn = config.onPrompt ?? defaultPrompt;
1755
+ async function beginLogin(config) {
1756
+ const log = config.onLog ?? (() => {
1757
+ });
1758
1758
  log("Fetching Apple service key...");
1759
1759
  const serviceKey = await fetchServiceKey();
1760
1760
  const initRes = await fetch(`${AUTH_BASE}/signin?widgetKey=${serviceKey}`, {
@@ -1771,27 +1771,94 @@ async function loginWithAppleId(config) {
1771
1771
  const cookieStr = Object.entries(initCookies).map(([k, v]) => k.startsWith("DES") ? `${k}="${v}"` : `${k}=${v}`).join("; ");
1772
1772
  log("Starting SIRP Apple ID login...");
1773
1773
  const response = await doSirp(config.email, config.password, serviceKey, cookieStr, hashcash);
1774
- const session = {
1774
+ const baseState = {
1775
1775
  cookies: { ...initCookies, ...response.cookies },
1776
1776
  sessionId: response.sessionId,
1777
1777
  scnt: response.scnt,
1778
1778
  serviceKey,
1779
- userEmail: config.email,
1780
- pendingAgreements: []
1779
+ userEmail: config.email
1781
1780
  };
1782
1781
  if (response.status === 403) {
1783
1782
  throw new Error(`Invalid username and password combination. Used '${config.email}' as the username.`);
1784
- } else if (response.status === 200) {
1785
- log("Login successful.");
1786
- await fetchOlympusSession(session);
1787
- } else if (response.status === 409) {
1788
- await handleTwoStepOrFactor(session, log, promptFn);
1789
- await fetchOlympusSession(session);
1790
- } else if (response.status === 412) {
1783
+ }
1784
+ if (response.status === 412) {
1791
1785
  throw new Error("Need to acknowledge Apple's Apple ID and Privacy statement. Please manually log into https://appleid.apple.com.");
1786
+ }
1787
+ if (response.status === 200) {
1788
+ log("Login successful (no 2FA).");
1789
+ const session = { ...baseState, pendingAgreements: [] };
1790
+ await finalizeSession(session, log);
1791
+ return { kind: "logged_in", session };
1792
+ }
1793
+ if (response.status === 409) {
1794
+ log("2FA required, fetching challenge...");
1795
+ const challenge = await fetchTwoFactorChallenge(baseState);
1796
+ return { kind: "needs_2fa", pending: baseState, challenge };
1797
+ }
1798
+ throw new Error(`Unexpected login response (${response.status}): ${JSON.stringify(response.body).slice(0, 500)}`);
1799
+ }
1800
+ async function fetchTwoFactorChallenge(pending) {
1801
+ const r = await fetch(`${AUTH_BASE}`, { headers: buildAuthHeadersFromPending(pending) });
1802
+ const body = await r.json();
1803
+ const trustedPhoneNumbers = (body.trustedPhoneNumbers ?? []).map((p) => ({
1804
+ id: p.id,
1805
+ numberWithDialCode: p.numberWithDialCode,
1806
+ pushMode: p.pushMode
1807
+ }));
1808
+ const phoneOnly = body.noTrustedDevices === true;
1809
+ const codeLength = body.securityCode?.length ?? 6;
1810
+ return {
1811
+ kind: phoneOnly ? "phone_only" : "device",
1812
+ codeLength,
1813
+ trustedPhoneNumbers
1814
+ };
1815
+ }
1816
+ async function requestSmsCode(input) {
1817
+ await fetch(`${AUTH_BASE}/verify/phone`, {
1818
+ method: "PUT",
1819
+ headers: { ...buildAuthHeadersFromPending(input.pending), "Content-Type": "application/json" },
1820
+ body: JSON.stringify({ phoneNumber: { id: input.phoneId }, mode: input.mode ?? "sms" })
1821
+ });
1822
+ }
1823
+ async function submitTwoFactorCode(input) {
1824
+ const log = input.onLog ?? (() => {
1825
+ });
1826
+ let path;
1827
+ let body;
1828
+ if (input.source === "device") {
1829
+ path = `${AUTH_BASE}/verify/trusteddevice/securitycode`;
1830
+ body = JSON.stringify({ securityCode: { code: input.code } });
1792
1831
  } else {
1793
- throw new Error(`Unexpected login response (${response.status}): ${JSON.stringify(response.body).slice(0, 500)}`);
1832
+ if (input.phoneId == null) throw new Error("phoneId is required when source='phone'");
1833
+ path = `${AUTH_BASE}/verify/phone/securitycode`;
1834
+ body = JSON.stringify({
1835
+ securityCode: { code: input.code },
1836
+ phoneNumber: { id: input.phoneId },
1837
+ mode: input.mode ?? "sms"
1838
+ });
1794
1839
  }
1840
+ log("Submitting 2FA code...");
1841
+ const verifyRes = await fetch(path, {
1842
+ method: "POST",
1843
+ headers: { ...buildAuthHeadersFromPending(input.pending), "Content-Type": "application/json" },
1844
+ body
1845
+ });
1846
+ if (!verifyRes.ok) {
1847
+ const err = await verifyRes.json().catch(() => ({}));
1848
+ const msgs = (err?.service_errors ?? err?.serviceErrors ?? []).map((e) => e.message).filter(Boolean);
1849
+ throw new Error(msgs.join("; ") || `Verification failed (${verifyRes.status})`);
1850
+ }
1851
+ const session = {
1852
+ ...input.pending,
1853
+ cookies: { ...input.pending.cookies, ...parseCookies(verifyRes.headers) },
1854
+ pendingAgreements: []
1855
+ };
1856
+ await trustSession(session);
1857
+ await finalizeSession(session, log);
1858
+ return session;
1859
+ }
1860
+ async function finalizeSession(session, log) {
1861
+ await fetchOlympusSession(session);
1795
1862
  const agreements = await fetchContractMessages(session);
1796
1863
  if (agreements.length > 0) {
1797
1864
  for (const msg of agreements) {
@@ -1800,7 +1867,53 @@ async function loginWithAppleId(config) {
1800
1867
  }
1801
1868
  session.pendingAgreements = agreements;
1802
1869
  log(`Logged in as ${session.userEmail}`);
1803
- return session;
1870
+ }
1871
+ async function loginWithAppleId(config) {
1872
+ const log = config.onLog ?? console.log;
1873
+ const promptFn = config.onPrompt ?? defaultPrompt;
1874
+ const result = await beginLogin({ email: config.email, password: config.password, onLog: log });
1875
+ if (result.kind === "logged_in") return result.session;
1876
+ const { pending, challenge } = result;
1877
+ const phones = challenge.trustedPhoneNumbers;
1878
+ if (challenge.kind === "device") {
1879
+ log("Two-factor Authentication (6 digit code) is enabled for this account");
1880
+ log("(Input 'sms' to escape this prompt and select a trusted phone number to send the code as a text message)");
1881
+ const input = await promptFn(`Please enter the ${challenge.codeLength} digit code: `);
1882
+ if (input.toLowerCase() === "sms") {
1883
+ log("Please select a trusted phone number:");
1884
+ for (let i = 0; i < phones.length; i++) log(` ${i + 1}. ${phones[i].numberWithDialCode}`);
1885
+ const choice2 = await promptFn("Enter number: ");
1886
+ const phone2 = phones[Math.max(0, parseInt(choice2, 10) - 1)] ?? phones[0];
1887
+ await requestSmsCode({ pending, phoneId: phone2.id, mode: phone2.pushMode });
1888
+ log(`Code sent to ${phone2.numberWithDialCode}`);
1889
+ const code2 = await promptFn(`Please enter the ${challenge.codeLength} digit code: `);
1890
+ return submitTwoFactorCode({ pending, code: code2, source: "phone", phoneId: phone2.id, mode: phone2.pushMode ?? "sms", onLog: log });
1891
+ }
1892
+ return submitTwoFactorCode({ pending, code: input, source: "device", onLog: log });
1893
+ }
1894
+ log("Two-factor Authentication (6 digit code) is enabled for this account");
1895
+ if (phones.length === 1) {
1896
+ const phone2 = phones[0];
1897
+ log(`Code automatically sent to ${phone2.numberWithDialCode}`);
1898
+ const code2 = await promptFn(`Please enter the ${challenge.codeLength} digit code: `);
1899
+ return submitTwoFactorCode({ pending, code: code2, source: "phone", phoneId: phone2.id, mode: phone2.pushMode ?? "sms", onLog: log });
1900
+ }
1901
+ log("Please select a trusted phone number:");
1902
+ for (let i = 0; i < phones.length; i++) log(` ${i + 1}. ${phones[i].numberWithDialCode}`);
1903
+ const choice = await promptFn("Enter number: ");
1904
+ const phone = phones[Math.max(0, parseInt(choice, 10) - 1)] ?? phones[0];
1905
+ await requestSmsCode({ pending, phoneId: phone.id, mode: phone.pushMode });
1906
+ log(`Code sent to ${phone.numberWithDialCode}`);
1907
+ const code = await promptFn(`Please enter the ${challenge.codeLength} digit code: `);
1908
+ return submitTwoFactorCode({ pending, code, source: "phone", phoneId: phone.id, mode: phone.pushMode ?? "sms", onLog: log });
1909
+ }
1910
+ function buildAuthHeadersFromPending(pending) {
1911
+ const h = { "X-Apple-Widget-Key": pending.serviceKey, Accept: "application/json" };
1912
+ if (pending.sessionId) h["X-Apple-Id-Session-Id"] = pending.sessionId;
1913
+ if (pending.scnt) h["scnt"] = pending.scnt;
1914
+ const c = Object.entries(pending.cookies).map(([k, v]) => `${k}=${v}`).join("; ");
1915
+ if (c) h["Cookie"] = c;
1916
+ return h;
1804
1917
  }
1805
1918
  async function doSirp(user, password, serviceKey, cookieStr, hashcash) {
1806
1919
  const client = new SRPClient(2048);
@@ -1856,99 +1969,6 @@ async function doSirp(user, password, serviceKey, cookieStr, hashcash) {
1856
1969
  scnt: completeRes.headers.get("scnt") ?? ""
1857
1970
  };
1858
1971
  }
1859
- async function handleTwoStepOrFactor(session, log, promptFn) {
1860
- const r = await fetch(`${AUTH_BASE}`, { headers: buildAuthHeaders(session) });
1861
- const body = await r.json();
1862
- if (body.trustedDevices?.length > 0) {
1863
- await handleTwoStep(session, body, log, promptFn);
1864
- } else if (body.trustedPhoneNumbers?.length > 0) {
1865
- await handleTwoFactor(session, body, log, promptFn);
1866
- } else {
1867
- throw new Error("2FA required but no trusted devices or phone numbers found.");
1868
- }
1869
- }
1870
- async function handleTwoFactor(session, authBody, log, promptFn) {
1871
- log("Two-factor Authentication (6 digit code) is enabled for this account");
1872
- const codeLength = authBody.securityCode?.length ?? 6;
1873
- const phones = authBody.trustedPhoneNumbers ?? [];
1874
- const noTrusted = authBody.noTrustedDevices === true;
1875
- let codeType;
1876
- let reqBody;
1877
- if (noTrusted && phones.length === 1) {
1878
- const phone = phones[0];
1879
- log(`Code automatically sent to ${phone.numberWithDialCode}`);
1880
- const code = await promptFn(`Please enter the ${codeLength} digit code you received at ${phone.numberWithDialCode}: `);
1881
- codeType = "phone";
1882
- reqBody = JSON.stringify({ securityCode: { code }, phoneNumber: { id: phone.id }, mode: phone.pushMode ?? "sms" });
1883
- } else if (noTrusted) {
1884
- const phone = await choosePhone(phones, log, promptFn);
1885
- await requestPhoneCode(session, phone);
1886
- log(`Successfully requested text message to ${phone.numberWithDialCode}`);
1887
- const code = await promptFn(`Please enter the ${codeLength} digit code: `);
1888
- codeType = "phone";
1889
- reqBody = JSON.stringify({ securityCode: { code }, phoneNumber: { id: phone.id }, mode: phone.pushMode ?? "sms" });
1890
- } else {
1891
- log("(Input 'sms' to escape this prompt and select a trusted phone number to send the code as a text message)");
1892
- const input = await promptFn(`Please enter the ${codeLength} digit code: `);
1893
- if (input.toLowerCase() === "sms") {
1894
- const phone = await choosePhone(phones, log, promptFn);
1895
- await requestPhoneCode(session, phone);
1896
- const code = await promptFn(`Please enter the ${codeLength} digit code sent to ${phone.numberWithDialCode}: `);
1897
- codeType = "phone";
1898
- reqBody = JSON.stringify({ securityCode: { code }, phoneNumber: { id: phone.id }, mode: phone.pushMode ?? "sms" });
1899
- } else {
1900
- codeType = "trusteddevice";
1901
- reqBody = JSON.stringify({ securityCode: { code: input } });
1902
- }
1903
- }
1904
- log("Requesting session...");
1905
- const verifyRes = await fetch(`${AUTH_BASE}/verify/${codeType}/securitycode`, {
1906
- method: "POST",
1907
- headers: { ...buildAuthHeaders(session), "Content-Type": "application/json" },
1908
- body: reqBody
1909
- });
1910
- if (!verifyRes.ok) {
1911
- const err = await verifyRes.json().catch(() => ({}));
1912
- const msgs = (err?.service_errors ?? err?.serviceErrors ?? []).map((e) => e.message).filter(Boolean);
1913
- throw new Error(msgs.join("; ") || `Verification failed (${verifyRes.status})`);
1914
- }
1915
- Object.assign(session.cookies, parseCookies(verifyRes.headers));
1916
- await trustSession(session);
1917
- }
1918
- async function handleTwoStep(session, authBody, log, promptFn) {
1919
- log("Two-step Verification (4 digit code) is enabled for this account");
1920
- const devices = authBody.trustedDevices ?? [];
1921
- log("Please select a trusted device:");
1922
- for (let i = 0; i < devices.length; i++) {
1923
- log(` ${i + 1}. ${devices[i].name} ${devices[i].modelName ?? "SMS"} (${devices[i].id})`);
1924
- }
1925
- const choice = await promptFn("Enter device number: ");
1926
- const device = devices[Math.max(0, parseInt(choice, 10) - 1)] ?? devices[0];
1927
- await fetch(`${AUTH_BASE}/verify/device/${device.id}/securitycode`, { method: "PUT", headers: buildAuthHeaders(session) });
1928
- log("Successfully requested notification");
1929
- const code = await promptFn("Please enter the 4 digit code: ");
1930
- const verifyRes = await fetch(`${AUTH_BASE}/verify/phone/securitycode`, {
1931
- method: "POST",
1932
- headers: { ...buildAuthHeaders(session), "Content-Type": "application/json" },
1933
- body: JSON.stringify({ phoneNumber: { id: device.id }, securityCode: { code }, mode: "sms" })
1934
- });
1935
- if (!verifyRes.ok) throw new Error("Incorrect verification code.");
1936
- Object.assign(session.cookies, parseCookies(verifyRes.headers));
1937
- await trustSession(session);
1938
- }
1939
- async function choosePhone(phones, log, promptFn) {
1940
- log("Please select a trusted phone number:");
1941
- for (let i = 0; i < phones.length; i++) log(` ${i + 1}. ${phones[i].numberWithDialCode}`);
1942
- const choice = await promptFn("Enter number: ");
1943
- return phones[Math.max(0, parseInt(choice, 10) - 1)] ?? phones[0];
1944
- }
1945
- async function requestPhoneCode(session, phone) {
1946
- await fetch(`${AUTH_BASE}/verify/phone`, {
1947
- method: "PUT",
1948
- headers: { ...buildAuthHeaders(session), "Content-Type": "application/json" },
1949
- body: JSON.stringify({ phoneNumber: { id: phone.id }, mode: phone.pushMode ?? "sms" })
1950
- });
1951
- }
1952
1972
  async function trustSession(session) {
1953
1973
  const r = await fetch(`${AUTH_BASE}/2sv/trust`, { headers: buildAuthHeaders(session) });
1954
1974
  Object.assign(session.cookies, parseCookies(r.headers));
@@ -2240,23 +2260,13 @@ var init_request = __esm({
2240
2260
  };
2241
2261
  }
2242
2262
  });
2243
-
2244
- // src/pilot/index.ts
2245
- var pilot_exports = {};
2246
- __export(pilot_exports, {
2247
- distributeToGroups: () => distributeToGroups,
2248
- expireBuild: () => expireBuild,
2249
- setChangelog: () => setChangelog,
2250
- uploadToTestFlight: () => uploadToTestFlight,
2251
- waitForProcessing: () => waitForProcessing
2252
- });
2253
- async function uploadToTestFlight(options) {
2263
+ async function uploadWithAltool(options) {
2254
2264
  if (!existsSync(options.ipaPath)) {
2255
2265
  throw new Error(`File not found: ${options.ipaPath}`);
2256
2266
  }
2257
2267
  const platform = options.platform ?? "ios";
2258
2268
  const timeout = options.timeout ?? 18e5;
2259
- const keyDir = await mkdtemp(join(tmpdir(), "fastnode-key-"));
2269
+ const keyDir = await mkdtemp(join(tmpdir(), "fastnode-altool-"));
2260
2270
  const keyPath = join(keyDir, `AuthKey_${options.apiKeyId}.p8`);
2261
2271
  await writeFile(keyPath, options.apiPrivateKey);
2262
2272
  return new Promise((resolve4) => {
@@ -2280,24 +2290,228 @@ async function uploadToTestFlight(options) {
2280
2290
  const timer = setTimeout(() => {
2281
2291
  child.kill("SIGTERM");
2282
2292
  }, timeout);
2283
- child.stdout.on("data", (data) => {
2293
+ const onData = (data) => {
2284
2294
  const chunk = data.toString();
2285
2295
  output += chunk;
2286
2296
  options.onOutput?.(chunk);
2297
+ };
2298
+ child.stdout.on("data", onData);
2299
+ child.stderr.on("data", onData);
2300
+ child.on("close", async (code) => {
2301
+ clearTimeout(timer);
2302
+ await unlink(keyPath).catch(() => {
2303
+ });
2304
+ await rm(keyDir, { recursive: true, force: true }).catch(() => {
2305
+ });
2306
+ resolve4({ success: code === 0, output, backend: "altool" });
2287
2307
  });
2288
- child.stderr.on("data", (data) => {
2308
+ });
2309
+ }
2310
+ var init_upload_altool = __esm({
2311
+ "src/pilot/upload-altool.ts"() {
2312
+ }
2313
+ });
2314
+ async function resolveTransporter() {
2315
+ const override = process.env.ITMSTRANSPORTER_BIN;
2316
+ if (override) {
2317
+ if (!existsSync(override)) {
2318
+ throw new Error(
2319
+ `ITMSTRANSPORTER_BIN is set to "${override}" but that path does not exist.`
2320
+ );
2321
+ }
2322
+ return override;
2323
+ }
2324
+ const candidates = process.platform === "darwin" ? [
2325
+ // Xcode 15+: Transporter.app bundled with Xcode
2326
+ "/Applications/Xcode.app/Contents/SharedFrameworks/ContentDeliveryServices.framework/Versions/A/itms/bin/iTMSTransporter",
2327
+ // Standalone Transporter.app from the Mac App Store
2328
+ "/Applications/Transporter.app/Contents/itms/bin/iTMSTransporter"
2329
+ ] : [
2330
+ "/usr/local/itms/bin/iTMSTransporter",
2331
+ "/opt/itms/bin/iTMSTransporter",
2332
+ "/usr/local/bin/iTMSTransporter"
2333
+ ];
2334
+ for (const path of candidates) {
2335
+ if (existsSync(path)) return path;
2336
+ }
2337
+ throw new Error(
2338
+ [
2339
+ "iTMSTransporter not found.",
2340
+ "",
2341
+ "Install options:",
2342
+ process.platform === "darwin" ? " - Install Xcode (includes Transporter)" : " - Download Apple's standalone iTMSTransporter package for Linux",
2343
+ " - Or set ITMSTRANSPORTER_BIN to the absolute path of the binary",
2344
+ "",
2345
+ `Searched: ${candidates.join(", ")}`
2346
+ ].join("\n")
2347
+ );
2348
+ }
2349
+ async function verifyJava() {
2350
+ return new Promise((resolve4, reject) => {
2351
+ const child = spawn("java", ["-version"], { stdio: ["ignore", "pipe", "pipe"] });
2352
+ let stderr = "";
2353
+ child.stderr.on("data", (d) => {
2354
+ stderr += d.toString();
2355
+ });
2356
+ child.on("error", (err) => {
2357
+ reject(
2358
+ new Error(
2359
+ `java not found on PATH (${err.message}). Install Java 17 LTS and ensure it is on PATH.`
2360
+ )
2361
+ );
2362
+ });
2363
+ child.on("close", (code) => {
2364
+ if (code !== 0) {
2365
+ reject(new Error(`java -version exited ${code}: ${stderr}`));
2366
+ return;
2367
+ }
2368
+ const match = stderr.match(/version "([^"]+)"/);
2369
+ resolve4({ version: match?.[1] ?? "unknown" });
2370
+ });
2371
+ });
2372
+ }
2373
+ var init_transporter_install = __esm({
2374
+ "src/pilot/transporter-install.ts"() {
2375
+ }
2376
+ });
2377
+ async function uploadWithTransporter(options) {
2378
+ if (!existsSync(options.ipaPath)) {
2379
+ throw new Error(`File not found: ${options.ipaPath}`);
2380
+ }
2381
+ await verifyJava();
2382
+ const transporterBin = await resolveTransporter();
2383
+ const platform = options.platform ?? "ios";
2384
+ const timeout = options.timeout ?? 18e5;
2385
+ const keyDir = await mkdtemp(join(tmpdir(), "fastnode-itms-"));
2386
+ const keyPath = join(keyDir, `AuthKey_${options.apiKeyId}.p8`);
2387
+ await writeFile(keyPath, options.apiPrivateKey);
2388
+ return new Promise((resolve4) => {
2389
+ const args = [
2390
+ "-m",
2391
+ "upload",
2392
+ "-assetFile",
2393
+ options.ipaPath,
2394
+ "-apiKey",
2395
+ options.apiKeyId,
2396
+ "-apiIssuer",
2397
+ options.apiIssuerId,
2398
+ // WONoPause prevents the JVM from waiting on stdin in non-TTY
2399
+ // environments (CI, LaunchAgent) where it would hang forever.
2400
+ "-WONoPause",
2401
+ "true"
2402
+ ];
2403
+ if (platform !== "ios") {
2404
+ args.push("-bundleType", platform);
2405
+ }
2406
+ const child = spawn(transporterBin, args, {
2407
+ env: {
2408
+ ...process.env,
2409
+ API_PRIVATE_KEYS_DIR: keyDir
2410
+ },
2411
+ stdio: ["ignore", "pipe", "pipe"]
2412
+ });
2413
+ let output = "";
2414
+ const timer = setTimeout(() => {
2415
+ child.kill("SIGTERM");
2416
+ }, timeout);
2417
+ const onData = (data) => {
2289
2418
  const chunk = data.toString();
2290
2419
  output += chunk;
2291
2420
  options.onOutput?.(chunk);
2292
- });
2421
+ };
2422
+ child.stdout.on("data", onData);
2423
+ child.stderr.on("data", onData);
2293
2424
  child.on("close", async (code) => {
2294
2425
  clearTimeout(timer);
2295
- await unlink(keyPath).catch(() => {
2426
+ await rm(keyDir, { recursive: true, force: true }).catch(() => {
2427
+ });
2428
+ resolve4({ success: code === 0, output, backend: "transporter" });
2429
+ });
2430
+ child.on("error", async (err) => {
2431
+ clearTimeout(timer);
2432
+ await rm(keyDir, { recursive: true, force: true }).catch(() => {
2433
+ });
2434
+ resolve4({
2435
+ success: false,
2436
+ output: output + `
2437
+ Process error: ${err.message}`,
2438
+ backend: "transporter"
2296
2439
  });
2297
- resolve4({ success: code === 0, output });
2298
2440
  });
2299
2441
  });
2300
2442
  }
2443
+ var init_upload_transporter = __esm({
2444
+ "src/pilot/upload-transporter.ts"() {
2445
+ init_transporter_install();
2446
+ }
2447
+ });
2448
+
2449
+ // src/pilot/classify.ts
2450
+ function classifyUploadError(output) {
2451
+ for (const { pattern, kind } of RULES) {
2452
+ if (pattern.test(output)) return kind;
2453
+ }
2454
+ return null;
2455
+ }
2456
+ function isTransientUploadError(output) {
2457
+ return classifyUploadError(output) !== null;
2458
+ }
2459
+ var RULES;
2460
+ var init_classify = __esm({
2461
+ "src/pilot/classify.ts"() {
2462
+ RULES = [
2463
+ // Apple's finalize-upload call returning 5xx — the most common transient
2464
+ // failure we see in practice. Example:
2465
+ // "CHANGE UPLOAD STATE TO COMPLETE (UPLOADING ASSET DESCRIPTION):
2466
+ // received status code 500; internal server error."
2467
+ { pattern: /CHANGE UPLOAD STATE TO COMPLETE/i, kind: "finalize_failed" },
2468
+ // Generic 5xx from ASC backend services
2469
+ { pattern: /status code 5\d\d/i, kind: "apple_5xx" },
2470
+ { pattern: /internal server error/i, kind: "apple_5xx" },
2471
+ { pattern: /Service Unavailable/i, kind: "apple_5xx" },
2472
+ { pattern: /Bad Gateway/i, kind: "apple_5xx" },
2473
+ // Network-level interruptions during the upload body transfer
2474
+ { pattern: /Connection reset/i, kind: "connection_reset" },
2475
+ { pattern: /SocketException/i, kind: "connection_reset" },
2476
+ { pattern: /Broken pipe/i, kind: "connection_reset" },
2477
+ // Timeouts — distinct from resets because the other side may have
2478
+ // actually processed the request, so dedupe logic may matter.
2479
+ { pattern: /Read timed out/i, kind: "network_timeout" },
2480
+ { pattern: /SocketTimeoutException/i, kind: "network_timeout" },
2481
+ { pattern: /Operation timed out/i, kind: "network_timeout" },
2482
+ // JVM-internal errors from iTMSTransporter (OOM, thread interruption, etc.)
2483
+ { pattern: /java\.lang\.OutOfMemoryError/i, kind: "transporter_jvm_error" },
2484
+ { pattern: /EOFException/i, kind: "transporter_jvm_error" }
2485
+ ];
2486
+ }
2487
+ });
2488
+
2489
+ // src/pilot/index.ts
2490
+ var pilot_exports = {};
2491
+ __export(pilot_exports, {
2492
+ classifyUploadError: () => classifyUploadError,
2493
+ distributeToGroups: () => distributeToGroups,
2494
+ expireBuild: () => expireBuild,
2495
+ isTransientUploadError: () => isTransientUploadError,
2496
+ resolveTransporter: () => resolveTransporter,
2497
+ setChangelog: () => setChangelog,
2498
+ uploadToTestFlight: () => uploadToTestFlight,
2499
+ uploadWithAltool: () => uploadWithAltool,
2500
+ uploadWithTransporter: () => uploadWithTransporter,
2501
+ verifyJava: () => verifyJava,
2502
+ waitForProcessing: () => waitForProcessing
2503
+ });
2504
+ async function uploadToTestFlight(options) {
2505
+ const backend = selectBackend(options.backend ?? "auto");
2506
+ if (backend === "altool") {
2507
+ return uploadWithAltool(options);
2508
+ }
2509
+ return uploadWithTransporter(options);
2510
+ }
2511
+ function selectBackend(pref) {
2512
+ if (pref !== "auto") return pref;
2513
+ return process.platform === "darwin" ? "altool" : "transporter";
2514
+ }
2301
2515
  async function waitForProcessing(client, params) {
2302
2516
  const timeout = params.timeout ?? 18e5;
2303
2517
  const pollInterval = params.pollInterval ?? 3e4;
@@ -2418,6 +2632,12 @@ function sleep2(ms) {
2418
2632
  var init_pilot = __esm({
2419
2633
  "src/pilot/index.ts"() {
2420
2634
  init_request();
2635
+ init_upload_altool();
2636
+ init_upload_transporter();
2637
+ init_upload_altool();
2638
+ init_upload_transporter();
2639
+ init_classify();
2640
+ init_transporter_install();
2421
2641
  }
2422
2642
  });
2423
2643
  async function loadMetadata(metadataPath) {
@@ -2505,9 +2725,9 @@ var init_metadata = __esm({
2505
2725
  // src/xcode/upload.ts
2506
2726
  var upload_exports = {};
2507
2727
  __export(upload_exports, {
2508
- uploadWithAltool: () => uploadWithAltool
2728
+ uploadWithAltool: () => uploadWithAltool2
2509
2729
  });
2510
- async function uploadWithAltool(options) {
2730
+ async function uploadWithAltool2(options) {
2511
2731
  requireMacOS("altool upload");
2512
2732
  let keyDir;
2513
2733
  if (options.apiPrivateKey && !options.apiKeyPath) {
@@ -2616,8 +2836,8 @@ async function uploadToAppStore(options) {
2616
2836
  if (!options.skipBinaryUpload) {
2617
2837
  const binaryPath = options.ipaPath ?? options.pkgPath;
2618
2838
  if (binaryPath && options.apiKeyId && options.apiIssuerId) {
2619
- const { uploadWithAltool: uploadWithAltool2 } = await Promise.resolve().then(() => (init_upload(), upload_exports));
2620
- await uploadWithAltool2({
2839
+ const { uploadWithAltool: uploadWithAltool3 } = await Promise.resolve().then(() => (init_upload(), upload_exports));
2840
+ await uploadWithAltool3({
2621
2841
  filePath: binaryPath,
2622
2842
  apiKeyId: options.apiKeyId,
2623
2843
  apiIssuerId: options.apiIssuerId,
@@ -3403,8 +3623,8 @@ async function captureScreenshots(options) {
3403
3623
  const outputDir = options.outputDirectory ?? join(process.cwd(), "screenshots");
3404
3624
  const retries = options.numberOfRetries ?? 1;
3405
3625
  if (options.clearPreviousScreenshots && existsSync(outputDir)) {
3406
- const { rm: rm2 } = await import('fs/promises');
3407
- await rm2(outputDir, { recursive: true, force: true });
3626
+ const { rm: rm4 } = await import('fs/promises');
3627
+ await rm4(outputDir, { recursive: true, force: true });
3408
3628
  }
3409
3629
  mkdirSync(outputDir, { recursive: true });
3410
3630
  const screenshots = {};
@@ -6111,6 +6331,264 @@ var init_portal = __esm({
6111
6331
  async init() {
6112
6332
  await this.post("account/listTeams.action", {});
6113
6333
  }
6334
+ /**
6335
+ * JSON POST — different content type than the standard form-encoded
6336
+ * `post()`. Used by the App Store Connect API key endpoints
6337
+ * (`account/auth/key/v2/create`), which Spaceship discovered take a
6338
+ * JSON body even though every other portal mutation is form-encoded.
6339
+ *
6340
+ * Like the form-encoded `post()`, this also runs the response through
6341
+ * `checkPortalResponse` — Apple returns HTTP 200 even for errors and
6342
+ * encodes the error in `resultCode`/`userString` fields, so a raw
6343
+ * status check would silently miss real failures.
6344
+ */
6345
+ async postJson(path, body) {
6346
+ const headers = {
6347
+ Cookie: this.cookieStr,
6348
+ "Content-Type": "application/json",
6349
+ Accept: "application/json"
6350
+ };
6351
+ if (this.csrf) {
6352
+ headers["csrf"] = this.csrf;
6353
+ headers["csrf_ts"] = this.csrfTs;
6354
+ }
6355
+ console.log(`[portal] POST(json) ${path}`);
6356
+ const res = await fetch(`${PORTAL_BASE}/${path}`, {
6357
+ method: "POST",
6358
+ headers,
6359
+ body: JSON.stringify(body)
6360
+ });
6361
+ if (res.headers.get("csrf")) {
6362
+ this.csrf = res.headers.get("csrf");
6363
+ this.csrfTs = res.headers.get("csrf_ts") ?? "";
6364
+ }
6365
+ for (const raw of res.headers.getSetCookie?.() ?? []) {
6366
+ const m = raw.match(/^([^=]+)=([^;]*)/);
6367
+ if (m && !this.cookieStr.includes(m[1] + "=")) this.cookieStr += "; " + m[1] + "=" + m[2];
6368
+ }
6369
+ const text = await res.text();
6370
+ let data = null;
6371
+ try {
6372
+ data = text ? JSON.parse(text) : null;
6373
+ } catch {
6374
+ }
6375
+ console.log(`[portal] POST(json) ${path} \u2192 ${res.status} ${text.slice(0, 400)}`);
6376
+ checkPortalResponse(data, this.session);
6377
+ return { status: res.status, body: data, rawText: text };
6378
+ }
6379
+ /**
6380
+ * GET helper for the portal endpoints that take query parameters
6381
+ * (currently just `account/auth/key/download`). Returns the raw text
6382
+ * since download endpoints can return PEMs or JSON depending on Apple's
6383
+ * mood — caller decides how to parse.
6384
+ */
6385
+ async getRaw(path, params = {}) {
6386
+ const url = new URL(`${PORTAL_BASE}/${path}`);
6387
+ for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
6388
+ const headers = {
6389
+ Cookie: this.cookieStr,
6390
+ Accept: "application/json, text/plain, application/x-pem-file, */*"
6391
+ };
6392
+ if (this.csrf) {
6393
+ headers["csrf"] = this.csrf;
6394
+ headers["csrf_ts"] = this.csrfTs;
6395
+ }
6396
+ console.log(`[portal] GET ${url.pathname}${url.search}`);
6397
+ const res = await fetch(url.toString(), { headers });
6398
+ for (const raw of res.headers.getSetCookie?.() ?? []) {
6399
+ const m = raw.match(/^([^=]+)=([^;]*)/);
6400
+ if (m && !this.cookieStr.includes(m[1] + "=")) this.cookieStr += "; " + m[1] + "=" + m[2];
6401
+ }
6402
+ const text = await res.text();
6403
+ const contentType = res.headers.get("content-type") ?? "";
6404
+ console.log(`[portal] GET ${url.pathname} \u2192 ${res.status} ${contentType} ${text.length}b`);
6405
+ return { status: res.status, rawText: text, contentType };
6406
+ }
6407
+ // ── App Store Connect API Keys (.p8) ────────────────────────────────────
6408
+ /**
6409
+ * Create an App Store Connect API key via the developer portal's
6410
+ * `account/auth/key/v2/create` endpoint. Reverse-engineered from the
6411
+ * _current_ @expo/apple-utils npm package (v2.1.21), which is what
6412
+ * EAS CLI uses to manage Apple credentials in production.
6413
+ *
6414
+ * This differs from older published reverse-engineering guides:
6415
+ * • URL uses the `/v2/create` suffix (Apple kept it)
6416
+ * • Field is `serviceConfigurations`, shape is an object keyed by
6417
+ * service id (NOT `serviceConfigurationsRequests: [...]` array)
6418
+ * • Body REQUIRES `scope: "team"`
6419
+ * • Needs a scope-specific CSRF warmup via the `keys` endpoint
6420
+ * before the create call (EAS's `ensureCSRFAsync("keys", …)`)
6421
+ *
6422
+ * For an App Store Connect API key (PUBLIC_API, used by altool for
6423
+ * TestFlight uploads), `serviceConfigurations` is an empty object `{}`.
6424
+ * For an APNs auth key, it's `{ "U27F4V844T": [] }`. For MusicKit:
6425
+ * `{ "6A7HVUVQ3M": [musicId] }`, etc.
6426
+ *
6427
+ * Apple's name validator rejects parentheses, brackets, and most
6428
+ * punctuation — sanitize to alphanumeric + space + dash + underscore
6429
+ * + period and collapse whitespace.
6430
+ */
6431
+ async createApiKey(rawName, serviceConfigurations = {}) {
6432
+ const name = rawName.replace(/[^A-Za-z0-9 _\-.]/g, " ").replace(/\s+/g, " ").trim().slice(0, 50);
6433
+ if (!name) throw new Error("createApiKey: name is empty after sanitization");
6434
+ try {
6435
+ await this.listApiKeys();
6436
+ } catch {
6437
+ }
6438
+ const body = {
6439
+ teamId: this.teamId,
6440
+ name,
6441
+ serviceConfigurations,
6442
+ scope: "team"
6443
+ };
6444
+ const result = await this.postJson("account/auth/key/v2/create", body);
6445
+ const created = result.body?.keys?.[0] ?? result.body?.key ?? result.body?.data ?? result.body;
6446
+ const keyId = created?.keyId ?? created?.id ?? created?.kid ?? created?.attributes?.kid;
6447
+ if (!keyId) {
6448
+ throw new Error(`createApiKey: no key id in response. Body: ${result.rawText.slice(0, 400)}`);
6449
+ }
6450
+ return { keyId, raw: created };
6451
+ }
6452
+ /**
6453
+ * Fetch a single API key by id via `account/auth/key/get`. Reverse-
6454
+ * engineered from Spaceship's `get_key`. Returns the raw key record so
6455
+ * the caller can extract whatever fields it needs (e.g. issuerId).
6456
+ *
6457
+ * Form-encoded POST — same shape as every other PortalClient mutation
6458
+ * except the JSON `create` endpoint.
6459
+ */
6460
+ async getApiKey(keyId) {
6461
+ const data = await this.post("account/auth/key/get", {
6462
+ teamId: this.teamId,
6463
+ keyId
6464
+ });
6465
+ return data?.keys?.[0] ?? data?.key ?? data?.data ?? data;
6466
+ }
6467
+ /**
6468
+ * Revoke an existing key. Form-encoded POST per Spaceship's
6469
+ * `revoke_key!`. Used for cleaning up orphan keys created during
6470
+ * failed wizard runs.
6471
+ */
6472
+ async revokeApiKey(keyId) {
6473
+ await this.post("account/auth/key/revoke", {
6474
+ teamId: this.teamId,
6475
+ keyId
6476
+ });
6477
+ }
6478
+ // ── APNs Authentication Keys (.p8) ──────────────────────────────────────
6479
+ /** Apple's hardcoded service id for APNs auth keys (from Spaceship). */
6480
+ static APNS_SERVICE_ID = "U27F4V844T";
6481
+ /**
6482
+ * Create an APNs Authentication Key (.p8) via the developer portal.
6483
+ *
6484
+ * Apple requires BOTH `serviceConfigurations` (the map) AND
6485
+ * `serviceConfigurationsRequests` (the array of full config objects)
6486
+ * in the v2/create body. Just sending the map alone results in
6487
+ * "No value was provided for the parameter 'serviceConfigurations'".
6488
+ *
6489
+ * The exact body comes from @expo/apple-utils v2.1.21 — both fields
6490
+ * are produced by separate functions (`d` for the map, `h` for the
6491
+ * array) and merged into the create payload.
6492
+ */
6493
+ async createApnsAuthKey(rawName) {
6494
+ const name = rawName.replace(/[^A-Za-z0-9 _\-.]/g, " ").replace(/\s+/g, " ").trim().slice(0, 50);
6495
+ if (!name) throw new Error("createApnsAuthKey: name is empty after sanitization");
6496
+ try {
6497
+ await this.listApiKeys();
6498
+ } catch {
6499
+ }
6500
+ const body = {
6501
+ teamId: this.teamId,
6502
+ name,
6503
+ serviceConfigurations: {
6504
+ [_PortalClient.APNS_SERVICE_ID]: []
6505
+ },
6506
+ serviceConfigurationsRequests: [
6507
+ {
6508
+ isNew: true,
6509
+ serviceId: _PortalClient.APNS_SERVICE_ID,
6510
+ identifiers: {},
6511
+ environment: "all",
6512
+ scope: "team"
6513
+ }
6514
+ ],
6515
+ scope: "team"
6516
+ };
6517
+ const result = await this.postJson("account/auth/key/v2/create", body);
6518
+ const created = result.body?.keys?.[0];
6519
+ if (!created?.keyId) {
6520
+ throw new Error(`createApnsAuthKey: no key id in response. Body: ${result.rawText.slice(0, 400)}`);
6521
+ }
6522
+ const pem = await this.downloadApiKey(created.keyId);
6523
+ return { keyId: created.keyId, pem, raw: created };
6524
+ }
6525
+ /**
6526
+ * Find existing APNs auth keys in the team. Used by the wizard to
6527
+ * detect "you already have one" cases and offer to reuse rather than
6528
+ * proliferate keys.
6529
+ */
6530
+ async listApnsAuthKeys() {
6531
+ const list = await this.listApiKeys();
6532
+ return (list.keys ?? []).filter(
6533
+ (k) => (k.services ?? []).some((s) => s.id === _PortalClient.APNS_SERVICE_ID || /apns/i.test(s.name ?? ""))
6534
+ ).map((k) => ({
6535
+ keyId: k.keyId,
6536
+ keyName: k.keyName,
6537
+ canDownload: Boolean(k.canDownload)
6538
+ }));
6539
+ }
6540
+ /**
6541
+ * Download an existing App Store Connect API key as PEM. Spaceship's
6542
+ * `download_key` endpoint — GET with teamId + keyId in query string.
6543
+ * Returns the raw .p8 PEM text. Apple shows the .p8 exactly once
6544
+ * (after creation), so call this immediately after createApiKey.
6545
+ */
6546
+ async downloadApiKey(keyId) {
6547
+ const { status, rawText, contentType } = await this.getRaw("account/auth/key/download", {
6548
+ teamId: this.teamId,
6549
+ keyId
6550
+ });
6551
+ if (status !== 200) {
6552
+ throw new Error(`downloadApiKey failed (${status}): ${rawText.slice(0, 200)}`);
6553
+ }
6554
+ if (rawText.includes("BEGIN PRIVATE KEY")) return rawText;
6555
+ if (contentType.includes("json")) {
6556
+ try {
6557
+ const parsed = JSON.parse(rawText);
6558
+ const candidates = [
6559
+ parsed?.privateKey,
6560
+ parsed?.key?.privateKey,
6561
+ parsed?.keys?.[0]?.privateKey,
6562
+ parsed?.data?.attributes?.privateKey,
6563
+ parsed?.value
6564
+ ];
6565
+ for (const c of candidates) {
6566
+ if (typeof c === "string" && c.includes("BEGIN PRIVATE KEY")) return c;
6567
+ }
6568
+ } catch {
6569
+ }
6570
+ }
6571
+ throw new Error(`downloadApiKey returned no PEM. Content-Type=${contentType} body=${rawText.slice(0, 300)}`);
6572
+ }
6573
+ /**
6574
+ * List existing API keys via the portal. Used to discover the team's
6575
+ * issuer id — every key in the team shares the same issuer id, and
6576
+ * altool needs it alongside the key id and .p8 file.
6577
+ *
6578
+ * Form-encoded POST (NOT JSON), with pagination params, per Spaceship's
6579
+ * `list_keys` method. JSON returned 415 from this endpoint.
6580
+ */
6581
+ async listApiKeys() {
6582
+ const data = await this.post("account/auth/key/list", {
6583
+ teamId: this.teamId,
6584
+ pageNumber: "1",
6585
+ pageSize: "500",
6586
+ sort: "name=asc"
6587
+ });
6588
+ const keys = data?.keys ?? [];
6589
+ const issuerId = data?.issuerId ?? data?.issuer ?? data?.team?.issuerId ?? keys[0]?.issuerId ?? keys[0]?.issuer;
6590
+ return { keys, issuerId };
6591
+ }
6114
6592
  async post(path, params) {
6115
6593
  const body = new URLSearchParams();
6116
6594
  for (const [k, v] of Object.entries(params)) {
@@ -6178,6 +6656,31 @@ var init_portal = __esm({
6178
6656
  async deleteAppId(appIdId) {
6179
6657
  await this.post("account/ios/identifiers/deleteAppId.action", { teamId: this.teamId, appIdId });
6180
6658
  }
6659
+ /**
6660
+ * Toggle a capability (a.k.a. "service") on a bundle ID. Mirrors
6661
+ * Spaceship::Portal's `update_service` — the legacy portal endpoint
6662
+ * still works and is the only session-cookie-authenticated way to flip
6663
+ * capabilities like Push Notifications and Sign in with Apple from
6664
+ * outside the Apple Developer web UI.
6665
+ *
6666
+ * Common service codes (from Spaceship portal/portal_client.rb):
6667
+ * push → push notifications
6668
+ * APG3427HIY → Sign in with Apple
6669
+ * IAD53UNK2F → in-app purchase
6670
+ * homeKit → HomeKit
6671
+ * healthKit → HealthKit
6672
+ *
6673
+ * @param featureType Apple's internal capability key (string code or short name)
6674
+ * @param enabled true → turn on, false → turn off
6675
+ */
6676
+ async setBundleCapability(params) {
6677
+ await this.post("account/ios/identifiers/updateAppService.action", {
6678
+ teamId: this.teamId,
6679
+ displayId: params.appIdId,
6680
+ featureType: params.featureType,
6681
+ featureValue: params.enabled ? "on" : "off"
6682
+ });
6683
+ }
6181
6684
  // ── Certificates ───────────────────────────────────────────────────────
6182
6685
  async listCertificates(types) {
6183
6686
  const iosTypes = types ?? [
@@ -6195,12 +6698,21 @@ var init_portal = __esm({
6195
6698
  return data.certRequests ?? [];
6196
6699
  }
6197
6700
  async listPushCertificates() {
6701
+ const types = Array.from(
6702
+ /* @__PURE__ */ new Set([
6703
+ _PortalClient.CERT_TYPES.IOS_PRODUCTION_PUSH,
6704
+ _PortalClient.CERT_TYPES.IOS_DEVELOPMENT_PUSH,
6705
+ // Legacy push codes from OLDER_IOS_CERTIFICATE_TYPES
6706
+ "3BQKVH9I2X",
6707
+ "BKLRAVXMGM"
6708
+ ])
6709
+ );
6198
6710
  const data = await this.post("account/ios/certificate/listCertRequests.action", {
6199
6711
  teamId: this.teamId,
6200
6712
  pageSize: "500",
6201
6713
  pageNumber: "1",
6202
6714
  sort: "certRequestStatusCode=asc",
6203
- types: [_PortalClient.CERT_TYPES.IOS_PRODUCTION_PUSH, _PortalClient.CERT_TYPES.IOS_DEVELOPMENT_PUSH].join(",")
6715
+ types: types.join(",")
6204
6716
  });
6205
6717
  return data.certRequests ?? [];
6206
6718
  }
@@ -6342,18 +6854,332 @@ var init_portal = __esm({
6342
6854
  }
6343
6855
  });
6344
6856
 
6857
+ // src/client/iris.ts
6858
+ var IRIS_BASE, IrisClient, IrisAuthError;
6859
+ var init_iris = __esm({
6860
+ "src/client/iris.ts"() {
6861
+ IRIS_BASE = "https://appstoreconnect.apple.com/iris/v1";
6862
+ IrisClient = class {
6863
+ constructor(session) {
6864
+ this.session = session;
6865
+ this.cookieStr = Object.entries(session.cookies).map(([k, v]) => `${k}=${v}`).join("; ");
6866
+ }
6867
+ session;
6868
+ cookieStr;
6869
+ buildHeaders() {
6870
+ return {
6871
+ Cookie: this.cookieStr,
6872
+ Accept: "application/vnd.api+json, application/json, text/plain, */*",
6873
+ "Content-Type": "application/vnd.api+json",
6874
+ "X-Requested-With": "XMLHttpRequest",
6875
+ // Mimic the App Store Connect web UI's user agent
6876
+ "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"
6877
+ };
6878
+ }
6879
+ /**
6880
+ * Issue a request and absorb any new cookies (Apple rotates session
6881
+ * cookies on a lot of iris calls).
6882
+ */
6883
+ async request(method, path, body) {
6884
+ const headers = this.buildHeaders();
6885
+ if (process.env.FASTNODE_DEBUG) {
6886
+ console.log(`[iris] ${method} ${path}${body ? ` body=${JSON.stringify(body).slice(0, 200)}` : ""}`);
6887
+ }
6888
+ const res = await fetch(`${IRIS_BASE}${path}`, {
6889
+ method,
6890
+ headers,
6891
+ body: body ? JSON.stringify(body) : void 0
6892
+ });
6893
+ for (const raw of res.headers.getSetCookie?.() ?? []) {
6894
+ const m = raw.match(/^([^=]+)=([^;]*)/);
6895
+ if (m) {
6896
+ this.session.cookies[m[1]] = m[2];
6897
+ }
6898
+ }
6899
+ this.cookieStr = Object.entries(this.session.cookies).map(([k, v]) => `${k}=${v}`).join("; ");
6900
+ const text = await res.text();
6901
+ let parsed = null;
6902
+ try {
6903
+ parsed = text ? JSON.parse(text) : null;
6904
+ } catch {
6905
+ }
6906
+ if (process.env.FASTNODE_DEBUG) {
6907
+ console.log(`[iris] \u2192 ${res.status} ${text.slice(0, 300)}`);
6908
+ }
6909
+ return { status: res.status, body: parsed, rawText: text };
6910
+ }
6911
+ /**
6912
+ * List existing API keys. Used both as a sanity check (the user has
6913
+ * permission) and to discover the team's issuer id (which is the same
6914
+ * for every key in the team and is needed by altool).
6915
+ *
6916
+ * Important: Apple's iris endpoint rejects most query parameters with
6917
+ * `PARAMETER_ERROR.INVALID`. Call with no params and let the API return
6918
+ * its default page.
6919
+ */
6920
+ async listApiKeys() {
6921
+ const { status, body, rawText } = await this.request("GET", "/apiKeys");
6922
+ if (status === 403) {
6923
+ throw new IrisAuthError(
6924
+ "You don't have permission to manage App Store Connect API keys (this requires the Account Holder or Admin role)."
6925
+ );
6926
+ }
6927
+ if (status >= 400 || !body) {
6928
+ throw new Error(`iris listApiKeys failed (${status}): ${rawText.slice(0, 200)}`);
6929
+ }
6930
+ const issuerId = body?.meta?.issuerId ?? body?.data?.[0]?.attributes?.issuerId;
6931
+ const keys = (body.data ?? []).map((d) => ({
6932
+ id: d.id,
6933
+ kid: d.attributes?.kid ?? d.id,
6934
+ nickname: d.attributes?.nickname ?? "",
6935
+ issuerId: d.attributes?.issuerId ?? issuerId,
6936
+ roles: d.attributes?.roles ?? [],
6937
+ allAppsVisible: d.attributes?.allAppsVisible ?? true
6938
+ }));
6939
+ return { keys, issuerId };
6940
+ }
6941
+ /**
6942
+ * Create a new API key. Apple returns the .p8 PEM exactly once in the
6943
+ * create response — capture it immediately or the key is dead weight.
6944
+ *
6945
+ * `keyType` is required by Apple's iris API:
6946
+ * • PUBLIC_API — the standard team-wide API key (what TestFlight uploads need)
6947
+ * • MARKETING_API — for App Analytics access only
6948
+ */
6949
+ async createApiKey(input) {
6950
+ const requestBody = {
6951
+ data: {
6952
+ type: "apiKeys",
6953
+ attributes: {
6954
+ nickname: input.nickname,
6955
+ roles: input.roles ?? ["APP_MANAGER"],
6956
+ allAppsVisible: input.allAppsVisible ?? true,
6957
+ keyType: input.keyType ?? "PUBLIC_API"
6958
+ }
6959
+ }
6960
+ };
6961
+ console.log("[iris] createApiKey request:", JSON.stringify(requestBody));
6962
+ const { status, body, rawText } = await this.request("POST", "/apiKeys", requestBody);
6963
+ console.log(`[iris] createApiKey response: ${status} ${rawText.slice(0, 800)}`);
6964
+ if (status === 403) {
6965
+ throw new IrisAuthError(
6966
+ "You don't have permission to create App Store Connect API keys (this requires the Account Holder or Admin role)."
6967
+ );
6968
+ }
6969
+ if (status >= 400 || !body) {
6970
+ const msg = body?.errors?.[0]?.detail ?? body?.errors?.[0]?.title ?? rawText.slice(0, 300) ?? `iris createApiKey failed (${status})`;
6971
+ throw new Error(msg);
6972
+ }
6973
+ const data = body.data ?? body;
6974
+ if (!data?.id) {
6975
+ throw new Error(`iris createApiKey returned no key id. Raw response: ${rawText.slice(0, 400)}`);
6976
+ }
6977
+ const key = {
6978
+ id: data.id,
6979
+ kid: data.attributes?.kid ?? data.id,
6980
+ nickname: data.attributes?.nickname ?? input.nickname,
6981
+ privateKey: data.attributes?.privateKey,
6982
+ issuerId: data.attributes?.issuerId,
6983
+ roles: data.attributes?.roles ?? input.roles ?? ["APP_MANAGER"],
6984
+ allAppsVisible: data.attributes?.allAppsVisible ?? true
6985
+ };
6986
+ return key;
6987
+ }
6988
+ /**
6989
+ * Fetch the .p8 PEM AND the team's issuer id for a previously-created
6990
+ * ASC API key. Both come back in a single request via:
6991
+ *
6992
+ * GET /iris/v1/apiKeys/{id}?fields[apiKeys]=privateKey&include=provider
6993
+ *
6994
+ * Sparse fieldset requesting ONLY `privateKey` is the magic that makes
6995
+ * Apple actually include the (base64-encoded) PEM in the response —
6996
+ * the default view returns `privateKey: null`. The `include=provider`
6997
+ * pulls the team's contentProvider record into `included[]`, and its
6998
+ * `id` field IS the issuer id altool needs (a UUID like
6999
+ * `cfadaf94-44ca-4c2c-8fa6-ecc28d3c7d0d`).
7000
+ *
7001
+ * Reverse-engineered from @expo/apple-utils v2.1.21 (the package that
7002
+ * powers EAS CLI), specifically the `ApiKey.downloadAsync` method
7003
+ * combined with `ApiKey.infoAsync` reading `provider?.id`.
7004
+ *
7005
+ * Returns `{ pem, issuerId }`, or `null` if Apple won't return the
7006
+ * private key (typically because the key was already downloaded once).
7007
+ */
7008
+ async fetchApiKeyPrivateKey(keyId) {
7009
+ try {
7010
+ const url = `${IRIS_BASE}/apiKeys/${keyId}?fields%5BapiKeys%5D=privateKey&include=provider`;
7011
+ const res = await fetch(url, {
7012
+ headers: {
7013
+ ...this.buildHeaders(),
7014
+ Accept: "application/vnd.api+json, application/json, text/plain, */*"
7015
+ }
7016
+ });
7017
+ const text = await res.text();
7018
+ console.log(`[iris] fetchApiKeyPrivateKey \u2192 ${res.status} (${text.length} bytes)`);
7019
+ if (res.status !== 200) {
7020
+ console.log(`[iris] err: ${text.slice(0, 300)}`);
7021
+ return null;
7022
+ }
7023
+ const body = JSON.parse(text);
7024
+ const encoded = body?.data?.attributes?.privateKey;
7025
+ if (typeof encoded !== "string" || encoded.length === 0) {
7026
+ console.log(`[iris] no privateKey in response`);
7027
+ return null;
7028
+ }
7029
+ const pem = Buffer.from(encoded, "base64").toString("utf-8");
7030
+ if (!pem.includes("BEGIN PRIVATE KEY")) {
7031
+ console.log(`[iris] decoded body didn't contain PEM marker`);
7032
+ return null;
7033
+ }
7034
+ const provider = (body?.included ?? []).find((i) => i.type === "contentProviders");
7035
+ const issuerId = provider?.id;
7036
+ console.log(`[iris] \u2713 PEM ${pem.length} bytes, issuerId=${issuerId ?? "(missing)"}`);
7037
+ return { pem, issuerId };
7038
+ } catch (err) {
7039
+ console.log(`[iris] fetchApiKeyPrivateKey error: ${err.message}`);
7040
+ return null;
7041
+ }
7042
+ }
7043
+ /**
7044
+ * @deprecated Kept as a fallback probe for debugging. The real path
7045
+ * is the sparse fieldset above — everything in this brute-force list
7046
+ * returned 404 during testing. Left here so we can re-verify if Apple
7047
+ * changes anything.
7048
+ */
7049
+ async fetchApiKeyPrivateKeyBruteForce(keyId) {
7050
+ const attempts = [
7051
+ // Sparse fieldsets — JSON-API spec lets us request specific attributes.
7052
+ // Apple may exclude privateKey by default and return it only when asked.
7053
+ { kind: "GET", path: `/apiKeys/${keyId}?fields[apiKeys]=privateKey,kid,issuerId,nickname,roles` },
7054
+ { kind: "GET", path: `/apiKeys/${keyId}?include=privateKey` },
7055
+ { kind: "GET", path: `/apiKeys/${keyId}?fields[apiKeys]=privateKey` },
7056
+ // Custom Accept headers — maybe Apple negotiates content type
7057
+ { kind: "GET", path: `/apiKeys/${keyId}`, accept: "application/x-pem-file" },
7058
+ { kind: "GET", path: `/apiKeys/${keyId}`, accept: "application/octet-stream" },
7059
+ { kind: "GET", path: `/apiKeys/${keyId}/p8`, accept: "application/x-pem-file" },
7060
+ // POST variants — Apple sometimes uses POST to mint a download token
7061
+ { kind: "POST", path: `/apiKeys/${keyId}/secrets`, body: {} },
7062
+ { kind: "POST", path: `/apiKeys/${keyId}/regenerate`, body: {} },
7063
+ { kind: "POST", path: `/apiKeys/${keyId}/p8`, body: {} },
7064
+ // Bare GET (last) — confirms canonical fields, in case my parser missed any
7065
+ { kind: "GET", path: `/apiKeys/${keyId}` },
7066
+ // Different host — the legacy developer.apple.com user-and-access namespace
7067
+ { kind: "ABSOLUTE", url: `https://appstoreconnect.apple.com/api/v1/apiKeys/${keyId}/p8` },
7068
+ { kind: "ABSOLUTE", url: `https://appstoreconnect.apple.com/access/api/keys/${keyId}/download` }
7069
+ ];
7070
+ for (const attempt of attempts) {
7071
+ try {
7072
+ let result;
7073
+ if (attempt.kind === "GET") {
7074
+ result = await this.requestWithHeaders("GET", attempt.path, void 0, {
7075
+ ...attempt.accept ? { Accept: attempt.accept } : {}
7076
+ });
7077
+ console.log(`[iris] fetchApiKeyPrivateKey GET ${attempt.path}${attempt.accept ? ` accept=${attempt.accept}` : ""} \u2192 ${result.status} (${result.rawText.length} bytes)`);
7078
+ } else if (attempt.kind === "POST") {
7079
+ result = await this.request("POST", attempt.path, attempt.body);
7080
+ console.log(`[iris] fetchApiKeyPrivateKey POST ${attempt.path} \u2192 ${result.status} (${result.rawText.length} bytes)`);
7081
+ } else {
7082
+ result = await this.requestAbsolute("GET", attempt.url);
7083
+ console.log(`[iris] fetchApiKeyPrivateKey GET ${attempt.url} \u2192 ${result.status} (${result.rawText.length} bytes)`);
7084
+ }
7085
+ if (result.status === 200) {
7086
+ console.log(`[iris] body: ${result.rawText.slice(0, 1500)}`);
7087
+ }
7088
+ if (result.status !== 200) continue;
7089
+ if (result.rawText && result.rawText.includes("BEGIN PRIVATE KEY")) {
7090
+ console.log(`[iris] \u2713 found PEM (plain text response)`);
7091
+ return result.rawText;
7092
+ }
7093
+ if (result.body) {
7094
+ const candidates = [
7095
+ result.body?.data?.attributes?.privateKey,
7096
+ result.body?.data?.attributes?.p8,
7097
+ result.body?.data?.attributes?.privateKeyContent,
7098
+ result.body?.data?.attributes?.kpem,
7099
+ result.body?.data?.attributes?.secret,
7100
+ result.body?.data?.attributes?.keyContent,
7101
+ result.body?.privateKey,
7102
+ result.body?.p8,
7103
+ result.body?.value,
7104
+ result.body?.secret
7105
+ ];
7106
+ for (const c of candidates) {
7107
+ if (typeof c === "string" && c.includes("BEGIN PRIVATE KEY")) {
7108
+ console.log(`[iris] \u2713 found PEM in JSON response`);
7109
+ return c;
7110
+ }
7111
+ }
7112
+ }
7113
+ } catch (err) {
7114
+ console.log(`[iris] fetchApiKeyPrivateKey attempt failed: ${err.message}`);
7115
+ }
7116
+ }
7117
+ console.log(`[iris] fetchApiKeyPrivateKey: no working download path for key ${keyId}`);
7118
+ return null;
7119
+ }
7120
+ /** Internal: like request() but lets us override headers. */
7121
+ async requestWithHeaders(method, path, body, extraHeaders = {}) {
7122
+ const headers = { ...this.buildHeaders(), ...extraHeaders };
7123
+ const res = await fetch(`${IRIS_BASE}${path}`, {
7124
+ method,
7125
+ headers,
7126
+ body: body ? JSON.stringify(body) : void 0
7127
+ });
7128
+ for (const raw of res.headers.getSetCookie?.() ?? []) {
7129
+ const m = raw.match(/^([^=]+)=([^;]*)/);
7130
+ if (m) this.session.cookies[m[1]] = m[2];
7131
+ }
7132
+ this.cookieStr = Object.entries(this.session.cookies).map(([k, v]) => `${k}=${v}`).join("; ");
7133
+ const text = await res.text();
7134
+ let parsed = null;
7135
+ try {
7136
+ parsed = text ? JSON.parse(text) : null;
7137
+ } catch {
7138
+ }
7139
+ return { status: res.status, body: parsed, rawText: text };
7140
+ }
7141
+ /** Internal: fetch an absolute URL with the session cookies. */
7142
+ async requestAbsolute(method, url) {
7143
+ const headers = this.buildHeaders();
7144
+ const res = await fetch(url, { method, headers });
7145
+ const text = await res.text();
7146
+ let parsed = null;
7147
+ try {
7148
+ parsed = text ? JSON.parse(text) : null;
7149
+ } catch {
7150
+ }
7151
+ return { status: res.status, body: parsed, rawText: text };
7152
+ }
7153
+ async deleteApiKey(keyId) {
7154
+ await this.request("DELETE", `/apiKeys/${keyId}`);
7155
+ }
7156
+ };
7157
+ IrisAuthError = class extends Error {
7158
+ constructor(message) {
7159
+ super(message);
7160
+ this.name = "IrisAuthError";
7161
+ }
7162
+ };
7163
+ }
7164
+ });
7165
+
6345
7166
  // src/client/index.ts
6346
7167
  var client_exports = {};
6347
7168
  __export(client_exports, {
6348
7169
  AppStoreConnectClient: () => AppStoreConnectClient,
6349
7170
  AppStoreConnectError: () => AppStoreConnectError,
7171
+ IrisAuthError: () => IrisAuthError,
7172
+ IrisClient: () => IrisClient,
6350
7173
  PortalClient: () => PortalClient,
6351
7174
  ProgramLicenseAgreementError: () => ProgramLicenseAgreementError,
6352
7175
  RateLimitError: () => RateLimitError,
6353
7176
  RequestClient: () => RequestClient,
6354
7177
  TokenManager: () => TokenManager,
7178
+ beginLogin: () => beginLogin,
6355
7179
  checkPortalResponse: () => checkPortalResponse,
6356
- loginWithAppleId: () => loginWithAppleId
7180
+ loginWithAppleId: () => loginWithAppleId,
7181
+ requestSmsCode: () => requestSmsCode,
7182
+ submitTwoFactorCode: () => submitTwoFactorCode
6357
7183
  });
6358
7184
  var AppStoreConnectClient;
6359
7185
  var init_client = __esm({
@@ -6398,6 +7224,7 @@ var init_client = __esm({
6398
7224
  init_request();
6399
7225
  init_apple_session();
6400
7226
  init_portal();
7227
+ init_iris();
6401
7228
  AppStoreConnectClient = class {
6402
7229
  http;
6403
7230
  certificates;