@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
package/dist/index.cjs CHANGED
@@ -12,6 +12,7 @@ var util = require('util');
12
12
  var promises = require('fs/promises');
13
13
  var emojiRegex = require('emoji-regex');
14
14
  var plist5 = require('plist');
15
+ var forge = require('node-forge');
15
16
  var commander = require('commander');
16
17
 
17
18
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -37,6 +38,7 @@ function _interopNamespace(e) {
37
38
  var x509__namespace = /*#__PURE__*/_interopNamespace(x509);
38
39
  var emojiRegex__default = /*#__PURE__*/_interopDefault(emojiRegex);
39
40
  var plist5__namespace = /*#__PURE__*/_interopNamespace(plist5);
41
+ var forge__default = /*#__PURE__*/_interopDefault(forge);
40
42
 
41
43
  var __defProp = Object.defineProperty;
42
44
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -244,9 +246,9 @@ Please accept the agreement at https://developer.apple.com/account before contin
244
246
  throw new Error(msg);
245
247
  }
246
248
  }
247
- async function loginWithAppleId(config) {
248
- const log = config.onLog ?? console.log;
249
- const promptFn = config.onPrompt ?? defaultPrompt;
249
+ async function beginLogin(config) {
250
+ const log = config.onLog ?? (() => {
251
+ });
250
252
  log("Fetching Apple service key...");
251
253
  const serviceKey = await fetchServiceKey();
252
254
  const initRes = await fetch(`${AUTH_BASE}/signin?widgetKey=${serviceKey}`, {
@@ -263,27 +265,94 @@ async function loginWithAppleId(config) {
263
265
  const cookieStr = Object.entries(initCookies).map(([k, v]) => k.startsWith("DES") ? `${k}="${v}"` : `${k}=${v}`).join("; ");
264
266
  log("Starting SIRP Apple ID login...");
265
267
  const response = await doSirp(config.email, config.password, serviceKey, cookieStr, hashcash);
266
- const session = {
268
+ const baseState = {
267
269
  cookies: { ...initCookies, ...response.cookies },
268
270
  sessionId: response.sessionId,
269
271
  scnt: response.scnt,
270
272
  serviceKey,
271
- userEmail: config.email,
272
- pendingAgreements: []
273
+ userEmail: config.email
273
274
  };
274
275
  if (response.status === 403) {
275
276
  throw new Error(`Invalid username and password combination. Used '${config.email}' as the username.`);
276
- } else if (response.status === 200) {
277
- log("Login successful.");
278
- await fetchOlympusSession(session);
279
- } else if (response.status === 409) {
280
- await handleTwoStepOrFactor(session, log, promptFn);
281
- await fetchOlympusSession(session);
282
- } else if (response.status === 412) {
277
+ }
278
+ if (response.status === 412) {
283
279
  throw new Error("Need to acknowledge Apple's Apple ID and Privacy statement. Please manually log into https://appleid.apple.com.");
280
+ }
281
+ if (response.status === 200) {
282
+ log("Login successful (no 2FA).");
283
+ const session = { ...baseState, pendingAgreements: [] };
284
+ await finalizeSession(session, log);
285
+ return { kind: "logged_in", session };
286
+ }
287
+ if (response.status === 409) {
288
+ log("2FA required, fetching challenge...");
289
+ const challenge = await fetchTwoFactorChallenge(baseState);
290
+ return { kind: "needs_2fa", pending: baseState, challenge };
291
+ }
292
+ throw new Error(`Unexpected login response (${response.status}): ${JSON.stringify(response.body).slice(0, 500)}`);
293
+ }
294
+ async function fetchTwoFactorChallenge(pending) {
295
+ const r = await fetch(`${AUTH_BASE}`, { headers: buildAuthHeadersFromPending(pending) });
296
+ const body = await r.json();
297
+ const trustedPhoneNumbers = (body.trustedPhoneNumbers ?? []).map((p) => ({
298
+ id: p.id,
299
+ numberWithDialCode: p.numberWithDialCode,
300
+ pushMode: p.pushMode
301
+ }));
302
+ const phoneOnly = body.noTrustedDevices === true;
303
+ const codeLength = body.securityCode?.length ?? 6;
304
+ return {
305
+ kind: phoneOnly ? "phone_only" : "device",
306
+ codeLength,
307
+ trustedPhoneNumbers
308
+ };
309
+ }
310
+ async function requestSmsCode(input) {
311
+ await fetch(`${AUTH_BASE}/verify/phone`, {
312
+ method: "PUT",
313
+ headers: { ...buildAuthHeadersFromPending(input.pending), "Content-Type": "application/json" },
314
+ body: JSON.stringify({ phoneNumber: { id: input.phoneId }, mode: input.mode ?? "sms" })
315
+ });
316
+ }
317
+ async function submitTwoFactorCode(input) {
318
+ const log = input.onLog ?? (() => {
319
+ });
320
+ let path;
321
+ let body;
322
+ if (input.source === "device") {
323
+ path = `${AUTH_BASE}/verify/trusteddevice/securitycode`;
324
+ body = JSON.stringify({ securityCode: { code: input.code } });
284
325
  } else {
285
- throw new Error(`Unexpected login response (${response.status}): ${JSON.stringify(response.body).slice(0, 500)}`);
326
+ if (input.phoneId == null) throw new Error("phoneId is required when source='phone'");
327
+ path = `${AUTH_BASE}/verify/phone/securitycode`;
328
+ body = JSON.stringify({
329
+ securityCode: { code: input.code },
330
+ phoneNumber: { id: input.phoneId },
331
+ mode: input.mode ?? "sms"
332
+ });
286
333
  }
334
+ log("Submitting 2FA code...");
335
+ const verifyRes = await fetch(path, {
336
+ method: "POST",
337
+ headers: { ...buildAuthHeadersFromPending(input.pending), "Content-Type": "application/json" },
338
+ body
339
+ });
340
+ if (!verifyRes.ok) {
341
+ const err = await verifyRes.json().catch(() => ({}));
342
+ const msgs = (err?.service_errors ?? err?.serviceErrors ?? []).map((e) => e.message).filter(Boolean);
343
+ throw new Error(msgs.join("; ") || `Verification failed (${verifyRes.status})`);
344
+ }
345
+ const session = {
346
+ ...input.pending,
347
+ cookies: { ...input.pending.cookies, ...parseCookies(verifyRes.headers) },
348
+ pendingAgreements: []
349
+ };
350
+ await trustSession(session);
351
+ await finalizeSession(session, log);
352
+ return session;
353
+ }
354
+ async function finalizeSession(session, log) {
355
+ await fetchOlympusSession(session);
287
356
  const agreements = await fetchContractMessages(session);
288
357
  if (agreements.length > 0) {
289
358
  for (const msg of agreements) {
@@ -292,7 +361,53 @@ async function loginWithAppleId(config) {
292
361
  }
293
362
  session.pendingAgreements = agreements;
294
363
  log(`Logged in as ${session.userEmail}`);
295
- return session;
364
+ }
365
+ async function loginWithAppleId(config) {
366
+ const log = config.onLog ?? console.log;
367
+ const promptFn = config.onPrompt ?? defaultPrompt;
368
+ const result = await beginLogin({ email: config.email, password: config.password, onLog: log });
369
+ if (result.kind === "logged_in") return result.session;
370
+ const { pending, challenge } = result;
371
+ const phones = challenge.trustedPhoneNumbers;
372
+ if (challenge.kind === "device") {
373
+ log("Two-factor Authentication (6 digit code) is enabled for this account");
374
+ log("(Input 'sms' to escape this prompt and select a trusted phone number to send the code as a text message)");
375
+ const input = await promptFn(`Please enter the ${challenge.codeLength} digit code: `);
376
+ if (input.toLowerCase() === "sms") {
377
+ log("Please select a trusted phone number:");
378
+ for (let i = 0; i < phones.length; i++) log(` ${i + 1}. ${phones[i].numberWithDialCode}`);
379
+ const choice2 = await promptFn("Enter number: ");
380
+ const phone2 = phones[Math.max(0, parseInt(choice2, 10) - 1)] ?? phones[0];
381
+ await requestSmsCode({ pending, phoneId: phone2.id, mode: phone2.pushMode });
382
+ log(`Code sent to ${phone2.numberWithDialCode}`);
383
+ const code2 = await promptFn(`Please enter the ${challenge.codeLength} digit code: `);
384
+ return submitTwoFactorCode({ pending, code: code2, source: "phone", phoneId: phone2.id, mode: phone2.pushMode ?? "sms", onLog: log });
385
+ }
386
+ return submitTwoFactorCode({ pending, code: input, source: "device", onLog: log });
387
+ }
388
+ log("Two-factor Authentication (6 digit code) is enabled for this account");
389
+ if (phones.length === 1) {
390
+ const phone2 = phones[0];
391
+ log(`Code automatically sent to ${phone2.numberWithDialCode}`);
392
+ const code2 = await promptFn(`Please enter the ${challenge.codeLength} digit code: `);
393
+ return submitTwoFactorCode({ pending, code: code2, source: "phone", phoneId: phone2.id, mode: phone2.pushMode ?? "sms", onLog: log });
394
+ }
395
+ log("Please select a trusted phone number:");
396
+ for (let i = 0; i < phones.length; i++) log(` ${i + 1}. ${phones[i].numberWithDialCode}`);
397
+ const choice = await promptFn("Enter number: ");
398
+ const phone = phones[Math.max(0, parseInt(choice, 10) - 1)] ?? phones[0];
399
+ await requestSmsCode({ pending, phoneId: phone.id, mode: phone.pushMode });
400
+ log(`Code sent to ${phone.numberWithDialCode}`);
401
+ const code = await promptFn(`Please enter the ${challenge.codeLength} digit code: `);
402
+ return submitTwoFactorCode({ pending, code, source: "phone", phoneId: phone.id, mode: phone.pushMode ?? "sms", onLog: log });
403
+ }
404
+ function buildAuthHeadersFromPending(pending) {
405
+ const h = { "X-Apple-Widget-Key": pending.serviceKey, Accept: "application/json" };
406
+ if (pending.sessionId) h["X-Apple-Id-Session-Id"] = pending.sessionId;
407
+ if (pending.scnt) h["scnt"] = pending.scnt;
408
+ const c = Object.entries(pending.cookies).map(([k, v]) => `${k}=${v}`).join("; ");
409
+ if (c) h["Cookie"] = c;
410
+ return h;
296
411
  }
297
412
  async function doSirp(user, password, serviceKey, cookieStr, hashcash) {
298
413
  const client = new SRPClient(2048);
@@ -348,99 +463,6 @@ async function doSirp(user, password, serviceKey, cookieStr, hashcash) {
348
463
  scnt: completeRes.headers.get("scnt") ?? ""
349
464
  };
350
465
  }
351
- async function handleTwoStepOrFactor(session, log, promptFn) {
352
- const r = await fetch(`${AUTH_BASE}`, { headers: buildAuthHeaders(session) });
353
- const body = await r.json();
354
- if (body.trustedDevices?.length > 0) {
355
- await handleTwoStep(session, body, log, promptFn);
356
- } else if (body.trustedPhoneNumbers?.length > 0) {
357
- await handleTwoFactor(session, body, log, promptFn);
358
- } else {
359
- throw new Error("2FA required but no trusted devices or phone numbers found.");
360
- }
361
- }
362
- async function handleTwoFactor(session, authBody, log, promptFn) {
363
- log("Two-factor Authentication (6 digit code) is enabled for this account");
364
- const codeLength = authBody.securityCode?.length ?? 6;
365
- const phones = authBody.trustedPhoneNumbers ?? [];
366
- const noTrusted = authBody.noTrustedDevices === true;
367
- let codeType;
368
- let reqBody;
369
- if (noTrusted && phones.length === 1) {
370
- const phone = phones[0];
371
- log(`Code automatically sent to ${phone.numberWithDialCode}`);
372
- const code = await promptFn(`Please enter the ${codeLength} digit code you received at ${phone.numberWithDialCode}: `);
373
- codeType = "phone";
374
- reqBody = JSON.stringify({ securityCode: { code }, phoneNumber: { id: phone.id }, mode: phone.pushMode ?? "sms" });
375
- } else if (noTrusted) {
376
- const phone = await choosePhone(phones, log, promptFn);
377
- await requestPhoneCode(session, phone);
378
- log(`Successfully requested text message to ${phone.numberWithDialCode}`);
379
- const code = await promptFn(`Please enter the ${codeLength} digit code: `);
380
- codeType = "phone";
381
- reqBody = JSON.stringify({ securityCode: { code }, phoneNumber: { id: phone.id }, mode: phone.pushMode ?? "sms" });
382
- } else {
383
- log("(Input 'sms' to escape this prompt and select a trusted phone number to send the code as a text message)");
384
- const input = await promptFn(`Please enter the ${codeLength} digit code: `);
385
- if (input.toLowerCase() === "sms") {
386
- const phone = await choosePhone(phones, log, promptFn);
387
- await requestPhoneCode(session, phone);
388
- const code = await promptFn(`Please enter the ${codeLength} digit code sent to ${phone.numberWithDialCode}: `);
389
- codeType = "phone";
390
- reqBody = JSON.stringify({ securityCode: { code }, phoneNumber: { id: phone.id }, mode: phone.pushMode ?? "sms" });
391
- } else {
392
- codeType = "trusteddevice";
393
- reqBody = JSON.stringify({ securityCode: { code: input } });
394
- }
395
- }
396
- log("Requesting session...");
397
- const verifyRes = await fetch(`${AUTH_BASE}/verify/${codeType}/securitycode`, {
398
- method: "POST",
399
- headers: { ...buildAuthHeaders(session), "Content-Type": "application/json" },
400
- body: reqBody
401
- });
402
- if (!verifyRes.ok) {
403
- const err = await verifyRes.json().catch(() => ({}));
404
- const msgs = (err?.service_errors ?? err?.serviceErrors ?? []).map((e) => e.message).filter(Boolean);
405
- throw new Error(msgs.join("; ") || `Verification failed (${verifyRes.status})`);
406
- }
407
- Object.assign(session.cookies, parseCookies(verifyRes.headers));
408
- await trustSession(session);
409
- }
410
- async function handleTwoStep(session, authBody, log, promptFn) {
411
- log("Two-step Verification (4 digit code) is enabled for this account");
412
- const devices = authBody.trustedDevices ?? [];
413
- log("Please select a trusted device:");
414
- for (let i = 0; i < devices.length; i++) {
415
- log(` ${i + 1}. ${devices[i].name} ${devices[i].modelName ?? "SMS"} (${devices[i].id})`);
416
- }
417
- const choice = await promptFn("Enter device number: ");
418
- const device = devices[Math.max(0, parseInt(choice, 10) - 1)] ?? devices[0];
419
- await fetch(`${AUTH_BASE}/verify/device/${device.id}/securitycode`, { method: "PUT", headers: buildAuthHeaders(session) });
420
- log("Successfully requested notification");
421
- const code = await promptFn("Please enter the 4 digit code: ");
422
- const verifyRes = await fetch(`${AUTH_BASE}/verify/phone/securitycode`, {
423
- method: "POST",
424
- headers: { ...buildAuthHeaders(session), "Content-Type": "application/json" },
425
- body: JSON.stringify({ phoneNumber: { id: device.id }, securityCode: { code }, mode: "sms" })
426
- });
427
- if (!verifyRes.ok) throw new Error("Incorrect verification code.");
428
- Object.assign(session.cookies, parseCookies(verifyRes.headers));
429
- await trustSession(session);
430
- }
431
- async function choosePhone(phones, log, promptFn) {
432
- log("Please select a trusted phone number:");
433
- for (let i = 0; i < phones.length; i++) log(` ${i + 1}. ${phones[i].numberWithDialCode}`);
434
- const choice = await promptFn("Enter number: ");
435
- return phones[Math.max(0, parseInt(choice, 10) - 1)] ?? phones[0];
436
- }
437
- async function requestPhoneCode(session, phone) {
438
- await fetch(`${AUTH_BASE}/verify/phone`, {
439
- method: "PUT",
440
- headers: { ...buildAuthHeaders(session), "Content-Type": "application/json" },
441
- body: JSON.stringify({ phoneNumber: { id: phone.id }, mode: phone.pushMode ?? "sms" })
442
- });
443
- }
444
466
  async function trustSession(session) {
445
467
  const r = await fetch(`${AUTH_BASE}/2sv/trust`, { headers: buildAuthHeaders(session) });
446
468
  Object.assign(session.cookies, parseCookies(r.headers));
@@ -2480,6 +2502,12 @@ var init_xcode_metrics = __esm({
2480
2502
  });
2481
2503
 
2482
2504
  // src/client/portal.ts
2505
+ function pickUniqueKeyName(base, taken) {
2506
+ if (!taken.has(base)) return base;
2507
+ let n = 1;
2508
+ while (taken.has(`${base} - ${n}`)) n++;
2509
+ return `${base} - ${n}`;
2510
+ }
2483
2511
  var PORTAL_BASE, PortalClient;
2484
2512
  var init_portal = __esm({
2485
2513
  "src/client/portal.ts"() {
@@ -2500,6 +2528,279 @@ var init_portal = __esm({
2500
2528
  async init() {
2501
2529
  await this.post("account/listTeams.action", {});
2502
2530
  }
2531
+ /**
2532
+ * JSON POST — different content type than the standard form-encoded
2533
+ * `post()`. Used by the App Store Connect API key endpoints
2534
+ * (`account/auth/key/v2/create`), which Spaceship discovered take a
2535
+ * JSON body even though every other portal mutation is form-encoded.
2536
+ *
2537
+ * Like the form-encoded `post()`, this also runs the response through
2538
+ * `checkPortalResponse` — Apple returns HTTP 200 even for errors and
2539
+ * encodes the error in `resultCode`/`userString` fields, so a raw
2540
+ * status check would silently miss real failures.
2541
+ */
2542
+ async postJson(path, body) {
2543
+ const headers = {
2544
+ Cookie: this.cookieStr,
2545
+ "Content-Type": "application/json",
2546
+ Accept: "application/json"
2547
+ };
2548
+ if (this.csrf) {
2549
+ headers["csrf"] = this.csrf;
2550
+ headers["csrf_ts"] = this.csrfTs;
2551
+ }
2552
+ console.log(`[portal] POST(json) ${path}`);
2553
+ const res = await fetch(`${PORTAL_BASE}/${path}`, {
2554
+ method: "POST",
2555
+ headers,
2556
+ body: JSON.stringify(body)
2557
+ });
2558
+ if (res.headers.get("csrf")) {
2559
+ this.csrf = res.headers.get("csrf");
2560
+ this.csrfTs = res.headers.get("csrf_ts") ?? "";
2561
+ }
2562
+ for (const raw of res.headers.getSetCookie?.() ?? []) {
2563
+ const m = raw.match(/^([^=]+)=([^;]*)/);
2564
+ if (m && !this.cookieStr.includes(m[1] + "=")) this.cookieStr += "; " + m[1] + "=" + m[2];
2565
+ }
2566
+ const text = await res.text();
2567
+ let data = null;
2568
+ try {
2569
+ data = text ? JSON.parse(text) : null;
2570
+ } catch {
2571
+ }
2572
+ console.log(`[portal] POST(json) ${path} \u2192 ${res.status} ${text.slice(0, 400)}`);
2573
+ checkPortalResponse(data, this.session);
2574
+ return { status: res.status, body: data, rawText: text };
2575
+ }
2576
+ /**
2577
+ * GET helper for the portal endpoints that take query parameters
2578
+ * (currently just `account/auth/key/download`). Returns the raw text
2579
+ * since download endpoints can return PEMs or JSON depending on Apple's
2580
+ * mood — caller decides how to parse.
2581
+ */
2582
+ async getRaw(path, params = {}) {
2583
+ const url = new URL(`${PORTAL_BASE}/${path}`);
2584
+ for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
2585
+ const headers = {
2586
+ Cookie: this.cookieStr,
2587
+ Accept: "application/json, text/plain, application/x-pem-file, */*"
2588
+ };
2589
+ if (this.csrf) {
2590
+ headers["csrf"] = this.csrf;
2591
+ headers["csrf_ts"] = this.csrfTs;
2592
+ }
2593
+ console.log(`[portal] GET ${url.pathname}${url.search}`);
2594
+ const res = await fetch(url.toString(), { headers });
2595
+ for (const raw of res.headers.getSetCookie?.() ?? []) {
2596
+ const m = raw.match(/^([^=]+)=([^;]*)/);
2597
+ if (m && !this.cookieStr.includes(m[1] + "=")) this.cookieStr += "; " + m[1] + "=" + m[2];
2598
+ }
2599
+ const text = await res.text();
2600
+ const contentType = res.headers.get("content-type") ?? "";
2601
+ console.log(`[portal] GET ${url.pathname} \u2192 ${res.status} ${contentType} ${text.length}b`);
2602
+ return { status: res.status, rawText: text, contentType };
2603
+ }
2604
+ // ── App Store Connect API Keys (.p8) ────────────────────────────────────
2605
+ /**
2606
+ * Create an App Store Connect API key via the developer portal's
2607
+ * `account/auth/key/v2/create` endpoint. Reverse-engineered from the
2608
+ * _current_ @expo/apple-utils npm package (v2.1.21), which is what
2609
+ * EAS CLI uses to manage Apple credentials in production.
2610
+ *
2611
+ * This differs from older published reverse-engineering guides:
2612
+ * • URL uses the `/v2/create` suffix (Apple kept it)
2613
+ * • Field is `serviceConfigurations`, shape is an object keyed by
2614
+ * service id (NOT `serviceConfigurationsRequests: [...]` array)
2615
+ * • Body REQUIRES `scope: "team"`
2616
+ * • Needs a scope-specific CSRF warmup via the `keys` endpoint
2617
+ * before the create call (EAS's `ensureCSRFAsync("keys", …)`)
2618
+ *
2619
+ * For an App Store Connect API key (PUBLIC_API, used by altool for
2620
+ * TestFlight uploads), `serviceConfigurations` is an empty object `{}`.
2621
+ * For an APNs auth key, it's `{ "U27F4V844T": [] }`. For MusicKit:
2622
+ * `{ "6A7HVUVQ3M": [musicId] }`, etc.
2623
+ *
2624
+ * Apple's name validator rejects parentheses, brackets, and most
2625
+ * punctuation — sanitize to alphanumeric + space + dash + underscore
2626
+ * + period and collapse whitespace.
2627
+ */
2628
+ async createApiKey(rawName, serviceConfigurations = {}) {
2629
+ const baseName = rawName.replace(/[^A-Za-z0-9 _\-.]/g, " ").replace(/\s+/g, " ").trim().slice(0, 45);
2630
+ if (!baseName) throw new Error("createApiKey: name is empty after sanitization");
2631
+ let existingNames = /* @__PURE__ */ new Set();
2632
+ try {
2633
+ const list = await this.listApiKeys();
2634
+ existingNames = new Set(
2635
+ (list.keys ?? []).map((k) => String(k.keyName ?? "").trim())
2636
+ );
2637
+ } catch {
2638
+ }
2639
+ const name = pickUniqueKeyName(baseName, existingNames);
2640
+ const body = {
2641
+ teamId: this.teamId,
2642
+ name,
2643
+ serviceConfigurations,
2644
+ scope: "team"
2645
+ };
2646
+ const result = await this.postJson("account/auth/key/v2/create", body);
2647
+ const created = result.body?.keys?.[0] ?? result.body?.key ?? result.body?.data ?? result.body;
2648
+ const keyId = created?.keyId ?? created?.id ?? created?.kid ?? created?.attributes?.kid;
2649
+ if (!keyId) {
2650
+ throw new Error(`createApiKey: no key id in response. Body: ${result.rawText.slice(0, 400)}`);
2651
+ }
2652
+ return { keyId, raw: created };
2653
+ }
2654
+ /**
2655
+ * Fetch a single API key by id via `account/auth/key/get`. Reverse-
2656
+ * engineered from Spaceship's `get_key`. Returns the raw key record so
2657
+ * the caller can extract whatever fields it needs (e.g. issuerId).
2658
+ *
2659
+ * Form-encoded POST — same shape as every other PortalClient mutation
2660
+ * except the JSON `create` endpoint.
2661
+ */
2662
+ async getApiKey(keyId) {
2663
+ const data = await this.post("account/auth/key/get", {
2664
+ teamId: this.teamId,
2665
+ keyId
2666
+ });
2667
+ return data?.keys?.[0] ?? data?.key ?? data?.data ?? data;
2668
+ }
2669
+ /**
2670
+ * Revoke an existing key. Form-encoded POST per Spaceship's
2671
+ * `revoke_key!`. Used for cleaning up orphan keys created during
2672
+ * failed wizard runs.
2673
+ */
2674
+ async revokeApiKey(keyId) {
2675
+ await this.post("account/auth/key/revoke", {
2676
+ teamId: this.teamId,
2677
+ keyId
2678
+ });
2679
+ }
2680
+ // ── APNs Authentication Keys (.p8) ──────────────────────────────────────
2681
+ /** Apple's hardcoded service id for APNs auth keys (from Spaceship). */
2682
+ static APNS_SERVICE_ID = "U27F4V844T";
2683
+ /**
2684
+ * Create an APNs Authentication Key (.p8) via the developer portal.
2685
+ *
2686
+ * Apple requires BOTH `serviceConfigurations` (the map) AND
2687
+ * `serviceConfigurationsRequests` (the array of full config objects)
2688
+ * in the v2/create body. Just sending the map alone results in
2689
+ * "No value was provided for the parameter 'serviceConfigurations'".
2690
+ *
2691
+ * The exact body comes from @expo/apple-utils v2.1.21 — both fields
2692
+ * are produced by separate functions (`d` for the map, `h` for the
2693
+ * array) and merged into the create payload.
2694
+ *
2695
+ * Apple also rejects duplicate key names ("Another key with same
2696
+ * name exists") — we dedupe by listing existing keys first and
2697
+ * appending " (N)" until we find a free slot, mirroring the
2698
+ * provisioning profile dedup.
2699
+ */
2700
+ async createApnsAuthKey(rawName) {
2701
+ const baseName = rawName.replace(/[^A-Za-z0-9 _\-.]/g, " ").replace(/\s+/g, " ").trim().slice(0, 45);
2702
+ if (!baseName) throw new Error("createApnsAuthKey: name is empty after sanitization");
2703
+ let existingNames = /* @__PURE__ */ new Set();
2704
+ try {
2705
+ const list = await this.listApiKeys();
2706
+ existingNames = new Set(
2707
+ (list.keys ?? []).map((k) => String(k.keyName ?? "").trim())
2708
+ );
2709
+ } catch {
2710
+ }
2711
+ const name = pickUniqueKeyName(baseName, existingNames);
2712
+ const body = {
2713
+ teamId: this.teamId,
2714
+ name,
2715
+ serviceConfigurations: {
2716
+ [_PortalClient.APNS_SERVICE_ID]: []
2717
+ },
2718
+ serviceConfigurationsRequests: [
2719
+ {
2720
+ isNew: true,
2721
+ serviceId: _PortalClient.APNS_SERVICE_ID,
2722
+ identifiers: {},
2723
+ environment: "all",
2724
+ scope: "team"
2725
+ }
2726
+ ],
2727
+ scope: "team"
2728
+ };
2729
+ const result = await this.postJson("account/auth/key/v2/create", body);
2730
+ const created = result.body?.keys?.[0];
2731
+ if (!created?.keyId) {
2732
+ throw new Error(`createApnsAuthKey: no key id in response. Body: ${result.rawText.slice(0, 400)}`);
2733
+ }
2734
+ const pem = await this.downloadApiKey(created.keyId);
2735
+ return { keyId: created.keyId, pem, raw: created };
2736
+ }
2737
+ /**
2738
+ * Find existing APNs auth keys in the team. Used by the wizard to
2739
+ * detect "you already have one" cases and offer to reuse rather than
2740
+ * proliferate keys.
2741
+ */
2742
+ async listApnsAuthKeys() {
2743
+ const list = await this.listApiKeys();
2744
+ return (list.keys ?? []).filter(
2745
+ (k) => (k.services ?? []).some((s) => s.id === _PortalClient.APNS_SERVICE_ID || /apns/i.test(s.name ?? ""))
2746
+ ).map((k) => ({
2747
+ keyId: k.keyId,
2748
+ keyName: k.keyName,
2749
+ canDownload: Boolean(k.canDownload)
2750
+ }));
2751
+ }
2752
+ /**
2753
+ * Download an existing App Store Connect API key as PEM. Spaceship's
2754
+ * `download_key` endpoint — GET with teamId + keyId in query string.
2755
+ * Returns the raw .p8 PEM text. Apple shows the .p8 exactly once
2756
+ * (after creation), so call this immediately after createApiKey.
2757
+ */
2758
+ async downloadApiKey(keyId) {
2759
+ const { status, rawText, contentType } = await this.getRaw("account/auth/key/download", {
2760
+ teamId: this.teamId,
2761
+ keyId
2762
+ });
2763
+ if (status !== 200) {
2764
+ throw new Error(`downloadApiKey failed (${status}): ${rawText.slice(0, 200)}`);
2765
+ }
2766
+ if (rawText.includes("BEGIN PRIVATE KEY")) return rawText;
2767
+ if (contentType.includes("json")) {
2768
+ try {
2769
+ const parsed = JSON.parse(rawText);
2770
+ const candidates = [
2771
+ parsed?.privateKey,
2772
+ parsed?.key?.privateKey,
2773
+ parsed?.keys?.[0]?.privateKey,
2774
+ parsed?.data?.attributes?.privateKey,
2775
+ parsed?.value
2776
+ ];
2777
+ for (const c of candidates) {
2778
+ if (typeof c === "string" && c.includes("BEGIN PRIVATE KEY")) return c;
2779
+ }
2780
+ } catch {
2781
+ }
2782
+ }
2783
+ throw new Error(`downloadApiKey returned no PEM. Content-Type=${contentType} body=${rawText.slice(0, 300)}`);
2784
+ }
2785
+ /**
2786
+ * List existing API keys via the portal. Used to discover the team's
2787
+ * issuer id — every key in the team shares the same issuer id, and
2788
+ * altool needs it alongside the key id and .p8 file.
2789
+ *
2790
+ * Form-encoded POST (NOT JSON), with pagination params, per Spaceship's
2791
+ * `list_keys` method. JSON returned 415 from this endpoint.
2792
+ */
2793
+ async listApiKeys() {
2794
+ const data = await this.post("account/auth/key/list", {
2795
+ teamId: this.teamId,
2796
+ pageNumber: "1",
2797
+ pageSize: "500",
2798
+ sort: "name=asc"
2799
+ });
2800
+ const keys = data?.keys ?? [];
2801
+ const issuerId = data?.issuerId ?? data?.issuer ?? data?.team?.issuerId ?? keys[0]?.issuerId ?? keys[0]?.issuer;
2802
+ return { keys, issuerId };
2803
+ }
2503
2804
  async post(path, params) {
2504
2805
  const body = new URLSearchParams();
2505
2806
  for (const [k, v] of Object.entries(params)) {
@@ -2567,6 +2868,31 @@ var init_portal = __esm({
2567
2868
  async deleteAppId(appIdId) {
2568
2869
  await this.post("account/ios/identifiers/deleteAppId.action", { teamId: this.teamId, appIdId });
2569
2870
  }
2871
+ /**
2872
+ * Toggle a capability (a.k.a. "service") on a bundle ID. Mirrors
2873
+ * Spaceship::Portal's `update_service` — the legacy portal endpoint
2874
+ * still works and is the only session-cookie-authenticated way to flip
2875
+ * capabilities like Push Notifications and Sign in with Apple from
2876
+ * outside the Apple Developer web UI.
2877
+ *
2878
+ * Common service codes (from Spaceship portal/portal_client.rb):
2879
+ * push → push notifications
2880
+ * APG3427HIY → Sign in with Apple
2881
+ * IAD53UNK2F → in-app purchase
2882
+ * homeKit → HomeKit
2883
+ * healthKit → HealthKit
2884
+ *
2885
+ * @param featureType Apple's internal capability key (string code or short name)
2886
+ * @param enabled true → turn on, false → turn off
2887
+ */
2888
+ async setBundleCapability(params) {
2889
+ await this.post("account/ios/identifiers/updateAppService.action", {
2890
+ teamId: this.teamId,
2891
+ displayId: params.appIdId,
2892
+ featureType: params.featureType,
2893
+ featureValue: params.enabled ? "on" : "off"
2894
+ });
2895
+ }
2570
2896
  // ── Certificates ───────────────────────────────────────────────────────
2571
2897
  async listCertificates(types) {
2572
2898
  const iosTypes = types ?? [
@@ -2584,12 +2910,21 @@ var init_portal = __esm({
2584
2910
  return data.certRequests ?? [];
2585
2911
  }
2586
2912
  async listPushCertificates() {
2913
+ const types = Array.from(
2914
+ /* @__PURE__ */ new Set([
2915
+ _PortalClient.CERT_TYPES.IOS_PRODUCTION_PUSH,
2916
+ _PortalClient.CERT_TYPES.IOS_DEVELOPMENT_PUSH,
2917
+ // Legacy push codes from OLDER_IOS_CERTIFICATE_TYPES
2918
+ "3BQKVH9I2X",
2919
+ "BKLRAVXMGM"
2920
+ ])
2921
+ );
2587
2922
  const data = await this.post("account/ios/certificate/listCertRequests.action", {
2588
2923
  teamId: this.teamId,
2589
2924
  pageSize: "500",
2590
2925
  pageNumber: "1",
2591
2926
  sort: "certRequestStatusCode=asc",
2592
- types: [_PortalClient.CERT_TYPES.IOS_PRODUCTION_PUSH, _PortalClient.CERT_TYPES.IOS_DEVELOPMENT_PUSH].join(",")
2927
+ types: types.join(",")
2593
2928
  });
2594
2929
  return data.certRequests ?? [];
2595
2930
  }
@@ -2731,18 +3066,332 @@ var init_portal = __esm({
2731
3066
  }
2732
3067
  });
2733
3068
 
3069
+ // src/client/iris.ts
3070
+ var IRIS_BASE, IrisClient, IrisAuthError;
3071
+ var init_iris = __esm({
3072
+ "src/client/iris.ts"() {
3073
+ IRIS_BASE = "https://appstoreconnect.apple.com/iris/v1";
3074
+ IrisClient = class {
3075
+ constructor(session) {
3076
+ this.session = session;
3077
+ this.cookieStr = Object.entries(session.cookies).map(([k, v]) => `${k}=${v}`).join("; ");
3078
+ }
3079
+ session;
3080
+ cookieStr;
3081
+ buildHeaders() {
3082
+ return {
3083
+ Cookie: this.cookieStr,
3084
+ Accept: "application/vnd.api+json, application/json, text/plain, */*",
3085
+ "Content-Type": "application/vnd.api+json",
3086
+ "X-Requested-With": "XMLHttpRequest",
3087
+ // Mimic the App Store Connect web UI's user agent
3088
+ "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"
3089
+ };
3090
+ }
3091
+ /**
3092
+ * Issue a request and absorb any new cookies (Apple rotates session
3093
+ * cookies on a lot of iris calls).
3094
+ */
3095
+ async request(method, path, body) {
3096
+ const headers = this.buildHeaders();
3097
+ if (process.env.FASTNODE_DEBUG) {
3098
+ console.log(`[iris] ${method} ${path}${body ? ` body=${JSON.stringify(body).slice(0, 200)}` : ""}`);
3099
+ }
3100
+ const res = await fetch(`${IRIS_BASE}${path}`, {
3101
+ method,
3102
+ headers,
3103
+ body: body ? JSON.stringify(body) : void 0
3104
+ });
3105
+ for (const raw of res.headers.getSetCookie?.() ?? []) {
3106
+ const m = raw.match(/^([^=]+)=([^;]*)/);
3107
+ if (m) {
3108
+ this.session.cookies[m[1]] = m[2];
3109
+ }
3110
+ }
3111
+ this.cookieStr = Object.entries(this.session.cookies).map(([k, v]) => `${k}=${v}`).join("; ");
3112
+ const text = await res.text();
3113
+ let parsed = null;
3114
+ try {
3115
+ parsed = text ? JSON.parse(text) : null;
3116
+ } catch {
3117
+ }
3118
+ if (process.env.FASTNODE_DEBUG) {
3119
+ console.log(`[iris] \u2192 ${res.status} ${text.slice(0, 300)}`);
3120
+ }
3121
+ return { status: res.status, body: parsed, rawText: text };
3122
+ }
3123
+ /**
3124
+ * List existing API keys. Used both as a sanity check (the user has
3125
+ * permission) and to discover the team's issuer id (which is the same
3126
+ * for every key in the team and is needed by altool).
3127
+ *
3128
+ * Important: Apple's iris endpoint rejects most query parameters with
3129
+ * `PARAMETER_ERROR.INVALID`. Call with no params and let the API return
3130
+ * its default page.
3131
+ */
3132
+ async listApiKeys() {
3133
+ const { status, body, rawText } = await this.request("GET", "/apiKeys");
3134
+ if (status === 403) {
3135
+ throw new IrisAuthError(
3136
+ "You don't have permission to manage App Store Connect API keys (this requires the Account Holder or Admin role)."
3137
+ );
3138
+ }
3139
+ if (status >= 400 || !body) {
3140
+ throw new Error(`iris listApiKeys failed (${status}): ${rawText.slice(0, 200)}`);
3141
+ }
3142
+ const issuerId = body?.meta?.issuerId ?? body?.data?.[0]?.attributes?.issuerId;
3143
+ const keys = (body.data ?? []).map((d) => ({
3144
+ id: d.id,
3145
+ kid: d.attributes?.kid ?? d.id,
3146
+ nickname: d.attributes?.nickname ?? "",
3147
+ issuerId: d.attributes?.issuerId ?? issuerId,
3148
+ roles: d.attributes?.roles ?? [],
3149
+ allAppsVisible: d.attributes?.allAppsVisible ?? true
3150
+ }));
3151
+ return { keys, issuerId };
3152
+ }
3153
+ /**
3154
+ * Create a new API key. Apple returns the .p8 PEM exactly once in the
3155
+ * create response — capture it immediately or the key is dead weight.
3156
+ *
3157
+ * `keyType` is required by Apple's iris API:
3158
+ * • PUBLIC_API — the standard team-wide API key (what TestFlight uploads need)
3159
+ * • MARKETING_API — for App Analytics access only
3160
+ */
3161
+ async createApiKey(input) {
3162
+ const requestBody = {
3163
+ data: {
3164
+ type: "apiKeys",
3165
+ attributes: {
3166
+ nickname: input.nickname,
3167
+ roles: input.roles ?? ["APP_MANAGER"],
3168
+ allAppsVisible: input.allAppsVisible ?? true,
3169
+ keyType: input.keyType ?? "PUBLIC_API"
3170
+ }
3171
+ }
3172
+ };
3173
+ console.log("[iris] createApiKey request:", JSON.stringify(requestBody));
3174
+ const { status, body, rawText } = await this.request("POST", "/apiKeys", requestBody);
3175
+ console.log(`[iris] createApiKey response: ${status} ${rawText.slice(0, 800)}`);
3176
+ if (status === 403) {
3177
+ throw new IrisAuthError(
3178
+ "You don't have permission to create App Store Connect API keys (this requires the Account Holder or Admin role)."
3179
+ );
3180
+ }
3181
+ if (status >= 400 || !body) {
3182
+ const msg = body?.errors?.[0]?.detail ?? body?.errors?.[0]?.title ?? rawText.slice(0, 300) ?? `iris createApiKey failed (${status})`;
3183
+ throw new Error(msg);
3184
+ }
3185
+ const data = body.data ?? body;
3186
+ if (!data?.id) {
3187
+ throw new Error(`iris createApiKey returned no key id. Raw response: ${rawText.slice(0, 400)}`);
3188
+ }
3189
+ const key = {
3190
+ id: data.id,
3191
+ kid: data.attributes?.kid ?? data.id,
3192
+ nickname: data.attributes?.nickname ?? input.nickname,
3193
+ privateKey: data.attributes?.privateKey,
3194
+ issuerId: data.attributes?.issuerId,
3195
+ roles: data.attributes?.roles ?? input.roles ?? ["APP_MANAGER"],
3196
+ allAppsVisible: data.attributes?.allAppsVisible ?? true
3197
+ };
3198
+ return key;
3199
+ }
3200
+ /**
3201
+ * Fetch the .p8 PEM AND the team's issuer id for a previously-created
3202
+ * ASC API key. Both come back in a single request via:
3203
+ *
3204
+ * GET /iris/v1/apiKeys/{id}?fields[apiKeys]=privateKey&include=provider
3205
+ *
3206
+ * Sparse fieldset requesting ONLY `privateKey` is the magic that makes
3207
+ * Apple actually include the (base64-encoded) PEM in the response —
3208
+ * the default view returns `privateKey: null`. The `include=provider`
3209
+ * pulls the team's contentProvider record into `included[]`, and its
3210
+ * `id` field IS the issuer id altool needs (a UUID like
3211
+ * `cfadaf94-44ca-4c2c-8fa6-ecc28d3c7d0d`).
3212
+ *
3213
+ * Reverse-engineered from @expo/apple-utils v2.1.21 (the package that
3214
+ * powers EAS CLI), specifically the `ApiKey.downloadAsync` method
3215
+ * combined with `ApiKey.infoAsync` reading `provider?.id`.
3216
+ *
3217
+ * Returns `{ pem, issuerId }`, or `null` if Apple won't return the
3218
+ * private key (typically because the key was already downloaded once).
3219
+ */
3220
+ async fetchApiKeyPrivateKey(keyId) {
3221
+ try {
3222
+ const url = `${IRIS_BASE}/apiKeys/${keyId}?fields%5BapiKeys%5D=privateKey&include=provider`;
3223
+ const res = await fetch(url, {
3224
+ headers: {
3225
+ ...this.buildHeaders(),
3226
+ Accept: "application/vnd.api+json, application/json, text/plain, */*"
3227
+ }
3228
+ });
3229
+ const text = await res.text();
3230
+ console.log(`[iris] fetchApiKeyPrivateKey \u2192 ${res.status} (${text.length} bytes)`);
3231
+ if (res.status !== 200) {
3232
+ console.log(`[iris] err: ${text.slice(0, 300)}`);
3233
+ return null;
3234
+ }
3235
+ const body = JSON.parse(text);
3236
+ const encoded = body?.data?.attributes?.privateKey;
3237
+ if (typeof encoded !== "string" || encoded.length === 0) {
3238
+ console.log(`[iris] no privateKey in response`);
3239
+ return null;
3240
+ }
3241
+ const pem = Buffer.from(encoded, "base64").toString("utf-8");
3242
+ if (!pem.includes("BEGIN PRIVATE KEY")) {
3243
+ console.log(`[iris] decoded body didn't contain PEM marker`);
3244
+ return null;
3245
+ }
3246
+ const provider = (body?.included ?? []).find((i) => i.type === "contentProviders");
3247
+ const issuerId = provider?.id;
3248
+ console.log(`[iris] \u2713 PEM ${pem.length} bytes, issuerId=${issuerId ?? "(missing)"}`);
3249
+ return { pem, issuerId };
3250
+ } catch (err) {
3251
+ console.log(`[iris] fetchApiKeyPrivateKey error: ${err.message}`);
3252
+ return null;
3253
+ }
3254
+ }
3255
+ /**
3256
+ * @deprecated Kept as a fallback probe for debugging. The real path
3257
+ * is the sparse fieldset above — everything in this brute-force list
3258
+ * returned 404 during testing. Left here so we can re-verify if Apple
3259
+ * changes anything.
3260
+ */
3261
+ async fetchApiKeyPrivateKeyBruteForce(keyId) {
3262
+ const attempts = [
3263
+ // Sparse fieldsets — JSON-API spec lets us request specific attributes.
3264
+ // Apple may exclude privateKey by default and return it only when asked.
3265
+ { kind: "GET", path: `/apiKeys/${keyId}?fields[apiKeys]=privateKey,kid,issuerId,nickname,roles` },
3266
+ { kind: "GET", path: `/apiKeys/${keyId}?include=privateKey` },
3267
+ { kind: "GET", path: `/apiKeys/${keyId}?fields[apiKeys]=privateKey` },
3268
+ // Custom Accept headers — maybe Apple negotiates content type
3269
+ { kind: "GET", path: `/apiKeys/${keyId}`, accept: "application/x-pem-file" },
3270
+ { kind: "GET", path: `/apiKeys/${keyId}`, accept: "application/octet-stream" },
3271
+ { kind: "GET", path: `/apiKeys/${keyId}/p8`, accept: "application/x-pem-file" },
3272
+ // POST variants — Apple sometimes uses POST to mint a download token
3273
+ { kind: "POST", path: `/apiKeys/${keyId}/secrets`, body: {} },
3274
+ { kind: "POST", path: `/apiKeys/${keyId}/regenerate`, body: {} },
3275
+ { kind: "POST", path: `/apiKeys/${keyId}/p8`, body: {} },
3276
+ // Bare GET (last) — confirms canonical fields, in case my parser missed any
3277
+ { kind: "GET", path: `/apiKeys/${keyId}` },
3278
+ // Different host — the legacy developer.apple.com user-and-access namespace
3279
+ { kind: "ABSOLUTE", url: `https://appstoreconnect.apple.com/api/v1/apiKeys/${keyId}/p8` },
3280
+ { kind: "ABSOLUTE", url: `https://appstoreconnect.apple.com/access/api/keys/${keyId}/download` }
3281
+ ];
3282
+ for (const attempt of attempts) {
3283
+ try {
3284
+ let result;
3285
+ if (attempt.kind === "GET") {
3286
+ result = await this.requestWithHeaders("GET", attempt.path, void 0, {
3287
+ ...attempt.accept ? { Accept: attempt.accept } : {}
3288
+ });
3289
+ console.log(`[iris] fetchApiKeyPrivateKey GET ${attempt.path}${attempt.accept ? ` accept=${attempt.accept}` : ""} \u2192 ${result.status} (${result.rawText.length} bytes)`);
3290
+ } else if (attempt.kind === "POST") {
3291
+ result = await this.request("POST", attempt.path, attempt.body);
3292
+ console.log(`[iris] fetchApiKeyPrivateKey POST ${attempt.path} \u2192 ${result.status} (${result.rawText.length} bytes)`);
3293
+ } else {
3294
+ result = await this.requestAbsolute("GET", attempt.url);
3295
+ console.log(`[iris] fetchApiKeyPrivateKey GET ${attempt.url} \u2192 ${result.status} (${result.rawText.length} bytes)`);
3296
+ }
3297
+ if (result.status === 200) {
3298
+ console.log(`[iris] body: ${result.rawText.slice(0, 1500)}`);
3299
+ }
3300
+ if (result.status !== 200) continue;
3301
+ if (result.rawText && result.rawText.includes("BEGIN PRIVATE KEY")) {
3302
+ console.log(`[iris] \u2713 found PEM (plain text response)`);
3303
+ return result.rawText;
3304
+ }
3305
+ if (result.body) {
3306
+ const candidates = [
3307
+ result.body?.data?.attributes?.privateKey,
3308
+ result.body?.data?.attributes?.p8,
3309
+ result.body?.data?.attributes?.privateKeyContent,
3310
+ result.body?.data?.attributes?.kpem,
3311
+ result.body?.data?.attributes?.secret,
3312
+ result.body?.data?.attributes?.keyContent,
3313
+ result.body?.privateKey,
3314
+ result.body?.p8,
3315
+ result.body?.value,
3316
+ result.body?.secret
3317
+ ];
3318
+ for (const c of candidates) {
3319
+ if (typeof c === "string" && c.includes("BEGIN PRIVATE KEY")) {
3320
+ console.log(`[iris] \u2713 found PEM in JSON response`);
3321
+ return c;
3322
+ }
3323
+ }
3324
+ }
3325
+ } catch (err) {
3326
+ console.log(`[iris] fetchApiKeyPrivateKey attempt failed: ${err.message}`);
3327
+ }
3328
+ }
3329
+ console.log(`[iris] fetchApiKeyPrivateKey: no working download path for key ${keyId}`);
3330
+ return null;
3331
+ }
3332
+ /** Internal: like request() but lets us override headers. */
3333
+ async requestWithHeaders(method, path, body, extraHeaders = {}) {
3334
+ const headers = { ...this.buildHeaders(), ...extraHeaders };
3335
+ const res = await fetch(`${IRIS_BASE}${path}`, {
3336
+ method,
3337
+ headers,
3338
+ body: body ? JSON.stringify(body) : void 0
3339
+ });
3340
+ for (const raw of res.headers.getSetCookie?.() ?? []) {
3341
+ const m = raw.match(/^([^=]+)=([^;]*)/);
3342
+ if (m) this.session.cookies[m[1]] = m[2];
3343
+ }
3344
+ this.cookieStr = Object.entries(this.session.cookies).map(([k, v]) => `${k}=${v}`).join("; ");
3345
+ const text = await res.text();
3346
+ let parsed = null;
3347
+ try {
3348
+ parsed = text ? JSON.parse(text) : null;
3349
+ } catch {
3350
+ }
3351
+ return { status: res.status, body: parsed, rawText: text };
3352
+ }
3353
+ /** Internal: fetch an absolute URL with the session cookies. */
3354
+ async requestAbsolute(method, url) {
3355
+ const headers = this.buildHeaders();
3356
+ const res = await fetch(url, { method, headers });
3357
+ const text = await res.text();
3358
+ let parsed = null;
3359
+ try {
3360
+ parsed = text ? JSON.parse(text) : null;
3361
+ } catch {
3362
+ }
3363
+ return { status: res.status, body: parsed, rawText: text };
3364
+ }
3365
+ async deleteApiKey(keyId) {
3366
+ await this.request("DELETE", `/apiKeys/${keyId}`);
3367
+ }
3368
+ };
3369
+ IrisAuthError = class extends Error {
3370
+ constructor(message) {
3371
+ super(message);
3372
+ this.name = "IrisAuthError";
3373
+ }
3374
+ };
3375
+ }
3376
+ });
3377
+
2734
3378
  // src/client/index.ts
2735
3379
  var client_exports = {};
2736
3380
  __export(client_exports, {
2737
3381
  AppStoreConnectClient: () => exports.AppStoreConnectClient,
2738
3382
  AppStoreConnectError: () => exports.AppStoreConnectError,
3383
+ IrisAuthError: () => IrisAuthError,
3384
+ IrisClient: () => IrisClient,
2739
3385
  PortalClient: () => PortalClient,
2740
3386
  ProgramLicenseAgreementError: () => ProgramLicenseAgreementError,
2741
3387
  RateLimitError: () => exports.RateLimitError,
2742
3388
  RequestClient: () => exports.RequestClient,
2743
3389
  TokenManager: () => exports.TokenManager,
3390
+ beginLogin: () => beginLogin,
2744
3391
  checkPortalResponse: () => checkPortalResponse,
2745
- loginWithAppleId: () => loginWithAppleId
3392
+ loginWithAppleId: () => loginWithAppleId,
3393
+ requestSmsCode: () => requestSmsCode,
3394
+ submitTwoFactorCode: () => submitTwoFactorCode
2746
3395
  });
2747
3396
  exports.AppStoreConnectClient = void 0;
2748
3397
  var init_client = __esm({
@@ -2787,6 +3436,7 @@ var init_client = __esm({
2787
3436
  init_request();
2788
3437
  init_apple_session();
2789
3438
  init_portal();
3439
+ init_iris();
2790
3440
  exports.AppStoreConnectClient = class {
2791
3441
  http;
2792
3442
  certificates;
@@ -7974,6 +8624,7 @@ init_review_submissions();
7974
8624
  // src/cert/index.ts
7975
8625
  var cert_exports2 = {};
7976
8626
  __export(cert_exports2, {
8627
+ bundleP12: () => bundleP12,
7977
8628
  createCertificate: () => createCertificate,
7978
8629
  downloadCertificate: () => downloadCertificate,
7979
8630
  findValidCertificates: () => findValidCertificates,
@@ -7984,6 +8635,41 @@ __export(cert_exports2, {
7984
8635
  });
7985
8636
  init_cert();
7986
8637
  init_csr();
8638
+ function derBufferToPem(der) {
8639
+ const b64 = der.toString("base64");
8640
+ const lines = [];
8641
+ for (let i = 0; i < b64.length; i += 64) lines.push(b64.slice(i, i + 64));
8642
+ return `-----BEGIN CERTIFICATE-----
8643
+ ${lines.join("\n")}
8644
+ -----END CERTIFICATE-----
8645
+ `;
8646
+ }
8647
+ function normalizeCertPem(input) {
8648
+ if (typeof input === "string") {
8649
+ if (input.includes("BEGIN CERTIFICATE")) return input;
8650
+ const b64 = input.replace(/\s+/g, "");
8651
+ return derBufferToPem(Buffer.from(b64, "base64"));
8652
+ }
8653
+ return derBufferToPem(input);
8654
+ }
8655
+ function bundleP12(options) {
8656
+ const certPem = normalizeCertPem(options.certificate);
8657
+ const cert = forge__default.default.pki.certificateFromPem(certPem);
8658
+ const privateKey = forge__default.default.pki.privateKeyFromPem(options.privateKeyPem);
8659
+ const friendlyName = options.friendlyName ?? "fastnode signing identity";
8660
+ const p12Asn1 = forge__default.default.pkcs12.toPkcs12Asn1(
8661
+ privateKey,
8662
+ [cert],
8663
+ options.password,
8664
+ {
8665
+ friendlyName,
8666
+ generateLocalKeyId: true,
8667
+ algorithm: "3des"
8668
+ }
8669
+ );
8670
+ const der = forge__default.default.asn1.toDer(p12Asn1).getBytes();
8671
+ return Buffer.from(der, "binary");
8672
+ }
7987
8673
 
7988
8674
  // src/index.ts
7989
8675
  init_sigh();
@@ -8331,6 +9017,440 @@ init_lane();
8331
9017
  init_lane();
8332
9018
  init_context();
8333
9019
  init_actions();
9020
+
9021
+ // src/setup/one-click.ts
9022
+ init_portal();
9023
+ init_iris();
9024
+ init_client();
9025
+ init_csr();
9026
+ var DIST_CERT_TYPE = PortalClient.CERT_TYPES.IOS_DISTRIBUTION;
9027
+ var PUSH_PROD_TYPE = PortalClient.CERT_TYPES.IOS_PRODUCTION_PUSH;
9028
+ var PUSH_DEV_TYPE = PortalClient.CERT_TYPES.IOS_DEVELOPMENT_PUSH;
9029
+ function randomPassword(length = 32) {
9030
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
9031
+ const bytes = crypto.randomBytes(length);
9032
+ let out = "";
9033
+ for (let i = 0; i < length; i++) out += alphabet[bytes[i] % alphabet.length];
9034
+ return out;
9035
+ }
9036
+ function extractProfileMetadata(profile) {
9037
+ const text = profile.toString("binary");
9038
+ const start = text.indexOf("<?xml");
9039
+ const end = text.indexOf("</plist>");
9040
+ if (start < 0 || end < 0) return {};
9041
+ const plistXml = text.slice(start, end + "</plist>".length);
9042
+ const nameMatch = plistXml.match(/<key>Name<\/key>\s*<string>([^<]+)<\/string>/);
9043
+ const uuidMatch = plistXml.match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);
9044
+ return { name: nameMatch?.[1], uuid: uuidMatch?.[1] };
9045
+ }
9046
+ function classifyPushCertType(typeString) {
9047
+ if (!typeString) return "other";
9048
+ const t = typeString.toLowerCase();
9049
+ if (t.includes("production")) return "production";
9050
+ if (t.includes("development") || t.includes("sandbox")) return "sandbox";
9051
+ return "other";
9052
+ }
9053
+ function buildProfileName(appName, existingNames) {
9054
+ const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
9055
+ const base = `${appName} App Store ${today}`;
9056
+ const taken = new Set(existingNames);
9057
+ if (!taken.has(base)) return base;
9058
+ let n = 1;
9059
+ while (taken.has(`${base} (${n})`)) n++;
9060
+ return `${base} (${n})`;
9061
+ }
9062
+ async function oneClickListTeams(session) {
9063
+ const portal = new PortalClient(session, "");
9064
+ const teams = await portal.listTeams();
9065
+ return (teams ?? []).map((t) => ({
9066
+ teamId: t.teamId,
9067
+ name: t.name,
9068
+ role: t.userRole?.name ?? t.type,
9069
+ status: t.status
9070
+ }));
9071
+ }
9072
+ async function oneClickInventory(session, teamId) {
9073
+ const portal = new PortalClient(session, teamId);
9074
+ await portal.init();
9075
+ const [appIds, allCerts, profiles, pushCerts, apiKeys] = await Promise.all([
9076
+ portal.listAppIds(),
9077
+ portal.listCertificates([DIST_CERT_TYPE]),
9078
+ portal.listProfiles(),
9079
+ portal.listPushCertificates(),
9080
+ portal.listApiKeys().catch(() => ({ keys: [] }))
9081
+ ]);
9082
+ const distributionCerts = (allCerts ?? []).map((c) => ({
9083
+ certificateId: c.certificateId,
9084
+ name: c.name ?? "Distribution",
9085
+ serialNumber: c.serialNum,
9086
+ expirationDate: c.expirationDateString,
9087
+ ownerName: c.ownerName
9088
+ }));
9089
+ const apnsAuthKeys = (apiKeys.keys ?? []).filter(
9090
+ (k) => (k.services ?? []).some(
9091
+ (s) => s.id === PortalClient.APNS_SERVICE_ID || /apns/i.test(s.name ?? "")
9092
+ )
9093
+ ).map((k) => ({
9094
+ keyId: k.keyId,
9095
+ keyName: k.keyName,
9096
+ dateCreated: k.dateCreated
9097
+ }));
9098
+ return {
9099
+ team: { id: teamId },
9100
+ bundleIds: (appIds ?? []).map((a) => ({
9101
+ appIdId: a.appIdId,
9102
+ identifier: a.identifier,
9103
+ name: a.name
9104
+ })),
9105
+ distributionCerts,
9106
+ distCertCapacity: { used: distributionCerts.length, max: 3 },
9107
+ apnsAuthKeys,
9108
+ apnsKeyCapacity: { used: apnsAuthKeys.length, max: 2 },
9109
+ pushCerts: (pushCerts ?? []).map((c) => ({
9110
+ certificateId: c.certificateId,
9111
+ name: c.name ?? "Push",
9112
+ type: classifyPushCertType(c.typeString),
9113
+ bundleIdentifier: c.appId?.identifier,
9114
+ expirationDate: c.expirationDateString
9115
+ })),
9116
+ profiles: (profiles ?? []).map((p) => ({
9117
+ provisioningProfileId: p.provisioningProfileId,
9118
+ name: p.name,
9119
+ type: p.type,
9120
+ status: p.status,
9121
+ expirationDate: p.expirationDate
9122
+ }))
9123
+ };
9124
+ }
9125
+ async function ensureBundleId(portal, identifier, name, warnings) {
9126
+ const existing = await portal.listAppIds();
9127
+ const hit = existing.find((a) => a.identifier === identifier);
9128
+ if (hit) {
9129
+ warnings.push(`Bundle ID ${identifier} already existed and was reused.`);
9130
+ return hit.appIdId;
9131
+ }
9132
+ const created = await portal.createAppId({ identifier, name, enablePush: true });
9133
+ return created.appIdId;
9134
+ }
9135
+ async function createDistCert(portal) {
9136
+ const { csr, privateKey } = generateRSACSR();
9137
+ const cert = await portal.createCertificate({ type: DIST_CERT_TYPE, csrContent: csr });
9138
+ let certContent;
9139
+ if (cert.certificateContent) {
9140
+ certContent = Buffer.from(cert.certificateContent, "base64");
9141
+ } else {
9142
+ certContent = await portal.downloadCertificate(cert.certificateId, DIST_CERT_TYPE);
9143
+ }
9144
+ return { certificateId: cert.certificateId, privateKeyPem: privateKey, certContent };
9145
+ }
9146
+ async function createPushCert(portal, appIdId, type) {
9147
+ const { csr, privateKey } = generateRSACSR();
9148
+ const cert = await portal.createCertificate({ type, csrContent: csr, appIdId });
9149
+ let certContent;
9150
+ if (cert.certificateContent) {
9151
+ certContent = Buffer.from(cert.certificateContent, "base64");
9152
+ } else {
9153
+ certContent = await portal.downloadCertificate(cert.certificateId, type);
9154
+ }
9155
+ return { certificateId: cert.certificateId, privateKeyPem: privateKey, certContent };
9156
+ }
9157
+ function findExistingPushCertForBundle(pushCerts, appIdId, bundleIdentifier, kind) {
9158
+ for (const c of pushCerts) {
9159
+ const appMatches = c.appId?.appIdId === appIdId || c.appId?.identifier === bundleIdentifier;
9160
+ if (!appMatches) continue;
9161
+ const ts = (c.typeString ?? "").toLowerCase();
9162
+ const name = (c.name ?? "").toLowerCase();
9163
+ const looksLikePush = ts.includes("push") || ts.includes("apns") || name.includes("apple push services");
9164
+ if (!looksLikePush) continue;
9165
+ const isProduction = ts.includes("production");
9166
+ const isSandbox = ts.includes("development") || ts.includes("sandbox");
9167
+ const isUnified = !isProduction && !isSandbox;
9168
+ if (!isUnified) {
9169
+ if (kind === "production" && !isProduction) continue;
9170
+ if (kind === "sandbox" && !isSandbox) continue;
9171
+ }
9172
+ return {
9173
+ certificateId: c.certificateId,
9174
+ name: c.name ?? "Apple Push Services",
9175
+ expirationDate: c.expirationDateString
9176
+ };
9177
+ }
9178
+ return null;
9179
+ }
9180
+ async function oneClickSetup(input) {
9181
+ const opts = {
9182
+ generateDistributionCert: input.options?.generateDistributionCert ?? true,
9183
+ generateStoreProfile: input.options?.generateStoreProfile ?? true,
9184
+ generateAscApiKey: input.options?.generateAscApiKey ?? true,
9185
+ generateApnsAuthKey: input.options?.generateApnsAuthKey ?? true,
9186
+ generatePushProductionCert: input.options?.generatePushProductionCert ?? false,
9187
+ generatePushSandboxCert: input.options?.generatePushSandboxCert ?? false,
9188
+ enableSignInWithApple: input.options?.enableSignInWithApple ?? true,
9189
+ enablePushNotifications: input.options?.enablePushNotifications ?? true,
9190
+ revokeCertIds: input.options?.revokeCertIds ?? [],
9191
+ revokeApnsKeyIds: input.options?.revokeApnsKeyIds ?? []
9192
+ };
9193
+ const onProgress = input.onProgress ?? (() => {
9194
+ });
9195
+ const warnings = [];
9196
+ const created = { revokedCertIds: [] };
9197
+ const additionalCerts = [];
9198
+ if (!opts.generateDistributionCert || !opts.generateStoreProfile) {
9199
+ throw new Error("Distribution cert and store profile are both required for an apple_credentials row.");
9200
+ }
9201
+ async function step(id, label, fn) {
9202
+ onProgress({ type: "step_start", step: id, label });
9203
+ try {
9204
+ const result = await fn();
9205
+ onProgress({ type: "step_done", step: id, label });
9206
+ return result;
9207
+ } catch (err) {
9208
+ onProgress({
9209
+ type: "step_failed",
9210
+ step: id,
9211
+ label,
9212
+ error: err instanceof Error ? err.message : String(err)
9213
+ });
9214
+ throw err;
9215
+ }
9216
+ }
9217
+ const portal = new PortalClient(input.session, input.teamId);
9218
+ await step("init", "Initialize Apple Developer portal session", () => portal.init());
9219
+ for (const certId of opts.revokeCertIds) {
9220
+ await step(`revoke:${certId}`, `Revoke distribution certificate ${certId}`, async () => {
9221
+ await portal.revokeCertificate(certId, DIST_CERT_TYPE);
9222
+ created.revokedCertIds.push(certId);
9223
+ });
9224
+ }
9225
+ const appIdId = await step(
9226
+ "bundle_id",
9227
+ `Bundle identifier ${input.bundleIdentifier}`,
9228
+ () => ensureBundleId(portal, input.bundleIdentifier, input.appName, warnings)
9229
+ );
9230
+ created.bundleIdId = appIdId;
9231
+ const dist = await step("dist_cert", "Distribution certificate", () => createDistCert(portal));
9232
+ created.certificateId = dist.certificateId;
9233
+ const certPassword = input.certPassword ?? randomPassword();
9234
+ const distP12 = await step(
9235
+ "p12",
9236
+ "Bundle distribution .p12",
9237
+ async () => bundleP12({
9238
+ certificate: dist.certContent,
9239
+ privateKeyPem: dist.privateKeyPem,
9240
+ password: certPassword,
9241
+ friendlyName: `${input.appName} Distribution`
9242
+ })
9243
+ );
9244
+ const existingProfiles = await portal.listProfiles();
9245
+ const profileName = buildProfileName(
9246
+ input.appName,
9247
+ (existingProfiles ?? []).map((p) => p.name)
9248
+ );
9249
+ const profile = await step("profile", `App Store provisioning profile (${profileName})`, async () => {
9250
+ const p = await portal.createProfile({
9251
+ appIdId,
9252
+ name: profileName,
9253
+ distributionType: "store",
9254
+ certificateIds: [dist.certificateId]
9255
+ });
9256
+ const content = await portal.downloadProfile(p.provisioningProfileId);
9257
+ return { id: p.provisioningProfileId, content };
9258
+ });
9259
+ created.provisioningProfileId = profile.id;
9260
+ const profileMeta = extractProfileMetadata(profile.content);
9261
+ if (profileMeta.uuid) created.profileUuid = profileMeta.uuid;
9262
+ for (const keyId of opts.revokeApnsKeyIds) {
9263
+ await step(`revoke_apns:${keyId}`, `Revoke APNs auth key ${keyId}`, async () => {
9264
+ await portal.revokeApiKey(keyId);
9265
+ });
9266
+ }
9267
+ if (opts.generateApnsAuthKey) {
9268
+ await step("apns_auth_key", "APNs Authentication Key (.p8)", async () => {
9269
+ try {
9270
+ const key = await portal.createApnsAuthKey(`${input.appName} APNs`);
9271
+ created.apnsAuthKeyId = key.keyId;
9272
+ additionalCerts.push({
9273
+ cert_type: "apns_key",
9274
+ cert_base64: Buffer.from(key.pem, "utf-8").toString("base64"),
9275
+ cert_password: key.keyId
9276
+ });
9277
+ } catch (err) {
9278
+ warnings.push(
9279
+ `APNs Authentication Key could not be created: ${err.message}. You can upload an existing .p8 manually from the credentials list.`
9280
+ );
9281
+ }
9282
+ });
9283
+ }
9284
+ let pushCertCache = null;
9285
+ const loadPushCerts = async () => {
9286
+ if (pushCertCache == null) {
9287
+ pushCertCache = await portal.listPushCertificates();
9288
+ }
9289
+ return pushCertCache;
9290
+ };
9291
+ async function provisionLegacyPushCert(stepId, label, kind, pushType, certType, friendlyName) {
9292
+ await step(stepId, label, async () => {
9293
+ try {
9294
+ const existing = findExistingPushCertForBundle(
9295
+ await loadPushCerts(),
9296
+ appIdId,
9297
+ input.bundleIdentifier,
9298
+ kind
9299
+ );
9300
+ if (existing) {
9301
+ warnings.push(
9302
+ `${label} already exists for ${input.bundleIdentifier} ("${existing.name}"` + (existing.expirationDate ? `, expires ${existing.expirationDate}` : "") + `). Skipped \u2014 Apple caps these at 1 per bundle per environment and we can't recover the existing private key. Revoke it manually in Apple Developer Portal and re-run if you need a sitepong-managed copy.`
9303
+ );
9304
+ return;
9305
+ }
9306
+ const c = await createPushCert(portal, appIdId, pushType);
9307
+ const pushPassword = randomPassword();
9308
+ const p12 = bundleP12({
9309
+ certificate: c.certContent,
9310
+ privateKeyPem: c.privateKeyPem,
9311
+ password: pushPassword,
9312
+ friendlyName
9313
+ });
9314
+ additionalCerts.push({
9315
+ cert_type: certType,
9316
+ cert_base64: p12.toString("base64"),
9317
+ cert_password: pushPassword
9318
+ });
9319
+ } catch (err) {
9320
+ warnings.push(
9321
+ `${label} could not be created: ${err.message}. You can upload an existing .p12 manually from the credentials list.`
9322
+ );
9323
+ }
9324
+ });
9325
+ }
9326
+ if (opts.generatePushProductionCert) {
9327
+ await provisionLegacyPushCert(
9328
+ "push_prod_cert",
9329
+ "APS Production push certificate (.p12)",
9330
+ "production",
9331
+ PUSH_PROD_TYPE,
9332
+ "aps_production",
9333
+ `${input.appName} APNs Production`
9334
+ );
9335
+ }
9336
+ if (opts.generatePushSandboxCert) {
9337
+ await provisionLegacyPushCert(
9338
+ "push_sandbox_cert",
9339
+ "APS Sandbox push certificate (.p12)",
9340
+ "sandbox",
9341
+ PUSH_DEV_TYPE,
9342
+ "aps_sandbox",
9343
+ `${input.appName} APNs Sandbox`
9344
+ );
9345
+ }
9346
+ let ascKeyId = "";
9347
+ let ascIssuerId = "";
9348
+ let ascP8Base64 = "";
9349
+ let ascP8Pem = "";
9350
+ if (opts.generateAscApiKey) {
9351
+ await step("asc_api_key", "App Store Connect API key (.p8)", async () => {
9352
+ try {
9353
+ const iris = new IrisClient(input.session);
9354
+ const createdKey = await iris.createApiKey({
9355
+ nickname: `${input.appName} SitePong`,
9356
+ roles: ["APP_MANAGER"],
9357
+ allAppsVisible: true,
9358
+ keyType: "PUBLIC_API"
9359
+ });
9360
+ created.ascApiKeyId = createdKey.id;
9361
+ const downloaded = await iris.fetchApiKeyPrivateKey(createdKey.id);
9362
+ if (!downloaded) {
9363
+ throw new Error(
9364
+ `Created key ${createdKey.kid} but Apple did not return the .p8. Revoke it at appstoreconnect.apple.com/access/integrations/api/${createdKey.id} before retrying.`
9365
+ );
9366
+ }
9367
+ if (!downloaded.issuerId) {
9368
+ throw new Error(
9369
+ `Created key ${createdKey.kid} and got the .p8 but Apple did not return an issuer id. Revoke it at appstoreconnect.apple.com/access/integrations/api/${createdKey.id} and check ApiKey.infoAsync semantics.`
9370
+ );
9371
+ }
9372
+ ascKeyId = createdKey.kid;
9373
+ ascIssuerId = downloaded.issuerId;
9374
+ ascP8Pem = downloaded.pem;
9375
+ ascP8Base64 = Buffer.from(downloaded.pem, "utf-8").toString("base64");
9376
+ } catch (err) {
9377
+ warnings.push(
9378
+ `Could not auto-create ASC API key: ${err.message}. Upload a .p8 manually after the wizard finishes.`
9379
+ );
9380
+ }
9381
+ });
9382
+ }
9383
+ if ((opts.enablePushNotifications || opts.enableSignInWithApple) && ascKeyId && ascIssuerId && ascP8Pem) {
9384
+ await step("capabilities", "Enable bundle capabilities (Push, Sign in with Apple)", async () => {
9385
+ try {
9386
+ const ascClient = new exports.AppStoreConnectClient({
9387
+ keyId: ascKeyId,
9388
+ issuerId: ascIssuerId,
9389
+ privateKey: ascP8Pem
9390
+ });
9391
+ const restBundle = await ascClient.bundleIds.find(input.bundleIdentifier);
9392
+ if (!restBundle) {
9393
+ warnings.push(
9394
+ `Could not look up bundle id ${input.bundleIdentifier} via REST API \u2014 capability flips skipped.`
9395
+ );
9396
+ return;
9397
+ }
9398
+ const existing = await ascClient.capabilities.listForBundleId(restBundle.id);
9399
+ const existingTypes = new Set(existing.map((c) => c.attributes?.capabilityType));
9400
+ const wanted = [];
9401
+ if (opts.enablePushNotifications) {
9402
+ wanted.push({ type: "PUSH_NOTIFICATIONS", label: "Push Notifications" });
9403
+ }
9404
+ if (opts.enableSignInWithApple) {
9405
+ wanted.push({
9406
+ type: "APPLE_ID_AUTH",
9407
+ label: "Sign in with Apple",
9408
+ settings: [
9409
+ {
9410
+ key: "APPLE_ID_AUTH_APP_CONSENT",
9411
+ options: [{ key: "PRIMARY_APP_CONSENT" }]
9412
+ }
9413
+ ]
9414
+ });
9415
+ }
9416
+ for (const w of wanted) {
9417
+ if (existingTypes.has(w.type)) continue;
9418
+ try {
9419
+ await ascClient.capabilities.enable({
9420
+ bundleIdId: restBundle.id,
9421
+ capabilityType: w.type,
9422
+ settings: w.settings
9423
+ });
9424
+ } catch (err) {
9425
+ warnings.push(`Could not enable ${w.label}: ${err.message}`);
9426
+ }
9427
+ }
9428
+ } catch (err) {
9429
+ warnings.push(`Capability setup failed: ${err.message}`);
9430
+ }
9431
+ });
9432
+ } else if ((opts.enablePushNotifications || opts.enableSignInWithApple) && !ascKeyId) {
9433
+ warnings.push(
9434
+ "Push / Sign in with Apple capabilities couldn't be flipped automatically (no ASC API key). Enable them manually in your Apple Developer Portal."
9435
+ );
9436
+ }
9437
+ return {
9438
+ team_id: input.teamId,
9439
+ bundle_identifier: input.bundleIdentifier,
9440
+ name: `${input.appName} \u2014 Distribution`,
9441
+ dist_cert_base64: distP12.toString("base64"),
9442
+ private_key_base64: Buffer.from(dist.privateKeyPem, "utf-8").toString("base64"),
9443
+ cert_password: certPassword,
9444
+ provisioning_profile_base64: profile.content.toString("base64"),
9445
+ profile_name: profileMeta.name ?? profileName,
9446
+ asc_key_id: ascKeyId,
9447
+ asc_issuer_id: ascIssuerId,
9448
+ asc_api_key_base64: ascP8Base64,
9449
+ additional_certs: additionalCerts,
9450
+ created,
9451
+ warnings
9452
+ };
9453
+ }
8334
9454
  function createRunCommand() {
8335
9455
  const cmd = new commander.Command("run").description("Execute a lane from Fastfile.ts").argument("<lane>", "Lane name to execute").argument("[params...]", "Key:value parameters").option("-p, --platform <platform>", "Platform (ios, android)").action(async (laneName, params, opts) => {
8336
9456
  const { loadFastfile: loadFastfile2 } = await Promise.resolve().then(() => (init_fastfile(), fastfile_exports));
@@ -8648,6 +9768,9 @@ exports.listActions = listActions;
8648
9768
  exports.listAvailableLanes = listAvailableLanes;
8649
9769
  exports.loadFastfile = loadFastfile;
8650
9770
  exports.match = match_exports;
9771
+ exports.oneClickInventory = oneClickInventory;
9772
+ exports.oneClickListTeams = oneClickListTeams;
9773
+ exports.oneClickSetup = oneClickSetup;
8651
9774
  exports.pem = pem_exports;
8652
9775
  exports.pilot = pilot_exports;
8653
9776
  exports.precheck = precheck_exports;