@cortexkit/common-auth 0.26.0 → 0.27.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 (43) hide show
  1. package/README.md +0 -16
  2. package/dist/claustrum/consumer.d.ts +77 -2
  3. package/dist/claustrum/consumer.js +320 -35
  4. package/dist/claustrum/custody.d.ts +36 -1
  5. package/dist/claustrum/custody.js +95 -11
  6. package/dist/claustrum/enrollment.js +37 -12
  7. package/dist/claustrum/hub.d.ts +195 -0
  8. package/dist/claustrum/hub.js +988 -0
  9. package/dist/claustrum/index.d.ts +13 -3
  10. package/dist/claustrum/index.js +37 -4
  11. package/dist/claustrum/quota-writer.d.ts +8 -1
  12. package/dist/claustrum/quota-writer.js +34 -12
  13. package/dist/claustrum/roster.d.ts +49 -1
  14. package/dist/claustrum/roster.js +187 -12
  15. package/dist/claustrum/shutdown.d.ts +8 -0
  16. package/dist/claustrum/shutdown.js +42 -0
  17. package/dist/fs/file-read-cache.d.ts +8 -0
  18. package/dist/fs/file-read-cache.js +57 -0
  19. package/dist/fs/refresh-file-lock.d.ts +1 -1
  20. package/dist/fs/refresh-file-lock.js +20 -11
  21. package/dist/opencode2/errors.d.ts +4 -1
  22. package/dist/opencode2/index.d.ts +2 -2
  23. package/dist/opencode2/index.js +1 -1
  24. package/dist/opencode2/install.d.ts +7 -5
  25. package/dist/opencode2/install.js +139 -13
  26. package/dist/opencode2/types.d.ts +42 -10
  27. package/dist/quota/commit-interval.d.ts +9 -0
  28. package/dist/quota/commit-interval.js +18 -0
  29. package/dist/redaction/index.d.ts +8 -0
  30. package/dist/redaction/index.js +490 -0
  31. package/dist/rpc/rpc-server.js +29 -19
  32. package/dist/setup/command.js +52 -14
  33. package/dist/setup/register.d.ts +2 -0
  34. package/dist/setup/register.js +90 -11
  35. package/dist/store/mutate.d.ts +2 -0
  36. package/dist/store/mutate.js +4 -0
  37. package/dist/store/pool.d.ts +6 -1
  38. package/dist/store/pool.js +1 -1
  39. package/dist/store/quota-writer.d.ts +5 -1
  40. package/dist/store/quota-writer.js +27 -13
  41. package/dist/store/settings.d.ts +1 -1
  42. package/dist/store/settings.js +16 -6
  43. package/package.json +6 -2
