owenloop 0.2.1 → 0.4.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.
package/dist/hub.js ADDED
@@ -0,0 +1,783 @@
1
+ /**
2
+ * Pure, unit-testable helpers for the hub-onboarding CLI verbs (`owenloop
3
+ * login` / `connect` / `push` / `logout`) — the client half of connecting the
4
+ * open-source engine to the hosted control plane.
5
+ *
6
+ * Same split as `src/add.ts`: the network-free, filesystem-adjacent pieces live
7
+ * here (origin normalization, PKCE, credential + project-binding (de)serialization
8
+ * with strict file-mode enforcement, server-diff computation, API-response shape
9
+ * guards); the async network + arg glue lives in `src/cli.ts` (`dispatchLogin`
10
+ * etc.) so this module stays trivially testable and `cli.ts` doesn't widen its
11
+ * export surface.
12
+ *
13
+ * The keychain backend selection and the read side of credential storage also
14
+ * live here (`defaultKeychain` / `resolveKeychain` / `credentialBackend` /
15
+ * `readStoredCredential`): the `security` shell-out is synchronous and
16
+ * injectable, so it stays consistent with this module's network-free, testable
17
+ * charter, and it lets the public barrel (`src/index.ts`) export a supported
18
+ * read-only `readStoredCredential` without pulling in `cli.ts` (which the
19
+ * core/hub boundary lint forbids). `cli.ts` keeps thin wrappers so there is one
20
+ * implementation of backend selection, not two.
21
+ *
22
+ * Backend precedence is **external → keychain → file**, resolved once in
23
+ * `credentialBackend`. The external backend is an OPTIONAL, explicitly
24
+ * configured command (`OWENLOOP_CREDENTIAL_COMMAND`) that prints a credential
25
+ * for the requested `(origin, slot)` — it gives non-macOS workers, CI, and
26
+ * users whose secrets live in a secret manager a supported way to feed owenloop
27
+ * a credential without owenloop learning about any specific manager. When it is
28
+ * configured it is AUTHORITATIVE: a failure of any kind is a loud error and
29
+ * never a fallthrough to a store (see `runCredentialCommand`). When it is not
30
+ * configured, behaviour is byte-for-byte what it was before it existed.
31
+ *
32
+ * Credentials are keyed by **slot**, not by origin alone: one stored credential
33
+ * per `(normalized origin, principal-account)` pair, the slot being `human` or
34
+ * `agent:<account>` (account defaults to `default`). See `CredentialSlotSelector`
35
+ * and `credentialSlot`. A reader must always name the slot it wants — it can
36
+ * never guess — so a host or CLI verb can never accidentally read the wrong
37
+ * principal's credential. There is deliberately NO migration from the older
38
+ * one-slot-per-origin keying: entries written under it are simply never found
39
+ * and read as absent; the upgrade step is re-running `login`.
40
+ *
41
+ * `.owenloop/hub.json` is a pure binding (which hub this project publishes to)
42
+ * — there is no client-side push ledger. `push` diffs local defs against the
43
+ * server's own `hash` (`GET /api/workflows`, see `computeServerDiff`), and
44
+ * `POST /api/create_workflow` is idempotent, so the server is always the
45
+ * source of truth for "did this change" — a client-side cache would just be a
46
+ * second copy of that truth that can go stale.
47
+ *
48
+ * Secret hygiene is a hard rule here: credentials never land in the repo or a
49
+ * plaintext `.env`. The 0600 file backend below (dir 0700) lives under the
50
+ * user's config dir, never the project; all paths derive from the
51
+ * caller-supplied `env` (HOME / XDG_CONFIG_HOME), never `process.env` directly,
52
+ * so tests fixture `$HOME` and never touch ambient machine state. Both this
53
+ * file and `.owenloop/hub.json` are written via `writeFileAtomic` — temp file
54
+ * in the same dir + rename, refusing a symlinked destination (SEC-3). The
55
+ * parent-directory half of that guard is `mkdirRefusingSymlink` (in `util.ts`,
56
+ * so the core store factory can share it without core depending on this hub
57
+ * module): before creating the project `.owenloop` dir we refuse a symlinked
58
+ * `.owenloop` component, so a hostile checkout shipping `.owenloop -> /elsewhere`
59
+ * cannot redirect the write outside the project even though the final file
60
+ * itself is not (yet) a symlink.
61
+ *
62
+ * The server-parity def content hash (`hashDefForHub`) also lives here: it is a
63
+ * hub-facing concern (reproducing owenloop-service's canonicalization for the
64
+ * `push` diff), so keeping it in this module — not in engine core — is what
65
+ * lets `defs.ts` stay host/hub-agnostic.
66
+ */
67
+ import { execFileSync } from 'node:child_process';
68
+ import { createHash, randomBytes } from 'node:crypto';
69
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
70
+ import { basename, dirname, join } from 'node:path';
71
+ import { parse as parseYaml } from 'yaml';
72
+ import { hashDef, parseDef } from "./defs.js";
73
+ import { mkdirRefusingSymlink } from "./util.js";
74
+ // ---- server-parity def content hash ------------------------------------------
75
+ /**
76
+ * Reproduce the hub service's def content hash for the CLI `push` diff
77
+ * (`owenloop-service` `apps/hub-edge/README.md`, "Hub API parity for CLI"):
78
+ * `sha256(JSON.stringify(parseDef(YAML.parse(yaml))))` sliced to 16 hex
79
+ * chars, computed with **no `baseDir`** — the compiled def (defaults filled),
80
+ * exactly as the server computes it when it has no stored `defs` row. Taking
81
+ * no `baseDir` is deliberate, not an oversight: it means `parseDef` throws a
82
+ * `DefError` on any def using `bodyFile:` ("bodyFile requires a workflow
83
+ * loaded from disk"), which is exactly the server's own limitation — such a
84
+ * def can't be pushed as raw YAML anyway, so the caller should catch that and
85
+ * refuse the push with a clear reason, the same way it already refuses an
86
+ * `include:` def.
87
+ *
88
+ * Stable only per pinned engine version: the service pins its `parseDef`/
89
+ * `hashDef` lineage to a specific commit (`VENDORED_SHA`). As of writing that
90
+ * commit is an ancestor of this repo's `HEAD` with no changes to
91
+ * `parseDef`/`buildDef`/`hashDef` in between, so a locally computed hash
92
+ * currently matches the server's — but a future engine default change could
93
+ * make them drift. A drifted hash reads as `changed`, not an error: pushing
94
+ * converges state, because the server's own idempotent `create_workflow`
95
+ * still recognizes byte-identical content and replies `unchanged: true`.
96
+ */
97
+ export function hashDefForHub(yaml) {
98
+ return hashDef(parseDef(parseYaml(yaml)));
99
+ }
100
+ // ---- origin normalization ----------------------------------------------------
101
+ /**
102
+ * Loopback hosts allowed to use plaintext `http` for local development. Exact
103
+ * hostname match: WHATWG `URL` already lowercases hostnames (`HTTP://LOCALHOST`
104
+ * → `localhost`), canonicalizes IPv4 shorthand (`http://127.1` → `127.0.0.1`),
105
+ * and keeps the brackets on IPv6 (`http://[::1]` → `[::1]`), so a bare set
106
+ * membership on `url.hostname` is correct and needs no range parsing.
107
+ *
108
+ * Deliberately NOT the whole `127.0.0.0/8` range nor `*.localhost` subdomains —
109
+ * the exact enumeration the transport policy names (SEC-2). `http://127.0.0.2`
110
+ * and `http://192.168.x.x` are remote for this purpose and rejected. Conservative
111
+ * and cheap to widen later (a two-way door).
112
+ */
113
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
114
+ /**
115
+ * Normalize a hub URL to a bare origin (`scheme://host[:port]`), stripping any
116
+ * path, query, trailing slash, and fragment. Requires an http(s) scheme. This
117
+ * is the credential-store key and the project binding value, so it must be
118
+ * canonical: `https://api.owenloop.com/` and `https://api.owenloop.com/foo`
119
+ * both key to `https://api.owenloop.com`.
120
+ *
121
+ * Transport policy (SEC-2): `https` is required for every hub origin EXCEPT the
122
+ * loopback hosts (`127.0.0.1`, `::1`, `localhost`), which may use `http` for
123
+ * local development. Remote `http` is rejected here, at normalization time, so a
124
+ * plaintext origin that would leak bearer/refresh tokens, auth codes, and
125
+ * workflow YAML to an on-path attacker can never be persisted into a credential
126
+ * key or a project binding.
127
+ */
128
+ export function normalizeOrigin(input) {
129
+ const trimmed = input.trim();
130
+ if (trimmed === '')
131
+ throw new Error('hub url is empty');
132
+ let url;
133
+ try {
134
+ url = new URL(trimmed);
135
+ }
136
+ catch {
137
+ throw new Error(`invalid hub url '${input}' — expected an http(s) URL`);
138
+ }
139
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
140
+ throw new Error(`invalid hub url '${input}' — must be http or https, got '${url.protocol}'`);
141
+ }
142
+ if (url.protocol === 'http:' && !LOOPBACK_HOSTS.has(url.hostname)) {
143
+ throw new Error(`invalid hub url '${input}' — http is only allowed for loopback hosts (127.0.0.1, ::1, localhost); use https`);
144
+ }
145
+ return url.origin;
146
+ }
147
+ /**
148
+ * Join an origin and an endpoint that may be absolute or a root-relative path,
149
+ * enforcing the same-origin policy for OAuth discovery metadata (SEC-4).
150
+ *
151
+ * This is the trust boundary for every endpoint consumed from OAuth metadata —
152
+ * authorization, token, and registration endpoints all flow through here, as do
153
+ * the CLI's own literal root-relative API paths. A metadata-derived absolute
154
+ * endpoint is allowed, but must resolve to the SAME origin as the hub; a
155
+ * cross-origin (or protocol-relative `//host`) endpoint is rejected so a
156
+ * discovered `token_endpoint` on a foreign origin can never receive a refresh
157
+ * token. Path and query are preserved — only `.origin` is compared. The
158
+ * https-except-loopback rule holds for free: `origin` here is already a
159
+ * `normalizeOrigin` output at every call site, so same-origin implies the
160
+ * transport policy.
161
+ */
162
+ export function resolveEndpoint(origin, endpoint) {
163
+ const resolved = new URL(endpoint, `${origin}/`);
164
+ if (resolved.origin !== origin) {
165
+ throw new Error(`refusing endpoint '${endpoint}' — it resolves to origin ${resolved.origin}, not the hub origin ${origin}`);
166
+ }
167
+ return resolved.toString();
168
+ }
169
+ // ---- PKCE (RFC 7636) + state -------------------------------------------------
170
+ /** URL-safe base64 with no padding (RFC 7636 §A). */
171
+ export function base64url(buf) {
172
+ return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
173
+ }
174
+ /**
175
+ * Generate a PKCE verifier/challenge pair for the S256 method. The verifier is
176
+ * 32 random bytes base64url-encoded (43 chars — within the RFC's 43..128 range
177
+ * and drawn from the unreserved charset); the challenge is
178
+ * base64url(sha256(verifier)).
179
+ */
180
+ export function pkcePair() {
181
+ const verifier = base64url(randomBytes(32));
182
+ const challenge = base64url(createHash('sha256').update(verifier).digest());
183
+ return { verifier, challenge };
184
+ }
185
+ /** A random anti-CSRF `state` token for the authorization request. */
186
+ export function randomState() {
187
+ return base64url(randomBytes(16));
188
+ }
189
+ /**
190
+ * Legal agent account names. Deliberately conservative — alphanumeric start,
191
+ * then alphanumerics plus `.`/`_`/`-`, 1..64 chars — so an empty, over-long, or
192
+ * exotic name can never reach the keychain or the file key. Widening this later
193
+ * is a two-way door; narrowing it would not be.
194
+ */
195
+ const ACCOUNT_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
196
+ /** The default agent account when `--as agent` names none. */
197
+ const DEFAULT_ACCOUNT = 'default';
198
+ /**
199
+ * Resolve a selector to its slot string: `'human'` or `` `agent:${account}` ``.
200
+ *
201
+ * This is the ONE place account defaulting and validation happen — every read,
202
+ * write, and delete path funnels through it, so no call site re-implements the
203
+ * `agent:` concatenation. Throws on an invalid account name, and on `account`
204
+ * supplied alongside `principal: 'human'`: TypeScript's excess-property check
205
+ * does not reliably reject that against a union, so it is a runtime error too
206
+ * rather than a silently ignored argument.
207
+ *
208
+ * `agent:human` cannot collide with `human` by construction — the `agent:`
209
+ * prefix differs — so no extra guard is needed.
210
+ */
211
+ export function credentialSlot(sel) {
212
+ if (sel.principal === 'human') {
213
+ if (sel.account !== undefined) {
214
+ throw new Error("credential slot: `account` is only meaningful with principal 'agent', not 'human'");
215
+ }
216
+ return 'human';
217
+ }
218
+ if (sel.principal !== 'agent') {
219
+ throw new Error(`credential slot: unknown principal '${String(sel.principal)}'`);
220
+ }
221
+ const account = sel.account ?? DEFAULT_ACCOUNT;
222
+ if (typeof account !== 'string' || !ACCOUNT_RE.test(account)) {
223
+ throw new Error(`invalid agent account '${String(account)}' — expected 1-64 chars matching [A-Za-z0-9][A-Za-z0-9._-]*`);
224
+ }
225
+ return `agent:${account}`;
226
+ }
227
+ /**
228
+ * The keychain SERVICE for a hub origin; the slot is the keychain ACCOUNT.
229
+ * `origin` must already be `normalizeOrigin`d — every call site normalizes
230
+ * first, so SEC-2 (remote plaintext rejected) happens before any keychain or
231
+ * filesystem access.
232
+ */
233
+ export function keychainServiceFor(normalizedOrigin) {
234
+ return `owenloop:${normalizedOrigin}`;
235
+ }
236
+ /**
237
+ * Shape-guard a stored credential value, returning `null` when it is not a
238
+ * well-formed `Credential`. Used on BOTH backends so "a corrupt entry reads as
239
+ * absent" is symmetric: previously the keychain path did an unchecked
240
+ * `JSON.parse(...) as Credential` and the file path validated nothing at all,
241
+ * so a truncated or hand-edited entry could surface as a bogus credential
242
+ * instead of a clean miss.
243
+ */
244
+ export function parseCredential(raw) {
245
+ if (typeof raw !== 'object' || raw === null)
246
+ return null;
247
+ const c = raw;
248
+ if (typeof c.accessToken !== 'string' || c.accessToken === '')
249
+ return null;
250
+ if (c.kind === 'agent' || c.kind === 'oauth-pasted') {
251
+ return { kind: c.kind, accessToken: c.accessToken };
252
+ }
253
+ if (c.kind === 'oauth') {
254
+ if (typeof c.refreshToken !== 'string' || c.refreshToken === '')
255
+ return null;
256
+ if (typeof c.expiresAt !== 'number' || !Number.isFinite(c.expiresAt))
257
+ return null;
258
+ if (typeof c.clientId !== 'string' || c.clientId === '')
259
+ return null;
260
+ return {
261
+ kind: 'oauth',
262
+ accessToken: c.accessToken,
263
+ refreshToken: c.refreshToken,
264
+ expiresAt: c.expiresAt,
265
+ clientId: c.clientId,
266
+ };
267
+ }
268
+ return null;
269
+ }
270
+ /** The user-level config dir (never the project dir). Derives from the caller's env. */
271
+ export function configDir(env) {
272
+ const xdg = env.XDG_CONFIG_HOME;
273
+ if (xdg && xdg.trim() !== '')
274
+ return join(xdg, 'owenloop');
275
+ const home = env.HOME;
276
+ if (home && home.trim() !== '')
277
+ return join(home, '.config', 'owenloop');
278
+ throw new Error('cannot locate a config directory: set HOME or XDG_CONFIG_HOME');
279
+ }
280
+ export function credentialFilePath(env) {
281
+ return join(configDir(env), 'credentials.json');
282
+ }
283
+ /**
284
+ * Read the credential file; a missing file is an empty store, not an error.
285
+ *
286
+ * A file whose `version` is not `2` also reads as an EMPTY store — no throw, no
287
+ * migration, no hybrid write. That is how entries under the older
288
+ * one-slot-per-origin keying become invisible (there are no external users, so
289
+ * the documented upgrade step is re-running `login`). Stated deliberately: the
290
+ * next write then replaces such a file wholesale, which is acceptable because
291
+ * its entries are unreachable by design.
292
+ *
293
+ * Genuinely broken JSON, or a `hubs` that is not an object, still throws —
294
+ * "corrupt reads as absent" is about a corrupt ENTRY (see `parseCredential`),
295
+ * not a destroyed file.
296
+ */
297
+ export function readCredentialFile(path) {
298
+ if (!existsSync(path))
299
+ return { version: 2, hubs: {} };
300
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
301
+ if (!parsed || typeof parsed !== 'object' || typeof parsed.hubs !== 'object' || parsed.hubs === null) {
302
+ throw new Error(`malformed credential file at ${path}`);
303
+ }
304
+ if (parsed.version !== 2)
305
+ return { version: 2, hubs: {} };
306
+ return { version: 2, hubs: parsed.hubs };
307
+ }
308
+ /**
309
+ * Write `data` to `path` atomically, refusing a symlinked (or directory)
310
+ * destination (SEC-3).
311
+ *
312
+ * 1. `lstat` the destination: if it already exists AND is a symlink, throw a
313
+ * clear error naming the path rather than clobbering the arbitrary,
314
+ * possibly-privileged file the link points at. A pre-existing directory is
315
+ * likewise refused with a named error (instead of a raw ENOTDIR from
316
+ * rename).
317
+ * 2. Write to a temp file in the SAME directory (same-dir is required — a
318
+ * cross-filesystem rename is not atomic), then `chmod` the temp to `mode`
319
+ * BEFORE the rename so the final file never momentarily exists with a lax,
320
+ * umask-widened mode (preserving the old "re-chmod on every write"
321
+ * guarantee, now applied to the temp).
322
+ * 3. `rename(tmp, path)` — an atomic replace. On any failure after the temp
323
+ * exists, best-effort unlink the temp and rethrow.
324
+ *
325
+ * The `lstat` check is a courtesy clear-error, not the security boundary:
326
+ * `rename` replaces the destination inode rather than following it, so even a
327
+ * symlink raced into place between the `lstat` and the `rename` is replaced,
328
+ * never followed — the write can never escape to the link target.
329
+ */
330
+ export function writeFileAtomic(path, data, opts) {
331
+ const existing = lstatSync(path, { throwIfNoEntry: false });
332
+ if (existing?.isSymbolicLink()) {
333
+ throw new Error(`refusing to write ${path}: it is a symbolic link`);
334
+ }
335
+ if (existing?.isDirectory()) {
336
+ throw new Error(`refusing to write ${path}: it is a directory`);
337
+ }
338
+ const tmp = join(dirname(path), `.${basename(path)}.${randomBytes(6).toString('hex')}.tmp`);
339
+ try {
340
+ writeFileSync(tmp, data, opts?.mode !== undefined ? { mode: opts.mode } : undefined);
341
+ if (opts?.mode !== undefined)
342
+ chmodSync(tmp, opts.mode);
343
+ renameSync(tmp, path);
344
+ }
345
+ catch (e) {
346
+ rmSync(tmp, { force: true });
347
+ throw e;
348
+ }
349
+ }
350
+ /**
351
+ * Write the credential file with strict permissions: dir 0700, file 0600.
352
+ * The file itself is written atomically via `writeFileAtomic` (temp + rename),
353
+ * which also chmods the temp to 0600 before the rename — so the secret is
354
+ * never visible under a laxer mode, even briefly, and a symlinked destination
355
+ * is refused (SEC-3).
356
+ */
357
+ export function writeCredentialFile(path, file) {
358
+ const dir = dirname(path);
359
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
360
+ chmodSync(dir, 0o700);
361
+ writeFileAtomic(path, `${JSON.stringify(file, null, 2)}\n`, { mode: 0o600 });
362
+ }
363
+ /**
364
+ * The default macOS keychain backend (generic passwords under service
365
+ * `owenloop:<origin>`, account = the credential slot). The secret is fed through
366
+ * the `security -i` command stream on stdin, never as a `-w` argv value, so it
367
+ * never appears in `ps`/shell history. Returns `undefined` off macOS or when
368
+ * `OWENLOOP_NO_KEYCHAIN=1`, so callers fall back to the 0600 credential file.
369
+ */
370
+ export function defaultKeychain(env) {
371
+ if (env.OWENLOOP_NO_KEYCHAIN === '1')
372
+ return undefined;
373
+ if (process.platform !== 'darwin')
374
+ return undefined;
375
+ return {
376
+ get(service, account) {
377
+ try {
378
+ const out = execFileSync('security', ['find-generic-password', '-s', service, '-a', account, '-w'], {
379
+ encoding: 'utf8',
380
+ stdio: ['ignore', 'pipe', 'ignore'],
381
+ });
382
+ return out.replace(/\n$/, '');
383
+ }
384
+ catch {
385
+ return null; // not found (errSecItemNotFound) — treated as "no credential"
386
+ }
387
+ },
388
+ set(service, account, value) {
389
+ // `security -i` reads newline-terminated commands from stdin; the secret
390
+ // rides in that stdin stream (single-quoted), never on this process's argv.
391
+ // The service string now carries `:` and `//` — inert for `security`, but
392
+ // the single-quote escaping stays as the general guard it always was.
393
+ const sq = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
394
+ const cmd = `add-generic-password -U -s ${sq(service)} -a ${sq(account)} -w ${sq(value)}\n`;
395
+ execFileSync('security', ['-i'], { input: cmd, stdio: ['pipe', 'ignore', 'ignore'] });
396
+ },
397
+ delete(service, account) {
398
+ try {
399
+ execFileSync('security', ['delete-generic-password', '-s', service, '-a', account], {
400
+ stdio: 'ignore',
401
+ });
402
+ }
403
+ catch {
404
+ // Not found — already absent; a no-op delete is success.
405
+ }
406
+ },
407
+ };
408
+ }
409
+ /**
410
+ * The configured external credential command, or `undefined` when it is unset
411
+ * or blank.
412
+ *
413
+ * Configuration is a single environment variable, `OWENLOOP_CREDENTIAL_COMMAND`,
414
+ * read off the caller-supplied `env` record like every other knob in this module
415
+ * (`OWENLOOP_NO_KEYCHAIN`, `OWENLOOP_HUB`, the `*_TIMEOUT_MS` overrides) — never
416
+ * `process.env` directly, so hosts and tests stay hermetic. Explicit config
417
+ * only: there is deliberately no discovery, no scanning for helper binaries, and
418
+ * no implicit default.
419
+ *
420
+ * An all-whitespace value is treated as NOT configured, and that decision is
421
+ * made HERE rather than at each call site, so "is the external backend active?"
422
+ * has exactly one answer.
423
+ */
424
+ export function externalCredentialCommand(env) {
425
+ const raw = env.OWENLOOP_CREDENTIAL_COMMAND;
426
+ if (typeof raw !== 'string' || raw.trim() === '')
427
+ return undefined;
428
+ return raw;
429
+ }
430
+ /** Request deadline for the external credential command; see `runCredentialCommand`. */
431
+ const CREDENTIAL_COMMAND_TIMEOUT_MS = 10_000;
432
+ /** Cap on the command's stdout, so a runaway helper cannot exhaust memory. */
433
+ const CREDENTIAL_COMMAND_MAX_BUFFER = 1024 * 1024;
434
+ function credentialCommandTimeoutMs(env) {
435
+ const override = Number(env.OWENLOOP_CREDENTIAL_COMMAND_TIMEOUT_MS);
436
+ return Number.isFinite(override) && override > 0 ? override : CREDENTIAL_COMMAND_TIMEOUT_MS;
437
+ }
438
+ /**
439
+ * Run the configured external credential command and return the credential it
440
+ * printed. THROWS on every failure — it never returns `null` and never falls
441
+ * through to a store.
442
+ *
443
+ * That asymmetry with the stores is deliberate. In a store a corrupt entry reads
444
+ * as absent (REL-6, see `parseCredential`); from the external command a corrupt
445
+ * result is a hard ERROR, because a configured command is AUTHORITATIVE and a
446
+ * silent miss there is exactly the failure this feature exists to prevent — a
447
+ * half-working helper quietly handing back a stale local key.
448
+ *
449
+ * Invocation contract:
450
+ * - The configured value is a shell command line, run as `/bin/sh -c <command>`,
451
+ * so a user can write `my-helper --hub prod` or a pipeline.
452
+ * - Context reaches the child through the ENVIRONMENT, never argv, so nothing
453
+ * has to be shell-quoted into the command string and the secret never rides on
454
+ * a command line: `OWENLOOP_CREDENTIAL_ORIGIN` (the NORMALIZED origin) and
455
+ * `OWENLOOP_CREDENTIAL_SLOT` (exactly what `credentialSlot()` returned).
456
+ * - `OWENLOOP_CREDENTIAL_COMMAND` is DELETED from the child's environment. That
457
+ * deletion is deliberate: a helper that shells back into `owenloop` would
458
+ * otherwise recurse forever.
459
+ * - stdout must be a JSON object that satisfies `parseCredential` — the same one
460
+ * guard both stores use, so there is exactly one definition of "a well-formed
461
+ * credential". A bare token is deliberately NOT accepted; inferring `kind`
462
+ * would duplicate `login`'s token-kind logic.
463
+ * - stdio is `['ignore', 'pipe', 'inherit']`: the helper's own diagnostics go
464
+ * straight to the user's stderr and owenloop never captures, stores, or echoes
465
+ * them (captured stderr could carry the secret into an error message or a
466
+ * log). stdout is captured and never logged.
467
+ */
468
+ function runCredentialCommand(command, env, origin, slot) {
469
+ // The command string itself came from the user's own config, not a secret
470
+ // store, so naming it is useful. Captured stdout is or contains the SECRET and
471
+ // must never reach an error message.
472
+ const fail = (detail) => {
473
+ throw new Error(`external credential command failed for ${origin} slot \`${slot}\`: ${detail}`);
474
+ };
475
+ const childEnv = {};
476
+ for (const [k, v] of Object.entries(env)) {
477
+ if (v !== undefined)
478
+ childEnv[k] = v;
479
+ }
480
+ delete childEnv.OWENLOOP_CREDENTIAL_COMMAND;
481
+ childEnv.OWENLOOP_CREDENTIAL_ORIGIN = origin;
482
+ childEnv.OWENLOOP_CREDENTIAL_SLOT = slot;
483
+ const timeout = credentialCommandTimeoutMs(env);
484
+ let out;
485
+ try {
486
+ out = execFileSync('/bin/sh', ['-c', command], {
487
+ encoding: 'utf8',
488
+ env: childEnv,
489
+ stdio: ['ignore', 'pipe', 'inherit'],
490
+ timeout,
491
+ maxBuffer: CREDENTIAL_COMMAND_MAX_BUFFER,
492
+ });
493
+ }
494
+ catch (e) {
495
+ const err = e;
496
+ if (err.code === 'ETIMEDOUT' || (err.status === null && typeof err.signal === 'string')) {
497
+ return fail(`command timed out after ${timeout}ms`);
498
+ }
499
+ if (typeof err.status === 'number')
500
+ return fail(`command exited with status ${err.status}`);
501
+ // Only the errno CODE is surfaced — it is a fixed token (ENOENT, ENOBUFS,
502
+ // …) that can never carry the child's output.
503
+ return fail(`command could not be run (${typeof err.code === 'string' ? err.code : 'unknown error'})`);
504
+ }
505
+ const trimmed = out.trim();
506
+ if (trimmed === '')
507
+ return fail('command produced no output');
508
+ let decoded;
509
+ try {
510
+ decoded = JSON.parse(trimmed);
511
+ }
512
+ catch {
513
+ return fail('command produced output that is not JSON');
514
+ }
515
+ const cred = parseCredential(decoded);
516
+ if (cred === null)
517
+ return fail('command produced a value that is not a well-formed credential');
518
+ return cred;
519
+ }
520
+ /**
521
+ * Resolve the keychain backend for this env, honoring the hard override:
522
+ * `OWENLOOP_NO_KEYCHAIN=1` forces the file backend (`undefined`) EVEN when a
523
+ * keychain is injected; otherwise the injected backend wins, else the platform
524
+ * default.
525
+ */
526
+ export function resolveKeychain(env, injected) {
527
+ if (env.OWENLOOP_NO_KEYCHAIN === '1')
528
+ return undefined;
529
+ return injected ?? defaultKeychain(env);
530
+ }
531
+ /**
532
+ * `OWENLOOP_NO_KEYCHAIN=1` deliberately does NOT affect the external branch: it
533
+ * selects between the two LOCAL stores, and the external command sits in front
534
+ * of both.
535
+ */
536
+ export function credentialBackend(env, injected) {
537
+ const command = externalCredentialCommand(env);
538
+ if (command !== undefined)
539
+ return { kind: 'external', command };
540
+ const kc = resolveKeychain(env, injected);
541
+ return kc ? { kind: 'keychain', kc } : { kind: 'file' };
542
+ }
543
+ /**
544
+ * Read the stored hub credential for `origin` **in the named slot** from the
545
+ * chosen backend ONLY — the supported, read-only programmatic surface
546
+ * (owenwork's CredentialReader seam wires to this once released). Secret hygiene
547
+ * is unchanged: this function never logs or echoes the returned credential, and
548
+ * there is deliberately no write/delete companion on the public surface —
549
+ * `login` / `logout` remain the only way to store or remove a credential.
550
+ *
551
+ * `opts` and its `principal` are both required, so a caller can never
552
+ * accidentally read the wrong principal's credential:
553
+ *
554
+ * ```ts
555
+ * readStoredCredential(origin, { principal: 'human' });
556
+ * readStoredCredential(origin, { principal: 'agent' }); // agent:default
557
+ * readStoredCredential(origin, { principal: 'agent', account: 'ci' }); // agent:ci
558
+ * ```
559
+ *
560
+ * Passing `account` with `principal: 'human'` throws (see `credentialSlot`),
561
+ * because TypeScript's excess-property check does not reliably reject it
562
+ * against a union.
563
+ *
564
+ * `origin` is normalized (idempotent on already-normalized input, so the CLI's
565
+ * pre-normalized callers are unaffected) BEFORE any keychain or filesystem
566
+ * access, so the storage key matches what `login` persisted and an invalid or
567
+ * plaintext-remote origin throws at normalization (SEC-2), exactly as the CLI
568
+ * would.
569
+ *
570
+ * Backend is selected once (`credentialBackend`), with precedence external →
571
+ * keychain → file. A keychain-backed read NEVER falls through to the file (that
572
+ * fallback was the REL-6 shadowing bug), and a corrupt entry reads as absent
573
+ * (`null`) on either store — never as a reason to consult the other. The file
574
+ * backend derives its path from the supplied `env` (HOME / XDG_CONFIG_HOME),
575
+ * never `process.env` directly, so a caller passing `opts.env` stays hermetic;
576
+ * only the top-level default falls back to `process.env`.
577
+ *
578
+ * **When `OWENLOOP_CREDENTIAL_COMMAND` is configured this function can THROW
579
+ * instead of returning `null`**, and it does not consult a store at all. The
580
+ * command is authoritative, so a nonzero exit, a timeout, empty output, or
581
+ * output that is not a well-formed credential is a loud error naming the origin
582
+ * and the slot — never a silent fallthrough to a stale local entry. See
583
+ * `runCredentialCommand`. When it is NOT configured, behaviour is exactly what
584
+ * it has always been.
585
+ */
586
+ export function readStoredCredential(origin, opts) {
587
+ const env = opts.env ?? process.env;
588
+ // Normalization runs FIRST, so SEC-2 (plaintext remote origins rejected) and
589
+ // slot validation both apply to the external path too — a bad origin or
590
+ // account never reaches the child process.
591
+ const key = normalizeOrigin(origin);
592
+ const slot = credentialSlot(opts);
593
+ const backend = credentialBackend(env, opts.keychain);
594
+ if (backend.kind === 'external') {
595
+ return runCredentialCommand(backend.command, env, key, slot);
596
+ }
597
+ if (backend.kind === 'keychain') {
598
+ const raw = backend.kc.get(keychainServiceFor(key), slot);
599
+ if (!raw)
600
+ return null;
601
+ let decoded;
602
+ try {
603
+ decoded = JSON.parse(raw);
604
+ }
605
+ catch {
606
+ return null; // corrupt entry — treat as absent; do NOT consult the file
607
+ }
608
+ return parseCredential(decoded);
609
+ }
610
+ const file = readCredentialFile(credentialFilePath(env));
611
+ return parseCredential(file.hubs[key]?.[slot]);
612
+ }
613
+ export function hubBindingPath(cwd) {
614
+ return join(cwd, '.owenloop', 'hub.json');
615
+ }
616
+ /**
617
+ * Read `.owenloop/hub.json`; a missing file is `null` (project not bound
618
+ * yet). A file written by a pre-server-diff CLI may still carry a `pushed`
619
+ * key (the old push ledger) — it parses fine and the key is silently
620
+ * ignored; the next `connect` rewrite drops it.
621
+ */
622
+ export function readHubBinding(path) {
623
+ if (!existsSync(path))
624
+ return null;
625
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
626
+ if (!parsed || typeof parsed.hub !== 'string') {
627
+ throw new Error(`malformed hub binding at ${path}`);
628
+ }
629
+ return { version: 1, hub: parsed.hub };
630
+ }
631
+ export function writeHubBinding(path, binding) {
632
+ // Refuse a symlinked `.owenloop` parent (SEC-3, parent-directory half): a
633
+ // hostile checkout can ship `.owenloop -> /elsewhere` to redirect this write
634
+ // outside the project. Unconditional — this function only ever writes the
635
+ // project binding, so there is no operator-supplied override to honor.
636
+ mkdirRefusingSymlink(dirname(path));
637
+ // Atomic + symlink-refusing on the FILE (SEC-3). Default mode — hub.json
638
+ // carries no secrets and is deliberately committable.
639
+ writeFileAtomic(path, `${JSON.stringify(binding, null, 2)}\n`);
640
+ }
641
+ /**
642
+ * Partition selected defs into those that need pushing vs. those already
643
+ * up-to-date, purely from the server's own `hash` for each name (from
644
+ * `GET /api/workflows`, via `parseWorkflowList`): a name absent from the
645
+ * server is `new`; present with a different (or missing) hash is `changed`;
646
+ * present with an equal hash is `unchanged` (skipped — no request sent).
647
+ *
648
+ * `force` pushes every candidate regardless of hash — labeled `new` when the
649
+ * server has no entry for it, `changed` otherwise (even when the hash is
650
+ * equal: force means "send it", and the label should still read true).
651
+ *
652
+ * Server names with no local counterpart are ignored (this is a push, not a
653
+ * sync — the CLI never deletes or reports on hub-only defs).
654
+ */
655
+ export function computeServerDiff(candidates, server, force) {
656
+ const toPush = [];
657
+ const unchanged = [];
658
+ for (const c of candidates) {
659
+ const remote = server.get(c.name);
660
+ const status = remote === undefined ? 'new' : 'changed';
661
+ if (force) {
662
+ toPush.push({ ...c, status });
663
+ }
664
+ else if (remote === undefined) {
665
+ toPush.push({ ...c, status: 'new' });
666
+ }
667
+ else if (remote.hash !== c.hash) {
668
+ toPush.push({ ...c, status: 'changed' });
669
+ }
670
+ else {
671
+ unchanged.push(c);
672
+ }
673
+ }
674
+ return { toPush, unchanged };
675
+ }
676
+ /**
677
+ * `POST /api/create_workflow` returns HTTP 200 with `{ok:false,error}` on a
678
+ * def-parse failure (engine-version skew is the realistic cause) — so a 200 is
679
+ * NOT sufficient; the body's `ok` must be inspected. Returns the parsed error
680
+ * text (verbatim) when the reply is a failure, or `null` when it is a success.
681
+ */
682
+ export function createWorkflowError(body) {
683
+ if (typeof body !== 'object' || body === null)
684
+ return 'unexpected response shape (not an object)';
685
+ const b = body;
686
+ if (b.ok === true)
687
+ return null;
688
+ const err = typeof b.error === 'string' ? b.error : 'unknown error';
689
+ return err;
690
+ }
691
+ /**
692
+ * Narrow a create_workflow success body to its typed shape (after
693
+ * `createWorkflowError` returns null), validating STRICTLY (REL-9): a 2xx with
694
+ * `ok:true` is not enough — the identity fields must be present, well-typed, and
695
+ * consistent with the def that was pushed, or the "success" is a malformed
696
+ * response and must be treated as a failure, not silently coerced to defaults.
697
+ *
698
+ * - `name` must be a string equal to `expectedName` (the pushed def's name) —
699
+ * a mismatch means the server acknowledged the wrong workflow.
700
+ * - `version` must be a positive integer (the server mints versions from 1).
701
+ * - `hash` must be a non-empty string. Presence and type only: it is NOT
702
+ * required to equal the locally computed `hashDefForHub`, because engine
703
+ * drift between CLI and hub legitimately produces differing hashes (see
704
+ * `hashDefForHub`'s doc comment).
705
+ * - `unchanged: true` passes through as an idempotent no-op, validated by the
706
+ * same field rules.
707
+ *
708
+ * Throws a descriptive `Error` (mirroring `asWhoami`'s throw-on-malformed style)
709
+ * on any violation; the caller records it as a per-def failure.
710
+ */
711
+ export function asCreateWorkflowOk(body, expectedName) {
712
+ if (typeof body !== 'object' || body === null) {
713
+ throw new Error('create_workflow: malformed success response — not an object');
714
+ }
715
+ const b = body;
716
+ if (typeof b.name !== 'string') {
717
+ throw new Error('create_workflow: malformed success response — missing string name');
718
+ }
719
+ if (b.name !== expectedName) {
720
+ throw new Error(`create_workflow: malformed success response — name '${b.name}' does not match pushed def '${expectedName}'`);
721
+ }
722
+ if (typeof b.version !== 'number' || !Number.isInteger(b.version) || b.version < 1) {
723
+ throw new Error('create_workflow: malformed success response — version must be a positive integer');
724
+ }
725
+ if (typeof b.hash !== 'string' || b.hash === '') {
726
+ throw new Error('create_workflow: malformed success response — missing non-empty hash');
727
+ }
728
+ const out = { ok: true, name: b.name, version: b.version, hash: b.hash };
729
+ if (b.unchanged === true)
730
+ out.unchanged = true;
731
+ return out;
732
+ }
733
+ /** Narrow a `GET /api/whoami` 200 body to its typed shape. Throws on a malformed body. */
734
+ export function asWhoami(body) {
735
+ if (typeof body !== 'object' || body === null)
736
+ throw new Error('whoami: unexpected response shape (not an object)');
737
+ const b = body;
738
+ if (typeof b.orgId !== 'string')
739
+ throw new Error('whoami: response missing string orgId');
740
+ const rawActor = (typeof b.actor === 'object' && b.actor !== null ? b.actor : {});
741
+ const identity = {
742
+ orgId: b.orgId,
743
+ orgName: typeof b.orgName === 'string' ? b.orgName : '',
744
+ actor: {
745
+ id: typeof rawActor.id === 'string' ? rawActor.id : '',
746
+ kind: typeof rawActor.kind === 'string' ? rawActor.kind : '',
747
+ role: typeof rawActor.role === 'string' ? rawActor.role : '',
748
+ },
749
+ authMethod: typeof b.authMethod === 'string' ? b.authMethod : '',
750
+ };
751
+ if (typeof b.email === 'string')
752
+ identity.email = b.email;
753
+ return identity;
754
+ }
755
+ /**
756
+ * Parse `GET /api/workflows`'s body into a `name -> WorkflowSummary` map for
757
+ * `computeServerDiff`. Throws a descriptive error (the caller wraps it in a
758
+ * `CliError`) on a missing/malformed `workflows` array.
759
+ */
760
+ export function parseWorkflowList(body) {
761
+ if (typeof body !== 'object' || body === null || !Array.isArray(body.workflows)) {
762
+ throw new Error('malformed response from the hub: expected a `workflows` array');
763
+ }
764
+ const list = body.workflows;
765
+ const out = new Map();
766
+ list.forEach((entry, i) => {
767
+ if (typeof entry !== 'object' || entry === null) {
768
+ throw new Error(`malformed response from the hub: workflows[${i}] is not an object`);
769
+ }
770
+ const e = entry;
771
+ if (typeof e.name !== 'string') {
772
+ throw new Error(`malformed response from the hub: workflows[${i}] missing string name`);
773
+ }
774
+ const summary = {
775
+ name: e.name,
776
+ hash: typeof e.hash === 'string' ? e.hash : '',
777
+ };
778
+ if (typeof e.version === 'number')
779
+ summary.version = e.version;
780
+ out.set(e.name, summary);
781
+ });
782
+ return out;
783
+ }