consumer.ts (15418B)
1 import init, { 2 BindingFixture, Client, Workspace, CommandRequest, ListingInput, InquiryInput, 3 Receipt, Failure, Admission, BusinessInstallation, Issuance, OperationKind, 4 SessionState, StartMode, TargetObservation, verify_listing_publications, 5 verify_binding_inquiry, advertisements, 6 FixtureRejection, SignerRejectionReason, 7 } from '@radroots/browser-feasibility'; 8 9 function assert(value: unknown, message: string): asserts value { 10 if (!value) throw Error(message); 11 } 12 const decode = (value: Uint8Array): unknown => JSON.parse(new TextDecoder().decode(value)); 13 const id = (byte: string): string => byte.repeat(32); 14 const peer = 'c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5'; 15 const now = (): string => String(Math.floor(Date.now() / 1000)); 16 const deadline = (): string => String(Math.floor(Date.now() / 1000) + 120); 17 const text = '\uFEFF cafe\u0301 / café 🥕\u0000 '; 18 19 async function rejectedSigners(base: string, context: string): Promise<void> { 20 const cases = [ 21 {mode:FixtureRejection.Malformed,reason:SignerRejectionReason.InvalidArtifact,covered:'34',total:'34',digest:'ba883ea08dff4c078672a055dd2be042d9debb5b22c66527e4499c068011879d'}, 22 {mode:FixtureRejection.Oversized,reason:SignerRejectionReason.TooLarge,covered:'65536',total:'65537',digest:'d2d5af5c0316f5c2b119635386239edc87abce035f851c3f6ee127e6c3cbf435'}, 23 {mode:FixtureRejection.Foreign,reason:SignerRejectionReason.BindingMismatch,covered:undefined,total:undefined,digest:undefined}, 24 ]; 25 for (const value of cases) { 26 const host=await BindingFixture.create_rejected(base.replace('http:','ws:')+'/listing/'+context,`rejected_${context}_${value.mode}`,value.mode); 27 const client=host.client(),scope=host.workspace(); await client.start(StartMode.Online); 28 const request=new CommandRequest(id('18'),deadline()),input=listingInput(); 29 let refused=false; 30 try { await client.publish_listing(scope,request,input); } 31 catch(error:unknown) { 32 assert(error instanceof Failure,'actual generated rejected failure'); refused=true; 33 assert(error.code==='signer_tampering'&&error.retry==='manual_reconciliation','original failure code/retry'); 34 assert(error.operation_id===id('18')&&error.admission===Admission.Confirmed,'original confirmed identity'); 35 const diagnostic=error.signer_rejection; assert(diagnostic,'bounded signer metadata'); 36 assert(diagnostic.reason===value.reason,'original fixed rejection reason'); 37 const fingerprint=diagnostic.fingerprint; 38 if(fingerprint){ 39 assert(fingerprint.covered_bytes===value.covered&&fingerprint.total_bytes===value.total,'exact coverage strings'); 40 const bytes=fingerprint.sha256; 41 assert(bytes.length===32&&Array.from(bytes).map(byte=>byte.toString(16).padStart(2,'0')).join('')===value.digest,'independent original prefix digest'); 42 fingerprint.free(); 43 }else assert(value.digest===undefined,'no invented or discarded fingerprint'); 44 diagnostic.free(); error.free(); 45 } 46 assert(refused&&host.signing_calls()===1,'one actual callback and no successful signature'); 47 const facts=await client.operation(scope,id('18'),undefined); 48 assert(facts&&facts.business_installation===BusinessInstallation.NotInstalled,'rejection is no business success'); 49 facts.free(); await client.close(); assert(host.callbacks_closed()===1,'rejected callback owner closes'); scope.close(); 50 for(const item of [request,input,scope,client,host])item.free(); 51 } 52 } 53 54 async function refuses(call: () => unknown, code: string): Promise<void> { 55 try { await call(); } catch (error: unknown) { 56 assert(error instanceof Failure, 'typed generated failure'); 57 assert(error.code === code, `safe failure ${error.code} expected ${code}`); 58 assert(!JSON.stringify([error.code,error.field,error.retry]).includes(text), 'input-free failure'); 59 error.free(); return; 60 } 61 throw Error(`expected ${code}`); 62 } 63 function receipt(value: Receipt, operation: string, kind: OperationKind): void { 64 assert(value.operation_id === operation && value.kind === kind, 'exact typed operation/family'); 65 assert(value.admission === Admission.Confirmed, 'confirmed durable admission'); 66 assert(value.business_installation === BusinessInstallation.Installed, 'actual installation'); 67 assert(value.issuance === Issuance.Obtained, 'actual obtained originals'); 68 for (const digest of [value.command_digest,value.operation_checkpoint,value.admission_transaction_id, 69 value.plan_transaction_id,value.installation_transaction_id]) assert(digest && /^[0-9a-f]{64}$/.test(digest), 'exact digest/transaction'); 70 assert(typeof value.prepared_at === 'string' && typeof value.first_issue_not_after === 'string' 71 && typeof value.installed_at === 'string' && typeof value.observed_at === 'string', 'exact time strings'); 72 assert(decode(value.captured_context_json) && decode(value.authority_checkpoint_json), 'source-owned structured context/checkpoint'); 73 assert(value.missing_sources.length === 0 && value.conflicting_records.length === 0 74 && value.conflicting_sources.length === 0 && value.error === undefined, 'all conflict/error axes'); 75 assert(value.record_ids.length === 0, 'known listing/chat have no fabricated structured-commerce record IDs'); 76 const artifacts=value.artifacts; 77 assert(artifacts.length > 0, 'actual original artifacts'); 78 for (const artifact of artifacts) { 79 assert(artifact.issuance === Issuance.Obtained && artifact.attempt_id && artifact.claim_transaction 80 && artifact.intent_digest && artifact.capture_transaction && artifact.obtained_digest 81 && artifact.publication_transaction, 'complete original artifact provenance'); 82 assert(artifact.observed_at_unix_ms === undefined || typeof artifact.observed_at_unix_ms === 'string', 'nullable exact artifact time'); 83 artifact.free(); 84 } 85 for (const attempt of value.delivery_attempts) { 86 const policy = attempt.policy; 87 assert(policy.kind === 'all' && policy.threshold === undefined && policy.fingerprints.length === 0, 'original closed policy'); 88 const targets=attempt.targets; 89 assert(attempt.selected_fingerprints.length === 1 && targets.length === 1 90 && attempt.target_ordinals.length === 1, 'actual target selection'); 91 for (const target of targets) { 92 assert(target.uri.startsWith('ws://127.0.0.1:') && target.kind && target.fingerprint, 'actual configured target'); 93 target.free(); 94 } 95 for (const field of [attempt.request_id,attempt.event_id,attempt.publication_policy_digest,attempt.intent_digest, 96 attempt.original_bytes_digest,attempt.transaction_id,attempt.work_transaction_id,attempt.retained_at,attempt.deadline_unix_ms]) assert(typeof field === 'string' && field.length > 0, 'complete original delivery commitment'); 97 policy.free(); attempt.free(); 98 } 99 for (const observation of value.delivery_observations) { 100 assert(observation.event_id && observation.target && observation.request_id && observation.target_fingerprint 101 && observation.target_ordinal > 0, 'complete correlated observation'); 102 assert(observation.observed_at_unix_ms === undefined || typeof observation.observed_at_unix_ms === 'string', 'nullable exact observation time'); 103 observation.free(); 104 } 105 assert(typeof value.delivery === 'number' && typeof value.wait_termination === 'number' 106 && Array.isArray(value.recovery), 'independent delivery/wait/recovery axes'); 107 } 108 function listingInput(): ListingInput { 109 return ListingInput.parse(new TextEncoder().encode(JSON.stringify({ 110 id:'01'.repeat(16),title:' Packed carrots 🥕 ',summary:'Quote required',description_markdown:'Exact public terms',published_at:now(), 111 profile:{profile:'radroots.listing',version:1,state:'active',product:{name:'Carrots',description:'Fresh carrots',producer:null,origin_summary:null}, 112 default_option:id('02'),options:[{id:id('02'),label:'Bunch',unit:{type:'package',label:'bunch',contents:{type:'unspecified'}}, 113 increment:'1',minimum:'1',price:{type:'quote_required'},supply:{type:'available',amount:'10'},lead_seconds:'0'}], 114 fulfillment:{modes:['pickup'],area:'Example',lead_seconds:'0'},authority:null,media:[]}, 115 }))); 116 } 117 async function query(client: Client, scope: Workspace, operation: string, digest: string): Promise<Receipt> { 118 const result = await client.operation(scope,operation,digest); 119 assert(result, 'actual retained original operation'); return result; 120 } 121 export async function run(base: string, context: string): Promise<unknown> { 122 await init(); 123 const publicRoute = '/listing/'+context, privateRoute = '/'+context; 124 await fetch(base+'/advertisements'+privateRoute,{method:'POST',body:advertisements(base.replace('http:','ws:')+privateRoute)}); 125 const seller = await BindingFixture.create(base.replace('http:','ws:')+publicRoute,'packed_public_'+context,true); 126 const client = seller.client(), scope = seller.workspace(); 127 assert(client.state() === SessionState.Ready, 'inert configured host'); 128 await client.start(StartMode.Online); 129 await refuses(()=>new CommandRequest(id('11').toUpperCase(),'253402300800'), 'InvalidInput'); 130 await refuses(()=>new CommandRequest(id('ab').toUpperCase(),deadline()), 'InvalidInput'); 131 await refuses(()=>new CommandRequest(id('11'),'0001'), 'InvalidInput'); 132 await refuses(()=>new InquiryInput(id('12'),peer,undefined,'x'.repeat(17000)), 'LimitExceeded'); 133 await refuses(()=>new InquiryInput(id('12'),peer,undefined,'\ud800'), 'InvalidInput'); 134 await refuses(()=>ListingInput.parse(new Uint8Array(65537)), 'LimitExceeded'); 135 await refuses(()=>ListingInput.parse(new TextEncoder().encode('{"id":"bad"}')), 'InvalidInput'); 136 const input=listingInput(), request=new CommandRequest(id('13'),deadline(),'packed-public'); 137 const original=await client.publish_listing(scope,request,input); 138 receipt(original,id('13'),OperationKind.Listing); 139 assert(original.message_id === undefined, 'public has no private message'); 140 const result=original.business_result; assert(result, 'typed public value'); 141 assert(result.chat_value() === undefined, 'public has no private placeholder'); 142 const listing=result.listing_value(); assert(listing && listing.title() === ' Packed carrots 🥕 ' 143 && listing.id() === '01'.repeat(16) && listing.published_at() && decode(listing.terms_json()), 'actual listing content'); 144 const revision=listing.revision(); listing.free(); result.free(); 145 for (const artifact of original.artifacts) { assert(artifact.recipient === undefined, 'public recipient absent'); artifact.free(); } 146 const observations=original.delivery_observations; 147 assert(observations.length === 1 && observations[0].outcome === TargetObservation.Rejected, 'actual public rejection'); 148 observations.forEach(value=>value.free()); 149 const digest=original.command_digest, checkpoint=original.operation_checkpoint; 150 const replay=await client.publish_listing(scope,request,input); 151 assert(replay.operation_checkpoint === checkpoint, 'idempotent JS replay'); replay.free(); 152 await client.close(); await client.close(); assert(seller.callbacks_closed() === 1, 'original callbacks closed once'); 153 const reopened=await seller.reopen(), resumedClient=reopened.client(), resumedScope=reopened.workspace(); 154 await resumedClient.start(StartMode.Online); 155 const retained=await query(resumedClient,resumedScope,id('13'),digest); 156 assert(retained.operation_checkpoint === checkpoint, 'reopen exact original checkpoint'); retained.free(); 157 const resumed=await resumedClient.resume(resumedScope,id('13'),digest); 158 receipt(resumed,id('13'),OperationKind.Listing); 159 assert(resumed.installation_transaction_id === original.installation_transaction_id 160 && resumed.first_issue_not_after === original.first_issue_not_after, 'original issuance/installation after retry'); 161 const attempts=resumed.delivery_attempts; 162 assert(attempts.length === 2 && attempts[0].original_bytes_digest === attempts[1].original_bytes_digest 163 && attempts[0].publication_policy_digest === attempts[1].publication_policy_digest, 'exact public retry/policy'); 164 assert(attempts.flatMap(value=>Array.from(value.target_ordinals)).sort().join(',') === '1,2', 'per-target original ordinals'); 165 attempts.forEach(value=>value.free()); 166 const accepted=resumed.delivery_observations; 167 assert(accepted.some(value=>value.outcome === TargetObservation.Accepted), 'actual retry acceptance'); accepted.forEach(value=>value.free()); 168 const publicEvents=await fetch(base+'/events'+publicRoute).then(response=>response.text()); 169 verify_listing_publications(publicEvents,revision); 170 const buyer=await BindingFixture.create(base.replace('http:','ws:')+privateRoute,'packed_private_'+context,false); 171 const buyerClient=buyer.client(), buyerScope=buyer.workspace(); await buyerClient.start(StartMode.Online); 172 const denied=new CommandRequest(id('14'),deadline()); 173 await refuses(()=>buyerClient.publish_listing(buyerScope,denied,input),'unauthorized'); 174 await refuses(()=>resumedClient.publish_listing(buyerScope,denied,input),'unauthorized'); 175 const inquiry=new InquiryInput(id('15'),peer,undefined,text), privateRequest=new CommandRequest(id('16'),deadline()); 176 const message=await buyerClient.inquire(buyerScope,privateRequest,inquiry); 177 receipt(message,id('16'),OperationKind.Chat); 178 const business=message.business_result; assert(business && business.listing_value() === undefined, 'private typed family'); 179 const chat=business.chat_value(); assert(chat && chat.text() === text && chat.thread_id() === id('15') && chat.peer() === peer 180 && chat.relation() === 'inquire' && chat.source() === undefined && chat.parent() === undefined, 'exact private original text/relation'); 181 const messageId=chat.id(); chat.free(); business.free(); 182 await verify_binding_inquiry(await fetch(base+'/events'+privateRoute).then(response=>response.text()),messageId,text); 183 const privateDigest=message.command_digest, privateCheckpoint=message.operation_checkpoint; 184 await buyerClient.close(); assert(buyer.callbacks_closed() === 1, 'private callbacks close once'); 185 const privateReopened=await buyer.reopen(), readClient=privateReopened.client(), readScope=privateReopened.workspace(); 186 await readClient.start(StartMode.LocalOnly); 187 const read=await query(readClient,readScope,id('16'),privateDigest); 188 assert(read.operation_checkpoint === privateCheckpoint && read.message_id === messageId, 'private exact reopen without network'); 189 await readClient.close(); await resumedClient.close(); 190 assert(privateReopened.callbacks_closed() === 1 && reopened.callbacks_closed() === 1, 'all original callback scopes close'); 191 await refuses(()=>client.start(StartMode.Online),'capability_unavailable'); 192 await rejectedSigners(base,context); 193 scope.close(); resumedScope.close(); buyerScope.close(); readScope.close(); 194 for (const value of [original,resumed,message,read]) value.free(); 195 for (const value of [request,denied,privateRequest,input,inquiry,scope,resumedScope,buyerScope,readScope,client,resumedClient,buyerClient,readClient,seller,reopened,buyer,privateReopened]) value.free(); 196 return {passed:['packed generated public call and exact replay','reopen/query and original exact-byte retry','all typed receipt axes','private JS call and independent nested authentication','bounded inputs, scope and lifecycle refusals','actual ordered close','bounded rejected signer metadata and exact coverage'],revision,messageId}; 197 }