switch-ext-kit 0.0.0-stage → 0.2.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/src/models.ts ADDED
@@ -0,0 +1,392 @@
1
+ // Models for an extension, through the host that runs it: an extension holds no model keys. Its
2
+ // requests go to the client over MCP, under the `ax.switch/models` extension, and the core answers
3
+ // them with the user's own profile: `models/decide` picks among choices, `models/complete` writes
4
+ // text. The same connection carries an extension's action items (`ax.switch/asks`): `asks/open` and
5
+ // `asks/close`, and the rest it asks of the host (`Host`): other extensions' tools, the user's
6
+ // connections, and brain events it follows.
7
+ import { existsSync, readFileSync } from "node:fs"
8
+ import path from "node:path"
9
+ import { Context, Deferred, Effect, Layer, Option, Queue, Schema } from "effect"
10
+ import type { Cause } from "effect"
11
+
12
+ import { writeFileAtomic } from "./files.ts"
13
+
14
+ /** The client capability extension a host declares when it answers model requests. */
15
+ export const MODELS = "ax.switch/models"
16
+
17
+ /** A role in the user's profile, which says what model runs it. */
18
+ export type Role = "turn" | "triage" | "gate" | "decision" | "browse"
19
+
20
+ export interface Choice {
21
+ readonly value: string
22
+ readonly description?: string
23
+ }
24
+
25
+ /** Pick one of `choices`. */
26
+ export interface Question {
27
+ readonly instructions: string
28
+ readonly choices: readonly Choice[]
29
+ }
30
+
31
+ /** `stable` goes first and is the same across many calls, so the provider can cache it. */
32
+ export interface Input {
33
+ readonly stable: string
34
+ readonly item: string
35
+ }
36
+
37
+ export interface Answer {
38
+ readonly choice: string
39
+ /** Every choice's probability. */
40
+ readonly probabilities: Readonly<Record<string, number>>
41
+ }
42
+
43
+ export interface Decision {
44
+ readonly answers: Readonly<Record<string, Answer>>
45
+ readonly ms: number
46
+ /** Dollars. */
47
+ readonly cost: number
48
+ }
49
+
50
+ export interface Completion {
51
+ readonly text: string
52
+ readonly ms: number
53
+ readonly cost: number
54
+ }
55
+
56
+ const answer = Schema.Struct({
57
+ choice: Schema.String,
58
+ probabilities: Schema.Record(Schema.String, Schema.Number),
59
+ })
60
+ const decision = Schema.Struct({
61
+ answers: Schema.Record(Schema.String, answer),
62
+ ms: Schema.Number,
63
+ cost: Schema.Number,
64
+ })
65
+ const completion = Schema.Struct({ text: Schema.String, ms: Schema.Number, cost: Schema.Number })
66
+
67
+ const TaggedFailure = Schema.TaggedError
68
+
69
+ const ModelErrorBase: Schema.Class<
70
+ ModelError,
71
+ Schema.TaggedStruct<"ModelError", { readonly message: Schema.String }>,
72
+ Cause.YieldableError
73
+ > = TaggedFailure<ModelError>()("ModelError", { message: Schema.String })
74
+
75
+ /** No host to ask, or the host's model failed. */
76
+ export class ModelError extends ModelErrorBase {}
77
+
78
+ export interface ModelsShape {
79
+ /** Asks the role's model every question about one input, in one call. */
80
+ readonly decide: (
81
+ input: Input,
82
+ questions: Readonly<Record<string, Question>>,
83
+ role?: Role,
84
+ ) => Effect.Effect<Decision, ModelError>
85
+ readonly complete: (
86
+ role: Role,
87
+ system: string,
88
+ prompt: string,
89
+ ) => Effect.Effect<Completion, ModelError>
90
+ }
91
+
92
+ /** The `Models` service's identifier, as a requirement. */
93
+ export interface ModelsService {
94
+ readonly Models: unique symbol
95
+ }
96
+
97
+ /** Sends one request to the client and decodes its result. */
98
+ export type Send = (method: string, params: Readonly<Record<string, unknown>>) => Promise<unknown>
99
+
100
+ /** A brain event an extension follows (`switch/follow`), as the host sends it (`switch/event`). */
101
+ export interface Followed {
102
+ readonly seq: number
103
+ readonly id: string
104
+ readonly type: string
105
+ readonly source: string
106
+ readonly time: number
107
+ readonly payload: unknown
108
+ }
109
+
110
+ /** Where `serve` hands over its connection, once the client has said what it offers. */
111
+ export interface PeerShape {
112
+ /** `null`: the client answers no model requests. Called again on each new client. */
113
+ readonly attach: (send: Send | null) => void
114
+ /** A brain event it follows, as it comes. */
115
+ readonly heard?: (event: unknown) => void
116
+ }
117
+
118
+ /** The `Peer` service's identifier, as a requirement. */
119
+ export interface PeerService {
120
+ readonly Peer: unique symbol
121
+ }
122
+
123
+ export const Peer: Context.Service<PeerService, PeerShape> = Context.Service<
124
+ PeerService,
125
+ PeerShape
126
+ >("switch-ext-kit/Peer")
127
+
128
+ /** How long a call waits for the client to connect before it gives up. */
129
+ const CONNECT_MS = 30_000
130
+
131
+ const failed = (e: unknown) =>
132
+ new ModelError({ message: e instanceof Error ? e.message : String(e) })
133
+
134
+ const modelsKey: Context.Service<ModelsService, ModelsShape> = Context.Service<
135
+ ModelsService,
136
+ ModelsShape
137
+ >("switch-ext-kit/Models")
138
+
139
+ /** The client capability extension a host declares when it takes an extension's action items. */
140
+ export const ASKS = "ax.switch/asks"
141
+
142
+ /** A draft: words to send in the user's name, editable on the card. */
143
+ export interface AskDraft {
144
+ readonly name: string
145
+ readonly label: string
146
+ readonly text: string
147
+ }
148
+
149
+ /** A file on the card: `blob` is its key in the brain's blob store, or `url` a link. */
150
+ export interface AskAttachment {
151
+ readonly name: string
152
+ readonly type: string
153
+ readonly size?: number
154
+ readonly blob?: string
155
+ readonly url?: string
156
+ /** Beside this option. */
157
+ readonly option?: number
158
+ }
159
+
160
+ /**
161
+ * An action item an extension puts in the user's queue. `answerTo` names one of its own tools (best
162
+ * `appOnly`) the core calls once it closes: with `{ item, status, answer }`, or for a sealed ask
163
+ * `{ item, use, enc, ct }`, which `openSealed` (switch-ext-kit/sealed) opens with the ask's secret key.
164
+ * A sealed ask's answer reaches only that tool; the brain records only that it was answered.
165
+ */
166
+ export interface AskInput {
167
+ readonly title: string
168
+ readonly body: string
169
+ readonly kind?: "task" | "question" | "approval" | "sealed"
170
+ /** Only this extension verifies completion; user dismissal remains available. */
171
+ readonly completion?: "owner"
172
+ /** An explicit action, such as retrying the private challenge. */
173
+ readonly action?: {
174
+ readonly label: string
175
+ readonly app: string
176
+ readonly tool: string
177
+ readonly args?: Readonly<Record<string, unknown>>
178
+ }
179
+ /** Its space; Home when absent. */
180
+ readonly space?: string
181
+ readonly options?: readonly string[]
182
+ readonly drafts?: readonly AskDraft[]
183
+ readonly attachments?: readonly AskAttachment[]
184
+ readonly resolveWhen?: string
185
+ readonly notify?: boolean
186
+ readonly answerTo?: string
187
+ /** A sealed ask's one-time key (`sealedKey().key`) and what the secret is for. */
188
+ readonly sealed?: { readonly key: string; readonly use: string }
189
+ }
190
+
191
+ export interface AsksShape {
192
+ /** Opens it, or revises the open one with `id` (an id this extension gave before). */
193
+ readonly open: (ask: AskInput, id?: string) => Effect.Effect<{ readonly id: string }, ModelError>
194
+ readonly close: (id: string, status: "done" | "dismissed") => Effect.Effect<void, ModelError>
195
+ }
196
+
197
+ /** The `Asks` service's identifier, as a requirement. */
198
+ export interface AsksService {
199
+ readonly Asks: unique symbol
200
+ }
201
+
202
+ const asksKey: Context.Service<AsksService, AsksShape> = Context.Service<AsksService, AsksShape>(
203
+ "switch-ext-kit/Asks",
204
+ )
205
+
206
+ const opened = Schema.Struct({ id: Schema.String })
207
+
208
+ /** What the host does for an extension beyond models and asks. */
209
+ export interface HostShape {
210
+ /** Any request to the host, its result decoded. */
211
+ readonly request: <A>(
212
+ method: string,
213
+ params: Readonly<Record<string, unknown>>,
214
+ result: Schema.Codec<A, unknown>,
215
+ ) => Effect.Effect<A, ModelError>
216
+ /** Another extension's tool (`switch/call`), one the manifest's `reaches.calls` names. */
217
+ readonly call: (
218
+ name: string,
219
+ args: Readonly<Record<string, unknown>>,
220
+ ) => Effect.Effect<Readonly<Record<string, unknown>>, ModelError>
221
+ /** The user's connected accounts for a provider the manifest needs. */
222
+ readonly accounts: (provider: string) => Effect.Effect<readonly string[], ModelError>
223
+ /** A fresh token (or key) for one of them. */
224
+ readonly token: (provider: string, account: string) => Effect.Effect<string, ModelError>
225
+ /**
226
+ * The brain's events of `types` (exact, or a prefix ending in `*`), each handled once, in order:
227
+ * the last one handled is kept in `follow.json` in its folder, and following resumes after it on
228
+ * every new client, so a restart on either side misses none.
229
+ */
230
+ readonly follow: (
231
+ types: readonly string[],
232
+ handle: (event: Followed) => Effect.Effect<void>,
233
+ ) => Effect.Effect<void, ModelError>
234
+ }
235
+
236
+ /** The `Host` service's identifier, as a requirement. */
237
+ export interface HostService {
238
+ readonly Host: unique symbol
239
+ }
240
+
241
+ const hostKey: Context.Service<HostService, HostShape> = Context.Service<HostService, HostShape>(
242
+ "switch-ext-kit/Host",
243
+ )
244
+
245
+ const followed = Schema.Struct({
246
+ seq: Schema.Finite,
247
+ id: Schema.String,
248
+ type: Schema.String,
249
+ source: Schema.String,
250
+ time: Schema.Finite,
251
+ payload: Schema.Unknown,
252
+ })
253
+ const decodeFollowed = Schema.decodeUnknownOption(followed)
254
+ const accountList = Schema.Struct({
255
+ accounts: Schema.Array(Schema.Struct({ account: Schema.String })),
256
+ })
257
+ const tokenOf = Schema.Struct({ token: Schema.String })
258
+ const record = Schema.Record(Schema.String, Schema.Unknown)
259
+ const lastHandled = Schema.decodeUnknownOption(
260
+ Schema.fromJsonString(Schema.Struct({ after: Schema.Finite })),
261
+ )
262
+ const FOLLOW_FILE = "follow.json"
263
+
264
+ const matches = (patterns: readonly string[], type: string) =>
265
+ patterns.some((p) => (p.endsWith("*") ? type.startsWith(p.slice(0, -1)) : p === type))
266
+
267
+ const modelsLayer: Layer.Layer<ModelsService | AsksService | HostService | PeerService> =
268
+ Layer.effectContext(
269
+ Effect.gen(function* making() {
270
+ const ready = yield* Deferred.make<Send | null>()
271
+ let current: Send | null = null
272
+ const handlers: {
273
+ readonly types: readonly string[]
274
+ readonly handle: (e: Followed) => Effect.Effect<void>
275
+ }[] = []
276
+ const file = path.resolve(FOLLOW_FILE)
277
+ let after = Option.match(
278
+ existsSync(file) ? lastHandled(readFileSync(file, "utf-8")) : Option.none(),
279
+ { onNone: () => 0, onSome: (x) => x.after },
280
+ )
281
+ const heard = yield* Queue.unbounded<Followed>()
282
+ yield* Effect.forkScoped(
283
+ Effect.forever(
284
+ Effect.gen(function* handling() {
285
+ const e = yield* Queue.take(heard)
286
+ if (e.seq <= after) {
287
+ return
288
+ }
289
+ for (const h of handlers) {
290
+ if (matches(h.types, e.type)) {
291
+ yield* h.handle(e)
292
+ }
293
+ }
294
+ after = e.seq
295
+ writeFileAtomic(file, JSON.stringify({ after }))
296
+ }),
297
+ ),
298
+ )
299
+ const refollow = (send: Send) => {
300
+ const types = [...new Set(handlers.flatMap((h) => h.types))]
301
+ if (types.length > 0) {
302
+ void send("switch/follow", { types, after }).catch(() => {
303
+ /* the next client follows again */
304
+ })
305
+ }
306
+ }
307
+ const peer: PeerShape = {
308
+ attach: (send) => {
309
+ current = send
310
+ Deferred.doneUnsafe(ready, Effect.succeed(send))
311
+ if (send !== null) {
312
+ refollow(send)
313
+ }
314
+ },
315
+ heard: (raw) => {
316
+ const e = decodeFollowed(raw)
317
+ if (Option.isSome(e)) {
318
+ Queue.offerUnsafe(heard, e.value)
319
+ }
320
+ },
321
+ }
322
+ const ask = <A>(
323
+ method: string,
324
+ params: Readonly<Record<string, unknown>>,
325
+ result: Schema.Codec<A, unknown>,
326
+ ) =>
327
+ Effect.gen(function* asking() {
328
+ const send = yield* Deferred.await(ready).pipe(
329
+ Effect.timeoutOrElse({
330
+ duration: CONNECT_MS,
331
+ orElse: () => Effect.fail(new ModelError({ message: "No host connected" })),
332
+ }),
333
+ )
334
+ const now = current ?? send
335
+ if (now === null) {
336
+ return yield* Effect.fail(new ModelError({ message: "The host offers none" }))
337
+ }
338
+ const raw = yield* Effect.tryPromise({
339
+ try: async () => await now(method, params),
340
+ catch: failed,
341
+ })
342
+ return yield* Schema.decodeUnknownEffect(result)(raw).pipe(Effect.mapError(failed))
343
+ })
344
+ const models: ModelsShape = {
345
+ decide: (input, questions, role = "decision") =>
346
+ ask("models/decide", { input, questions, role }, decision),
347
+ complete: (role, system, prompt) =>
348
+ ask("models/complete", { role, system, prompt }, completion),
349
+ }
350
+ const asks: AsksShape = {
351
+ open: (input, id) =>
352
+ ask("asks/open", { ask: input, ...(id !== undefined && { id }) }, opened),
353
+ close: (id, status) => Effect.asVoid(ask("asks/close", { id, status }, Schema.Unknown)),
354
+ }
355
+ const host: HostShape = {
356
+ request: ask,
357
+ call: (name, args) => ask("switch/call", { name, arguments: args }, record),
358
+ accounts: (provider) =>
359
+ Effect.map(ask("connections/list", { provider }, accountList), (r) =>
360
+ r.accounts.map((a) => a.account),
361
+ ),
362
+ token: (provider, account) =>
363
+ Effect.map(ask("connections/token", { provider, account }, tokenOf), (t) => t.token),
364
+ follow: (types, handle) =>
365
+ Effect.gen(function* following() {
366
+ handlers.push({ types, handle })
367
+ const all = [...new Set(handlers.flatMap((h) => h.types))]
368
+ yield* ask("switch/follow", { types: all, after }, Schema.Unknown)
369
+ }),
370
+ }
371
+ return Context.make(modelsKey, models).pipe(
372
+ Context.add(asksKey, asks),
373
+ Context.add(hostKey, host),
374
+ Context.add(Peer, peer),
375
+ )
376
+ }),
377
+ )
378
+
379
+ /** The host's other services (calls, connections, follows): provided by `Models.layer`. */
380
+ export const Host: Context.Service<HostService, HostShape> & {
381
+ readonly layer: typeof modelsLayer
382
+ } = Object.assign(hostKey, { layer: modelsLayer })
383
+
384
+ /** Action items through the host: provided by `Models.layer`, which `serve` connects. */
385
+ export const Asks: Context.Service<AsksService, AsksShape> & {
386
+ readonly layer: typeof modelsLayer
387
+ } = Object.assign(asksKey, { layer: modelsLayer })
388
+
389
+ /** Models through the host: `serve` connects it. */
390
+ export const Models: Context.Service<ModelsService, ModelsShape> & {
391
+ readonly layer: typeof modelsLayer
392
+ } = Object.assign(modelsKey, { layer: modelsLayer })
package/src/record.ts ADDED
@@ -0,0 +1,84 @@
1
+ // The events of an extension ported from a Switchboard appendage, as the shim made them: each type
2
+ // version 1, its payload the appendage's record (`kind`, `stream`, its body as `data`, and the
3
+ // envelope's `about`, `refs`, `importance`, `sender` and `message`), its id the record's own when it
4
+ // gives one. A port emits these, so what lands in the brain is what landed before.
5
+ import { Schema } from "effect"
6
+
7
+ import { defineEvent } from "./events.ts"
8
+ import type { DefinedEvent, Draft } from "./events.ts"
9
+ import type { Message, Sender } from "./messages.ts"
10
+
11
+ export const RecordPayload: Schema.Codec<RecordShape, unknown> = Schema.Struct({
12
+ kind: Schema.String,
13
+ stream: Schema.String,
14
+ data: Schema.Unknown,
15
+ about: Schema.optionalKey(Schema.Array(Schema.String)),
16
+ refs: Schema.optionalKey(Schema.Array(Schema.String)),
17
+ importance: Schema.optionalKey(Schema.Finite),
18
+ sender: Schema.optionalKey(Schema.Unknown),
19
+ message: Schema.optionalKey(Schema.Unknown),
20
+ })
21
+
22
+ export interface RecordShape {
23
+ readonly kind: string
24
+ readonly stream: string
25
+ readonly data: unknown
26
+ readonly about?: readonly string[]
27
+ readonly refs?: readonly string[]
28
+ readonly importance?: number
29
+ readonly sender?: unknown
30
+ readonly message?: unknown
31
+ }
32
+
33
+ /** What an appendage's `emit` took beside the body. */
34
+ export interface Envelope {
35
+ readonly about?: readonly string[]
36
+ readonly refs?: readonly string[]
37
+ readonly importance?: number
38
+ /** The record's own id: the event's id, so emitting it again is one event. */
39
+ readonly id?: string
40
+ /** Where this occurrence lands, within its type's. */
41
+ readonly stream?: string
42
+ readonly sender?: Sender
43
+ readonly message?: Message
44
+ /** The event's id when the record has none (`event_id`). */
45
+ readonly eventId?: string
46
+ /** When it happened, as an ISO instant. */
47
+ readonly at?: string
48
+ }
49
+
50
+ export interface RecordEvent<T extends string> extends DefinedEvent<T, RecordShape> {
51
+ /** One occurrence: its body and envelope as the appendage's `emit` took them. */
52
+ readonly record: (data: unknown, envelope?: Envelope) => Draft
53
+ }
54
+
55
+ /**
56
+ * `<extension>.<name>`, landing as `kind` in `stream` (the appendage's `event()` placement; else an
57
+ * `event` in `events/<extension>`).
58
+ */
59
+ export const defineRecord = <const T extends string>(
60
+ type: T,
61
+ placed: { readonly kind?: string; readonly stream?: string } = {},
62
+ ): RecordEvent<T> => {
63
+ const def = defineEvent(type, 1, RecordPayload)
64
+ const extension = type.slice(0, type.indexOf("."))
65
+ return {
66
+ ...def,
67
+ record: (data, envelope = {}) => {
68
+ const { id, eventId, at, stream, ...rest } = envelope
69
+ const payload: RecordShape = {
70
+ ...rest,
71
+ kind: placed.kind ?? "event",
72
+ stream: stream ?? placed.stream ?? `events/${extension}`,
73
+ data: data ?? null,
74
+ }
75
+ const given = id ?? eventId
76
+ return {
77
+ type,
78
+ payload,
79
+ ...(given !== undefined && { id: given }),
80
+ ...(at !== undefined && { time: at }),
81
+ }
82
+ },
83
+ }
84
+ }
package/src/sealed.ts ADDED
@@ -0,0 +1,177 @@
1
+ // Sealed answers: how a secret the user types reaches the one extension that asked for it without
2
+ // ever touching the brain, a chat or a model's context. The extension makes a one-time key pair
3
+ // (`sealedKey`), keeps the private half, and raises a sealed ask carrying the public half and what
4
+ // it's for (`use`). The user's client seals what they type to that key (`seal`); the core relays
5
+ // the sealed bytes to the extension's `answerTo` tool, which opens them (`openSealed`). The brain
6
+ // records only that it was answered.
7
+ //
8
+ // The seal is HPKE base mode (RFC 9180), single shot: DHKEM(X25519, HKDF-SHA256), HKDF-SHA256,
9
+ // AES-256-GCM, empty aad. The ask's id and its use are bound into the key schedule through `info`
10
+ // ("switch-sealed-v1", the item's id and the use, NUL-separated), so a sealed answer opens for no
11
+ // other ask or use. The iPhone seals the same way with CryptoKit's HPKE
12
+ // (`.Curve25519_SHA256_AES_GCM_256`). Only WebCrypto is used, so it runs in Bun and in a webview.
13
+
14
+ /** The prefix of `info`: Switch's sealed answers, this version of the binding. */
15
+ export const SEALED_DOMAIN = "switch-sealed-v1"
16
+
17
+ /** A secret sealed to a key: the encapsulated key and the ciphertext with its tag, each base64. */
18
+ export interface SealedAnswer {
19
+ readonly enc: string
20
+ readonly ct: string
21
+ }
22
+
23
+ const KEM = 0x00_20
24
+ const KDF = 0x00_01
25
+ const AEAD = 0x00_02
26
+
27
+ const text = new TextEncoder()
28
+ const subtle = (): SubtleCrypto => globalThis.crypto.subtle
29
+
30
+ const concat = (...parts: readonly Uint8Array[]): Uint8Array<ArrayBuffer> => {
31
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))
32
+ let at = 0
33
+ for (const p of parts) {
34
+ out.set(p, at)
35
+ at += p.length
36
+ }
37
+ return out
38
+ }
39
+
40
+ /** Two bytes, big-endian. */
41
+ const u16 = (n: number) => new Uint8Array([Math.floor(n / 256) % 256, n % 256])
42
+
43
+ const b64 = (bytes: Uint8Array): string => btoa(String.fromCodePoint(...bytes))
44
+ const unb64 = (s: string): Uint8Array<ArrayBuffer> =>
45
+ Uint8Array.from(atob(s), (c) => c.codePointAt(0) ?? 0)
46
+ const unb64url = (s: string) => unb64(s.replaceAll("-", "+").replaceAll("_", "/"))
47
+
48
+ const hmac = async (key: Uint8Array, data: Uint8Array) => {
49
+ // HMAC pads a short key with zeros, so an empty salt is the hash length of zeros.
50
+ const k = await subtle().importKey(
51
+ "raw",
52
+ key.length === 0 ? new Uint8Array(32) : concat(key),
53
+ { name: "HMAC", hash: "SHA-256" },
54
+ false,
55
+ ["sign"],
56
+ )
57
+ return new Uint8Array(await subtle().sign("HMAC", k, concat(data)))
58
+ }
59
+
60
+ const VERSION = text.encode("HPKE-v1")
61
+
62
+ const extract = async (suite: Uint8Array, salt: Uint8Array, label: string, ikm: Uint8Array) =>
63
+ await hmac(salt, concat(VERSION, suite, text.encode(label), ikm))
64
+
65
+ // One block of HKDF-Expand: every length here is at most 32.
66
+ const expand = async (
67
+ suite: Uint8Array,
68
+ prk: Uint8Array,
69
+ label: string,
70
+ info: Uint8Array,
71
+ length: number,
72
+ ) => {
73
+ const labeled = concat(u16(length), VERSION, suite, text.encode(label), info)
74
+ const block = await hmac(prk, concat(labeled, new Uint8Array([1])))
75
+ return block.slice(0, length)
76
+ }
77
+
78
+ const KEM_SUITE = concat(text.encode("KEM"), u16(KEM))
79
+ const SUITE = concat(text.encode("HPKE"), u16(KEM), u16(KDF), u16(AEAD))
80
+ const EMPTY = new Uint8Array(0)
81
+
82
+ /** The `info` that binds a sealing to one item and one use. */
83
+ export const sealedInfo = (item: string, use: string): Uint8Array<ArrayBuffer> =>
84
+ concat(
85
+ text.encode(SEALED_DOMAIN),
86
+ new Uint8Array([0]),
87
+ text.encode(item),
88
+ new Uint8Array([0]),
89
+ text.encode(use),
90
+ )
91
+
92
+ const sharedSecret = async (dh: Uint8Array, enc: Uint8Array, recipient: Uint8Array) => {
93
+ const prk = await extract(KEM_SUITE, EMPTY, "eae_prk", dh)
94
+ return await expand(KEM_SUITE, prk, "shared_secret", concat(enc, recipient), 32)
95
+ }
96
+
97
+ const schedule = async (shared: Uint8Array, info: Uint8Array) => {
98
+ const pskId = await extract(SUITE, EMPTY, "psk_id_hash", EMPTY)
99
+ const infoHash = await extract(SUITE, EMPTY, "info_hash", info)
100
+ const context = concat(new Uint8Array([0]), pskId, infoHash)
101
+ const secret = await extract(SUITE, shared, "secret", EMPTY)
102
+ const key = await expand(SUITE, secret, "key", context, 32)
103
+ const nonce = await expand(SUITE, secret, "base_nonce", context, 12)
104
+ return {
105
+ key: await subtle().importKey("raw", concat(key), "AES-GCM", false, ["encrypt", "decrypt"]),
106
+ nonce: concat(nonce),
107
+ }
108
+ }
109
+
110
+ const X25519 = { name: "X25519" }
111
+
112
+ const keyPair = async (): Promise<CryptoKeyPair> => {
113
+ const made = await subtle().generateKey(X25519, true, ["deriveBits"])
114
+ if ("privateKey" in made) {
115
+ return made
116
+ }
117
+ throw new Error("X25519 made no key pair")
118
+ }
119
+
120
+ const dh = async (privateKey: CryptoKey, publicKey: CryptoKey) =>
121
+ new Uint8Array(await subtle().deriveBits({ name: "X25519", public: publicKey }, privateKey, 256))
122
+
123
+ const importPublic = async (raw: Uint8Array) =>
124
+ await subtle().importKey("raw", concat(raw), X25519, true, [])
125
+
126
+ /**
127
+ * A one-time key pair for a sealed ask: `key` goes on the ask, `secretKey` stays with the extension
128
+ * (in memory, or its Keychain while the ask waits) and opens the answer.
129
+ */
130
+ export const sealedKey = async (): Promise<{ key: string; secretKey: string }> => {
131
+ const pair = await keyPair()
132
+ const jwk = await subtle().exportKey("jwk", pair.privateKey)
133
+ const raw = new Uint8Array(await subtle().exportKey("raw", pair.publicKey))
134
+ return { key: b64(raw), secretKey: `${jwk.d ?? ""}.${jwk.x ?? ""}` }
135
+ }
136
+
137
+ /** Seals `secret` to an ask's `key`, bound to its item and use. What the user's client sends. */
138
+ export const seal = async (
139
+ key: string,
140
+ item: string,
141
+ use: string,
142
+ secret: string,
143
+ ): Promise<SealedAnswer> => {
144
+ const recipient = unb64(key)
145
+ const ephemeral = await keyPair()
146
+ const enc = new Uint8Array(await subtle().exportKey("raw", ephemeral.publicKey))
147
+ const shared = await sharedSecret(
148
+ await dh(ephemeral.privateKey, await importPublic(recipient)),
149
+ enc,
150
+ recipient,
151
+ )
152
+ const s = await schedule(shared, sealedInfo(item, use))
153
+ const ct = await subtle().encrypt({ name: "AES-GCM", iv: s.nonce }, s.key, text.encode(secret))
154
+ return { enc: b64(enc), ct: b64(new Uint8Array(ct)) }
155
+ }
156
+
157
+ /** Opens a sealed answer for exactly this item and use; anything else, or tampered, throws. */
158
+ export const openSealed = async (
159
+ secretKey: string,
160
+ item: string,
161
+ use: string,
162
+ sealed: SealedAnswer,
163
+ ): Promise<string> => {
164
+ const [d = "", x = ""] = secretKey.split(".")
165
+ const privateKey = await subtle().importKey(
166
+ "jwk",
167
+ { kty: "OKP", crv: "X25519", d, x },
168
+ X25519,
169
+ false,
170
+ ["deriveBits"],
171
+ )
172
+ const enc = unb64(sealed.enc)
173
+ const shared = await sharedSecret(await dh(privateKey, await importPublic(enc)), enc, unb64url(x))
174
+ const s = await schedule(shared, sealedInfo(item, use))
175
+ const plain = await subtle().decrypt({ name: "AES-GCM", iv: s.nonce }, s.key, unb64(sealed.ct))
176
+ return new TextDecoder().decode(plain)
177
+ }