@referalli/cli 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +2 -0
- package/dist/src/apply.d.ts +71 -0
- package/dist/src/apply.js +352 -0
- package/dist/src/client.d.ts +1 -0
- package/dist/src/client.js +1 -1
- package/dist/src/commands.d.ts +2 -0
- package/dist/src/commands.js +61 -1
- package/dist/src/index.d.ts +1 -1
- package/dist/src/index.js +13 -2
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +4 -1
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.3.1 - 2026-11-02
|
|
9
|
+
|
|
10
|
+
- Fixed: `apply` accepts `balanceCurrency` and `createCustomerIfMissing` under `stripeCredits`. Before, it refused them, and applying a file to a program that had them set turned them off without showing it in the plan.
|
|
11
|
+
|
|
12
|
+
## 0.3.0 - 2026-11-02
|
|
13
|
+
|
|
14
|
+
- `trigger --stripe <event> --connection <id> [--data JSON]`: send a Stripe event fixture into a test-mode billing connection (`POST /v1/sandbox/stripe-fixtures`) and print the commissions it created.
|
|
15
|
+
- `plan <file>` and `apply <file> [--plan] [--check] [--secret-file PATH]`: declarative config for programs, commission rules, Stripe credit settings, webhook endpoints and API keys (YAML or JSON). Matched by slug, url and name + owner; creates send an `Idempotency-Key`; `--check` exits 2 on drift (1 is an error); no deletes, rotations or revocations.
|
|
16
|
+
- New runtime dependency: `js-yaml`.
|
|
17
|
+
- `api --secret-file <path>`: write a returned secret (API key, webhook signing secret) to a new 0600 file instead of printing it.
|
|
18
|
+
- API additions from `referalli` 0.3.0: one-call referrers, partner summary, portal links, program-scoped API keys and the Stripe balance credit rail.
|
|
19
|
+
|
|
8
20
|
## 0.2.0 - 2026-10-24
|
|
9
21
|
|
|
10
22
|
- API 2026-11-01 additions: 56 new operations (inbound signup connectors, billing product filters, per-org SSO and partner-portal sign-in, support-tool context cards, data-rights executors, account closure, rewards, integration health, plans, the event feed and bulk webhook replay) and 2 webhook topics (`webhook_endpoint.failing`, `webhook_endpoint.recovered`).
|
package/README.md
CHANGED
|
@@ -58,6 +58,8 @@ referalli keys revoke key_…
|
|
|
58
58
|
referalli api GET /v1/partners
|
|
59
59
|
referalli api POST /v1/links --data '{"partnerId":"prt_…","programId":"prg_…"}'
|
|
60
60
|
referalli open docs # also: dashboard, keys, webhooks, spec, status
|
|
61
|
+
referalli plan referalli.yaml --check # declarative config; see https://referalli.com/docs (CLI page)
|
|
62
|
+
referalli apply referalli.yaml --secret-file new-secrets.json
|
|
61
63
|
```
|
|
62
64
|
|
|
63
65
|
## Environment
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { Client } from './client.js';
|
|
2
|
+
/**
|
|
3
|
+
* `referalli plan|apply <file>`: make the account match a declarative file.
|
|
4
|
+
* Every resource is matched by a stable key (program slug, webhook url, API key
|
|
5
|
+
* name + owner); creates carry an Idempotency-Key derived from that key and the
|
|
6
|
+
* request, so a retried apply never creates twice. Nothing missing from the file
|
|
7
|
+
* is ever deleted, rotated or revoked.
|
|
8
|
+
*/
|
|
9
|
+
export declare class ConfigError extends Error {
|
|
10
|
+
}
|
|
11
|
+
type Obj = Record<string, unknown>;
|
|
12
|
+
interface ProgramSpec extends Obj {
|
|
13
|
+
slug: string;
|
|
14
|
+
commissionRule?: Obj;
|
|
15
|
+
stripeCredits?: Obj & {
|
|
16
|
+
secretKeyEnv?: string;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
interface WebhookSpec extends Obj {
|
|
20
|
+
url: string;
|
|
21
|
+
topics?: string[];
|
|
22
|
+
programs?: string[];
|
|
23
|
+
status?: 'active' | 'paused';
|
|
24
|
+
}
|
|
25
|
+
interface ApiKeySpec extends Obj {
|
|
26
|
+
name: string;
|
|
27
|
+
owner?: string;
|
|
28
|
+
programs?: string[];
|
|
29
|
+
}
|
|
30
|
+
export interface ApplyConfig {
|
|
31
|
+
programs: ProgramSpec[];
|
|
32
|
+
webhooks: WebhookSpec[];
|
|
33
|
+
apiKeys: ApiKeySpec[];
|
|
34
|
+
}
|
|
35
|
+
/** Parse and check a referalli.yaml (JSON is YAML too). */
|
|
36
|
+
export declare function parseConfig(text: string, file?: string): ApplyConfig;
|
|
37
|
+
export type Field = [name: string, from: unknown, to: unknown];
|
|
38
|
+
export interface Change {
|
|
39
|
+
action: 'create' | 'update' | 'noop';
|
|
40
|
+
kind: string;
|
|
41
|
+
label: string;
|
|
42
|
+
fields: Field[];
|
|
43
|
+
/** Performs the change; returns once-shown secrets as [label, value]. */
|
|
44
|
+
run?: (ctx: RunCtx) => Promise<Array<[string, string]>>;
|
|
45
|
+
}
|
|
46
|
+
interface RunCtx {
|
|
47
|
+
client: Client;
|
|
48
|
+
/** Program slug → id, filled in as programs are created. */
|
|
49
|
+
ids: Map<string, string>;
|
|
50
|
+
}
|
|
51
|
+
/** Compare the file with the account; nothing is written. */
|
|
52
|
+
export declare function buildPlan(client: Client, config: ApplyConfig, env: NodeJS.ProcessEnv): Promise<{
|
|
53
|
+
changes: Change[];
|
|
54
|
+
ids: Map<string, string>;
|
|
55
|
+
}>;
|
|
56
|
+
/** Plan lines. Values come from the file and the API's public fields: no secret is ever in them. */
|
|
57
|
+
export declare function formatPlan(changes: Change[]): string[];
|
|
58
|
+
export interface ApplyIo {
|
|
59
|
+
out(line: string): void;
|
|
60
|
+
env: NodeJS.ProcessEnv;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Plan (and with `apply`, perform) the file. Returns the exit code: 0, or 2
|
|
64
|
+
* with `check` when anything would change.
|
|
65
|
+
*/
|
|
66
|
+
export declare function runApply(io: ApplyIo, client: Client, file: string, opts: {
|
|
67
|
+
apply: boolean;
|
|
68
|
+
check: boolean;
|
|
69
|
+
secretFile?: string;
|
|
70
|
+
}): Promise<number>;
|
|
71
|
+
export {};
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { load } from 'js-yaml';
|
|
4
|
+
/**
|
|
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); creates carry an Idempotency-Key derived from that key and the
|
|
8
|
+
* request, so a retried apply never creates twice. Nothing missing from the file
|
|
9
|
+
* is ever deleted, rotated or revoked.
|
|
10
|
+
*/
|
|
11
|
+
export class ConfigError extends Error {
|
|
12
|
+
}
|
|
13
|
+
// Program fields compared against GET /v1/programs/{id} and sent as-is on PATCH.
|
|
14
|
+
const PROGRAM_TOP = ['name', 'attributionModel', 'cookieWindowDays', 'signupToConversionDays', 'termsMd', 'status', 'publicHandle'];
|
|
15
|
+
// 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_KEYS = ['slug', ...PROGRAM_TOP, ...PROGRAM_SETTINGS, 'destinationUrl', 'commissionRule', 'stripeCredits'];
|
|
18
|
+
const STRIPE_KEYS = ['enabled', 'referrerMatch', 'metadataKey', 'refereeRewards', 'balanceCurrency', 'createCustomerIfMissing', 'secretKeyEnv'];
|
|
19
|
+
const WEBHOOK_KEYS = ['url', 'topics', 'programs', 'status', 'alertContacts'];
|
|
20
|
+
const API_KEY_KEYS = ['name', 'owner', 'mode', 'scopes', 'expiresInDays', 'programs', 'apiVersion'];
|
|
21
|
+
// What the API stores when a rule leaves these out (packages/commissions ruleConfigSchema).
|
|
22
|
+
const RULE_DEFAULTS = { appliesTo: 'gross', recurring: { type: 'lifetime' }, holdDays: 30, rounding: 'half_even', overrides: [] };
|
|
23
|
+
const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
24
|
+
function checkKeys(o, allowed, where, required) {
|
|
25
|
+
if (!isObj(o))
|
|
26
|
+
throw new ConfigError(`${where}: expected a mapping`);
|
|
27
|
+
for (const k of Object.keys(o)) {
|
|
28
|
+
if (k === 'secretKey')
|
|
29
|
+
throw new ConfigError(`${where}: secrets never go in the file; use secretKeyEnv: ENV_VAR_NAME`);
|
|
30
|
+
if (!allowed.includes(k))
|
|
31
|
+
throw new ConfigError(`${where}: unknown field "${k}" (allowed: ${allowed.join(', ')})`);
|
|
32
|
+
}
|
|
33
|
+
if (required && (typeof o[required] !== 'string' || !o[required]))
|
|
34
|
+
throw new ConfigError(`${where}: "${required}" is required`);
|
|
35
|
+
}
|
|
36
|
+
const list = (v, where) => {
|
|
37
|
+
if (v === undefined || v === null)
|
|
38
|
+
return [];
|
|
39
|
+
if (!Array.isArray(v))
|
|
40
|
+
throw new ConfigError(`${where}: expected a list`);
|
|
41
|
+
return v;
|
|
42
|
+
};
|
|
43
|
+
/** Parse and check a referalli.yaml (JSON is YAML too). */
|
|
44
|
+
export function parseConfig(text, file = 'config') {
|
|
45
|
+
let doc;
|
|
46
|
+
try {
|
|
47
|
+
doc = load(text);
|
|
48
|
+
}
|
|
49
|
+
catch (err) {
|
|
50
|
+
throw new ConfigError(`${file}: ${err.message}`);
|
|
51
|
+
}
|
|
52
|
+
checkKeys(doc ?? {}, ['programs', 'webhooks', 'apiKeys'], file);
|
|
53
|
+
const d = (doc ?? {});
|
|
54
|
+
const programs = list(d.programs, 'programs').map((p, i) => {
|
|
55
|
+
const where = `programs[${i}]`;
|
|
56
|
+
checkKeys(p, PROGRAM_KEYS, where, 'slug');
|
|
57
|
+
if (p.commissionRule !== undefined && !isObj(p.commissionRule))
|
|
58
|
+
throw new ConfigError(`${where}.commissionRule: expected a mapping`);
|
|
59
|
+
if (p.stripeCredits !== undefined) {
|
|
60
|
+
checkKeys(p.stripeCredits, STRIPE_KEYS, `${where}.stripeCredits`);
|
|
61
|
+
if (typeof p.stripeCredits.enabled !== 'boolean')
|
|
62
|
+
throw new ConfigError(`${where}.stripeCredits: "enabled" (true/false) is required`);
|
|
63
|
+
}
|
|
64
|
+
return p;
|
|
65
|
+
});
|
|
66
|
+
const slugs = programs.map((p) => p.slug);
|
|
67
|
+
const dup = slugs.find((s, i) => slugs.indexOf(s) !== i);
|
|
68
|
+
if (dup)
|
|
69
|
+
throw new ConfigError(`programs: slug "${dup}" is listed twice`);
|
|
70
|
+
const webhooks = list(d.webhooks, 'webhooks').map((w, i) => {
|
|
71
|
+
checkKeys(w, WEBHOOK_KEYS, `webhooks[${i}]`, 'url');
|
|
72
|
+
if (w.status !== undefined && w.status !== 'active' && w.status !== 'paused')
|
|
73
|
+
throw new ConfigError(`webhooks[${i}].status: active or paused`);
|
|
74
|
+
return w;
|
|
75
|
+
});
|
|
76
|
+
const apiKeys = list(d.apiKeys, 'apiKeys').map((k, i) => {
|
|
77
|
+
checkKeys(k, API_KEY_KEYS, `apiKeys[${i}]`, 'name');
|
|
78
|
+
return k;
|
|
79
|
+
});
|
|
80
|
+
return { programs, webhooks, apiKeys };
|
|
81
|
+
}
|
|
82
|
+
/** Key-order-insensitive JSON, for comparing values. */
|
|
83
|
+
const canon = (v) => JSON.stringify(v, (_k, x) => (isObj(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => a.localeCompare(b))) : x));
|
|
84
|
+
const same = (a, b) => canon(a ?? null) === canon(b ?? null);
|
|
85
|
+
const sorted = (v) => [...(v ?? [])].sort();
|
|
86
|
+
/** An Idempotency-Key that is the same for a retry of the same create, and only for that. */
|
|
87
|
+
const idemKey = (kind, key, body) => `referalli-apply-${kind}-${createHash('sha256').update(`${key}\n${canon(body)}`).digest('hex').slice(0, 40)}`;
|
|
88
|
+
const create = (client, path, kind, key, body) => client.request('POST', path, body, { headers: { 'idempotency-key': idemKey(kind, key, body) } });
|
|
89
|
+
/** Every row of a list endpoint: a plain array, or the 2026-11-01 list envelope followed page by page. */
|
|
90
|
+
async function listAll(client, path) {
|
|
91
|
+
const out = [];
|
|
92
|
+
let url = path;
|
|
93
|
+
for (;;) {
|
|
94
|
+
const res = await client.request('GET', url);
|
|
95
|
+
if (Array.isArray(res))
|
|
96
|
+
return res;
|
|
97
|
+
out.push(...res.data);
|
|
98
|
+
if (!res.has_more || res.data.length === 0)
|
|
99
|
+
return out;
|
|
100
|
+
url = `${path}${path.includes('?') ? '&' : '?'}limit=100&starting_after=${encodeURIComponent(res.data.at(-1).id)}`;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const programIdsFor = (ctx, slugs) => slugs?.length
|
|
104
|
+
? slugs.map((s) => {
|
|
105
|
+
const id = ctx.ids.get(s);
|
|
106
|
+
if (!id)
|
|
107
|
+
throw new ConfigError(`unknown program "${s}" (not on the account and not in the file)`);
|
|
108
|
+
return id;
|
|
109
|
+
})
|
|
110
|
+
: null;
|
|
111
|
+
/** Compare the file with the account; nothing is written. */
|
|
112
|
+
export async function buildPlan(client, config, env) {
|
|
113
|
+
const changes = [];
|
|
114
|
+
const programs = await listAll(client, '/v1/programs');
|
|
115
|
+
const ids = new Map(programs.map((p) => [p.slug, p.id]));
|
|
116
|
+
const slugOf = new Map(programs.map((p) => [p.id, p.slug]));
|
|
117
|
+
const known = new Set([...ids.keys(), ...config.programs.map((p) => p.slug)]);
|
|
118
|
+
const checkRefs = (refs, where) => {
|
|
119
|
+
for (const s of refs ?? [])
|
|
120
|
+
if (!known.has(s))
|
|
121
|
+
throw new ConfigError(`${where}: unknown program "${s}"`);
|
|
122
|
+
};
|
|
123
|
+
for (const spec of config.programs) {
|
|
124
|
+
const cur = programs.find((p) => p.slug === spec.slug);
|
|
125
|
+
const label = `program "${spec.slug}"`;
|
|
126
|
+
const desired = {};
|
|
127
|
+
for (const k of [...PROGRAM_TOP, ...PROGRAM_SETTINGS, 'destinationUrl'])
|
|
128
|
+
if (spec[k] !== undefined)
|
|
129
|
+
desired[k] = spec[k];
|
|
130
|
+
if (!cur) {
|
|
131
|
+
const { destinationUrl, ...rest } = desired;
|
|
132
|
+
// POST takes the destination as the widget setting; PATCH moves it (and its links).
|
|
133
|
+
const body = { slug: spec.slug, name: spec.slug, ...rest, ...(destinationUrl ? { widget: { destinationUrl } } : {}) };
|
|
134
|
+
changes.push({
|
|
135
|
+
action: 'create',
|
|
136
|
+
kind: 'program',
|
|
137
|
+
label,
|
|
138
|
+
fields: Object.entries(desired).map(([k, v]) => [k, undefined, v]),
|
|
139
|
+
run: async (ctx) => {
|
|
140
|
+
const made = await create(ctx.client, '/v1/programs', 'program', spec.slug, body);
|
|
141
|
+
ctx.ids.set(spec.slug, made.id);
|
|
142
|
+
return [];
|
|
143
|
+
},
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
const now = (k) => k === 'destinationUrl'
|
|
148
|
+
? (cur.settings.widget?.destinationUrl ?? null)
|
|
149
|
+
: PROGRAM_SETTINGS.includes(k)
|
|
150
|
+
? cur.settings[k]
|
|
151
|
+
: cur[k];
|
|
152
|
+
const fields = Object.entries(desired)
|
|
153
|
+
.filter(([k, v]) => !same(now(k), v))
|
|
154
|
+
.map(([k, v]) => [k, now(k), v]);
|
|
155
|
+
const patch = Object.fromEntries(fields.map(([k, , v]) => [k, v]));
|
|
156
|
+
changes.push({
|
|
157
|
+
action: fields.length ? 'update' : 'noop',
|
|
158
|
+
kind: 'program',
|
|
159
|
+
label,
|
|
160
|
+
fields,
|
|
161
|
+
run: async (ctx) => {
|
|
162
|
+
await ctx.client.request('PATCH', `/v1/programs/${cur.id}`, patch);
|
|
163
|
+
return [];
|
|
164
|
+
},
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
if (spec.commissionRule) {
|
|
168
|
+
const want = { ...RULE_DEFAULTS, ...spec.commissionRule };
|
|
169
|
+
const rlabel = `commissionRule "${spec.slug}"`;
|
|
170
|
+
const latest = cur ? (await listAll(client, `/v1/commission-rules?programId=${encodeURIComponent(cur.id)}`))[0] : undefined;
|
|
171
|
+
const publish = async (ctx) => {
|
|
172
|
+
const programId = ctx.ids.get(spec.slug);
|
|
173
|
+
await create(ctx.client, '/v1/commission-rules', 'rule', spec.slug, { programId, config: spec.commissionRule });
|
|
174
|
+
return [];
|
|
175
|
+
};
|
|
176
|
+
if (!latest) {
|
|
177
|
+
changes.push({ action: 'create', kind: 'commissionRule', label: rlabel, fields: Object.entries(spec.commissionRule).map(([k, v]) => [k, undefined, v]), run: publish });
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
const keys = [...new Set([...Object.keys(want), ...Object.keys(latest.config)])];
|
|
181
|
+
const fields = keys.filter((k) => !same(latest.config[k], want[k])).map((k) => [k, latest.config[k], want[k]]);
|
|
182
|
+
changes.push({ action: fields.length ? 'update' : 'noop', kind: 'commissionRule', label: `${rlabel} (v${latest.version})`, fields, run: publish });
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
if (spec.stripeCredits) {
|
|
186
|
+
const { secretKeyEnv, ...s } = spec.stripeCredits;
|
|
187
|
+
// Every field, defaults included: the PUT replaces the settings, so one left out would be switched off.
|
|
188
|
+
const want = {
|
|
189
|
+
enabled: s.enabled,
|
|
190
|
+
referrerMatch: s.referrerMatch ?? 'billing_link',
|
|
191
|
+
metadataKey: s.metadataKey ?? null,
|
|
192
|
+
refereeRewards: s.refereeRewards ?? false,
|
|
193
|
+
balanceCurrency: typeof s.balanceCurrency === 'string' ? s.balanceCurrency.toLowerCase() : null,
|
|
194
|
+
createCustomerIfMissing: s.createCustomerIfMissing ?? null,
|
|
195
|
+
};
|
|
196
|
+
const curS = cur ? await client.request('GET', `/v1/programs/${cur.id}/stripe-credits`) : null;
|
|
197
|
+
const fields = Object.keys(want)
|
|
198
|
+
.filter((k) => !curS || !same(curS[k], want[k]))
|
|
199
|
+
.map((k) => [k, curS?.[k], want[k]]);
|
|
200
|
+
// shortcut: the API never returns the key, so one already set is left alone; replace it with `referalli api PUT`.
|
|
201
|
+
const sendKey = Boolean(secretKeyEnv) && !curS?.hasOwnKey;
|
|
202
|
+
if (sendKey) {
|
|
203
|
+
if (!env[secretKeyEnv])
|
|
204
|
+
throw new ConfigError(`programs "${spec.slug}".stripeCredits: environment variable ${secretKeyEnv} is not set`);
|
|
205
|
+
fields.push(['secretKey', curS ? '(none)' : undefined, `(from $${secretKeyEnv})`]);
|
|
206
|
+
}
|
|
207
|
+
changes.push({
|
|
208
|
+
action: !curS ? 'create' : fields.length ? 'update' : 'noop',
|
|
209
|
+
kind: 'stripeCredits',
|
|
210
|
+
label: `stripeCredits "${spec.slug}"`,
|
|
211
|
+
fields,
|
|
212
|
+
run: async (ctx) => {
|
|
213
|
+
const body = { ...want, metadataKey: want.metadataKey ?? undefined, ...(sendKey ? { secretKey: env[secretKeyEnv] } : {}) };
|
|
214
|
+
await ctx.client.request('PUT', `/v1/programs/${ctx.ids.get(spec.slug)}/stripe-credits`, body);
|
|
215
|
+
return [];
|
|
216
|
+
},
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
if (config.webhooks.length) {
|
|
221
|
+
const endpoints = await listAll(client, '/v1/webhook-endpoints');
|
|
222
|
+
for (const spec of config.webhooks) {
|
|
223
|
+
checkRefs(spec.programs, `webhook ${spec.url}`);
|
|
224
|
+
const cur = endpoints.find((e) => e.url === spec.url);
|
|
225
|
+
const want = { topics: sorted(spec.topics ?? ['*']), programs: sorted(spec.programs), status: spec.status ?? 'active' };
|
|
226
|
+
if (spec.alertContacts !== undefined)
|
|
227
|
+
want.alertContacts = sorted(spec.alertContacts);
|
|
228
|
+
const label = `webhook ${spec.url}`;
|
|
229
|
+
const body = (ctx) => ({
|
|
230
|
+
topics: want.topics,
|
|
231
|
+
programIds: programIdsFor(ctx, spec.programs),
|
|
232
|
+
status: want.status,
|
|
233
|
+
...(want.alertContacts ? { alertContacts: want.alertContacts } : {}),
|
|
234
|
+
});
|
|
235
|
+
if (!cur) {
|
|
236
|
+
changes.push({
|
|
237
|
+
action: 'create',
|
|
238
|
+
kind: 'webhook',
|
|
239
|
+
label,
|
|
240
|
+
fields: Object.entries(want).map(([k, v]) => [k, undefined, v]),
|
|
241
|
+
run: async (ctx) => {
|
|
242
|
+
const made = await create(ctx.client, '/v1/webhook-endpoints', 'webhook', spec.url, { url: spec.url, ...body(ctx) });
|
|
243
|
+
return [[`webhook ${spec.url}`, made.secret]];
|
|
244
|
+
},
|
|
245
|
+
});
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
const now = {
|
|
249
|
+
topics: sorted(cur.topics),
|
|
250
|
+
programs: sorted((cur.programIds ?? []).map((id) => slugOf.get(id) ?? id)),
|
|
251
|
+
status: cur.status,
|
|
252
|
+
alertContacts: sorted(cur.alertContacts),
|
|
253
|
+
};
|
|
254
|
+
const fields = Object.keys(want).filter((k) => !same(now[k], want[k])).map((k) => [k, now[k], want[k]]);
|
|
255
|
+
changes.push({
|
|
256
|
+
action: fields.length ? 'update' : 'noop',
|
|
257
|
+
kind: 'webhook',
|
|
258
|
+
label,
|
|
259
|
+
fields,
|
|
260
|
+
run: async (ctx) => {
|
|
261
|
+
await ctx.client.request('PATCH', `/v1/webhook-endpoints/${cur.id}`, body(ctx));
|
|
262
|
+
return [];
|
|
263
|
+
},
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
for (const spec of config.apiKeys) {
|
|
268
|
+
checkRefs(spec.programs, `apiKey "${spec.name}"`);
|
|
269
|
+
const owner = spec.owner ?? null;
|
|
270
|
+
const label = `apiKey "${spec.name}"${owner ? ` (owner ${owner})` : ''}`;
|
|
271
|
+
const existing = await listAll(client, `/v1/api-keys${owner ? `?owner=${encodeURIComponent(owner)}` : ''}`);
|
|
272
|
+
// Create-only: an existing key is never rotated, revoked or edited from the file.
|
|
273
|
+
if (existing.some((k) => k.name === spec.name && (k.owner ?? null) === owner && !k.revokedAt)) {
|
|
274
|
+
changes.push({ action: 'noop', kind: 'apiKey', label, fields: [] });
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
const { programs: refs, ...rest } = spec;
|
|
278
|
+
const shown = { mode: 'both', ...rest };
|
|
279
|
+
changes.push({
|
|
280
|
+
action: 'create',
|
|
281
|
+
kind: 'apiKey',
|
|
282
|
+
label,
|
|
283
|
+
fields: Object.entries({ ...shown, ...(refs ? { programs: refs } : {}) }).map(([k, v]) => [k, undefined, v]),
|
|
284
|
+
run: async (ctx) => {
|
|
285
|
+
const programIds = programIdsFor(ctx, refs);
|
|
286
|
+
const res = await create(ctx.client, '/v1/api-keys', 'apikey', `${spec.name}\n${owner ?? ''}`, { ...shown, ...(programIds ? { programIds } : {}) });
|
|
287
|
+
const issued = (isObj(res.live) ? [res.live, res.test] : [res]);
|
|
288
|
+
return issued.map((k) => [`apiKey ${spec.name}${owner ? ` (${owner})` : ''} ${k.livemode ? 'live' : 'test'}`, k.key]);
|
|
289
|
+
},
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
return { changes, ids };
|
|
293
|
+
}
|
|
294
|
+
// --- output ----------------------------------------------------------------------
|
|
295
|
+
const show = (v) => (v === undefined ? '(unset)' : JSON.stringify(v));
|
|
296
|
+
const SIGN = { create: '+ create', update: '~ update', noop: '= unchanged' };
|
|
297
|
+
/** Plan lines. Values come from the file and the API's public fields: no secret is ever in them. */
|
|
298
|
+
export function formatPlan(changes) {
|
|
299
|
+
const lines = [];
|
|
300
|
+
for (const c of changes) {
|
|
301
|
+
lines.push(`${SIGN[c.action]} ${c.label}`);
|
|
302
|
+
for (const [k, from, to] of c.fields)
|
|
303
|
+
lines.push(c.action === 'create' ? ` ${k}: ${show(to)}` : ` ${k}: ${show(from)} → ${show(to)}`);
|
|
304
|
+
}
|
|
305
|
+
const n = (a) => changes.filter((c) => c.action === a).length;
|
|
306
|
+
lines.push(`Plan: ${n('create')} to create, ${n('update')} to update, ${n('noop')} unchanged.`);
|
|
307
|
+
return lines;
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Plan (and with `apply`, perform) the file. Returns the exit code: 0, or 2
|
|
311
|
+
* with `check` when anything would change.
|
|
312
|
+
*/
|
|
313
|
+
export async function runApply(io, client, file, opts) {
|
|
314
|
+
const config = parseConfig(readFileSync(file, 'utf8'), file);
|
|
315
|
+
const { changes, ids } = await buildPlan(client, config, io.env);
|
|
316
|
+
for (const line of formatPlan(changes))
|
|
317
|
+
io.out(line);
|
|
318
|
+
const pending = changes.filter((c) => c.action !== 'noop');
|
|
319
|
+
if (opts.check) {
|
|
320
|
+
if (pending.length)
|
|
321
|
+
io.out('Drift: the account does not match the file.');
|
|
322
|
+
return pending.length ? 2 : 0; // 2, not 1: CI can tell drift from an error
|
|
323
|
+
}
|
|
324
|
+
if (!opts.apply || pending.length === 0)
|
|
325
|
+
return 0;
|
|
326
|
+
// Checked first: a secret file that can't be written after the creates would lose the secrets.
|
|
327
|
+
if (opts.secretFile && existsSync(opts.secretFile))
|
|
328
|
+
throw new ConfigError(`--secret-file ${opts.secretFile} already exists; pick a new path`);
|
|
329
|
+
const ctx = { client, ids };
|
|
330
|
+
const secrets = [];
|
|
331
|
+
try {
|
|
332
|
+
for (const c of pending) {
|
|
333
|
+
secrets.push(...(await c.run(ctx)));
|
|
334
|
+
io.out(`${c.action === 'create' ? 'Created' : 'Updated'} ${c.label}`);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
finally {
|
|
338
|
+
// Even when a later change fails, secrets already issued are handed over: they can't be fetched again.
|
|
339
|
+
if (secrets.length && opts.secretFile) {
|
|
340
|
+
writeFileSync(opts.secretFile, `${JSON.stringify(Object.fromEntries(secrets), null, 2)}\n`, { mode: 0o600, flag: 'wx' });
|
|
341
|
+
chmodSync(opts.secretFile, 0o600);
|
|
342
|
+
io.out(`New secrets written to ${opts.secretFile} (mode 600). They are shown once.`);
|
|
343
|
+
}
|
|
344
|
+
else if (secrets.length) {
|
|
345
|
+
io.out('New secrets, shown once. Store them now:');
|
|
346
|
+
for (const [label, value] of secrets)
|
|
347
|
+
io.out(` ${label} ${value}`);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
io.out(`Apply complete: ${pending.length} change(s).`);
|
|
351
|
+
return 0;
|
|
352
|
+
}
|
package/dist/src/client.d.ts
CHANGED
package/dist/src/client.js
CHANGED
|
@@ -15,7 +15,7 @@ export function createClient(opts) {
|
|
|
15
15
|
return {
|
|
16
16
|
baseUrl,
|
|
17
17
|
async request(method, path, body, ropts = {}) {
|
|
18
|
-
const headers = { 'user-agent': `referalli-cli/${VERSION}
|
|
18
|
+
const headers = { 'user-agent': `referalli-cli/${VERSION}`, ...ropts.headers };
|
|
19
19
|
if (opts.key)
|
|
20
20
|
headers.authorization = `Bearer ${opts.key}`;
|
|
21
21
|
if (body !== undefined)
|
package/dist/src/commands.d.ts
CHANGED
|
@@ -38,3 +38,5 @@ 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]`. */
|
|
42
|
+
export declare function apply(io: Io, file: string | undefined, flags: Flags, planOnly: boolean): Promise<number>;
|
package/dist/src/commands.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { chmodSync, writeFileSync } from 'node:fs';
|
|
1
2
|
import { hostname } from 'node:os';
|
|
3
|
+
import { ConfigError, runApply } from './apply.js';
|
|
2
4
|
import { ApiError, createClient } from './client.js';
|
|
3
5
|
import { DEFAULT_BASE_URL, readConfig, removeConfig, writeConfig } from './config.js';
|
|
4
6
|
/** A user-facing failure: printed without a stack trace, exit code 1. */
|
|
@@ -245,6 +247,8 @@ export async function open(io, target, flags) {
|
|
|
245
247
|
// --- trigger -----------------------------------------------------------------------
|
|
246
248
|
export async function trigger(io, topic, flags) {
|
|
247
249
|
const { client } = signedIn(io);
|
|
250
|
+
if (typeof flags.stripe === 'string')
|
|
251
|
+
return triggerStripe(io, client, flags.stripe, flags);
|
|
248
252
|
if (!topic) {
|
|
249
253
|
const { topics } = await client.request('GET', '/v1/cli/topics');
|
|
250
254
|
throw new CliError(`Usage: referalli trigger <topic>. Topics: ${topics.join(', ')}`);
|
|
@@ -262,6 +266,29 @@ export async function trigger(io, topic, flags) {
|
|
|
262
266
|
io.out(`Triggered ${topic} [${res.eventId}]: ${res.deliveredTo.listeners} listener(s), ${res.deliveredTo.endpoints} webhook endpoint(s).`);
|
|
263
267
|
return 0;
|
|
264
268
|
}
|
|
269
|
+
/** `trigger --stripe <event> --connection <id> [--data overrides]`: a Stripe fixture into a test-mode billing connection. */
|
|
270
|
+
async function triggerStripe(io, client, event, flags) {
|
|
271
|
+
if (typeof flags.connection !== 'string') {
|
|
272
|
+
throw new CliError('Usage: referalli trigger --stripe <event> --connection <billing connection id> [--data JSON]');
|
|
273
|
+
}
|
|
274
|
+
let overrides = {};
|
|
275
|
+
if (typeof flags.data === 'string') {
|
|
276
|
+
try {
|
|
277
|
+
overrides = JSON.parse(flags.data);
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
throw new CliError('--data must be a JSON object, e.g. --data \'{"customerRef": "cus_123", "amountMinor": 4900}\'');
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
// `eventId` in --data replays that event instead of sending a new one.
|
|
284
|
+
const { eventId, ...rest } = overrides;
|
|
285
|
+
const res = await client.request('POST', '/v1/sandbox/stripe-fixtures', { connectionId: flags.connection, event, overrides: rest, ...(eventId !== undefined ? { eventId } : {}) });
|
|
286
|
+
const dup = res.results.some((r) => r.duplicate) ? ' (duplicate)' : '';
|
|
287
|
+
io.out(`Sent ${event} [${res.eventId}]${dup}: ${res.received} billing event(s), ${res.commissions.length} commission event(s).`);
|
|
288
|
+
for (const c of res.commissions)
|
|
289
|
+
io.out(` ${c.type} ${c.amountMinor} ${c.currency} ${c.id}`);
|
|
290
|
+
return 0;
|
|
291
|
+
}
|
|
265
292
|
const logLine = (e) => `${time(e.ts)} ${e.method.padEnd(6)} ${e.path} ${e.status} ${e.latencyMs}ms ${e.requestId}`;
|
|
266
293
|
export async function logsTail(io, flags) {
|
|
267
294
|
const { client } = signedIn(io);
|
|
@@ -354,7 +381,7 @@ export async function keys(io, sub, arg, flags) {
|
|
|
354
381
|
// --- api ---------------------------------------------------------------------------
|
|
355
382
|
export async function api(io, method, path, flags) {
|
|
356
383
|
if (!method || !path)
|
|
357
|
-
throw new CliError('Usage: referalli api <METHOD> <path> [--data JSON]');
|
|
384
|
+
throw new CliError('Usage: referalli api <METHOD> <path> [--data JSON] [--secret-file PATH]');
|
|
358
385
|
const { client } = signedIn(io);
|
|
359
386
|
let body;
|
|
360
387
|
if (typeof flags.data === 'string') {
|
|
@@ -366,6 +393,39 @@ export async function api(io, method, path, flags) {
|
|
|
366
393
|
}
|
|
367
394
|
}
|
|
368
395
|
const res = await client.request(method.toUpperCase(), path.startsWith('/') ? path : `/${path}`, body);
|
|
396
|
+
if (typeof flags['secret-file'] === 'string') {
|
|
397
|
+
// A secret shown once (a billing connection's webhookSecret, a new key): to a 0600 file, never to the terminal.
|
|
398
|
+
const field = SECRET_FIELDS.find((f) => typeof res?.[f] === 'string');
|
|
399
|
+
if (!field)
|
|
400
|
+
throw new CliError(`--secret-file: the response has no ${SECRET_FIELDS.join(', ')} field`);
|
|
401
|
+
const file = flags['secret-file'];
|
|
402
|
+
writeFileSync(file, `${res[field]}\n`, { mode: 0o600, flag: 'wx' });
|
|
403
|
+
chmodSync(file, 0o600);
|
|
404
|
+
io.out(JSON.stringify({ ...res, [field]: `(written to ${file})` }, null, 2));
|
|
405
|
+
return 0;
|
|
406
|
+
}
|
|
369
407
|
io.out(JSON.stringify(res, null, 2));
|
|
370
408
|
return 0;
|
|
371
409
|
}
|
|
410
|
+
const SECRET_FIELDS = ['webhookSecret', 'secret', 'key'];
|
|
411
|
+
// --- plan / apply ------------------------------------------------------------------
|
|
412
|
+
/** `referalli plan <file>` / `referalli apply <file> [--plan] [--check] [--secret-file PATH]`. */
|
|
413
|
+
export async function apply(io, file, flags, planOnly) {
|
|
414
|
+
if (!file)
|
|
415
|
+
throw new CliError(planOnly ? 'Usage: referalli plan <referalli.yaml> [--check]' : 'Usage: referalli apply <referalli.yaml> [--plan] [--check] [--secret-file PATH]');
|
|
416
|
+
const { client } = signedIn(io);
|
|
417
|
+
try {
|
|
418
|
+
return await runApply(io, client, file, {
|
|
419
|
+
apply: !planOnly && !flags.plan,
|
|
420
|
+
check: flags.check === true,
|
|
421
|
+
secretFile: typeof flags['secret-file'] === 'string' ? flags['secret-file'] : undefined,
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
catch (err) {
|
|
425
|
+
if (err instanceof ConfigError)
|
|
426
|
+
throw new CliError(err.message);
|
|
427
|
+
if (err.code === 'ENOENT')
|
|
428
|
+
throw new CliError(`${file}: no such file`);
|
|
429
|
+
throw err;
|
|
430
|
+
}
|
|
431
|
+
}
|
package/dist/src/index.d.ts
CHANGED
|
@@ -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 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]\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\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)";
|
|
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 --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\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)";
|
|
7
7
|
/** Run one command; returns the process exit code. */
|
|
8
8
|
export declare function runCli(argv: string[], io: Io): Promise<number>;
|
package/dist/src/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { parseArgs } from 'node:util';
|
|
2
2
|
import { ApiError } from './client.js';
|
|
3
|
-
import { api, CliError, eventsTail, keys, login, listen, logout, logsTail, open, trigger, whoami } from './commands.js';
|
|
3
|
+
import { api, apply, CliError, eventsTail, keys, login, listen, logout, logsTail, open, trigger, whoami } from './commands.js';
|
|
4
4
|
import { VERSION } from './version.js';
|
|
5
5
|
export { readConfig, writeConfig, configPath } from './config.js';
|
|
6
6
|
export { createClient, ApiError } from './client.js';
|
|
@@ -13,13 +13,16 @@ Usage:
|
|
|
13
13
|
referalli whoami
|
|
14
14
|
referalli listen [--forward-to URL] [--events topic,topic] [--max-events N]
|
|
15
15
|
referalli trigger <topic> [--data JSON]
|
|
16
|
+
referalli trigger --stripe <event> --connection <id> [--data JSON] (test mode)
|
|
16
17
|
referalli events tail [--events topic,topic] [--since 1h|ISO] [--json] [--max N]
|
|
17
18
|
referalli logs tail [--max N]
|
|
18
19
|
referalli open [docs|dashboard|keys|webhooks|spec|status]
|
|
19
|
-
referalli api <METHOD> <path> [--data JSON]
|
|
20
|
+
referalli api <METHOD> <path> [--data JSON] [--secret-file PATH]
|
|
20
21
|
referalli keys create --name NAME [--owner WHO] [--mode both|live|test] [--scopes full,…] [--expires-days N]
|
|
21
22
|
referalli keys list [--owner WHO] [--mode live|test]
|
|
22
23
|
referalli keys revoke <key id> [--pair] [--cascade]
|
|
24
|
+
referalli plan <referalli.yaml> [--check]
|
|
25
|
+
referalli apply <referalli.yaml> [--plan] [--check] [--secret-file PATH]
|
|
23
26
|
|
|
24
27
|
Environment:
|
|
25
28
|
REFERALLI_API_KEY use this key instead of the saved login
|
|
@@ -44,6 +47,9 @@ export async function runCli(argv, io) {
|
|
|
44
47
|
max: { type: 'string' },
|
|
45
48
|
wait: { type: 'string' },
|
|
46
49
|
data: { type: 'string' },
|
|
50
|
+
stripe: { type: 'string' },
|
|
51
|
+
connection: { type: 'string' },
|
|
52
|
+
'secret-file': { type: 'string' },
|
|
47
53
|
name: { type: 'string' },
|
|
48
54
|
owner: { type: 'string' },
|
|
49
55
|
mode: { type: 'string' },
|
|
@@ -51,6 +57,8 @@ export async function runCli(argv, io) {
|
|
|
51
57
|
'expires-days': { type: 'string' },
|
|
52
58
|
pair: { type: 'boolean' },
|
|
53
59
|
cascade: { type: 'boolean' },
|
|
60
|
+
plan: { type: 'boolean' },
|
|
61
|
+
check: { type: 'boolean' },
|
|
54
62
|
json: { type: 'boolean' },
|
|
55
63
|
help: { type: 'boolean', short: 'h' },
|
|
56
64
|
version: { type: 'boolean', short: 'v' },
|
|
@@ -101,6 +109,9 @@ export async function runCli(argv, io) {
|
|
|
101
109
|
return await api(io, rest[0], rest[1], flags);
|
|
102
110
|
case 'keys':
|
|
103
111
|
return await keys(io, rest[0], rest[1], flags);
|
|
112
|
+
case 'plan':
|
|
113
|
+
case 'apply':
|
|
114
|
+
return await apply(io, rest[0], flags, command === 'plan');
|
|
104
115
|
default:
|
|
105
116
|
io.err(`Unknown command "${command}".`);
|
|
106
117
|
io.err(HELP);
|
package/dist/src/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** Kept in step with package.json by test/version.test.ts. */
|
|
2
|
-
export declare const VERSION = "0.
|
|
2
|
+
export declare const VERSION = "0.3.1";
|
package/dist/src/version.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** Kept in step with package.json by test/version.test.ts. */
|
|
2
|
-
export const VERSION = '0.
|
|
2
|
+
export const VERSION = '0.3.1';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@referalli/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
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",
|
|
@@ -48,6 +48,9 @@
|
|
|
48
48
|
"typecheck": "tsc --noEmit",
|
|
49
49
|
"start": "tsx bin/referalli.ts"
|
|
50
50
|
},
|
|
51
|
+
"dependencies": {
|
|
52
|
+
"js-yaml": "4.3.1"
|
|
53
|
+
},
|
|
51
54
|
"devDependencies": {
|
|
52
55
|
"@types/node": "^22.9.0",
|
|
53
56
|
"tsx": "^4.19.2",
|