owenloop 0.4.0 → 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 +19 -0
- package/README.md +48 -2
- package/dist/add.d.ts +12 -40
- package/dist/add.js +11 -176
- package/dist/cli.d.ts +51 -2
- package/dist/cli.js +959 -325
- 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 +133 -0
- package/dist/hub.js +172 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- 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 +337 -4
- package/docs/design.md +86 -12
- package/docs/embedding.md +29 -5
- package/package.json +1 -1
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Credential WRITE + OAuth refresh library surface.
|
|
3
|
+
*
|
|
4
|
+
* Extracted from `src/cli.ts` (where these were module-private) so external
|
|
5
|
+
* consumers — a future `owenloop mcp` stdio server, an `owenwork join` command —
|
|
6
|
+
* can store credentials and keep an OAuth access token fresh without depending
|
|
7
|
+
* on the CLI module. The exported `storeCredential` / `deleteCredential` /
|
|
8
|
+
* `ensureFreshOAuth` are re-imported by `cli.ts`, so every existing subcommand
|
|
9
|
+
* keeps its exact behavior.
|
|
10
|
+
*
|
|
11
|
+
* **Concurrency safety (the reason this module exists):** the refresh-and-persist
|
|
12
|
+
* critical section is serialized by a lockfile next to the store
|
|
13
|
+
* (`~/.config/owenloop/credentials.lock`, via `src/lock.ts`). Multiple long-lived
|
|
14
|
+
* processes sharing one slot (the `mcp` server case) would otherwise race a
|
|
15
|
+
* refresh — both read the old refresh token, both rotate it server-side, and the
|
|
16
|
+
* loser persists a now-dead token, causing a silent logout an hour later. The
|
|
17
|
+
* lock turns "two refreshes race" into "the second process adopts the first's
|
|
18
|
+
* result": acquire → re-read the slot → adopt-or-refresh → persist → release.
|
|
19
|
+
*
|
|
20
|
+
* This module imports ONLY `hub.ts` (store internals), `util.ts` (`CliError`,
|
|
21
|
+
* `nowMs`), and `lock.ts` (node-builtin-only) — never `cli.ts`. That keeps the
|
|
22
|
+
* package barrel (`src/index.ts`) free of the CLI/add/untar runtime closure and
|
|
23
|
+
* avoids an import cycle.
|
|
24
|
+
*/
|
|
25
|
+
import type { Credential, CredentialSlotSelector, Keychain } from './hub.ts';
|
|
26
|
+
/**
|
|
27
|
+
* The dependencies the credential surface needs — a strict subset of the CLI's
|
|
28
|
+
* `CliIO`, which structurally satisfies this interface, so every `cli.ts` call
|
|
29
|
+
* site keeps passing its `io` unchanged. A library consumer constructs just
|
|
30
|
+
* `{ env: process.env }` (plus an optional keychain/fetch) without faking the
|
|
31
|
+
* CLI's `out`/`err`/`cwd`.
|
|
32
|
+
*/
|
|
33
|
+
export interface CredentialIO {
|
|
34
|
+
env: Record<string, string | undefined>;
|
|
35
|
+
/**
|
|
36
|
+
* OS keychain backend for credential storage. `undefined` — non-mac, or
|
|
37
|
+
* `OWENLOOP_NO_KEYCHAIN=1` — selects the file backend. A keychain write
|
|
38
|
+
* failure is a hard error, never a silent file fallback (REL-6).
|
|
39
|
+
*/
|
|
40
|
+
keychain?: Keychain;
|
|
41
|
+
/** Injectable for hermetic tests — the OAuth-refresh network calls use this. */
|
|
42
|
+
fetch?: typeof globalThis.fetch;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Store a credential for `origin` in `slot`, in the chosen backend ONLY;
|
|
46
|
+
* returns which one. Serialized by the credential lock so a plain write from
|
|
47
|
+
* `login` / `agent new` can never interleave with a refresh-and-persist.
|
|
48
|
+
*
|
|
49
|
+
* The external-command refusal runs BEFORE acquiring the lock: in that mode the
|
|
50
|
+
* command (not the local store) is authoritative, so a write is refused with no
|
|
51
|
+
* lockfile/config-dir side effect at all.
|
|
52
|
+
*
|
|
53
|
+
* Async because gaining the lock made it so — acceptable because this function
|
|
54
|
+
* was module-private before this change; the NEW public API is born async.
|
|
55
|
+
*/
|
|
56
|
+
export declare function storeCredential(io: CredentialIO, origin: string, slot: CredentialSlotSelector, cred: Credential): Promise<'keychain' | 'file'>;
|
|
57
|
+
/**
|
|
58
|
+
* Delete the stored credential for `(origin, slot)` from BOTH backends, under
|
|
59
|
+
* the credential lock so a logout can never interleave with a concurrent
|
|
60
|
+
* refresh-and-persist. Returns whether anything was removed. Async for the same
|
|
61
|
+
* born-with-the-lock reason as `storeCredential`.
|
|
62
|
+
*/
|
|
63
|
+
export declare function deleteCredential(io: CredentialIO, origin: string, slot: CredentialSlotSelector): Promise<boolean>;
|
|
64
|
+
/** The Bearer value for an authenticated request. Never logged. */
|
|
65
|
+
export declare function authHeader(cred: Credential): string;
|
|
66
|
+
export declare function hubMaxResponseBytes(io: CredentialIO): number;
|
|
67
|
+
/**
|
|
68
|
+
* Read a `Response` body into memory with a hard byte cap, streaming so an
|
|
69
|
+
* oversized body is rejected without first buffering the whole thing. Also used
|
|
70
|
+
* by the `add` tarball/sha fetches in `cli.ts` (which import it back), hence the
|
|
71
|
+
* `export`. `label` names the request in the error and is origin+path or
|
|
72
|
+
* `owner/repo@sha` only — never a token. Counting post-decode bytes (what lands
|
|
73
|
+
* in memory) is deliberate: the cap protects memory, not wire bytes.
|
|
74
|
+
*
|
|
75
|
+
* `res.body === null` (empty/no-body response) yields empty bytes, so callers
|
|
76
|
+
* behave exactly as they did under `arrayBuffer()`. An absent, malformed, or
|
|
77
|
+
* multi-valued `Content-Length` skips the header check — the counting path is
|
|
78
|
+
* the real guard (GitHub codeload tarballs are typically chunked, no header). A
|
|
79
|
+
* `TimeoutError`/`AbortError` from `read()` (the abort signal fired mid-body)
|
|
80
|
+
* propagates untouched, so each call site's existing timeout mapping still
|
|
81
|
+
* fires exactly as it did for `arrayBuffer()` rejections. `cancel()` may reject
|
|
82
|
+
* on an already-errored stream — swallowed; the cap `CliError` is the story.
|
|
83
|
+
*/
|
|
84
|
+
export declare function readBodyBounded(res: Response, cap: number, label: string): Promise<Uint8Array>;
|
|
85
|
+
/**
|
|
86
|
+
* `fetch` wrapper putting a deadline on every hub/auth call (REL-7). The abort
|
|
87
|
+
* signal is threaded into `fetch` AND the body is read (via `readBodyBounded`,
|
|
88
|
+
* which caps the response size — see HUB_MAX_RESPONSE_BYTES) inside the same
|
|
89
|
+
* try, so the deadline covers a stalled BODY read too — the exact undici
|
|
90
|
+
* behavior the two `add` fetches document (`AbortSignal.timeout` ties the
|
|
91
|
+
* signal to the body stream). The returned `Response` re-exposes the read
|
|
92
|
+
* body, so every call site's `res.json()` / `res.status` /
|
|
93
|
+
* `res.headers.get(...)` usage is byte-for-byte unchanged. A
|
|
94
|
+
* `TimeoutError`/`AbortError` becomes a clear `CliError` (naming the request,
|
|
95
|
+
* which is origin+path only — never a token); anything else is rethrown
|
|
96
|
+
* untouched.
|
|
97
|
+
*
|
|
98
|
+
* `redirect: 'error'` is forced on every call — after the `...init` spread, so
|
|
99
|
+
* no caller can override it — to close the redirect gap `resolveEndpoint`
|
|
100
|
+
* (SEC-4) cannot see: same-origin validation covers only the INITIAL URL, but a
|
|
101
|
+
* validated endpoint answering 307/308 would re-send the POST body (refresh
|
|
102
|
+
* token, PKCE verifier, auth code, workflow YAML) to a foreign origin — undici
|
|
103
|
+
* strips the Authorization header on a cross-origin redirect but RESENDS the
|
|
104
|
+
* body. The hub protocol has no redirects, so any 3xx is a hard, loud failure
|
|
105
|
+
* mapped to a `CliError` (again naming origin+path only, never a token).
|
|
106
|
+
*/
|
|
107
|
+
export declare function hubFetch(io: CredentialIO, url: string, init?: RequestInit): Promise<Response>;
|
|
108
|
+
interface AsMetadata {
|
|
109
|
+
authorization_endpoint?: string;
|
|
110
|
+
token_endpoint?: string;
|
|
111
|
+
registration_endpoint?: string;
|
|
112
|
+
}
|
|
113
|
+
export declare function discoverMetadata(io: CredentialIO, origin: string): Promise<AsMetadata>;
|
|
114
|
+
export declare function discoverTokenEndpoint(io: CredentialIO, origin: string): Promise<string>;
|
|
115
|
+
/**
|
|
116
|
+
* Ensure an `oauth` credential's access token is fresh: if it expires within
|
|
117
|
+
* 60s, refresh once (grant_type=refresh_token) and persist the new token. No-op
|
|
118
|
+
* for `agent`/`oauth-pasted` credentials (they don't refresh). Returns the
|
|
119
|
+
* possibly-updated credential.
|
|
120
|
+
*
|
|
121
|
+
* The `expiresAt - nowMs() > FRESH_WINDOW_MS` fast path is the cheap first check
|
|
122
|
+
* of a double-checked pattern: it returns WITHOUT locking; the re-read under the
|
|
123
|
+
* lock inside `refreshOAuth` is the second check.
|
|
124
|
+
*
|
|
125
|
+
* `slot` is the slot the credential was READ from — a refreshed token must be
|
|
126
|
+
* written back to that same slot, never to a default one.
|
|
127
|
+
*/
|
|
128
|
+
export declare function ensureFreshOAuth(io: CredentialIO, origin: string, slot: CredentialSlotSelector, cred: Credential, persist?: boolean): Promise<Credential>;
|
|
129
|
+
/**
|
|
130
|
+
* Refresh an `oauth` credential's access token.
|
|
131
|
+
*
|
|
132
|
+
* `persist` defaults to true — the normal case is refreshing an ALREADY stored,
|
|
133
|
+
* trusted credential (push/connect), where persisting immediately matters
|
|
134
|
+
* because refresh tokens can be single-use/rotating: losing the new one to a
|
|
135
|
+
* later crash would strand the user. `verifyCredential`'s login-time use passes
|
|
136
|
+
* `persist: false` — a not-yet-stored credential must never be written to
|
|
137
|
+
* disk/keychain before it is proven to work end to end.
|
|
138
|
+
*
|
|
139
|
+
* Two paths:
|
|
140
|
+
*
|
|
141
|
+
* - **Unlocked** (`persist: false`, i.e. login-time verify; OR an external
|
|
142
|
+
* credential command is configured): byte-for-byte the pre-lock behavior —
|
|
143
|
+
* refresh over HTTP, do NOT touch the store, do NOT lock, do NOT adopt.
|
|
144
|
+
* `persist: false` must never adopt a stored credential: the caller is
|
|
145
|
+
* verifying a specific not-yet-stored token, and handing back some other slot
|
|
146
|
+
* occupant would verify the WRONG credential. In external-command mode
|
|
147
|
+
* owenloop owns none of the credential lifecycle, so it neither locks nor
|
|
148
|
+
* persists (matching the old `persist && externalCredentialCommand ===
|
|
149
|
+
* undefined` gate).
|
|
150
|
+
*
|
|
151
|
+
* - **Locked** (`persist: true` and no external command): acquire the credential
|
|
152
|
+
* lock, RE-READ the slot, then decide:
|
|
153
|
+
* * stored is oauth AND its accessToken differs from ours AND it is fresh
|
|
154
|
+
* (> `FRESH_WINDOW_MS` from expiry) → another process already refreshed;
|
|
155
|
+
* adopt its credential with ZERO network calls and ZERO writes.
|
|
156
|
+
* * stored is oauth AND differs from ours but is NOT fresh → refresh using
|
|
157
|
+
* STORED as input (its refreshToken is the newest link in the rotation
|
|
158
|
+
* chain; ours is provably older), persist, return.
|
|
159
|
+
* * otherwise (stored same token, absent, or non-oauth) → refresh using
|
|
160
|
+
* `cred`, persist, return.
|
|
161
|
+
* Release the lock in `finally`.
|
|
162
|
+
*
|
|
163
|
+
* The `accessToken !== cred.accessToken` guard (not freshness alone) exists
|
|
164
|
+
* because `authedGet` calls this on a 401 with a token that may not be near
|
|
165
|
+
* expiry: freshness-only adoption would hand the caller back its own
|
|
166
|
+
* just-rejected token and turn a recoverable 401 into a hard failure.
|
|
167
|
+
* Token-differs ⇒ someone else moved the chain; token-same ⇒ we are first,
|
|
168
|
+
* refresh for real. The locked-section persist calls `storeCredentialUnlocked`
|
|
169
|
+
* (not the exported wrapper) — it already holds the lock.
|
|
170
|
+
*/
|
|
171
|
+
export declare function refreshOAuth(io: CredentialIO, origin: string, slot: CredentialSlotSelector, cred: Extract<Credential, {
|
|
172
|
+
kind: 'oauth';
|
|
173
|
+
}>, persist?: boolean): Promise<Credential>;
|
|
174
|
+
/**
|
|
175
|
+
* The result of `mintAgentCredential`. Deliberately carries NO token field —
|
|
176
|
+
* only non-secret handles the caller may print. The minted `olp_` plaintext is
|
|
177
|
+
* written to the credential store inside `mintAgentCredential` and never leaves
|
|
178
|
+
* it, so no caller can leak what it never received (§6 "rule of gates").
|
|
179
|
+
*/
|
|
180
|
+
export interface MintAgentResult {
|
|
181
|
+
/** Token id — a non-secret revocation handle. */
|
|
182
|
+
id: string;
|
|
183
|
+
/** The minted agent's id — a non-secret handle. */
|
|
184
|
+
agentId: string;
|
|
185
|
+
/** Resolved pool NAMES from the server. */
|
|
186
|
+
pools: string[];
|
|
187
|
+
/** Which local backend the token landed in. */
|
|
188
|
+
storage: 'keychain' | 'file';
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Mint a new agent identity on `origin` as the human `cred` and persist the
|
|
192
|
+
* returned `olp_` token to slot `agent:<name>`. CLI-free (no `Args`, no exit
|
|
193
|
+
* codes — the caller maps failures to exit codes) so both `owenloop agent new`
|
|
194
|
+
* (O3) and `owenloop mcp`'s `create_agent` (O2) can reuse it.
|
|
195
|
+
*
|
|
196
|
+
* **The token NEVER leaves this function.** It flows exactly one hop —
|
|
197
|
+
* `asMintAgentTokenOk(body).token` → `storeCredential` — and is never returned,
|
|
198
|
+
* thrown, logged, or embedded in any message (identity model §6). The returned
|
|
199
|
+
* `MintAgentResult` structurally omits it. The hub's 4xx `message` (e.g. H1's
|
|
200
|
+
* `agent name already taken: "…"`) is surfaced verbatim via `CliError`; a
|
|
201
|
+
* malformed 2xx names the offending FIELD only, never a value.
|
|
202
|
+
*
|
|
203
|
+
* Order is load-bearing (PR #69 lesson): the client-side name check and the
|
|
204
|
+
* external-command refusal both run BEFORE any network call. Refusing only at
|
|
205
|
+
* `storeCredential` time would mint a server-side token that can never be stored
|
|
206
|
+
* locally — permanently burning the agent name (re-running refuses "taken").
|
|
207
|
+
*
|
|
208
|
+
* @param humanSlot the slot `cred` was read from (always `{principal:'human'}`
|
|
209
|
+
* today; explicit for symmetry with the store/refresh signatures).
|
|
210
|
+
* @param params.scopes defaults to `['work']` — the H3 route REQUIRES a
|
|
211
|
+
* non-empty `scopes`; an empty list is server-refused.
|
|
212
|
+
* @param params.pools omitted when absent so the server defaults to the minter's
|
|
213
|
+
* personal pool (`pools: []` is server-refused with `pool_invalid`).
|
|
214
|
+
*/
|
|
215
|
+
export declare function mintAgentCredential(io: CredentialIO, origin: string, humanSlot: CredentialSlotSelector, cred: Credential, params: {
|
|
216
|
+
name: string;
|
|
217
|
+
pools?: string[];
|
|
218
|
+
scopes?: string[];
|
|
219
|
+
}): Promise<MintAgentResult>;
|
|
220
|
+
/**
|
|
221
|
+
* The result of `rekeyAgentCredential`. Like `MintAgentResult`, carries NO token
|
|
222
|
+
* field — only non-secret handles the caller may print. The new `olp_` plaintext
|
|
223
|
+
* is written to the store inside `rekeyAgentCredential` and never leaves it.
|
|
224
|
+
*
|
|
225
|
+
* `revokedTokenIds` are the ids the rekey invalidated server-side — the OLD
|
|
226
|
+
* installation's credential(s). Their presence is the honest signal that any
|
|
227
|
+
* still-running copy of this agent elsewhere is now disconnected. No `pools`
|
|
228
|
+
* field: rekey changes no pool membership.
|
|
229
|
+
*/
|
|
230
|
+
export interface RekeyAgentResult {
|
|
231
|
+
/** New token id — a non-secret revocation handle. */
|
|
232
|
+
id: string;
|
|
233
|
+
/** The rekeyed agent's id — a non-secret handle. */
|
|
234
|
+
agentId: string;
|
|
235
|
+
/** Ids of the tokens this rekey revoked (the old installation's). */
|
|
236
|
+
revokedTokenIds: string[];
|
|
237
|
+
/** The new token's scopes. */
|
|
238
|
+
scopes: string[];
|
|
239
|
+
/** Which local backend the new token landed in. */
|
|
240
|
+
storage: 'keychain' | 'file';
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Re-key an EXISTING agent identity on `origin` as the human `cred`: the hub
|
|
244
|
+
* mints a fresh `olp_` token for `agentId`, REVOKES the identity's current
|
|
245
|
+
* token(s), and this function persists the new token into the SAME
|
|
246
|
+
* `agent:<name>` slot — overwriting the old one. Sibling of
|
|
247
|
+
* `mintAgentCredential` with the identical §6 discipline; the only shape
|
|
248
|
+
* differences are the endpoint (`/api/rekey_agent_token`), the request body
|
|
249
|
+
* (`{agentId}` — no name/scopes/pools; rekey preserves pools), and the response
|
|
250
|
+
* guard (`asRekeyAgentTokenOk` — no `pools` field).
|
|
251
|
+
*
|
|
252
|
+
* **The token NEVER leaves this function.** It flows exactly one hop —
|
|
253
|
+
* `asRekeyAgentTokenOk(body).token` → `storeCredential` — and is never returned,
|
|
254
|
+
* thrown, logged, or embedded in any message. The returned `RekeyAgentResult`
|
|
255
|
+
* structurally omits it.
|
|
256
|
+
*
|
|
257
|
+
* **Irreversibility (why the caller must gate this behind a hard auth step):**
|
|
258
|
+
* a successful rekey has ALREADY revoked the old token server-side by the time
|
|
259
|
+
* this function returns. If the local `storeCredential` then fails, the old
|
|
260
|
+
* installation is disconnected AND the new token is unrecoverable locally — the
|
|
261
|
+
* error says exactly that and points at console Reconnect; it never prints the
|
|
262
|
+
* token as a fallback.
|
|
263
|
+
*
|
|
264
|
+
* @param humanSlot the slot `cred` was read from (always `{principal:'human'}`).
|
|
265
|
+
* @param params.agentId the identity to rekey (resolved by the caller from the
|
|
266
|
+
* `agent_identities` listing by NAME — names are org-unique).
|
|
267
|
+
* @param params.name the agent account name — the local slot `agent:<name>` the
|
|
268
|
+
* new token is written to. Validated before any I/O.
|
|
269
|
+
*/
|
|
270
|
+
export declare function rekeyAgentCredential(io: CredentialIO, origin: string, humanSlot: CredentialSlotSelector, cred: Credential, params: {
|
|
271
|
+
agentId: string;
|
|
272
|
+
name: string;
|
|
273
|
+
}): Promise<RekeyAgentResult>;
|
|
274
|
+
export {};
|