ontiver-cli 0.0.0-stage → 0.1.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,19 @@
1
- # Temporary Holding Version
1
+ # Ontiver CLI
2
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.
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
+ Production keys are refused: production events never leave Ontiver through the CLI.
18
+
19
+ 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,51 @@
1
+ /** The few Ontiver API calls the CLI makes, all under /api/v1/banking/cli with a sandbox key. */
2
+ export class OntiverApiError extends Error {
3
+ constructor(message, status, code) {
4
+ super(message);
5
+ this.status = status;
6
+ this.code = code;
7
+ }
8
+ }
9
+
10
+ export function createApi({ apiKey, apiSecret, apiUrl }, fetchImpl = globalThis.fetch) {
11
+ const base = `${apiUrl}/api/v1/banking/cli`;
12
+
13
+ async function call(method, path, body, { timeoutMs = 30_000 } = {}) {
14
+ const controller = new AbortController();
15
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
16
+ try {
17
+ const headers = { Authorization: `Bearer ${apiKey}`, Accept: 'application/json', 'User-Agent': 'ontiver-cli' };
18
+ if (apiSecret) headers['X-Ontiver-API-Secret'] = apiSecret;
19
+ if (body !== undefined) headers['Content-Type'] = 'application/json';
20
+ const response = await fetchImpl(`${base}${path}`, {
21
+ method,
22
+ headers,
23
+ body: body === undefined ? undefined : JSON.stringify(body),
24
+ signal: controller.signal,
25
+ });
26
+ const text = await response.text();
27
+ let parsed = null;
28
+ try {
29
+ parsed = text ? JSON.parse(text) : null;
30
+ } catch {
31
+ parsed = null;
32
+ }
33
+ if (!response.ok) {
34
+ const error = parsed?.error ?? parsed?.detail ?? {};
35
+ const message = typeof error === 'string' ? error : error.message || `Ontiver answered ${response.status}`;
36
+ throw new OntiverApiError(message, response.status, typeof error === 'object' ? error.code : undefined);
37
+ }
38
+ return parsed?.data ?? parsed;
39
+ } finally {
40
+ clearTimeout(timer);
41
+ }
42
+ }
43
+
44
+ return {
45
+ events: () => call('GET', '/events'),
46
+ openSession: (events) => call('POST', '/sessions', { events }),
47
+ poll: (sessionId, wait = 20) => call('GET', `/sessions/${encodeURIComponent(sessionId)}/events?wait=${wait}`, undefined, { timeoutMs: (wait + 15) * 1000 }),
48
+ closeSession: (sessionId) => call('DELETE', `/sessions/${encodeURIComponent(sessionId)}`),
49
+ trigger: (event) => call('POST', '/trigger', { event }),
50
+ };
51
+ }
package/lib/cli.mjs ADDED
@@ -0,0 +1,190 @@
1
+ import { createInterface } from 'node:readline';
2
+
3
+ import { OntiverApiError, createApi } from './api.mjs';
4
+ import { clearConfig, configPath, credentials, isSandboxKey, maskKey, readConfig, writeConfig } from './config.mjs';
5
+ import { checkForwardUrl, forward } from './forward.mjs';
6
+
7
+ export const VERSION = '0.1.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 logout
18
+
19
+ Commands
20
+ login Save a sandbox API key (and its secret) to ${configPath()}
21
+ listen Forward this workspace's sandbox events to your local server, signed like real webhooks
22
+ trigger Send a sample sandbox event, for example: ontiver trigger verification.completed
23
+ events List the events you can listen for and trigger
24
+ logout Forget the saved key
25
+
26
+ The CLI only works with sandbox keys (sb_...). ONTIVER_API_KEY, ONTIVER_API_SECRET and
27
+ ONTIVER_API_URL override the saved login. Docs: https://docs.ontiver.com/sdks/cli`;
28
+
29
+ export function parseArgs(argv) {
30
+ const positional = [];
31
+ const flags = {};
32
+ for (let index = 0; index < argv.length; index += 1) {
33
+ const arg = argv[index];
34
+ if (arg.startsWith('--')) {
35
+ const [name, inline] = arg.slice(2).split('=', 2);
36
+ if (inline !== undefined) flags[name] = inline;
37
+ else if (argv[index + 1] && !argv[index + 1].startsWith('--')) flags[name] = argv[(index += 1)];
38
+ else flags[name] = true;
39
+ } else if (arg === '-h') flags.help = true;
40
+ else if (arg === '-v') flags.version = true;
41
+ else positional.push(arg);
42
+ }
43
+ return { command: positional[0], args: positional.slice(1), flags };
44
+ }
45
+
46
+ function ask(question, { hidden = false, io }) {
47
+ return new Promise((resolve) => {
48
+ const rl = createInterface({ input: io.stdin, output: io.stdout, terminal: Boolean(io.stdin.isTTY) });
49
+ if (hidden && io.stdin.isTTY) {
50
+ // Don't echo the secret while it's typed.
51
+ rl._writeToOutput = (text) => {
52
+ if (text.includes(question)) io.stdout.write(text);
53
+ };
54
+ }
55
+ rl.question(question, (answer) => {
56
+ rl.close();
57
+ if (hidden && io.stdin.isTTY) io.stdout.write('\n');
58
+ resolve(answer.trim());
59
+ });
60
+ });
61
+ }
62
+
63
+ function describe(error) {
64
+ if (error instanceof OntiverApiError) {
65
+ if (error.status === 401) return 'Ontiver didn’t accept that key. Check it in the developer dashboard → API keys, then run `ontiver login` again.';
66
+ return error.message;
67
+ }
68
+ return String(error?.message || error);
69
+ }
70
+
71
+ async function login(flags, io, deps) {
72
+ const saved = readConfig();
73
+ const apiKey = String(flags.key || (await ask('Sandbox API key (sb_...): ', { io })));
74
+ if (!isSandboxKey(apiKey)) throw new Error('That isn’t a sandbox key. The CLI only uses sandbox keys, which start with sb_.');
75
+ const apiSecret = String(flags.secret || (await ask('API secret (sec_..., leave blank if your key has none): ', { io, hidden: true })) || '');
76
+ const apiUrl = String(flags['api-url'] || saved.apiUrl || 'https://api.ontiver.com').replace(/\/+$/, '');
77
+ const api = deps.createApi({ apiKey, apiSecret, apiUrl });
78
+ await api.events();
79
+ writeConfig({ apiKey, apiSecret, apiUrl });
80
+ io.stdout.write(`Signed in with ${maskKey(apiKey)}. Saved to ${configPath()}.\n`);
81
+ }
82
+
83
+ async function listen(flags, io, deps) {
84
+ const creds = credentials();
85
+ if (!isSandboxKey(creds.apiKey)) throw new Error('Run `ontiver login` with a sandbox key first (or set ONTIVER_API_KEY).');
86
+ const url = checkForwardUrl(String(flags['forward-to'] || DEFAULT_FORWARD));
87
+ const events = flags.events ? String(flags.events).split(',').map((item) => item.trim()).filter(Boolean) : ['*'];
88
+ const api = deps.createApi(creds);
89
+ const session = await api.openSession(events);
90
+ io.stdout.write(
91
+ `Ready. Forwarding ${session.events.includes('*') ? 'all sandbox events' : session.events.join(', ')} to ${url}\n` +
92
+ `Webhook signing secret for this session: ${session.secret}\n` +
93
+ 'Use it to verify X-Ontiver-Signature in your local server. Press Ctrl+C to stop.\n',
94
+ );
95
+
96
+ let stopping = false;
97
+ const stop = async () => {
98
+ if (stopping) return;
99
+ stopping = true;
100
+ io.stdout.write('\nStopping…\n');
101
+ await api.closeSession(session.sessionId).catch(() => undefined);
102
+ };
103
+ deps.onSignal?.(stop);
104
+
105
+ let failures = 0;
106
+ while (!stopping && !(deps.shouldStop?.() ?? false)) {
107
+ try {
108
+ const batch = await api.poll(session.sessionId, deps.waitSeconds ?? 20);
109
+ failures = 0;
110
+ for (const item of batch.items ?? []) {
111
+ const result = await forward({ url, secret: session.secret, payload: item.payload, fetchImpl: deps.fetchImpl });
112
+ const time = new Date().toLocaleTimeString();
113
+ const outcome = result.error ? `✗ ${result.error}` : `${result.status >= 200 && result.status < 300 ? '→' : '✗'} ${result.status}`;
114
+ io.stdout.write(`${time} ${outcome} ${item.event} ${item.payload?.eventId ?? ''} (${result.ms} ms)\n`);
115
+ }
116
+ } catch (error) {
117
+ if (error instanceof OntiverApiError && [401, 403, 404, 410].includes(error.status)) {
118
+ io.stderr.write(`${describe(error)}\n`);
119
+ return 1;
120
+ }
121
+ failures += 1;
122
+ io.stderr.write(`Couldn’t reach Ontiver (${describe(error)}). Retrying…\n`);
123
+ await new Promise((resolve) => setTimeout(resolve, Math.min(30_000, 2_000 * failures)));
124
+ }
125
+ }
126
+ await stop();
127
+ return 0;
128
+ }
129
+
130
+ async function trigger(args, io, deps) {
131
+ const event = args[0];
132
+ if (!event) throw new Error('Name an event, for example: ontiver trigger verification.completed (see `ontiver events`).');
133
+ const creds = credentials();
134
+ if (!isSandboxKey(creds.apiKey)) throw new Error('Run `ontiver login` with a sandbox key first (or set ONTIVER_API_KEY).');
135
+ const result = await deps.createApi(creds).trigger(event);
136
+ io.stdout.write(`Sent a sample ${result.event} to your sandbox webhooks and any \`ontiver listen\` sessions.\n`);
137
+ }
138
+
139
+ async function listEvents(io, deps) {
140
+ const creds = credentials();
141
+ if (!isSandboxKey(creds.apiKey)) throw new Error('Run `ontiver login` with a sandbox key first (or set ONTIVER_API_KEY).');
142
+ const data = await deps.createApi(creds).events();
143
+ let group = '';
144
+ for (const item of data.items ?? []) {
145
+ if (item.group !== group) {
146
+ group = item.group;
147
+ io.stdout.write(`\n${group}\n`);
148
+ }
149
+ io.stdout.write(` ${item.event.padEnd(42)} ${item.description}\n`);
150
+ }
151
+ }
152
+
153
+ /** Runs one command. Returns the process exit code. */
154
+ export async function run(argv, io = process, deps = {}) {
155
+ const resolved = { createApi, ...deps };
156
+ const { command, args, flags } = parseArgs(argv);
157
+ if (flags.version) {
158
+ io.stdout.write(`${VERSION}\n`);
159
+ return 0;
160
+ }
161
+ if (!command || flags.help || command === 'help') {
162
+ io.stdout.write(`${HELP}\n`);
163
+ return command || flags.help ? 0 : 1;
164
+ }
165
+ try {
166
+ switch (command) {
167
+ case 'login':
168
+ await login(flags, io, resolved);
169
+ return 0;
170
+ case 'logout':
171
+ clearConfig();
172
+ io.stdout.write('Signed out.\n');
173
+ return 0;
174
+ case 'listen':
175
+ return await listen(flags, io, resolved);
176
+ case 'trigger':
177
+ await trigger(args, io, resolved);
178
+ return 0;
179
+ case 'events':
180
+ await listEvents(io, resolved);
181
+ return 0;
182
+ default:
183
+ io.stderr.write(`Unknown command "${command}". Run \`ontiver --help\`.\n`);
184
+ return 1;
185
+ }
186
+ } catch (error) {
187
+ io.stderr.write(`${describe(error)}\n`);
188
+ return 1;
189
+ }
190
+ }
package/lib/config.mjs ADDED
@@ -0,0 +1,53 @@
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
+ /** sb_live_abcd... -> sb_live_ab… (never print a whole key) */
50
+ export function maskKey(key) {
51
+ const value = String(key || '');
52
+ return value.length > 10 ? `${value.slice(0, 10)}…` : value;
53
+ }
@@ -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
1
  {
2
2
  "name": "ontiver-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "The Ontiver CLI: forward sandbox webhooks to your local server and trigger sample events",
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
+ }