@sitepong/fastnode 0.1.2 → 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 (70) hide show
  1. package/README.md +148 -0
  2. package/dist/actions/index.cjs +737 -110
  3. package/dist/actions/index.cjs.map +1 -1
  4. package/dist/actions/index.mjs +737 -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-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 +737 -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 +737 -110
  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-D6zjGlPL.d.cts → index-AD8QXY1T.d.cts} +1 -1
  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-DHw08dUc.d.ts → index-D82CmjMP.d.ts} +1 -1
  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 +1094 -110
  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 +1091 -111
  51. package/dist/index.mjs.map +1 -1
  52. package/dist/lane/index.cjs +737 -110
  53. package/dist/lane/index.cjs.map +1 -1
  54. package/dist/lane/index.mjs +737 -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
@@ -205,9 +205,9 @@ Please accept the agreement at https://developer.apple.com/account before contin
205
205
  throw new Error(msg);
206
206
  }
207
207
  }
208
- async function loginWithAppleId(config) {
209
- const log = config.onLog ?? console.log;
210
- const promptFn = config.onPrompt ?? defaultPrompt;
208
+ async function beginLogin(config) {
209
+ const log = config.onLog ?? (() => {
210
+ });
211
211
  log("Fetching Apple service key...");
212
212
  const serviceKey = await fetchServiceKey();
213
213
  const initRes = await fetch(`${AUTH_BASE}/signin?widgetKey=${serviceKey}`, {
@@ -224,27 +224,94 @@ async function loginWithAppleId(config) {
224
224
  const cookieStr = Object.entries(initCookies).map(([k, v]) => k.startsWith("DES") ? `${k}="${v}"` : `${k}=${v}`).join("; ");
225
225
  log("Starting SIRP Apple ID login...");
226
226
  const response = await doSirp(config.email, config.password, serviceKey, cookieStr, hashcash);
227
- const session = {
227
+ const baseState = {
228
228
  cookies: { ...initCookies, ...response.cookies },
229
229
  sessionId: response.sessionId,
230
230
  scnt: response.scnt,
231
231
  serviceKey,
232
- userEmail: config.email,
233
- pendingAgreements: []
232
+ userEmail: config.email
234
233
  };
235
234
  if (response.status === 403) {
236
235
  throw new Error(`Invalid username and password combination. Used '${config.email}' as the username.`);
237
- } else if (response.status === 200) {
238
- log("Login successful.");
239
- await fetchOlympusSession(session);
240
- } else if (response.status === 409) {
241
- await handleTwoStepOrFactor(session, log, promptFn);
242
- await fetchOlympusSession(session);
243
- } else if (response.status === 412) {
236
+ }
237
+ if (response.status === 412) {
244
238
  throw new Error("Need to acknowledge Apple's Apple ID and Privacy statement. Please manually log into https://appleid.apple.com.");
239
+ }
240
+ if (response.status === 200) {
241
+ log("Login successful (no 2FA).");
242
+ const session = { ...baseState, pendingAgreements: [] };
243
+ await finalizeSession(session, log);
244
+ return { kind: "logged_in", session };
245
+ }
246
+ if (response.status === 409) {
247
+ log("2FA required, fetching challenge...");
248
+ const challenge = await fetchTwoFactorChallenge(baseState);
249
+ return { kind: "needs_2fa", pending: baseState, challenge };
250
+ }
251
+ throw new Error(`Unexpected login response (${response.status}): ${JSON.stringify(response.body).slice(0, 500)}`);
252
+ }
253
+ async function fetchTwoFactorChallenge(pending) {
254
+ const r = await fetch(`${AUTH_BASE}`, { headers: buildAuthHeadersFromPending(pending) });
255
+ const body = await r.json();
256
+ const trustedPhoneNumbers = (body.trustedPhoneNumbers ?? []).map((p) => ({
257
+ id: p.id,
258
+ numberWithDialCode: p.numberWithDialCode,
259
+ pushMode: p.pushMode
260
+ }));
261
+ const phoneOnly = body.noTrustedDevices === true;
262
+ const codeLength = body.securityCode?.length ?? 6;
263
+ return {
264
+ kind: phoneOnly ? "phone_only" : "device",
265
+ codeLength,
266
+ trustedPhoneNumbers
267
+ };
268
+ }
269
+ async function requestSmsCode(input) {
270
+ await fetch(`${AUTH_BASE}/verify/phone`, {
271
+ method: "PUT",
272
+ headers: { ...buildAuthHeadersFromPending(input.pending), "Content-Type": "application/json" },
273
+ body: JSON.stringify({ phoneNumber: { id: input.phoneId }, mode: input.mode ?? "sms" })
274
+ });
275
+ }
276
+ async function submitTwoFactorCode(input) {
277
+ const log = input.onLog ?? (() => {
278
+ });
279
+ let path;
280
+ let body;
281
+ if (input.source === "device") {
282
+ path = `${AUTH_BASE}/verify/trusteddevice/securitycode`;
283
+ body = JSON.stringify({ securityCode: { code: input.code } });
245
284
  } else {
246
- throw new Error(`Unexpected login response (${response.status}): ${JSON.stringify(response.body).slice(0, 500)}`);
285
+ if (input.phoneId == null) throw new Error("phoneId is required when source='phone'");
286
+ path = `${AUTH_BASE}/verify/phone/securitycode`;
287
+ body = JSON.stringify({
288
+ securityCode: { code: input.code },
289
+ phoneNumber: { id: input.phoneId },
290
+ mode: input.mode ?? "sms"
291
+ });
247
292
  }
293
+ log("Submitting 2FA code...");
294
+ const verifyRes = await fetch(path, {
295
+ method: "POST",
296
+ headers: { ...buildAuthHeadersFromPending(input.pending), "Content-Type": "application/json" },
297
+ body
298
+ });
299
+ if (!verifyRes.ok) {
300
+ const err = await verifyRes.json().catch(() => ({}));
301
+ const msgs = (err?.service_errors ?? err?.serviceErrors ?? []).map((e) => e.message).filter(Boolean);
302
+ throw new Error(msgs.join("; ") || `Verification failed (${verifyRes.status})`);
303
+ }
304
+ const session = {
305
+ ...input.pending,
306
+ cookies: { ...input.pending.cookies, ...parseCookies(verifyRes.headers) },
307
+ pendingAgreements: []
308
+ };
309
+ await trustSession(session);
310
+ await finalizeSession(session, log);
311
+ return session;
312
+ }
313
+ async function finalizeSession(session, log) {
314
+ await fetchOlympusSession(session);
248
315
  const agreements = await fetchContractMessages(session);
249
316
  if (agreements.length > 0) {
250
317
  for (const msg of agreements) {
@@ -253,7 +320,53 @@ async function loginWithAppleId(config) {
253
320
  }
254
321
  session.pendingAgreements = agreements;
255
322
  log(`Logged in as ${session.userEmail}`);
256
- return session;
323
+ }
324
+ async function loginWithAppleId(config) {
325
+ const log = config.onLog ?? console.log;
326
+ const promptFn = config.onPrompt ?? defaultPrompt;
327
+ const result = await beginLogin({ email: config.email, password: config.password, onLog: log });
328
+ if (result.kind === "logged_in") return result.session;
329
+ const { pending, challenge } = result;
330
+ const phones = challenge.trustedPhoneNumbers;
331
+ if (challenge.kind === "device") {
332
+ log("Two-factor Authentication (6 digit code) is enabled for this account");
333
+ log("(Input 'sms' to escape this prompt and select a trusted phone number to send the code as a text message)");
334
+ const input = await promptFn(`Please enter the ${challenge.codeLength} digit code: `);
335
+ if (input.toLowerCase() === "sms") {
336
+ log("Please select a trusted phone number:");
337
+ for (let i = 0; i < phones.length; i++) log(` ${i + 1}. ${phones[i].numberWithDialCode}`);
338
+ const choice2 = await promptFn("Enter number: ");
339
+ const phone2 = phones[Math.max(0, parseInt(choice2, 10) - 1)] ?? phones[0];
340
+ await requestSmsCode({ pending, phoneId: phone2.id, mode: phone2.pushMode });
341
+ log(`Code sent to ${phone2.numberWithDialCode}`);
342
+ const code2 = await promptFn(`Please enter the ${challenge.codeLength} digit code: `);
343
+ return submitTwoFactorCode({ pending, code: code2, source: "phone", phoneId: phone2.id, mode: phone2.pushMode ?? "sms", onLog: log });
344
+ }
345
+ return submitTwoFactorCode({ pending, code: input, source: "device", onLog: log });
346
+ }
347
+ log("Two-factor Authentication (6 digit code) is enabled for this account");
348
+ if (phones.length === 1) {
349
+ const phone2 = phones[0];
350
+ log(`Code automatically sent to ${phone2.numberWithDialCode}`);
351
+ const code2 = await promptFn(`Please enter the ${challenge.codeLength} digit code: `);
352
+ return submitTwoFactorCode({ pending, code: code2, source: "phone", phoneId: phone2.id, mode: phone2.pushMode ?? "sms", onLog: log });
353
+ }
354
+ log("Please select a trusted phone number:");
355
+ for (let i = 0; i < phones.length; i++) log(` ${i + 1}. ${phones[i].numberWithDialCode}`);
356
+ const choice = await promptFn("Enter number: ");
357
+ const phone = phones[Math.max(0, parseInt(choice, 10) - 1)] ?? phones[0];
358
+ await requestSmsCode({ pending, phoneId: phone.id, mode: phone.pushMode });
359
+ log(`Code sent to ${phone.numberWithDialCode}`);
360
+ const code = await promptFn(`Please enter the ${challenge.codeLength} digit code: `);
361
+ return submitTwoFactorCode({ pending, code, source: "phone", phoneId: phone.id, mode: phone.pushMode ?? "sms", onLog: log });
362
+ }
363
+ function buildAuthHeadersFromPending(pending) {
364
+ const h = { "X-Apple-Widget-Key": pending.serviceKey, Accept: "application/json" };
365
+ if (pending.sessionId) h["X-Apple-Id-Session-Id"] = pending.sessionId;
366
+ if (pending.scnt) h["scnt"] = pending.scnt;
367
+ const c = Object.entries(pending.cookies).map(([k, v]) => `${k}=${v}`).join("; ");
368
+ if (c) h["Cookie"] = c;
369
+ return h;
257
370
  }
258
371
  async function doSirp(user, password, serviceKey, cookieStr, hashcash) {
259
372
  const client = new SRPClient(2048);
@@ -309,99 +422,6 @@ async function doSirp(user, password, serviceKey, cookieStr, hashcash) {
309
422
  scnt: completeRes.headers.get("scnt") ?? ""
310
423
  };
311
424
  }
312
- async function handleTwoStepOrFactor(session, log, promptFn) {
313
- const r = await fetch(`${AUTH_BASE}`, { headers: buildAuthHeaders(session) });
314
- const body = await r.json();
315
- if (body.trustedDevices?.length > 0) {
316
- await handleTwoStep(session, body, log, promptFn);
317
- } else if (body.trustedPhoneNumbers?.length > 0) {
318
- await handleTwoFactor(session, body, log, promptFn);
319
- } else {
320
- throw new Error("2FA required but no trusted devices or phone numbers found.");
321
- }
322
- }
323
- async function handleTwoFactor(session, authBody, log, promptFn) {
324
- log("Two-factor Authentication (6 digit code) is enabled for this account");
325
- const codeLength = authBody.securityCode?.length ?? 6;
326
- const phones = authBody.trustedPhoneNumbers ?? [];
327
- const noTrusted = authBody.noTrustedDevices === true;
328
- let codeType;
329
- let reqBody;
330
- if (noTrusted && phones.length === 1) {
331
- const phone = phones[0];
332
- log(`Code automatically sent to ${phone.numberWithDialCode}`);
333
- const code = await promptFn(`Please enter the ${codeLength} digit code you received at ${phone.numberWithDialCode}: `);
334
- codeType = "phone";
335
- reqBody = JSON.stringify({ securityCode: { code }, phoneNumber: { id: phone.id }, mode: phone.pushMode ?? "sms" });
336
- } else if (noTrusted) {
337
- const phone = await choosePhone(phones, log, promptFn);
338
- await requestPhoneCode(session, phone);
339
- log(`Successfully requested text message to ${phone.numberWithDialCode}`);
340
- const code = await promptFn(`Please enter the ${codeLength} digit code: `);
341
- codeType = "phone";
342
- reqBody = JSON.stringify({ securityCode: { code }, phoneNumber: { id: phone.id }, mode: phone.pushMode ?? "sms" });
343
- } else {
344
- log("(Input 'sms' to escape this prompt and select a trusted phone number to send the code as a text message)");
345
- const input = await promptFn(`Please enter the ${codeLength} digit code: `);
346
- if (input.toLowerCase() === "sms") {
347
- const phone = await choosePhone(phones, log, promptFn);
348
- await requestPhoneCode(session, phone);
349
- const code = await promptFn(`Please enter the ${codeLength} digit code sent to ${phone.numberWithDialCode}: `);
350
- codeType = "phone";
351
- reqBody = JSON.stringify({ securityCode: { code }, phoneNumber: { id: phone.id }, mode: phone.pushMode ?? "sms" });
352
- } else {
353
- codeType = "trusteddevice";
354
- reqBody = JSON.stringify({ securityCode: { code: input } });
355
- }
356
- }
357
- log("Requesting session...");
358
- const verifyRes = await fetch(`${AUTH_BASE}/verify/${codeType}/securitycode`, {
359
- method: "POST",
360
- headers: { ...buildAuthHeaders(session), "Content-Type": "application/json" },
361
- body: reqBody
362
- });
363
- if (!verifyRes.ok) {
364
- const err = await verifyRes.json().catch(() => ({}));
365
- const msgs = (err?.service_errors ?? err?.serviceErrors ?? []).map((e) => e.message).filter(Boolean);
366
- throw new Error(msgs.join("; ") || `Verification failed (${verifyRes.status})`);
367
- }
368
- Object.assign(session.cookies, parseCookies(verifyRes.headers));
369
- await trustSession(session);
370
- }
371
- async function handleTwoStep(session, authBody, log, promptFn) {
372
- log("Two-step Verification (4 digit code) is enabled for this account");
373
- const devices = authBody.trustedDevices ?? [];
374
- log("Please select a trusted device:");
375
- for (let i = 0; i < devices.length; i++) {
376
- log(` ${i + 1}. ${devices[i].name} ${devices[i].modelName ?? "SMS"} (${devices[i].id})`);
377
- }
378
- const choice = await promptFn("Enter device number: ");
379
- const device = devices[Math.max(0, parseInt(choice, 10) - 1)] ?? devices[0];
380
- await fetch(`${AUTH_BASE}/verify/device/${device.id}/securitycode`, { method: "PUT", headers: buildAuthHeaders(session) });
381
- log("Successfully requested notification");
382
- const code = await promptFn("Please enter the 4 digit code: ");
383
- const verifyRes = await fetch(`${AUTH_BASE}/verify/phone/securitycode`, {
384
- method: "POST",
385
- headers: { ...buildAuthHeaders(session), "Content-Type": "application/json" },
386
- body: JSON.stringify({ phoneNumber: { id: device.id }, securityCode: { code }, mode: "sms" })
387
- });
388
- if (!verifyRes.ok) throw new Error("Incorrect verification code.");
389
- Object.assign(session.cookies, parseCookies(verifyRes.headers));
390
- await trustSession(session);
391
- }
392
- async function choosePhone(phones, log, promptFn) {
393
- log("Please select a trusted phone number:");
394
- for (let i = 0; i < phones.length; i++) log(` ${i + 1}. ${phones[i].numberWithDialCode}`);
395
- const choice = await promptFn("Enter number: ");
396
- return phones[Math.max(0, parseInt(choice, 10) - 1)] ?? phones[0];
397
- }
398
- async function requestPhoneCode(session, phone) {
399
- await fetch(`${AUTH_BASE}/verify/phone`, {
400
- method: "PUT",
401
- headers: { ...buildAuthHeaders(session), "Content-Type": "application/json" },
402
- body: JSON.stringify({ phoneNumber: { id: phone.id }, mode: phone.pushMode ?? "sms" })
403
- });
404
- }
405
425
  async function trustSession(session) {
406
426
  const r = await fetch(`${AUTH_BASE}/2sv/trust`, { headers: buildAuthHeaders(session) });
407
427
  Object.assign(session.cookies, parseCookies(r.headers));
@@ -2264,6 +2284,264 @@ var PortalClient = class _PortalClient {
2264
2284
  async init() {
2265
2285
  await this.post("account/listTeams.action", {});
2266
2286
  }
2287
+ /**
2288
+ * JSON POST — different content type than the standard form-encoded
2289
+ * `post()`. Used by the App Store Connect API key endpoints
2290
+ * (`account/auth/key/v2/create`), which Spaceship discovered take a
2291
+ * JSON body even though every other portal mutation is form-encoded.
2292
+ *
2293
+ * Like the form-encoded `post()`, this also runs the response through
2294
+ * `checkPortalResponse` — Apple returns HTTP 200 even for errors and
2295
+ * encodes the error in `resultCode`/`userString` fields, so a raw
2296
+ * status check would silently miss real failures.
2297
+ */
2298
+ async postJson(path, body) {
2299
+ const headers = {
2300
+ Cookie: this.cookieStr,
2301
+ "Content-Type": "application/json",
2302
+ Accept: "application/json"
2303
+ };
2304
+ if (this.csrf) {
2305
+ headers["csrf"] = this.csrf;
2306
+ headers["csrf_ts"] = this.csrfTs;
2307
+ }
2308
+ console.log(`[portal] POST(json) ${path}`);
2309
+ const res = await fetch(`${PORTAL_BASE}/${path}`, {
2310
+ method: "POST",
2311
+ headers,
2312
+ body: JSON.stringify(body)
2313
+ });
2314
+ if (res.headers.get("csrf")) {
2315
+ this.csrf = res.headers.get("csrf");
2316
+ this.csrfTs = res.headers.get("csrf_ts") ?? "";
2317
+ }
2318
+ for (const raw of res.headers.getSetCookie?.() ?? []) {
2319
+ const m = raw.match(/^([^=]+)=([^;]*)/);
2320
+ if (m && !this.cookieStr.includes(m[1] + "=")) this.cookieStr += "; " + m[1] + "=" + m[2];
2321
+ }
2322
+ const text = await res.text();
2323
+ let data = null;
2324
+ try {
2325
+ data = text ? JSON.parse(text) : null;
2326
+ } catch {
2327
+ }
2328
+ console.log(`[portal] POST(json) ${path} \u2192 ${res.status} ${text.slice(0, 400)}`);
2329
+ checkPortalResponse(data, this.session);
2330
+ return { status: res.status, body: data, rawText: text };
2331
+ }
2332
+ /**
2333
+ * GET helper for the portal endpoints that take query parameters
2334
+ * (currently just `account/auth/key/download`). Returns the raw text
2335
+ * since download endpoints can return PEMs or JSON depending on Apple's
2336
+ * mood — caller decides how to parse.
2337
+ */
2338
+ async getRaw(path, params = {}) {
2339
+ const url = new URL(`${PORTAL_BASE}/${path}`);
2340
+ for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
2341
+ const headers = {
2342
+ Cookie: this.cookieStr,
2343
+ Accept: "application/json, text/plain, application/x-pem-file, */*"
2344
+ };
2345
+ if (this.csrf) {
2346
+ headers["csrf"] = this.csrf;
2347
+ headers["csrf_ts"] = this.csrfTs;
2348
+ }
2349
+ console.log(`[portal] GET ${url.pathname}${url.search}`);
2350
+ const res = await fetch(url.toString(), { headers });
2351
+ for (const raw of res.headers.getSetCookie?.() ?? []) {
2352
+ const m = raw.match(/^([^=]+)=([^;]*)/);
2353
+ if (m && !this.cookieStr.includes(m[1] + "=")) this.cookieStr += "; " + m[1] + "=" + m[2];
2354
+ }
2355
+ const text = await res.text();
2356
+ const contentType = res.headers.get("content-type") ?? "";
2357
+ console.log(`[portal] GET ${url.pathname} \u2192 ${res.status} ${contentType} ${text.length}b`);
2358
+ return { status: res.status, rawText: text, contentType };
2359
+ }
2360
+ // ── App Store Connect API Keys (.p8) ────────────────────────────────────
2361
+ /**
2362
+ * Create an App Store Connect API key via the developer portal's
2363
+ * `account/auth/key/v2/create` endpoint. Reverse-engineered from the
2364
+ * _current_ @expo/apple-utils npm package (v2.1.21), which is what
2365
+ * EAS CLI uses to manage Apple credentials in production.
2366
+ *
2367
+ * This differs from older published reverse-engineering guides:
2368
+ * • URL uses the `/v2/create` suffix (Apple kept it)
2369
+ * • Field is `serviceConfigurations`, shape is an object keyed by
2370
+ * service id (NOT `serviceConfigurationsRequests: [...]` array)
2371
+ * • Body REQUIRES `scope: "team"`
2372
+ * • Needs a scope-specific CSRF warmup via the `keys` endpoint
2373
+ * before the create call (EAS's `ensureCSRFAsync("keys", …)`)
2374
+ *
2375
+ * For an App Store Connect API key (PUBLIC_API, used by altool for
2376
+ * TestFlight uploads), `serviceConfigurations` is an empty object `{}`.
2377
+ * For an APNs auth key, it's `{ "U27F4V844T": [] }`. For MusicKit:
2378
+ * `{ "6A7HVUVQ3M": [musicId] }`, etc.
2379
+ *
2380
+ * Apple's name validator rejects parentheses, brackets, and most
2381
+ * punctuation — sanitize to alphanumeric + space + dash + underscore
2382
+ * + period and collapse whitespace.
2383
+ */
2384
+ async createApiKey(rawName, serviceConfigurations = {}) {
2385
+ const name = rawName.replace(/[^A-Za-z0-9 _\-.]/g, " ").replace(/\s+/g, " ").trim().slice(0, 50);
2386
+ if (!name) throw new Error("createApiKey: name is empty after sanitization");
2387
+ try {
2388
+ await this.listApiKeys();
2389
+ } catch {
2390
+ }
2391
+ const body = {
2392
+ teamId: this.teamId,
2393
+ name,
2394
+ serviceConfigurations,
2395
+ scope: "team"
2396
+ };
2397
+ const result = await this.postJson("account/auth/key/v2/create", body);
2398
+ const created = result.body?.keys?.[0] ?? result.body?.key ?? result.body?.data ?? result.body;
2399
+ const keyId = created?.keyId ?? created?.id ?? created?.kid ?? created?.attributes?.kid;
2400
+ if (!keyId) {
2401
+ throw new Error(`createApiKey: no key id in response. Body: ${result.rawText.slice(0, 400)}`);
2402
+ }
2403
+ return { keyId, raw: created };
2404
+ }
2405
+ /**
2406
+ * Fetch a single API key by id via `account/auth/key/get`. Reverse-
2407
+ * engineered from Spaceship's `get_key`. Returns the raw key record so
2408
+ * the caller can extract whatever fields it needs (e.g. issuerId).
2409
+ *
2410
+ * Form-encoded POST — same shape as every other PortalClient mutation
2411
+ * except the JSON `create` endpoint.
2412
+ */
2413
+ async getApiKey(keyId) {
2414
+ const data = await this.post("account/auth/key/get", {
2415
+ teamId: this.teamId,
2416
+ keyId
2417
+ });
2418
+ return data?.keys?.[0] ?? data?.key ?? data?.data ?? data;
2419
+ }
2420
+ /**
2421
+ * Revoke an existing key. Form-encoded POST per Spaceship's
2422
+ * `revoke_key!`. Used for cleaning up orphan keys created during
2423
+ * failed wizard runs.
2424
+ */
2425
+ async revokeApiKey(keyId) {
2426
+ await this.post("account/auth/key/revoke", {
2427
+ teamId: this.teamId,
2428
+ keyId
2429
+ });
2430
+ }
2431
+ // ── APNs Authentication Keys (.p8) ──────────────────────────────────────
2432
+ /** Apple's hardcoded service id for APNs auth keys (from Spaceship). */
2433
+ static APNS_SERVICE_ID = "U27F4V844T";
2434
+ /**
2435
+ * Create an APNs Authentication Key (.p8) via the developer portal.
2436
+ *
2437
+ * Apple requires BOTH `serviceConfigurations` (the map) AND
2438
+ * `serviceConfigurationsRequests` (the array of full config objects)
2439
+ * in the v2/create body. Just sending the map alone results in
2440
+ * "No value was provided for the parameter 'serviceConfigurations'".
2441
+ *
2442
+ * The exact body comes from @expo/apple-utils v2.1.21 — both fields
2443
+ * are produced by separate functions (`d` for the map, `h` for the
2444
+ * array) and merged into the create payload.
2445
+ */
2446
+ async createApnsAuthKey(rawName) {
2447
+ const name = rawName.replace(/[^A-Za-z0-9 _\-.]/g, " ").replace(/\s+/g, " ").trim().slice(0, 50);
2448
+ if (!name) throw new Error("createApnsAuthKey: name is empty after sanitization");
2449
+ try {
2450
+ await this.listApiKeys();
2451
+ } catch {
2452
+ }
2453
+ const body = {
2454
+ teamId: this.teamId,
2455
+ name,
2456
+ serviceConfigurations: {
2457
+ [_PortalClient.APNS_SERVICE_ID]: []
2458
+ },
2459
+ serviceConfigurationsRequests: [
2460
+ {
2461
+ isNew: true,
2462
+ serviceId: _PortalClient.APNS_SERVICE_ID,
2463
+ identifiers: {},
2464
+ environment: "all",
2465
+ scope: "team"
2466
+ }
2467
+ ],
2468
+ scope: "team"
2469
+ };
2470
+ const result = await this.postJson("account/auth/key/v2/create", body);
2471
+ const created = result.body?.keys?.[0];
2472
+ if (!created?.keyId) {
2473
+ throw new Error(`createApnsAuthKey: no key id in response. Body: ${result.rawText.slice(0, 400)}`);
2474
+ }
2475
+ const pem = await this.downloadApiKey(created.keyId);
2476
+ return { keyId: created.keyId, pem, raw: created };
2477
+ }
2478
+ /**
2479
+ * Find existing APNs auth keys in the team. Used by the wizard to
2480
+ * detect "you already have one" cases and offer to reuse rather than
2481
+ * proliferate keys.
2482
+ */
2483
+ async listApnsAuthKeys() {
2484
+ const list = await this.listApiKeys();
2485
+ return (list.keys ?? []).filter(
2486
+ (k) => (k.services ?? []).some((s) => s.id === _PortalClient.APNS_SERVICE_ID || /apns/i.test(s.name ?? ""))
2487
+ ).map((k) => ({
2488
+ keyId: k.keyId,
2489
+ keyName: k.keyName,
2490
+ canDownload: Boolean(k.canDownload)
2491
+ }));
2492
+ }
2493
+ /**
2494
+ * Download an existing App Store Connect API key as PEM. Spaceship's
2495
+ * `download_key` endpoint — GET with teamId + keyId in query string.
2496
+ * Returns the raw .p8 PEM text. Apple shows the .p8 exactly once
2497
+ * (after creation), so call this immediately after createApiKey.
2498
+ */
2499
+ async downloadApiKey(keyId) {
2500
+ const { status, rawText, contentType } = await this.getRaw("account/auth/key/download", {
2501
+ teamId: this.teamId,
2502
+ keyId
2503
+ });
2504
+ if (status !== 200) {
2505
+ throw new Error(`downloadApiKey failed (${status}): ${rawText.slice(0, 200)}`);
2506
+ }
2507
+ if (rawText.includes("BEGIN PRIVATE KEY")) return rawText;
2508
+ if (contentType.includes("json")) {
2509
+ try {
2510
+ const parsed = JSON.parse(rawText);
2511
+ const candidates = [
2512
+ parsed?.privateKey,
2513
+ parsed?.key?.privateKey,
2514
+ parsed?.keys?.[0]?.privateKey,
2515
+ parsed?.data?.attributes?.privateKey,
2516
+ parsed?.value
2517
+ ];
2518
+ for (const c of candidates) {
2519
+ if (typeof c === "string" && c.includes("BEGIN PRIVATE KEY")) return c;
2520
+ }
2521
+ } catch {
2522
+ }
2523
+ }
2524
+ throw new Error(`downloadApiKey returned no PEM. Content-Type=${contentType} body=${rawText.slice(0, 300)}`);
2525
+ }
2526
+ /**
2527
+ * List existing API keys via the portal. Used to discover the team's
2528
+ * issuer id — every key in the team shares the same issuer id, and
2529
+ * altool needs it alongside the key id and .p8 file.
2530
+ *
2531
+ * Form-encoded POST (NOT JSON), with pagination params, per Spaceship's
2532
+ * `list_keys` method. JSON returned 415 from this endpoint.
2533
+ */
2534
+ async listApiKeys() {
2535
+ const data = await this.post("account/auth/key/list", {
2536
+ teamId: this.teamId,
2537
+ pageNumber: "1",
2538
+ pageSize: "500",
2539
+ sort: "name=asc"
2540
+ });
2541
+ const keys = data?.keys ?? [];
2542
+ const issuerId = data?.issuerId ?? data?.issuer ?? data?.team?.issuerId ?? keys[0]?.issuerId ?? keys[0]?.issuer;
2543
+ return { keys, issuerId };
2544
+ }
2267
2545
  async post(path, params) {
2268
2546
  const body = new URLSearchParams();
2269
2547
  for (const [k, v] of Object.entries(params)) {
@@ -2331,6 +2609,31 @@ var PortalClient = class _PortalClient {
2331
2609
  async deleteAppId(appIdId) {
2332
2610
  await this.post("account/ios/identifiers/deleteAppId.action", { teamId: this.teamId, appIdId });
2333
2611
  }
2612
+ /**
2613
+ * Toggle a capability (a.k.a. "service") on a bundle ID. Mirrors
2614
+ * Spaceship::Portal's `update_service` — the legacy portal endpoint
2615
+ * still works and is the only session-cookie-authenticated way to flip
2616
+ * capabilities like Push Notifications and Sign in with Apple from
2617
+ * outside the Apple Developer web UI.
2618
+ *
2619
+ * Common service codes (from Spaceship portal/portal_client.rb):
2620
+ * push → push notifications
2621
+ * APG3427HIY → Sign in with Apple
2622
+ * IAD53UNK2F → in-app purchase
2623
+ * homeKit → HomeKit
2624
+ * healthKit → HealthKit
2625
+ *
2626
+ * @param featureType Apple's internal capability key (string code or short name)
2627
+ * @param enabled true → turn on, false → turn off
2628
+ */
2629
+ async setBundleCapability(params) {
2630
+ await this.post("account/ios/identifiers/updateAppService.action", {
2631
+ teamId: this.teamId,
2632
+ displayId: params.appIdId,
2633
+ featureType: params.featureType,
2634
+ featureValue: params.enabled ? "on" : "off"
2635
+ });
2636
+ }
2334
2637
  // ── Certificates ───────────────────────────────────────────────────────
2335
2638
  async listCertificates(types) {
2336
2639
  const iosTypes = types ?? [
@@ -2348,12 +2651,21 @@ var PortalClient = class _PortalClient {
2348
2651
  return data.certRequests ?? [];
2349
2652
  }
2350
2653
  async listPushCertificates() {
2654
+ const types = Array.from(
2655
+ /* @__PURE__ */ new Set([
2656
+ _PortalClient.CERT_TYPES.IOS_PRODUCTION_PUSH,
2657
+ _PortalClient.CERT_TYPES.IOS_DEVELOPMENT_PUSH,
2658
+ // Legacy push codes from OLDER_IOS_CERTIFICATE_TYPES
2659
+ "3BQKVH9I2X",
2660
+ "BKLRAVXMGM"
2661
+ ])
2662
+ );
2351
2663
  const data = await this.post("account/ios/certificate/listCertRequests.action", {
2352
2664
  teamId: this.teamId,
2353
2665
  pageSize: "500",
2354
2666
  pageNumber: "1",
2355
2667
  sort: "certRequestStatusCode=asc",
2356
- types: [_PortalClient.CERT_TYPES.IOS_PRODUCTION_PUSH, _PortalClient.CERT_TYPES.IOS_DEVELOPMENT_PUSH].join(",")
2668
+ types: types.join(",")
2357
2669
  });
2358
2670
  return data.certRequests ?? [];
2359
2671
  }
@@ -2493,6 +2805,310 @@ var PortalClient = class _PortalClient {
2493
2805
  ];
2494
2806
  };
2495
2807
 
2808
+ // src/client/iris.ts
2809
+ var IRIS_BASE = "https://appstoreconnect.apple.com/iris/v1";
2810
+ var IrisClient = class {
2811
+ constructor(session) {
2812
+ this.session = session;
2813
+ this.cookieStr = Object.entries(session.cookies).map(([k, v]) => `${k}=${v}`).join("; ");
2814
+ }
2815
+ session;
2816
+ cookieStr;
2817
+ buildHeaders() {
2818
+ return {
2819
+ Cookie: this.cookieStr,
2820
+ Accept: "application/vnd.api+json, application/json, text/plain, */*",
2821
+ "Content-Type": "application/vnd.api+json",
2822
+ "X-Requested-With": "XMLHttpRequest",
2823
+ // Mimic the App Store Connect web UI's user agent
2824
+ "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"
2825
+ };
2826
+ }
2827
+ /**
2828
+ * Issue a request and absorb any new cookies (Apple rotates session
2829
+ * cookies on a lot of iris calls).
2830
+ */
2831
+ async request(method, path, body) {
2832
+ const headers = this.buildHeaders();
2833
+ if (process.env.FASTNODE_DEBUG) {
2834
+ console.log(`[iris] ${method} ${path}${body ? ` body=${JSON.stringify(body).slice(0, 200)}` : ""}`);
2835
+ }
2836
+ const res = await fetch(`${IRIS_BASE}${path}`, {
2837
+ method,
2838
+ headers,
2839
+ body: body ? JSON.stringify(body) : void 0
2840
+ });
2841
+ for (const raw of res.headers.getSetCookie?.() ?? []) {
2842
+ const m = raw.match(/^([^=]+)=([^;]*)/);
2843
+ if (m) {
2844
+ this.session.cookies[m[1]] = m[2];
2845
+ }
2846
+ }
2847
+ this.cookieStr = Object.entries(this.session.cookies).map(([k, v]) => `${k}=${v}`).join("; ");
2848
+ const text = await res.text();
2849
+ let parsed = null;
2850
+ try {
2851
+ parsed = text ? JSON.parse(text) : null;
2852
+ } catch {
2853
+ }
2854
+ if (process.env.FASTNODE_DEBUG) {
2855
+ console.log(`[iris] \u2192 ${res.status} ${text.slice(0, 300)}`);
2856
+ }
2857
+ return { status: res.status, body: parsed, rawText: text };
2858
+ }
2859
+ /**
2860
+ * List existing API keys. Used both as a sanity check (the user has
2861
+ * permission) and to discover the team's issuer id (which is the same
2862
+ * for every key in the team and is needed by altool).
2863
+ *
2864
+ * Important: Apple's iris endpoint rejects most query parameters with
2865
+ * `PARAMETER_ERROR.INVALID`. Call with no params and let the API return
2866
+ * its default page.
2867
+ */
2868
+ async listApiKeys() {
2869
+ const { status, body, rawText } = await this.request("GET", "/apiKeys");
2870
+ if (status === 403) {
2871
+ throw new IrisAuthError(
2872
+ "You don't have permission to manage App Store Connect API keys (this requires the Account Holder or Admin role)."
2873
+ );
2874
+ }
2875
+ if (status >= 400 || !body) {
2876
+ throw new Error(`iris listApiKeys failed (${status}): ${rawText.slice(0, 200)}`);
2877
+ }
2878
+ const issuerId = body?.meta?.issuerId ?? body?.data?.[0]?.attributes?.issuerId;
2879
+ const keys = (body.data ?? []).map((d) => ({
2880
+ id: d.id,
2881
+ kid: d.attributes?.kid ?? d.id,
2882
+ nickname: d.attributes?.nickname ?? "",
2883
+ issuerId: d.attributes?.issuerId ?? issuerId,
2884
+ roles: d.attributes?.roles ?? [],
2885
+ allAppsVisible: d.attributes?.allAppsVisible ?? true
2886
+ }));
2887
+ return { keys, issuerId };
2888
+ }
2889
+ /**
2890
+ * Create a new API key. Apple returns the .p8 PEM exactly once in the
2891
+ * create response — capture it immediately or the key is dead weight.
2892
+ *
2893
+ * `keyType` is required by Apple's iris API:
2894
+ * • PUBLIC_API — the standard team-wide API key (what TestFlight uploads need)
2895
+ * • MARKETING_API — for App Analytics access only
2896
+ */
2897
+ async createApiKey(input) {
2898
+ const requestBody = {
2899
+ data: {
2900
+ type: "apiKeys",
2901
+ attributes: {
2902
+ nickname: input.nickname,
2903
+ roles: input.roles ?? ["APP_MANAGER"],
2904
+ allAppsVisible: input.allAppsVisible ?? true,
2905
+ keyType: input.keyType ?? "PUBLIC_API"
2906
+ }
2907
+ }
2908
+ };
2909
+ console.log("[iris] createApiKey request:", JSON.stringify(requestBody));
2910
+ const { status, body, rawText } = await this.request("POST", "/apiKeys", requestBody);
2911
+ console.log(`[iris] createApiKey response: ${status} ${rawText.slice(0, 800)}`);
2912
+ if (status === 403) {
2913
+ throw new IrisAuthError(
2914
+ "You don't have permission to create App Store Connect API keys (this requires the Account Holder or Admin role)."
2915
+ );
2916
+ }
2917
+ if (status >= 400 || !body) {
2918
+ const msg = body?.errors?.[0]?.detail ?? body?.errors?.[0]?.title ?? rawText.slice(0, 300) ?? `iris createApiKey failed (${status})`;
2919
+ throw new Error(msg);
2920
+ }
2921
+ const data = body.data ?? body;
2922
+ if (!data?.id) {
2923
+ throw new Error(`iris createApiKey returned no key id. Raw response: ${rawText.slice(0, 400)}`);
2924
+ }
2925
+ const key = {
2926
+ id: data.id,
2927
+ kid: data.attributes?.kid ?? data.id,
2928
+ nickname: data.attributes?.nickname ?? input.nickname,
2929
+ privateKey: data.attributes?.privateKey,
2930
+ issuerId: data.attributes?.issuerId,
2931
+ roles: data.attributes?.roles ?? input.roles ?? ["APP_MANAGER"],
2932
+ allAppsVisible: data.attributes?.allAppsVisible ?? true
2933
+ };
2934
+ return key;
2935
+ }
2936
+ /**
2937
+ * Fetch the .p8 PEM AND the team's issuer id for a previously-created
2938
+ * ASC API key. Both come back in a single request via:
2939
+ *
2940
+ * GET /iris/v1/apiKeys/{id}?fields[apiKeys]=privateKey&include=provider
2941
+ *
2942
+ * Sparse fieldset requesting ONLY `privateKey` is the magic that makes
2943
+ * Apple actually include the (base64-encoded) PEM in the response —
2944
+ * the default view returns `privateKey: null`. The `include=provider`
2945
+ * pulls the team's contentProvider record into `included[]`, and its
2946
+ * `id` field IS the issuer id altool needs (a UUID like
2947
+ * `cfadaf94-44ca-4c2c-8fa6-ecc28d3c7d0d`).
2948
+ *
2949
+ * Reverse-engineered from @expo/apple-utils v2.1.21 (the package that
2950
+ * powers EAS CLI), specifically the `ApiKey.downloadAsync` method
2951
+ * combined with `ApiKey.infoAsync` reading `provider?.id`.
2952
+ *
2953
+ * Returns `{ pem, issuerId }`, or `null` if Apple won't return the
2954
+ * private key (typically because the key was already downloaded once).
2955
+ */
2956
+ async fetchApiKeyPrivateKey(keyId) {
2957
+ try {
2958
+ const url = `${IRIS_BASE}/apiKeys/${keyId}?fields%5BapiKeys%5D=privateKey&include=provider`;
2959
+ const res = await fetch(url, {
2960
+ headers: {
2961
+ ...this.buildHeaders(),
2962
+ Accept: "application/vnd.api+json, application/json, text/plain, */*"
2963
+ }
2964
+ });
2965
+ const text = await res.text();
2966
+ console.log(`[iris] fetchApiKeyPrivateKey \u2192 ${res.status} (${text.length} bytes)`);
2967
+ if (res.status !== 200) {
2968
+ console.log(`[iris] err: ${text.slice(0, 300)}`);
2969
+ return null;
2970
+ }
2971
+ const body = JSON.parse(text);
2972
+ const encoded = body?.data?.attributes?.privateKey;
2973
+ if (typeof encoded !== "string" || encoded.length === 0) {
2974
+ console.log(`[iris] no privateKey in response`);
2975
+ return null;
2976
+ }
2977
+ const pem = Buffer.from(encoded, "base64").toString("utf-8");
2978
+ if (!pem.includes("BEGIN PRIVATE KEY")) {
2979
+ console.log(`[iris] decoded body didn't contain PEM marker`);
2980
+ return null;
2981
+ }
2982
+ const provider = (body?.included ?? []).find((i) => i.type === "contentProviders");
2983
+ const issuerId = provider?.id;
2984
+ console.log(`[iris] \u2713 PEM ${pem.length} bytes, issuerId=${issuerId ?? "(missing)"}`);
2985
+ return { pem, issuerId };
2986
+ } catch (err) {
2987
+ console.log(`[iris] fetchApiKeyPrivateKey error: ${err.message}`);
2988
+ return null;
2989
+ }
2990
+ }
2991
+ /**
2992
+ * @deprecated Kept as a fallback probe for debugging. The real path
2993
+ * is the sparse fieldset above — everything in this brute-force list
2994
+ * returned 404 during testing. Left here so we can re-verify if Apple
2995
+ * changes anything.
2996
+ */
2997
+ async fetchApiKeyPrivateKeyBruteForce(keyId) {
2998
+ const attempts = [
2999
+ // Sparse fieldsets — JSON-API spec lets us request specific attributes.
3000
+ // Apple may exclude privateKey by default and return it only when asked.
3001
+ { kind: "GET", path: `/apiKeys/${keyId}?fields[apiKeys]=privateKey,kid,issuerId,nickname,roles` },
3002
+ { kind: "GET", path: `/apiKeys/${keyId}?include=privateKey` },
3003
+ { kind: "GET", path: `/apiKeys/${keyId}?fields[apiKeys]=privateKey` },
3004
+ // Custom Accept headers — maybe Apple negotiates content type
3005
+ { kind: "GET", path: `/apiKeys/${keyId}`, accept: "application/x-pem-file" },
3006
+ { kind: "GET", path: `/apiKeys/${keyId}`, accept: "application/octet-stream" },
3007
+ { kind: "GET", path: `/apiKeys/${keyId}/p8`, accept: "application/x-pem-file" },
3008
+ // POST variants — Apple sometimes uses POST to mint a download token
3009
+ { kind: "POST", path: `/apiKeys/${keyId}/secrets`, body: {} },
3010
+ { kind: "POST", path: `/apiKeys/${keyId}/regenerate`, body: {} },
3011
+ { kind: "POST", path: `/apiKeys/${keyId}/p8`, body: {} },
3012
+ // Bare GET (last) — confirms canonical fields, in case my parser missed any
3013
+ { kind: "GET", path: `/apiKeys/${keyId}` },
3014
+ // Different host — the legacy developer.apple.com user-and-access namespace
3015
+ { kind: "ABSOLUTE", url: `https://appstoreconnect.apple.com/api/v1/apiKeys/${keyId}/p8` },
3016
+ { kind: "ABSOLUTE", url: `https://appstoreconnect.apple.com/access/api/keys/${keyId}/download` }
3017
+ ];
3018
+ for (const attempt of attempts) {
3019
+ try {
3020
+ let result;
3021
+ if (attempt.kind === "GET") {
3022
+ result = await this.requestWithHeaders("GET", attempt.path, void 0, {
3023
+ ...attempt.accept ? { Accept: attempt.accept } : {}
3024
+ });
3025
+ console.log(`[iris] fetchApiKeyPrivateKey GET ${attempt.path}${attempt.accept ? ` accept=${attempt.accept}` : ""} \u2192 ${result.status} (${result.rawText.length} bytes)`);
3026
+ } else if (attempt.kind === "POST") {
3027
+ result = await this.request("POST", attempt.path, attempt.body);
3028
+ console.log(`[iris] fetchApiKeyPrivateKey POST ${attempt.path} \u2192 ${result.status} (${result.rawText.length} bytes)`);
3029
+ } else {
3030
+ result = await this.requestAbsolute("GET", attempt.url);
3031
+ console.log(`[iris] fetchApiKeyPrivateKey GET ${attempt.url} \u2192 ${result.status} (${result.rawText.length} bytes)`);
3032
+ }
3033
+ if (result.status === 200) {
3034
+ console.log(`[iris] body: ${result.rawText.slice(0, 1500)}`);
3035
+ }
3036
+ if (result.status !== 200) continue;
3037
+ if (result.rawText && result.rawText.includes("BEGIN PRIVATE KEY")) {
3038
+ console.log(`[iris] \u2713 found PEM (plain text response)`);
3039
+ return result.rawText;
3040
+ }
3041
+ if (result.body) {
3042
+ const candidates = [
3043
+ result.body?.data?.attributes?.privateKey,
3044
+ result.body?.data?.attributes?.p8,
3045
+ result.body?.data?.attributes?.privateKeyContent,
3046
+ result.body?.data?.attributes?.kpem,
3047
+ result.body?.data?.attributes?.secret,
3048
+ result.body?.data?.attributes?.keyContent,
3049
+ result.body?.privateKey,
3050
+ result.body?.p8,
3051
+ result.body?.value,
3052
+ result.body?.secret
3053
+ ];
3054
+ for (const c of candidates) {
3055
+ if (typeof c === "string" && c.includes("BEGIN PRIVATE KEY")) {
3056
+ console.log(`[iris] \u2713 found PEM in JSON response`);
3057
+ return c;
3058
+ }
3059
+ }
3060
+ }
3061
+ } catch (err) {
3062
+ console.log(`[iris] fetchApiKeyPrivateKey attempt failed: ${err.message}`);
3063
+ }
3064
+ }
3065
+ console.log(`[iris] fetchApiKeyPrivateKey: no working download path for key ${keyId}`);
3066
+ return null;
3067
+ }
3068
+ /** Internal: like request() but lets us override headers. */
3069
+ async requestWithHeaders(method, path, body, extraHeaders = {}) {
3070
+ const headers = { ...this.buildHeaders(), ...extraHeaders };
3071
+ const res = await fetch(`${IRIS_BASE}${path}`, {
3072
+ method,
3073
+ headers,
3074
+ body: body ? JSON.stringify(body) : void 0
3075
+ });
3076
+ for (const raw of res.headers.getSetCookie?.() ?? []) {
3077
+ const m = raw.match(/^([^=]+)=([^;]*)/);
3078
+ if (m) this.session.cookies[m[1]] = m[2];
3079
+ }
3080
+ this.cookieStr = Object.entries(this.session.cookies).map(([k, v]) => `${k}=${v}`).join("; ");
3081
+ const text = await res.text();
3082
+ let parsed = null;
3083
+ try {
3084
+ parsed = text ? JSON.parse(text) : null;
3085
+ } catch {
3086
+ }
3087
+ return { status: res.status, body: parsed, rawText: text };
3088
+ }
3089
+ /** Internal: fetch an absolute URL with the session cookies. */
3090
+ async requestAbsolute(method, url) {
3091
+ const headers = this.buildHeaders();
3092
+ const res = await fetch(url, { method, headers });
3093
+ const text = await res.text();
3094
+ let parsed = null;
3095
+ try {
3096
+ parsed = text ? JSON.parse(text) : null;
3097
+ } catch {
3098
+ }
3099
+ return { status: res.status, body: parsed, rawText: text };
3100
+ }
3101
+ async deleteApiKey(keyId) {
3102
+ await this.request("DELETE", `/apiKeys/${keyId}`);
3103
+ }
3104
+ };
3105
+ var IrisAuthError = class extends Error {
3106
+ constructor(message) {
3107
+ super(message);
3108
+ this.name = "IrisAuthError";
3109
+ }
3110
+ };
3111
+
2496
3112
  // src/client/index.ts
2497
3113
  var AppStoreConnectClient = class {
2498
3114
  http;
@@ -2581,12 +3197,17 @@ var AppStoreConnectClient = class {
2581
3197
 
2582
3198
  exports.AppStoreConnectClient = AppStoreConnectClient;
2583
3199
  exports.AppStoreConnectError = AppStoreConnectError;
3200
+ exports.IrisAuthError = IrisAuthError;
3201
+ exports.IrisClient = IrisClient;
2584
3202
  exports.PortalClient = PortalClient;
2585
3203
  exports.ProgramLicenseAgreementError = ProgramLicenseAgreementError;
2586
3204
  exports.RateLimitError = RateLimitError;
2587
3205
  exports.RequestClient = RequestClient;
2588
3206
  exports.TokenManager = TokenManager;
3207
+ exports.beginLogin = beginLogin;
2589
3208
  exports.checkPortalResponse = checkPortalResponse;
2590
3209
  exports.loginWithAppleId = loginWithAppleId;
3210
+ exports.requestSmsCode = requestSmsCode;
3211
+ exports.submitTwoFactorCode = submitTwoFactorCode;
2591
3212
  //# sourceMappingURL=index.cjs.map
2592
3213
  //# sourceMappingURL=index.cjs.map