switch-ext-kit 0.0.0-stage → 0.2.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/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
+ }
package/src/shell.ts ADDED
@@ -0,0 +1,244 @@
1
+ // A shell command line's simple commands, ported from Switchboard's `sb guard`: enough of sh to say
2
+ // what a line runs, never to run it.
3
+
4
+ interface Lexer {
5
+ readonly line: string
6
+ i: number
7
+ word: string
8
+ inWord: boolean
9
+ words: string[]
10
+ readonly commands: string[][]
11
+ heredocs: { readonly delimiter: string; readonly tabs: boolean }[]
12
+ }
13
+
14
+ const at = (l: Lexer, offset = 0) => l.line.charAt(l.i + offset)
15
+
16
+ const until = (s: string, from: number, c: string) => {
17
+ const found = s.indexOf(c, from)
18
+ return found === -1 ? s.length : found
19
+ }
20
+
21
+ /** Where the bracket opened before `from` closes, past nested ones and quotes. */
22
+ const closing = (s: string, from: number) => {
23
+ let depth = 1
24
+ let quote = ""
25
+ for (let i = from; i < s.length; i += 1) {
26
+ const c = s.charAt(i)
27
+ if (quote !== "") {
28
+ quote = c === quote ? "" : quote
29
+ } else if (c === "'" || c === '"') {
30
+ quote = c
31
+ } else if (c === "\\") {
32
+ i += 1
33
+ } else if (c === "(" || c === ")") {
34
+ depth += c === "(" ? 1 : -1
35
+ if (depth === 0) {
36
+ return i
37
+ }
38
+ }
39
+ }
40
+ return s.length
41
+ }
42
+
43
+ const endWord = (l: Lexer) => {
44
+ if (l.inWord) {
45
+ l.words.push(l.word)
46
+ l.word = ""
47
+ l.inWord = false
48
+ }
49
+ }
50
+
51
+ const endCommand = (l: Lexer) => {
52
+ if (l.words.length > 0) {
53
+ l.commands.push(l.words)
54
+ l.words = []
55
+ }
56
+ }
57
+
58
+ /** `$(…)` or a backquote from `open`: its commands go first; what it prints stands as `$`. */
59
+ const substitution = (l: Lexer, open: number, backquote: boolean) => {
60
+ const close = backquote ? until(l.line, open, "`") : closing(l.line, open)
61
+ l.commands.push(...simpleCommands(l.line.slice(open, close)))
62
+ l.word += "$"
63
+ l.inWord = true
64
+ l.i = close + 1
65
+ }
66
+
67
+ const doubleQuoted = (l: Lexer) => {
68
+ l.i += 1
69
+ l.inWord = true
70
+ while (l.i < l.line.length && at(l) !== '"') {
71
+ const d = at(l)
72
+ if (d === "\\" && '"\\$`'.includes(at(l, 1)) && l.i + 1 < l.line.length) {
73
+ l.word += at(l, 1)
74
+ l.i += 2
75
+ } else if (d === "$" && at(l, 1) === "(") {
76
+ substitution(l, l.i + 2, false)
77
+ } else if (d === "`") {
78
+ substitution(l, l.i + 1, true)
79
+ } else {
80
+ l.word += d
81
+ l.i += 1
82
+ }
83
+ }
84
+ l.i += 1
85
+ }
86
+
87
+ const newline = (l: Lexer) => {
88
+ endWord(l)
89
+ endCommand(l)
90
+ l.i += 1
91
+ // Here documents' bodies, line by line to each delimiter.
92
+ for (const h of l.heredocs) {
93
+ while (l.i < l.line.length) {
94
+ const eol = until(l.line, l.i, "\n")
95
+ const body = l.line.slice(l.i, eol)
96
+ l.i = eol + 1
97
+ if ((h.tabs ? body.replace(/^\t+/u, "") : body) === h.delimiter) {
98
+ break
99
+ }
100
+ }
101
+ }
102
+ l.heredocs = []
103
+ }
104
+
105
+ const operator = (l: Lexer) => {
106
+ endWord(l)
107
+ // `2>&1` and `&>` are redirections, not a list's `&`.
108
+ if (at(l) === "&" && (at(l, 1) === ">" || at(l, -1) === ">")) {
109
+ l.i += 1
110
+ return
111
+ }
112
+ endCommand(l)
113
+ l.i += 1
114
+ }
115
+
116
+ const BREAKS = ";&|<>()"
117
+
118
+ const hereDocument = (l: Lexer) => {
119
+ let j = l.i + 2
120
+ const tabs = l.line.charAt(j) === "-"
121
+ j += tabs ? 1 : 0
122
+ while (l.line.charAt(j) === " " || l.line.charAt(j) === "\t") {
123
+ j += 1
124
+ }
125
+ let delimiter = ""
126
+ while (j < l.line.length && !/\s/u.test(l.line.charAt(j)) && !BREAKS.includes(l.line.charAt(j))) {
127
+ const d = l.line.charAt(j)
128
+ delimiter += d === "'" || d === '"' || d === "\\" ? "" : d
129
+ j += 1
130
+ }
131
+ l.heredocs.push({ delimiter, tabs })
132
+ l.i = j
133
+ }
134
+
135
+ /** The word a redirection sends to: skipped, quotes and all. */
136
+ const target = (l: Lexer) => {
137
+ while (at(l) === " " || at(l) === "\t") {
138
+ l.i += 1
139
+ }
140
+ let quote = ""
141
+ while (l.i < l.line.length) {
142
+ const t = at(l)
143
+ if (quote !== "") {
144
+ quote = t === quote ? "" : quote
145
+ } else if (t === "'" || t === '"') {
146
+ quote = t
147
+ } else if (/\s/u.test(t) || BREAKS.includes(t)) {
148
+ return
149
+ }
150
+ l.i += 1
151
+ }
152
+ }
153
+
154
+ const redirection = (l: Lexer) => {
155
+ // A file descriptor's number just before it isn't a word (`2>`).
156
+ if (l.inWord && /^\d+$/u.test(l.word)) {
157
+ l.word = ""
158
+ l.inWord = false
159
+ }
160
+ endWord(l)
161
+ if (at(l) === "<" && at(l, 1) === "<" && at(l, 2) !== "<") {
162
+ hereDocument(l)
163
+ return
164
+ }
165
+ l.i += 1
166
+ while (l.i < l.line.length && "<>|".includes(at(l))) {
167
+ l.i += 1
168
+ }
169
+ if (at(l) === "&") {
170
+ l.i += 1
171
+ while (l.i < l.line.length && /[\d-]/u.test(at(l))) {
172
+ l.i += 1
173
+ }
174
+ return
175
+ }
176
+ target(l)
177
+ }
178
+
179
+ const plain = (l: Lexer, c: string) => {
180
+ l.word += c
181
+ l.inWord = true
182
+ l.i += 1
183
+ }
184
+
185
+ const step = (l: Lexer) => {
186
+ const c = at(l)
187
+ if (c === "\\") {
188
+ const next = at(l, 1)
189
+ if (next !== "" && next !== "\n") {
190
+ plain(l, next)
191
+ l.i += 1
192
+ return
193
+ }
194
+ l.i += 2
195
+ } else if (c === "'") {
196
+ const close = until(l.line, l.i + 1, "'")
197
+ l.word += l.line.slice(l.i + 1, close)
198
+ l.inWord = true
199
+ l.i = close + 1
200
+ } else if (c === '"') {
201
+ doubleQuoted(l)
202
+ } else if (c === "$" && at(l, 1) === "(") {
203
+ substitution(l, l.i + 2, false)
204
+ } else if (c === "`") {
205
+ substitution(l, l.i + 1, true)
206
+ } else if (c === "#" && !l.inWord) {
207
+ l.i = until(l.line, l.i, "\n")
208
+ } else if (c === " " || c === "\t") {
209
+ endWord(l)
210
+ l.i += 1
211
+ } else if (c === "\n") {
212
+ newline(l)
213
+ } else if (";&|()".includes(c)) {
214
+ operator(l)
215
+ } else if (c === "<" || c === ">") {
216
+ redirection(l)
217
+ } else {
218
+ plain(l, c)
219
+ }
220
+ }
221
+
222
+ /**
223
+ * A command line's simple commands, each as its words with quotes taken off, in the order they'd
224
+ * run: split at `;`, `&`, `|`, newlines and parentheses, with each `$(…)` and backquoted command
225
+ * among them, ahead of the command it's in. Redirections, comments and here documents' bodies
226
+ * aren't words.
227
+ */
228
+ export const simpleCommands = (line: string): string[][] => {
229
+ const l: Lexer = {
230
+ line,
231
+ i: 0,
232
+ word: "",
233
+ inWord: false,
234
+ words: [],
235
+ commands: [],
236
+ heredocs: [],
237
+ }
238
+ while (l.i < line.length) {
239
+ step(l)
240
+ }
241
+ endWord(l)
242
+ endCommand(l)
243
+ return l.commands
244
+ }