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