incoming-wire.ts (6355B)
1 import { getEventHash, type UnsignedEvent } from 'applesauce-core/helpers'; 2 import { PRIVATE_TRANSPORT_BUDGETS } from '../config/budgets.ts'; 3 import { canonicalPublicKey } from '../contracts/public-key.ts'; 4 import { exactLocalFields } from '../contracts/local-records.ts'; 5 import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts'; 6 import { 7 messageFromWireParts, 8 type MessageV1 9 } from '../contracts/message-v1/index.ts'; 10 import { safeUnsignedInteger } from './envelope-bounds.ts'; 11 import { boundedEnvelopeTags } from './verified-envelope.ts'; 12 13 // Syntax-only duplicate detection precedes ordinary JSON semantics. Escaped 14 // field aliases count as the same key; harmless whitespace stays supported. 15 function uniqueJSONFields(raw: string): boolean { 16 type Frame = { 17 array: boolean; 18 key: boolean; 19 parent: Frame | undefined; 20 accept: (name: string) => boolean; 21 }; 22 function frame(parent: Frame | undefined, array: boolean): Frame { 23 const names = new Set<string>(); 24 return { 25 parent, 26 array, 27 key: !array, 28 accept: (name: string) => { 29 if (names.has(name)) return false; 30 names.add(name); 31 return true; 32 } 33 }; 34 } 35 let current: Frame | undefined; 36 try { 37 for (let index = 0; index < raw.length; index++) { 38 const character = raw[index]; 39 if (character === '"') { 40 let end = index + 1; 41 while (end < raw.length) { 42 if (raw[end] === '\\') { 43 end += 2; 44 continue; 45 } 46 if (raw[end] === '"') break; 47 end++; 48 } 49 if (end >= raw.length) return false; 50 if (current && !current.array && current.key) { 51 const name: unknown = JSON.parse(raw.slice(index, end + 1)); 52 if (typeof name !== 'string' || !current.accept(name)) return false; 53 current = { 54 parent: current.parent, 55 array: current.array, 56 accept: current.accept, 57 key: false 58 }; 59 } 60 index = end; 61 } else if (character === '{' || character === '[') 62 current = frame(current, character === '['); 63 else if (character === '}' || character === ']') { 64 if (!current) return false; 65 current = current.parent; 66 } else if (character === ',' && current && !current.array) 67 current = { 68 parent: current.parent, 69 array: current.array, 70 accept: current.accept, 71 key: true 72 }; 73 } 74 return current === undefined; 75 } catch { 76 return false; 77 } 78 } 79 export function parseIncomingLayer(raw: unknown, bytes: number): unknown { 80 if ( 81 typeof raw !== 'string' || 82 !boundedUtf8(raw, bytes) || 83 !uniqueJSONFields(raw) 84 ) 85 return undefined; 86 try { 87 let invalid = false; 88 const parsed: unknown = JSON.parse( 89 raw, 90 function (key: string, value: unknown, context?: { source?: string }) { 91 if ( 92 !key.isWellFormed() || 93 (typeof value === 'string' && !value.isWellFormed()) 94 ) 95 invalid = true; 96 if ( 97 typeof value === 'number' && 98 (!Number.isFinite(value) || 99 ((key === 'kind' || key === 'created_at') && 100 (context?.source === undefined || 101 !/^[0-9]+$/u.test(context.source)))) 102 ) 103 invalid = true; 104 return value; 105 } 106 ); 107 return invalid ? undefined : parsed; 108 } catch { 109 return undefined; 110 } 111 } 112 // Receive-only syntax/projection. These detached values grant no signature, 113 // nested custody, routing, persistence, publication or conversation authority. 114 export function incomingGiftWrapTags( 115 tags: unknown, 116 expectedOwner: unknown 117 ): boolean { 118 const owner = canonicalPublicKey(expectedOwner); 119 if ( 120 !owner || 121 !boundedEnvelopeTags(tags) || 122 tags.some((row) => row[0] === 'expiration') 123 ) 124 return false; 125 const recipients = tags.filter((row) => row[0] === 'p'); 126 return ( 127 recipients.length === 1 && 128 (recipients[0].length === 2 || recipients[0].length === 3) && 129 recipients[0][1] === owner 130 ); 131 } 132 133 export type IncomingPairRumor = Readonly<{ 134 original: Readonly<UnsignedEvent & { id: string }>; 135 message: MessageV1; 136 }>; 137 138 // Hash the original ordered fields. Semantic projection is deliberately 139 // independent of the strict outgoing writer; hints and unknown tags grant no effects. 140 export function readIncomingPairRumor( 141 raw: unknown, 142 expectedSender?: unknown 143 ): IncomingPairRumor | undefined { 144 const parsed = parseIncomingLayer(raw, PRIVATE_TRANSPORT_BUDGETS.rumorBytes); 145 if ( 146 !exactLocalFields(parsed, [ 147 'id', 148 'pubkey', 149 'created_at', 150 'kind', 151 'tags', 152 'content' 153 ]) || 154 parsed.kind !== 14 || 155 typeof parsed.id !== 'string' || 156 !/^[0-9a-f]{64}$/u.test(parsed.id) || 157 safeUnsignedInteger(parsed.created_at) === undefined || 158 !boundedEnvelopeTags(parsed.tags) 159 ) 160 return undefined; 161 const sender = canonicalPublicKey(parsed.pubkey); 162 if ( 163 !sender || 164 (expectedSender !== undefined && 165 canonicalPublicKey(expectedSender) !== sender) 166 ) 167 return undefined; 168 const tags = parsed.tags; 169 // Unsupported retention/attachment semantics never become inert acceptance. 170 if (tags.some((row) => ['expiration', 'file', 'imeta'].includes(row[0]))) 171 return undefined; 172 const recipients = tags.filter((row) => row[0] === 'p'), 173 parents = tags.filter((row) => row[0] === 'e'), 174 subjects = tags.filter((row) => row[0] === 'subject'); 175 if ( 176 recipients.length !== 1 || 177 ![2, 3].includes(recipients[0].length) || 178 parents.length > 1 || 179 parents.some((row) => ![2, 3].includes(row.length)) || 180 subjects.length > 1 || 181 subjects.some((row) => row.length !== 2) 182 ) 183 return undefined; 184 const decoded = messageFromWireParts( 185 JSON.stringify({ kind: 14, tags, content: parsed.content }) 186 ); 187 if ( 188 !decoded || 189 decoded.recipients.length !== 1 || 190 decoded.recipients[0].public_key === sender 191 ) 192 return undefined; 193 const template: UnsignedEvent = { 194 pubkey: sender, 195 kind: 14, 196 created_at: parsed.created_at as number, 197 tags: tags.map((row) => [...row]), 198 content: decoded.content 199 }; 200 if (getEventHash(template) !== parsed.id) return undefined; 201 return { original: { id: parsed.id, ...template }, message: decoded }; 202 }