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,391 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* driverkit/relay — who the caller is, and nothing more than that.
|
|
3
|
+
*
|
|
4
|
+
* A port of `python/src/driverkit/auth.py`, claim for claim and refusal for
|
|
5
|
+
* refusal. The long-form argument lives in that file's docstring and in
|
|
6
|
+
* PROTOCOL.md's "Who is allowed to do this"; what follows here is the summary
|
|
7
|
+
* and the places this half could plausibly drift.
|
|
8
|
+
*
|
|
9
|
+
* This module answers one question: WHICH PERSON is on the other end of this
|
|
10
|
+
* request? It never answers "may they do this", because PROTOCOL.md's core
|
|
11
|
+
* property is untouched by any of it:
|
|
12
|
+
*
|
|
13
|
+
* THE RELAY GRANTS NO AUTHORITY. It forwards a verb to a tab that is already
|
|
14
|
+
* logged in as a person, and that tab's own session is what the app checks.
|
|
15
|
+
*
|
|
16
|
+
* A credential here buys its holder nothing they could not already do in their
|
|
17
|
+
* own browser. What it buys the RELAY is the ability to keep a hundred people's
|
|
18
|
+
* tabs apart. Isolation, not authorisation.
|
|
19
|
+
*
|
|
20
|
+
* The token:
|
|
21
|
+
*
|
|
22
|
+
* dkt1.<base64url(payload JSON)>.<base64url(HMAC-SHA256(key, "dkt1." + payload))>
|
|
23
|
+
*
|
|
24
|
+
* The algorithm is in the PREFIX, not in the payload, which is the deliberate
|
|
25
|
+
* departure from JWT: a JWT names its own algorithm in a header the verifier
|
|
26
|
+
* has not authenticated yet, and that is the root of both the `alg: none`
|
|
27
|
+
* family of bugs and the HMAC/RSA confusion family. Here there is nothing to
|
|
28
|
+
* negotiate. A future `dkt2` is a new prefix -- a greppable change rather than
|
|
29
|
+
* a field an attacker can set.
|
|
30
|
+
*
|
|
31
|
+
* Claims: `sub` (the principal), `aud` (which relay this is for), `iat`/`exp`
|
|
32
|
+
* (Unix seconds, honoured with `DEFAULT_SKEW_S` of slack), `kid` (which key
|
|
33
|
+
* signed it; read before verification, used only to SELECT the key, so an
|
|
34
|
+
* attacker who edits it fails the MAC), and an optional `tab` binding the
|
|
35
|
+
* credential to one tab id.
|
|
36
|
+
*
|
|
37
|
+
* Anonymous: `anon1.<base64url(32 random bytes)>`, minted by the page, keyless
|
|
38
|
+
* in the relay, resolving to `anon:<sha256("driverkit-anon-v1." + secret)[:16]>`.
|
|
39
|
+
* Independent per visitor -- "anonymous" is never one bucket. It is a bearer
|
|
40
|
+
* capability and not an identity, it dies with the tab, and it confers nothing
|
|
41
|
+
* at the app.
|
|
42
|
+
*
|
|
43
|
+
* Zero dependencies: `node:crypto` only.
|
|
44
|
+
*/
|
|
45
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
46
|
+
/** The version prefix that IS the algorithm. */
|
|
47
|
+
export const TOKEN_PREFIX = "dkt1";
|
|
48
|
+
/** The anonymous credential's prefix. */
|
|
49
|
+
export const ANON_PREFIX = "anon1";
|
|
50
|
+
/** What an anonymous principal id starts with. */
|
|
51
|
+
export const ANON_ID_PREFIX = "anon:";
|
|
52
|
+
/**
|
|
53
|
+
* The principal every request resolves to when auth is off.
|
|
54
|
+
*
|
|
55
|
+
* One principal means the scoping in `relay.ts` is a no-op and the
|
|
56
|
+
* unconfigured loopback relay a single developer runs is byte-for-byte what it
|
|
57
|
+
* was before any of this existed.
|
|
58
|
+
*/
|
|
59
|
+
export const LOCAL_PRINCIPAL = "local";
|
|
60
|
+
/**
|
|
61
|
+
* Shortest key accepted. A 16-character shared secret makes the HMAC theatre,
|
|
62
|
+
* and the moment to say so is at construction rather than in a post-mortem.
|
|
63
|
+
*/
|
|
64
|
+
export const MIN_SECRET_BYTES = 32;
|
|
65
|
+
/**
|
|
66
|
+
* How long a freshly minted token lasts, in ms.
|
|
67
|
+
*
|
|
68
|
+
* Short, because a short lifetime is what substitutes for the revocation a
|
|
69
|
+
* stateless token cannot have. The page asks for a new one on every reconnect,
|
|
70
|
+
* so this does not need to cover a session.
|
|
71
|
+
*/
|
|
72
|
+
export const DEFAULT_TTL_MS = 120_000;
|
|
73
|
+
/**
|
|
74
|
+
* Clock slack on `exp`, and the window by which an `iat` may lead now.
|
|
75
|
+
*
|
|
76
|
+
* Sixty seconds, not five minutes. Skew tolerance is a direct extension of
|
|
77
|
+
* every token's lifetime, so a five-minute window on a two-minute token would
|
|
78
|
+
* more than treble the time a leaked one stays useful. Sixty covers two hosts
|
|
79
|
+
* with working NTP, which is the case this is for; a fleet whose clocks are
|
|
80
|
+
* minutes apart has a problem a wider window hides rather than solves.
|
|
81
|
+
*/
|
|
82
|
+
export const DEFAULT_SKEW_MS = 60_000;
|
|
83
|
+
const ANON_DOMAIN = "driverkit-anon-v1.";
|
|
84
|
+
/**
|
|
85
|
+
* A credential did not check out.
|
|
86
|
+
*
|
|
87
|
+
* Deliberately carries no machine-readable reason. The relay answers every
|
|
88
|
+
* instance with one slug -- `bad-credential` -- because the distinctions a
|
|
89
|
+
* caller might want are exactly the distinctions an attacker wants: "the
|
|
90
|
+
* signature verified but the audience was wrong" tells a forger the forgery
|
|
91
|
+
* worked. A legitimate client's move is the same in every case (mint a fresh
|
|
92
|
+
* token, retry once), so the split buys it nothing.
|
|
93
|
+
*/
|
|
94
|
+
export class AuthError extends Error {
|
|
95
|
+
name = "AuthError";
|
|
96
|
+
}
|
|
97
|
+
/** The principal id an `anon1.` credential resolves to. Pure and keyless. */
|
|
98
|
+
export function anonPrincipalId(credential) {
|
|
99
|
+
const dot = credential.indexOf(".");
|
|
100
|
+
const secret = dot === -1 ? "" : credential.slice(dot + 1);
|
|
101
|
+
const digest = createHash("sha256").update(ANON_DOMAIN + secret, "utf8").digest();
|
|
102
|
+
return ANON_ID_PREFIX + digest.subarray(0, 16).toString("hex");
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* A fresh anonymous credential. For a page, or a test; never the relay.
|
|
106
|
+
*
|
|
107
|
+
* 256 bits, because this string is the whole of an anonymous visitor's
|
|
108
|
+
* isolation: anybody who can guess it is that visitor.
|
|
109
|
+
*/
|
|
110
|
+
export function mintAnonCredential() {
|
|
111
|
+
return `${ANON_PREFIX}.${b64u(randomBytes(32))}`;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Verification, and the minter the app's backend uses.
|
|
115
|
+
*
|
|
116
|
+
* The app's backend is the only thing that knows who a browser is, so it is
|
|
117
|
+
* the only thing that may mint. Give it the same `keys` and `audience` the
|
|
118
|
+
* relay has and it needs nothing else -- no relay client, no callback, no
|
|
119
|
+
* shared database.
|
|
120
|
+
*
|
|
121
|
+
* Rotation is additive and ordered:
|
|
122
|
+
*
|
|
123
|
+
* 1. Add the new key to the RELAY's `keys`. Deploy. It accepts both; nothing
|
|
124
|
+
* mints with the new one yet.
|
|
125
|
+
* 2. Point the minter at it (`activeKid`). Deploy.
|
|
126
|
+
* 3. After `ttlMs + skewMs`, drop the old key from the relay.
|
|
127
|
+
*
|
|
128
|
+
* The order is the whole of it. A key the relay does not know yet refuses
|
|
129
|
+
* every token signed with it, and a key dropped before the last token signed
|
|
130
|
+
* with it expires logs a hundred people out at once.
|
|
131
|
+
*/
|
|
132
|
+
export class TabAuth {
|
|
133
|
+
audience;
|
|
134
|
+
ttlMs;
|
|
135
|
+
skewMs;
|
|
136
|
+
anonymous;
|
|
137
|
+
requireTabBinding;
|
|
138
|
+
activeKid;
|
|
139
|
+
#keys = new Map();
|
|
140
|
+
constructor(options) {
|
|
141
|
+
const { audience, keys, secret } = options;
|
|
142
|
+
if (keys && secret !== undefined)
|
|
143
|
+
throw new Error("driverkit: pass keys or secret, not both");
|
|
144
|
+
// Sugar for the single-key case, which is every deployment until the first
|
|
145
|
+
// rotation. It still gets a kid, so a single-key relay's tokens are shaped
|
|
146
|
+
// exactly like a rotating one's and rotation needs no format change.
|
|
147
|
+
const table = keys ?? (secret === undefined ? undefined : { k1: secret });
|
|
148
|
+
if (!table || Object.keys(table).length === 0) {
|
|
149
|
+
throw new Error("driverkit: TabAuth needs keys or secret");
|
|
150
|
+
}
|
|
151
|
+
if (!audience)
|
|
152
|
+
throw new Error("driverkit: TabAuth needs an audience naming this relay");
|
|
153
|
+
for (const [kid, value] of Object.entries(table)) {
|
|
154
|
+
const raw = typeof value === "string" ? Buffer.from(value, "utf8") : Buffer.from(value);
|
|
155
|
+
if (raw.length < MIN_SECRET_BYTES) {
|
|
156
|
+
throw new Error(`driverkit: key "${kid}" is ${raw.length} bytes; at least ${MIN_SECRET_BYTES} are ` +
|
|
157
|
+
`needed. \`node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))"\``);
|
|
158
|
+
}
|
|
159
|
+
if (!kid || kid.includes("."))
|
|
160
|
+
throw new Error(`driverkit: "${kid}" is not a usable key id`);
|
|
161
|
+
this.#keys.set(kid, raw);
|
|
162
|
+
}
|
|
163
|
+
this.audience = audience;
|
|
164
|
+
this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
|
|
165
|
+
this.skewMs = options.skewMs ?? DEFAULT_SKEW_MS;
|
|
166
|
+
this.anonymous = options.anonymous ?? true;
|
|
167
|
+
this.requireTabBinding = options.requireTabBinding ?? false;
|
|
168
|
+
this.activeKid = options.activeKid ?? this.#keys.keys().next().value;
|
|
169
|
+
if (!this.#keys.has(this.activeKid)) {
|
|
170
|
+
throw new Error(`driverkit: activeKid "${this.activeKid}" is not in keys`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* A token saying `principal` is who the bearer is.
|
|
175
|
+
*
|
|
176
|
+
* `tab` binds it to one tab id, and whether to use it is the one real
|
|
177
|
+
* judgement call here.
|
|
178
|
+
*
|
|
179
|
+
* It costs a round trip. The tab mints its own id -- PROTOCOL.md requires
|
|
180
|
+
* that, so a reconnect resumes identity -- which means the backend cannot
|
|
181
|
+
* know the id at page-render time. Binding turns one template variable into
|
|
182
|
+
* "the page asks the backend for a token AFTER the JS has picked an id", and
|
|
183
|
+
* re-asks on every reconnect that changes it.
|
|
184
|
+
*
|
|
185
|
+
* IT IS NOT STRICTLY SAFER, and the asymmetry is worth understanding before
|
|
186
|
+
* choosing. Both cases assume a stolen token, which is the only case either
|
|
187
|
+
* addresses.
|
|
188
|
+
*
|
|
189
|
+
* Unbound: the thief cannot read or drive the victim's tabs. They can
|
|
190
|
+
* register a tab THEY control under the victim's principal. It runs in their
|
|
191
|
+
* browser, where their own session is what the app checks, so they gain no
|
|
192
|
+
* authority -- but the victim's agent now sees a tab that is not the
|
|
193
|
+
* victim's and may drive it, typing the victim's data onto the attacker's
|
|
194
|
+
* screen. An extra tab; the real ones untouched.
|
|
195
|
+
*
|
|
196
|
+
* Bound to tab T: the thief cannot do that. What they can do is open a stream
|
|
197
|
+
* for T -- and a second stream for a known (principal, tab) is a RECONNECT,
|
|
198
|
+
* which supersedes the first. The victim's own page is hung up on and the
|
|
199
|
+
* thief's becomes that tab, until the victim's `EventSource` reconnects and
|
|
200
|
+
* supersedes back. That is a takeover of the exact tab the agent is already
|
|
201
|
+
* driving, which is worse than an extra tab in the list.
|
|
202
|
+
*
|
|
203
|
+
* What bounds both is the token not leaking: deliver it in a `__Host-`
|
|
204
|
+
* cookie rather than a query parameter, and keep the lifetime short.
|
|
205
|
+
*
|
|
206
|
+
* A credential for an AGENT should be bound whenever the agent drives one
|
|
207
|
+
* known tab. There it is free -- the agent has the tab id already -- and the
|
|
208
|
+
* supersede hazard does not apply, because an agent never opens a tab stream.
|
|
209
|
+
*/
|
|
210
|
+
mint(principal, options = {}) {
|
|
211
|
+
if (!principal)
|
|
212
|
+
throw new Error("driverkit: a token needs a principal");
|
|
213
|
+
if (principal.startsWith(ANON_ID_PREFIX)) {
|
|
214
|
+
// Otherwise a backend bug could mint a signed token claiming an anonymous
|
|
215
|
+
// principal, and the two kinds would stop being distinguishable -- which
|
|
216
|
+
// is the one thing `Principal.anonymous` is for.
|
|
217
|
+
throw new Error(`driverkit: "${ANON_ID_PREFIX}" is reserved for anonymous visitors`);
|
|
218
|
+
}
|
|
219
|
+
const issued = options.now ?? Date.now();
|
|
220
|
+
const life = options.ttlMs ?? this.ttlMs;
|
|
221
|
+
const claims = {
|
|
222
|
+
aud: this.audience,
|
|
223
|
+
exp: Math.floor((issued + life) / 1000),
|
|
224
|
+
iat: Math.floor(issued / 1000),
|
|
225
|
+
kid: this.activeKid,
|
|
226
|
+
sub: principal,
|
|
227
|
+
...(options.tab ? { tab: options.tab } : {}),
|
|
228
|
+
};
|
|
229
|
+
// Sorted keys, so the same claims are the same bytes in both languages.
|
|
230
|
+
const ordered = {};
|
|
231
|
+
for (const key of Object.keys(claims).sort())
|
|
232
|
+
ordered[key] = claims[key];
|
|
233
|
+
const body = b64u(Buffer.from(JSON.stringify(ordered), "utf8"));
|
|
234
|
+
return `${TOKEN_PREFIX}.${body}.${b64u(this.#mac(this.activeKid, body))}`;
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* The principal a credential proves, or `AuthError`.
|
|
238
|
+
*
|
|
239
|
+
* Anonymous first, because it needs no key and cannot be confused with a
|
|
240
|
+
* token: the prefixes are disjoint and both are checked exactly.
|
|
241
|
+
*/
|
|
242
|
+
principal(credential, now = Date.now()) {
|
|
243
|
+
const text = (credential ?? "").trim();
|
|
244
|
+
if (!text)
|
|
245
|
+
throw new AuthError("empty credential");
|
|
246
|
+
if (text.startsWith(`${ANON_PREFIX}.`)) {
|
|
247
|
+
if (!this.anonymous)
|
|
248
|
+
throw new AuthError("anonymous credentials are not accepted");
|
|
249
|
+
const secret = text.slice(ANON_PREFIX.length + 1);
|
|
250
|
+
// 32 base64url characters is 24 bytes. A short anonymous secret is a
|
|
251
|
+
// guessable principal, and a guessable anonymous principal is the shared
|
|
252
|
+
// bucket this design exists to avoid.
|
|
253
|
+
if (secret.length < 32)
|
|
254
|
+
throw new AuthError("an anonymous secret is too short");
|
|
255
|
+
return { id: anonPrincipalId(text), anonymous: true };
|
|
256
|
+
}
|
|
257
|
+
const parts = text.split(".");
|
|
258
|
+
if (parts.length !== 3 || parts[0] !== TOKEN_PREFIX)
|
|
259
|
+
throw new AuthError("not a dkt1 token");
|
|
260
|
+
const body = parts[1];
|
|
261
|
+
const claims = parseJson(b64uDecode(body));
|
|
262
|
+
if (typeof claims !== "object" || claims === null || Array.isArray(claims)) {
|
|
263
|
+
throw new AuthError("the payload is not a JSON object");
|
|
264
|
+
}
|
|
265
|
+
const c = claims;
|
|
266
|
+
const kid = c["kid"];
|
|
267
|
+
// Refused, never retried against the other keys. "Try them all" turns a
|
|
268
|
+
// rotation window into a period where every key is live for every token,
|
|
269
|
+
// which is the opposite of what rotating is for.
|
|
270
|
+
if (typeof kid !== "string" || !this.#keys.has(kid))
|
|
271
|
+
throw new AuthError("unknown key id");
|
|
272
|
+
const want = this.#mac(kid, body);
|
|
273
|
+
const got = b64uDecode(parts[2]);
|
|
274
|
+
// `timingSafeEqual` THROWS on unequal lengths rather than returning false,
|
|
275
|
+
// which would turn a truncated signature into a 500 instead of a refusal.
|
|
276
|
+
if (want.length !== got.length || !timingSafeEqual(want, got)) {
|
|
277
|
+
throw new AuthError("the signature does not verify");
|
|
278
|
+
}
|
|
279
|
+
// Everything below reads an AUTHENTICATED payload. The order matters:
|
|
280
|
+
// nothing from `c` was trusted above except `kid`, which only selects the
|
|
281
|
+
// key the MAC is then checked with.
|
|
282
|
+
if (c["aud"] !== this.audience)
|
|
283
|
+
throw new AuthError("the token is for another audience");
|
|
284
|
+
const sub = c["sub"];
|
|
285
|
+
if (typeof sub !== "string" || !sub)
|
|
286
|
+
throw new AuthError("the token names no principal");
|
|
287
|
+
if (sub.startsWith(ANON_ID_PREFIX)) {
|
|
288
|
+
throw new AuthError(`a signed token may not claim an "${ANON_ID_PREFIX}" principal`);
|
|
289
|
+
}
|
|
290
|
+
const exp = c["exp"];
|
|
291
|
+
const iat = c["iat"];
|
|
292
|
+
if (typeof exp !== "number" || typeof iat !== "number") {
|
|
293
|
+
throw new AuthError("the token has no usable iat/exp");
|
|
294
|
+
}
|
|
295
|
+
if (exp * 1000 + this.skewMs < now)
|
|
296
|
+
throw new AuthError("the token has expired");
|
|
297
|
+
// A token from the future is not evidence. Accepting it would let a minter
|
|
298
|
+
// with a wrong clock issue credentials that outlive their stated lifetime
|
|
299
|
+
// by however far the clock is out.
|
|
300
|
+
if (iat * 1000 - this.skewMs > now)
|
|
301
|
+
throw new AuthError("the token was issued in the future");
|
|
302
|
+
const tab = c["tab"];
|
|
303
|
+
if (tab !== undefined && (typeof tab !== "string" || !tab)) {
|
|
304
|
+
throw new AuthError("the tab claim is not a tab id");
|
|
305
|
+
}
|
|
306
|
+
if (this.requireTabBinding && !tab)
|
|
307
|
+
throw new AuthError("a tab-bound token is required");
|
|
308
|
+
return { id: sub, ...(tab ? { tab } : {}) };
|
|
309
|
+
}
|
|
310
|
+
#mac(kid, body) {
|
|
311
|
+
// The prefix is inside the MAC, so a `dkt2` with a different meaning cannot
|
|
312
|
+
// be produced by relabelling a `dkt1` payload.
|
|
313
|
+
return createHmac("sha256", this.#keys.get(kid)).update(`${TOKEN_PREFIX}.${body}`, "utf8").digest();
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
function b64u(raw) {
|
|
317
|
+
return raw.toString("base64url");
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Unpadded base64url, with anything undecodable raised as an `AuthError`.
|
|
321
|
+
*
|
|
322
|
+
* Node's `base64url` decoder is lenient and never throws, so the round trip is
|
|
323
|
+
* what rejects: a payload that merely LOOKS like base64 would otherwise become
|
|
324
|
+
* a mojibake principal id rather than a refusal.
|
|
325
|
+
*/
|
|
326
|
+
function b64uDecode(text) {
|
|
327
|
+
const raw = Buffer.from(text, "base64url");
|
|
328
|
+
if (raw.length === 0 && text.length > 0)
|
|
329
|
+
throw new AuthError("not base64url");
|
|
330
|
+
return raw;
|
|
331
|
+
}
|
|
332
|
+
function parseJson(raw) {
|
|
333
|
+
try {
|
|
334
|
+
return JSON.parse(raw.toString("utf8"));
|
|
335
|
+
}
|
|
336
|
+
catch {
|
|
337
|
+
throw new AuthError("the payload is not JSON");
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* The caller's credential, from the four places it can arrive.
|
|
342
|
+
*
|
|
343
|
+
* In order, and the order is the order of preference:
|
|
344
|
+
*
|
|
345
|
+
* 1. `Authorization: Bearer` -- what an agent, an MCP server or any HTTP
|
|
346
|
+
* client should use. Standard, and not logged by anything by default.
|
|
347
|
+
* 2. `X-DK-Token` -- for a client whose `Authorization` is already spoken for
|
|
348
|
+
* by the app the relay is embedded in.
|
|
349
|
+
* 3. The `dk_token` cookie (`__Host-` prefixed or not) -- the one that works
|
|
350
|
+
* for `EventSource`, which cannot set a header at all. In the deployment
|
|
351
|
+
* PROTOCOL.md recommends, where the relay is same-origin with the app, this
|
|
352
|
+
* is the best option a page has: the app sets the cookie and the browser
|
|
353
|
+
* attaches it to the stream request with no token anywhere in a URL.
|
|
354
|
+
* 4. `?dk_token=` -- the last resort, for a cross-origin `EventSource` where
|
|
355
|
+
* no cookie will be sent. A QUERY PARAMETER ENDS UP IN EVERY REVERSE
|
|
356
|
+
* PROXY'S ACCESS LOG, which is the one place a token must not be. It is
|
|
357
|
+
* accepted because refusing it would mean cross-origin pages could not
|
|
358
|
+
* connect at all, and it is last and documented as a liability. Short token
|
|
359
|
+
* lifetimes are what make a logged one survivable.
|
|
360
|
+
*/
|
|
361
|
+
export function credentialFrom(headers, query) {
|
|
362
|
+
const raw = one(headers["authorization"]);
|
|
363
|
+
if (raw && raw.slice(0, 7).toLowerCase() === "bearer ")
|
|
364
|
+
return raw.slice(7).trim() || undefined;
|
|
365
|
+
const direct = one(headers["x-dk-token"])?.trim();
|
|
366
|
+
if (direct)
|
|
367
|
+
return direct;
|
|
368
|
+
// Node joins a repeated `Cookie` with "; " already, but HTTP/2 splits it and
|
|
369
|
+
// some proxies pass an array through, so both shapes are handled: keeping
|
|
370
|
+
// only the first copy would silently drop the credential in a jar with
|
|
371
|
+
// several entries.
|
|
372
|
+
const jar = headers["cookie"];
|
|
373
|
+
const cookie = Array.isArray(jar) ? jar.join("; ") : jar;
|
|
374
|
+
if (cookie) {
|
|
375
|
+
for (const part of cookie.split(";")) {
|
|
376
|
+
const at = part.indexOf("=");
|
|
377
|
+
if (at === -1)
|
|
378
|
+
continue;
|
|
379
|
+
const name = part.slice(0, at).trim();
|
|
380
|
+
const value = part.slice(at + 1).trim();
|
|
381
|
+
if ((name === "dk_token" || name === "__Host-dk_token") && value) {
|
|
382
|
+
return decodeURIComponent(value);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
return query.get("dk_token") || undefined;
|
|
387
|
+
}
|
|
388
|
+
function one(value) {
|
|
389
|
+
return Array.isArray(value) ? value[0] : value;
|
|
390
|
+
}
|
|
391
|
+
//# sourceMappingURL=auth.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../src/relay/auth.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AAEH,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEnF,gDAAgD;AAChD,MAAM,CAAC,MAAM,YAAY,GAAG,MAAM,CAAC;AACnC,yCAAyC;AACzC,MAAM,CAAC,MAAM,WAAW,GAAG,OAAO,CAAC;AACnC,kDA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AAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;YACtC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;YACxC,IAAI,CAAC,IAAI,KAAK,UAAU,IAAI,IAAI,KAAK,iBAAiB,CAAC,IAAI,KAAK,EAAE,CAAC;gBACjE,OAAO,kBAAkB,CAAC,KAAK,CAAC,CAAC;YACnC,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,SAAS,CAAC;AAC5C,CAAC;AAED,SAAS,GAAG,CAAC,KAAoC;IAC/C,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;AACjD,CAAC","sourcesContent":["/**\n * driverkit/relay — who the caller is, and nothing more than that.\n *\n * A port of `python/src/driverkit/auth.py`, claim for claim and refusal for\n * refusal. The long-form argument lives in that file's docstring and in\n * PROTOCOL.md's \"Who is allowed to do this\"; what follows here is the summary\n * and the places this half could plausibly drift.\n *\n * This module answers one question: WHICH PERSON is on the other end of this\n * request? It never answers \"may they do this\", because PROTOCOL.md's core\n * property is untouched by any of it:\n *\n * THE RELAY GRANTS NO AUTHORITY. It forwards a verb to a tab that is already\n * logged in as a person, and that tab's own session is what the app checks.\n *\n * A credential here buys its holder nothing they could not already do in their\n * own browser. What it buys the RELAY is the ability to keep a hundred people's\n * tabs apart. Isolation, not authorisation.\n *\n * The token:\n *\n * dkt1.<base64url(payload JSON)>.<base64url(HMAC-SHA256(key, \"dkt1.\" + payload))>\n *\n * The algorithm is in the PREFIX, not in the payload, which is the deliberate\n * departure from JWT: a JWT names its own algorithm in a header the verifier\n * has not authenticated yet, and that is the root of both the `alg: none`\n * family of bugs and the HMAC/RSA confusion family. Here there is nothing to\n * negotiate. A future `dkt2` is a new prefix -- a greppable change rather than\n * a field an attacker can set.\n *\n * Claims: `sub` (the principal), `aud` (which relay this is for), `iat`/`exp`\n * (Unix seconds, honoured with `DEFAULT_SKEW_S` of slack), `kid` (which key\n * signed it; read before verification, used only to SELECT the key, so an\n * attacker who edits it fails the MAC), and an optional `tab` binding the\n * credential to one tab id.\n *\n * Anonymous: `anon1.<base64url(32 random bytes)>`, minted by the page, keyless\n * in the relay, resolving to `anon:<sha256(\"driverkit-anon-v1.\" + secret)[:16]>`.\n * Independent per visitor -- \"anonymous\" is never one bucket. It is a bearer\n * capability and not an identity, it dies with the tab, and it confers nothing\n * at the app.\n *\n * Zero dependencies: `node:crypto` only.\n */\n\nimport { createHash, createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\n\n/** The version prefix that IS the algorithm. */\nexport const TOKEN_PREFIX = \"dkt1\";\n/** The anonymous credential's prefix. */\nexport const ANON_PREFIX = \"anon1\";\n/** What an anonymous principal id starts with. */\nexport const ANON_ID_PREFIX = \"anon:\";\n/**\n * The principal every request resolves to when auth is off.\n *\n * One principal means the scoping in `relay.ts` is a no-op and the\n * unconfigured loopback relay a single developer runs is byte-for-byte what it\n * was before any of this existed.\n */\nexport const LOCAL_PRINCIPAL = \"local\";\n\n/**\n * Shortest key accepted. A 16-character shared secret makes the HMAC theatre,\n * and the moment to say so is at construction rather than in a post-mortem.\n */\nexport const MIN_SECRET_BYTES = 32;\n\n/**\n * How long a freshly minted token lasts, in ms.\n *\n * Short, because a short lifetime is what substitutes for the revocation a\n * stateless token cannot have. The page asks for a new one on every reconnect,\n * so this does not need to cover a session.\n */\nexport const DEFAULT_TTL_MS = 120_000;\n\n/**\n * Clock slack on `exp`, and the window by which an `iat` may lead now.\n *\n * Sixty seconds, not five minutes. Skew tolerance is a direct extension of\n * every token's lifetime, so a five-minute window on a two-minute token would\n * more than treble the time a leaked one stays useful. Sixty covers two hosts\n * with working NTP, which is the case this is for; a fleet whose clocks are\n * minutes apart has a problem a wider window hides rather than solves.\n */\nexport const DEFAULT_SKEW_MS = 60_000;\n\nconst ANON_DOMAIN = \"driverkit-anon-v1.\";\n\n/**\n * A credential did not check out.\n *\n * Deliberately carries no machine-readable reason. The relay answers every\n * instance with one slug -- `bad-credential` -- because the distinctions a\n * caller might want are exactly the distinctions an attacker wants: \"the\n * signature verified but the audience was wrong\" tells a forger the forgery\n * worked. A legitimate client's move is the same in every case (mint a fresh\n * token, retry once), so the split buys it nothing.\n */\nexport class AuthError extends Error {\n override readonly name = \"AuthError\";\n}\n\n/**\n * Who a request is from.\n *\n * `id` is the registry key half that makes isolation structural: a tab is\n * stored under `(principal, tab id)`, so one principal cannot reach another's\n * tab by any code path, including one somebody adds later and forgets to\n * guard.\n *\n * `tab` is the optional binding from the credential. When it is set the caller\n * may address that tab and no other.\n */\nexport interface Principal {\n readonly id: string;\n readonly tab?: string;\n readonly anonymous?: boolean;\n}\n\nexport interface TabAuthOptions {\n /**\n * Which relay these tokens are for. No default: a default audience is an\n * audience nobody chose, and two relays that both accept \"driverkit\" are one\n * relay as far as a stolen token is concerned.\n */\n audience: string;\n /** Key id to secret. Rotation is additive; see `TabAuth`. */\n keys?: Record<string, string | Buffer>;\n /** Sugar for the single-key case. Mutually exclusive with `keys`. */\n secret?: string | Buffer;\n /** Which key `mint` signs with. Defaults to the first in `keys`. */\n activeKid?: string;\n ttlMs?: number;\n skewMs?: number;\n /**\n * Accept `anon1.` credentials. On by default so an unauthenticated visitor\n * is not an error; turn it off in an app where every user is logged in,\n * because an anonymous credential there can only be somebody probing.\n */\n anonymous?: boolean;\n /** Refuse any `dkt1` token without a `tab` claim. See `mint`. */\n requireTabBinding?: boolean;\n}\n\n/** The principal id an `anon1.` credential resolves to. Pure and keyless. */\nexport function anonPrincipalId(credential: string): string {\n const dot = credential.indexOf(\".\");\n const secret = dot === -1 ? \"\" : credential.slice(dot + 1);\n const digest = createHash(\"sha256\").update(ANON_DOMAIN + secret, \"utf8\").digest();\n return ANON_ID_PREFIX + digest.subarray(0, 16).toString(\"hex\");\n}\n\n/**\n * A fresh anonymous credential. For a page, or a test; never the relay.\n *\n * 256 bits, because this string is the whole of an anonymous visitor's\n * isolation: anybody who can guess it is that visitor.\n */\nexport function mintAnonCredential(): string {\n return `${ANON_PREFIX}.${b64u(randomBytes(32))}`;\n}\n\n/**\n * Verification, and the minter the app's backend uses.\n *\n * The app's backend is the only thing that knows who a browser is, so it is\n * the only thing that may mint. Give it the same `keys` and `audience` the\n * relay has and it needs nothing else -- no relay client, no callback, no\n * shared database.\n *\n * Rotation is additive and ordered:\n *\n * 1. Add the new key to the RELAY's `keys`. Deploy. It accepts both; nothing\n * mints with the new one yet.\n * 2. Point the minter at it (`activeKid`). Deploy.\n * 3. After `ttlMs + skewMs`, drop the old key from the relay.\n *\n * The order is the whole of it. A key the relay does not know yet refuses\n * every token signed with it, and a key dropped before the last token signed\n * with it expires logs a hundred people out at once.\n */\nexport class TabAuth {\n readonly audience: string;\n readonly ttlMs: number;\n readonly skewMs: number;\n readonly anonymous: boolean;\n readonly requireTabBinding: boolean;\n readonly activeKid: string;\n readonly #keys = new Map<string, Buffer>();\n\n constructor(options: TabAuthOptions) {\n const { audience, keys, secret } = options;\n if (keys && secret !== undefined) throw new Error(\"driverkit: pass keys or secret, not both\");\n // Sugar for the single-key case, which is every deployment until the first\n // rotation. It still gets a kid, so a single-key relay's tokens are shaped\n // exactly like a rotating one's and rotation needs no format change.\n const table = keys ?? (secret === undefined ? undefined : { k1: secret });\n if (!table || Object.keys(table).length === 0) {\n throw new Error(\"driverkit: TabAuth needs keys or secret\");\n }\n if (!audience) throw new Error(\"driverkit: TabAuth needs an audience naming this relay\");\n\n for (const [kid, value] of Object.entries(table)) {\n const raw = typeof value === \"string\" ? Buffer.from(value, \"utf8\") : Buffer.from(value);\n if (raw.length < MIN_SECRET_BYTES) {\n throw new Error(\n `driverkit: key \"${kid}\" is ${raw.length} bytes; at least ${MIN_SECRET_BYTES} are ` +\n `needed. \\`node -e \"console.log(require('node:crypto').randomBytes(32).toString('hex'))\"\\``,\n );\n }\n if (!kid || kid.includes(\".\")) throw new Error(`driverkit: \"${kid}\" is not a usable key id`);\n this.#keys.set(kid, raw);\n }\n\n this.audience = audience;\n this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;\n this.skewMs = options.skewMs ?? DEFAULT_SKEW_MS;\n this.anonymous = options.anonymous ?? true;\n this.requireTabBinding = options.requireTabBinding ?? false;\n this.activeKid = options.activeKid ?? this.#keys.keys().next().value!;\n if (!this.#keys.has(this.activeKid)) {\n throw new Error(`driverkit: activeKid \"${this.activeKid}\" is not in keys`);\n }\n }\n\n /**\n * A token saying `principal` is who the bearer is.\n *\n * `tab` binds it to one tab id, and whether to use it is the one real\n * judgement call here.\n *\n * It costs a round trip. The tab mints its own id -- PROTOCOL.md requires\n * that, so a reconnect resumes identity -- which means the backend cannot\n * know the id at page-render time. Binding turns one template variable into\n * \"the page asks the backend for a token AFTER the JS has picked an id\", and\n * re-asks on every reconnect that changes it.\n *\n * IT IS NOT STRICTLY SAFER, and the asymmetry is worth understanding before\n * choosing. Both cases assume a stolen token, which is the only case either\n * addresses.\n *\n * Unbound: the thief cannot read or drive the victim's tabs. They can\n * register a tab THEY control under the victim's principal. It runs in their\n * browser, where their own session is what the app checks, so they gain no\n * authority -- but the victim's agent now sees a tab that is not the\n * victim's and may drive it, typing the victim's data onto the attacker's\n * screen. An extra tab; the real ones untouched.\n *\n * Bound to tab T: the thief cannot do that. What they can do is open a stream\n * for T -- and a second stream for a known (principal, tab) is a RECONNECT,\n * which supersedes the first. The victim's own page is hung up on and the\n * thief's becomes that tab, until the victim's `EventSource` reconnects and\n * supersedes back. That is a takeover of the exact tab the agent is already\n * driving, which is worse than an extra tab in the list.\n *\n * What bounds both is the token not leaking: deliver it in a `__Host-`\n * cookie rather than a query parameter, and keep the lifetime short.\n *\n * A credential for an AGENT should be bound whenever the agent drives one\n * known tab. There it is free -- the agent has the tab id already -- and the\n * supersede hazard does not apply, because an agent never opens a tab stream.\n */\n mint(principal: string, options: { tab?: string; ttlMs?: number; now?: number } = {}): string {\n if (!principal) throw new Error(\"driverkit: a token needs a principal\");\n if (principal.startsWith(ANON_ID_PREFIX)) {\n // Otherwise a backend bug could mint a signed token claiming an anonymous\n // principal, and the two kinds would stop being distinguishable -- which\n // is the one thing `Principal.anonymous` is for.\n throw new Error(`driverkit: \"${ANON_ID_PREFIX}\" is reserved for anonymous visitors`);\n }\n const issued = options.now ?? Date.now();\n const life = options.ttlMs ?? this.ttlMs;\n const claims: Record<string, string | number> = {\n aud: this.audience,\n exp: Math.floor((issued + life) / 1000),\n iat: Math.floor(issued / 1000),\n kid: this.activeKid,\n sub: principal,\n ...(options.tab ? { tab: options.tab } : {}),\n };\n // Sorted keys, so the same claims are the same bytes in both languages.\n const ordered: Record<string, string | number> = {};\n for (const key of Object.keys(claims).sort()) ordered[key] = claims[key]!;\n const body = b64u(Buffer.from(JSON.stringify(ordered), \"utf8\"));\n return `${TOKEN_PREFIX}.${body}.${b64u(this.#mac(this.activeKid, body))}`;\n }\n\n /**\n * The principal a credential proves, or `AuthError`.\n *\n * Anonymous first, because it needs no key and cannot be confused with a\n * token: the prefixes are disjoint and both are checked exactly.\n */\n principal(credential: string, now = Date.now()): Principal {\n const text = (credential ?? \"\").trim();\n if (!text) throw new AuthError(\"empty credential\");\n\n if (text.startsWith(`${ANON_PREFIX}.`)) {\n if (!this.anonymous) throw new AuthError(\"anonymous credentials are not accepted\");\n const secret = text.slice(ANON_PREFIX.length + 1);\n // 32 base64url characters is 24 bytes. A short anonymous secret is a\n // guessable principal, and a guessable anonymous principal is the shared\n // bucket this design exists to avoid.\n if (secret.length < 32) throw new AuthError(\"an anonymous secret is too short\");\n return { id: anonPrincipalId(text), anonymous: true };\n }\n\n const parts = text.split(\".\");\n if (parts.length !== 3 || parts[0] !== TOKEN_PREFIX) throw new AuthError(\"not a dkt1 token\");\n const body = parts[1]!;\n const claims = parseJson(b64uDecode(body));\n if (typeof claims !== \"object\" || claims === null || Array.isArray(claims)) {\n throw new AuthError(\"the payload is not a JSON object\");\n }\n const c = claims as Record<string, unknown>;\n\n const kid = c[\"kid\"];\n // Refused, never retried against the other keys. \"Try them all\" turns a\n // rotation window into a period where every key is live for every token,\n // which is the opposite of what rotating is for.\n if (typeof kid !== \"string\" || !this.#keys.has(kid)) throw new AuthError(\"unknown key id\");\n\n const want = this.#mac(kid, body);\n const got = b64uDecode(parts[2]!);\n // `timingSafeEqual` THROWS on unequal lengths rather than returning false,\n // which would turn a truncated signature into a 500 instead of a refusal.\n if (want.length !== got.length || !timingSafeEqual(want, got)) {\n throw new AuthError(\"the signature does not verify\");\n }\n\n // Everything below reads an AUTHENTICATED payload. The order matters:\n // nothing from `c` was trusted above except `kid`, which only selects the\n // key the MAC is then checked with.\n if (c[\"aud\"] !== this.audience) throw new AuthError(\"the token is for another audience\");\n\n const sub = c[\"sub\"];\n if (typeof sub !== \"string\" || !sub) throw new AuthError(\"the token names no principal\");\n if (sub.startsWith(ANON_ID_PREFIX)) {\n throw new AuthError(`a signed token may not claim an \"${ANON_ID_PREFIX}\" principal`);\n }\n\n const exp = c[\"exp\"];\n const iat = c[\"iat\"];\n if (typeof exp !== \"number\" || typeof iat !== \"number\") {\n throw new AuthError(\"the token has no usable iat/exp\");\n }\n if (exp * 1000 + this.skewMs < now) throw new AuthError(\"the token has expired\");\n // A token from the future is not evidence. Accepting it would let a minter\n // with a wrong clock issue credentials that outlive their stated lifetime\n // by however far the clock is out.\n if (iat * 1000 - this.skewMs > now) throw new AuthError(\"the token was issued in the future\");\n\n const tab = c[\"tab\"];\n if (tab !== undefined && (typeof tab !== \"string\" || !tab)) {\n throw new AuthError(\"the tab claim is not a tab id\");\n }\n if (this.requireTabBinding && !tab) throw new AuthError(\"a tab-bound token is required\");\n\n return { id: sub, ...(tab ? { tab } : {}) };\n }\n\n #mac(kid: string, body: string): Buffer {\n // The prefix is inside the MAC, so a `dkt2` with a different meaning cannot\n // be produced by relabelling a `dkt1` payload.\n return createHmac(\"sha256\", this.#keys.get(kid)!).update(`${TOKEN_PREFIX}.${body}`, \"utf8\").digest();\n }\n}\n\nfunction b64u(raw: Buffer): string {\n return raw.toString(\"base64url\");\n}\n\n/**\n * Unpadded base64url, with anything undecodable raised as an `AuthError`.\n *\n * Node's `base64url` decoder is lenient and never throws, so the round trip is\n * what rejects: a payload that merely LOOKS like base64 would otherwise become\n * a mojibake principal id rather than a refusal.\n */\nfunction b64uDecode(text: string): Buffer {\n const raw = Buffer.from(text, \"base64url\");\n if (raw.length === 0 && text.length > 0) throw new AuthError(\"not base64url\");\n return raw;\n}\n\nfunction parseJson(raw: Buffer): unknown {\n try {\n return JSON.parse(raw.toString(\"utf8\"));\n } catch {\n throw new AuthError(\"the payload is not JSON\");\n }\n}\n\n/**\n * The caller's credential, from the four places it can arrive.\n *\n * In order, and the order is the order of preference:\n *\n * 1. `Authorization: Bearer` -- what an agent, an MCP server or any HTTP\n * client should use. Standard, and not logged by anything by default.\n * 2. `X-DK-Token` -- for a client whose `Authorization` is already spoken for\n * by the app the relay is embedded in.\n * 3. The `dk_token` cookie (`__Host-` prefixed or not) -- the one that works\n * for `EventSource`, which cannot set a header at all. In the deployment\n * PROTOCOL.md recommends, where the relay is same-origin with the app, this\n * is the best option a page has: the app sets the cookie and the browser\n * attaches it to the stream request with no token anywhere in a URL.\n * 4. `?dk_token=` -- the last resort, for a cross-origin `EventSource` where\n * no cookie will be sent. A QUERY PARAMETER ENDS UP IN EVERY REVERSE\n * PROXY'S ACCESS LOG, which is the one place a token must not be. It is\n * accepted because refusing it would mean cross-origin pages could not\n * connect at all, and it is last and documented as a liability. Short token\n * lifetimes are what make a logged one survivable.\n */\nexport function credentialFrom(\n headers: Record<string, string | string[] | undefined>,\n query: URLSearchParams,\n): string | undefined {\n const raw = one(headers[\"authorization\"]);\n if (raw && raw.slice(0, 7).toLowerCase() === \"bearer \") return raw.slice(7).trim() || undefined;\n\n const direct = one(headers[\"x-dk-token\"])?.trim();\n if (direct) return direct;\n\n // Node joins a repeated `Cookie` with \"; \" already, but HTTP/2 splits it and\n // some proxies pass an array through, so both shapes are handled: keeping\n // only the first copy would silently drop the credential in a jar with\n // several entries.\n const jar = headers[\"cookie\"];\n const cookie = Array.isArray(jar) ? jar.join(\"; \") : jar;\n if (cookie) {\n for (const part of cookie.split(\";\")) {\n const at = part.indexOf(\"=\");\n if (at === -1) continue;\n const name = part.slice(0, at).trim();\n const value = part.slice(at + 1).trim();\n if ((name === \"dk_token\" || name === \"__Host-dk_token\") && value) {\n return decodeURIComponent(value);\n }\n }\n }\n\n return query.get(\"dk_token\") || undefined;\n}\n\nfunction one(value: string | string[] | undefined): string | undefined {\n return Array.isArray(value) ? value[0] : value;\n}\n"]}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The wire frames, as PROTOCOL.md defines them.
|
|
3
|
+
*
|
|
4
|
+
* These are declared here and again in `driverkit/browser` rather than shared
|
|
5
|
+
* from one module, and that duplication is deliberate. PROTOCOL.md is the
|
|
6
|
+
* contract; a shared TypeScript type is not. The whole point of writing the
|
|
7
|
+
* protocol down was that the relay can be written in any language and the page side can
|
|
8
|
+
* be a hand-written `fetch` loop, so neither side may acquire a compile-time
|
|
9
|
+
* dependency on the other's source. Two small copies that must agree with a
|
|
10
|
+
* document beat one copy that quietly becomes the real specification.
|
|
11
|
+
*
|
|
12
|
+
* `Snapshot`, `Manifest` and `Result` DO come from core, by relative path.
|
|
13
|
+
* Those are the payload types an app author already imports, and inventing a
|
|
14
|
+
* second definition of `Result` is how the relay would start disagreeing with
|
|
15
|
+
* the driver about what an answer looks like. The path is relative because
|
|
16
|
+
* driverkit has no node_modules: with zero dependencies there is no package
|
|
17
|
+
* resolution to hang a bare specifier on.
|
|
18
|
+
*/
|
|
19
|
+
import type { Manifest, RelayRefusal, Result, Scalar, Snapshot, TabFocus, WireResult } from "../core/index.ts";
|
|
20
|
+
export type { Manifest, RelayRefusal, Result, Scalar, Snapshot, TabFocus, WireResult };
|
|
21
|
+
/** Tab → relay, once, immediately on connecting. */
|
|
22
|
+
export interface HelloFrame {
|
|
23
|
+
t: "hello";
|
|
24
|
+
tab: string;
|
|
25
|
+
app?: string;
|
|
26
|
+
manifest?: Manifest;
|
|
27
|
+
snapshot?: Snapshot;
|
|
28
|
+
/** Only so a human can tell two tabs apart when asked "which one?". */
|
|
29
|
+
title?: string;
|
|
30
|
+
url?: string;
|
|
31
|
+
/** Where this tab stands in the person's attention; see `TabFocus`. In
|
|
32
|
+
* `hello` as well as in `snapshot` because `hello` is the only frame a tab
|
|
33
|
+
* that is opened and left alone ever sends. */
|
|
34
|
+
focus?: TabFocus;
|
|
35
|
+
}
|
|
36
|
+
/** Tab → relay, the answer to exactly one `call`. */
|
|
37
|
+
export interface ResultFrame {
|
|
38
|
+
t: "result";
|
|
39
|
+
/** Echoed from the `call` frame. This is the only correlation there is. */
|
|
40
|
+
id: string;
|
|
41
|
+
result: Result;
|
|
42
|
+
/**
|
|
43
|
+
* How long the TAB's own work took, in whole milliseconds, with any person's
|
|
44
|
+
* time already taken out of it. Absent means the tab did not measure, which
|
|
45
|
+
* is UNKNOWN and not zero; see PROTOCOL.md.
|
|
46
|
+
*
|
|
47
|
+
* On the frame and NOT inside `result`, which is the one placement decision
|
|
48
|
+
* here that matters. `result` is what the APP returned, so a duration in
|
|
49
|
+
* there would be an app's claim about its own speed; this is the measurement
|
|
50
|
+
* the page-side harness takes around the single call it makes into the
|
|
51
|
+
* driver, which is the same bracket `drive` puts around `driver.call()` and
|
|
52
|
+
* is the only reason either number means anything. See `renderDuration`.
|
|
53
|
+
*/
|
|
54
|
+
tookMs?: number;
|
|
55
|
+
/** How much of the wall clock was a PERSON, as the amount already subtracted
|
|
56
|
+
* from `tookMs`. Here so the gap between an agent's round trip and `tookMs`
|
|
57
|
+
* is accounted for rather than guessed at; never added back by a client.
|
|
58
|
+
* See `DriveOptions.waited`, which is the same quantity in the in-page loop. */
|
|
59
|
+
waitedMs?: number;
|
|
60
|
+
/** Not in PROTOCOL.md's frame listing; see the note in `relay.ts` about how
|
|
61
|
+
* the relay learns which tab a POST came from. */
|
|
62
|
+
tab?: string;
|
|
63
|
+
}
|
|
64
|
+
/** Tab → relay, the page moved on its own because a person clicked something. */
|
|
65
|
+
export interface SnapshotFrame {
|
|
66
|
+
t: "snapshot";
|
|
67
|
+
snapshot: Snapshot;
|
|
68
|
+
tab?: string;
|
|
69
|
+
/**
|
|
70
|
+
* The tab's url as it is NOW.
|
|
71
|
+
*
|
|
72
|
+
* Here as well as in `hello` because `hello` is sent once per stream and a
|
|
73
|
+
* single-page app navigates without reconnecting -- so `TabInfo.url`, which
|
|
74
|
+
* came from `hello` alone, was stale from the first client-side route change
|
|
75
|
+
* and had no way back. A push is already going out whenever the page moves.
|
|
76
|
+
*/
|
|
77
|
+
url?: string;
|
|
78
|
+
/** The tab's focus as it is NOW. A change of focus is pushed on this frame
|
|
79
|
+
* rather than on a frame of its own: the protocol gains a field, and a relay
|
|
80
|
+
* written before it goes on reading the frame it always read. */
|
|
81
|
+
focus?: TabFocus;
|
|
82
|
+
}
|
|
83
|
+
/** Relay → tab, run a verb. */
|
|
84
|
+
export interface CallFrame {
|
|
85
|
+
t: "call";
|
|
86
|
+
id: string;
|
|
87
|
+
name: string;
|
|
88
|
+
args?: Record<string, Scalar>;
|
|
89
|
+
/** The agent's claim about what it was looking at. Forwarded untouched: the
|
|
90
|
+
* relay has no opinion about staleness, the driver does. */
|
|
91
|
+
rev?: number;
|
|
92
|
+
/** The agent's claim about WHICH SCREEN it was looking at, checked by the
|
|
93
|
+
* driver before `rev` and refused as `wrong-screen`. Forwarded untouched for
|
|
94
|
+
* the same reason `rev` is: the relay does not know which screen a tab is
|
|
95
|
+
* on, and a relay that compared screens would be a second set of rules
|
|
96
|
+
* beside the core's. See `CallOptions.screen`. */
|
|
97
|
+
screen?: string;
|
|
98
|
+
/** The plan token the agent is presenting: the opaque string a `describe`
|
|
99
|
+
* returned in `Result.plan`, which a verb declaring `consumes: "plan"` must
|
|
100
|
+
* be called with. Forwarded untouched for the same reason `rev` and `screen`
|
|
101
|
+
* are, and with one more: the relay could not check it if it wanted to —
|
|
102
|
+
* only the core that minted it knows what it binds. See `CallOptions.plan`. */
|
|
103
|
+
plan?: string;
|
|
104
|
+
}
|
|
105
|
+
export type UpFrame = HelloFrame | ResultFrame | SnapshotFrame;
|
|
106
|
+
export type DownFrame = CallFrame;
|
|
107
|
+
/**
|
|
108
|
+
* One row of `GET /dk/tabs`, pinned by PROTOCOL.md.
|
|
109
|
+
*
|
|
110
|
+
* The id field is `tab`, spelled the same as in the `hello` frame: one name
|
|
111
|
+
* for one thing. It is not `id`, which would collide in a reader's head with
|
|
112
|
+
* the `id` on a `call` frame and the `id` on a row.
|
|
113
|
+
*/
|
|
114
|
+
export interface TabSummary {
|
|
115
|
+
tab: string;
|
|
116
|
+
app?: string;
|
|
117
|
+
title?: string;
|
|
118
|
+
url?: string;
|
|
119
|
+
/** The manifest's `version`, not the manifest. An agent caches the manifest
|
|
120
|
+
* and polls this to learn its copy went stale, which is the whole reason
|
|
121
|
+
* `Manifest.version` exists -- so it is lifted to the top level here rather
|
|
122
|
+
* than left for a client to dig out of a nested object it did not want. */
|
|
123
|
+
manifestVersion?: string;
|
|
124
|
+
/** The `rev` of the last snapshot the relay was told about. */
|
|
125
|
+
rev?: number;
|
|
126
|
+
/** Where the person's attention is, as the tab last reported it. Carried
|
|
127
|
+
* through untouched: the relay cannot see `document.hasFocus()` and has no
|
|
128
|
+
* opinion about the answer, exactly as with `rev`. */
|
|
129
|
+
focus?: TabFocus;
|
|
130
|
+
/** ISO 8601, not epoch millis. This is a value a human reads in a "which
|
|
131
|
+
* tab?" prompt, and it crosses into clients whose JSON numbers are floats. */
|
|
132
|
+
since: string;
|
|
133
|
+
}
|
|
134
|
+
/** A `snapshot` frame as `GET /dk/tabs/:tab/watch` emits it. Deliberately the
|
|
135
|
+
* same shape the tab sends up, so one parser serves both directions. */
|
|
136
|
+
export interface WatchFrame {
|
|
137
|
+
t: "snapshot";
|
|
138
|
+
tab: string;
|
|
139
|
+
snapshot: Snapshot;
|
|
140
|
+
}
|
|
141
|
+
//# sourceMappingURL=frames.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"frames.d.ts","sourceRoot":"","sources":["../../src/relay/frames.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EACV,QAAQ,EACR,YAAY,EACZ,MAAM,EACN,MAAM,EACN,QAAQ,EACR,QAAQ,EACR,UAAU,EACX,MAAM,kBAAkB,CAAC;AAE1B,YAAY,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC;AAEvF,oDAAoD;AACpD,MAAM,WAAW,UAAU;IACzB,CAAC,EAAE,OAAO,CAAC;IACX,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,uEAAuE;IACvE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;oDAEgD;IAChD,KAAK,CAAC,EAAE,QAAQ,CAAC;CAClB;AAED,qDAAqD;AACrD,MAAM,WAAW,WAAW;IAC1B,CAAC,EAAE,QAAQ,CAAC;IACZ,2EAA2E;IAC3E,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;qFAGiF;IACjF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;uDACmD;IACnD,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED,iFAAiF;AACjF,MAAM,WAAW,aAAa;IAC5B,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2
|
+
* The wire frames, as PROTOCOL.md defines them.
|
|
3
|
+
*
|
|
4
|
+
* These are declared here and again in `driverkit/browser` rather than shared
|
|
5
|
+
* from one module, and that duplication is deliberate. PROTOCOL.md is the
|
|
6
|
+
* contract; a shared TypeScript type is not. The whole point of writing the
|
|
7
|
+
* protocol down was that the relay can be written in any language and the page side can
|
|
8
|
+
* be a hand-written `fetch` loop, so neither side may acquire a compile-time
|
|
9
|
+
* dependency on the other's source. Two small copies that must agree with a
|
|
10
|
+
* document beat one copy that quietly becomes the real specification.
|
|
11
|
+
*
|
|
12
|
+
* `Snapshot`, `Manifest` and `Result` DO come from core, by relative path.
|
|
13
|
+
* Those are the payload types an app author already imports, and inventing a
|
|
14
|
+
* second definition of `Result` is how the relay would start disagreeing with
|
|
15
|
+
* the driver about what an answer looks like. The path is relative because
|
|
16
|
+
* driverkit has no node_modules: with zero dependencies there is no package
|
|
17
|
+
* resolution to hang a bare specifier on.
|
|
18
|
+
*/
|
|
19
|
+
export {};
|
|
20
|
+
//# sourceMappingURL=frames.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"frames.js","sourceRoot":"","sources":["../../src/relay/frames.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG","sourcesContent":["/**\n * The wire frames, as PROTOCOL.md defines them.\n *\n * These are declared here and again in `driverkit/browser` rather than shared\n * from one module, and that duplication is deliberate. PROTOCOL.md is the\n * contract; a shared TypeScript type is not. The whole point of writing the\n * protocol down was that the relay can be written in any language and the page side can\n * be a hand-written `fetch` loop, so neither side may acquire a compile-time\n * dependency on the other's source. Two small copies that must agree with a\n * document beat one copy that quietly becomes the real specification.\n *\n * `Snapshot`, `Manifest` and `Result` DO come from core, by relative path.\n * Those are the payload types an app author already imports, and inventing a\n * second definition of `Result` is how the relay would start disagreeing with\n * the driver about what an answer looks like. The path is relative because\n * driverkit has no node_modules: with zero dependencies there is no package\n * resolution to hang a bare specifier on.\n */\n\nimport type {\n Manifest,\n RelayRefusal,\n Result,\n Scalar,\n Snapshot,\n TabFocus,\n WireResult,\n} from \"../core/index.ts\";\n\nexport type { Manifest, RelayRefusal, Result, Scalar, Snapshot, TabFocus, WireResult };\n\n/** Tab → relay, once, immediately on connecting. */\nexport interface HelloFrame {\n t: \"hello\";\n tab: string;\n app?: string;\n manifest?: Manifest;\n snapshot?: Snapshot;\n /** Only so a human can tell two tabs apart when asked \"which one?\". */\n title?: string;\n url?: string;\n /** Where this tab stands in the person's attention; see `TabFocus`. In\n * `hello` as well as in `snapshot` because `hello` is the only frame a tab\n * that is opened and left alone ever sends. */\n focus?: TabFocus;\n}\n\n/** Tab → relay, the answer to exactly one `call`. */\nexport interface ResultFrame {\n t: \"result\";\n /** Echoed from the `call` frame. This is the only correlation there is. */\n id: string;\n result: Result;\n /**\n * How long the TAB's own work took, in whole milliseconds, with any person's\n * time already taken out of it. Absent means the tab did not measure, which\n * is UNKNOWN and not zero; see PROTOCOL.md.\n *\n * On the frame and NOT inside `result`, which is the one placement decision\n * here that matters. `result` is what the APP returned, so a duration in\n * there would be an app's claim about its own speed; this is the measurement\n * the page-side harness takes around the single call it makes into the\n * driver, which is the same bracket `drive` puts around `driver.call()` and\n * is the only reason either number means anything. See `renderDuration`.\n */\n tookMs?: number;\n /** How much of the wall clock was a PERSON, as the amount already subtracted\n * from `tookMs`. Here so the gap between an agent's round trip and `tookMs`\n * is accounted for rather than guessed at; never added back by a client.\n * See `DriveOptions.waited`, which is the same quantity in the in-page loop. */\n waitedMs?: number;\n /** Not in PROTOCOL.md's frame listing; see the note in `relay.ts` about how\n * the relay learns which tab a POST came from. */\n tab?: string;\n}\n\n/** Tab → relay, the page moved on its own because a person clicked something. */\nexport interface SnapshotFrame {\n t: \"snapshot\";\n snapshot: Snapshot;\n tab?: string;\n /**\n * The tab's url as it is NOW.\n *\n * Here as well as in `hello` because `hello` is sent once per stream and a\n * single-page app navigates without reconnecting -- so `TabInfo.url`, which\n * came from `hello` alone, was stale from the first client-side route change\n * and had no way back. A push is already going out whenever the page moves.\n */\n url?: string;\n /** The tab's focus as it is NOW. A change of focus is pushed on this frame\n * rather than on a frame of its own: the protocol gains a field, and a relay\n * written before it goes on reading the frame it always read. */\n focus?: TabFocus;\n}\n\n/** Relay → tab, run a verb. */\nexport interface CallFrame {\n t: \"call\";\n id: string;\n name: string;\n args?: Record<string, Scalar>;\n /** The agent's claim about what it was looking at. Forwarded untouched: the\n * relay has no opinion about staleness, the driver does. */\n rev?: number;\n /** The agent's claim about WHICH SCREEN it was looking at, checked by the\n * driver before `rev` and refused as `wrong-screen`. Forwarded untouched for\n * the same reason `rev` is: the relay does not know which screen a tab is\n * on, and a relay that compared screens would be a second set of rules\n * beside the core's. See `CallOptions.screen`. */\n screen?: string;\n /** The plan token the agent is presenting: the opaque string a `describe`\n * returned in `Result.plan`, which a verb declaring `consumes: \"plan\"` must\n * be called with. Forwarded untouched for the same reason `rev` and `screen`\n * are, and with one more: the relay could not check it if it wanted to —\n * only the core that minted it knows what it binds. See `CallOptions.plan`. */\n plan?: string;\n}\n\nexport type UpFrame = HelloFrame | ResultFrame | SnapshotFrame;\nexport type DownFrame = CallFrame;\n\n/**\n * One row of `GET /dk/tabs`, pinned by PROTOCOL.md.\n *\n * The id field is `tab`, spelled the same as in the `hello` frame: one name\n * for one thing. It is not `id`, which would collide in a reader's head with\n * the `id` on a `call` frame and the `id` on a row.\n */\nexport interface TabSummary {\n tab: string;\n app?: string;\n title?: string;\n url?: string;\n /** The manifest's `version`, not the manifest. An agent caches the manifest\n * and polls this to learn its copy went stale, which is the whole reason\n * `Manifest.version` exists -- so it is lifted to the top level here rather\n * than left for a client to dig out of a nested object it did not want. */\n manifestVersion?: string;\n /** The `rev` of the last snapshot the relay was told about. */\n rev?: number;\n /** Where the person's attention is, as the tab last reported it. Carried\n * through untouched: the relay cannot see `document.hasFocus()` and has no\n * opinion about the answer, exactly as with `rev`. */\n focus?: TabFocus;\n /** ISO 8601, not epoch millis. This is a value a human reads in a \"which\n * tab?\" prompt, and it crosses into clients whose JSON numbers are floats. */\n since: string;\n}\n\n/** A `snapshot` frame as `GET /dk/tabs/:tab/watch` emits it. Deliberately the\n * same shape the tab sends up, so one parser serves both directions. */\nexport interface WatchFrame {\n t: \"snapshot\";\n tab: string;\n snapshot: Snapshot;\n}\n"]}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { createRelay } from "./relay.ts";
|
|
2
|
+
export type { Relay, RelayOptions, RelayAuditEvent } from "./relay.ts";
|
|
3
|
+
export type { CallFrame, DownFrame, HelloFrame, RelayRefusal, ResultFrame, SnapshotFrame, TabFocus, TabSummary, UpFrame, WatchFrame, WireResult, } from "./frames.ts";
|
|
4
|
+
export { TabAuth, AuthError, anonPrincipalId, mintAnonCredential, credentialFrom, ANON_ID_PREFIX, ANON_PREFIX, LOCAL_PRINCIPAL, MIN_SECRET_BYTES, TOKEN_PREFIX, } from "./auth.ts";
|
|
5
|
+
export type { Principal, TabAuthOptions } from "./auth.ts";
|
|
6
|
+
export { serve } from "./serve.ts";
|
|
7
|
+
export type { ServeOptions } from "./serve.ts";
|
|
8
|
+
//# sourceMappingURL=index.d.ts.map
|