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,142 @@
1
+ /**
2
+ * key-seal.ts — `one key lock | seal | open | identity`: sealed notes without ONE's web page.
3
+ *
4
+ * Every command here is offline — no network — and none prompts, because an agent runs
5
+ * them. The key is a key file (`--key`, what `one key new --out` writes) or
6
+ * ONE_WALLET_MNEMONIC; the note is a file argument or stdin. Each answers `--json` and
7
+ * sets the exit code: 0 done, 1 refused (with a plain sentence, and a `code` under --json).
8
+ *
9
+ * lock the `age1…` lock for this key — what anyone seals a note to
10
+ * seal a note → an armored age block, for one or more `age1…` locks
11
+ * open an age block → the note, with this key
12
+ * identity the `AGE-SECRET-KEY-1…` line, so the stock `age -d -i` opens a note with
13
+ * no ONE code on the machine
14
+ *
15
+ * `identity` is the one verb that prints a secret to stdout, on purpose: the spec for
16
+ * this door is "age -d works with nothing else installed". A stderr warning always
17
+ * says so; under --json the warning is a field. Everything else in `one key` keeps its
18
+ * posture of never printing key material.
19
+ */
20
+ import { Command } from 'commander';
21
+ import { jsonMode } from './lib/client.js';
22
+ import { ageFailure, ageModule, loadMessageKey, readNote, } from './lib/message-seal.js';
23
+ function fail(cmd, f) {
24
+ if (jsonMode(cmd))
25
+ process.stdout.write(JSON.stringify(f) + '\n');
26
+ else
27
+ process.stderr.write(`error ${f.error}\n`);
28
+ process.exitCode = 1;
29
+ }
30
+ const collect = (v, prev = []) => [...prev, v];
31
+ /** Utf-8 text when the bytes are valid utf-8, base64 when they are not (a binary note). */
32
+ function textOrBase64(bytes) {
33
+ try {
34
+ return { text: new TextDecoder('utf-8', { fatal: true }).decode(bytes) };
35
+ }
36
+ catch {
37
+ return { base64: Buffer.from(bytes).toString('base64') };
38
+ }
39
+ }
40
+ const KEY_OPT = '--key <file>';
41
+ const KEY_HELP = 'Key file made by `one key new --out` (else ONE_WALLET_MNEMONIC). Never read from stdin';
42
+ export function keySealCommands() {
43
+ const lock = new Command('lock')
44
+ .description('Print the age1… lock for this key — give it to anyone who should be able to seal you a note')
45
+ .option(KEY_OPT, KEY_HELP)
46
+ .action(async (o, c) => {
47
+ const k = await loadMessageKey(o.key);
48
+ if ('ok' in k)
49
+ return fail(c, k);
50
+ const recipient = k.recipient;
51
+ k.secret.fill(0);
52
+ if (jsonMode(c))
53
+ process.stdout.write(JSON.stringify({ ok: true, lock: recipient }) + '\n');
54
+ else
55
+ process.stdout.write(recipient + '\n');
56
+ });
57
+ const seal = new Command('seal')
58
+ .description('Seal a note (file or stdin) to one or more age1… locks — prints an armored age block')
59
+ .argument('[file]', 'The note to seal; omit or "-" to read stdin')
60
+ .option('--to <lock>', 'An age1… lock to seal to (repeat for several)', collect)
61
+ .option('--self', 'Also seal to this key, so you can reopen what you sent (needs --key or ONE_WALLET_MNEMONIC)')
62
+ .option(KEY_OPT, KEY_HELP)
63
+ .action(async (file, o, c) => {
64
+ const locks = [...(o.to ?? [])];
65
+ if (o.self) {
66
+ const k = await loadMessageKey(o.key);
67
+ if ('ok' in k)
68
+ return fail(c, k);
69
+ k.secret.fill(0);
70
+ locks.push(k.recipient);
71
+ }
72
+ if (locks.length === 0)
73
+ return fail(c, { ok: false, error: 'seal it to someone — pass --to age1… (or --self)', code: 'no_recipient' });
74
+ const age = await ageModule();
75
+ for (const l of locks) {
76
+ try {
77
+ age.decodeRecipient(l);
78
+ }
79
+ catch {
80
+ return fail(c, { ok: false, error: `${l} is not an age lock — it starts age1…`, code: 'bad_key' });
81
+ }
82
+ }
83
+ const note = await readNote(file);
84
+ if ('ok' in note)
85
+ return fail(c, note);
86
+ const unique = [...new Set(locks.map((l) => l.trim()))];
87
+ const sealed = age.armor(age.encrypt(note, unique));
88
+ if (jsonMode(c))
89
+ process.stdout.write(JSON.stringify({ ok: true, sealed, recipients: unique.length }) + '\n');
90
+ else
91
+ process.stdout.write(sealed);
92
+ });
93
+ const open = new Command('open')
94
+ .description('Open a sealed note (file or stdin) with this key — prints the note')
95
+ .argument('[file]', 'The armored age block; omit or "-" to read stdin')
96
+ .option(KEY_OPT, KEY_HELP)
97
+ .action(async (file, o, c) => {
98
+ const k = await loadMessageKey(o.key);
99
+ if ('ok' in k)
100
+ return fail(c, k);
101
+ const note = await readNote(file);
102
+ if ('ok' in note) {
103
+ k.secret.fill(0);
104
+ return fail(c, note);
105
+ }
106
+ const age = await ageModule();
107
+ try {
108
+ // Armored anywhere in the bytes (a quoted email) or a raw binary age file.
109
+ const asText = new TextDecoder().decode(note.subarray(0, Math.min(note.length, 1 << 20)));
110
+ const bytes = asText.includes(age.AGE_ARMOR_BEGIN) ? age.dearmor(new TextDecoder().decode(note)) : note;
111
+ const plain = age.decrypt(bytes, [k.secret]);
112
+ if (jsonMode(c))
113
+ process.stdout.write(JSON.stringify({ ok: true, ...textOrBase64(plain) }) + '\n');
114
+ else
115
+ process.stdout.write(plain);
116
+ }
117
+ catch (e) {
118
+ fail(c, ageFailure(e));
119
+ }
120
+ finally {
121
+ k.secret.fill(0);
122
+ }
123
+ });
124
+ const identity = new Command('identity')
125
+ .description('Print the AGE-SECRET-KEY-1… line so `age -d -i` opens your notes with no ONE code. A SECRET — warns on stderr')
126
+ .option(KEY_OPT, KEY_HELP)
127
+ .action(async (o, c) => {
128
+ const k = await loadMessageKey(o.key);
129
+ if ('ok' in k)
130
+ return fail(c, k);
131
+ const age = await ageModule();
132
+ const line = age.encodeIdentity(k.secret);
133
+ k.secret.fill(0);
134
+ const warning = 'this line opens every note sealed to your lock — keep it out of logs, chat and shell history';
135
+ process.stderr.write(`warning ${warning}\n`);
136
+ if (jsonMode(c))
137
+ process.stdout.write(JSON.stringify({ ok: true, identity: line, warning }) + '\n');
138
+ else
139
+ process.stdout.write(line + '\n');
140
+ });
141
+ return [lock, seal, open, identity];
142
+ }
package/dist/src/key.js CHANGED
@@ -30,13 +30,16 @@ import { jsonMode, resolveBase, resolveKey } from './lib/client.js';
30
30
  import { promptSecret, writeKeysFile } from './wallet.js';
