@qerexa/cli 0.0.0-stage → 0.1.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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +65 -2
  3. package/index.mjs +308 -0
  4. package/package.json +40 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Qerexa Inc.
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,66 @@
1
- # Temporary Holding Version
1
+ # Qerexa CLI (preview)
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
+ Put a Qerexa check in front of your CI jobs, and manage short-lived secrets
4
+ from the terminal.
5
+
6
+ `qerexa-cli gate` exits 0 only when Qerexa gives a clear, current yes: an
7
+ `allowed` decision with its own ID and an expiry still in the future. Every
8
+ other outcome exits non-zero, so the pipeline step that depends on it simply
9
+ doesn't run. When a human review is needed, `--no-wait` exits with code 2 right
10
+ away instead of polling.
11
+
12
+ An approved review still exits non-zero. Approving a review isn't permission
13
+ to deploy or move money, so feed that decision into your own action-bound
14
+ execution step rather than treating it as a green light.
15
+
16
+ This is a preview, not a certified execution control. Redirects are never
17
+ followed, so your API key stays with the API host you configure.
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ npm install -g @qerexa/cli # or: npx @qerexa/cli help
23
+ qerexa-cli help
24
+ ```
25
+
26
+ From this repository:
27
+
28
+ ```bash
29
+ node packages/cli/index.mjs help
30
+ ```
31
+
32
+ ## Config
33
+
34
+ The CLI reads `~/.qerexarc` (or legacy `~/.trustrc`) JSON:
35
+
36
+ ```json
37
+ { "apiKey": "qrx_api_...", "baseUrl": "https://api.qerexa.com" }
38
+ ```
39
+
40
+ The base URL defaults to `https://api.qerexa.com`. For local development pass
41
+ `--base-url http://localhost:3000` or set `QEREXA_BASE_URL`.
42
+
43
+ Environment overrides:
44
+
45
+ - `QEREXA_API_KEY`
46
+ - `QEREXA_BASE_URL`
47
+ - Legacy: `TRUST_API_KEY`, `TRUST_BASE_URL`
48
+
49
+ ## Commands
50
+
51
+ - `qerexa-cli create [--ttl <seconds>] [--stdin|--text <value>]`
52
+ - `qerexa-cli read <id>`
53
+ - `qerexa-cli burn <id>`
54
+ - `qerexa-cli gate --action deploy.production --file .github/workflows/deploy.yml --source cicd --provider github`
55
+
56
+ The `gate` command submits the supplied file as intent. Inspect it for embedded
57
+ secrets before use. It polls a durable review flow, but even an approved flow
58
+ does not yield a successful gate result.
59
+
60
+ Each `gate` call sends an `Idempotency-Key`. In GitHub Actions or GitLab CI the
61
+ key is derived from the run ID, the run attempt (or job ID), and a hash of the
62
+ request, so retries of the same gate deduplicate while other gates in the run,
63
+ and re-run attempts, are evaluated afresh. Outside CI a random key is used. Set
64
+ `QEREXA_REQUEST_ID` to override it; use a value unique to each gate request.
65
+
66
+ Output is JSON.
package/index.mjs ADDED
@@ -0,0 +1,308 @@
1
+ #!/usr/bin/env node
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+
6
+ const HELP = `qerexa-cli <command>
7
+
8
+ Commands:
9
+ create [--ttl <seconds>] [--stdin] Create a secret (reads plaintext from --stdin or --text)
10
+ read <id> Read a secret by id
11
+ burn <id> Burn a secret by id
12
+ gate --action <action> [--file <yaml>] Evaluate; review approval requires separate execution authorization
13
+
14
+ Options:
15
+ --base-url <url> Override API base URL (default https://api.qerexa.com or config)
16
+ --text <value> Plaintext for create when --stdin is not used
17
+ --source <type> canonical, kubernetes, cicd, or llm_tool_call
18
+ --provider <name> CI provider hint (github, gitlab, jenkins, generic)
19
+ --actor <name> Machine actor identity (default ci-runner)
20
+ --reason <text> Human-readable reason for the action
21
+ --no-wait Return immediately when human approval is required
22
+ --approval-timeout <seconds> Overall wait limit (default 1800)
23
+
24
+ Config:
25
+ Reads ~/.qerexarc (or legacy ~/.trustrc) JSON { "apiKey": "qrx_api_...", "baseUrl": "https://api.qerexa.com" }
26
+ Env overrides: QEREXA_API_KEY, QEREXA_BASE_URL (legacy: TRUST_API_KEY, TRUST_BASE_URL)
27
+ `;
28
+
29
+ function loadConfig() {
30
+ const home = process.env.HOME || process.env.USERPROFILE || "";
31
+ const primaryPath = path.join(home, ".qerexarc");
32
+ const legacyPath = path.join(home, ".trustrc");
33
+ for (const configPath of [primaryPath, legacyPath]) {
34
+ if (fs.existsSync(configPath)) {
35
+ try {
36
+ return JSON.parse(fs.readFileSync(configPath, "utf8"));
37
+ } catch {
38
+ // fall through
39
+ }
40
+ }
41
+ }
42
+ return {};
43
+ }
44
+
45
+ function parseArgs(argv) {
46
+ const [command, ...rest] = argv;
47
+ const args = { command, positional: [] };
48
+ for (let i = 0; i < rest.length; i++) {
49
+ const token = rest[i];
50
+ if (token === "--ttl") {
51
+ args.ttl = Number(rest[++i]);
52
+ } else if (token === "--stdin") {
53
+ args.stdin = true;
54
+ } else if (token === "--base-url") {
55
+ args.baseUrl = rest[++i];
56
+ } else if (token === "--text") {
57
+ args.text = rest[++i];
58
+ } else if (token === "--action") {
59
+ args.action = rest[++i];
60
+ } else if (token === "--file") {
61
+ args.file = rest[++i];
62
+ } else if (token === "--source") {
63
+ args.source = rest[++i];
64
+ } else if (token === "--provider") {
65
+ args.provider = rest[++i];
66
+ } else if (token === "--actor") {
67
+ args.actor = rest[++i];
68
+ } else if (token === "--reason") {
69
+ args.reason = rest[++i];
70
+ } else if (token === "--approval-timeout") {
71
+ args.approvalTimeout = Number(rest[++i]);
72
+ } else if (token === "--no-wait") {
73
+ args.noWait = true;
74
+ } else if (!token.startsWith("--")) {
75
+ args.positional.push(token);
76
+ }
77
+ }
78
+ return args;
79
+ }
80
+
81
+ function delay(milliseconds) {
82
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
83
+ }
84
+
85
+ async function resilientFetch(url, init, attempts = 3) {
86
+ let lastError;
87
+ for (let attempt = 0; attempt < attempts; attempt++) {
88
+ try {
89
+ // The API never redirects. Following one would send X-API-Key to another
90
+ // host (fetch drops only Authorization), and a 3xx is never an allow.
91
+ const response = await fetch(url, {
92
+ ...init,
93
+ redirect: "manual",
94
+ signal: AbortSignal.timeout(10_000),
95
+ });
96
+ if (response.status !== 429 && response.status < 500) return response;
97
+ if (attempt === attempts - 1) return response;
98
+ } catch (error) {
99
+ lastError = error;
100
+ if (attempt === attempts - 1) throw error;
101
+ }
102
+ await delay(Math.min(1000, 200 * 2 ** attempt));
103
+ }
104
+ throw lastError ?? new Error("Qerexa request failed");
105
+ }
106
+
107
+ // One key per distinct request: retries of the same gate dedupe, while other
108
+ // gates in the same CI run (and re-run attempts) are evaluated afresh.
109
+ function gateIdempotencyKey(payload) {
110
+ if (process.env.QEREXA_REQUEST_ID) return process.env.QEREXA_REQUEST_ID;
111
+ const runId = process.env.GITHUB_RUN_ID || process.env.CI_PIPELINE_ID;
112
+ if (!runId) return randomUUID();
113
+ const attempt = process.env.GITHUB_RUN_ATTEMPT || process.env.CI_JOB_ID || "1";
114
+ const digest = createHash("sha256").update(JSON.stringify(payload)).digest("hex").slice(0, 32);
115
+ return `ci-${runId}-${attempt}-${digest}`;
116
+ }
117
+
118
+ async function gateAction(args, apiKey, baseUrl) {
119
+ if (!args.action) throw new Error("gate requires --action <action>");
120
+ const payload = {
121
+ action: args.action,
122
+ actor: args.actor || process.env.CI_JOB_NAME || process.env.GITHUB_JOB || "ci-runner",
123
+ reasoning: args.reason || `CI gate for ${args.action}`,
124
+ metadata: {
125
+ run_id:
126
+ process.env.GITHUB_RUN_ID || process.env.CI_PIPELINE_ID || process.env.BUILD_NUMBER || null,
127
+ repository: process.env.GITHUB_REPOSITORY || process.env.CI_PROJECT_PATH || null,
128
+ ref: process.env.GITHUB_REF || process.env.CI_COMMIT_REF_NAME || null,
129
+ },
130
+ };
131
+ if (args.file) {
132
+ payload.intent = {
133
+ source: args.source || "cicd",
134
+ provider: args.provider || "generic",
135
+ payload: fs.readFileSync(args.file, "utf8"),
136
+ };
137
+ }
138
+
139
+ const response = await resilientFetch(`${baseUrl}/api/v1/gates/evaluate`, {
140
+ method: "POST",
141
+ headers: {
142
+ Authorization: `Bearer ${apiKey}`,
143
+ "X-API-Key": apiKey,
144
+ "Content-Type": "application/json",
145
+ "Idempotency-Key": gateIdempotencyKey(payload),
146
+ },
147
+ body: JSON.stringify(payload),
148
+ });
149
+ const result = await response.json().catch(() => ({}));
150
+ const expiresAt = Date.parse(result.expires_at || "");
151
+ if (response.status === 200 && result.decision === "allowed" && result.allowed === true
152
+ && typeof result.decision_id === "string" && result.decision_id
153
+ && Number.isFinite(expiresAt) && expiresAt > Date.now()) {
154
+ console.log(JSON.stringify(result, null, 2));
155
+ return;
156
+ }
157
+ if (response.status !== 202 || result.decision !== "approval_required"
158
+ || result.allowed !== false || typeof result.flow_id !== "string" || !result.flow_id) {
159
+ throw new Error(
160
+ `Qerexa blocked ${args.action}: ${result.reason || result.error || response.status}`
161
+ );
162
+ }
163
+ console.error(`Qerexa approval required. Flow: ${result.flow_id}`);
164
+ if (args.noWait) {
165
+ console.log(JSON.stringify(result, null, 2));
166
+ process.exitCode = 2;
167
+ return;
168
+ }
169
+
170
+ const configuredTimeout = Number.isFinite(args.approvalTimeout)
171
+ ? args.approvalTimeout * 1000
172
+ : 1_800_000;
173
+ const serverDeadline = Date.parse(result.review_deadline || "");
174
+ const deadline = Number.isFinite(serverDeadline)
175
+ ? Math.min(Date.now() + configuredTimeout, serverDeadline)
176
+ : Date.now() + configuredTimeout;
177
+ while (Date.now() < deadline) {
178
+ const statusResponse = await resilientFetch(
179
+ `${baseUrl}/api/v1/trust-flows/${encodeURIComponent(result.flow_id)}`,
180
+ { headers: { Authorization: `Bearer ${apiKey}`, "X-API-Key": apiKey } }
181
+ );
182
+ if (!statusResponse.ok) throw new Error(`Qerexa flow status failed: ${statusResponse.status}`);
183
+ const flow = await statusResponse.json().catch(() => ({}));
184
+ for (const field of ["expires_at", "time_window_end"]) {
185
+ if (flow[field] !== undefined) {
186
+ const expiry = Date.parse(flow[field]);
187
+ if (!Number.isFinite(expiry) || expiry <= Date.now()) {
188
+ throw new Error(`Qerexa flow ${result.flow_id} has invalid or expired ${field}`);
189
+ }
190
+ }
191
+ }
192
+ if (flow.time_window_start !== undefined) {
193
+ const start = Date.parse(flow.time_window_start);
194
+ if (!Number.isFinite(start) || start > Date.now()) {
195
+ throw new Error(`Qerexa flow ${result.flow_id} execution window is not open`);
196
+ }
197
+ }
198
+ const status = String(flow.status || "").toLowerCase();
199
+ if (status === "approved") {
200
+ throw new Error(`Qerexa review flow ${result.flow_id} was approved, but separate action-bound execution authorization is required`);
201
+ }
202
+ if (status === "completed") {
203
+ throw new Error(`Qerexa flow ${result.flow_id} is already completed; do not execute again`);
204
+ }
205
+ if (["rejected", "denied", "blocked", "expired", "revoked"].includes(status)) {
206
+ throw new Error(`Qerexa flow ${result.flow_id} ended with status ${status}`);
207
+ }
208
+ await delay(Math.min(2000, Math.max(0, deadline - Date.now())));
209
+ }
210
+ throw new Error(`Qerexa approval timed out for flow ${result.flow_id}`);
211
+ }
212
+
213
+ async function readStdin() {
214
+ const chunks = [];
215
+ for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
216
+ return Buffer.concat(chunks).toString("utf8");
217
+ }
218
+
219
+ async function trFetch(pathname, method, apiKey, body, baseUrl) {
220
+ const res = await fetch(`${baseUrl}${pathname}`, {
221
+ method,
222
+ headers: {
223
+ "Content-Type": "application/json",
224
+ "X-API-Key": apiKey,
225
+ },
226
+ body: body ? JSON.stringify(body) : undefined,
227
+ });
228
+ if (!res.ok) {
229
+ const text = await res.text();
230
+ throw new Error(`${method} ${pathname} failed ${res.status}: ${text}`);
231
+ }
232
+ return res.json();
233
+ }
234
+
235
+ async function main() {
236
+ const cfg = loadConfig();
237
+ const args = parseArgs(process.argv.slice(2));
238
+
239
+ if (!args.command || args.command === "help" || args.command === "--help") {
240
+ console.log(HELP);
241
+ return;
242
+ }
243
+
244
+ const apiKey = process.env.QEREXA_API_KEY || process.env.TRUST_API_KEY || cfg.apiKey;
245
+ const baseUrl =
246
+ args.baseUrl ||
247
+ process.env.QEREXA_BASE_URL ||
248
+ process.env.TRUST_BASE_URL ||
249
+ cfg.baseUrl ||
250
+ "https://api.qerexa.com";
251
+ if (!apiKey) {
252
+ console.error('API key missing. Set QEREXA_API_KEY or ~/.qerexarc { "apiKey": "..." }');
253
+ process.exit(1);
254
+ }
255
+
256
+ if (args.command === "gate") {
257
+ await gateAction(args, apiKey, baseUrl.replace(/\/$/, ""));
258
+ return;
259
+ }
260
+
261
+ if (args.command === "create") {
262
+ const ttl = Number.isFinite(args.ttl) ? args.ttl : undefined;
263
+ let plaintext = args.text;
264
+ if (args.stdin) {
265
+ plaintext = await readStdin();
266
+ }
267
+ if (!plaintext) {
268
+ console.error("Provide plaintext via --text or --stdin");
269
+ process.exit(1);
270
+ }
271
+ const body = { plaintext, one_time: false };
272
+ if (ttl) body.ttl_seconds = ttl;
273
+ const res = await trFetch("/api/v1/secrets", "POST", apiKey, body, baseUrl);
274
+ console.log(JSON.stringify(res, null, 2));
275
+ return;
276
+ }
277
+
278
+ if (args.command === "read") {
279
+ const id = args.positional[0];
280
+ if (!id) {
281
+ console.error("Usage: qerexa-cli read <id>");
282
+ process.exit(1);
283
+ }
284
+ const res = await trFetch(`/api/v1/secret/${id}`, "GET", apiKey, undefined, baseUrl);
285
+ console.log(JSON.stringify(res, null, 2));
286
+ return;
287
+ }
288
+
289
+ if (args.command === "burn") {
290
+ const id = args.positional[0];
291
+ if (!id) {
292
+ console.error("Usage: qerexa-cli burn <id>");
293
+ process.exit(1);
294
+ }
295
+ const res = await trFetch(`/api/v1/secret/${id}/burn`, "POST", apiKey, undefined, baseUrl);
296
+ console.log(JSON.stringify(res, null, 2));
297
+ return;
298
+ }
299
+
300
+ console.error("Unknown command\n");
301
+ console.log(HELP);
302
+ process.exit(1);
303
+ }
304
+
305
+ main().catch((err) => {
306
+ console.error(err instanceof Error ? err.message : err);
307
+ process.exit(1);
308
+ });
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@qerexa/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Preview CLI for Qerexa execution gates and secret workflows.",
5
+ "type": "module",
6
+ "bin": {
7
+ "qerexa-cli": "index.mjs",
8
+ "trust-cli": "index.mjs"
9
+ },
10
+ "files": [
11
+ "index.mjs",
12
+ "README.md",
13
+ "LICENSE"
14
+ ],
15
+ "scripts": {
16
+ "test": "node --test index.test.mjs"
17
+ },
18
+ "keywords": [
19
+ "qerexa",
20
+ "trust-rails",
21
+ "secrets",
22
+ "cli"
23
+ ],
24
+ "author": "Qerexa",
25
+ "license": "MIT",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/rodriguew/Trust-Rails.git",
29
+ "directory": "packages/cli"
30
+ },
31
+ "homepage": "https://qerexa.com",
32
+ "bugs": {
33
+ "url": "https://github.com/rodriguew/Trust-Rails/issues"
34
+ },
35
+ "engines": {
36
+ "node": ">=18.18.0"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public",
40
+ "registry": "https://registry.npmjs.org/"
41
+ }
42
+ }