@aiveth/cli 0.0.0-stage → 0.35.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/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## 0.35.0 — unreleased
4
+
5
+ - First release: `login`, `logout`, `init`, `env pull`, `doctor`, `config pull`, `config patch`, `webhooks listen`, `testing-token`, `redirect-urls`, `people import`. Same version as the other Aiveth SDKs.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,25 @@
1
- # Temporary Holding Version
1
+ # @aiveth/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
+ Aiveth's command line: set a project up, check it, keep your sign-in settings in a file, forward
4
+ webhooks to your own machine, and more.
5
+
6
+ ```bash
7
+ npx @aiveth/cli login # paste an API key from the console (typed here, saved for you only)
8
+ npx @aiveth/cli init --app okc_test_…
9
+ npx @aiveth/cli doctor
10
+ ```
11
+
12
+ | Command | What it does |
13
+ | --- | --- |
14
+ | `aiveth login` / `logout` | Save or forget an API key. `AIVETH_SECRET_KEY` and `AIVETH_URL` override it (CI). |
15
+ | `aiveth init --app <client_id>` | Write `AIVETH_ISSUER` and `AIVETH_CLIENT_ID` to `.env.local`, and the next steps for your stack. Never a secret. |
16
+ | `aiveth env pull --app <client_id>` | The same, without the next steps. |
17
+ | `aiveth doctor` | Check Node, the env file, that Aiveth answers, that the app exists and the SDK is installed. |
18
+ | `aiveth config pull [--out file]` | Your sign-in settings as a file (`config:read`). |
19
+ | `aiveth config patch <file> [--dry-run]` | Apply a settings file; only what differs changes (`config:write`). |
20
+ | `aiveth webhooks listen --forward-to http://localhost:3000/api/webhooks` | Your events as they happen, posted to your machine and signed with a secret made for the run (`events:read`). |
21
+ | `aiveth testing-token` | A testing token for your automated tests, in Development (`testing_tokens:write`). |
22
+ | `aiveth redirect-urls list\|add\|remove --app <id> [url]` | An app's return addresses, e.g. for preview deployments (`app_urls:write`). |
23
+ | `aiveth people import <file.json> [--dry-run]` | Bring people in from another system (`people:manage`). |
24
+
25
+ Docs: https://docs.aiveth.com/sdks/cli
@@ -0,0 +1,164 @@
1
+ /* Every command of `aiveth` — each a call to Aiveth's admin API (the server holds every rule) or a
2
+ * file in the project. Clerk's CLI, checked 2026-12-05: init, doctor, env pull, config pull/patch,
3
+ * webhooks listen, migrate (here: people import). `impersonate` needs a person's console sign-in,
4
+ * so it stays in the console. */
5
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
6
+ import { call, CliError, reach } from './http.js';
7
+ import { read as readEnv, write as writeEnv } from './envfile.js';
8
+ import { newSecret, signed } from './sign.js';
9
+ const SDK_FOR = {
10
+ next: '@aiveth/nextjs', react: '@aiveth/react', express: '@aiveth/node', fastify: '@aiveth/node', hono: '@aiveth/node',
11
+ };
12
+ const DOCS = 'https://docs.aiveth.com';
13
+ /** The framework a project uses, from its package.json — '' when none of the known ones. */
14
+ export function framework(dir = '.') {
15
+ const path = `${dir}/package.json`;
16
+ if (!existsSync(path))
17
+ return existsSync(`${dir}/pyproject.toml`) || existsSync(`${dir}/requirements.txt`) ? 'python' : '';
18
+ const pkg = JSON.parse(readFileSync(path, 'utf8'));
19
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
20
+ return Object.keys(SDK_FOR).find((name) => name in deps) ?? '';
21
+ }
22
+ export function sdkFor(found) {
23
+ return found === 'python' ? 'aiveth (pip install aiveth)' : SDK_FOR[found] ?? '@aiveth/node';
24
+ }
25
+ /** `aiveth env pull` / `init`: the issuer and the app's client ID into the env file — never a
26
+ * secret; checked against the app's public page first. */
27
+ export async function envPull(api, app, file, say) {
28
+ if (!app)
29
+ throw new CliError('Name the app: --app <client_id> (Developers → Apps in the console).');
30
+ const known = await reach(`${api.base}/v1/branding/public?client_id=${encodeURIComponent(app)}`);
31
+ if (!known.ok)
32
+ throw new CliError(`Aiveth doesn't know the app ${app} (${known.status}).`);
33
+ writeEnv(file, { AIVETH_ISSUER: api.base, AIVETH_CLIENT_ID: app });
34
+ say(`Wrote AIVETH_ISSUER and AIVETH_CLIENT_ID to ${file}.`);
35
+ say('A server app also needs AIVETH_CLIENT_SECRET: set it yourself from the console; it never goes in a chat or a log.');
36
+ }
37
+ export async function init(api, app, file, say) {
38
+ await envPull(api, app, file, say);
39
+ const found = framework();
40
+ say(found ? `This looks like ${found}. Install ${sdkFor(found)}.` : `Install the SDK for your stack: ${DOCS}/sdks/overview`);
41
+ say(`Then follow ${DOCS}/quickstart, and run: aiveth doctor`);
42
+ }
43
+ /** `aiveth doctor`: what the project still lacks — exit code 1 when something must be fixed. */
44
+ export async function doctor(api, file, say) {
45
+ const env = { ...readEnv(file), ...Object.fromEntries(Object.entries(process.env).filter(([k]) => k.startsWith('AIVETH_'))) };
46
+ let good = true;
47
+ const check = (ok, line, fix) => {
48
+ say(`${ok ? '✓' : '✗'} ${line}${ok ? '' : ` — ${fix}`}`);
49
+ good &&= ok;
50
+ };
51
+ const major = Number(process.versions.node.split('.')[0]);
52
+ check(major >= 18, `Node ${process.versions.node}`, 'Aiveth needs Node 18.17 or newer');
53
+ const issuer = (env.AIVETH_ISSUER || api.base).replace(/\/+$/, '');
54
+ check(!!env.AIVETH_ISSUER, `AIVETH_ISSUER in ${file}`, 'run: aiveth env pull --app <client_id>');
55
+ check(!!env.AIVETH_CLIENT_ID, `AIVETH_CLIENT_ID in ${file}`, 'run: aiveth env pull --app <client_id>');
56
+ const discovery = await reach(`${issuer}/.well-known/openid-configuration`);
57
+ check(discovery.ok, `${issuer} answers`, `it said ${discovery.status || 'nothing'}`);
58
+ if (env.AIVETH_CLIENT_ID) {
59
+ const app = await reach(`${issuer}/v1/branding/public?client_id=${encodeURIComponent(env.AIVETH_CLIENT_ID)}`);
60
+ check(app.ok, `the app ${env.AIVETH_CLIENT_ID} exists`, 'check the client ID in the console');
61
+ }
62
+ const found = framework();
63
+ if (found && found !== 'python') {
64
+ const pkg = JSON.parse(readFileSync('package.json', 'utf8'));
65
+ const sdk = SDK_FOR[found] ?? '@aiveth/node';
66
+ check(!!pkg.dependencies?.[sdk], `${sdk} installed`, `npm install ${sdk}`);
67
+ }
68
+ if (api.key && env.AIVETH_CLIENT_ID) {
69
+ try {
70
+ const { redirect_urls } = await call(api, 'GET', `/v1/admin/apps/${encodeURIComponent(env.AIVETH_CLIENT_ID)}/redirect-urls`);
71
+ say(` return addresses: ${redirect_urls.join(', ')}`);
72
+ }
73
+ catch { /* a key without app_urls:write: nothing more to show */ }
74
+ }
75
+ say(good ? 'All good.' : 'Fix the ✗ lines, then run aiveth doctor again.');
76
+ return good;
77
+ }
78
+ export async function configPull(api, out, say) {
79
+ const file = await call(api, 'GET', '/v1/admin/config');
80
+ const text = JSON.stringify(file, null, 2) + '\n';
81
+ if (out) {
82
+ writeFileSync(out, text);
83
+ say(`Wrote your settings to ${out}.`);
84
+ }
85
+ else
86
+ process.stdout.write(text);
87
+ }
88
+ export async function configPatch(api, path, dryRun, say) {
89
+ if (!path)
90
+ throw new CliError('Name the file: aiveth config patch aiveth-settings.json');
91
+ const config = JSON.parse(readFileSync(path, 'utf8'));
92
+ const done = await call(api, 'POST', '/v1/admin/config', { config, dry_run: dryRun });
93
+ const lines = Object.entries(done.changes).flatMap(([s, fields]) => Object.entries(fields).map(([f, [now, then]]) => ` ${s}.${f}: ${JSON.stringify(now)} → ${JSON.stringify(then)}`));
94
+ if (!lines.length) {
95
+ say('Nothing differs.');
96
+ return;
97
+ }
98
+ say(dryRun ? 'Would change:' : 'Changed:');
99
+ lines.forEach(say);
100
+ if (dryRun)
101
+ say('Run again without --dry-run to apply.');
102
+ }
103
+ export async function testingToken(api, say) {
104
+ const made = await call(api, 'POST', '/v1/admin/testing-tokens');
105
+ say(made.token);
106
+ say(`Ends ${made.expires_at}. Pass it as ?aiveth_testing_token= or the Aiveth-Testing-Token header.`);
107
+ }
108
+ export async function redirectUrls(api, action, app, url, say) {
109
+ if (!app)
110
+ throw new CliError('Name the app: --app <client_id>');
111
+ const path = `/v1/admin/apps/${encodeURIComponent(app)}/redirect-urls`;
112
+ const got = action === 'add' ? await call(api, 'POST', path, { url })
113
+ : action === 'remove' ? await call(api, 'DELETE', `${path}?url=${encodeURIComponent(url)}`)
114
+ : await call(api, 'GET', path);
115
+ got.redirect_urls.forEach((u) => say(u));
116
+ }
117
+ export async function peopleImport(api, path, dryRun, say) {
118
+ if (!path)
119
+ throw new CliError('Name the file: aiveth people import people.json');
120
+ const raw = JSON.parse(readFileSync(path, 'utf8'));
121
+ const people = Array.isArray(raw) ? raw : raw.people;
122
+ if (!Array.isArray(people))
123
+ throw new CliError('The file is a list of people, or {"people": [...]}.');
124
+ const report = await call(api, 'POST', '/v1/admin/people/import', { people, dry_run: dryRun });
125
+ say(JSON.stringify(report, null, 2));
126
+ }
127
+ /** `aiveth webhooks listen`: your organization's events, as they happen, posted to a local address
128
+ * and signed as Aiveth signs webhooks — with a secret made for this run (shown once). */
129
+ export async function listen(api, forwardTo, types, say, { rounds = Infinity, every = 2000 } = {}) {
130
+ if (!/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?\//.test(forwardTo)) {
131
+ throw new CliError('Forward to your own machine: --forward-to http://localhost:3000/api/webhooks');
132
+ }
133
+ const secret = newSecret();
134
+ say(`Forwarding events to ${forwardTo}. Your webhook secret for this run: ${secret}`);
135
+ say('Set it as your app\'s webhook secret while testing. Press Ctrl+C to stop.');
136
+ let after = null; // the cursor, once there is one
137
+ const since = new Date().toISOString(); // until then: only what happens from now on
138
+ for (let round = 0; round < rounds; round += 1) {
139
+ const q = new URLSearchParams();
140
+ if (types.length)
141
+ q.set('types', types.join(','));
142
+ if (after)
143
+ q.set('after', after);
144
+ else
145
+ q.set('range_start', since);
146
+ const page = await call(api, 'GET', `/v1/events?${q}`);
147
+ for (const event of page.data) {
148
+ const body = JSON.stringify(event);
149
+ const headers = { 'Content-Type': 'application/json', ...signed(secret, event.id, Math.floor(Date.now() / 1000), body) };
150
+ try {
151
+ const res = await fetch(forwardTo, { method: 'POST', headers, body });
152
+ say(`${event.type} ${event.id} → ${res.status}`);
153
+ }
154
+ catch {
155
+ say(`${event.type} ${event.id} → your app didn't answer`);
156
+ }
157
+ after = event.id;
158
+ }
159
+ if (page.list_metadata.after)
160
+ after = page.list_metadata.after;
161
+ if (round + 1 < rounds)
162
+ await new Promise((r) => setTimeout(r, every));
163
+ }
164
+ }
@@ -0,0 +1,27 @@
1
+ /* The saved key: ~/.config/aiveth/credentials.json, readable by its owner only. AIVETH_SECRET_KEY
2
+ * and AIVETH_URL (the issuer) take precedence — what CI uses. */
3
+ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, join } from 'node:path';
6
+ export const DEFAULT_BASE = 'https://accounts.aiveth.com';
7
+ export function credentialsPath(home = homedir()) {
8
+ return join(process.env.XDG_CONFIG_HOME || join(home, '.config'), 'aiveth', 'credentials.json');
9
+ }
10
+ export function load(path = credentialsPath()) {
11
+ let saved = {};
12
+ if (existsSync(path))
13
+ saved = JSON.parse(readFileSync(path, 'utf8'));
14
+ const base = (process.env.AIVETH_URL || saved.base_url || DEFAULT_BASE).replace(/\/+$/, '');
15
+ return { base, key: process.env.AIVETH_SECRET_KEY || saved.api_key || null };
16
+ }
17
+ export function save(key, base, path = credentialsPath()) {
18
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
19
+ writeFileSync(path, JSON.stringify({ api_key: key, base_url: base }, null, 2), { mode: 0o600 });
20
+ chmodSync(path, 0o600);
21
+ }
22
+ export function forget(path = credentialsPath()) {
23
+ if (!existsSync(path))
24
+ return false;
25
+ rmSync(path);
26
+ return true;
27
+ }
@@ -0,0 +1,28 @@
1
+ /* A project's env file: set some keys, keep every other line as it was. Never a secret here —
2
+ * the CLI writes the issuer and the client ID only. */
3
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
4
+ export function merged(current, values) {
5
+ const left = { ...values };
6
+ const lines = current.split('\n').map((line) => {
7
+ const key = /^\s*([A-Z0-9_]+)\s*=/.exec(line)?.[1];
8
+ if (key && key in left) {
9
+ const out = `${key}=${left[key]}`;
10
+ delete left[key];
11
+ return out;
12
+ }
13
+ return line;
14
+ });
15
+ while (lines.length && lines[lines.length - 1] === '')
16
+ lines.pop();
17
+ return [...lines, ...Object.entries(left).map(([k, v]) => `${k}=${v}`)].join('\n') + '\n';
18
+ }
19
+ export function write(path, values) {
20
+ writeFileSync(path, merged(existsSync(path) ? readFileSync(path, 'utf8') : '', values));
21
+ }
22
+ export function read(path) {
23
+ if (!existsSync(path))
24
+ return {};
25
+ return Object.fromEntries(readFileSync(path, 'utf8').split('\n')
26
+ .map((l) => /^\s*([A-Z0-9_]+)\s*=\s*(.*)$/.exec(l)).filter((m) => !!m)
27
+ .map((m) => [m[1], m[2].replace(/^["']|["']$/g, '')]));
28
+ }
package/dist/http.js ADDED
@@ -0,0 +1,29 @@
1
+ /* One call to Aiveth's admin API with the saved key — its answer, or an error in Aiveth's words. */
2
+ export class CliError extends Error {
3
+ }
4
+ export async function call(api, method, path, body) {
5
+ if (!api.key)
6
+ throw new CliError('Sign in first: aiveth login (or set AIVETH_SECRET_KEY).');
7
+ const res = await fetch(`${api.base}${path}`, {
8
+ method,
9
+ headers: { Authorization: `Bearer ${api.key}`, 'User-Agent': 'aiveth-cli', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) },
10
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
11
+ });
12
+ const text = await res.text();
13
+ const data = text ? JSON.parse(text) : undefined;
14
+ if (!res.ok) {
15
+ const said = typeof data === 'object' && data && 'detail' in data ? String(data.detail) : res.statusText;
16
+ throw new CliError(`${res.status}: ${said}`);
17
+ }
18
+ return data;
19
+ }
20
+ /** A public call (no key): the issuer's discovery, an app's public look. */
21
+ export async function reach(url) {
22
+ try {
23
+ const res = await fetch(url, { headers: { 'User-Agent': 'aiveth-cli' } });
24
+ return { ok: res.ok, status: res.status };
25
+ }
26
+ catch {
27
+ return { ok: false, status: 0 };
28
+ }
29
+ }
package/dist/index.js ADDED
@@ -0,0 +1,119 @@
1
+ #!/usr/bin/env node
2
+ /* `aiveth` — Aiveth's command line (`commands.ts` holds what each command does). */
3
+ import { createInterface } from 'node:readline';
4
+ import { Writable } from 'node:stream';
5
+ import * as cmd from './commands.js';
6
+ import { DEFAULT_BASE, credentialsPath, forget, load, save } from './credentials.js';
7
+ import { call, CliError } from './http.js';
8
+ const HELP = `aiveth — Aiveth's command line
9
+
10
+ aiveth login save an API key (typed here, never on the command line)
11
+ aiveth logout
12
+ aiveth init --app <client_id> write the issuer and client ID to .env.local, and the next steps
13
+ aiveth env pull --app <client_id> write the issuer and client ID to .env.local
14
+ aiveth doctor check this project's Aiveth setup
15
+ aiveth config pull [--out <file>] your sign-in settings as a file
16
+ aiveth config patch <file> [--dry-run]
17
+ aiveth webhooks listen --forward-to <http://localhost:…> [--types user.created,…]
18
+ aiveth testing-token a testing token for your automated tests (Development)
19
+ aiveth redirect-urls list|add|remove --app <client_id> [<url>]
20
+ aiveth people import <file.json> [--dry-run]
21
+
22
+ --file <path> the env file (default .env.local)
23
+ AIVETH_SECRET_KEY and AIVETH_URL override the saved key and address (for CI).
24
+ Docs: https://docs.aiveth.com/sdks/cli`;
25
+ export function parse(argv) {
26
+ const words = [];
27
+ const flags = {};
28
+ for (let i = 0; i < argv.length; i += 1) {
29
+ const arg = argv[i];
30
+ if (!arg.startsWith('--')) {
31
+ words.push(arg);
32
+ continue;
33
+ }
34
+ const [name, value] = arg.slice(2).split('=', 2);
35
+ const next = argv[i + 1];
36
+ if (value !== undefined)
37
+ flags[name] = value;
38
+ else if (next !== undefined && !next.startsWith('--') && name !== 'dry-run') {
39
+ flags[name] = next;
40
+ i += 1;
41
+ }
42
+ else
43
+ flags[name] = true;
44
+ }
45
+ return { words, flags };
46
+ }
47
+ function hidden(question) {
48
+ let muted = false;
49
+ const out = new Writable({ write(chunk, _enc, done) { if (!muted)
50
+ process.stdout.write(chunk); done(); } });
51
+ const rl = createInterface({ input: process.stdin, output: out, terminal: true });
52
+ return new Promise((resolve) => {
53
+ rl.question(question, (answer) => { rl.close(); process.stdout.write('\n'); resolve(answer.trim()); });
54
+ muted = true;
55
+ });
56
+ }
57
+ const text = (v) => (typeof v === 'string' ? v : '');
58
+ export async function run(argv, say = (l) => console.log(l)) {
59
+ const { words, flags } = parse(argv);
60
+ const [first = 'help', second = '', third = ''] = words;
61
+ const api = load();
62
+ const file = text(flags.file) || '.env.local';
63
+ const dryRun = flags['dry-run'] === true;
64
+ switch (`${first} ${second}`.trim()) {
65
+ case 'login': {
66
+ const key = await hidden('Paste an API key from the console (API keys): ');
67
+ if (!key.startsWith('aiveth_sk_'))
68
+ throw new CliError('That isn’t an Aiveth API key (they start aiveth_sk_).');
69
+ const base = text(flags.url) || process.env.AIVETH_URL || DEFAULT_BASE;
70
+ await call({ base, key }, 'GET', '/v1/admin/roles').catch((e) => {
71
+ if (e instanceof CliError && e.message.startsWith('401'))
72
+ throw new CliError('Aiveth didn’t accept that key.');
73
+ });
74
+ save(key, base);
75
+ say(`Saved to ${credentialsPath()} (only you can read it).`);
76
+ return 0;
77
+ }
78
+ case 'logout':
79
+ say(forget() ? 'Signed out: the saved key is gone.' : 'No saved key.');
80
+ return 0;
81
+ case 'init':
82
+ await cmd.init(api, text(flags.app), file, say);
83
+ return 0;
84
+ case 'env pull':
85
+ await cmd.envPull(api, text(flags.app), file, say);
86
+ return 0;
87
+ case 'doctor': return (await cmd.doctor(api, file, say)) ? 0 : 1;
88
+ case 'config pull':
89
+ await cmd.configPull(api, text(flags.out) || undefined, say);
90
+ return 0;
91
+ case 'config patch':
92
+ await cmd.configPatch(api, third, dryRun, say);
93
+ return 0;
94
+ case 'webhooks listen':
95
+ await cmd.listen(api, text(flags['forward-to']), text(flags.types).split(',').filter(Boolean), say);
96
+ return 0;
97
+ case 'testing-token':
98
+ await cmd.testingToken(api, say);
99
+ return 0;
100
+ case 'redirect-urls list':
101
+ case 'redirect-urls add':
102
+ case 'redirect-urls remove':
103
+ await cmd.redirectUrls(api, second, text(flags.app), third, say);
104
+ return 0;
105
+ case 'people import':
106
+ await cmd.peopleImport(api, third, dryRun, say);
107
+ return 0;
108
+ default:
109
+ say(HELP);
110
+ return first === 'help' || first === '--help' ? 0 : 1;
111
+ }
112
+ }
113
+ const invoked = process.argv[1] ?? '';
114
+ if (invoked.endsWith('/aiveth') || invoked.endsWith('index.js')) {
115
+ run(process.argv.slice(2)).then((code) => { process.exitCode = code; }, (e) => {
116
+ console.error(e instanceof CliError ? e.message : e);
117
+ process.exitCode = 1;
118
+ });
119
+ }
package/dist/sign.js ADDED
@@ -0,0 +1,11 @@
1
+ /* Standard Webhooks signing, as Aiveth signs every webhook: `webhook-signature` =
2
+ * "v1," + base64 HMAC-SHA256 over "id.timestamp.body", keyed with the secret after `whsec_`. */
3
+ import { createHmac, randomBytes } from 'node:crypto';
4
+ export function newSecret() {
5
+ return `whsec_${randomBytes(24).toString('base64')}`;
6
+ }
7
+ export function signed(secret, id, timestamp, body) {
8
+ const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
9
+ const signature = createHmac('sha256', key).update(`${id}.${timestamp}.${body}`).digest('base64');
10
+ return { 'webhook-id': id, 'webhook-timestamp': String(timestamp), 'webhook-signature': `v1,${signature}` };
11
+ }
package/package.json CHANGED
@@ -1,6 +1,24 @@
1
1
  {
2
2
  "name": "@aiveth/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.35.0",
4
+ "description": "Aiveth's command line: set a project up, check it, pull and apply settings, forward webhooks to localhost, testing tokens, return addresses and people import.",
5
+ "license": "Apache-2.0",
6
+ "author": "Aiveth team",
7
+ "keywords": ["aiveth", "auth", "cli", "webhooks", "oidc"],
8
+ "type": "module",
9
+ "bin": { "aiveth": "./dist/index.js" },
10
+ "files": ["dist", "LICENSE", "README.md", "CHANGELOG.md"],
11
+ "engines": { "node": ">=18.17" },
12
+ "publishConfig": { "access": "public" },
13
+ "scripts": {
14
+ "build": "tsc -p tsconfig.build.json",
15
+ "typecheck": "tsc -p tsconfig.json --noEmit",
16
+ "test": "vitest run",
17
+ "prepublishOnly": "npm run typecheck && npm test && npm run build"
18
+ },
19
+ "devDependencies": {
20
+ "@types/node": "20.17.10",
21
+ "typescript": "5.6.3",
22
+ "vitest": "2.1.8"
23
+ }
24
+ }