owenloop 0.3.1 → 0.4.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.
- package/CHANGELOG.md +32 -0
- package/README.md +53 -1
- package/dist/add.d.ts +12 -40
- package/dist/add.js +11 -176
- package/dist/cli.d.ts +52 -7
- package/dist/cli.js +1072 -382
- package/dist/credentials.d.ts +274 -0
- package/dist/credentials.js +695 -0
- package/dist/defs.js +23 -0
- package/dist/engine.js +15 -6
- package/dist/hub.d.ts +363 -6
- package/dist/hub.js +551 -4
- package/dist/index.d.ts +4 -1
- package/dist/index.js +2 -1
- package/dist/lock.d.ts +80 -0
- package/dist/lock.js +217 -0
- package/dist/mcp/serve.d.ts +84 -0
- package/dist/mcp/serve.js +565 -0
- package/dist/mcp/server.d.ts +135 -0
- package/dist/mcp/server.js +330 -0
- package/dist/model.d.ts +59 -4
- package/dist/model.js +148 -21
- package/dist/owenwork.d.ts +57 -0
- package/dist/owenwork.js +84 -0
- package/dist/types.d.ts +48 -6
- package/dist/util.d.ts +24 -0
- package/dist/util.js +25 -0
- package/docs/authoring.md +9 -0
- package/docs/cli.md +411 -15
- package/docs/design.md +86 -12
- package/docs/embedding.md +58 -0
- package/package.json +1 -1
package/dist/hub.js
CHANGED
|
@@ -10,6 +10,34 @@
|
|
|
10
10
|
* etc.) so this module stays trivially testable and `cli.ts` doesn't widen its
|
|
11
11
|
* export surface.
|
|
12
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
|
+
*
|
|
13
41
|
* `.owenloop/hub.json` is a pure binding (which hub this project publishes to)
|
|
14
42
|
* — there is no client-side push ledger. `push` diffs local defs against the
|
|
15
43
|
* server's own `hash` (`GET /api/workflows`, see `computeServerDiff`), and
|
|
@@ -36,6 +64,7 @@
|
|
|
36
64
|
* `push` diff), so keeping it in this module — not in engine core — is what
|
|
37
65
|
* lets `defs.ts` stay host/hub-agnostic.
|
|
38
66
|
*/
|
|
67
|
+
import { execFileSync } from 'node:child_process';
|
|
39
68
|
import { createHash, randomBytes } from 'node:crypto';
|
|
40
69
|
import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
41
70
|
import { basename, dirname, join } from 'node:path';
|
|
@@ -157,6 +186,87 @@ export function pkcePair() {
|
|
|
157
186
|
export function randomState() {
|
|
158
187
|
return base64url(randomBytes(16));
|
|
159
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
|
+
}
|
|
160
270
|
/** The user-level config dir (never the project dir). Derives from the caller's env. */
|
|
161
271
|
export function configDir(env) {
|
|
162
272
|
const xdg = env.XDG_CONFIG_HOME;
|
|
@@ -170,15 +280,30 @@ export function configDir(env) {
|
|
|
170
280
|
export function credentialFilePath(env) {
|
|
171
281
|
return join(configDir(env), 'credentials.json');
|
|
172
282
|
}
|
|
173
|
-
/**
|
|
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
|
+
*/
|
|
174
297
|
export function readCredentialFile(path) {
|
|
175
298
|
if (!existsSync(path))
|
|
176
|
-
return { version:
|
|
299
|
+
return { version: 2, hubs: {} };
|
|
177
300
|
const parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
178
|
-
if (!parsed || typeof parsed !== 'object' || typeof parsed.hubs !== 'object') {
|
|
301
|
+
if (!parsed || typeof parsed !== 'object' || typeof parsed.hubs !== 'object' || parsed.hubs === null) {
|
|
179
302
|
throw new Error(`malformed credential file at ${path}`);
|
|
180
303
|
}
|
|
181
|
-
|
|
304
|
+
if (parsed.version !== 2)
|
|
305
|
+
return { version: 2, hubs: {} };
|
|
306
|
+
return { version: 2, hubs: parsed.hubs };
|
|
182
307
|
}
|
|
183
308
|
/**
|
|
184
309
|
* Write `data` to `path` atomically, refusing a symlinked (or directory)
|
|
@@ -235,6 +360,299 @@ export function writeCredentialFile(path, file) {
|
|
|
235
360
|
chmodSync(dir, 0o700);
|
|
236
361
|
writeFileAtomic(path, `${JSON.stringify(file, null, 2)}\n`, { mode: 0o600 });
|
|
237
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
|
+
/**
|
|
614
|
+
* Enumerate the hub origins that have a usable `human` credential stored, or
|
|
615
|
+
* `null` when the active backend cannot be enumerated.
|
|
616
|
+
*
|
|
617
|
+
* Consumer: `owenloop mcp`'s origin inference (`resolveMcpOrigin` in
|
|
618
|
+
* `src/mcp/serve.ts`). When the host spawns the server with neither `--hub` nor
|
|
619
|
+
* `OWENLOOP_HUB`, the server tries to infer the single hub the user is logged
|
|
620
|
+
* in to. That inference is only sound on the FILE backend, which can list its
|
|
621
|
+
* `hubs` map; the keychain and external-command backends cannot enumerate:
|
|
622
|
+
*
|
|
623
|
+
* - **file** → the origins in `readCredentialFile(credentialFilePath(env)).hubs`
|
|
624
|
+
* whose `human` slot parses as a well-formed `Credential` (`parseCredential`).
|
|
625
|
+
* An origin present only under an `agent:<name>` slot is NOT returned — the
|
|
626
|
+
* control plane authenticates as the human.
|
|
627
|
+
* - **keychain** → `null`. The `Keychain` interface (get/set/delete by
|
|
628
|
+
* `(service, account)`) has no list operation — macOS `security` cannot
|
|
629
|
+
* enumerate the accounts under a service without a keychain-wide dump this
|
|
630
|
+
* module deliberately does not perform. There is no way to know which origins
|
|
631
|
+
* have entries, so it returns `null` ("cannot enumerate") rather than a
|
|
632
|
+
* misleading empty list.
|
|
633
|
+
* - **external** → `null`, for the same reason: the command answers a single
|
|
634
|
+
* `(origin, slot)` query; it has no listing contract.
|
|
635
|
+
*
|
|
636
|
+
* `null` (cannot enumerate), `[]` (nothing stored), and a length>1 result are
|
|
637
|
+
* all distinct signals the caller turns into tailored exit-2 messages — this
|
|
638
|
+
* function reports the fact, it never decides the outcome. It never logs or
|
|
639
|
+
* echoes any credential; only the origin KEYS (never secrets) are returned.
|
|
640
|
+
*
|
|
641
|
+
* `env`/`keychain` are threaded exactly as `readStoredCredential` threads them,
|
|
642
|
+
* so a caller passing a fixture `env` stays hermetic.
|
|
643
|
+
*/
|
|
644
|
+
export function listStoredHubOrigins(env, keychain) {
|
|
645
|
+
const backend = credentialBackend(env, keychain);
|
|
646
|
+
if (backend.kind !== 'file')
|
|
647
|
+
return null;
|
|
648
|
+
const file = readCredentialFile(credentialFilePath(env));
|
|
649
|
+
const origins = [];
|
|
650
|
+
for (const [origin, slots] of Object.entries(file.hubs)) {
|
|
651
|
+
if (parseCredential(slots?.['human']) !== null)
|
|
652
|
+
origins.push(origin);
|
|
653
|
+
}
|
|
654
|
+
return origins;
|
|
655
|
+
}
|
|
238
656
|
export function hubBindingPath(cwd) {
|
|
239
657
|
return join(cwd, '.owenloop', 'hub.json');
|
|
240
658
|
}
|
|
@@ -377,6 +795,135 @@ export function asWhoami(body) {
|
|
|
377
795
|
identity.email = b.email;
|
|
378
796
|
return identity;
|
|
379
797
|
}
|
|
798
|
+
/**
|
|
799
|
+
* Narrow a `POST /api/mint_agent_token` 200 body to its typed success shape,
|
|
800
|
+
* validating STRICTLY (mirrors `asWhoami`/`asCreateWorkflowOk`'s throw-on-
|
|
801
|
+
* malformed style): a 2xx is not enough — the identity fields must be present
|
|
802
|
+
* and well-typed, or the "success" is a malformed response and must be treated
|
|
803
|
+
* as a failure rather than silently coerced.
|
|
804
|
+
*
|
|
805
|
+
* **Token hygiene (load-bearing):** every error message names the offending
|
|
806
|
+
* FIELD only — it never echoes a field VALUE. A malformed body could still carry
|
|
807
|
+
* the `olp_` plaintext (in `text`, or in a mistyped `token`), so echoing values
|
|
808
|
+
* here would be the exact leak §6 forbids. `id`/`agentId` must be non-empty
|
|
809
|
+
* strings; `token` a non-empty string starting `olp_`; `pools` an array of
|
|
810
|
+
* strings (empty allowed defensively — the server always resolves at least one,
|
|
811
|
+
* but the client does not depend on that to stay leak-safe).
|
|
812
|
+
*/
|
|
813
|
+
export function asMintAgentTokenOk(body) {
|
|
814
|
+
if (typeof body !== 'object' || body === null) {
|
|
815
|
+
throw new Error('mint_agent_token: malformed success response — not an object');
|
|
816
|
+
}
|
|
817
|
+
const b = body;
|
|
818
|
+
if (typeof b.id !== 'string' || b.id === '') {
|
|
819
|
+
throw new Error('mint_agent_token: malformed success response — missing non-empty string id');
|
|
820
|
+
}
|
|
821
|
+
if (typeof b.agentId !== 'string' || b.agentId === '') {
|
|
822
|
+
throw new Error('mint_agent_token: malformed success response — missing non-empty string agentId');
|
|
823
|
+
}
|
|
824
|
+
if (typeof b.token !== 'string' || b.token === '') {
|
|
825
|
+
throw new Error('mint_agent_token: malformed success response — missing non-empty string token');
|
|
826
|
+
}
|
|
827
|
+
if (!b.token.startsWith('olp_')) {
|
|
828
|
+
throw new Error('mint_agent_token: malformed success response — token is not an olp_ token');
|
|
829
|
+
}
|
|
830
|
+
if (!Array.isArray(b.pools) || b.pools.some((p) => typeof p !== 'string')) {
|
|
831
|
+
throw new Error('mint_agent_token: malformed success response — pools must be an array of strings');
|
|
832
|
+
}
|
|
833
|
+
return { id: b.id, token: b.token, agentId: b.agentId, pools: b.pools };
|
|
834
|
+
}
|
|
835
|
+
/**
|
|
836
|
+
* Narrow `GET /api/agent_identities`'s 200 body (`{identities: [...]}`) to a
|
|
837
|
+
* typed array. Throws on a malformed body (missing `identities` array, or a row
|
|
838
|
+
* missing `id`/`name`). Non-secret shape — the rows carry no token — so errors
|
|
839
|
+
* may name indices/fields freely. `lastContactAt`/`lastUsedAt` tolerate `null`
|
|
840
|
+
* or absence (→ `null`) but reject a present non-number; `pools` defaults to an
|
|
841
|
+
* empty array when absent, rejects a present non-array-of-strings; `disabled`
|
|
842
|
+
* defaults to `false`.
|
|
843
|
+
*/
|
|
844
|
+
export function asAgentIdentities(body) {
|
|
845
|
+
if (typeof body !== 'object' || body === null || !Array.isArray(body.identities)) {
|
|
846
|
+
throw new Error('agent_identities: malformed response — expected an `identities` array');
|
|
847
|
+
}
|
|
848
|
+
const list = body.identities;
|
|
849
|
+
return list.map((entry, i) => {
|
|
850
|
+
if (typeof entry !== 'object' || entry === null) {
|
|
851
|
+
throw new Error(`agent_identities: malformed response — identities[${i}] is not an object`);
|
|
852
|
+
}
|
|
853
|
+
const e = entry;
|
|
854
|
+
if (typeof e.id !== 'string' || e.id === '') {
|
|
855
|
+
throw new Error(`agent_identities: malformed response — identities[${i}] missing non-empty string id`);
|
|
856
|
+
}
|
|
857
|
+
if (typeof e.name !== 'string' || e.name === '') {
|
|
858
|
+
throw new Error(`agent_identities: malformed response — identities[${i}] missing non-empty string name`);
|
|
859
|
+
}
|
|
860
|
+
const epochOrNull = (v, field) => {
|
|
861
|
+
if (v === undefined || v === null)
|
|
862
|
+
return null;
|
|
863
|
+
if (typeof v !== 'number')
|
|
864
|
+
throw new Error(`agent_identities: malformed response — identities[${i}].${field} must be a number or null`);
|
|
865
|
+
return v;
|
|
866
|
+
};
|
|
867
|
+
let pools = [];
|
|
868
|
+
if (e.pools !== undefined) {
|
|
869
|
+
if (!Array.isArray(e.pools) || e.pools.some((p) => typeof p !== 'string')) {
|
|
870
|
+
throw new Error(`agent_identities: malformed response — identities[${i}].pools must be an array of strings`);
|
|
871
|
+
}
|
|
872
|
+
pools = e.pools;
|
|
873
|
+
}
|
|
874
|
+
return {
|
|
875
|
+
id: e.id,
|
|
876
|
+
name: e.name,
|
|
877
|
+
disabled: e.disabled === true,
|
|
878
|
+
pools,
|
|
879
|
+
lastContactAt: epochOrNull(e.lastContactAt, 'lastContactAt'),
|
|
880
|
+
lastUsedAt: epochOrNull(e.lastUsedAt, 'lastUsedAt'),
|
|
881
|
+
};
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
/**
|
|
885
|
+
* Narrow a `POST /api/rekey_agent_token` 200 body to its typed success shape.
|
|
886
|
+
* Mirrors `asMintAgentTokenOk`'s discipline exactly: STRICT validation of the
|
|
887
|
+
* identity fields, and every error names the offending FIELD only — never a
|
|
888
|
+
* field VALUE — because a malformed body could still carry the `olp_` plaintext
|
|
889
|
+
* (in `text`, or a mistyped `token`), and echoing values would be the exact leak
|
|
890
|
+
* §6 forbids. `id`/`agentId` non-empty strings; `token` a non-empty string
|
|
891
|
+
* starting `olp_`; `revokedTokenIds`/`scopes` arrays of strings, each tolerated
|
|
892
|
+
* absent (→ empty array) but rejected if present-and-malformed.
|
|
893
|
+
*/
|
|
894
|
+
export function asRekeyAgentTokenOk(body) {
|
|
895
|
+
if (typeof body !== 'object' || body === null) {
|
|
896
|
+
throw new Error('rekey_agent_token: malformed success response — not an object');
|
|
897
|
+
}
|
|
898
|
+
const b = body;
|
|
899
|
+
if (typeof b.id !== 'string' || b.id === '') {
|
|
900
|
+
throw new Error('rekey_agent_token: malformed success response — missing non-empty string id');
|
|
901
|
+
}
|
|
902
|
+
if (typeof b.agentId !== 'string' || b.agentId === '') {
|
|
903
|
+
throw new Error('rekey_agent_token: malformed success response — missing non-empty string agentId');
|
|
904
|
+
}
|
|
905
|
+
if (typeof b.token !== 'string' || b.token === '') {
|
|
906
|
+
throw new Error('rekey_agent_token: malformed success response — missing non-empty string token');
|
|
907
|
+
}
|
|
908
|
+
if (!b.token.startsWith('olp_')) {
|
|
909
|
+
throw new Error('rekey_agent_token: malformed success response — token is not an olp_ token');
|
|
910
|
+
}
|
|
911
|
+
const strArray = (v, field) => {
|
|
912
|
+
if (v === undefined)
|
|
913
|
+
return [];
|
|
914
|
+
if (!Array.isArray(v) || v.some((x) => typeof x !== 'string')) {
|
|
915
|
+
throw new Error(`rekey_agent_token: malformed success response — ${field} must be an array of strings`);
|
|
916
|
+
}
|
|
917
|
+
return v;
|
|
918
|
+
};
|
|
919
|
+
return {
|
|
920
|
+
id: b.id,
|
|
921
|
+
token: b.token,
|
|
922
|
+
agentId: b.agentId,
|
|
923
|
+
revokedTokenIds: strArray(b.revokedTokenIds, 'revokedTokenIds'),
|
|
924
|
+
scopes: strArray(b.scopes, 'scopes'),
|
|
925
|
+
};
|
|
926
|
+
}
|
|
380
927
|
/**
|
|
381
928
|
* Parse `GET /api/workflows`'s body into a `name -> WorkflowSummary` map for
|
|
382
929
|
* `computeServerDiff`. Throws a descriptive error (the caller wraps it in a
|
package/dist/index.d.ts
CHANGED
|
@@ -18,8 +18,11 @@ export type { CreateEngineOpts, CreatedEngine } from './factory.ts';
|
|
|
18
18
|
export { Store, openStore, StoreVersionError } from './store.ts';
|
|
19
19
|
export type { ArtifactRow, RunRow, TaskRow, WorkflowRow } from './store.ts';
|
|
20
20
|
export { buildDef, DefError, expandIncludes, finalizeDefs, hashDef, lintDef, loadDefFile, loadDefs, loadDefsRaw, parseDef, SUPPORTED_ENGINE_VERSION, validateDef } from './defs.ts';
|
|
21
|
-
export { hashDefForHub } from './hub.ts';
|
|
21
|
+
export { credentialSlot, hashDefForHub, keychainServiceFor, normalizeOrigin, readStoredCredential } from './hub.ts';
|
|
22
|
+
export type { Credential, CredentialSlotSelector, Keychain, ReadStoredCredentialOpts } from './hub.ts';
|
|
22
23
|
export type { DefLoadFailure } from './defs.ts';
|
|
24
|
+
export { deleteCredential, ensureFreshOAuth, storeCredential } from './credentials.ts';
|
|
25
|
+
export type { CredentialIO } from './credentials.ts';
|
|
23
26
|
export { buildGraph, buildTrace, eligibleFirings, graphToDot, graphToMermaid, isStalled, modelCheck, workflowStatus, } from './model.ts';
|
|
24
27
|
export type { ArtifactMap, Blocker, Firing, TimeFacts, WorkflowStatus } from './model.ts';
|
|
25
28
|
export { parseConsume, parseProduce, } from './paths.ts';
|
package/dist/index.js
CHANGED
|
@@ -15,7 +15,8 @@ export { Engine } from "./engine.js";
|
|
|
15
15
|
export { createEngine } from "./factory.js";
|
|
16
16
|
export { Store, openStore, StoreVersionError } from "./store.js";
|
|
17
17
|
export { buildDef, DefError, expandIncludes, finalizeDefs, hashDef, lintDef, loadDefFile, loadDefs, loadDefsRaw, parseDef, SUPPORTED_ENGINE_VERSION, validateDef } from "./defs.js";
|
|
18
|
-
export { hashDefForHub } from "./hub.js";
|
|
18
|
+
export { credentialSlot, hashDefForHub, keychainServiceFor, normalizeOrigin, readStoredCredential } from "./hub.js";
|
|
19
|
+
export { deleteCredential, ensureFreshOAuth, storeCredential } from "./credentials.js";
|
|
19
20
|
export { buildGraph, buildTrace, eligibleFirings, graphToDot, graphToMermaid, isStalled, modelCheck, workflowStatus, } from "./model.js";
|
|
20
21
|
export { parseConsume, parseProduce, } from "./paths.js";
|
|
21
22
|
export { assertValidSchema, summarizeIssues, validateValue } from "./schema.js";
|