@blen/uspto-mcp-server 0.0.0-stage → 0.1.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.
Files changed (201) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +55 -0
  4. package/README.md +229 -2
  5. package/SECURITY.md +142 -0
  6. package/dist/accounts/app.d.ts +18 -0
  7. package/dist/accounts/app.d.ts.map +1 -0
  8. package/dist/accounts/app.js +407 -0
  9. package/dist/accounts/app.js.map +1 -0
  10. package/dist/accounts/config.d.ts +21 -0
  11. package/dist/accounts/config.d.ts.map +1 -0
  12. package/dist/accounts/config.js +55 -0
  13. package/dist/accounts/config.js.map +1 -0
  14. package/dist/accounts/crypto.d.ts +18 -0
  15. package/dist/accounts/crypto.d.ts.map +1 -0
  16. package/dist/accounts/crypto.js +43 -0
  17. package/dist/accounts/crypto.js.map +1 -0
  18. package/dist/accounts/keyGates.d.ts +19 -0
  19. package/dist/accounts/keyGates.d.ts.map +1 -0
  20. package/dist/accounts/keyGates.js +47 -0
  21. package/dist/accounts/keyGates.js.map +1 -0
  22. package/dist/accounts/paths.d.ts +10 -0
  23. package/dist/accounts/paths.d.ts.map +1 -0
  24. package/dist/accounts/paths.js +10 -0
  25. package/dist/accounts/paths.js.map +1 -0
  26. package/dist/accounts/portal.d.ts +7 -0
  27. package/dist/accounts/portal.d.ts.map +1 -0
  28. package/dist/accounts/portal.js +225 -0
  29. package/dist/accounts/portal.js.map +1 -0
  30. package/dist/accounts/provider.d.ts +2610 -0
  31. package/dist/accounts/provider.d.ts.map +1 -0
  32. package/dist/accounts/provider.js +108 -0
  33. package/dist/accounts/provider.js.map +1 -0
  34. package/dist/accounts/runtime.d.ts +26 -0
  35. package/dist/accounts/runtime.d.ts.map +1 -0
  36. package/dist/accounts/runtime.js +168 -0
  37. package/dist/accounts/runtime.js.map +1 -0
  38. package/dist/accounts/store.d.ts +30 -0
  39. package/dist/accounts/store.d.ts.map +1 -0
  40. package/dist/accounts/store.js +155 -0
  41. package/dist/accounts/store.js.map +1 -0
  42. package/dist/bin.d.ts +3 -0
  43. package/dist/bin.d.ts.map +1 -0
  44. package/dist/bin.js +195 -0
  45. package/dist/bin.js.map +1 -0
  46. package/dist/index.d.ts +11 -0
  47. package/dist/index.d.ts.map +1 -0
  48. package/dist/index.js +8 -0
  49. package/dist/index.js.map +1 -0
  50. package/dist/sandbox/deno.d.ts +35 -0
  51. package/dist/sandbox/deno.d.ts.map +1 -0
  52. package/dist/sandbox/deno.js +373 -0
  53. package/dist/sandbox/deno.js.map +1 -0
  54. package/dist/sandbox/index.d.ts +28 -0
  55. package/dist/sandbox/index.d.ts.map +1 -0
  56. package/dist/sandbox/index.js +55 -0
  57. package/dist/sandbox/index.js.map +1 -0
  58. package/dist/sandbox/isolate.d.ts +17 -0
  59. package/dist/sandbox/isolate.d.ts.map +1 -0
  60. package/dist/sandbox/isolate.js +195 -0
  61. package/dist/sandbox/isolate.js.map +1 -0
  62. package/dist/sandbox/limits.d.ts +60 -0
  63. package/dist/sandbox/limits.d.ts.map +1 -0
  64. package/dist/sandbox/limits.js +86 -0
  65. package/dist/sandbox/limits.js.map +1 -0
  66. package/dist/sandbox/policy.d.ts +7 -0
  67. package/dist/sandbox/policy.d.ts.map +1 -0
  68. package/dist/sandbox/policy.js +87 -0
  69. package/dist/sandbox/policy.js.map +1 -0
  70. package/dist/sandbox/types.d.ts +57 -0
  71. package/dist/sandbox/types.d.ts.map +1 -0
  72. package/dist/sandbox/types.js +6 -0
  73. package/dist/sandbox/types.js.map +1 -0
  74. package/dist/sdk/bindings.d.ts +13 -0
  75. package/dist/sdk/bindings.d.ts.map +1 -0
  76. package/dist/sdk/bindings.js +22 -0
  77. package/dist/sdk/bindings.js.map +1 -0
  78. package/dist/sdk/odp-client.d.ts +167 -0
  79. package/dist/sdk/odp-client.d.ts.map +1 -0
  80. package/dist/sdk/odp-client.js +253 -0
  81. package/dist/sdk/odp-client.js.map +1 -0
  82. package/dist/sdk/runtime.d.ts +21 -0
  83. package/dist/sdk/runtime.d.ts.map +1 -0
  84. package/dist/sdk/runtime.js +32 -0
  85. package/dist/sdk/runtime.js.map +1 -0
  86. package/dist/sdk/sources/corpus-loader.d.ts +8 -0
  87. package/dist/sdk/sources/corpus-loader.d.ts.map +1 -0
  88. package/dist/sdk/sources/corpus-loader.js +17 -0
  89. package/dist/sdk/sources/corpus-loader.js.map +1 -0
  90. package/dist/sdk/sources/index.d.ts +8 -0
  91. package/dist/sdk/sources/index.d.ts.map +1 -0
  92. package/dist/sdk/sources/index.js +25 -0
  93. package/dist/sdk/sources/index.js.map +1 -0
  94. package/dist/sdk/sources/odp.d.ts +5 -0
  95. package/dist/sdk/sources/odp.d.ts.map +1 -0
  96. package/dist/sdk/sources/odp.js +78 -0
  97. package/dist/sdk/sources/odp.js.map +1 -0
  98. package/dist/sdk/sources/source.d.ts +44 -0
  99. package/dist/sdk/sources/source.d.ts.map +1 -0
  100. package/dist/sdk/sources/source.js +3 -0
  101. package/dist/sdk/sources/source.js.map +1 -0
  102. package/dist/sdk/sources/tsdr.d.ts +5 -0
  103. package/dist/sdk/sources/tsdr.d.ts.map +1 -0
  104. package/dist/sdk/sources/tsdr.js +38 -0
  105. package/dist/sdk/sources/tsdr.js.map +1 -0
  106. package/dist/sdk/tsdr-client.d.ts +24 -0
  107. package/dist/sdk/tsdr-client.d.ts.map +1 -0
  108. package/dist/sdk/tsdr-client.js +65 -0
  109. package/dist/sdk/tsdr-client.js.map +1 -0
  110. package/dist/search/bm25.d.ts +25 -0
  111. package/dist/search/bm25.d.ts.map +1 -0
  112. package/dist/search/bm25.js +67 -0
  113. package/dist/search/bm25.js.map +1 -0
  114. package/dist/search/corpus.d.ts +24 -0
  115. package/dist/search/corpus.d.ts.map +1 -0
  116. package/dist/search/corpus.js +23 -0
  117. package/dist/search/corpus.js.map +1 -0
  118. package/dist/server/authz.d.ts +40 -0
  119. package/dist/server/authz.d.ts.map +1 -0
  120. package/dist/server/authz.js +70 -0
  121. package/dist/server/authz.js.map +1 -0
  122. package/dist/server/http.d.ts +44 -0
  123. package/dist/server/http.d.ts.map +1 -0
  124. package/dist/server/http.js +199 -0
  125. package/dist/server/http.js.map +1 -0
  126. package/dist/server/ipRateLimiter.d.ts +22 -0
  127. package/dist/server/ipRateLimiter.d.ts.map +1 -0
  128. package/dist/server/ipRateLimiter.js +58 -0
  129. package/dist/server/ipRateLimiter.js.map +1 -0
  130. package/dist/server/mcpServer.d.ts +22 -0
  131. package/dist/server/mcpServer.d.ts.map +1 -0
  132. package/dist/server/mcpServer.js +90 -0
  133. package/dist/server/mcpServer.js.map +1 -0
  134. package/dist/server/stdio.d.ts +3 -0
  135. package/dist/server/stdio.d.ts.map +1 -0
  136. package/dist/server/stdio.js +16 -0
  137. package/dist/server/stdio.js.map +1 -0
  138. package/dist/server/toolCatalog.d.ts +162 -0
  139. package/dist/server/toolCatalog.d.ts.map +1 -0
  140. package/dist/server/toolCatalog.js +83 -0
  141. package/dist/server/toolCatalog.js.map +1 -0
  142. package/dist/server/wellKnown.d.ts +16 -0
  143. package/dist/server/wellKnown.d.ts.map +1 -0
  144. package/dist/server/wellKnown.js +17 -0
  145. package/dist/server/wellKnown.js.map +1 -0
  146. package/dist/server/zodToJsonSchema.d.ts +8 -0
  147. package/dist/server/zodToJsonSchema.d.ts.map +1 -0
  148. package/dist/server/zodToJsonSchema.js +14 -0
  149. package/dist/server/zodToJsonSchema.js.map +1 -0
  150. package/dist/supervisor/index.d.ts +54 -0
  151. package/dist/supervisor/index.d.ts.map +1 -0
  152. package/dist/supervisor/index.js +62 -0
  153. package/dist/supervisor/index.js.map +1 -0
  154. package/dist/tools/describeSchema.d.ts +23 -0
  155. package/dist/tools/describeSchema.d.ts.map +1 -0
  156. package/dist/tools/describeSchema.js +14 -0
  157. package/dist/tools/describeSchema.js.map +1 -0
  158. package/dist/tools/execute.d.ts +36 -0
  159. package/dist/tools/execute.d.ts.map +1 -0
  160. package/dist/tools/execute.js +70 -0
  161. package/dist/tools/execute.js.map +1 -0
  162. package/dist/tools/searchApi.d.ts +21 -0
  163. package/dist/tools/searchApi.d.ts.map +1 -0
  164. package/dist/tools/searchApi.js +14 -0
  165. package/dist/tools/searchApi.js.map +1 -0
  166. package/dist/util/executionContext.d.ts +6 -0
  167. package/dist/util/executionContext.d.ts.map +1 -0
  168. package/dist/util/executionContext.js +26 -0
  169. package/dist/util/executionContext.js.map +1 -0
  170. package/dist/util/executionLimiter.d.ts +19 -0
  171. package/dist/util/executionLimiter.d.ts.map +1 -0
  172. package/dist/util/executionLimiter.js +41 -0
  173. package/dist/util/executionLimiter.js.map +1 -0
  174. package/dist/util/httpClient.d.ts +116 -0
  175. package/dist/util/httpClient.d.ts.map +1 -0
  176. package/dist/util/httpClient.js +434 -0
  177. package/dist/util/httpClient.js.map +1 -0
  178. package/dist/util/logger.d.ts +7 -0
  179. package/dist/util/logger.d.ts.map +1 -0
  180. package/dist/util/logger.js +25 -0
  181. package/dist/util/logger.js.map +1 -0
  182. package/dist/util/quotas.d.ts +13 -0
  183. package/dist/util/quotas.d.ts.map +1 -0
  184. package/dist/util/quotas.js +29 -0
  185. package/dist/util/quotas.js.map +1 -0
  186. package/dist/util/tokenBucket.d.ts +11 -0
  187. package/dist/util/tokenBucket.d.ts.map +1 -0
  188. package/dist/util/tokenBucket.js +30 -0
  189. package/dist/util/tokenBucket.js.map +1 -0
  190. package/dist/util/upstreamGate.d.ts +36 -0
  191. package/dist/util/upstreamGate.d.ts.map +1 -0
  192. package/dist/util/upstreamGate.js +112 -0
  193. package/dist/util/upstreamGate.js.map +1 -0
  194. package/dist/web/THIRD_PARTY_NOTICES.txt +1940 -0
  195. package/dist/web/assets/blen-logo-BKJFojyj.png +0 -0
  196. package/dist/web/assets/index-Dbbu8lq3.js +317 -0
  197. package/dist/web/assets/index-DkKvyv-b.css +2 -0
  198. package/dist/web/index.html +14 -0
  199. package/package.json +127 -4
  200. package/schema/odp.json +743 -0
  201. package/schema/tsdr.json +129 -0