31
31
  import { wordsStdoutRefusal } from './lib/agent-env.js';
32
32
  import { keySweepCommands } from './key-sweep.js';
33
+ import { keySealCommands } from './key-seal.js';
34
+ import { keyPublishCommands } from './key-publish.js';
35
+ import { renderKeyReceipt, startKeyReceipt } from './lib/key-receipt.js';
33
36
  const REFUSE_ARGV_SECRET = 'A secret on the command line is refused on purpose: it is written to your shell history and is ' +
34
37
  'visible in `ps` to every user on this machine. Set ONE_WALLET_MNEMONIC or pipe the words on stdin.';
35
38
  const REFUSE_ARGV = 'Unrecognised argument. It is not repeated here on purpose — it may BE your recovery phrase. ' +
36
39
  'Words go on stdin or in ONE_WALLET_MNEMONIC, never on the command line. Run --help.';
37
40
  const INVALID_PHRASE = 'That is not a valid 24-word BIP-39 recovery phrase. Nothing was derived.';
38
41
  // text/key.md, verbatim in substance: the difference is silent and it costs money.
39
- const NOT_SUI = 'These 24 words are not a Sui wallet mnemonic under v1: ONE derives every chain by HKDF from their ' +
42
+ const NOT_SUI = 'These 24 words are not a Sui wallet mnemonic under v1: ONE derives each chain by HKDF from their ' +
40
43
  '32 bytes of entropy, while a standard wallet derives by BIP-44/SLIP-0010 from the same phrase. ' +
41
44
  'Both succeed; the standard one shows different, empty addresses. Recover them here, at /key, or with @oneie/recover.';
