@referalli/cli 0.4.6 → 0.4.8

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.
package/dist/src/apply.js CHANGED
@@ -3,31 +3,46 @@ import { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
3
3
  import { load } from 'js-yaml';
4
4
  /**
5
5
  * `referalli plan|apply <file>`: make the account match a declarative file.
6
- * Every resource is matched by a stable key (program slug, webhook url, API key
7
- * name + owner, billing connection name, auth connection provider + instance + program); creates carry an Idempotency-Key derived from that key and the
6
+ * Every resource is matched by a stable key (program slug, webhook id or url, API key
7
+ * name + owner, billing connection name, auth connection provider + instance + program,
8
+ * payout provider); creates carry an Idempotency-Key derived from that key and the
8
9
  * request, so a retried apply never creates twice. Nothing missing from the file
9
- * is ever deleted, rotated or revoked.
10
+ * is deleted unless `--prune` asks (never programs, never the calling key).
10
11
  */
11
12
  export class ConfigError extends Error {
12
13
  }
13
14
  // Program fields compared against GET /v1/programs/{id} and sent as-is on PATCH.
14
15
  const PROGRAM_TOP = ['name', 'attributionModel', 'cookieWindowDays', 'signupToConversionDays', 'termsMd', 'status', 'publicHandle'];
15
16
  // Program settings: PATCH takes them top-level, GET returns them under `settings`.
16
- const PROGRAM_SETTINGS = ['probabilisticPolicy', 'selfReferralPolicy', 'splitCommissions', 'allowPaidSearch', 'challengeLinks', 'settlement'];
17
+ const PROGRAM_SETTINGS = ['probabilisticPolicy', 'selfReferralPolicy', 'splitCommissions', 'allowPaidSearch', 'challengeLinks', 'settlement', 'howItWorksMd'];
18
+ // Passed through to PATCH as-is; read back top-level, else under `settings` (R-07/R-22/R-31 fields).
19
+ const PROGRAM_PASS = ['termsUrl', 'faqUrl', 'supportUrl', 'trackingConsent'];
17
20
  // Mappings merged into what's live: only the keys the file names are compared, and PATCH sends the live block with them applied.
18
- const PROGRAM_BLOCKS = { publicPage: ['pitch', 'autoApprove'], riskPolicy: ['holdBotScore', 'holdRiskScore', 'holdHighRiskLevel', 'holdDisposableEmail', 'holdVelocity', 'holdUnverifiedEmail', 'holdSelfReferral'] };
19
- const PROGRAM_KEYS = ['slug', ...PROGRAM_TOP, ...PROGRAM_SETTINGS, ...Object.keys(PROGRAM_BLOCKS), 'destinationUrl', 'commissionRule', 'stripeCredits'];
21
+ const PROGRAM_BLOCKS = {
22
+ publicPage: ['pitch', 'autoApprove'],
23
+ riskPolicy: ['holdBotScore', 'holdRiskScore', 'holdHighRiskLevel', 'holdDisposableEmail', 'holdVelocity', 'holdUnverifiedEmail', 'holdSelfReferral'],
24
+ widget: ['autoEnroll', 'destinationUrl'],
25
+ notificationEmails: ['enabled'],
26
+ brand: ['name', 'logoUrl', 'theme', 'supportUrl', 'linkDomain', 'portalDomain', 'emailFrom'],
27
+ };
28
+ // Blocks GET returns under `settings`.
29
+ const SETTINGS_BLOCKS = ['riskPolicy', 'widget', 'notificationEmails'];
30
+ const PROGRAM_KEYS = ['slug', ...PROGRAM_TOP, ...PROGRAM_SETTINGS, ...PROGRAM_PASS, ...Object.keys(PROGRAM_BLOCKS), 'destinationUrl', 'commissionRule', 'stripeCredits', 'refereeReward'];
20
31
  const STRIPE_KEYS = ['enabled', 'referrerMatch', 'metadataKey', 'refereeRewards', 'balanceCurrency', 'createCustomerIfMissing', 'waitForCustomer', 'secretKeyEnv'];
21
- const WEBHOOK_KEYS = ['url', 'topics', 'programs', 'status', 'alertContacts'];
32
+ const WEBHOOK_KEYS = ['id', 'url', 'topics', 'programs', 'status', 'alertContacts', 'managedBy'];
22
33
  const API_KEY_KEYS = ['name', 'owner', 'mode', 'scopes', 'expiresInDays', 'programs', 'apiVersion'];
23
34
  const BILLING_KEYS = ['name', 'provider', 'programs', 'status', 'customerRefMetadataKey', 'filter', 'stripeKeyEnv'];
24
- // Compared only when listed. shortcut: no tokenVerification (a preset expands on save, may hold a secret) or keys (GET doesn't return them), so no drift check; set them with `referalli api`.
35
+ // Compared only when listed. shortcut: no metadata keys (GET doesn't return them), so no drift check; set them with `referalli api`.
25
36
  const AUTH_FIELDS = ['name', 'status', 'autoEnrollUsers', 'destinationUrl', 'resolveBillingCustomers', 'signatureVersion', 'allowedOrigins'];
26
- const AUTH_KEYS = ['provider', 'program', 'instanceId', 'appId', ...AUTH_FIELDS];
37
+ const AUTH_KEYS = ['provider', 'program', 'instanceId', 'appId', 'tokenVerification', ...AUTH_FIELDS];
27
38
  // POST ignores these: they go in a PATCH right after the create.
28
39
  const AUTH_PATCH_ONLY = ['status', 'resolveBillingCustomers', 'signatureVersion'];
29
40
  const AUTH_PROTOCOL = ['atlas', 'custom'];
30
- const SECRET_KEYS = ['secretKey', 'stripeKey', 'webhookSecret', 'credentials'];
41
+ const PAYOUT_KEYS = ['provider', 'env', 'credentialEnv'];
42
+ const EMAIL_KEYS = ['provider', 'apiKeyEnv', 'fromAddress', 'fromName', 'replyTo', 'defaultLocale', 'logoUrl', 'primaryColor'];
43
+ const HOSTED_KEYS = ['consent', 'chat', 'customOrigins'];
44
+ const SECTIONS = ['programs', 'webhooks', 'apiKeys', 'billingConnections', 'authConnections', 'payouts', 'email', 'trackingConsent', 'hostedPages'];
45
+ const SECRET_KEYS = ['secretKey', 'stripeKey', 'webhookSecret', 'credentials', 'apiKey', 'sharedSecret', 'identitySecret'];
31
46
  // What the API stores when a rule leaves these out (packages/commissions ruleConfigSchema).
32
47
  const RULE_DEFAULTS = { appliesTo: 'gross', recurring: { type: 'lifetime' }, holdDays: 30, rounding: 'half_even', overrides: [] };
33
48
  const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
@@ -36,7 +51,7 @@ function checkKeys(o, allowed, where, required) {
36
51
  throw new ConfigError(`${where}: expected a mapping`);
37
52
  for (const k of Object.keys(o)) {
38
53
  if (SECRET_KEYS.includes(k))
39
- throw new ConfigError(`${where}: secrets never go in the file; use secretKeyEnv / stripeKeyEnv: ENV_VAR_NAME`);
54
+ throw new ConfigError(`${where}: secrets never go in the file; name an environment variable instead (secretKeyEnv, stripeKeyEnv, apiKeyEnv, sharedSecretEnv, identitySecretEnv, credentialEnv)`);
40
55
  if (!allowed.includes(k))
41
56
  throw new ConfigError(`${where}: unknown field "${k}" (allowed: ${allowed.join(', ')})`);
42
57
  }
@@ -60,7 +75,7 @@ export function parseConfig(text, file = 'config') {
60
75
  catch (err) {
61
76
  throw new ConfigError(`${file}: ${err.message}`);
62
77
  }
63
- checkKeys(doc ?? {}, ['programs', 'webhooks', 'apiKeys', 'billingConnections', 'authConnections'], file);
78
+ checkKeys(doc ?? {}, SECTIONS, file);
64
79
  const d = (doc ?? {});
65
80
  const programs = list(d.programs, 'programs').map((p, i) => {
66
81
  const where = `programs[${i}]`;
@@ -74,11 +89,17 @@ export function parseConfig(text, file = 'config') {
74
89
  throw new ConfigError(`${where}.${block}: expected a mapping`);
75
90
  checkKeys(p[block], [...keys], `${where}.${block}`);
76
91
  }
92
+ if (p.destinationUrl !== undefined && isObj(p.widget) && p.widget.destinationUrl !== undefined) {
93
+ throw new ConfigError(`${where}: set destinationUrl or widget.destinationUrl, not both`);
94
+ }
77
95
  if (p.stripeCredits !== undefined) {
78
96
  checkKeys(p.stripeCredits, STRIPE_KEYS, `${where}.stripeCredits`);
79
97
  if (typeof p.stripeCredits.enabled !== 'boolean')
80
98
  throw new ConfigError(`${where}.stripeCredits: "enabled" (true/false) is required`);
81
99
  }
100
+ // null turns it off; a mapping is the PUT /v1/programs/{id}/referee-reward body.
101
+ if (p.refereeReward !== undefined && p.refereeReward !== null && !isObj(p.refereeReward))
102
+ throw new ConfigError(`${where}.refereeReward: expected a mapping (or null to turn it off)`);
82
103
  return p;
83
104
  });
84
105
  const slugs = programs.map((p) => p.slug);
@@ -89,8 +110,16 @@ export function parseConfig(text, file = 'config') {
89
110
  checkKeys(w, WEBHOOK_KEYS, `webhooks[${i}]`, 'url');
90
111
  if (w.status !== undefined && w.status !== 'active' && w.status !== 'paused')
91
112
  throw new ConfigError(`webhooks[${i}].status: active or paused`);
113
+ if (w.id !== undefined && (typeof w.id !== 'string' || !w.id.startsWith('whe_')))
114
+ throw new ConfigError(`webhooks[${i}].id: a webhook endpoint id (whe_…)`);
115
+ if (w.topics !== undefined && (!Array.isArray(w.topics) || w.topics.some((t) => typeof t !== 'string')))
116
+ throw new ConfigError(`webhooks[${i}].topics: expected a list of topics`);
92
117
  return w;
93
118
  });
119
+ const hookKeys = webhooks.map((w) => w.id ?? w.url);
120
+ const dupHook = hookKeys.find((s, i) => hookKeys.indexOf(s) !== i);
121
+ if (dupHook)
122
+ throw new ConfigError(`webhooks: "${dupHook}" is listed twice`);
94
123
  const apiKeys = list(d.apiKeys, 'apiKeys').map((k, i) => {
95
124
  checkKeys(k, API_KEY_KEYS, `apiKeys[${i}]`, 'name');
96
125
  return k;
@@ -129,13 +158,51 @@ export function parseConfig(text, file = 'config') {
129
158
  throw new ConfigError(`${where}.status: active or paused`);
130
159
  if (a.allowedOrigins !== undefined && !Array.isArray(a.allowedOrigins))
131
160
  throw new ConfigError(`${where}.allowedOrigins: expected a list`);
161
+ // Any POST /v1/auth/connections tokenVerification field, the secret by env name; null removes it.
162
+ if (a.tokenVerification !== undefined && a.tokenVerification !== null) {
163
+ if (!isObj(a.tokenVerification))
164
+ throw new ConfigError(`${where}.tokenVerification: expected a mapping (or null)`);
165
+ checkKeys(a.tokenVerification, Object.keys(a.tokenVerification), `${where}.tokenVerification`);
166
+ }
132
167
  return a;
133
168
  });
134
169
  const authKeys = authConnections.map(authKey);
135
170
  const dupAuth = authKeys.find((s, i) => authKeys.indexOf(s) !== i);
136
171
  if (dupAuth)
137
172
  throw new ConfigError(`authConnections: "${dupAuth}" is listed twice`);
138
- return { programs, webhooks, apiKeys, billingConnections, authConnections };
173
+ const payouts = list(d.payouts, 'payouts').map((p, i) => {
174
+ const where = `payouts[${i}]`;
175
+ checkKeys(p, PAYOUT_KEYS, where, 'provider');
176
+ const env = p.credentialEnv;
177
+ if (!isObj(env) || Object.keys(env).length === 0 || Object.values(env).some((v) => typeof v !== 'string' || !v)) {
178
+ throw new ConfigError(`${where}.credentialEnv: a mapping of credential field to environment variable name, e.g. { secretKey: STRIPE_PAYOUT_KEY }`);
179
+ }
180
+ return p;
181
+ });
182
+ const providers = payouts.map((p) => p.provider);
183
+ const dupProvider = providers.find((s, i) => providers.indexOf(s) !== i);
184
+ if (dupProvider)
185
+ throw new ConfigError(`payouts: provider "${dupProvider}" is listed twice`);
186
+ const single = (key, keys) => {
187
+ if (d[key] === undefined || d[key] === null)
188
+ return undefined;
189
+ if (keys)
190
+ checkKeys(d[key], keys, key);
191
+ else if (!isObj(d[key]))
192
+ throw new ConfigError(`${key}: expected a mapping`);
193
+ return d[key];
194
+ };
195
+ const email = single('email', EMAIL_KEYS);
196
+ const trackingConsent = single('trackingConsent');
197
+ const hostedPages = single('hostedPages', HOSTED_KEYS);
198
+ if (hostedPages) {
199
+ if (hostedPages.consent !== undefined)
200
+ checkKeys(hostedPages.consent, ['adapter', 'config'], 'hostedPages.consent', 'adapter');
201
+ if (hostedPages.chat !== undefined && hostedPages.chat !== null)
202
+ checkKeys(hostedPages.chat, ['adapter', 'config', 'identitySecretEnv'], 'hostedPages.chat', 'adapter');
203
+ }
204
+ const sections = SECTIONS.filter((k) => d[k] !== undefined);
205
+ return { programs, webhooks, apiKeys, billingConnections, authConnections, payouts, email, trackingConsent, hostedPages, sections };
139
206
  }
140
207
  /** Key-order-insensitive JSON, for comparing values. */
141
208
  const canon = (v) => JSON.stringify(v, (_k, x) => (isObj(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => a.localeCompare(b))) : x));
@@ -167,7 +234,7 @@ const programIdsFor = (ctx, slugs) => slugs?.length
167
234
  })
