@llmguard/opencode 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/MANUAL-TEST-G.md +167 -0
  2. package/README.md +334 -2
  3. package/RELEASE.md +122 -0
  4. package/bin/darwin-amd64/helper +0 -0
  5. package/bin/darwin-arm64/helper +0 -0
  6. package/bin/linux-amd64/helper +0 -0
  7. package/bin/linux-arm64/helper +0 -0
  8. package/bin/manifest.json +51 -0
  9. package/bin/windows-amd64/helper.exe +0 -0
  10. package/bin/windows-arm64/helper.exe +0 -0
  11. package/bridge/client.d.ts +55 -0
  12. package/bridge/client.js +425 -0
  13. package/bridge/framing.d.ts +19 -0
  14. package/bridge/framing.js +110 -0
  15. package/bridge/process.d.ts +38 -0
  16. package/bridge/process.js +378 -0
  17. package/bridge/protocol.d.ts +184 -0
  18. package/bridge/protocol.js +683 -0
  19. package/connection-catalog.d.ts +69 -0
  20. package/connection-catalog.js +287 -0
  21. package/connections-tui.d.ts +11 -0
  22. package/connections-tui.js +394 -0
  23. package/demasking.d.ts +2 -0
  24. package/demasking.js +445 -0
  25. package/gui-experimental.cjs +33 -0
  26. package/hook-trace.d.ts +2 -0
  27. package/hook-trace.js +35 -0
  28. package/index.d.ts +1 -0
  29. package/index.js +1 -0
  30. package/licenses/Go-LICENSE +27 -0
  31. package/messages.d.ts +230 -0
  32. package/messages.js +231 -0
  33. package/native/index.d.ts +1 -0
  34. package/native/index.js +1 -0
  35. package/native/tui.d.ts +1 -0
  36. package/native/tui.js +1 -0
  37. package/package.json +49 -4
  38. package/plugin-runtime.d.ts +3 -0
  39. package/plugin-runtime.js +3 -0
  40. package/plugin-settings.d.ts +77 -0
  41. package/plugin-settings.js +487 -0
  42. package/plugin.d.ts +41 -0
  43. package/plugin.js +10 -0
  44. package/response-diagnostics.d.ts +13 -0
  45. package/response-diagnostics.js +142 -0
  46. package/runtime/attachments.d.ts +4 -0
  47. package/runtime/attachments.js +19 -0
  48. package/runtime/errors.d.ts +18 -0
  49. package/runtime/errors.js +26 -0
  50. package/runtime/json.d.ts +14 -0
  51. package/runtime/json.js +243 -0
  52. package/runtime/limits.d.ts +2 -0
  53. package/runtime/limits.js +3 -0
  54. package/runtime/native-edit.d.ts +14 -0
  55. package/runtime/native-edit.js +73 -0
  56. package/runtime/runtime.d.ts +43 -0
  57. package/runtime/runtime.js +345 -0
  58. package/runtime/session-state.d.ts +13 -0
  59. package/runtime/session-state.js +73 -0
  60. package/runtime/text-layout.d.ts +9 -0
  61. package/runtime/text-layout.js +47 -0
  62. package/server.d.ts +1 -0
  63. package/server.js +1 -0
  64. package/settings-rpc.d.ts +511 -0
  65. package/settings-rpc.js +197 -0
  66. package/tui-messages.d.ts +1 -0
  67. package/tui-messages.js +84 -0
  68. package/tui.d.ts +17 -0
  69. package/tui.js +427 -0
  70. package/v1/hooks.d.ts +81 -0
  71. package/v1/hooks.js +97 -0
  72. package/v1/projection.d.ts +32 -0
  73. package/v1/projection.js +217 -0
  74. package/v1.d.ts +2 -0
  75. package/v1.js +2 -0
  76. package/v2/projection.d.ts +36 -0
  77. package/v2/projection.js +374 -0
  78. package/v2/server.d.ts +6 -0
  79. package/v2/server.js +633 -0