42
45
  const PAPER = 'Write these on paper. The paper is the only backup — ONE never holds this key and cannot recover it.';
@@ -150,7 +153,7 @@ function verdictOf(local, refs) {
150
153
  }
151
154
  // ── the command ──────────────────────────────────────────────────────────────
152
155
  export function keyCmd() {
153
- const cmd = new Command('key').description('One key — new · recover · public · verify. Offline except verify, which sends only your API key');
156
+ const cmd = new Command('key').description('One key — new · recover · public · verify · lock · seal · open · identity · publish-lock · lock-of. Offline except verify, publish-lock, lock-of');
154
157
  cmd.command('new')
155
158
  .description('Mint a key on this machine: 24 words, printed ONCE, for paper. No network')
156
159
  .argument('[refused...]')
@@ -181,13 +184,20 @@ export function keyCmd() {
181
184
  if (why)
182
185
  return fail(sub, why);
183
186
  }
187
+ // Counted, not claimed: every connection, lookup and datagram this process opens while the key is made.
188
+ const measure = startKeyReceipt();
184
189
  const wallet = await generateWallet(derivation);
185
190
  const addresses = addressesOf(wallet);
186
191
  const userIdPub = await userIdPubFromPhrase(wallet.mnemonic);
192
+ const receipt = measure.seal();
187
193
  if (opts.out) {
188
194
  const contents = JSON.stringify({ mnemonic: wallet.mnemonic, derivation, userIdPub, addresses, keys: wallet.keys }, null, 2) + '\n';
189
195
  writeKeysFile(opts.out, contents, true);
190
- return done(sub, { ok: true, out: opts.out, derivation, label: labelFor(derivation), addresses, userIdPub });
196
+ const data = { ok: true, out: opts.out, derivation, label: labelFor(derivation), addresses, userIdPub };
197
+ if (jsonMode(sub))
198
+ return done(sub, { ...data, receipt });
199
+ done(sub, data);
200
+ return void process.stdout.write(`\n${renderKeyReceipt(receipt)}`);
191
201
  }
192
202
  // Straight to stdout, never through a JSON receipt (refused above).
193
203
  const words = wallet.mnemonic.split(' ');
@@ -195,7 +205,8 @@ export function keyCmd() {
195
205
  process.stdout.write(`\n${PAPER}\n\n${sheet}\n\n${NOT_SUI}\n\n` +
196
206
  `derivation ${labelFor(derivation)}\n` +
197
207
  Object.entries(addresses).map(([c, a]) => `${c.padEnd(11)} ${a}`).join('\n') +
198
- `\nidentity ${userIdPub}\n\nThis is the only time the words are shown. Close the terminal when they are on paper.\n`);
208
+ `\nidentity ${userIdPub}\n\nThis is the only time the words are shown. Close the terminal when they are on paper.\n\n` +
209
+ renderKeyReceipt(receipt));
199
210
  });
200
211
  cmd.addCommand(wordsCommand('recover', 'Rebuild a key from its 24 words (stdin or ONE_WALLET_MNEMONIC) — both address sets, no network')
201
212
  .option('--derivation <v>', 'which set --out writes: v1 (default) or v2', 'v1')
@@ -234,7 +245,7 @@ export function keyCmd() {
234
245
  ...(opts.out ? { out: opts.out, wrote: derivation } : {}),
235
246
  });
236
247
  }));
