@superwall/cli 1.6.2 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +110 -3
  2. package/dist/{actions-H7f6knyY.js → actions-B7ym3oVS.js} +2 -2
  3. package/dist/{api-Dv3LyZ5m.js → api-CZzirVMj.js} +6 -6
  4. package/dist/{app-mJC5NDtW.js → app-DH6U8yuI.js} +11 -10
  5. package/dist/{asa-D6H7Pjae.js → asa-C-sQzPPn.js} +8 -8
  6. package/dist/{asc-xCin0akG.js → asc-1ZBJ6DwS.js} +280 -41
  7. package/dist/asc-Bf7zBbyS.js +65 -0
  8. package/dist/{asc-products-Dvcyef3_.js → asc-products-9JXtDxI4.js} +2 -35
  9. package/dist/{auth-ZlLL-Gko.js → auth-YRhlV3DE.js} +11 -10
  10. package/dist/auth.js +2 -2
  11. package/dist/{billing-C8kBge_S.js → billing-CCYHdApx.js} +1 -1
  12. package/dist/{bind-BIzaGq8K.js → bind-YrJvuRF9.js} +3 -3
  13. package/dist/{build-B7BS1rF2.js → build-DLoCW5Ri.js} +7 -7
  14. package/dist/bundle-id-CKxl_026.js +121 -0
  15. package/dist/{command-3fGYyC8r.js → command-CMIz81Da.js} +5 -5
  16. package/dist/{create-CwnnNqv4.js → create-pkANt1Gs.js} +22 -22
  17. package/dist/dev-DZy6pOnB.js +22 -0
  18. package/dist/{dev-CgGAb5Al.js → dev-DmB3XqaJ.js} +12 -7
  19. package/dist/{doctor-CyUvut31.js → doctor-H-hf-Yww.js} +10 -10
  20. package/dist/{drivers-6RMOPIdn.js → drivers-Qx9LxmRN.js} +2 -2
  21. package/dist/entry.js +382 -39
  22. package/dist/{existing-DHpPn1y6.js → existing-AVEfZu2A.js} +2 -2
  23. package/dist/{feedback-RKyGuQ8_.js → feedback-CKf-rpBW.js} +6 -6
  24. package/dist/{hosted-BeGVAntr.js → hosted-CXe9TrWx.js} +2 -2
  25. package/dist/{integrate-BR2LR-EK.js → integrate-brmhPG-S.js} +23 -22
  26. package/dist/{login-Bhxgqwtm.js → login-Do4wFuLv.js} +31 -16
  27. package/dist/{migrate-C-4ISELN.js → migrate-C9ERDR6y.js} +24 -24
  28. package/dist/notification-url-DuKF2659.js +1273 -0
  29. package/dist/{open-studio-BnVD6tJ9.js → open-studio-DOw-6ydc.js} +10 -10
  30. package/dist/{org-CQduIOic.js → org-sj7uyvp-.js} +2 -2
  31. package/dist/{output-C-4UKMot.js → output-C4o2gJ1K.js} +12 -2
  32. package/dist/{pipeline-CHX0Syre.js → pipeline-BqzqZhX1.js} +6 -6
  33. package/dist/{print-skill-BiZLdCKv.js → print-skill-ZojRSybs.js} +7 -7
  34. package/dist/{promote-Pgpz-3xl.js → promote-BG8X4Nv_.js} +17 -17
  35. package/dist/publish-sxLh-G4G.js +35 -0
  36. package/dist/push-bQ6Vxtg8.js +35 -0
  37. package/dist/{query-CWLaZkdm.js → query-_FbybaH-.js} +8 -8
  38. package/dist/{resource-jwASPCrw.js → resource-CGIwSd29.js} +16 -176
  39. package/dist/revenue-provider-ebsRINY8.js +100 -0
  40. package/dist/{run-D-NbZLpj.js → run-DsVZ5snL.js} +2 -2
  41. package/dist/{scan-BmAW413l.js → scan-zKsddO72.js} +1 -1
  42. package/dist/scope-BvzD-kO4.js +223 -0
  43. package/dist/{selection-BGi6GyxC.js → selection-CxZoX4NT.js} +2 -2
  44. package/dist/setup-Bxj22rYi.js +189 -0
  45. package/dist/{skills-AxAf7bDB.js → skills-DPzlnfCK.js} +3 -3
  46. package/dist/{skills-FK5aDuNV.js → skills-D_R-lEsK.js} +8 -8
  47. package/dist/{spinner-DFctF_Jw.js → spinner-TWa0hia6.js} +1 -1
  48. package/dist/{telemetry-Ch9cCTI-.js → telemetry-DeA1mvnT.js} +1 -1
  49. package/dist/{token-BGAVPSQc.js → token-C0it-Xh7.js} +1 -1
  50. package/dist/{ui-4gLyfrgl.js → ui-Dy0b-9L8.js} +4 -3
  51. package/dist/{update-DIXbL-H9.js → update-B2fWIc4q.js} +2 -2
  52. package/dist/{upgrade-De7JMI1g.js → upgrade-BmzkTKrh.js} +6 -6
  53. package/package.json +2 -2
  54. package/dist/dev-Dx99K183.js +0 -22
  55. package/dist/publish-BPeuc3lq.js +0 -35
  56. package/dist/push-DcSQ4odB.js +0 -35
  57. /package/dist/{reports-DqMs9xNR.js → reports-CfJqoava.js} +0 -0
  58. /package/dist/{storekit-CC4gnTI6.js → storekit-Cj9Cpjcz.js} +0 -0
