private-access-records.test.ts (12635B)
1 import { describe, expect, it } from 'vitest'; 2 import { finalizeEvent, generateSecretKey } from 'applesauce-core/helpers'; 3 import { nip44 } from 'applesauce-core/helpers/encryption'; 4 import { 5 decodePrivateRecord, 6 inspectPrivateSendRecord, 7 privateRecordSnapshot, 8 privateRecordWire, 9 privateReceivedOuterMetadata, 10 type PrivateAccessProbe, 11 type PrivateAccessProbeReceipt 12 } from '../../src/lib/persistence/private-records.ts'; 13 import { privateRecordSettlement } from '../../src/lib/persistence/local-inventory.ts'; 14 import { privateSendStatus } from '../../src/lib/messaging/send-status.ts'; 15 16 const owner = 17 '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'; 18 const peer = 'c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5'; 19 const command = '12345678-1234-4234-8234-123456789abc'; 20 const readOrigin = 'wss://read.example.org'; 21 const archiveOrigin = 'wss://archive.example.org'; 22 function policy() { 23 return { 24 schemaVersion: 1, 25 public: [ 26 { 27 origin: 'wss://public.example.org', 28 read: true, 29 write: false, 30 nip50: false 31 } 32 ], 33 inbox: [ 34 { origin: readOrigin, read: true, write: false }, 35 { origin: archiveOrigin, read: false, write: true } 36 ], 37 postingEnabled: false, 38 messagingEnabled: true, 39 operatorDenylist: [] 40 }; 41 } 42 function operator(policyWire = JSON.stringify(policy())) { 43 return { 44 schemaVersion: 1, 45 revision: 1, 46 authority: 'source_fixture', 47 policyWire, 48 evidenceSha256: 'a'.repeat(64), 49 relays: [readOrigin, archiveOrigin].map((origin) => ({ 50 origin, 51 auth: 'not_required', 52 recipientRead: 'supported', 53 namedArchiveAck: 'supported', 54 exactReadback: 'supported', 55 retention: 'operator_defined' 56 })) 57 }; 58 } 59 // Genuine outer signatures/ciphertext structure only; this fixture does not 60 // prove nested probe contents, operator facts or an actual access workflow. 61 function artifact(destination = owner) { 62 const key = generateSecretKey(); 63 let conversation: Uint8Array | undefined; 64 try { 65 conversation = nip44.v2.utils.getConversationKey(key, destination); 66 const event = finalizeEvent( 67 { 68 kind: 1059, 69 created_at: 1700000000, 70 tags: [['p', destination]], 71 content: nip44.v2.encrypt( 72 'Structural codec fixture; no nonce proof', 73 conversation 74 ) 75 }, 76 key 77 ); 78 return { eventId: event.id, wire: JSON.stringify(event) }; 79 } finally { 80 conversation?.fill(0); 81 key.fill(0); 82 } 83 } 84 function reservation(): PrivateAccessProbe { 85 const policyWire = JSON.stringify(policy()); 86 return { 87 schema: 1, 88 family: 'private_access_probe', 89 owner, 90 id: command, 91 revision: 0, 92 rumorHash: 'b'.repeat(64), 93 createdAt: 1700000000, 94 binding: { 95 preferenceId: 'c'.repeat(64), 96 preferenceCreatedAt: 1699999999, 97 readTargets: [readOrigin], 98 archiveTargets: [archiveOrigin], 99 policyWire, 100 operatorWire: JSON.stringify(operator(policyWire)) 101 }, 102 self: null, 103 receipts: [] 104 }; 105 } 106 function prepared(): PrivateAccessProbe { 107 return { ...reservation(), revision: 1, self: artifact() }; 108 } 109 function fact( 110 row: PrivateAccessProbe, 111 status: PrivateAccessProbeReceipt['status'] = 'accepted' 112 ): PrivateAccessProbeReceipt { 113 const readback = status === 'readback' || status === 'nonce_verified'; 114 return { 115 actionId: command, 116 origin: readback ? readOrigin : archiveOrigin, 117 role: readback ? 'access_readback' : 'access_archive', 118 attempt: 1, 119 eventId: row.self!.eventId, 120 status, 121 observedAtMilliseconds: 1700000000000, 122 readbackWire: readback ? row.self!.wire : null 123 }; 124 } 125 const decode = (row: unknown, expectedOwner = owner, expectedId = command) => 126 decodePrivateRecord(JSON.stringify(row), expectedOwner, expectedId); 127 128 describe('CR008 S2 strict separate probe journal codec', () => { 129 it('retains reservation and own ciphertext phases with no plaintext or permission', () => { 130 for (const row of [reservation(), prepared()]) { 131 const result = decode(row); 132 expect(result.ok).toBe(true); 133 if (!result.ok) throw Error('valid structural probe rejected'); 134 expect(privateRecordSnapshot(result.value, owner, command)).toEqual(row); 135 expect(privateRecordWire(result.value, owner, command)).toBe( 136 JSON.stringify(row) 137 ); 138 expect( 139 privateRecordSnapshot(result.value, peer, command) 140 ).toBeUndefined(); 141 expect( 142 privateReceivedOuterMetadata(result.value, owner, command) 143 ).toBeUndefined(); 144 expect( 145 inspectPrivateSendRecord(JSON.stringify(row), owner, command) 146 ).toBeUndefined(); 147 expect(privateSendStatus(result.value, owner, command)).toBeUndefined(); 148 expect(privateRecordSettlement(row)).toBe('protected'); 149 } 150 }); 151 it('admits exact local archive/readback facts without granting readiness or settled cleanup', () => { 152 const row = prepared(); 153 for (const status of [ 154 'accepted', 155 'refused', 156 'timed_out', 157 'unknown', 158 'stopped', 159 'readback', 160 'nonce_verified' 161 ] as const) { 162 const next = { ...row, revision: 2, receipts: [fact(row, status)] }; 163 expect(decode(next).ok).toBe(true); 164 expect(privateRecordSettlement(next)).toBe('protected'); 165 } 166 const completeLooking = { 167 ...row, 168 revision: 4, 169 receipts: [fact(row), fact(row, 'readback'), fact(row, 'nonce_verified')] 170 }; 171 expect(decode(completeLooking).ok).toBe(true); 172 expect(privateRecordSettlement(completeLooking)).toBe('protected'); 173 expect(decode({ ...completeLooking, readiness: true }).ok).toBe(false); 174 }); 175 it('preserves explicit unsupported capability metadata without converting it into success', () => { 176 const row = reservation(), 177 declaration = operator(); 178 declaration.relays[0].exactReadback = 'unsupported'; 179 expect( 180 decode({ 181 ...row, 182 binding: { ...row.binding, operatorWire: JSON.stringify(declaration) } 183 }).ok 184 ).toBe(true); 185 }); 186 it('requires separate read/write grants, configured declarations and their exact policy wire', () => { 187 const row = reservation(); 188 for (const patch of [ 189 { readTargets: [] }, 190 { archiveTargets: [] }, 191 { readTargets: [archiveOrigin] }, 192 { archiveTargets: [readOrigin] }, 193 { readTargets: [readOrigin, readOrigin] }, 194 { readTargets: [readOrigin, 'wss://outside.example.org'] }, 195 { archiveTargets: [archiveOrigin + '/'] }, 196 { readTargets: [readOrigin, readOrigin, readOrigin, readOrigin] }, 197 { preferenceId: 'bad' }, 198 { preferenceCreatedAt: -1 }, 199 { preferenceCreatedAt: 1.1 }, 200 { policyWire: '{}' }, 201 { operatorWire: '{}' } 202 ]) 203 expect(decode({ ...row, binding: { ...row.binding, ...patch } }).ok).toBe( 204 false 205 ); 206 for (const declaration of [ 207 { 208 ...operator(), 209 authority: 'unconfigured', 210 evidenceSha256: null, 211 relays: [] 212 }, 213 { ...operator(), relays: [operator().relays[0]] }, 214 { 215 ...operator(), 216 policyWire: JSON.stringify({ ...policy(), messagingEnabled: false }) 217 } 218 ]) 219 expect( 220 decode({ 221 ...row, 222 binding: { ...row.binding, operatorWire: JSON.stringify(declaration) } 223 }).ok 224 ).toBe(false); 225 }); 226 it('rejects owner/id/schema/revision violations and phases lacking immutable ciphertext', () => { 227 const row = prepared(); 228 for (const patch of [ 229 { schema: 2 }, 230 { family: 'private_send_operation' }, 231 { owner: peer }, 232 { id: row.rumorHash }, 233 { revision: -1 }, 234 { revision: 1.1 }, 235 { revision: Number.MAX_SAFE_INTEGER + 1 }, 236 { rumorHash: 'bad' }, 237 { createdAt: -1 }, 238 { createdAt: 1.5 }, 239 { revision: 0 }, 240 { self: null } 241 ]) 242 expect(decode({ ...row, ...patch }).ok).toBe(false); 243 expect(decode(row, peer).ok).toBe(false); 244 expect(decode(row, owner, row.rumorHash).ok).toBe(false); 245 expect(decode({ ...reservation(), receipts: [fact(row)] }).ok).toBe(false); 246 }); 247 it('requires independently signed strict own1059 and preserves full original bytes', () => { 248 const row = prepared(), 249 original = JSON.parse(row.self!.wire) as Record<string, unknown>; 250 for (const patch of [ 251 { kind: 14 }, 252 { kind: 13 }, 253 { sig: '0'.repeat(128) }, 254 { content: 'PRIVATE_PLAINTEXT_SENTINEL' }, 255 { 256 tags: [ 257 ['p', owner], 258 ['nonce', '1', '1'] 259 ] 260 }, 261 { tags: [['p', peer]] }, 262 { extra: true } 263 ]) 264 expect( 265 decode({ 266 ...row, 267 self: { ...row.self, wire: JSON.stringify({ ...original, ...patch }) } 268 }).ok 269 ).toBe(false); 270 expect(decode({ ...row, self: artifact(peer) }).ok).toBe(false); 271 expect( 272 decode({ ...row, self: { ...row.self, eventId: 'd'.repeat(64) } }).ok 273 ).toBe(false); 274 expect( 275 decode({ 276 ...row, 277 self: { ...row.self, wire: row.self!.wire + ' '.repeat(32768) } 278 }).ok 279 ).toBe(false); 280 const whitespace = { 281 ...row, 282 self: { ...row.self!, wire: row.self!.wire + '\n\t' } 283 }, 284 result = decode(whitespace); 285 expect(result.ok).toBe(true); 286 if (!result.ok) throw Error('valid exact wire rejected'); 287 expect(privateRecordSnapshot(result.value, owner, command)).toEqual( 288 whitespace 289 ); 290 }); 291 it('rejects relabelled ordinary roles, wrong targets/ids and non-exact readbacks', () => { 292 const row = prepared(); 293 for (const patch of [ 294 { actionId: 'bad' }, 295 { role: 'peer' }, 296 { role: 'self_archive' }, 297 { origin: readOrigin }, 298 { attempt: 0 }, 299 { attempt: 4 }, 300 { attempt: 1.1 }, 301 { eventId: 'd'.repeat(64) }, 302 { status: 'readback' }, 303 { observedAtMilliseconds: -1 }, 304 { readbackWire: row.self!.wire } 305 ]) 306 expect( 307 decode({ ...row, revision: 2, receipts: [{ ...fact(row), ...patch }] }) 308 .ok 309 ).toBe(false); 310 for (const patch of [ 311 { origin: archiveOrigin }, 312 { readbackWire: null }, 313 { status: 'accepted' }, 314 { status: 'nonce_verified', readbackWire: artifact().wire } 315 ]) 316 expect( 317 decode({ 318 ...row, 319 revision: 2, 320 receipts: [{ ...fact(row, 'readback'), ...patch }] 321 }).ok 322 ).toBe(false); 323 }); 324 it('retains harmless serialized observation bytes for probe readback metadata without effect authority', () => { 325 const row = prepared(), 326 wire = row.self!.wire + '\n'; 327 const observed = { 328 ...row, 329 revision: 2, 330 receipts: [{ ...fact(row, 'readback'), readbackWire: wire }] 331 }; 332 const result = decode(observed); 333 expect(result.ok).toBe(true); 334 if (!result.ok) throw Error('bounded signed-equivalent observation'); 335 expect(privateRecordSnapshot(result.value, owner, command)).toEqual( 336 observed 337 ); 338 expect(privateRecordSettlement(observed)).toBe('protected'); 339 }); 340 it('rejects plaintext, unknown/missing fields and duplicate aliases at every nested level', () => { 341 const row = prepared(); 342 for (const key of [ 343 'body', 344 'nonce', 345 'subject', 346 'peer', 347 'session', 348 'verified' 349 ]) { 350 expect(decode({ ...row, [key]: 'PRIVATE_SENTINEL' }).ok).toBe(false); 351 expect( 352 decode({ 353 ...row, 354 binding: { ...row.binding, [key]: 'PRIVATE_SENTINEL' } 355 }).ok 356 ).toBe(false); 357 } 358 for (const key of Object.keys(row)) { 359 const broken: Record<string, unknown> = { ...row }; 360 delete broken[key]; 361 expect(decode(broken).ok).toBe(false); 362 } 363 for (const key of Object.keys(row.binding)) { 364 const broken: Record<string, unknown> = { ...row.binding }; 365 delete broken[key]; 366 expect(decode({ ...row, binding: broken }).ok).toBe(false); 367 } 368 const raw = JSON.stringify(row); 369 for (const duplicate of [ 370 raw.replace('"schema":1', '"schema":2,"schema":1'), 371 raw.replace( 372 '"preferenceId":', 373 '"\\u0070referenceId":"d","preferenceId":' 374 ), 375 raw.replace('"eventId":', '"eventId":"d","eventId":') 376 ]) 377 expect(decodePrivateRecord(duplicate, owner, command).ok).toBe(false); 378 for (const operatorWire of [ 379 JSON.stringify(operator()).replace( 380 '"revision":1', 381 '"revision":2,"revision":1' 382 ), 383 JSON.stringify(operator(), null, 2) 384 ]) 385 expect( 386 decode({ ...row, binding: { ...row.binding, operatorWire } }).ok 387 ).toBe(false); 388 }); 389 });