@byollm/protocol 0.1.0-alpha.10 → 0.1.0-alpha.100
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/ABOUT-SHORT.md +7 -0
- package/ABOUT.md +60 -0
- package/README.md +120 -4
- package/dist/chunk-J3HTAGMX.js +242 -0
- package/dist/chunk-J3HTAGMX.js.map +1 -0
- package/dist/index.d.ts +2666 -1532
- package/dist/index.js +1937 -550
- package/dist/index.js.map +1 -1
- package/dist/portable-C6rfiCXi.d.ts +511 -0
- package/dist/portable.d.ts +2 -0
- package/dist/portable.js +45 -0
- package/dist/portable.js.map +1 -0
- package/package.json +8 -2
package/ABOUT-SHORT.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
BYOLLM – Bring Your Own LLM – lets you use your own AI on websites you authorize. A small program installed on your machine lets you use your own models and subscriptions on any BYOLLM-integrated site, including new models the moment you get access – no site updates required. BYOLLM Cloud connects sites to your devices with end-to-end encryption, so no one, including us, can see your data.
|
|
2
|
+
|
|
3
|
+
<!-- lede ends here. Surfaces with room show the tail below; the welcome screen shows the lede only. -->
|
|
4
|
+
|
|
5
|
+
Sites can charge you less because you bring your own – see why that matters →. Teams can optionally share the free or metered services on their devices with people they name. Personal subscriptions are never shared.
|
|
6
|
+
|
|
7
|
+
**Learn more →**
|
package/ABOUT.md
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# About BYOLLM
|
|
2
|
+
|
|
3
|
+
**What BYOLLM is**
|
|
4
|
+
|
|
5
|
+
BYOLLM lets you use your own AI on websites. You install one small program on
|
|
6
|
+
your computer. Then, websites that support BYOLLM can use the AI you already
|
|
7
|
+
have — a free model running on your machine, or an AI service you already pay
|
|
8
|
+
for — instead of the website paying for AI and passing the cost to you.
|
|
9
|
+
|
|
10
|
+
**Why it matters**
|
|
11
|
+
|
|
12
|
+
For you:
|
|
13
|
+
|
|
14
|
+
- Your favorite model, everywhere you go.
|
|
15
|
+
- New models the moment you get them – not when a site gets around to adding
|
|
16
|
+
them.
|
|
17
|
+
- Encrypted end-to-end. Your prompts go to your own device; byollm.cloud can't
|
|
18
|
+
read them.
|
|
19
|
+
- Sites never learn which model you use, and your subscriptions are never
|
|
20
|
+
shared.
|
|
21
|
+
- Pay less. Sites that don't pay for AI can charge you less – or nothing.
|
|
22
|
+
|
|
23
|
+
For sites and developers:
|
|
24
|
+
|
|
25
|
+
- Zero AI bills. Your users bring their own compute.
|
|
26
|
+
- No floating money – you don't pay LLM bills up front and hope to collect
|
|
27
|
+
later, and you never ask people to prepay just to try you.
|
|
28
|
+
- Free trials that cost you nothing to offer.
|
|
29
|
+
- Ship the AI features you kept private for fear of the API bill.
|
|
30
|
+
- One small integration. Your users choose the models.
|
|
31
|
+
|
|
32
|
+
**Your device**
|
|
33
|
+
|
|
34
|
+
The `byollm` program runs on your computer. It knows which AI services you have
|
|
35
|
+
set up: free open-source models on your machine, metered services you pay per
|
|
36
|
+
use, or your own subscriptions like Claude Pro/Max. When a website you have
|
|
37
|
+
enabled sends work, your device runs it with the service you chose. Your
|
|
38
|
+
prompts are encrypted end-to-end to your own device. byollm.cloud passes them
|
|
39
|
+
along and cannot read them.
|
|
40
|
+
|
|
41
|
+
**Sites**
|
|
42
|
+
|
|
43
|
+
A website that wants to use BYOLLM says what it needs — "writing help," "chat,"
|
|
44
|
+
and so on. When you connect the site, you pick which of your services answers
|
|
45
|
+
each one. The site never learns which model you use. You can turn a site off at
|
|
46
|
+
any time, and it stops getting your work.
|
|
47
|
+
|
|
48
|
+
**Teams (optional)**
|
|
49
|
+
|
|
50
|
+
A team lets you share what runs on your devices with people you name — the free
|
|
51
|
+
open-source models on your machine, or a metered service with a spending limit
|
|
52
|
+
you set. Your subscription accounts (like Claude Pro/Max) are never shared with
|
|
53
|
+
anyone. That is a rule, not a setting.
|
|
54
|
+
|
|
55
|
+
**byollm.cloud (or your own relay)**
|
|
56
|
+
|
|
57
|
+
Many sites, many devices, many people. byollm.cloud keeps track of who has
|
|
58
|
+
allowed what and sends each job to the right device. It never sees your
|
|
59
|
+
prompts. If you would rather run this part yourself, the relay is open source —
|
|
60
|
+
you can run your own instead of using byollm.cloud.
|
package/README.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
> [!WARNING]
|
|
2
|
-
> **Alpha (`0.1.0-alpha.
|
|
2
|
+
> **Alpha (`0.1.0-alpha.100`) — under active development. Don't use this yet.**
|
|
3
3
|
>
|
|
4
4
|
> Install it deliberately: `npm install @byollm/protocol@alpha`.
|
|
5
5
|
>
|
|
@@ -11,12 +11,114 @@
|
|
|
11
11
|
> npm assigns `latest` on a first publish and won't let it be removed, so a
|
|
12
12
|
> bare install resolves here too. This notice is the only guard — deliberately
|
|
13
13
|
> not an npm deprecation, which would read as *abandoned* rather than *early*.
|
|
14
|
-
> Ask for `@alpha` explicitly so your lockfile records that you meant to
|
|
14
|
+
> Ask for `@alpha` explicitly so your lockfile records that you meant to.>
|
|
15
|
+
> **`alpha.15` is a breaking wire change, and it breaks daemons and relays —
|
|
16
|
+
> not app authors.** If you call `app.enqueue(...)` and read results, nothing
|
|
17
|
+
> in your code changes. If you run a daemon or an upstream, every package must
|
|
18
|
+
> move together: a mixed pair refuses on both sides, because both ends parse
|
|
19
|
+
> `.strict()`.
|
|
20
|
+
>
|
|
21
|
+
> What moved, all of it reconciling the frozen `byollm_009` with its code:
|
|
22
|
+
> `JobStub` gains `site` (the site's identity key id) and loses
|
|
23
|
+
> `audienceAllow`; `ResultRequest` gains `leaseId`; `HeartbeatResponse` loses
|
|
24
|
+
> `leases`, which nothing read; `WireErrorCode` gains `not-ready`,
|
|
25
|
+
> `clock-skew` and `forbidden`, and `403` is `forbidden` rather than
|
|
26
|
+
> `unauthorized`. `RESULT_PROVENANCE` is superseded by
|
|
27
|
+
> `PROVENANCE_NAMES_DEVICE`. See `byollm_009` Amendment A.>
|
|
28
|
+
> **`alpha.16` is a breaking wire change — daemons and relays again, not app
|
|
29
|
+
> authors.** `app.enqueue(...)` and reading results are unchanged. All five
|
|
30
|
+
> packages move together: both ends parse `.strict()`, so a mixed pair
|
|
31
|
+
> refuses.
|
|
32
|
+
>
|
|
33
|
+
> What moved, all of it Tier 2 of `cloud_008`: `model`, `backendClass` and
|
|
34
|
+
> `durationMs` come off `ResultRequest` and are sealed **inside** the result
|
|
35
|
+
> envelope as `SealedOutcome = { outcome, ran }` — so a daemon can no longer
|
|
36
|
+
> declare a model it did not sign, and a relay carries neither.
|
|
37
|
+
> `HeartbeatResponse` loses `leases` (nothing read it) and now reports real
|
|
38
|
+
> cancellations instead of an empty list. `WireErrorCode` gains `forbidden`
|
|
39
|
+
> for 403, leaving `unauthorized` at exactly 401. The relay gained a
|
|
40
|
+
> site-plane `cancel` endpoint, honours `stub.deadlineAt`, honours
|
|
41
|
+
> `stub.audience`, and remembers a refusal.>
|
|
42
|
+
> **`alpha.17` is additive** — no wire change. It exports `ReleaseReason`,
|
|
43
|
+
> which `RoutingStore.releaseLeases` names and the package did not export, so
|
|
44
|
+
> the interface was unimplementable outside this repo.>
|
|
45
|
+
> **`alpha.18` is a breaking wire change — daemons and relays, not app
|
|
46
|
+
> authors.** `app.enqueue(...)` and reading results are unchanged. All five
|
|
47
|
+
> packages move together.
|
|
48
|
+
>
|
|
49
|
+
> The **bearer token is gone**: off `PairPollResponse`, off the runner row,
|
|
50
|
+
> off the daemon's pairings file, out of the adapter's schema. It was minted,
|
|
51
|
+
> hashed and stored on two disks and never sent, looked up or compared —
|
|
52
|
+
> `REQUESTS_SIGNED_NOT_BEARER` was enforced by signatures the whole time. If
|
|
53
|
+
> you run the Supabase adapter, apply
|
|
54
|
+
> `20260819000000_drop_runner_token.sql`; `byollm_approve_pairing` now takes
|
|
55
|
+
> one argument. A pairings file written by an older daemon still loads.
|
|
56
|
+
>
|
|
57
|
+
> `model`, `backendClass` and `durationMs` moved **inside** the sealed result
|
|
58
|
+
> (`SealedOutcome = { outcome, ran }`), so a daemon cannot declare a model it
|
|
59
|
+
> did not sign and a relay carries none of them. Writing a `RoutingStore`?
|
|
60
|
+
> `releaseLeases` takes an optional `reason` and `complete` requires
|
|
61
|
+
> `leaseId`, and **an implementation that ignores either still typechecks** —
|
|
62
|
+
> run the store contract tests.>
|
|
63
|
+
> **`alpha.19` is additive on the wire and a behaviour change in every
|
|
64
|
+
> store.** `ResultResponse` gains an optional `duplicate`. Nothing is removed,
|
|
65
|
+
> so an older daemon keeps working — but the *order* two rules are checked in
|
|
66
|
+
> has changed, and a `RoutingStore` implementation must change with it.
|
|
67
|
+
>
|
|
68
|
+
> `complete` now checks **terminal state before holder**, scoped to the device
|
|
69
|
+
> that finished the job: a replay from that device is answered `duplicate:
|
|
70
|
+
> true` with a 2xx, and anyone else gets exactly the refusal they would get
|
|
71
|
+
> for a job that is not terminal. Previously `RESULT_IDEMPOTENT` held only
|
|
72
|
+
> because the lease is nulled on success, so the holder check tripped first —
|
|
73
|
+
> deleting the idempotency branch failed no test. Run the store contract
|
|
74
|
+
> tests; the compiler cannot see this.
|
|
15
75
|
>
|
|
16
76
|
> **`alpha.3` is a breaking change.** `BackendDescriptor.account` is gone —
|
|
17
77
|
> read `cost` (`free` / `metered` / `subscription`) instead. Four new MUSTs
|
|
18
78
|
> come with it; see `byollm_007`.
|
|
19
79
|
|
|
80
|
+
<!-- release-note 0.1.0-alpha.21 -->
|
|
81
|
+
> [!NOTE]
|
|
82
|
+
> **`0.1.0-alpha.20` is not a complete release — do not pin it.** Four
|
|
83
|
+
> packages published and `@byollm/server` did not: a Sigstore
|
|
84
|
+
> transparency-log 409 on its provenance attestation. The workflow's
|
|
85
|
+
> "already published" guard correctly refuses to resume a partial publish,
|
|
86
|
+
> so `0.1.0-alpha.21` is that release, whole.
|
|
87
|
+
>
|
|
88
|
+
> If you run the Supabase adapter, `alpha.21` needs
|
|
89
|
+
> `20260819010000_completed_by_lease_id.sql`: alpha.19 shipped §3.6's
|
|
90
|
+
> ordering without the column it stores the grant in.
|
|
91
|
+
|
|
92
|
+
<!-- release-note 0.1.0-alpha.40 -->
|
|
93
|
+
**`byollm start` — stop keeping a terminal open.** The daemon can now run
|
|
94
|
+
under your computer's own supervisor and restart itself if it stops: a launchd
|
|
95
|
+
agent on macOS, a `systemd --user` unit on Linux, a logon task on Windows. All
|
|
96
|
+
user-level — no root, no system directories, and `byollm stop` takes it
|
|
97
|
+
away. `byollm status` gained a line saying whether it is actually supervised
|
|
98
|
+
right now, including the state that matters most: installed but not running,
|
|
99
|
+
which looks fine from an app's dashboard and serves nothing.
|
|
100
|
+
|
|
101
|
+
If you are running via `npx`, install properly first (`npm install -g
|
|
102
|
+
byollm@latest`) — `install` refuses to supervise a copy in npx's cache, because
|
|
103
|
+
npm deletes that directory and the service would fail at some later boot.
|
|
104
|
+
|
|
105
|
+
<!-- release-note 0.1.0-alpha.41 -->
|
|
106
|
+
**`onNoRunner` takes a string.** Your fallback answer is your own value, not
|
|
107
|
+
wire data, and handing back a whole result record for it was ceremony — the
|
|
108
|
+
README's own example got the shape wrong, which is how this was found.
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
const { outcome, fallback } = await job.result({
|
|
112
|
+
onNoRunner: () => runOnHostedModel(transcript),
|
|
113
|
+
});
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Whatever you return, `result()` labels it `fallback: true` — the stamp is
|
|
117
|
+
applied by the wait, not taken from you, so an answer that did not run on
|
|
118
|
+
somebody's device cannot be reported as though it did (`FALLBACK_LABELED`).
|
|
119
|
+
Both delivery channels do it, polling and Supabase Realtime. Records still
|
|
120
|
+
work; they just get labelled too.
|
|
121
|
+
|
|
20
122
|
# `@byollm/protocol`
|
|
21
123
|
|
|
22
124
|
The BYOLLM wire contract: TypeScript types, zod schemas, and the pure rules
|
|
@@ -64,10 +166,10 @@ job's owner.
|
|
|
64
166
|
import { matchAudience } from "@byollm/protocol";
|
|
65
167
|
|
|
66
168
|
matchAudience(
|
|
67
|
-
{ owner: "alice", audience: "
|
|
169
|
+
{ owner: "alice", audience: "team" },
|
|
68
170
|
{
|
|
69
171
|
owner: "bob",
|
|
70
|
-
offerScope: "
|
|
172
|
+
offerScope: "team",
|
|
71
173
|
account: "open",
|
|
72
174
|
// The daemon's OWN allowlist decides — never the server's assertion.
|
|
73
175
|
locallyAllows: (owner) => owner === "alice",
|
|
@@ -85,3 +187,17 @@ to know which one happened.
|
|
|
85
187
|
conformance id that appears in this package's `MUSTS` registry.
|
|
86
188
|
|
|
87
189
|
MIT
|
|
190
|
+
|
|
191
|
+
<!-- family:start -->
|
|
192
|
+
|
|
193
|
+
## The rest of byollm
|
|
194
|
+
|
|
195
|
+
Six packages, and they are only interesting together:
|
|
196
|
+
|
|
197
|
+
- [`byollm`](https://www.npmjs.com/package/byollm) — the daemon — runs models on your own machine and answers for it
|
|
198
|
+
- [`@byollm/server`](https://www.npmjs.com/package/@byollm/server) — the SDK a site uses to ask a device for work
|
|
199
|
+
- [`@byollm/relay`](https://www.npmjs.com/package/@byollm/relay) — the broker that holds jobs between a site and a device, and can read neither
|
|
200
|
+
- [`@byollm/control-plane`](https://www.npmjs.com/package/@byollm/control-plane) — who may ask whom, and the policy store behind it
|
|
201
|
+
- [`@byollm/conformance`](https://www.npmjs.com/package/@byollm/conformance) — the kit that proves an implementation is one — including a posture audit that holds nothing but a URL
|
|
202
|
+
|
|
203
|
+
<!-- family:end -->
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
// src/public-identity.ts
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
var PublicIdentity = z.object({
|
|
4
|
+
/** Raw Ed25519 public key. The pinned one. */
|
|
5
|
+
identity: z.string().min(1),
|
|
6
|
+
/** Raw X25519 public key, for sealing to this party. */
|
|
7
|
+
encryption: z.string().min(1),
|
|
8
|
+
/**
|
|
9
|
+
* Ed25519 signature over the encryption key, by the identity key.
|
|
10
|
+
*
|
|
11
|
+
* This is what stops an upstream substituting an encryption key of its
|
|
12
|
+
* own while relaying a genuine identity: the receiver pins the identity
|
|
13
|
+
* and refuses any encryption key not signed by it.
|
|
14
|
+
*/
|
|
15
|
+
encryptionSig: z.string().min(1)
|
|
16
|
+
}).strict();
|
|
17
|
+
|
|
18
|
+
// src/envelope-format.ts
|
|
19
|
+
var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
20
|
+
var CHARS = ALPHABET.split("");
|
|
21
|
+
var VALUES = /* @__PURE__ */ (() => {
|
|
22
|
+
const table = new Uint8Array(128).fill(255);
|
|
23
|
+
for (let at = 0; at < ALPHABET.length; at += 1) {
|
|
24
|
+
table[ALPHABET.charCodeAt(at)] = at;
|
|
25
|
+
}
|
|
26
|
+
return table;
|
|
27
|
+
})();
|
|
28
|
+
function toBase64Url(bytes) {
|
|
29
|
+
let out = "";
|
|
30
|
+
for (let at = 0; at < bytes.length; at += 3) {
|
|
31
|
+
const a = bytes[at] ?? 0;
|
|
32
|
+
const b = bytes[at + 1];
|
|
33
|
+
const c = bytes[at + 2];
|
|
34
|
+
const word = a << 16 | (b ?? 0) << 8 | (c ?? 0);
|
|
35
|
+
out += CHARS[word >> 18 & 63] ?? "";
|
|
36
|
+
out += CHARS[word >> 12 & 63] ?? "";
|
|
37
|
+
if (b !== void 0) out += CHARS[word >> 6 & 63] ?? "";
|
|
38
|
+
if (c !== void 0) out += CHARS[word & 63] ?? "";
|
|
39
|
+
}
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
function fromBase64Url(text) {
|
|
43
|
+
const length = text.length;
|
|
44
|
+
if (length % 4 === 1) return void 0;
|
|
45
|
+
const bytes = new Uint8Array(Math.floor(length * 3 / 4));
|
|
46
|
+
let written = 0;
|
|
47
|
+
let word = 0;
|
|
48
|
+
let bits = 0;
|
|
49
|
+
for (let at = 0; at < length; at += 1) {
|
|
50
|
+
const code = text.charCodeAt(at);
|
|
51
|
+
const value = code < 128 ? VALUES[code] : 255;
|
|
52
|
+
if (value === void 0 || value === 255) return void 0;
|
|
53
|
+
word = word << 6 | value;
|
|
54
|
+
bits += 6;
|
|
55
|
+
if (bits >= 8) {
|
|
56
|
+
bits -= 8;
|
|
57
|
+
bytes[written] = word >> bits & 255;
|
|
58
|
+
written += 1;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return bytes.subarray(0, written);
|
|
62
|
+
}
|
|
63
|
+
var ENVELOPE_BODY_VERSION = "byollm/v1/envelope";
|
|
64
|
+
function envelopeSignedBody(context, plaintext) {
|
|
65
|
+
return new TextEncoder().encode(
|
|
66
|
+
JSON.stringify({
|
|
67
|
+
v: ENVELOPE_BODY_VERSION,
|
|
68
|
+
jobId: context.jobId,
|
|
69
|
+
senderKeyId: context.senderKeyId,
|
|
70
|
+
recipientKeyId: context.recipientKeyId,
|
|
71
|
+
deadlineAt: context.deadlineAt,
|
|
72
|
+
direction: context.direction,
|
|
73
|
+
plaintext
|
|
74
|
+
})
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
function encodeEnvelopeInner(body, signature) {
|
|
78
|
+
return JSON.stringify({ body: toBase64Url(body), signature });
|
|
79
|
+
}
|
|
80
|
+
function decodeEnvelopeInner(text) {
|
|
81
|
+
let parsed;
|
|
82
|
+
try {
|
|
83
|
+
parsed = JSON.parse(text);
|
|
84
|
+
} catch {
|
|
85
|
+
return void 0;
|
|
86
|
+
}
|
|
87
|
+
if (typeof parsed.body !== "string" || typeof parsed.signature !== "string") {
|
|
88
|
+
return void 0;
|
|
89
|
+
}
|
|
90
|
+
const body = fromBase64Url(parsed.body);
|
|
91
|
+
if (body === void 0) return void 0;
|
|
92
|
+
return { body, signature: parsed.signature };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// src/console.ts
|
|
96
|
+
import { z as z2 } from "zod";
|
|
97
|
+
var CONSOLE_FRAME_VERSION = "byollm/v1/console";
|
|
98
|
+
var CONSOLE_MAX_DATA_BYTES = 64 * 1024;
|
|
99
|
+
function encodeConsoleData(bytes) {
|
|
100
|
+
return toBase64Url(bytes);
|
|
101
|
+
}
|
|
102
|
+
function decodeConsoleData(text) {
|
|
103
|
+
const padding = /(={0,2})$/.exec(text)?.[1]?.length ?? 0;
|
|
104
|
+
const body = text.slice(0, text.length - padding);
|
|
105
|
+
return fromBase64Url(body.replace(/\+/g, "-").replace(/\//g, "_"));
|
|
106
|
+
}
|
|
107
|
+
function consoleDataBytes(data2) {
|
|
108
|
+
return decodeConsoleData(data2) ?? new Uint8Array();
|
|
109
|
+
}
|
|
110
|
+
var data = z2.string().max(Math.ceil(CONSOLE_MAX_DATA_BYTES * 4 / 3) + 4).refine((text) => decodeConsoleData(text) !== void 0, {
|
|
111
|
+
message: "not base64"
|
|
112
|
+
});
|
|
113
|
+
var cols = z2.number().int().min(1).max(1e4);
|
|
114
|
+
var rows = z2.number().int().min(1).max(1e4);
|
|
115
|
+
var seq = z2.number().int().positive();
|
|
116
|
+
var ConsoleHello = z2.object({
|
|
117
|
+
v: z2.literal(CONSOLE_FRAME_VERSION),
|
|
118
|
+
kind: z2.literal("hello"),
|
|
119
|
+
seq: z2.literal(1),
|
|
120
|
+
/**
|
|
121
|
+
* The browser's EPHEMERAL identity for this session, and the reason hello
|
|
122
|
+
* exists as its own frame.
|
|
123
|
+
*
|
|
124
|
+
* A browser has no long-term key — it is a tab, not a machine — so it
|
|
125
|
+
* generates one per session and the box seals its output to it. That key
|
|
126
|
+
* has to reach the box without the hub being able to substitute one of its
|
|
127
|
+
* own, which is the classic broker attack. So it travels SEALED TO THE
|
|
128
|
+
* BOX'S PINNED IDENTITY like every other frame: the hub cannot read it and
|
|
129
|
+
* cannot replace it, because replacing it means producing a sealed box
|
|
130
|
+
* the box's key opens and the browser's key signed.
|
|
131
|
+
*
|
|
132
|
+
* The box does not pin this. It cannot — it is new every session, and
|
|
133
|
+
* nothing authorises it cryptographically. What authorises the browser is
|
|
134
|
+
* the hub's per-session grant (ruling item 2); what this key does is keep
|
|
135
|
+
* the hub from READING what it authorised.
|
|
136
|
+
*/
|
|
137
|
+
browser: PublicIdentity,
|
|
138
|
+
cols,
|
|
139
|
+
rows
|
|
140
|
+
}).strict();
|
|
141
|
+
var ConsoleStdin = z2.object({
|
|
142
|
+
v: z2.literal(CONSOLE_FRAME_VERSION),
|
|
143
|
+
/** Browser→box only. A `stdin` arriving from the box is `wrong-way`. */
|
|
144
|
+
kind: z2.literal("stdin"),
|
|
145
|
+
seq,
|
|
146
|
+
data
|
|
147
|
+
}).strict();
|
|
148
|
+
var ConsoleStdout = z2.object({
|
|
149
|
+
v: z2.literal(CONSOLE_FRAME_VERSION),
|
|
150
|
+
/** Box→browser only. */
|
|
151
|
+
kind: z2.literal("stdout"),
|
|
152
|
+
seq,
|
|
153
|
+
data
|
|
154
|
+
}).strict();
|
|
155
|
+
var ConsoleResize = z2.object({
|
|
156
|
+
v: z2.literal(CONSOLE_FRAME_VERSION),
|
|
157
|
+
kind: z2.literal("resize"),
|
|
158
|
+
seq,
|
|
159
|
+
cols,
|
|
160
|
+
rows
|
|
161
|
+
}).strict();
|
|
162
|
+
var ConsoleBye = z2.object({
|
|
163
|
+
v: z2.literal(CONSOLE_FRAME_VERSION),
|
|
164
|
+
kind: z2.literal("bye"),
|
|
165
|
+
seq,
|
|
166
|
+
/** Shown to the owner in the session feed, so it is a sentence. */
|
|
167
|
+
reason: z2.string().min(1).max(200)
|
|
168
|
+
}).strict();
|
|
169
|
+
var ConsoleFrame = z2.discriminatedUnion("kind", [
|
|
170
|
+
ConsoleHello,
|
|
171
|
+
ConsoleStdin,
|
|
172
|
+
ConsoleStdout,
|
|
173
|
+
ConsoleResize,
|
|
174
|
+
ConsoleBye
|
|
175
|
+
]);
|
|
176
|
+
function consoleEnvelope(input) {
|
|
177
|
+
return {
|
|
178
|
+
jobId: input.sessionId,
|
|
179
|
+
senderKeyId: input.senderKeyId,
|
|
180
|
+
recipientKeyId: input.recipientKeyId,
|
|
181
|
+
deadlineAt: input.deadlineAt,
|
|
182
|
+
direction: input.from === "browser" ? "payload" : "result"
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
function consoleOrder(from) {
|
|
186
|
+
const maySend = {
|
|
187
|
+
// The browser drives: it opens, it types, it sets the size, it leaves.
|
|
188
|
+
browser: ["hello", "stdin", "resize", "bye"],
|
|
189
|
+
// The box answers, and can end a session. Nothing else.
|
|
190
|
+
box: ["stdout", "bye"]
|
|
191
|
+
};
|
|
192
|
+
const allowed = maySend[from];
|
|
193
|
+
const opensWithHello = from === "browser";
|
|
194
|
+
let last = 0;
|
|
195
|
+
let closed = false;
|
|
196
|
+
return {
|
|
197
|
+
/** The last sequence accepted. 0 before anything has been. */
|
|
198
|
+
get seen() {
|
|
199
|
+
return last;
|
|
200
|
+
},
|
|
201
|
+
accept(frame) {
|
|
202
|
+
if (closed) return { ok: false, fault: "closed" };
|
|
203
|
+
if (!allowed.includes(frame.kind)) {
|
|
204
|
+
return { ok: false, fault: "wrong-way" };
|
|
205
|
+
}
|
|
206
|
+
const isFirst = last === 0;
|
|
207
|
+
const wantsHello = isFirst && opensWithHello;
|
|
208
|
+
if (wantsHello !== (frame.kind === "hello")) {
|
|
209
|
+
return { ok: false, fault: "out-of-turn" };
|
|
210
|
+
}
|
|
211
|
+
if (frame.seq <= last) return { ok: false, fault: "replayed" };
|
|
212
|
+
if (frame.seq !== last + 1) return { ok: false, fault: "gap" };
|
|
213
|
+
last = frame.seq;
|
|
214
|
+
if (frame.kind === "bye") closed = true;
|
|
215
|
+
return { ok: true };
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export {
|
|
221
|
+
PublicIdentity,
|
|
222
|
+
toBase64Url,
|
|
223
|
+
fromBase64Url,
|
|
224
|
+
ENVELOPE_BODY_VERSION,
|
|
225
|
+
envelopeSignedBody,
|
|
226
|
+
encodeEnvelopeInner,
|
|
227
|
+
decodeEnvelopeInner,
|
|
228
|
+
CONSOLE_FRAME_VERSION,
|
|
229
|
+
CONSOLE_MAX_DATA_BYTES,
|
|
230
|
+
encodeConsoleData,
|
|
231
|
+
decodeConsoleData,
|
|
232
|
+
consoleDataBytes,
|
|
233
|
+
ConsoleHello,
|
|
234
|
+
ConsoleStdin,
|
|
235
|
+
ConsoleStdout,
|
|
236
|
+
ConsoleResize,
|
|
237
|
+
ConsoleBye,
|
|
238
|
+
ConsoleFrame,
|
|
239
|
+
consoleEnvelope,
|
|
240
|
+
consoleOrder
|
|
241
|
+
};
|
|
242
|
+
//# sourceMappingURL=chunk-J3HTAGMX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/public-identity.ts","../src/envelope-format.ts","../src/console.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/**\n * A party's public keys, as they travel — extracted from `keys.ts` for B018c.\n *\n * ## Why it lives on its own\n *\n * The browser end of a console session needs this SCHEMA at runtime, and\n * `keys.ts` is irreducibly node-only: `generateKeyPairSync`,\n * `createPrivateKey`, `createHash`. So every route to the console types\n * dragged the node world into a bundle meant for a tab.\n *\n * Nothing about the shape changed. `keys.ts` re-exports it, so every existing\n * import still resolves and the wire is untouched — this is a file move, and\n * the tests that were passing before it are the proof.\n *\n * Pure zod: no crypto, no node, nothing to make unportable later.\n */\nexport const PublicIdentity = z\n .object({\n /** Raw Ed25519 public key. The pinned one. */\n identity: z.string().min(1),\n /** Raw X25519 public key, for sealing to this party. */\n encryption: z.string().min(1),\n /**\n * Ed25519 signature over the encryption key, by the identity key.\n *\n * This is what stops an upstream substituting an encryption key of its\n * own while relaying a genuine identity: the receiver pins the identity\n * and refuses any encryption key not signed by it.\n */\n encryptionSig: z.string().min(1),\n })\n .strict();\nexport type PublicIdentity = z.infer<typeof PublicIdentity>;\n","/**\n * The envelope's FORMAT, with no primitives and no platform — B018c step 3.\n *\n * ## Why this file exists\n *\n * The browser is one of the two ends a console stream is encrypted between,\n * and it cannot run `envelope.ts`: the sealing is WASM and portable, but the\n * inner signature goes through `node:crypto`'s Ed25519. So the browser needs\n * its own primitives.\n *\n * What it must NOT have is its own *format*. Two implementations of \"which\n * bytes get signed\" is the defect class this codebase spends most of its\n * checks on, and here the two copies would diverge silently — a mismatched\n * signature is indistinguishable from an attack, so the first symptom would\n * be a console that refuses to open and a log line saying `bad-signature`.\n *\n * Everything here is therefore pure: no `node:` imports, no `Buffer`, no\n * `btoa`. `envelope-is-portable.test.ts` asserts that mechanically, because\n * \"somebody will import Buffer for convenience one day\" is a prediction, and\n * this project's rule is that a prediction ships with the test that catches it.\n *\n * ## Why base64url is written out by hand\n *\n * `Buffer` is Node's and `btoa` takes a binary string, so neither is both\n * portable and pleasant. Twenty lines of table lookup is: it agrees with\n * `Buffer` on every byte value, which the test proves rather than assumes.\n */\n\nconst ALPHABET =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n\n/** Indexed as an array so the compiler knows every lookup lands. */\nconst CHARS: readonly string[] = ALPHABET.split(\"\");\n\n/** Reverse table, built once. 255 marks \"not a base64url character\". */\nconst VALUES = /* @__PURE__ */ (() => {\n const table = new Uint8Array(128).fill(255);\n for (let at = 0; at < ALPHABET.length; at += 1) {\n table[ALPHABET.charCodeAt(at)] = at;\n }\n return table;\n})();\n\n/** Unpadded base64url, the encoding every key and signature on this wire uses. */\nexport function toBase64Url(bytes: Uint8Array): string {\n let out = \"\";\n for (let at = 0; at < bytes.length; at += 3) {\n const a = bytes[at] ?? 0;\n const b = bytes[at + 1];\n const c = bytes[at + 2];\n const word = (a << 16) | ((b ?? 0) << 8) | (c ?? 0);\n out += CHARS[(word >> 18) & 63] ?? \"\";\n out += CHARS[(word >> 12) & 63] ?? \"\";\n if (b !== undefined) out += CHARS[(word >> 6) & 63] ?? \"\";\n if (c !== undefined) out += CHARS[word & 63] ?? \"\";\n }\n return out;\n}\n\n/** The inverse. Returns undefined rather than throwing — this parses input. */\nexport function fromBase64Url(text: string): Uint8Array | undefined {\n const length = text.length;\n // 1 leftover character cannot encode any whole byte.\n if (length % 4 === 1) return undefined;\n const bytes = new Uint8Array(Math.floor((length * 3) / 4));\n let written = 0;\n let word = 0;\n let bits = 0;\n for (let at = 0; at < length; at += 1) {\n const code = text.charCodeAt(at);\n const value = code < 128 ? VALUES[code] : 255;\n if (value === undefined || value === 255) return undefined;\n word = (word << 6) | value;\n bits += 6;\n if (bits >= 8) {\n bits -= 8;\n bytes[written] = (word >> bits) & 0xff;\n written += 1;\n }\n }\n return bytes.subarray(0, written);\n}\n\n/** Domain tag for the bytes an envelope's signature covers. */\nexport const ENVELOPE_BODY_VERSION = \"byollm/v1/envelope\";\n\n/** What an envelope's signature is over — the fields, in this order. */\nexport interface EnvelopeBodyContext {\n readonly jobId: string;\n readonly senderKeyId: string;\n readonly recipientKeyId: string;\n readonly deadlineAt: number;\n readonly direction: string;\n}\n\n/**\n * The exact bytes an envelope's signature covers.\n *\n * **Field order is part of the format**, because `JSON.stringify` emits keys\n * in insertion order and the verifier hashes bytes, not meaning. Reordering\n * these lines is a wire change that no type would catch and every signature\n * would fail — which is why they are written out rather than spread from an\n * object somebody could reshape.\n */\nexport function envelopeSignedBody(\n context: EnvelopeBodyContext,\n plaintext: string,\n): Uint8Array {\n return new TextEncoder().encode(\n JSON.stringify({\n v: ENVELOPE_BODY_VERSION,\n jobId: context.jobId,\n senderKeyId: context.senderKeyId,\n recipientKeyId: context.recipientKeyId,\n deadlineAt: context.deadlineAt,\n direction: context.direction,\n plaintext,\n }),\n );\n}\n\n/** The signed body and its signature, as they travel inside the sealed box. */\nexport function encodeEnvelopeInner(\n body: Uint8Array,\n signature: string,\n): string {\n return JSON.stringify({ body: toBase64Url(body), signature });\n}\n\nexport interface EnvelopeInner {\n readonly body: Uint8Array;\n readonly signature: string;\n}\n\n/**\n * Read the inner object back.\n *\n * Returns undefined for anything malformed rather than throwing, because\n * every byte reaching this has come out of a decryption and is therefore\n * input — `malformed` is one of the outcomes `open()` already distinguishes.\n */\nexport function decodeEnvelopeInner(text: string): EnvelopeInner | undefined {\n let parsed: { body?: unknown; signature?: unknown };\n try {\n parsed = JSON.parse(text) as { body?: unknown; signature?: unknown };\n } catch {\n return undefined;\n }\n if (typeof parsed.body !== \"string\" || typeof parsed.signature !== \"string\") {\n return undefined;\n }\n const body = fromBase64Url(parsed.body);\n if (body === undefined) return undefined;\n return { body, signature: parsed.signature };\n}\n","import { z } from \"zod\";\nimport { fromBase64Url, toBase64Url } from \"./envelope-format.js\";\nimport { PublicIdentity } from \"./public-identity.js\";\nimport type { EnvelopeContext } from \"./envelope.js\";\n\n/**\n * The terminal stream a hosted box's console runs over — byollm_018 §\"Console\n * redesign: brokered E2E replaces SSH-first (RULED, Todd 2026-09-03)\".\n *\n * The ruling's item 3 is the whole reason this file exists: *\"The terminal\n * stream is E2E encrypted browser↔agent with the sealed-channel pattern jobs\n * use; the hub routes ciphertext.\"* So the bytes are carried by\n * {@link seal}/{@link open} exactly as a job's payload is, and what is defined\n * here is the thing a sealed envelope does not carry: **what a frame means,\n * and where it sits in the stream.**\n *\n * ## Why an ordering rule is protocol and not an implementation detail\n *\n * Sealing makes the hub unable to READ the stream. It does nothing to make\n * the hub unable to reshape it. A router that holds ciphertext can drop a\n * frame, deliver two out of order, or send the same frame twice, and every\n * envelope still opens, still verifies against the pinned identity, and still\n * looks perfect to the receiver — because each envelope is authenticated on\n * its own and says nothing about the ones around it.\n *\n * On a terminal that is not a theoretical loss of tidiness. A dropped\n * keystroke is a different command; two frames swapped is a different command;\n * a replayed frame is a command run twice. The console carries vendor\n * sign-in flows (byollm_018 item 5), so \"a different command\" can mean an auth\n * code going somewhere it was not typed.\n *\n * Hence {@link consoleOrder}: a sequence inside the ciphertext, checked by\n * both ends. Inside, because a counter the hub could see is a counter the hub\n * could rewrite.\n *\n * ## One definition, both ends, and there are three ends\n *\n * The browser, the box's agent, and the hub broker all handle these frames,\n * and the first two must agree byte for byte or the stream silently corrupts.\n * The hub must NOT be able to agree — it only ever sees the sealed envelope.\n * This module is the single definition the two real ends share; neither\n * retypes it.\n *\n * ## The pinned box key is the PAIRING key (CCB's call, 09-16)\n *\n * The ruling says \"box key pinned at first session\", and the backlog left one\n * delta open: whether the identity the owner already approved at pairing can\n * serve as that pinned key. It can, and it should, for three reasons.\n *\n * 1. **The pairing key is the only one a human ever chose.** `PairStartRequest`\n * carries the device's {@link PublicIdentity} and says why: *\"Pairing is\n * where the two parties learn each other's identities, because it is the\n * one moment a human is already deciding to trust: the approval click. A\n * key exchanged anywhere else would be a key nobody chose.\"* A fresh\n * trust-on-first-use pin at the first console session is precisely a key\n * nobody chose — it trusts whoever answers first, which on a brokered\n * channel is whoever the broker points at.\n * 2. **Two pins of one box can disagree, and silently.** A console pin\n * separate from the pairing pin is a second record of the same fact, which\n * is this project's most-repeated defect. When they diverge, nothing reads\n * both, so nothing notices.\n * 3. **Alarm-on-change comes free from the split already in `keys.ts`.** The\n * Ed25519 identity is the pinned half and the X25519 encryption key is\n * signed by it, so {@link verifyPublicIdentity} lets the box rotate its\n * encryption key without a new ceremony while an IDENTITY change fails to\n * verify and alarms — which is what the ruling asks for, and it is already\n * written.\n *\n * **What this does not claim.** Pinning the pairing key does not make the hub\n * unable to lie about which key that was; the hub is the one telling the\n * browser. The ruling is explicit that we build the operator-ACCOUNTABLE\n * version, not the operator-incapable one, and item 4's session feed is where\n * that accountability is paid. What the pin buys is that a CHANGE is\n * detectable, and that the key being pinned is one an owner approved rather\n * than one a broker supplied.\n */\n\n/** Domain tag for the plaintext inside a console envelope. */\nexport const CONSOLE_FRAME_VERSION = \"byollm/v1/console\";\n\n/**\n * The largest `data` payload one frame may carry, before base64.\n *\n * Far below {@link MAX_ENVELOPE_BYTES}, and deliberately: an envelope cap\n * stops a memory attack, while this stops a latency one. A console is\n * interactive, so a peer that batches a megabyte into one frame has made the\n * stream unusable without ever exceeding a limit.\n */\nexport const CONSOLE_MAX_DATA_BYTES = 64 * 1024;\n\n/**\n * Encode one frame's payload. Canonical, and the only encoder either end may\n * use — see {@link decodeConsoleData} for what retyping it cost.\n */\nexport function encodeConsoleData(bytes: Uint8Array): string {\n return toBase64Url(bytes);\n}\n\n/**\n * Decode one frame's payload, accepting either base64 alphabet.\n *\n * The two alphabets disagree on three characters — `+`, `/`, and the `=`\n * padding — and a box that encoded with Node's standard base64 produced\n * frames that sealed, opened, verified against the pinned identity, and\n * ordered correctly, and then decoded to nothing in a strict base64url\n * reader. Nothing faulted, because a decode that returns nothing is not a\n * fault anywhere in this file. What an operator saw was a console that ate\n * every keystroke and roughly two output chunks in three: one typed character\n * is one byte, which always pads, while a longer chunk survives exactly when\n * its length is a multiple of three and its bytes happen to avoid `+` and `/`.\n *\n * So the tolerance here is deliberate, not lax. A box is software on someone\n * else's machine, and a browser that accepted only the canonical spelling\n * would fix the console for whoever upgraded and for nobody else. Anything\n * that is neither spelling still returns `undefined`, and {@link ConsoleFrame}\n * rejects it at the schema so it fails loudly rather than vanishing.\n */\nexport function decodeConsoleData(text: string): Uint8Array | undefined {\n /* Base64 pads to a multiple of four with at most two `=`. More than two is\n not a lenient spelling of anything, so it falls through and is refused. */\n const padding = /(={0,2})$/.exec(text)?.[1]?.length ?? 0;\n const body = text.slice(0, text.length - padding);\n return fromBase64Url(body.replace(/\\+/g, \"-\").replace(/\\//g, \"_\"));\n}\n\n/**\n * The bytes of a payload that has already passed {@link ConsoleFrame}.\n *\n * Total on purpose. The schema refuses a payload that cannot be read, so both\n * ends would otherwise carry a fallback arm that no input can reach — and an\n * arm nothing can reach is an arm nothing can test. The guarantee lives here,\n * once, where a test can hold it to both answers.\n */\nexport function consoleDataBytes(data: string): Uint8Array {\n return decodeConsoleData(data) ?? new Uint8Array();\n}\n\nconst data = z\n .string()\n .max(Math.ceil((CONSOLE_MAX_DATA_BYTES * 4) / 3) + 4)\n /* A law with a check. This field spent its whole life described as base64\n and validated as nothing, which is why a box could disagree with a\n browser about what it was sending and no test anywhere could tell. */\n .refine((text) => decodeConsoleData(text) !== undefined, {\n message: \"not base64\",\n });\n\n/** Terminal geometry. Bounded because a pty rejects absurd sizes anyway. */\nconst cols = z.number().int().min(1).max(10_000);\nconst rows = z.number().int().min(1).max(10_000);\n\n/**\n * A frame's position in its direction's stream. Starts at 1, never repeats,\n * never skips — see {@link consoleOrder} for what each of those catches.\n */\nconst seq = z.number().int().positive();\n\nexport const ConsoleHello = z\n .object({\n v: z.literal(CONSOLE_FRAME_VERSION),\n kind: z.literal(\"hello\"),\n seq: z.literal(1),\n /**\n * The browser's EPHEMERAL identity for this session, and the reason hello\n * exists as its own frame.\n *\n * A browser has no long-term key — it is a tab, not a machine — so it\n * generates one per session and the box seals its output to it. That key\n * has to reach the box without the hub being able to substitute one of its\n * own, which is the classic broker attack. So it travels SEALED TO THE\n * BOX'S PINNED IDENTITY like every other frame: the hub cannot read it and\n * cannot replace it, because replacing it means producing a sealed box\n * the box's key opens and the browser's key signed.\n *\n * The box does not pin this. It cannot — it is new every session, and\n * nothing authorises it cryptographically. What authorises the browser is\n * the hub's per-session grant (ruling item 2); what this key does is keep\n * the hub from READING what it authorised.\n */\n browser: PublicIdentity,\n cols,\n rows,\n })\n .strict();\nexport type ConsoleHello = z.infer<typeof ConsoleHello>;\n\n/**\n * Two schemas rather than one with a `kind: z.enum([...])`, because the union\n * below discriminates on `kind` and a discriminator that is itself a set is\n * how a union quietly stops discriminating.\n */\nexport const ConsoleStdin = z\n .object({\n v: z.literal(CONSOLE_FRAME_VERSION),\n /** Browser→box only. A `stdin` arriving from the box is `wrong-way`. */\n kind: z.literal(\"stdin\"),\n seq,\n data,\n })\n .strict();\nexport type ConsoleStdin = z.infer<typeof ConsoleStdin>;\n\nexport const ConsoleStdout = z\n .object({\n v: z.literal(CONSOLE_FRAME_VERSION),\n /** Box→browser only. */\n kind: z.literal(\"stdout\"),\n seq,\n data,\n })\n .strict();\nexport type ConsoleStdout = z.infer<typeof ConsoleStdout>;\n\nexport const ConsoleResize = z\n .object({\n v: z.literal(CONSOLE_FRAME_VERSION),\n kind: z.literal(\"resize\"),\n seq,\n cols,\n rows,\n })\n .strict();\nexport type ConsoleResize = z.infer<typeof ConsoleResize>;\n\nexport const ConsoleBye = z\n .object({\n v: z.literal(CONSOLE_FRAME_VERSION),\n kind: z.literal(\"bye\"),\n seq,\n /** Shown to the owner in the session feed, so it is a sentence. */\n reason: z.string().min(1).max(200),\n })\n .strict();\nexport type ConsoleBye = z.infer<typeof ConsoleBye>;\n\nexport const ConsoleFrame = z.discriminatedUnion(\"kind\", [\n ConsoleHello,\n ConsoleStdin,\n ConsoleStdout,\n ConsoleResize,\n ConsoleBye,\n]);\nexport type ConsoleFrame = z.infer<typeof ConsoleFrame>;\n\n/**\n * The envelope context for a console frame.\n *\n * Exported so that neither end computes it: the session id goes in `jobId`\n * and the direction is derived, and if the two ends disagreed about either,\n * every envelope would fail to open with `not-for-us` — a failure that looks\n * exactly like an attack.\n */\nexport function consoleEnvelope(input: {\n sessionId: string;\n from: \"browser\" | \"box\";\n senderKeyId: string;\n recipientKeyId: string;\n deadlineAt: number;\n}): EnvelopeContext {\n return {\n jobId: input.sessionId,\n senderKeyId: input.senderKeyId,\n recipientKeyId: input.recipientKeyId,\n deadlineAt: input.deadlineAt,\n direction: input.from === \"browser\" ? \"payload\" : \"result\",\n };\n}\n\n/** Why a frame was refused. Each one is a distinct thing a router can do. */\nexport type ConsoleOrderFault =\n /** Seq went backwards or repeated — the router sent it twice. */\n | \"replayed\"\n /** Seq skipped — the router dropped what was between. */\n | \"gap\"\n /** A `hello` that was not the first frame, or a first frame that was not `hello`. */\n | \"out-of-turn\"\n /** A `stdin` from the box, or a `stdout` from the browser. */\n | \"wrong-way\"\n /** Anything after `bye`. The stream is over. */\n | \"closed\";\n\nexport type ConsoleOrderResult =\n | { readonly ok: true }\n | { readonly ok: false; readonly fault: ConsoleOrderFault };\n\n/**\n * One direction's ordering rule, which both ends run over what they receive.\n *\n * **Strictly +1, not merely increasing.** Increasing would catch replay and\n * reorder while letting a DROP through silently, and a dropped frame on a\n * terminal is a truncated command that still runs. There is no benign gap\n * here to tolerate: the transport underneath is an ordered, reliable stream,\n * so a gap means something between the ends removed a frame.\n *\n * Every fault is fatal to the session by design. A console has no\n * resynchronisation story that is safe — you cannot ask \"what did I miss\" of\n * a party that may be the one who took it.\n */\n/**\n * One direction's receiver-side ordering state.\n *\n * Named as an interface rather than inferred, so the box's agent and the\n * browser hold the SAME type — an inferred one would let the two ends drift\n * apart without a compiler ever objecting.\n */\nexport interface ConsoleOrder {\n /** The last sequence accepted. 0 before anything has been. */\n readonly seen: number;\n accept(frame: ConsoleFrame): ConsoleOrderResult;\n}\n\nexport function consoleOrder(from: \"browser\" | \"box\"): ConsoleOrder {\n /**\n * The two directions are NOT symmetric, and reading them as symmetric was\n * this function's first bug: `hello` carries the browser's ephemeral key, so\n * the browser sends exactly one and the box never sends any. A rule that\n * demanded a leading `hello` in both directions would reject every real box\n * stream at its first frame.\n */\n /**\n * What this side is allowed to send AT ALL, rather than a special case per\n * kind. CW's review caught `resize` travelling box→browser unchecked: the\n * rule named stdin and stdout and said nothing about the rest, so every\n * kind added later would have defaulted to \"allowed in both directions\"\n * and needed somebody to notice. A list of what each side may send has no\n * default to forget.\n */\n const maySend: Readonly<Record<\"browser\" | \"box\", readonly string[]>> = {\n // The browser drives: it opens, it types, it sets the size, it leaves.\n browser: [\"hello\", \"stdin\", \"resize\", \"bye\"],\n // The box answers, and can end a session. Nothing else.\n box: [\"stdout\", \"bye\"],\n };\n const allowed = maySend[from];\n const opensWithHello = from === \"browser\";\n\n let last = 0;\n let closed = false;\n\n return {\n /** The last sequence accepted. 0 before anything has been. */\n get seen(): number {\n return last;\n },\n accept(frame: ConsoleFrame): ConsoleOrderResult {\n if (closed) return { ok: false, fault: \"closed\" };\n\n if (!allowed.includes(frame.kind)) {\n return { ok: false, fault: \"wrong-way\" };\n }\n\n // `hello` opens the browser's stream, appears once, and never opens the\n // box's. Both halves matter: a second `hello` mid-stream would be a new\n // browser key, which is the substitution the sealing exists to stop.\n const isFirst = last === 0;\n const wantsHello = isFirst && opensWithHello;\n if (wantsHello !== (frame.kind === \"hello\")) {\n return { ok: false, fault: \"out-of-turn\" };\n }\n\n if (frame.seq <= last) return { ok: false, fault: \"replayed\" };\n if (frame.seq !== last + 1) return { ok: false, fault: \"gap\" };\n\n last = frame.seq;\n if (frame.kind === \"bye\") closed = true;\n return { ok: true };\n },\n };\n}\n"],"mappings":";AAAA,SAAS,SAAS;AAkBX,IAAM,iBAAiB,EAC3B,OAAO;AAAA;AAAA,EAEN,UAAU,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA;AAAA,EAE1B,YAAY,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ5B,eAAe,EAAE,OAAO,EAAE,IAAI,CAAC;AACjC,CAAC,EACA,OAAO;;;ACLV,IAAM,WACJ;AAGF,IAAM,QAA2B,SAAS,MAAM,EAAE;AAGlD,IAAM,SAA0B,uBAAM;AACpC,QAAM,QAAQ,IAAI,WAAW,GAAG,EAAE,KAAK,GAAG;AAC1C,WAAS,KAAK,GAAG,KAAK,SAAS,QAAQ,MAAM,GAAG;AAC9C,UAAM,SAAS,WAAW,EAAE,CAAC,IAAI;AAAA,EACnC;AACA,SAAO;AACT,GAAG;AAGI,SAAS,YAAY,OAA2B;AACrD,MAAI,MAAM;AACV,WAAS,KAAK,GAAG,KAAK,MAAM,QAAQ,MAAM,GAAG;AAC3C,UAAM,IAAI,MAAM,EAAE,KAAK;AACvB,UAAM,IAAI,MAAM,KAAK,CAAC;AACtB,UAAM,IAAI,MAAM,KAAK,CAAC;AACtB,UAAM,OAAQ,KAAK,MAAQ,KAAK,MAAM,KAAM,KAAK;AACjD,WAAO,MAAO,QAAQ,KAAM,EAAE,KAAK;AACnC,WAAO,MAAO,QAAQ,KAAM,EAAE,KAAK;AACnC,QAAI,MAAM,OAAW,QAAO,MAAO,QAAQ,IAAK,EAAE,KAAK;AACvD,QAAI,MAAM,OAAW,QAAO,MAAM,OAAO,EAAE,KAAK;AAAA,EAClD;AACA,SAAO;A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