owenloop 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (211) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +137 -35
  3. package/bin/owenloop.mjs +49 -1
  4. package/dist/packages/work/src/agent/brief.d.ts +8 -4
  5. package/dist/packages/work/src/agent/brief.js +7 -3
  6. package/dist/packages/work/src/agent/loop.d.ts +13 -7
  7. package/dist/packages/work/src/agent/loop.js +136 -9
  8. package/dist/packages/work/src/agent/model-policy.d.ts +49 -0
  9. package/dist/packages/work/src/agent/model-policy.js +138 -0
  10. package/dist/packages/work/src/bundle/cache.d.ts +7 -5
  11. package/dist/packages/work/src/bundle/cache.js +20 -6
  12. package/dist/packages/work/src/bundle/fetch.d.ts +7 -5
  13. package/dist/packages/work/src/bundle/fetch.js +27 -7
  14. package/dist/packages/work/src/bundle/types.d.ts +8 -4
  15. package/dist/packages/work/src/consumed-verifier.d.ts +45 -0
  16. package/dist/packages/work/src/consumed-verifier.js +205 -0
  17. package/dist/packages/work/src/exec/instructions.d.ts +99 -0
  18. package/dist/packages/work/src/exec/instructions.js +323 -0
  19. package/dist/packages/work/src/exec/loop.d.ts +12 -1
  20. package/dist/packages/work/src/exec/loop.js +137 -20
  21. package/dist/packages/work/src/exec/payload.d.ts +29 -0
  22. package/dist/packages/work/src/exec/payload.js +54 -0
  23. package/dist/packages/work/src/exec/receipt.d.ts +9 -6
  24. package/dist/packages/work/src/exec/receipt.js +12 -1
  25. package/dist/packages/work/src/exec/runner.d.ts +7 -1
  26. package/dist/packages/work/src/exec/runner.js +74 -3
  27. package/dist/packages/work/src/harness/child-env.js +7 -0
  28. package/dist/packages/work/src/harness/claude.d.ts +20 -8
  29. package/dist/packages/work/src/harness/claude.js +260 -58
  30. package/dist/packages/work/src/harness/codex.d.ts +5 -4
  31. package/dist/packages/work/src/harness/codex.js +169 -41
  32. package/dist/packages/work/src/harness/contract.d.ts +36 -11
  33. package/dist/packages/work/src/harness/fake.js +1 -0
  34. package/dist/packages/work/src/harness/jsonrpc-stdio.js +7 -0
  35. package/dist/packages/work/src/harness/permissions.d.ts +16 -3
  36. package/dist/packages/work/src/harness/permissions.js +102 -13
  37. package/dist/packages/work/src/harness/session-store.d.ts +27 -9
  38. package/dist/packages/work/src/harness/session-store.js +271 -67
  39. package/dist/packages/work/src/hold/mcp.d.ts +25 -5
  40. package/dist/packages/work/src/hold/mcp.js +126 -11
  41. package/dist/packages/work/src/hub/client.d.ts +2 -1
  42. package/dist/packages/work/src/hub/client.js +14 -1
  43. package/dist/packages/work/src/hub/types.d.ts +69 -33
  44. package/dist/packages/work/src/hub/types.js +8 -10
  45. package/dist/packages/work/src/mcp/server.js +1 -1
  46. package/dist/packages/work/src/owenloop-bin.d.ts +1 -0
  47. package/dist/packages/work/src/owenloop-bin.js +18 -0
  48. package/dist/packages/work/src/roles/agent-run.d.ts +12 -6
  49. package/dist/packages/work/src/roles/agent-run.js +116 -34
  50. package/dist/packages/work/src/roles/exec.d.ts +8 -0
  51. package/dist/packages/work/src/roles/exec.js +27 -2
  52. package/dist/packages/work/src/roles/hold.d.ts +4 -0
  53. package/dist/packages/work/src/roles/hold.js +44 -5
  54. package/dist/packages/work/src/roles/lint.d.ts +3 -4
  55. package/dist/packages/work/src/roles/lint.js +41 -7
  56. package/dist/packages/work/src/roles/settings.js +5 -0
  57. package/dist/packages/work/src/roles/shift.d.ts +1 -0
  58. package/dist/packages/work/src/roles/shift.js +23 -1
  59. package/dist/packages/work/src/settings/settings.d.ts +17 -1
  60. package/dist/packages/work/src/settings/settings.js +39 -0
  61. package/dist/packages/work/src/shift/loop.d.ts +14 -3
  62. package/dist/packages/work/src/shift/loop.js +447 -164
  63. package/dist/packages/work/src/shift/protocol.d.ts +4 -0
  64. package/dist/packages/work/src/shift/runtime.d.ts +2 -0
  65. package/dist/packages/work/src/shift/runtime.js +66 -3
  66. package/dist/packages/work/src/shift/spawn.d.ts +41 -18
  67. package/dist/packages/work/src/shift/spawn.js +89 -31
  68. package/dist/packages/work/src/shift/state.d.ts +53 -51
  69. package/dist/packages/work/src/shift/state.js +325 -102
  70. package/dist/packages/work/src/submit-proof.d.ts +36 -0
  71. package/dist/packages/work/src/submit-proof.js +93 -0
  72. package/dist/src/add.d.ts +64 -259
  73. package/dist/src/add.js +81 -615
  74. package/dist/src/archive.d.ts +97 -0
  75. package/dist/src/archive.js +591 -0
  76. package/dist/src/bundle/index.d.ts +64 -0
  77. package/dist/src/bundle/index.js +508 -0
  78. package/dist/src/bundle/manifest.d.ts +50 -0
  79. package/dist/src/bundle/manifest.js +435 -0
  80. package/dist/src/bundle/runtime.d.ts +26 -0
  81. package/dist/src/bundle/runtime.js +64 -0
  82. package/dist/src/bundle/tar.d.ts +62 -0
  83. package/dist/src/bundle/tar.js +238 -0
  84. package/dist/src/bundle/types.d.ts +105 -0
  85. package/dist/src/bundle/types.js +21 -0
  86. package/dist/src/cli.d.ts +90 -20
  87. package/dist/src/cli.js +2407 -365
  88. package/dist/src/credentials.d.ts +4 -3
  89. package/dist/src/credentials.js +21 -19
  90. package/dist/src/crypto/allowed-signers.d.ts +68 -0
  91. package/dist/src/crypto/allowed-signers.js +307 -0
  92. package/dist/src/crypto/canonical.d.ts +8 -0
  93. package/dist/src/crypto/canonical.js +92 -0
  94. package/dist/src/crypto/chain.d.ts +65 -0
  95. package/dist/src/crypto/chain.js +377 -0
  96. package/dist/src/crypto/dsse.d.ts +209 -0
  97. package/dist/src/crypto/dsse.js +282 -0
  98. package/dist/src/crypto/enrollment.d.ts +78 -0
  99. package/dist/src/crypto/enrollment.js +186 -0
  100. package/dist/src/crypto/index.d.ts +48 -0
  101. package/dist/src/crypto/index.js +44 -0
  102. package/dist/src/crypto/keys.d.ts +258 -0
  103. package/dist/src/crypto/keys.js +908 -0
  104. package/dist/src/crypto/org-root.d.ts +33 -0
  105. package/dist/src/crypto/org-root.js +78 -0
  106. package/dist/src/crypto/origin-rules.d.ts +56 -0
  107. package/dist/src/crypto/origin-rules.js +143 -0
  108. package/dist/src/crypto/policy-floor.d.ts +98 -0
  109. package/dist/src/crypto/policy-floor.js +353 -0
  110. package/dist/src/crypto/records.d.ts +316 -0
  111. package/dist/src/crypto/records.js +157 -0
  112. package/dist/src/crypto/scope.d.ts +49 -0
  113. package/dist/src/crypto/scope.js +83 -0
  114. package/dist/src/crypto/ssh.d.ts +171 -0
  115. package/dist/src/crypto/ssh.js +396 -0
  116. package/dist/src/crypto/submission.d.ts +33 -0
  117. package/dist/src/crypto/submission.js +47 -0
  118. package/dist/src/crypto/trust-roots.d.ts +29 -0
  119. package/dist/src/crypto/trust-roots.js +39 -0
  120. package/dist/src/crypto/verify-consumed.d.ts +67 -0
  121. package/dist/src/crypto/verify-consumed.js +259 -0
  122. package/dist/src/crypto/verify-origin.d.ts +50 -0
  123. package/dist/src/crypto/verify-origin.js +151 -0
  124. package/dist/src/crypto/verify-publication.d.ts +60 -0
  125. package/dist/src/crypto/verify-publication.js +150 -0
  126. package/dist/src/defs.d.ts +24 -1
  127. package/dist/src/defs.js +145 -25
  128. package/dist/src/engine.d.ts +99 -3
  129. package/dist/src/engine.js +238 -34
  130. package/dist/src/factory.d.ts +16 -0
  131. package/dist/src/factory.js +16 -4
  132. package/dist/src/global-config.d.ts +59 -0
  133. package/dist/src/global-config.js +84 -0
  134. package/dist/src/hub.d.ts +75 -21
  135. package/dist/src/hub.js +123 -40
  136. package/dist/src/index.d.ts +17 -2
  137. package/dist/src/index.js +20 -2
  138. package/dist/src/install.d.ts +538 -0
  139. package/dist/src/install.js +1981 -0
  140. package/dist/src/lock.d.ts +15 -57
  141. package/dist/src/lock.js +251 -143
  142. package/dist/src/mcp/serve.d.ts +46 -22
  143. package/dist/src/mcp/serve.js +167 -44
  144. package/dist/src/mcp/server.js +12 -1
  145. package/dist/src/model.d.ts +15 -0
  146. package/dist/src/model.js +111 -1
  147. package/dist/src/order-resolver.d.ts +184 -0
  148. package/dist/src/order-resolver.js +252 -0
  149. package/dist/src/package-version.d.ts +10 -0
  150. package/dist/src/package-version.js +42 -0
  151. package/dist/src/paths.d.ts +14 -1
  152. package/dist/src/paths.js +18 -0
  153. package/dist/src/schemas/enrollment-grant.v1.schema.json +90 -0
  154. package/dist/src/schemas/index.d.ts +1416 -0
  155. package/dist/src/schemas/index.js +31 -0
  156. package/dist/src/schemas/order.v1.schema.json +106 -0
  157. package/dist/src/schemas/origin.v1.schema.json +68 -0
  158. package/dist/src/schemas/policy-floor.v1.schema.json +29 -0
  159. package/dist/src/schemas/publication.v1.schema.json +31 -0
  160. package/dist/src/schemas/revocation.v1.schema.json +39 -0
  161. package/dist/src/schemas/submission.v1.schema.json +61 -0
  162. package/dist/src/store/def-source.d.ts +52 -0
  163. package/dist/src/store/def-source.js +335 -0
  164. package/dist/src/store/index-file.d.ts +69 -0
  165. package/dist/src/store/index-file.js +151 -0
  166. package/dist/src/store/index.d.ts +27 -0
  167. package/dist/src/store/index.js +22 -0
  168. package/dist/src/store/ingestor.d.ts +43 -0
  169. package/dist/src/store/ingestor.js +211 -0
  170. package/dist/src/store/install.d.ts +228 -0
  171. package/dist/src/store/install.js +555 -0
  172. package/dist/src/store/instruction-source.d.ts +49 -0
  173. package/dist/src/store/instruction-source.js +298 -0
  174. package/dist/src/store/origin-evidence.d.ts +21 -0
  175. package/dist/src/store/origin-evidence.js +66 -0
  176. package/dist/src/store/pre-commit-verifier.d.ts +68 -0
  177. package/dist/src/store/pre-commit-verifier.js +418 -0
  178. package/dist/src/store/resolve.d.ts +138 -0
  179. package/dist/src/store/resolve.js +363 -0
  180. package/dist/src/store/types.d.ts +288 -0
  181. package/dist/src/store/types.js +356 -0
  182. package/dist/src/types.d.ts +45 -11
  183. package/dist/src/untar.d.ts +8 -23
  184. package/dist/src/untar.js +10 -136
  185. package/docs/agent-runner.md +86 -0
  186. package/docs/authoring.md +57 -6
  187. package/docs/bundles.md +250 -0
  188. package/docs/cli.md +1171 -97
  189. package/docs/crypto.md +816 -0
  190. package/docs/design.md +342 -20
  191. package/docs/embedding.md +132 -25
  192. package/docs/wire-contracts.md +380 -0
  193. package/package.json +6 -1
  194. package/plugins/claude-code/.claude-plugin/marketplace.json +14 -0
  195. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +8 -0
  196. package/plugins/claude-code/plugin/.mcp.json +14 -0
  197. package/plugins/claude-code/plugin/hooks/hooks.json +26 -0
  198. package/plugins/claude-code/plugin/hooks/session-end.sh +40 -0
  199. package/plugins/claude-code/plugin/hooks/session-start.sh +52 -0
  200. package/plugins/claude-code/plugin/skills/author/SKILL.md +181 -0
  201. package/plugins/claude-code/plugin/skills/conduct/SKILL.md +106 -0
  202. package/plugins/claude-code/plugin/skills/shift/SKILL.md +105 -0
  203. package/plugins/codex/.agents/plugins/marketplace.json +21 -0
  204. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +7 -0
  205. package/plugins/codex/plugins/owenloop/.mcp.json +20 -0
  206. package/plugins/codex/plugins/owenloop/hooks/hooks.json +26 -0
  207. package/plugins/codex/plugins/owenloop/hooks/session-end.sh +40 -0
  208. package/plugins/codex/plugins/owenloop/hooks/session-start.sh +52 -0
  209. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +181 -0
  210. package/plugins/codex/plugins/owenloop/skills/conduct/SKILL.md +106 -0
  211. package/plugins/codex/plugins/owenloop/skills/shift/SKILL.md +105 -0