@@ -0,0 +1,683 @@
1
+ // IPC metadata only. Guard responses and opaque projection JSON are validated
2
+ // by Go; this module cannot authorize a native mutation.
3
+ export const protocol = 1;
4
+ export const maxFrame = 16 << 20;
5
+ export const maxProjection = 4 << 20;
6
+ // Attachments travel beside the projection. Base64 inflates them by a third, so
7
+ // with a full projection the frame still fits maxFrame.
8
+ export const maxAttachments = 128;
9
+ export const maxAttachmentBytes = 8 << 20;
10
+ export const maxBudgetMS = 180_250;
11
+ export const limits = {
12
+ max_frame_bytes: maxFrame,
13
+ max_active_checks: 16,
14
+ max_pending: 32,
15
+ max_writer_queue_bytes: 32 << 20,
16
+ max_check_budget_ms: maxBudgetMS,
17
+ };
18
+ export const methods = [
19
+ "hello",
20
+ "connection.validate",
21
+ "connection.configure",
22
+ "connection.test",
23
+ "operation.check",
24
+ "operation.cancel",
25
+ "attachments.policy",
26
+ "attachments.configure",
27
+ "route.lease",
28
+ "ping",
29
+ "shutdown",
30
+ ];
31
+ export const profiles = [
32
+ "v1.model.messages",
33
+ "v1.model.system",
34
+ "v1.tool.before",
35
+ "v2.model.context",
36
+ "v2.model.compaction",
37
+ "v2.model.generate",
38
+ "v2.model.title",
39
+ "v2.tool.before",
40
+ "tool.after.observe",
41
+ ];
42
+ export const errorCodes = [
43
+ "invalid_envelope",
44
+ "unsupported_version",
45
+ "unsupported_protocol",
46
+ "unknown_method",
47
+ "invalid_params",
48
+ "not_configured",
49
+ "stale_generation",
50
+ "resource_exhausted",
51
+ "cancelled",
52
+ "timeout",
53
+ "guard_error",
54
+ "invalid_state",
55
+ "shutting_down",
56
+ "internal_error",
57
+ ];
58
+ export class ProtocolError extends Error {
59
+ code;
60
+ constructor(code) {
61
+ super(`opencode: ${code}`);
62
+ this.code = code;
63
+ }
64
+ }
65
+ const id = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
66
+ const epoch = /^[A-Za-z0-9_-]{1,64}$/;
67
+ const textID = /^[A-Za-z0-9_.:-]{1,128}$/;
68
+ const checkCode = /^[a-z][a-z0-9_]{0,63}$/;
69
+ function reject(code = "invalid_params") {
70
+ throw new ProtocolError(code);
71
+ }
72
+ function object(value, required, optional = []) {
73
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
74
+ reject();
75
+ }
76
+ const obj = value;
77
+ if (required.some((key) => !Object.hasOwn(obj, key)) ||
78
+ Object.keys(obj).some((key) => !required.includes(key) && !optional.includes(key))) {
79
+ reject();
80
+ }
81
+ return obj;
82
+ }
83
+ function integer(value, max = Number.MAX_SAFE_INTEGER) {
84
+ return (typeof value === "number" &&
85
+ Number.isSafeInteger(value) &&
86
+ value > 0 &&
87
+ value <= max);
88
+ }
89
+ function str(value, max, empty = false) {
90
+ return (typeof value === "string" &&
91
+ (empty || value.length > 0) &&
92
+ Buffer.byteLength(value) <= max);
93
+ }
94
+ function matching(value, pattern) {
95
+ return typeof value === "string" && pattern.test(value);
96
+ }
97
+ function list(value, max, valid) {
98
+ return Array.isArray(value) && value.length <= max && value.every(valid);
99
+ }
100
+ // Deliberate denylist of code points that reorder or hide text in a terminal
101
+ // or in model context; not the whole Unicode Cf category. Joiners (U+200C/D),
102
+ // variation selectors and the soft hyphen stay allowed, as do \n and \t.
103
+ // Mirrors internal/contract/block_message.go and the rules-engine; change all
104
+ // copies together. tests/fixtures/block-message/cases.json is shared with Go.
105
+ const displayUnsafeRanges = [
106
+ [0x061c, 0x061c], // Arabic letter mark
107
+ [0x200b, 0x200b], // zero width space
108
+ [0x200e, 0x200f], // left-to-right and right-to-left marks
109
+ [0x2028, 0x2029], // line and paragraph separators
110
+ [0x202a, 0x202e], // bidirectional embeddings and overrides
111
+ [0x2060, 0x2064], // word joiner and invisible operators
112
+ [0x2066, 0x2069], // bidirectional isolates
113
+ [0xfeff, 0xfeff], // zero width no-break space
114
+ [0xe0000, 0xe007f], // tag characters that smuggle invisible ASCII
115
+ ];
116
+ function displayUnsafe(char) {
117
+ const code = char.codePointAt(0);
118
+ return ((code < 32 && char !== "\n" && char !== "\t") ||
119
+ (code >= 127 && code <= 159) ||
120
+ displayUnsafeRanges.some(([first, last]) => code >= first && code <= last));
121
+ }
122
+ // A repeated regex group recurses per character in V8 and overflows the stack
123
+ // on multi-megabyte payloads; a flat character class does not.
124
+ function binary(value) {
125
+ if (typeof value !== "string" ||
126
+ value.length % 4 !== 0 ||
127
+ !/^[A-Za-z0-9+/]*={0,2}$/.test(value)) {
128
+ return false;
129
+ }
130
+ const length = Buffer.from(value, "base64").length;
131
+ return length > 0 && length <= maxProjection;
132
+ }
133
+ function decision(value) {
134
+ return (value === null ||
135
+ value === "allow" ||
136
+ value === "deny" ||
137
+ value === "transform");
138
+ }
139
+ function member(value, set) {
140
+ return typeof value === "string" && set.includes(value);
141
+ }
142
+ function providerRoutePath(value) {
143
+ if (member(value, [
144
+ "/chat/completions",
145
+ "/responses",
146
+ "/messages",
147
+ "/route-status",
148
+ ])) {
149
+ return true;
150
+ }
151
+ if (typeof value !== "string") {
152
+ return false;
153
+ }
154
+ const gemini = value.match(/^\/gemini\/([A-Za-z0-9._-]{1,128})\/(generateContent|streamGenerateContent)$/);
155
+ return gemini !== null && gemini[1] !== "." && gemini[1] !== "..";
156
+ }
157
+ function clean(value, max, empty = false) {
158
+ return (str(value, max, empty) &&
159
+ !value.includes("\0") &&
160
+ !value.includes("\r") &&
161
+ !value.includes("\n"));
162
+ }
163
+ // Attachments belong to model requests only. The decoded size is computed from
164
+ // the base64 text, never by decoding it here.
165
+ const modelProfiles = [
166
+ "v1.model.messages",
167
+ "v2.model.context",
168
+ "v2.model.compaction",
169
+ "v2.model.generate",
170
+ "v2.model.title",
171
+ ];
172
+ function decodeAttachments(value, profile) {
173
+ if (!member(profile, modelProfiles) ||
174
+ !Array.isArray(value) ||
175
+ value.length > maxAttachments) {
176
+ reject();
177
+ }
178
+ let total = 0;
179
+ for (const item of value) {
180
+ const a = object(item, [], ["media_type", "data_b64", "uninspectable", "layout"]);
181
+ const bytes = a.media_type !== undefined || a.data_b64 !== undefined;
182
+ if (a.uninspectable !== undefined) {
183
+ if (bytes ||
184
+ !member(a.uninspectable, ["url", "file_id", "unsupported_source"])) {
185
+ reject();
186
+ }
187
+ }
188
+ else {
189
+ if (!str(a.media_type, 128) ||
190
+ a.media_type.includes("\0") ||
191
+ a.media_type.includes("\r") ||
192
+ a.media_type.includes("\n") ||
193
+ a.media_type.includes(",") ||
194
+ typeof a.data_b64 !== "string" ||
195
+ a.data_b64.length === 0 ||
196
+ a.data_b64.length % 4 !== 0 ||
197
+ !/^[A-Za-z0-9+/]*={0,2}$/.test(a.data_b64)) {
198
+ reject();
199
+ }
200
+ const text = a.data_b64;
201
+ const padding = text.endsWith("==") ? 2 : text.endsWith("=") ? 1 : 0;
202
+ total += (text.length / 4) * 3 - padding;
203
+ }
204
+ if (a.layout !== undefined) {
205
+ const l = object(a.layout, ["role", "kind"]);
206
+ if (!member(l.role, ["system", "user", "assistant", "tool"]) ||
207
+ !member(l.kind, ["context", "history", "current_prompt"])) {
208
+ reject();
209
+ }
210
+ }
211
+ }
212
+ if (total > maxAttachmentBytes) {
213
+ reject();
214
+ }
215
+ }
216
+ export function decodeParams(method, value) {
217
+ switch (method) {
218
+ case "hello": {
219
+ const p = object(value, ["protocols", "required_features"]);
220
+ if (!list(p.protocols, 8, (v) => integer(v, 1000)) ||
221
+ p.protocols.length === 0 ||
222
+ !list(p.required_features, 32, (v) => matching(v, textID))) {
223
+ reject();
224
+ }
225
+ if (!p.protocols.includes(1)) {
226
+ reject("unsupported_protocol");
227
+ }
228
+ break;
229
+ }
230
+ case "connection.validate":
231
+ case "connection.configure": {
232
+ const p = object(value, [
233
+ "origin",
234
+ "project_sid",
235
+ "token",
236
+ "allow_loopback_http",
237
+ "timeout_ms",
238
+ ]);
239
+ if (!str(p.origin, 2048) ||
240
+ !matching(p.project_sid, textID) ||
241
+ !clean(p.token, 4096) ||
242
+ typeof p.allow_loopback_http !== "boolean" ||
243
+ !integer(p.timeout_ms, 180_000)) {
244
+ reject();
245
+ }
246
+ break;
247
+ }
248
+ case "connection.test": {
249
+ const p = object(value, ["generation", "budget_ms"]);
250
+ if (!integer(p.generation) || !integer(p.budget_ms, maxBudgetMS)) {
251
+ reject();
252
+ }
253
+ break;
254
+ }
255
+ case "route.lease": {
256
+ const p = object(value, [
257
+ "generation",
258
+ "session_id",
259
+ "lease_token",
260
+ "action",
261
+ "budget_ms",
262
+ ]);
263
+ if (!integer(p.generation) ||
264
+ !matching(p.session_id, /^[A-Za-z0-9_.:-]{1,128}$/) ||
265
+ !matching(p.lease_token, /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/) ||
266
+ !member(p.action, ["renew", "release"]) ||
267
+ !integer(p.budget_ms, maxBudgetMS)) {
268
+ reject();
269
+ }
270
+ break;
271
+ }
272
+ case "operation.check": {
273
+ const p = object(value, ["generation", "profile", "projected_json_b64", "budget_ms"], [
274
+ "session_id",
275
+ "call_id",
276
+ "tool_name",
277
+ "layout",
278
+ "cwd",
279
+ "attachments",
280
+ "model",
281
+ "route_path",
282
+ ]);
283
+ if (!integer(p.generation) ||
284
+ !member(p.profile, profiles) ||
285
+ !binary(p.projected_json_b64) ||
286
+ !integer(p.budget_ms, maxBudgetMS)) {
287
+ reject();
288
+ }
289
+ if (p.route_path !== undefined &&
290
+ (!providerRoutePath(p.route_path) ||
291
+ p.profile !== "v2.model.generate" ||
292
+ !matching(p.session_id, textID) ||
293
+ p.call_id != null ||
294
+ p.tool_name != null ||
295
+ p.layout !== undefined)) {
296
+ reject();
297
+ }
298
+ if (p.cwd !== undefined &&
299
+ p.cwd !== null &&
300
+ (!str(p.cwd, 4096, true) || p.cwd.includes("\0"))) {
301
+ reject();
302
+ }
303
+ for (const key of ["session_id", "call_id", "tool_name", "model"]) {
304
+ if (p[key] !== undefined && p[key] !== null && !clean(p[key], 512)) {
305
+ reject();
306
+ }
307
+ }
308
+ if (p.layout !== undefined &&
309
+ !list(p.layout, 4096, (item) => {
310
+ const l = object(item, ["role", "kind"]);
311
+ return (member(l.role, ["system", "user", "assistant", "tool"]) &&
312
+ member(l.kind, ["context", "history", "current_prompt"]));
313
+ })) {
314
+ reject();
315
+ }
316
+ if (p.attachments !== undefined) {
317
+ decodeAttachments(p.attachments, p.profile);
318
+ }
319
+ break;
320
+ }
321
+ case "operation.cancel": {
322
+ const p = object(value, ["target"]);
323
+ if (!matching(p.target, id)) {
324
+ reject();
325
+ }
326
+ break;
327
+ }
328
+ case "attachments.configure": {
329
+ const p = object(value, ["file_inspection", "uninspectable_files"]);
330
+ if (!member(p.file_inspection, ["off", "inspect"]) ||
331
+ !member(p.uninspectable_files, ["block", "allow"])) {
332
+ reject();
333
+ }
334
+ break;
335
+ }
336
+ case "attachments.policy":
337
+ case "ping":
338
+ case "shutdown":
339
+ object(value, []);
340
+ break;
341
+ default:
342
+ reject("unknown_method");
343
+ }
344
+ return value;
345
+ }
346
+ export function decodeResult(method, value) {
347
+ switch (method) {
348
+ case "hello": {
349
+ const r = object(value, ["protocol", "epoch", "limits", "features"]);
350
+ const l = object(r.limits, Object.keys(limits));
351
+ if (r.protocol !== 1 ||
352
+ !matching(r.epoch, epoch) ||
353
+ !list(r.features, 32, (v) => matching(v, textID)) ||
354
+ Object.entries(limits).some(([k, v]) => l[k] !== v)) {
355
+ reject();
356
+ }
357
+ break;
358
+ }
359
+ case "connection.validate": {
360
+ const r = object(value, ["valid"], ["code"]);
361
+ if (typeof r.valid !== "boolean" ||
362
+ (r.valid
363
+ ? r.code !== undefined && r.code !== ""
364
+ : !member(r.code, errorCodes))) {
365
+ reject();
366
+ }
367
+ break;
368
+ }
369
+ case "connection.configure": {
370
+ const r = object(value, ["generation"]);
371
+ if (!integer(r.generation)) {
372
+ reject();
373
+ }
374
+ break;
375
+ }
376
+ case "connection.test": {
377
+ const r = object(value, ["connected", "check_code", "decision"]);
378
+ if (typeof r.connected !== "boolean" ||
379
+ !matching(r.check_code, checkCode) ||
380
+ r.connected !== (r.check_code === "success") ||
381
+ !decision(r.decision)) {
382
+ reject();
383
+ }
384
+ break;
385
+ }
386
+ case "route.lease": {
387
+ const r = object(value, ["valid_for_ms"]);
388
+ if (typeof r.valid_for_ms !== "number" ||
389
+ !Number.isSafeInteger(r.valid_for_ms) ||
390
+ r.valid_for_ms < 0 ||
391
+ r.valid_for_ms > 20000) {
392
+ reject();
393
+ }
394
+ break;
395
+ }
396
+ case "operation.check": {
397
+ const r = object(value, [
398
+ "authorization",
399
+ "check_code",
400
+ "decision",
401
+ "reason_code",
402
+ "request_id",
403
+ "operation_id",
404
+ "generation",
405
+ "prepared_json_b64",
406
+ "bindings",
407
+ ], [
408
+ "block_message",
409
+ "attachment_replacements",
410
+ "local_route",
411
+ "route_lease",
412
+ ]);
413
+ if (!member(r.authorization, [
414
+ "allow",
415
+ "transformed",
416
+ "blocked",
417
+ "observed",
418
+ ]) ||
419
+ !matching(r.check_code, checkCode) ||
420
+ !decision(r.decision) ||
421
+ !clean(r.reason_code, 128, true) ||
422
+ (r.block_message !== undefined &&
423
+ (typeof r.block_message !== "string" ||
424
+ new TextEncoder().encode(r.block_message).length > 1024 ||
425
+ [...r.block_message].some(displayUnsafe))) ||
426
+ !matching(r.request_id, textID) ||
427
+ !matching(r.operation_id, textID) ||
428
+ !integer(r.generation) ||
429
+ (r.local_route !== undefined && typeof r.local_route !== "boolean") ||
430
+ (r.route_lease !== undefined &&
431
+ (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(String(r.route_lease)) ||
432
+ r.local_route !== false ||
433
+ (r.authorization !== "allow" && r.authorization !== "transformed")))) {
434
+ reject();
435
+ }
436
+ const seen = new Set();
437
+ if (!list(r.bindings, 4096, (v) => {
438
+ const b = object(v, ["token", "original"]);
439
+ if (!str(b.token, 256) ||
440
+ !str(b.original, maxProjection, true) ||
441
+ seen.has(b.token)) {
442
+ return false;
443
+ }
444
+ seen.add(b.token);
445
+ return true;
446
+ })) {
447
+ reject();
448
+ }
449
+ if (r.attachment_replacements !== undefined) {
450
+ const indexes = new Set();
451
+ if (r.authorization !== "transformed" ||
452
+ !list(r.attachment_replacements, maxAttachments, (v) => {
453
+ const a = object(v, ["index", "data_b64"]);
454
+ if (typeof a.index !== "number" ||
455
+ !Number.isSafeInteger(a.index) ||
456
+ a.index < 0 ||
457
+ a.index >= maxAttachments ||
458
+ !binary(a.data_b64) ||
459
+ a.data_b64.length === 0 ||
460
+ indexes.has(a.index)) {
461
+ return false;
462
+ }
463
+ indexes.add(a.index);
464
+ return true;
465
+ })) {
466
+ reject();
467
+ }
468
+ }
469
+ const count = r.bindings.length;
470
+ if (r.authorization === "blocked" || r.authorization === "observed") {
471
+ if (r.prepared_json_b64 !== null || count !== 0) {
472
+ reject();
473
+ }
474
+ }
475
+ else if (!binary(r.prepared_json_b64) ||
476
+ (r.authorization === "allow" && count !== 0)) {
477
+ reject();
478
+ }
479
+ break;
480
+ }
481
+ case "attachments.policy":
482
+ case "attachments.configure": {
483
+ const r = object(value, [
484
+ "inspect",
485
+ "allow_uninspectable",
486
+ "source",
487
+ "damaged",
488
+ ]);
489
+ if (typeof r.inspect !== "boolean" ||
490
+ typeof r.allow_uninspectable !== "boolean" ||
491
+ typeof r.damaged !== "boolean" ||
492
+ !member(r.source, ["default", "file", "env"])) {
493
+ reject();
494
+ }
495
+ break;
496
+ }
497
+ case "operation.cancel": {
498
+ const r = object(value, ["acknowledged"]);
499
+ if (typeof r.acknowledged !== "boolean") {
500
+ reject();
501
+ }
502
+ break;
503
+ }
504
+ case "ping": {
505
+ const r = object(value, ["ready"]);
506
+ if (typeof r.ready !== "boolean") {
507
+ reject();
508
+ }
509
+ break;
510
+ }
511
+ case "shutdown": {
512
+ const r = object(value, ["accepted"]);
513
+ if (typeof r.accepted !== "boolean") {
514
+ reject();
515
+ }
516
+ break;
517
+ }
518
+ default:
519
+ reject("unknown_method");
520
+ }
521
+ return value;
522
+ }
523
+ export function decodeEnvelope(raw) {
524
+ try {
525
+ const value = strictJSON(raw);
526
+ const base = object(value, ["v", "kind", "id", "epoch"], ["method", "params", "ok", "result", "error"]);
527
+ if (base.v !== 1) {
528
+ reject("unsupported_version");
529
+ }
530
+ if (!matching(base.id, id) ||
531
+ !(base.epoch === "" || matching(base.epoch, epoch))) {
532
+ reject("invalid_envelope");
533
+ }
534
+ if (base.kind === "request") {
535
+ object(base, ["v", "kind", "id", "epoch", "method", "params"]);
536
+ if (!member(base.method, methods)) {
537
+ reject("unknown_method");
538
+ }
539
+ if (base.params === null) {
540
+ reject("invalid_envelope");
541
+ }
542
+ }
543
+ else if (base.kind === "response" && typeof base.ok === "boolean") {
544
+ object(base, [
545
+ "v",
546
+ "kind",
547
+ "id",
548
+ "epoch",
549
+ "ok",
550
+ base.ok ? "result" : "error",
551
+ ]);
552
+ if (base.ok) {
553
+ if (base.result === null) {
554
+ reject("invalid_envelope");
555
+ }
556
+ }
557
+ else {
558
+ const f = object(base.error, ["code"], ["http_status"]);
559
+ if (!member(f.code, errorCodes) ||
560
+ (f.http_status !== undefined &&
561
+ (!integer(f.http_status, 599) || f.http_status < 100))) {
562
+ reject("invalid_envelope");
563
+ }
564
+ }
565
+ }
566
+ else {
567
+ reject("invalid_envelope");
568
+ }
569
+ return value;
570
+ }
571
+ catch (error) {
572
+ if (error instanceof ProtocolError &&
573
+ (error.code === "unsupported_version" || error.code === "unknown_method")) {
574
+ throw error;
575
+ }
576
+ throw new ProtocolError("invalid_envelope");
577
+ }
578
+ }
579
+ // Walk syntax before JSON.parse to reject duplicate decoded keys, malformed
580
+ // Unicode and excessive nesting. Content bytes stay opaque base64 strings.
581
+ export function strictJSON(raw) {
582
+ if (raw.byteLength === 0 || raw.byteLength > maxFrame) {
583
+ reject("invalid_envelope");
584
+ }
585
+ const text = new TextDecoder("utf-8", {
586
+ fatal: true,
587
+ ignoreBOM: true,
588
+ }).decode(raw);
589
+ let pos = 0;
590
+ const ws = () => {
591
+ while (/[ \t\r\n]/.test(text[pos] ?? "x")) {
592
+ pos++;
593
+ }
594
+ };
595
+ const string = () => {
596
+ const start = pos++;
597
+ while (pos < text.length) {
598
+ const c = text[pos++];
599
+ if (c === "\\") {
600
+ pos++;
601
+ continue;
602
+ }
603
+ if (c === '"') {
604
+ const result = JSON.parse(text.slice(start, pos));
605
+ for (let i = 0; i < result.length; i++) {
606
+ const n = result.charCodeAt(i);
607
+ if (n >= 0xd800 && n <= 0xdbff) {
608
+ const next = result.charCodeAt(++i);
609
+ if (!(next >= 0xdc00 && next <= 0xdfff)) {
610
+ reject();
611
+ }
612
+ }
613
+ else if (n >= 0xdc00 && n <= 0xdfff) {
614
+ reject();
615
+ }
616
+ }
617
+ return result;
618
+ }
619
+ }
620
+ return reject();
621
+ };
622
+ const walk = (depth) => {
623
+ ws();
624
+ if (depth > 32) {
625
+ reject();
626
+ }
627
+ const c = text[pos];
628
+ if (c === '"') {
629
+ string();
630
+ return;
631
+ }
632
+ if (c === "{" || c === "[") {
633
+ pos++;
634
+ ws();
635
+ const end = c === "{" ? "}" : "]";
636
+ const keys = new Set();
637
+ if (text[pos] === end) {
638
+ pos++;
639
+ return;
640
+ }
641
+ for (;;) {
642
+ ws();
643
+ if (c === "{") {
644
+ if (text[pos] !== '"') {
645
+ reject();
646
+ }
647
+ const key = string();
648
+ if (keys.has(key)) {
649
+ reject();
650
+ }
651
+ keys.add(key);
652
+ ws();
653
+ if (text[pos++] !== ":") {
654
+ reject();
655
+ }
656
+ }
657
+ walk(depth + 1);
658
+ ws();
659
+ const sep = text[pos++];
660
+ if (sep === end) {
661
+ return;
662
+ }
663
+ if (sep !== ",") {
664
+ reject();
665
+ }
666
+ }
667
+ }
668
+ const match = /^(?:true|false|null|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)/.exec(text.slice(pos));
669
+ if (!match) {
670
+ reject();
671
+ }
672
+ if (/^-?[0-9]/.test(match[0]) && !Number.isSafeInteger(Number(match[0]))) {
673
+ reject();
674
+ }
675
+ pos += match[0].length;
676
+ };
677
+ walk(0);
678
+ ws();
679
+ if (pos !== text.length) {
680
+ reject();
681
+ }
682
+ return JSON.parse(text);
683
+ }