oneie 5.6.0 → 5.7.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.
Files changed (41) hide show
  1. package/README.md +29 -0
  2. package/dist/package.json +2 -2
  3. package/dist/src/index.js +15 -15
  4. package/dist/src/init.d.ts +10 -1
  5. package/dist/src/init.js +26 -11
  6. package/dist/src/join.d.ts +1 -1
  7. package/dist/src/join.js +2 -1
  8. package/dist/src/key-publish.d.ts +40 -0
  9. package/dist/src/key-publish.js +232 -0
  10. package/dist/src/key-seal.d.ts +21 -0
  11. package/dist/src/key-seal.js +142 -0
  12. package/dist/src/key.js +22 -5
  13. package/dist/src/lib/age-plugin.d.ts +51 -0
  14. package/dist/src/lib/age-plugin.js +130 -0
  15. package/dist/src/lib/env-sealed.d.ts +53 -0
  16. package/dist/src/lib/env-sealed.js +184 -0
  17. package/dist/src/lib/journey.d.ts +137 -0
  18. package/dist/src/lib/journey.js +232 -0
  19. package/dist/src/lib/key-receipt.d.ts +48 -0
  20. package/dist/src/lib/key-receipt.js +116 -0
  21. package/dist/src/lib/lock-lookup.d.ts +40 -0
  22. package/dist/src/lib/lock-lookup.js +92 -0
  23. package/dist/src/lib/message-seal.d.ts +63 -0
  24. package/dist/src/lib/message-seal.js +150 -0
  25. package/dist/src/lib/vault-read.d.ts +24 -0
  26. package/dist/src/lib/vault-read.js +77 -0
  27. package/dist/src/media.d.ts +15 -0
  28. package/dist/src/media.js +126 -4
  29. package/dist/src/secrets-device.d.ts +32 -0
  30. package/dist/src/secrets-device.js +127 -0
  31. package/dist/src/secrets-give.d.ts +125 -0
  32. package/dist/src/secrets-give.js +236 -0
  33. package/dist/src/secrets-run.d.ts +31 -0
  34. package/dist/src/secrets-run.js +182 -0
  35. package/dist/src/secrets.d.ts +32 -0
  36. package/dist/src/secrets.js +197 -0
  37. package/dist/src/start.d.ts +15 -0
  38. package/dist/src/start.js +200 -0
  39. package/dist/src/write.d.ts +43 -0
  40. package/dist/src/write.js +174 -0
  41. package/package.json +2 -2