237
- cmd.addCommand(wordsCommand('public', 'The public identity + the four chain addresses for your words — nothing secret, no network')
248
+ cmd.addCommand(wordsCommand('public', 'The public identity + the five chain addresses for your words (four for a v1 key) — nothing secret, no network')
238
249
  .option('--derivation <v>', 'v1 or v2 — omit it and both sets print, because the words carry no marker')
239
250
  .action(async (rest, opts, sub) => {
240
251
  if (refuseArgv(sub, opts, rest))
@@ -310,6 +321,12 @@ export function keyCmd() {
310
321
  // sweep (key-sweep.ts). Keys come from the folder's sealed vault, never argv.
311
322
  for (const sub of keySweepCommands())
312
323
  cmd.addCommand(sub);
324
+ // lock · seal · open · identity — sealed notes from a terminal (key-seal.ts). Offline.
325
+ // publish-lock · lock-of — put a lock under a name / read one back, checked (key-publish.ts).
326
+ for (const sub of keySealCommands())
327
+ cmd.addCommand(sub);
328
+ for (const sub of keyPublishCommands())
329
+ cmd.addCommand(sub);
313
330
  // `one key <token>`: commander would print "unknown command '<token>'" — and the
314
331
  // token may BE the first word of a phrase. Refuse it here without repeating it.
315
332
  cmd.argument('[refused...]').allowUnknownOption().action((rest, _opts, c) => {
@@ -0,0 +1,51 @@
1
+ /**
2
+ * age-plugin.ts — seal to, and open with, an `age1se1…` Secure Enclave lock through the
3
+ * real `age` binary and `age-plugin-se` (text/secrets.md deliverable 3; text/secrets-todo.md § C3).
4
+ *
5
+ * packages/sdk/src/age.ts seals X25519 only, so a file with a Secure Enclave reader is
6
+ * made by `age -e -r <lock> -r <lock>…` — every reader on the one command line, so the
7
+ * file stays ONE age file per value with one stanza per reader (paper X25519 + the
8
+ * plugin's). The SDK still opens it with the paper identity: it skips a stanza it does not
9
+ * know as long as an X25519 one is there.
10
+ *
11
+ * Rules this file keeps:
12
+ * • argv arrays, never a shell; the value goes in on stdin and comes out on stdout —
13
+ * no temp file, no argument, no environment variable ever holds a plaintext.
14
+ * • `age`'s stderr is never read. A failure is an exit code and a FIXED message, because
15
+ * age's own text can echo an input.
16
+ * • A missing binary is a refusal (`no_age_binary` / `no_plugin`), never a silent drop of
17
+ * the device.
18
+ */
19
+ export type AgePluginCode = 'no_age_binary' | 'no_plugin' | 'seal_failed' | 'open_failed';
20
+ /** A plugin failure: a code and one of the fixed messages above — never age's own text. */
21
+ export declare class AgePluginError extends Error {
22
+ readonly code: AgePluginCode;
23
+ constructor(code: AgePluginCode);
24
+ }
25
+ /** The lock of a Secure Enclave key. */
26
+ export declare const isPluginLock: (lock: string) => boolean;
27
+ /** The shape of an age1se1… lock (bech32 body) — checked before one is handed to `age`. */
28
+ export declare const PLUGIN_LOCK_RE: RegExp;
29
+ /** Test seam: replace the directories searched for the binaries (no PATH, no fallback). `undefined` restores. */
30
+ export declare function setSearchDirs(dirs: string[] | undefined): void;
31
+ /** Absolute path of an executable on PATH, then /opt/homebrew/bin; null when it is nowhere. */
32
+ export declare function findBinary(name: string): string | null;
33
+ /** The two programs, or the refusal that names the missing one. */
34
+ export declare function requireAge(needAge?: boolean): {
35
+ age: string;
36
+ plugin: string;
37
+ } | AgePluginCode;
38
+ /**
39
+ * Seal one value to every lock in a single `age -e` call; the result is one binary age
40
+ * file with a stanza per lock. Plain bytes go in on stdin only.
41
+ */
42
+ export declare function sealWithAge(plain: Uint8Array, locks: string[]): Uint8Array;
43
+ /**
44
+ * Open one age file with an identity file (`age -d -i`). A Secure Enclave identity made
45
+ * with a biometry rule asks for the finger here. The plaintext comes back on stdout only.
46
+ */
47
+ export declare function openWithAge(file: Uint8Array, identityPath: string): Uint8Array;
48
+ /** `age-plugin-se keygen --access-control <ac> -o <out>`; true when it exited 0. Output is never read. */
49
+ export declare function keygen(out: string, accessControl: string): boolean | AgePluginCode;
50
+ /** The `age1se1…` lock of an identity file (`age-plugin-se recipients -i`), or null. */
51
+ export declare function recipientOf(identityPath: string): string | null;
@@ -0,0 +1,130 @@
1
+ /**
2
+ * age-plugin.ts — seal to, and open with, an `age1se1…` Secure Enclave lock through the
3
+ * real `age` binary and `age-plugin-se` (text/secrets.md deliverable 3; text/secrets-todo.md § C3).
4
+ *
5
+ * packages/sdk/src/age.ts seals X25519 only, so a file with a Secure Enclave reader is
6
+ * made by `age -e -r <lock> -r <lock>…` — every reader on the one command line, so the
7
+ * file stays ONE age file per value with one stanza per reader (paper X25519 + the
8
+ * plugin's). The SDK still opens it with the paper identity: it skips a stanza it does not
9
+ * know as long as an X25519 one is there.
10
+ *
11
+ * Rules this file keeps:
12
+ * • argv arrays, never a shell; the value goes in on stdin and comes out on stdout —
13
+ * no temp file, no argument, no environment variable ever holds a plaintext.
14
+ * • `age`'s stderr is never read. A failure is an exit code and a FIXED message, because
15
+ * age's own text can echo an input.
16
+ * • A missing binary is a refusal (`no_age_binary` / `no_plugin`), never a silent drop of
17
+ * the device.
18
+ */
19
+ import { spawnSync } from 'node:child_process';
20
+ import { accessSync, constants, statSync } from 'node:fs';
21
+ import { delimiter, dirname, join } from 'node:path';
22
+ import { MAX_INPUT_BYTES } from './message-seal.js';
23
+ const MESSAGES = {
24
+ no_age_binary: 'the `age` program is not installed — install it (brew install age) to seal to this Mac',
25
+ no_plugin: 'the `age-plugin-se` program is not installed — install it (brew install age-plugin-se) to use this Mac as a reader',
26
+ seal_failed: 'age could not seal this value to the Secure Enclave lock',
27
+ open_failed: 'age could not open this value with the Secure Enclave identity',
28
+ };
29
+ /** A plugin failure: a code and one of the fixed messages above — never age's own text. */
30
+ export class AgePluginError extends Error {
31
+ code;
32
+ constructor(code) {
33
+ super(MESSAGES[code]);
34
+ this.code = code;
35
+ this.name = 'AgePluginError';
36
+ }
37
+ }
38
+ /** The lock of a Secure Enclave key. */
39
+ export const isPluginLock = (lock) => lock.startsWith('age1se1');
40
+ /** The shape of an age1se1… lock (bech32 body) — checked before one is handed to `age`. */
41
+ export const PLUGIN_LOCK_RE = /^age1se1[02-9ac-hj-np-z]+$/;
42
+ const FALLBACK_DIRS = ['/opt/homebrew/bin', '/usr/local/bin'];
43
+ let dirsOverride;
44
+ /** Test seam: replace the directories searched for the binaries (no PATH, no fallback). `undefined` restores. */
45
+ export function setSearchDirs(dirs) {
46
+ dirsOverride = dirs;
47
+ }
48
+ function searchDirs() {
49
+ if (dirsOverride)
50
+ return dirsOverride;
51
+ return [...(process.env.PATH ?? '').split(delimiter).filter(Boolean), ...FALLBACK_DIRS];
52
+ }
53
+ /** Absolute path of an executable on PATH, then /opt/homebrew/bin; null when it is nowhere. */
54
+ export function findBinary(name) {
55
+ for (const d of searchDirs()) {
56
+ const p = join(d, name);
57
+ try {
58
+ if (!statSync(p).isFile())
59
+ continue;
60
+ accessSync(p, constants.X_OK);
61
+ return p;
62
+ }
63
+ catch {
64
+ /* next */
65
+ }
66
+ }
67
+ return null;
68
+ }
69
+ /** The two programs, or the refusal that names the missing one. */
70
+ export function requireAge(needAge = true) {
71
+ const plugin = findBinary('age-plugin-se');
72
+ if (!plugin)
73
+ return 'no_plugin';
74
+ const age = findBinary('age');
75
+ if (needAge && !age)
76
+ return 'no_age_binary';
77
+ return { age: age ?? '', plugin };
78
+ }
79
+ /** `age` finds `age-plugin-se` on PATH, so PATH leads with the directories the two were found in. */
80
+ function childEnv(bins) {
81
+ const dirs = [...new Set([bins.age && dirname(bins.age), dirname(bins.plugin)].filter(Boolean))];
82
+ return { ...process.env, PATH: [...dirs, process.env.PATH ?? ''].join(delimiter) };
83
+ }
84
+ const MAX_BUFFER = MAX_INPUT_BYTES * 2 + 1024 * 1024;
85
+ /**
86
+ * Seal one value to every lock in a single `age -e` call; the result is one binary age
87
+ * file with a stanza per lock. Plain bytes go in on stdin only.
88
+ */
89
+ export function sealWithAge(plain, locks) {
90
+ const bins = requireAge();
91
+ if (typeof bins === 'string')
92
+ throw new AgePluginError(bins);
93
+ const argv = ['-e', ...locks.flatMap((l) => ['-r', l])];
94
+ const r = spawnSync(bins.age, argv, { input: plain, env: childEnv(bins), stdio: ['pipe', 'pipe', 'ignore'], maxBuffer: MAX_BUFFER });
95
+ if (r.error || r.status !== 0 || !r.stdout || r.stdout.length === 0)
96
+ throw new AgePluginError('seal_failed');
97
+ return new Uint8Array(r.stdout);
98
+ }
99
+ /**
100
+ * Open one age file with an identity file (`age -d -i`). A Secure Enclave identity made
101
+ * with a biometry rule asks for the finger here. The plaintext comes back on stdout only.
102
+ */
103
+ export function openWithAge(file, identityPath) {
104
+ const bins = requireAge();
105
+ if (typeof bins === 'string')
106
+ throw new AgePluginError(bins);
107
+ const r = spawnSync(bins.age, ['-d', '-i', identityPath], { input: file, env: childEnv(bins), stdio: ['pipe', 'pipe', 'ignore'], maxBuffer: MAX_BUFFER });
108
+ if (r.error || r.status !== 0 || !r.stdout)
109
+ throw new AgePluginError('open_failed');
110
+ return new Uint8Array(r.stdout);
111
+ }
112
+ /** `age-plugin-se keygen --access-control <ac> -o <out>`; true when it exited 0. Output is never read. */
113
+ export function keygen(out, accessControl) {
114
+ const bins = requireAge();
115
+ if (typeof bins === 'string')
116
+ return bins;
117
+ const r = spawnSync(bins.plugin, ['keygen', '--access-control', accessControl, '-o', out], { env: childEnv(bins), stdio: ['ignore', 'ignore', 'ignore'] });
118
+ return !r.error && r.status === 0;
119
+ }
120
+ /** The `age1se1…` lock of an identity file (`age-plugin-se recipients -i`), or null. */
121
+ export function recipientOf(identityPath) {
122
+ const plugin = findBinary('age-plugin-se');
123
+ if (!plugin)
124
+ return null;
125
+ const r = spawnSync(plugin, ['recipients', '-i', identityPath], { stdio: ['ignore', 'pipe', 'ignore'] });
126
+ if (r.error || r.status !== 0)
127
+ return null;
128
+ const lock = r.stdout.toString('utf8').split(/\r?\n/).map((l) => l.trim()).find((l) => PLUGIN_LOCK_RE.test(l));
129
+ return lock ?? null;
130
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * env-sealed.ts — parse a plaintext .env, and write and read `.env.sealed` v1
3
+ * (text/secrets-plan.md § Data shape).
4
+ *
5
+ * # one-secrets v1
6
+ * # readers age1… age1…
7
+ * # vault <id> (only when one is known)
8
+ * NAME=age:<base64 of one binary age file>
9
+ *
10
+ * One age file per value, in the .env's own order; comments and blank lines are dropped.
11
+ * Names stay readable, values do not. Nothing here prints, logs or writes a value: every
12
+ * error names a line NUMBER, never a line, because a line of a .env is a secret.
13
+ *
14
+ * The age module loads lazily (same reason as message-seal.ts): `one secrets` is
15
+ * registered from index.ts, and a static `@oneie/sdk/age` import would crash every verb
16
+ * on an installed SDK that predates the export.
17
+ */
18
+ import type { Fail } from './message-seal.js';
19
+ export declare const SEALED_HEADER = "# one-secrets v1";
20
+ export interface EnvEntry {
21
+ name: string;
22
+ value: string;
23
+ }
24
+ export interface SealedEntry {
25
+ name: string;
26
+ /** One binary age file. */
27
+ file: Uint8Array;
28
+ }
29
+ export interface SealedFile {
30
+ readers: string[];
31
+ vault?: string;
32
+ entries: SealedEntry[];
33
+ }
34
+ export declare const isVaultId: (v: string) => boolean;
35
+ /**
36
+ * Parse a .env the way dotenv reads it: `NAME=value`, an optional `export `, "double"
37
+ * quotes (with \n \r \t \" \\ escapes, may span lines), 'single' quotes (literal, may
38
+ * span lines), and unquoted values that end at whitespace-then-#. A value may hold `=`
39
+ * and `#`. Duplicate names are refused, never merged.
40
+ */
41
+ export declare function parseEnv(text: string): EnvEntry[] | Fail;
42
+ /** The `.env.sealed` v1 text. */
43
+ export declare function renderSealed(f: SealedFile): string;
44
+ /** Read `.env.sealed` v1 back. Refuses anything that is not exactly the format. */
45
+ export declare function parseSealed(text: string): SealedFile | Fail;
46
+ /** Seal every value to every lock: one binary age file per value. */
47
+ export declare function sealEntries(entries: EnvEntry[], locks: string[]): Promise<SealedEntry[]>;
48
+ /**
49
+ * Open the sealed file's values with one identity and compare them to `expected` byte for
50
+ * byte — same names, same order, same count, every reader on every value. Returns null
51
+ * when it all holds, else a plain failure that names a variable, never a value.
52
+ */
53
+ export declare function verifySealed(sealed: SealedFile, expected: EnvEntry[], secret: Uint8Array): Promise<Fail | null>;
@@ -0,0 +1,184 @@
1
+ /**
2
+ * env-sealed.ts — parse a plaintext .env, and write and read `.env.sealed` v1
3
+ * (text/secrets-plan.md § Data shape).
4
+ *
5
+ * # one-secrets v1
6
+ * # readers age1… age1…
7
+ * # vault <id> (only when one is known)
8
+ * NAME=age:<base64 of one binary age file>
9
+ *
10
+ * One age file per value, in the .env's own order; comments and blank lines are dropped.
11
+ * Names stay readable, values do not. Nothing here prints, logs or writes a value: every
12
+ * error names a line NUMBER, never a line, because a line of a .env is a secret.
13
+ *
14
+ * The age module loads lazily (same reason as message-seal.ts): `one secrets` is
15
+ * registered from index.ts, and a static `@oneie/sdk/age` import would crash every verb
16
+ * on an installed SDK that predates the export.
17
+ */
18
+ import { ageModule } from './message-seal.js';
19
+ import { isPluginLock, sealWithAge } from './age-plugin.js';
20
+ export const SEALED_HEADER = '# one-secrets v1';
21
+ const bad = (error, code = 'bad_env') => ({ ok: false, error, code });
22
+ const NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
23
+ const VAULT_RE = /^[A-Za-z0-9_.:-]{1,128}$/;
24
+ const B64_RE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
25
+ export const isVaultId = (v) => VAULT_RE.test(v);
26
+ /** The tail of a line after a closing quote may only be blank or a comment. */
27
+ function tailOk(tail) {
28
+ const t = tail.trim();
29
+ return t === '' || t.startsWith('#');
30
+ }
31
+ /**
32
+ * Parse a .env the way dotenv reads it: `NAME=value`, an optional `export `, "double"
33
+ * quotes (with \n \r \t \" \\ escapes, may span lines), 'single' quotes (literal, may
34
+ * span lines), and unquoted values that end at whitespace-then-#. A value may hold `=`
35
+ * and `#`. Duplicate names are refused, never merged.
36
+ */
37
+ export function parseEnv(text) {
38
+ const lines = text.replace(/^/, '').split(/\r?\n/);
39
+ const out = [];
40
+ const seen = new Set();
41
+ for (let i = 0; i < lines.length; i++) {
42
+ const line = lines[i].trimStart();
43
+ if (line === '' || line.startsWith('#'))
44
+ continue;
45
+ const m = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*=[ \t]*(.*)$/.exec(line);
46
+ if (!m)
47
+ return bad(`line ${i + 1} of the .env is not NAME=value`);
48
+ const name = m[1];
49
+ const rest = m[2];
50
+ const startLine = i + 1;
51
+ let value;
52
+ const q = rest[0];
53
+ if (q === '"' || q === "'") {
54
+ // Find the closing quote, pulling in the following lines while it is open.
55
+ let body = '';
56
+ let buf = rest.slice(1);
57
+ let closed = false;
58
+ let tail = '';
59
+ for (;;) {
60
+ let j = 0;
61
+ for (; j < buf.length; j++) {
62
+ const c = buf[j];
63
+ if (q === '"' && c === '\\' && j + 1 < buf.length) {
64
+ const n = buf[j + 1];
65
+ body += n === 'n' ? '\n' : n === 'r' ? '\r' : n === 't' ? '\t' : n === '"' ? '"' : n === '\\' ? '\\' : '\\' + n;
66
+ j++;
67
+ continue;
68
+ }
69
+ if (c === q) {
70
+ closed = true;
71
+ tail = buf.slice(j + 1);
72
+ break;
73
+ }
74
+ body += c;
75
+ }
76
+ if (closed)
77
+ break;
78
+ if (++i >= lines.length)
79
+ return bad(`line ${startLine} of the .env opens a quote that never closes`);
80
+ body += '\n';
81
+ buf = lines[i];
82
+ }
83
+ if (!tailOk(tail))
84
+ return bad(`line ${i + 1} of the .env has text after the closing quote`);
85
+ value = body;
86
+ }
87
+ else {
88
+ value = rest.replace(/(^|[ \t])#.*$/, '').trimEnd();
89
+ }
90
+ if (seen.has(name))
91
+ return bad(`${name} is set twice in the .env — keep one`, 'duplicate_name');
92
+ seen.add(name);
93
+ out.push({ name, value });
94
+ }
95
+ return out;
96
+ }
97
+ /** The `.env.sealed` v1 text. */
98
+ export function renderSealed(f) {
99
+ const lines = [SEALED_HEADER, `# readers ${f.readers.join(' ')}`];
100
+ if (f.vault)
101
+ lines.push(`# vault ${f.vault}`);
102
+ for (const e of f.entries)
103
+ lines.push(`${e.name}=age:${Buffer.from(e.file).toString('base64')}`);
104
+ return lines.join('\n') + '\n';
105
+ }
106
+ /** Read `.env.sealed` v1 back. Refuses anything that is not exactly the format. */
107
+ export function parseSealed(text) {
108
+ const lines = text.split(/\r?\n/);
109
+ if (lines[0] !== SEALED_HEADER)
110
+ return bad('this is not a one-secrets v1 file', 'not_sealed');
111
+ let readers;
112
+ let vault;
113
+ const entries = [];
114
+ const seen = new Set();
115
+ for (let i = 1; i < lines.length; i++) {
116
+ const l = lines[i];
117
+ if (l === '')
118
+ continue;
119
+ if (l.startsWith('# ')) {
120
+ if (entries.length)
121
+ return bad(`line ${i + 1}: the header comes before the values`, 'not_sealed');
122
+ if (l.startsWith('# readers ') && !readers)
123
+ readers = l.slice('# readers '.length).split(' ').filter(Boolean);
124
+ else if (l.startsWith('# vault ') && vault === undefined && isVaultId(l.slice('# vault '.length)))
125
+ vault = l.slice('# vault '.length);
126
+ else
127
+ return bad(`line ${i + 1}: unknown header line`, 'not_sealed');
128
+ continue;
129
+ }
130
+ const m = /^([A-Za-z_][A-Za-z0-9_]*)=age:(.*)$/.exec(l);
131
+ if (!m || !B64_RE.test(m[2]) || m[2] === '' || !NAME_RE.test(m[1]))
132
+ return bad(`line ${i + 1}: not NAME=age:<base64>`, 'not_sealed');
133
+ if (seen.has(m[1]))
134
+ return bad(`${m[1]} appears twice`, 'not_sealed');
135
+ seen.add(m[1]);
136
+ entries.push({ name: m[1], file: new Uint8Array(Buffer.from(m[2], 'base64')) });
137
+ }
138
+ if (!readers || readers.length === 0)
139
+ return bad('the file lists no readers', 'not_sealed');
140
+ return { readers, vault, entries };
141
+ }
142
+ /** Seal every value to every lock: one binary age file per value. */
143
+ export async function sealEntries(entries, locks) {
144
+ const enc = new TextEncoder();
145
+ // A Secure Enclave reader means the `age` program seals the file (every reader on one command line);
146
+ // with none, the SDK's own age does exactly what it always did.
147
+ if (locks.some(isPluginLock))
148
+ return entries.map((e) => ({ name: e.name, file: sealWithAge(enc.encode(e.value), locks) }));
149
+ const age = await ageModule();
150
+ return entries.map((e) => ({ name: e.name, file: age.encrypt(enc.encode(e.value), locks) }));
151
+ }
152
+ /**
153
+ * Open the sealed file's values with one identity and compare them to `expected` byte for
154
+ * byte — same names, same order, same count, every reader on every value. Returns null
155
+ * when it all holds, else a plain failure that names a variable, never a value.
156
+ */
157
+ export async function verifySealed(sealed, expected, secret) {
158
+ const age = await ageModule();
159
+ const enc = new TextEncoder();
160
+ const fail = (error) => ({ ok: false, error, code: 'readback_failed' });
161
+ if (sealed.entries.length !== expected.length)
162
+ return fail('the sealed file has a different number of variables than the .env');
163
+ for (let i = 0; i < expected.length; i++) {
164
+ const got = sealed.entries[i];
165
+ const want = expected[i];
166
+ if (got.name !== want.name)
167
+ return fail(`variable ${i + 1} reads back under a different name`);
168
+ let stanzas;
169
+ let plain;
170
+ try {
171
+ stanzas = age.parseHeader(got.file).stanzas.length;
172
+ plain = age.decrypt(got.file, [secret]);
173
+ }
174
+ catch {
175
+ return fail(`${want.name} does not open with the paper key`);
176
+ }
177
+ if (stanzas !== sealed.readers.length)
178
+ return fail(`${want.name} is not sealed to every reader`);
179
+ const w = enc.encode(want.value);
180
+ if (plain.length !== w.length || !plain.every((b, k) => b === w[k]))
181
+ return fail(`${want.name} does not read back byte for byte`);
182
+ }
183
+ return null;
184
+ }