@@ -0,0 +1,1273 @@
1
+ import { C as appleCredentialsFromEnv, h as ENV_APPLE_PASSWORD, m as ENV_APPLE_ID, r as formatJson, t as blocks, v as SUPERWALL_HOME, x as VERSION } from "./output-C4o2gJ1K.js";
2
+ import { r as ApiError } from "./command-CMIz81Da.js";
3
+ import { h as listProjects, n as createApplication, s as createProject } from "./resources-Bf9O1JNM.js";
4
+ import { n as emitJson, t as apiCall } from "./api-output-aJNw7Syy.js";
5
+ import { a as getAppNotificationUrl, c as saveAppAscKey, l as saveAppPurchaseKey } from "./asc-Bf7zBbyS.js";
6
+ import { a as checkServerNotifications, c as getIntegrations, m as setServerNotifications } from "./scope-BvzD-kO4.js";
7
+ import { n as testModeWarning } from "./bundle-id-CKxl_026.js";
8
+ import { join } from "node:path";
9
+ import { homedir } from "node:os";
10
+ import { createHash, pbkdf2Sync, randomBytes } from "node:crypto";
11
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
12
+
13
+ //#region src/core/apple/pending.ts
14
+ const LIFETIME_MS = 600 * 1e3;
15
+ function dir() {
16
+ return SUPERWALL_HOME() ?? join(homedir(), ".superwall");
17
+ }
18
+ function file() {
19
+ return join(dir(), "apple-sign-in.json");
20
+ }
21
+ function savePending(pending, now = Date.now()) {
22
+ mkdirSync(dir(), {
23
+ recursive: true,
24
+ mode: 448
25
+ });
26
+ const stored = {
27
+ savedAt: now,
28
+ pending
29
+ };
30
+ writeFileSync(file(), `${formatJson(stored)}\n`, { mode: 384 });
31
+ }
32
+ function loadPending(now = Date.now()) {
33
+ try {
34
+ if (!existsSync(file())) return void 0;
35
+ const stored = JSON.parse(readFileSync(file(), "utf8"));
36
+ if (now - stored.savedAt > LIFETIME_MS) {
37
+ clearPending();
38
+ return;
39
+ }
40
+ return stored.pending;
41
+ } catch {
42
+ return;
43
+ }
44
+ }
45
+ function clearPending() {
46
+ rmSync(file(), { force: true });
47
+ }
48
+
49
+ //#endregion
50
+ //#region src/core/apple/cookies.ts
51
+ function parse(url, line) {
52
+ const [pair = "", ...attributes] = line.split(";");
53
+ const separator = pair.indexOf("=");
54
+ if (separator <= 0) return void 0;
55
+ const cookie = {
56
+ name: pair.slice(0, separator).trim(),
57
+ value: pair.slice(separator + 1).trim(),
58
+ domain: url.hostname.toLowerCase(),
59
+ hostOnly: true,
60
+ path: "/"
61
+ };
62
+ let expired = false;
63
+ for (const attribute of attributes) {
64
+ const split = attribute.indexOf("=");
65
+ const key = (split === -1 ? attribute : attribute.slice(0, split)).trim().toLowerCase();
66
+ const value = split === -1 ? "" : attribute.slice(split + 1).trim();
67
+ if (key === "domain" && value) {
68
+ cookie.domain = value.replace(/^\./, "").toLowerCase();
69
+ cookie.hostOnly = false;
70
+ } else if (key === "path" && value.startsWith("/")) cookie.path = value;
71
+ else if (key === "max-age" && Number(value) <= 0) expired = true;
72
+ else if (key === "expires") {
73
+ const at = Date.parse(value);
74
+ if (!Number.isNaN(at) && at <= Date.now()) expired = true;
75
+ }
76
+ }
77
+ return {
78
+ cookie,
79
+ expired
80
+ };
81
+ }
82
+ function matches(cookie, url) {
83
+ const host = url.hostname.toLowerCase();
84
+ if (!(cookie.hostOnly ? host === cookie.domain : host === cookie.domain || host.endsWith(`.${cookie.domain}`))) return false;
85
+ if (cookie.path === "/") return true;
86
+ return url.pathname === cookie.path || url.pathname.startsWith(`${cookie.path.replace(/\/$/, "")}/`);
87
+ }
88
+ function createCookieJar(initial = []) {
89
+ let cookies = [...initial];
90
+ const same = (a, b) => a.name === b.name && a.domain === b.domain && a.path === b.path;
91
+ return {
92
+ store(url, setCookie) {
93
+ for (const line of setCookie) {
94
+ const parsed = parse(url, line);
95
+ if (!parsed) continue;
96
+ cookies = cookies.filter((existing) => !same(existing, parsed.cookie));
97
+ if (!parsed.expired) cookies.push(parsed.cookie);
98
+ }
99
+ },
100
+ header(url) {
101
+ const sent = cookies.filter((cookie) => matches(cookie, url));
102
+ return sent.length === 0 ? void 0 : sent.map((cookie) => `${cookie.name}=${cookie.value}`).join("; ");
103
+ },
104
+ snapshot: () => cookies.map((cookie) => ({ ...cookie }))
105
+ };
106
+ }
107
+
108
+ //#endregion
109
+ //#region src/core/apple/hashcash.ts
110
+ function leadingZeroBits(sum, bits) {
111
+ const whole = Math.floor(bits / 8);
112
+ for (let index = 0; index < whole; index++) if (sum[index] !== 0) return false;
113
+ const remaining = bits % 8;
114
+ return remaining === 0 || (sum[whole] & 255 << 8 - remaining) === 0;
115
+ }
116
+ const two = (value) => String(value).padStart(2, "0");
117
+ function mintHashcash(bits, challenge, now) {
118
+ const date = String(now.getUTCFullYear()) + two(now.getUTCMonth() + 1) + two(now.getUTCDate()) + two(now.getUTCHours()) + two(now.getUTCMinutes()) + two(now.getUTCSeconds());
119
+ for (let counter = 0;; counter++) {
120
+ const candidate = `1:${bits}:${date}:${challenge}::${counter}`;
121
+ if (leadingZeroBits(createHash("sha1").update(candidate).digest(), bits)) return candidate;
122
+ }
123
+ }
124
+
125
+ //#endregion
126
+ //#region src/core/apple/srp.ts
127
+ const MODULUS_HEX = "ac6bdb41324a9a9bf166de5e1389582faf72b6651987ee07fc3192943db56050a37329cbb4a099ed8193e0757767a13dd52312ab4b03310dcd7f48a9da04fd50e8083969edb767b0cf6095179a163ab3661a05fbd5faaae82918a9962f0b93b855f97993ec975eeaa80d740adbf4ff747359d041d5c33ea71d281e446b14773bca97b43a23fb801676bd207a436c6481f1d2b9078717461a5b9d32e688f87748544523b524b0d57d5ea77a2775d2ecfa032cfbdbf52fb3786160279004e57ae6af874e7303ce53299ccc041c7bc308d82a5698f3a8d0c38271ae35f8e9dbfbb694b5c803d89f7ae435de236d525f54759b65e372fcd68ef20fa7111f9e4aff73";
128
+ const MODULUS = BigInt(`0x${MODULUS_HEX}`);
129
+ const GENERATOR = 2n;
130
+ const WIDTH = 512;
131
+ const SECRET_BYTES = 256;
132
+ const DERIVED_BYTES = 32;
133
+ const digest = (bytes) => createHash("sha256").update(bytes).digest();
134
+ const hashHex = (hex) => digest(Buffer.from(hex, "hex")).toString("hex");
135
+ const evenHex = (value) => {
136
+ const hex = value.toString(16);
137
+ return hex.length % 2 === 1 ? `0${hex}` : hex;
138
+ };
139
+ const paddedHash = (...values) => BigInt(`0x${hashHex(values.map((value) => value.padStart(WIDTH, "0")).join(""))}`);
140
+ function modPow(base, exponent, modulus) {
141
+ let result = 1n;
142
+ let factor = base % modulus;
143
+ let remaining = exponent;
144
+ while (remaining > 0n) {
145
+ if (remaining & 1n) result = result * factor % modulus;
146
+ factor = factor * factor % modulus;
147
+ remaining >>= 1n;
148
+ }
149
+ return result;
150
+ }
151
+ function createEphemeral(random = randomBytes) {
152
+ const secret = BigInt(`0x${random(SECRET_BYTES).toString("hex")}`);
153
+ return {
154
+ secret,
155
+ publicKey: Buffer.from(evenHex(modPow(GENERATOR, secret, MODULUS)), "hex").toString("base64")
156
+ };
157
+ }
158
+ function derivePassword(input, salt) {
159
+ const hashed = digest(Buffer.from(input.password, "utf8"));
160
+ return pbkdf2Sync(input.protocol === "s2k_fo" ? Buffer.from(hashed.toString("hex"), "utf8") : hashed, salt, input.iterations, DERIVED_BYTES, "sha256");
161
+ }
162
+ function createProof(input) {
163
+ const salt = Buffer.from(input.salt, "base64");
164
+ const serverHex = Buffer.from(input.serverPublicKey, "base64").toString("hex");
165
+ if (serverHex.length > WIDTH) throw new Error("Apple sent an invalid sign-in challenge.");
166
+ const serverPublic = BigInt(`0x${serverHex || "0"}`);
167
+ if (serverPublic % MODULUS === 0n) throw new Error("Apple sent an invalid sign-in challenge.");
168
+ const clientHex = evenHex(modPow(GENERATOR, input.secret, MODULUS));
169
+ const saltHex = salt.toString("hex");
170
+ const derivedHex = derivePassword(input, salt).toString("hex");
171
+ const x = BigInt(`0x${hashHex(saltHex + hashHex(`3a${derivedHex}`))}`);
172
+ const k = paddedHash(MODULUS_HEX, evenHex(GENERATOR));
173
+ const u = paddedHash(clientHex, serverHex);
174
+ if (u === 0n) throw new Error("Apple sent an invalid sign-in challenge.");
175
+ const sessionKey = hashHex(evenHex(modPow(((serverPublic - k * modPow(GENERATOR, x, MODULUS) % MODULUS) % MODULUS + MODULUS) % MODULUS, input.secret + u * x, MODULUS)));
176
+ const modulusHash = digest(Buffer.from(MODULUS_HEX, "hex"));
177
+ const generatorHash = digest(Buffer.from(evenHex(GENERATOR).padStart(WIDTH, "0"), "hex"));
178
+ const mixed = Buffer.from(modulusHash.map((byte, index) => byte ^ generatorHash[index]));
179
+ const accountHash = digest(Buffer.from(input.accountName, "utf8")).toString("hex");
180
+ const m1 = hashHex(mixed.toString("hex") + accountHash + saltHex + clientHex + serverHex + sessionKey);
181
+ const m2 = hashHex(clientHex + m1 + sessionKey);
182
+ return {
183
+ m1: Buffer.from(m1, "hex").toString("base64"),
184
+ m2: Buffer.from(m2, "hex").toString("base64")
185
+ };
186
+ }
187
+
188
+ //#endregion
189
+ //#region src/core/apple/transport.ts
190
+ const MAX_REDIRECTS = 5;
191
+ var AppleUnreachableError = class extends Error {
192
+ constructor(cause) {
193
+ super("Couldn't reach Apple. Check your network or proxy, then try again.");
194
+ this.name = "AppleUnreachableError";
195
+ this.cause = cause;
196
+ }
197
+ };
198
+ function createTransport(jar, doFetch = fetch) {
199
+ return { async send(method, url, request = {}) {
200
+ let target = new URL(url);
201
+ let verb = method;
202
+ let body = request.body === void 0 ? void 0 : JSON.stringify(request.body);
203
+ for (let hop = 0;; hop++) {
204
+ const cookie = jar.header(target);
205
+ let response;
206
+ try {
207
+ response = await doFetch(target, {
208
+ method: verb,
209
+ redirect: "manual",
210
+ headers: {
211
+ accept: "application/json",
212
+ "user-agent": `superwall-cli/${VERSION}`,
213
+ ...body === void 0 ? {} : { "content-type": "application/json" },
214
+ ...request.headers,
215
+ ...cookie ? { cookie } : {}
216
+ },
217
+ ...body === void 0 ? {} : { body }
218
+ });
219
+ } catch (error) {
220
+ throw new AppleUnreachableError(error);
221
+ }
222
+ jar.store(target, response.headers.getSetCookie());
223
+ const location = response.headers.get("location");
224
+ if (!(response.status >= 300 && response.status < 400 && location) || hop >= MAX_REDIRECTS) return {
225
+ status: response.status,
226
+ headers: response.headers,
227
+ body: await response.text()
228
+ };
229
+ target = new URL(location, target);
230
+ if (response.status !== 307 && response.status !== 308) {
231
+ verb = "GET";
232
+ body = void 0;
233
+ }
234
+ }
235
+ } };
236
+ }
237
+ function parseJson(body) {
238
+ if (body.trim() === "") return void 0;
239
+ try {
240
+ return JSON.parse(body);
241
+ } catch {
242
+ return;
243
+ }
244
+ }
245
+ function field(value, key) {
246
+ return typeof value === "object" && value !== null ? Reflect.get(value, key) : void 0;
247
+ }
248
+ function textField(value, key) {
249
+ const found = field(value, key);
250
+ return typeof found === "string" && found.trim() !== "" ? found.trim() : void 0;
251
+ }
252
+ function listField(value, key) {
253
+ const found = field(value, key);
254
+ return Array.isArray(found) ? found : [];
255
+ }
256
+
257
+ //#endregion
258
+ //#region src/core/apple/session.ts
259
+ const AUTH_URL = "https://idmsa.apple.com/appleauth/auth";
260
+ const ASC_URL = "https://appstoreconnect.apple.com";
261
+ var AppleError = class extends Error {
262
+ constructor(kind, message, status) {
263
+ super(message);
264
+ this.kind = kind;
265
+ this.status = status;
266
+ this.name = "AppleError";
267
+ }
268
+ };
269
+ function serviceMessages(body) {
270
+ return [
271
+ ...listField(body, "serviceErrors"),
272
+ ...listField(body, "service_errors"),
273
+ ...listField(body, "validationErrors")
274
+ ].map((error) => {
275
+ const message = textField(error, "message") ?? textField(error, "title") ?? "request rejected";
276
+ const code = field(error, "code");
277
+ return typeof code === "string" || typeof code === "number" ? `${message} (${code})` : message;
278
+ });
279
+ }
280
+ function failureMessage(response) {
281
+ const body = parseJson(response.body);
282
+ const service = serviceMessages(body);
283
+ if (service.length > 0) return service.join("; ");
284
+ const first = listField(body, "errors")[0];
285
+ return textField(first, "detail") ?? textField(first, "title") ?? `HTTP ${response.status}`;
286
+ }
287
+ function phoneMatches(requested, masked) {
288
+ const clean = (value) => value.replace(/[\s \-()"]/g, "");
289
+ const number = clean(requested);
290
+ const label = clean(masked);
291
+ const bullets = [...label].filter((character) => character === "•").length;
292
+ if (bullets === 0) return number === label;
293
+ const prefix = label.slice(0, label.indexOf("•"));
294
+ const suffix = label.slice(label.lastIndexOf("•") + 1);
295
+ const hidden = number.slice(prefix.length, number.length - suffix.length);
296
+ return number.startsWith(prefix) && number.endsWith(suffix) && /^\d+$/.test(hidden) && hidden.length >= Math.max(1, bullets - 2) && hidden.length <= bullets;
297
+ }
298
+ function readTeam(value) {
299
+ const id = field(value, "providerId");
300
+ if (typeof id !== "number") return void 0;
301
+ return {
302
+ id,
303
+ issuerId: textField(value, "publicProviderId"),
304
+ name: textField(value, "name") ?? String(id)
305
+ };
306
+ }
307
+ function createAppleSession(options = {}) {
308
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
309
+ const doFetch = options.fetch ?? fetch;
310
+ const jar = createCookieJar(options.pending?.cookies);
311
+ const transport = createTransport(jar, doFetch);
312
+ let appleId = options.pending?.appleId ?? "";
313
+ let serviceKey = options.pending?.serviceKey ?? "";
314
+ let sessionId = options.pending?.sessionId ?? "";
315
+ let scnt = options.pending?.scnt ?? "";
316
+ let factor = options.pending?.factor;
317
+ let current;
318
+ let available = [];
319
+ const authHeaders = () => ({
320
+ accept: "application/json, text/javascript",
321
+ "x-requested-with": "XMLHttpRequest",
322
+ "x-apple-widget-key": serviceKey,
323
+ ...sessionId ? { "x-apple-id-session-id": sessionId } : {},
324
+ ...scnt ? { scnt } : {}
325
+ });
326
+ const auth = async (method, path, body) => {
327
+ const response = await transport.send(method, `${AUTH_URL}${path}`, {
328
+ headers: authHeaders(),
329
+ body
330
+ });
331
+ const parsed = parseJson(response.body);
332
+ if (response.status < 200 || response.status >= 300 || serviceMessages(parsed).length > 0) throw new AppleError("verification", failureMessage(response), response.status);
333
+ return parsed;
334
+ };
335
+ const loadServiceKey = async () => {
336
+ let location;
337
+ try {
338
+ location = (await doFetch(`${ASC_URL}/logout`, {
339
+ method: "HEAD",
340
+ redirect: "manual"
341
+ })).headers.get("location");
342
+ } catch (error) {
343
+ throw new AppleUnreachableError(error);
344
+ }
345
+ const key = location ? new URL(location, ASC_URL).searchParams.get("widgetKey")?.trim() : "";
346
+ if (!key) throw new AppleError("request", "Apple didn't return its sign-in configuration.");
347
+ return key;
348
+ };
349
+ const loadHashcash = async () => {
350
+ const response = await transport.send("GET", `${AUTH_URL}/signin?widgetKey=${encodeURIComponent(serviceKey)}`);
351
+ const bits = Number(response.headers.get("x-apple-hc-bits"));
352
+ const challenge = response.headers.get("x-apple-hc-challenge");
353
+ if (!challenge || !Number.isInteger(bits) || bits <= 0) return void 0;
354
+ return mintHashcash(bits, challenge, now());
355
+ };
356
+ const loadTeams = async () => {
357
+ const response = await transport.send("GET", `${ASC_URL}/olympus/v1/session`);
358
+ if (response.status < 200 || response.status >= 300) throw new AppleError(response.status === 401 || response.status === 403 ? "forbidden" : "request", `App Store Connect didn't accept the sign-in: ${failureMessage(response)}`, response.status);
359
+ const body = parseJson(response.body);
360
+ current = readTeam(field(body, "provider"));
361
+ const listed = listField(body, "availableProviders").map(readTeam).filter((team) => team !== void 0);
362
+ available = current && !listed.some((team) => team.id === current?.id) ? [current, ...listed] : listed;
363
+ appleId = textField(field(body, "user"), "emailAddress") ?? appleId;
364
+ if (!current) throw new AppleError("forbidden", "This Apple Account has no App Store Connect team. Join the Apple Developer Program or accept your team invite, then try again.");
365
+ };
366
+ const trustedPhones = (optionsBody) => listField(optionsBody, "trustedPhoneNumbers").flatMap((phone) => {
367
+ const id = field(phone, "id");
368
+ if (typeof id !== "number") return [];
369
+ return [{
370
+ id,
371
+ mode: textField(phone, "pushMode") ?? "sms",
372
+ label: textField(phone, "numberWithDialCode") ?? ""
373
+ }];
374
+ });
375
+ const requireContinuation = () => {
376
+ if (!serviceKey || !sessionId || !scnt) throw new AppleError("verification", "The Apple sign-in expired. Start again.");
377
+ };
378
+ return {
379
+ async signIn(email, password) {
380
+ appleId = email.trim();
381
+ sessionId = "";
382
+ scnt = "";
383
+ factor = void 0;
384
+ serviceKey = await loadServiceKey();
385
+ const ephemeral = createEphemeral(options.random);
386
+ const init = await transport.send("POST", `${AUTH_URL}/signin/init`, {
387
+ headers: authHeaders(),
388
+ body: {
389
+ a: ephemeral.publicKey,
390
+ accountName: appleId,
391
+ protocols: ["s2k", "s2k_fo"]
392
+ }
393
+ });
394
+ if (init.status === 401 || init.status === 403) throw new AppleError("credentials", "Incorrect Apple Account email or password.", init.status);
395
+ const challenge = parseJson(init.body);
396
+ const salt = textField(challenge, "salt");
397
+ const serverPublicKey = textField(challenge, "b");
398
+ const iterations = field(challenge, "iteration");
399
+ const protocol = textField(challenge, "protocol");
400
+ if (init.status !== 200 || !salt || !serverPublicKey || typeof iterations !== "number" || protocol !== "s2k" && protocol !== "s2k_fo") throw new AppleError("request", `Apple sign-in failed: ${failureMessage(init)}`, init.status);
401
+ const proof = createProof({
402
+ accountName: appleId,
403
+ password,
404
+ protocol,
405
+ salt,
406
+ iterations,
407
+ serverPublicKey,
408
+ secret: ephemeral.secret
409
+ });
410
+ const hashcash = await loadHashcash();
411
+ const complete = await transport.send("POST", `${AUTH_URL}/signin/complete?isRememberMeEnabled=false`, {
412
+ headers: {
413
+ ...authHeaders(),
414
+ ...hashcash ? { "x-apple-hc": hashcash } : {}
415
+ },
416
+ body: {
417
+ accountName: appleId,
418
+ c: field(challenge, "c"),
419
+ m1: proof.m1,
420
+ m2: proof.m2,
421
+ rememberMe: false
422
+ }
423
+ });
424
+ if (complete.status === 409) {
425
+ sessionId = complete.headers.get("x-apple-id-session-id") ?? "";
426
+ scnt = complete.headers.get("scnt") ?? "";
427
+ requireContinuation();
428
+ return "verification-required";
429
+ }
430
+ if (complete.status === 401 || complete.status === 403) throw new AppleError("credentials", "Incorrect Apple Account email or password.", complete.status);
431
+ if (complete.status === 412) throw new AppleError("account-action", "Apple needs you to review something on this account first. Sign in at https://account.apple.com, finish the prompt, then try again.", complete.status);
432
+ if (complete.status !== 200 || serviceMessages(parseJson(complete.body)).length > 0) throw new AppleError("request", `Apple sign-in failed: ${failureMessage(complete)}`, complete.status);
433
+ await loadTeams();
434
+ return "signed-in";
435
+ },
436
+ async requestCode(request = {}) {
437
+ requireContinuation();
438
+ const body = await auth("GET", "");
439
+ const length = field(field(body, "securityCode"), "length");
440
+ const codeLength = typeof length === "number" && length > 0 ? length : 6;
441
+ const noTrustedDevices = field(body, "noTrustedDevices") === true;
442
+ const phones = trustedPhones(body);
443
+ if (!request.sms && !request.phone && !noTrustedDevices) {
444
+ factor = {
445
+ method: "device",
446
+ codeLength
447
+ };
448
+ return {
449
+ method: "device",
450
+ codeLength
451
+ };
452
+ }
453
+ if (phones.length === 0) throw new AppleError("verification", "This Apple Account has no trusted phone number.");
454
+ const phone = request.phone ? phones.find((candidate) => phoneMatches(request.phone ?? "", candidate.label)) : phones[0];
455
+ if (!phone) throw new AppleError("verification", `No trusted phone number matches ${request.phone}. Apple lists: ${phones.map((candidate) => candidate.label).join(", ")}.`);
456
+ if (!(noTrustedDevices && phones.length === 1)) await auth("PUT", "/verify/phone", {
457
+ phoneNumber: { id: phone.id },
458
+ mode: phone.mode
459
+ });
460
+ factor = {
461
+ method: "phone",
462
+ phoneId: phone.id,
463
+ phoneMode: phone.mode,
464
+ destination: phone.label,
465
+ codeLength
466
+ };
467
+ return {
468
+ method: phone.mode === "voice" ? "voice" : "sms",
469
+ destination: phone.label || void 0,
470
+ codeLength
471
+ };
472
+ },
473
+ async submitCode(code) {
474
+ requireContinuation();
475
+ const securityCode = { code: code.trim() };
476
+ if (factor?.method === "phone") await auth("POST", "/verify/phone/securitycode", {
477
+ securityCode,
478
+ phoneNumber: { id: factor.phoneId },
479
+ mode: factor.phoneMode
480
+ });
481
+ else await auth("POST", "/verify/trusteddevice/securitycode", { securityCode });
482
+ await auth("GET", "/2sv/trust");
483
+ await loadTeams();
484
+ },
485
+ pending() {
486
+ requireContinuation();
487
+ return {
488
+ appleId,
489
+ serviceKey,
490
+ sessionId,
491
+ scnt,
492
+ cookies: jar.snapshot(),
493
+ factor
494
+ };
495
+ },
496
+ team() {
497
+ if (!current) throw new AppleError("request", "Sign in to Apple first.");
498
+ return current;
499
+ },
500
+ teams: () => available,
501
+ async selectTeam(id) {
502
+ if (current?.id === id) return;
503
+ if (!available.some((team) => team.id === id)) throw new AppleError("request", `This Apple Account isn't on team ${id}. Its teams: ${available.map((team) => `${team.id} (${team.name})`).join(", ")}.`);
504
+ const response = await transport.send("POST", `${ASC_URL}/olympus/v1/session`, {
505
+ headers: { "x-requested-with": "olympus-ui" },
506
+ body: { provider: { providerId: id } }
507
+ });
508
+ if (response.status < 200 || response.status >= 300) throw new AppleError("request", `Couldn't switch Apple team: ${failureMessage(response)}`, response.status);
509
+ await loadTeams();
510
+ if (current?.id !== id) throw new AppleError("request", `Apple didn't switch to team ${id}.`);
511
+ },
512
+ async iris(method, path, request = {}) {
513
+ const query = new URLSearchParams(request.query).toString();
514
+ const response = await transport.send(method, `${ASC_URL}/iris/v1${path}${query ? `?${query}` : ""}`, {
515
+ headers: {
516
+ accept: "application/vnd.api+json, application/json",
517
+ origin: ASC_URL,
518
+ referer: `${ASC_URL}/access/integrations/api`,
519
+ "x-csrf-itc": "[asc-ui]"
520
+ },
521
+ body: request.body
522
+ });
523
+ if (response.status < 200 || response.status >= 300) throw new AppleError(response.status === 401 || response.status === 403 ? "forbidden" : "request", failureMessage(response), response.status);
524
+ return parseJson(response.body);
525
+ }
526
+ };
527
+ }
528
+
529
+ //#endregion
530
+ //#region src/commands/platform/apple-deps.ts
531
+ const appleDeps = {
532
+ session: createAppleSession,
533
+ credentials: appleCredentialsFromEnv,
534
+ pending: {
535
+ load: () => loadPending(),
536
+ save: (pending) => savePending(pending),
537
+ clear: clearPending
538
+ },
539
+ sleep: (ms) => new Promise((done) => setTimeout(done, ms)),
540
+ writeKeyFile: (name, privateKey) => {
541
+ const path = join(process.cwd(), name);
542
+ writeFileSync(path, privateKey, { mode: 384 });
543
+ return path;
544
+ }
545
+ };
546
+
547
+ //#endregion
548
+ //#region src/core/apple/apps.ts
549
+ function readApps(body) {
550
+ return listField(body, "data").flatMap((app) => {
551
+ const id = textField(app, "id");
552
+ if (!id) return [];
553
+ const attributes = field(app, "attributes");
554
+ return [{
555
+ id,
556
+ name: textField(attributes, "name"),
557
+ bundleId: textField(attributes, "bundleId")
558
+ }];
559
+ });
560
+ }
561
+ async function listApps(session) {
562
+ return readApps(await session.iris("GET", "/apps", { query: { limit: "200" } }));
563
+ }
564
+ async function findApp(session, bundleId) {
565
+ return readApps(await session.iris("GET", "/apps", { query: {
566
+ "filter[bundleId]": bundleId,
567
+ limit: "10"
568
+ } })).find((app) => app.bundleId === bundleId);
569
+ }
570
+
571
+ //#endregion
572
+ //#region src/commands/platform/apple-app.ts
573
+ const NEW_APP = "__new__";
574
+ const LISTED_APPS = 8;
575
+ const isIos = (app) => (app.platform ?? "").toLowerCase() === "ios";
576
+ async function iosApps(ctx, api, flags) {
577
+ const projects = await apiCall(ctx, "Loading your apps", () => listProjects(api));
578
+ const scoped = flags.project ? projects.filter((project) => String(project.id) === flags.project) : projects;
579
+ if (flags.project && scoped.length === 0) throw new Error(`No project ${flags.project} in this organization.`);
580
+ const candidates = scoped.flatMap((project) => (project.applications ?? []).filter(isIos).map((app) => ({
581
+ project,
582
+ app
583
+ })));
584
+ if (!flags.app) return {
585
+ scoped,
586
+ candidates
587
+ };
588
+ const named = candidates.find(({ app }) => String(app.id) === flags.app || app.name === flags.app);
589
+ if (!named) throw new Error(`No iOS app ${flags.app} in this organization.`);
590
+ return {
591
+ scoped,
592
+ candidates,
593
+ named
594
+ };
595
+ }
596
+ function severalApps(candidates) {
597
+ const shown = candidates.slice(0, LISTED_APPS).map(({ app }) => `${app.id} (${app.name ?? "unnamed"})`).join(", ");
598
+ const more = candidates.length > LISTED_APPS ? `, and ${candidates.length - LISTED_APPS} more (\`superwall apps\` lists them all)` : "";
599
+ return /* @__PURE__ */ new Error(`Several iOS apps found: ${shown}${more}. Pass --app <id>.`);
600
+ }
601
+ const appOptions = (candidates) => candidates.map(({ app, project }) => ({
602
+ value: String(app.id),
603
+ label: app.name ?? String(app.id),
604
+ hint: app.bundle_id ?? project.name
605
+ }));
606
+ async function chooseIosApp(ctx, api, flags) {
607
+ const { candidates, named } = await iosApps(ctx, api, flags);
608
+ if (named) return named;
609
+ if (candidates.length === 0) throw new Error("There's no iOS app in Superwall yet. Create one with `superwall apps create`, or run `superwall setup apple`.");
610
+ if (candidates.length === 1) return candidates[0];
611
+ if (!ctx.interactive) throw severalApps(candidates);
612
+ const picked = await ctx.ui.select({
613
+ message: "Which Superwall app?",
614
+ options: appOptions(candidates)
615
+ });
616
+ if (picked === null) throw new Error("Cancelled.");
617
+ return candidates.find(({ app }) => String(app.id) === picked);
618
+ }
619
+ async function chooseAppIntent(ctx, api, flags) {
620
+ const { scoped, candidates, named } = await iosApps(ctx, api, flags);
621
+ if (named) return {
622
+ kind: "existing",
623
+ ...named
624
+ };
625
+ const createIn = scoped.length === 1 ? scoped[0] : void 0;
626
+ if (candidates.length === 0) {
627
+ if (!ctx.interactive && !flags.bundleId) throw new Error("There's no iOS app in Superwall yet. Pass --bundle-id <id> to create one for that App Store Connect app.");
628
+ return {
629
+ kind: "create",
630
+ project: createIn
631
+ };
632
+ }
633
+ if (flags.bundleId) {
634
+ const found = candidates.find(({ app }) => app.bundle_id === flags.bundleId);
635
+ return found ? {
636
+ kind: "existing",
637
+ ...found
638
+ } : {
639
+ kind: "create",
640
+ project: createIn
641
+ };
642
+ }
643
+ if (!ctx.interactive) {
644
+ if (candidates.length === 1) return {
645
+ kind: "existing",
646
+ ...candidates[0]
647
+ };
648
+ throw severalApps(candidates);
649
+ }
650
+ const picked = await ctx.ui.select({
651
+ message: "Which Superwall app is this for?",
652
+ options: [...appOptions(candidates), {
653
+ value: NEW_APP,
654
+ label: "Create a new iOS app"
655
+ }]
656
+ });
657
+ if (picked === null) throw new Error("Cancelled.");
658
+ if (picked === NEW_APP) return {
659
+ kind: "create",
660
+ project: createIn
661
+ };
662
+ return {
663
+ kind: "existing",
664
+ ...candidates.find(({ app }) => String(app.id) === picked)
665
+ };
666
+ }
667
+ async function chooseAppleApp(ctx, session, bundleId) {
668
+ const hasBundle = (app) => app.bundleId !== void 0;
669
+ const team = session.team().name;
670
+ if (bundleId) {
671
+ const found = await apiCall(ctx, "Finding the App Store Connect app", () => findApp(session, bundleId));
672
+ if (found && hasBundle(found)) return found;
673
+ const others = (await listApps(session)).filter(hasBundle).map((app) => app.bundleId);
674
+ const shown = others.slice(0, LISTED_APPS).join(", ");
675
+ const more = others.length > LISTED_APPS ? `, and ${others.length - LISTED_APPS} more` : "";
676
+ throw new Error(`No App Store Connect app with bundle ID ${bundleId} on the Apple team "${team}". Nothing was created.` + (others.length > 0 ? `\nThis team's apps: ${shown}${more}.` : "\nThis team has no apps yet.") + "\nCheck the bundle ID, sign in with an Apple Account on the right team, or create the app in App Store Connect.");
677
+ }
678
+ const apps = (await apiCall(ctx, "Loading App Store Connect apps", () => listApps(session))).filter(hasBundle);
679
+ if (apps.length === 0) throw new Error(`The Apple team "${team}" has no apps in App Store Connect yet. Create the app there, then run this again.`);
680
+ if (!ctx.interactive) throw new Error(`Pass --bundle-id <id>. This team's apps: ${apps.map((app) => app.bundleId).join(", ")}.`);
681
+ const picked = await ctx.ui.select({
682
+ message: "Which App Store Connect app?",
683
+ options: apps.map((app) => ({
684
+ value: app.id,
685
+ label: app.name ?? app.bundleId,
686
+ hint: app.bundleId
687
+ }))
688
+ });
689
+ if (picked === null) throw new Error("Cancelled.");
690
+ return apps.find((app) => app.id === picked);
691
+ }
692
+ async function projectForNewApp(ctx, api, intent, name) {
693
+ if (intent.project) return String(intent.project.id);
694
+ const projects = await listProjects(api);
695
+ if (projects.length === 0) {
696
+ const created = await apiCall(ctx, "Creating a project", () => createProject(api, name));
697
+ return String(created.id);
698
+ }
699
+ if (!ctx.interactive) throw new Error(`Several projects found: ${projects.map((project) => `${project.id} (${project.name ?? "unnamed"})`).join(", ")}. Pass --project <id>.`);
700
+ const picked = await ctx.ui.select({
701
+ message: "Which project should the new app go in?",
702
+ options: projects.map((project) => ({
703
+ value: String(project.id),
704
+ label: project.name ?? String(project.id)
705
+ }))
706
+ });
707
+ if (picked === null) throw new Error("Cancelled.");
708
+ return picked;
709
+ }
710
+ async function resolveApp(ctx, api, session, intent, flags) {
711
+ if (intent.kind === "existing") {
712
+ const { app, project } = intent;
713
+ const name$1 = app.name ?? String(app.id);
714
+ const saved = savedBundleId(app);
715
+ if (flags.bundleId && saved && flags.bundleId !== saved) throw new Error(differentBundleId(name$1, String(app.id), saved, flags.bundleId));
716
+ const chosen$1 = await chooseAppleApp(ctx, session, flags.bundleId ?? saved ?? void 0);
717
+ return {
718
+ projectId: String(project.id),
719
+ applicationId: String(app.id),
720
+ name: name$1,
721
+ bundleId: chosen$1.bundleId,
722
+ savedBundleId: saved,
723
+ ascAppId: chosen$1.id,
724
+ created: false
725
+ };
726
+ }
727
+ const chosen = await chooseAppleApp(ctx, session, flags.bundleId);
728
+ const name = chosen.name ?? chosen.bundleId;
729
+ const projectId = await projectForNewApp(ctx, api, intent, name);
730
+ const created = ((await apiCall(ctx, `Creating ${name} in Superwall`, () => createApplication(api, { projectId }, {
731
+ name,
732
+ platform: "ios",
733
+ bundleId: chosen.bundleId
734
+ }))).applications ?? []).filter(isIos).find((app) => app.bundle_id === chosen.bundleId);
735
+ if (!created) throw new Error(`Superwall created ${name} but didn't return it. Nothing was created at Apple. Run this again with --app <id> (\`superwall apps\` lists ids).`);
736
+ return {
737
+ projectId,
738
+ applicationId: String(created.id),
739
+ name,
740
+ bundleId: chosen.bundleId,
741
+ savedBundleId: chosen.bundleId,
742
+ ascAppId: chosen.id,
743
+ created: true
744
+ };
745
+ }
746
+ function savedBundleId(app) {
747
+ const value = app.bundle_id?.trim();
748
+ return value ? value : null;
749
+ }
750
+ function differentBundleId(name, applicationId, saved, wanted) {
751
+ return `\`${name}\` has the bundle ID ${saved} in Superwall, not ${wanted}. Nothing was created or saved. To change it, run \`superwall apps bundle-id ${wanted} --app ${applicationId} --replace\` first, once a person has agreed.`;
752
+ }
753
+
754
+ //#endregion
755
+ //#region src/core/apple/keys.ts
756
+ const RESOURCE = {
757
+ team: "apiKeys",
758
+ purchase: "subscriptionKeys"
759
+ };
760
+ function decodePrivateKey(value) {
761
+ const trimmed = value.trim();
762
+ if (trimmed.includes("PRIVATE KEY")) return `${trimmed}\n`;
763
+ const decoded = Buffer.from(trimmed, "base64").toString("utf8").trim();
764
+ let pem = decoded;
765
+ try {
766
+ const unquoted = JSON.parse(decoded);
767
+ if (typeof unquoted === "string") pem = unquoted.trim();
768
+ } catch {
769
+ pem = decoded;
770
+ }
771
+ if (!pem.includes("PRIVATE KEY")) throw new AppleError("request", "Apple returned something that isn't a private key.");
772
+ return `${pem}\n`;
773
+ }
774
+ async function createKey(session, kind, attributes) {
775
+ const resource = RESOURCE[kind];
776
+ const issuerId = session.team().issuerId;
777
+ if (!issuerId) throw new AppleError("request", "App Store Connect didn't say which issuer this team uses.");
778
+ const id = textField(field(await session.iris("POST", `/${resource}`, { body: { data: {
779
+ type: resource,
780
+ attributes
781
+ } } }), "data"), "id");
782
+ if (!id) throw new AppleError("request", "Apple created a key but didn't return its ID.");
783
+ const privateKey = textField(field(field(await session.iris("GET", `/${resource}/${encodeURIComponent(id)}`, { query: { [`fields[${resource}]`]: "privateKey" } }), "data"), "attributes"), "privateKey");
784
+ if (!privateKey) throw new AppleError("request", `Apple created key ${id} but didn't release its private key. Revoke it in App Store Connect → Users and Access → Integrations, then try again.`);
785
+ return {
786
+ id,
787
+ issuerId,
788
+ privateKey: decodePrivateKey(privateKey)
789
+ };
790
+ }
791
+ function createTeamKey(session, options) {
792
+ return createKey(session, "team", {
793
+ nickname: options.name,
794
+ roles: [options.role],
795
+ allAppsVisible: true,
796
+ keyType: "PUBLIC_API"
797
+ });
798
+ }
799
+ function createPurchaseKey(session, options) {
800
+ return createKey(session, "purchase", { nickname: options.name });
801
+ }
802
+ async function checkKeyAccess(session, kind) {
803
+ await session.iris("GET", `/${RESOURCE[kind]}`, { query: { limit: "1" } });
804
+ }
805
+
806
+ //#endregion
807
+ //#region src/commands/platform/apple-sign-in.ts
808
+ const MAX_CODE_ATTEMPTS = 3;
809
+ function describeChallenge(challenge) {
810
+ if (challenge.method === "device") return "Apple sent a code to your trusted devices.";
811
+ return `Apple ${challenge.method === "voice" ? "is calling" : "texted a code to"} ${challenge.destination ?? "your trusted phone number"}.`;
812
+ }
813
+ async function startSession(ctx, deps, flags) {
814
+ const stored = deps.pending.load();
815
+ if (stored !== void 0 && (flags.code !== void 0 || flags.sms || flags.phone !== void 0) && (!flags.appleId || flags.appleId.toLowerCase() === stored.appleId.toLowerCase())) return {
816
+ session: deps.session({ pending: stored }),
817
+ needsCode: true,
818
+ continued: true
819
+ };
820
+ deps.pending.clear();
821
+ const env = deps.credentials();
822
+ let appleId = flags.appleId ?? env.appleId;
823
+ let password = flags.password ?? env.password;
824
+ if (ctx.interactive && (!appleId || !password)) {
825
+ ctx.ui.note("Your Apple password goes from this computer straight to Apple.\nSuperwall never receives it and it is not saved.", "Sign in to Apple");
826
+ if (!appleId) {
827
+ const typed = await ctx.ui.text({
828
+ message: "Apple Account email",
829
+ placeholder: "you@example.com",
830
+ validate: (value) => value.trim() ? void 0 : "Required"
831
+ });
832
+ if (typed === null) throw new Error("Cancelled.");
833
+ appleId = typed.trim();
834
+ }
835
+ if (!password) {
836
+ const typed = await ctx.ui.text({
837
+ message: "Apple Account password",
838
+ secret: true,
839
+ validate: (value) => value ? void 0 : "Required"
840
+ });
841
+ if (typed === null) throw new Error("Cancelled.");
842
+ password = typed;
843
+ }
844
+ }
845
+ if (!appleId || !password) throw new Error([
846
+ `Can't prompt for Apple sign-in here. Run this in a terminal, or supply the email and password with --apple-id/--apple-password (or ${ENV_APPLE_ID}/${ENV_APPLE_PASSWORD}).`,
847
+ "If you are an agent, never ask for the password in chat. Instead:",
848
+ ` 1. Create a private file (chmod 600) holding two lines: \`${ENV_APPLE_ID}=\` and \`${ENV_APPLE_PASSWORD}=\`.`,
849
+ " 2. Open it in the user's text editor and ask them to fill in both values and save.",
850
+ " 3. Read each value into that environment variable without printing it, then run this again.",
851
+ " 4. Delete the file when you are done."
852
+ ].join("\n"));
853
+ const email = appleId;
854
+ const secret = password;
855
+ const session = deps.session();
856
+ return {
857
+ session,
858
+ needsCode: await apiCall(ctx, "Signing in to Apple", () => session.signIn(email, secret)) === "verification-required",
859
+ continued: false
860
+ };
861
+ }
862
+ async function signInToApple(ctx, deps, flags) {
863
+ const { session, needsCode, continued } = await startSession(ctx, deps, flags);
864
+ if (!needsCode) return {
865
+ status: "signed-in",
866
+ session
867
+ };
868
+ let code = flags.code;
869
+ let challenge = {
870
+ method: "device",
871
+ codeLength: 6
872
+ };
873
+ if (!continued || !code) challenge = await apiCall(ctx, "Requesting a verification code", () => session.requestCode({
874
+ sms: flags.sms,
875
+ phone: flags.phone
876
+ }));
877
+ for (let attempt = 1;; attempt++) {
878
+ if (!code) {
879
+ if (!ctx.interactive) {
880
+ deps.pending.save(session.pending());
881
+ return {
882
+ status: "verification-required",
883
+ challenge
884
+ };
885
+ }
886
+ ctx.ui.info(describeChallenge(challenge));
887
+ const typed = await ctx.ui.text({
888
+ message: "Verification code",
889
+ placeholder: "0".repeat(challenge.codeLength),
890
+ footer: challenge.method === "device" ? "No code? Type sms to get a text message instead." : void 0,
891
+ validate: (value) => value.trim() ? void 0 : "Required"
892
+ });
893
+ if (typed === null) throw new Error("Cancelled.");
894
+ if (typed.trim().toLowerCase() === "sms") {
895
+ challenge = await apiCall(ctx, "Requesting a text message", () => session.requestCode({
896
+ sms: true,
897
+ phone: flags.phone
898
+ }));
899
+ continue;
900
+ }
901
+ code = typed.trim();
902
+ }
903
+ const submitted = code;
904
+ try {
905
+ await apiCall(ctx, "Verifying", () => session.submitCode(submitted));
906
+ break;
907
+ } catch (error) {
908
+ if (!(error instanceof AppleError) || error.kind !== "verification") throw error;
909
+ const message = `Apple didn't accept that code: ${error.message}`;
910
+ if (!ctx.interactive) {
911
+ deps.pending.save(session.pending());
912
+ throw new Error(`${message}\nRun it again with --code <code>, or --sms to get a text.`);
913
+ }
914
+ if (attempt >= MAX_CODE_ATTEMPTS) throw new Error(message);
915
+ ctx.ui.warn(message);
916
+ code = void 0;
917
+ }
918
+ }
919
+ deps.pending.clear();
920
+ return {
921
+ status: "signed-in",
922
+ session
923
+ };
924
+ }
925
+
926
+ //#endregion
927
+ //#region src/commands/platform/apple-keys.ts
928
+ const KEY_KINDS = ["api_key", "purchase_key"];
929
+ const KEY_LABEL = {
930
+ api_key: "App Store Connect API key",
931
+ purchase_key: "In-App Purchase key"
932
+ };
933
+ const KEY_NAME = "Superwall";
934
+ const KEY_FILE = {
935
+ api_key: "AuthKey",
936
+ purchase_key: "SubscriptionKey"
937
+ };
938
+ const APPLE_KIND = {
939
+ api_key: "team",
940
+ purchase_key: "purchase"
941
+ };
942
+ const ACTIVATION_DELAYS = [
943
+ 1e3,
944
+ 2e3,
945
+ 3e3
946
+ ];
947
+ const ACTIVATION_STATUSES = new Set([
948
+ 400,
949
+ 401,
950
+ 403,
951
+ 422,
952
+ 502
953
+ ]);
954
+ function text(ctx, name) {
955
+ const value = ctx.argv[name];
956
+ if (typeof value === "number") return String(value);
957
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
958
+ }
959
+ function keyKind(value) {
960
+ return KEY_KINDS.find((kind) => kind === value);
961
+ }
962
+ function keyRole(ctx) {
963
+ const value = (text(ctx, "key-role") ?? "app_manager").toUpperCase().replace(/-/g, "_");
964
+ if (value === "APP_MANAGER" || value === "ADMIN") return value;
965
+ throw new Error("--key-role must be app_manager or admin.");
966
+ }
967
+ const appFlags = (ctx) => ({
968
+ app: text(ctx, "app"),
969
+ project: text(ctx, "project"),
970
+ bundleId: text(ctx, "bundle-id")
971
+ });
972
+ const signInFlags = (ctx) => ({
973
+ appleId: text(ctx, "apple-id"),
974
+ password: typeof ctx.argv["apple-password"] === "string" && ctx.argv["apple-password"] !== "" ? ctx.argv["apple-password"] : void 0,
975
+ code: text(ctx, "code"),
976
+ sms: ctx.argv.sms === true,
977
+ phone: text(ctx, "phone")
978
+ });
979
+ const savedKey = (saved, kind) => (kind === "api_key" ? saved.app_store_connect_configuration : saved.in_app_purchase_configuration) ?? void 0;
980
+ function keyRefusal(error, kind) {
981
+ const message = error.message.toLowerCase();
982
+ if (message.includes("maximum") || message.includes("revoke")) return "This team is at Apple's limit of active keys. Revoke an unused one in App Store Connect → Users and Access → Integrations, then run this again.";
983
+ if (error.kind === "forbidden" || message.includes("does not allow")) return kind === "purchase_key" ? "Apple refused. Either this Apple Account isn't an Admin or the Account Holder, or the team has an agreement waiting to be signed at https://appstoreconnect.apple.com/agreements." : "Apple refused. Only an Admin or the Account Holder can create team keys, and the team's agreements must be signed at https://appstoreconnect.apple.com/agreements.";
984
+ return `Apple refused: ${error.message}`;
985
+ }
986
+ async function untilActive(ctx, deps, label, work, rejected) {
987
+ return apiCall(ctx, label, async () => {
988
+ for (let attempt = 0;; attempt++) {
989
+ const delay = ACTIVATION_DELAYS[attempt];
990
+ try {
991
+ const result = await work();
992
+ if (!rejected(result) || delay === void 0) return result;
993
+ } catch (error) {
994
+ if (!(error instanceof ApiError && ACTIVATION_STATUSES.has(error.status)) || delay === void 0) throw error;
995
+ }
996
+ await deps.sleep(delay);
997
+ }
998
+ });
999
+ }
1000
+ async function chooseTeam(ctx, session, requested) {
1001
+ const teams = session.teams();
1002
+ if (requested) {
1003
+ const found = teams.find((team) => String(team.id) === requested || team.name.toLowerCase() === requested.toLowerCase());
1004
+ if (!found) throw new Error(`This Apple Account isn't on team ${requested}. Its teams: ${teams.map((team) => `${team.id} (${team.name})`).join(", ")}.`);
1005
+ await session.selectTeam(found.id);
1006
+ return session.team();
1007
+ }
1008
+ if (teams.length <= 1) return session.team();
1009
+ if (!ctx.interactive) throw new Error(`This Apple Account is on several teams: ${teams.map((team) => `${team.id} (${team.name})`).join(", ")}. Pass --team <id>.`);
1010
+ const picked = await ctx.ui.select({
1011
+ message: "Which Apple team?",
1012
+ options: teams.map((team) => ({
1013
+ value: String(team.id),
1014
+ label: team.name
1015
+ })),
1016
+ initialValue: String(session.team().id)
1017
+ });
1018
+ if (picked === null) throw new Error("Cancelled.");
1019
+ await session.selectTeam(Number(picked));
1020
+ return session.team();
1021
+ }
1022
+ async function signIn(ctx, deps, command) {
1023
+ const signedIn = await signInToApple(ctx, deps, signInFlags(ctx));
1024
+ if (signedIn.status === "signed-in") return signedIn.session;
1025
+ const next = `superwall ${command} --code <code>`;
1026
+ if (ctx.json) emitJson(ctx, {
1027
+ status: "verification_required",
1028
+ method: signedIn.challenge.method,
1029
+ destination: signedIn.challenge.destination ?? null,
1030
+ next
1031
+ });
1032
+ else ctx.ui.warn(`${describeChallenge(signedIn.challenge)}\nRun \`${next}\` with the same flags within 10 minutes to continue, or add --sms to get a text instead.`);
1033
+ process.exitCode = 1;
1034
+ }
1035
+ async function keyAccess(ctx, session, kind) {
1036
+ try {
1037
+ await apiCall(ctx, `Checking ${KEY_LABEL[kind]} access`, () => checkKeyAccess(session, APPLE_KIND[kind]));
1038
+ return "ok";
1039
+ } catch (error) {
1040
+ if (!(error instanceof AppleError)) throw error;
1041
+ return keyRefusal(error, kind);
1042
+ }
1043
+ }
1044
+ function keepKey(ctx, deps, kind, key, reason) {
1045
+ const detail = `${reason} Apple only releases a key once, so it was saved to ${deps.writeKeyFile(`${KEY_FILE[kind]}_${key.id}.p8`, key.privateKey)} (issuer ${key.issuerId}).`;
1046
+ ctx.output.render(blocks.warning(detail));
1047
+ return detail;
1048
+ }
1049
+ async function createAndSaveKey(ctx, deps, api, session, app, kind, role) {
1050
+ let key;
1051
+ try {
1052
+ key = await apiCall(ctx, `Creating the ${KEY_LABEL[kind]}`, () => kind === "api_key" ? createTeamKey(session, {
1053
+ name: KEY_NAME,
1054
+ role
1055
+ }) : createPurchaseKey(session, { name: KEY_NAME }));
1056
+ } catch (error) {
1057
+ if (!(error instanceof AppleError)) throw error;
1058
+ const detail = keyRefusal(error, kind);
1059
+ ctx.output.render(blocks.warning(`${KEY_LABEL[kind]}: ${detail}`));
1060
+ return {
1061
+ status: "failed",
1062
+ detail
1063
+ };
1064
+ }
1065
+ const appRef = {
1066
+ projectId: app.projectId,
1067
+ applicationId: app.applicationId
1068
+ };
1069
+ const credentials = {
1070
+ keyId: key.id,
1071
+ issuerId: key.issuerId,
1072
+ privateKey: key.privateKey
1073
+ };
1074
+ const setApplicationBundleId = kind === "purchase_key" && app.savedBundleId === null;
1075
+ const save = () => kind === "api_key" ? saveAppAscKey(api, appRef, credentials) : saveAppPurchaseKey(api, appRef, {
1076
+ ...credentials,
1077
+ bundleId: app.bundleId,
1078
+ setApplicationBundleId
1079
+ });
1080
+ let reason;
1081
+ try {
1082
+ const verdict = await untilActive(ctx, deps, `Saving the ${KEY_LABEL[kind]} on ${app.name}`, save, (result) => !result.valid);
1083
+ if (verdict.valid) {
1084
+ if (setApplicationBundleId) ctx.output.render(blocks.info(`Saved the bundle ID ${app.bundleId} on \`${app.name}\` with the key`));
1085
+ return {
1086
+ status: "done",
1087
+ detail: key.id
1088
+ };
1089
+ }
1090
+ reason = `Apple hasn't accepted the new key yet${verdict.error ? ` (${verdict.error})` : ""}.`;
1091
+ } catch (error) {
1092
+ if (!(error instanceof ApiError)) throw error;
1093
+ reason = `Superwall couldn't save the key: ${error.message}.`;
1094
+ }
1095
+ return {
1096
+ status: "failed",
1097
+ detail: keepKey(ctx, deps, kind, key, reason)
1098
+ };
1099
+ }
1100
+ async function createAppKey(ctx, deps) {
1101
+ const { api } = ctx;
1102
+ const kind = keyKind(ctx.argv.value2);
1103
+ if (!kind) throw new Error("Usage: superwall asc keys create <api_key | purchase_key> --app <id>");
1104
+ const role = keyRole(ctx);
1105
+ const flags = appFlags(ctx);
1106
+ const command = `asc keys create ${kind}`;
1107
+ ctx.output.render(blocks.intro(`Create an ${KEY_LABEL[kind]}`));
1108
+ const chosen = await chooseIosApp(ctx, api, flags);
1109
+ const applicationId = String(chosen.app.id);
1110
+ const appName = chosen.app.name ?? applicationId;
1111
+ const existing = savedKey(await apiCall(ctx, "Checking what is saved", () => getIntegrations(api, applicationId)), kind);
1112
+ if (existing && ctx.argv.replace !== true) {
1113
+ if (ctx.json) return emitJson(ctx, {
1114
+ status: "already_saved",
1115
+ kind,
1116
+ key_id: existing.key_id,
1117
+ app: {
1118
+ id: applicationId,
1119
+ project_id: String(chosen.project.id),
1120
+ name: appName
1121
+ }
1122
+ });
1123
+ ctx.ui.success(`\`${appName}\` already has an ${KEY_LABEL[kind]} (${existing.key_id}). Nothing was created. Pass --replace to create another and save it instead.`);
1124
+ return;
1125
+ }
1126
+ const session = await signIn(ctx, deps, command);
1127
+ if (!session) return;
1128
+ const team = await chooseTeam(ctx, session, text(ctx, "team"));
1129
+ ctx.output.render(blocks.info(`Apple team \`${team.name}\``));
1130
+ if (ctx.dryRun) {
1131
+ const access = await keyAccess(ctx, session, kind);
1132
+ if (ctx.json) return emitJson(ctx, {
1133
+ dryRun: true,
1134
+ kind,
1135
+ team,
1136
+ access
1137
+ });
1138
+ ctx.ui.report(`${access === "ok" ? "✓" : "✗"} ${KEY_LABEL[kind]} ${access}`);
1139
+ ctx.ui.info("[dry-run] nothing was created or changed.");
1140
+ return;
1141
+ }
1142
+ const app = await resolveApp(ctx, api, session, {
1143
+ kind: "existing",
1144
+ ...chosen
1145
+ }, flags);
1146
+ if (kind === "purchase_key" && app.savedBundleId === null) {
1147
+ const warning = await testModeWarning(ctx, api, app.applicationId, app.bundleId);
1148
+ if (warning) ctx.output.render(blocks.warning(warning));
1149
+ }
1150
+ const result = await createAndSaveKey(ctx, deps, api, session, app, kind, role);
1151
+ const created = result.status === "done";
1152
+ if (ctx.json) emitJson(ctx, {
1153
+ status: created ? "created" : "failed",
1154
+ kind,
1155
+ key_id: created ? result.detail : null,
1156
+ detail: created ? null : result.detail,
1157
+ replaced: created && existing ? existing.key_id : null,
1158
+ team,
1159
+ app: {
1160
+ id: app.applicationId,
1161
+ project_id: app.projectId,
1162
+ name: app.name,
1163
+ bundle_id: app.bundleId
1164
+ },
1165
+ ...kind === "purchase_key" ? { bundle_id_saved: created && app.savedBundleId === null } : {}
1166
+ });
1167
+ else if (created) ctx.ui.success(`${KEY_LABEL[kind]} ${result.detail} created and saved on \`${app.name}\`.`);
1168
+ if (!created) process.exitCode = 1;
1169
+ }
1170
+
1171
+ //#endregion
1172
+ //#region src/commands/platform/notification-url.ts
1173
+ const RETRY_DELAYS = [
1174
+ 1e3,
1175
+ 2e3,
1176
+ 3e3
1177
+ ];
1178
+ async function settled(sleep, work) {
1179
+ for (let attempt = 0;; attempt++) {
1180
+ const outcome = await work();
1181
+ const delay = RETRY_DELAYS[attempt];
1182
+ if (outcome.status !== "failed" || !outcome.retryable || delay === void 0) return outcome;
1183
+ await sleep(delay);
1184
+ }
1185
+ }
1186
+ function ensureNotificationUrl(ctx, sleep, api, app, options) {
1187
+ return apiCall(ctx, "Setting the server notification URL", () => settled(sleep, () => setServerNotifications(api, app, options)));
1188
+ }
1189
+ function holder(environment) {
1190
+ switch (environment.owner) {
1191
+ case "this_app": return "this app's Superwall URL";
1192
+ case "none": return "none";
1193
+ case "superwall_app": return environment.application ? `another Superwall app, ${environment.application.name} (app ${environment.application.id})` : "another Superwall app";
1194
+ case "other": return "another server";
1195
+ }
1196
+ }
1197
+ function environmentLines(outcome) {
1198
+ return ["production", "sandbox"].flatMap((name) => {
1199
+ const environment = outcome[name];
1200
+ if (!environment) return [];
1201
+ const label = name === "production" ? "Production" : "Sandbox";
1202
+ const shown = environment.owner === "this_app" || environment.owner === "none" ? "" : ` ${environment.url ?? ""}`;
1203
+ return [`${label}: ${holder(environment)}${shown}`];
1204
+ });
1205
+ }
1206
+ function describeNotificationUrl(outcome) {
1207
+ switch (outcome.status) {
1208
+ case "set": return "Apple now sends this app's server notifications to Superwall.";
1209
+ case "already_set": return "Apple already sends this app's server notifications to Superwall.";
1210
+ case "not_set": return "Apple has no server notification URL for this app in production, sandbox, or both. No other server holds either.";
1211
+ case "conflict": {
1212
+ const holders = ["production", "sandbox"].map((name) => outcome[name]).filter((environment) => environment?.owner === "superwall_app" || environment?.owner === "other");
1213
+ return holders.length > 0 && holders.every((environment) => environment.owner === "superwall_app") ? "Apple sends this app's server notifications to another Superwall app. Superwall won't replace it." : "Apple sends this app's server notifications to another server. Superwall won't replace it.";
1214
+ }
1215
+ case "skipped": return outcome.message ?? "Apple can't be asked about this app's server notification URL.";
1216
+ case "failed": return outcome.message ?? "Apple couldn't be asked about this app's server notification URL.";
1217
+ }
1218
+ }
1219
+ async function runNotificationUrl(ctx, sleep) {
1220
+ const { api } = ctx;
1221
+ const action = ctx.argv.value ?? "get";
1222
+ if (action !== "get" && action !== "check" && action !== "set") throw new Error(`Unknown "asc notification-url ${action}". Use get | check | set.`);
1223
+ const chosen = await chooseIosApp(ctx, api, appFlags(ctx));
1224
+ const app = {
1225
+ projectId: String(chosen.project.id),
1226
+ applicationId: String(chosen.app.id)
1227
+ };
1228
+ if (action === "get") {
1229
+ const url = await apiCall(ctx, "Loading the URL", () => getAppNotificationUrl(api, app));
1230
+ if (ctx.json) return emitJson(ctx, {
1231
+ application_id: app.applicationId,
1232
+ url
1233
+ });
1234
+ ctx.output.text(url);
1235
+ return;
1236
+ }
1237
+ const setRevenueProvider = ctx.argv["set-revenue-provider"] === true;
1238
+ if (action === "set" && ctx.dryRun) {
1239
+ const url = await apiCall(ctx, "Loading the URL", () => getAppNotificationUrl(api, app));
1240
+ if (ctx.json) return emitJson(ctx, {
1241
+ dryRun: true,
1242
+ action: "set",
1243
+ application_id: app.applicationId,
1244
+ url,
1245
+ set_revenue_provider: setRevenueProvider
1246
+ });
1247
+ ctx.ui.info(`[dry-run] would set ${url} where Apple has no server notification URL.`);
1248
+ return;
1249
+ }
1250
+ const outcome = action === "check" ? await apiCall(ctx, "Reading the server notification URL", () => checkServerNotifications(api, app)) : await ensureNotificationUrl(ctx, sleep, api, app, { setRevenueProvider });
1251
+ const ok = action === "check" ? outcome.status !== "failed" && outcome.status !== "skipped" : outcome.status === "set" || outcome.status === "already_set";
1252
+ if (ctx.json) emitJson(ctx, {
1253
+ application_id: app.applicationId,
1254
+ url: outcome.url,
1255
+ apple: {
1256
+ status: outcome.status,
1257
+ message: outcome.message,
1258
+ production: outcome.production,
1259
+ sandbox: outcome.sandbox
1260
+ },
1261
+ ...action === "set" ? { set_revenue_provider: setRevenueProvider } : {}
1262
+ });
1263
+ else {
1264
+ const message = [describeNotificationUrl(outcome), ...environmentLines(outcome).map((line) => ` ${line}`)].join("\n");
1265
+ if (!ok) ctx.ui.error(message);
1266
+ else if (outcome.status === "set" || outcome.status === "already_set") ctx.ui.success(message);
1267
+ else ctx.ui.info(message);
1268
+ }
1269
+ if (!ok) process.exitCode = 1;
1270
+ }
1271
+
1272
+ //#endregion
1273
+ export { appleDeps as S, chooseAppIntent as _, KEY_KINDS as a, resolveApp as b, chooseTeam as c, keyAccess as d, keyKind as f, text as g, signIn as h, runNotificationUrl as i, createAndSaveKey as l, savedKey as m, ensureNotificationUrl as n, KEY_LABEL as o, keyRole as p, environmentLines as r, appFlags as s, describeNotificationUrl as t, createAppKey as u, chooseIosApp as v, savedBundleId as x, differentBundleId as y };