@@ -0,0 +1,182 @@
1
+ /**
2
+ * secrets-run.ts — `one run -- <cmd…>` and `one secrets run -- <cmd…>`; `one secrets hash`.
3
+ * (text/secrets.md deliverable 2; text/secrets-todo.md § C2.)
4
+ *
5
+ * Opens `.env.sealed` once, hands the values to ONE child process through its environment,
6
+ * and writes nothing anywhere. The order is the point:
7
+ *
8
+ * 1. read the file's exact bytes, parse the header (no key yet)
9
+ * 2. sha256 of those bytes must equal the `sealed_hash` of the vault named by `# vault`
10
+ * — a file the vault does not know opens NOTHING (the key is not even loaded)
11
+ * 3. open every value with the owner's paper identity, in memory
12
+ * 4. spawn the child with `{ ...process.env, ...values }`, stdio inherited
13
+ * 5. zero the decrypted buffers; exit with the child's exit code
14
+ *
15
+ * There is no flag that skips step 2. `process.env` of this process is never changed, no
16
+ * value is printed, and an error names a variable or a line number, never a value or the key.
17
+ */
18
+ import { spawn } from 'node:child_process';
19
+ import { createHash } from 'node:crypto';
20
+ import { readFileSync } from 'node:fs';
21
+ import { constants as osConstants } from 'node:os';
22
+ import { resolve } from 'node:path';
23
+ import { Command } from 'commander';
24
+ import { jsonMode } from './lib/client.js';
25
+ import { parseSealed } from './lib/env-sealed.js';
26
+ import { ageModule, loadSecretsKey, MAX_INPUT_BYTES } from './lib/message-seal.js';
27
+ import { readVault } from './lib/vault-read.js';
28
+ function fail(cmd, f, exit = 1) {
29
+ if (jsonMode(cmd))
30
+ process.stdout.write(JSON.stringify(f) + '\n');
31
+ else
32
+ process.stderr.write(`error ${f.error}\n`);
33
+ process.exitCode = exit;
34
+ }
35
+ const sha256 = (b) => createHash('sha256').update(b).digest('hex');
36
+ function readSealedBytes(file) {
37
+ try {
38
+ const b = readFileSync(resolve(file));
39
+ if (b.length > MAX_INPUT_BYTES)
40
+ return { ok: false, error: `${file} is more than ${MAX_INPUT_BYTES / (1024 * 1024)} MiB`, code: 'too_big' };
41
+ return b;
42
+ }
43
+ catch {
44
+ return { ok: false, error: `cannot read ${file}`, code: 'no_input' };
45
+ }
46
+ }
47
+ /**
48
+ * Was `--` the word that ended this command's own flags? Commander strips the `--`, so look
49
+ * at the raw argv: between the command's name and the first `--` there may be only flags
50
+ * (and the values of --file / --key). Any other word there means `one run bun dev`, where
51
+ * `bun` would be taken for the command without the person ever saying where it starts.
52
+ */
53
+ function dashDashStartsCommand(c) {
54
+ let root = c;
55
+ while (root.parent)
56
+ root = root.parent;
57
+ // commander sets rawArgs on the root; its typings do not declare it
58
+ const raw = (root.rawArgs ?? []).slice(2);
59
+ const at = raw.indexOf(c.name());
60
+ if (at < 0)
61
+ return false;
62
+ const rest = raw.slice(at + 1);
63
+ const end = rest.indexOf('--');
64
+ if (end < 0)
65
+ return false;
66
+ for (let i = 0; i < end; i++) {
67
+ const t = rest[i];
68
+ if (t === '--file' || t === '--key')
69
+ i++;
70
+ else if (!t.startsWith('-'))
71
+ return false;
72
+ }
73
+ return true;
74
+ }
75
+ export async function runAction(cmdArgs, o, c) {
76
+ if (cmdArgs.length === 0 || !dashDashStartsCommand(c)) {
77
+ return fail(c, { ok: false, error: 'usage: one run [--file .env.sealed] [--key <file>] -- <command> [args…] (the -- is required)', code: 'usage' }, 2);
78
+ }
79
+ const bytes = readSealedBytes(o.file);
80
+ if (!Buffer.isBuffer(bytes))
81
+ return fail(c, bytes);
82
+ const sealed = parseSealed(bytes.toString('utf8'));
83
+ if ('ok' in sealed)
84
+ return fail(c, sealed);
85
+ // The check comes first and has no way around it.
86
+ if (!sealed.vault) {
87
+ return fail(c, { ok: false, error: `${o.file} names no vault (# vault <id>) — there is nothing to check it against, so it is not run`, code: 'unknown_file' });
88
+ }
89
+ const vault = await readVault(sealed.vault);
90
+ if ('ok' in vault)
91
+ return fail(c, { ok: false, error: vault.error, code: 'cannot_verify' });
92
+ if (!vault.sealedHash) {
93
+ return fail(c, { ok: false, error: 'the vault has no sealed hash for this file — set one with: one secrets hash, then set_sealed_hash', code: 'unknown_file' });
94
+ }
95
+ if (vault.sealedHash.toLowerCase() !== sha256(bytes)) {
96
+ return fail(c, { ok: false, error: `${o.file} is not the file your vault knows — its hash differs, so nothing was opened`, code: 'unknown_file' });
97
+ }
98
+ const k = await loadSecretsKey(o.key);
99
+ if ('ok' in k)
100
+ return fail(c, k);
101
+ const opened = [];
102
+ try {
103
+ const age = await ageModule();
104
+ const dec = new TextDecoder();
105
+ const values = {};
106
+ for (const e of sealed.entries) {
107
+ let plain;
108
+ try {
109
+ plain = age.decrypt(e.file, [k.secret]);
110
+ }
111
+ catch {
112
+ return fail(c, { ok: false, error: `${e.name} does not open with this key`, code: 'no_identity' });
113
+ }
114
+ opened.push(plain);
115
+ values[e.name] = dec.decode(plain);
116
+ }
117
+ const [bin, ...args] = cmdArgs;
118
+ const code = await new Promise((done) => {
119
+ const child = spawn(bin, args, { stdio: 'inherit', env: { ...process.env, ...values } });
120
+ // spawn has copied the environment; nothing in this process needs a value any more.
121
+ for (const p of opened)
122
+ p.fill(0);
123
+ for (const n of Object.keys(values))
124
+ delete values[n];
125
+ const forward = (sig) => () => {
126
+ child.kill(sig);
127
+ };
128
+ const onInt = forward('SIGINT');
129
+ const onTerm = forward('SIGTERM');
130
+ process.on('SIGINT', onInt);
131
+ process.on('SIGTERM', onTerm);
132
+ const finish = (n) => {
133
+ process.off('SIGINT', onInt);
134
+ process.off('SIGTERM', onTerm);
135
+ done(n);
136
+ };
137
+ child.on('error', (err) => {
138
+ process.stderr.write(`error cannot start ${bin}: ${err.code ?? 'failed'}\n`);
139
+ finish(127);
140
+ });
141
+ child.on('exit', (status, signal) => finish(status ?? 128 + (signal ? (osConstants.signals[signal] ?? 0) : 0)));
142
+ });
143
+ process.exitCode = code;
144
+ }
145
+ finally {
146
+ for (const p of opened)
147
+ p.fill(0);
148
+ k.secret.fill(0);
149
+ }
150
+ }
151
+ /** The `run` subcommand, fresh per call (a Command has one parent). */
152
+ export function buildRun() {
153
+ return new Command('run')
154
+ .description('Run a command with the sealed values in its environment only — nothing is written to disk')
155
+ .argument('[command...]', 'The command and its arguments, after --')
156
+ .option('--file <file>', 'The sealed file', '.env.sealed')
157
+ .option('--key <file>', 'Key file made by `one key new --out` (else ONE_WALLET_MNEMONIC). Never read from stdin')
158
+ .allowUnknownOption() // a stray flag must reach the usage check (exit 2), not commander's own error
159
+ .action((cmdArgs, o, c) => runAction(cmdArgs, o, c));
160
+ }
161
+ /** The top-level `one run`. */
162
+ export const runCmd = () => buildRun();
163
+ /** `one secrets hash [file]` — the sha256 an owner sets on their vault. Names no value, needs no key. */
164
+ export async function hashAction(file, _o, c) {
165
+ const bytes = readSealedBytes(file);
166
+ if (!Buffer.isBuffer(bytes))
167
+ return fail(c, bytes);
168
+ const sealed = parseSealed(bytes.toString('utf8'));
169
+ if ('ok' in sealed)
170
+ return fail(c, sealed);
171
+ const hash = sha256(bytes);
172
+ if (jsonMode(c))
173
+ process.stdout.write(JSON.stringify({ ok: true, file: resolve(file), sealedHash: hash }) + '\n');
174
+ else
175
+ process.stdout.write(hash + '\n');
176
+ }
177
+ export function buildHash() {
178
+ return new Command('hash')
179
+ .description("Print the sha256 of a sealed file — the value to set on your vault with set_sealed_hash")
180
+ .argument('[file]', 'The sealed file', '.env.sealed')
181
+ .action(hashAction);
182
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * secrets.ts — `one secrets seal | run | add-device | give`: the sealed .env.
3
+ * (text/secrets.md deliverables 1 and 5; text/secrets-todo.md § C1.)
4
+ *
5
+ * `seal` is the one verb built here. It turns a plaintext .env into `.env.sealed` v1 —
6
+ * names readable, one age file per value — and the readers of every value are ONLY the
7
+ * owner's: the paper lock (the 24 words, HKDF `secrets-x25519-v1`) and the device locks
8
+ * the owner listed in ~/.one/secrets-readers.json (`add-device`, C3, writes it). A lock
9
+ * that is in neither is refused `not_your_reader`: no other person and no agent ever
10
+ * holds a key.
11
+ *
12
+ * Like key-seal.ts it is offline, never prompts, answers `--json`, and exits 0 done /
13
+ * 1 refused. It never prints a value, a line of the .env, or the key words; an error
14
+ * names a variable or a line number. The key is a key file (`--key`) or
15
+ * ONE_WALLET_MNEMONIC — never stdin.
16
+ *
17
+ * `run` and `hash` live in secrets-run.ts (C2). `add-device` (secrets-device.ts, C3) makes this
18
+ * Mac a reader; a Secure Enclave lock among the readers seals through the `age` program
19
+ * (lib/age-plugin.ts). `give` (secrets-give.ts, C8) hands a key to ONE, sealed to the lock ONE's
20
+ * vault names and signed by an agent's own key.
21
+ */
22
+ import { Command } from 'commander';
23
+ import { type Fail } from './lib/message-seal.js';
24
+ export declare function fail(cmd: Command, f: Fail): void;
25
+ /** The owner's device-lock list. ONE_SECRETS_READERS moves it (tests); `add-device` (C3) writes it. */
26
+ export declare function readersFile(): string;
27
+ /**
28
+ * The owner's device locks: a JSON array of locks, or `{ "readers": [...] }`, each entry a
29
+ * lock string or `{ "lock": "…" }`. No file is no devices — the paper lock is then the only reader.
30
+ */
31
+ export declare function deviceLocks(path?: string): string[] | Fail;
32
+ export declare function secretsCmd(): Command;
@@ -0,0 +1,197 @@
1
+ /**
2
+ * secrets.ts — `one secrets seal | run | add-device | give`: the sealed .env.
3
+ * (text/secrets.md deliverables 1 and 5; text/secrets-todo.md § C1.)
4
+ *
5
+ * `seal` is the one verb built here. It turns a plaintext .env into `.env.sealed` v1 —
6
+ * names readable, one age file per value — and the readers of every value are ONLY the
7
+ * owner's: the paper lock (the 24 words, HKDF `secrets-x25519-v1`) and the device locks
8
+ * the owner listed in ~/.one/secrets-readers.json (`add-device`, C3, writes it). A lock
9
+ * that is in neither is refused `not_your_reader`: no other person and no agent ever
10
+ * holds a key.
11
+ *
12
+ * Like key-seal.ts it is offline, never prompts, answers `--json`, and exits 0 done /
13
+ * 1 refused. It never prints a value, a line of the .env, or the key words; an error
14
+ * names a variable or a line number. The key is a key file (`--key`) or
15
+ * ONE_WALLET_MNEMONIC — never stdin.
16
+ *
17
+ * `run` and `hash` live in secrets-run.ts (C2). `add-device` (secrets-device.ts, C3) makes this
18
+ * Mac a reader; a Secure Enclave lock among the readers seals through the `age` program
19
+ * (lib/age-plugin.ts). `give` (secrets-give.ts, C8) hands a key to ONE, sealed to the lock ONE's
20
+ * vault names and signed by an agent's own key.
21
+ */
22
+ import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
23
+ import { homedir } from 'node:os';
24
+ import { join, resolve } from 'node:path';
25
+ import { Command } from 'commander';
26
+ import { jsonMode } from './lib/client.js';
27
+ import { isVaultId, parseEnv, parseSealed, renderSealed, sealEntries, verifySealed } from './lib/env-sealed.js';
28
+ import { ageModule, loadSecretsKey, MAX_INPUT_BYTES } from './lib/message-seal.js';
29
+ import { AgePluginError, isPluginLock, PLUGIN_LOCK_RE, requireAge } from './lib/age-plugin.js';
30
+ import { addDeviceAction } from './secrets-device.js';
31
+ import { buildGive } from './secrets-give.js';
32
+ import { buildHash, buildRun } from './secrets-run.js';
33
+ export function fail(cmd, f) {
34
+ if (jsonMode(cmd))
35
+ process.stdout.write(JSON.stringify(f) + '\n');
36
+ else
37
+ process.stderr.write(`error ${f.error}\n`);
38
+ process.exitCode = 1;
39
+ }
40
+ const collect = (v, prev = []) => [...prev, v];
41
+ /** The owner's device-lock list. ONE_SECRETS_READERS moves it (tests); `add-device` (C3) writes it. */
42
+ export function readersFile() {
43
+ return process.env.ONE_SECRETS_READERS?.trim() || join(homedir(), '.one', 'secrets-readers.json');
44
+ }
45
+ /**
46
+ * The owner's device locks: a JSON array of locks, or `{ "readers": [...] }`, each entry a
47
+ * lock string or `{ "lock": "…" }`. No file is no devices — the paper lock is then the only reader.
48
+ */
49
+ export function deviceLocks(path = readersFile()) {
50
+ if (!existsSync(path))
51
+ return [];
52
+ const badFile = () => ({ ok: false, error: `${path} is not a list of age1… locks`, code: 'bad_readers_file' });
53
+ let parsed;
54
+ try {
55
+ parsed = JSON.parse(readFileSync(path, 'utf8'));
56
+ }
57
+ catch {
58
+ return badFile();
59
+ }
60
+ const list = Array.isArray(parsed) ? parsed : parsed?.readers;
61
+ if (!Array.isArray(list))
62
+ return badFile();
63
+ const locks = [];
64
+ for (const e of list) {
65
+ const l = typeof e === 'string' ? e : e?.lock;
66
+ if (typeof l !== 'string' || !l.trim())
67
+ return badFile();
68
+ locks.push(l.trim());
69
+ }
70
+ return locks;
71
+ }
72
+ async function sealAction(file, o, c) {
73
+ const envPath = resolve(file);
74
+ const outPath = resolve(o.out ?? `${file}.sealed`);
75
+ if (outPath === envPath)
76
+ return fail(c, { ok: false, error: 'the sealed file cannot be the .env itself — pass a different --out', code: 'bad_out' });
77
+ if (o.vault !== undefined && !isVaultId(o.vault))
78
+ return fail(c, { ok: false, error: 'that is not a vault id', code: 'bad_vault' });
79
+ let raw;
80
+ try {
81
+ const b = readFileSync(envPath);
82
+ if (b.length > MAX_INPUT_BYTES)
83
+ return fail(c, { ok: false, error: `${file} is more than ${MAX_INPUT_BYTES / (1024 * 1024)} MiB — too big to seal here`, code: 'too_big' });
84
+ raw = b.toString('utf8');
85
+ }
86
+ catch {
87
+ return fail(c, { ok: false, error: `cannot read ${file}`, code: 'no_input' });
88
+ }
89
+ const k = await loadSecretsKey(o.key);
90
+ if ('ok' in k)
91
+ return fail(c, k);
92
+ try {
93
+ // The readers: the paper lock, the owner's device locks, nobody else.
94
+ const devices = deviceLocks();
95
+ if (!Array.isArray(devices))
96
+ return fail(c, devices);
97
+ const owners = new Set([k.recipient, ...devices]);
98
+ for (const l of o.reader ?? []) {
99
+ if (!owners.has(l.trim())) {
100
+ return fail(c, { ok: false, error: `${l.trim()} is not your lock — a secret is readable only by your paper and your own devices (add one with: one secrets add-device)`, code: 'not_your_reader' });
101
+ }
102
+ }
103
+ const readers = [...owners];
104
+ const age = await ageModule();
105
+ for (const l of readers) {
106
+ if (isPluginLock(l)) {
107
+ // A Secure Enclave lock is sealed through the `age` program. A missing program is a refusal, never a dropped device.
108
+ if (!PLUGIN_LOCK_RE.test(l))
109
+ return fail(c, { ok: false, error: `${l} is not an age lock — it starts age1…`, code: 'bad_key' });
110
+ const bins = requireAge();
111
+ if (typeof bins === 'string') {
112
+ return fail(c, { ok: false, error: bins === 'no_plugin' ? 'a Secure Enclave reader needs `age-plugin-se` — brew install age-plugin-se' : 'a Secure Enclave reader needs `age` — brew install age', code: bins });
113
+ }
114
+ continue;
115
+ }
116
+ try {
117
+ age.decodeRecipient(l);
118
+ }
119
+ catch {
120
+ return fail(c, { ok: false, error: `${l} is not an age lock — it starts age1…`, code: 'bad_key' });
121
+ }
122
+ }
123
+ const entries = parseEnv(raw);
124
+ if (!Array.isArray(entries))
125
+ return fail(c, entries);
126
+ if (entries.length === 0)
127
+ return fail(c, { ok: false, error: `${file} has no NAME=value lines to seal`, code: 'empty_env' });
128
+ const text = renderSealed({ readers, vault: o.vault, entries: await sealEntries(entries, readers) });
129
+ // Write beside the target, open every value back from the bytes on disk, and only then
130
+ // put it in place. The temp file holds sealed bytes only.
131
+ const tmp = `${outPath}.tmp-${process.pid}`;
132
+ writeFileSync(tmp, text, { mode: 0o644 });
133
+ try {
134
+ const back = parseSealed(readFileSync(tmp, 'utf8'));
135
+ if ('ok' in back)
136
+ return fail(c, { ...back, code: 'readback_failed' });
137
+ const bad = await verifySealed(back, entries, k.secret);
138
+ if (bad)
139
+ return fail(c, bad);
140
+ renameSync(tmp, outPath);
141
+ }
142
+ finally {
143
+ if (existsSync(tmp))
144
+ unlinkSync(tmp);
145
+ }
146
+ if (o.remove)
147
+ unlinkSync(envPath);
148
+ const names = entries.map((e) => e.name);
149
+ if (jsonMode(c))
150
+ process.stdout.write(JSON.stringify({ ok: true, file: outPath, names, readers: readers.length, removed: Boolean(o.remove) }) + '\n');
151
+ else {
152
+ process.stdout.write(`sealed ${names.length} value${names.length === 1 ? '' : 's'} → ${outPath} (${readers.length} reader${readers.length === 1 ? '' : 's'})\n`);
153
+ if (o.remove)
154
+ process.stdout.write(`removed ${file}\n`);
155
+ }
156
+ }
157
+ catch (e) {
158
+ // Never `e.message` of a failure that may sit next to a value; the cause is one of a few I/O errors
159
+ // or an age-plugin failure, which carries a code and a fixed message.
160
+ if (e instanceof AgePluginError)
161
+ return fail(c, { ok: false, error: e.message, code: e.code });
162
+ fail(c, { ok: false, error: `could not seal ${file}: ${e.code ?? 'failed'}`, code: 'failed' });
163
+ }
164
+ finally {
165
+ k.secret.fill(0);
166
+ }
167
+ }
168
+ const stub = (name, cycle, description) => new Command(name)
169
+ .description(`${description} (not built yet — ${cycle})`)
170
+ .allowUnknownOption()
171
+ .allowExcessArguments()
172
+ .action(() => {
173
+ process.stderr.write(`one secrets ${name}: not built yet (${cycle})\n`);
174
+ process.exitCode = 2;
175
+ });
176
+ export function secretsCmd() {
177
+ const seal = new Command('seal')
178
+ .description('Seal a .env to .env.sealed — names stay readable, every value is sealed to your paper and your own devices')
179
+ .argument('[file]', 'The .env to seal', '.env')
180
+ .option('--out <file>', 'Where to write the sealed file (default: <file>.sealed)')
181
+ .option('--reader <lock>', "Name a reader to include; it must be your paper lock or one in ~/.one/secrets-readers.json (repeat for several)", collect)
182
+ .option('--vault <id>', "Record the owner's vault id in the file header")
183
+ .option('--remove', 'Delete the .env once every value has been opened back from the sealed file and compared byte for byte')
184
+ .option('--key <file>', 'Key file made by `one key new --out` (else ONE_WALLET_MNEMONIC). Never read from stdin')
185
+ .action(sealAction);
186
+ return new Command('secrets')
187
+ .description('Seal a .env so it is safe to commit; only your paper and your own devices can open it')
188
+ .addCommand(seal)
189
+ .addCommand(buildHash())
190
+ .addCommand(buildRun())
191
+ .addCommand(new Command('add-device')
192
+ .description('Make this Mac a reader of your sealed files — a Secure Enclave key opened by Touch ID')
193
+ .option('--name <label>', 'A name for this Mac (default: its hostname)')
194
+ .option('--replace', 'Make a new key even though one exists (the old one stops being a reader)')
195
+ .action(addDeviceAction))
196
+ .addCommand(buildGive());
197
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `oneie start`, and bare `npx oneie`: the whole journey in the current folder —
3
+ * key → products → test sale → handover link. The logic is `lib/journey.ts`;
4
+ * this file is the wiring: disk, network, Keychain, and the printed receipt.
5
+ *
6
+ * The journey's key lives in THIS folder (`.one/agent.key`, 0600, git-ignored
7
+ * before it is written) and never in ~/.config/one/key — a stray run must not
8
+ * replace the machine key someone already logs in with.
9
+ */
10
+ import { Command } from 'commander';
11
+ /** The flags bare `npx oneie --email …` hands to `start` — the journey's own, nothing else. */
12
+ export declare const START_FLAGS: Set<string>;
13
+ /** Bare `oneie`, or `oneie` led by a journey flag, runs `start`. Everything else is untouched. */
14
+ export declare function startArgv(argv: string[]): string[];
15
+ export declare function startCmd(): Command;
@@ -0,0 +1,200 @@
1
+ /**
2
+ * `oneie start`, and bare `npx oneie`: the whole journey in the current folder —
3
+ * key → products → test sale → handover link. The logic is `lib/journey.ts`;
4
+ * this file is the wiring: disk, network, Keychain, and the printed receipt.
5
+ *
6
+ * The journey's key lives in THIS folder (`.one/agent.key`, 0600, git-ignored
7
+ * before it is written) and never in ~/.config/one/key — a stray run must not
8
+ * replace the machine key someone already logs in with.
9
+ */
10
+ import { Command } from 'commander';
11
+ import { chmodSync, existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
12
+ import { join } from 'node:path';
13
+ import { askPath } from './lib/api-path.js';
14
+ import { jsonMode } from './lib/client.js';
15
+ import { KEY_DIR_NAME, KEY_FILE_NAME, LEGACY_KEY_DIR_NAME, META_FILE_NAME, readKeyFolder, writeKeyFolder } from './lib/keyfile.js';
16
+ import { keychainAvailable, readVaultFolder, vaultPath } from './lib/vaultfile.js';
17
+ import { cliPrefix } from './lib/invoked-as.js';
18
+ import { provisionLocalWallet } from './init.js';
19
+ import { promptSecret, registerSealedWallet } from './wallet.js';
20
+ import { parseProductSpec, runJourney, } from './lib/journey.js';
21
+ const DEFAULT_API = process.env.ONEIE_BASE_URL ?? 'https://one.ie';
22
+ /** The flags bare `npx oneie --email …` hands to `start` — the journey's own, nothing else. */
23
+ export const START_FLAGS = new Set(['--name', '--email', '--product', '--currency', '--wait', '--api']);
24
+ /** Bare `oneie`, or `oneie` led by a journey flag, runs `start`. Everything else is untouched. */
25
+ export function startArgv(argv) {
26
+ if (argv.length === 2)
27
+ return [...argv, 'start'];
28
+ const first = argv[2]?.split('=')[0] ?? '';
29
+ if (START_FLAGS.has(first))
30
+ return [argv[0], argv[1], 'start', ...argv.slice(2)];
31
+ return argv;
32
+ }
33
+ const statePath = (dir) => join(dir, KEY_DIR_NAME, 'journey.json');
34
+ function loadState(dir) {
35
+ const p = statePath(dir);
36
+ if (!existsSync(p))
37
+ return null;
38
+ try {
39
+ const s = JSON.parse(readFileSync(p, 'utf8'));
40
+ return s && s.v === 1 && typeof s.workspace === 'string' ? s : null;
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ }
46
+ /** 0600 and atomic: the state carries the owner link, which is a bearer credential. */
47
+ function saveState(dir, s) {
48
+ const p = statePath(dir);
49
+ const tmp = `${p}.${process.pid}.tmp`;
50
+ writeFileSync(tmp, JSON.stringify(s, null, 2) + '\n', { mode: 0o600 });
51
+ chmodSync(tmp, 0o600);
52
+ renameSync(tmp, p);
53
+ }
54
+ /**
55
+ * Keychain where there is one (Touch ID opens it, nothing is typed); a
56
+ * passphrase only at a real terminal. An agent shell elsewhere is refused by
57
+ * name — never downgraded to a plaintext file.
58
+ */
59
+ async function walletStore(dir) {
60
+ if (keychainAvailable())
61
+ return { kind: 'keychain', dir };
62
+ if (!process.stdin.isTTY) {
63
+ return { error: 'no Apple Keychain here and no terminal to type a passphrase into — run `npx oneie wallet new` in your own terminal, then `npx oneie wallet register --kind agent`' };
64
+ }
65
+ const passphrase = await promptSecret('Passphrase to seal the agent wallet: ');
66
+ if (passphrase !== (await promptSecret('Repeat it: ')))
67
+ return { error: 'passphrases did not match — no wallet was made' };
68
+ if (passphrase.length < 8)
69
+ return { error: 'passphrase too short — no wallet was made' };
70
+ return { kind: 'vault', dir, passphrase };
71
+ }
72
+ function deps(dir, api) {
73
+ return {
74
+ load: () => loadState(dir),
75
+ save: (s) => saveState(dir, s),
76
+ key: () => {
77
+ const f = readKeyFolder(dir);
78
+ if (!f)
79
+ return null;
80
+ const reg = f.meta.regKey;
81
+ return typeof reg === 'string' && reg ? reg : f.apiKey;
82
+ },
83
+ existingKey: () => {
84
+ for (const d of [KEY_DIR_NAME, LEGACY_KEY_DIR_NAME]) {
85
+ if (!existsSync(join(dir, d, KEY_FILE_NAME)))
86
+ continue;
87
+ try {
88
+ const meta = JSON.parse(readFileSync(join(dir, d, META_FILE_NAME), 'utf8'));
89
+ return typeof meta.workspace === 'string' ? meta.workspace : '';
90
+ }
91
+ catch {
92
+ return '';
93
+ }
94
+ }
95
+ return null;
96
+ },
97
+ provision: async (body) => {
98
+ const res = await fetch(`${api}/api/provision/agent`, {
99
+ method: 'POST',
100
+ headers: { 'Content-Type': 'application/json' },
101
+ body: JSON.stringify(body),
102
+ });
103
+ const json = (await res.json().catch(() => ({})));
104
+ return { ok: res.ok, status: res.status, json };
105
+ },
106
+ saveKey: (p) => writeKeyFolder({ dir, api, ...p }),
107
+ wallet: async ({ key, workspace }) => {
108
+ // A wallet sealed on an earlier run whose registration did not land: open it
109
+ // (Touch ID for a Keychain seal) and register THAT one — minting again would
110
+ // be refused, and would leave the first wallet's addresses orphaned.
111
+ if (existsSync(vaultPath(dir))) {
112
+ const r = await registerSealedWallet({ base: api, key, workspace, actor: workspace, dir });
113
+ return r.ok
114
+ ? { ok: true, file: vaultPath(dir), keychain: readVaultFolder(dir)?.wrap === 'keychain', addresses: (r.addresses ?? {}) }
115
+ : { ok: false, file: vaultPath(dir), error: `${String(r.error ?? 'wallet:create refused')} — the sealed wallet is kept; run \`npx oneie\` again to retry` };
116
+ }
117
+ const store = await walletStore(dir);
118
+ if ('error' in store)
119
+ return { ok: false, error: store.error };
120
+ return provisionLocalWallet({ api, key, workspace, store });
121
+ },
122
+ ask: async (key, receiver, data) => {
123
+ const res = await fetch(askPath(api, receiver), {
124
+ method: 'POST',
125
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },
126
+ body: JSON.stringify({ data }),
127
+ });
128
+ const body = (await res.json().catch(() => ({})));
129
+ // A transport-level refusal is its own outcome — never read as an empty success.
130
+ if (!res.ok)
131
+ return { outcome: `http_${res.status}`, error: String(body.error ?? body.detail ?? '') };
132
+ return body;
133
+ },
134
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
135
+ now: () => Date.now(),
136
+ };
137
+ }
138
+ const MARK = { done: '✓', pending: '…', waiting: '·', failed: '✗' };
139
+ function render(r, cli) {
140
+ const lines = ['ONE — key → products → test sale → handover', ''];
141
+ for (const s of r.steps) {
142
+ lines.push(`${MARK[s.status] ?? '?'} ${s.step.padEnd(9)} ${s.status}${s.reused ? ' (earlier run)' : ''}`);
143
+ for (const [k, v] of Object.entries(s.detail)) {
144
+ if (Array.isArray(v)) {
145
+ lines.push(` ${k}:`);
146
+ for (const item of v)
147
+ lines.push(` ${String(item)}`);
148
+ }
149
+ else if (v && typeof v === 'object') {
150
+ lines.push(` ${k}: ${Object.entries(v).map(([a, b]) => `${a} ${String(b)}`).join(', ')}`);
151
+ }
152
+ else if (v !== undefined) {
153
+ lines.push(` ${k}: ${String(v)}`);
154
+ }
155
+ }
156
+ }
157
+ if (r.next)
158
+ lines.push('', `next: ${r.next.replaceAll('npx oneie', cli)}`);
159
+ return lines.join('\n') + '\n';
160
+ }
161
+ export function startCmd() {
162
+ const cmd = new Command('start')
163
+ .description('The whole journey in this folder — key → products → test sale → handover link. Bare `npx oneie` runs it; a re-run resumes')
164
+ .option('--name <name>', 'Workspace / agent display name', 'My Shop')
165
+ .option('--email <email>', "The new owner's email — the handover link is sent there as well as printed")
166
+ .option('--product <name=price>', 'A product in major units, e.g. "Mug=12.50" (repeatable; default one Test product at 1.00)', (v, acc) => [...acc, v], [])
167
+ .option('--currency <iso>', 'ISO 4217 for --product prices', 'usd')
168
+ .option('--wait <seconds>', 'Keep reading back the test sale this long before stopping at pending', '0')
169
+ .option('--api <url>', 'API base URL', DEFAULT_API)
170
+ .action(async (opts, sub) => {
171
+ const products = [];
172
+ for (const raw of opts.product) {
173
+ const p = parseProductSpec(raw, opts.currency);
174
+ if (!p.ok) {
175
+ if (jsonMode(sub))
176
+ process.stdout.write(JSON.stringify({ ok: false, error: p.error }) + '\n');
177
+ else
178
+ process.stderr.write(`✗ ${p.error}\n`);
179
+ process.exitCode = 1;
180
+ return;
181
+ }
182
+ products.push(p.product);
183
+ }
184
+ const api = opts.api.replace(/\/$/, '');
185
+ const report = await runJourney(deps(process.cwd(), api), {
186
+ api,
187
+ name: opts.name,
188
+ ...(opts.email ? { email: opts.email } : {}),
189
+ products,
190
+ waitSeconds: Math.max(0, Number(opts.wait) || 0),
191
+ });
192
+ if (jsonMode(sub))
193
+ process.stdout.write(JSON.stringify(report) + '\n');
194
+ else
195
+ process.stdout.write(render(report, cliPrefix()));
196
+ if (!report.ok)
197
+ process.exitCode = 1;
198
+ });
199
+ return cmd;
200
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * write.ts — `one write <slug> --to age1… [file|-]`: seal a note HERE, on this machine,
3
+ * and drop the ciphertext in a holder's inbox through the door already live on one.ie.
4
+ *
5
+ * POST <web base>/api/write { ws, sealed, from? }
6
+ *
7
+ * THE PLAINTEXT NEVER LEAVES THIS PROCESS. The note is sealed to the `--to` lock(s)
8
+ * before any request is built, and the request body is built from the armored block and
9
+ * the slug alone — `sealNote` takes the plaintext, `postSealed` takes only what is
10
+ * already sealed, and a test pins that the posted body does not contain the note.
11
+ * The door itself refuses anything that is not one armored age block.
12
+ *
13
+ * `/api/write` is a WEB route (one.ie), not a gateway receiver, so this does not go
14
+ * through `askPath`. An env base that points at the gateway (api.one.ie) would 404, so
15
+ * unless `--api` names a host explicitly, that base is replaced with https://one.ie.
16
+ *
17
+ * `--to` is the literal `age1…` the holder gave you, used as given — no lookup, no check.
18
+ * Leave `--to` off and the name's PUBLISHED lock is looked up and verified here first
19
+ * (lib/lock-lookup.ts: GET /api/lock/<slug>, the Sui signature re-checked locally). An
20
+ * unpublished name, a lookup that is not live or unreachable, or a lock that does not
21
+ * verify stops the note before anything is sealed or posted — it never falls back to a
22
+ * lock nobody checked.
23
+ */
24
+ import { Command } from 'commander';
25
+ import { type Fail } from './lib/message-seal.js';
26
+ /** The door's own limits (one.ie/web pages/api/write.ts + lib/key/sealed-post.ts). */
27
+ export declare const SEALED_MAX_CHARS = 8000;
28
+ export declare function writeBase(explicit?: string, env?: NodeJS.ProcessEnv): string;
29
+ /** Plaintext in, armored block out — or a plain refusal. Nothing here touches the network. */
30
+ export declare function sealNote(note: Uint8Array, locks: string[]): Promise<{
31
+ ok: true;
32
+ sealed: string;
33
+ } | Fail>;
34
+ export interface PostResult {
35
+ ok: true;
36
+ workspace: string;
37
+ threadId: string | null;
38
+ messageId: string | null;
39
+ sealedChars: number;
40
+ }
41
+ /** Post an ALREADY SEALED block. Its inputs carry no plaintext, by signature. */
42
+ export declare function postSealed(base: string, ws: string, sealed: string, from: string | undefined, fetchImpl?: typeof fetch): Promise<PostResult | Fail>;
43
+ export declare function writeCmd(): Command;