@@ -0,0 +1,18 @@
1
+ // Atomic quota commits create locks, markers and a renamed temp file. Keep
2
+ // those filesystem events at least 30 s apart under normal load; routing sees
3
+ // pending readings immediately, while other processes may lag by one interval.
4
+ // Shutdown drains and a full bounded pool queue can commit sooner.
5
+ // The vault shares one gate per resolved path; each pool handle has its own.
6
+ // N pool handles on one file can therefore make N normal commits per interval
7
+ // in one process. These gates do not coordinate with other processes.
8
+ export const QUOTA_COMMIT_INTERVAL_MS = 30_000;
9
+ export const quotaCommitTimer = {
10
+ now: () => performance.now(),
11
+ schedule(delayMs, run) {
12
+ const timer = setTimeout(() => void run(), delayMs);
13
+ return {
14
+ cancel: () => clearTimeout(timer),
15
+ unref: () => timer.unref?.(),
16
+ };
17
+ },
18
+ };
@@ -0,0 +1,8 @@
1
+ /** Scan both spellings: decoding is independent of provider JSON parsing. */
2
+ export declare function redactCredentialText(text: string, credential?: string): string;
3
+ /** Return a fresh Error with only size-limited, scrubbed data needed for abort, quota and host retry decisions. */
4
+ export declare function redactCredentialError(error: unknown, credential?: string): Error;
5
+ /** Only error frames are rewritten; normal model output must remain byte-identical. */
6
+ export declare function redactCredentialFrame(frame: string, credential?: string): string;
7
+ /** Scrub HTTP errors and caller-declared SSE errors without buffering successful output. */
8
+ export declare function redactCredentialResponse(response: Response, credential?: string, mode?: 'event-stream' | 'http'): Promise<Response>;
@@ -0,0 +1,490 @@
1
+ import { types } from 'node:util';
2
+ import { redactStrings } from '../logger/redact.js';
3
+ const escapedErrorField = /"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"\s*:/i;
4
+ const escapedErrorType = /"(?:t|\\u0074)(?:y|\\u0079)(?:p|\\u0070)(?:e|\\u0065)"\s*:\s*"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"/i;
5
+ /** Decode diagnostic escapes without letting JSON.parse discard duplicate fields. */
6
+ function decodeEscapes(text) {
7
+ return text.replace(/\\(?:u([a-f\d]{4})|(["\\/bfnrt]))/gi, (sequence, hex, short) => {
8
+ if (hex)
9
+ return String.fromCharCode(Number.parseInt(hex, 16));
10
+ return ({ b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' }[short] ??
11
+ short ??
12
+ sequence);
13
+ });
14
+ }
15
+ /** Match a known token before generic Bearer masking can consume only its wrapped prefix. */
16
+ function maskKnownCredential(text, credential) {
17
+ if (!credential)
18
+ return text;
19
+ const literal = text.split(credential).join('[credential]');
20
+ const needle = credential.replace(/\s/g, '');
21
+ if (!needle)
22
+ return literal;
23
+ const normalized = literal.replace(/\s/g, '');
24
+ if (!normalized.includes(needle))
25
+ return literal;
26
+ const positions = [];
27
+ for (let index = 0; index < literal.length; index++) {
28
+ const character = literal[index] ?? '';
29
+ if (!/\s/.test(character))
30
+ positions.push(index);
31
+ }
32
+ const parts = [];
33
+ let copied = 0;
34
+ for (let from = normalized.indexOf(needle); from >= 0; from = normalized.indexOf(needle, from + needle.length)) {
35
+ const start = positions[from] ?? copied;
36
+ const end = (positions[from + needle.length - 1] ?? start) + 1;
37
+ parts.push(literal.slice(copied, start), '[credential]');
38
+ copied = end;
39
+ }
40
+ return parts.length ? parts.join('') + literal.slice(copied) : literal;
41
+ }
42
+ function redactRawText(text, credential) {
43
+ const masked = maskKnownCredential(text, credential);
44
+ return redactStrings(masked).replaceAll('***REDACTED***', '[credential]');
45
+ }
46
+ /** Scan both spellings: decoding is independent of provider JSON parsing. */
47
+ export function redactCredentialText(text, credential) {
48
+ const raw = redactRawText(text, credential);
49
+ const decoded = decodeEscapes(raw);
50
+ const safe = redactRawText(decoded, credential);
51
+ return safe === decoded ? raw : safe;
52
+ }
53
+ /** Compare decimal values without converting long ids to rounded floating-point numbers. */
54
+ function canonicalNumber(text) {
55
+ const parts = /^(-?)(0|[1-9]\d*)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(text);
56
+ if (!parts)
57
+ return undefined;
58
+ const fraction = parts[3] ?? '';
59
+ const digits = (parts[2] ?? '') + fraction;
60
+ let first = 0;
61
+ while (digits[first] === '0')
62
+ first++;
63
+ if (first === digits.length)
64
+ return '0';
65
+ let end = digits.length;
66
+ while (digits[end - 1] === '0')
67
+ end--;
68
+ const exponent = parts[4] ?? '0';
69
+ let start = exponent.startsWith('-') || exponent.startsWith('+') ? 1 : 0;
70
+ while (exponent[start] === '0')
71
+ start++;
72
+ const significant = exponent.slice(start) || '0';
73
+ // A bounded exponent calculation avoids expensive BigInt parsing of hostile exponent strings.
74
+ if (significant.length > 16)
75
+ return undefined;
76
+ const scale = BigInt((exponent.startsWith('-') ? '-' : '') + significant) -
77
+ BigInt(fraction.length) +
78
+ BigInt(digits.length - end);
79
+ return `${parts[1]}${digits.slice(first, end)}e${scale}`;
80
+ }
81
+ /** Visit JSON scalar literals in place, preserving every unredacted numeric lexeme. */
82
+ function redactCredentialJsonText(text, credential) {
83
+ const numericCredential = credential ? canonicalNumber(credential) : undefined;
84
+ return text.replace(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null/g, (literal) => {
85
+ if (!literal.startsWith('"')) {
86
+ const matches = credential &&
87
+ (literal === credential ||
88
+ (numericCredential !== undefined &&
89
+ canonicalNumber(literal) === numericCredential) ||
90
+ ((credential === 'Infinity' || credential === '-Infinity') &&
91
+ /^[-\d]/.test(literal) &&
92
+ String(Number(literal)) === credential));
93
+ return matches ? '"[credential]"' : literal;
94
+ }
95
+ const decoded = decodeEscapes(literal.slice(1, -1));
96
+ const redacted = redactCredentialText(decoded, credential);
97
+ return redacted === decoded ? literal : JSON.stringify(redacted);
98
+ });
99
+ }
100
+ function redactDiagnosticBody(body, credential) {
101
+ const lexical = redactCredentialJsonText(body, credential);
102
+ try {
103
+ JSON.parse(body);
104
+ return lexical;
105
+ }
106
+ catch {
107
+ // Non-JSON HTTP diagnostics can contain SSE or unquoted escaped text.
108
+ return redactCredentialText(lexical, credential);
109
+ }
110
+ }
111
+ const diagnosticLimit = 16_384;
112
+ const responseBodyLimit = 64 * 1024;
113
+ // OpenCode 1's session retry policy (session/retry.ts) matches these patterns
114
+ // against an API error's responseBody and retries on a match, even when
115
+ // isRetryable is false. A body cut down to the size limit must still contain
116
+ // any marker the original had, or a retryable failure would stop retrying.
117
+ const retryBodyPatterns = [
118
+ /429|500|502|503|504|524/i,
119
+ /rate increased too quickly|rate limit|rate-limit|rate_limit|too many requests/i,
120
+ /overloaded|service unavailable|service_unavailable|service-unavailable|internal error|internal_error|internal server error|server error|server_error|server-error|provider returned error|provider_returned_error|provider-returned-error/i,
121
+ /terminated|fetch failed|failed to fetch|network[-_\s]error|upstream connect|connection error|connection refused|connection lost|socket connection was closed|socket hang up|reset before headers|getaddrinfo|enotfound|eai_again|econnrefused|econnreset|etimedout/i,
122
+ /^timeout$|\b(?:request|response|connection|network|stream|read) (?:timeout|timed out|time out)\b/i,
123
+ /try your request again|retry your request|resource exhausted|resource_exhausted/i,
124
+ /\btry again (?:later|in\b)|\b(?:currently|temporarily) at capacity\b/i,
125
+ ];
126
+ /** Numeric request ids are quoted from their source lexeme, not a rounded JS number. */
127
+ function requestIdFromBody(body) {
128
+ try {
129
+ const value = ownData(JSON.parse(body), 'request_id');
130
+ if (typeof value === 'string')
131
+ return value;
132
+ if (typeof value !== 'number')
133
+ return undefined;
134
+ let depth = 0;
135
+ let key;
136
+ let atKey = true;
137
+ let atValue = false;
138
+ let requestId;
139
+ for (const match of body.matchAll(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}[\]:,]/g)) {
140
+ const token = match[0];
141
+ if (token === '{' || token === '[') {
142
+ depth++;
143
+ continue;
144
+ }
145
+ if (token === '}' || token === ']') {
146
+ depth--;
147
+ continue;
148
+ }
149
+ if (depth !== 1)
150
+ continue;
151
+ if (token === ',') {
152
+ atKey = true;
153
+ atValue = false;
154
+ key = undefined;
155
+ continue;
156
+ }
157
+ if (token === ':') {
158
+ atValue = true;
159
+ continue;
160
+ }
161
+ if (atKey && token.startsWith('"')) {
162
+ key = JSON.parse(token);
163
+ atKey = false;
164
+ continue;
165
+ }
166
+ if (atValue && key === 'request_id' && !token.startsWith('"'))
167
+ requestId = token;
168
+ atValue = false;
169
+ }
170
+ return requestId;
171
+ }
172
+ catch {
173
+ return undefined;
174
+ }
175
+ }
176
+ /** Keep small bodies readable; reduce large bodies to error codes, retry phrases and usage-limit metadata. */
177
+ function projectResponseBody(body, credential) {
178
+ const safe = redactDiagnosticBody(body, credential);
179
+ if (Buffer.byteLength(safe, 'utf8') <= responseBodyLimit)
180
+ return safe;
181
+ const markers = retryBodyPatterns.flatMap((pattern) => pattern.exec(safe)?.[0] ?? []);
182
+ for (const marker of ['FreeUsageLimitError', 'GoUsageLimitError']) {
183
+ if (safe.includes(marker))
184
+ markers.push(marker);
185
+ }
186
+ const compact = { retry: markers };
187
+ try {
188
+ const parsed = JSON.parse(safe);
189
+ if (ownData(parsed, 'type') === 'error')
190
+ compact.type = 'error';
191
+ const source = ownData(parsed, 'error');
192
+ const error = {};
193
+ for (const key of ['code', 'type']) {
194
+ const value = ownData(source, key);
195
+ if (typeof value === 'string')
196
+ error[key] = value.slice(0, 256);
197
+ }
198
+ if (Object.keys(error).length)
199
+ compact.error = error;
200
+ const metadata = {};
201
+ for (const key of ['workspace', 'limitName']) {
202
+ const value = ownData(ownData(parsed, 'metadata'), key);
203
+ if (typeof value === 'string')
204
+ metadata[key] = value.slice(0, 256);
205
+ }
206
+ if (Object.keys(metadata).length)
207
+ compact.metadata = metadata;
208
+ }
209
+ catch {
210
+ // Invalid JSON cannot supply error.code=context_length_exceeded, but retry phrases still matter.
211
+ }
212
+ return JSON.stringify(compact);
213
+ }
214
+ /** Descriptor reads on proxies run caller code, including proxies in a prototype chain. */
215
+ function safeObject(value) {
216
+ if (!value || typeof value !== 'object')
217
+ return false;
218
+ let prototype = value;
219
+ for (let depth = 0; prototype && depth < 16; depth++) {
220
+ if (types.isProxy(prototype))
221
+ return false;
222
+ prototype = Object.getPrototypeOf(prototype);
223
+ }
224
+ return prototype === null;
225
+ }
226
+ function ownData(value, key) {
227
+ if (!safeObject(value))
228
+ return undefined;
229
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
230
+ return descriptor && 'value' in descriptor ? descriptor.value : undefined;
231
+ }
232
+ function boundedText(text, credential) {
233
+ // Scrub before truncating so a credential crossing the limit cannot survive as a prefix.
234
+ return redactCredentialText(text, credential).slice(0, diagnosticLimit);
235
+ }
236
+ function nativeGetter(prototype, key) {
237
+ const getter = Object.getOwnPropertyDescriptor(prototype, key)?.get;
238
+ if (!getter)
239
+ throw new Error(`Missing native ${key} accessor`);
240
+ return getter;
241
+ }
242
+ const domMessage = nativeGetter(DOMException.prototype, 'message');
243
+ const domName = nativeGetter(DOMException.prototype, 'name');
244
+ /** Return a fresh Error with only size-limited, scrubbed data needed for abort, quota and host retry decisions. */
245
+ export function redactCredentialError(error, credential) {
246
+ let message = ownData(error, 'message');
247
+ let name = ownData(error, 'name');
248
+ if (safeObject(error) && error instanceof DOMException) {
249
+ try {
250
+ message = domMessage.call(error);
251
+ name = domName.call(error);
252
+ }
253
+ catch {
254
+ // An object inheriting DOMException.prototype need not have native exception slots.
255
+ }
256
+ }
257
+ const result = new Error(boundedText(typeof message === 'string'
258
+ ? message
259
+ : typeof error === 'string'
260
+ ? error
261
+ : 'Provider request failed', credential));
262
+ for (const key of Object.getOwnPropertyNames(result)) {
263
+ if (key !== 'message')
264
+ Reflect.deleteProperty(result, key);
265
+ }
266
+ Object.defineProperty(result, 'name', {
267
+ value: typeof name === 'string' ? boundedText(name, credential) : 'Error',
268
+ configurable: true,
269
+ writable: true,
270
+ });
271
+ const copy = (source, target, key) => {
272
+ const value = ownData(source, key);
273
+ if (typeof value === 'string' ||
274
+ (typeof value === 'number' && Number.isFinite(value)) ||
275
+ typeof value === 'boolean')
276
+ Object.defineProperty(target, key, {
277
+ value: typeof value === 'string' ? boundedText(value, credential) : value,
278
+ enumerable: true,
279
+ configurable: true,
280
+ writable: true,
281
+ });
282
+ };
283
+ for (const key of [
284
+ 'status',
285
+ 'statusCode',
286
+ 'status_code',
287
+ 'resets_at',
288
+ 'resets_in_seconds',
289
+ ]) {
290
+ const value = ownData(error, key);
291
+ if (typeof value === 'number' && Number.isFinite(value))
292
+ copy(error, result, key);
293
+ }
294
+ for (const key of ['code', 'type', 'isRetryable'])
295
+ copy(error, result, key);
296
+ for (const key of ['error', 'data']) {
297
+ const source = ownData(error, key);
298
+ const fields = Object.create(null);
299
+ for (const field of [
300
+ 'type',
301
+ 'code',
302
+ 'message',
303
+ 'resets_at',
304
+ 'resets_in_seconds',
305
+ ])
306
+ copy(source, fields, field);
307
+ const nested = ownData(source, 'error');
308
+ if (safeObject(nested)) {
309
+ const classification = Object.create(null);
310
+ for (const field of [
311
+ 'type',
312
+ 'code',
313
+ 'message',
314
+ 'resets_at',
315
+ 'resets_in_seconds',
316
+ ])
317
+ copy(nested, classification, field);
318
+ fields.error = classification;
319
+ }
320
+ if (Object.keys(fields).length)
321
+ Object.defineProperty(result, key, { value: fields, enumerable: true });
322
+ }
323
+ const headers = ownData(error, 'responseHeaders');
324
+ if (headers && typeof headers === 'object') {
325
+ const ownedHeaders = {};
326
+ for (const key of ['retry-after-ms', 'retry-after']) {
327
+ const value = ownData(headers, key);
328
+ if (typeof value === 'string')
329
+ ownedHeaders[key] = boundedText(value, credential);
330
+ }
331
+ Object.defineProperty(result, 'responseHeaders', {
332
+ value: ownedHeaders,
333
+ enumerable: true,
334
+ });
335
+ }
336
+ const body = ownData(error, 'responseBody');
337
+ if (typeof body === 'string')
338
+ Object.defineProperty(result, 'responseBody', {
339
+ value: projectResponseBody(body, credential),
340
+ enumerable: true,
341
+ });
342
+ const directId = ownData(error, 'request_id');
343
+ const headerId = ownData(headers, 'x-request-id');
344
+ const requestId = typeof directId === 'string'
345
+ ? directId
346
+ : typeof headerId === 'string'
347
+ ? headerId
348
+ : typeof body === 'string'
349
+ ? requestIdFromBody(redactDiagnosticBody(body, credential))
350
+ : undefined;
351
+ if (typeof requestId === 'string')
352
+ Object.defineProperty(result, 'request_id', {
353
+ value: boundedText(requestId, credential),
354
+ enumerable: true,
355
+ });
356
+ // The AI SDK recognizes API errors by these Boolean brands, not by instanceof.
357
+ for (const marker of ['vercel.ai.error', 'vercel.ai.error.AI_APICallError']) {
358
+ const key = Symbol.for(marker);
359
+ if (ownData(error, key) === true)
360
+ Object.defineProperty(result, key, { value: true });
361
+ }
362
+ return result;
363
+ }
364
+ /** Only error frames are rewritten; normal model output must remain byte-identical. */
365
+ export function redactCredentialFrame(frame, credential) {
366
+ // Parse only frames that can be an error envelope: any frame containing the
367
+ // word, or one that spells the error key or type with Unicode escapes.
368
+ // Ordinary deltas, including escaped non-ASCII text, skip the parse.
369
+ if (!frame.includes('error') &&
370
+ (!frame.includes('\\u00') ||
371
+ (!escapedErrorField.test(frame) && !escapedErrorType.test(frame))))
372
+ return frame;
373
+ let value;
374
+ try {
375
+ value = JSON.parse(frame);
376
+ }
377
+ catch {
378
+ // Non-JSON frames are not provider error envelopes.
379
+ return frame;
380
+ }
381
+ if (value?.type === 'error' || value?.error || value?.response?.error)
382
+ return redactCredentialJsonText(frame, credential);
383
+ return frame;
384
+ }
385
+ const responseStatus = nativeGetter(Response.prototype, 'status');
386
+ const responseStatusText = nativeGetter(Response.prototype, 'statusText');
387
+ const responseHeaders = nativeGetter(Response.prototype, 'headers');
388
+ const responseBody = nativeGetter(Response.prototype, 'body');
389
+ const responseText = Response.prototype.text;
390
+ const headerEntries = Headers.prototype.entries;
391
+ /** Scrub HTTP errors and caller-declared SSE errors without buffering successful output. */
392
+ export async function redactCredentialResponse(response, credential, mode = 'http') {
393
+ try {
394
+ if (!safeObject(response))
395
+ throw new Error('Invalid provider response');
396
+ const status = responseStatus.call(response);
397
+ const headers = responseHeaders.call(response);
398
+ const bodyStream = responseBody.call(response);
399
+ const ownedHeaders = new Headers();
400
+ for (const [name, value] of headerEntries.call(headers))
401
+ ownedHeaders.append(name, value);
402
+ const init = {
403
+ status,
404
+ statusText: redactCredentialText(responseStatusText.call(response), credential),
405
+ headers: ownedHeaders,
406
+ };
407
+ if (status < 200 || status > 299) {
408
+ for (const [name, value] of headerEntries.call(headers)) {
409
+ if (redactCredentialText(name, credential?.toLowerCase()) !== name) {
410
+ init.headers.delete(name);
411
+ continue;
412
+ }
413
+ try {
414
+ init.headers.set(name, redactCredentialText(value, credential));
415
+ }
416
+ catch {
417
+ // An unrepresentable diagnostic is safer to omit than to forward verbatim.
418
+ init.headers.delete(name);
419
+ }
420
+ }
421
+ init.headers.delete('content-length');
422
+ const body = await responseText.call(response);
423
+ // Scan lexical strings even in malformed JSON or HTTP bodies containing SSE.
424
+ return new Response(redactDiagnosticBody(body, credential), init);
425
+ }
426
+ // Hosts parse model streams as SSE even when a provider omits or mislabels the header.
427
+ if (!bodyStream || mode === 'http')
428
+ return response;
429
+ init.headers.delete('content-length');
430
+ const reader = ReadableStream.prototype.getReader.call(bodyStream);
431
+ const decoder = new TextDecoder('utf-8', { ignoreBOM: true });
432
+ const encoder = new TextEncoder();
433
+ let pending = '';
434
+ let atStart = true;
435
+ function scrub(event) {
436
+ const bom = atStart && event.startsWith('\ufeff') ? '\ufeff' : '';
437
+ atStart = false;
438
+ return (bom +
439
+ event
440
+ .slice(bom.length)
441
+ .replace(/^data: ?([^\r\n]*)/gm, (line, data) => line.slice(0, line.length - data.length) +
442
+ redactCredentialFrame(data, credential)));
443
+ }
444
+ return new Response(new ReadableStream({
445
+ async pull(controller) {
446
+ try {
447
+ for (;;) {
448
+ const chunk = await reader.read();
449
+ pending += decoder.decode(chunk.value, { stream: !chunk.done });
450
+ let emitted = false;
451
+ for (;;) {
452
+ const boundary = /\r?\n\r?\n/.exec(pending);
453
+ if (!boundary)
454
+ break;
455
+ const end = boundary.index + boundary[0].length;
456
+ controller.enqueue(encoder.encode(scrub(pending.slice(0, end))));
457
+ pending = pending.slice(end);
458
+ emitted = true;
459
+ }
460
+ if (chunk.done) {
461
+ if (pending)
462
+ controller.enqueue(encoder.encode(scrub(pending)));
463
+ controller.close();
464
+ return;
465
+ }
466
+ if (emitted)
467
+ return;
468
+ }
469
+ }
470
+ catch (error) {
471
+ controller.error(redactCredentialError(error, credential));
472
+ }
473
+ },
474
+ async cancel(reason) {
475
+ try {
476
+ await reader.cancel(reason);
477
+ }
478
+ catch (error) {
479
+ throw redactCredentialError(error, credential);
480
+ }
481
+ finally {
482
+ reader.releaseLock();
483
+ }
484
+ },
485
+ }), init);
486
+ }
487
+ catch (error) {
488
+ throw redactCredentialError(error, credential);
489
+ }
490
+ }
@@ -34,12 +34,8 @@ class BodyTooLargeError extends Error {
34
34
  function readBody(req) {
35
35
  return new Promise((resolve, reject) => {
36
36
  const tooLarge = (declaredOversize = false) => {
37
- // Streamed overflow drains without closing at response finish: doing so
38
- // caused EPIPE on a Bun 1.4.2 uploader. Declared oversize also drains, but
39
- // half-closes after the 413: Bun 1.3.14 reused refused fetch connections
40
- // despite Connection: close. Half-close preserved complete 413 JSON for
41
- // tested fetch and slow declared-length uploaders on both runtimes (see
42
- // research/load-probe/RPC-413-CLOSE.md for the delivery/lifecycle samples).
37
+ // Keep draining refused uploads so the client can finish sending after
38
+ // receiving the 413. The response path controls when the socket closes.
43
39
  req.removeAllListeners('data');
44
40
  req.on('data', () => { });
45
41
  req.resume();
@@ -143,20 +139,34 @@ export async function startRpcServer(options) {
143
139
  catch (error) {
144
140
  if (!(error instanceof BodyTooLargeError))
145
141
  throw error;
146
- if (error.declaredOversize) {
147
- const socket = req.socket;
148
- res.once('finish', () => {
149
- socket.end();
150
- // Bound an abandoned upload to two seconds, matching the server's
151
- // default request-delivery timeout. end() alone left Bun 1.3.14
152
- // compatibility sockets open.
153
- const timer = setTimeout(() => socket.destroy(), 2_000);
154
- timer.unref();
155
- req.once('end', () => socket.destroy());
156
- socket.once('close', () => clearTimeout(timer));
157
- if (req.complete)
158
- socket.destroy();
142
+ const socket = req.socket;
143
+ res.once('finish', () => {
144
+ socket.end();
145
+ // Bound an abandoned declared upload to two seconds, matching the
146
+ // default request-delivery timeout. On Bun 1.3.14, end() alone left
147
+ // the connection open while the client was still uploading.
148
+ const timer = setTimeout(() => socket.destroy(), 2_000);
149
+ timer.unref();
150
+ req.once('end', () => socket.destroy());
151
+ socket.once('close', () => clearTimeout(timer));
152
+ if (req.complete)
153
+ socket.destroy();
154
+ });
155
+ if (!error.declaredOversize && !req.complete) {
156
+ if (res.headersSent || res.writableEnded || res.destroyed)
157
+ return;
158
+ // Bun 1.4.4 closes Connection: close sockets at response finish even
159
+ // while an upload is in flight. Content-Length delivers complete 413
160
+ // JSON now; defer finish (and socket closure) until the body drains.
161
+ const body = JSON.stringify({ error: 'body too large' });
162
+ res.writeHead(413, {
163
+ 'content-type': 'application/json',
164
+ 'content-length': Buffer.byteLength(body),
165
+ connection: 'close',
159
166
  });
167
+ res.write(body);
168
+ req.once('end', () => res.end());
169
+ return;
160
170
  }
161
171
  return json(413, { error: 'body too large' }, { connection: 'close' });
162
172
  }