168
235
  : null;
169
236
  /** Compare the file with the account; nothing is written. */
170
- export async function buildPlan(client, config, env) {
237
+ export async function buildPlan(client, config, env, opts = {}) {
171
238
  const changes = [];
172
239
  const programs = await listAll(client, '/v1/programs');
173
240
  const ids = new Map(programs.map((p) => [p.slug, p.id]));
@@ -182,13 +249,13 @@ export async function buildPlan(client, config, env) {
182
249
  const cur = programs.find((p) => p.slug === spec.slug);
183
250
  const label = `program "${spec.slug}"`;
184
251
  const desired = {};
185
- for (const k of [...PROGRAM_TOP, ...PROGRAM_SETTINGS, ...Object.keys(PROGRAM_BLOCKS), 'destinationUrl'])
252
+ for (const k of [...PROGRAM_TOP, ...PROGRAM_SETTINGS, ...PROGRAM_PASS, ...Object.keys(PROGRAM_BLOCKS), 'destinationUrl'])
186
253
  if (spec[k] !== undefined)
187
254
  desired[k] = spec[k];
188
255
  if (!cur) {
189
256
  const { destinationUrl, ...rest } = desired;
190
257
  // POST takes the destination as the widget setting; PATCH moves it (and its links).
191
- const body = { slug: spec.slug, name: spec.slug, ...rest, ...(destinationUrl ? { widget: { destinationUrl } } : {}) };
258
+ const body = { slug: spec.slug, name: spec.slug, ...rest, ...(destinationUrl ? { widget: { ...rest.widget, destinationUrl } } : {}) };
192
259
  changes.push({
193
260
  action: 'create',
194
261
  kind: 'program',
@@ -204,9 +271,11 @@ export async function buildPlan(client, config, env) {
204
271
  else {
205
272
  const now = (k) => k === 'destinationUrl'
206
273
  ? (cur.settings.widget?.destinationUrl ?? null)
207
- : PROGRAM_SETTINGS.includes(k) || k === 'riskPolicy'
274
+ : PROGRAM_SETTINGS.includes(k) || SETTINGS_BLOCKS.includes(k)
208
275
  ? cur.settings[k]
209
- : cur[k];
276
+ : k === 'brand' || PROGRAM_PASS.includes(k)
277
+ ? (cur[k] !== undefined ? cur[k] : (cur.settings[k] ?? null))
278
+ : cur[k];
210
279
  // A block counts as changed only on the keys the file names; the new value is the live block with them applied.
211
280
  const want = (k, v) => (k in PROGRAM_BLOCKS ? { ...(now(k) ?? {}), ...v } : v);
212
281
  const fields = Object.entries(desired)
@@ -277,53 +346,115 @@ export async function buildPlan(client, config, env) {
277
346
  },
278
347
  });
279
348
  }
349
+ if (spec.refereeReward !== undefined) {
350
+ // The file holds the PUT body; GET stores a normalized form, so only the keys the file names are compared.
351
+ const file = spec.refereeReward;
352
+ const off = file === null || file.enabled === false;
353
+ const live = cur?.settings.refereeReward ?? null;
354
+ const cmp = (k, v) => (k === 'currency' && typeof v === 'string' ? v.toLowerCase() : v);
355
+ const fields = off
356
+ ? live
357
+ ? [['refereeReward', live, null]]
358
+ : []
359
+ : live
360
+ ? Object.entries(file).filter(([k, v]) => k !== 'enabled' && !same(live[k], cmp(k, v))).map(([k, v]) => [k, live[k], cmp(k, v)])
361
+ : Object.entries(file).map(([k, v]) => [k, undefined, v]);
362
+ changes.push({
363
+ action: !fields.length ? 'noop' : !live && !off ? 'create' : 'update',
364
+ kind: 'refereeReward',
365
+ label: `refereeReward "${spec.slug}"`,
366
+ fields,
367
+ run: async (ctx) => {
368
+ await ctx.client.request('PUT', `/v1/programs/${ctx.ids.get(spec.slug)}/referee-reward`, off ? { enabled: false } : file);
369
+ return [];
370
+ },
371
+ });
372
+ }
280
373
  }
281
- if (config.webhooks.length) {
374
+ const me = opts.prune ? await client.request('GET', '/v1/me') : null;
375
+ const fileIds = config.programs.map((p) => ids.get(p.slug)).filter((x) => Boolean(x));
376
+ const scope = me?.apiKey?.programIds ?? (config.programs.length ? fileIds : null);
377
+ /** Only what is wholly inside the scope is pruned: never another product's resources, nor an org-wide one under a scope. */
378
+ const prunable = (programIds) => !scope || Boolean(programIds?.length && programIds.every((id) => scope.includes(id)));
379
+ const pruning = (section) => Boolean(opts.prune && config.sections.includes(section));
380
+ const remove = (kind, label, path) => ({
381
+ action: 'delete',
382
+ kind,
383
+ label,
384
+ fields: [],
385
+ run: async (ctx) => {
386
+ await ctx.client.request('DELETE', path);
387
+ return [];
388
+ },
389
+ });
390
+ if (config.webhooks.length || pruning('webhooks')) {
282
391
  const endpoints = await listAll(client, '/v1/webhook-endpoints');
392
+ await checkTopics(client, config.webhooks);
393
+ const matched = new Set();
283
394
  for (const spec of config.webhooks) {
284
395
  checkRefs(spec.programs, `webhook ${spec.url}`);
285
- const cur = endpoints.find((e) => e.url === spec.url);
286
- const want = { topics: sorted(spec.topics ?? ['*']), programs: sorted(spec.programs), status: spec.status ?? 'active' };
396
+ const cur = spec.id ? endpoints.find((e) => e.id === spec.id) : endpoints.find((e) => e.url === spec.url);
397
+ if (spec.id && !cur)
398
+ throw new ConfigError(`webhook ${spec.id}: no such endpoint on the account (remove the id to create one at ${spec.url})`);
399
+ if (cur)
400
+ matched.add(cur.id);
401
+ // Another system owns the endpoint (Atlas's sync webhook): its topics are its own, and only what the file lists is compared (R-20).
402
+ const managed = Boolean(cur?.managedBy ?? spec.managedBy);
403
+ const want = managed
404
+ ? {
405
+ ...(spec.topics ? { topics: sorted(spec.topics) } : {}),
406
+ ...(spec.programs ? { programs: sorted(spec.programs) } : {}),
407
+ ...(spec.status ? { status: spec.status } : {}),
408
+ }
409
+ : { topics: sorted(spec.topics ?? ['*']), programs: sorted(spec.programs), status: spec.status ?? 'active' };
287
410
  if (spec.alertContacts !== undefined)
288
411
  want.alertContacts = sorted(spec.alertContacts);
289
- const label = `webhook ${spec.url}`;
290
- const body = (ctx) => ({
291
- topics: want.topics,
292
- programIds: programIdsFor(ctx, spec.programs),
293
- status: want.status,
294
- ...(want.alertContacts ? { alertContacts: want.alertContacts } : {}),
295
- });
412
+ if (spec.managedBy !== undefined)
413
+ want.managedBy = spec.managedBy;
414
+ const body = (ctx, keys) => Object.fromEntries(keys.map((k) => (k === 'programs' ? ['programIds', programIdsFor(ctx, spec.programs)] : [k, want[k]])));
296
415
  if (!cur) {
297
416
  changes.push({
298
417
  action: 'create',
299
418
  kind: 'webhook',
300
- label,
419
+ label: `webhook ${spec.url}`,
301
420
  fields: Object.entries(want).map(([k, v]) => [k, undefined, v]),
302
421
  run: async (ctx) => {
303
- const made = await create(ctx.client, '/v1/webhook-endpoints', 'webhook', spec.url, { url: spec.url, ...body(ctx) });
422
+ const made = await create(ctx.client, '/v1/webhook-endpoints', 'webhook', spec.url, { url: spec.url, ...body(ctx, Object.keys(want)) });
304
423
  return [[`webhook ${spec.url}`, made.secret]];
305
424
  },
306
425
  });
307
426
  continue;
308
427
  }
309
428
  const now = {
429
+ url: cur.url,
310
430
  topics: sorted(cur.topics),
311
431
  programs: sorted((cur.programIds ?? []).map((id) => slugOf.get(id) ?? id)),
312
432
  status: cur.status,
313
433
  alertContacts: sorted(cur.alertContacts),
434
+ managedBy: cur.managedBy ?? null,
314
435
  };
436
+ // Matched by id, the url may move: same endpoint and secret, new address.
437
+ if (cur.url !== spec.url)
438
+ want.url = spec.url;
315
439
  const fields = Object.keys(want).filter((k) => !same(now[k], want[k])).map((k) => [k, now[k], want[k]]);
316
440
  changes.push({
317
441
  action: fields.length ? 'update' : 'noop',
318
442
  kind: 'webhook',
319
- label,
443
+ label: cur.url !== spec.url ? `webhook url: ${cur.url} → ${spec.url}` : `webhook ${spec.id ?? spec.url}`,
320
444
  fields,
321
445
  run: async (ctx) => {
322
- await ctx.client.request('PATCH', `/v1/webhook-endpoints/${cur.id}`, body(ctx));
446
+ await ctx.client.request('PATCH', `/v1/webhook-endpoints/${cur.id}`, body(ctx, fields.map(([k]) => k)));
323
447
  return [];
324
448
  },
325
449
  });
326
450
  }
451
+ if (pruning('webhooks')) {
452
+ for (const e of endpoints) {
453
+ if (matched.has(e.id) || e.managedBy || !prunable(e.programIds))
454
+ continue;
455
+ changes.push(remove('webhook', `webhook ${e.url} (${e.id})`, `/v1/webhook-endpoints/${e.id}`));
456
+ }
457
+ }
327
458
  }
328
459
  for (const spec of config.apiKeys) {
329
460
  checkRefs(spec.programs, `apiKey "${spec.name}"`);
@@ -350,7 +481,19 @@ export async function buildPlan(client, config, env) {
350
481
  },
351
482
  });
352
483
  }
353
- if (config.billingConnections.length) {
484
+ if (pruning('apiKeys')) {
485
+ const keys = await listAll(client, '/v1/api-keys');
486
+ const self = keys.find((k) => k.id === me?.apiKey?.id);
487
+ for (const k of keys) {
488
+ if (k.revokedAt || config.apiKeys.some((s) => s.name === k.name && (s.owner ?? null) === (k.owner ?? null)))
489
+ continue;
490
+ // Never the key making this call, nor its live/test twin.
491
+ if (k.id === me?.apiKey?.id || (self?.pairId && k.pairId === self.pairId) || !prunable(k.programIds))
492
+ continue;
493
+ changes.push(remove('apiKey', `apiKey "${k.name}"${k.owner ? ` (owner ${k.owner})` : ''} ${k.livemode === false ? 'test' : 'live'} (${k.id}, revoked)`, `/v1/api-keys/${k.id}`));
494
+ }
495
+ }
496
+ if (config.billingConnections.length || pruning('billingConnections')) {
354
497
  const conns = await listAll(client, '/v1/billing/connections');
355
498
  for (const spec of config.billingConnections) {
356
499
  const label = `billingConnection "${spec.name}"`;
@@ -412,9 +555,17 @@ export async function buildPlan(client, config, env) {
412
555
  },
413
556
  });
414
557
  }
558
+ if (pruning('billingConnections')) {
559
+ for (const c of conns) {
560
+ if (config.billingConnections.some((s) => s.name === c.name) || !prunable(c.programIds))
561
+ continue;
562
+ changes.push(remove('billingConnection', `billingConnection "${c.name}" (${c.id})`, `/v1/billing/connections/${c.id}`));
563
+ }
564
+ }
415
565
  }
416
- if (config.authConnections.length) {
566
+ if (config.authConnections.length || pruning('authConnections')) {
417
567
  const conns = await listAll(client, '/v1/auth/connections');
568
+ const matchedAuth = new Set();
418
569
  for (const spec of config.authConnections) {
419
570
  const label = `authConnection "${authKey(spec)}"`;
420
571
  checkRefs([spec.program], label);
@@ -422,17 +573,30 @@ export async function buildPlan(client, config, env) {
422
573
  if (matches.length > 1)
423
574
  throw new ConfigError(`${label}: ${matches.length} connections on the account match (${matches.map((c) => c.id).join(', ')}); delete the extras (DELETE /v1/auth/connections/{id})`);
424
575
  const cur = matches[0];
576
+ if (cur)
577
+ matchedAuth.add(cur.id);
425
578
  const want = {};
426
579
  for (const k of AUTH_FIELDS)
427
580
  if (spec[k] !== undefined)
428
581
  want[k] = k === 'allowedOrigins' ? sorted(spec[k]) : spec[k];
582
+ // tokenVerification: a preset expands on save, so only the keys the file names are compared; the secret comes from sharedSecretEnv.
583
+ const tvSpec = spec.tokenVerification;
584
+ const { sharedSecretEnv, ...tv } = tvSpec ?? {};
585
+ const liveTv = cur?.tokenVerification ?? null;
586
+ const tvChanged = tvSpec !== undefined && (tvSpec === null ? liveTv !== null : !liveTv || Object.keys(tv).some((k) => !same(liveTv[k], tv[k])));
587
+ if (tvChanged && sharedSecretEnv && !env[sharedSecretEnv])
588
+ throw new ConfigError(`${label}.tokenVerification: environment variable ${sharedSecretEnv} is not set`);
589
+ const tvShown = tvSpec === null ? null : { ...tv, ...(sharedSecretEnv ? { sharedSecret: `(from $${sharedSecretEnv})` } : {}) };
590
+ const tvBody = () => (tvSpec === null ? null : { ...tv, ...(sharedSecretEnv ? { sharedSecret: env[sharedSecretEnv] } : {}) });
429
591
  if (!cur) {
430
592
  const { provider, program, instanceId, appId } = spec;
431
593
  changes.push({
432
594
  action: 'create',
433
595
  kind: 'authConnection',
434
596
  label,
435
- fields: Object.entries({ provider, program, instanceId, appId, ...want }).filter(([, v]) => v !== undefined).map(([k, v]) => [k, undefined, v]),
597
+ fields: Object.entries({ provider, program, instanceId, appId, ...want, ...(tvSpec ? { tokenVerification: tvShown } : {}) })
598
+ .filter(([, v]) => v !== undefined)
599
+ .map(([k, v]) => [k, undefined, v]),
436
600
  run: async (ctx) => {
437
601
  const onCreate = Object.entries(want).filter(([k, v]) => !AUTH_PATCH_ONLY.includes(k) && v !== null);
438
602
  const made = await create(ctx.client, '/v1/auth/connections', 'auth', authKey(spec), {
@@ -441,6 +605,7 @@ export async function buildPlan(client, config, env) {
441
605
  ...(instanceId ? { instanceId } : {}),
442
606
  ...(appId ? { appId } : {}),
443
607
  ...Object.fromEntries(onCreate),
608
+ ...(tvSpec ? { tokenVerification: tvBody() } : {}),
444
609
  });
445
610
  // Printed before the PATCH: if that fails the secret still reached the user. It can't be fetched again.
446
611
  ctx.out(`${label} is ${made.id}. Its signing secret, shown once and saved nowhere (--secret-file doesn't take it), so store it now: ${made.secret}`);
@@ -454,23 +619,178 @@ export async function buildPlan(client, config, env) {
454
619
  }
455
620
  const now = (k) => (k === 'allowedOrigins' ? sorted(cur.allowedOrigins) : cur[k]);
456
621
  const fields = Object.keys(want).filter((k) => !same(now(k), want[k])).map((k) => [k, now(k), want[k]]);
622
+ if (tvChanged)
623
+ fields.push(['tokenVerification', liveTv, tvShown]);
457
624
  changes.push({
458
625
  action: fields.length ? 'update' : 'noop',
459
626
  kind: 'authConnection',
460
627
  label,
461
628
  fields,
462
629
  run: async (ctx) => {
463
- await ctx.client.request('PATCH', `/v1/auth/connections/${cur.id}`, Object.fromEntries(fields.map(([k, , v]) => [k, v])));
630
+ const body = Object.fromEntries(fields.map(([k, , v]) => [k, k === 'tokenVerification' ? tvBody() : v]));
631
+ await ctx.client.request('PATCH', `/v1/auth/connections/${cur.id}`, body);
464
632
  return [];
465
633
  },
466
634
  });
467
635
  }
636
+ if (pruning('authConnections')) {
637
+ for (const c of conns) {
638
+ if (matchedAuth.has(c.id) || !prunable([c.programId]))
639
+ continue;
640
+ changes.push(remove('authConnection', `authConnection "${[c.provider, c.instanceId ?? c.appId, slugOf.get(c.programId) ?? c.programId].filter(Boolean).join(' ')}" (${c.id})`, `/v1/auth/connections/${c.id}`));
641
+ }
642
+ }
643
+ }
644
+ // Payout rails (R-11): BYOK credentials from the environment. The API never returns them, so a connected
645
+ // provider is re-sent only when its env changes. shortcut: rotating a key needs `referalli api PUT`.
646
+ if (config.payouts.length || pruning('payouts')) {
647
+ const res = await client.request('GET', '/v1/payout-connections');
648
+ const conns = Array.isArray(res) ? res : res.data;
649
+ for (const spec of config.payouts) {
650
+ const label = `payout "${spec.provider}"`;
651
+ const cur = conns.find((c) => c.provider === spec.provider && c.status === 'active');
652
+ const changed = !cur || (spec.env !== undefined && spec.env !== cur.env);
653
+ if (changed) {
654
+ for (const name of Object.values(spec.credentialEnv))
655
+ if (!env[name])
656
+ throw new ConfigError(`${label}: environment variable ${name} is not set`);
657
+ }
658
+ const fields = !cur
659
+ ? [['provider', undefined, spec.provider], ...(spec.env ? [['env', undefined, spec.env]] : []), ...Object.entries(spec.credentialEnv).map(([k, v]) => [k, undefined, `(from $${v})`])]
660
+ : changed
661
+ ? [['env', cur.env, spec.env]]
662
+ : [];
663
+ changes.push({
664
+ action: !cur ? 'create' : changed ? 'update' : 'noop',
665
+ kind: 'payout',
666
+ label,
667
+ fields,
668
+ run: async (ctx) => {
669
+ const creds = Object.fromEntries(Object.entries(spec.credentialEnv).map(([k, v]) => [k, env[v]]));
670
+ await ctx.client.request('PUT', `/v1/payout-connections/${encodeURIComponent(spec.provider)}`, { ...creds, ...(spec.env ? { env: spec.env } : {}) });
671
+ return [];
672
+ },
673
+ });
674
+ }
675
+ // Payout rails are org-wide: pruned only with no program scope.
676
+ if (pruning('payouts') && !scope) {
677
+ for (const c of conns) {
678
+ if (config.payouts.some((s) => s.provider === c.provider))
679
+ continue;
680
+ changes.push(remove('payout', `payout "${c.provider}"`, `/v1/payout-connections/${encodeURIComponent(c.provider)}`));
681
+ }
682
+ }
683
+ }
684
+ // Email (R-11): PUT /v1/email/settings merges what it's sent; the key (BYOK) from apiKeyEnv, sent while none is stored or the provider changes.
685
+ if (config.email) {
686
+ const { apiKeyEnv, ...want } = config.email;
687
+ const cur = await client.request('GET', '/v1/email/settings');
688
+ const fields = Object.entries(want).filter(([k, v]) => !same(cur[k], v)).map(([k, v]) => [k, cur[k], v]);
689
+ const sendKey = Boolean(apiKeyEnv) && (!cur.hasApiKey || (want.provider !== undefined && want.provider !== cur.provider));
690
+ if (sendKey) {
691
+ if (!env[apiKeyEnv])
692
+ throw new ConfigError(`email: environment variable ${apiKeyEnv} is not set`);
693
+ fields.push(['apiKey', cur.hasApiKey ? '(set)' : '(none)', `(from $${apiKeyEnv})`]);
694
+ }
695
+ changes.push({
696
+ action: fields.length ? 'update' : 'noop',
697
+ kind: 'email',
698
+ label: 'email settings',
699
+ fields,
700
+ run: async (ctx) => {
701
+ const body = Object.fromEntries(fields.filter(([k]) => k !== 'apiKey').map(([k, , v]) => [k, v]));
702
+ await ctx.client.request('PUT', '/v1/email/settings', { ...body, ...(sendKey ? { apiKey: env[apiKeyEnv] } : {}) });
703
+ return [];
704
+ },
705
+ });
706
+ }
707
+ // Org tracking consent (R-11): the PUT replaces the setting, so it sends the live one with the file's keys applied.
708
+ if (config.trackingConsent) {
709
+ const cur = await client.request('GET', '/v1/org/tracking-consent');
710
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- read-only parts of the GET
711
+ const { configured: _c, adapters: _a, ...live } = cur;
712
+ const fields = Object.entries(config.trackingConsent).filter(([k, v]) => !same(live[k], v)).map(([k, v]) => [k, live[k], v]);
713
+ changes.push({
714
+ action: fields.length ? 'update' : 'noop',
715
+ kind: 'trackingConsent',
716
+ label: 'org trackingConsent',
717
+ fields,
718
+ run: async (ctx) => {
719
+ await ctx.client.request('PUT', '/v1/org/tracking-consent', { ...live, ...config.trackingConsent });
720
+ return [];
721
+ },
722
+ });
723
+ }
724
+ // Hosted pages (R-11): consent banner and support chat on the pages Referalli hosts. The PUT replaces all three parts.
725
+ if (config.hostedPages) {
726
+ const cur = await client.request('GET', '/v1/org/hosted-pages');
727
+ const hp = config.hostedPages;
728
+ const chatSpec = hp.chat;
729
+ const { identitySecretEnv, ...chatWant } = chatSpec ?? {};
730
+ const liveChat = cur.chat ? { adapter: cur.chat.adapter, config: cur.chat.config } : null;
731
+ const want = {
732
+ consent: hp.consent !== undefined ? { config: {}, ...hp.consent } : { adapter: cur.consent.adapter, config: cur.consent.config },
733
+ chat: chatSpec === undefined ? liveChat : chatSpec === null ? null : { config: {}, ...chatWant },
734
+ customOrigins: hp.customOrigins ?? cur.customOrigins,
735
+ };
736
+ const now = { consent: { adapter: cur.consent.adapter, config: cur.consent.config }, chat: liveChat, customOrigins: cur.customOrigins };
737
+ const fields = Object.keys(want).filter((k) => !same(now[k], want[k])).map((k) => [k, now[k], want[k]]);
738
+ // The secret goes with the chat it belongs to: while none is stored, or when the chat vendor changes (which drops it).
739
+ const sendSecret = Boolean(identitySecretEnv) && Boolean(chatSpec) && (!cur.chat?.hasIdentitySecret || cur.chat.adapter !== chatWant.adapter);
740
+ if (sendSecret) {
741
+ if (!env[identitySecretEnv])
742
+ throw new ConfigError(`hostedPages.chat: environment variable ${identitySecretEnv} is not set`);
743
+ fields.push(['chat.identitySecret', cur.chat?.hasIdentitySecret ? '(set)' : '(none)', `(from $${identitySecretEnv})`]);
744
+ }
745
+ changes.push({
746
+ action: fields.length ? 'update' : 'noop',
747
+ kind: 'hostedPages',
748
+ label: 'org hostedPages',
749
+ fields,
750
+ run: async (ctx) => {
751
+ const chat = want.chat ? { ...want.chat, ...(sendSecret ? { identitySecret: env[identitySecretEnv] } : {}) } : null;
752
+ await ctx.client.request('PUT', '/v1/org/hosted-pages', { consent: want.consent, chat, customOrigins: want.customOrigins });
753
+ return [];
754
+ },
755
+ });
468
756
  }
469
757
  return { changes, ids };
470
758
  }
759
+ /** Edit distance, for "did you mean". */
760
+ function distance(a, b) {
761
+ let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
762
+ for (let i = 1; i <= a.length; i++) {
763
+ const cur = [i];
764
+ for (let j = 1; j <= b.length; j++)
765
+ cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
766
+ prev = cur;
767
+ }
768
+ return prev[b.length];
769
+ }
770
+ /** R-19: a topic must be published, `*`, or `prefix.*` covering one; an unknown one would never be delivered. */
771
+ async function checkTopics(client, webhooks) {
772
+ if (!webhooks.some((w) => w.topics?.length))
773
+ return;
774
+ let topics;
775
+ try {
776
+ topics = (await client.request('GET', '/v1/cli/topics')).topics;
777
+ }
778
+ catch {
779
+ return; // an API without the list: POST /v1/webhook-endpoints checks them
780
+ }
781
+ const valid = (t) => t === '*' || topics.includes(t) || (t.endsWith('.*') && topics.some((n) => n.startsWith(t.slice(0, -1))));
782
+ for (const w of webhooks) {
783
+ const bad = (w.topics ?? []).find((t) => !valid(t));
784
+ if (!bad)
785
+ continue;
786
+ const best = [...topics].sort((x, y) => distance(bad, x) - distance(bad, y))[0];
787
+ const hint = best && distance(bad, best) <= Math.max(3, Math.floor(bad.length / 3)) ? ` (did you mean ${best}?)` : '';
788
+ throw new ConfigError(`webhook ${w.url}: unknown topic "${bad}"${hint}; topics are *, <prefix>.* or one of: ${topics.join(', ')}`);
789
+ }
790
+ }
471
791
  // --- output ----------------------------------------------------------------------
472
792
  const show = (v) => (v === undefined ? '(unset)' : JSON.stringify(v));
473
- const SIGN = { create: '+ create', update: '~ update', noop: '= unchanged' };
793
+ const SIGN = { create: '+ create', update: '~ update', delete: '- delete', noop: '= unchanged' };
474
794
  /** Plan lines. Values come from the file and the API's public fields: no secret is ever in them. */
475
795
  export function formatPlan(changes) {
476
796
  const lines = [];
@@ -480,7 +800,8 @@ export function formatPlan(changes) {
480
800
  lines.push(c.action === 'create' ? ` ${k}: ${show(to)}` : ` ${k}: ${show(from)} → ${show(to)}`);
481
801
  }
482
802
  const n = (a) => changes.filter((c) => c.action === a).length;
483
- lines.push(`Plan: ${n('create')} to create, ${n('update')} to update, ${n('noop')} unchanged.`);
803
+ const deletes = n('delete') ? `${n('delete')} to delete, ` : '';
804
+ lines.push(`Plan: ${n('create')} to create, ${n('update')} to update, ${deletes}${n('noop')} unchanged.`);
484
805
  return lines;
485
806
  }
486
807
  /**
@@ -489,10 +810,11 @@ export function formatPlan(changes) {
489
810
  */
490
811
  export async function runApply(io, client, file, opts) {
491
812
  const config = parseConfig(readFileSync(file, 'utf8'), file);
492
- const { changes, ids } = await buildPlan(client, config, io.env);
813
+ const { changes, ids } = await buildPlan(client, config, io.env, { prune: opts.prune });
493
814
  for (const line of formatPlan(changes))
494
815
  io.out(line);
495
- const pending = changes.filter((c) => c.action !== 'noop');
816
+ // Deletes last: whatever the file adds is in place before anything goes.
817
+ const pending = [...changes.filter((c) => c.action !== 'noop' && c.action !== 'delete'), ...changes.filter((c) => c.action === 'delete')];
496
818
  if (opts.check) {
497
819
  if (pending.length)
498
820
  io.out('Drift: the account does not match the file.');
@@ -508,7 +830,7 @@ export async function runApply(io, client, file, opts) {
508
830
  try {
509
831
  for (const c of pending) {
510
832
  secrets.push(...(await c.run(ctx)));
511
- io.out(`${c.action === 'create' ? 'Created' : 'Updated'} ${c.label}`);
833
+ io.out(`${c.action === 'create' ? 'Created' : c.action === 'delete' ? 'Deleted' : 'Updated'} ${c.label}`);
512
834
  }
513
835
  }
514
836
  finally {
@@ -38,7 +38,7 @@ export declare function logsTail(io: Io, flags: Flags): Promise<number>;
38
38
  */
39
39
  export declare function keys(io: Io, sub: string | undefined, arg: string | undefined, flags: Flags): Promise<number>;
40
40
  export declare function api(io: Io, method: string | undefined, path: string | undefined, flags: Flags): Promise<number>;
41
- /** `referalli plan <file>` / `referalli apply <file> [--plan] [--check] [--secret-file PATH]`. */
41
+ /** `referalli plan <file> [--prune]` / `referalli apply <file> [--plan] [--check] [--prune] [--secret-file PATH]`. */
42
42
  export declare function apply(io: Io, file: string | undefined, flags: Flags, planOnly: boolean): Promise<number>;
43
43
  /** `referalli doctor [--program <id>] [--json]`, or `--scan <dir> [--strict]`, which needs no key. */
44
44
  export declare function doctor(io: Io, flags: Flags): Promise<number>;
@@ -48,6 +48,8 @@ export declare function doctor(io: Io, flags: Flags): Promise<number>;
48
48
  * partner list has the one that applies (program's, else the partner's) but no enrolled date.
49
49
  */
50
50
  export declare function partners(io: Io, sub: string | undefined, flags: Flags): Promise<number>;
51
+ /** `billing owner set <accountRef> <customerRef>`: the user whose referral an organization's payments earn for. */
52
+ export declare function billing(io: Io, args: string[]): Promise<number>;
51
53
  /**
52
54
  * `referalli env pull [--mode live|test]`: one mode's public ids as .env lines
53
55
  * on stdout (`> .env.test`). Default: the key's mode. Program ids differ per