@referalli/cli 0.4.2 → 0.4.4

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/CHANGELOG.md CHANGED
@@ -5,6 +5,18 @@ All notable changes to `@referalli/cli` are recorded here. The format follows
5
5
  [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Before 1.0, a minor
6
6
  bump may include breaking changes; they are called out under **Changed**.
7
7
 
8
+ ## 0.4.4 - 2026-11-05
9
+
10
+ - `doctor --scan <dir> [--strict]`: finds the old names `REFERALLY_*`, `referally-version`, `referally_ctx`, `x-referally-*` and `@referally/*` in a source tree, each with file:line, replacement and removal date (or "no removal date set"). Warnings exit 0; `--strict` exits 1 on any. Needs no key.
11
+ - `REFERALLY_API_KEY`, `REFERALLY_API_URL`, `REFERALLY_CONFIG_DIR` and the old tracking token names are read when the new name isn't set, with a one-line notice.
12
+ - `plan`/`apply` manage `authConnections`: matched by provider + `instanceId`/`appId` + `program`, none deleted. The new signing secret is printed once and never written to a file. `--check` exits 2 on drift too.
13
+ - `doctor` with a program-scoped key: the auth and tracking checks it can't run say so, with the key scope that would run them.
14
+ - New `partners list --program <id> [--since 7d|ISO] [--json]`: every approved enrollment with its `externalRef`.
15
+
16
+ ## 0.4.3 - 2026-11-04
17
+
18
+ - `doctor` fails an auth connection whose last refused call (`lastError`) is newer than its last sign-up, with the error. It also warns when the org's tracking consent mode is `none` (live keys).
19
+
8
20
  ## 0.4.2 - 2026-11-03
9
21
 
10
22
  - Fixed: `plan`/`apply` with a `billingConnections:` list failed with `conns.filter is not a function` (the connections list now arrives in the list envelope).
@@ -2,7 +2,7 @@ import type { Client } from './client.js';
2
2
  /**
3
3
  * `referalli plan|apply <file>`: make the account match a declarative file.
4
4
  * Every resource is matched by a stable key (program slug, webhook url, API key
5
- * name + owner, billing connection name); creates carry an Idempotency-Key derived from that key and the
5
+ * name + owner, billing connection name, auth connection provider + instance + program); creates carry an Idempotency-Key derived from that key and the
6
6
  * request, so a retried apply never creates twice. Nothing missing from the file
7
7
  * is ever deleted, rotated or revoked.
8
8
  */
@@ -34,11 +34,18 @@ interface BillingConnectionSpec extends Obj {
34
34
  status?: 'active' | 'paused';
35
35
  stripeKeyEnv?: string;
36
36
  }
37
+ interface AuthConnectionSpec extends Obj {
38
+ provider: string;
39
+ program: string;
40
+ instanceId?: string;
41
+ appId?: string;
42
+ }
37
43
  export interface ApplyConfig {
38
44
  programs: ProgramSpec[];
39
45
  webhooks: WebhookSpec[];
40
46
  apiKeys: ApiKeySpec[];
41
47
  billingConnections: BillingConnectionSpec[];
48
+ authConnections: AuthConnectionSpec[];
42
49
  }
43
50
  /** Parse and check a referalli.yaml (JSON is YAML too). */
44
51
  export declare function parseConfig(text: string, file?: string): ApplyConfig;
@@ -55,7 +62,13 @@ interface RunCtx {
55
62
  client: Client;
56
63
  /** Program slug → id, filled in as programs are created. */
57
64
  ids: Map<string, string>;
65
+ /** Printed at once, never to --secret-file. */
66
+ out(line: string): void;
58
67
  }
68
+ /** Every row of a list endpoint: a plain array, or the 2026-11-01 list envelope followed page by page. */
69
+ export declare function listAll<T extends {
70
+ id: string;
71
+ }>(client: Client, path: string, headers?: Record<string, string>): Promise<T[]>;
59
72
  /** Compare the file with the account; nothing is written. */
60
73
  export declare function buildPlan(client: Client, config: ApplyConfig, env: NodeJS.ProcessEnv): Promise<{
61
74
  changes: Change[];
package/dist/src/apply.js CHANGED
@@ -4,7 +4,7 @@ import { load } from 'js-yaml';
4
4
  /**
5
5
  * `referalli plan|apply <file>`: make the account match a declarative file.
6
6
  * Every resource is matched by a stable key (program slug, webhook url, API key
7
- * name + owner, billing connection name); creates carry an Idempotency-Key derived from that key and the
7
+ * name + owner, billing connection name, auth connection provider + instance + program); creates carry an Idempotency-Key derived from that key and the
8
8
  * request, so a retried apply never creates twice. Nothing missing from the file
9
9
  * is ever deleted, rotated or revoked.
10
10
  */
@@ -21,6 +21,12 @@ const STRIPE_KEYS = ['enabled', 'referrerMatch', 'metadataKey', 'refereeRewards'
21
21
  const WEBHOOK_KEYS = ['url', 'topics', 'programs', 'status', 'alertContacts'];
22
22
  const API_KEY_KEYS = ['name', 'owner', 'mode', 'scopes', 'expiresInDays', 'programs', 'apiVersion'];
23
23
  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`.
25
+ const AUTH_FIELDS = ['name', 'status', 'autoEnrollUsers', 'destinationUrl', 'resolveBillingCustomers', 'signatureVersion', 'allowedOrigins'];
26
+ const AUTH_KEYS = ['provider', 'program', 'instanceId', 'appId', ...AUTH_FIELDS];
27
+ // POST ignores these: they go in a PATCH right after the create.
28
+ const AUTH_PATCH_ONLY = ['status', 'resolveBillingCustomers', 'signatureVersion'];
29
+ const AUTH_PROTOCOL = ['atlas', 'custom'];
24
30
  const SECRET_KEYS = ['secretKey', 'stripeKey', 'webhookSecret', 'credentials'];
25
31
  // What the API stores when a rule leaves these out (packages/commissions ruleConfigSchema).
26
32
  const RULE_DEFAULTS = { appliesTo: 'gross', recurring: { type: 'lifetime' }, holdDays: 30, rounding: 'half_even', overrides: [] };
@@ -44,6 +50,7 @@ const list = (v, where) => {
44
50
  throw new ConfigError(`${where}: expected a list`);
45
51
  return v;
46
52
  };
53
+ const authKey = (a) => [a.provider, a.instanceId ?? a.appId, a.program].filter(Boolean).join(' ');
47
54
  /** Parse and check a referalli.yaml (JSON is YAML too). */
48
55
  export function parseConfig(text, file = 'config') {
49
56
  let doc;
@@ -53,7 +60,7 @@ export function parseConfig(text, file = 'config') {
53
60
  catch (err) {
54
61
  throw new ConfigError(`${file}: ${err.message}`);
55
62
  }
56
- checkKeys(doc ?? {}, ['programs', 'webhooks', 'apiKeys', 'billingConnections'], file);
63
+ checkKeys(doc ?? {}, ['programs', 'webhooks', 'apiKeys', 'billingConnections', 'authConnections'], file);
57
64
  const d = (doc ?? {});
58
65
  const programs = list(d.programs, 'programs').map((p, i) => {
59
66
  const where = `programs[${i}]`;
@@ -103,7 +110,32 @@ export function parseConfig(text, file = 'config') {
103
110
  const dupName = names.find((s, i) => names.indexOf(s) !== i);
104
111
  if (dupName)
105
112
  throw new ConfigError(`billingConnections: name "${dupName}" is listed twice`);
106
- return { programs, webhooks, apiKeys, billingConnections };
113
+ const authConnections = list(d.authConnections, 'authConnections').map((a, i) => {
114
+ const where = `authConnections[${i}]`;
115
+ checkKeys(a, AUTH_KEYS, where, 'provider');
116
+ if (typeof a.program !== 'string' || !a.program)
117
+ throw new ConfigError(`${where}: "program" (a slug) is required`);
118
+ for (const k of ['instanceId', 'appId', 'name']) {
119
+ if (a[k] !== undefined && (typeof a[k] !== 'string' || !a[k]))
120
+ throw new ConfigError(`${where}.${k}: expected a non-empty string`);
121
+ }
122
+ // The API drops these for other providers, so such a row could never match and each apply would create another.
123
+ if (!AUTH_PROTOCOL.includes(a.provider) && (a.instanceId || a.appId || a.signatureVersion)) {
124
+ throw new ConfigError(`${where}: instanceId, appId and signatureVersion are for provider atlas or custom`);
125
+ }
126
+ if (a.provider === 'atlas' && !a.instanceId === !a.appId)
127
+ throw new ConfigError(`${where}: atlas needs exactly one of instanceId or appId`);
128
+ if (a.status !== undefined && a.status !== 'active' && a.status !== 'paused')
129
+ throw new ConfigError(`${where}.status: active or paused`);
130
+ if (a.allowedOrigins !== undefined && !Array.isArray(a.allowedOrigins))
131
+ throw new ConfigError(`${where}.allowedOrigins: expected a list`);
132
+ return a;
133
+ });
134
+ const authKeys = authConnections.map(authKey);
135
+ const dupAuth = authKeys.find((s, i) => authKeys.indexOf(s) !== i);
136
+ if (dupAuth)
137
+ throw new ConfigError(`authConnections: "${dupAuth}" is listed twice`);
138
+ return { programs, webhooks, apiKeys, billingConnections, authConnections };
107
139
  }
108
140
  /** Key-order-insensitive JSON, for comparing values. */
109
141
  const canon = (v) => JSON.stringify(v, (_k, x) => (isObj(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => a.localeCompare(b))) : x));
@@ -113,11 +145,11 @@ const sorted = (v) => [...(v ?? [])].sort();
113
145
  const idemKey = (kind, key, body) => `referalli-apply-${kind}-${createHash('sha256').update(`${key}\n${canon(body)}`).digest('hex').slice(0, 40)}`;
114
146
  const create = (client, path, kind, key, body) => client.request('POST', path, body, { headers: { 'idempotency-key': idemKey(kind, key, body) } });
115
147
  /** Every row of a list endpoint: a plain array, or the 2026-11-01 list envelope followed page by page. */
116
- async function listAll(client, path) {
148
+ export async function listAll(client, path, headers) {
117
149
  const out = [];
118
150
  let url = path;
119
151
  for (;;) {
120
- const res = await client.request('GET', url);
152
+ const res = await client.request('GET', url, undefined, { headers });
121
153
  if (Array.isArray(res))
122
154
  return res;
123
155
  out.push(...res.data);
@@ -381,6 +413,59 @@ export async function buildPlan(client, config, env) {
381
413
  });
382
414
  }
383
415
  }
416
+ if (config.authConnections.length) {
417
+ const conns = await listAll(client, '/v1/auth/connections');
418
+ for (const spec of config.authConnections) {
419
+ const label = `authConnection "${authKey(spec)}"`;
420
+ checkRefs([spec.program], label);
421
+ const matches = conns.filter((c) => c.provider === spec.provider && c.programId === ids.get(spec.program) && (c.instanceId ?? null) === (spec.instanceId ?? null) && (c.appId ?? null) === (spec.appId ?? null));
422
+ if (matches.length > 1)
423
+ 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
+ const cur = matches[0];
425
+ const want = {};
426
+ for (const k of AUTH_FIELDS)
427
+ if (spec[k] !== undefined)
428
+ want[k] = k === 'allowedOrigins' ? sorted(spec[k]) : spec[k];
429
+ if (!cur) {
430
+ const { provider, program, instanceId, appId } = spec;
431
+ changes.push({
432
+ action: 'create',
433
+ kind: 'authConnection',
434
+ label,
435
+ fields: Object.entries({ provider, program, instanceId, appId, ...want }).filter(([, v]) => v !== undefined).map(([k, v]) => [k, undefined, v]),
436
+ run: async (ctx) => {
437
+ const onCreate = Object.entries(want).filter(([k, v]) => !AUTH_PATCH_ONLY.includes(k) && v !== null);
438
+ const made = await create(ctx.client, '/v1/auth/connections', 'auth', authKey(spec), {
439
+ provider,
440
+ programId: programIdsFor(ctx, [program])[0],
441
+ ...(instanceId ? { instanceId } : {}),
442
+ ...(appId ? { appId } : {}),
443
+ ...Object.fromEntries(onCreate),
444
+ });
445
+ // Printed before the PATCH: if that fails the secret still reached the user. It can't be fetched again.
446
+ 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}`);
447
+ const after = Object.entries(want).filter(([k]) => AUTH_PATCH_ONLY.includes(k));
448
+ if (after.length)
449
+ await ctx.client.request('PATCH', `/v1/auth/connections/${made.id}`, Object.fromEntries(after));
450
+ return [];
451
+ },
452
+ });
453
+ continue;
454
+ }
455
+ const now = (k) => (k === 'allowedOrigins' ? sorted(cur.allowedOrigins) : cur[k]);
456
+ const fields = Object.keys(want).filter((k) => !same(now(k), want[k])).map((k) => [k, now(k), want[k]]);
457
+ changes.push({
458
+ action: fields.length ? 'update' : 'noop',
459
+ kind: 'authConnection',
460
+ label,
461
+ fields,
462
+ run: async (ctx) => {
463
+ await ctx.client.request('PATCH', `/v1/auth/connections/${cur.id}`, Object.fromEntries(fields.map(([k, , v]) => [k, v])));
464
+ return [];
465
+ },
466
+ });
467
+ }
468
+ }
384
469
  return { changes, ids };
