driverkit 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONTROLS.md +578 -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 +153 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"relay.js","sourceRoot":"","sources":["../../src/relay/relay.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgEG;AAIH,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,OAAO,EAAE,cAAc,EAAkB,MAAM,WAAW,CAAC;AAiOhG,MAAM,WAAW,GAAG;IAClB,cAAc,EAAE,kCAAkC;IAClD,eAAe,EAAE,wBAAwB;IACzC,UAAU,EAAE,YAAY;IACxB,6EAA6E;IAC7E,6EAA6E;IAC7E,+BAA+B;IAC/B,mBAAmB,EAAE,IAAI;CACjB,CAAC;AAEX;;;;;;GAMG;AACH,MAAM,QAAQ,GAAG,CAAC,IAAI,EAAE,CAAC;AAEzB;yEACyE;AACzE,MAAM,QAAQ,GAAG,QAAQ,GAAG,EAAE,CAAC;AAE/B;;;;GAIG;AACH,MAAM,YAAY,GAAG,EAAE,kBAAkB,EAAE,0BAA0B,EAAW,CAAC;AAEjF;;;;;;;;GAQG;AACH,MAAM,gBAAgB,GAAG,0BAA0B,CAAC;AAEpD,qDAAqD;AACrD,MAAM,KAAK,GAAc,EAAE,EAAE,EAAE,eAAe,EAAE,CAAC;AA0BjD,SAAS,KAAK,CAAC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CAAC,MAAM,CAAC;YACjB,IAAI,IAAI,GAAG,QAAQ,EAAE,CAAC;gBACpB,IAAI,GAAG,IAAI,CAAC;gBACZ,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,mDAAmD;gBACtE,IAAI,IAAI,GAAG,QAAQ,EAAE,CAAC;oBACpB,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAC;oBACnB,GAAG,CAAC,OAAO,EAAE,CAAC;gBAChB,CAAC;gBACD,OAAO;YACT,CAAC;YACD,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACjB,CAAC,CAAC,CAAC;QACH,GAAG,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;YACjB,IAAI,IAAI;gBAAE,OAAO,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAC;YACpC,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;YACpD,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE;gBAAE,OAAO,OAAO,CAAC,EAAE,CAAC,CAAC;YACrC,IAAI,CAAC;gBACH,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;YAC5B,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,MAAM,CAAC,GAAG,CAAC,CAAC;YACd,CAAC;QACH,CAAC,CAAC,CAAC;QACH,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IAC1B,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * driverkit/relay — the one place both parties can reach.\n *\n * Nothing can call into a browser tab, so the tab dials out and holds a stream\n * open; the agent speaks ordinary request/response HTTP. The relay's whole job\n * is to turn one into the other: a `POST /dk/tabs/:tab/call` blocks on an open\n * promise until a `result` frame with the matching `id` arrives on a separate\n * POST from that tab, and then answers with it.\n *\n * Two properties are worth stating before the code, because both are easy to\n * break with a change that looks like a cleanup:\n *\n * THE RELAY GRANTS NO AUTHORITY. It forwards a verb name to a tab that is\n * already logged in as a person. It never decides whether a call is allowed,\n * never rewrites args, never interprets `rev`. Every refusal it originates\n * is about reachability -- \"no tab\", \"the tab went away\", \"the tab never\n * answered\" -- and never about the verb. The moment the relay has an opinion\n * about a verb, there are two sets of rules and one of them is wrong.\n *\n * EVERY ANSWER IS A `WireResult`, AND THE BODY IS AUTHORITATIVE. An agent\n * asking for a call gets the same shape at 200 whether the tab refused, the\n * tab vanished, or the tab id was a typo. A 4xx here would conflate a\n * transport failure with a business rule, and those want opposite handling:\n * one is retry-elsewhere, the other is rephrase-and-retry. So a non-2xx from\n * this relay means no `WireResult` was produced at all -- malformed body,\n * unroutable path -- and never \"the app said no\".\n *\n * A relay refusal carries NO `snapshot`. The three it can originate are a\n * closed set (`RelayRefusal`), and in none of them did anything run or\n * anybody look. Inventing an empty snapshot would tell an agent the app has\n * no rows, which is a lie about the app rather than about the call.\n *\n * CHOICES PROTOCOL.md LEAVES TO THE RELAY, recorded here so the next reader\n * does not have to rediscover them by experiment:\n *\n * - A second `/dk/events` stream for a known tab id SUPERSEDES the first.\n * The id is minted by the tab so a reconnect resumes identity; treating the\n * second stream as a new tab would defeat the only reason the id exists.\n * - Calls in flight CARRY ACROSS that supersede. A tab that was mid-verb when\n * its stream blinked can still POST the result on the new one, and failing\n * those would turn a recovered hiccup into an error the agent must handle.\n * - `hello` UPSERTS FIELD BY FIELD. It arrives again after every reconnect and\n * the app may have navigated in between, so the later one wins on each\n * field it carries and leaves the others alone.\n * - Everything in `hello` but `tab` is OPTIONAL. The consequence is a real\n * window: a tab enters the registry when its stream opens and `hello` lands\n * a moment later on a separate POST. During it `/manifest` answers 404\n * rather than an empty verb list, because an empty list is a false claim\n * that the app has no verbs.\n * - `attach()` is MIDDLEWARE, not a prepended listener. See the comment on it.\n *\n * A TAB BELONGS TO A PRINCIPAL, AND THE REGISTRY KEY SAYS SO. Tabs are\n * stored under `principal\\u0000tab`, not under the tab id alone. That is not a\n * check, it is a shape: there is no lookup by bare tab id anywhere in this\n * file, so a caller cannot reach another principal's tab through a code path\n * somebody adds next year and forgets to guard. It also removes the question\n * of what to do when two people mint the same tab id -- nothing, they are two\n * tabs -- and with it an existence oracle for other people's ids.\n *\n * Isolation is NOT authorisation. A credential buys its holder nothing they\n * could not already do in their own browser; it tells the relay which\n * hundredth of its registry to show them. See `auth.ts`.\n *\n * Zero dependencies: `node:http` types and `node:crypto` only.\n */\n\nimport type { IncomingMessage, Server, ServerResponse } from \"node:http\";\n\nimport { AuthError, LOCAL_PRINCIPAL, TabAuth, credentialFrom, type Principal } from \"./auth.ts\";\nimport type {\n CallFrame,\n DownFrame,\n Manifest,\n RelayRefusal,\n Scalar,\n Snapshot,\n TabFocus,\n TabSummary,\n UpFrame,\n WatchFrame,\n WireResult,\n} from \"./frames.ts\";\n\nexport interface RelayOptions {\n /**\n * How long a `POST /dk/tabs/:tab/call` waits for the matching `result`.\n * **Defaults to 60 seconds.**\n *\n * PROTOCOL.md has no queue on purpose: a call either reaches a connected tab\n * or fails cleanly. The timeout is the other half of that promise. Without\n * it a tab whose JavaScript died -- stream still open, event loop wedged --\n * holds the agent's request forever, which is the one failure mode worse\n * than a refusal, because an agent cannot retry what has not returned.\n *\n * **WHY THE DEFAULT MOVED FROM 15s TO 60s.** The old number was tuned for a\n * button click, where the p99 is tens of milliseconds and 15s is a margin of\n * three hundred times. It is not a margin at all for the verb an adopter\n * actually reaches for this library to drive: a report fetch, an export, a\n * cross-system lookup. A legitimate 20-second fetch came back `timeout`, and\n * `timeout` does not mean \"slow\" — PROTOCOL.md defines it as **outcome\n * unknown**, so a commit that came back that way may already have run and\n * the agent is told not to retry it. The deadline was therefore converting\n * SUCCESSES into the most expensive answer in the system. The two errors are\n * not symmetric: firing late costs an agent some latency, and firing early\n * costs a task it cannot safely resume.\n *\n * **WHY NOT MUCH LONGER.** A long deadline is also wrong, for three reasons\n * that are all about what else is holding a socket.\n *\n * - The deadline is the only thing that answers an agent at all when a tab\n * is alive but wedged -- an infinite loop in a verb body, a modal nobody\n * will dismiss. `tab-went-away` covers a tab that DIED; nothing else\n * covers one that is merely stuck. At five minutes the agent and the\n * person both sit there with no answer and no way to tell slow from\n * wedged.\n * - Something in the middle will give up first. Nginx, ALBs, Cloud Run and\n * the average corporate proxy cut an idle response at 30 to 60 seconds,\n * so a server-side deadline above that is answered by a socket error at\n * the client -- an unknown outcome with no slug, no hint and no `Result`\n * shape, which is strictly worse than the `timeout` it was meant to\n * avoid.\n * - Each pending call holds a timer, a response and a closure.\n *\n * **WHAT AN ADOPTER SHOULD SET.** The p99.9 of your slowest declared verb,\n * plus a second, and if the app gates commits in the page then plus however\n * long a person takes to read a dialog -- that wait is inside the call. If a\n * verb can legitimately exceed about a minute, raising this is the wrong\n * repair: declare a `read` verb that starts the work and returns a handle,\n * and another that reports whether it is done. An agent parked on one tool\n * call for five minutes cannot be paced, cannot be stopped, cannot be shown\n * to the person as progress, and will be cut off by something anyway.\n */\n timeoutMs?: number;\n /** The keep-alive comment interval. PROTOCOL.md says 20s. */\n pingMs?: number;\n /**\n * Serve requests that did not come from loopback.\n *\n * Off by default, and that default is the security model, not a convenience.\n * A tab's own session is what the app checks, so a relay someone else can\n * reach is that person driving your logged-in session -- not a scoped token\n * they could be given, your actual account. There is nothing to revoke\n * because nothing was ever granted. See \"Who is allowed to do this\".\n *\n * WITHOUT `auth` OR `resolvePrincipal`, THIS THROWS. That combination is the\n * one the whole of `auth.ts` exists to prevent: an exposed relay with no\n * notion of who is calling publishes a hundred people's logged-in sessions\n * to each other and to anybody who can reach the port. It used to be\n * reachable by setting one flag that reads like a convenience, so now it is\n * not reachable at all -- turning on remote access means naming how callers\n * are identified, in the same call.\n */\n allowRemote?: boolean;\n /**\n * How the relay learns which person a request is from.\n *\n * It grants nothing. See `auth.ts`: a credential buys its holder nothing\n * they could not already do in their own browser, and buys the relay the\n * ability to keep a hundred people's tabs apart.\n */\n auth?: TabAuth;\n /**\n * The other door: a function from request headers to a principal id.\n *\n * For a relay embedded in an app that already has sessions and can simply\n * say who the caller is -- no secret to share, no token to mint. Consulted\n * before `auth`, and returning undefined falls through, so it can handle\n * logged-in users and leave anonymous visitors to the token path.\n */\n resolvePrincipal?: (headers: Record<string, string | string[] | undefined>) => string | undefined;\n /** Called with anything thrown while writing to a stream. Default: ignore. */\n onError?: (err: unknown) => void;\n /**\n * Where this relay's own audit records go. One per `/call` it handled; see\n * `RelayAuditEvent`.\n *\n * WHY THE RELAY EMITS AT ALL, when `MountOptions.onAudit` already records\n * every call that reaches a driver. Because of one fact the in-page hook\n * cannot know and this one cannot help knowing: WHICH PRINCIPAL asked. The\n * core sees a `call()` and has no idea whether it came from the panel in\n * front of a person, a cron job, or somebody else's agent holding a token;\n * the relay resolved the credential itself, so it is the only place in the\n * library where \"who\" is a fact rather than a guess.\n *\n * AND WHY IT SAYS SO LITTLE. It does not report what the verb did. The\n * driver decided that, in another process, and a copy of somebody else's\n * decision is the second source of truth that can disagree with the first —\n * a relay that logged `ok` for a call whose tab died mid-commit would be\n * asserting an outcome nobody observed. So this records what the RELAY\n * decided: that a call arrived, from whom, for which tab and verb, and\n * whether it was delivered or stopped here. What happened to the data is in\n * the driver's own record, where it was decided. The two are not two\n * countings of one event; see `RelayAuditEvent.outcome`.\n *\n * Called and not awaited, like the core's hook, and a throw is passed to\n * `onError` rather than allowed to fail the call: a relay that returned a\n * 500 because its logging backend was down would turn an audit trail into\n * an outage.\n */\n onAudit?: (event: RelayAuditEvent) => void;\n}\n\n/**\n * One call this relay handled, and nothing about what the app did with it.\n *\n * The fields are the relay's own knowledge and stop there. `principal` is the\n * one an in-page hook cannot have; `outcome` is the relay's own verdict and\n * never the driver's.\n *\n * KEPT IDENTICAL IN THE PYTHON RELAY, field for field and name for name, by\n * the same standing promise that governs the rest of these two files: there\n * are two independent implementations of this protocol and a difference\n * between them is a difference nobody finds until an operator switches.\n */\nexport interface RelayAuditEvent {\n /** `Date.now()` when the call settled, in milliseconds since the epoch. */\n at: number;\n /**\n * How long the relay held the call, in milliseconds: the round trip to the\n * tab, which on a gated commit includes the time a person spent deciding.\n *\n * THE TAB'S OWN `tookMs` IS DELIBERATELY NOT HERE, although the relay now\n * carries one to the agent. It is a figure measured in another process, and\n * copying somebody else's measurement into this record is the same mistake as\n * copying their verdict -- see `outcome`, and \"a relay logging `ok` for a call\n * whose tab died mid-commit asserts an outcome nobody observed\". The relay\n * cannot check it and would be asserting it. It would also invite the one\n * subtraction nobody should make: `ms - tookMs` is not \"the network\", it is\n * the network plus however long the frame sat in the tab's event loop plus\n * whatever a proxy buffered. The duration belongs in the driver's own record,\n * where it was measured, and in the answer the agent gets.\n */\n ms: number;\n /** Who asked, as the relay resolved them — a token's subject, a host's own\n * session id, or `LOCAL_PRINCIPAL` on an unconfigured loopback relay, where\n * everything is one principal and this field says so rather than implying\n * an identity nobody established. */\n principal: string;\n /** The tab the call was addressed to. Present even when no such tab was\n * found: an agent calling a tab id it does not own is the thing worth\n * having in a log. */\n tab: string;\n /** The verb, as asked for. Not checked against any manifest — the relay does\n * not hold one it trusts — so this is the agent's word for what it wanted. */\n verb: string;\n /**\n * What the RELAY did with it, which is never what the app did.\n *\n * `delivered` the tab answered. What it answered is in the driver's\n * own audit record, which is where it was decided; this\n * relay deliberately does not copy it.\n * `no-such-tab` no tab of this principal's by that id. Nothing ran.\n * `tab-went-away` the stream was gone, or went while the call was in\n * flight. The verb MAY have run; see `RelayRefusal`.\n * `timeout` no answer inside the deadline. Outcome unknown.\n *\n * So `delivered` is the one value that means \"ask the other log\", and the\n * other three are the cases where there is no other log to ask because the\n * call never reached, or never returned from, a driver. That is the line\n * that keeps the two records from being two countings of one call: COUNT\n * COMMITS FROM THE DRIVER'S RECORDS, and read this one for who asked and for\n * the calls that never arrived.\n */\n outcome: \"delivered\" | RelayRefusal;\n}\n\nexport interface Relay {\n /**\n * Handle one request. Returns false if the path is not ours, so the relay\n * can sit in front of an app that owns the rest of the URL space. It does\n * NOT 404 on a miss: deciding that an unknown path is an error is the host\n * server's business, and a relay that answers 404 for everything cannot be\n * embedded in anything.\n */\n handler: (req: IncomingMessage, res: ServerResponse) => boolean;\n /** Put the handler in front of an existing server's own routes. */\n attach: (server: Server) => void;\n /**\n * Every connected tab, across every principal.\n *\n * The operator's in-process view: a process that embeds the relay may\n * legitimately want to know what is connected. NOTHING REACHABLE OVER HTTP\n * USES IT -- `GET /dk/tabs` serves `tabsFor` instead. The cross-principal\n * listing was the inventory of other people's sessions, titles and URLs\n * attached, that the split exists to remove.\n */\n tabs: () => TabSummary[];\n /** The tabs one principal owns -- what `GET /dk/tabs` actually serves. */\n tabsFor: (principal: string, tab?: string) => TabSummary[];\n /** Hang up every stream and fail every call in flight. Idempotent. */\n close: () => void;\n}\n\nconst SSE_HEADERS = {\n \"content-type\": \"text/event-stream; charset=utf-8\",\n \"cache-control\": \"no-cache, no-transform\",\n connection: \"keep-alive\",\n // Nginx buffers proxied responses by default, which turns a live stream into\n // one that arrives when it ends. The ping comments keep the connection open;\n // this keeps the bytes moving.\n \"x-accel-buffering\": \"no\",\n} as const;\n\n/**\n * 1 MiB, pinned by PROTOCOL.md, and over it is a 413.\n *\n * Not a limit to raise. A snapshot approaching this size is a bug in the app's\n * `visible()` -- the whole design says an agent sees a screenful, so a megabyte\n * of rows means the page is reporting its database rather than its screen.\n */\nconst MAX_BODY = 1 << 20;\n\n/** Past this, the sender is not going to stop and the connection goes. See\n * `readJson` for why the limit itself is not enforced by hanging up. */\nconst ABORT_AT = MAX_BODY * 16;\n\n/**\n * The 401's challenge header. `Bearer` names the scheme an agent should use;\n * the realm is fixed, because a realm that named the app or the principal\n * would be a 401 that leaks who else is here.\n */\nconst AUTH_HEADERS = { \"www-authenticate\": 'Bearer realm=\"driverkit\"' } as const;\n\n/**\n * The hint on every `no-such-tab`, whatever the real reason.\n *\n * One string, with no tab id in it, because the four reasons an agent can get\n * this -- never minted, closed, somebody else's, outside a tab-bound\n * credential's reach -- must be one answer. A hint that said \"no tab `abc` is\n * connected\" for one and something else for another would make the endpoint\n * the membership test the status code was carefully chosen not to be.\n */\nconst NO_SUCH_TAB_HINT = \"no such tab is connected\";\n\n/** The principal every request is, with auth off. */\nconst LOCAL: Principal = { id: LOCAL_PRINCIPAL };\n\ninterface Pending {\n /**\n * Answer the call, once, saying what the RELAY decided.\n *\n * The outcome is a required argument rather than something derived from `r`,\n * and that is deliberate: a relay refusal is recognisable from a `WireResult`\n * only by its missing `snapshot`, which is a type-level invariant that the\n * wire can violate, and an audit record must not rest on one. Required also\n * means the compiler finds every place a call can be settled -- there are\n * five, two of them nowhere near the dispatch -- so a sixth added later\n * cannot forget to say what it is.\n */\n settle: (r: WireResult, outcome: RelayAuditEvent[\"outcome\"]) => void;\n timer: ReturnType<typeof setTimeout>;\n}\n\n/** What `ingest` reports back: accepted, or the exact status to answer with. */\ninterface Ingested {\n ok: boolean;\n status?: number;\n error?: string;\n why?: string;\n}\n\nfunction no400(error: string, why: string): Ingested {\n return { ok: false, status: 400, error, why };\n}\n\ninterface Tab {\n tab: string;\n /**\n * Who this tab belongs to. The other half of the registry key, kept on the\n * record too so a summary and a watcher fan-out can find it without carrying\n * the key around.\n */\n principal: string;\n app?: string;\n title?: string;\n url?: string;\n /** Where the tab said its person's attention is. Stored as the tab sent it\n * and never computed: the relay cannot see `document.hasFocus()`. */\n focus?: TabFocus;\n manifest?: Manifest;\n snapshot?: Snapshot;\n /** ISO 8601. Formatted once, at connect, rather than on every list. */\n since: string;\n res: ServerResponse;\n ping: ReturnType<typeof setInterval>;\n pending: Map<string, Pending>;\n}\n\nexport function createRelay(options: RelayOptions = {}): Relay {\n const timeoutMs = options.timeoutMs ?? 60_000;\n const pingMs = options.pingMs ?? 20_000;\n const allowRemote = options.allowRemote ?? false;\n const auth = options.auth;\n const resolvePrincipal = options.resolvePrincipal;\n const onError = options.onError ?? (() => {});\n const onAudit = options.onAudit;\n\n /**\n * Hand one record to the host, and survive the host.\n *\n * A throw goes to `onError`, which is where everything else this relay\n * cannot help goes, rather than to the caller: a 500 because the logging\n * backend is down would make an audit trail into an outage. Not awaited --\n * nothing here is async, and a hook that wants to be is the host's business.\n */\n const audit = (\n principal: string,\n tab: string,\n verb: string,\n started: number,\n outcome: RelayAuditEvent[\"outcome\"],\n ): void => {\n if (onAudit === undefined) return;\n const at = Date.now();\n try {\n onAudit({ at, ms: at - started, principal, tab, verb, outcome });\n } catch (err) {\n onError(err);\n }\n };\n\n if (allowRemote && !auth && !resolvePrincipal) {\n // Thrown at construction, before a socket exists, for the same reason\n // `serve()` refuses a non-loopback host there: a misconfiguration that\n // surfaced later is one somebody forgot to check, and the failure mode of\n // forgetting is a listening public port that drives strangers' browsers.\n throw new Error(\n \"driverkit: allowRemote needs auth or resolvePrincipal. A relay that serves \" +\n \"non-loopback callers and cannot tell them apart is every connected tab offered to \" +\n 'every caller. Read \"Who is allowed to do this\" in PROTOCOL.md, then pass ' +\n \"auth: new TabAuth({ secret, audience }).\",\n );\n }\n\n /**\n * Connected tabs, keyed by `principal\\u0000tab`.\n *\n * The pair, never the bare id. A NUL joins them because it cannot occur in a\n * principal id or a tab id that arrived as a URL path segment, so there is no\n * pair of distinct identities that collides into one key -- which a `:`\n * separator would allow for an id containing a colon.\n */\n const tabs = new Map<string, Tab>();\n /**\n * `GET /dk/tabs/:tab/watch` subscribers, keyed by tab id.\n *\n * A SET, because PROTOCOL.md requires every watcher to get the frames: two\n * agents beside one human is the shared-presence case, and a single-slot\n * registry would silently make the second one blind rather than refuse it.\n *\n * Kept OUTSIDE the tab record on purpose. A tab record dies with its stream,\n * and a watcher must survive the page reloading -- that reload is one of the\n * things it is watching for.\n */\n const watchers = new Map<string, Set<ServerResponse>>();\n /** The rev last broadcast per tab, so a refusal that moved nothing is quiet. */\n const broadcast = new Map<string, number>();\n\n const key = (principal: string, tabId: string) => `${principal}\\u0000${tabId}`;\n\n /**\n * The caller's tab, or undefined. The ONLY way this file finds a tab.\n *\n * `undefined` covers three cases on purpose -- no such tab, somebody else's\n * tab, and a tab outside what a tab-bound credential may address -- and every\n * caller turns it into the same `no-such-tab`. Collapsing them here rather\n * than at each endpoint is what makes the property hold for an endpoint added\n * later: there is no lookup by bare tab id to reach for.\n */\n function owned(who: Principal, tabId: string): Tab | undefined {\n if (who.tab !== undefined && who.tab !== tabId) return undefined;\n return tabs.get(key(who.id, tabId));\n }\n let nextCall = 1;\n let closed = false;\n\n function send(tab: Tab, frame: DownFrame): boolean {\n try {\n // The event name matters: the page listens for `call` specifically, so an\n // unnamed `message` would be silently dropped by `EventSource`.\n tab.res.write(`event: ${frame.t}\\ndata: ${JSON.stringify(frame)}\\n\\n`);\n return true;\n } catch (err) {\n onError(err);\n return false;\n }\n }\n\n /**\n * Open a tab's stream and BIND the tab to the caller's principal.\n *\n * The binding happens here, at first contact, rather than on `hello`.\n * PROTOCOL.md already describes the window between a stream opening and its\n * `hello` landing on a separate POST; binding at `hello` would make that a\n * window in which a tab exists and belongs to nobody, and an unowned tab is\n * one every principal either can or cannot see, both of which are wrong.\n *\n * What this means for a credential that expires MID-SESSION: nothing. The\n * binding is the relay's record and lasts as long as the stream, not as long\n * as the token. A relay that hung up at `exp` would disconnect every tab in\n * the deployment once per token lifetime, mid-verb, while a person watched --\n * and the fix people reach for, a longer lifetime, is strictly worse because\n * it also widens the window a leaked token is useful in. Short tokens plus a\n * binding that outlives them gives both.\n *\n * The credential is still needed for `POST /dk/result`, which is a new\n * request and carries its own; see `connect`'s token getter, which is a\n * function for exactly this reason.\n */\n function openStream(\n who: Principal,\n tabId: string,\n req: IncomingMessage,\n res: ServerResponse,\n ): void {\n const id = key(who.id, tabId);\n res.writeHead(200, SSE_HEADERS);\n // A first comment byte makes the browser fire `open` now rather than when\n // the first real frame happens to arrive, and `open` is where the page\n // sends `hello`. Without it a freshly loaded tab is connected but unknown.\n res.write(\": driverkit\\n\\n\");\n\n const existing = tabs.get(id);\n const ping = setInterval(() => {\n try {\n // A comment line, per PROTOCOL.md: it carries nothing, and a comment\n // cannot be mistaken for a frame by a client that does not know it.\n res.write(\": ping\\n\\n\");\n } catch (err) {\n onError(err);\n }\n }, pingMs);\n // The relay must never be the reason a process will not exit; a test that\n // forgets `close()` should fail loudly, not hang.\n ping.unref?.();\n\n const tab: Tab = existing\n ? // A second stream for a known id is a reconnect, not a new tab: the id\n // is minted by the tab precisely so it survives one. Carry the known\n // facts and the calls in flight across -- a tab that was mid-verb when\n // its stream blinked can still POST the result on the new one, and\n // failing those calls would turn a recovered hiccup into an error the\n // agent has to handle.\n { ...existing, res, ping, since: existing.since }\n : {\n tab: tabId,\n principal: who.id,\n since: new Date().toISOString(),\n res,\n ping,\n pending: new Map<string, Pending>(),\n };\n\n if (existing && existing.res !== res) {\n clearInterval(existing.ping);\n try {\n existing.res.end();\n } catch (err) {\n onError(err);\n }\n }\n tabs.set(id, tab);\n\n const gone = () => {\n clearInterval(ping);\n // Only drop the registry entry if it is still OURS. A reconnect replaces\n // the record first and then ends the old response, so the old `close`\n // fires afterwards and would otherwise delete the live tab.\n if (tabs.get(id) !== tab) return;\n tabs.delete(id);\n // Fail what is in flight instead of letting each call sit out its own\n // timeout. The answer is already known -- nobody is going to reply -- and\n // \"no queue\" means the agent learns that now, while it still has the\n // context to try something else.\n for (const [, p] of tab.pending) {\n clearTimeout(p.timer);\n p.settle(relayRefusal(\"tab-went-away\", `tab \\`${tabId}\\` closed its stream`), \"tab-went-away\");\n }\n tab.pending.clear();\n };\n\n res.on(\"close\", gone);\n req.on(\"aborted\", gone);\n }\n\n /**\n * One tab->relay frame.\n *\n * A TAB MAY NOT ANSWER ANOTHER TAB'S CALL, and two things enforce it. A tab\n * the caller does not own is not found at all (`owned`), so the\n * cross-PERSON case is the same 409 as a tab that is not connected. Within\n * one person, who legitimately has several tabs open, `pending` is per-tab-\n * record and call ids are unique across the relay, so a `result` for a call\n * issued to another of their tabs finds nothing to settle and is dropped as a\n * late answer. A credential carrying a `tab` claim closes that case\n * cryptographically as well; without one, the pending map is what holds,\n * which is a weaker statement and is said here rather than assumed.\n */\n function ingest(who: Principal, frame: UpFrame, tabId: string | undefined): Ingested {\n const id = frame.t === \"hello\" ? frame.tab : (tabId ?? frame.tab);\n // 400, not 409: a frame that names no tab is malformed. There is no state\n // of the relay under which it could have been accepted, which is what 4xx\n // against 409 is supposed to tell the sender.\n if (!id) return no400(\"unplaceable\", \"no tab id: pass ?tab= or a `tab` field\");\n const tab = owned(who, id);\n // A tab that belongs to someone else lands here too, with the same body,\n // which is the oracle rule applied to the tab's own endpoint: \"not yours\"\n // and \"not connected\" must be one answer.\n if (!tab) return { ok: false, status: 409, error: \"no-such-tab\", why: NO_SUCH_TAB_HINT };\n\n switch (frame.t) {\n case \"hello\": {\n // Upsert, not insert. `hello` arrives again after every reconnect, and\n // the app may have navigated in between, so the later one wins on every\n // field it carries.\n if (frame.app !== undefined) tab.app = frame.app;\n if (frame.title !== undefined) tab.title = frame.title;\n if (frame.url !== undefined) tab.url = frame.url;\n if (frame.focus !== undefined) tab.focus = frame.focus;\n if (frame.manifest !== undefined) tab.manifest = frame.manifest;\n if (frame.snapshot !== undefined) {\n tab.snapshot = frame.snapshot;\n push(tab);\n }\n return { ok: true };\n }\n case \"snapshot\": {\n tab.snapshot = frame.snapshot;\n // The same upsert rule `hello` uses, on the two fields a push may now\n // carry. `url` is here because it had no other way of ever being\n // right: it came from `hello` alone, and a single-page app navigates\n // without reconnecting, so a tab's url in `/dk/tabs` was whatever it\n // had been at page load. Absent leaves the stored value alone, which\n // is what keeps a tab connected by a hand-written loop -- or by a\n // driverkit older than this field -- reading exactly as it did.\n if (frame.url !== undefined) tab.url = frame.url;\n if (frame.focus !== undefined) tab.focus = frame.focus;\n // Always forwarded, even at an unchanged rev. This frame is the tab\n // SAYING the page moved, and second-guessing it here would make the\n // relay the thing that decides what counts as a change -- which is the\n // app's judgement, carried in `rev`, not the relay's.\n push(tab, true);\n return { ok: true };\n }\n case \"result\": {\n // Checked BEFORE the pending lookup, and the call is deliberately left\n // pending when it fails.\n //\n // This is the one promise `/call` makes: the body is always a\n // `WireResult`. Settling with a non-object would put `undefined`\n // through `JSON.stringify` and answer the agent a body that is\n // literally the four characters `null` -- or nothing at all -- which no\n // client can parse and which no amount of careful client code can\n // recover from. Rejecting the frame instead leaves the call to time out\n // honestly: `timeout` is a documented unknown outcome, and an unknown\n // outcome is a far better thing to hand an agent than garbage.\n if (typeof frame.result !== \"object\" || frame.result === null || Array.isArray(frame.result)) {\n return no400(\"bad-frame\", `the \\`result\\` for \\`${frame.id}\\` is not an object`);\n }\n const pending = tab.pending.get(frame.id);\n // An id the relay is not waiting on is dropped, not an error. It means\n // the call already timed out and the tab answered late; resurrecting it\n // would deliver an answer to a request that has already been responded\n // to.\n if (!pending) return { ok: true, why: `no call \\`${frame.id}\\` in flight` };\n tab.pending.delete(frame.id);\n clearTimeout(pending.timer);\n // The `Result` is forwarded byte for byte. A `stale` refusal the driver\n // produced must reach the agent as the driver wrote it, hint and\n // snapshot included -- that hint is how the agent knows to re-read\n // instead of retrying the same dead rev.\n if (frame.result?.snapshot) {\n tab.snapshot = frame.result.snapshot;\n // Watchers hear about an agent's change too, not only a human's.\n // `/watch` exists so a watcher need not poll; one that learned only\n // about human-caused moves would still have to poll for the rest,\n // which is the cost the endpoint was added to remove. Deduped on\n // `rev`, so a refusal that moved nothing stays quiet.\n push(tab);\n }\n // `delivered`, and nothing more. The tab answered; what it answered is\n // the driver's own record to make, in the process where it was decided.\n // The tab's own elapsed time rides along on the answer and is NOT in\n // the record: see `timed`, and `RelayAuditEvent` for the argument.\n pending.settle(timed(frame.result, frame), \"delivered\");\n return { ok: true };\n }\n }\n }\n\n function dispatch(\n who: Principal,\n tabId: string,\n body: { name?: unknown; args?: unknown; rev?: unknown; screen?: unknown; plan?: unknown },\n ): Promise<WireResult> | null {\n // Null means \"this was never a call\", and the caller answers non-2xx. A\n // body with no `name` is malformed, not refused: there is no verb to have\n // said no, so dressing it as a `WireResult` would teach an agent to look\n // for a `bad-request` slug that the closed set does not contain.\n if (typeof body.name !== \"string\" || !body.name) return null;\n\n // Before the lookup, so `ms` is the time the agent actually waited and not\n // the time minus whatever the registry cost.\n const started = Date.now();\n\n const tab = owned(who, tabId);\n if (!tab) {\n // Shaped like every other answer. An agent holding a tab id from a\n // closed window gets a refusal it can read with the same code path it\n // uses for \"that row is not deletable\".\n //\n // And a tab belonging to another principal gets THIS, not a 403: a\n // refusal an agent reads as \"that window is gone\", identical in status,\n // slug and hint to one for an id that was never minted. A 403 here would\n // turn /call into a membership test for other people's tab ids.\n // Recorded, and this is the half of the trail the driver cannot have:\n // nothing reached a tab, so no `onAudit` anywhere else in the library\n // will ever hear about this call. An agent working through tab ids it\n // does not own leaves its marks only here.\n audit(who.id, tabId, body.name, started, \"no-such-tab\");\n return Promise.resolve(\n relayRefusal(\"no-such-tab\", `${NO_SUCH_TAB_HINT}; GET /dk/tabs to list them`),\n );\n }\n\n const id = `c-${nextCall++}`;\n const frame: CallFrame = {\n t: \"call\",\n id,\n name: body.name,\n ...(body.args && typeof body.args === \"object\" ? { args: body.args as Record<string, Scalar> } : {}),\n // Forwarded only when the agent sent one. Defaulting it would silently\n // opt an agent into a staleness check it did not ask for; dropping it\n // would silently opt it out of one it did. Neither is the relay's call.\n ...(typeof body.rev === \"number\" ? { rev: body.rev } : {}),\n // `screen` on exactly the same terms, and with the same restraint: the\n // relay does not know which screen the tab is on, does not compare it,\n // and does not refuse it. It is the agent's claim and the driver's check.\n // An empty string is dropped rather than forwarded, because it is not the\n // id of any screen and no app should be asked to refuse a call over a\n // field left blank.\n ...(typeof body.screen === \"string\" && body.screen ? { screen: body.screen } : {}),\n // `plan` on the same terms again, and here the restraint is not even a\n // choice: the token is opaque to everything but the core that minted it,\n // so a relay has nothing to compare it against and could only ever get\n // the comparison wrong. Dropped when blank, like `screen`, because an\n // empty string is not a token and the core's refusal should name the\n // field the agent actually left out.\n ...(typeof body.plan === \"string\" && body.plan ? { plan: body.plan } : {}),\n };\n\n return new Promise<WireResult>((resolve) => {\n let done = false;\n const settle = (r: WireResult, outcome: RelayAuditEvent[\"outcome\"]) => {\n if (done) return;\n done = true;\n // ONE record per call, from the one place a call can be answered. The\n // `done` guard above is what makes it one: the deadline and a late\n // `result` frame race, and the loser must not log a second outcome for\n // a call that has already been answered.\n audit(who.id, tabId, frame.name, started, outcome);\n resolve(r);\n };\n const timer = setTimeout(() => {\n tab.pending.delete(id);\n // NOT a promise the call did not happen. The tab may have run the verb\n // and died before answering, so a `commit` that times out has an\n // unknown outcome and the agent must read the screen before retrying.\n // The relay says only \"no answer arrived\"; guessing further here is how\n // every client ends up inventing a different guess.\n settle(\n relayRefusal(\"timeout\", `tab \\`${tabId}\\` did not answer \\`${frame.name}\\` within ${timeoutMs}ms`),\n \"timeout\",\n );\n }, timeoutMs);\n timer.unref?.();\n tab.pending.set(id, { settle, timer });\n\n if (!send(tab, frame)) {\n tab.pending.delete(id);\n clearTimeout(timer);\n settle(relayRefusal(\"tab-went-away\", `writing to tab \\`${tabId}\\` failed`), \"tab-went-away\");\n }\n });\n }\n\n const handler = (req: IncomingMessage, res: ServerResponse): boolean => {\n const raw = req.url ?? \"/\";\n const qmark = raw.indexOf(\"?\");\n const path = qmark === -1 ? raw : raw.slice(0, qmark);\n if (!path.startsWith(\"/dk/\")) return false;\n\n if (closed) {\n json(res, 503, { error: \"relay closed\" });\n return true;\n }\n if (!allowRemote && !isLoopback(req.socket.remoteAddress)) {\n // Refused here rather than by not binding, because `attach()` means the\n // relay often does not own the listening socket and so cannot choose the\n // interface. The check has to live where the requests are.\n json(res, 403, {\n error: \"forbidden\",\n hint: \"this relay drives a logged-in browser session; set allowRemote and put your app's own auth in front of it\",\n });\n return true;\n }\n\n const query = new URLSearchParams(qmark === -1 ? \"\" : raw.slice(qmark + 1));\n const method = req.method ?? \"GET\";\n\n // Identity BEFORE routing. A caller who cannot be identified is told that\n // and nothing else -- not which methods a path takes, not whether the path\n // exists. Authenticating after routing is how an unauthorised caller gets\n // to map the surface.\n const who = whoami(req);\n if (!(\"id\" in who)) {\n // The body is drained first for the same reason a 405 drains it: bytes\n // left in the socket become the next request on a keep-alive connection.\n void drain(req);\n json(res, 401, { error: who.error, hint: who.hint }, AUTH_HEADERS);\n return true;\n }\n\n // --- the two the tab uses --------------------------------------------\n if (path === \"/dk/events\") {\n if (method !== \"GET\") return bad(res, 405, \"GET only\", \"bad-method\");\n const tabId = query.get(\"tab\");\n if (!tabId) return bad(res, 400, \"GET /dk/events needs ?tab=\");\n if (who.tab !== undefined && who.tab !== tabId) {\n // 403 and not `no-such-tab`, and the difference is the point. The\n // oracle rule is about ADDRESSING somebody else's tab; this caller is\n // opening its own and presented a credential bound to a different id,\n // which it already knows. Telling it so leaks nothing and is the only\n // answer it can act on.\n return bad(res, 403, \"this credential is bound to another tab id\", \"forbidden\");\n }\n openStream(who, tabId, req, res);\n return true;\n }\n\n if (path === \"/dk/result\") {\n if (method !== \"POST\") return bad(res, 405, \"POST only\", \"bad-method\");\n void readJson(req).then((body) => {\n if (!body || typeof body !== \"object\") return bad(res, 400, \"expected a JSON frame\");\n const frame = body as UpFrame;\n if (frame.t !== \"hello\" && frame.t !== \"result\" && frame.t !== \"snapshot\") {\n return bad(res, 400, \"unknown frame `t`\", \"bad-frame\");\n }\n const out = ingest(who, frame, query.get(\"tab\") ?? undefined);\n if (!out.ok) return bad(res, out.status ?? 400, out.why ?? \"rejected\", out.error ?? \"bad-frame\");\n // 202, not 200: the tab is told its frame was accepted, and nothing\n // more. The answer to a call travels to the AGENT, not back up this\n // POST, so a body here would be an invitation to build a second,\n // divergent return path.\n json(res, 202, { ok: true, ...(out.why ? { note: out.why } : {}) });\n }, (err) => {\n onError(err);\n const f = bodyFailure(err);\n bad(res, f.status, f.hint, f.error);\n });\n return true;\n }\n\n // --- the four the agent uses -----------------------------------------\n if (path === \"/dk/tabs\") {\n if (method !== \"GET\") return bad(res, 405, \"GET only\", \"bad-method\");\n // The caller's own tabs, and never anybody else's. A listing of every\n // connected tab is an inventory of other people's sessions with their\n // titles and URLs attached, which is the single worst thing on this\n // surface and was the default.\n json(res, 200, { tabs: summaries(who.id, who.tab) });\n return true;\n }\n\n const parts = path.split(\"/\").filter(Boolean); // dk, tabs, :tab, leaf\n if (parts.length === 4 && parts[1] === \"tabs\") {\n const tabId = decodeURIComponent(parts[2]!);\n const leaf = parts[3];\n\n if (leaf === \"manifest\" || leaf === \"snapshot\") {\n if (method !== \"GET\") return bad(res, 405, \"GET only\", \"bad-method\");\n const tab = owned(who, tabId);\n // Not Result-shaped, and that asymmetry is on purpose. A `Result` is\n // the outcome of a CALL; these two read state, and wrapping \"there is\n // no such tab\" in a fake `{ok:false, snapshot}` would hand the agent a\n // snapshot that describes nothing. Only /call promises one shape,\n // because only /call is the thing an agent must be able to handle\n // uniformly.\n //\n // A tab somebody else owns answers exactly this, byte for byte, so the\n // endpoint cannot be used to probe for other people's tab ids. Checked\n // BEFORE the `no-manifest` case below: a foreign tab that has sent no\n // manifest must not answer `no-manifest`, which would confirm it exists.\n if (!tab) return bad(res, 404, NO_SUCH_TAB_HINT, \"no-such-tab\");\n const value = leaf === \"manifest\" ? tab.manifest : tab.snapshot;\n if (!value) return bad(res, 404, `tab \\`${tabId}\\` has sent no ${leaf}`, `no-${leaf}`);\n json(res, 200, value);\n return true;\n }\n\n if (leaf === \"watch\") {\n if (method !== \"GET\") return bad(res, 405, \"GET only\", \"bad-method\");\n // 404 for a tab that is not connected, rather than an open stream that\n // may never carry anything. Consistent with /snapshot, and it is the\n // answer that tells a client to re-read /dk/tabs instead of waiting on\n // a subscription to a screen that does not exist.\n if (!owned(who, tabId)) return bad(res, 404, NO_SUCH_TAB_HINT, \"no-such-tab\");\n openWatch(who, tabId, req, res);\n return true;\n }\n\n if (leaf === \"call\") {\n if (method !== \"POST\") return bad(res, 405, \"POST only\", \"bad-method\");\n void readJson(req).then(\n (body) => {\n const answer = dispatch(who, tabId, (body ?? {}) as Record<string, unknown>);\n if (!answer) {\n // `bad` returns `true` for `handler`'s benefit -- that is how it\n // says \"answered, stop looking for a route\" -- and returning it\n // from an `onfulfilled` callback is a genuine signature error,\n // not a missing type: a `then` handler must produce `void` or a\n // promise, and `true` makes this branch and the one below\n // disagree about what the chain resolves to. Discarded here, and\n // discarded explicitly rather than by widening the callback's\n // type, because the value is only meaningful to a caller that\n // has a route to decline and this one does not.\n bad(res, 400, \"a call needs a `name`\");\n return;\n }\n return answer.then((result) => {\n // 200 even for a refusal. The HTTP layer succeeded: the question\n // was asked and answered. `ok:false` is the answer, not a\n // transport failure, and conflating the two is how an agent ends\n // up retrying a refusal it should have read.\n json(res, 200, result);\n });\n },\n (err) => {\n // Non-2xx, because no `WireResult` was produced: nothing was asked\n // of any tab. An agent must read this as an exception, not a no.\n onError(err);\n const f = bodyFailure(err);\n bad(res, f.status, f.hint, f.error);\n },\n );\n return true;\n }\n }\n\n return bad(res, 404, `no driverkit route ${method} ${path}`, \"no-route\");\n };\n\n /**\n * Subscribe an agent to a tab's `snapshot` frames.\n *\n * The same SSE shape the tab's own stream uses, down to the opening comment\n * and the ping, so a client needs one parser for both directions rather than\n * two that drift.\n */\n function openWatch(\n who: Principal,\n tabId: string,\n req: IncomingMessage,\n res: ServerResponse,\n ): void {\n const id = key(who.id, tabId);\n res.writeHead(200, SSE_HEADERS);\n res.write(\": driverkit\\n\\n\");\n\n let set = watchers.get(id);\n if (!set) watchers.set(id, (set = new Set<ServerResponse>()));\n set.add(res);\n\n // The current snapshot goes out immediately. A watcher that attached to an\n // idle screen would otherwise know nothing at all until the next click,\n // and would have to fetch /snapshot anyway -- which is the poll the\n // endpoint exists to remove.\n const known = tabs.get(id)?.snapshot;\n if (known) write(res, { t: \"snapshot\", tab: tabId, snapshot: known });\n\n const ping = setInterval(() => write(res, null), pingMs);\n ping.unref?.();\n\n const gone = () => {\n clearInterval(ping);\n const live = watchers.get(id);\n live?.delete(res);\n if (live && live.size === 0) watchers.delete(id);\n };\n res.on(\"close\", gone);\n req.on(\"aborted\", gone);\n }\n\n /** Fan a tab's current snapshot out to its watchers. */\n function push(tab: Tab, force = false): void {\n const snapshot = tab.snapshot;\n if (!snapshot) return;\n const id = key(tab.principal, tab.tab);\n if (!force && broadcast.get(id) === snapshot.rev) return;\n broadcast.set(id, snapshot.rev);\n const set = watchers.get(id);\n if (!set) return;\n const frame: WatchFrame = { t: \"snapshot\", tab: tab.tab, snapshot };\n // A copy, because a watcher that has hung up is removed from the set by its\n // own `close` handler while this loop is running.\n for (const res of [...set]) write(res, frame);\n }\n\n /** One SSE write: a frame, or a ping comment when `frame` is null. */\n function write(res: ServerResponse, frame: WatchFrame | null): void {\n try {\n res.write(frame ? `event: ${frame.t}\\ndata: ${JSON.stringify(frame)}\\n\\n` : \": ping\\n\\n\");\n } catch (err) {\n onError(err);\n }\n }\n\n function summaries(principal?: string, tab?: string): TabSummary[] {\n return [...tabs.values()]\n .filter(\n (t) =>\n (principal === undefined || t.principal === principal) &&\n (tab === undefined || t.tab === tab),\n )\n .map((t) => ({\n tab: t.tab,\n ...(t.app === undefined ? {} : { app: t.app }),\n ...(t.title === undefined ? {} : { title: t.title }),\n ...(t.url === undefined ? {} : { url: t.url }),\n // Forwarded exactly as the tab said it, including not at all. Absence is\n // \"the tab did not say\", which a client must not read as \"not the one\";\n // see `TabFocus`. The relay has no opinion here and originates no value,\n // for the same reason it does not interpret `rev`.\n ...(t.focus === undefined ? {} : { focus: t.focus }),\n // The version, not the manifest. Listing tabs is the cheap call an agent\n // makes often; inlining every manifest would make it the expensive one.\n ...(t.manifest === undefined ? {} : { manifestVersion: t.manifest.version }),\n ...(t.snapshot === undefined ? {} : { rev: t.snapshot.rev }),\n since: t.since,\n }));\n }\n\n /**\n * The caller's principal, or the 401 to answer instead.\n *\n * Three doors, in this order:\n *\n * 1. AUTH OFF. Neither `auth` nor `resolvePrincipal` configured: everything\n * is one principal and nothing is scoped. The unconfigured loopback relay\n * a single developer runs, needing no tokens, no keys and no setup -- and\n * the combination `allowRemote` makes impossible is the one where this is\n * also exposed.\n * 2. `resolvePrincipal`. The embedded case: an app that already has sessions\n * answers from its own middleware.\n * 3. THE CREDENTIAL. See `credentialFrom` for where it is read from.\n *\n * NO CREDENTIAL AND A BAD CREDENTIAL ARE DIFFERENT ANSWERS, and neither is\n * \"anonymous\". Silently treating an unreadable credential as a fresh\n * anonymous visitor was the tempting shape and is wrong twice over: a user\n * whose token lapsed would quietly become a stranger and lose their own tabs,\n * and an agent with a misconfigured key would be told \"you have no tabs\"\n * rather than \"your key is wrong\". Anonymous is a credential of its own kind,\n * so it is never what the absence of one means.\n */\n function whoami(req: IncomingMessage): Principal | { error: string; hint: string } {\n if (!auth && !resolvePrincipal) return LOCAL;\n\n const headers = req.headers as Record<string, string | string[] | undefined>;\n if (resolvePrincipal) {\n let resolved: string | undefined;\n try {\n resolved = resolvePrincipal(headers);\n } catch (err) {\n // A host hook that throws must not become a 500 that mentions the app's\n // internals, and must certainly not become an authenticated request.\n // It is an unidentified caller.\n onError(err);\n }\n if (resolved) return { id: resolved };\n }\n\n if (!auth) {\n return { error: \"no-credential\", hint: \"this relay identifies callers by session\" };\n }\n\n const url = req.url ?? \"/\";\n const at = url.indexOf(\"?\");\n const credential = credentialFrom(\n headers,\n new URLSearchParams(at === -1 ? \"\" : url.slice(at + 1)),\n );\n if (!credential) {\n return {\n error: \"no-credential\",\n hint:\n \"present a tab token: Authorization: Bearer, X-DK-Token, the dk_token cookie, \" +\n \"or ?dk_token= (the last of those ends up in proxy access logs)\",\n };\n }\n try {\n return auth.principal(credential);\n } catch (err) {\n if (!(err instanceof AuthError)) throw err;\n // ONE slug for every way a credential can fail, and the hint is fixed.\n // \"The signature verified but the audience was wrong\" tells a forger that\n // the forgery worked; \"expired\" and \"not yet valid\" tell a prober the\n // clock. A legitimate client's move is the same in every case -- mint a\n // fresh token, retry once -- so the distinction buys it nothing and buys\n // an attacker a test harness. The reason is never logged either: it would\n // be a log line about a credential.\n return { error: \"bad-credential\", hint: \"present a fresh tab token\" };\n }\n }\n\n return {\n handler,\n attach(server: Server) {\n // The listeners already on the server are taken off and re-called by\n // hand, rather than simply prepending the relay to them.\n //\n // `node:http` runs EVERY `request` listener, so prepending would mean\n // the app's own handler also runs for /dk/* and writes a second set of\n // headers into a response the relay already answered. Making it work\n // would require every host app to start with `if (res.headersSent)\n // return` -- a line nobody adds until the day it crashes a stream. So\n // `attach` behaves the way the word implies: the relay takes /dk/*, and\n // everything else is passed along untouched.\n //\n // The consequence worth knowing: listeners registered AFTER attach are\n // not wrapped and will see /dk/* too. Attach last.\n const downstream = server.listeners(\"request\") as Array<\n (req: IncomingMessage, res: ServerResponse) => void\n >;\n server.removeAllListeners(\"request\");\n server.on(\"request\", (req, res) => {\n if (handler(req as IncomingMessage, res as ServerResponse)) return;\n for (const next of downstream) next.call(server, req as IncomingMessage, res as ServerResponse);\n });\n },\n tabs: () => summaries(),\n tabsFor: (principal: string, tab?: string) => summaries(principal, tab),\n close() {\n closed = true;\n for (const tab of [...tabs.values()]) {\n clearInterval(tab.ping);\n for (const [, p] of tab.pending) {\n clearTimeout(p.timer);\n p.settle(relayRefusal(\"tab-went-away\", \"the relay is shutting down\"), \"tab-went-away\");\n }\n tab.pending.clear();\n try {\n tab.res.end();\n } catch (err) {\n onError(err);\n }\n }\n tabs.clear();\n for (const set of watchers.values()) {\n for (const res of set) {\n try {\n res.end();\n } catch (err) {\n onError(err);\n }\n }\n }\n watchers.clear();\n broadcast.clear();\n },\n };\n}\n\n/**\n * A refusal the relay originated: one of a closed set, and with NO `snapshot`.\n *\n * The missing field is the whole signal. `Result` requires a snapshot because a\n * driver mounted in a page always has one; the relay often does not -- a call\n * to a tab that never connected has no screen behind it at all -- so\n * `WireResult` widens the type rather than letting the relay invent a value.\n *\n * An invented snapshot would be worse than a missing one in both directions.\n * An empty one tells an agent the app has no rows, which is a lie about the\n * app rather than about the call. A sentinel like `{where:\"(not connected)\"}`\n * is still a snapshot, so some client eventually renders it to a model as\n * though it were a screen. Absence cannot be mistaken for either: a client\n * reads it as \"the call did not arrive\", never as \"the screen is empty\".\n */\n/**\n * The tab's answer, plus the two timing fields the tab sent beside it.\n *\n * THE RELAY DOES NOT MEASURE, AND MUST NOT. It has one number of its own --\n * the round trip it held the call open for, which is in the audit record -- and\n * that number is the network out, plus the tab's work, plus any question the\n * page put to a person, plus the network back. Substituting it for a missing\n * `tookMs` would hand an agent exactly the sum `tookMs` exists to take apart.\n * So this copies, validates and otherwise has no opinion, which is the same\n * restraint `rev`, `screen`, `plan` and `focus` get on their way through.\n *\n * WHY THE KEYS ARE STRIPPED FIRST. They are reserved on this body. `result` is\n * what the APP returned, and an app that filled in `tookMs` itself would be\n * making a claim about its own speed where the agent is entitled to an\n * observation -- so a value found in there is dropped and only the frame's own\n * field, written by the page-side harness around its one call into the driver,\n * is forwarded. The copy is shallow and touches nothing else: every other field\n * of the `result`, a `stale` hint and the snapshot included, is forwarded byte\n * for byte as before.\n *\n * ABSENT MEANS UNKNOWN. A tab from before this existed, or one that cannot say\n * honestly, sends nothing, and nothing is what the agent gets: never a zero,\n * which every client would render as \"instant\". A figure that is not a finite\n * number at or above zero is dropped on the way through, the rule `Tab.focus`\n * already has for a value that is not a string.\n */\nfunction timed(result: WireResult, frame: { tookMs?: unknown; waitedMs?: unknown }): WireResult {\n const out = { ...(result as Record<string, unknown>) };\n delete out.tookMs;\n delete out.waitedMs;\n const took = ms(frame.tookMs);\n if (took !== undefined) {\n out.tookMs = took;\n // Only beside a `tookMs`, never on its own. `waitedMs` is defined as the\n // amount already subtracted from it, so without one it is a quantity\n // relative to nothing -- and a reader might well subtract it a second time.\n const waited = ms(frame.waitedMs);\n if (waited !== undefined) out.waitedMs = waited;\n }\n return out as WireResult;\n}\n\n/** A duration off the wire, or undefined for anything that is not one. Whole\n * milliseconds: a float survives JSON and nothing downstream wants tenths of a\n * millisecond, so it is floored here rather than in each reader. */\nfunction ms(value: unknown): number | undefined {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) return undefined;\n return Math.floor(value);\n}\n\nfunction relayRefusal(refused: RelayRefusal, hint: string): WireResult {\n return { ok: false, refused, hint };\n}\n\nfunction isLoopback(address: string | undefined): boolean {\n if (!address) return false; // A unix socket or an unknown peer is not proven local.\n return (\n address === \"::1\" ||\n address === \"::ffff:127.0.0.1\" ||\n address.startsWith(\"127.\") ||\n address.startsWith(\"::ffff:127.\")\n );\n}\n\nfunction json(\n res: ServerResponse,\n status: number,\n body: unknown,\n extra: Record<string, string> = {},\n): void {\n const text = JSON.stringify(body);\n res.writeHead(status, {\n \"content-type\": \"application/json; charset=utf-8\",\n \"content-length\": Buffer.byteLength(text),\n // A tab id is a capability, so nothing here is cacheable by anything.\n \"cache-control\": \"no-store\",\n ...extra,\n });\n res.end(text);\n}\n\n/**\n * Read and discard a body we are not going to parse.\n *\n * PROTOCOL.md: \"An unread body is worse than a wrong answer.\" On a keep-alive\n * connection the bytes a relay failed to read are still in the socket when the\n * next request is parsed off it, so they BECOME that request. A 401 that left\n * the body behind would answer one caller correctly and destroy every later\n * request on that socket.\n */\nfunction drain(req: IncomingMessage): void {\n req.resume();\n}\n\n/** A non-2xx answer: no `WireResult` was produced, so the client must read it\n * as a transport failure rather than as an app's \"no\". The `error` slug is\n * pinned per case by PROTOCOL.md's status table. */\nfunction bad(res: ServerResponse, status: number, hint: string, error = \"bad-request\"): true {\n json(res, status, { error, hint });\n return true;\n}\n\ninterface BodyError extends Error {\n dkStatus: number;\n dkError: string;\n}\n\nfunction tooLarge(): BodyError {\n return Object.assign(new Error(`body over the ${MAX_BODY}-byte limit`), {\n dkStatus: 413,\n dkError: \"too-large\",\n });\n}\n\n/** The status a failed body read should answer with: 413 when it was too big,\n * 400 when it was unparseable. Distinguished because they are different\n * problems for the sender -- one is \"send less\", the other is \"send JSON\". */\nfunction bodyFailure(err: unknown): { status: number; error: string; hint: string } {\n const e = err as Partial<BodyError>;\n return e?.dkStatus\n ? { status: e.dkStatus, error: e.dkError ?? \"too-large\", hint: e.message ?? \"body too large\" }\n : { status: 400, error: \"bad-request\", hint: \"could not read the body\" };\n}\n\n/**\n * Read a JSON body, with the size limit enforced the way a 413 can survive.\n *\n * Over the limit, buffering stops but READING CONTINUES, and the rejection\n * waits for `end`. The obvious implementation -- hang up the moment the limit\n * is crossed -- loses the 413 it is trying to send: the sender is still writing,\n * so it gets a reset on its own socket and never reads the response that would\n * have told it what was wrong. A sender that cannot learn why it failed retries\n * identically, which is the opposite of what a limit is for.\n *\n * Memory stays bounded because the overflow is counted and discarded rather\n * than kept. `ABORT_AT` is the backstop for a sender that is not going to stop:\n * past it the connection does go, because at that point the upload is an attack\n * and not a mistake, and politely reading all of it is the attack succeeding.\n */\nfunction readJson(req: IncomingMessage): Promise<unknown> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n let size = 0;\n let over = false;\n req.on(\"data\", (c: Buffer) => {\n size += c.length;\n if (size > MAX_BODY) {\n over = true;\n chunks.length = 0; // Nothing here will be parsed; stop paying for it.\n if (size > ABORT_AT) {\n reject(tooLarge());\n req.destroy();\n }\n return;\n }\n chunks.push(c);\n });\n req.on(\"end\", () => {\n if (over) return reject(tooLarge());\n const text = Buffer.concat(chunks).toString(\"utf8\");\n if (!text.trim()) return resolve({});\n try {\n resolve(JSON.parse(text));\n } catch (err) {\n reject(err);\n }\n });\n req.on(\"error\", reject);\n });\n}\n"]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run the relay on its own.
|
|
3
|
+
*
|
|
4
|
+
* node --experimental-strip-types packages/relay/src/serve.ts
|
|
5
|
+
* DK_PORT=7777 node --experimental-strip-types packages/relay/src/serve.ts
|
|
6
|
+
*
|
|
7
|
+
* Most deployments should not use this file. PROTOCOL.md's argument for SSE is
|
|
8
|
+
* that the relay belongs inside a server you already run -- an extra process is
|
|
9
|
+
* an extra thing to supervise. This
|
|
10
|
+
* exists for the case where there is no such server yet: a local dev loop, or a
|
|
11
|
+
* static page you want to drive today.
|
|
12
|
+
*/
|
|
13
|
+
import { type Server } from "node:http";
|
|
14
|
+
import { type Relay, type RelayOptions } from "./relay.ts";
|
|
15
|
+
export interface ServeOptions extends RelayOptions {
|
|
16
|
+
port?: number;
|
|
17
|
+
/**
|
|
18
|
+
* Loopback by default, and changing it takes TWO deliberate acts: a host here
|
|
19
|
+
* and `allowRemote` in the relay itself. That is not redundancy. Binding
|
|
20
|
+
* 0.0.0.0 is a thing people do by reflex to reach a dev server from a phone;
|
|
21
|
+
* here it would publish the ability to drive the logged-in session of whoever
|
|
22
|
+
* has a tab open. Requiring the second flag means nobody arrives at a
|
|
23
|
+
* remotely drivable browser by muscle memory.
|
|
24
|
+
*/
|
|
25
|
+
host?: string;
|
|
26
|
+
}
|
|
27
|
+
export declare function serve(options?: ServeOptions): Promise<{
|
|
28
|
+
server: Server;
|
|
29
|
+
relay: Relay;
|
|
30
|
+
port: number;
|
|
31
|
+
url: string;
|
|
32
|
+
}>;
|
|
33
|
+
//# sourceMappingURL=serve.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"serve.d.ts","sourceRoot":"","sources":["../../src/relay/serve.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAgB,KAAK,MAAM,EAAE,MAAM,WAAW,CAAC;AACtD,OAAO,EAAe,KAAK,KAAK,EAAE,KAAK,YAAY,EAAE,MAAM,YAAY,CAAC;AAGxE,MAAM,WAAW,YAAa,SAAQ,YAAY;IAChD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;;;;;OAOG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,wBAAgB,KAAK,CAAC,OAAO,GAAE,YAAiB,GAAG,OAAO,CAAC;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,KAAK,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAAC,CA8BtH"}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run the relay on its own.
|
|
3
|
+
*
|
|
4
|
+
* node --experimental-strip-types packages/relay/src/serve.ts
|
|
5
|
+
* DK_PORT=7777 node --experimental-strip-types packages/relay/src/serve.ts
|
|
6
|
+
*
|
|
7
|
+
* Most deployments should not use this file. PROTOCOL.md's argument for SSE is
|
|
8
|
+
* that the relay belongs inside a server you already run -- an extra process is
|
|
9
|
+
* an extra thing to supervise. This
|
|
10
|
+
* exists for the case where there is no such server yet: a local dev loop, or a
|
|
11
|
+
* static page you want to drive today.
|
|
12
|
+
*/
|
|
13
|
+
import { createServer } from "node:http";
|
|
14
|
+
import { createRelay } from "./relay.js";
|
|
15
|
+
import { TabAuth } from "./auth.js";
|
|
16
|
+
export function serve(options = {}) {
|
|
17
|
+
const host = options.host ?? "127.0.0.1";
|
|
18
|
+
const port = options.port ?? 0;
|
|
19
|
+
// `createRelay` itself refuses `allowRemote` without `auth` or
|
|
20
|
+
// `resolvePrincipal`, so there is no second copy of that rule here to fall
|
|
21
|
+
// out of step with the first. This one is only about the interface.
|
|
22
|
+
if (host !== "127.0.0.1" && host !== "localhost" && host !== "::1" && !options.allowRemote) {
|
|
23
|
+
throw new Error(`driverkit: refusing to bind ${host} without allowRemote. A reachable relay is someone else ` +
|
|
24
|
+
`driving your logged-in browser session. Read "Who is allowed to do this" in PROTOCOL.md, ` +
|
|
25
|
+
`put your app's own auth in front of the relay, then pass allowRemote: true.`);
|
|
26
|
+
}
|
|
27
|
+
const relay = createRelay(options);
|
|
28
|
+
// Standalone, so an unknown path IS an error -- unlike the embedded case,
|
|
29
|
+
// where `handler` returning false means "not mine, let the app answer".
|
|
30
|
+
const server = createServer((req, res) => {
|
|
31
|
+
if (relay.handler(req, res))
|
|
32
|
+
return;
|
|
33
|
+
res.writeHead(404, { "content-type": "application/json" });
|
|
34
|
+
res.end(JSON.stringify({ error: "not-found", hint: "this process serves /dk/* only" }));
|
|
35
|
+
});
|
|
36
|
+
return new Promise((resolve) => {
|
|
37
|
+
server.listen(port, host, () => {
|
|
38
|
+
const addr = server.address();
|
|
39
|
+
const bound = typeof addr === "object" && addr ? addr.port : port;
|
|
40
|
+
resolve({ server, relay, port: bound, url: `http://${host}:${bound}` });
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
// Node 22.19+ sets `import.meta.main` only for the entry module, so importing
|
|
45
|
+
// `serve` from a test or an app does not start a server.
|
|
46
|
+
if (import.meta.main) {
|
|
47
|
+
// Spread rather than `?? undefined`, because `exactOptionalPropertyTypes` is
|
|
48
|
+
// on and it is right to be on here: `ServeOptions.timeoutMs` being absent
|
|
49
|
+
// means "use the relay's default", and passing it explicitly as `undefined`
|
|
50
|
+
// is a different statement that happens to behave the same today. An unset
|
|
51
|
+
// env var must say nothing at all rather than say "no timeout".
|
|
52
|
+
// DK_SECRET, not an argument: an argument is visible in `ps` to every user on
|
|
53
|
+
// the box, and a secret that leaks to a shell history is a secret.
|
|
54
|
+
const secret = process.env.DK_SECRET;
|
|
55
|
+
const audience = process.env.DK_AUDIENCE;
|
|
56
|
+
if (Boolean(secret) !== Boolean(audience)) {
|
|
57
|
+
console.error("driverkit relay: DK_SECRET and DK_AUDIENCE go together. The secret verifies a token; " +
|
|
58
|
+
"the audience says which relay it was minted for.");
|
|
59
|
+
process.exit(2);
|
|
60
|
+
}
|
|
61
|
+
const auth = secret && audience
|
|
62
|
+
? new TabAuth({
|
|
63
|
+
secret,
|
|
64
|
+
audience,
|
|
65
|
+
anonymous: process.env.DK_NO_ANONYMOUS !== "1",
|
|
66
|
+
requireTabBinding: process.env.DK_REQUIRE_TAB_BINDING === "1",
|
|
67
|
+
})
|
|
68
|
+
: undefined;
|
|
69
|
+
const { url } = await serve({
|
|
70
|
+
port: process.env.DK_PORT ? Number(process.env.DK_PORT) : 7777,
|
|
71
|
+
...(process.env.DK_HOST ? { host: process.env.DK_HOST } : {}),
|
|
72
|
+
allowRemote: process.env.DK_ALLOW_REMOTE === "1",
|
|
73
|
+
...(auth ? { auth } : {}),
|
|
74
|
+
...(process.env.DK_TIMEOUT_MS ? { timeoutMs: Number(process.env.DK_TIMEOUT_MS) } : {}),
|
|
75
|
+
onError: (err) => console.error("driverkit relay:", err),
|
|
76
|
+
});
|
|
77
|
+
console.error(`driverkit relay on ${url} (tabs: ${url}/dk/tabs)`);
|
|
78
|
+
if (process.env.DK_ALLOW_REMOTE === "1") {
|
|
79
|
+
console.error(`driverkit relay: allowRemote is ON. Callers are identified by tab token ` +
|
|
80
|
+
`(audience ${JSON.stringify(audience)}); each sees only its own tabs.`);
|
|
81
|
+
}
|
|
82
|
+
else if (auth) {
|
|
83
|
+
console.error("driverkit relay: tab tokens required, loopback only.");
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
//# sourceMappingURL=serve.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"serve.js","sourceRoot":"","sources":["../../src/relay/serve.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,YAAY,EAAe,MAAM,WAAW,CAAC;AACtD,OAAO,EAAE,WAAW,EAAiC,MAAM,YAAY,CAAC;AACxE,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAepC,MAAM,UAAU,KAAK,CAAC,UAAwB,EAAE;IAC9C,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,WAAW,CAAC;IACzC,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,CAAC,CAAC;IAC/B,+DAA+D;IAC/D,2EAA2E;IAC3E,oEAAoE;IACpE,IAAI,IAAI,KAAK,WAAW,IAAI,IAAI,KAAK,WAAW,IAAI,IAAI,KAAK,KAAK,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC;QAC3F,MAAM,IAAI,KAAK,CACb,+BAA+B,IAAI,0DAA0D;YAC3F,2FAA2F;YAC3F,6EAA6E,CAChF,CAAC;IACJ,CAAC;IAED,MAAM,KAAK,GAAG,WAAW,CAAC,OAAO,CAAC,CA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AC;KACzD,CAAC,CAAC;IACH,OAAO,CAAC,KAAK,CAAC,sBAAsB,GAAG,YAAY,GAAG,WAAW,CAAC,CAAC;IACnE,IAAI,OAAO,CAAC,GAAG,CAAC,eAAe,KAAK,GAAG,EAAE,CAAC;QACxC,OAAO,CAAC,KAAK,CACX,0EAA0E;YACxE,aAAa,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,iCAAiC,CACzE,CAAC;IACJ,CAAC;SAAM,IAAI,IAAI,EAAE,CAAC;QAChB,OAAO,CAAC,KAAK,CAAC,sDAAsD,CAAC,CAAC;IACxE,CAAC;AACH,CAAC","sourcesContent":["/**\n * Run the relay on its own.\n *\n * node --experimental-strip-types packages/relay/src/serve.ts\n * DK_PORT=7777 node --experimental-strip-types packages/relay/src/serve.ts\n *\n * Most deployments should not use this file. PROTOCOL.md's argument for SSE is\n * that the relay belongs inside a server you already run -- an extra process is\n * an extra thing to supervise. This\n * exists for the case where there is no such server yet: a local dev loop, or a\n * static page you want to drive today.\n */\n\nimport { createServer, type Server } from \"node:http\";\nimport { createRelay, type Relay, type RelayOptions } from \"./relay.ts\";\nimport { TabAuth } from \"./auth.ts\";\n\nexport interface ServeOptions extends RelayOptions {\n port?: number;\n /**\n * Loopback by default, and changing it takes TWO deliberate acts: a host here\n * and `allowRemote` in the relay itself. That is not redundancy. Binding\n * 0.0.0.0 is a thing people do by reflex to reach a dev server from a phone;\n * here it would publish the ability to drive the logged-in session of whoever\n * has a tab open. Requiring the second flag means nobody arrives at a\n * remotely drivable browser by muscle memory.\n */\n host?: string;\n}\n\nexport function serve(options: ServeOptions = {}): Promise<{ server: Server; relay: Relay; port: number; url: string }> {\n const host = options.host ?? \"127.0.0.1\";\n const port = options.port ?? 0;\n // `createRelay` itself refuses `allowRemote` without `auth` or\n // `resolvePrincipal`, so there is no second copy of that rule here to fall\n // out of step with the first. This one is only about the interface.\n if (host !== \"127.0.0.1\" && host !== \"localhost\" && host !== \"::1\" && !options.allowRemote) {\n throw new Error(\n `driverkit: refusing to bind ${host} without allowRemote. A reachable relay is someone else ` +\n `driving your logged-in browser session. Read \"Who is allowed to do this\" in PROTOCOL.md, ` +\n `put your app's own auth in front of the relay, then pass allowRemote: true.`,\n );\n }\n\n const relay = createRelay(options);\n // Standalone, so an unknown path IS an error -- unlike the embedded case,\n // where `handler` returning false means \"not mine, let the app answer\".\n const server = createServer((req, res) => {\n if (relay.handler(req, res)) return;\n res.writeHead(404, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"not-found\", hint: \"this process serves /dk/* only\" }));\n });\n\n return new Promise((resolve) => {\n server.listen(port, host, () => {\n const addr = server.address();\n const bound = typeof addr === \"object\" && addr ? addr.port : port;\n resolve({ server, relay, port: bound, url: `http://${host}:${bound}` });\n });\n });\n}\n\n// Node 22.19+ sets `import.meta.main` only for the entry module, so importing\n// `serve` from a test or an app does not start a server.\nif ((import.meta as unknown as { main?: boolean }).main) {\n // Spread rather than `?? undefined`, because `exactOptionalPropertyTypes` is\n // on and it is right to be on here: `ServeOptions.timeoutMs` being absent\n // means \"use the relay's default\", and passing it explicitly as `undefined`\n // is a different statement that happens to behave the same today. An unset\n // env var must say nothing at all rather than say \"no timeout\".\n // DK_SECRET, not an argument: an argument is visible in `ps` to every user on\n // the box, and a secret that leaks to a shell history is a secret.\n const secret = process.env.DK_SECRET;\n const audience = process.env.DK_AUDIENCE;\n if (Boolean(secret) !== Boolean(audience)) {\n console.error(\n \"driverkit relay: DK_SECRET and DK_AUDIENCE go together. The secret verifies a token; \" +\n \"the audience says which relay it was minted for.\",\n );\n process.exit(2);\n }\n const auth = secret && audience\n ? new TabAuth({\n secret,\n audience,\n anonymous: process.env.DK_NO_ANONYMOUS !== \"1\",\n requireTabBinding: process.env.DK_REQUIRE_TAB_BINDING === \"1\",\n })\n : undefined;\n\n const { url } = await serve({\n port: process.env.DK_PORT ? Number(process.env.DK_PORT) : 7777,\n ...(process.env.DK_HOST ? { host: process.env.DK_HOST } : {}),\n allowRemote: process.env.DK_ALLOW_REMOTE === \"1\",\n ...(auth ? { auth } : {}),\n ...(process.env.DK_TIMEOUT_MS ? { timeoutMs: Number(process.env.DK_TIMEOUT_MS) } : {}),\n onError: (err) => console.error(\"driverkit relay:\", err),\n });\n console.error(`driverkit relay on ${url} (tabs: ${url}/dk/tabs)`);\n if (process.env.DK_ALLOW_REMOTE === \"1\") {\n console.error(\n `driverkit relay: allowRemote is ON. Callers are identified by tab token ` +\n `(audience ${JSON.stringify(audience)}); each sees only its own tabs.`,\n );\n } else if (auth) {\n console.error(\"driverkit relay: tab tokens required, loopback only.\");\n }\n}\n"]}
|