package/dist/bin.js ADDED
@@ -0,0 +1,195 @@
1
+ #!/usr/bin/env node
2
+ import { startStdio } from './server/stdio.js';
3
+ import { startHttp } from './server/http.js';
4
+ import { buildSupervisor, EXECUTION_DEFAULTS, LIMIT_DEFAULTS } from './supervisor/index.js';
5
+ import { ODP_BASE_URL } from './sdk/sources/odp.js';
6
+ import { TSDR_BASE_URL } from './sdk/sources/tsdr.js';
7
+ import { DEFAULT_MAX_RESPONSE_BYTES } from './util/httpClient.js';
8
+ import { log } from './util/logger.js';
9
+ function parseArgs(argv) {
10
+ const args = {
11
+ http: false,
12
+ port: Number(process.env.PORT ?? 8080),
13
+ host: process.env.HOST ?? '0.0.0.0',
14
+ hostExplicit: Boolean(process.env.HOST),
15
+ sandbox: process.env.USPTO_SANDBOX ?? 'auto',
16
+ insecure: false,
17
+ };
18
+ for (let i = 0; i < argv.length; i++) {
19
+ const a = argv[i];
20
+ if (a === '--http')
21
+ args.http = true;
22
+ else if (a === '--insecure')
23
+ args.insecure = true;
24
+ else if (a === '--port')
25
+ args.port = Number(argv[++i]);
26
+ else if (a === '--host') {
27
+ args.host = String(argv[++i]);
28
+ args.hostExplicit = true;
29
+ }
30
+ else if (a === '--sandbox')
31
+ args.sandbox = argv[++i];
32
+ else if (a === '--help' || a === '-h') {
33
+ printHelp();
34
+ process.exit(0);
35
+ }
36
+ }
37
+ if (!['auto', 'isolate', 'deno'].includes(args.sandbox))
38
+ throw new Error(`Unknown sandbox '${args.sandbox}'. Use auto, isolate or deno.`);
39
+ // An unauthenticated server listens on loopback unless told otherwise.
40
+ if (args.insecure && !args.hostExplicit)
41
+ args.host = '127.0.0.1';
42
+ return args;
43
+ }
44
+ function printHelp() {
45
+ process.stdout.write(`uspto-mcp-server [options]
46
+
47
+ --http Run Streamable HTTP transport (default: stdio)
48
+ --port N HTTP port (default 8080, env PORT)
49
+ --host H HTTP bind host (default 0.0.0.0; 127.0.0.1 with --insecure; env HOST)
50
+ --sandbox auto|isolate|deno
51
+ Sandbox runner (default auto, env USPTO_SANDBOX)
52
+ --insecure HTTP without authentication (local development; binds loopback by default)
53
+ -h, --help Show this help
54
+ `);
55
+ }
56
+ /** A positive number (and at least `min`) from the environment, or `fallback` when unset or invalid. */
57
+ function positive(value, fallback, min = 0) {
58
+ const n = Number(value ?? fallback);
59
+ return Number.isFinite(n) && n > 0 && n >= min ? n : fallback;
60
+ }
61
+ /**
62
+ * A secret from the environment, or undefined when unset, blank, or an unexpanded host
63
+ * placeholder (an MCPB host may pass '${user_config.x}' literally for an optional field left empty).
64
+ */
65
+ function secret(value) {
66
+ const v = value?.trim();
67
+ return v && !/^\$\{[^}]*\}$/.test(v) ? v : undefined;
68
+ }
69
+ /** A non-negative integer from the environment, or `fallback` when unset or invalid. */
70
+ function nonNegativeInt(value, fallback) {
71
+ const n = Number(value ?? fallback);
72
+ return Number.isInteger(n) && n >= 0 ? n : fallback;
73
+ }
74
+ /** A number >= 1 from the environment, or `fallback` when unset or invalid. */
75
+ function atLeastOne(value, fallback) {
76
+ return positive(value, fallback, 1);
77
+ }
78
+ async function main() {
79
+ const args = parseArgs(process.argv.slice(2));
80
+ const accounts = args.http && process.env.USPTO_AUTH_PROVIDER === 'accounts';
81
+ if (accounts && args.insecure)
82
+ throw new Error('Account authentication cannot be combined with --insecure');
83
+ const env = process.env;
84
+ const shutdownController = new AbortController();
85
+ const limits = (name) => {
86
+ const d = LIMIT_DEFAULTS[name];
87
+ const p = `USPTO_${name.toUpperCase()}_`;
88
+ return {
89
+ // 0 is a valid budget ("no calls"), but to disable a source leave its key unset instead.
90
+ maxCallsPerExecute: nonNegativeInt(env[`${p}MAX_CALLS_PER_EXECUTE`], d.maxCallsPerExecute),
91
+ // Require >= 1: a rate of 0 would silently block ALL calls (it is NOT "unlimited").
92
+ ratePerHour: atLeastOne(env[`${p}RATE_PER_HOUR`], d.ratePerHour),
93
+ subjectRatePerHour: atLeastOne(env[`${p}SUBJECT_RATE_PER_HOUR`], d.subjectRatePerHour),
94
+ // USPTO blocks parallel requests on one key; raising this mostly produces 429s.
95
+ concurrency: atLeastOne(env[`${p}CONCURRENCY`], d.concurrency),
96
+ ratePerSec: positive(env[`${p}RATE_PER_SEC`], d.ratePerSec),
97
+ maxWaitMs: atLeastOne(env[`${p}MAX_WAIT_MS`], d.maxWaitMs),
98
+ };
99
+ };
100
+ const cfg = {
101
+ odpBaseUrl: env.USPTO_ODP_BASE_URL ?? ODP_BASE_URL,
102
+ tsdrBaseUrl: env.USPTO_TSDR_BASE_URL ?? TSDR_BASE_URL,
103
+ // Personal keys for stdio and self-hosted single-user HTTP. Account mode never uses them for
104
+ // anyone (USPTO keys must not be shared): signed-in users use only their own saved keys.
105
+ odpApiKey: secret(env.USPTO_API_KEY),
106
+ tsdrApiKey: secret(env.USPTO_TSDR_API_KEY),
107
+ userAgent: env.USPTO_USER_AGENT ?? 'uspto-mcp-server/0.1 (+https://github.com/blen-labs/uspto-mcp-server)',
108
+ upstreamTimeoutMs: atLeastOne(env.USPTO_UPSTREAM_TIMEOUT_MS, 30_000),
109
+ upstreamRetries: nonNegativeInt(env.USPTO_UPSTREAM_RETRIES, 2),
110
+ cacheTtlMs: nonNegativeInt(env.USPTO_CACHE_TTL_MS, 600_000),
111
+ cacheMaxItems: nonNegativeInt(env.USPTO_CACHE_MAX_ITEMS, 1000),
112
+ maxResponseBytes: atLeastOne(env.USPTO_MAX_RESPONSE_BYTES, DEFAULT_MAX_RESPONSE_BYTES),
113
+ sandbox: args.sandbox,
114
+ // Authenticated HTTP serves many users: user code must run out of process (Deno only).
115
+ processIsolation: args.http && !args.insecure,
116
+ limits: { odp: limits('odp'), tsdr: limits('tsdr') },
117
+ maxConcurrentExecutions: atLeastOne(env.USPTO_MAX_CONCURRENT_EXECUTIONS, EXECUTION_DEFAULTS.maxConcurrent),
118
+ maxExecutionsPerSubject: atLeastOne(env.USPTO_MAX_EXECUTIONS_PER_SUBJECT, EXECUTION_DEFAULTS.perSubject),
119
+ shutdownSignal: shutdownController.signal,
120
+ };
121
+ const deps = await buildSupervisor(cfg);
122
+ // Base --http with real auth serves every token holder through the process keys. USPTO keys are
123
+ // personal, so that mode is for one owner (yourself behind your own IdP); multi-user hosting
124
+ // must use USPTO_AUTH_PROVIDER=accounts, where each user brings their own key.
125
+ if (args.http && !accounts && !args.insecure && (cfg.odpApiKey || cfg.tsdrApiKey)) {
126
+ log.warn('http.personal_keys_shared', { note: 'USPTO keys are personal: every authenticated caller uses this server\'s keys. Use USPTO_AUTH_PROVIDER=accounts for multiple users.' });
127
+ }
128
+ let handle;
129
+ if (accounts) {
130
+ const { loadAccountConfig } = await import('./accounts/config.js');
131
+ const { startAccountHttp } = await import('./accounts/runtime.js');
132
+ handle = await startAccountHttp(deps, cfg, loadAccountConfig(process.env), args.port, args.host);
133
+ }
134
+ else if (args.http) {
135
+ const allowedOrigins = process.env.USPTO_ALLOWED_ORIGINS
136
+ ? process.env.USPTO_ALLOWED_ORIGINS.split(',').map(s => s.trim().toLowerCase()).filter(Boolean)
137
+ : undefined;
138
+ const allowedHosts = process.env.USPTO_ALLOWED_HOSTS
139
+ ? process.env.USPTO_ALLOWED_HOSTS.split(',').map(s => s.trim().toLowerCase()).filter(Boolean)
140
+ : undefined;
141
+ handle = await startHttp(deps, {
142
+ port: args.port,
143
+ host: args.host,
144
+ // rps must be > 0 (a NaN or non-positive rate makes the bucket arithmetic meaningless);
145
+ // burst must be >= 1, since a bucket that can never hold a whole token rejects everything.
146
+ rps: positive(process.env.USPTO_IP_RPS, 5),
147
+ burst: positive(process.env.USPTO_IP_BURST, 20, 1),
148
+ clientIpHeader: (() => {
149
+ const name = process.env.USPTO_CLIENT_IP_HEADER?.trim().toLowerCase();
150
+ if (!name)
151
+ return undefined;
152
+ if (/^[a-z0-9-]+$/.test(name))
153
+ return name;
154
+ log.warn('config.invalid_client_ip_header', { header: name });
155
+ return undefined;
156
+ })(),
157
+ // An empty or invalid value falls back to the default (Number('') is 0, which would allow one request a day).
158
+ subjectDailyQuota: atLeastOne(process.env.USPTO_SUBJECT_DAILY_QUOTA, 10_000),
159
+ insecure: args.insecure,
160
+ allowedHosts,
161
+ allowedOrigins,
162
+ publicOrigin: process.env.USPTO_PUBLIC_ORIGIN,
163
+ auth: {
164
+ provider: (process.env.USPTO_AUTH_PROVIDER ?? 'none'),
165
+ issuer: process.env.USPTO_AUTH_ISSUER,
166
+ audience: process.env.USPTO_AUTH_AUDIENCE,
167
+ jwksUrl: process.env.USPTO_AUTH_JWKS_URL,
168
+ scopes: process.env.USPTO_AUTH_SCOPES?.split(',').map(s => s.trim()).filter(Boolean),
169
+ },
170
+ });
171
+ }
172
+ else {
173
+ await startStdio(deps);
174
+ }
175
+ // Graceful shutdown (Railway sends SIGTERM, K8s sends SIGTERM, Ctrl-C sends SIGINT)
176
+ const shutdown = async (signal) => {
177
+ log.info('shutdown.start', { signal });
178
+ shutdownController.abort();
179
+ try {
180
+ if (handle)
181
+ await handle.close();
182
+ }
183
+ catch (err) {
184
+ log.warn('shutdown.error', { error: err.message });
185
+ }
186
+ process.exit(0);
187
+ };
188
+ process.on('SIGTERM', () => void shutdown('SIGTERM'));
189
+ process.on('SIGINT', () => void shutdown('SIGINT'));
190
+ }
191
+ main().catch(err => {
192
+ log.error('bin.fatal', { error: err.message, stack: err.stack });
193
+ process.exit(1);
194
+ });
195
+ //# sourceMappingURL=bin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin.js","sourceRoot":"","sources":["../src/bin.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAmB,MAAM,kBAAkB,CAAC;AAC9D,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,cAAc,EAA2C,MAAM,uBAAuB,CAAC;AACrI,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEtD,OAAO,E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,CAAC;AACtD,CAAC;AAGD,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE;IACjB,GAAG,CAAC,KAAK,CAAC,WAAW,EAAE,EAAE,KAAK,EAAG,GAAa,CAAC,OAAO,EAAE,KAAK,EAAG,GAAa,CAAC,KAAK,EAAE,CAAC,CAAC;IACvF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC"}
@@ -0,0 +1,11 @@
1
+ export { buildMcpServer } from './server/mcpServer.js';
2
+ export { startStdio } from './server/stdio.js';
3
+ export { startHttp } from './server/http.js';
4
+ export { buildSupervisor } from './supervisor/index.js';
5
+ export { buildSdk } from './sdk/bindings.js';
6
+ export { pickSandbox } from './sandbox/index.js';
7
+ export { buildVerifier } from './server/authz.js';
8
+ export type { Sdk } from './sdk/bindings.js';
9
+ export type { SandboxKind, SandboxRunner, ExecuteOptions, ExecuteResult } from './sandbox/types.js';
10
+ export type { AuthConfig, AuthContext, Verifier } from './server/authz.js';
11
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,YAAY,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAC7C,YAAY,EAAE,WAAW,EAAE,aAAa,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACpG,YAAY,EAAE,UAAU,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ export { buildMcpServer } from './server/mcpServer.js';
2
+ export { startStdio } from './server/stdio.js';
3
+ export { startHttp } from './server/http.js';
4
+ export { buildSupervisor } from './supervisor/index.js';
5
+ export { buildSdk } from './sdk/bindings.js';
6
+ export { pickSandbox } from './sandbox/index.js';
7
+ export { buildVerifier } from './server/authz.js';
8
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC"}
@@ -0,0 +1,35 @@
1
+ import { type ExecuteOptions, type ExecuteResult, type RpcBridge, type SandboxRunner } from './types.js';
2
+ import { type SandboxLimits } from './limits.js';
3
+ /**
4
+ * Deno sandbox.
5
+ *
6
+ * Boundary: Node host (owns the deadline, byte budgets, and the child's lifetime)
7
+ * → `deno run` of a fixed supervisor script with NO --allow-* flags (deny-by-default: no net, fs,
8
+ * env, ffi, subprocess), a minimal environment, and no user code on disk
9
+ * → a module Worker that receives the user code by message. Before user code runs, the worker's
10
+ * ambient globals that could reach the process or the protocol (`Deno`, `postMessage`, `fetch`,
11
+ * `Worker`, ...) are replaced with `undefined` and `console` is redirected to log messages.
12
+ *
13
+ * Protocol: the supervisor talks to the host over stdin/stdout with one JSON frame per line,
14
+ * prefixed by a random token the supervisor generates and announces before the worker exists.
15
+ * The worker never sees the token, so it cannot forge frames; any other stdout bytes are treated
16
+ * as untrusted log text. All child output is untrusted: frames are size-bounded and validated, the
17
+ * execution settles exactly once, and the process group is killed on every exit path. A frame can
18
+ * never cancel the host's deadline or its cleanup.
19
+ */
20
+ export declare class DenoRunner implements SandboxRunner {
21
+ private readonly limits;
22
+ kind: 'deno';
23
+ private static supervisorPath?;
24
+ constructor(limits?: SandboxLimits);
25
+ available(): Promise<boolean>;
26
+ /** The supervisor holds no user data; it is written once per process, readable only by us. */
27
+ private static supervisor;
28
+ execute(opts: ExecuteOptions, rpc: RpcBridge): Promise<ExecuteResult>;
29
+ }
30
+ /**
31
+ * Runs in Deno with no permissions. Holds no user data until the start frame arrives over stdin.
32
+ * Binding names come from the host (pre-validated identifiers) and are only used as object keys.
33
+ */
34
+ export declare const SUPERVISOR_SOURCE: string;
35
+ //# sourceMappingURL=deno.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deno.d.ts","sourceRoot":"","sources":["../../src/sandbox/deno.ts"],"names":[],"mappings":"AAIA,OAAO,EAAY,KAAK,cAAc,EAAE,KAAK,aAAa,EAAE,KAAK,SAAS,EAAE,KAAK,aAAa,EAAE,MAAM,YAAY,CAAC;AAGnH,OAAO,EAAwJ,KAAK,aAAa,EAAE,MAAM,aAAa,CAAC;AAEvM;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,UAAW,YAAW,aAAa;IAIlC,OAAO,CAAC,QAAQ,CAAC,MAAM;IAHnC,IAAI,EAAG,MAAM,CAAU;IACvB,OAAO,CAAC,MAAM,CAAC,cAAc,CAAC,CAAS;IAEvC,YAA6B,MAAM,GAAE,aAA8B,EAAI;IAEjE,SAAS,IAAI,OAAO,CAAC,OAAO,CAAC,CAMlC;IAED,8FAA8F;IAC9F,OAAO,CAAC,MAAM,CAAC,UAAU;IAYnB,OAAO,CAAC,IAAI,EAAE,cAAc,EAAE,GAAG,EAAE,SAAS,GAAG,OAAO,CAAC,aAAa,CAAC,CA8I1E;CACF;AAqBD;;;GAGG;AACH,eAAO,MAAM,iBAAiB,QA8H7B,CAAC"}
@@ -0,0 +1,373 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { mkdtempSync, rmSync, writeFileSync, chmodSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { TEARDOWN } from './types.js';
6
+ import { log } from '../util/logger.js';
7
+ import { preflight } from './policy.js';
8
+ import { DEFAULT_LIMITS, LOG_LINE_OVERHEAD, LOG_TRUNCATED, LogSink, MAX_ERROR_MESSAGE, boundMessage, checkRpcArgs, finishValue, policyMessage, resultTooLarge } from './limits.js';
9
+ /**
10
+ * Deno sandbox.
11
+ *
12
+ * Boundary: Node host (owns the deadline, byte budgets, and the child's lifetime)
13
+ * → `deno run` of a fixed supervisor script with NO --allow-* flags (deny-by-default: no net, fs,
14
+ * env, ffi, subprocess), a minimal environment, and no user code on disk
15
+ * → a module Worker that receives the user code by message. Before user code runs, the worker's
16
+ * ambient globals that could reach the process or the protocol (`Deno`, `postMessage`, `fetch`,
17
+ * `Worker`, ...) are replaced with `undefined` and `console` is redirected to log messages.
18
+ *
19
+ * Protocol: the supervisor talks to the host over stdin/stdout with one JSON frame per line,
20
+ * prefixed by a random token the supervisor generates and announces before the worker exists.
21
+ * The worker never sees the token, so it cannot forge frames; any other stdout bytes are treated
22
+ * as untrusted log text. All child output is untrusted: frames are size-bounded and validated, the
23
+ * execution settles exactly once, and the process group is killed on every exit path. A frame can
24
+ * never cancel the host's deadline or its cleanup.
25
+ */
26
+ export class DenoRunner {
27
+ limits;
28
+ kind = 'deno';
29
+ static supervisorPath;
30
+ constructor(limits = DEFAULT_LIMITS) {
31
+ this.limits = limits;
32
+ }
33
+ async available() {
34
+ return await new Promise(resolve => {
35
+ const p = spawn('deno', ['--version'], { stdio: 'ignore', env: childEnv() });
36
+ p.on('error', () => resolve(false));
37
+ p.on('exit', code => resolve(code === 0));
38
+ });
39
+ }
40
+ /** The supervisor holds no user data; it is written once per process, readable only by us. */
41
+ static supervisor() {
42
+ if (!DenoRunner.supervisorPath) {
43
+ const dir = mkdtempSync(join(tmpdir(), 'uspto-deno-'));
44
+ chmodSync(dir, 0o700);
45
+ const path = join(dir, 'supervisor.js');
46
+ writeFileSync(path, SUPERVISOR_SOURCE, { mode: 0o600 });
47
+ DenoRunner.supervisorPath = path;
48
+ process.once('exit', () => { try {
49
+ rmSync(dir, { recursive: true, force: true });
50
+ }
51
+ catch { /* ignore */ } });
52
+ }
53
+ return DenoRunner.supervisorPath;
54
+ }
55
+ async execute(opts, rpc) {
56
+ const started = Date.now();
57
+ const limits = { ...this.limits, ...(opts.limits ?? {}) };
58
+ const timeoutMs = opts.timeoutMs ?? 15_000;
59
+ const fail = (name, message, logs = []) => ({ ok: false, logs, error: { name, message }, durationMs: Date.now() - started });
60
+ const policy = preflight(opts.code);
61
+ if (!policy.ok)
62
+ return fail('PolicyError', policyMessage(policy.errors));
63
+ if (Buffer.byteLength(opts.code, 'utf8') > limits.maxCodeBytes)
64
+ return fail('CodeTooLarge', `Code exceeds ${limits.maxCodeBytes} bytes.`);
65
+ let child;
66
+ try {
67
+ child = spawn('deno', [
68
+ 'run', '--no-prompt', '--no-config', '--no-lock', '--no-remote', '--no-npm', '--quiet',
69
+ `--v8-flags=--max-old-space-size=${Math.max(16, opts.memoryMb ?? 64)}`,
70
+ DenoRunner.supervisor(),
71
+ ], { stdio: ['pipe', 'pipe', 'pipe'], env: childEnv(), detached: process.platform !== 'win32' });
72
+ }
73
+ catch (err) {
74
+ return fail('SpawnError', err.message);
75
+ }
76
+ const logs = new LogSink(limits.maxLogBytes, limits.maxLogLines);
77
+ const signal = opts.signal;
78
+ return await new Promise(resolve => {
79
+ let settled = false;
80
+ let token;
81
+ let buffered = '';
82
+ let bufferedBytes = 0;
83
+ let pendingRpc = 0;
84
+ // Choosing the outcome and tearing down are separate: the first terminal event fixes the
85
+ // result, and the promise resolves only once the child has exited (bounded wait), so the
86
+ // execution slot is never released while its process is still alive.
87
+ let exited = false;
88
+ const exitWaiters = [];
89
+ child.once('close', () => { exited = true; for (const w of exitWaiters.splice(0))
90
+ w(); });
91
+ const settle = (result) => {
92
+ if (settled)
93
+ return;
94
+ settled = true;
95
+ clearTimeout(deadline);
96
+ signal?.removeEventListener('abort', onAbort);
97
+ const outcome = { ...result, logs: logs.lines(), durationMs: Date.now() - started };
98
+ killTree(child);
99
+ if (exited)
100
+ return resolve(outcome);
101
+ // Normally the child exits within milliseconds of the kill. If it has not after 2 s, return
102
+ // the result anyway, but keep its capacity quarantined (TEARDOWN) until exit is confirmed.
103
+ const gone = new Promise(r => exitWaiters.push(r));
104
+ const giveUp = setTimeout(() => {
105
+ log.error('sandbox.teardown_pending', { pid: child.pid, note: 'execution slot held until the sandbox process exits' });
106
+ killTree(child);
107
+ resolve(Object.defineProperty(outcome, TEARDOWN, { value: gone, enumerable: false }));
108
+ }, 2000);
109
+ void gone.then(() => { clearTimeout(giveUp); resolve(outcome); });
110
+ };
111
+ const onAbort = () => settle({ ok: false, error: { name: 'AbortError', message: 'Execution was cancelled.' } });
112
+ const deadline = setTimeout(() => settle({ ok: false, error: { name: 'TimeoutError', message: `Execution exceeded ${timeoutMs}ms` } }), timeoutMs);
113
+ child.on('error', err => settle({ ok: false, error: { name: 'SpawnError', message: err.message } }));
114
+ child.on('exit', code => settle({ ok: false, error: { name: 'ExitError', message: `The sandbox exited unexpectedly (code ${code}).` } }));
115
+ if (signal?.aborted)
116
+ return onAbort();
117
+ signal?.addEventListener('abort', onAbort, { once: true });
118
+ const send = (frame) => {
119
+ if (settled || !token)
120
+ return;
121
+ try {
122
+ child.stdin.write(`${token}${JSON.stringify(frame)}\n`);
123
+ }
124
+ catch { /* child gone; exit handler settles */ }
125
+ };
126
+ const onFrame = async (raw) => {
127
+ let msg;
128
+ try {
129
+ msg = JSON.parse(raw);
130
+ }
131
+ catch {
132
+ return settle({ ok: false, error: { name: 'SandboxProtocolError', message: 'The sandbox sent a malformed frame.' } });
133
+ }
134
+ if (msg.t === 'log' && typeof msg.text === 'string')
135
+ return logs.push(msg.text);
136
+ if (msg.t === 'rpc' && Number.isSafeInteger(msg.id) && typeof msg.binding === 'string'
137
+ && Array.isArray(msg.path) && Array.isArray(msg.args)) {
138
+ if (pendingRpc >= limits.maxPendingRpc) {
139
+ return send({ t: 'rpc-result', id: msg.id, ok: false, error: { name: 'TooManyPendingCalls', message: `At most ${limits.maxPendingRpc} SDK calls may be pending at once.` } });
140
+ }
141
+ const tooBig = checkRpcArgs(msg.args, limits);
142
+ if (tooBig)
143
+ return send({ t: 'rpc-result', id: msg.id, ok: false, error: tooBig });
144
+ pendingRpc++;
145
+ try {
146
+ const res = await rpc.dispatch({ binding: msg.binding, path: msg.path, args: msg.args }, { signal });
147
+ send({ t: 'rpc-result', id: msg.id, ok: res.ok, value: res.value, error: res.error });
148
+ }
149
+ finally {
150
+ pendingRpc--;
151
+ }
152
+ return;
153
+ }
154
+ if (msg.t === 'done') {
155
+ if (msg.ok === true && typeof msg.json === 'string')
156
+ return settle(finishValue(msg.json, limits));
157
+ if (msg.tooLarge === true && typeof msg.size === 'number')
158
+ return settle({ ok: false, error: resultTooLarge(msg.size, limits) });
159
+ const e = (msg.error ?? {});
160
+ return settle({
161
+ ok: false,
162
+ error: {
163
+ name: typeof e.name === 'string' ? e.name.slice(0, 100) : 'Error',
164
+ message: typeof e.message === 'string' ? boundMessage(e.message) : 'Execution failed',
165
+ ...(typeof e.status === 'number' ? { status: e.status } : {}),
166
+ },
167
+ });
168
+ }
169
+ return settle({ ok: false, error: { name: 'SandboxProtocolError', message: 'The sandbox sent an unexpected frame.' } });
170
+ };
171
+ child.stdout.setEncoding('utf8');
172
+ child.stdout.on('data', (chunk) => {
173
+ if (settled)
174
+ return;
175
+ bufferedBytes += Buffer.byteLength(chunk, 'utf8');
176
+ if (bufferedBytes > limits.maxStdoutBytes) {
177
+ return settle({ ok: false, error: { name: 'OutputTooLarge', message: `The sandbox produced more than ${limits.maxStdoutBytes} bytes of output.` } });
178
+ }
179
+ buffered += chunk;
180
+ let nl;
181
+ while (!settled && (nl = buffered.indexOf('\n')) >= 0) {
182
+ const line = buffered.slice(0, nl);
183
+ buffered = buffered.slice(nl + 1);
184
+ if (!token) {
185
+ // The supervisor's first line announces the frame token; nothing else may precede it.
186
+ const m = /^USPTO-SANDBOX ([0-9a-f]{64})$/.exec(line);
187
+ if (!m)
188
+ return settle({ ok: false, error: { name: 'SandboxProtocolError', message: 'The sandbox did not start correctly.' } });
189
+ token = m[1];
190
+ send({ t: 'start', code: opts.code, bindings: opts.bindings ?? [], limits: {
191
+ maxLogBytes: limits.maxLogBytes, maxLogLines: limits.maxLogLines, logLineOverhead: LOG_LINE_OVERHEAD,
192
+ logTruncated: LOG_TRUNCATED, maxRpcArgBytes: limits.maxRpcArgBytes, maxResultBytes: limits.maxResultBytes,
193
+ maxError: MAX_ERROR_MESSAGE,
194
+ } });
195
+ continue;
196
+ }
197
+ if (line.startsWith(token))
198
+ void onFrame(line.slice(token.length));
199
+ else if (line.length)
200
+ logs.push(line);
201
+ }
202
+ if (buffered.length > limits.maxFrameBytes) {
203
+ settle({ ok: false, error: { name: 'OutputTooLarge', message: `A sandbox message exceeded ${limits.maxFrameBytes} bytes.` } });
204
+ }
205
+ });
206
+ child.stderr.setEncoding('utf8');
207
+ child.stderr.on('data', (chunk) => { if (!settled)
208
+ logs.push(chunk.trimEnd()); });
209
+ child.stdin.on('error', () => { });
210
+ });
211
+ }
212
+ }
213
+ /** Only what Deno needs to start; never the server's secrets. */
214
+ function childEnv() {
215
+ const env = { NO_COLOR: '1', DENO_NO_UPDATE_CHECK: '1', DENO_NO_PROMPT: '1' };
216
+ for (const k of ['PATH', 'HOME', 'DENO_DIR', 'TMPDIR', 'SystemRoot', 'USERPROFILE', 'LOCALAPPDATA']) {
217
+ if (process.env[k])
218
+ env[k] = process.env[k];
219
+ }
220
+ return env;
221
+ }
222
+ /** Kill the child and anything it started. POSIX: the whole process group. */
223
+ function killTree(child) {
224
+ try {
225
+ child.stdin.destroy();
226
+ }
227
+ catch { /* ignore */ }
228
+ if (child.exitCode !== null || child.signalCode !== null)
229
+ return;
230
+ if (process.platform !== 'win32' && child.pid) {
231
+ try {
232
+ process.kill(-child.pid, 'SIGKILL');
233
+ return;
234
+ }
235
+ catch { /* fall through */ }
236
+ }
237
+ try {
238
+ child.kill('SIGKILL');
239
+ }
240
+ catch { /* ignore */ }
241
+ }
242
+ /**
243
+ * Runs in Deno with no permissions. Holds no user data until the start frame arrives over stdin.
244
+ * Binding names come from the host (pre-validated identifiers) and are only used as object keys.
245
+ */
246
+ export const SUPERVISOR_SOURCE = String.raw `
247
+ const enc = new TextEncoder();
248
+ const bytes = new Uint8Array(32);
249
+ crypto.getRandomValues(bytes);
250
+ const TOKEN = Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
251
+ const writeLine = (s) => { const b = enc.encode(s + '\n'); let o = 0; while (o < b.length) o += Deno.stdout.writeSync(b.subarray(o)); };
252
+ const frame = (obj) => writeLine(TOKEN + JSON.stringify(obj));
253
+ writeLine('USPTO-SANDBOX ' + TOKEN);
254
+
255
+ const WORKER_SOURCE = ${'`'}
256
+ // Trusted primitives, captured before user code exists: budgets below use these, so user code that
257
+ // replaces JSON.stringify, TextEncoder or Promise.prototype.then cannot push oversized data out.
258
+ const post = self.postMessage.bind(self);
259
+ const listen = self.addEventListener.bind(self);
260
+ const S = JSON.stringify, P = JSON.parse, Str = String, apply = Reflect.apply, then = Promise.prototype.then;
261
+ const encoder = new TextEncoder(), encode = TextEncoder.prototype.encode, sl = String.prototype.slice;
262
+ // The intrinsic %TypedArray%.prototype.byteLength getter, captured: user code may redefine
263
+ // Uint8Array.prototype.length, but cannot change a getter we already hold.
264
+ const byteLength = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), 'byteLength').get;
265
+ const bytes = (s) => apply(byteLength, apply(encode, encoder, [s]), []);
266
+ const cut = (s, n) => s.length > n ? apply(sl, s, [0, n]) : s;
267
+ let started = false;
268
+ const pending = new Map();
269
+ let nextId = 1;
270
+ listen('message', (ev) => {
271
+ const m = ev.data;
272
+ if (m && m.t === 'rpc-result') {
273
+ const p = pending.get(m.id);
274
+ if (!p) return;
275
+ pending.delete(m.id);
276
+ if (m.ok) p.resolve(m.value);
277
+ else { const e = new Error(String(m.error?.message ?? 'SDK call failed')); e.name = String(m.error?.name ?? 'Error'); if (typeof m.error?.status === 'number') e.status = m.error.status; p.reject(e); }
278
+ return;
279
+ }
280
+ if (!m || m.t !== 'start' || started) return;
281
+ started = true;
282
+ run(String(m.code), Array.isArray(m.bindings) ? m.bindings.map(String) : [], m.limits || {});
283
+ });
284
+ let L = {};
285
+ function call(binding, path, args) {
286
+ return new Promise((resolve, reject) => {
287
+ let json;
288
+ try { json = S(args ?? []); } catch (e) { reject(new TypeError('SDK arguments must be JSON-serializable')); return; }
289
+ if (typeof json !== 'string' || bytes(json) > L.maxRpcArgBytes) { const e = new Error('SDK call arguments exceed ' + L.maxRpcArgBytes + ' bytes.'); e.name = 'ArgumentsTooLarge'; reject(e); return; }
290
+ const id = nextId++;
291
+ pending.set(id, { resolve, reject });
292
+ post({ t: 'rpc', id, binding, path, args: P(json) });
293
+ });
294
+ }
295
+ function makeProxy(binding) {
296
+ const handler = (path) => new Proxy(function () {}, {
297
+ get(_, key) { return typeof key === 'symbol' ? undefined : handler([...path, String(key)]); },
298
+ apply(_, __, args) { return call(binding, path, args); },
299
+ });
300
+ return handler([]);
301
+ }
302
+ function run(code, bindings, limits) {
303
+ L = limits;
304
+ const show = (v) => { if (typeof v === 'string') return v; try { const j = S(v); return j === undefined ? Str(v) : j; } catch { return Str(v); } };
305
+ let logBytes = 0, logLines = 0, logDone = false;
306
+ const log = (...a) => {
307
+ if (logDone) return;
308
+ let text = '';
309
+ for (let i = 0; i < a.length; i++) text += (i ? ' ' : '') + show(a[i]);
310
+ text = cut(text, L.maxLogBytes);
311
+ logBytes += bytes(text) + L.logLineOverhead; logLines++;
312
+ if (logBytes > L.maxLogBytes - L.logTruncated.length - L.logLineOverhead || logLines >= L.maxLogLines) { logDone = true; text = L.logTruncated; }
313
+ post({ t: 'log', text });
314
+ };
315
+ self.console = { log, info: log, warn: log, error: log, debug: log };
316
+ for (const k of ['Deno', 'postMessage', 'close', 'fetch', 'WebSocket', 'WebSocketStream', 'Worker', 'EventSource',
317
+ 'navigator', 'caches', 'localStorage', 'sessionStorage', 'importScripts', 'BroadcastChannel']) {
318
+ try { Object.defineProperty(self, k, { value: undefined, writable: false, configurable: false }); } catch {}
319
+ }
320
+ for (const name of bindings) {
321
+ try { Object.defineProperty(self, name, { value: makeProxy(name), writable: false, configurable: false }); } catch {}
322
+ }
323
+ let fn;
324
+ try { fn = new Function('"use strict"; return (async () => {\\n' + code + '\\n})();'); }
325
+ catch (e) { post({ t: 'done', ok: false, error: { name: Str(e?.name ?? 'SyntaxError'), message: cut(Str(e?.message ?? e), L.maxError) } }); return; }
326
+ const fail = (e) => {
327
+ let name = 'Error', message = '', status;
328
+ try { name = cut(Str(e?.name ?? 'Error'), 100); message = cut(Str(e?.message !== undefined ? e.message : e), L.maxError); status = typeof e?.status === 'number' ? e.status : undefined; } catch {}
329
+ post({ t: 'done', ok: false, error: { name, message, ...(status === undefined ? {} : { status }) } });
330
+ };
331
+ const done = (value) => {
332
+ let json;
333
+ try { json = S(value === undefined ? null : value); } catch (e) { fail({ name: 'TypeError', message: 'The returned value is not JSON-serializable' }); return; }
334
+ if (typeof json !== 'string') json = 'null';
335
+ const size = bytes(json);
336
+ if (size > L.maxResultBytes) post({ t: 'done', ok: false, tooLarge: true, size });
337
+ else post({ t: 'done', ok: true, json });
338
+ };
339
+ let started;
340
+ try { started = fn(); } catch (e) { fail(e); return; }
341
+ apply(then, started, [done, fail]);
342
+ }
343
+ ${'`'};
344
+
345
+ const url = URL.createObjectURL(new Blob([WORKER_SOURCE], { type: 'application/javascript' }));
346
+ const worker = new Worker(url, { type: 'module' });
347
+ worker.onmessage = (ev) => {
348
+ const m = ev.data;
349
+ if (!m || typeof m !== 'object') return;
350
+ if (m.t === 'log') frame({ t: 'log', text: String(m.text).slice(0, 65536) });
351
+ else if (m.t === 'rpc') frame({ t: 'rpc', id: m.id, binding: m.binding, path: m.path, args: m.args });
352
+ else if (m.t === 'done') frame({ t: 'done', ok: m.ok === true, json: m.json, error: m.error, tooLarge: m.tooLarge === true, size: m.size });
353
+ };
354
+ worker.onerror = (e) => { e.preventDefault(); frame({ t: 'done', ok: false, error: { name: 'Error', message: String(e.message ?? 'Worker error') } }); };
355
+
356
+ // Host → supervisor: token-prefixed JSON lines on stdin.
357
+ const dec = new TextDecoder();
358
+ let buf = '';
359
+ for await (const chunk of Deno.stdin.readable) {
360
+ buf += dec.decode(chunk, { stream: true });
361
+ let nl;
362
+ while ((nl = buf.indexOf('\n')) >= 0) {
363
+ const line = buf.slice(0, nl);
364
+ buf = buf.slice(nl + 1);
365
+ if (!line.startsWith(TOKEN)) continue;
366
+ let msg;
367
+ try { msg = JSON.parse(line.slice(TOKEN.length)); } catch { continue; }
368
+ if (msg.t === 'start') worker.postMessage({ t: 'start', code: msg.code, bindings: msg.bindings, limits: msg.limits });
369
+ else if (msg.t === 'rpc-result') worker.postMessage(msg);
370
+ }
371
+ }
372
+ `;
373
+ //# sourceMappingURL=deno.js.map