@sitepong/fastnode 0.1.2 → 0.2.1

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 (70) hide show
  1. package/README.md +148 -0
  2. package/dist/actions/index.cjs +758 -110
  3. package/dist/actions/index.cjs.map +1 -1
  4. package/dist/actions/index.mjs +758 -110
  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-owkOFNW8.d.ts → cert-e5GAgAPb.d.ts} +1 -1
  13. package/dist/{cert-BmJGtYtb.d.cts → cert-uLLdb5a7.d.cts} +1 -1
  14. package/dist/cli/index.cjs +758 -110
  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 +758 -110
  19. package/dist/cli/index.mjs.map +1 -1
  20. package/dist/client/index.cjs +751 -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 +747 -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-BFdNOmPJ.d.cts → index-BN0iWhuw.d.cts} +1 -1
  29. package/dist/index-BNP7Bpu5.d.ts +61 -0
  30. package/dist/{index-1Vu2cRQ2.d.ts → index-BbY_H_f6.d.ts} +1 -1
  31. package/dist/{index-D6zjGlPL.d.cts → index-BgHagzj1.d.cts} +1 -1
  32. package/dist/{index-D5eihzwM.d.cts → index-BjkOUQcQ.d.cts} +1 -1
  33. package/dist/{index-D1Izm7qt.d.ts → index-BwwpAlk2.d.ts} +363 -2
  34. package/dist/{index-A5MimeQk.d.ts → index-C2YLoFVl.d.ts} +1 -1
  35. package/dist/{index-TfXqwuac.d.ts → index-CEldrbyz.d.ts} +1 -1
  36. package/dist/{index-BLubSlgK.d.cts → index-CdfgEZwh.d.cts} +363 -2
  37. package/dist/{index-DfCUVJX1.d.cts → index-Clyf4-lu.d.cts} +1 -1
  38. package/dist/index-CtydPNxA.d.cts +61 -0
  39. package/dist/{index-BQJIJlK7.d.cts → index-DHxi-QPC.d.cts} +3 -3
  40. package/dist/{index-BN0ubxjZ.d.ts → index-Di4Ic0EE.d.ts} +3 -3
  41. package/dist/{index-EcVvViW8.d.cts → index-DrCOh0Vh.d.cts} +1 -1
  42. package/dist/{index-B0yhu_LZ.d.ts → index-EKU_G1G5.d.ts} +1 -1
  43. package/dist/{index-CWNLnSOL.d.cts → index-XsMsVc3O.d.cts} +1 -1
  44. package/dist/{index-B9yXicrQ.d.ts → index-jeI44Q5G.d.ts} +1 -1
  45. package/dist/{index-DHw08dUc.d.ts → index-mddpvrRX.d.ts} +1 -1
  46. package/dist/index.cjs +1233 -110
  47. package/dist/index.cjs.map +1 -1
  48. package/dist/index.d.cts +226 -10
  49. package/dist/index.d.ts +226 -10
  50. package/dist/index.mjs +1230 -111
  51. package/dist/index.mjs.map +1 -1
  52. package/dist/lane/index.cjs +758 -110
  53. package/dist/lane/index.cjs.map +1 -1
  54. package/dist/lane/index.mjs +758 -110
  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.d.cts +2 -2
  61. package/dist/pilot/index.d.ts +2 -2
  62. package/dist/precheck/index.d.cts +2 -2
  63. package/dist/precheck/index.d.ts +2 -2
  64. package/dist/produce/index.d.cts +2 -2
  65. package/dist/produce/index.d.ts +2 -2
  66. package/dist/sigh/index.d.cts +2 -2
  67. package/dist/sigh/index.d.ts +2 -2
  68. package/package.json +3 -1
  69. package/dist/index-DfirmFbC.d.ts +0 -32
  70. package/dist/index-lt819Jgj.d.cts +0 -32
@@ -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));
@@ -6291,6 +6311,12 @@ var init_xcode_metrics = __esm({
6291
6311
  });
6292
6312
 
6293
6313
  // src/client/portal.ts
6314
+ function pickUniqueKeyName(base, taken) {
6315
+ if (!taken.has(base)) return base;
6316
+ let n = 1;
6317
+ while (taken.has(`${base} - ${n}`)) n++;
6318
+ return `${base} - ${n}`;
6319
+ }
6294
6320
  var PORTAL_BASE, PortalClient;