@@ -0,0 +1,908 @@
1
+ /**
2
+ * Principal signing-key management: generate, store, and materialize Ed25519
3
+ * keys for owenloop's three local principals (human, machine, agent).
4
+ *
5
+ * **Key handles are namespaced by `{ origin, kind, id }`** — the normalized
6
+ * hub origin plus a stable principal identity:
7
+ * - human: `id` = the hub actor id (`whoami.actor.id`)
8
+ * - machine: `id` = `"local"` (the local store already supplies host scope;
9
+ * origin prevents cross-hub collision and linkability)
10
+ * - agent: `id` = the agent identity id (`agentId`)
11
+ * Rekeying an existing agent credential retains the agent's signing key (the
12
+ * `agentId` is unchanged); minting a new agent gets a new key.
13
+ *
14
+ * **One selected backend, chosen once, never error-fallback** (REL-6 — a
15
+ * fallback after a selected store fails can create two different private keys
16
+ * for the same principal, a "shadow identity"):
17
+ * 1. macOS: `security` generic-password entries;
18
+ * 2. Linux: `secret-tool` when the executable is on `PATH`;
19
+ * 3. otherwise: one atomic `0600` record file under `$HOME/.owenloop/keys/`
20
+ * (both `$HOME/.owenloop` and `keys` forced to `0700`, symlinked or
21
+ * non-directory paths refused).
22
+ * `OWENLOOP_NO_KEYCHAIN=1` forces the file backend — the same explicit
23
+ * override the credential store uses.
24
+ *
25
+ * **Private bytes never leave the store.** `security`/`secret-tool` receive
26
+ * records on child stdin, and their lookup commands' secret-bearing stdout is
27
+ * redirected directly to a pre-opened `0600` temp file descriptor — never
28
+ * captured, inherited, logged, or interpolated into an error message. Child
29
+ * failures produce fixed operation/status messages. A generated key
30
+ * materializes for `ssh-keygen` only inside a unique `0700` temp dir as a
31
+ * `0600` file, removed in `finally`; a reused key passes only its canonical
32
+ * path. No public API hands a caller private-key text.
33
+ *
34
+ * `ensure` is serialized per key ref by the repo's file lock
35
+ * (`$HOME/.owenloop/keys/<hash>.lock`): acquire → re-read → generate only when
36
+ * still absent. A corrupt/unreadable existing key is a hard failure, never a
37
+ * silent rotation.
38
+ */
39
+ import { spawnSync } from 'node:child_process';
40
+ import { createHash, randomBytes } from 'node:crypto';
41
+ import { chmodSync, closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, } from 'node:fs';
42
+ import { tmpdir } from 'node:os';
43
+ import { delimiter, dirname, isAbsolute, join, resolve } from 'node:path';
44
+ import { acquireFileLock, releaseFileLock } from "../lock.js";
45
+ import { normalizeOrigin, writeFileAtomic } from "../hub.js";
46
+ import { assertEd25519PubText } from "./ssh.js";
47
+ import { CliError } from "../util.js";
48
+ const OPENSSH_PRIVATE_BEGIN = '-----BEGIN OPENSSH PRIVATE KEY-----';
49
+ const OPENSSH_PRIVATE_END = '-----END OPENSSH PRIVATE KEY-----';
50
+ const OPENSSH_PRIVATE_LINE_WIDTH = 70;
51
+ /**
52
+ * Reconstruct only the exact pre-fix macOS damage: JSON `\\n` escapes in a
53
+ * stock ssh-keygen OpenSSH private key were consumed by `security -i` and
54
+ * stored as literal `n` separators. Stock OpenSSH armor wraps body lines at 70
55
+ * bytes, so separator positions are deterministic even when Base64 contains
56
+ * genuine `n` characters. Identity verification still gates every rewrite.
57
+ */
58
+ function reconstructDamagedOpenSshPrivateKey(value) {
59
+ const prefix = `${OPENSSH_PRIVATE_BEGIN}n`;
60
+ const suffix = `n${OPENSSH_PRIVATE_END}n`;
61
+ if (!value.startsWith(prefix) || !value.endsWith(suffix))
62
+ return { kind: 'not-damaged' };
63
+ let body = value.slice(prefix.length, -suffix.length);
64
+ const lines = [];
65
+ while (body.length > OPENSSH_PRIVATE_LINE_WIDTH) {
66
+ const line = body.slice(0, OPENSSH_PRIVATE_LINE_WIDTH);
67
+ if (body[OPENSSH_PRIVATE_LINE_WIDTH] !== 'n' || !/^[A-Za-z0-9+/=]+$/.test(line)) {
68
+ return { kind: 'unrecoverable' };
69
+ }
70
+ lines.push(line);
71
+ body = body.slice(OPENSSH_PRIVATE_LINE_WIDTH + 1);
72
+ }
73
+ if (lines.length === 0 || body.length === 0 || !/^[A-Za-z0-9+/=]+$/.test(body)) {
74
+ return { kind: 'unrecoverable' };
75
+ }
76
+ lines.push(body);
77
+ return {
78
+ kind: 'candidate',
79
+ privateKey: `${OPENSSH_PRIVATE_BEGIN}\n${lines.join('\n')}\n${OPENSSH_PRIVATE_END}\n`,
80
+ };
81
+ }
82
+ /** Fixed error for a backend operation. Never includes child output. */
83
+ function backendError(backend, detail) {
84
+ return new CliError(`signing-key storage (${backend}) failed: ${detail}`);
85
+ }
86
+ /** Canonical, order-stable serialization of a key ref (for hashing). */
87
+ export function canonicalKeyRef(ref) {
88
+ assertKeyRef(ref);
89
+ return JSON.stringify({ origin: ref.origin, kind: ref.kind, id: ref.id });
90
+ }
91
+ /** Validate a key ref shape. Throws a fixed `CliError` on any bad field. */
92
+ export function assertKeyRef(ref) {
93
+ if (typeof ref.origin !== 'string' || ref.origin.trim() === '') {
94
+ throw new CliError('signing-key ref: origin must be a non-empty string');
95
+ }
96
+ let normalized;
97
+ try {
98
+ normalized = normalizeOrigin(ref.origin);
99
+ }
100
+ catch {
101
+ throw new CliError('signing-key ref: origin must be a valid normalized http(s) origin');
102
+ }
103
+ if (normalized !== ref.origin) {
104
+ throw new CliError('signing-key ref: origin must be a normalized origin');
105
+ }
106
+ if (ref.kind !== 'human' && ref.kind !== 'machine' && ref.kind !== 'agent') {
107
+ throw new CliError(`signing-key ref: kind must be human, machine, or agent (got '${String(ref.kind)}')`);
108
+ }
109
+ if (typeof ref.id !== 'string' || ref.id.trim() === '') {
110
+ throw new CliError('signing-key ref: id must be a non-empty string');
111
+ }
112
+ }
113
+ /** The SHA-256 hex of the canonical ref — file name / keychain account. */
114
+ export function keyRefHash(ref) {
115
+ return createHash('sha256').update(canonicalKeyRef(ref)).digest('hex');
116
+ }
117
+ /** Compute the `SHA256:<unpadded-base64>` fingerprint of a public-key blob. */
118
+ export function keyidFromBlob(blob) {
119
+ return `SHA256:${createHash('sha256').update(blob).digest('base64').replace(/=+$/, '')}`;
120
+ }
121
+ /** Decode a standard OpenSSH public-key blob without Node's permissive Base64 rules. */
122
+ function decodePublicKeyBlob(text) {
123
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(text) || text.length % 4 === 1) {
124
+ throw new CliError('public key Base64 is malformed');
125
+ }
126
+ const body = text.replace(/=+$/, '');
127
+ const expectedPadding = body.length % 4 === 0 ? 0 : 4 - (body.length % 4);
128
+ if (text.length - body.length !== expectedPadding)
129
+ throw new CliError('public key Base64 is malformed');
130
+ const blob = Buffer.from(text, 'base64');
131
+ if (blob.length === 0)
132
+ throw new CliError('public key blob is empty');
133
+ return blob;
134
+ }
135
+ /** Parse an OpenSSH public-key line into a descriptor (never reads private bytes). */
136
+ export function publicKeyDescriptor(pubText) {
137
+ const line = pubText.split(/\r?\n/).find((l) => l.trim() !== '');
138
+ if (line === undefined)
139
+ throw new CliError('public key file is empty');
140
+ const parts = line.trim().split(/\s+/);
141
+ if (parts.length < 2)
142
+ throw new CliError('public key line is malformed');
143
+ const keyType = parts[0];
144
+ const blob = decodePublicKeyBlob(parts[1]);
145
+ const comment = parts.slice(2).join(' ');
146
+ return { keyid: keyidFromBlob(blob), keyType, openSshPublicKey: parts.slice(0, 2).join(' ') + (comment ? ` ${comment}` : ''), comment };
147
+ }
148
+ const KEYGEN_TIMEOUT_MS = 15_000;
149
+ /** The default `spawnSync` runner — `shell: false`, never inherits stdio. */
150
+ const defaultRunner = {
151
+ run(cmd, args, opts) {
152
+ const stdio = [
153
+ opts.stdin !== undefined ? 'pipe' : 'ignore',
154
+ opts.stdoutFd !== undefined ? opts.stdoutFd : opts.captureStdout ? 'pipe' : 'ignore',
155
+ 'ignore',
156
+ ];
157
+ const r = spawnSync(cmd, args, {
158
+ shell: false,
159
+ input: opts.stdin,
160
+ stdio,
161
+ timeout: opts.timeoutMs ?? KEYGEN_TIMEOUT_MS,
162
+ });
163
+ const stdout = opts.captureStdout && r.stdout !== null && r.stdout !== undefined ? r.stdout : Buffer.alloc(0);
164
+ return { status: r.status, stdout };
165
+ },
166
+ };
167
+ /**
168
+ * The principal key manager. One backend is selected at construction; all
169
+ * operations use it exclusively (no error-fallback — see the module doc).
170
+ */
171
+ export class PrincipalKeyManager {
172
+ env;
173
+ backendKind;
174
+ runner;
175
+ homeDir;
176
+ tempBase;
177
+ sshKeygen;
178
+ constructor(opts) {
179
+ this.env = opts.env;
180
+ this.runner = opts.runner ?? defaultRunner;
181
+ this.tempBase = opts.tempDir ?? tmpdir();
182
+ this.sshKeygen = opts.sshKeygen ?? 'ssh-keygen';
183
+ const home = opts.homeDir ?? opts.env.HOME;
184
+ if (!home || home.trim() === '') {
185
+ throw new CliError('signing-key storage needs $HOME to be set');
186
+ }
187
+ this.homeDir = home;
188
+ this.backendKind = opts.backend ?? this.selectBackend(opts.platform ?? process.platform, opts.commandExists);
189
+ }
190
+ /** Which backend was selected (non-secret; printable). */
191
+ get backend() {
192
+ return this.backendKind;
193
+ }
194
+ /**
195
+ * Backend selection: `OWENLOOP_NO_KEYCHAIN=1` forces `file`; macOS uses
196
+ * `security`; Linux uses `secret-tool` when present on PATH; everything else
197
+ * falls back to the secure file store.
198
+ */
199
+ selectBackend(platform, commandExists) {
200
+ if (this.env.OWENLOOP_NO_KEYCHAIN === '1')
201
+ return 'file';
202
+ if (platform === 'darwin')
203
+ return 'macos-security';
204
+ if (platform === 'linux') {
205
+ const probe = commandExists ?? ((cmd) => commandOnPath(this.env, cmd));
206
+ return probe('secret-tool') ? 'secret-tool' : 'file';
207
+ }
208
+ return 'file';
209
+ }
210
+ /** `$HOME/.owenloop`. */
211
+ baseDir() {
212
+ return join(this.homeDir, '.owenloop');
213
+ }
214
+ /** `$HOME/.owenloop/keys`. */
215
+ keysDir() {
216
+ return join(this.baseDir(), 'keys');
217
+ }
218
+ /** Force `0700`, refusing symlinked / non-directory paths. */
219
+ ensureSecureDir(dir) {
220
+ const st = lstatSync(dir, { throwIfNoEntry: false });
221
+ if (st !== undefined) {
222
+ if (st.isSymbolicLink())
223
+ throw new CliError(`refusing to write under ${dir}: it is a symbolic link`);
224
+ if (!st.isDirectory())
225
+ throw new CliError(`refusing to write under ${dir}: it is not a directory`);
226
+ }
227
+ else {
228
+ mkdirSync(dir);
229
+ }
230
+ chmodSync(dir, 0o700);
231
+ }
232
+ /** Ensure both storage dirs exist with the required modes. */
233
+ ensureDirs() {
234
+ this.ensureSecureDir(this.baseDir());
235
+ this.ensureSecureDir(this.keysDir());
236
+ }
237
+ /** The file-backend record path for a ref. */
238
+ recordPath(ref) {
239
+ return join(this.keysDir(), `${keyRefHash(ref)}.json`);
240
+ }
241
+ /** The per-ref lock path. */
242
+ lockPath(ref) {
243
+ return join(this.keysDir(), `${keyRefHash(ref)}.lock`);
244
+ }
245
+ /** A non-secret per-ref ownership marker that prevents backend shadowing. */
246
+ backendMarkerPath(ref) {
247
+ return join(this.keysDir(), `${keyRefHash(ref)}.backend`);
248
+ }
249
+ /** A non-secret pointer that lets offline callers recover the principal ref. */
250
+ refPointerPath(ref) {
251
+ return join(this.keysDir(), `${keyRefHash(ref)}.ref`);
252
+ }
253
+ readBackendOwner(ref) {
254
+ const marker = this.backendMarkerPath(ref);
255
+ if (!existsSync(marker))
256
+ return null;
257
+ const value = readFileSync(marker, 'utf8').trim();
258
+ if (value !== 'macos-security' && value !== 'secret-tool' && value !== 'file') {
259
+ throw new CliError(`signing-key backend ownership for ${ref.kind}:${ref.id} is corrupt`);
260
+ }
261
+ return value;
262
+ }
263
+ /** Refuse a selected backend that differs from the persisted owner. */
264
+ assertBackendOwner(ref) {
265
+ const owner = this.readBackendOwner(ref);
266
+ if (owner !== null && owner !== this.backendKind) {
267
+ throw new CliError(`signing-key ref ${ref.kind}:${ref.id} belongs to backend ${owner}, not the selected backend ${this.backendKind}`);
268
+ }
269
+ // A pre-marker file record is detectable even when PATH now selects a
270
+ // different backend. Refuse the new backend rather than creating a shadow.
271
+ if (owner === null && this.backendKind !== 'file' && existsSync(this.recordPath(ref))) {
272
+ throw new CliError(`signing-key ref ${ref.kind}:${ref.id} has a file-backed record, but the selected backend is ${this.backendKind}`);
273
+ }
274
+ }
275
+ /** Claim ownership before the first write; marker writes are non-secret. */
276
+ claimBackend(ref) {
277
+ this.assertBackendOwner(ref);
278
+ const marker = this.backendMarkerPath(ref);
279
+ if (!existsSync(marker)) {
280
+ writeFileAtomic(marker, `${this.backendKind}\n`, { mode: 0o600 });
281
+ chmodSync(marker, 0o600);
282
+ }
283
+ }
284
+ // ---- backend read/write ---------------------------------------------------
285
+ /** Read the raw record text from the selected backend, or `null` when absent. */
286
+ readRecordText(ref) {
287
+ this.ensureDirs();
288
+ this.assertBackendOwner(ref);
289
+ const hash = keyRefHash(ref);
290
+ if (this.backendKind === 'file') {
291
+ const path = this.recordPath(ref);
292
+ if (!existsSync(path))
293
+ return null;
294
+ const text = readFileSync(path, 'utf8');
295
+ this.claimBackend(ref);
296
+ return text;
297
+ }
298
+ // security / secret-tool: redirect the lookup's secret-bearing stdout to a
299
+ // pre-opened 0600 temp fd; command, read, close, and unlink all share one
300
+ // outer finally so every return and every failure cleans up the temp file.
301
+ const tmpPath = join(this.tempBase, `owenloop-keyread-${randomBytes(8).toString('hex')}`);
302
+ const fd = openSync(tmpPath, 'w', 0o600);
303
+ try {
304
+ let r;
305
+ if (this.backendKind === 'macos-security') {
306
+ // `-w` is what makes `security` print the secret itself; without it
307
+ // stdout carries the item's attribute dump, which is not the record.
308
+ r = this.runner.run('security', ['find-generic-password', '-s', 'owenloop-signing', '-a', hash, '-w'], {
309
+ stdoutFd: fd,
310
+ });
311
+ // 44 = errSecItemNotFound — a clean absence.
312
+ if (r.status === 44)
313
+ return null;
314
+ if (r.status !== 0)
315
+ throw backendError('macos-security', `lookup exited with status ${r.status}`);
316
+ }
317
+ else {
318
+ r = this.runner.run('secret-tool', ['lookup', 'owenloop-service', 'owenloop-signing', 'owenloop-ref', hash], { stdoutFd: fd });
319
+ // libsecret uses status 1 for an absent item. It is not a backend
320
+ // failure; all other nonzero statuses remain hard failures.
321
+ if (r.status === 1)
322
+ return null;
323
+ if (r.status !== 0)
324
+ throw backendError('secret-tool', `lookup exited with status ${r.status}`);
325
+ }
326
+ const text = readFileSync(tmpPath, 'utf8');
327
+ if (text === '')
328
+ return null;
329
+ this.claimBackend(ref);
330
+ return text;
331
+ }
332
+ finally {
333
+ try {
334
+ closeSync(fd);
335
+ }
336
+ finally {
337
+ rmSync(tmpPath, { force: true });
338
+ }
339
+ }
340
+ }
341
+ /** Write the raw record text to the selected backend. Loud failure, fixed message. */
342
+ writeRecordText(ref, recordText) {
343
+ this.ensureDirs();
344
+ this.claimBackend(ref);
345
+ const hash = keyRefHash(ref);
346
+ if (this.backendKind === 'file') {
347
+ writeFileAtomic(this.recordPath(ref), recordText, { mode: 0o600 });
348
+ chmodSync(this.recordPath(ref), 0o600);
349
+ return;
350
+ }
351
+ if (this.backendKind === 'macos-security') {
352
+ // The secret rides on the `-i` command stream's stdin (single-quoted),
353
+ // never on argv. Same escaping as hub.ts's defaultKeychain. `security -i`
354
+ // treats `\` as an escape character even inside single quotes, so
355
+ // backslashes must be doubled FIRST (before quote-escaping inserts its
356
+ // own), or the record's JSON `\n` escapes degrade to bare `n` on store.
357
+ const sq = (s) => `'${s.replace(/\\/g, '\\\\').replace(/'/g, `'\\''`)}'`;
358
+ const cmd = `add-generic-password -U -s ${sq('owenloop-signing')} -a ${sq(hash)} -w ${sq(recordText)}\n`;
359
+ const r = this.runner.run('security', ['-i'], { stdin: Buffer.from(cmd, 'utf8') });
360
+ if (r.status !== 0)
361
+ throw backendError('macos-security', `store exited with status ${r.status}`);
362
+ return;
363
+ }
364
+ const r = this.runner.run('secret-tool', ['store', '--label', `owenloop signing key ${ref.kind}`, 'owenloop-service', 'owenloop-signing', 'owenloop-ref', hash], { stdin: Buffer.from(recordText, 'utf8') });
365
+ if (r.status !== 0)
366
+ throw backendError('secret-tool', `store exited with status ${r.status}`);
367
+ }
368
+ /** Derive a public key from generated private material without exposing it. */
369
+ deriveGeneratedPublic(privateKey) {
370
+ const dir = this.mkTempKeyDir();
371
+ try {
372
+ const keyPath = join(dir, 'id');
373
+ writeFileAtomic(keyPath, privateKey, { mode: 0o600 });
374
+ chmodSync(keyPath, 0o600);
375
+ const result = this.runner.run(this.sshKeygen, ['-y', '-f', keyPath], { captureStdout: true });
376
+ if (result.status !== 0)
377
+ throw new Error('derivation failed');
378
+ const text = result.stdout.toString('utf8');
379
+ const descriptor = publicKeyDescriptor(text);
380
+ assertEd25519PubText(text, 'stored signing key');
381
+ return descriptor;
382
+ }
383
+ catch {
384
+ throw new CliError('signing-key record is corrupt (private key does not derive a valid Ed25519 public key)');
385
+ }
386
+ finally {
387
+ rmSync(dir, { recursive: true, force: true });
388
+ }
389
+ }
390
+ /** Parse + validate a record against the requested ref. Corrupt = hard error. */
391
+ parseRecord(ref, text) {
392
+ let raw;
393
+ try {
394
+ raw = JSON.parse(text);
395
+ }
396
+ catch {
397
+ throw new CliError(`signing-key record for ${ref.kind}:${ref.id} is corrupt — refusing to use or replace it`);
398
+ }
399
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
400
+ throw new CliError(`signing-key record for ${ref.kind}:${ref.id} is corrupt — refusing to use or replace it`);
401
+ }
402
+ const rec = raw;
403
+ if (rec.version !== 1 ||
404
+ rec.ref === undefined ||
405
+ rec.ref.origin !== ref.origin ||
406
+ rec.ref.kind !== ref.kind ||
407
+ rec.ref.id !== ref.id) {
408
+ throw new CliError(`signing-key record for ${ref.kind}:${ref.id} does not match the requested ref — refusing to use it`);
409
+ }
410
+ if (rec.kind !== 'generated' && rec.kind !== 'reused') {
411
+ throw new CliError(`signing-key record for ${ref.kind}:${ref.id} is corrupt (unknown key kind) — refusing to use it`);
412
+ }
413
+ if (rec.kind === 'generated' && (typeof rec.privateKey !== 'string' || rec.privateKey === '')) {
414
+ throw new CliError(`signing-key record for ${ref.kind}:${ref.id} is corrupt (missing key material) — refusing to use it`);
415
+ }
416
+ if (rec.kind === 'reused' && (typeof rec.path !== 'string' || rec.path === '')) {
417
+ throw new CliError(`signing-key record for ${ref.kind}:${ref.id} is corrupt (missing reused path) — refusing to use it`);
418
+ }
419
+ if (typeof rec.publicKey !== 'string' || typeof rec.fingerprint !== 'string' || typeof rec.createdAt !== 'string') {
420
+ throw new CliError(`signing-key record for ${ref.kind}:${ref.id} is corrupt (invalid record fields) — refusing to use it`);
421
+ }
422
+ let descriptor;
423
+ try {
424
+ descriptor = publicKeyDescriptor(rec.publicKey);
425
+ assertEd25519PubText(rec.publicKey, 'stored signing key');
426
+ }
427
+ catch {
428
+ throw new CliError(`signing-key record for ${ref.kind}:${ref.id} is corrupt (invalid Ed25519 public key) — refusing to use it`);
429
+ }
430
+ if (!/^SHA256:[A-Za-z0-9+/]+$/.test(rec.fingerprint) || rec.fingerprint !== descriptor.keyid) {
431
+ throw new CliError(`signing-key record for ${ref.kind}:${ref.id} is corrupt (fingerprint mismatch) — refusing to use it`);
432
+ }
433
+ try {
434
+ if (new Date(rec.createdAt).toISOString() !== rec.createdAt)
435
+ throw new Error('not canonical ISO-8601');
436
+ }
437
+ catch {
438
+ throw new CliError(`signing-key record for ${ref.kind}:${ref.id} is corrupt (invalid createdAt) — refusing to use it`);
439
+ }
440
+ if (rec.kind === 'generated') {
441
+ if (rec.path !== undefined) {
442
+ throw new CliError(`signing-key record for ${ref.kind}:${ref.id} is corrupt (unexpected reused path) — refusing to use it`);
443
+ }
444
+ const derived = this.deriveGeneratedPublic(rec.privateKey);
445
+ if (derived.keyid !== descriptor.keyid) {
446
+ throw new CliError(`signing-key record for ${ref.kind}:${ref.id} is corrupt (private/public key mismatch) — refusing to use it`);
447
+ }
448
+ }
449
+ else if (rec.privateKey !== undefined) {
450
+ throw new CliError(`signing-key record for ${ref.kind}:${ref.id} is corrupt (reused record contains key material) — refusing to use it`);
451
+ }
452
+ return rec;
453
+ }
454
+ /**
455
+ * The repair command deliberately names the exact non-secret Keychain account
456
+ * handle. Deleting that one damaged item and rerunning setup is the supported
457
+ * explicit rotation path when identity-preserving migration cannot verify.
458
+ */
459
+ damagedMacosRecordError(ref) {
460
+ return new CliError(`signing-key record for ${ref.kind}:${ref.id} has pre-fix macOS Keychain newline damage, ` +
461
+ 'but the original key identity cannot be verified — rotate explicitly with ' +
462
+ `\`security delete-generic-password -s owenloop-signing -a ${keyRefHash(ref)}\` ` +
463
+ 'and then run `owenloop setup`');
464
+ }
465
+ /**
466
+ * Migrate the one known v1 macOS writer defect while the caller holds the
467
+ * per-ref lock. A candidate is rewritten only after full record validation
468
+ * derives the already-stored public fingerprint from the repaired private key.
469
+ */
470
+ migrateDamagedMacosRecord(ref, text) {
471
+ if (this.backendKind !== 'macos-security')
472
+ return text;
473
+ let raw;
474
+ try {
475
+ raw = JSON.parse(text);
476
+ }
477
+ catch {
478
+ return text;
479
+ }
480
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
481
+ return text;
482
+ const rec = raw;
483
+ if (rec.version !== 1 || rec.kind !== 'generated' || typeof rec.privateKey !== 'string')
484
+ return text;
485
+ const repaired = reconstructDamagedOpenSshPrivateKey(rec.privateKey);
486
+ if (repaired.kind === 'not-damaged')
487
+ return text;
488
+ if (repaired.kind === 'unrecoverable')
489
+ throw this.damagedMacosRecordError(ref);
490
+ const repairedText = JSON.stringify({ ...rec, privateKey: repaired.privateKey });
491
+ try {
492
+ this.parseRecord(ref, repairedText);
493
+ }
494
+ catch {
495
+ throw this.damagedMacosRecordError(ref);
496
+ }
497
+ this.writeRecordText(ref, repairedText);
498
+ return repairedText;
499
+ }
500
+ /**
501
+ * Read + validate the stored record for a ref, or `null` when absent. macOS
502
+ * reads share the per-ref lock with `ensure`, so every normal read path can
503
+ * perform the identity-preserving v1 migration without racing key creation.
504
+ */
505
+ async readRecord(ref) {
506
+ assertKeyRef(ref);
507
+ if (this.backendKind !== 'macos-security') {
508
+ const text = this.readRecordText(ref);
509
+ return text === null ? null : this.parseRecord(ref, text);
510
+ }
511
+ let lock = null;
512
+ try {
513
+ lock = await acquireFileLock(this.lockPath(ref), {
514
+ waitMs: 30_000,
515
+ label: 'owenloop signing-key migration',
516
+ });
517
+ const text = this.readRecordText(ref);
518
+ return text === null
519
+ ? null
520
+ : this.parseRecord(ref, this.migrateDamagedMacosRecord(ref, text));
521
+ }
522
+ finally {
523
+ if (lock !== null)
524
+ releaseFileLock(lock);
525
+ }
526
+ }
527
+ // ---- public API ------------------------------------------------------------
528
+ /**
529
+ * Non-secret inspection: does a key exist for this ref, and what is its
530
+ * public descriptor / source / backend? For generated records, validation
531
+ * temporarily materializes private bytes in a 0600 file so stock ssh-keygen
532
+ * can derive and compare the public half; private bytes never enter the
533
+ * returned result.
534
+ */
535
+ async inspect(ref) {
536
+ assertKeyRef(ref);
537
+ if (this.backendKind === 'file')
538
+ this.ensureDirs();
539
+ const rec = await this.readRecord(ref);
540
+ if (rec === null)
541
+ return { exists: false, source: undefined, backend: undefined, publicKey: undefined };
542
+ const desc = publicKeyDescriptor(rec.publicKey);
543
+ return {
544
+ exists: true,
545
+ source: rec.kind,
546
+ backend: rec.kind === 'reused' ? 'reused' : this.backendKind,
547
+ publicKey: desc,
548
+ };
549
+ }
550
+ /** Write the non-secret ref pointer with strict file permissions. */
551
+ writeRefPointer(ref) {
552
+ writeFileAtomic(this.refPointerPath(ref), canonicalKeyRef(ref), { mode: 0o600 });
553
+ chmodSync(this.refPointerPath(ref), 0o600);
554
+ }
555
+ /**
556
+ * List valid non-secret principal-ref pointers. Malformed, symlinked, and
557
+ * mismatched entries are ignored so a stray file cannot block key discovery.
558
+ */
559
+ listRefs() {
560
+ // Resolution is a read-only discovery operation. Do not create the key
561
+ // store merely because a signed publish is probing for a missing key.
562
+ const base = this.baseDir();
563
+ const baseStat = lstatSync(base, { throwIfNoEntry: false });
564
+ if (baseStat === undefined)
565
+ return [];
566
+ if (baseStat.isSymbolicLink())
567
+ throw new CliError(`refusing to read under ${base}: it is a symbolic link`);
568
+ if (!baseStat.isDirectory())
569
+ throw new CliError(`refusing to read under ${base}: it is not a directory`);
570
+ const keys = this.keysDir();
571
+ const keysStat = lstatSync(keys, { throwIfNoEntry: false });
572
+ if (keysStat === undefined)
573
+ return [];
574
+ if (keysStat.isSymbolicLink())
575
+ throw new CliError(`refusing to read under ${keys}: it is a symbolic link`);
576
+ if (!keysStat.isDirectory())
577
+ throw new CliError(`refusing to read under ${keys}: it is not a directory`);
578
+ const refs = [];
579
+ for (const name of readdirSync(keys)) {
580
+ if (!name.endsWith('.ref'))
581
+ continue;
582
+ const path = join(this.keysDir(), name);
583
+ try {
584
+ const st = lstatSync(path);
585
+ if (!st.isFile())
586
+ continue;
587
+ const raw = JSON.parse(readFileSync(path, 'utf8'));
588
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
589
+ continue;
590
+ const value = raw;
591
+ if (typeof value.origin !== 'string' || typeof value.kind !== 'string' || typeof value.id !== 'string')
592
+ continue;
593
+ const ref = { origin: value.origin, kind: value.kind, id: value.id };
594
+ assertKeyRef(ref);
595
+ if (name !== `${keyRefHash(ref)}.ref` || JSON.stringify(raw) !== canonicalKeyRef(ref))
596
+ continue;
597
+ refs.push(ref);
598
+ }
599
+ catch {
600
+ // A malformed pointer cannot identify a signing key; skip it.
601
+ }
602
+ }
603
+ refs.sort((a, b) => canonicalKeyRef(a).localeCompare(canonicalKeyRef(b)));
604
+ return refs;
605
+ }
606
+ /** Resolve one principal ref by origin and kind for offline signing. */
607
+ resolveRef(origin, kind) {
608
+ let normalized;
609
+ try {
610
+ normalized = normalizeOrigin(origin);
611
+ }
612
+ catch {
613
+ throw new CliError('signing-key ref: origin must be a valid normalized http(s) origin');
614
+ }
615
+ if (kind !== 'human' && kind !== 'machine' && kind !== 'agent') {
616
+ throw new CliError(`signing-key ref: kind must be human, machine, or agent (got '${String(kind)}')`);
617
+ }
618
+ const matches = this.listRefs().filter((ref) => ref.origin === normalized && ref.kind === kind);
619
+ if (matches.length === 0)
620
+ return null;
621
+ if (matches.length > 1) {
622
+ throw new CliError(`multiple ${kind} signing-key refs found for ${normalized} — run owenloop setup to repair the key store`);
623
+ }
624
+ return matches[0];
625
+ }
626
+ /**
627
+ * Idempotently ensure a key exists for `ref`.
628
+ *
629
+ * - Present key ⇒ `{ state: 'existing' }` (zero key-record writes; the
630
+ * non-secret ref pointer is backfilled when needed).
631
+ * - `opts.reuse` on an ABSENT human key ⇒ validate the candidate SSH key
632
+ * (Ed25519 only) with a non-secret sign/verify challenge, then store only
633
+ * its canonical path + public key + fingerprint (`state: 'reused'`). The
634
+ * candidate's private bytes are never copied.
635
+ * - `opts.reuse` against a PRESENT key ⇒ hard conflict error (no rotation in
636
+ * WP-A2).
637
+ * - Otherwise generate a dedicated Ed25519 key in a unique `0700` temp dir
638
+ * and store it through the selected backend (`state: 'created'`).
639
+ *
640
+ * Serialized per ref by the file lock; after acquiring, the store is
641
+ * re-read before generating.
642
+ */
643
+ async ensure(ref, opts) {
644
+ assertKeyRef(ref);
645
+ this.ensureDirs();
646
+ let lock = null;
647
+ try {
648
+ lock = await acquireFileLock(this.lockPath(ref), {
649
+ waitMs: 30_000,
650
+ label: 'owenloop signing-key creation',
651
+ });
652
+ const existingText = this.readRecordText(ref);
653
+ const existing = existingText === null
654
+ ? null
655
+ : this.parseRecord(ref, this.migrateDamagedMacosRecord(ref, existingText));
656
+ if (existing !== null) {
657
+ if (opts?.reuse !== undefined) {
658
+ throw new CliError(`a ${ref.kind} signing key already exists for ${ref.origin} — rotation is not part of WP-A2; ` +
659
+ `the existing key is kept`);
660
+ }
661
+ this.writeRefPointer(ref);
662
+ return {
663
+ ref,
664
+ state: 'existing',
665
+ backend: existing.kind === 'reused' ? 'reused' : this.backendKind,
666
+ publicKey: publicKeyDescriptor(existing.publicKey),
667
+ };
668
+ }
669
+ if (opts?.reuse !== undefined) {
670
+ if (ref.kind !== 'human') {
671
+ throw new CliError('explicit SSH key reuse applies only to the human principal key');
672
+ }
673
+ const result = this.storeReused(ref, opts.reuse.path);
674
+ this.writeRefPointer(ref);
675
+ return result;
676
+ }
677
+ const result = this.generate(ref);
678
+ this.writeRefPointer(ref);
679
+ return result;
680
+ }
681
+ finally {
682
+ if (lock !== null)
683
+ releaseFileLock(lock);
684
+ }
685
+ }
686
+ /** Derive a candidate's public key from a public path, adjacent `.pub`, or private path. */
687
+ candidatePublicText(canonicalPath) {
688
+ try {
689
+ const ownText = readFileSync(canonicalPath, 'utf8');
690
+ const first = ownText.split(/\r?\n/).find((l) => l.trim() !== '')?.trim() ?? '';
691
+ if (/^(?:ssh-|ecdsa-|sk-)/.test(first))
692
+ return ownText;
693
+ }
694
+ catch {
695
+ // Let ssh-keygen produce the fixed derivation failure below.
696
+ }
697
+ // A private path is always derived by stock ssh-keygen. An adjacent .pub
698
+ // file is deliberately ignored because it may be stale or mismatched.
699
+ const result = this.runner.run(this.sshKeygen, ['-y', '-f', canonicalPath], { captureStdout: true });
700
+ if (result.status !== 0)
701
+ throw new Error('public-key derivation failed');
702
+ return result.stdout.toString('utf8');
703
+ }
704
+ /** Validate + record an explicit SSH key (human principal only). */
705
+ storeReused(ref, rawPath) {
706
+ const lexical = isAbsolute(rawPath) ? resolve(rawPath) : resolve(process.cwd(), rawPath);
707
+ if (!existsSync(lexical)) {
708
+ throw new CliError('--reuse-ssh-key: no such file');
709
+ }
710
+ let canonical;
711
+ try {
712
+ canonical = realpathSync(lexical);
713
+ }
714
+ catch {
715
+ throw new CliError('--reuse-ssh-key: cannot resolve the key path');
716
+ }
717
+ const st = statSync(canonical);
718
+ if (!st.isFile())
719
+ throw new CliError('--reuse-ssh-key: key path is not a regular file');
720
+ let pubText;
721
+ try {
722
+ pubText = this.candidatePublicText(canonical);
723
+ }
724
+ catch {
725
+ throw new CliError('--reuse-ssh-key: cannot derive an Ed25519 public key from the candidate');
726
+ }
727
+ try {
728
+ assertEd25519PubText(pubText, 'candidate key');
729
+ }
730
+ catch {
731
+ throw new CliError('--reuse-ssh-key: only Ed25519 keys are supported');
732
+ }
733
+ const desc = publicKeyDescriptor(pubText);
734
+ // Non-secret sign/verify challenge with the CANDIDATE key: proves the
735
+ // private half is usable (directly, or through ssh-agent for a public-key
736
+ // path) before the reference is recorded.
737
+ this.challengeSignVerify(canonical, desc);
738
+ const rec = {
739
+ version: 1,
740
+ ref,
741
+ kind: 'reused',
742
+ publicKey: desc.openSshPublicKey,
743
+ fingerprint: desc.keyid,
744
+ createdAt: new Date().toISOString(),
745
+ path: canonical,
746
+ };
747
+ this.writeRecordText(ref, JSON.stringify(rec));
748
+ return { ref, state: 'reused', backend: 'reused', publicKey: desc };
749
+ }
750
+ /**
751
+ * Sign a fixed challenge message with the candidate key and verify it with
752
+ * stock `ssh-keygen -Y verify` against the candidate's own public key as the
753
+ * sole allowed signer. Public-key-only inputs; the message is public.
754
+ */
755
+ challengeSignVerify(candidatePath, desc) {
756
+ const dir = this.mkTempKeyDir();
757
+ try {
758
+ const message = Buffer.from(`owenloop key validation challenge ${randomBytes(16).toString('hex')}`, 'utf8');
759
+ const principal = `owenloop-validate-${randomBytes(4).toString('hex')}`;
760
+ // sign: `-f <candidate>` — works for a private key path OR a public key
761
+ // whose private half is in ssh-agent; the message rides on stdin.
762
+ const signRes = this.runner.run(this.sshKeygen, ['-Y', 'sign', '-f', candidatePath, '-n', 'owenloop-key-validation'], {
763
+ stdin: message,
764
+ captureStdout: true,
765
+ });
766
+ if (signRes.status !== 0) {
767
+ throw new CliError('--reuse-ssh-key: the private half of the candidate is not usable (sign failed) — ' +
768
+ 'for a public-key path the key must be loaded in ssh-agent');
769
+ }
770
+ const armored = signRes.stdout.toString('utf8');
771
+ if (!armored.includes('-----BEGIN SSH SIGNATURE-----')) {
772
+ throw new CliError('--reuse-ssh-key: sign produced no armored signature');
773
+ }
774
+ const sigPath = join(dir, 'challenge.sig');
775
+ const allowedPath = join(dir, 'challenge.allowed');
776
+ writeFileAtomic(sigPath, armored, { mode: 0o600 });
777
+ writeFileAtomic(allowedPath, `${principal} ${desc.openSshPublicKey}\n`, { mode: 0o600 });
778
+ const verifyRes = this.runner.run(this.sshKeygen, ['-Y', 'verify', '-f', allowedPath, '-I', principal, '-n', 'owenloop-key-validation', '-s', sigPath], { stdin: message });
779
+ if (verifyRes.status !== 0) {
780
+ throw new CliError('--reuse-ssh-key: validation signature did not verify against the candidate public key');
781
+ }
782
+ }
783
+ finally {
784
+ rmSync(dir, { recursive: true, force: true });
785
+ }
786
+ }
787
+ /** Generate a dedicated Ed25519 key and store it through the backend. */
788
+ generate(ref) {
789
+ const dir = this.mkTempKeyDir();
790
+ try {
791
+ const keyPath = join(dir, 'id');
792
+ const genRes = this.runner.run(this.sshKeygen, ['-q', '-t', 'ed25519', '-N', '', '-C', `owenloop-${ref.kind}`, '-f', keyPath], { stdin: Buffer.alloc(0) });
793
+ if (genRes.status !== 0) {
794
+ throw new CliError(`signing-key generation failed (ssh-keygen exited with status ${genRes.status ?? 'null'})`);
795
+ }
796
+ const pubText = readFileSync(`${keyPath}.pub`, 'utf8');
797
+ const desc = publicKeyDescriptor(pubText);
798
+ if (desc.keyType !== 'ssh-ed25519') {
799
+ throw new CliError(`signing-key generation produced a non-Ed25519 key (${desc.keyType})`);
800
+ }
801
+ const privateKey = readFileSync(keyPath, 'utf8');
802
+ const rec = {
803
+ version: 1,
804
+ ref,
805
+ kind: 'generated',
806
+ publicKey: desc.openSshPublicKey,
807
+ fingerprint: desc.keyid,
808
+ createdAt: new Date().toISOString(),
809
+ privateKey,
810
+ };
811
+ this.writeRecordText(ref, JSON.stringify(rec));
812
+ return { ref, state: 'created', backend: this.backendKind, publicKey: desc };
813
+ }
814
+ finally {
815
+ rmSync(dir, { recursive: true, force: true });
816
+ }
817
+ }
818
+ /**
819
+ * Materialize the signing key for `ref` as a filesystem path and pass it to
820
+ * `callback`. Generated keys on keychain backends materialize as a `0600`
821
+ * file inside a unique `0700` temp dir, removed in `finally`; the file
822
+ * backend passes its persistent `0600` record's key file path indirectly by
823
+ * materializing the record's private material the same way (one code path —
824
+ * the record file is a JSON document, not a key file). Reused keys pass only
825
+ * their canonical path. No private text is returned to the caller.
826
+ */
827
+ async withSigningKey(ref, callback) {
828
+ assertKeyRef(ref);
829
+ this.ensureDirs();
830
+ const rec = await this.readRecord(ref);
831
+ if (rec === null) {
832
+ throw new CliError(`no ${ref.kind} signing key stored for ${ref.origin} — run owenloop setup`);
833
+ }
834
+ if (rec.kind === 'reused') {
835
+ if (rec.path === undefined || !existsSync(rec.path)) {
836
+ throw new CliError(`the reused ${ref.kind} signing key file is missing — re-run owenloop setup --reuse-ssh-key`);
837
+ }
838
+ let currentPath;
839
+ try {
840
+ currentPath = realpathSync(rec.path);
841
+ }
842
+ catch {
843
+ throw new CliError(`the reused ${ref.kind} signing key file is missing — re-run owenloop setup --reuse-ssh-key`);
844
+ }
845
+ if (currentPath !== rec.path) {
846
+ throw new CliError(`the reused ${ref.kind} signing key path changed — re-run owenloop setup --reuse-ssh-key`);
847
+ }
848
+ let current;
849
+ try {
850
+ current = publicKeyDescriptor(this.candidatePublicText(currentPath));
851
+ assertEd25519PubText(current.openSshPublicKey, 'reused signing key');
852
+ }
853
+ catch {
854
+ throw new CliError(`the reused ${ref.kind} signing key is no longer a valid Ed25519 key`);
855
+ }
856
+ if (current.keyid !== rec.fingerprint) {
857
+ throw new CliError(`the reused ${ref.kind} signing key identity changed — re-run owenloop setup --reuse-ssh-key`);
858
+ }
859
+ return callback(currentPath);
860
+ }
861
+ if (rec.privateKey === undefined) {
862
+ throw new CliError(`signing-key record for ${ref.kind}:${ref.id} is corrupt (missing key material)`);
863
+ }
864
+ const dir = this.mkTempKeyDir();
865
+ try {
866
+ const keyPath = join(dir, 'id');
867
+ writeFileAtomic(keyPath, rec.privateKey, { mode: 0o600 });
868
+ chmodSync(keyPath, 0o600);
869
+ // ssh-keygen wants a matching .pub next to the private key for -Y sign.
870
+ writeFileAtomic(`${keyPath}.pub`, `${rec.publicKey}\n`, { mode: 0o644 });
871
+ return await callback(keyPath);
872
+ }
873
+ finally {
874
+ rmSync(dir, { recursive: true, force: true });
875
+ }
876
+ }
877
+ /** Create a unique `0700` temp dir under the configured temp base. */
878
+ mkTempKeyDir() {
879
+ const dir = join(this.tempBase, `owenloop-key-${randomBytes(8).toString('hex')}`);
880
+ mkdirSync(dir, { mode: 0o700 });
881
+ chmodSync(dir, 0o700);
882
+ return dir;
883
+ }
884
+ }
885
+ /** PATH scan for an executable (pure fs, hermetic-testable via `env.PATH`). */
886
+ function commandOnPath(env, cmd) {
887
+ const path = env.PATH;
888
+ if (!path)
889
+ return false;
890
+ for (const dir of path.split(delimiter)) {
891
+ if (dir === '')
892
+ continue;
893
+ const full = join(dir, cmd);
894
+ try {
895
+ const st = statSync(full);
896
+ if (st.isFile() && (st.mode & 0o111) !== 0)
897
+ return true;
898
+ }
899
+ catch {
900
+ // not here — keep scanning
901
+ }
902
+ }
903
+ return false;
904
+ }
905
+ /** Convenience: the directory name helper is reused by tests. */
906
+ export function keysDirFor(homeDir) {
907
+ return join(homeDir, '.owenloop', 'keys');
908
+ }