@eserstack/noskills-client 0.0.0-bootstrap.0 โ†’ 5.0.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/LICENSE ADDED
@@ -0,0 +1,13 @@
1
+ Copyright 2023-present Eser Ozvataf and other contributors.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,286 @@
1
+ # ๐Ÿ”Œ [@eserstack/noskills-client](./)
2
+
3
+ > **Note:** JSR is frozen at 4.5.x. From 5.0.0, `@eserstack/noskills-client` is
4
+ > published on npm under the same name (`pnpm add @eserstack/noskills-client`);
5
+ > the JSR versions stay available but get no updates.
6
+
7
+ > **eserstack Tool** ยท [eser/stack on GitHub](https://github.com/eser/stack) ยท
8
+ > **Install:** `pnpm add @eserstack/noskills-client`
9
+
10
+ `@eserstack/noskills-client` connects a browser app or a script to a running
11
+ [`noskills-server`](../../../cmd/noskills-server/README.md) daemon.
12
+ `NoskillsClient` calls the daemon's REST API: PIN login, projects, sessions and
13
+ Web Push subscriptions. `attachSession` opens a WebTransport stream to one
14
+ session; the daemon replays the session's ledger over it, then streams live
15
+ events, and you send commands back on the same stream.
16
+
17
+ ## Quick Start
18
+
19
+ Log in with the daemon's PIN, start a session in a registered project and print
20
+ the events it sends:
21
+
22
+ ```typescript
23
+ import * as noskillsClient from "@eserstack/noskills-client";
24
+
25
+ const config = { baseUrl: "https://localhost:4433" };
26
+ const client = noskillsClient.createNoskillsClient(config);
27
+
28
+ const { token } = await client.login("your_pin");
29
+ const { sessionId } = await client.createSession("your_project_slug");
30
+
31
+ const session = await noskillsClient.attachSession(
32
+ { ...config, token },
33
+ "your_project_slug",
34
+ sessionId,
35
+ );
36
+
37
+ for await (const event of session.events()) {
38
+ console.log(event.type);
39
+ }
40
+ ```
41
+
42
+ `attachSession` needs a runtime with a global `WebTransport`, such as a current
43
+ browser. The REST calls use the global `fetch`; outside a browser, pass a
44
+ `fetch` that speaks HTTP/3 as the second argument of `createNoskillsClient`.
45
+
46
+ ## REST Client
47
+
48
+ `createNoskillsClient(config, fetchFn?)` returns a `NoskillsClient`. `config`
49
+ takes `baseUrl`, and optionally the `token` from an earlier login, `certHashes`
50
+ for `attachSession` and `timeoutMs` for the REST calls. `login` stores the token
51
+ it receives, and every later call sends it as a Bearer token.
52
+
53
+ | Method | Request |
54
+ | ---------------------------------------------------- | -------------------------------------------------- |
55
+ | `setup(pin)` | `POST /auth/setup`: sets the daemon's PIN |
56
+ | `login(pin)` | `POST /auth/login`: returns `{ token, expiresAt }` |
57
+ | `logout()` | `POST /auth/logout`, then forgets the token |
58
+ | `setToken(token)`, `token` | Sets or reads the token, for one you stored |
59
+ | `health()` | `GET /api/health`: `{ version, uptime }` |
60
+ | `listProjects()` | `GET /api/projects` |
61
+ | `registerProject({ path?, git?, slug? })` | `POST /api/projects` |
62
+ | `deleteProject(slug)` | `DELETE /api/projects/{slug}` |
63
+ | `listSessions(slug)` | `GET /api/projects/{slug}/sessions` |
64
+ | `createSession(slug, { resumeFrom?, kind? })` | `POST /api/projects/{slug}/sessions` |
65
+ | `forkSession(slug, sessionId, atMessageId?, label?)` | `POST /api/projects/{slug}/sessions/{id}/fork` |
66
+ | `getSessionLineage(slug, sessionId)` | `GET /api/projects/{slug}/sessions/{id}/lineage` |
67
+ | `getVapidPublicKey()` | `GET /api/push/vapid-public-key` |
68
+ | `subscribePush(subscription, sessionFilter?)` | `POST /api/push/subscribe` |
69
+ | `unsubscribePush(subscriptionId)` | `DELETE /api/push/subscribe/{id}` |
70
+
71
+ `registerProject({ path })` takes an absolute path to an existing directory in
72
+ the daemon's workspace root, the home directory unless the daemon was started
73
+ with `--workspace-root`; the daemon answers 400 for any other path.
74
+
75
+ Slugs and ids in the path are percent-encoded. A response with an error status
76
+ throws a `NoskillsResponseError` with `method`, `path`, `status` and `detail`
77
+ (the response body), and a message of the form
78
+ `<method> <path> โ†’ <status>: <response body>`.
79
+
80
+ ### Time Limits and Cancellation
81
+
82
+ Every call waits 10 seconds for the daemon, or `config.timeoutMs` milliseconds
83
+ when you set it, and then throws a `NoskillsTimeoutError` that names the call.
84
+ `registerProject` with a `git` URL and no `path` waits 5 minutes (300 000 ms)
85
+ instead, because the daemon answers only after it has cloned the repository.
86
+
87
+ Each method that calls the daemon takes an optional last argument with a
88
+ `signal` that cancels the call and a `timeoutMs` for this call alone. A
89
+ cancelled call rejects with the signal's reason. Give a large repository more
90
+ time to clone:
91
+
92
+ ```typescript
93
+ import * as noskillsClient from "@eserstack/noskills-client";
94
+
95
+ const client = noskillsClient.createNoskillsClient({
96
+ baseUrl: "https://localhost:4433",
97
+ token: "your_token",
98
+ });
99
+
100
+ const project = await client.registerProject(
101
+ { git: "https://github.com/your_org/your_repo.git" },
102
+ { timeoutMs: 600_000 },
103
+ );
104
+ ```
105
+
106
+ ## Attaching to a Session
107
+
108
+ `attachSession(config, slug, sessionId, options?)` resolves to an
109
+ `AttachSession`:
110
+
111
+ | Member | Description |
112
+ | --------------- | ---------------------------------------------------------------- |
113
+ | `events()` | Async iterable of `DaemonEvent` objects, replay first, then live |
114
+ | `send(command)` | Sends a `ClientCommand`; throws once the session is closed |
115
+ | `close()` | Closes the stream and the WebTransport session |
116
+ | `lastSeq` | Sequence number of the last event received |
117
+
118
+ The options are `kind` (`"mux"` for a terminal-multiplexer session, otherwise an
119
+ agent session), `afterSeq`, `certHash`, `headers`, `signal` and `timeoutMs`. The
120
+ token travels in the query string, because the browser `WebTransport` API cannot
121
+ set headers.
122
+
123
+ The attach, from the fingerprint fetch to the open stream, takes at most 10
124
+ seconds, or `timeoutMs`, and then throws a `NoskillsTimeoutError`. `signal`
125
+ cancels it while it connects; once the session is attached, end it with
126
+ `close()`.
127
+
128
+ Answer the agent's permission requests as they arrive:
129
+
130
+ ```typescript
131
+ import * as noskillsClient from "@eserstack/noskills-client";
132
+
133
+ const session = await noskillsClient.attachSession(
134
+ { baseUrl: "https://localhost:4433", token: "your_token" },
135
+ "your_project_slug",
136
+ "your_session_id",
137
+ );
138
+
139
+ await session.send({ type: "user_message", content: "Run the tests" });
140
+
141
+ for await (const event of session.events()) {
142
+ if (event.type === "permission_request") {
143
+ await session.send({
144
+ type: "permission_response",
145
+ id: event.requestId,
146
+ decision: "allow",
147
+ });
148
+ }
149
+ }
150
+ ```
151
+
152
+ ### Events and Commands
153
+
154
+ Every event has a `type` and may carry the `seq` the daemon stamped on it:
155
+
156
+ - `transcript_replay_start` and `transcript_replay_end` bracket the ledger
157
+ replay; events in between are history.
158
+ - `sdk_event` carries model output: an Agent Client Protocol (ACP) session
159
+ update in `event`. Check `event.sessionUpdate` before you use it, since
160
+ ledgers written by older daemons hold other payloads.
161
+ - `permission_request` asks to run a tool; `permission_decision` records the
162
+ answer, and `permission_response_rejected` says the daemon refused one.
163
+ - `query_done` ends a turn, with `stopReason` when the agent reported one.
164
+ - `session_meta`, `client_count`, `fanout`, `fork_created`, `spawn_progress`,
165
+ `worker_ready`, `worker_died` and `error` report session state.
166
+ - `mux` carries a terminal-multiplexer frame in `frame`.
167
+ - `cert_rotating` is declared for certificate rotation; the daemon does not send
168
+ it yet.
169
+
170
+ The commands are `user_message`, `permission_response`, `stop`, `abort`,
171
+ `set_permission_mode`, `set_model` and `mux`. The daemon handles `stop` and
172
+ `abort` alike, and logs `set_model` as unsupported without acting on it.
173
+
174
+ A `permission_response` carries one of four decisions: `allow` for this call,
175
+ `allow_always` to keep allowing the tool, `deny` for this call, or
176
+ `deny_remember` to keep denying it. The daemon answers any other value with
177
+ `permission_response_rejected`.
178
+
179
+ ### Resuming After a Dropped Connection
180
+
181
+ Pass the `lastSeq` of the previous session as `afterSeq`, and the daemon skips
182
+ the events you already received:
183
+
184
+ ```typescript
185
+ import * as noskillsClient from "@eserstack/noskills-client";
186
+
187
+ const config = { baseUrl: "https://localhost:4433", token: "your_token" };
188
+ const first = await noskillsClient.attachSession(
189
+ config,
190
+ "your_project_slug",
191
+ "your_session_id",
192
+ );
193
+ // ... the connection drops ...
194
+ const resumed = await noskillsClient.attachSession(
195
+ config,
196
+ "your_project_slug",
197
+ "your_session_id",
198
+ { afterSeq: first.lastSeq },
199
+ );
200
+ ```
201
+
202
+ ## Certificate Pinning
203
+
204
+ By default the daemon serves a self-signed certificate. `attachSession` pins it
205
+ through WebTransport's `serverCertificateHashes`, taking the hashes from the
206
+ first of these that is set:
207
+
208
+ 1. the `certHash` option, one hash (`null` pins nothing and fetches nothing);
209
+ 2. every entry of `config.certHashes`, so a daemon that is rotating its
210
+ certificate can match either one;
211
+ 3. `getCertFingerprint(config.baseUrl)`.
212
+
213
+ Each hash is the 32-byte SHA-256 fingerprint of the certificate; a hash of
214
+ another length throws a `RangeError`. When the daemon has no fingerprint
215
+ endpoint, the stream opens without a pin, and the certificate has to be trusted
216
+ by the operating system, for example one made with mkcert.
217
+
218
+ | Function | Description |
219
+ | ----------------------------------------------- | ------------------------------------------------------------------------------------------- |
220
+ | `getCertFingerprint(baseUrl, options?)` | Returns the fingerprint cached for the daemon, or calls `fetchAndPinCertFingerprint` |
221
+ | `fetchAndPinCertFingerprint(baseUrl, options?)` | Fetches `GET /api/cert-fingerprint` (10 s limit), caches it, returns it as an `ArrayBuffer` |
222
+ | `storeCertFingerprint(baseUrl, hex)` | Writes a hex fingerprint to the IndexedDB cache for the daemon |
223
+ | `loadCertFingerprint(baseUrl)` | Reads the hex fingerprint cached for the daemon, or `null` |
224
+
225
+ The cache in IndexedDB holds one fingerprint per daemon, keyed by the origin of
226
+ its `baseUrl`. A fingerprint is 64 hex digits, optionally separated by colons or
227
+ spaces; `storeCertFingerprint` refuses anything else with a `RangeError`.
228
+
229
+ `fetchAndPinCertFingerprint` returns `null` only when the daemon answers 404,
230
+ meaning it has no fingerprint endpoint. It throws a `CertFingerprintError` (with
231
+ `url` and `status`) when the request fails, the endpoint answers another error
232
+ status, or the answer is not a SHA-256 fingerprint, and a `NoskillsTimeoutError`
233
+ when the daemon does not answer in time. `options` takes the same `signal` and
234
+ `timeoutMs` as the REST calls.
235
+
236
+ When the handshake fails with a cached fingerprint, `attachSession` fetches the
237
+ daemon's current one and, if the certificate changed, dials once more with it.
238
+ The daemon does not send `cert_rotating` yet; the event is declared to carry the
239
+ next fingerprint, which you would pass to
240
+ `storeCertFingerprint(baseUrl, event.newFingerprint)` before you attach again.
241
+
242
+ ## Upgrading from 4.x
243
+
244
+ These changes since 4.5.2 need a change in code, commands or files that use this
245
+ package. The [changelog](https://github.com/eser/stack/blob/main/CHANGELOG.md)
246
+ lists the changes in every package.
247
+
248
+ - `storeCertFingerprint` and `loadCertFingerprint` take the daemon's base URL.
249
+ Entries cached under the old `active` key are not read; the next attach
250
+ fetches the fingerprint again:
251
+
252
+ ```typescript
253
+ import * as noskillsClient from "@eserstack/noskills-client";
254
+
255
+ // Before: await noskillsClient.storeCertFingerprint(fingerprint);
256
+ await noskillsClient.storeCertFingerprint(
257
+ "https://localhost:4433",
258
+ fingerprint,
259
+ );
260
+ ```
261
+
262
+ - `fetchAndPinCertFingerprint` and `getCertFingerprint` return `null` only when
263
+ the daemon answers 404. A network error, another error status, a body that is
264
+ not JSON or an invalid fingerprint throws `CertFingerprintError`, and a
265
+ timeout throws `NoskillsTimeoutError`. Catch these where `null` used to mean
266
+ "no pin".
267
+ - `storeCertFingerprint` throws `RangeError` for a value that is not 64 hex
268
+ digits (colons and spaces are allowed), and `attachSession` for a `certHash`
269
+ or `config.certHashes` entry that is not 32 bytes. Pass real SHA-256
270
+ fingerprints.
271
+ - `attachSession` pins every `config.certHashes` entry, not only the first. Drop
272
+ old hashes from the list if they must not be accepted any more.
273
+ - REST calls time out after 10 s (`registerProject` with a git URL: 300 s), and
274
+ `attachSession` after 10 s, with `NoskillsTimeoutError`; they had no limit.
275
+ Set `config.timeoutMs`, or pass `{ timeoutMs }` per call or in
276
+ `AttachOptions`.
277
+
278
+ ## ๐Ÿ”— Links
279
+
280
+ - [eser/stack on GitHub](https://github.com/eser/stack)
281
+ - [`noskills-server`](../../../cmd/noskills-server/README.md): the daemon this
282
+ client talks to
283
+ - [`@eserstack/webtransport`](../webtransport/README.md): the WebTransport
284
+ client `attachSession` uses
285
+ - [`@eserstack/mux`](../mux/): the multiplexer protocol inside `mux` events and
286
+ commands
@@ -0,0 +1,85 @@
1
+ import type { AttachSession, NoskillsClientConfig } from "./types.ts";
2
+ /** Options for {@link attachSession}. */
3
+ export interface AttachOptions {
4
+ /**
5
+ * One SHA-256 certificate fingerprint (32 bytes) to pin in place of
6
+ * `config.certHashes`. `null` pins nothing and fetches nothing, for a
7
+ * certificate the operating system trusts. If omitted, the attach pins
8
+ * `config.certHashes`, or else calls getCertFingerprint(config.baseUrl)
9
+ * (fetches daemon endpoint + caches in IndexedDB).
10
+ */
11
+ certHash?: ArrayBuffer | null;
12
+ /**
13
+ * Additional headers sent on the WebTransport CONNECT request.
14
+ * Most useful for passing the token on non-browser platforms; browsers
15
+ * can't set arbitrary headers on WebTransport so use ?token= instead.
16
+ */
17
+ headers?: Record<string, string>;
18
+ /**
19
+ * Resume from this sequence number (the lastSeq of a previous AttachSession).
20
+ * The server will skip ledger replay events whose seq โ‰ค afterSeq, sending
21
+ * only new events. Use this after a network partition to avoid re-receiving
22
+ * events the client already processed.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * import * as noskillsClient from "@eserstack/noskills-client";
27
+ *
28
+ * const config = { baseUrl: "https://localhost:4433", token: "your_token" };
29
+ * let session = await noskillsClient.attachSession(config, "your_project_slug", "your_session_id");
30
+ * // ... network drop ...
31
+ * session = await noskillsClient.attachSession(config, "your_project_slug", "your_session_id", {
32
+ * afterSeq: session.lastSeq,
33
+ * });
34
+ * ```
35
+ */
36
+ afterSeq?: number;
37
+ /**
38
+ * Worker flavour to attach with โ€” must match the session's `kind` (sent as
39
+ * `?kind=` so the daemon spawns the right worker on first attach). Use "mux"
40
+ * for a terminal-multiplexer session; omit (or "agent"/"acp") for an agent
41
+ * session, which is served by the ACP worker.
42
+ */
43
+ kind?: "agent" | "acp" | "mux";
44
+ /**
45
+ * Cancels the attach while it fetches the fingerprint, dials and opens the
46
+ * stream; the promise then rejects with the signal's reason. It does not
47
+ * close a session that is already attached: call `close()` for that.
48
+ */
49
+ signal?: AbortSignal;
50
+ /**
51
+ * Milliseconds the whole attach may take, the fingerprint fetch, the
52
+ * WebTransport handshake and the stream included, before it throws
53
+ * `NoskillsTimeoutError`. Defaults to 10 000.
54
+ */
55
+ timeoutMs?: number;
56
+ }
57
+ /**
58
+ * Attach to a running session on the daemon.
59
+ *
60
+ * Opens a WebTransport bidi stream to /attach/{slug}/{sessionId}?token={token}.
61
+ * The token is appended as a query parameter because browser WebTransport does
62
+ * not support custom headers; the daemon's PIN auth middleware reads it there.
63
+ *
64
+ * Without a configured pin, the attach pins the fingerprint cached for the
65
+ * daemon. When the handshake fails with that pin, it asks the daemon for its
66
+ * current fingerprint and, if the certificate changed, dials once more.
67
+ *
68
+ * @throws {NoskillsTimeoutError} When the attach takes longer than
69
+ * `timeoutMs` (10 000 by default).
70
+ *
71
+ * @example
72
+ * ```ts
73
+ * import * as noskillsClient from "@eserstack/noskills-client";
74
+ *
75
+ * const session = await noskillsClient.attachSession(
76
+ * { baseUrl: "https://localhost:4433", token: "your_token" },
77
+ * "your_project_slug",
78
+ * "your_session_id",
79
+ * );
80
+ * for await (const evt of session.events()) {
81
+ * if (evt.type === "query_done") break;
82
+ * }
83
+ * ```
84
+ */
85
+ export declare function attachSession(config: NoskillsClientConfig, slug: string, sessionId: string, opts?: AttachOptions): Promise<AttachSession>;
package/dist/attach.js ADDED
@@ -0,0 +1,234 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * WebTransport session attach for noskills-client.
4
+ *
5
+ * Opens a bidi stream to /attach/{slug}/{sessionId} on the daemon and
6
+ * exposes a typed async-iterable event stream plus a send() helper.
7
+ *
8
+ * The daemon replays the JSONL ledger first (transcript_replay_start โ€ฆ
9
+ * transcript_replay_end) then enters live mode. The caller iterates
10
+ * events() and renders them in sequence โ€” no distinction needed between
11
+ * replay and live; the marker events are included for UI progress if wanted.
12
+ *
13
+ * On cert_rotating: stop iteration, call storeCertFingerprint(baseUrl,
14
+ * newFingerprint), then attach again.
15
+ *
16
+ * @module
17
+ */
18
+ import * as webtransport from "@eserstack/webtransport";
19
+ import * as cert from "./cert.js";
20
+ import * as deadline from "./deadline.js";
21
+ const ATTACH_TIMEOUT_MS = 10_000;
22
+ const SHA256_BYTES = 32;
23
+ // =============================================================================
24
+ // Line-delimited JSON reader over a bidi stream
25
+ // =============================================================================
26
+ async function* readLines(readable) {
27
+ const reader = readable.getReader();
28
+ const decoder = new TextDecoder();
29
+ let buf = "";
30
+ try {
31
+ while (true) {
32
+ // A stream reader hands out chunks in order, one read at a time.
33
+ // oxlint-disable-next-line no-await-in-loop
34
+ const { value, done } = await reader.read();
35
+ if (done)
36
+ break;
37
+ buf += decoder.decode(value, { stream: true });
38
+ let nl;
39
+ while ((nl = buf.indexOf("\n")) !== -1) {
40
+ const line = buf.slice(0, nl).trimEnd();
41
+ buf = buf.slice(nl + 1);
42
+ if (line.length > 0) {
43
+ yield line;
44
+ }
45
+ }
46
+ }
47
+ // Flush any remaining partial line (shouldn't happen in NDJSON but be safe)
48
+ const remaining = buf.trimEnd();
49
+ if (remaining.length > 0) {
50
+ yield remaining;
51
+ }
52
+ }
53
+ finally {
54
+ reader.releaseLock();
55
+ }
56
+ }
57
+ // =============================================================================
58
+ // AttachSession implementation
59
+ // =============================================================================
60
+ class AttachSessionImpl {
61
+ #session;
62
+ #stream;
63
+ #writer;
64
+ #encoder;
65
+ #closed = false;
66
+ #lastSeq = 0;
67
+ constructor(session, stream) {
68
+ this.#session = session;
69
+ this.#stream = stream;
70
+ this.#writer = stream.writable.getWriter();
71
+ this.#encoder = new TextEncoder();
72
+ }
73
+ get lastSeq() {
74
+ return this.#lastSeq;
75
+ }
76
+ async *events() {
77
+ for await (const line of readLines(this.#stream.readable)) {
78
+ let evt;
79
+ try {
80
+ evt = JSON.parse(line);
81
+ }
82
+ catch {
83
+ // A line that is not JSON is skipped rather than ending the stream.
84
+ continue;
85
+ }
86
+ if (typeof evt.seq === "number") {
87
+ this.#lastSeq = evt.seq;
88
+ }
89
+ yield evt;
90
+ }
91
+ }
92
+ async send(cmd) {
93
+ if (this.#closed) {
94
+ throw new Error("AttachSession is closed");
95
+ }
96
+ const line = JSON.stringify(cmd) + "\n";
97
+ await this.#writer.write(this.#encoder.encode(line));
98
+ }
99
+ close() {
100
+ if (this.#closed)
101
+ return;
102
+ this.#closed = true;
103
+ this.#writer.releaseLock();
104
+ this.#session.close();
105
+ }
106
+ }
107
+ /** Checks that a configured pin has the size of a SHA-256 fingerprint. */
108
+ function checkPin(hash, name) {
109
+ if (hash.byteLength !== SHA256_BYTES) {
110
+ throw new RangeError(`${name} is ${hash.byteLength} bytes; a SHA-256 certificate fingerprint is ${SHA256_BYTES} bytes`);
111
+ }
112
+ return hash;
113
+ }
114
+ /**
115
+ * The pins the caller configured: every `config.certHashes` entry, the
116
+ * `certHash` option in their place, or `[]` for `certHash: null`. Returns null
117
+ * when nothing is configured and the daemon has to be asked.
118
+ */
119
+ function configuredPins(config, opts) {
120
+ if (opts.certHash === null) {
121
+ return [];
122
+ }
123
+ if (opts.certHash !== undefined) {
124
+ return [checkPin(opts.certHash, "the certHash option")];
125
+ }
126
+ if (config.certHashes !== undefined && config.certHashes.length > 0) {
127
+ return config.certHashes.map((hash, index) => checkPin(hash, `config.certHashes[${index}]`));
128
+ }
129
+ return null;
130
+ }
131
+ function sameBytes(a, b) {
132
+ const left = new Uint8Array(a);
133
+ const right = new Uint8Array(b);
134
+ return (left.length === right.length &&
135
+ left.every((byte, index) => byte === right[index]));
136
+ }
137
+ /** Dials the daemon with `pins` and opens the session's bidi stream. */
138
+ async function dial(config, pins, path, headers, timeoutMs, signal) {
139
+ const wtClient = webtransport.createWebTransportClient({
140
+ baseUrl: config.baseUrl,
141
+ certHashes: pins.length > 0 ? [...pins] : undefined,
142
+ // connect() takes no signal, so a handshake the attach gave up on is
143
+ // closed by this limit instead.
144
+ dialTimeout: timeoutMs,
145
+ });
146
+ const wtSession = await deadline.raceSignal(wtClient.connect(path, headers), signal, (late) => late.close());
147
+ try {
148
+ const stream = await deadline.raceSignal(wtSession.openBidirectionalStream(), signal, () => { });
149
+ return new AttachSessionImpl(wtSession, stream);
150
+ }
151
+ catch (error) {
152
+ wtSession.close();
153
+ throw error;
154
+ }
155
+ }
156
+ /**
157
+ * Attach to a running session on the daemon.
158
+ *
159
+ * Opens a WebTransport bidi stream to /attach/{slug}/{sessionId}?token={token}.
160
+ * The token is appended as a query parameter because browser WebTransport does
161
+ * not support custom headers; the daemon's PIN auth middleware reads it there.
162
+ *
163
+ * Without a configured pin, the attach pins the fingerprint cached for the
164
+ * daemon. When the handshake fails with that pin, it asks the daemon for its
165
+ * current fingerprint and, if the certificate changed, dials once more.
166
+ *
167
+ * @throws {NoskillsTimeoutError} When the attach takes longer than
168
+ * `timeoutMs` (10 000 by default).
169
+ *
170
+ * @example
171
+ * ```ts
172
+ * import * as noskillsClient from "@eserstack/noskills-client";
173
+ *
174
+ * const session = await noskillsClient.attachSession(
175
+ * { baseUrl: "https://localhost:4433", token: "your_token" },
176
+ * "your_project_slug",
177
+ * "your_session_id",
178
+ * );
179
+ * for await (const evt of session.events()) {
180
+ * if (evt.type === "query_done") break;
181
+ * }
182
+ * ```
183
+ */
184
+ export async function attachSession(config, slug, sessionId, opts = {}) {
185
+ const timeoutMs = opts.timeoutMs ?? ATTACH_TIMEOUT_MS;
186
+ const pins = configuredPins(config, opts);
187
+ // Build query string: token and after go here because browser WebTransport
188
+ // cannot set custom headers on the CONNECT request.
189
+ const params = new URLSearchParams();
190
+ if (config.token !== undefined && config.token !== "") {
191
+ params.set("token", config.token);
192
+ }
193
+ if (opts.afterSeq !== undefined && opts.afterSeq > 0) {
194
+ params.set("after", String(opts.afterSeq));
195
+ }
196
+ if (opts.kind !== undefined) {
197
+ params.set("kind", opts.kind);
198
+ }
199
+ const query = params.size > 0 ? `?${params.toString()}` : "";
200
+ const path = `/attach/${encodeURIComponent(slug)}/${encodeURIComponent(sessionId)}${query}`;
201
+ return await deadline.withDeadline(`attach ${slug}/${sessionId}`, timeoutMs, opts.signal, async (signal) => {
202
+ if (pins !== null) {
203
+ return await dial(config, pins, path, opts.headers, timeoutMs, signal);
204
+ }
205
+ const fetchOptions = { signal, timeoutMs };
206
+ const pin = await cert.getCertFingerprint(config.baseUrl, fetchOptions);
207
+ if (pin === null) {
208
+ return await dial(config, [], path, opts.headers, timeoutMs, signal);
209
+ }
210
+ try {
211
+ return await dial(config, [pin], path, opts.headers, timeoutMs, signal);
212
+ }
213
+ catch (error) {
214
+ if (signal.aborted) {
215
+ throw error;
216
+ }
217
+ // The pin may be stale: the daemon can have a new certificate since
218
+ // it was cached. Ask for the current one and dial again if it changed.
219
+ let current;
220
+ try {
221
+ current = await cert.fetchAndPinCertFingerprint(config.baseUrl, fetchOptions);
222
+ }
223
+ catch {
224
+ // The daemon cannot report a fingerprint either; the dial error
225
+ // says why the attach failed.
226
+ throw error;
227
+ }
228
+ if (current === null || sameBytes(current, pin)) {
229
+ throw error;
230
+ }
231
+ return await dial(config, [current], path, opts.headers, timeoutMs, signal);
232
+ }
233
+ }, (late) => late.close());
234
+ }
package/dist/cert.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Cert fingerprint helpers for noskills-client.
3
+ *
4
+ * Fetches GET /api/cert-fingerprint (unauthenticated) and caches the result in
5
+ * IndexedDB, keyed by the origin of the daemon's base URL, so WebTransport
6
+ * clients can pin each daemon's self-signed leaf cert via
7
+ * serverCertificateHashes. This bypasses OS CA trust entirely, which is the
8
+ * only option on iOS Safari 16.4+ for PWA mode.
9
+ *
10
+ * When the daemon emits a {type:"cert_rotating", newFingerprint} event, call
11
+ * storeCertFingerprint(baseUrl, newFingerprint), then attach again.
12
+ *
13
+ * @module
14
+ */
15
+ import type { CallOptions } from "./types.ts";
16
+ /**
17
+ * Persist the hex fingerprint of the daemon at `baseUrl` to IndexedDB, in
18
+ * place of the one stored for the same origin.
19
+ *
20
+ * @throws {RangeError} When `fingerprint` is not a SHA-256 fingerprint.
21
+ */
22
+ export declare function storeCertFingerprint(baseUrl: string, fingerprint: string): Promise<void>;
23
+ /**
24
+ * Load the hex fingerprint stored for the daemon at `baseUrl` from IndexedDB.
25
+ * Returns null if that origin has none.
26
+ */
27
+ export declare function loadCertFingerprint(baseUrl: string): Promise<string | null>;
28
+ /**
29
+ * Fetch the current daemon TLS fingerprint from GET /api/cert-fingerprint,
30
+ * store it in IndexedDB and return it as an ArrayBuffer for WebTransport.
31
+ *
32
+ * Returns null when the daemon has no fingerprint endpoint (a 404): its
33
+ * certificate is one the operating system trusts, such as mkcert's, and there
34
+ * is nothing to pin. The request waits 10 000 ms unless `options.timeoutMs`
35
+ * says otherwise.
36
+ *
37
+ * @throws {CertFingerprintError} When the request fails, the endpoint answers
38
+ * with another error status, or the answer is not a SHA-256 fingerprint.
39
+ * @throws {NoskillsTimeoutError} When the daemon does not answer in time.
40
+ */
41
+ export declare function fetchAndPinCertFingerprint(baseUrl: string, options?: CallOptions): Promise<ArrayBuffer | null>;
42
+ /**
43
+ * Return the fingerprint cached for the daemon at `baseUrl`, or fetch it with
44
+ * fetchAndPinCertFingerprint when there is none or IndexedDB is unavailable.
45
+ * Use this on reconnect to avoid a round-trip when the cert is still valid;
46
+ * attachSession refetches by itself when a cached pin stops matching.
47
+ */
48
+ export declare function getCertFingerprint(baseUrl: string, options?: CallOptions): Promise<ArrayBuffer | null>;