6295
6321
  var init_portal = __esm({
6296
6322
  "src/client/portal.ts"() {
@@ -6311,6 +6337,279 @@ var init_portal = __esm({
6311
6337
  async init() {
6312
6338
  await this.post("account/listTeams.action", {});
6313
6339
  }
6340
+ /**
6341
+ * JSON POST — different content type than the standard form-encoded
6342
+ * `post()`. Used by the App Store Connect API key endpoints
6343
+ * (`account/auth/key/v2/create`), which Spaceship discovered take a
6344
+ * JSON body even though every other portal mutation is form-encoded.
6345
+ *
6346
+ * Like the form-encoded `post()`, this also runs the response through
6347
+ * `checkPortalResponse` — Apple returns HTTP 200 even for errors and
6348
+ * encodes the error in `resultCode`/`userString` fields, so a raw
6349
+ * status check would silently miss real failures.
6350
+ */
6351
+ async postJson(path, body) {
6352
+ const headers = {
6353
+ Cookie: this.cookieStr,
6354
+ "Content-Type": "application/json",
6355
+ Accept: "application/json"
6356
+ };
6357
+ if (this.csrf) {
6358
+ headers["csrf"] = this.csrf;
6359
+ headers["csrf_ts"] = this.csrfTs;
6360
+ }
6361
+ console.log(`[portal] POST(json) ${path}`);
6362
+ const res = await fetch(`${PORTAL_BASE}/${path}`, {
6363
+ method: "POST",
6364
+ headers,
6365
+ body: JSON.stringify(body)
6366
+ });
6367
+ if (res.headers.get("csrf")) {
6368
+ this.csrf = res.headers.get("csrf");
6369
+ this.csrfTs = res.headers.get("csrf_ts") ?? "";
6370
+ }
6371
+ for (const raw of res.headers.getSetCookie?.() ?? []) {
6372
+ const m = raw.match(/^([^=]+)=([^;]*)/);
6373
+ if (m && !this.cookieStr.includes(m[1] + "=")) this.cookieStr += "; " + m[1] + "=" + m[2];
6374
+ }
6375
+ const text = await res.text();
6376
+ let data = null;
6377
+ try {
6378
+ data = text ? JSON.parse(text) : null;
6379
+ } catch {
6380
+ }
6381
+ console.log(`[portal] POST(json) ${path} \u2192 ${res.status} ${text.slice(0, 400)}`);
6382
+ checkPortalResponse(data, this.session);
6383
+ return { status: res.status, body: data, rawText: text };
6384
+ }
6385
+ /**
6386
+ * GET helper for the portal endpoints that take query parameters
6387
+ * (currently just `account/auth/key/download`). Returns the raw text
6388
+ * since download endpoints can return PEMs or JSON depending on Apple's
6389
+ * mood — caller decides how to parse.
6390
+ */
6391
+ async getRaw(path, params = {}) {
6392
+ const url = new URL(`${PORTAL_BASE}/${path}`);
6393
+ for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
6394
+ const headers = {
6395
+ Cookie: this.cookieStr,
6396
+ Accept: "application/json, text/plain, application/x-pem-file, */*"
6397
+ };
6398
+ if (this.csrf) {
6399
+ headers["csrf"] = this.csrf;
6400
+ headers["csrf_ts"] = this.csrfTs;
6401
+ }
6402
+ console.log(`[portal] GET ${url.pathname}${url.search}`);
6403
+ const res = await fetch(url.toString(), { headers });
6404
+ for (const raw of res.headers.getSetCookie?.() ?? []) {
6405
+ const m = raw.match(/^([^=]+)=([^;]*)/);
6406
+ if (m && !this.cookieStr.includes(m[1] + "=")) this.cookieStr += "; " + m[1] + "=" + m[2];
6407
+ }
6408
+ const text = await res.text();
6409
+ const contentType = res.headers.get("content-type") ?? "";
6410
+ console.log(`[portal] GET ${url.pathname} \u2192 ${res.status} ${contentType} ${text.length}b`);
6411
+ return { status: res.status, rawText: text, contentType };
6412
+ }
6413
+ // ── App Store Connect API Keys (.p8) ────────────────────────────────────
6414
+ /**
6415
+ * Create an App Store Connect API key via the developer portal's
6416
+ * `account/auth/key/v2/create` endpoint. Reverse-engineered from the
6417
+ * _current_ @expo/apple-utils npm package (v2.1.21), which is what
6418
+ * EAS CLI uses to manage Apple credentials in production.
6419
+ *
6420
+ * This differs from older published reverse-engineering guides:
6421
+ * • URL uses the `/v2/create` suffix (Apple kept it)
6422
+ * • Field is `serviceConfigurations`, shape is an object keyed by
6423
+ * service id (NOT `serviceConfigurationsRequests: [...]` array)
6424
+ * • Body REQUIRES `scope: "team"`
6425
+ * • Needs a scope-specific CSRF warmup via the `keys` endpoint
6426
+ * before the create call (EAS's `ensureCSRFAsync("keys", …)`)
6427
+ *
6428
+ * For an App Store Connect API key (PUBLIC_API, used by altool for
6429
+ * TestFlight uploads), `serviceConfigurations` is an empty object `{}`.
6430
+ * For an APNs auth key, it's `{ "U27F4V844T": [] }`. For MusicKit:
6431
+ * `{ "6A7HVUVQ3M": [musicId] }`, etc.
6432
+ *
6433
+ * Apple's name validator rejects parentheses, brackets, and most
6434
+ * punctuation — sanitize to alphanumeric + space + dash + underscore
6435
+ * + period and collapse whitespace.
6436
+ */
6437
+ async createApiKey(rawName, serviceConfigurations = {}) {
6438
+ const baseName = rawName.replace(/[^A-Za-z0-9 _\-.]/g, " ").replace(/\s+/g, " ").trim().slice(0, 45);
6439
+ if (!baseName) throw new Error("createApiKey: name is empty after sanitization");
6440
+ let existingNames = /* @__PURE__ */ new Set();
6441
+ try {
6442
+ const list = await this.listApiKeys();
6443
+ existingNames = new Set(
6444
+ (list.keys ?? []).map((k) => String(k.keyName ?? "").trim())
6445
+ );
6446
+ } catch {
6447
+ }
6448
+ const name = pickUniqueKeyName(baseName, existingNames);
6449
+ const body = {
6450
+ teamId: this.teamId,
6451
+ name,
6452
+ serviceConfigurations,
6453
+ scope: "team"
6454
+ };
6455
+ const result = await this.postJson("account/auth/key/v2/create", body);
6456
+ const created = result.body?.keys?.[0] ?? result.body?.key ?? result.body?.data ?? result.body;
6457
+ const keyId = created?.keyId ?? created?.id ?? created?.kid ?? created?.attributes?.kid;
6458
+ if (!keyId) {
6459
+ throw new Error(`createApiKey: no key id in response. Body: ${result.rawText.slice(0, 400)}`);
6460
+ }
6461
+ return { keyId, raw: created };
6462
+ }
6463
+ /**
6464
+ * Fetch a single API key by id via `account/auth/key/get`. Reverse-
6465
+ * engineered from Spaceship's `get_key`. Returns the raw key record so
6466
+ * the caller can extract whatever fields it needs (e.g. issuerId).
6467
+ *
6468
+ * Form-encoded POST — same shape as every other PortalClient mutation
6469
+ * except the JSON `create` endpoint.
6470
+ */
6471
+ async getApiKey(keyId) {
6472
+ const data = await this.post("account/auth/key/get", {
6473
+ teamId: this.teamId,
6474
+ keyId
6475
+ });
6476
+ return data?.keys?.[0] ?? data?.key ?? data?.data ?? data;
6477
+ }
6478
+ /**
6479
+ * Revoke an existing key. Form-encoded POST per Spaceship's
6480
+ * `revoke_key!`. Used for cleaning up orphan keys created during
6481
+ * failed wizard runs.
6482
+ */
6483
+ async revokeApiKey(keyId) {
6484
+ await this.post("account/auth/key/revoke", {
6485
+ teamId: this.teamId,
6486
+ keyId
6487
+ });
6488
+ }
6489
+ // ── APNs Authentication Keys (.p8) ──────────────────────────────────────
6490
+ /** Apple's hardcoded service id for APNs auth keys (from Spaceship). */
6491
+ static APNS_SERVICE_ID = "U27F4V844T";
6492
+ /**
6493
+ * Create an APNs Authentication Key (.p8) via the developer portal.
6494
+ *
6495
+ * Apple requires BOTH `serviceConfigurations` (the map) AND
6496
+ * `serviceConfigurationsRequests` (the array of full config objects)
6497
+ * in the v2/create body. Just sending the map alone results in
6498
+ * "No value was provided for the parameter 'serviceConfigurations'".
6499
+ *
6500
+ * The exact body comes from @expo/apple-utils v2.1.21 — both fields
6501
+ * are produced by separate functions (`d` for the map, `h` for the
6502
+ * array) and merged into the create payload.
6503
+ *
6504
+ * Apple also rejects duplicate key names ("Another key with same
6505
+ * name exists") — we dedupe by listing existing keys first and
6506
+ * appending " (N)" until we find a free slot, mirroring the
6507
+ * provisioning profile dedup.
6508
+ */
6509
+ async createApnsAuthKey(rawName) {
6510
+ const baseName = rawName.replace(/[^A-Za-z0-9 _\-.]/g, " ").replace(/\s+/g, " ").trim().slice(0, 45);
6511
+ if (!baseName) throw new Error("createApnsAuthKey: name is empty after sanitization");
6512
+ let existingNames = /* @__PURE__ */ new Set();
6513
+ try {
6514
+ const list = await this.listApiKeys();
6515
+ existingNames = new Set(
6516
+ (list.keys ?? []).map((k) => String(k.keyName ?? "").trim())
6517
+ );
6518
+ } catch {
6519
+ }
6520
+ const name = pickUniqueKeyName(baseName, existingNames);
6521
+ const body = {
6522
+ teamId: this.teamId,
6523
+ name,
6524
+ serviceConfigurations: {
6525
+ [_PortalClient.APNS_SERVICE_ID]: []
6526
+ },
6527
+ serviceConfigurationsRequests: [
6528
+ {
6529
+ isNew: true,
6530
+ serviceId: _PortalClient.APNS_SERVICE_ID,
6531
+ identifiers: {},
6532
+ environment: "all",
6533
+ scope: "team"
6534
+ }
6535
+ ],
6536
+ scope: "team"
6537
+ };
6538
+ const result = await this.postJson("account/auth/key/v2/create", body);
6539
+ const created = result.body?.keys?.[0];
6540
+ if (!created?.keyId) {
6541
+ throw new Error(`createApnsAuthKey: no key id in response. Body: ${result.rawText.slice(0, 400)}`);
6542
+ }
6543
+ const pem = await this.downloadApiKey(created.keyId);
6544
+ return { keyId: created.keyId, pem, raw: created };
6545
+ }
6546
+ /**
6547
+ * Find existing APNs auth keys in the team. Used by the wizard to
6548
+ * detect "you already have one" cases and offer to reuse rather than
6549
+ * proliferate keys.
6550
+ */
6551
+ async listApnsAuthKeys() {
6552
+ const list = await this.listApiKeys();
6553
+ return (list.keys ?? []).filter(
6554
+ (k) => (k.services ?? []).some((s) => s.id === _PortalClient.APNS_SERVICE_ID || /apns/i.test(s.name ?? ""))
6555
+ ).map((k) => ({
6556
+ keyId: k.keyId,
6557
+ keyName: k.keyName,
6558
+ canDownload: Boolean(k.canDownload)
6559
+ }));
6560
+ }
6561
+ /**
6562
+ * Download an existing App Store Connect API key as PEM. Spaceship's
6563
+ * `download_key` endpoint — GET with teamId + keyId in query string.
6564
+ * Returns the raw .p8 PEM text. Apple shows the .p8 exactly once
6565
+ * (after creation), so call this immediately after createApiKey.
6566
+ */
6567
+ async downloadApiKey(keyId) {
6568
+ const { status, rawText, contentType } = await this.getRaw("account/auth/key/download", {
6569
+ teamId: this.teamId,
6570
+ keyId
6571
+ });
6572
+ if (status !== 200) {
6573
+ throw new Error(`downloadApiKey failed (${status}): ${rawText.slice(0, 200)}`);
6574
+ }
6575
+ if (rawText.includes("BEGIN PRIVATE KEY")) return rawText;
6576
+ if (contentType.includes("json")) {
6577
+ try {
6578
+ const parsed = JSON.parse(rawText);
6579
+ const candidates = [
6580
+ parsed?.privateKey,
6581
+ parsed?.key?.privateKey,
6582
+ parsed?.keys?.[0]?.privateKey,
6583
+ parsed?.data?.attributes?.privateKey,
6584
+ parsed?.value
6585
+ ];
6586
+ for (const c of candidates) {
6587
+ if (typeof c === "string" && c.includes("BEGIN PRIVATE KEY")) return c;
6588
+ }
6589
+ } catch {
6590
+ }
6591
+ }
6592
+ throw new Error(`downloadApiKey returned no PEM. Content-Type=${contentType} body=${rawText.slice(0, 300)}`);
6593
+ }
6594
+ /**
6595
+ * List existing API keys via the portal. Used to discover the team's
6596
+ * issuer id — every key in the team shares the same issuer id, and
6597
+ * altool needs it alongside the key id and .p8 file.
6598
+ *
6599
+ * Form-encoded POST (NOT JSON), with pagination params, per Spaceship's
6600
+ * `list_keys` method. JSON returned 415 from this endpoint.
6601
+ */
6602
+ async listApiKeys() {
6603
+ const data = await this.post("account/auth/key/list", {
6604
+ teamId: this.teamId,
6605
+ pageNumber: "1",
6606
+ pageSize: "500",
6607
+ sort: "name=asc"
6608
+ });
6609
+ const keys = data?.keys ?? [];
6610
+ const issuerId = data?.issuerId ?? data?.issuer ?? data?.team?.issuerId ?? keys[0]?.issuerId ?? keys[0]?.issuer;
6611
+ return { keys, issuerId };
6612
+ }
6314
6613
  async post(path, params) {
6315
6614
  const body = new URLSearchParams();
6316
6615
  for (const [k, v] of Object.entries(params)) {
@@ -6378,6 +6677,31 @@ var init_portal = __esm({
6378
6677
  async deleteAppId(appIdId) {
6379
6678
  await this.post("account/ios/identifiers/deleteAppId.action", { teamId: this.teamId, appIdId });
6380
6679
  }
6680
+ /**
6681
+ * Toggle a capability (a.k.a. "service") on a bundle ID. Mirrors
6682
+ * Spaceship::Portal's `update_service` — the legacy portal endpoint
6683
+ * still works and is the only session-cookie-authenticated way to flip
6684
+ * capabilities like Push Notifications and Sign in with Apple from
6685
+ * outside the Apple Developer web UI.
6686
+ *
6687
+ * Common service codes (from Spaceship portal/portal_client.rb):
6688
+ * push → push notifications
6689
+ * APG3427HIY → Sign in with Apple
6690
+ * IAD53UNK2F → in-app purchase
6691
+ * homeKit → HomeKit
6692
+ * healthKit → HealthKit
6693
+ *
6694
+ * @param featureType Apple's internal capability key (string code or short name)
6695
+ * @param enabled true → turn on, false → turn off
6696
+ */
6697
+ async setBundleCapability(params) {
6698
+ await this.post("account/ios/identifiers/updateAppService.action", {
6699
+ teamId: this.teamId,
6700
+ displayId: params.appIdId,
6701
+ featureType: params.featureType,
6702
+ featureValue: params.enabled ? "on" : "off"
6703
+ });
6704
+ }
6381
6705
  // ── Certificates ───────────────────────────────────────────────────────
6382
6706
  async listCertificates(types) {
6383
6707
  const iosTypes = types ?? [
@@ -6395,12 +6719,21 @@ var init_portal = __esm({
6395
6719
  return data.certRequests ?? [];
6396
6720
  }
6397
6721
  async listPushCertificates() {
6722
+ const types = Array.from(
6723
+ /* @__PURE__ */ new Set([
6724
+ _PortalClient.CERT_TYPES.IOS_PRODUCTION_PUSH,
6725
+ _PortalClient.CERT_TYPES.IOS_DEVELOPMENT_PUSH,
6726
+ // Legacy push codes from OLDER_IOS_CERTIFICATE_TYPES
6727
+ "3BQKVH9I2X",
6728
+ "BKLRAVXMGM"
6729
+ ])
6730
+ );
6398
6731
  const data = await this.post("account/ios/certificate/listCertRequests.action", {
6399
6732
  teamId: this.teamId,
6400
6733
  pageSize: "500",
6401
6734
  pageNumber: "1",
6402
6735
  sort: "certRequestStatusCode=asc",
6403
- types: [_PortalClient.CERT_TYPES.IOS_PRODUCTION_PUSH, _PortalClient.CERT_TYPES.IOS_DEVELOPMENT_PUSH].join(",")
6736
+ types: types.join(",")
6404
6737
  });
6405
6738
  return data.certRequests ?? [];
6406
6739
  }
@@ -6542,18 +6875,332 @@ var init_portal = __esm({
6542
6875
  }
6543
6876
  });
6544
6877
 
6878
+ // src/client/iris.ts
6879
+ var IRIS_BASE, IrisClient, IrisAuthError;
6880
+ var init_iris = __esm({
6881
+ "src/client/iris.ts"() {
6882
+ IRIS_BASE = "https://appstoreconnect.apple.com/iris/v1";
6883
+ IrisClient = class {
6884
+ constructor(session) {
6885
+ this.session = session;
6886
+ this.cookieStr = Object.entries(session.cookies).map(([k, v]) => `${k}=${v}`).join("; ");
6887
+ }
6888
+ session;
6889
+ cookieStr;
6890
+ buildHeaders() {
6891
+ return {
6892
+ Cookie: this.cookieStr,
6893
+ Accept: "application/vnd.api+json, application/json, text/plain, */*",
6894
+ "Content-Type": "application/vnd.api+json",
6895
+ "X-Requested-With": "XMLHttpRequest",
6896
+ // Mimic the App Store Connect web UI's user agent
6897
+ "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"
6898
+ };
6899
+ }
6900
+ /**
6901
+ * Issue a request and absorb any new cookies (Apple rotates session
6902
+ * cookies on a lot of iris calls).
6903
+ */
6904
+ async request(method, path, body) {
6905
+ const headers = this.buildHeaders();
6906
+ if (process.env.FASTNODE_DEBUG) {
6907
+ console.log(`[iris] ${method} ${path}${body ? ` body=${JSON.stringify(body).slice(0, 200)}` : ""}`);
6908
+ }
6909
+ const res = await fetch(`${IRIS_BASE}${path}`, {
6910
+ method,
6911
+ headers,
6912
+ body: body ? JSON.stringify(body) : void 0
6913
+ });
6914
+ for (const raw of res.headers.getSetCookie?.() ?? []) {
6915
+ const m = raw.match(/^([^=]+)=([^;]*)/);
6916
+ if (m) {
6917
+ this.session.cookies[m[1]] = m[2];
6918
+ }
6919
+ }
6920
+ this.cookieStr = Object.entries(this.session.cookies).map(([k, v]) => `${k}=${v}`).join("; ");
6921
+ const text = await res.text();
6922
+ let parsed = null;
6923
+ try {
6924
+ parsed = text ? JSON.parse(text) : null;
6925
+ } catch {
6926
+ }
6927
+ if (process.env.FASTNODE_DEBUG) {
6928
+ console.log(`[iris] \u2192 ${res.status} ${text.slice(0, 300)}`);
6929
+ }
6930
+ return { status: res.status, body: parsed, rawText: text };
6931
+ }
6932
+ /**
6933
+ * List existing API keys. Used both as a sanity check (the user has
6934
+ * permission) and to discover the team's issuer id (which is the same
6935
+ * for every key in the team and is needed by altool).
6936
+ *
6937
+ * Important: Apple's iris endpoint rejects most query parameters with
6938
+ * `PARAMETER_ERROR.INVALID`. Call with no params and let the API return
6939
+ * its default page.
6940
+ */
6941
+ async listApiKeys() {
6942
+ const { status, body, rawText } = await this.request("GET", "/apiKeys");
6943
+ if (status === 403) {
6944
+ throw new IrisAuthError(
6945
+ "You don't have permission to manage App Store Connect API keys (this requires the Account Holder or Admin role)."
6946
+ );
6947
+ }
6948
+ if (status >= 400 || !body) {
6949
+ throw new Error(`iris listApiKeys failed (${status}): ${rawText.slice(0, 200)}`);
6950
+ }
6951
+ const issuerId = body?.meta?.issuerId ?? body?.data?.[0]?.attributes?.issuerId;
6952
+ const keys = (body.data ?? []).map((d) => ({
6953
+ id: d.id,
6954
+ kid: d.attributes?.kid ?? d.id,
6955
+ nickname: d.attributes?.nickname ?? "",
6956
+ issuerId: d.attributes?.issuerId ?? issuerId,
6957
+ roles: d.attributes?.roles ?? [],
6958
+ allAppsVisible: d.attributes?.allAppsVisible ?? true
6959
+ }));
6960
+ return { keys, issuerId };
6961
+ }
6962
+ /**
6963
+ * Create a new API key. Apple returns the .p8 PEM exactly once in the
6964
+ * create response — capture it immediately or the key is dead weight.
6965
+ *
6966
+ * `keyType` is required by Apple's iris API:
6967
+ * • PUBLIC_API — the standard team-wide API key (what TestFlight uploads need)
6968
+ * • MARKETING_API — for App Analytics access only
6969
+ */
6970
+ async createApiKey(input) {
6971
+ const requestBody = {
6972
+ data: {
6973
+ type: "apiKeys",
6974
+ attributes: {
6975
+ nickname: input.nickname,
6976
+ roles: input.roles ?? ["APP_MANAGER"],
6977
+ allAppsVisible: input.allAppsVisible ?? true,
6978
+ keyType: input.keyType ?? "PUBLIC_API"
6979
+ }
6980
+ }
6981
+ };
6982
+ console.log("[iris] createApiKey request:", JSON.stringify(requestBody));
6983
+ const { status, body, rawText } = await this.request("POST", "/apiKeys", requestBody);
6984
+ console.log(`[iris] createApiKey response: ${status} ${rawText.slice(0, 800)}`);
6985
+ if (status === 403) {
6986
+ throw new IrisAuthError(
6987
+ "You don't have permission to create App Store Connect API keys (this requires the Account Holder or Admin role)."
6988
+ );
6989
+ }
6990
+ if (status >= 400 || !body) {
6991
+ const msg = body?.errors?.[0]?.detail ?? body?.errors?.[0]?.title ?? rawText.slice(0, 300) ?? `iris createApiKey failed (${status})`;
6992
+ throw new Error(msg);
6993
+ }
6994
+ const data = body.data ?? body;
6995
+ if (!data?.id) {
6996
+ throw new Error(`iris createApiKey returned no key id. Raw response: ${rawText.slice(0, 400)}`);
6997
+ }
6998
+ const key = {
6999
+ id: data.id,
7000
+ kid: data.attributes?.kid ?? data.id,
7001
+ nickname: data.attributes?.nickname ?? input.nickname,
7002
+ privateKey: data.attributes?.privateKey,
7003
+ issuerId: data.attributes?.issuerId,
7004
+ roles: data.attributes?.roles ?? input.roles ?? ["APP_MANAGER"],
7005
+ allAppsVisible: data.attributes?.allAppsVisible ?? true
7006
+ };
7007
+ return key;
7008
+ }
7009
+ /**
7010
+ * Fetch the .p8 PEM AND the team's issuer id for a previously-created
7011
+ * ASC API key. Both come back in a single request via:
7012
+ *
7013
+ * GET /iris/v1/apiKeys/{id}?fields[apiKeys]=privateKey&include=provider
7014
+ *
7015
+ * Sparse fieldset requesting ONLY `privateKey` is the magic that makes
7016
+ * Apple actually include the (base64-encoded) PEM in the response —
7017
+ * the default view returns `privateKey: null`. The `include=provider`
7018
+ * pulls the team's contentProvider record into `included[]`, and its
7019
+ * `id` field IS the issuer id altool needs (a UUID like
7020
+ * `cfadaf94-44ca-4c2c-8fa6-ecc28d3c7d0d`).
7021
+ *
7022
+ * Reverse-engineered from @expo/apple-utils v2.1.21 (the package that
7023
+ * powers EAS CLI), specifically the `ApiKey.downloadAsync` method
7024
+ * combined with `ApiKey.infoAsync` reading `provider?.id`.
7025
+ *
7026
+ * Returns `{ pem, issuerId }`, or `null` if Apple won't return the
7027
+ * private key (typically because the key was already downloaded once).
7028
+ */
7029
+ async fetchApiKeyPrivateKey(keyId) {
7030
+ try {
7031
+ const url = `${IRIS_BASE}/apiKeys/${keyId}?fields%5BapiKeys%5D=privateKey&include=provider`;
7032
+ const res = await fetch(url, {
7033
+ headers: {
7034
+ ...this.buildHeaders(),
7035
+ Accept: "application/vnd.api+json, application/json, text/plain, */*"
7036
+ }
7037
+ });
7038
+ const text = await res.text();
7039
+ console.log(`[iris] fetchApiKeyPrivateKey \u2192 ${res.status} (${text.length} bytes)`);
7040
+ if (res.status !== 200) {
7041
+ console.log(`[iris] err: ${text.slice(0, 300)}`);
7042
+ return null;
7043
+ }
7044
+ const body = JSON.parse(text);
7045
+ const encoded = body?.data?.attributes?.privateKey;
7046
+ if (typeof encoded !== "string" || encoded.length === 0) {
7047
+ console.log(`[iris] no privateKey in response`);
7048
+ return null;
7049
+ }
7050
+ const pem = Buffer.from(encoded, "base64").toString("utf-8");
7051
+ if (!pem.includes("BEGIN PRIVATE KEY")) {
7052
+ console.log(`[iris] decoded body didn't contain PEM marker`);
7053
+ return null;
7054
+ }
7055
+ const provider = (body?.included ?? []).find((i) => i.type === "contentProviders");
7056
+ const issuerId = provider?.id;
7057
+ console.log(`[iris] \u2713 PEM ${pem.length} bytes, issuerId=${issuerId ?? "(missing)"}`);
7058
+ return { pem, issuerId };
7059
+ } catch (err) {
7060
+ console.log(`[iris] fetchApiKeyPrivateKey error: ${err.message}`);
7061
+ return null;
7062
+ }
7063
+ }
7064
+ /**
7065
+ * @deprecated Kept as a fallback probe for debugging. The real path
7066
+ * is the sparse fieldset above — everything in this brute-force list
7067
+ * returned 404 during testing. Left here so we can re-verify if Apple
7068
+ * changes anything.
7069
+ */
7070
+ async fetchApiKeyPrivateKeyBruteForce(keyId) {
7071
+ const attempts = [
7072
+ // Sparse fieldsets — JSON-API spec lets us request specific attributes.
7073
+ // Apple may exclude privateKey by default and return it only when asked.
7074
+ { kind: "GET", path: `/apiKeys/${keyId}?fields[apiKeys]=privateKey,kid,issuerId,nickname,roles` },
7075
+ { kind: "GET", path: `/apiKeys/${keyId}?include=privateKey` },
7076
+ { kind: "GET", path: `/apiKeys/${keyId}?fields[apiKeys]=privateKey` },
7077
+ // Custom Accept headers — maybe Apple negotiates content type
7078
+ { kind: "GET", path: `/apiKeys/${keyId}`, accept: "application/x-pem-file" },
7079
+ { kind: "GET", path: `/apiKeys/${keyId}`, accept: "application/octet-stream" },
7080
+ { kind: "GET", path: `/apiKeys/${keyId}/p8`, accept: "application/x-pem-file" },
7081
+ // POST variants — Apple sometimes uses POST to mint a download token
7082
+ { kind: "POST", path: `/apiKeys/${keyId}/secrets`, body: {} },
7083
+ { kind: "POST", path: `/apiKeys/${keyId}/regenerate`, body: {} },
7084
+ { kind: "POST", path: `/apiKeys/${keyId}/p8`, body: {} },
7085
+ // Bare GET (last) — confirms canonical fields, in case my parser missed any
7086
+ { kind: "GET", path: `/apiKeys/${keyId}` },
7087
+ // Different host — the legacy developer.apple.com user-and-access namespace
7088
+ { kind: "ABSOLUTE", url: `https://appstoreconnect.apple.com/api/v1/apiKeys/${keyId}/p8` },
7089
+ { kind: "ABSOLUTE", url: `https://appstoreconnect.apple.com/access/api/keys/${keyId}/download` }
7090
+ ];
7091
+ for (const attempt of attempts) {
7092
+ try {
7093
+ let result;
7094
+ if (attempt.kind === "GET") {
7095
+ result = await this.requestWithHeaders("GET", attempt.path, void 0, {
7096
+ ...attempt.accept ? { Accept: attempt.accept } : {}
7097
+ });
7098
+ console.log(`[iris] fetchApiKeyPrivateKey GET ${attempt.path}${attempt.accept ? ` accept=${attempt.accept}` : ""} \u2192 ${result.status} (${result.rawText.length} bytes)`);
7099
+ } else if (attempt.kind === "POST") {
7100
+ result = await this.request("POST", attempt.path, attempt.body);
7101
+ console.log(`[iris] fetchApiKeyPrivateKey POST ${attempt.path} \u2192 ${result.status} (${result.rawText.length} bytes)`);
7102
+ } else {
7103
+ result = await this.requestAbsolute("GET", attempt.url);
7104
+ console.log(`[iris] fetchApiKeyPrivateKey GET ${attempt.url} \u2192 ${result.status} (${result.rawText.length} bytes)`);
7105
+ }
7106
+ if (result.status === 200) {
7107
+ console.log(`[iris] body: ${result.rawText.slice(0, 1500)}`);
7108
+ }
7109
+ if (result.status !== 200) continue;
7110
+ if (result.rawText && result.rawText.includes("BEGIN PRIVATE KEY")) {
7111
+ console.log(`[iris] \u2713 found PEM (plain text response)`);
7112
+ return result.rawText;
7113
+ }
7114
+ if (result.body) {
7115
+ const candidates = [
7116
+ result.body?.data?.attributes?.privateKey,
7117
+ result.body?.data?.attributes?.p8,
7118
+ result.body?.data?.attributes?.privateKeyContent,
7119
+ result.body?.data?.attributes?.kpem,
7120
+ result.body?.data?.attributes?.secret,
7121
+ result.body?.data?.attributes?.keyContent,
7122
+ result.body?.privateKey,
7123
+ result.body?.p8,
7124
+ result.body?.value,
7125
+ result.body?.secret
7126
+ ];
7127
+ for (const c of candidates) {
7128
+ if (typeof c === "string" && c.includes("BEGIN PRIVATE KEY")) {
7129
+ console.log(`[iris] \u2713 found PEM in JSON response`);
7130
+ return c;
7131
+ }
7132
+ }
7133
+ }
7134
+ } catch (err) {
7135
+ console.log(`[iris] fetchApiKeyPrivateKey attempt failed: ${err.message}`);
7136
+ }
7137
+ }
7138
+ console.log(`[iris] fetchApiKeyPrivateKey: no working download path for key ${keyId}`);
7139
+ return null;
7140
+ }
7141
+ /** Internal: like request() but lets us override headers. */
7142
+ async requestWithHeaders(method, path, body, extraHeaders = {}) {
7143
+ const headers = { ...this.buildHeaders(), ...extraHeaders };
7144
+ const res = await fetch(`${IRIS_BASE}${path}`, {
7145
+ method,
7146
+ headers,
7147
+ body: body ? JSON.stringify(body) : void 0
7148
+ });
7149
+ for (const raw of res.headers.getSetCookie?.() ?? []) {
7150
+ const m = raw.match(/^([^=]+)=([^;]*)/);
7151
+ if (m) this.session.cookies[m[1]] = m[2];
7152
+ }
7153
+ this.cookieStr = Object.entries(this.session.cookies).map(([k, v]) => `${k}=${v}`).join("; ");
7154
+ const text = await res.text();
7155
+ let parsed = null;
7156
+ try {
7157
+ parsed = text ? JSON.parse(text) : null;
7158
+ } catch {
7159
+ }
7160
+ return { status: res.status, body: parsed, rawText: text };
7161
+ }
7162
+ /** Internal: fetch an absolute URL with the session cookies. */
7163
+ async requestAbsolute(method, url) {
7164
+ const headers = this.buildHeaders();
7165
+ const res = await fetch(url, { method, headers });
7166
+ const text = await res.text();
7167
+ let parsed = null;
7168
+ try {
7169
+ parsed = text ? JSON.parse(text) : null;
7170
+ } catch {
7171
+ }
7172
+ return { status: res.status, body: parsed, rawText: text };
7173
+ }
7174
+ async deleteApiKey(keyId) {
7175
+ await this.request("DELETE", `/apiKeys/${keyId}`);
7176
+ }
7177
+ };
7178
+ IrisAuthError = class extends Error {
7179
+ constructor(message) {
7180
+ super(message);
7181
+ this.name = "IrisAuthError";
7182
+ }
7183
+ };
7184
+ }
7185
+ });
7186
+
6545
7187
  // src/client/index.ts
6546
7188
  var client_exports = {};
6547
7189
  __export(client_exports, {
6548
7190
  AppStoreConnectClient: () => AppStoreConnectClient,
6549
7191
  AppStoreConnectError: () => AppStoreConnectError,
7192
+ IrisAuthError: () => IrisAuthError,
7193
+ IrisClient: () => IrisClient,
6550
7194
  PortalClient: () => PortalClient,
6551
7195
  ProgramLicenseAgreementError: () => ProgramLicenseAgreementError,
6552
7196
  RateLimitError: () => RateLimitError,
6553
7197
  RequestClient: () => RequestClient,
6554
7198
  TokenManager: () => TokenManager,
7199
+ beginLogin: () => beginLogin,
6555
7200
  checkPortalResponse: () => checkPortalResponse,
6556
- loginWithAppleId: () => loginWithAppleId
7201
+ loginWithAppleId: () => loginWithAppleId,
7202
+ requestSmsCode: () => requestSmsCode,
7203
+ submitTwoFactorCode: () => submitTwoFactorCode
6557
7204
  });
6558
7205
  var AppStoreConnectClient;
6559
7206
  var init_client = __esm({
@@ -6598,6 +7245,7 @@ var init_client = __esm({
6598
7245
  init_request();
6599
7246
  init_apple_session();
6600
7247
  init_portal();
7248
+ init_iris();
6601
7249
  AppStoreConnectClient = class {
6602
7250
  http;
6603
7251
  certificates;