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/factory.d.ts CHANGED
@@ -43,6 +43,18 @@ export interface CreateEngineOpts {
43
43
  defsDir?: string;
44
44
  /** Forwarded to the `Engine` — the stranded-lease reap TTL in milliseconds. */
45
45
  reapTtlMs?: number;
46
+ /** Forwarded to the `Engine` — an OPT-IN hard cap on total lease lifetime in
47
+ * milliseconds (A3/REL-8). Per-step `maxLease` overrides it. Unset (default):
48
+ * no cap; heartbeats extend a lease indefinitely. */
49
+ maxLeaseMs?: number;
50
+ /**
51
+ * Forwarded to the `Engine` — the hard cap on `calls:` composition depth
52
+ * (REL-4 defense in depth). Construction-time validation already rejects
53
+ * `calls:` cycles in the resolved def set, so this only matters for a host
54
+ * that wires an `Engine` with a custom `DefResolver` construction validation
55
+ * cannot inspect. Defaults to the engine's `DEFAULT_MAX_CALL_DEPTH` (64).
56
+ */
57
+ maxCallDepth?: number;
46
58
  /**
47
59
  * A push-style observer registered up front, equivalent to calling
48
60
  * `engine.subscribe` immediately after construction. Fires synchronously
@@ -61,5 +73,12 @@ export interface CreatedEngine {
61
73
  /**
62
74
  * Open a store, resolve definitions, and return a wired `Engine` ready to
63
75
  * `createInstance` / `tick` / `green` / … . See `docs/embedding.md`.
76
+ *
77
+ * REL-4: an in-memory `defs` set is now validated as a whole (calls targets
78
+ * exist, `callsInputs` keys valid, exactly-one child output, per-def validation,
79
+ * and calls-cycle detection) exactly like the filesystem `defsDir` loader — so
80
+ * `createEngine({ defs })` THROWS `DefError` on an invalid set instead of
81
+ * silently registering it. The returned `defs` is the validated copy the
82
+ * resolver closes over.
64
83
  */
65
84
  export declare function createEngine(opts?: CreateEngineOpts): CreatedEngine;
package/dist/factory.js CHANGED
@@ -22,19 +22,36 @@ import { existsSync, mkdirSync } from 'node:fs';
22
22
  import { dirname, join } from 'node:path';
23
23
  import { Engine } from "./engine.js";
24
24
  import { openStore } from "./store.js";
25
- import { loadDefs } from "./defs.js";
25
+ import { dbPathRefusingSymlink, mkdirRefusingSymlink } from "./util.js";
26
+ import { finalizeDefs, loadDefs } from "./defs.js";
26
27
  /**
27
28
  * Open a store, resolve definitions, and return a wired `Engine` ready to
28
29
  * `createInstance` / `tick` / `green` / … . See `docs/embedding.md`.
30
+ *
31
+ * REL-4: an in-memory `defs` set is now validated as a whole (calls targets
32
+ * exist, `callsInputs` keys valid, exactly-one child output, per-def validation,
33
+ * and calls-cycle detection) exactly like the filesystem `defsDir` loader — so
34
+ * `createEngine({ defs })` THROWS `DefError` on an invalid set instead of
35
+ * silently registering it. The returned `defs` is the validated copy the
36
+ * resolver closes over.
29
37
  */
30
38
  export function createEngine(opts = {}) {
31
39
  const db = opts.db ?? join('.owenloop', 'state.db');
32
- if (db !== ':memory:')
33
- mkdirSync(dirname(db), { recursive: true });
34
- const store = openStore(db);
40
+ // Resolve (and validate) the def set BEFORE opening the store: a validation
41
+ // throw here must not leak an open SQLite handle (the `defsDir` branch also
42
+ // validated inside `loadDefs`, but used to do so after `openStore` — that
43
+ // reorder is safe, its only observable effect is the leak we're closing).
35
44
  let defs;
36
45
  if (opts.defs !== undefined) {
37
- defs = Array.isArray(opts.defs) ? new Map(opts.defs.map((d) => [d.name, d])) : opts.defs;
46
+ // REL-4: validate the ENTIRE in-memory set exactly like the filesystem
47
+ // loader — calls targets exist, callsInputs keys valid, exactly-one-output,
48
+ // per-def validateDef, and cross-def calls-cycle detection. Reuses the
49
+ // loader's own Phase-2/3 validator (`finalizeDefs`); no second validator.
50
+ // The resolver below closes over this FINALIZED copy, so mutating the
51
+ // caller's original Map/array after construction no longer silently changes
52
+ // resolution — that hole was part of REL-4's surface.
53
+ const raw = Array.isArray(opts.defs) ? new Map(opts.defs.map((d) => [d.name, d])) : opts.defs;
54
+ defs = finalizeDefs(raw);
38
55
  }
39
56
  else if (opts.defsDir !== undefined) {
40
57
  defs = existsSync(opts.defsDir) ? loadDefs(opts.defsDir) : new Map();
@@ -42,6 +59,21 @@ export function createEngine(opts = {}) {
42
59
  else {
43
60
  defs = new Map();
44
61
  }
62
+ if (db !== ':memory:') {
63
+ // Guard the built-in default (`.owenloop/state.db`) against a symlinked
64
+ // `.owenloop` from a hostile checkout (SEC-3). Directory guard first, then
65
+ // the file-level guard on `state.db` and its SQLite sidecars — a symlinked
66
+ // db file inside a REAL `.owenloop` would otherwise redirect writes SQLite
67
+ // follows. An explicit `opts.db` comes from the caller, not the repo, so it
68
+ // keeps today's plain mkdir behavior.
69
+ if (opts.db === undefined) {
70
+ mkdirRefusingSymlink(dirname(db));
71
+ dbPathRefusingSymlink(db);
72
+ }
73
+ else
74
+ mkdirSync(dirname(db), { recursive: true });
75
+ }
76
+ const store = openStore(db);
45
77
  const resolveDef = (name) => {
46
78
  const d = defs.get(name);
47
79
  if (!d)
@@ -51,6 +83,10 @@ export function createEngine(opts = {}) {
51
83
  const engineOpts = {};
52
84
  if (opts.reapTtlMs !== undefined)
53
85
  engineOpts.reapTtlMs = opts.reapTtlMs;
86
+ if (opts.maxLeaseMs !== undefined)
87
+ engineOpts.maxLeaseMs = opts.maxLeaseMs;
88
+ if (opts.maxCallDepth !== undefined)
89
+ engineOpts.maxCallDepth = opts.maxCallDepth;
54
90
  if (opts.onEvent !== undefined)
55
91
  engineOpts.onEvent = opts.onEvent;
56
92
  if (opts.onListenerError !== undefined)
package/dist/hub.d.ts ADDED
@@ -0,0 +1,514 @@
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
+ /**
68
+ * Reproduce the hub service's def content hash for the CLI `push` diff
69
+ * (`owenloop-service` `apps/hub-edge/README.md`, "Hub API parity for CLI"):
70
+ * `sha256(JSON.stringify(parseDef(YAML.parse(yaml))))` sliced to 16 hex
71
+ * chars, computed with **no `baseDir`** — the compiled def (defaults filled),
72
+ * exactly as the server computes it when it has no stored `defs` row. Taking
73
+ * no `baseDir` is deliberate, not an oversight: it means `parseDef` throws a
74
+ * `DefError` on any def using `bodyFile:` ("bodyFile requires a workflow
75
+ * loaded from disk"), which is exactly the server's own limitation — such a
76
+ * def can't be pushed as raw YAML anyway, so the caller should catch that and
77
+ * refuse the push with a clear reason, the same way it already refuses an
78
+ * `include:` def.
79
+ *
80
+ * Stable only per pinned engine version: the service pins its `parseDef`/
81
+ * `hashDef` lineage to a specific commit (`VENDORED_SHA`). As of writing that
82
+ * commit is an ancestor of this repo's `HEAD` with no changes to
83
+ * `parseDef`/`buildDef`/`hashDef` in between, so a locally computed hash
84
+ * currently matches the server's — but a future engine default change could
85
+ * make them drift. A drifted hash reads as `changed`, not an error: pushing
86
+ * converges state, because the server's own idempotent `create_workflow`
87
+ * still recognizes byte-identical content and replies `unchanged: true`.
88
+ */
89
+ export declare function hashDefForHub(yaml: string): string;
90
+ /**
91
+ * Normalize a hub URL to a bare origin (`scheme://host[:port]`), stripping any
92
+ * path, query, trailing slash, and fragment. Requires an http(s) scheme. This
93
+ * is the credential-store key and the project binding value, so it must be
94
+ * canonical: `https://api.owenloop.com/` and `https://api.owenloop.com/foo`
95
+ * both key to `https://api.owenloop.com`.
96
+ *
97
+ * Transport policy (SEC-2): `https` is required for every hub origin EXCEPT the
98
+ * loopback hosts (`127.0.0.1`, `::1`, `localhost`), which may use `http` for
99
+ * local development. Remote `http` is rejected here, at normalization time, so a
100
+ * plaintext origin that would leak bearer/refresh tokens, auth codes, and
101
+ * workflow YAML to an on-path attacker can never be persisted into a credential
102
+ * key or a project binding.
103
+ */
104
+ export declare function normalizeOrigin(input: string): string;
105
+ /**
106
+ * Join an origin and an endpoint that may be absolute or a root-relative path,
107
+ * enforcing the same-origin policy for OAuth discovery metadata (SEC-4).
108
+ *
109
+ * This is the trust boundary for every endpoint consumed from OAuth metadata —
110
+ * authorization, token, and registration endpoints all flow through here, as do
111
+ * the CLI's own literal root-relative API paths. A metadata-derived absolute
112
+ * endpoint is allowed, but must resolve to the SAME origin as the hub; a
113
+ * cross-origin (or protocol-relative `//host`) endpoint is rejected so a
114
+ * discovered `token_endpoint` on a foreign origin can never receive a refresh
115
+ * token. Path and query are preserved — only `.origin` is compared. The
116
+ * https-except-loopback rule holds for free: `origin` here is already a
117
+ * `normalizeOrigin` output at every call site, so same-origin implies the
118
+ * transport policy.
119
+ */
120
+ export declare function resolveEndpoint(origin: string, endpoint: string): string;
121
+ /** URL-safe base64 with no padding (RFC 7636 §A). */
122
+ export declare function base64url(buf: Buffer): string;
123
+ export interface PkcePair {
124
+ verifier: string;
125
+ challenge: string;
126
+ }
127
+ /**
128
+ * Generate a PKCE verifier/challenge pair for the S256 method. The verifier is
129
+ * 32 random bytes base64url-encoded (43 chars — within the RFC's 43..128 range
130
+ * and drawn from the unreserved charset); the challenge is
131
+ * base64url(sha256(verifier)).
132
+ */
133
+ export declare function pkcePair(): PkcePair;
134
+ /** A random anti-CSRF `state` token for the authorization request. */
135
+ export declare function randomState(): string;
136
+ /**
137
+ * Stored per **slot** — one credential per `(normalized origin, slot)` pair,
138
+ * the slot being `human` or `agent:<account>` (see `CredentialSlotSelector`).
139
+ * Never logged or echoed. `oauth` carries a refreshable pair (loopback flow);
140
+ * `agent` is a pasted `olp_` token and `oauth-pasted` a pasted `mcpat_` access
141
+ * token — neither refreshes.
142
+ */
143
+ export type Credential = {
144
+ kind: 'oauth';
145
+ accessToken: string;
146
+ refreshToken: string;
147
+ expiresAt: number;
148
+ clientId: string;
149
+ } | {
150
+ kind: 'agent';
151
+ accessToken: string;
152
+ } | {
153
+ kind: 'oauth-pasted';
154
+ accessToken: string;
155
+ };
156
+ /**
157
+ * Which stored credential to address: the human's, or a named agent account's.
158
+ *
159
+ * A credential lives in a **slot** — `human`, or `agent:<account>` with
160
+ * `account` defaulting to `'default'`. The slot is part of the storage key on
161
+ * both backends (keychain account, and the second level of the credential
162
+ * file's `hubs` map), so `human` and `agent:default` on the same origin are
163
+ * distinct entries that never collide, and neither does `agent:ci` with
164
+ * `agent:release`.
165
+ *
166
+ * The discriminator is an **account**, never a "label" — labels are a different
167
+ * axis of the system and the word is reserved.
168
+ */
169
+ export type CredentialSlotSelector = {
170
+ principal: 'human';
171
+ } | {
172
+ principal: 'agent';
173
+ account?: string;
174
+ };
175
+ /**
176
+ * The credential file (`~/.config/owenloop/credentials.json`), v2: origin →
177
+ * slot → credential. `version` is `2`; a file carrying any other version reads
178
+ * as an EMPTY store (see `readCredentialFile`) — that is how entries under the
179
+ * older one-slot-per-origin keying become invisible without any migration code.
180
+ */
181
+ export interface CredentialFile {
182
+ version: 2;
183
+ hubs: Record<string, Record<string, Credential>>;
184
+ }
185
+ /**
186
+ * Resolve a selector to its slot string: `'human'` or `` `agent:${account}` ``.
187
+ *
188
+ * This is the ONE place account defaulting and validation happen — every read,
189
+ * write, and delete path funnels through it, so no call site re-implements the
190
+ * `agent:` concatenation. Throws on an invalid account name, and on `account`
191
+ * supplied alongside `principal: 'human'`: TypeScript's excess-property check
192
+ * does not reliably reject that against a union, so it is a runtime error too
193
+ * rather than a silently ignored argument.
194
+ *
195
+ * `agent:human` cannot collide with `human` by construction — the `agent:`
196
+ * prefix differs — so no extra guard is needed.
197
+ */
198
+ export declare function credentialSlot(sel: CredentialSlotSelector): string;
199
+ /**
200
+ * The keychain SERVICE for a hub origin; the slot is the keychain ACCOUNT.
201
+ * `origin` must already be `normalizeOrigin`d — every call site normalizes
202
+ * first, so SEC-2 (remote plaintext rejected) happens before any keychain or
203
+ * filesystem access.
204
+ */
205
+ export declare function keychainServiceFor(normalizedOrigin: string): string;
206
+ /**
207
+ * Shape-guard a stored credential value, returning `null` when it is not a
208
+ * well-formed `Credential`. Used on BOTH backends so "a corrupt entry reads as
209
+ * absent" is symmetric: previously the keychain path did an unchecked
210
+ * `JSON.parse(...) as Credential` and the file path validated nothing at all,
211
+ * so a truncated or hand-edited entry could surface as a bogus credential
212
+ * instead of a clean miss.
213
+ */
214
+ export declare function parseCredential(raw: unknown): Credential | null;
215
+ /** The user-level config dir (never the project dir). Derives from the caller's env. */
216
+ export declare function configDir(env: Record<string, string | undefined>): string;
217
+ export declare function credentialFilePath(env: Record<string, string | undefined>): string;
218
+ /**
219
+ * Read the credential file; a missing file is an empty store, not an error.
220
+ *
221
+ * A file whose `version` is not `2` also reads as an EMPTY store — no throw, no
222
+ * migration, no hybrid write. That is how entries under the older
223
+ * one-slot-per-origin keying become invisible (there are no external users, so
224
+ * the documented upgrade step is re-running `login`). Stated deliberately: the
225
+ * next write then replaces such a file wholesale, which is acceptable because
226
+ * its entries are unreachable by design.
227
+ *
228
+ * Genuinely broken JSON, or a `hubs` that is not an object, still throws —
229
+ * "corrupt reads as absent" is about a corrupt ENTRY (see `parseCredential`),
230
+ * not a destroyed file.
231
+ */
232
+ export declare function readCredentialFile(path: string): CredentialFile;
233
+ /**
234
+ * Write `data` to `path` atomically, refusing a symlinked (or directory)
235
+ * destination (SEC-3).
236
+ *
237
+ * 1. `lstat` the destination: if it already exists AND is a symlink, throw a
238
+ * clear error naming the path rather than clobbering the arbitrary,
239
+ * possibly-privileged file the link points at. A pre-existing directory is
240
+ * likewise refused with a named error (instead of a raw ENOTDIR from
241
+ * rename).
242
+ * 2. Write to a temp file in the SAME directory (same-dir is required — a
243
+ * cross-filesystem rename is not atomic), then `chmod` the temp to `mode`
244
+ * BEFORE the rename so the final file never momentarily exists with a lax,
245
+ * umask-widened mode (preserving the old "re-chmod on every write"
246
+ * guarantee, now applied to the temp).
247
+ * 3. `rename(tmp, path)` — an atomic replace. On any failure after the temp
248
+ * exists, best-effort unlink the temp and rethrow.
249
+ *
250
+ * The `lstat` check is a courtesy clear-error, not the security boundary:
251
+ * `rename` replaces the destination inode rather than following it, so even a
252
+ * symlink raced into place between the `lstat` and the `rename` is replaced,
253
+ * never followed — the write can never escape to the link target.
254
+ */
255
+ export declare function writeFileAtomic(path: string, data: string, opts?: {
256
+ mode?: number;
257
+ }): void;
258
+ /**
259
+ * Write the credential file with strict permissions: dir 0700, file 0600.
260
+ * The file itself is written atomically via `writeFileAtomic` (temp + rename),
261
+ * which also chmods the temp to 0600 before the rename — so the secret is
262
+ * never visible under a laxer mode, even briefly, and a symlinked destination
263
+ * is refused (SEC-3).
264
+ */
265
+ export declare function writeCredentialFile(path: string, file: CredentialFile): void;
266
+ /**
267
+ * An OS keychain backend, keyed by `(service, account)` — the service is
268
+ * `keychainServiceFor(origin)` (`owenloop:<origin>`) and the account is the
269
+ * credential slot (`human` / `agent:<name>`). The pair mirrors macOS
270
+ * `security`'s own `-s`/`-a` arguments. The default implementation (macOS
271
+ * `security` generic passwords) is `defaultKeychain`; tests and embedding hosts
272
+ * inject their own. Never logs or echoes the secret.
273
+ */
274
+ export interface Keychain {
275
+ get(service: string, account: string): string | null;
276
+ set(service: string, account: string, value: string): void;
277
+ delete(service: string, account: string): void;
278
+ }
279
+ /**
280
+ * The default macOS keychain backend (generic passwords under service
281
+ * `owenloop:<origin>`, account = the credential slot). The secret is fed through
282
+ * the `security -i` command stream on stdin, never as a `-w` argv value, so it
283
+ * never appears in `ps`/shell history. Returns `undefined` off macOS or when
284
+ * `OWENLOOP_NO_KEYCHAIN=1`, so callers fall back to the 0600 credential file.
285
+ */
286
+ export declare function defaultKeychain(env: Record<string, string | undefined>): Keychain | undefined;
287
+ /**
288
+ * The configured external credential command, or `undefined` when it is unset
289
+ * or blank.
290
+ *
291
+ * Configuration is a single environment variable, `OWENLOOP_CREDENTIAL_COMMAND`,
292
+ * read off the caller-supplied `env` record like every other knob in this module
293
+ * (`OWENLOOP_NO_KEYCHAIN`, `OWENLOOP_HUB`, the `*_TIMEOUT_MS` overrides) — never
294
+ * `process.env` directly, so hosts and tests stay hermetic. Explicit config
295
+ * only: there is deliberately no discovery, no scanning for helper binaries, and
296
+ * no implicit default.
297
+ *
298
+ * An all-whitespace value is treated as NOT configured, and that decision is
299
+ * made HERE rather than at each call site, so "is the external backend active?"
300
+ * has exactly one answer.
301
+ */
302
+ export declare function externalCredentialCommand(env: Record<string, string | undefined>): string | undefined;
303
+ /**
304
+ * Resolve the keychain backend for this env, honoring the hard override:
305
+ * `OWENLOOP_NO_KEYCHAIN=1` forces the file backend (`undefined`) EVEN when a
306
+ * keychain is injected; otherwise the injected backend wins, else the platform
307
+ * default.
308
+ */
309
+ export declare function resolveKeychain(env: Record<string, string | undefined>, injected?: Keychain): Keychain | undefined;
310
+ /**
311
+ * The credential backend, decided ONCE from env/config and then used
312
+ * consistently for read and write. Deciding once — rather than per-operation —
313
+ * is the REL-6 fix: the old error-driven fallback let a write land in the file
314
+ * while a later read hit the (absent/stale) keychain, so a credential could
315
+ * shadow itself across backends.
316
+ *
317
+ * Precedence is **external → keychain → file**. Resolving all three here, in one
318
+ * place, is what makes "decided once" and "a configured external command wins
319
+ * over a populated keychain or file entry" the same fact, with no second
320
+ * decision point that could drift.
321
+ */
322
+ export type CredentialBackend = {
323
+ kind: 'external';
324
+ command: string;
325
+ } | {
326
+ kind: 'keychain';
327
+ kc: Keychain;
328
+ } | {
329
+ kind: 'file';
330
+ };
331
+ /**
332
+ * `OWENLOOP_NO_KEYCHAIN=1` deliberately does NOT affect the external branch: it
333
+ * selects between the two LOCAL stores, and the external command sits in front
334
+ * of both.
335
+ */
336
+ export declare function credentialBackend(env: Record<string, string | undefined>, injected?: Keychain): CredentialBackend;
337
+ /**
338
+ * Options for `readStoredCredential`. The slot selector is REQUIRED (it is
339
+ * spread into this type, not optional): the caller must name which principal's
340
+ * credential it wants.
341
+ */
342
+ export type ReadStoredCredentialOpts = CredentialSlotSelector & {
343
+ /** Environment to consult (OWENLOOP_NO_KEYCHAIN, HOME/XDG_CONFIG_HOME). Default: `process.env`. */
344
+ env?: Record<string, string | undefined>;
345
+ /** Injectable keychain backend (tests / embedding hosts). Ignored when OWENLOOP_NO_KEYCHAIN=1. */
346
+ keychain?: Keychain;
347
+ };
348
+ /**
349
+ * Read the stored hub credential for `origin` **in the named slot** from the
350
+ * chosen backend ONLY — the supported, read-only programmatic surface
351
+ * (owenwork's CredentialReader seam wires to this once released). Secret hygiene
352
+ * is unchanged: this function never logs or echoes the returned credential, and
353
+ * there is deliberately no write/delete companion on the public surface —
354
+ * `login` / `logout` remain the only way to store or remove a credential.
355
+ *
356
+ * `opts` and its `principal` are both required, so a caller can never
357
+ * accidentally read the wrong principal's credential:
358
+ *
359
+ * ```ts
360
+ * readStoredCredential(origin, { principal: 'human' });
361
+ * readStoredCredential(origin, { principal: 'agent' }); // agent:default
362
+ * readStoredCredential(origin, { principal: 'agent', account: 'ci' }); // agent:ci
363
+ * ```
364
+ *
365
+ * Passing `account` with `principal: 'human'` throws (see `credentialSlot`),
366
+ * because TypeScript's excess-property check does not reliably reject it
367
+ * against a union.
368
+ *
369
+ * `origin` is normalized (idempotent on already-normalized input, so the CLI's
370
+ * pre-normalized callers are unaffected) BEFORE any keychain or filesystem
371
+ * access, so the storage key matches what `login` persisted and an invalid or
372
+ * plaintext-remote origin throws at normalization (SEC-2), exactly as the CLI
373
+ * would.
374
+ *
375
+ * Backend is selected once (`credentialBackend`), with precedence external →
376
+ * keychain → file. A keychain-backed read NEVER falls through to the file (that
377
+ * fallback was the REL-6 shadowing bug), and a corrupt entry reads as absent
378
+ * (`null`) on either store — never as a reason to consult the other. The file
379
+ * backend derives its path from the supplied `env` (HOME / XDG_CONFIG_HOME),
380
+ * never `process.env` directly, so a caller passing `opts.env` stays hermetic;
381
+ * only the top-level default falls back to `process.env`.
382
+ *
383
+ * **When `OWENLOOP_CREDENTIAL_COMMAND` is configured this function can THROW
384
+ * instead of returning `null`**, and it does not consult a store at all. The
385
+ * command is authoritative, so a nonzero exit, a timeout, empty output, or
386
+ * output that is not a well-formed credential is a loud error naming the origin
387
+ * and the slot — never a silent fallthrough to a stale local entry. See
388
+ * `runCredentialCommand`. When it is NOT configured, behaviour is exactly what
389
+ * it has always been.
390
+ */
391
+ export declare function readStoredCredential(origin: string, opts: ReadStoredCredentialOpts): Credential | null;
392
+ /**
393
+ * `.owenloop/hub.json` — written by `connect`. Safe to commit: contains no
394
+ * secrets, only the bound hub origin. Purely a binding — `push` diffs against
395
+ * server truth (`GET /api/workflows`), so there is no client-side ledger to
396
+ * carry here.
397
+ */
398
+ export interface HubBinding {
399
+ version: 1;
400
+ hub: string;
401
+ }
402
+ export declare function hubBindingPath(cwd: string): string;
403
+ /**
404
+ * Read `.owenloop/hub.json`; a missing file is `null` (project not bound
405
+ * yet). A file written by a pre-server-diff CLI may still carry a `pushed`
406
+ * key (the old push ledger) — it parses fine and the key is silently
407
+ * ignored; the next `connect` rewrite drops it.
408
+ */
409
+ export declare function readHubBinding(path: string): HubBinding | null;
410
+ export declare function writeHubBinding(path: string, binding: HubBinding): void;
411
+ /** A local def selected for a push, with its server-canonical content hash and raw source yaml. */
412
+ export interface DefPushCandidate {
413
+ name: string;
414
+ hash: string;
415
+ yaml: string;
416
+ }
417
+ /** One entry from `GET /api/workflows`'s `workflows` array. */
418
+ export interface WorkflowSummary {
419
+ name: string;
420
+ hash: string;
421
+ version?: number;
422
+ }
423
+ export interface ServerDiff<T extends {
424
+ name: string;
425
+ hash: string;
426
+ }> {
427
+ toPush: (T & {
428
+ status: 'new' | 'changed';
429
+ })[];
430
+ unchanged: T[];
431
+ }
432
+ /**
433
+ * Partition selected defs into those that need pushing vs. those already
434
+ * up-to-date, purely from the server's own `hash` for each name (from
435
+ * `GET /api/workflows`, via `parseWorkflowList`): a name absent from the
436
+ * server is `new`; present with a different (or missing) hash is `changed`;
437
+ * present with an equal hash is `unchanged` (skipped — no request sent).
438
+ *
439
+ * `force` pushes every candidate regardless of hash — labeled `new` when the
440
+ * server has no entry for it, `changed` otherwise (even when the hash is
441
+ * equal: force means "send it", and the label should still read true).
442
+ *
443
+ * Server names with no local counterpart are ignored (this is a push, not a
444
+ * sync — the CLI never deletes or reports on hub-only defs).
445
+ */
446
+ export declare function computeServerDiff<T extends {
447
+ name: string;
448
+ hash: string;
449
+ }>(candidates: T[], server: Map<string, WorkflowSummary>, force: boolean): ServerDiff<T>;
450
+ /** Success shape of `POST /api/create_workflow`. */
451
+ export interface CreateWorkflowOk {
452
+ ok: true;
453
+ name: string;
454
+ version: number;
455
+ hash: string;
456
+ /** `true` when the posted content's hash equals the latest stored version
457
+ * (server-side idempotent no-op) — no new version was minted. */
458
+ unchanged?: boolean;
459
+ }
460
+ /**
461
+ * `POST /api/create_workflow` returns HTTP 200 with `{ok:false,error}` on a
462
+ * def-parse failure (engine-version skew is the realistic cause) — so a 200 is
463
+ * NOT sufficient; the body's `ok` must be inspected. Returns the parsed error
464
+ * text (verbatim) when the reply is a failure, or `null` when it is a success.
465
+ */
466
+ export declare function createWorkflowError(body: unknown): string | null;
467
+ /**
468
+ * Narrow a create_workflow success body to its typed shape (after
469
+ * `createWorkflowError` returns null), validating STRICTLY (REL-9): a 2xx with
470
+ * `ok:true` is not enough — the identity fields must be present, well-typed, and
471
+ * consistent with the def that was pushed, or the "success" is a malformed
472
+ * response and must be treated as a failure, not silently coerced to defaults.
473
+ *
474
+ * - `name` must be a string equal to `expectedName` (the pushed def's name) —
475
+ * a mismatch means the server acknowledged the wrong workflow.
476
+ * - `version` must be a positive integer (the server mints versions from 1).
477
+ * - `hash` must be a non-empty string. Presence and type only: it is NOT
478
+ * required to equal the locally computed `hashDefForHub`, because engine
479
+ * drift between CLI and hub legitimately produces differing hashes (see
480
+ * `hashDefForHub`'s doc comment).
481
+ * - `unchanged: true` passes through as an idempotent no-op, validated by the
482
+ * same field rules.
483
+ *
484
+ * Throws a descriptive `Error` (mirroring `asWhoami`'s throw-on-malformed style)
485
+ * on any violation; the caller records it as a per-def failure.
486
+ */
487
+ export declare function asCreateWorkflowOk(body: unknown, expectedName: string): CreateWorkflowOk;
488
+ /**
489
+ * Identity returned by `GET /api/whoami` (bearer auth, no RBAC verb — a 200
490
+ * proves the credential authenticates, not that it carries any particular
491
+ * scope; `tokenStatus` is always `'active'` over the wire because a
492
+ * revoked/unknown/disabled credential 401s in auth middleware before the
493
+ * handler runs, so it is deliberately not carried here — branch on the HTTP
494
+ * status, never on a `tokenStatus` field).
495
+ */
496
+ export interface WhoamiIdentity {
497
+ orgId: string;
498
+ orgName: string;
499
+ actor: {
500
+ id: string;
501
+ kind: string;
502
+ role: string;
503
+ };
504
+ authMethod: string;
505
+ email?: string;
506
+ }
507
+ /** Narrow a `GET /api/whoami` 200 body to its typed shape. Throws on a malformed body. */
508
+ export declare function asWhoami(body: unknown): WhoamiIdentity;
509
+ /**
510
+ * Parse `GET /api/workflows`'s body into a `name -> WorkflowSummary` map for
511
+ * `computeServerDiff`. Throws a descriptive error (the caller wraps it in a
512
+ * `CliError`) on a missing/malformed `workflows` array.
513
+ */
514
+ export declare function parseWorkflowList(body: unknown): Map<string, WorkflowSummary>;