385
470
  }
386
471
  // --- output ----------------------------------------------------------------------
@@ -418,7 +503,7 @@ export async function runApply(io, client, file, opts) {
418
503
  // Checked first: a secret file that can't be written after the creates would lose the secrets.
419
504
  if (opts.secretFile && existsSync(opts.secretFile))
420
505
  throw new ConfigError(`--secret-file ${opts.secretFile} already exists; pick a new path`);
421
- const ctx = { client, ids };
506
+ const ctx = { client, ids, out: (line) => io.out(line) };
422
507
  const secrets = [];
423
508
  try {
424
509
  for (const c of pending) {
@@ -40,8 +40,14 @@ export declare function keys(io: Io, sub: string | undefined, arg: string | unde
40
40
  export declare function api(io: Io, method: string | undefined, path: string | undefined, flags: Flags): Promise<number>;
41
41
  /** `referalli plan <file>` / `referalli apply <file> [--plan] [--check] [--secret-file PATH]`. */
42
42
  export declare function apply(io: Io, file: string | undefined, flags: Flags, planOnly: boolean): Promise<number>;
43
- /** `referalli doctor [--program <id>] [--json]`. */
44
- export declare const doctor: (io: Io, flags: Flags) => Promise<number>;
43
+ /** `referalli doctor [--program <id>] [--json]`, or `--scan <dir> [--strict]`, which needs no key. */
44
+ export declare function doctor(io: Io, flags: Flags): Promise<number>;
45
+ /**
46
+ * `referalli partners list --program <id> [--since 7d|ISO] [--json]`: approved enrollments.
47
+ * The enrollment has the enrolled date but only the program's own externalRef; the
48
+ * partner list has the one that applies (program's, else the partner's) but no enrolled date.
49
+ */
50
+ export declare function partners(io: Io, sub: string | undefined, flags: Flags): Promise<number>;
45
51
  /**
46
52
  * `referalli env pull [--mode live|test]`: one mode's public ids as .env lines
47
53
  * on stdout (`> .env.test`). Default: the key's mode. Program ids differ per
@@ -1,8 +1,9 @@
1
1
  import { chmodSync, writeFileSync } from 'node:fs';
2
2
  import { hostname } from 'node:os';
3
- import { ConfigError, runApply } from './apply.js';
3
+ import { ConfigError, listAll, runApply } from './apply.js';
4
4
  import { ApiError, createClient } from './client.js';
5
5
  import { runDoctor } from './doctor.js';
6
+ import { runScan } from './scan.js';
6
7
  import { DEFAULT_BASE_URL, readConfig, removeConfig, writeConfig } from './config.js';
7
8
  /** A user-facing failure: printed without a stack trace, exit code 1. */
8
9
  export class CliError extends Error {
@@ -436,8 +437,56 @@ export async function apply(io, file, flags, planOnly) {
436
437
  throw err;
437
438
  }
438
439
  }
439
- /** `referalli doctor [--program <id>] [--json]`. */
440
- export const doctor = (io, flags) => runDoctor(io, signedIn(io).client, flags);
440
+ /** `referalli doctor [--program <id>] [--json]`, or `--scan <dir> [--strict]`, which needs no key. */
441
+ export async function doctor(io, flags) {
442
+ if (flags.strict && typeof flags.scan !== 'string')
443
+ throw new CliError('--strict goes with --scan <dir>');
444
+ if (typeof flags.scan !== 'string')
445
+ return runDoctor(io, signedIn(io).client, flags);
446
+ try {
447
+ return runScan((l) => io.out(l), (l) => io.err(l), flags.scan, { strict: flags.strict === true, json: flags.json === true });
448
+ }
449
+ catch (err) {
450
+ throw new CliError(err.message);
451
+ }
452
+ }
453
+ // --- partners ----------------------------------------------------------------------
454
+ /**
455
+ * `referalli partners list --program <id> [--since 7d|ISO] [--json]`: approved enrollments.
456
+ * The enrollment has the enrolled date but only the program's own externalRef; the
457
+ * partner list has the one that applies (program's, else the partner's) but no enrolled date.
458
+ */
459
+ export async function partners(io, sub, flags) {
460
+ if (sub !== 'list' || typeof flags.program !== 'string')
461
+ throw new CliError('Usage: referalli partners list --program <id> [--since 7d|ISO] [--json]');
462
+ const { client } = signedIn(io);
463
+ const program = encodeURIComponent(flags.program);
464
+ const q = new URLSearchParams({ status: 'approved' });
465
+ if (typeof flags.since === 'string')
466
+ q.set('created[gte]', parseSince(flags.since, new Date()).toISOString());
467
+ // A key pinned to the 2026-10-21 version gets capped arrays: ask for the paged lists.
468
+ const headers = { 'referalli-version': '2026-11-01' };
469
+ const [enrollments, people] = await Promise.all([
470
+ listAll(client, `/v1/programs/${program}/enrollments?${q}`, headers),
471
+ listAll(client, `/v1/partners?programId=${program}&includeArchived=true`, headers),
472
+ ]);
473
+ const byId = new Map(people.map((p) => [p.id, p]));
474
+ const rows = enrollments.map((e) => ({
475
+ partnerId: e.partnerId,
476
+ externalRef: e.externalRef ?? byId.get(e.partnerId)?.externalRef ?? null,
477
+ email: e.partnerEmail,
478
+ name: e.partnerName,
479
+ status: byId.get(e.partnerId)?.status ?? null,
480
+ enrolledAt: e.createdAt,
481
+ }));
482
+ if (flags.json)
483
+ io.out(JSON.stringify(rows, null, 2));
484
+ else
485
+ for (const r of rows)
486
+ io.out([r.partnerId, r.externalRef ?? '-', r.email, r.status ?? '-', `enrolled ${r.enrolledAt}`].join(' '));
487
+ io.err(`${rows.length} enrolled partner(s).`);
488
+ return 0;
489
+ }
441
490
  /**
442
491
  * `referalli env pull [--mode live|test]`: one mode's public ids as .env lines
443
492
  * on stdout (`> .env.test`). Default: the key's mode. Program ids differ per
@@ -8,6 +8,11 @@ export interface CliConfig {
8
8
  export declare const DEFAULT_BASE_URL = "https://referalli.com";
9
9
  export declare const configDir: (env?: NodeJS.ProcessEnv) => string;
10
10
  export declare const configPath: (env?: NodeJS.ProcessEnv) => string;
11
+ /** The env with pre-rename names filled in under the new ones (a new name wins), and which were used. */
12
+ export declare function withLegacyEnv(env: NodeJS.ProcessEnv): {
13
+ env: NodeJS.ProcessEnv;
14
+ notice: string | null;
15
+ };
11
16
  export declare function readConfig(env?: NodeJS.ProcessEnv): CliConfig | null;
12
17
  export declare function writeConfig(config: CliConfig, env?: NodeJS.ProcessEnv): string;
13
18
  export declare function removeConfig(env?: NodeJS.ProcessEnv): boolean;
@@ -4,6 +4,16 @@ import { join } from 'node:path';
4
4
  export const DEFAULT_BASE_URL = 'https://referalli.com';
5
5
  export const configDir = (env = process.env) => env.REFERALLI_CONFIG_DIR ?? join(env.XDG_CONFIG_HOME ?? join(homedir(), '.config'), 'referalli');
6
6
  export const configPath = (env = process.env) => join(configDir(env), 'cli.json');
7
+ const READ_ENV = ['REFERALLI_API_KEY', 'REFERALLI_API_URL', 'REFERALLI_CONFIG_DIR', 'REFERALLI_TRACKING_TOKEN', 'NEXT_PUBLIC_REFERALLI_TRACKING_TOKEN'];
8
+ const oldName = (name) => name.replace('REFERALLI_', 'REFERALLY_');
9
+ /** The env with pre-rename names filled in under the new ones (a new name wins), and which were used. */
10
+ export function withLegacyEnv(env) {
11
+ const used = READ_ENV.filter((name) => !env[name] && env[oldName(name)]);
12
+ return {
13
+ env: { ...env, ...Object.fromEntries(used.map((name) => [name, env[oldName(name)]])) },
14
+ notice: used.length ? `Notice: read ${used.map((name) => `${oldName(name)} as ${name}`).join(', ')}; rename it (no removal date set).` : null,
15
+ };
16
+ }
7
17
  export function readConfig(env = process.env) {
8
18
  // Env wins, so CI can run the CLI without a saved login.
9
19
  if (env.REFERALLI_API_KEY) {
@@ -7,5 +7,6 @@ export interface Check {
7
7
  message: string;
8
8
  fix?: string;
9
9
  }
10
+ export declare function printChecks(out: (line: string) => void, checks: Check[], json: unknown): void;
10
11
  /** `referalli doctor [--program <id>] [--json]`: read-only health checks. Exit 1 when any check fails. */
11
12
  export declare function runDoctor(io: Io, client: Client, flags: Flags, now?: Date): Promise<number>;
@@ -36,7 +36,7 @@ async function keyCheck(client, now) {
36
36
  out.push({
37
37
  id: 'key.programs',
38
38
  status: 'warn',
39
- message: `the key is limited to programs ${k.programIds.join(', ')}: other programs and org-wide setup aren't visible to it`,
39
+ message: `the key is limited to programs ${k.programIds.join(', ')}: webhook and billing checks see only these programs, and org-wide checks are skipped (listed below)`,
40
40
  fix: 'run doctor with an org-wide key to check everything',
41
41
  });
42
42
  }
@@ -100,6 +100,10 @@ async function authChecks(client, now) {
100
100
  if (c.tokenVerification && c.allowedOrigins.length === 0) {
101
101
  return { id, status: 'warn', message: `${label} verifies tokens but has no allowedOrigins: the widget session refuses browsers`, fix: `PATCH /v1/auth/connections/${c.id} {"allowedOrigins":["https://your.app"]}` };
102
102
  }
103
+ // A refusal newer than the last sign-up: the platform is calling, and its calls are failing.
104
+ if (c.lastError && (!c.lastSignupAt || new Date(c.lastError.at) > new Date(c.lastSignupAt))) {
105
+ return { id, status: 'fail', message: `${label} refused its last call (${c.lastError.at}): ${c.lastError.code}: ${c.lastError.message}`, fix: `fix the caller's request body, then retry its failed calls (Atlas: POST /v1/instance/referrals/calls/retry_failed)` };
106
+ }
103
107
  // Protocol connections (Atlas, custom) can't be pinged with an API key: when it last filed a sign-up says it's wired.
104
108
  // undefined: an API from before lastSignupAt, nothing to say.
105
109
  if (c.lastSignupAt === null) {
@@ -130,6 +134,15 @@ async function trackingCheck(client, env) {
130
134
  throw err;
131
135
  out.push({ id: 'tracking', status: 'fail', message: `tracking token ${org.trackingToken} is unknown to /t/…/config.json`, fix: '/settings' });
132
136
  }
137
+ // Consent mode `none` (orgs from before consent support start there): aff.js stores the referral before the visitor chooses.
138
+ if (org.livemode !== false) {
139
+ out.push(...(await guard('tracking.consent', '/settings → Install', async () => {
140
+ const c = await client.request('GET', '/v1/org/tracking-consent');
141
+ return c.mode === 'none'
142
+ ? [{ id: 'tracking.consent', status: 'warn', message: "tracking consent is 'none': aff.js stores the referral before the visitor chooses", fix: `PUT /v1/org/tracking-consent {"mode":"auto"} (or /settings → Install)` }]
143
+ : [{ id: 'tracking.consent', status: 'ok', message: `tracking consent: ${c.mode}` }];
144
+ })));
145
+ }
133
146
  // The token the product is configured with (run doctor with the app's env) must be this mode's.
134
147
  const name = env.REFERALLI_TRACKING_TOKEN ? 'REFERALLI_TRACKING_TOKEN' : env.NEXT_PUBLIC_REFERALLI_TRACKING_TOKEN ? 'NEXT_PUBLIC_REFERALLI_TRACKING_TOKEN' : null;
135
148
  if (!name)
@@ -153,25 +166,49 @@ async function trackingCheck(client, env) {
153
166
  return [...out, ...tokens];
154
167
  }
155
168
  const MARK = { ok: '✓', warn: '⚠', fail: '✗' };
169
+ export function printChecks(out, checks, json) {
170
+ if (json) {
171
+ out(JSON.stringify({ checks }, null, 2));
172
+ return;
173
+ }
174
+ for (const c of checks) {
175
+ out(`${MARK[c.status]} ${c.id}: ${c.message}`);
176
+ if (c.fix && c.status !== 'ok')
177
+ out(` fix: ${c.fix}`);
178
+ }
179
+ }
180
+ // What a program-scoped key is refused (the API's programScopedAllows), and the scope an org-wide key needs instead.
181
+ const ORG_WIDE = {
182
+ auth: { what: 'auth connections, Atlas sign-ups', scope: 'integrations:read or connections:read' },
183
+ tracking: { what: 'tracking token, consent mode, configured token', scope: 'org:read' },
184
+ };
156
185
  /** `referalli doctor [--program <id>] [--json]`: read-only health checks. Exit 1 when any check fails. */
157
186
  export async function runDoctor(io, client, flags, now = new Date()) {
158
187
  const program = typeof flags.program === 'string' ? flags.program : undefined;
159
- const checks = (await Promise.all([
160
- guard('key', 'referalli login', () => keyCheck(client, now)),
161
- guard('programs', undefined, () => termsChecks(client, program)),
162
- guard('webhooks', undefined, () => webhookChecks(client)),
163
- guard('billing', undefined, () => billingChecks(client)),
164
- guard('auth', undefined, () => authChecks(client, now)),
165
- guard('tracking', undefined, () => trackingCheck(client, io.env)),
166
- ])).flat();
167
- if (flags.json)
168
- io.out(JSON.stringify({ checks }, null, 2));
169
- else {
170
- for (const c of checks) {
171
- io.out(`${MARK[c.status]} ${c.id}: ${c.message}`);
172
- if (c.fix && c.status !== 'ok')
173
- io.out(` fix: ${c.fix}`);
188
+ const key = await guard('key', 'referalli login', () => keyCheck(client, now));
189
+ const scoped = key.some((c) => c.id === 'key.programs');
190
+ // Asks the API rather than copying its allowlist: if it opens one of these to scoped keys, the check just runs.
191
+ const orgWide = (id, fn) => guard(id, undefined, async () => {
192
+ try {
193
+ return await fn();
174
194
  }
175
- }
195
+ catch (err) {
196
+ if (!scoped || !(err instanceof ApiError) || err.status !== 403)
197
+ throw err;
198
+ const { what, scope } = ORG_WIDE[id];
199
+ return [{ id, status: 'warn', message: `skipped, this program-scoped key can't read it (${what})`, fix: `run doctor with an org-wide key (no programs) with ${scope}; read or full also work` }];
200
+ }
201
+ });
202
+ const checks = [
203
+ ...key,
204
+ ...(await Promise.all([
205
+ guard('programs', undefined, () => termsChecks(client, program)),
206
+ guard('webhooks', undefined, () => webhookChecks(client)),
207
+ guard('billing', undefined, () => billingChecks(client)),
208
+ orgWide('auth', () => authChecks(client, now)),
209
+ orgWide('tracking', () => trackingCheck(client, io.env)),
210
+ ])).flat(),
211
+ ];
212
+ printChecks((l) => io.out(l), checks, flags.json);
176
213
  return checks.some((c) => c.status === 'fail') ? 1 : 0;
177
214
  }
@@ -3,6 +3,6 @@ export { readConfig, writeConfig, configPath, type CliConfig } from './config.js
3
3
  export { createClient, ApiError } from './client.js';
4
4
  export type { Io } from './commands.js';
5
5
  export { VERSION } from './version.js';
6
- export declare const HELP = "referalli: the Referalli command line\n\nUsage:\n referalli login [--key rk_\u2026] [--base-url URL] [--no-browser]\n referalli logout\n referalli whoami\n referalli listen [--forward-to URL] [--events topic,topic] [--max-events N]\n referalli trigger <topic> [--data JSON]\n referalli trigger --billing <event> --connection <id> [--data JSON] (test mode; e.g. payment.paid)\n referalli trigger --stripe <event> --connection <id> [--data JSON] (test mode)\n referalli events tail [--events topic,topic] [--since 1h|ISO] [--json] [--max N]\n referalli logs tail [--max N]\n referalli open [docs|dashboard|keys|webhooks|spec|status]\n referalli api <METHOD> <path> [--data JSON] [--secret-file PATH]\n referalli keys create --name NAME [--owner WHO] [--mode both|live|test] [--scopes full,\u2026] [--expires-days N]\n referalli keys list [--owner WHO] [--mode live|test]\n referalli keys revoke <key id> [--pair] [--cascade]\n referalli plan <referalli.yaml> [--check]\n referalli apply <referalli.yaml> [--plan] [--check] [--secret-file PATH]\n referalli doctor [--program <id>] [--json]\n referalli env pull [--mode live|test] (.env lines on stdout; default: the key's mode)\n\nEnvironment:\n REFERALLI_API_KEY use this key instead of the saved login\n REFERALLI_API_URL API base URL (default: the hosted API)\n REFERALLI_CONFIG_DIR where the login is saved (default ~/.config/referalli)\n REFERALLI_TRACKING_TOKEN doctor checks it is this mode's token (or NEXT_PUBLIC_REFERALLI_TRACKING_TOKEN)";
6
+ export declare const HELP = "referalli: the Referalli command line\n\nUsage:\n referalli login [--key rk_\u2026] [--base-url URL] [--no-browser]\n referalli logout\n referalli whoami\n referalli listen [--forward-to URL] [--events topic,topic] [--max-events N]\n referalli trigger <topic> [--data JSON]\n referalli trigger --billing <event> --connection <id> [--data JSON] (test mode; e.g. payment.paid)\n referalli trigger --stripe <event> --connection <id> [--data JSON] (test mode)\n referalli events tail [--events topic,topic] [--since 1h|ISO] [--json] [--max N]\n referalli logs tail [--max N]\n referalli open [docs|dashboard|keys|webhooks|spec|status]\n referalli api <METHOD> <path> [--data JSON] [--secret-file PATH]\n referalli keys create --name NAME [--owner WHO] [--mode both|live|test] [--scopes full,\u2026] [--expires-days N]\n referalli keys list [--owner WHO] [--mode live|test]\n referalli keys revoke <key id> [--pair] [--cascade]\n referalli plan <referalli.yaml> [--check]\n referalli apply <referalli.yaml> [--plan] [--check] [--secret-file PATH]\n referalli doctor [--program <id>] [--json]\n referalli doctor --scan <dir> [--strict] [--json] (old Referally names in a source tree; no key needed)\n referalli partners list --program <id> [--since 7d|ISO] [--json]\n referalli env pull [--mode live|test] (.env lines on stdout; default: the key's mode)\n\nEnvironment:\n REFERALLI_API_KEY use this key instead of the saved login\n REFERALLI_API_URL API base URL (default: the hosted API)\n REFERALLI_CONFIG_DIR where the login is saved (default ~/.config/referalli)\n REFERALLI_TRACKING_TOKEN doctor checks it is this mode's token (or NEXT_PUBLIC_REFERALLI_TRACKING_TOKEN)\n REFERALLY_* spellings of these still work, with a notice";
7
7
  /** Run one command; returns the process exit code. */
8
- export declare function runCli(argv: string[], io: Io): Promise<number>;
8
+ export declare function runCli(argv: string[], baseIo: Io): Promise<number>;
package/dist/src/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { parseArgs } from 'node:util';
2
2
  import { ApiError } from './client.js';
3
- import { api, apply, CliError, doctor, env, eventsTail, keys, login, listen, logout, logsTail, open, trigger, whoami } from './commands.js';
3
+ import { api, apply, CliError, doctor, env, eventsTail, keys, login, listen, logout, logsTail, open, partners, trigger, whoami } from './commands.js';
4
+ import { withLegacyEnv } from './config.js';
4
5
  import { VERSION } from './version.js';
5
6
  export { readConfig, writeConfig, configPath } from './config.js';
6
7
  export { createClient, ApiError } from './client.js';
@@ -25,15 +26,20 @@ Usage:
25
26
  referalli plan <referalli.yaml> [--check]
26
27
  referalli apply <referalli.yaml> [--plan] [--check] [--secret-file PATH]
27
28
  referalli doctor [--program <id>] [--json]
29
+ referalli doctor --scan <dir> [--strict] [--json] (old Referally names in a source tree; no key needed)
30
+ referalli partners list --program <id> [--since 7d|ISO] [--json]
28
31
  referalli env pull [--mode live|test] (.env lines on stdout; default: the key's mode)
29
32
 
30
33
  Environment:
31
34
  REFERALLI_API_KEY use this key instead of the saved login
32
35
  REFERALLI_API_URL API base URL (default: the hosted API)
33
36
  REFERALLI_CONFIG_DIR where the login is saved (default ~/.config/referalli)
34
- REFERALLI_TRACKING_TOKEN doctor checks it is this mode's token (or NEXT_PUBLIC_REFERALLI_TRACKING_TOKEN)`;
37
+ REFERALLI_TRACKING_TOKEN doctor checks it is this mode's token (or NEXT_PUBLIC_REFERALLI_TRACKING_TOKEN)
38
+ REFERALLY_* spellings of these still work, with a notice`;
35
39
  /** Run one command; returns the process exit code. */
36
- export async function runCli(argv, io) {
40
+ export async function runCli(argv, baseIo) {
41
+ const legacy = withLegacyEnv(baseIo.env);
42
+ const io = { ...baseIo, env: legacy.env };
37
43
  let parsed;
38
44
  try {
39
45
  parsed = parseArgs({
@@ -66,6 +72,8 @@ export async function runCli(argv, io) {
66
72
  plan: { type: 'boolean' },
67
73
  check: { type: 'boolean' },
68
74
  json: { type: 'boolean' },
75
+ scan: { type: 'string' },
76
+ strict: { type: 'boolean' },
69
77
  help: { type: 'boolean', short: 'h' },
70
78
  version: { type: 'boolean', short: 'v' },
71
79
  },
@@ -86,6 +94,8 @@ export async function runCli(argv, io) {
86
94
  io.out(HELP);
87
95
  return command || flags.help ? 0 : 2;
88
96
  }
97
+ if (legacy.notice)
98
+ io.err(legacy.notice);
89
99
  try {
90
100
  switch (command) {
91
101
  case 'login':
@@ -122,6 +132,8 @@ export async function runCli(argv, io) {
122
132
  return await doctor(io, flags);
123
133
  case 'env':
124
134
  return await env(io, rest[0], flags);
135
+ case 'partners':
136
+ return await partners(io, rest[0], flags);
125
137
  default:
126
138
  io.err(`Unknown command "${command}".`);
127
139
  io.err(HELP);
@@ -0,0 +1,5 @@
1
+ /** `referalli doctor --scan <dir> [--strict]`: old names in a source tree. Needs no key and calls no API. */
2
+ export declare function runScan(out: (line: string) => void, err: (line: string) => void, dir: string, opts: {
3
+ strict: boolean;
4
+ json: boolean;
5
+ }): number;
@@ -0,0 +1,71 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { printChecks } from './doctor.js';
4
+ const MAX_BYTES = 1024 * 1024;
5
+ const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', '.next']);
6
+ const LOCKFILE = /\.(lock|lockb)$|^(pnpm-lock\.yaml|package-lock\.json|npm-shrinkwrap\.json|go\.sum)$/;
7
+ const NO_DATE = 'no removal date set';
8
+ const PUBLISHED = new Set(['cli', 'express', 'mcp', 'next', 'react', 'react-native']);
9
+ const packageName = (old) => {
10
+ const name = old.slice('@referally/'.length);
11
+ if (name === 'sdk-js')
12
+ return 'referalli';
13
+ return PUBLISHED.has(name) ? `@referalli/${name}` : 'no published replacement';
14
+ };
15
+ // Dates come from docs: Renamed from Referally. Only the cookie twin has one; the rest are "until further notice".
16
+ const RULES = [
17
+ { re: /\w*REFERALLY_\w*/g, to: (o) => o.replace('REFERALLY_', 'REFERALLI_'), removal: NO_DATE },
18
+ { re: /referally-version/gi, to: () => 'referalli-version', removal: NO_DATE },
19
+ { re: /referally_ctx/g, to: () => 'referalli_ctx', removal: 'removal 2027-01-31' },
20
+ { re: /x-referally-[\w-]*/gi, to: (o) => o.toLowerCase().replace('referally', 'referalli'), removal: NO_DATE },
21
+ { re: /@referally\/[\w.-]*/g, to: packageName, removal: NO_DATE },
22
+ ];
23
+ /** One warning per old name per line. Only the name is reported, never the line: it may be a .env value. */
24
+ function scanFile(path, text) {
25
+ if (!/referally/i.test(text))
26
+ return [];
27
+ return text.split('\n').flatMap((line, i) => RULES.flatMap(({ re, to, removal }) => [...new Set(line.match(re) ?? [])].map((old) => ({
28
+ id: `${path}:${i + 1}`,
29
+ status: 'warn',
30
+ message: `${old} → ${to(old)} (${removal})`,
31
+ }))));
32
+ }
33
+ /** `referalli doctor --scan <dir> [--strict]`: old names in a source tree. Needs no key and calls no API. */
34
+ export function runScan(out, err, dir, opts) {
35
+ const hits = [];
36
+ let files = 0;
37
+ let skipped = 0;
38
+ const walk = (current) => {
39
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
40
+ const path = join(current, entry.name);
41
+ try {
42
+ if (entry.isDirectory()) {
43
+ if (!SKIP_DIRS.has(entry.name))
44
+ walk(path);
45
+ }
46
+ else if (entry.isFile() && !LOCKFILE.test(entry.name)) { // symlinks aren't followed: no loops
47
+ if (statSync(path).size > MAX_BYTES) {
48
+ skipped++;
49
+ continue;
50
+ }
51
+ const buf = readFileSync(path);
52
+ if (buf.subarray(0, 8000).includes(0)) {
53
+ skipped++;
54
+ continue;
55
+ }
56
+ files++;
57
+ hits.push(...scanFile(path, buf.toString('utf8')));
58
+ }
59
+ }
60
+ catch {
61
+ skipped++; // unreadable: counted, the rest of the tree still scans
62
+ }
63
+ }
64
+ };
65
+ if (!existsSync(dir) || !statSync(dir).isDirectory())
66
+ throw new Error(`${dir}: not a directory`);
67
+ walk(dir);
68
+ printChecks(out, hits.length ? hits : [{ id: 'names', status: 'ok', message: 'no old Referally names found' }], opts.json);
69
+ err(`Scanned ${files} file(s), ${hits.length} old name(s); skipped ${skipped} (over 1 MB, binary or unreadable).`);
70
+ return opts.strict && hits.length ? 1 : 0;
71
+ }
@@ -1,2 +1,2 @@
1
1
  /** Kept in step with package.json by test/version.test.ts. */
2
- export declare const VERSION = "0.4.2";
2
+ export declare const VERSION = "0.4.4";
@@ -1,2 +1,2 @@
1
1
  /** Kept in step with package.json by test/version.test.ts. */
2
- export const VERSION = '0.4.2';
2
+ export const VERSION = '0.4.4';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@referalli/cli",
3
- "version": "0.4.2",
3
+ "version": "0.4.4",
4
4
  "description": "The Referalli command line: sign in, forward webhooks to localhost, trigger test events, tail events and API logs.",
5
5
  "license": "MIT",
6
6
  "type": "module",