oneie 5.5.2 → 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 (43) 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/shop-init.js +2 -2
  26. package/dist/src/lib/vault-read.d.ts +24 -0
  27. package/dist/src/lib/vault-read.js +77 -0
  28. package/dist/src/media.d.ts +27 -0
  29. package/dist/src/media.js +249 -18
  30. package/dist/src/secrets-device.d.ts +32 -0
  31. package/dist/src/secrets-device.js +127 -0
  32. package/dist/src/secrets-give.d.ts +125 -0
  33. package/dist/src/secrets-give.js +236 -0
  34. package/dist/src/secrets-run.d.ts +31 -0
  35. package/dist/src/secrets-run.js +182 -0
  36. package/dist/src/secrets.d.ts +32 -0
  37. package/dist/src/secrets.js +197 -0
  38. package/dist/src/social.js +27 -8
  39. package/dist/src/start.d.ts +15 -0
  40. package/dist/src/start.js +200 -0
  41. package/dist/src/write.d.ts +43 -0
  42. package/dist/src/write.js +174 -0
  43. package/package.json +2 -2
@@ -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
+ }
@@ -1,5 +1,6 @@
1
1
  import { Command } from 'commander';
2
2
  import { out, resolveBase, resolveKey } from './lib/client.js';
3
+ import { webBase } from './lib/roster.js';
3
4
  const DEFAULT_API = resolveBase({}, 'https://one.ie');
4
5
  function readApiKey() {
5
6
  const key = resolveKey();
@@ -16,7 +17,7 @@ export function socialCmd() {
16
17
  .option('--api <url>', 'API base URL', DEFAULT_API)
17
18
  .action(async (opts) => {
18
19
  const key = readApiKey();
19
- const base = opts.api.replace(/\/$/, '');
20
+ const base = webBase(opts.api).replace(/\/$/, '');
20
21
  const params = new URLSearchParams({ groupId: opts.group, limit: opts.limit });
21
22
  if (opts.status)
22
23
  params.set('status', opts.status);
@@ -32,11 +33,13 @@ export function socialCmd() {
32
33
  });
33
34
  cmd
34
35
  .command('create')
35
- .description('Create a draft social post')
36
+ .description('Create a DRAFT social post. A key drafts only — scheduling or publishing is a person\'s step on ' +
37
+ '/u/<group>/marketing/social, because a scheduled post publishes itself with nobody in the loop.')
36
38
  .requiredOption('--group <groupId>', 'Group ID')
37
39
  .requiredOption('--content <text>', 'Post content')
38
40
  .requiredOption('--platforms <list>', 'Comma-separated platforms (twitter,linkedin,...)')
39
- .option('--schedule <epoch>', 'Scheduled publish time (Unix epoch seconds)')
41
+ .option('--media-url <url>', 'Absolute URL of an image or video (e.g. the url `one media upload` prints)')
42
+ .option('--media-type <type>', 'image | video (default: guessed from the URL extension)')
40
43
  .option('--api <url>', 'API base URL', DEFAULT_API)
41
44
  .action(async (opts) => {
42
45
  const key = readApiKey();
@@ -44,11 +47,22 @@ export function socialCmd() {
44
47
  out(cmd, { ok: false, error: 'no API key — run: oneie auth login' });
45
48
  return;
46
49
  }
47
- const base = opts.api.replace(/\/$/, '');
50
+ const base = webBase(opts.api).replace(/\/$/, '');
48
51
  const platforms = opts.platforms.split(',').map((p) => p.trim());
49
52
  const body = { groupId: opts.group, content: opts.content, platforms };
50
- if (opts.schedule)
51
- body.scheduledAt = parseInt(opts.schedule, 10);
53
+ if (opts.mediaUrl) {
54
+ if (!/^https?:\/\//i.test(opts.mediaUrl)) {
55
+ out(cmd, { ok: false, error: '--media-url must be absolute — platforms fetch it from their own servers' });
56
+ return;
57
+ }
58
+ const mediaType = opts.mediaType ?? (/\.(mp4|m4v|mov|webm)(\?|#|$)/i.test(opts.mediaUrl) ? 'video' : 'image');
59
+ if (mediaType !== 'image' && mediaType !== 'video') {
60
+ out(cmd, { ok: false, error: "--media-type must be 'image' or 'video'" });
61
+ return;
62
+ }
63
+ body.mediaUrl = opts.mediaUrl;
64
+ body.mediaType = mediaType;
65
+ }
52
66
  const res = await fetch(`${base}/api/social/posts`, {
53
67
  method: 'POST',
54
68
  headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },
@@ -60,7 +74,12 @@ export function socialCmd() {
60
74
  return;
61
75
  }
62
76
  const data = await res.json();
63
- out(cmd, { ok: true, id: data.post.id, status: data.post.status });
77
+ out(cmd, {
78
+ ok: true,
79
+ id: data.post.id,
80
+ status: data.post.status,
81
+ review: `${base}/u/${opts.group}/marketing/social`,
82
+ });
64
83
  });
65
84
  cmd
66
85
  .command('accounts')
@@ -72,7 +91,7 @@ export function socialCmd() {
72
91
  out(cmd, { ok: false, error: 'no API key — run: oneie auth login' });
73
92
  return;
74
93
  }
75
- const base = opts.api.replace(/\/$/, '');
94
+ const base = webBase(opts.api).replace(/\/$/, '');
76
95
  const res = await fetch(`${base}/api/social/accounts`, {
77
96
  headers: { Authorization: `Bearer ${key}` },
78
97
  });
@@ -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;