driverkit 0.0.0-stage → 0.0.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/CONTROLS.md +578 -0
- package/REACT.md +477 -0
- package/README.md +104 -2
- package/dist/agent/backend.d.ts +69 -0
- package/dist/agent/backend.d.ts.map +1 -0
- package/dist/agent/backend.js +130 -0
- package/dist/agent/backend.js.map +1 -0
- package/dist/agent/control.d.ts +148 -0
- package/dist/agent/control.d.ts.map +1 -0
- package/dist/agent/control.js +342 -0
- package/dist/agent/control.js.map +1 -0
- package/dist/agent/index.d.ts +9 -0
- package/dist/agent/index.d.ts.map +1 -0
- package/dist/agent/index.js +6 -0
- package/dist/agent/index.js.map +1 -0
- package/dist/agent/loop.d.ts +136 -0
- package/dist/agent/loop.d.ts.map +1 -0
- package/dist/agent/loop.js +824 -0
- package/dist/agent/loop.js.map +1 -0
- package/dist/agent/render.d.ts +173 -0
- package/dist/agent/render.d.ts.map +1 -0
- package/dist/agent/render.js +425 -0
- package/dist/agent/render.js.map +1 -0
- package/dist/agent/tools.d.ts +138 -0
- package/dist/agent/tools.d.ts.map +1 -0
- package/dist/agent/tools.js +622 -0
- package/dist/agent/tools.js.map +1 -0
- package/dist/agent/types.d.ts +566 -0
- package/dist/agent/types.d.ts.map +1 -0
- package/dist/agent/types.js +32 -0
- package/dist/agent/types.js.map +1 -0
- package/dist/browser/budget.d.ts +92 -0
- package/dist/browser/budget.d.ts.map +1 -0
- package/dist/browser/budget.js +151 -0
- package/dist/browser/budget.js.map +1 -0
- package/dist/browser/connect.d.ts +368 -0
- package/dist/browser/connect.d.ts.map +1 -0
- package/dist/browser/connect.js +1038 -0
- package/dist/browser/connect.js.map +1 -0
- package/dist/browser/elsewhere.d.ts +89 -0
- package/dist/browser/elsewhere.d.ts.map +1 -0
- package/dist/browser/elsewhere.js +91 -0
- package/dist/browser/elsewhere.js.map +1 -0
- package/dist/browser/frames.d.ts +85 -0
- package/dist/browser/frames.d.ts.map +1 -0
- package/dist/browser/frames.js +11 -0
- package/dist/browser/frames.js.map +1 -0
- package/dist/browser/index.d.ts +8 -0
- package/dist/browser/index.d.ts.map +1 -0
- package/dist/browser/index.js +9 -0
- package/dist/browser/index.js.map +1 -0
- package/dist/check/check.d.ts +171 -0
- package/dist/check/check.d.ts.map +1 -0
- package/dist/check/check.js +666 -0
- package/dist/check/check.js.map +1 -0
- package/dist/check/index.d.ts +3 -0
- package/dist/check/index.d.ts.map +1 -0
- package/dist/check/index.js +2 -0
- package/dist/check/index.js.map +1 -0
- package/dist/check/types.d.ts +149 -0
- package/dist/check/types.d.ts.map +1 -0
- package/dist/check/types.js +29 -0
- package/dist/check/types.js.map +1 -0
- package/dist/controls/controls.d.ts +198 -0
- package/dist/controls/controls.d.ts.map +1 -0
- package/dist/controls/controls.js +742 -0
- package/dist/controls/controls.js.map +1 -0
- package/dist/controls/dom.d.ts +108 -0
- package/dist/controls/dom.d.ts.map +1 -0
- package/dist/controls/dom.js +56 -0
- package/dist/controls/dom.js.map +1 -0
- package/dist/controls/index.d.ts +26 -0
- package/dist/controls/index.d.ts.map +1 -0
- package/dist/controls/index.js +23 -0
- package/dist/controls/index.js.map +1 -0
- package/dist/controls/rows.d.ts +66 -0
- package/dist/controls/rows.d.ts.map +1 -0
- package/dist/controls/rows.js +127 -0
- package/dist/controls/rows.js.map +1 -0
- package/dist/core/index.d.ts +3 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/index.js +15 -0
- package/dist/core/index.js.map +1 -0
- package/dist/core/registry.d.ts +192 -0
- package/dist/core/registry.d.ts.map +1 -0
- package/dist/core/registry.js +2799 -0
- package/dist/core/registry.js.map +1 -0
- package/dist/core/types.d.ts +2468 -0
- package/dist/core/types.d.ts.map +1 -0
- package/dist/core/types.js +19 -0
- package/dist/core/types.js.map +1 -0
- package/dist/otel/index.d.ts +122 -0
- package/dist/otel/index.d.ts.map +1 -0
- package/dist/otel/index.js +157 -0
- package/dist/otel/index.js.map +1 -0
- package/dist/react/index.d.ts +191 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +547 -0
- package/dist/react/index.js.map +1 -0
- package/dist/react/runtime.d.ts +95 -0
- package/dist/react/runtime.d.ts.map +1 -0
- package/dist/react/runtime.js +54 -0
- package/dist/react/runtime.js.map +1 -0
- package/dist/react/store.d.ts +333 -0
- package/dist/react/store.d.ts.map +1 -0
- package/dist/react/store.js +695 -0
- package/dist/react/store.js.map +1 -0
- package/dist/relay/auth.d.ts +244 -0
- package/dist/relay/auth.d.ts.map +1 -0
- package/dist/relay/auth.js +391 -0
- package/dist/relay/auth.js.map +1 -0
- package/dist/relay/frames.d.ts +141 -0
- package/dist/relay/frames.d.ts.map +1 -0
- package/dist/relay/frames.js +20 -0
- package/dist/relay/frames.js.map +1 -0
- package/dist/relay/index.d.ts +8 -0
- package/dist/relay/index.d.ts.map +1 -0
- package/dist/relay/index.js +4 -0
- package/dist/relay/index.js.map +1 -0
- package/dist/relay/relay.d.ts +277 -0
- package/dist/relay/relay.d.ts.map +1 -0
- package/dist/relay/relay.js +1026 -0
- package/dist/relay/relay.js.map +1 -0
- package/dist/relay/serve.d.ts +33 -0
- package/dist/relay/serve.d.ts.map +1 -0
- package/dist/relay/serve.js +86 -0
- package/dist/relay/serve.js.map +1 -0
- package/dist/widget/chat.d.ts +290 -0
- package/dist/widget/chat.d.ts.map +1 -0
- package/dist/widget/chat.js +486 -0
- package/dist/widget/chat.js.map +1 -0
- package/dist/widget/css.d.ts +49 -0
- package/dist/widget/css.d.ts.map +1 -0
- package/dist/widget/css.js +532 -0
- package/dist/widget/css.js.map +1 -0
- package/dist/widget/dom.d.ts +143 -0
- package/dist/widget/dom.d.ts.map +1 -0
- package/dist/widget/dom.js +27 -0
- package/dist/widget/dom.js.map +1 -0
- package/dist/widget/highlight.d.ts +64 -0
- package/dist/widget/highlight.d.ts.map +1 -0
- package/dist/widget/highlight.js +136 -0
- package/dist/widget/highlight.js.map +1 -0
- package/dist/widget/index.d.ts +9 -0
- package/dist/widget/index.d.ts.map +1 -0
- package/dist/widget/index.js +20 -0
- package/dist/widget/index.js.map +1 -0
- package/dist/widget/position.d.ts +166 -0
- package/dist/widget/position.d.ts.map +1 -0
- package/dist/widget/position.js +497 -0
- package/dist/widget/position.js.map +1 -0
- package/dist/widget/settings.d.ts +116 -0
- package/dist/widget/settings.d.ts.map +1 -0
- package/dist/widget/settings.js +117 -0
- package/dist/widget/settings.js.map +1 -0
- package/dist/widget/widget.d.ts +442 -0
- package/dist/widget/widget.d.ts.map +1 -0
- package/dist/widget/widget.js +2005 -0
- package/dist/widget/widget.js.map +1 -0
- package/package.json +144 -4
|
@@ -0,0 +1,1026 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* driverkit/relay — the one place both parties can reach.
|
|
3
|
+
*
|
|
4
|
+
* Nothing can call into a browser tab, so the tab dials out and holds a stream
|
|
5
|
+
* open; the agent speaks ordinary request/response HTTP. The relay's whole job
|
|
6
|
+
* is to turn one into the other: a `POST /dk/tabs/:tab/call` blocks on an open
|
|
7
|
+
* promise until a `result` frame with the matching `id` arrives on a separate
|
|
8
|
+
* POST from that tab, and then answers with it.
|
|
9
|
+
*
|
|
10
|
+
* Two properties are worth stating before the code, because both are easy to
|
|
11
|
+
* break with a change that looks like a cleanup:
|
|
12
|
+
*
|
|
13
|
+
* THE RELAY GRANTS NO AUTHORITY. It forwards a verb name to a tab that is
|
|
14
|
+
* already logged in as a person. It never decides whether a call is allowed,
|
|
15
|
+
* never rewrites args, never interprets `rev`. Every refusal it originates
|
|
16
|
+
* is about reachability -- "no tab", "the tab went away", "the tab never
|
|
17
|
+
* answered" -- and never about the verb. The moment the relay has an opinion
|
|
18
|
+
* about a verb, there are two sets of rules and one of them is wrong.
|
|
19
|
+
*
|
|
20
|
+
* EVERY ANSWER IS A `WireResult`, AND THE BODY IS AUTHORITATIVE. An agent
|
|
21
|
+
* asking for a call gets the same shape at 200 whether the tab refused, the
|
|
22
|
+
* tab vanished, or the tab id was a typo. A 4xx here would conflate a
|
|
23
|
+
* transport failure with a business rule, and those want opposite handling:
|
|
24
|
+
* one is retry-elsewhere, the other is rephrase-and-retry. So a non-2xx from
|
|
25
|
+
* this relay means no `WireResult` was produced at all -- malformed body,
|
|
26
|
+
* unroutable path -- and never "the app said no".
|
|
27
|
+
*
|
|
28
|
+
* A relay refusal carries NO `snapshot`. The three it can originate are a
|
|
29
|
+
* closed set (`RelayRefusal`), and in none of them did anything run or
|
|
30
|
+
* anybody look. Inventing an empty snapshot would tell an agent the app has
|
|
31
|
+
* no rows, which is a lie about the app rather than about the call.
|
|
32
|
+
*
|
|
33
|
+
* CHOICES PROTOCOL.md LEAVES TO THE RELAY, recorded here so the next reader
|
|
34
|
+
* does not have to rediscover them by experiment:
|
|
35
|
+
*
|
|
36
|
+
* - A second `/dk/events` stream for a known tab id SUPERSEDES the first.
|
|
37
|
+
* The id is minted by the tab so a reconnect resumes identity; treating the
|
|
38
|
+
* second stream as a new tab would defeat the only reason the id exists.
|
|
39
|
+
* - Calls in flight CARRY ACROSS that supersede. A tab that was mid-verb when
|
|
40
|
+
* its stream blinked can still POST the result on the new one, and failing
|
|
41
|
+
* those would turn a recovered hiccup into an error the agent must handle.
|
|
42
|
+
* - `hello` UPSERTS FIELD BY FIELD. It arrives again after every reconnect and
|
|
43
|
+
* the app may have navigated in between, so the later one wins on each
|
|
44
|
+
* field it carries and leaves the others alone.
|
|
45
|
+
* - Everything in `hello` but `tab` is OPTIONAL. The consequence is a real
|
|
46
|
+
* window: a tab enters the registry when its stream opens and `hello` lands
|
|
47
|
+
* a moment later on a separate POST. During it `/manifest` answers 404
|
|
48
|
+
* rather than an empty verb list, because an empty list is a false claim
|
|
49
|
+
* that the app has no verbs.
|
|
50
|
+
* - `attach()` is MIDDLEWARE, not a prepended listener. See the comment on it.
|
|
51
|
+
*
|
|
52
|
+
* A TAB BELONGS TO A PRINCIPAL, AND THE REGISTRY KEY SAYS SO. Tabs are
|
|
53
|
+
* stored under `principal\u0000tab`, not under the tab id alone. That is not a
|
|
54
|
+
* check, it is a shape: there is no lookup by bare tab id anywhere in this
|
|
55
|
+
* file, so a caller cannot reach another principal's tab through a code path
|
|
56
|
+
* somebody adds next year and forgets to guard. It also removes the question
|
|
57
|
+
* of what to do when two people mint the same tab id -- nothing, they are two
|
|
58
|
+
* tabs -- and with it an existence oracle for other people's ids.
|
|
59
|
+
*
|
|
60
|
+
* Isolation is NOT authorisation. A credential buys its holder nothing they
|
|
61
|
+
* could not already do in their own browser; it tells the relay which
|
|
62
|
+
* hundredth of its registry to show them. See `auth.ts`.
|
|
63
|
+
*
|
|
64
|
+
* Zero dependencies: `node:http` types and `node:crypto` only.
|
|
65
|
+
*/
|
|
66
|
+
import { AuthError, LOCAL_PRINCIPAL, TabAuth, credentialFrom } from "./auth.js";
|
|
67
|
+
const SSE_HEADERS = {
|
|
68
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
69
|
+
"cache-control": "no-cache, no-transform",
|
|
70
|
+
connection: "keep-alive",
|
|
71
|
+
// Nginx buffers proxied responses by default, which turns a live stream into
|
|
72
|
+
// one that arrives when it ends. The ping comments keep the connection open;
|
|
73
|
+
// this keeps the bytes moving.
|
|
74
|
+
"x-accel-buffering": "no",
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* 1 MiB, pinned by PROTOCOL.md, and over it is a 413.
|
|
78
|
+
*
|
|
79
|
+
* Not a limit to raise. A snapshot approaching this size is a bug in the app's
|
|
80
|
+
* `visible()` -- the whole design says an agent sees a screenful, so a megabyte
|
|
81
|
+
* of rows means the page is reporting its database rather than its screen.
|
|
82
|
+
*/
|
|
83
|
+
const MAX_BODY = 1 << 20;
|
|
84
|
+
/** Past this, the sender is not going to stop and the connection goes. See
|
|
85
|
+
* `readJson` for why the limit itself is not enforced by hanging up. */
|
|
86
|
+
const ABORT_AT = MAX_BODY * 16;
|
|
87
|
+
/**
|
|
88
|
+
* The 401's challenge header. `Bearer` names the scheme an agent should use;
|
|
89
|
+
* the realm is fixed, because a realm that named the app or the principal
|
|
90
|
+
* would be a 401 that leaks who else is here.
|
|
91
|
+
*/
|
|
92
|
+
const AUTH_HEADERS = { "www-authenticate": 'Bearer realm="driverkit"' };
|
|
93
|
+
/**
|
|
94
|
+
* The hint on every `no-such-tab`, whatever the real reason.
|
|
95
|
+
*
|
|
96
|
+
* One string, with no tab id in it, because the four reasons an agent can get
|
|
97
|
+
* this -- never minted, closed, somebody else's, outside a tab-bound
|
|
98
|
+
* credential's reach -- must be one answer. A hint that said "no tab `abc` is
|
|
99
|
+
* connected" for one and something else for another would make the endpoint
|
|
100
|
+
* the membership test the status code was carefully chosen not to be.
|
|
101
|
+
*/
|
|
102
|
+
const NO_SUCH_TAB_HINT = "no such tab is connected";
|
|
103
|
+
/** The principal every request is, with auth off. */
|
|
104
|
+
const LOCAL = { id: LOCAL_PRINCIPAL };
|
|
105
|
+
function no400(error, why) {
|
|
106
|
+
return { ok: false, status: 400, error, why };
|
|
107
|
+
}
|
|
108
|
+
export function createRelay(options = {}) {
|
|
109
|
+
const timeoutMs = options.timeoutMs ?? 60_000;
|
|
110
|
+
const pingMs = options.pingMs ?? 20_000;
|
|
111
|
+
const allowRemote = options.allowRemote ?? false;
|
|
112
|
+
const auth = options.auth;
|
|
113
|
+
const resolvePrincipal = options.resolvePrincipal;
|
|
114
|
+
const onError = options.onError ?? (() => { });
|
|
115
|
+
const onAudit = options.onAudit;
|
|
116
|
+
/**
|
|
117
|
+
* Hand one record to the host, and survive the host.
|
|
118
|
+
*
|
|
119
|
+
* A throw goes to `onError`, which is where everything else this relay
|
|
120
|
+
* cannot help goes, rather than to the caller: a 500 because the logging
|
|
121
|
+
* backend is down would make an audit trail into an outage. Not awaited --
|
|
122
|
+
* nothing here is async, and a hook that wants to be is the host's business.
|
|
123
|
+
*/
|
|
124
|
+
const audit = (principal, tab, verb, started, outcome) => {
|
|
125
|
+
if (onAudit === undefined)
|
|
126
|
+
return;
|
|
127
|
+
const at = Date.now();
|
|
128
|
+
try {
|
|
129
|
+
onAudit({ at, ms: at - started, principal, tab, verb, outcome });
|
|
130
|
+
}
|
|
131
|
+
catch (err) {
|
|
132
|
+
onError(err);
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
if (allowRemote && !auth && !resolvePrincipal) {
|
|
136
|
+
// Thrown at construction, before a socket exists, for the same reason
|
|
137
|
+
// `serve()` refuses a non-loopback host there: a misconfiguration that
|
|
138
|
+
// surfaced later is one somebody forgot to check, and the failure mode of
|
|
139
|
+
// forgetting is a listening public port that drives strangers' browsers.
|
|
140
|
+
throw new Error("driverkit: allowRemote needs auth or resolvePrincipal. A relay that serves " +
|
|
141
|
+
"non-loopback callers and cannot tell them apart is every connected tab offered to " +
|
|
142
|
+
'every caller. Read "Who is allowed to do this" in PROTOCOL.md, then pass ' +
|
|
143
|
+
"auth: new TabAuth({ secret, audience }).");
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Connected tabs, keyed by `principal\u0000tab`.
|
|
147
|
+
*
|
|
148
|
+
* The pair, never the bare id. A NUL joins them because it cannot occur in a
|
|
149
|
+
* principal id or a tab id that arrived as a URL path segment, so there is no
|
|
150
|
+
* pair of distinct identities that collides into one key -- which a `:`
|
|
151
|
+
* separator would allow for an id containing a colon.
|
|
152
|
+
*/
|
|
153
|
+
const tabs = new Map();
|
|
154
|
+
/**
|
|
155
|
+
* `GET /dk/tabs/:tab/watch` subscribers, keyed by tab id.
|
|
156
|
+
*
|
|
157
|
+
* A SET, because PROTOCOL.md requires every watcher to get the frames: two
|
|
158
|
+
* agents beside one human is the shared-presence case, and a single-slot
|
|
159
|
+
* registry would silently make the second one blind rather than refuse it.
|
|
160
|
+
*
|
|
161
|
+
* Kept OUTSIDE the tab record on purpose. A tab record dies with its stream,
|
|
162
|
+
* and a watcher must survive the page reloading -- that reload is one of the
|
|
163
|
+
* things it is watching for.
|
|
164
|
+
*/
|
|
165
|
+
const watchers = new Map();
|
|
166
|
+
/** The rev last broadcast per tab, so a refusal that moved nothing is quiet. */
|
|
167
|
+
const broadcast = new Map();
|
|
168
|
+
const key = (principal, tabId) => `${principal}\u0000${tabId}`;
|
|
169
|
+
/**
|
|
170
|
+
* The caller's tab, or undefined. The ONLY way this file finds a tab.
|
|
171
|
+
*
|
|
172
|
+
* `undefined` covers three cases on purpose -- no such tab, somebody else's
|
|
173
|
+
* tab, and a tab outside what a tab-bound credential may address -- and every
|
|
174
|
+
* caller turns it into the same `no-such-tab`. Collapsing them here rather
|
|
175
|
+
* than at each endpoint is what makes the property hold for an endpoint added
|
|
176
|
+
* later: there is no lookup by bare tab id to reach for.
|
|
177
|
+
*/
|
|
178
|
+
function owned(who, tabId) {
|
|
179
|
+
if (who.tab !== undefined && who.tab !== tabId)
|
|
180
|
+
return undefined;
|
|
181
|
+
return tabs.get(key(who.id, tabId));
|
|
182
|
+
}
|
|
183
|
+
let nextCall = 1;
|
|
184
|
+
let closed = false;
|
|
185
|
+
function send(tab, frame) {
|
|
186
|
+
try {
|
|
187
|
+
// The event name matters: the page listens for `call` specifically, so an
|
|
188
|
+
// unnamed `message` would be silently dropped by `EventSource`.
|
|
189
|
+
tab.res.write(`event: ${frame.t}\ndata: ${JSON.stringify(frame)}\n\n`);
|
|
190
|
+
return true;
|
|
191
|
+
}
|
|
192
|
+
catch (err) {
|
|
193
|
+
onError(err);
|
|
194
|
+
return false;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Open a tab's stream and BIND the tab to the caller's principal.
|
|
199
|
+
*
|
|
200
|
+
* The binding happens here, at first contact, rather than on `hello`.
|
|
201
|
+
* PROTOCOL.md already describes the window between a stream opening and its
|
|
202
|
+
* `hello` landing on a separate POST; binding at `hello` would make that a
|
|
203
|
+
* window in which a tab exists and belongs to nobody, and an unowned tab is
|
|
204
|
+
* one every principal either can or cannot see, both of which are wrong.
|
|
205
|
+
*
|
|
206
|
+
* What this means for a credential that expires MID-SESSION: nothing. The
|
|
207
|
+
* binding is the relay's record and lasts as long as the stream, not as long
|
|
208
|
+
* as the token. A relay that hung up at `exp` would disconnect every tab in
|
|
209
|
+
* the deployment once per token lifetime, mid-verb, while a person watched --
|
|
210
|
+
* and the fix people reach for, a longer lifetime, is strictly worse because
|
|
211
|
+
* it also widens the window a leaked token is useful in. Short tokens plus a
|
|
212
|
+
* binding that outlives them gives both.
|
|
213
|
+
*
|
|
214
|
+
* The credential is still needed for `POST /dk/result`, which is a new
|
|
215
|
+
* request and carries its own; see `connect`'s token getter, which is a
|
|
216
|
+
* function for exactly this reason.
|
|
217
|
+
*/
|
|
218
|
+
function openStream(who, tabId, req, res) {
|
|
219
|
+
const id = key(who.id, tabId);
|
|
220
|
+
res.writeHead(200, SSE_HEADERS);
|
|
221
|
+
// A first comment byte makes the browser fire `open` now rather than when
|
|
222
|
+
// the first real frame happens to arrive, and `open` is where the page
|
|
223
|
+
// sends `hello`. Without it a freshly loaded tab is connected but unknown.
|
|
224
|
+
res.write(": driverkit\n\n");
|
|
225
|
+
const existing = tabs.get(id);
|
|
226
|
+
const ping = setInterval(() => {
|
|
227
|
+
try {
|
|
228
|
+
// A comment line, per PROTOCOL.md: it carries nothing, and a comment
|
|
229
|
+
// cannot be mistaken for a frame by a client that does not know it.
|
|
230
|
+
res.write(": ping\n\n");
|
|
231
|
+
}
|
|
232
|
+
catch (err) {
|
|
233
|
+
onError(err);
|
|
234
|
+
}
|
|
235
|
+
}, pingMs);
|
|
236
|
+
// The relay must never be the reason a process will not exit; a test that
|
|
237
|
+
// forgets `close()` should fail loudly, not hang.
|
|
238
|
+
ping.unref?.();
|
|
239
|
+
const tab = existing
|
|
240
|
+
? // A second stream for a known id is a reconnect, not a new tab: the id
|
|
241
|
+
// is minted by the tab precisely so it survives one. Carry the known
|
|
242
|
+
// facts and the calls in flight across -- a tab that was mid-verb when
|
|
243
|
+
// its stream blinked can still POST the result on the new one, and
|
|
244
|
+
// failing those calls would turn a recovered hiccup into an error the
|
|
245
|
+
// agent has to handle.
|
|
246
|
+
{ ...existing, res, ping, since: existing.since }
|
|
247
|
+
: {
|
|
248
|
+
tab: tabId,
|
|
249
|
+
principal: who.id,
|
|
250
|
+
since: new Date().toISOString(),
|
|
251
|
+
res,
|
|
252
|
+
ping,
|
|
253
|
+
pending: new Map(),
|
|
254
|
+
};
|
|
255
|
+
if (existing && existing.res !== res) {
|
|
256
|
+
clearInterval(existing.ping);
|
|
257
|
+
try {
|
|
258
|
+
existing.res.end();
|
|
259
|
+
}
|
|
260
|
+
catch (err) {
|
|
261
|
+
onError(err);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
tabs.set(id, tab);
|
|
265
|
+
const gone = () => {
|
|
266
|
+
clearInterval(ping);
|
|
267
|
+
// Only drop the registry entry if it is still OURS. A reconnect replaces
|
|
268
|
+
// the record first and then ends the old response, so the old `close`
|
|
269
|
+
// fires afterwards and would otherwise delete the live tab.
|
|
270
|
+
if (tabs.get(id) !== tab)
|
|
271
|
+
return;
|
|
272
|
+
tabs.delete(id);
|
|
273
|
+
// Fail what is in flight instead of letting each call sit out its own
|
|
274
|
+
// timeout. The answer is already known -- nobody is going to reply -- and
|
|
275
|
+
// "no queue" means the agent learns that now, while it still has the
|
|
276
|
+
// context to try something else.
|
|
277
|
+
for (const [, p] of tab.pending) {
|
|
278
|
+
clearTimeout(p.timer);
|
|
279
|
+
p.settle(relayRefusal("tab-went-away", `tab \`${tabId}\` closed its stream`), "tab-went-away");
|
|
280
|
+
}
|
|
281
|
+
tab.pending.clear();
|
|
282
|
+
};
|
|
283
|
+
res.on("close", gone);
|
|
284
|
+
req.on("aborted", gone);
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* One tab->relay frame.
|
|
288
|
+
*
|
|
289
|
+
* A TAB MAY NOT ANSWER ANOTHER TAB'S CALL, and two things enforce it. A tab
|
|
290
|
+
* the caller does not own is not found at all (`owned`), so the
|
|
291
|
+
* cross-PERSON case is the same 409 as a tab that is not connected. Within
|
|
292
|
+
* one person, who legitimately has several tabs open, `pending` is per-tab-
|
|
293
|
+
* record and call ids are unique across the relay, so a `result` for a call
|
|
294
|
+
* issued to another of their tabs finds nothing to settle and is dropped as a
|
|
295
|
+
* late answer. A credential carrying a `tab` claim closes that case
|
|
296
|
+
* cryptographically as well; without one, the pending map is what holds,
|
|
297
|
+
* which is a weaker statement and is said here rather than assumed.
|
|
298
|
+
*/
|
|
299
|
+
function ingest(who, frame, tabId) {
|
|
300
|
+
const id = frame.t === "hello" ? frame.tab : (tabId ?? frame.tab);
|
|
301
|
+
// 400, not 409: a frame that names no tab is malformed. There is no state
|
|
302
|
+
// of the relay under which it could have been accepted, which is what 4xx
|
|
303
|
+
// against 409 is supposed to tell the sender.
|
|
304
|
+
if (!id)
|
|
305
|
+
return no400("unplaceable", "no tab id: pass ?tab= or a `tab` field");
|
|
306
|
+
const tab = owned(who, id);
|
|
307
|
+
// A tab that belongs to someone else lands here too, with the same body,
|
|
308
|
+
// which is the oracle rule applied to the tab's own endpoint: "not yours"
|
|
309
|
+
// and "not connected" must be one answer.
|
|
310
|
+
if (!tab)
|
|
311
|
+
return { ok: false, status: 409, error: "no-such-tab", why: NO_SUCH_TAB_HINT };
|
|
312
|
+
switch (frame.t) {
|
|
313
|
+
case "hello": {
|
|
314
|
+
// Upsert, not insert. `hello` arrives again after every reconnect, and
|
|
315
|
+
// the app may have navigated in between, so the later one wins on every
|
|
316
|
+
// field it carries.
|
|
317
|
+
if (frame.app !== undefined)
|
|
318
|
+
tab.app = frame.app;
|
|
319
|
+
if (frame.title !== undefined)
|
|
320
|
+
tab.title = frame.title;
|
|
321
|
+
if (frame.url !== undefined)
|
|
322
|
+
tab.url = frame.url;
|
|
323
|
+
if (frame.focus !== undefined)
|
|
324
|
+
tab.focus = frame.focus;
|
|
325
|
+
if (frame.manifest !== undefined)
|
|
326
|
+
tab.manifest = frame.manifest;
|
|
327
|
+
if (frame.snapshot !== undefined) {
|
|
328
|
+
tab.snapshot = frame.snapshot;
|
|
329
|
+
push(tab);
|
|
330
|
+
}
|
|
331
|
+
return { ok: true };
|
|
332
|
+
}
|
|
333
|
+
case "snapshot": {
|
|
334
|
+
tab.snapshot = frame.snapshot;
|
|
335
|
+
// The same upsert rule `hello` uses, on the two fields a push may now
|
|
336
|
+
// carry. `url` is here because it had no other way of ever being
|
|
337
|
+
// right: it came from `hello` alone, and a single-page app navigates
|
|
338
|
+
// without reconnecting, so a tab's url in `/dk/tabs` was whatever it
|
|
339
|
+
// had been at page load. Absent leaves the stored value alone, which
|
|
340
|
+
// is what keeps a tab connected by a hand-written loop -- or by a
|
|
341
|
+
// driverkit older than this field -- reading exactly as it did.
|
|
342
|
+
if (frame.url !== undefined)
|
|
343
|
+
tab.url = frame.url;
|
|
344
|
+
if (frame.focus !== undefined)
|
|
345
|
+
tab.focus = frame.focus;
|
|
346
|
+
// Always forwarded, even at an unchanged rev. This frame is the tab
|
|
347
|
+
// SAYING the page moved, and second-guessing it here would make the
|
|
348
|
+
// relay the thing that decides what counts as a change -- which is the
|
|
349
|
+
// app's judgement, carried in `rev`, not the relay's.
|
|
350
|
+
push(tab, true);
|
|
351
|
+
return { ok: true };
|
|
352
|
+
}
|
|
353
|
+
case "result": {
|
|
354
|
+
// Checked BEFORE the pending lookup, and the call is deliberately left
|
|
355
|
+
// pending when it fails.
|
|
356
|
+
//
|
|
357
|
+
// This is the one promise `/call` makes: the body is always a
|
|
358
|
+
// `WireResult`. Settling with a non-object would put `undefined`
|
|
359
|
+
// through `JSON.stringify` and answer the agent a body that is
|
|
360
|
+
// literally the four characters `null` -- or nothing at all -- which no
|
|
361
|
+
// client can parse and which no amount of careful client code can
|
|
362
|
+
// recover from. Rejecting the frame instead leaves the call to time out
|
|
363
|
+
// honestly: `timeout` is a documented unknown outcome, and an unknown
|
|
364
|
+
// outcome is a far better thing to hand an agent than garbage.
|
|
365
|
+
if (typeof frame.result !== "object" || frame.result === null || Array.isArray(frame.result)) {
|
|
366
|
+
return no400("bad-frame", `the \`result\` for \`${frame.id}\` is not an object`);
|
|
367
|
+
}
|
|
368
|
+
const pending = tab.pending.get(frame.id);
|
|
369
|
+
// An id the relay is not waiting on is dropped, not an error. It means
|
|
370
|
+
// the call already timed out and the tab answered late; resurrecting it
|
|
371
|
+
// would deliver an answer to a request that has already been responded
|
|
372
|
+
// to.
|
|
373
|
+
if (!pending)
|
|
374
|
+
return { ok: true, why: `no call \`${frame.id}\` in flight` };
|
|
375
|
+
tab.pending.delete(frame.id);
|
|
376
|
+
clearTimeout(pending.timer);
|
|
377
|
+
// The `Result` is forwarded byte for byte. A `stale` refusal the driver
|
|
378
|
+
// produced must reach the agent as the driver wrote it, hint and
|
|
379
|
+
// snapshot included -- that hint is how the agent knows to re-read
|
|
380
|
+
// instead of retrying the same dead rev.
|
|
381
|
+
if (frame.result?.snapshot) {
|
|
382
|
+
tab.snapshot = frame.result.snapshot;
|
|
383
|
+
// Watchers hear about an agent's change too, not only a human's.
|
|
384
|
+
// `/watch` exists so a watcher need not poll; one that learned only
|
|
385
|
+
// about human-caused moves would still have to poll for the rest,
|
|
386
|
+
// which is the cost the endpoint was added to remove. Deduped on
|
|
387
|
+
// `rev`, so a refusal that moved nothing stays quiet.
|
|
388
|
+
push(tab);
|
|
389
|
+
}
|
|
390
|
+
// `delivered`, and nothing more. The tab answered; what it answered is
|
|
391
|
+
// the driver's own record to make, in the process where it was decided.
|
|
392
|
+
// The tab's own elapsed time rides along on the answer and is NOT in
|
|
393
|
+
// the record: see `timed`, and `RelayAuditEvent` for the argument.
|
|
394
|
+
pending.settle(timed(frame.result, frame), "delivered");
|
|
395
|
+
return { ok: true };
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
function dispatch(who, tabId, body) {
|
|
400
|
+
// Null means "this was never a call", and the caller answers non-2xx. A
|
|
401
|
+
// body with no `name` is malformed, not refused: there is no verb to have
|
|
402
|
+
// said no, so dressing it as a `WireResult` would teach an agent to look
|
|
403
|
+
// for a `bad-request` slug that the closed set does not contain.
|
|
404
|
+
if (typeof body.name !== "string" || !body.name)
|
|
405
|
+
return null;
|
|
406
|
+
// Before the lookup, so `ms` is the time the agent actually waited and not
|
|
407
|
+
// the time minus whatever the registry cost.
|
|
408
|
+
const started = Date.now();
|
|
409
|
+
const tab = owned(who, tabId);
|
|
410
|
+
if (!tab) {
|
|
411
|
+
// Shaped like every other answer. An agent holding a tab id from a
|
|
412
|
+
// closed window gets a refusal it can read with the same code path it
|
|
413
|
+
// uses for "that row is not deletable".
|
|
414
|
+
//
|
|
415
|
+
// And a tab belonging to another principal gets THIS, not a 403: a
|
|
416
|
+
// refusal an agent reads as "that window is gone", identical in status,
|
|
417
|
+
// slug and hint to one for an id that was never minted. A 403 here would
|
|
418
|
+
// turn /call into a membership test for other people's tab ids.
|
|
419
|
+
// Recorded, and this is the half of the trail the driver cannot have:
|
|
420
|
+
// nothing reached a tab, so no `onAudit` anywhere else in the library
|
|
421
|
+
// will ever hear about this call. An agent working through tab ids it
|
|
422
|
+
// does not own leaves its marks only here.
|
|
423
|
+
audit(who.id, tabId, body.name, started, "no-such-tab");
|
|
424
|
+
return Promise.resolve(relayRefusal("no-such-tab", `${NO_SUCH_TAB_HINT}; GET /dk/tabs to list them`));
|
|
425
|
+
}
|
|
426
|
+
const id = `c-${nextCall++}`;
|
|
427
|
+
const frame = {
|
|
428
|
+
t: "call",
|
|
429
|
+
id,
|
|
430
|
+
name: body.name,
|
|
431
|
+
...(body.args && typeof body.args === "object" ? { args: body.args } : {}),
|
|
432
|
+
// Forwarded only when the agent sent one. Defaulting it would silently
|
|
433
|
+
// opt an agent into a staleness check it did not ask for; dropping it
|
|
434
|
+
// would silently opt it out of one it did. Neither is the relay's call.
|
|
435
|
+
...(typeof body.rev === "number" ? { rev: body.rev } : {}),
|
|
436
|
+
// `screen` on exactly the same terms, and with the same restraint: the
|
|
437
|
+
// relay does not know which screen the tab is on, does not compare it,
|
|
438
|
+
// and does not refuse it. It is the agent's claim and the driver's check.
|
|
439
|
+
// An empty string is dropped rather than forwarded, because it is not the
|
|
440
|
+
// id of any screen and no app should be asked to refuse a call over a
|
|
441
|
+
// field left blank.
|
|
442
|
+
...(typeof body.screen === "string" && body.screen ? { screen: body.screen } : {}),
|
|
443
|
+
// `plan` on the same terms again, and here the restraint is not even a
|
|
444
|
+
// choice: the token is opaque to everything but the core that minted it,
|
|
445
|
+
// so a relay has nothing to compare it against and could only ever get
|
|
446
|
+
// the comparison wrong. Dropped when blank, like `screen`, because an
|
|
447
|
+
// empty string is not a token and the core's refusal should name the
|
|
448
|
+
// field the agent actually left out.
|
|
449
|
+
...(typeof body.plan === "string" && body.plan ? { plan: body.plan } : {}),
|
|
450
|
+
};
|
|
451
|
+
return new Promise((resolve) => {
|
|
452
|
+
let done = false;
|
|
453
|
+
const settle = (r, outcome) => {
|
|
454
|
+
if (done)
|
|
455
|
+
return;
|
|
456
|
+
done = true;
|
|
457
|
+
// ONE record per call, from the one place a call can be answered. The
|
|
458
|
+
// `done` guard above is what makes it one: the deadline and a late
|
|
459
|
+
// `result` frame race, and the loser must not log a second outcome for
|
|
460
|
+
// a call that has already been answered.
|
|
461
|
+
audit(who.id, tabId, frame.name, started, outcome);
|
|
462
|
+
resolve(r);
|
|
463
|
+
};
|
|
464
|
+
const timer = setTimeout(() => {
|
|
465
|
+
tab.pending.delete(id);
|
|
466
|
+
// NOT a promise the call did not happen. The tab may have run the verb
|
|
467
|
+
// and died before answering, so a `commit` that times out has an
|
|
468
|
+
// unknown outcome and the agent must read the screen before retrying.
|
|
469
|
+
// The relay says only "no answer arrived"; guessing further here is how
|
|
470
|
+
// every client ends up inventing a different guess.
|
|
471
|
+
settle(relayRefusal("timeout", `tab \`${tabId}\` did not answer \`${frame.name}\` within ${timeoutMs}ms`), "timeout");
|
|
472
|
+
}, timeoutMs);
|
|
473
|
+
timer.unref?.();
|
|
474
|
+
tab.pending.set(id, { settle, timer });
|
|
475
|
+
if (!send(tab, frame)) {
|
|
476
|
+
tab.pending.delete(id);
|
|
477
|
+
clearTimeout(timer);
|
|
478
|
+
settle(relayRefusal("tab-went-away", `writing to tab \`${tabId}\` failed`), "tab-went-away");
|
|
479
|
+
}
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
const handler = (req, res) => {
|
|
483
|
+
const raw = req.url ?? "/";
|
|
484
|
+
const qmark = raw.indexOf("?");
|
|
485
|
+
const path = qmark === -1 ? raw : raw.slice(0, qmark);
|
|
486
|
+
if (!path.startsWith("/dk/"))
|
|
487
|
+
return false;
|
|
488
|
+
if (closed) {
|
|
489
|
+
json(res, 503, { error: "relay closed" });
|
|
490
|
+
return true;
|
|
491
|
+
}
|
|
492
|
+
if (!allowRemote && !isLoopback(req.socket.remoteAddress)) {
|
|
493
|
+
// Refused here rather than by not binding, because `attach()` means the
|
|
494
|
+
// relay often does not own the listening socket and so cannot choose the
|
|
495
|
+
// interface. The check has to live where the requests are.
|
|
496
|
+
json(res, 403, {
|
|
497
|
+
error: "forbidden",
|
|
498
|
+
hint: "this relay drives a logged-in browser session; set allowRemote and put your app's own auth in front of it",
|
|
499
|
+
});
|
|
500
|
+
return true;
|
|
501
|
+
}
|
|
502
|
+
const query = new URLSearchParams(qmark === -1 ? "" : raw.slice(qmark + 1));
|
|
503
|
+
const method = req.method ?? "GET";
|
|
504
|
+
// Identity BEFORE routing. A caller who cannot be identified is told that
|
|
505
|
+
// and nothing else -- not which methods a path takes, not whether the path
|
|
506
|
+
// exists. Authenticating after routing is how an unauthorised caller gets
|
|
507
|
+
// to map the surface.
|
|
508
|
+
const who = whoami(req);
|
|
509
|
+
if (!("id" in who)) {
|
|
510
|
+
// The body is drained first for the same reason a 405 drains it: bytes
|
|
511
|
+
// left in the socket become the next request on a keep-alive connection.
|
|
512
|
+
void drain(req);
|
|
513
|
+
json(res, 401, { error: who.error, hint: who.hint }, AUTH_HEADERS);
|
|
514
|
+
return true;
|
|
515
|
+
}
|
|
516
|
+
// --- the two the tab uses --------------------------------------------
|
|
517
|
+
if (path === "/dk/events") {
|
|
518
|
+
if (method !== "GET")
|
|
519
|
+
return bad(res, 405, "GET only", "bad-method");
|
|
520
|
+
const tabId = query.get("tab");
|
|
521
|
+
if (!tabId)
|
|
522
|
+
return bad(res, 400, "GET /dk/events needs ?tab=");
|
|
523
|
+
if (who.tab !== undefined && who.tab !== tabId) {
|
|
524
|
+
// 403 and not `no-such-tab`, and the difference is the point. The
|
|
525
|
+
// oracle rule is about ADDRESSING somebody else's tab; this caller is
|
|
526
|
+
// opening its own and presented a credential bound to a different id,
|
|
527
|
+
// which it already knows. Telling it so leaks nothing and is the only
|
|
528
|
+
// answer it can act on.
|
|
529
|
+
return bad(res, 403, "this credential is bound to another tab id", "forbidden");
|
|
530
|
+
}
|
|
531
|
+
openStream(who, tabId, req, res);
|
|
532
|
+
return true;
|
|
533
|
+
}
|
|
534
|
+
if (path === "/dk/result") {
|
|
535
|
+
if (method !== "POST")
|
|
536
|
+
return bad(res, 405, "POST only", "bad-method");
|
|
537
|
+
void readJson(req).then((body) => {
|
|
538
|
+
if (!body || typeof body !== "object")
|
|
539
|
+
return bad(res, 400, "expected a JSON frame");
|
|
540
|
+
const frame = body;
|
|
541
|
+
if (frame.t !== "hello" && frame.t !== "result" && frame.t !== "snapshot") {
|
|
542
|
+
return bad(res, 400, "unknown frame `t`", "bad-frame");
|
|
543
|
+
}
|
|
544
|
+
const out = ingest(who, frame, query.get("tab") ?? undefined);
|
|
545
|
+
if (!out.ok)
|
|
546
|
+
return bad(res, out.status ?? 400, out.why ?? "rejected", out.error ?? "bad-frame");
|
|
547
|
+
// 202, not 200: the tab is told its frame was accepted, and nothing
|
|
548
|
+
// more. The answer to a call travels to the AGENT, not back up this
|
|
549
|
+
// POST, so a body here would be an invitation to build a second,
|
|
550
|
+
// divergent return path.
|
|
551
|
+
json(res, 202, { ok: true, ...(out.why ? { note: out.why } : {}) });
|
|
552
|
+
}, (err) => {
|
|
553
|
+
onError(err);
|
|
554
|
+
const f = bodyFailure(err);
|
|
555
|
+
bad(res, f.status, f.hint, f.error);
|
|
556
|
+
});
|
|
557
|
+
return true;
|
|
558
|
+
}
|
|
559
|
+
// --- the four the agent uses -----------------------------------------
|
|
560
|
+
if (path === "/dk/tabs") {
|
|
561
|
+
if (method !== "GET")
|
|
562
|
+
return bad(res, 405, "GET only", "bad-method");
|
|
563
|
+
// The caller's own tabs, and never anybody else's. A listing of every
|
|
564
|
+
// connected tab is an inventory of other people's sessions with their
|
|
565
|
+
// titles and URLs attached, which is the single worst thing on this
|
|
566
|
+
// surface and was the default.
|
|
567
|
+
json(res, 200, { tabs: summaries(who.id, who.tab) });
|
|
568
|
+
return true;
|
|
569
|
+
}
|
|
570
|
+
const parts = path.split("/").filter(Boolean); // dk, tabs, :tab, leaf
|
|
571
|
+
if (parts.length === 4 && parts[1] === "tabs") {
|
|
572
|
+
const tabId = decodeURIComponent(parts[2]);
|
|
573
|
+
const leaf = parts[3];
|
|
574
|
+
if (leaf === "manifest" || leaf === "snapshot") {
|
|
575
|
+
if (method !== "GET")
|
|
576
|
+
return bad(res, 405, "GET only", "bad-method");
|
|
577
|
+
const tab = owned(who, tabId);
|
|
578
|
+
// Not Result-shaped, and that asymmetry is on purpose. A `Result` is
|
|
579
|
+
// the outcome of a CALL; these two read state, and wrapping "there is
|
|
580
|
+
// no such tab" in a fake `{ok:false, snapshot}` would hand the agent a
|
|
581
|
+
// snapshot that describes nothing. Only /call promises one shape,
|
|
582
|
+
// because only /call is the thing an agent must be able to handle
|
|
583
|
+
// uniformly.
|
|
584
|
+
//
|
|
585
|
+
// A tab somebody else owns answers exactly this, byte for byte, so the
|
|
586
|
+
// endpoint cannot be used to probe for other people's tab ids. Checked
|
|
587
|
+
// BEFORE the `no-manifest` case below: a foreign tab that has sent no
|
|
588
|
+
// manifest must not answer `no-manifest`, which would confirm it exists.
|
|
589
|
+
if (!tab)
|
|
590
|
+
return bad(res, 404, NO_SUCH_TAB_HINT, "no-such-tab");
|
|
591
|
+
const value = leaf === "manifest" ? tab.manifest : tab.snapshot;
|
|
592
|
+
if (!value)
|
|
593
|
+
return bad(res, 404, `tab \`${tabId}\` has sent no ${leaf}`, `no-${leaf}`);
|
|
594
|
+
json(res, 200, value);
|
|
595
|
+
return true;
|
|
596
|
+
}
|
|
597
|
+
if (leaf === "watch") {
|
|
598
|
+
if (method !== "GET")
|
|
599
|
+
return bad(res, 405, "GET only", "bad-method");
|
|
600
|
+
// 404 for a tab that is not connected, rather than an open stream that
|
|
601
|
+
// may never carry anything. Consistent with /snapshot, and it is the
|
|
602
|
+
// answer that tells a client to re-read /dk/tabs instead of waiting on
|
|
603
|
+
// a subscription to a screen that does not exist.
|
|
604
|
+
if (!owned(who, tabId))
|
|
605
|
+
return bad(res, 404, NO_SUCH_TAB_HINT, "no-such-tab");
|
|
606
|
+
openWatch(who, tabId, req, res);
|
|
607
|
+
return true;
|
|
608
|
+
}
|
|
609
|
+
if (leaf === "call") {
|
|
610
|
+
if (method !== "POST")
|
|
611
|
+
return bad(res, 405, "POST only", "bad-method");
|
|
612
|
+
void readJson(req).then((body) => {
|
|
613
|
+
const answer = dispatch(who, tabId, (body ?? {}));
|
|
614
|
+
if (!answer) {
|
|
615
|
+
// `bad` returns `true` for `handler`'s benefit -- that is how it
|
|
616
|
+
// says "answered, stop looking for a route" -- and returning it
|
|
617
|
+
// from an `onfulfilled` callback is a genuine signature error,
|
|
618
|
+
// not a missing type: a `then` handler must produce `void` or a
|
|
619
|
+
// promise, and `true` makes this branch and the one below
|
|
620
|
+
// disagree about what the chain resolves to. Discarded here, and
|
|
621
|
+
// discarded explicitly rather than by widening the callback's
|
|
622
|
+
// type, because the value is only meaningful to a caller that
|
|
623
|
+
// has a route to decline and this one does not.
|
|
624
|
+
bad(res, 400, "a call needs a `name`");
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
return answer.then((result) => {
|
|
628
|
+
// 200 even for a refusal. The HTTP layer succeeded: the question
|
|
629
|
+
// was asked and answered. `ok:false` is the answer, not a
|
|
630
|
+
// transport failure, and conflating the two is how an agent ends
|
|
631
|
+
// up retrying a refusal it should have read.
|
|
632
|
+
json(res, 200, result);
|
|
633
|
+
});
|
|
634
|
+
}, (err) => {
|
|
635
|
+
// Non-2xx, because no `WireResult` was produced: nothing was asked
|
|
636
|
+
// of any tab. An agent must read this as an exception, not a no.
|
|
637
|
+
onError(err);
|
|
638
|
+
const f = bodyFailure(err);
|
|
639
|
+
bad(res, f.status, f.hint, f.error);
|
|
640
|
+
});
|
|
641
|
+
return true;
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
return bad(res, 404, `no driverkit route ${method} ${path}`, "no-route");
|
|
645
|
+
};
|
|
646
|
+
/**
|
|
647
|
+
* Subscribe an agent to a tab's `snapshot` frames.
|
|
648
|
+
*
|
|
649
|
+
* The same SSE shape the tab's own stream uses, down to the opening comment
|
|
650
|
+
* and the ping, so a client needs one parser for both directions rather than
|
|
651
|
+
* two that drift.
|
|
652
|
+
*/
|
|
653
|
+
function openWatch(who, tabId, req, res) {
|
|
654
|
+
const id = key(who.id, tabId);
|
|
655
|
+
res.writeHead(200, SSE_HEADERS);
|
|
656
|
+
res.write(": driverkit\n\n");
|
|
657
|
+
let set = watchers.get(id);
|
|
658
|
+
if (!set)
|
|
659
|
+
watchers.set(id, (set = new Set()));
|
|
660
|
+
set.add(res);
|
|
661
|
+
// The current snapshot goes out immediately. A watcher that attached to an
|
|
662
|
+
// idle screen would otherwise know nothing at all until the next click,
|
|
663
|
+
// and would have to fetch /snapshot anyway -- which is the poll the
|
|
664
|
+
// endpoint exists to remove.
|
|
665
|
+
const known = tabs.get(id)?.snapshot;
|
|
666
|
+
if (known)
|
|
667
|
+
write(res, { t: "snapshot", tab: tabId, snapshot: known });
|
|
668
|
+
const ping = setInterval(() => write(res, null), pingMs);
|
|
669
|
+
ping.unref?.();
|
|
670
|
+
const gone = () => {
|
|
671
|
+
clearInterval(ping);
|
|
672
|
+
const live = watchers.get(id);
|
|
673
|
+
live?.delete(res);
|
|
674
|
+
if (live && live.size === 0)
|
|
675
|
+
watchers.delete(id);
|
|
676
|
+
};
|
|
677
|
+
res.on("close", gone);
|
|
678
|
+
req.on("aborted", gone);
|
|
679
|
+
}
|
|
680
|
+
/** Fan a tab's current snapshot out to its watchers. */
|
|
681
|
+
function push(tab, force = false) {
|
|
682
|
+
const snapshot = tab.snapshot;
|
|
683
|
+
if (!snapshot)
|
|
684
|
+
return;
|
|
685
|
+
const id = key(tab.principal, tab.tab);
|
|
686
|
+
if (!force && broadcast.get(id) === snapshot.rev)
|
|
687
|
+
return;
|
|
688
|
+
broadcast.set(id, snapshot.rev);
|
|
689
|
+
const set = watchers.get(id);
|
|
690
|
+
if (!set)
|
|
691
|
+
return;
|
|
692
|
+
const frame = { t: "snapshot", tab: tab.tab, snapshot };
|
|
693
|
+
// A copy, because a watcher that has hung up is removed from the set by its
|
|
694
|
+
// own `close` handler while this loop is running.
|
|
695
|
+
for (const res of [...set])
|
|
696
|
+
write(res, frame);
|
|
697
|
+
}
|
|
698
|
+
/** One SSE write: a frame, or a ping comment when `frame` is null. */
|
|
699
|
+
function write(res, frame) {
|
|
700
|
+
try {
|
|
701
|
+
res.write(frame ? `event: ${frame.t}\ndata: ${JSON.stringify(frame)}\n\n` : ": ping\n\n");
|
|
702
|
+
}
|
|
703
|
+
catch (err) {
|
|
704
|
+
onError(err);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
function summaries(principal, tab) {
|
|
708
|
+
return [...tabs.values()]
|
|
709
|
+
.filter((t) => (principal === undefined || t.principal === principal) &&
|
|
710
|
+
(tab === undefined || t.tab === tab))
|
|
711
|
+
.map((t) => ({
|
|
712
|
+
tab: t.tab,
|
|
713
|
+
...(t.app === undefined ? {} : { app: t.app }),
|
|
714
|
+
...(t.title === undefined ? {} : { title: t.title }),
|
|
715
|
+
...(t.url === undefined ? {} : { url: t.url }),
|
|
716
|
+
// Forwarded exactly as the tab said it, including not at all. Absence is
|
|
717
|
+
// "the tab did not say", which a client must not read as "not the one";
|
|
718
|
+
// see `TabFocus`. The relay has no opinion here and originates no value,
|
|
719
|
+
// for the same reason it does not interpret `rev`.
|
|
720
|
+
...(t.focus === undefined ? {} : { focus: t.focus }),
|
|
721
|
+
// The version, not the manifest. Listing tabs is the cheap call an agent
|
|
722
|
+
// makes often; inlining every manifest would make it the expensive one.
|
|
723
|
+
...(t.manifest === undefined ? {} : { manifestVersion: t.manifest.version }),
|
|
724
|
+
...(t.snapshot === undefined ? {} : { rev: t.snapshot.rev }),
|
|
725
|
+
since: t.since,
|
|
726
|
+
}));
|
|
727
|
+
}
|
|
728
|
+
/**
|
|
729
|
+
* The caller's principal, or the 401 to answer instead.
|
|
730
|
+
*
|
|
731
|
+
* Three doors, in this order:
|
|
732
|
+
*
|
|
733
|
+
* 1. AUTH OFF. Neither `auth` nor `resolvePrincipal` configured: everything
|
|
734
|
+
* is one principal and nothing is scoped. The unconfigured loopback relay
|
|
735
|
+
* a single developer runs, needing no tokens, no keys and no setup -- and
|
|
736
|
+
* the combination `allowRemote` makes impossible is the one where this is
|
|
737
|
+
* also exposed.
|
|
738
|
+
* 2. `resolvePrincipal`. The embedded case: an app that already has sessions
|
|
739
|
+
* answers from its own middleware.
|
|
740
|
+
* 3. THE CREDENTIAL. See `credentialFrom` for where it is read from.
|
|
741
|
+
*
|
|
742
|
+
* NO CREDENTIAL AND A BAD CREDENTIAL ARE DIFFERENT ANSWERS, and neither is
|
|
743
|
+
* "anonymous". Silently treating an unreadable credential as a fresh
|
|
744
|
+
* anonymous visitor was the tempting shape and is wrong twice over: a user
|
|
745
|
+
* whose token lapsed would quietly become a stranger and lose their own tabs,
|
|
746
|
+
* and an agent with a misconfigured key would be told "you have no tabs"
|
|
747
|
+
* rather than "your key is wrong". Anonymous is a credential of its own kind,
|
|
748
|
+
* so it is never what the absence of one means.
|
|
749
|
+
*/
|
|
750
|
+
function whoami(req) {
|
|
751
|
+
if (!auth && !resolvePrincipal)
|
|
752
|
+
return LOCAL;
|
|
753
|
+
const headers = req.headers;
|
|
754
|
+
if (resolvePrincipal) {
|
|
755
|
+
let resolved;
|
|
756
|
+
try {
|
|
757
|
+
resolved = resolvePrincipal(headers);
|
|
758
|
+
}
|
|
759
|
+
catch (err) {
|
|
760
|
+
// A host hook that throws must not become a 500 that mentions the app's
|
|
761
|
+
// internals, and must certainly not become an authenticated request.
|
|
762
|
+
// It is an unidentified caller.
|
|
763
|
+
onError(err);
|
|
764
|
+
}
|
|
765
|
+
if (resolved)
|
|
766
|
+
return { id: resolved };
|
|
767
|
+
}
|
|
768
|
+
if (!auth) {
|
|
769
|
+
return { error: "no-credential", hint: "this relay identifies callers by session" };
|
|
770
|
+
}
|
|
771
|
+
const url = req.url ?? "/";
|
|
772
|
+
const at = url.indexOf("?");
|
|
773
|
+
const credential = credentialFrom(headers, new URLSearchParams(at === -1 ? "" : url.slice(at + 1)));
|
|
774
|
+
if (!credential) {
|
|
775
|
+
return {
|
|
776
|
+
error: "no-credential",
|
|
777
|
+
hint: "present a tab token: Authorization: Bearer, X-DK-Token, the dk_token cookie, " +
|
|
778
|
+
"or ?dk_token= (the last of those ends up in proxy access logs)",
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
try {
|
|
782
|
+
return auth.principal(credential);
|
|
783
|
+
}
|
|
784
|
+
catch (err) {
|
|
785
|
+
if (!(err instanceof AuthError))
|
|
786
|
+
throw err;
|
|
787
|
+
// ONE slug for every way a credential can fail, and the hint is fixed.
|
|
788
|
+
// "The signature verified but the audience was wrong" tells a forger that
|
|
789
|
+
// the forgery worked; "expired" and "not yet valid" tell a prober the
|
|
790
|
+
// clock. A legitimate client's move is the same in every case -- mint a
|
|
791
|
+
// fresh token, retry once -- so the distinction buys it nothing and buys
|
|
792
|
+
// an attacker a test harness. The reason is never logged either: it would
|
|
793
|
+
// be a log line about a credential.
|
|
794
|
+
return { error: "bad-credential", hint: "present a fresh tab token" };
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
return {
|
|
798
|
+
handler,
|
|
799
|
+
attach(server) {
|
|
800
|
+
// The listeners already on the server are taken off and re-called by
|
|
801
|
+
// hand, rather than simply prepending the relay to them.
|
|
802
|
+
//
|
|
803
|
+
// `node:http` runs EVERY `request` listener, so prepending would mean
|
|
804
|
+
// the app's own handler also runs for /dk/* and writes a second set of
|
|
805
|
+
// headers into a response the relay already answered. Making it work
|
|
806
|
+
// would require every host app to start with `if (res.headersSent)
|
|
807
|
+
// return` -- a line nobody adds until the day it crashes a stream. So
|
|
808
|
+
// `attach` behaves the way the word implies: the relay takes /dk/*, and
|
|
809
|
+
// everything else is passed along untouched.
|
|
810
|
+
//
|
|
811
|
+
// The consequence worth knowing: listeners registered AFTER attach are
|
|
812
|
+
// not wrapped and will see /dk/* too. Attach last.
|
|
813
|
+
const downstream = server.listeners("request");
|
|
814
|
+
server.removeAllListeners("request");
|
|
815
|
+
server.on("request", (req, res) => {
|
|
816
|
+
if (handler(req, res))
|
|
817
|
+
return;
|
|
818
|
+
for (const next of downstream)
|
|
819
|
+
next.call(server, req, res);
|
|
820
|
+
});
|
|
821
|
+
},
|
|
822
|
+
tabs: () => summaries(),
|
|
823
|
+
tabsFor: (principal, tab) => summaries(principal, tab),
|
|
824
|
+
close() {
|
|
825
|
+
closed = true;
|
|
826
|
+
for (const tab of [...tabs.values()]) {
|
|
827
|
+
clearInterval(tab.ping);
|
|
828
|
+
for (const [, p] of tab.pending) {
|
|
829
|
+
clearTimeout(p.timer);
|
|
830
|
+
p.settle(relayRefusal("tab-went-away", "the relay is shutting down"), "tab-went-away");
|
|
831
|
+
}
|
|
832
|
+
tab.pending.clear();
|
|
833
|
+
try {
|
|
834
|
+
tab.res.end();
|
|
835
|
+
}
|
|
836
|
+
catch (err) {
|
|
837
|
+
onError(err);
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
tabs.clear();
|
|
841
|
+
for (const set of watchers.values()) {
|
|
842
|
+
for (const res of set) {
|
|
843
|
+
try {
|
|
844
|
+
res.end();
|
|
845
|
+
}
|
|
846
|
+
catch (err) {
|
|
847
|
+
onError(err);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
watchers.clear();
|
|
852
|
+
broadcast.clear();
|
|
853
|
+
},
|
|
854
|
+
};
|
|
855
|
+
}
|
|
856
|
+
/**
|
|
857
|
+
* A refusal the relay originated: one of a closed set, and with NO `snapshot`.
|
|
858
|
+
*
|
|
859
|
+
* The missing field is the whole signal. `Result` requires a snapshot because a
|
|
860
|
+
* driver mounted in a page always has one; the relay often does not -- a call
|
|
861
|
+
* to a tab that never connected has no screen behind it at all -- so
|
|
862
|
+
* `WireResult` widens the type rather than letting the relay invent a value.
|
|
863
|
+
*
|
|
864
|
+
* An invented snapshot would be worse than a missing one in both directions.
|
|
865
|
+
* An empty one tells an agent the app has no rows, which is a lie about the
|
|
866
|
+
* app rather than about the call. A sentinel like `{where:"(not connected)"}`
|
|
867
|
+
* is still a snapshot, so some client eventually renders it to a model as
|
|
868
|
+
* though it were a screen. Absence cannot be mistaken for either: a client
|
|
869
|
+
* reads it as "the call did not arrive", never as "the screen is empty".
|
|
870
|
+
*/
|
|
871
|
+
/**
|
|
872
|
+
* The tab's answer, plus the two timing fields the tab sent beside it.
|
|
873
|
+
*
|
|
874
|
+
* THE RELAY DOES NOT MEASURE, AND MUST NOT. It has one number of its own --
|
|
875
|
+
* the round trip it held the call open for, which is in the audit record -- and
|
|
876
|
+
* that number is the network out, plus the tab's work, plus any question the
|
|
877
|
+
* page put to a person, plus the network back. Substituting it for a missing
|
|
878
|
+
* `tookMs` would hand an agent exactly the sum `tookMs` exists to take apart.
|
|
879
|
+
* So this copies, validates and otherwise has no opinion, which is the same
|
|
880
|
+
* restraint `rev`, `screen`, `plan` and `focus` get on their way through.
|
|
881
|
+
*
|
|
882
|
+
* WHY THE KEYS ARE STRIPPED FIRST. They are reserved on this body. `result` is
|
|
883
|
+
* what the APP returned, and an app that filled in `tookMs` itself would be
|
|
884
|
+
* making a claim about its own speed where the agent is entitled to an
|
|
885
|
+
* observation -- so a value found in there is dropped and only the frame's own
|
|
886
|
+
* field, written by the page-side harness around its one call into the driver,
|
|
887
|
+
* is forwarded. The copy is shallow and touches nothing else: every other field
|
|
888
|
+
* of the `result`, a `stale` hint and the snapshot included, is forwarded byte
|
|
889
|
+
* for byte as before.
|
|
890
|
+
*
|
|
891
|
+
* ABSENT MEANS UNKNOWN. A tab from before this existed, or one that cannot say
|
|
892
|
+
* honestly, sends nothing, and nothing is what the agent gets: never a zero,
|
|
893
|
+
* which every client would render as "instant". A figure that is not a finite
|
|
894
|
+
* number at or above zero is dropped on the way through, the rule `Tab.focus`
|
|
895
|
+
* already has for a value that is not a string.
|
|
896
|
+
*/
|
|
897
|
+
function timed(result, frame) {
|
|
898
|
+
const out = { ...result };
|
|
899
|
+
delete out.tookMs;
|
|
900
|
+
delete out.waitedMs;
|
|
901
|
+
const took = ms(frame.tookMs);
|
|
902
|
+
if (took !== undefined) {
|
|
903
|
+
out.tookMs = took;
|
|
904
|
+
// Only beside a `tookMs`, never on its own. `waitedMs` is defined as the
|
|
905
|
+
// amount already subtracted from it, so without one it is a quantity
|
|
906
|
+
// relative to nothing -- and a reader might well subtract it a second time.
|
|
907
|
+
const waited = ms(frame.waitedMs);
|
|
908
|
+
if (waited !== undefined)
|
|
909
|
+
out.waitedMs = waited;
|
|
910
|
+
}
|
|
911
|
+
return out;
|
|
912
|
+
}
|
|
913
|
+
/** A duration off the wire, or undefined for anything that is not one. Whole
|
|
914
|
+
* milliseconds: a float survives JSON and nothing downstream wants tenths of a
|
|
915
|
+
* millisecond, so it is floored here rather than in each reader. */
|
|
916
|
+
function ms(value) {
|
|
917
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0)
|
|
918
|
+
return undefined;
|
|
919
|
+
return Math.floor(value);
|
|
920
|
+
}
|
|
921
|
+
function relayRefusal(refused, hint) {
|
|
922
|
+
return { ok: false, refused, hint };
|
|
923
|
+
}
|
|
924
|
+
function isLoopback(address) {
|
|
925
|
+
if (!address)
|
|
926
|
+
return false; // A unix socket or an unknown peer is not proven local.
|
|
927
|
+
return (address === "::1" ||
|
|
928
|
+
address === "::ffff:127.0.0.1" ||
|
|
929
|
+
address.startsWith("127.") ||
|
|
930
|
+
address.startsWith("::ffff:127."));
|
|
931
|
+
}
|
|
932
|
+
function json(res, status, body, extra = {}) {
|
|
933
|
+
const text = JSON.stringify(body);
|
|
934
|
+
res.writeHead(status, {
|
|
935
|
+
"content-type": "application/json; charset=utf-8",
|
|
936
|
+
"content-length": Buffer.byteLength(text),
|
|
937
|
+
// A tab id is a capability, so nothing here is cacheable by anything.
|
|
938
|
+
"cache-control": "no-store",
|
|
939
|
+
...extra,
|
|
940
|
+
});
|
|
941
|
+
res.end(text);
|
|
942
|
+
}
|
|
943
|
+
/**
|
|
944
|
+
* Read and discard a body we are not going to parse.
|
|
945
|
+
*
|
|
946
|
+
* PROTOCOL.md: "An unread body is worse than a wrong answer." On a keep-alive
|
|
947
|
+
* connection the bytes a relay failed to read are still in the socket when the
|
|
948
|
+
* next request is parsed off it, so they BECOME that request. A 401 that left
|
|
949
|
+
* the body behind would answer one caller correctly and destroy every later
|
|
950
|
+
* request on that socket.
|
|
951
|
+
*/
|
|
952
|
+
function drain(req) {
|
|
953
|
+
req.resume();
|
|
954
|
+
}
|
|
955
|
+
/** A non-2xx answer: no `WireResult` was produced, so the client must read it
|
|
956
|
+
* as a transport failure rather than as an app's "no". The `error` slug is
|
|
957
|
+
* pinned per case by PROTOCOL.md's status table. */
|
|
958
|
+
function bad(res, status, hint, error = "bad-request") {
|
|
959
|
+
json(res, status, { error, hint });
|
|
960
|
+
return true;
|
|
961
|
+
}
|
|
962
|
+
function tooLarge() {
|
|
963
|
+
return Object.assign(new Error(`body over the ${MAX_BODY}-byte limit`), {
|
|
964
|
+
dkStatus: 413,
|
|
965
|
+
dkError: "too-large",
|
|
966
|
+
});
|
|
967
|
+
}
|
|
968
|
+
/** The status a failed body read should answer with: 413 when it was too big,
|
|
969
|
+
* 400 when it was unparseable. Distinguished because they are different
|
|
970
|
+
* problems for the sender -- one is "send less", the other is "send JSON". */
|
|
971
|
+
function bodyFailure(err) {
|
|
972
|
+
const e = err;
|
|
973
|
+
return e?.dkStatus
|
|
974
|
+
? { status: e.dkStatus, error: e.dkError ?? "too-large", hint: e.message ?? "body too large" }
|
|
975
|
+
: { status: 400, error: "bad-request", hint: "could not read the body" };
|
|
976
|
+
}
|
|
977
|
+
/**
|
|
978
|
+
* Read a JSON body, with the size limit enforced the way a 413 can survive.
|
|
979
|
+
*
|
|
980
|
+
* Over the limit, buffering stops but READING CONTINUES, and the rejection
|
|
981
|
+
* waits for `end`. The obvious implementation -- hang up the moment the limit
|
|
982
|
+
* is crossed -- loses the 413 it is trying to send: the sender is still writing,
|
|
983
|
+
* so it gets a reset on its own socket and never reads the response that would
|
|
984
|
+
* have told it what was wrong. A sender that cannot learn why it failed retries
|
|
985
|
+
* identically, which is the opposite of what a limit is for.
|
|
986
|
+
*
|
|
987
|
+
* Memory stays bounded because the overflow is counted and discarded rather
|
|
988
|
+
* than kept. `ABORT_AT` is the backstop for a sender that is not going to stop:
|
|
989
|
+
* past it the connection does go, because at that point the upload is an attack
|
|
990
|
+
* and not a mistake, and politely reading all of it is the attack succeeding.
|
|
991
|
+
*/
|
|
992
|
+
function readJson(req) {
|
|
993
|
+
return new Promise((resolve, reject) => {
|
|
994
|
+
const chunks = [];
|
|
995
|
+
let size = 0;
|
|
996
|
+
let over = false;
|
|
997
|
+
req.on("data", (c) => {
|
|
998
|
+
size += c.length;
|
|
999
|
+
if (size > MAX_BODY) {
|
|
1000
|
+
over = true;
|
|
1001
|
+
chunks.length = 0; // Nothing here will be parsed; stop paying for it.
|
|
1002
|
+
if (size > ABORT_AT) {
|
|
1003
|
+
reject(tooLarge());
|
|
1004
|
+
req.destroy();
|
|
1005
|
+
}
|
|
1006
|
+
return;
|
|
1007
|
+
}
|
|
1008
|
+
chunks.push(c);
|
|
1009
|
+
});
|
|
1010
|
+
req.on("end", () => {
|
|
1011
|
+
if (over)
|
|
1012
|
+
return reject(tooLarge());
|
|
1013
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
1014
|
+
if (!text.trim())
|
|
1015
|
+
return resolve({});
|
|
1016
|
+
try {
|
|
1017
|
+
resolve(JSON.parse(text));
|
|
1018
|
+
}
|
|
1019
|
+
catch (err) {
|
|
1020
|
+
reject(err);
|
|
1021
|
+
}
|
|
1022
|
+
});
|
|
1023
|
+
req.on("error", reject);
|
|
1024
|
+
});
|
|
1025
|
+
}
|
|
1026
|
+
//# sourceMappingURL=relay.js.map
|