decoded-inbox-wire.ts (3159B)
1 import { PUBLIC_INGRESS_BUDGETS } from '../config/budgets.ts'; 2 3 // The qualified SDK exposes parsed JSON, not original transport text. Preserve 4 // every decoded JSON field without invoking getters, toJSON or SDK symbols. 5 // Bounds are post-parse logical work; this makes no allocation/preparse claim. 6 export function decodedInboxWire( 7 input: unknown, 8 assertActive: () => void 9 ): string | undefined { 10 const parts: string[] = []; 11 const encoder = new TextEncoder(); 12 let bytes = 0, 13 nodes = 0; 14 function append(text: string) { 15 bytes += encoder.encode(text).length; 16 if (bytes > PUBLIC_INGRESS_BUDGETS.eventBytes) 17 throw new Error('candidate_invalid'); 18 parts.push(text); 19 } 20 function inspect( 21 value: object, 22 name: string 23 ): PropertyDescriptor | undefined { 24 assertActive(); 25 const descriptor = Object.getOwnPropertyDescriptor(value, name); 26 assertActive(); 27 return descriptor; 28 } 29 function data(value: object, name: string): unknown { 30 const descriptor = inspect(value, name); 31 if (!descriptor || !('value' in descriptor)) 32 throw new Error('candidate_invalid'); 33 return descriptor.value; 34 } 35 function visit(value: unknown): void { 36 assertActive(); 37 if (++nodes > PUBLIC_INGRESS_BUDGETS.eventBytes) 38 throw new Error('candidate_invalid'); 39 if ( 40 value === null || 41 typeof value === 'boolean' || 42 typeof value === 'number' 43 ) { 44 if (typeof value === 'number' && !Number.isFinite(value)) 45 throw new Error('candidate_invalid'); 46 append(JSON.stringify(value)); 47 } else if (typeof value === 'string') { 48 if (value.length > PUBLIC_INGRESS_BUDGETS.eventBytes) 49 throw new Error('candidate_invalid'); 50 append(JSON.stringify(value)); 51 } else if (typeof value === 'object') { 52 if (Array.isArray(value)) { 53 const length = data(value, 'length'); 54 if ( 55 typeof length !== 'number' || 56 !Number.isSafeInteger(length) || 57 length < 0 || 58 length > PUBLIC_INGRESS_BUDGETS.eventBytes 59 ) 60 throw new Error('candidate_invalid'); 61 append('['); 62 for (let index = 0; index < length; index++) { 63 if (index) append(','); 64 visit(data(value, String(index))); 65 } 66 append(']'); 67 } else { 68 append('{'); 69 let index = 0; 70 for (const name in value) { 71 assertActive(); 72 const descriptor = inspect(value, name); 73 if (!descriptor) continue; 74 if (index >= PUBLIC_INGRESS_BUDGETS.eventBytes) 75 throw new Error('candidate_invalid'); 76 if (index) append(','); 77 if (name.length > PUBLIC_INGRESS_BUDGETS.eventBytes) 78 throw new Error('candidate_invalid'); 79 append(JSON.stringify(name)); 80 append(':'); 81 visit(data(value, name)); 82 index++; 83 } 84 append('}'); 85 } 86 } else throw new Error('candidate_invalid'); 87 } 88 try { 89 if (!input || typeof input !== 'object' || Array.isArray(input)) 90 return undefined; 91 visit(input); 92 return parts.join(''); 93 } catch { 94 return undefined; 95 } 96 }