ontiver-cli 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ontiver
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,27 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # Ontiver CLI
2
+
3
+ Build your Ontiver webhook handler on your own machine: forward your sandbox events to a local server, signed exactly like real deliveries, and send sample events on demand.
4
+
5
+ ```bash
6
+ npm install -g ontiver-cli
7
+ ontiver login
8
+ ontiver listen --forward-to http://localhost:3000/webhooks/ontiver
9
+ ontiver trigger verification.completed
10
+ ```
11
+
12
+ - `ontiver login` saves a **sandbox** key (`sb_...`) and its secret to `~/.ontiver/cli.json`, readable only by you. `ONTIVER_API_KEY`, `ONTIVER_API_SECRET` and `ONTIVER_API_URL` override it.
13
+ - `ontiver listen` prints a signing secret for the session. Each forwarded request carries `X-Ontiver-Signature: t=<timestamp>,v1=<HMAC-SHA256 of "<timestamp>.<body>">`, as every delivery does, so your verification code runs unchanged. `--events a,b` limits what is forwarded.
14
+ - `ontiver trigger <event>` sends a sample sandbox event, marked `"sample": true`, to your sandbox webhooks and listening sessions.
15
+ - `ontiver events` lists the events.
16
+
17
+ `listen` and `trigger` refuse production keys: production events never leave Ontiver through the CLI.
18
+
19
+ In production, with a key given **Command line (Ontiver CLI)** access in the dashboard and read from `ONTIVER_API_KEY` / `ONTIVER_API_SECRET` (never saved):
20
+
21
+ - `ontiver deliveries [--failed]` lists webhook deliveries: event, status, attempts and your endpoint's host, never the payload.
22
+ - `ontiver deliveries replay <id>` resends one to your registered endpoint; you type the id to confirm.
23
+ - `ontiver logs [--errors]` lists this key's requests: method, endpoint (ids folded), status and time.
24
+
25
+ Every production use is audited, and your workspace is alerted the first time each day a key is used from the CLI.
26
+
27
+ Docs: https://docs.ontiver.com/sdks/cli
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import { run } from '../lib/cli.mjs';
3
+
4
+ const handlers = [];
5
+ for (const signal of ['SIGINT', 'SIGTERM']) {
6
+ process.on(signal, async () => {
7
+ for (const handler of handlers) await handler();
8
+ process.exit(130);
9
+ });
10
+ }
11
+
12
+ process.exitCode = await run(process.argv.slice(2), process, { onSignal: (handler) => handlers.push(handler) });
package/lib/api.mjs ADDED
@@ -0,0 +1,66 @@
1
+ import { randomUUID } from 'node:crypto';
2
+
3
+ /** The Ontiver API calls the CLI makes, all under /api/v1/banking/cli. */
4
+ export class OntiverApiError extends Error {
5
+ constructor(message, status, code) {
6
+ super(message);
7
+ this.status = status;
8
+ this.code = code;
9
+ }
10
+ }
11
+
12
+ export function createApi({ apiKey, apiSecret, apiUrl }, fetchImpl = globalThis.fetch) {
13
+ const base = `${apiUrl}/api/v1/banking/cli`;
14
+
15
+ async function call(method, path, body, { timeoutMs = 30_000, headers: extra = {} } = {}) {
16
+ const controller = new AbortController();
17
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
18
+ try {
19
+ const headers = { Authorization: `Bearer ${apiKey}`, Accept: 'application/json', 'User-Agent': 'ontiver-cli', ...extra };
20
+ if (apiSecret) headers['X-Ontiver-API-Secret'] = apiSecret;
21
+ if (body !== undefined) headers['Content-Type'] = 'application/json';
22
+ const response = await fetchImpl(`${base}${path}`, {
23
+ method,
24
+ headers,
25
+ body: body === undefined ? undefined : JSON.stringify(body),
26
+ signal: controller.signal,
27
+ redirect: 'error', // Never follow a redirect with the key attached.
28
+ });
29
+ const text = await response.text();
30
+ let parsed = null;
31
+ try {
32
+ parsed = text ? JSON.parse(text) : null;
33
+ } catch {
34
+ parsed = null;
35
+ }
36
+ if (!response.ok) {
37
+ const error = parsed?.error ?? parsed?.detail ?? {};
38
+ const message = typeof error === 'string' ? error : error.message || `Ontiver answered ${response.status}`;
39
+ throw new OntiverApiError(message, response.status, typeof error === 'object' ? error.code : undefined);
40
+ }
41
+ return parsed?.data ?? parsed;
42
+ } finally {
43
+ clearTimeout(timer);
44
+ }
45
+ }
46
+
47
+ const query = (params) => {
48
+ const entries = Object.entries(params).filter(([, value]) => value !== undefined && value !== '' && value !== false);
49
+ return entries.length ? `?${new URLSearchParams(entries.map(([key, value]) => [key, String(value)])).toString()}` : '';
50
+ };
51
+
52
+ return {
53
+ events: () => call('GET', '/events'),
54
+ openSession: (events) => call('POST', '/sessions', { events }),
55
+ poll: (sessionId, wait = 20) => call('GET', `/sessions/${encodeURIComponent(sessionId)}/events?wait=${wait}`, undefined, { timeoutMs: (wait + 15) * 1000 }),
56
+ closeSession: (sessionId) => call('DELETE', `/sessions/${encodeURIComponent(sessionId)}`),
57
+ trigger: (event) => call('POST', '/trigger', { event }),
58
+ deliveries: ({ status, event, limit } = {}) => call('GET', `/deliveries${query({ status, event, limit })}`),
59
+ logs: ({ errors, limit } = {}) => call('GET', `/logs${query({ status: errors ? 'errors' : '', limit })}`),
60
+ // A single-use nonce and a fresh idempotency key: a captured request can't be sent again.
61
+ replay: (deliveryId) =>
62
+ call('POST', `/deliveries/${encodeURIComponent(deliveryId)}/replay`, { confirm: deliveryId }, {
63
+ headers: { 'X-Ontiver-Nonce': randomUUID(), 'X-Ontiver-Timestamp': String(Math.floor(Date.now() / 1000)), 'Idempotency-Key': randomUUID() },
64
+ }),
65
+ };
66
+ }
package/lib/cli.mjs ADDED
@@ -0,0 +1,259 @@
1
+ import { createInterface } from 'node:readline';
2
+
3
+ import { OntiverApiError, createApi } from './api.mjs';
4
+ import { clearConfig, configPath, credentials, isProductionKey, isSandboxKey, maskKey, productionSafeCredentials, readConfig, writeConfig } from './config.mjs';
5
+ import { checkForwardUrl, forward } from './forward.mjs';
6
+
7
+ export const VERSION = '0.2.0';
8
+ const DEFAULT_FORWARD = 'http://localhost:3000/webhooks/ontiver';
9
+
10
+ const HELP = `Ontiver CLI ${VERSION}
11
+
12
+ Usage
13
+ ontiver login [--key sb_...] [--secret sec_...] [--api-url URL]
14
+ ontiver listen [--forward-to URL] [--events a,b]
15
+ ontiver trigger <event>
16
+ ontiver events
17
+ ontiver deliveries [--failed | --status STATUS] [--event NAME] [--limit N]
18
+ ontiver deliveries replay <deliveryId> [--yes]
19
+ ontiver logs [--errors] [--limit N]
20
+ ontiver logout
21
+
22
+ Commands
23
+ login Save a sandbox API key (and its secret) to ${configPath()}
24
+ listen Forward this workspace's sandbox events to your local server, signed like real webhooks
25
+ trigger Send a sample sandbox event, for example: ontiver trigger verification.completed
26
+ events List the events you can listen for and trigger
27
+ deliveries Recent webhook deliveries (event, status, attempts, endpoint host; never the payload)
28
+ replay <id> resends one to your registered endpoint; you type the id to confirm
29
+ logs This key's recent API requests (method, endpoint, status; no bodies)
30
+ logout Forget the saved key
31
+
32
+ listen and trigger work with sandbox keys only. deliveries and logs also work in production with
33
+ a key that has Command line (Ontiver CLI) access; production keys are read from ONTIVER_API_KEY and
34
+ ONTIVER_API_SECRET only and are never saved. Docs: https://docs.ontiver.com/sdks/cli`;
35
+
36
+ export function parseArgs(argv) {
37
+ const positional = [];
38
+ const flags = {};
39
+ for (let index = 0; index < argv.length; index += 1) {
40
+ const arg = argv[index];
41
+ if (arg.startsWith('--')) {
42
+ const [name, inline] = arg.slice(2).split('=', 2);
43
+ if (inline !== undefined) flags[name] = inline;
44
+ else if (argv[index + 1] && !argv[index + 1].startsWith('--')) flags[name] = argv[(index += 1)];
45
+ else flags[name] = true;
46
+ } else if (arg === '-h') flags.help = true;
47
+ else if (arg === '-v') flags.version = true;
48
+ else positional.push(arg);
49
+ }
50
+ return { command: positional[0], args: positional.slice(1), flags };
51
+ }
52
+
53
+ function ask(question, { hidden = false, io }) {
54
+ return new Promise((resolve) => {
55
+ const rl = createInterface({ input: io.stdin, output: io.stdout, terminal: Boolean(io.stdin.isTTY) });
56
+ if (hidden && io.stdin.isTTY) {
57
+ // Don't echo the secret while it's typed.
58
+ rl._writeToOutput = (text) => {
59
+ if (text.includes(question)) io.stdout.write(text);
60
+ };
61
+ }
62
+ rl.question(question, (answer) => {
63
+ rl.close();
64
+ if (hidden && io.stdin.isTTY) io.stdout.write('\n');
65
+ resolve(answer.trim());
66
+ });
67
+ });
68
+ }
69
+
70
+ function sandboxOnly(creds, command) {
71
+ if (isProductionKey(creds.apiKey)) throw new Error(`\`ontiver ${command}\` works with sandbox keys only: production events never leave Ontiver through the CLI. Use \`ontiver deliveries\` and \`ontiver logs\` in production.`);
72
+ if (!isSandboxKey(creds.apiKey)) throw new Error('Run `ontiver login` with a sandbox key first (or set ONTIVER_API_KEY).');
73
+ }
74
+
75
+ function describe(error) {
76
+ if (error instanceof OntiverApiError) {
77
+ if (error.status === 401) return 'Ontiver didn’t accept that key or secret. Check them in the dashboard → API keys.';
78
+ if (error.status === 429) return 'Too many requests from this key in the last hour. Try again later.';
79
+ return error.message;
80
+ }
81
+ return String(error?.message || error);
82
+ }
83
+
84
+ async function login(flags, io, deps) {
85
+ const saved = readConfig();
86
+ const apiKey = String(flags.key || (await ask('Sandbox API key (sb_...): ', { io })));
87
+ if (isProductionKey(apiKey)) throw new Error('The CLI never saves a production key. Set ONTIVER_API_KEY and ONTIVER_API_SECRET in your shell (ideally from your secrets manager) instead.');
88
+ if (!isSandboxKey(apiKey)) throw new Error('That isn’t a sandbox key (sb_...).');
89
+ const apiSecret = String(flags.secret || (await ask('API secret (sec_..., leave blank if your key has none): ', { io, hidden: true })) || '');
90
+ const apiUrl = String(flags['api-url'] || saved.apiUrl || 'https://api.ontiver.com').replace(/\/+$/, '');
91
+ const api = deps.createApi({ apiKey, apiSecret, apiUrl });
92
+ await api.events();
93
+ writeConfig({ apiKey, apiSecret, apiUrl });
94
+ io.stdout.write(`Signed in with ${maskKey(apiKey)}. Saved to ${configPath()}.\n`);
95
+ }
96
+
97
+ async function listen(flags, io, deps) {
98
+ const creds = credentials();
99
+ sandboxOnly(creds, 'listen');
100
+ const url = checkForwardUrl(String(flags['forward-to'] || DEFAULT_FORWARD));
101
+ const events = flags.events ? String(flags.events).split(',').map((item) => item.trim()).filter(Boolean) : ['*'];
102
+ const api = deps.createApi(creds);
103
+ const session = await api.openSession(events);
104
+ io.stdout.write(
105
+ `Ready. Forwarding ${session.events.includes('*') ? 'all sandbox events' : session.events.join(', ')} to ${url}\n` +
106
+ `Webhook signing secret for this session: ${session.secret}\n` +
107
+ 'Use it to verify X-Ontiver-Signature in your local server. Press Ctrl+C to stop.\n',
108
+ );
109
+
110
+ let stopping = false;
111
+ const stop = async () => {
112
+ if (stopping) return;
113
+ stopping = true;
114
+ io.stdout.write('\nStopping…\n');
115
+ await api.closeSession(session.sessionId).catch(() => undefined);
116
+ };
117
+ deps.onSignal?.(stop);
118
+
119
+ let failures = 0;
120
+ while (!stopping && !(deps.shouldStop?.() ?? false)) {
121
+ try {
122
+ const batch = await api.poll(session.sessionId, deps.waitSeconds ?? 20);
123
+ failures = 0;
124
+ for (const item of batch.items ?? []) {
125
+ const result = await forward({ url, secret: session.secret, payload: item.payload, fetchImpl: deps.fetchImpl });
126
+ const time = new Date().toLocaleTimeString();
127
+ const outcome = result.error ? `✗ ${result.error}` : `${result.status >= 200 && result.status < 300 ? '→' : '✗'} ${result.status}`;
128
+ io.stdout.write(`${time} ${outcome} ${item.event} ${item.payload?.eventId ?? ''} (${result.ms} ms)\n`);
129
+ }
130
+ } catch (error) {
131
+ if (error instanceof OntiverApiError && [401, 403, 404, 410].includes(error.status)) {
132
+ io.stderr.write(`${describe(error)}\n`);
133
+ return 1;
134
+ }
135
+ failures += 1;
136
+ io.stderr.write(`Couldn’t reach Ontiver (${describe(error)}). Retrying…\n`);
137
+ await new Promise((resolve) => setTimeout(resolve, Math.min(30_000, 2_000 * failures)));
138
+ }
139
+ }
140
+ await stop();
141
+ return 0;
142
+ }
143
+
144
+ async function trigger(args, io, deps) {
145
+ const event = args[0];
146
+ if (!event) throw new Error('Name an event, for example: ontiver trigger verification.completed (see `ontiver events`).');
147
+ const creds = credentials();
148
+ sandboxOnly(creds, 'trigger');
149
+ const result = await deps.createApi(creds).trigger(event);
150
+ io.stdout.write(`Sent a sample ${result.event} to your sandbox webhooks and any \`ontiver listen\` sessions.\n`);
151
+ }
152
+
153
+ async function listEvents(io, deps) {
154
+ const creds = credentials();
155
+ sandboxOnly(creds, 'events');
156
+ const data = await deps.createApi(creds).events();
157
+ let group = '';
158
+ for (const item of data.items ?? []) {
159
+ if (item.group !== group) {
160
+ group = item.group;
161
+ io.stdout.write(`\n${group}\n`);
162
+ }
163
+ io.stdout.write(` ${item.event.padEnd(42)} ${item.description}\n`);
164
+ }
165
+ }
166
+
167
+ function short(value) {
168
+ return value ? new Date(value).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }) : '-';
169
+ }
170
+
171
+ function banner(io, creds) {
172
+ if (isProductionKey(creds.apiKey)) io.stdout.write(`PRODUCTION · key ${maskKey(creds.apiKey)}\n`);
173
+ }
174
+
175
+ async function deliveries(args, flags, io, deps) {
176
+ const creds = productionSafeCredentials();
177
+ const api = deps.createApi(creds);
178
+ banner(io, creds);
179
+ if (args[0] === 'replay') {
180
+ const deliveryId = String(args[1] || '');
181
+ if (!/^[A-Za-z0-9_-]{6,80}$/.test(deliveryId)) throw new Error('Name the delivery: ontiver deliveries replay <deliveryId>');
182
+ if (!flags.yes) {
183
+ const typed = await ask(`Resend ${deliveryId} to your registered endpoint? Type the delivery id to confirm: `, { io });
184
+ if (typed !== deliveryId) throw new Error('Not replayed: the id you typed didn’t match.');
185
+ }
186
+ const result = await api.replay(deliveryId);
187
+ io.stdout.write(`Replay queued as ${result.deliveryId}. Ontiver sends it to your registered endpoint; watch it with \`ontiver deliveries\`.\n`);
188
+ return;
189
+ }
190
+ const status = flags.failed ? 'failed' : flags.status ? String(flags.status) : undefined;
191
+ const data = await api.deliveries({ status, event: flags.event ? String(flags.event) : undefined, limit: flags.limit ? Number(flags.limit) : undefined });
192
+ const items = data.items ?? [];
193
+ if (!items.length) {
194
+ io.stdout.write(`No deliveries in the last ${data.windowDays ?? 7} days${status ? ` with status ${status}` : ''}.\n`);
195
+ return;
196
+ }
197
+ for (const item of items) {
198
+ io.stdout.write(`${short(item.createdAt).padEnd(16)} ${String(item.status).padEnd(9)} ${String(item.lastResponseCode ?? '-').padEnd(4)} ${String(item.attempts).padStart(2)}× ${item.event.padEnd(34)} ${item.deliveryId} → ${item.endpointHost ?? '-'}\n`);
199
+ }
200
+ }
201
+
202
+ async function logs(flags, io, deps) {
203
+ const creds = productionSafeCredentials();
204
+ banner(io, creds);
205
+ const data = await deps.createApi(creds).logs({ errors: Boolean(flags.errors), limit: flags.limit ? Number(flags.limit) : undefined });
206
+ const items = data.items ?? [];
207
+ if (!items.length) {
208
+ io.stdout.write(`No requests from this key in the last ${data.windowDays ?? 7} days${flags.errors ? ' with errors' : ''}.\n`);
209
+ return;
210
+ }
211
+ for (const item of items) {
212
+ io.stdout.write(`${short(item.occurredAt).padEnd(16)} ${String(item.status ?? '-').padEnd(4)} ${String(item.method).padEnd(6)} ${item.path} ${item.durationMs != null ? `${item.durationMs} ms` : ''} ${item.requestId}\n`);
213
+ }
214
+ }
215
+
216
+ /** Runs one command. Returns the process exit code. */
217
+ export async function run(argv, io = process, deps = {}) {
218
+ const resolved = { createApi, ...deps };
219
+ const { command, args, flags } = parseArgs(argv);
220
+ if (flags.version) {
221
+ io.stdout.write(`${VERSION}\n`);
222
+ return 0;
223
+ }
224
+ if (!command || flags.help || command === 'help') {
225
+ io.stdout.write(`${HELP}\n`);
226
+ return command || flags.help ? 0 : 1;
227
+ }
228
+ try {
229
+ switch (command) {
230
+ case 'login':
231
+ await login(flags, io, resolved);
232
+ return 0;
233
+ case 'logout':
234
+ clearConfig();
235
+ io.stdout.write('Signed out.\n');
236
+ return 0;
237
+ case 'listen':
238
+ return await listen(flags, io, resolved);
239
+ case 'trigger':
240
+ await trigger(args, io, resolved);
241
+ return 0;
242
+ case 'events':
243
+ await listEvents(io, resolved);
244
+ return 0;
245
+ case 'deliveries':
246
+ await deliveries(args, flags, io, resolved);
247
+ return 0;
248
+ case 'logs':
249
+ await logs(flags, io, resolved);
250
+ return 0;
251
+ default:
252
+ io.stderr.write(`Unknown command "${command}". Run \`ontiver --help\`.\n`);
253
+ return 1;
254
+ }
255
+ } catch (error) {
256
+ io.stderr.write(`${describe(error)}\n`);
257
+ return 1;
258
+ }
259
+ }
package/lib/config.mjs ADDED
@@ -0,0 +1,77 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+
5
+ export const DEFAULT_API_URL = 'https://api.ontiver.com';
6
+
7
+ /** Where `ontiver login` keeps the sandbox key: ~/.ontiver/cli.json, readable only by you. */
8
+ export function configPath(home = process.env.ONTIVER_HOME || join(homedir(), '.ontiver')) {
9
+ return join(home, 'cli.json');
10
+ }
11
+
12
+ export function readConfig(path = configPath()) {
13
+ if (!existsSync(path)) return {};
14
+ try {
15
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
16
+ return parsed && typeof parsed === 'object' ? parsed : {};
17
+ } catch {
18
+ return {};
19
+ }
20
+ }
21
+
22
+ export function writeConfig(values, path = configPath()) {
23
+ mkdirSync(join(path, '..'), { recursive: true, mode: 0o700 });
24
+ writeFileSync(path, `${JSON.stringify(values, null, 2)}\n`, { mode: 0o600 });
25
+ try {
26
+ chmodSync(path, 0o600);
27
+ } catch {
28
+ // Windows keeps the file in the user's own profile instead.
29
+ }
30
+ }
31
+
32
+ export function clearConfig(path = configPath()) {
33
+ rmSync(path, { force: true });
34
+ }
35
+
36
+ /** Environment variables win over the saved login, so CI can run without `ontiver login`. */
37
+ export function credentials(env = process.env, saved = readConfig()) {
38
+ return {
39
+ apiKey: env.ONTIVER_API_KEY || saved.apiKey || '',
40
+ apiSecret: env.ONTIVER_API_SECRET || saved.apiSecret || '',
41
+ apiUrl: (env.ONTIVER_API_URL || saved.apiUrl || DEFAULT_API_URL).replace(/\/+$/, ''),
42
+ };
43
+ }
44
+
45
+ export function isSandboxKey(key) {
46
+ return /^sb_[A-Za-z0-9_-]{8,}$/.test(String(key || ''));
47
+ }
48
+
49
+ export function isProductionKey(key) {
50
+ return /^prod_[A-Za-z0-9_-]{8,}$/.test(String(key || ''));
51
+ }
52
+
53
+ /**
54
+ * Credentials for the production-capable commands. A production key is only ever read from the
55
+ * environment (never saved by `ontiver login`), needs its secret, and only travels over HTTPS.
56
+ */
57
+ export function productionSafeCredentials(env = process.env, saved = readConfig()) {
58
+ const creds = credentials(env, saved);
59
+ if (isProductionKey(creds.apiKey)) {
60
+ if (!env.ONTIVER_API_KEY) throw new Error('Production keys are read from ONTIVER_API_KEY only; the CLI never saves them.');
61
+ // Never pair a production key with a saved (sandbox) secret: both come from the environment.
62
+ if (!env.ONTIVER_API_SECRET) throw new Error('Set ONTIVER_API_SECRET too: production commands need the key’s secret.');
63
+ creds.apiSecret = env.ONTIVER_API_SECRET;
64
+ const url = new URL(creds.apiUrl);
65
+ const local = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
66
+ if (url.protocol !== 'https:' && !local) throw new Error('Production keys are only sent over HTTPS.');
67
+ } else if (!isSandboxKey(creds.apiKey)) {
68
+ throw new Error('Run `ontiver login` with a sandbox key, or set ONTIVER_API_KEY and ONTIVER_API_SECRET for production.');
69
+ }
70
+ return creds;
71
+ }
72
+
73
+ /** sb_live_abcd... -> sb_live_ab… (never print a whole key) */
74
+ export function maskKey(key) {
75
+ const value = String(key || '');
76
+ return value.length > 10 ? `${value.slice(0, 10)}…` : value;
77
+ }
@@ -0,0 +1,49 @@
1
+ import { createHmac } from 'node:crypto';
2
+
3
+ /**
4
+ * The headers a real Ontiver webhook delivery carries, signed with `secret`:
5
+ * X-Ontiver-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<body>">
6
+ */
7
+ export function signedHeaders({ secret, body, payload, now = Date.now() }) {
8
+ const timestamp = String(Math.floor(now / 1000));
9
+ const signature = createHmac('sha256', secret).update(`${timestamp}.${body}`).digest('hex');
10
+ return {
11
+ 'Content-Type': 'application/json',
12
+ 'User-Agent': 'Ontiver-Webhooks/1.0 (ontiver-cli)',
13
+ 'X-Ontiver-Event': String(payload.event ?? ''),
14
+ 'X-Ontiver-Delivery-Id': String(payload.deliveryId ?? ''),
15
+ 'X-Ontiver-Event-Id': String(payload.eventId ?? ''),
16
+ 'X-Ontiver-Timestamp': timestamp,
17
+ 'X-Ontiver-Event-Version': String(payload.eventVersion ?? 1),
18
+ 'X-Ontiver-Signature': `t=${timestamp},v1=${signature}`,
19
+ };
20
+ }
21
+
22
+ export function checkForwardUrl(raw) {
23
+ let url;
24
+ try {
25
+ url = new URL(raw);
26
+ } catch {
27
+ throw new Error(`"${raw}" isn't a URL. Use something like http://localhost:3000/webhooks/ontiver`);
28
+ }
29
+ if (!['http:', 'https:'].includes(url.protocol)) throw new Error('The forward URL must start with http:// or https://');
30
+ return url.toString();
31
+ }
32
+
33
+ /** Post one event to the local server. Returns { status, ms } or { error, ms }. */
34
+ export async function forward({ url, secret, payload, fetchImpl = globalThis.fetch, timeoutMs = 10_000 }) {
35
+ const body = JSON.stringify(payload);
36
+ const started = Date.now();
37
+ const controller = new AbortController();
38
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
39
+ try {
40
+ const response = await fetchImpl(url, { method: 'POST', headers: signedHeaders({ secret, body, payload }), body, signal: controller.signal });
41
+ await response.arrayBuffer().catch(() => undefined);
42
+ return { status: response.status, ms: Date.now() - started };
43
+ } catch (error) {
44
+ const reason = error?.cause?.code === 'ECONNREFUSED' ? 'connection refused (is your server running?)' : error?.name === 'AbortError' ? 'timed out after 10s' : String(error?.message || error);
45
+ return { error: reason, ms: Date.now() - started };
46
+ } finally {
47
+ clearTimeout(timer);
48
+ }
49
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
- {
2
- "name": "ontiver-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "ontiver-cli",
3
+ "version": "0.2.0",
4
+ "description": "The Ontiver CLI: forward sandbox webhooks to your local server, trigger sample events, and check deliveries and request logs",
5
+ "type": "module",
6
+ "bin": {
7
+ "ontiver": "./bin/ontiver.mjs"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "lib",
12
+ "README.md",
13
+ "LICENSE"
14
+ ],
15
+ "engines": {
16
+ "node": ">=18.17"
17
+ },
18
+ "scripts": {
19
+ "test": "node --test tests/*.test.mjs"
20
+ },
21
+ "keywords": [
22
+ "ontiver",
23
+ "cli",
24
+ "webhooks",
25
+ "kyc",
26
+ "identity"
27
+ ],
28
+ "author": "Ontiver",
29
+ "license": "MIT",
30
+ "homepage": "https://docs.ontiver.com/sdks/cli",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/joinverza/Ontiver.git",
34
+ "directory": "sdks/cli"
35
+ }
36
+ }