owenloop 0.2.1 → 0.3.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/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,290 @@
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
+ * `.owenloop/hub.json` is a pure binding (which hub this project publishes to)
14
+ * — there is no client-side push ledger. `push` diffs local defs against the
15
+ * server's own `hash` (`GET /api/workflows`, see `computeServerDiff`), and
16
+ * `POST /api/create_workflow` is idempotent, so the server is always the
17
+ * source of truth for "did this change" — a client-side cache would just be a
18
+ * second copy of that truth that can go stale.
19
+ *
20
+ * Secret hygiene is a hard rule here: credentials never land in the repo or a
21
+ * plaintext `.env`. The 0600 file backend below (dir 0700) lives under the
22
+ * user's config dir, never the project; all paths derive from the
23
+ * caller-supplied `env` (HOME / XDG_CONFIG_HOME), never `process.env` directly,
24
+ * so tests fixture `$HOME` and never touch ambient machine state. Both this
25
+ * file and `.owenloop/hub.json` are written via `writeFileAtomic` — temp file
26
+ * in the same dir + rename, refusing a symlinked destination (SEC-3). The
27
+ * parent-directory half of that guard is `mkdirRefusingSymlink` (in `util.ts`,
28
+ * so the core store factory can share it without core depending on this hub
29
+ * module): before creating the project `.owenloop` dir we refuse a symlinked
30
+ * `.owenloop` component, so a hostile checkout shipping `.owenloop -> /elsewhere`
31
+ * cannot redirect the write outside the project even though the final file
32
+ * itself is not (yet) a symlink.
33
+ *
34
+ * The server-parity def content hash (`hashDefForHub`) also lives here: it is a
35
+ * hub-facing concern (reproducing owenloop-service's canonicalization for the
36
+ * `push` diff), so keeping it in this module — not in engine core — is what
37
+ * lets `defs.ts` stay host/hub-agnostic.
38
+ */
39
+ /**
40
+ * Reproduce the hub service's def content hash for the CLI `push` diff
41
+ * (`owenloop-service` `apps/hub-edge/README.md`, "Hub API parity for CLI"):
42
+ * `sha256(JSON.stringify(parseDef(YAML.parse(yaml))))` sliced to 16 hex
43
+ * chars, computed with **no `baseDir`** — the compiled def (defaults filled),
44
+ * exactly as the server computes it when it has no stored `defs` row. Taking
45
+ * no `baseDir` is deliberate, not an oversight: it means `parseDef` throws a
46
+ * `DefError` on any def using `bodyFile:` ("bodyFile requires a workflow
47
+ * loaded from disk"), which is exactly the server's own limitation — such a
48
+ * def can't be pushed as raw YAML anyway, so the caller should catch that and
49
+ * refuse the push with a clear reason, the same way it already refuses an
50
+ * `include:` def.
51
+ *
52
+ * Stable only per pinned engine version: the service pins its `parseDef`/
53
+ * `hashDef` lineage to a specific commit (`VENDORED_SHA`). As of writing that
54
+ * commit is an ancestor of this repo's `HEAD` with no changes to
55
+ * `parseDef`/`buildDef`/`hashDef` in between, so a locally computed hash
56
+ * currently matches the server's — but a future engine default change could
57
+ * make them drift. A drifted hash reads as `changed`, not an error: pushing
58
+ * converges state, because the server's own idempotent `create_workflow`
59
+ * still recognizes byte-identical content and replies `unchanged: true`.
60
+ */
61
+ export declare function hashDefForHub(yaml: string): string;
62
+ /**
63
+ * Normalize a hub URL to a bare origin (`scheme://host[:port]`), stripping any
64
+ * path, query, trailing slash, and fragment. Requires an http(s) scheme. This
65
+ * is the credential-store key and the project binding value, so it must be
66
+ * canonical: `https://api.owenloop.com/` and `https://api.owenloop.com/foo`
67
+ * both key to `https://api.owenloop.com`.
68
+ *
69
+ * Transport policy (SEC-2): `https` is required for every hub origin EXCEPT the
70
+ * loopback hosts (`127.0.0.1`, `::1`, `localhost`), which may use `http` for
71
+ * local development. Remote `http` is rejected here, at normalization time, so a
72
+ * plaintext origin that would leak bearer/refresh tokens, auth codes, and
73
+ * workflow YAML to an on-path attacker can never be persisted into a credential
74
+ * key or a project binding.
75
+ */
76
+ export declare function normalizeOrigin(input: string): string;
77
+ /**
78
+ * Join an origin and an endpoint that may be absolute or a root-relative path,
79
+ * enforcing the same-origin policy for OAuth discovery metadata (SEC-4).
80
+ *
81
+ * This is the trust boundary for every endpoint consumed from OAuth metadata —
82
+ * authorization, token, and registration endpoints all flow through here, as do
83
+ * the CLI's own literal root-relative API paths. A metadata-derived absolute
84
+ * endpoint is allowed, but must resolve to the SAME origin as the hub; a
85
+ * cross-origin (or protocol-relative `//host`) endpoint is rejected so a
86
+ * discovered `token_endpoint` on a foreign origin can never receive a refresh
87
+ * token. Path and query are preserved — only `.origin` is compared. The
88
+ * https-except-loopback rule holds for free: `origin` here is already a
89
+ * `normalizeOrigin` output at every call site, so same-origin implies the
90
+ * transport policy.
91
+ */
92
+ export declare function resolveEndpoint(origin: string, endpoint: string): string;
93
+ /** URL-safe base64 with no padding (RFC 7636 §A). */
94
+ export declare function base64url(buf: Buffer): string;
95
+ export interface PkcePair {
96
+ verifier: string;
97
+ challenge: string;
98
+ }
99
+ /**
100
+ * Generate a PKCE verifier/challenge pair for the S256 method. The verifier is
101
+ * 32 random bytes base64url-encoded (43 chars — within the RFC's 43..128 range
102
+ * and drawn from the unreserved charset); the challenge is
103
+ * base64url(sha256(verifier)).
104
+ */
105
+ export declare function pkcePair(): PkcePair;
106
+ /** A random anti-CSRF `state` token for the authorization request. */
107
+ export declare function randomState(): string;
108
+ /**
109
+ * Stored per hub origin. Never logged or echoed. `oauth` carries a refreshable
110
+ * pair (loopback flow); `agent` is a pasted `olp_` token and `oauth-pasted` a
111
+ * pasted `mcpat_` access token — neither refreshes.
112
+ */
113
+ export type Credential = {
114
+ kind: 'oauth';
115
+ accessToken: string;
116
+ refreshToken: string;
117
+ expiresAt: number;
118
+ clientId: string;
119
+ } | {
120
+ kind: 'agent';
121
+ accessToken: string;
122
+ } | {
123
+ kind: 'oauth-pasted';
124
+ accessToken: string;
125
+ };
126
+ export interface CredentialFile {
127
+ version: 1;
128
+ hubs: Record<string, Credential>;
129
+ }
130
+ /** The user-level config dir (never the project dir). Derives from the caller's env. */
131
+ export declare function configDir(env: Record<string, string | undefined>): string;
132
+ export declare function credentialFilePath(env: Record<string, string | undefined>): string;
133
+ /** Read the credential file; a missing file is an empty store, not an error. */
134
+ export declare function readCredentialFile(path: string): CredentialFile;
135
+ /**
136
+ * Write `data` to `path` atomically, refusing a symlinked (or directory)
137
+ * destination (SEC-3).
138
+ *
139
+ * 1. `lstat` the destination: if it already exists AND is a symlink, throw a
140
+ * clear error naming the path rather than clobbering the arbitrary,
141
+ * possibly-privileged file the link points at. A pre-existing directory is
142
+ * likewise refused with a named error (instead of a raw ENOTDIR from
143
+ * rename).
144
+ * 2. Write to a temp file in the SAME directory (same-dir is required — a
145
+ * cross-filesystem rename is not atomic), then `chmod` the temp to `mode`
146
+ * BEFORE the rename so the final file never momentarily exists with a lax,
147
+ * umask-widened mode (preserving the old "re-chmod on every write"
148
+ * guarantee, now applied to the temp).
149
+ * 3. `rename(tmp, path)` — an atomic replace. On any failure after the temp
150
+ * exists, best-effort unlink the temp and rethrow.
151
+ *
152
+ * The `lstat` check is a courtesy clear-error, not the security boundary:
153
+ * `rename` replaces the destination inode rather than following it, so even a
154
+ * symlink raced into place between the `lstat` and the `rename` is replaced,
155
+ * never followed — the write can never escape to the link target.
156
+ */
157
+ export declare function writeFileAtomic(path: string, data: string, opts?: {
158
+ mode?: number;
159
+ }): void;
160
+ /**
161
+ * Write the credential file with strict permissions: dir 0700, file 0600.
162
+ * The file itself is written atomically via `writeFileAtomic` (temp + rename),
163
+ * which also chmods the temp to 0600 before the rename — so the secret is
164
+ * never visible under a laxer mode, even briefly, and a symlinked destination
165
+ * is refused (SEC-3).
166
+ */
167
+ export declare function writeCredentialFile(path: string, file: CredentialFile): void;
168
+ /**
169
+ * `.owenloop/hub.json` — written by `connect`. Safe to commit: contains no
170
+ * secrets, only the bound hub origin. Purely a binding — `push` diffs against
171
+ * server truth (`GET /api/workflows`), so there is no client-side ledger to
172
+ * carry here.
173
+ */
174
+ export interface HubBinding {
175
+ version: 1;
176
+ hub: string;
177
+ }
178
+ export declare function hubBindingPath(cwd: string): string;
179
+ /**
180
+ * Read `.owenloop/hub.json`; a missing file is `null` (project not bound
181
+ * yet). A file written by a pre-server-diff CLI may still carry a `pushed`
182
+ * key (the old push ledger) — it parses fine and the key is silently
183
+ * ignored; the next `connect` rewrite drops it.
184
+ */
185
+ export declare function readHubBinding(path: string): HubBinding | null;
186
+ export declare function writeHubBinding(path: string, binding: HubBinding): void;
187
+ /** A local def selected for a push, with its server-canonical content hash and raw source yaml. */
188
+ export interface DefPushCandidate {
189
+ name: string;
190
+ hash: string;
191
+ yaml: string;
192
+ }
193
+ /** One entry from `GET /api/workflows`'s `workflows` array. */
194
+ export interface WorkflowSummary {
195
+ name: string;
196
+ hash: string;
197
+ version?: number;
198
+ }
199
+ export interface ServerDiff<T extends {
200
+ name: string;
201
+ hash: string;
202
+ }> {
203
+ toPush: (T & {
204
+ status: 'new' | 'changed';
205
+ })[];
206
+ unchanged: T[];
207
+ }
208
+ /**
209
+ * Partition selected defs into those that need pushing vs. those already
210
+ * up-to-date, purely from the server's own `hash` for each name (from
211
+ * `GET /api/workflows`, via `parseWorkflowList`): a name absent from the
212
+ * server is `new`; present with a different (or missing) hash is `changed`;
213
+ * present with an equal hash is `unchanged` (skipped — no request sent).
214
+ *
215
+ * `force` pushes every candidate regardless of hash — labeled `new` when the
216
+ * server has no entry for it, `changed` otherwise (even when the hash is
217
+ * equal: force means "send it", and the label should still read true).
218
+ *
219
+ * Server names with no local counterpart are ignored (this is a push, not a
220
+ * sync — the CLI never deletes or reports on hub-only defs).
221
+ */
222
+ export declare function computeServerDiff<T extends {
223
+ name: string;
224
+ hash: string;
225
+ }>(candidates: T[], server: Map<string, WorkflowSummary>, force: boolean): ServerDiff<T>;
226
+ /** Success shape of `POST /api/create_workflow`. */
227
+ export interface CreateWorkflowOk {
228
+ ok: true;
229
+ name: string;
230
+ version: number;
231
+ hash: string;
232
+ /** `true` when the posted content's hash equals the latest stored version
233
+ * (server-side idempotent no-op) — no new version was minted. */
234
+ unchanged?: boolean;
235
+ }
236
+ /**
237
+ * `POST /api/create_workflow` returns HTTP 200 with `{ok:false,error}` on a
238
+ * def-parse failure (engine-version skew is the realistic cause) — so a 200 is
239
+ * NOT sufficient; the body's `ok` must be inspected. Returns the parsed error
240
+ * text (verbatim) when the reply is a failure, or `null` when it is a success.
241
+ */
242
+ export declare function createWorkflowError(body: unknown): string | null;
243
+ /**
244
+ * Narrow a create_workflow success body to its typed shape (after
245
+ * `createWorkflowError` returns null), validating STRICTLY (REL-9): a 2xx with
246
+ * `ok:true` is not enough — the identity fields must be present, well-typed, and
247
+ * consistent with the def that was pushed, or the "success" is a malformed
248
+ * response and must be treated as a failure, not silently coerced to defaults.
249
+ *
250
+ * - `name` must be a string equal to `expectedName` (the pushed def's name) —
251
+ * a mismatch means the server acknowledged the wrong workflow.
252
+ * - `version` must be a positive integer (the server mints versions from 1).
253
+ * - `hash` must be a non-empty string. Presence and type only: it is NOT
254
+ * required to equal the locally computed `hashDefForHub`, because engine
255
+ * drift between CLI and hub legitimately produces differing hashes (see
256
+ * `hashDefForHub`'s doc comment).
257
+ * - `unchanged: true` passes through as an idempotent no-op, validated by the
258
+ * same field rules.
259
+ *
260
+ * Throws a descriptive `Error` (mirroring `asWhoami`'s throw-on-malformed style)
261
+ * on any violation; the caller records it as a per-def failure.
262
+ */
263
+ export declare function asCreateWorkflowOk(body: unknown, expectedName: string): CreateWorkflowOk;
264
+ /**
265
+ * Identity returned by `GET /api/whoami` (bearer auth, no RBAC verb — a 200
266
+ * proves the credential authenticates, not that it carries any particular
267
+ * scope; `tokenStatus` is always `'active'` over the wire because a
268
+ * revoked/unknown/disabled credential 401s in auth middleware before the
269
+ * handler runs, so it is deliberately not carried here — branch on the HTTP
270
+ * status, never on a `tokenStatus` field).
271
+ */
272
+ export interface WhoamiIdentity {
273
+ orgId: string;
274
+ orgName: string;
275
+ actor: {
276
+ id: string;
277
+ kind: string;
278
+ role: string;
279
+ };
280
+ authMethod: string;
281
+ email?: string;
282
+ }
283
+ /** Narrow a `GET /api/whoami` 200 body to its typed shape. Throws on a malformed body. */
284
+ export declare function asWhoami(body: unknown): WhoamiIdentity;
285
+ /**
286
+ * Parse `GET /api/workflows`'s body into a `name -> WorkflowSummary` map for
287
+ * `computeServerDiff`. Throws a descriptive error (the caller wraps it in a
288
+ * `CliError`) on a missing/malformed `workflows` array.
289
+ */
290
+ export declare function parseWorkflowList(body: unknown): Map<string, WorkflowSummary>;