@dibssoftware/dibs 0.0.180 → 0.0.195
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 +111 -1
- package/README.md +10 -8
- package/bin/dibs.mjs +379 -74
- package/docs/agents.md +303 -0
- package/docs/council.md +88 -0
- package/docs/files.md +3 -3
- package/docs/guard.md +86 -11
- package/docs/json.md +211 -0
- package/docs/later.md +5 -5
- package/docs/machines.md +6 -6
- package/docs/questions.md +104 -3
- package/docs/reference.md +124 -30
- package/docs/relay.md +135 -11
- package/docs/releasing.md +7 -1
- package/docs/scheduling.md +28 -6
- package/docs/secrets.md +53 -0
- package/docs/simulators.md +3 -3
- package/docs/windows.md +3 -3
- package/package.json +1 -1
- package/skills/dibs/SKILL.md +79 -149
- package/src/about.mjs +341 -0
- package/src/acquire.mjs +113 -28
- package/src/after.mjs +127 -0
- package/src/agents.mjs +2 -1
- package/src/alerts.mjs +109 -48
- package/src/answers.mjs +2 -2
- package/src/board.mjs +21 -16
- package/src/broker.mjs +23 -7
- package/src/carry.mjs +287 -0
- package/src/codex.mjs +132 -0
- package/src/commands.mjs +254 -86
- package/src/config.mjs +85 -14
- package/src/connect.mjs +4 -2
- package/src/cool.mjs +28 -12
- package/src/council.mjs +482 -0
- package/src/cwd.mjs +9 -0
- package/src/decisions.mjs +250 -0
- package/src/declare.mjs +96 -0
- package/src/diskreport.mjs +306 -0
- package/src/diskuse.mjs +420 -0
- package/src/diskwarn.mjs +68 -13
- package/src/doctor.mjs +149 -0
- package/src/doors.mjs +547 -0
- package/src/durable.mjs +143 -0
- package/src/envs.mjs +372 -0
- package/src/events.mjs +7 -2
- package/src/files.mjs +121 -7
- package/src/guard.mjs +288 -105
- package/src/guardd.mjs +8 -1
- package/src/halt.mjs +63 -0
- package/src/handoffs.mjs +362 -0
- package/src/history.mjs +34 -4
- package/src/hogs.mjs +36 -8
- package/src/jobprogress.mjs +283 -0
- package/src/later.mjs +21 -10
- package/src/lock.mjs +51 -11
- package/src/measure.mjs +60 -14
- package/src/media.mjs +240 -0
- package/src/news.mjs +31 -0
- package/src/notes.mjs +49 -8
- package/src/notices.mjs +126 -43
- package/src/ondemand.mjs +25 -2
- package/src/outcome.mjs +163 -0
- package/src/overlap.mjs +2 -2
- package/src/override.mjs +149 -79
- package/src/owner.mjs +15 -2
- package/src/people.mjs +236 -0
- package/src/pickup.mjs +72 -0
- package/src/picture.mjs +321 -0
- package/src/plain.mjs +84 -18
- package/src/platform.mjs +29 -7
- package/src/preempt.mjs +123 -15
- package/src/primer.mjs +91 -20
- package/src/prints.mjs +99 -0
- package/src/proc.mjs +11 -1
- package/src/progress.mjs +49 -3
- package/src/proof.mjs +102 -0
- package/src/push.mjs +271 -0
- package/src/questions.mjs +328 -57
- package/src/quota.mjs +1 -1
- package/src/recap.mjs +205 -0
- package/src/relay.mjs +262 -26
- package/src/remote.mjs +23 -10
- package/src/reviewgate.mjs +268 -0
- package/src/reviews.mjs +377 -0
- package/src/route.mjs +263 -0
- package/src/rules.mjs +216 -0
- package/src/schedule.mjs +238 -44
- package/src/schema.mjs +62 -0
- package/src/scratch.mjs +2 -2
- package/src/serve.mjs +3 -2
- package/src/service.mjs +5 -1
- package/src/signed.mjs +97 -0
- package/src/simpool.mjs +46 -1
- package/src/spend.mjs +375 -0
- package/src/state.mjs +43 -17
- package/src/talk.mjs +1082 -134
- package/src/thin.sh +2 -0
- package/src/trail.mjs +290 -0
- package/src/trailnote.mjs +209 -0
- package/src/util.mjs +7 -0
- package/src/vault.mjs +435 -0
- package/src/vendors.mjs +327 -0
- package/src/version.mjs +1 -1
- package/src/web.mjs +354 -60
- package/src/work.mjs +487 -0
- package/src/worker.mjs +7 -1
package/src/vault.mjs
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
// dibs secret: credentials an agent can use without ever seeing them. The person stores a value
|
|
2
|
+
// once; an agent runs one command with it (dibs secret run NAME -- cmd), where it's $NAME for
|
|
3
|
+
// that command alone, and the command's output comes back with the value blanked out. Every use
|
|
4
|
+
// is on the record. The values live in the macOS Keychain (through the security CLI), or, where
|
|
5
|
+
// there's none, in a file encrypted with AES-256-GCM. What dibs keeps beside them (vault.json)
|
|
6
|
+
// is names, rules and the use log, never a value. docs/secrets.md has the threat model.
|
|
7
|
+
//
|
|
8
|
+
// The one exception to "agents may do anything the person can": approving a use, loosening a
|
|
9
|
+
// secret's rules and replacing a stored value are the person's alone. An agent that could hand
|
|
10
|
+
// itself a credential would make the whole thing theatre. Agents may still store a new secret,
|
|
11
|
+
// tighten the rules, and revoke.
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import os from 'node:os';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import crypto from 'node:crypto';
|
|
16
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
17
|
+
import { fileURLToPath } from 'node:url';
|
|
18
|
+
import { HOME } from './config.mjs';
|
|
19
|
+
import { underLock, commit } from './lock.mjs';
|
|
20
|
+
import { identity } from './proc.mjs';
|
|
21
|
+
import { actor } from './owner.mjs';
|
|
22
|
+
import { projectKey } from './files.mjs';
|
|
23
|
+
import { event } from './events.mjs';
|
|
24
|
+
import { writePrints, readPrints, find, MIN_LEN } from './prints.mjs';
|
|
25
|
+
import { die, say, now, dur, clock, fakeFull } from './util.mjs';
|
|
26
|
+
import { readJSON } from './durable.mjs';
|
|
27
|
+
|
|
28
|
+
const FILE = path.join(HOME, 'vault.json');
|
|
29
|
+
const LOCK = path.join(HOME, 'vault.lock');
|
|
30
|
+
// The values, where there's no Keychain: encrypted, its key kept apart from it.
|
|
31
|
+
const STORE = path.join(HOME, 'vault.enc');
|
|
32
|
+
// The key sits outside ~/.dibs by default, so a copy of ~/.dibs alone opens nothing.
|
|
33
|
+
const KEY = process.env.DIBS_SECRET_KEY || (process.env.DIBS_HOME ? path.join(HOME, 'vault.key') : path.join(os.homedir(), '.config', 'dibs', 'vault.key'));
|
|
34
|
+
// A --file secret is written here for one command, and gone when it ends.
|
|
35
|
+
const RUNS = path.join(HOME, 'vault-run');
|
|
36
|
+
const BIN = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'dibs.mjs');
|
|
37
|
+
const LOCK_WAIT = 5000;
|
|
38
|
+
// The use log keeps this many; older ones go first.
|
|
39
|
+
const LOG_KEEP = 500;
|
|
40
|
+
// How long a use waits for the person to say yes before giving up (exit 75: it didn't run).
|
|
41
|
+
const ASK_FOR = 30 * 6e4;
|
|
42
|
+
// Exit 78: the use was refused (a rule, or the person said no). Nothing ran.
|
|
43
|
+
export const REFUSED = 78;
|
|
44
|
+
const NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
|
|
45
|
+
// How strict each way of asking is: an agent may move a secret up this list, never down.
|
|
46
|
+
const ASK = { never: 0, session: 1, each: 2 };
|
|
47
|
+
const DEFAULT_RULES = { projects: [], agents: [], ask: 'session' };
|
|
48
|
+
|
|
49
|
+
// ---- where the values live ------------------------------------------------------------
|
|
50
|
+
|
|
51
|
+
const keychain = () => (process.env.DIBS_SECRET_STORE || (process.platform === 'darwin' ? 'keychain' : 'file')) === 'keychain';
|
|
52
|
+
const SECURITY = () => process.env.DIBS_SECURITY || '/usr/bin/security';
|
|
53
|
+
// A test home's secrets never mix with the real ones.
|
|
54
|
+
const SERVICE = process.env.DIBS_HOME ? `dibs secret (${HOME})` : 'dibs secret';
|
|
55
|
+
|
|
56
|
+
// Stored base64, so reading it back with -w is unambiguous whatever the value holds. The value
|
|
57
|
+
// goes in on stdin (security -i), never on a command line another process could read.
|
|
58
|
+
function kcSet(name, value) {
|
|
59
|
+
const hex = Buffer.from(Buffer.from(value, 'utf8').toString('base64')).toString('hex');
|
|
60
|
+
const r = spawnSync(SECURITY(), ['-i'], { input: `add-generic-password -U -s "${SERVICE}" -a "${name}" -X ${hex}\n`, encoding: 'utf8' });
|
|
61
|
+
if (r.status !== 0 || /error|fail/i.test(r.stderr || '')) die(`couldn't store ${name} in the Keychain: ${(r.stderr || r.error?.message || '').trim() || `security exited ${r.status}`}`, 1);
|
|
62
|
+
}
|
|
63
|
+
function kcGet(name) {
|
|
64
|
+
const r = spawnSync(SECURITY(), ['find-generic-password', '-s', SERVICE, '-a', name, '-w'], { encoding: 'utf8' });
|
|
65
|
+
if (r.status !== 0) return null;
|
|
66
|
+
return Buffer.from(r.stdout.trim(), 'base64').toString('utf8');
|
|
67
|
+
}
|
|
68
|
+
function kcDelete(name) {
|
|
69
|
+
spawnSync(SECURITY(), ['delete-generic-password', '-s', SERVICE, '-a', name], { encoding: 'utf8' });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function fileKey() {
|
|
73
|
+
try { const k = Buffer.from(fs.readFileSync(KEY, 'utf8').trim(), 'base64'); if (k.length === 32) return k; } catch {}
|
|
74
|
+
const k = crypto.randomBytes(32);
|
|
75
|
+
fs.mkdirSync(path.dirname(KEY), { recursive: true, mode: 0o700 });
|
|
76
|
+
fs.writeFileSync(KEY, k.toString('base64'), { mode: 0o600, flag: 'wx' });
|
|
77
|
+
return k;
|
|
78
|
+
}
|
|
79
|
+
function fileAll() {
|
|
80
|
+
let box = {};
|
|
81
|
+
try { box = JSON.parse(fs.readFileSync(STORE, 'utf8')); } catch {}
|
|
82
|
+
return box;
|
|
83
|
+
}
|
|
84
|
+
function fileSet(name, value) {
|
|
85
|
+
const key = fileKey(), iv = crypto.randomBytes(12);
|
|
86
|
+
const c = crypto.createCipheriv('aes-256-gcm', key, iv);
|
|
87
|
+
c.setAAD(Buffer.from(`dibs-secret ${name}`));
|
|
88
|
+
const box = fileAll();
|
|
89
|
+
if (value == null) delete box[name];
|
|
90
|
+
else box[name] = Buffer.concat([iv, c.update(value, 'utf8'), c.final(), c.getAuthTag()]).toString('base64');
|
|
91
|
+
fs.mkdirSync(HOME, { recursive: true });
|
|
92
|
+
fs.writeFileSync(`${STORE}.${process.pid}`, JSON.stringify(box), { mode: 0o600 });
|
|
93
|
+
fs.renameSync(`${STORE}.${process.pid}`, STORE);
|
|
94
|
+
}
|
|
95
|
+
function fileGet(name) {
|
|
96
|
+
const b = fileAll()[name];
|
|
97
|
+
if (!b) return null;
|
|
98
|
+
try {
|
|
99
|
+
const buf = Buffer.from(b, 'base64');
|
|
100
|
+
const d = crypto.createDecipheriv('aes-256-gcm', fileKey(), buf.subarray(0, 12));
|
|
101
|
+
d.setAAD(Buffer.from(`dibs-secret ${name}`));
|
|
102
|
+
d.setAuthTag(buf.subarray(buf.length - 16));
|
|
103
|
+
return Buffer.concat([d.update(buf.subarray(12, buf.length - 16)), d.final()]).toString('utf8');
|
|
104
|
+
} catch { return null; }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const putValue = (name, value) => (keychain() ? kcSet(name, value) : fileSet(name, value));
|
|
108
|
+
const getValue = name => (keychain() ? kcGet(name) : fileGet(name));
|
|
109
|
+
const dropValue = name => (keychain() ? kcDelete(name) : fileSet(name, null));
|
|
110
|
+
|
|
111
|
+
// ---- names, rules and the log ---------------------------------------------------------
|
|
112
|
+
|
|
113
|
+
function load() {
|
|
114
|
+
try {
|
|
115
|
+
const s = readJSON(FILE);
|
|
116
|
+
return { secrets: s.secrets || {}, approved: s.approved || {}, log: Array.isArray(s.log) ? s.log : [] };
|
|
117
|
+
} catch { return { secrets: {}, approved: {}, log: [] }; }
|
|
118
|
+
}
|
|
119
|
+
function locked(fn) {
|
|
120
|
+
fs.mkdirSync(HOME, { recursive: true });
|
|
121
|
+
const r = underLock(LOCK, h => {
|
|
122
|
+
const s = load();
|
|
123
|
+
const out = fn(s);
|
|
124
|
+
s.log = s.log.slice(-LOG_KEEP);
|
|
125
|
+
commit(h, FILE, JSON.stringify(s, null, 1), { fake: () => fakeFull('state') });
|
|
126
|
+
return out;
|
|
127
|
+
}, { wait: LOCK_WAIT, files: [FILE] });
|
|
128
|
+
if (!r) die(`${LOCK} stayed locked for ${LOCK_WAIT / 1000} s. Try again in a moment.`, 75);
|
|
129
|
+
return r.out;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// The fingerprints the guard and the redaction read, from the values themselves.
|
|
133
|
+
function refreshPrints(s) {
|
|
134
|
+
const values = {};
|
|
135
|
+
for (const n of Object.keys(s.secrets)) if (!s.secrets[n].revoked) { const v = getValue(n); if (v != null) values[n] = v; }
|
|
136
|
+
writePrints(values);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const list = s => (Array.isArray(s) ? s : []);
|
|
140
|
+
// Whether new rules let in anything the old ones didn't.
|
|
141
|
+
export function loosens(old, next) {
|
|
142
|
+
const wider = (a, b) => (list(a).length && (!list(b).length || list(b).some(x => !list(a).includes(x))));
|
|
143
|
+
return (ASK[next.ask] ?? 2) < (ASK[old.ask] ?? 2) || wider(old.projects, next.projects) || wider(old.agents, next.agents);
|
|
144
|
+
}
|
|
145
|
+
const ruleLine = r => [list(r.projects).length ? `projects ${r.projects.join(', ')}` : 'any project',
|
|
146
|
+
list(r.agents).length ? `agents ${r.agents.join(', ')}` : 'any agent',
|
|
147
|
+
{ each: 'the person says yes to each use', session: 'the person says yes once per session', never: 'no asking' }[r.ask] || r.ask].join('; ');
|
|
148
|
+
|
|
149
|
+
// ---- the command ----------------------------------------------------------------------
|
|
150
|
+
|
|
151
|
+
const HELP = `dibs secret: credentials agents use without seeing them.
|
|
152
|
+
dibs secret set NAME [--file path] store a value: typed (not shown), piped on stdin, or read from a file. Never on the command line
|
|
153
|
+
dibs secret run NAME[,NAME2] [--file] [-m why] -- <command>
|
|
154
|
+
run one command with $NAME set (--file: $NAME is a file holding it, deleted after);
|
|
155
|
+
its output comes back with the value blanked. Exit 78: refused, nothing ran
|
|
156
|
+
dibs secret rules NAME [--projects a,b|--any-project] [--agents x,y|--any-agent] [--ask each|session|never]
|
|
157
|
+
who may use it, and when the person is asked (default: once per session).
|
|
158
|
+
Only the person can loosen them; anyone can tighten
|
|
159
|
+
dibs secret list [--json] names, rules and last use (never values)
|
|
160
|
+
dibs secret log [NAME] [-n 20] [--json] every use: who, when, which command
|
|
161
|
+
dibs secret revoke NAME delete the value; anyone may`;
|
|
162
|
+
|
|
163
|
+
export async function secret(args) {
|
|
164
|
+
const [verb, ...rest] = args;
|
|
165
|
+
if (!verb || /^(help|-h|--help)$/.test(verb)) return console.log(HELP);
|
|
166
|
+
if (verb === 'set') return set(rest);
|
|
167
|
+
if (verb === 'run') return runWith(rest);
|
|
168
|
+
if (verb === 'rules') return rules(rest);
|
|
169
|
+
if (verb === 'list' || verb === 'ls') return show(rest);
|
|
170
|
+
if (verb === 'log') return log(rest);
|
|
171
|
+
if (verb === 'revoke') return revoke(rest);
|
|
172
|
+
die(`dibs secret ${verb}? It's set, run, rules, list, log or revoke.\n${HELP}`);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function parseRules(args, from) {
|
|
176
|
+
const r = { ...from, projects: [...list(from.projects)], agents: [...list(from.agents)] };
|
|
177
|
+
const rest = [];
|
|
178
|
+
for (let i = 0; i < args.length; i++) {
|
|
179
|
+
const a = args[i], next = () => args[++i] ?? die(`${a} needs a value`);
|
|
180
|
+
if (a === '--projects') r.projects = next().split(',').map(x => x.trim()).filter(Boolean);
|
|
181
|
+
else if (a === '--any-project') r.projects = [];
|
|
182
|
+
else if (a === '--agents') r.agents = next().split(',').map(x => x.trim()).filter(Boolean);
|
|
183
|
+
else if (a === '--any-agent') r.agents = [];
|
|
184
|
+
else if (a === '--ask') { r.ask = next(); if (!(r.ask in ASK)) die('--ask is each, session or never'); }
|
|
185
|
+
else rest.push(a);
|
|
186
|
+
}
|
|
187
|
+
return { r, rest };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// The value, from a file, from stdin when it's piped, or typed at a prompt with nothing shown.
|
|
191
|
+
async function readValue(file) {
|
|
192
|
+
if (file) return fs.readFileSync(file, 'utf8').replace(/\r?\n$/, '');
|
|
193
|
+
if (!process.stdin.isTTY) return fs.readFileSync(0, 'utf8').replace(/\r?\n$/, '');
|
|
194
|
+
process.stderr.write('Value (not shown): ');
|
|
195
|
+
process.stdin.setRawMode(true);
|
|
196
|
+
process.stdin.resume();
|
|
197
|
+
let v = '';
|
|
198
|
+
return new Promise(resolve => {
|
|
199
|
+
process.stdin.on('data', d => {
|
|
200
|
+
for (const ch of d.toString('utf8')) {
|
|
201
|
+
if (ch === '\r' || ch === '\n') { process.stdin.setRawMode(false); process.stdin.pause(); process.stderr.write('\n'); return resolve(v); }
|
|
202
|
+
if (ch === '\u0003') { process.stdin.setRawMode(false); process.stderr.write('\n'); process.exit(130); }
|
|
203
|
+
if (ch === '\u007f') v = v.slice(0, -1); else v += ch;
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async function set(args) {
|
|
210
|
+
let file = null;
|
|
211
|
+
const words = [];
|
|
212
|
+
for (let i = 0; i < args.length; i++) {
|
|
213
|
+
if (args[i] === '--file') file = args[++i] ?? die('--file needs a path');
|
|
214
|
+
else if (args[i].startsWith('--')) die(`dibs secret set takes a name and --file, not ${args[i]}. Set rules after: dibs secret rules`);
|
|
215
|
+
else words.push(args[i]);
|
|
216
|
+
}
|
|
217
|
+
const [name, ...extra] = words;
|
|
218
|
+
if (!name || !NAME.test(name)) die('name the secret the way its command reads it, like an environment variable: dibs secret set ASC_KEY');
|
|
219
|
+
// A value typed after the name would sit in the shell's history and the process table.
|
|
220
|
+
if (extra.length) die(`a value never goes on the command line, where history and the process list keep it. Nothing was stored. Pipe it in, type it at the prompt (dibs secret set ${name}), or use --file.`);
|
|
221
|
+
const who = actor();
|
|
222
|
+
// Replacing a value the person stored would point every use of it at a credential an agent chose.
|
|
223
|
+
const replaces = () => { const was = load().secrets[name]; return !!was && !was.revoked; };
|
|
224
|
+
const notYours = () => die(`only the person can replace ${name}'s value. You're an agent (${who.name}): refused, nothing was stored (exit 78). Ask them: dibs question "Replace ${name}?" --needs-you "store the new value: dibs secret set ${name}"`, REFUSED);
|
|
225
|
+
if (who.agent && replaces()) notYours();
|
|
226
|
+
const value = await readValue(file);
|
|
227
|
+
if (!value) die('that value is empty. Nothing was stored.');
|
|
228
|
+
if (who.agent && replaces()) notYours();
|
|
229
|
+
putValue(name, value);
|
|
230
|
+
const fresh = locked(s => {
|
|
231
|
+
const was = s.secrets[name];
|
|
232
|
+
s.secrets[name] = { at: now(), by: who.name, rules: was && !was.revoked ? was.rules : { ...DEFAULT_RULES } };
|
|
233
|
+
refreshPrints(s);
|
|
234
|
+
return !was || was.revoked;
|
|
235
|
+
});
|
|
236
|
+
event({ kind: 'override', act: 'secret set', secret: name, by: who.name, byAgent: who.agent, ...(who.via && { via: who.via }) });
|
|
237
|
+
console.log(`${fresh ? 'Stored' : 'Replaced'} ${name}${keychain() ? ' in the Keychain' : ''}. Use it: dibs secret run ${name} -- <command that reads $${name}>`);
|
|
238
|
+
if (value.length < MIN_LEN) say(`it's under ${MIN_LEN} characters, so dibs can't spot it in commands or output: it would match ordinary text.`);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function rules(args) {
|
|
242
|
+
const name = args[0];
|
|
243
|
+
const s0 = load();
|
|
244
|
+
const sec = s0.secrets[name];
|
|
245
|
+
if (!name || !sec || sec.revoked) die(`no secret called ${name || '?'}. See them: dibs secret list`, 1);
|
|
246
|
+
if (args.length === 1) return console.log(`${name}: ${ruleLine(sec.rules)}`);
|
|
247
|
+
const { r, rest } = parseRules(args.slice(1), sec.rules);
|
|
248
|
+
if (rest.length) die(`dibs secret rules ${name} takes --projects, --any-project, --agents, --any-agent and --ask, not ${rest.join(' ')}`);
|
|
249
|
+
const who = actor();
|
|
250
|
+
// An agent widening who may use a credential is the one thing it may not do for the person.
|
|
251
|
+
if (who.agent && loosens(sec.rules, r)) die(`only the person can loosen ${name}'s rules; you may tighten them. Nothing changed. Ask them: dibs question "Let me use ${name} for ..." --needs-you "change ${name}'s rules"`);
|
|
252
|
+
locked(s => { s.secrets[name].rules = r; });
|
|
253
|
+
event({ kind: 'override', act: 'secret rules', secret: name, rules: r, by: who.name, byAgent: who.agent });
|
|
254
|
+
console.log(`${name}: ${ruleLine(r)}`);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function revoke(args) {
|
|
258
|
+
const name = args[0];
|
|
259
|
+
if (!name) die('which one? dibs secret revoke NAME');
|
|
260
|
+
const who = actor();
|
|
261
|
+
const had = locked(s => {
|
|
262
|
+
if (!s.secrets[name] || s.secrets[name].revoked) return false;
|
|
263
|
+
dropValue(name);
|
|
264
|
+
Object.assign(s.secrets[name], { revoked: now(), revokedBy: who.name });
|
|
265
|
+
delete s.approved[name];
|
|
266
|
+
refreshPrints(s);
|
|
267
|
+
return true;
|
|
268
|
+
});
|
|
269
|
+
if (!had) die(`no secret called ${name}. See them: dibs secret list`, 1);
|
|
270
|
+
event({ kind: 'override', act: 'secret revoke', secret: name, by: who.name, byAgent: who.agent, ...(who.via && { via: who.via }) });
|
|
271
|
+
console.log(`Revoked ${name}: its value is deleted, and nothing can use it until the person stores it again.`);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// What the page and the phone see: names, rules and uses. Never a value.
|
|
275
|
+
export function secretsJson() {
|
|
276
|
+
const s = load();
|
|
277
|
+
return {
|
|
278
|
+
secrets: Object.entries(s.secrets).filter(([, x]) => !x.revoked).map(([name, x]) => {
|
|
279
|
+
const uses = s.log.filter(l => l.name === name);
|
|
280
|
+
return { name, at: x.at, by: x.by, rules: x.rules, rule: ruleLine(x.rules), uses: uses.length, last: uses.at(-1) || null };
|
|
281
|
+
}),
|
|
282
|
+
log: s.log.slice(-100).reverse(),
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function show(args) {
|
|
287
|
+
const j = secretsJson();
|
|
288
|
+
if (args.includes('--json')) return console.log(JSON.stringify(j));
|
|
289
|
+
if (!j.secrets.length) return console.log('No secrets stored. Store one: dibs secret set NAME');
|
|
290
|
+
for (const x of j.secrets) {
|
|
291
|
+
console.log(`${x.name} stored ${dur(now() - x.at)} ago by ${x.by}; ${x.rule}`);
|
|
292
|
+
console.log(` ${x.last ? `last used ${dur(now() - x.last.at)} ago by ${x.last.who}${x.last.ok ? '' : ' (refused)'}` : 'never used'}${x.uses > 1 ? `, ${x.uses} uses` : ''}`);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function log(args) {
|
|
297
|
+
let name = null, n = 20, json = false;
|
|
298
|
+
for (let i = 0; i < args.length; i++) {
|
|
299
|
+
if (args[i] === '-n') n = Number(args[++i]) || 20;
|
|
300
|
+
else if (args[i] === '--json') json = true;
|
|
301
|
+
else name = args[i];
|
|
302
|
+
}
|
|
303
|
+
const rows = load().log.filter(l => !name || l.name === name).slice(-n);
|
|
304
|
+
if (json) return console.log(JSON.stringify(rows));
|
|
305
|
+
if (!rows.length) return console.log(name ? `${name} hasn't been used.` : 'No secret has been used.');
|
|
306
|
+
for (const l of rows) console.log(`${clock(l.at)} ${l.name} ${l.who}${l.ok ? '' : ` refused: ${l.why}`} ${l.cmd}`);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// ---- using one --------------------------------------------------------------------------
|
|
310
|
+
|
|
311
|
+
const sessionKey = id => process.env.CLAUDE_CODE_SESSION_ID || (id.spid ? `${id.spid}:${id.sstart}` : id.who);
|
|
312
|
+
|
|
313
|
+
// Asks the person with a --needs-you question and waits. True only for the person's own yes:
|
|
314
|
+
// an agent's answer doesn't count, so a phone's answer (signed after Face ID) does.
|
|
315
|
+
async function personSays(names, who, cmdText, why) {
|
|
316
|
+
const text = `Let ${who} use ${names.join(' and ')} for one command: ${cmdText}`;
|
|
317
|
+
const r = await new Promise(resolve => {
|
|
318
|
+
const p = spawn(process.execPath, [BIN, 'question', text.slice(0, 300), '--options', 'yes,no', '--recommend', 'yes', '-m', why || 'it needs the credential to run this',
|
|
319
|
+
'--needs-you', `approve using ${names.join(' and ')}`, '--wait', '--timeout', `${ASK_FOR / 6e4}m`], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
320
|
+
let out = '', err = '';
|
|
321
|
+
p.stdout.on('data', d => { out += d; });
|
|
322
|
+
p.stderr.on('data', d => { err += d; process.stderr.write(d); });
|
|
323
|
+
p.on('close', code => resolve({ code, out: out.trim(), err }));
|
|
324
|
+
});
|
|
325
|
+
if (r.code === 75) return { wait: true };
|
|
326
|
+
if (r.code !== 0) return { no: 'the question could not be asked' };
|
|
327
|
+
if (/an agent, not the person/.test(r.err)) return { no: 'an agent answered, and only the person can approve a secret' };
|
|
328
|
+
return r.out.toLowerCase() === 'yes' ? { yes: true } : { no: `the person said ${r.out || 'no'}` };
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function record(entry) {
|
|
332
|
+
try { locked(s => { s.log.push(entry); if (entry.ok && entry.session) { for (const n of entry.names) { s.approved[n] = list(s.approved[n]); if (!s.approved[n].includes(entry.session)) s.approved[n].push(entry.session); s.approved[n] = s.approved[n].slice(-50); } } }); } catch {}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// Copies a stream, with every stored value in it blanked. A value can straddle two chunks, so
|
|
336
|
+
// the last (longest value - 1) characters wait for the next chunk.
|
|
337
|
+
function blanking(input, output, pairs) {
|
|
338
|
+
const values = pairs.map(p => p[1]);
|
|
339
|
+
const hold = Math.max(0, ...values.map(v => v.length)) - 1;
|
|
340
|
+
let buf = '';
|
|
341
|
+
const clean = t => { for (const [n, v] of pairs) t = t.split(v).join(`[secret ${n}]`); return t; };
|
|
342
|
+
input.setEncoding('utf8');
|
|
343
|
+
input.on('data', d => {
|
|
344
|
+
buf += d;
|
|
345
|
+
const cut = Math.max(0, buf.length - hold);
|
|
346
|
+
// Never cut inside a value: if one starts before the cut and runs past it, wait for it whole.
|
|
347
|
+
let safe = cut;
|
|
348
|
+
for (const v of values) for (let at = buf.indexOf(v); at >= 0 && at < cut; at = buf.indexOf(v, at + 1)) if (at + v.length > safe) safe = at + v.length;
|
|
349
|
+
output.write(clean(buf.slice(0, safe)));
|
|
350
|
+
buf = buf.slice(safe);
|
|
351
|
+
});
|
|
352
|
+
return new Promise(resolve => input.on('end', () => { output.write(clean(buf)); resolve(); }));
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function sweepRuns() {
|
|
356
|
+
try {
|
|
357
|
+
for (const f of fs.readdirSync(RUNS)) {
|
|
358
|
+
const pid = Number(f.split('-')[0]);
|
|
359
|
+
try { process.kill(pid, 0); } catch { fs.rmSync(path.join(RUNS, f), { force: true }); }
|
|
360
|
+
}
|
|
361
|
+
} catch {}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
async function runWith(args) {
|
|
365
|
+
const dd = args.indexOf('--');
|
|
366
|
+
if (dd < 0 || dd === args.length - 1) die('what should run with it? dibs secret run NAME -- <command>');
|
|
367
|
+
const cmd = args.slice(dd + 1);
|
|
368
|
+
let asFile = false, why = null;
|
|
369
|
+
const words = [];
|
|
370
|
+
const head = args.slice(0, dd);
|
|
371
|
+
for (let i = 0; i < head.length; i++) {
|
|
372
|
+
if (head[i] === '--file') asFile = true;
|
|
373
|
+
else if (head[i] === '-m') why = head[++i] ?? die('-m needs a reason');
|
|
374
|
+
else if (head[i].startsWith('-')) die(`dibs secret run takes --file and -m, not ${head[i]}`);
|
|
375
|
+
else words.push(head[i]);
|
|
376
|
+
}
|
|
377
|
+
const names = [...new Set(words.join(',').split(',').map(x => x.trim()).filter(Boolean))];
|
|
378
|
+
if (!names.length) die('which secret? dibs secret run NAME -- <command>');
|
|
379
|
+
const id = identity();
|
|
380
|
+
const who = actor();
|
|
381
|
+
const project = process.env.DIBS_REPO || projectKey(process.cwd());
|
|
382
|
+
const s = load();
|
|
383
|
+
const cmdText = cmd.join(' ').slice(0, 200);
|
|
384
|
+
const base = { at: now(), names, name: names.join(','), who: who.name, agent: who.agent, project, cmd: cmdText, ...(why && { why: why.slice(0, 200) }) };
|
|
385
|
+
const refuse = (msg, code = REFUSED) => {
|
|
386
|
+
record({ ...base, ok: false, why: msg });
|
|
387
|
+
event({ kind: 'secret', act: 'refused', secret: base.name, who: who.name, cmd: cmdText, why: msg });
|
|
388
|
+
die(`${msg}. Nothing ran.`, code);
|
|
389
|
+
};
|
|
390
|
+
for (const n of names) {
|
|
391
|
+
const sec = s.secrets[n];
|
|
392
|
+
if (!sec || sec.revoked) refuse(`there's no secret called ${n} (dibs secret list)`, 1);
|
|
393
|
+
const r = sec.rules || DEFAULT_RULES;
|
|
394
|
+
if (list(r.projects).length && !r.projects.some(p => p === project || path.basename(project).replace(/\.git$/, '') === p)) refuse(`${n} is only for ${r.projects.join(', ')}, and this is ${project}. The person can add it: dibs secret rules ${n} --projects ...`);
|
|
395
|
+
if (list(r.agents).length && who.agent && !r.agents.includes(id.agent || id.who) && !r.agents.includes(who.name)) refuse(`${n} is only for ${r.agents.join(', ')}. The person can add you: dibs secret rules ${n} --agents ...`);
|
|
396
|
+
}
|
|
397
|
+
// The person running it themselves needs nobody's yes.
|
|
398
|
+
const session = sessionKey(id);
|
|
399
|
+
if (who.agent) {
|
|
400
|
+
const need = names.filter(n => { const a = s.secrets[n].rules?.ask || 'session'; return a === 'each' || (a === 'session' && !list(s.approved[n]).includes(session)); });
|
|
401
|
+
if (need.length) {
|
|
402
|
+
const a = await personSays(need, who.name, cmdText, why);
|
|
403
|
+
if (a.wait) refuse(`no answer from the person in ${ASK_FOR / 6e4} minutes (exit 75: run the same command again to ask again)`, 75);
|
|
404
|
+
if (!a.yes) refuse(`${a.no}`);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
const values = names.map(n => getValue(n));
|
|
408
|
+
const missing = names.filter((n, i) => values[i] == null);
|
|
409
|
+
if (missing.length) refuse(`${missing.join(', ')} ${missing.length === 1 ? 'has' : 'have'} no value stored on this machine (the Keychain entry is gone?). The person can store it again: dibs secret set ${missing[0]}`, 1);
|
|
410
|
+
const env = { ...process.env, DIBS_SECRET_NAMES: names.join(',') };
|
|
411
|
+
const files = [];
|
|
412
|
+
if (asFile) {
|
|
413
|
+
sweepRuns();
|
|
414
|
+
fs.mkdirSync(RUNS, { recursive: true, mode: 0o700 });
|
|
415
|
+
names.forEach((n, i) => { const f = path.join(RUNS, `${process.pid}-${n}`); fs.writeFileSync(f, values[i], { mode: 0o600 }); files.push(f); env[n] = f; });
|
|
416
|
+
} else names.forEach((n, i) => { env[n] = values[i]; });
|
|
417
|
+
record({ ...base, ok: true, session: who.agent ? session : null });
|
|
418
|
+
event({ kind: 'secret', act: 'used', secret: base.name, who: who.name, cmd: cmdText, project });
|
|
419
|
+
const child = spawn(cmd[0], cmd.slice(1), { env, stdio: ['inherit', 'pipe', 'pipe'] });
|
|
420
|
+
const gone = () => { for (const f of files) fs.rmSync(f, { force: true }); };
|
|
421
|
+
for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(sig, () => { try { child.kill(sig); } catch {} });
|
|
422
|
+
const pairs = names.map((n, i) => [n, values[i]]).filter(([, v]) => v.length);
|
|
423
|
+
const piped = [blanking(child.stdout, process.stdout, pairs), blanking(child.stderr, process.stderr, pairs)];
|
|
424
|
+
const code = await new Promise(resolve => {
|
|
425
|
+
child.on('error', e => { gone(); resolve(e.code === 'ENOENT' ? 127 : 126); say(`couldn't start ${cmd[0]}: ${e.message}`); });
|
|
426
|
+
child.on('close', (c, sig) => resolve(c ?? 128 + (os.constants.signals[sig] || 0)));
|
|
427
|
+
});
|
|
428
|
+
await Promise.all(piped);
|
|
429
|
+
gone();
|
|
430
|
+
process.exit(code);
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
// For the guard and dibs run: whether any stored value is in this text, by name.
|
|
434
|
+
export const valuesIn = text => [...new Set(find(text).map(h => h.name))];
|
|
435
|
+
export { readPrints };
|