@facto-to/card 0.0.0-stage → 0.0.1-beta.2

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 (69) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +63 -2
  5. package/dist/card-inbox-DzsHFRPT.d.cts +312 -0
  6. package/dist/card-inbox-DzsHFRPT.d.ts +312 -0
  7. package/dist/chunk-KBS2PWM4.js +2 -0
  8. package/dist/cli/index.js +6 -0
  9. package/dist/docs/README.md +9 -0
  10. package/dist/docs/authentication.md +96 -0
  11. package/dist/docs/authorization-binding.md +182 -0
  12. package/dist/docs/authorizations.md +182 -0
  13. package/dist/docs/concepts.md +36 -0
  14. package/dist/docs/deliveries.md +170 -0
  15. package/dist/docs/errors.md +100 -0
  16. package/dist/docs/getting-access.md +56 -0
  17. package/dist/docs/idempotency.md +78 -0
  18. package/dist/docs/integration-checklist.md +15 -0
  19. package/dist/docs/integration.zh.md +59 -0
  20. package/dist/docs/interlace-adapter-v1.md +87 -0
  21. package/dist/docs/interlace-adapter-v1.zh.md +87 -0
  22. package/dist/docs/not-yet-available.md +13 -0
  23. package/dist/docs/quickstart.md +126 -0
  24. package/dist/docs/reconciliation.md +86 -0
  25. package/dist/docs/reference/api.md +2541 -0
  26. package/dist/docs/reference/events.md +639 -0
  27. package/dist/docs/reference/schemas.json +6603 -0
  28. package/dist/docs/reference/schemas.md +1001 -0
  29. package/dist/docs/simulator.md +235 -0
  30. package/dist/docs/versioning.md +9 -0
  31. package/dist/index.cjs +3 -0
  32. package/dist/index.d.cts +987 -0
  33. package/dist/index.d.ts +987 -0
  34. package/dist/index.js +2 -0
  35. package/dist/source/build.mjs +5 -0
  36. package/dist/source/package.json +16 -0
  37. package/dist/source/src/connect/cli/deliveries.ts +48 -0
  38. package/dist/source/src/connect/cli/index.ts +57 -0
  39. package/dist/source/src/connect/server/card-binding-assertion.ts +312 -0
  40. package/dist/source/src/connect/server/card-client.ts +1018 -0
  41. package/dist/source/src/connect/server/card-delivery.ts +301 -0
  42. package/dist/source/src/connect/server/card-events.ts +473 -0
  43. package/dist/source/src/connect/server/card-idempotency.ts +27 -0
  44. package/dist/source/src/connect/server/card-inbox.ts +82 -0
  45. package/dist/source/src/connect/server/card-intent-token.ts +588 -0
  46. package/dist/source/src/connect/server/card-polling.ts +69 -0
  47. package/dist/source/src/connect/server/card-signing.ts +115 -0
  48. package/dist/source/src/connect/server/card-transport.ts +282 -0
  49. package/dist/source/src/connect/server/errors.ts +280 -0
  50. package/dist/source/src/connect/server/fixtures/engine/card-events.synthetic.ts +84 -0
  51. package/dist/source/src/connect/server/retry-after.ts +12 -0
  52. package/dist/source/src/connect/testing/card-inbox.ts +124 -0
  53. package/dist/source/src/connect/testing/card-scenarios.ts +243 -0
  54. package/dist/source/src/connect/testing/card-simulator-vectors.ts +262 -0
  55. package/dist/source/src/connect/testing/card-simulator.ts +531 -0
  56. package/dist/source/src/connect/testing/interlace-card-transactions.ts +704 -0
  57. package/dist/source/src/connect/testing/pure-sha256.ts +123 -0
  58. package/dist/source/src/connect/wire.d.ts +544 -0
  59. package/dist/source/src/index.ts +163 -0
  60. package/dist/source/src/testing-browser.ts +24 -0
  61. package/dist/source/src/testing.ts +26 -0
  62. package/dist/source/tsconfig.json +20 -0
  63. package/dist/testing-browser.d.ts +220 -0
  64. package/dist/testing-browser.js +5 -0
  65. package/dist/testing.cjs +6 -0
  66. package/dist/testing.d.cts +199 -0
  67. package/dist/testing.d.ts +199 -0
  68. package/dist/testing.js +5 -0
  69. package/package.json +60 -4
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import{createHash as At,randomUUID as nt}from"node:crypto";import{createServer as dn}from"node:http";import{createHash as Yt,createHmac as Qt,timingSafeEqual as Xt}from"node:crypto";var Jt=new Set([400,401,402,403,404,410,412,422,423]),Wt=new Set(["idempotency_payload_mismatch","mapping_revision_not_approved","fact_type_not_allowed","managed_route_refused","ambiguous_lookup_selector"]);function Gt(e){if(typeof e!="object"||e===null||Array.isArray(e))return{engineCode:void 0,requestId:void 0};let t=e;if(typeof t.error=="string"&&t.error.length>0)return{engineCode:t.error,requestId:typeof t.request_id=="string"&&t.request_id.length>0?t.request_id:void 0};if(typeof t.error=="object"&&t.error!==null&&!Array.isArray(t.error)){let r=t.error;return{engineCode:typeof r.code=="string"&&r.code.length>0?r.code:void 0,requestId:typeof r.request_id=="string"&&r.request_id.length>0?r.request_id:void 0}}return{engineCode:typeof t.code=="string"&&t.code.length>0?t.code:void 0,requestId:typeof t.request_id=="string"&&t.request_id.length>0?t.request_id:void 0}}function Zt(e,t,r){return e==="FACTO_CONFIG_INVALID"?"config_invalid":e==="FACTO_ENGINE_RESPONSE_INVALID"||e==="FACTO_REQUEST_ABORTED"||e==="FACTO_STATUS_POLL_ABORTED"||t===void 0?"unknown":Jt.has(t)||t===409&&r!==void 0&&Wt.has(r)?"refused":"unknown"}var Ze=class extends Error{code;retryable;status;details;retryAfterSeconds;constructor(t,r,n){super(r),this.name="FactoConnectServerError",this.code=t,this.retryable=n.retryable,this.status=n.status,this.details=n.details,this.retryAfterSeconds=n.retryAfterSeconds}},B=class extends Ze{outcome;engineCode;httpStatus;requestId;constructor(t,r,n){let a=n.httpStatus??n.status;super(t,r,{retryable:n.retryable,status:a,details:n.details,retryAfterSeconds:n.retryAfterSeconds}),this.name="CardError",this.httpStatus=a;let c=Gt(n.details);this.engineCode=n.engineCode??c.engineCode,this.requestId=n.requestId??c.requestId,this.outcome=n.outcome??Zt(t,a,this.engineCode)}};var en=/^(?:[0-9a-fA-F]{2})+$/;function ue(e){return new B("FACTO_CONFIG_INVALID",e,{retryable:!1})}function Te(e){if(typeof e=="string")throw ue("apiKeySecret cannot be a bare string; pass { encoding: 'hex', value }, { encoding: 'utf8', value }, or Uint8Array");if(e instanceof Uint8Array){if(e.byteLength===0)throw ue("apiKeySecret Uint8Array must not be empty");return new Uint8Array(e)}if(typeof e!="object"||e===null||Array.isArray(e))throw ue("apiKeySecret must be { encoding: 'hex', value }, { encoding: 'utf8', value }, or Uint8Array");if(Object.keys(e).length!==2||!Object.hasOwn(e,"encoding")||!Object.hasOwn(e,"value"))throw ue("apiKeySecret must contain only { encoding: 'hex' | 'utf8', value: string }");let{encoding:r,value:n}=e;if(r==="utf8"){if(typeof n!="string"||n.length===0)throw ue("apiKeySecret with encoding 'utf8' must have a non-empty string value");return new TextEncoder().encode(n)}if(r==="hex"){if(typeof n!="string"||!en.test(n))throw ue("apiKeySecret with encoding 'hex' must be a non-empty, even-length hexadecimal string");let a=new Uint8Array(n.length/2);for(let c=0;c<n.length;c+=2)a[c/2]=Number.parseInt(n.slice(c,c+2),16);return a}throw ue("apiKeySecret encoding must be 'hex' or 'utf8', or pass a Uint8Array")}function he(e){let t=Te(e.secret),r=Yt("sha256").update(e.body).digest("hex"),n=["FACTO-HMAC-V2",e.method,e.target,String(e.timestamp),e.nonce,r].join(`
3
+ `),a=new Headers({"x-api-key":e.apiKeyId,"x-api-timestamp":String(e.timestamp),"x-api-nonce":e.nonce,"x-api-signature":Qt("sha256",t).update(n,"utf8").digest("hex")});return e.idempotencyKey!==void 0&&a.set("Idempotency-Key",e.idempotencyKey),a}function yt(e){let t=Te(e.secret),r=new Headers(e.headers),n=r.get("x-api-timestamp"),a=r.get("x-api-nonce"),c=r.get("x-api-signature");if(r.get("x-api-key")!==e.apiKeyId||!n||!/^\d{10}$/.test(n)||!a||!/^[\x21-\x7e]{1,128}$/.test(a)||!c||!/^[a-f0-9]{64}$/.test(c))return!1;let m=he({...e,secret:t,timestamp:Number(n),nonce:a}).get("x-api-signature");return Xt(Buffer.from(c,"hex"),Buffer.from(m,"hex"))}var F={envelope_version:2,event_id:"00000000-0000-4000-8000-000000000001",environment:"dev",program_id:"cprog_SYNTHETIC00000001",origin_connection_id:"pconn_SYNTHETIC00000001",connection_sequence:1,occurred_at:"2026-11-18T00:00:00Z"},L={...F,binding_id:"cb_01JZ9X8K4M2V7R5T3N6P8Q0W2Z",binding_revision:1},Qe={network:"Visa",type:"virtual",last4:"4242"},Pe={network:null,type:null,last4:null},De={binding_id:L.binding_id,intent_id:null,external_card_id:"scp_card_0001",subject_link_id:"csl_synthetic",card:Qe,approved_scopes:["card.metadata.view"],consent_revision:"synthetic"},le={operation_type:"authorization_requested",resource_version:"v1",external_authorization_id:"synthetic-auth",mapping_revision:"synthetic-mapping"},ft=[{kind:"facto_admission",state:"confirmed",recorded_at:F.occurred_at,source_system:"facto",observed_at:F.occurred_at},{kind:"durable_commit",state:"confirmed",recorded_at:F.occurred_at,source_system:"facto",observed_at:F.occurred_at},{kind:"provider_authorization",state:"unobserved",recorded_at:F.occurred_at,source_system:"provider"},{kind:"chain_finality",state:"confirmed",recorded_at:F.occurred_at,source_system:"chain",observed_at:F.occurred_at},{kind:"provider_settlement",state:"unobserved",recorded_at:F.occurred_at,source_system:"provider"}],tn=ft.map(e=>e.kind==="provider_authorization"?{...e,state:"confirmed",observed_at:F.occurred_at}:e),Ye={receipt_event_id:F.event_id,charge_id:"0x"+"0".repeat(62)+"01",external_authorization_id:le.external_authorization_id,mapping_revision:le.mapping_revision,operation_type:le.operation_type,resource_version:le.resource_version,execution_outcome:"succeeded",terminal_action:"releaseFor",finalized_at:F.occurred_at,facts_at_finality:ft},Ne=[{...L,event_kind:"card.binding.linked",data:De},{...L,event_kind:"card.binding.linked",connection_sequence:null,data:{...De,intent_id:"cint_01JZ9X8K4M2V7R5T3N6P8Q0W2Y",card:Pe}},{...L,event_kind:"card.binding.relinked",data:De},{...L,event_kind:"card.binding.relinked",connection_sequence:null,data:{...De,intent_id:"cint_01JZ9X8K4M2V7R5T3N6P8Q0W2Y",card:Pe}},{...L,event_kind:"card.binding.revoked",data:{binding_id:L.binding_id,binding_revision:1,external_card_id:"scp_card_0001",card:Qe,revocation_source:"user_portfolio",reason_code:"user_requested",payable_projections_closed:0,routes_detached:0}},{...L,event_kind:"card.binding.revoked",connection_sequence:null,data:{binding_id:L.binding_id,binding_revision:1,external_card_id:"scp_card_0001",card:Pe,revocation_source:"provider_lifecycle_event",payable_projections_closed:0,routes_detached:0}},{...L,event_kind:"card.binding.route_changed",data:{binding_id:L.binding_id,binding_revision:1,association_status:"associated"}},{...L,event_kind:"card.binding.route_changed",connection_sequence:null,data:{binding_id:L.binding_id,binding_revision:1,association_status:"unassociated"}},{...L,event_kind:"card.binding.limits_changed",data:{binding_id:L.binding_id,binding_revision:1,per_tx_limit:"1.000000",period_limit:"2.000000",period:"monthly",expires_at:"2027-01-01T00:00:00Z"}},{...L,event_kind:"card.binding.limits_changed",connection_sequence:null,data:{binding_id:L.binding_id,binding_revision:1,per_tx_limit:"1.000000",period_limit:"2.000000",period:"monthly",expires_at:null}},{...L,event_kind:"card.binding.ownership_transferred",data:{previous_binding_id:L.binding_id,new_binding_id:"cb_new0000000000001",external_card_id:"scp_card_0001",card:Qe,transferred_at:F.occurred_at}},{...L,event_kind:"card.binding.ownership_transferred",connection_sequence:null,data:{previous_binding_id:L.binding_id,new_binding_id:"cb_new0000000000001",external_card_id:"scp_card_0001",card:Pe,transferred_at:F.occurred_at}},{...F,event_kind:"card.charge.finalized",data:{authorization_revision:1,...le,final_receipt:Ye}},{...F,event_id:"00000000-0000-4000-8000-000000000002",event_kind:"card.charge.facts_updated",connection_sequence:2,data:{authorization_revision:2,...le,charge_id:Ye.charge_id,final_receipt_event_id:Ye.receipt_event_id,previous_authorization_revision:1,facts:tn}},{...F,event_kind:"card.authorization.updated",data:{lifecycle_revision:1,...le,authorization:{amount:"1.000000",currency:"USDC"},charge:null,issuer:{state:"authorized",cleared_amount:"0.000000",reversed_amount:"0.000000",refunded_amount:"0.000000",entry_count:0,unlinked_count:0},refunds:{case_count:0,status_counts:{awaiting_charge_final:0,awaiting_funds:0,payable:0,paid:0,failed:0,not_payable:0},total_amount:"0.000000",total_paid_amount:"0.000000",total_excess_amount:"0.000000"},change:{type:"authorization.recorded",at:F.occurred_at}}}];var nn=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),rn=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),on=new TextEncoder;function gt(e){return typeof e=="string"?on.encode(e):e}function ne(e,t){return e>>>t|e<<32-t}function qe(e){let t=gt(e),r=Math.floor(t.byteLength*8/4294967296),n=t.byteLength*8>>>0,a=Math.ceil((t.byteLength+9)/64)*64,c=new Uint8Array(a);c.set(t),c[t.byteLength]=128;let m=new DataView(c.buffer);m.setUint32(a-8,r,!1),m.setUint32(a-4,n,!1);let y=new Uint32Array(rn),i=new Uint32Array(64);for(let _=0;_<a;_+=64){for(let l=0;l<16;l+=1)i[l]=m.getUint32(_+l*4,!1);for(let l=16;l<64;l+=1){let I=ne(i[l-15],7)^ne(i[l-15],18)^i[l-15]>>>3,h=ne(i[l-2],17)^ne(i[l-2],19)^i[l-2]>>>10;i[l]=i[l-16]+I+i[l-7]+h>>>0}let f=y[0],d=y[1],A=y[2],O=y[3],D=y[4],N=y[5],o=y[6],S=y[7];for(let l=0;l<64;l+=1){let I=ne(D,6)^ne(D,11)^ne(D,25),h=D&N^~D&o,w=S+I+h+nn[l]+i[l]>>>0,M=ne(f,2)^ne(f,13)^ne(f,22),de=f&d^f&A^d&A,J=M+de>>>0;S=o,o=N,N=D,D=O+w>>>0,O=A,A=d,d=f,f=w+J>>>0}y[0]=y[0]+f>>>0,y[1]=y[1]+d>>>0,y[2]=y[2]+A>>>0,y[3]=y[3]+O>>>0,y[4]=y[4]+D>>>0,y[5]=y[5]+N>>>0,y[6]=y[6]+o>>>0,y[7]=y[7]+S>>>0}let u=new Uint8Array(32),s=new DataView(u.buffer);for(let _=0;_<8;_+=1)s.setUint32(_*4,y[_],!1);return u}function mt(e){let t="";for(let r=0;r<e.byteLength;r+=1)t+=e[r].toString(16).padStart(2,"0");return t}function be(e){return mt(qe(e))}function ve(e,t){let n=new Uint8Array(64),a=e.byteLength>64?qe(e):e;n.set(a);let c=new Uint8Array(64),m=new Uint8Array(64);for(let _=0;_<64;_+=1)c[_]=n[_]^54,m[_]=n[_]^92;let y=gt(t),i=new Uint8Array(64+y.byteLength);i.set(c,0),i.set(y,64);let u=qe(i),s=new Uint8Array(96);return s.set(m,0),s.set(u,64),mt(qe(s))}var vt={connectionId:"pconn_SYNTHETIC00000001",environment:"dev",programId:"cprog_SYNTHETIC00000001",targetRevision:"00000000-0000-4000-8000-000000000001"},Xe="card.binding.linked",wt=new TextEncoder().encode("synthetic-delivery-test-key"),ht={...vt,keyId:"synthetic-key",signerKeyVersion:1,notBefore:"2026-01-01T00:00:00Z",expiresAt:"2027-01-01T00:00:00Z",status:"active",eventKinds:[Xe],secret:wt};function xe(e,t=!1,r=!1){let n=`00000000-0000-4000-8000-${String(e).padStart(12,"0")}`,a=JSON.stringify({...Ne[t||r?1:0],event_id:n,binding_revision:e,connection_sequence:t?null:e}),c=new TextEncoder().encode(a),m="1792713600",y=be(c),i=ve(wt,["facto:card:outbound-delivery-signature","v1",n,Xe,m,y].join(`
4
+ `));return{rawBody:c,headers:[["facto-signature",`v1=${i}`],["facto-signature-key-id",ht.keyId],["facto-event-id",n],["facto-event-kind",Xe],["facto-event-timestamp-seconds",m],["facto-delivery-attempt","1"]],registry:[ht],expectedScope:vt,nowSeconds:Number(m)}}var we=xe(1),an=xe(2),bt=xe(3),fe={duplicate:{deliveries:[we,we]},outOfOrder:{deliveries:[we,bt,an]},gap:{deliveries:[we,bt]},nullableCard:{deliveries:[xe(1,!1,!0)]},unsequenced:{deliveries:[xe(4,!0),we]}};var xt=Object.freeze({revision:"2026-11-18-card-events.1",digest:"sha256:9fcad68499ef3f770533ad3f3a4c4950d16c0385c56b2b0af6bba5375038aa98",approvedFeatureSnapshot:Object.freeze(["binding","new_consumption","supplier_fact_updates"]),featureClosures:Object.freeze({binding:Object.freeze(["card.binding.linked","card.binding.relinked","card.binding.revoked","card.binding.route_changed","card.binding.limits_changed","card.binding.ownership_transferred"]),new_consumption:Object.freeze(["card.charge.finalized"]),supplier_fact_updates:Object.freeze(["card.charge.facts_updated"])})}),kr=Object.freeze({revision:"2026-11-18-card-events.1",digest:"sha256:9fcad68499ef3f770533ad3f3a4c4950d16c0385c56b2b0af6bba5375038aa98",approvedFeatureSnapshot:Object.freeze([...xt.approvedFeatureSnapshot,"authorization_updates"]),featureClosures:Object.freeze({...xt.featureClosures,authorization_updates:Object.freeze(["card.authorization.updated"])})}),sn="synthetic-delivery-test-key",X=["duplicate","outOfOrder","gap","nullableCard","unsequenced","authorizationOutOfOrder","authorizationRedelivery","refundAwaitingChargeFinal","refundAwaitingFunds","refundPayable","refundPaid","refundFailed","refundNotPayable","chargeFailed"],et="card.binding.linked",tt="card.authorization.updated";function ge(e){let t=X.indexOf(e)+1;return{name:e,selectionId:`00000000-0000-4000-8000-${String(100+t).padStart(12,"0")}`,connectionId:`pconn_SYNTHETIC0000000${t}`,programId:"cprog_SYNTHETIC00000001",environment:"dev",targetRevision:"00000000-0000-4000-8000-000000000001",keyId:`synthetic-delivery-${e}`,secretUtf8:sn,signerKeyVersion:1,notBefore:"2020-01-01T00:00:00Z",expiresAt:"2099-01-01T00:00:00Z",status:"active",eventKinds:[t>5?tt:et]}}function me(e,t=Math.floor(Date.now()/1e3),r=1){let n=ge(e),a={connectionId:n.connectionId,programId:n.programId,environment:n.environment,targetRevision:n.targetRevision},c={...a,keyId:n.keyId,secret:new TextEncoder().encode(n.secretUtf8),signerKeyVersion:n.signerKeyVersion,notBefore:n.notBefore,expiresAt:n.expiresAt,status:n.status,eventKinds:n.eventKinds};if(e.startsWith("authorization")||e.startsWith("refund")||e==="chargeFailed"){let i=Ne.find(f=>f.event_kind==="card.authorization.updated"),s={refundAwaitingChargeFinal:"awaiting_charge_final",refundAwaitingFunds:"awaiting_funds",refundPayable:"payable",refundPaid:"paid",refundFailed:"failed",refundNotPayable:"not_payable"}[e],_=(f,d)=>{let A=`00000000-0000-4000-8002-${String(X.indexOf(e)*10+f+(d?1:0)).padStart(12,"0")}`,O=s?{case_id:"rfc_00000000000000000000000000000001",source_operation_type:"refund",status:s,amount:"1.000000",excess_amount:"0.000000",updated_at:i.occurred_at,...s==="paid"?{paid_amount:"1.000000",refund_payment:{chain_id:8453,tx_hash:`0x${"1".repeat(64)}`,paid_amount:"1.000000",recorded_by:"operator"}}:{}}:void 0,D={...i,event_id:A,program_id:n.programId,origin_connection_id:n.connectionId,connection_sequence:f+(d?1:0),data:{...i.data,lifecycle_revision:f,...s?{refunds:{...i.data.refunds,case_count:1,status_counts:{...i.data.refunds.status_counts,[s]:1},total_amount:"1.000000",total_paid_amount:s==="paid"?"1.000000":"0.000000"},charge:{charge_id:`0x${"2".repeat(64)}`,status:s==="awaiting_charge_final"?"processing":"succeeded",amount:"1.000000",fee_total:"0.000000",total_debited:"1.000000",currency:"USDC",updated_at:i.occurred_at}}:{},...e==="chargeFailed"?{charge:{charge_id:`0x${"2".repeat(64)}`,status:"failed",amount:"1.000000",fee_total:"0.000000",total_debited:"0.000000",currency:"USDC",failure_code:"synthetic_failure",updated_at:i.occurred_at}}:{},change:s?{type:`refund_case.${s}`,at:i.occurred_at,refund_case:O}:i.data.change}},N=new TextEncoder().encode(JSON.stringify(D)),o=String(t),S=be(N),I=[["facto-signature",`v1=${ve(c.secret,["facto:card:outbound-delivery-signature","v1",A,tt,o,S].join(`
5
+ `))}`],["facto-signature-key-id",c.keyId],["facto-event-id",A],["facto-event-kind",tt],["facto-event-timestamp-seconds",o],["facto-delivery-attempt",String(d?Math.max(r,2):r)]];return d&&I.push(["facto-redelivery-reason","retry"]),{rawBody:N,headers:I,registry:[c],expectedScope:a}};return{config:n,deliveries:e==="authorizationOutOfOrder"?[_(2,!1),_(1,!1)]:e==="authorizationRedelivery"?[_(1,!1),_(1,!0)]:[_(1,!1)]}}let m=fe[e],y=(i,u)=>{let s=JSON.parse(new TextDecoder().decode(i.rawBody)),_=Number(s.event_id.slice(-12));s.event_id=`00000000-0000-4000-8001-${X.indexOf(e)+1}${String(_).padStart(11,"0")}`,s.origin_connection_id=n.connectionId;let f=new TextEncoder().encode(JSON.stringify(s)),d=String(t),A=be(f),O=ve(c.secret,["facto:card:outbound-delivery-signature","v1",s.event_id,et,d,A].join(`
6
+ `));return{rawBody:f,headers:[["facto-signature",`v1=${O}`],["facto-signature-key-id",c.keyId],["facto-event-id",s.event_id],["facto-event-kind",et],["facto-event-timestamp-seconds",d],["facto-delivery-attempt",String(u)]],registry:[c],expectedScope:a}};return{config:n,deliveries:m.deliveries.map((i,u)=>y(i,r+(e==="duplicate"&&u===1?1:0)))}}var U={connectionId:"pconn_SYNTHETIC00000001",programId:"synthetic-program",apiKeyId:"synthetic-key",apiKeySecret:{encoding:"utf8",value:"SYNTHETIC-TEST-KEY-NOT-A-SECRET"}},ae="00000000-0000-4000-8000-000000000001",_e="00000000-0000-4000-8000-000000000002",cn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,St=/^cint_[A-Za-z0-9_-]{16,}$/;async function It(e=0,t={}){let r=t.capacity??1e3,n=t.ttlMs??6e5,a=t.nowMs??Date.now;if(!Number.isSafeInteger(r)||r<1||!Number.isSafeInteger(n)||n<1)throw new Error("Invalid simulator limits");let c=new Map,m=new Map,y=new Map,i=new Map,u=new Map,s=new Map,_=new Map,f=(l,I)=>JSON.stringify([l,I]),d=(l,I)=>JSON.stringify([l,I]),A=(l,I)=>JSON.stringify([typeof l=="string"?l.trim():l,I]),O=l=>{let I=typeof l.amount=="string"?l.amount.trim().match(/^(\d+)(?:\.(\d{1,6}))?$/):null,h=l.cardholder_verification,w=l.supplier_transaction_id!==void 0||l.client_transaction_id!==void 0,M=l.supplier_transaction_id!==void 0||l.decision_mode==="synchronous",de=J=>typeof J=="string"?J.trim():null;return JSON.stringify({card:l.external_card_id,currency:l.currency,amount:I?(BigInt(I[1])*1000000n+BigInt((I[2]??"").padEnd(6,"0"))).toString():l.amount,...w?{supplier:de(l.supplier_transaction_id),client:de(l.client_transaction_id)}:{},...M?{merchant:l.merchant_name??null,mcc:l.merchant_mcc??null,method:h?.method,verifiedAt:h?.verified_at,evidence:h?.evidence_id}:{},...l.decision_mode==="synchronous"?{mode:"synchronous",timeout:l.decision_timeout_ms??2e3,deadline:l.deadline_at??null}:{}})},D=(l,I)=>{let h=w=>typeof w=="string"?w.trim():null;return JSON.stringify({externalAuthId:l,factType:I.fact_type,currency:I.currency,amount:I.amount,predecessor:I.predecessor_version,supplier:h(I.supplier_transaction_id),parent:h(I.parent_supplier_transaction_id),client:h(I.client_transaction_id)})};function N(l){for(let[I,h]of _)h<=l&&_.delete(I);for(let[I,h]of s)h.expiresAt<=l&&s.delete(I);for(let[I,h]of m)if(h.expiresAt<=l){m.delete(I),y.delete(h.lineageVersion),u.delete(h.chargeId),h.supplierIdentity&&i.delete(h.supplierIdentity);for(let w of h.keys)c.delete(w)}}let o=dn(async(l,I)=>{let h=(v,b,k={})=>{I.writeHead(v,{"content-type":"application/json",...k}),I.end(JSON.stringify(b))},w=(v,b,k)=>h(v,{error:b,message:"Synthetic simulator response",request_id:"synthetic-request"},k),M=[],de=0;for await(let v of l){let b=Buffer.from(v);if(de+=b.length,de>1024*1024){w(413,"invalid_request");return}M.push(b)}let J=Buffer.concat(M),re=a();N(re);let ze=new URL(l.url??"/","http://127.0.0.1"),ce=ze.pathname,Oe=l.headers["x-api-timestamp"],Re=l.headers["x-api-nonce"],dt=l.headers["x-api-signature"],oe=l.method==="POST"||l.method==="PUT"||l.method==="GET"?l.method:null;if(!oe||l.headers["x-api-key"]!==U.apiKeyId||typeof Oe!="string"||!/^\d{10}$/.test(Oe)||Math.abs(Math.floor(re/1e3)-Number(Oe))>300||typeof Re!="string"||!Re||_.has(Re)||typeof dt!="string"||!/^[0-9a-f]{64}$/.test(dt)){w(401,"authentication_failed");return}let ct=new Headers;for(let[v,b]of Object.entries(l.headers))typeof b=="string"&&ct.set(v,b);if(!yt({secret:U.apiKeySecret,apiKeyId:U.apiKeyId,method:oe,target:l.url??"",body:J,headers:ct})){w(401,"authentication_failed");return}if(_.size>=r){w(503,"internal_error");return}if(_.set(Re,(Number(Oe)+301)*1e3),oe==="GET"&&ce==="/api/card/deliveries/dead-letters"){if(J.length>0){w(400,"invalid_request");return}let v=ze.searchParams.get("limit");for(let[b]of ze.searchParams)if(b!=="limit"){w(400,"invalid_request");return}if(ze.searchParams.getAll("limit").length>1){w(400,"invalid_request");return}if(v!==null&&(!/^\d+$/.test(v)||Number(v)<1||Number(v)>100)){w(400,"invalid_request");return}h(200,{items:[]});return}let Ge=v=>typeof v=="string"&&[...v].length>=32&&[...v].length<=8192&&/^[\x21-\x7e]+$/.test(v),ut=ce.match(/^\/api\/card\/connect\/intents\/([^/]+)\/cards$/);if(ut){let v=decodeURIComponent(ut[1]);if(!St.test(v)){w(400,"invalid_request");return}if(oe==="GET"){let b=l.headers["x-facto-intent-token"];if(J.length>0||!Ge(b)){w(400,"invalid_request");return}h(200,{id:v,revision:`sha256:${"0".repeat(64)}`,cards:[]});return}if(oe==="PUT"){let b=l.headers["idempotency-key"];if(typeof b!="string"||b.length<16){w(400,"invalid_request");return}let k;try{k=JSON.parse(J.toString("utf8"))}catch{w(400,"invalid_request");return}if(!Ge(k.intent_token)||typeof k.approval_id!="string"||k.approval_id.length===0||typeof k.approval_sha256!="string"||!/^[a-f0-9]{64}$/.test(k.approval_sha256)||typeof k.revision!="string"||!/^sha256:[a-fA-F0-9]{64}$/.test(k.revision)){w(400,"invalid_request");return}let G=Array.isArray(k.cards)?k.cards:[];h(200,{id:v,status:"applied",revision:`sha256:${"f".repeat(64)}`,added_binding_ids:G.map((T,K)=>`cb_SYNTHETIC0000000${K+1}`),removed_binding_ids:[],kept_binding_ids:[]});return}w(404,"not_found");return}let lt=ce.match(/^\/api\/card\/connect\/intents\/([^/]+)\/cancel$/);if(oe==="POST"&&lt){let v=decodeURIComponent(lt[1]);if(!St.test(v)){w(400,"invalid_request");return}let b;try{b=JSON.parse(J.toString("utf8"))}catch{w(400,"invalid_request");return}if(!b||typeof b!="object"||Array.isArray(b)||!Ge(b.intent_token)){w(400,"invalid_request");return}h(200,{id:v,status:"cancelled"});return}let _t=ce.match(/^\/api\/card\/deliveries\/dead-letters\/([^/]+)\/replay$/);if(oe==="POST"&&_t){let v=decodeURIComponent(_t[1]);if(!cn.test(v)){w(404,"not_found");return}h(202,{id:v,status:"accepted"});return}if(oe!=="POST"){w(404,"not_found");return}let p;try{if(p=JSON.parse(J.length?J.toString("utf8"):"{}"),!p||typeof p!="object"||Array.isArray(p))throw new Error}catch{w(400,"invalid_request");return}typeof p.supplier_transaction_id=="string"&&(p.supplier_transaction_id=p.supplier_transaction_id.trim());let pt=ce.match(/^\/api\/card\/authorizations\/([^/]+)\/facts$/);if(pt){let v=decodeURIComponent(pt[1]);if(p.program_id!==U.programId){w(403,"program_grant_denied");return}let b=l.headers["idempotency-key"];if(typeof b!="string"||b.length<16){w(400,"invalid_request");return}if(!["authorization_updated","clearing","reversal","refund","chargeback","settlement"].includes(String(p.fact_type))||typeof p.predecessor_version!="string"||!p.predecessor_version||p.predecessor_version===p.resource_version||typeof p.recorded_at!="string"||!Number.isFinite(Date.parse(p.recorded_at))){w(400,"invalid_request");return}let G=J,T=c.get(b);if(T&&!T.raw.equals(G)){w(409,"integrity_conflict");return}let K=f(v,p.resource_version),te=D(v,p),C=m.get(K);if(C&&C.normalized!==te){w(409,"integrity_conflict");return}if(!y.has(d(v,p.predecessor_version))){w(409,"integrity_conflict");return}let q=d(v,p.resource_version),Q=y.get(q);if(Q&&Q.identity!==K){w(409,"integrity_conflict");return}let Z=p.supplier_transaction_id?i.get(A(p.supplier_transaction_id,p.resource_version)):void 0;if(Z&&Z.identity!==K){w(409,"integrity_conflict");return}if(!T&&c.size>=r){w(503,"internal_error");return}let j=T?.operation??C;if(!j){let W=nt(),Ht=`0x${"0".repeat(32)}${W.replaceAll("-","")}`;j={externalAuthorizationId:v,factType:String(p.fact_type),body:{...p,external_authorization_id:v},identity:K,normalized:te,lineageVersion:q,chargeId:Ht,operationId:W,expiresAt:re+n,keys:new Set,statusReads:0,...p.supplier_transaction_id?{supplierIdentity:A(p.supplier_transaction_id,p.resource_version)}:{}},m.set(K,j),y.set(q,j),j.supplierIdentity&&i.set(j.supplierIdentity,j)}T||(c.set(b,{raw:G,operation:j}),j.keys.add(b)),h(200,{operation_id:j.operationId,status:"recorded"});return}if(["/api/card/authorizations","/api/card/authorizations/lookup","/api/card/deliveries/reconciliations/list","/api/card/deliveries/replays"].includes(ce)&&p.program_id!==U.programId){w(403,"program_grant_denied");return}let Ee=J,Y=new Date(re).toISOString(),ee=l.headers["idempotency-key"];switch(ce){case"/api/card/authorizations":{if(typeof ee!="string"||ee.length<16){w(400,"invalid_request");return}if(p.decision_mode==="synchronous"&&(p.decision_timeout_ms!==void 0&&(typeof p.decision_timeout_ms!="number"||!Number.isInteger(p.decision_timeout_ms)||p.decision_timeout_ms<50||p.decision_timeout_ms>5e3)||p.deadline_at!==void 0&&(typeof p.deadline_at!="string"||!Number.isFinite(Date.parse(p.deadline_at))))){w(400,"invalid_request");return}if(p.decision_mode!=="synchronous"&&(p.decision_timeout_ms!==void 0||p.deadline_at!==void 0)){w(400,"invalid_request");return}if(typeof p.external_authorization_id!="string"||!p.external_authorization_id||typeof p.external_card_id!="string"||!p.external_card_id){w(400,"invalid_request");return}let v=c.get(ee);if(v&&!v.raw.equals(Ee)){w(409,"integrity_conflict");return}let b=f(p.external_authorization_id,p.resource_version),k=O(p),G=m.get(b);if(G&&G.normalized!==k){w(409,"integrity_conflict");return}if(p.decision_mode!=="synchronous"&&p.external_card_id==="synthetic-rate-limited-card"){h(429,{error:{category:"rate_limited",code:"too_many_requests",message:"Synthetic rate limit",request_id:"synthetic-request",retryable:!0}},{"retry-after":"2"});return}if(p.decision_mode!=="synchronous"&&p.external_card_id==="synthetic-bad-gateway-card"){I.writeHead(502,{"content-type":"text/html","retry-after":"2"}),I.end("<html>Synthetic gateway error</html>");return}if(p.decision_mode!=="synchronous"&&p.external_card_id==="synthetic-nested-500-card"){h(500,{error:{category:"internal",code:"synthetic_unavailable",message:"Synthetic failure",request_id:"synthetic-request",retryable:!1}});return}if(p.decision_mode!=="synchronous"&&p.external_card_id==="synthetic-retry-card"&&!v){let q=s.get(ee);if(!q){if(s.size>=r){w(503,"internal_error");return}s.set(ee,{raw:Ee,expiresAt:re+n}),w(503,"internal_error");return}if(!q.raw.equals(Ee)){w(409,"integrity_conflict");return}s.delete(ee)}let T=d(p.external_authorization_id,p.resource_version),K=y.get(T);if(K&&K.identity!==b){w(409,"integrity_conflict");return}let te=p.supplier_transaction_id?i.get(A(p.supplier_transaction_id,p.resource_version)):void 0;if(te&&te.identity!==b){w(409,"integrity_conflict");return}if(!v&&c.size>=r){w(503,"internal_error");return}let C=v?.operation??G;if(!C){let q=p.decision_mode==="synchronous"?Math.min(re+(typeof p.decision_timeout_ms=="number"?p.decision_timeout_ms:2e3),typeof p.deadline_at=="string"?Date.parse(p.deadline_at):1/0):void 0,Q=nt(),Z=`0x${"0".repeat(32)}${Q.replaceAll("-","")}`;C={externalAuthorizationId:p.external_authorization_id,factType:"authorization_requested",body:p,identity:b,normalized:k,lineageVersion:T,chargeId:Z,operationId:Q,deadline:q,expiresAt:re+n,keys:new Set,statusReads:0,...q!==void 0?{decision:q<=re?"self_reversed_timeout":"declined"}:{},...p.supplier_transaction_id?{supplierIdentity:A(p.supplier_transaction_id,p.resource_version)}:{}},m.set(b,C),y.set(T,C),C.supplierIdentity&&i.set(C.supplierIdentity,C),p.decision_mode!=="synchronous"&&u.set(Z,C)}if(v||(c.set(ee,{raw:Ee,operation:C}),C.keys.add(ee)),p.decision_mode==="synchronous"){let q=C.deadline!==void 0&&C.deadline<=re;h(q?408:422,{...q?{}:{decision:"declined",decided_at:Y},error:q?"decision_deadline_exceeded":"sync_approval_admission_closed",message:"Synthetic simulator decision",request_id:"synthetic-request",decision_id:C.operationId,deadline_at:new Date(C.deadline).toISOString()});return}if(p.external_card_id==="synthetic-declined-card"){w(402,"spending_limit_exceeded");return}h(200,{charge_id:C.chargeId,status:"processing"});return}case"/api/card/authorizations/lookup":{let v=p.criteria,b=v?.by==="idempotency_key"&&v.original_credential_key_id===U.apiKeyId&&typeof v.idempotency_key=="string"?c.get(v.idempotency_key)?.operation:v?.by==="charge_id"&&typeof v.charge_id=="string"?u.get(v.charge_id):v?.by==="external_authorization_id"?m.get(f(v.external_authorization_id,v.resource_version)):v?.by==="supplier_transaction_id"?i.get(A(v.supplier_transaction_id,v.resource_version)):void 0;if(!b||(v?.by==="external_authorization_id"||v?.by==="supplier_transaction_id")&&(v.mapping_revision!==b.body.mapping_revision||v.fact_type!==void 0&&v.fact_type!==b.factType)){h(200,{observed_at:Y,resolution:"not_observed"});return}let k=b.body,G=b.statusReads++;if(["synthetic-terminal-card","synthetic-failed-card"].includes(String(k.external_card_id))&&b.factType==="authorization_requested"&&G>0){let C=b.finalizedAt??Y;b.finalizedAt=C;let q=["facto_admission","durable_commit","provider_authorization","chain_finality","provider_settlement"].map(W=>W.startsWith("provider_")?{kind:W,state:"unobserved",source_system:"provider",recorded_at:C}:{kind:W,state:"confirmed",source_system:W==="chain_finality"?"chain":"facto",recorded_at:C,observed_at:C}),Q={resource_version:k.resource_version,mapping_revision:k.mapping_revision,external_authorization_id:b.externalAuthorizationId,charge_id:b.chargeId},Z=k.external_card_id==="synthetic-failed-card",j={receipt_event_id:b.operationId,charge_id:b.chargeId,authorization_ref:b.externalAuthorizationId,mapping_revision:k.mapping_revision,operation_type:b.factType,resource_version:k.resource_version,execution_outcome:Z?"failed":"succeeded",terminal_action:Z?"cancelReservation":"releaseFor",finalized_at:C,facts_at_finality:q};h(200,{observed_at:Y,resolution:"resolved",authorization:{...Q,operation_type:b.factType,origin_connection_id:U.connectionId,processing_status:Z?"failed":"succeeded",facts:q,revision:2,final_receipt:j,...k.supplier_transaction_id?{supplier_transaction_id:k.supplier_transaction_id}:{}}});return}let T=b.factType==="authorization_requested",K=b.decision||k.external_card_id==="synthetic-declined-card",te=["facto_admission","durable_commit","provider_authorization","chain_finality","provider_settlement"].map(C=>{let q=C==="durable_commit"||C==="facto_admission"&&T&&!K;return{kind:C,state:q?"confirmed":"unobserved",source_system:C.startsWith("provider_")?"provider":C==="chain_finality"?"chain":"facto",recorded_at:Y,...q?{observed_at:Y}:{}}});h(200,{observed_at:Y,resolution:K?"resolved":T?"pending":"unknown",authorization:{origin_connection_id:U.connectionId,processing_status:K?"failed":T?"processing":"indeterminate",facts:te,revision:1,operation_type:b.factType,resource_version:k.resource_version,mapping_revision:k.mapping_revision,external_authorization_id:b.externalAuthorizationId,...T&&!b.decision?{charge_id:b.chargeId}:{},...b.decision?{decision:b.decision,decline_reason_code:b.decision==="declined"?"sync_approval_admission_closed":"decision_deadline_exceeded"}:k.external_card_id==="synthetic-declined-card"?{decline_reason_code:"spending_limit_exceeded"}:{},...k.supplier_transaction_id?{supplier_transaction_id:k.supplier_transaction_id}:{}}});return}case"/api/card/deliveries/reconciliations/list":{let v=X.find(T=>ge(T).selectionId===p.selection_id);if(v&&p.target_revision===ae){let T=me(v),K=new Map;for(let j of T.deliveries){let W=JSON.parse(new TextDecoder().decode(j.rawBody));K.set(W.event_id,{event_id:W.event_id,origin_connection_id:T.config.connectionId,connection_sequence:W.connection_sequence,event_sha256:At("sha256").update(j.rawBody).digest("hex"),target_revision:T.config.targetRevision,delivery_state:"accepted"})}let te=[...K.values()].sort((j,W)=>(j.connection_sequence??0)-(W.connection_sequence??0)),C=typeof p.cursor=="string"?Number(p.cursor.slice(17)):0,q=typeof p.page_size=="number"?p.page_size:100,Q=te.slice(C,C+q),Z=C+Q.length>=te.length;h(200,{snapshot_token:"synthetic-snapshot-token",snapshot_at:Y,to_at:typeof p.to_at=="string"?p.to_at:Y,items:Q,next_cursor:Z?null:`synthetic-cursor-${C+Q.length}`,complete:Z});return}let b=fe.duplicate.deliveries[0],k=b.headers.find(([T])=>T==="facto-event-id")?.[1],G=p.selection_id===_e&&p.target_revision===ae?[{event_id:k,origin_connection_id:b.expectedScope.connectionId,connection_sequence:1,event_sha256:At("sha256").update(b.rawBody).digest("hex"),target_revision:b.expectedScope.targetRevision,delivery_state:"accepted"}]:[];h(200,{snapshot_token:"synthetic-snapshot-token",snapshot_at:Y,to_at:typeof p.to_at=="string"?p.to_at:Y,items:G,next_cursor:null,complete:!0});return}case"/api/card/deliveries/replays":if(typeof ee!="string"||ee.length<16){w(400,"invalid_request");return}h(202,{replay_id:nt(),selection_id:p.selection_id,target_revision:ae,status:"accepted"});return;case"/api/card/bindings/lookup":h(200,{binding:null});return;case"/api/card/events":h(200,{delivery_id:p.delivery_id,disposition:"applied",effect:"none"});return;default:w(404,"not_found")}});await new Promise((l,I)=>{o.once("error",I),o.listen(e,"127.0.0.1",()=>{o.off("error",I),l()})});let S=o.address();if(!S||typeof S=="string")throw new Error("Simulator listener unavailable");return{server:o,url:`http://127.0.0.1:${S.port}`}}import{randomUUID as Kt}from"node:crypto";import{randomUUID as En}from"node:crypto";import{createPrivateKey as fn,sign as gn}from"node:crypto";function Ae(e){let t=e.headers.get("retry-after");if(!(t===null||!/^[0-9]+$/.test(t)))return Number(t)}var un=1048576,rt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Ue=/^pconn_[A-Za-z0-9_-]{16,}$/,it=/^[a-f0-9]{64}$/,$e=/^sha256:[a-f0-9]{64}$/,kt=["environment","apiBaseUrl","timeoutMs","retry","maxResponseBytes","fetch"];function $(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function x(e,t=1,r=255){return typeof e=="string"&&[...e].length>=t&&[...e].length<=r}function pe(e,t=1,r=255){return x(e,t,r)&&/^[\x21-\x7e]+$/.test(e)}function H(e){return typeof e=="string"&&rt.test(e)&&e!=="00000000-0000-0000-0000-000000000000"}function zt(e){return typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=2147483647}function E(e){return typeof e=="string"&&/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(e)&&Number.isFinite(Date.parse(e))}function R(e,t,r=[]){return $(e)&&t.every(n=>Object.hasOwn(e,n))&&Object.keys(e).every(n=>t.includes(n)||r.includes(n))}function z(e,t,r=[]){return $(e)&&t.every(n=>Object.hasOwn(e,n))}function g(e,t){if(!e)throw new B("FACTO_CONFIG_INVALID",t,{retryable:!1})}function Be(e){return e===429||e>=500}function Le(e){let t=e?.headers.get("x-request-id")?.trim();return t&&t.length>0?t:void 0}function V(e,t){return new B("FACTO_ENGINE_RESPONSE_INVALID","Card API response does not match the producer contract",{retryable:Be(e),status:e,retryAfterSeconds:t?Ae(t):void 0,requestId:Le(t)})}function Ct(e,t){return new B("FACTO_ENGINE_RESPONSE_INVALID",`Card API response body exceeds maxResponseBytes (${t} bytes)`,{retryable:Be(e.status),status:e.status,details:{reason:"response_body_too_large",maxResponseBytes:t},retryAfterSeconds:Ae(e),requestId:Le(e)})}async function ln(e,t,r){let n=e.headers.get("content-length")?.trim();if(n!==void 0&&/^\d+$/.test(n)&&Number(n)>t)throw await e.body?.cancel().catch(()=>{}),Ct(e,t);if(!e.body)return"";let a=e.body.getReader(),c=[],m=0;try{for(;;){let{done:u,value:s}=await a.read();if(u)break;if(m+=s.byteLength,m>t||r.aborted)throw await a.cancel().catch(()=>{}),r.aborted?new B("FACTO_REQUEST_ABORTED","Card API request aborted or timed out",{retryable:!1}):Ct(e,t);c.push(s)}}finally{a.releaseLock()}let y=new Uint8Array(m),i=0;for(let u of c)y.set(u,i),i+=u.byteLength;return new TextDecoder().decode(y)}var _n=512;function pn(e){return z(e,["error","message","request_id"])&&x(e.error,1,128)&&/^[a-z][a-z0-9_]*$/.test(e.error)&&x(e.message,1,_n)&&x(e.request_id,1,128)}function Fe(e){if(!z(e,["error"])||!z(e.error,["category","code","message","request_id","retryable"],["details"]))return!1;let t=e.error;return!(typeof t.category!="string"||typeof t.code!="string"||typeof t.message!="string"||typeof t.request_id!="string"||typeof t.retryable!="boolean")}function yn(e){e!==void 0&&(g($(e),"retry options must be an object"),e.maxRetries!==void 0&&g(typeof e.maxRetries=="number"&&Number.isSafeInteger(e.maxRetries)&&e.maxRetries>=0,"retry.maxRetries must be a non-negative integer"),e.baseDelayMs!==void 0&&g(typeof e.baseDelayMs=="number"&&Number.isFinite(e.baseDelayMs)&&e.baseDelayMs>=0,"retry.baseDelayMs must be non-negative"),e.maxDelayMs!==void 0&&g(typeof e.maxDelayMs=="number"&&Number.isFinite(e.maxDelayMs)&&e.maxDelayMs>=0,"retry.maxDelayMs must be non-negative"),e.maxRetryAfterMs!==void 0&&g(typeof e.maxRetryAfterMs=="number"&&Number.isFinite(e.maxRetryAfterMs)&&e.maxRetryAfterMs>=0&&e.maxRetryAfterMs<=2147483647,"retry.maxRetryAfterMs is out of range"))}function Ot(e,t){g(typeof window>"u","Card API credentials require a server runtime"),g(e.environment==="dev"||e.environment==="production","An explicit dev or production environment is required"),yn(e.retry);let r={dev:"https://dev-api.facto.to",production:"https://api.facto.to"},n;g(e.environment!=="production"||typeof e.apiBaseUrl=="string","Production requires an explicit apiBaseUrl");try{n=new URL(e.apiBaseUrl??r.dev)}catch{throw new B("FACTO_CONFIG_INVALID","apiBaseUrl must be an absolute HTTP(S) origin",{retryable:!1})}g(!n.username&&!n.password&&!n.search&&!n.hash&&n.pathname==="/"&&(n.protocol==="https:"||n.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(n.hostname)),"apiBaseUrl must be an HTTPS origin or an explicit loopback HTTP origin");let a=`${n.protocol}//${n.hostname.replace(/\.+$/,"")}${n.port?`:${n.port}`:""}`;g(!Object.values(r).includes(a)||a===r[e.environment],"The published endpoint must match the client environment");let c=n.origin,m=e.timeoutMs??3e4;g(Number.isSafeInteger(m)&&m>0,"timeoutMs must be a positive integer");let y=e.maxResponseBytes??un;g(Number.isSafeInteger(y)&&y>0,"maxResponseBytes must be a positive integer");let i=e.fetch??globalThis.fetch?.bind(globalThis);return g(typeof i=="function","A server fetch implementation is required"),async function(s,_,f,d,A,O,D={}){let N=new AbortController,o=()=>N.abort();D.signal?.addEventListener("abort",o,{once:!0}),D.signal?.aborted&&o();let S=setTimeout(o,m),l,I=new Promise((h,w)=>{l=()=>w(new B("FACTO_REQUEST_ABORTED","Card API request aborted or timed out",{retryable:!1})),N.signal.addEventListener("abort",l,{once:!0}),N.signal.aborted&&l()});try{if(N.signal.aborted)return await I;f.set("accept","application/json"),d!==void 0&&f.set("content-type","application/json");let h=await Promise.race([i(`${c}${_}`,{method:s,headers:f,redirect:"error",signal:N.signal,...d!==void 0?{body:d}:{}}),I]),w=await Promise.race([ln(h,y,N.signal),I]),M;try{M=JSON.parse(w)}catch{throw V(h.status,h)}if(A.includes(h.status)&&O(M,h.status))return M;if(!h.ok){if(pn(M))throw new B("FACTO_ENGINE_REQUEST_FAILED",`Card API ${t} request failed with status ${h.status}`,{retryable:Be(h.status),status:h.status,details:M,retryAfterSeconds:Ae(h),requestId:M.request_id||Le(h)});if(Fe(M))throw new B("FACTO_ENGINE_REQUEST_FAILED",`Card API ${t} request failed with status ${h.status}`,{retryable:Be(h.status),status:h.status,details:M,retryAfterSeconds:Ae(h),requestId:M.error.request_id||Le(h)})}throw V(h.status,h)}catch(h){throw h instanceof B?h:new B("FACTO_ENGINE_REQUEST_FAILED","Card API transport failed; inspect the original operation before any new action",{retryable:!1})}finally{clearTimeout(S),D.signal?.removeEventListener("abort",o),l&&N.signal.removeEventListener("abort",l)}}}var mn="facto-card-binding+jwt",hn=/^pc_[A-Za-z0-9_-]{16,}$/,bn=/^cbs_[A-Za-z0-9_-]{16,}$/,vn=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,wn=/^[A-Za-z0-9_-]+$/,xn=/^[0-9]{4}$/,Rt=300,Et=600,An=["card.metadata.view","card.use_for_facto_payments"],Sn=["passkey","mfa","reauthenticated_session"],In=["provider_authenticated_app","device_bound_confirmation"],Cn={dev:"urn:facto:sandbox:card-program-connect:binding-proof",production:"urn:facto:production:card-program-connect:binding-proof"};function Tt(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function Se(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1e9&&e<=9999999999}function Pt(e){return typeof e=="string"&&wn.test(e)&&Buffer.from(e,"base64url").byteLength===32}function kn(e){return/^[0-9]{12,19}$/.test(e)||/[0-9]{13}/.test(e)}function zn(e,t){return g($(e),"Binding assertion proof claim is required"),e.mode==="provider_reauthentication"?(g(R(e,["mode","authenticatedAtSeconds","assurance"])&&Se(e.authenticatedAtSeconds)&&e.authenticatedAtSeconds<=t&&t-e.authenticatedAtSeconds<=Et&&Sn.includes(e.assurance),"Reauthentication proof requires valid authenticatedAtSeconds (within 600 seconds before issuedAtSeconds) and assurance"),{mode:"provider_reauthentication",authenticated_at:e.authenticatedAtSeconds,assurance:e.assurance}):(g(e.mode==="provider_second_channel"&&R(e,["mode","approvedAtSeconds","approvalRef","channelType"])&&Se(e.approvedAtSeconds)&&e.approvedAtSeconds<=t&&t-e.approvedAtSeconds<=Et&&x(e.approvalRef,16,255)&&In.includes(e.channelType),"Second-channel proof requires valid approvedAtSeconds (within 600 seconds before issuedAtSeconds), approvalRef (16-255 chars), and channelType"),{mode:"provider_second_channel",approved_at:e.approvedAtSeconds,approval_ref:e.approvalRef,channel_type:e.channelType})}function On(e){g(Array.isArray(e)&&e.length>=1&&e.length<=20,"Binding assertion requires 1 to 20 asserted cards");let t=new Set,r=0;return e.map(n=>{g(R(n,["externalCardId"],["isEntryCard","display"])&&x(n.externalCardId,8,512)&&!kn(n.externalCardId)&&(n.isEntryCard===void 0||typeof n.isEntryCard=="boolean"),"Each asserted card requires an opaque externalCardId (8-512 non-PAN chars) and optional boolean isEntryCard"),g(!t.has(n.externalCardId),"Asserted cards must have unique externalCardId values"),t.add(n.externalCardId),n.isEntryCard===!0&&(r+=1,g(r<=1,"At most one asserted card may set isEntryCard to true"));let a;if(n.display!==void 0){g(R(n.display,[],["network","cardType","last4"]),"Asserted card display accepts only network, cardType, and last4");let c=n.display;g((c.network===void 0||x(c.network,1,32))&&(c.cardType===void 0||x(c.cardType,1,32))&&(c.last4===void 0||typeof c.last4=="string"&&xn.test(c.last4)),"Asserted card display fields are out of contract bounds");let m={};c.network!==void 0&&(m.network=c.network),c.cardType!==void 0&&(m.card_type=c.cardType),c.last4!==void 0&&(m.last4=c.last4),Object.keys(m).length>0&&(a=m)}return{card_ref:n.externalCardId,relationship_type:"owner",...n.isEntryCard===!0?{is_entry_card:!0}:{},...a!==void 0?{display:a}:{}}})}async function Rn(e,t,r){if(typeof e=="function"){let n=await e(t);return g(n instanceof Uint8Array&&n.byteLength===64,"Binding assertion signer must return a 64-byte Ed25519 signature"),n}g(R(e,["kty","crv","x","d"],["kid","alg","use","key_ops","ext"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&(e.alg===void 0||e.alg==="EdDSA"||e.alg==="Ed25519")&&(e.use===void 0||e.use==="sig")&&(e.key_ops===void 0||Array.isArray(e.key_ops)&&e.key_ops.every(n=>typeof n=="string")&&e.key_ops.includes("sign"))&&(e.ext===void 0||typeof e.ext=="boolean")&&(e.kid===void 0||e.kid===r)&&Pt(e.x)&&Pt(e.d),"Binding assertion signer must be a valid Ed25519 private JWK (matching signingKeyId when kid is present) or async signing callback");try{let n=fn({key:{kty:"OKP",crv:"Ed25519",x:e.x,d:e.d},format:"jwk"});return new Uint8Array(gn(null,t,n))}catch{throw new B("FACTO_CONFIG_INVALID","Invalid Ed25519 private JWK for binding assertion signing",{retryable:!1})}}async function Dt(e){g(R(e,["environment","providerConnectionId","programId","bindingSessionId","issuer","subject","jti","factoChallenge","sessionRequestDigest","requestedUserConsents","proof","cards","signingKeyId","signer"],["issuedAtSeconds","notBeforeSeconds","expiresAtSeconds"]),"Binding assertion input contains missing or unknown fields"),g(e.environment==="dev"||e.environment==="production","environment must be dev or production"),g(typeof e.providerConnectionId=="string"&&hn.test(e.providerConnectionId),"providerConnectionId must be a pc_ provider connection identifier (not a pconn_ program connection identifier)"),g(x(e.programId,1,255),"programId must be 1 to 255 characters"),g(typeof e.bindingSessionId=="string"&&bn.test(e.bindingSessionId),"bindingSessionId must be a cbs_ identifier"),g(x(e.issuer,1,512),"issuer is required"),g(x(e.subject,16,512),"subject must be a pairwise opaque identifier of 16 to 512 characters"),g(x(e.jti,16,255),"jti must be 16 to 255 characters"),g(x(e.factoChallenge,1,512),"factoChallenge is required"),g(typeof e.sessionRequestDigest=="string"&&$e.test(e.sessionRequestDigest),"sessionRequestDigest must be a sha256:<hex> digest"),g(x(e.signingKeyId,1,255)&&e.signingKeyId.trim()===e.signingKeyId&&!e.signingKeyId.includes("\0"),"signingKeyId must be a non-empty trimmed identifier without NUL bytes");let t=e.requestedUserConsents;g(Array.isArray(t)&&t.length>0&&new Set(t).size===t.length&&t.every(f=>An.includes(f)),"requestedUserConsents must be a non-empty unique set of supported consent purposes");let r=e.issuedAtSeconds??Math.floor(Date.now()/1e3),n=e.notBeforeSeconds??r,a=e.expiresAtSeconds??r+Rt;g(Se(r)&&Se(n)&&Se(a)&&n<=r&&r<=a&&a-r<=Rt,"Binding assertion timestamps must satisfy nbf <= iat <= exp with lifetime <= 300 seconds");let c=zn(e.proof,r),m=On(e.cards),y=Tt({typ:mn,alg:"EdDSA",kid:e.signingKeyId}),i=Tt({iss:e.issuer,aud:Cn[e.environment],sub:e.subject,iat:r,nbf:n,exp:a,jti:e.jti,binding_session_id:e.bindingSessionId,facto_challenge:e.factoChallenge,session_request_digest:e.sessionRequestDigest,connection_id:e.providerConnectionId,environment:e.environment,program_ref:e.programId,proof:c,cards:m,requested_user_consents:[...t]}),u=new TextEncoder().encode(`${y}.${i}`),s=await Rn(e.signer,u,e.signingKeyId),_=`${y}.${i}.${Buffer.from(s).toString("base64url")}`;return g(_.length>=128&&_.length<=16384&&vn.test(_),"Signed binding assertion exceeds compact JWS bounds"),_}var ke=/^cbs_[A-Za-z0-9_-]{16,}$/,He=/^cint_[A-Za-z0-9_-]{16,}$/,Je=/^cb_[A-Za-z0-9_-]{16,}$/,at=/^sha256:[a-fA-F0-9]{64}$/,Lt=["authorization_updated","clearing","reversal","refund","chargeback","settlement"],Ve=["authorization_requested",...Lt],Tn=["facto_admission","durable_commit","provider_authorization","chain_finality","provider_settlement"],Pn=["active","frozen","closed","replaced"],Dn=/^[A-Za-z0-9_.:-]{1,64}$/,Nn=/^[0-9]+\.[0-9]{2,6}$/,qn=/^-?[0-9]+\.[0-9]{2,6}$/;function P(e,t){return typeof e=="string"&&t.test(e)}function Ut(e){return e===null||typeof e=="string"}function je(e,t=-2147483648){return typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=2147483647}function Ce(e,t=128){return x(e,1,t)&&!/[0-9]{13}/.test(e)}function Ie(e,t){return e==null||t(e)}function Me(e){return Array.isArray(e)&&e.every(t=>P(t,Je))}function $t(e){return z(e,["network","type","last4"])&&Ut(e.network)&&(e.type===null||["virtual","physical","unknown"].includes(String(e.type)))&&(e.last4===null||typeof e.last4=="string"&&/^[0-9]{4}$/.test(e.last4))}function se(e){return typeof e=="string"&&/^0x0{32}[0-9a-fA-F]{32}$/.test(e)}function Bn(e){return typeof e=="string"&&Dn.test(e)}function Ln(e){return!z(e,["snapshot_token","snapshot_at","to_at","items","next_cursor","complete"])||!x(e.snapshot_token,16,4096)||!E(e.snapshot_at)||!E(e.to_at)||typeof e.complete!="boolean"||e.next_cursor!==null&&!x(e.next_cursor,1,4096)||e.complete&&e.next_cursor!==null||!Array.isArray(e.items)||e.items.length>100?!1:e.items.every(t=>z(t,["event_id","origin_connection_id","connection_sequence","event_sha256","target_revision","delivery_state"],["accepted_at"])&&H(t.event_id)&&typeof t.origin_connection_id=="string"&&Ue.test(t.origin_connection_id)&&(t.connection_sequence===null||typeof t.connection_sequence=="number"&&Number.isSafeInteger(t.connection_sequence)&&t.connection_sequence>=1)&&typeof t.event_sha256=="string"&&it.test(t.event_sha256)&&H(t.target_revision)&&typeof t.delivery_state=="string"&&(t.accepted_at===void 0||E(t.accepted_at)))}function Un(e){return z(e,["replay_id","selection_id","target_revision","status"])&&H(e.replay_id)&&H(e.selection_id)&&H(e.target_revision)&&e.status==="accepted"}function $n(e){g(R(e,["target_revision","page_size"],["selection_id","from_at","to_at","snapshot_token","cursor"]),"Reconciliation requires only the generated query fields"),g(H(e.target_revision)&&typeof e.page_size=="number"&&Number.isInteger(e.page_size)&&e.page_size>=1&&e.page_size<=100,"Reconciliation target_revision and page_size are invalid"),g(H(e.selection_id)&&!Object.hasOwn(e,"from_at")&&!Object.hasOwn(e,"to_at")||!Object.hasOwn(e,"selection_id")&&E(e.from_at)&&E(e.to_at)&&Date.parse(e.from_at)<=Date.parse(e.to_at),"Select exactly one fixed selection or explicit time window"),g((e.snapshot_token===void 0||x(e.snapshot_token,16,4096))&&(e.cursor===void 0||x(e.cursor,16,4096)&&x(e.snapshot_token,16,4096)),"A cursor requires its original snapshot token")}function Fn(e){g($(e),"Authorization lookup requires criteria");let t=Object.hasOwn(e,"criteria")?(g(R(e,["criteria"])&&$(e.criteria),"Authorization lookup wrapper requires only criteria"),e.criteria):e;g($(t),"Authorization lookup requires criteria");let r=t.by==="external_authorization_id"?R(t,["by","external_authorization_id","resource_version","mapping_revision"],["fact_type"])&&x(t.external_authorization_id,1,256)&&x(t.resource_version,1,255)&&x(t.mapping_revision,1,255)&&(t.fact_type===void 0||Ve.includes(String(t.fact_type))):t.by==="supplier_transaction_id"?R(t,["by","supplier_transaction_id","resource_version","mapping_revision"],["fact_type"])&&typeof t.supplier_transaction_id=="string"&&x(t.supplier_transaction_id.trim(),1,256)&&x(t.resource_version,1,255)&&x(t.mapping_revision,1,255)&&(t.fact_type===void 0||Ve.includes(String(t.fact_type))):t.by==="idempotency_key"?R(t,["by","idempotency_key","original_credential_key_id"],["operation"])&&x(t.idempotency_key,16,255)&&x(t.original_credential_key_id,1,255)&&(t.operation===void 0||t.operation==="create_authorization"):t.by==="charge_id"&&R(t,["by","charge_id"])&&se(t.charge_id);return g(r,"Select exactly one complete external_authorization_id, supplier_transaction_id, idempotency_key, or public charge_id"),t}function Kn(e){g(R(e,["external_card_id","external_authorization_id","amount","currency","resource_version","mapping_revision","cardholder_verification"],["supplier_transaction_id","client_transaction_id","merchant_name","merchant_mcc","merchant_country","occurred_at","decision_mode","decision_timeout_ms","deadline_at"]),"Authorization create requires the complete generated request");let n=e.cardholder_verification;g(Ce(e.external_card_id,512)&&x(e.external_authorization_id,1,256)&&P(e.amount,Nn)&&(e.currency==="USD"||e.currency==="USDC")&&x(e.resource_version,1,255)&&x(e.mapping_revision,1,255)&&(e.merchant_name===void 0||x(e.merchant_name,0,256))&&(e.merchant_mcc===void 0||P(e.merchant_mcc,/^[0-9]{4}$/))&&(e.merchant_country===void 0||x(e.merchant_country,2,3))&&(e.occurred_at===void 0||E(e.occurred_at))&&[e.supplier_transaction_id,e.client_transaction_id].every(a=>a===void 0||typeof a=="string"&&x(a.trim(),1,256))&&(e.decision_mode===void 0||e.decision_mode==="asynchronous"||e.decision_mode==="synchronous")&&(e.decision_timeout_ms===void 0||e.decision_mode==="synchronous"&&typeof e.decision_timeout_ms=="number"&&Number.isInteger(e.decision_timeout_ms)&&e.decision_timeout_ms>=50&&e.decision_timeout_ms<=5e3)&&(e.deadline_at===void 0||e.decision_mode==="synchronous"&&E(e.deadline_at))&&R(n,["method","verified_at","evidence_id"])&&["pin","biometric","cdcvm","signature","no_cvm","provider_attested"].includes(String(n.method))&&E(n.verified_at)&&x(n.evidence_id,1,256),"Authorization fields, currency, mapping/version, or cardholder verification is invalid")}function jn(e,t){g(x(e,1,255)&&e!=="."&&e!==".."&&!e.includes("/"),"externalId must be a valid external authorization identifier"),g(R(t,["fact_type","amount","currency","resource_version","predecessor_version","mapping_revision","recorded_at"],["supplier_transaction_id","parent_supplier_transaction_id","client_transaction_id","merchant_name","merchant_mcc","merchant_country"]),"Authorization fact requires the complete generated request"),g(Lt.includes(String(t.fact_type))&&P(t.amount,qn)&&(t.currency==="USD"||t.currency==="USDC")&&x(t.resource_version,1,255)&&typeof t.predecessor_version=="string"&&x(t.predecessor_version.trim(),1,255)&&t.predecessor_version!==t.resource_version&&x(t.mapping_revision,1,255)&&E(t.recorded_at)&&(t.merchant_name===void 0||x(t.merchant_name,1,255))&&(t.merchant_mcc===void 0||P(t.merchant_mcc,/^[0-9]{4}$/))&&(t.merchant_country===void 0||x(t.merchant_country,2,3))&&[t.supplier_transaction_id,t.parent_supplier_transaction_id,t.client_transaction_id].every(a=>a===void 0||typeof a=="string"&&x(a.trim(),1,255)),"Authorization fact type, predecessor version, amount, or timestamp is invalid")}function Ft(e){return Array.isArray(e)&&e.length===5&&e.every((t,r)=>z(t,["kind","state","recorded_at","source_system"],["observed_at","safe_code"])&&t.kind===Tn[r]&&["unobserved","pending","confirmed","rejected","indeterminate"].includes(String(t.state))&&E(t.recorded_at)&&["facto","provider","chain"].includes(String(t.source_system))&&(t.safe_code===void 0||x(t.safe_code,1,64))&&(t.observed_at===void 0||E(t.observed_at))&&(t.state!=="confirmed"||E(t.observed_at))&&(t.state!=="unobserved"||!Object.hasOwn(t,"observed_at")))}function Mn(e){return!z(e,["receipt_event_id","charge_id","mapping_revision","operation_type","resource_version","execution_outcome","terminal_action","finalized_at","facts_at_finality"],["external_authorization_id","authorization_ref"])||!H(e.receipt_event_id)||!se(e.charge_id)||!(x(e.external_authorization_id,1,256)||x(e.authorization_ref,1,256))||!x(e.mapping_revision,1,255)||!Ve.includes(String(e.operation_type))||!x(e.resource_version,1,255)||!E(e.finalized_at)||!Ft(e.facts_at_finality)||e.facts_at_finality[3].state!=="confirmed"?!1:e.terminal_action==="releaseFor"?e.execution_outcome==="succeeded"&&e.facts_at_finality[0].state==="confirmed"&&e.facts_at_finality[1].state==="confirmed":e.terminal_action==="cancelReservation"&&e.execution_outcome==="failed"}function Vn(e){if(e===void 0)return!0;if(!$(e)||!$(e.issuer)||!Array.isArray(e.issuer.entries)||!Array.isArray(e.refund_cases))return!1;let t=e.issuer,r=t.entries;return["state","cleared_amount","reversed_amount","refunded_amount"].every(n=>typeof t[n]=="string")&&r.every(n=>$(n)&&["operation_type","resource_version","amount","currency","recorded_at","link_status"].every(a=>typeof n[a]=="string")&&n.currency==="USDC"&&(n.unlinked_reason===void 0||typeof n.unlinked_reason=="string"))&&e.refund_cases.every(n=>$(n)&&["case_id","source_operation_type","source_resource_version","status","amount","excess_amount","updated_at"].every(a=>typeof n[a]=="string")&&(n.paid_amount===void 0||typeof n.paid_amount=="string")&&(n.not_payable_reason===void 0||typeof n.not_payable_reason=="string"))}function Hn(e,t){if(e===void 0)return!0;if(!$(e)||typeof e.fee_total!="string"||!$(e.fee_breakdown))return!1;let r=e.fee_breakdown;if(!["base_fee","fast_pay_fee","pooled_surcharge"].every(a=>typeof r[a]=="string"))return!1;let n=e.user_payment;return n!==void 0&&(!$(n)||!Number.isSafeInteger(n.chain_id)||typeof n.tx_hash!="string"||!/^0x[0-9a-fA-F]{64}$/.test(n.tx_hash)||n.asset_symbol!==void 0&&typeof n.asset_symbol!="string")?!1:e.refund_payments===void 0||t&&Array.isArray(e.refund_payments)&&e.refund_payments.every(a=>$(a)&&Number.isSafeInteger(a.chain_id)&&typeof a.case_id=="string"&&typeof a.paid_amount=="string"&&typeof a.recorded_by=="string"&&typeof a.tx_hash=="string"&&/^0x[0-9a-fA-F]{64}$/.test(a.tx_hash))}function Jn(e){if(!z(e,["external_authorization_id","processing_status","origin_connection_id","resource_version","mapping_revision"],["charge_id","final_receipt","decline_reason_code","supplier_transaction_id","facts","revision","operation_type","decision","lifecycle","payment_details"])||!x(e.external_authorization_id,1,256)||typeof e.origin_connection_id!="string"||!Ue.test(e.origin_connection_id)||!x(e.resource_version,1,255)||!x(e.mapping_revision,1,255)||e.charge_id!==void 0&&e.charge_id!==null&&!se(e.charge_id)||e.supplier_transaction_id!==void 0&&!x(e.supplier_transaction_id,1,256)||e.facts!==void 0&&!Ft(e.facts)||e.revision!==void 0&&!zt(e.revision)||e.operation_type!==void 0&&!Ve.includes(String(e.operation_type))||e.decision!==void 0&&!["approved","declined","self_reversed_timeout"].includes(String(e.decision))||e.decline_reason_code!==void 0&&!Bn(e.decline_reason_code)||!Vn(e.lifecycle)||!Hn(e.payment_details,e.lifecycle!==void 0))return!1;if(e.processing_status==="succeeded"||e.processing_status==="failed"){if(Object.hasOwn(e,"final_receipt")&&e.final_receipt!==void 0){if(!se(e.charge_id)||!Mn(e.final_receipt)||Object.hasOwn(e,"decline_reason_code"))return!1;let t=e.final_receipt,r=t.external_authorization_id??t.authorization_ref;return t.execution_outcome===e.processing_status&&t.charge_id===e.charge_id&&r===e.external_authorization_id&&t.mapping_revision===e.mapping_revision&&t.resource_version===e.resource_version&&(e.operation_type===void 0||t.operation_type===e.operation_type)}return e.processing_status==="succeeded"?!Object.hasOwn(e,"decline_reason_code")&&(e.charge_id===void 0||se(e.charge_id)):se(e.charge_id)||(e.charge_id===void 0||e.charge_id===null)&&(e.decision==="declined"||e.decision==="self_reversed_timeout"||e.decline_reason_code!==void 0)}return!Object.hasOwn(e,"final_receipt")&&!Object.hasOwn(e,"decline_reason_code")&&(e.processing_status==="processing"||e.processing_status==="indeterminate"&&(e.charge_id===void 0||e.charge_id===null))}function Wn(e){return!z(e,["observed_at","resolution"],["authorization"])||!E(e.observed_at)?!1:e.resolution==="not_observed"?!Object.hasOwn(e,"authorization")||e.authorization===void 0:Jn(e.authorization)?e.resolution==="resolved"?["succeeded","failed"].includes(e.authorization.processing_status):e.resolution==="pending"?e.authorization.processing_status==="processing":e.resolution==="unknown"&&e.authorization.processing_status==="indeterminate":!1}function Gn(e){return z(e,["charge_id","status"])&&se(e.charge_id)&&["processing","approved","declined"].includes(String(e.status))&&!Object.hasOwn(e,"final_receipt")}function Zn(e){return z(e,["operation_id","status"])&&H(e.operation_id)&&e.status==="recorded"}function Yn(e,t){return!z(e,["deadline_at","decision_id"])||!E(e.deadline_at)||!H(e.decision_id)?!1:t===200?e.decision==="approved"&&e.status==="approved"&&se(e.charge_id)&&E(e.decided_at):typeof e.error!="string"||typeof e.message!="string"||typeof e.request_id!="string"?!1:t===408&&e.error==="decision_deadline_exceeded"&&!Object.hasOwn(e,"decision")?!0:E(e.decided_at)&&(t===422&&e.decision==="declined"||t===408&&e.decision==="self_reversed_timeout")}function Qn(e){if(!z(e,["binding_session_id","status","binding_url","expires_at","proof_policy"])||!P(e.binding_session_id,ke)||e.status!=="pending"||typeof e.binding_url!="string"||!E(e.expires_at))return!1;let t=e.proof_policy;return z(t,["allowed_modes","challenge_after_facto_auth","challenge_delivery"],["card_selection_supported"])&&Array.isArray(t.allowed_modes)&&t.allowed_modes.length>0&&new Set(t.allowed_modes).size===t.allowed_modes.length&&t.allowed_modes.every(r=>r==="provider_reauthentication"||r==="provider_second_channel")&&t.challenge_after_facto_auth===!0&&(t.challenge_delivery==="browser_handoff"||t.challenge_delivery==="provider_backend")&&(t.card_selection_supported===void 0||t.card_selection_supported===!0)}function Nt(e){if(!$(e)||!P(e.binding_session_id,ke)||!E(e.expires_at))return!1;let t=["binding_session_id","status","expires_at"];return["pending","proof_pending","consent_pending"].includes(String(e.status))?z(e,t)&&!["outcome","binding_ids","failure_reason","completed_at"].some(r=>Object.hasOwn(e,r)):e.status==="completed"?Object.hasOwn(e,"completed_at")&&!E(e.completed_at)?!1:e.outcome==="bound"?z(e,[...t,"outcome","binding_ids"],["completed_at"])&&!Object.hasOwn(e,"failure_reason")&&Me(e.binding_ids):e.outcome==="declined"&&z(e,[...t,"outcome","failure_reason"],["completed_at"])&&!Object.hasOwn(e,"binding_ids")&&e.failure_reason==="declined_by_user":e.status==="cancelled"?z(e,t,["completed_at","failure_reason"])&&!["outcome","binding_ids"].some(r=>Object.hasOwn(e,r))&&(!Object.hasOwn(e,"completed_at")||E(e.completed_at))&&(!Object.hasOwn(e,"failure_reason")||["cancelled_by_user","cancelled_by_partner","proof_rejected","admission_closed","no_eligible_cards","integrity_conflict"].includes(String(e.failure_reason))):e.status==="expired"&&z(e,t,["failure_reason"])&&!["completed_at","outcome","binding_ids"].some(r=>Object.hasOwn(e,r))&&(!Object.hasOwn(e,"failure_reason")||e.failure_reason==="expired"||e.failure_reason==="proof_timeout")}function Xn(e){return z(e,["binding_session_id","status","proof_received_at"])&&P(e.binding_session_id,ke)&&e.status==="consent_pending"&&E(e.proof_received_at)}function er(e){return z(e,["binding_session_id","facto_challenge","session_request_digest","expires_at"])&&P(e.binding_session_id,ke)&&x(e.facto_challenge,1,512)&&P(e.session_request_digest,$e)&&E(e.expires_at)}function tr(e){g(R(e,["requested_user_consents","return_uri"]),"Binding session requires the generated consent and return URI fields");let t=e.requested_user_consents;g(Array.isArray(t)&&t.length>0&&new Set(t).size===t.length&&t.every(r=>r==="card.metadata.view"||r==="card.use_for_facto_payments"),"Binding session consents are invalid"),g(typeof e.return_uri=="string"&&Buffer.byteLength(e.return_uri,"utf8")<=2048&&e.return_uri.startsWith("https://")&&!/[#\r\n]/.test(e.return_uri)&&e.return_uri.slice(8).split(/[/?]/,1)[0].length>0&&!e.return_uri.slice(8).split(/[/?]/,1)[0].includes("@"),"An exact registered HTTPS return URI is required")}function qt(e){g(R(e,["proof_format","binding_assertion"])&&e.proof_format==="compact-jws"&&typeof e.binding_assertion=="string"&&e.binding_assertion.length>=128&&e.binding_assertion.length<=16384&&/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e.binding_assertion),"The original compact JWS provider proof is required")}function nr(e){return z(e,["id","revision","cards"])&&P(e.id,He)&&P(e.revision,at)&&Array.isArray(e.cards)&&e.cards.every(t=>z(t,["binding_id","status","card"])&&P(t.binding_id,Je)&&typeof t.status=="string"&&$t(t.card))}function rr(e){return z(e,["id","status","revision","added_binding_ids","removed_binding_ids","kept_binding_ids"])&&P(e.id,He)&&["applied","no_change"].includes(String(e.status))&&P(e.revision,at)&&Me(e.added_binding_ids)&&Me(e.removed_binding_ids)&&Me(e.kept_binding_ids)}function ir(e){return z(e,["id","status"])&&P(e.id,He)&&e.status==="cancelled"}function or(e){return e===void 0||z(e,["configured","state"],["reason"])&&typeof e.configured=="boolean"&&["ready","not_configured","unavailable"].includes(String(e.state))&&(e.reason===void 0||e.reason===null||typeof e.reason=="string")}function ar(e){if(!z(e,["binding"],["found"])||e.found!==void 0&&typeof e.found!="boolean")return!1;let t=e.binding;return t===null?e.found!==!0:(e.found===void 0||e.found===!0)&&z(t,["id","status","revision","card"],["funding"])&&P(t.id,Je)&&typeof t.status=="string"&&je(t.revision,1)&&$t(t.card)&&or(t.funding)}function sr(e){return z(e,["items"])&&Array.isArray(e.items)&&e.items.every(t=>z(t,["id","event_kind","binding_id","binding_revision","connection_sequence","delivery_attempts","last_delivery_error","dead_lettered_at","replay_count"])&&P(t.id,rt)&&typeof t.event_kind=="string"&&P(t.binding_id,Je)&&je(t.binding_revision,1)&&(t.connection_sequence===null||typeof t.connection_sequence=="number"&&Number.isSafeInteger(t.connection_sequence)&&t.connection_sequence>=1)&&je(t.delivery_attempts,1)&&Ut(t.last_delivery_error)&&(t.dead_lettered_at===null||E(t.dead_lettered_at))&&je(t.replay_count,0))}function dr(e){return z(e,["id","status"])&&H(e.id)&&e.status==="accepted"}function cr(e){return z(e,["delivery_id","disposition","effect"])&&H(e.delivery_id)&&(e.disposition==="duplicate"?e.effect===null:e.disposition==="applied"&&["revoked","status_updated","released","none"].includes(String(e.effect)))}function ur(e){g(R(e,["intent_token","approval_id","approval_sha256","revision","cards"],["external_account_id"])&&pe(e.intent_token,32,8192)&&x(e.approval_id,1,255)&&P(e.approval_sha256,it)&&P(e.revision,at)&&Ie(e.external_account_id,t=>typeof t=="string"&&t.length>0&&Buffer.byteLength(t,"utf8")<=512),"Card replacement requires the original complete approved request"),g(Array.isArray(e.cards)&&e.cards.length<=50&&e.cards.every(t=>R(t,["external_card_id"],["network","type","last4"])&&Ce(t.external_card_id,255)&&Ie(t.network,r=>Ce(r,40))&&Ie(t.type,r=>r==="virtual"||r==="physical"||r==="unknown")&&Ie(t.last4,r=>typeof r=="string"&&/^[0-9]{4}$/.test(r))),"Target cards must match the generated safe card projection")}function lr(e){g(R(e,["delivery_id","kind","assertion_jws"],["external_card_id","lifecycle_status","external_account_id"])&&H(e.delivery_id)&&typeof e.assertion_jws=="string"&&e.assertion_jws.trim().length>=32,"Inbound event requires a UUID delivery_id and signed assertion_jws");let t=r=>r==null;g(e.kind==="account.released"?x(e.external_account_id,1,512)&&t(e.external_card_id)&&t(e.lifecycle_status):Ce(e.external_card_id)&&t(e.external_account_id)&&(e.kind==="card.unbound"?t(e.lifecycle_status):e.kind==="card.lifecycle_changed"&&Pn.includes(String(e.lifecycle_status))),"Inbound event fields must match the declared event kind")}function ye(e){return g(e&&pe(e.idempotencyKey,16,255),"An explicit original Idempotency-Key of 16 to 255 characters is required"),e.idempotencyKey}function Ke(e){return g(P(e,ke),"id must be the original binding session identifier"),`/api/card/connect/sessions/${e}`}function ot(e){return g(P(e,He),"id must be the original connect intent identifier"),`/api/card/connect/intents/${e}`}function Bt(e){return g(e?.rawBody===void 0||typeof e?.rawBody=="string","rawBody must preserve the original authenticated request bytes"),e?.rawBody}function We(e){g(R(e,["environment","connectionId","programId","apiKeyId","apiKeySecret"],[...kt,"nowSeconds","createNonce"]),"Card client options cannot contain human session or arbitrary authentication fields"),g(typeof e.connectionId=="string"&&Ue.test(e.connectionId),"connectionId must be a pconn_ connection identifier"),g(x(e.programId,1,128)&&pe(e.apiKeyId),"programId and apiKeyId are required");let t=Te(e.apiKeySecret),r=Ot(e,"program"),n=Object.freeze({connectionId:e.connectionId,environment:e.environment,programId:e.programId}),a=e.apiKeyId,c=e.nowSeconds??(()=>Math.floor(Date.now()/1e3)),m=e.createNonce??En;function y(i,u,s,_="POST"){let f=c(),d=m();return g(Number.isSafeInteger(f)&&f>=1e9&&f<=9999999999,"nowSeconds must return a ten-digit Unix timestamp in seconds"),g(pe(d,1,128),"createNonce must return a bounded canonical nonce"),he({secret:t,apiKeyId:a,method:_,target:i,timestamp:f,nonce:d,body:u,idempotencyKey:s})}return Object.freeze({scope:n,sessions:Object.freeze({async create(i,u){tr(i),g(R(u,["idempotencyKey"],["cardSelection","signal"]),"Binding session create options accept only idempotencyKey, optional cardSelection, and optional signal");let s=ye(u);g(u.cardSelection===void 0||typeof u.cardSelection=="boolean","cardSelection must be a boolean when provided");let _={...i,program_ref:n.programId},f=JSON.stringify(_),d="/api/card/connect/sessions",A=y(d,f,s);return u.cardSelection===!0&&A.set("x-facto-card-selection","1"),r("POST",d,A,f,[201],Qn,u)},async get(i,u){let s=Ke(i),_=await r("GET",s,y(s,"",void 0,"GET"),void 0,[200],Nt,u);if(_.binding_session_id!==i)throw V(200);return _},async submitProof(i,u,s){let _=`${Ke(i)}/provider-proof`,f=ye(s);g($(u),"Provider proof input is required");let d;if(Object.hasOwn(u,"proof_format")||Object.hasOwn(u,"binding_assertion"))qt(u),d=u;else{g(!["environment","programId","bindingSessionId","connectionId"].some(S=>Object.hasOwn(u,S)),"Provider proof assertion inherits environment, programId, and bindingSessionId from client scope and session id, and requires explicit providerConnectionId (pc_...)");let D=u,N=D.issuedAtSeconds??c();d={proof_format:"compact-jws",binding_assertion:await Dt({...D,environment:n.environment,programId:n.programId,bindingSessionId:i,issuedAtSeconds:N})},qt(d)}let A=JSON.stringify(d),O=await r("POST",_,y(_,A,f),A,[202],Xn,s);if(O.binding_session_id!==i)throw V(202);return O},async getProofChallenge(i,u){let s=`${Ke(i)}/proof-challenge`,_=await r("GET",s,y(s,"",void 0,"GET"),void 0,[200],er,u);if(_.binding_session_id!==i)throw V(200);return _},async cancel(i,u){let s=`${Ke(i)}/cancel`,_=ye(u),f=Bt(u)??"{}",d=await r("POST",s,y(s,f,_),f,[200],Nt,u);if(d.binding_session_id!==i)throw V(200);return d}}),intents:Object.freeze({async listCards(i,u){let s=`${ot(i)}/cards`;g(R(u,["intentToken"],["signal"])&&pe(u.intentToken,32,8192),"intentToken must be a valid HTTP header value of at least 32 characters");let _=y(s,"",void 0,"GET");_.set("x-facto-intent-token",u.intentToken);let f=await r("GET",s,_,void 0,[200],nr,u);if(f.id!==i)throw V(200);return f},async replaceCards(i,u,s){let _=`${ot(i)}/cards`;ur(u);let f=ye(s),d=JSON.stringify(u),A=await r("PUT",_,y(_,d,f,"PUT"),d,[200],rr,s);if(A.id!==i)throw V(200);return A},async cancel(i,u,s){let _=`${ot(i)}/cancel`;g(R(u,["intent_token"])&&pe(u.intent_token,32,8192),"Cancel requires the original intent_token body of at least 32 characters");let f=JSON.stringify(u),d=await r("POST",_,y(_,f),f,[200],ir,s);if(d.id!==i)throw V(200);return d}}),bindings:Object.freeze({async lookup(i,u){g(R(i,["external_card_id"])&&Ce(i.external_card_id),"Binding lookup requires only an opaque external_card_id in its body");let s=JSON.stringify(i),_="/api/card/bindings/lookup";return r("POST",_,y(_,s),s,[200],ar,u)}}),authorizations:Object.freeze({create:(async(i,u)=>{Kn(i);let s=ye(u),_={...i,program_id:n.programId},f=JSON.stringify(_),d="/api/card/authorizations";return i.decision_mode==="synchronous"?r("POST",d,y(d,f,s),f,[200,422,408],Yn,u):r("POST",d,y(d,f,s),f,[200],Gn,u)}),async recordFact(i,u,s){jn(i,u);let _=ye(s),f={...u,program_id:n.programId},d=JSON.stringify(f),A=`/api/card/authorizations/${encodeURIComponent(i)}/facts`;return r("POST",A,y(A,d,_),d,[200],Zn,s)},async lookup(i,u){let s=Fn(i),_={program_id:n.programId,criteria:s},f=JSON.stringify(_),d="/api/card/authorizations/lookup",A=await r("POST",d,y(d,f),f,[200],Wn,u),O=A.authorization;if(O&&(O.origin_connection_id!==n.connectionId||s.by==="charge_id"&&O.charge_id?.toLowerCase()!==s.charge_id.toLowerCase()||s.by==="external_authorization_id"&&(O.external_authorization_id!==s.external_authorization_id||O.resource_version!==s.resource_version||O.mapping_revision!==s.mapping_revision||s.fact_type!==void 0&&O.operation_type!==void 0&&O.operation_type!==s.fact_type)||s.by==="supplier_transaction_id"&&(O.supplier_transaction_id!==s.supplier_transaction_id.trim()||O.resource_version!==s.resource_version||O.mapping_revision!==s.mapping_revision||s.fact_type!==void 0&&O.operation_type!==void 0&&O.operation_type!==s.fact_type)))throw V(200);return A}}),events:Object.freeze({async record(i,u){lr(i);let s=JSON.stringify(i),_="/api/card/events",f=await r("POST",_,y(_,s),s,[200],cr,u),d=i.kind==="card.unbound"?"revoked":i.kind==="card.lifecycle_changed"?"status_updated":"released";if(f.delivery_id!==i.delivery_id||f.disposition==="applied"&&f.effect!=="none"&&f.effect!==d)throw V(200);return f}}),deliveries:Object.freeze({async list(i,u){$n(i);let s={...i,program_id:n.programId},_=JSON.stringify(s),f="/api/card/deliveries/reconciliations/list",d=await r("POST",f,y(f,_),_,[200],Ln,u);if(d.items.length>i.page_size)throw V(200);return d}}),deliveryReplays:Object.freeze({async create(i,u){g(R(i,["selection_id"])&&H(i.selection_id),"Delivery replay requires a fixed selection_id UUID");let s=ye(u),_={...i,program_id:n.programId},f=JSON.stringify(_),d="/api/card/deliveries/replays",A=await r("POST",d,y(d,f,s),f,[202],Un,u);if(A.selection_id!==i.selection_id)throw V(202);return A}}),deadLetters:Object.freeze({async list(i,u){g(i===void 0||R(i,[],["limit"])&&Ie(i.limit,d=>typeof d=="number"&&Number.isInteger(d)&&d>=1&&d<=100),"Dead-letter limit must be null, absent, or an integer from 1 to 100");let s=typeof i?.limit=="number"?i.limit:void 0,_=s!==void 0?`/api/card/deliveries/dead-letters?limit=${s}`:"/api/card/deliveries/dead-letters",f=await r("GET",_,y(_,"",void 0,"GET"),void 0,[200],sr,u);if(f.items.length>(s??50))throw V(200);return f},async replay(i,u){g(H(i),"The dead-letter path identifier must be a UUID");let s=`/api/card/deliveries/dead-letters/${i}/replay`,_=Bt(u),f=await r("POST",s,y(s,_??""),_,[202],dr,u);if(f.id!==i)throw V(202);return f}})})}function ie(e,t,r){return!e||typeof e!="object"||!("status"in e)||e.status!==t?!1:r?"details"in e&&!!e.details&&typeof e.details=="object"&&"error"in e.details&&e.details.error===r:!0}async function jt(e,t=console.log){let r=new URL(e);if(r.protocol!=="http:"||r.hostname!=="127.0.0.1"||r.pathname!=="/"||r.search||r.hash||r.username||r.password)throw new Error("Simulator vectors only support a loopback HTTP origin");let n=(o={})=>We({environment:"dev",...U,apiBaseUrl:r.origin,...o}),a=n(),c=Kt(),m={external_card_id:"synthetic-card",external_authorization_id:`synthetic-${c}`,supplier_transaction_id:`synthetic-supplier-${c}`,amount:"1.00",currency:"USD",cardholder_verification:{method:"provider_attested",verified_at:"2026-01-01T00:00:00Z",evidence_id:"synthetic-proof"},resource_version:"v1",mapping_revision:"v1"},y=`synthetic-key-${c}`,i=o=>({...m,external_authorization_id:`${m.external_authorization_id}-${o}`,supplier_transaction_id:`${m.supplier_transaction_id}-${o}`}),u=o=>a.authorizations.lookup({by:"idempotency_key",idempotency_key:o,original_credential_key_id:U.apiKeyId}),s=async(o,S,l)=>{let I=he({secret:U.apiKeySecret,apiKeyId:U.apiKeyId,method:"POST",target:o,timestamp:Math.floor(Date.now()/1e3),nonce:Kt(),body:S,idempotencyKey:l});return I.set("content-type","application/json"),fetch(`${r.origin}${o}`,{method:"POST",headers:I,body:S,redirect:"error"})},_=!0,f="";async function d(o,S){try{if(await S()){t(`vector_passed:${o}`);return}}catch{}_=!1,t(`vector_failed:${o}`)}await d("authorization",async()=>{let o=await a.authorizations.create(m,{idempotencyKey:y});return f=o.charge_id,o.status==="processing"}),await d("authorization_replay",async()=>(await a.authorizations.create(m,{idempotencyKey:y})).charge_id===f&&f!==""),await d("integrity_conflict",async()=>{try{return await a.authorizations.create({...m,amount:"2.00"},{idempotencyKey:y}),!1}catch(o){return ie(o,409,"integrity_conflict")}}),await d("operation_identity_conflict",async()=>{try{return await a.authorizations.create({...m,amount:"2.00"},{idempotencyKey:`different-key-${c}`}),!1}catch(o){return ie(o,409,"integrity_conflict")}}),await d("byte_integrity_conflict",async()=>{let o=await s("/api/card/authorizations",JSON.stringify({...m,program_id:U.programId},null,2),y),S=await o.json();return o.status===409&&!!S&&typeof S=="object"&&"error"in S&&S.error==="integrity_conflict"});let A={fact_type:"clearing",supplier_transaction_id:m.supplier_transaction_id,amount:"1.00",currency:"USD",resource_version:"v2",predecessor_version:"v1",mapping_revision:"v1",recorded_at:"2026-01-01T01:00:00Z"};await d("clearing_fact",async()=>(await a.authorizations.recordFact(m.external_authorization_id,A,{idempotencyKey:`fact-${c}`})).status==="recorded"),await d("fact_status",async()=>{let o=await a.authorizations.lookup({by:"external_authorization_id",external_authorization_id:m.external_authorization_id,resource_version:A.resource_version,mapping_revision:A.mapping_revision});return o.resolution==="unknown"&&o.authorization.facts?.[0]?.state==="unobserved"&&o.authorization.facts?.[1]?.state==="confirmed"}),await d("fact_missing_predecessor",async()=>{let{predecessor_version:o,...S}=A;return(await s(`/api/card/authorizations/${encodeURIComponent(m.external_authorization_id)}/facts`,JSON.stringify({...S,program_id:U.programId}),`missing-${c}`)).status===400}),await d("fact_version_conflict",async()=>{try{return await a.authorizations.recordFact(m.external_authorization_id,{...A,fact_type:"reversal",resource_version:"v1",predecessor_version:"v2"},{idempotencyKey:`conflict-${c}`}),!1}catch(o){return ie(o,409,"integrity_conflict")}});for(let[o,S]of["authorization_updated","reversal","refund","chargeback","settlement"].entries())await d(`fact_${S}`,async()=>(await a.authorizations.recordFact(m.external_authorization_id,{...A,fact_type:S,resource_version:`v${o+3}`,predecessor_version:`v${o+2}`},{idempotencyKey:`fact-${S}-${c}`})).status==="recorded");await d("status",async()=>{let o=await a.authorizations.lookup({by:"external_authorization_id",external_authorization_id:m.external_authorization_id,resource_version:m.resource_version,mapping_revision:m.mapping_revision});return o.resolution==="pending"&&o.authorization.facts?.[0]?.state==="confirmed"&&o.authorization.facts?.[1]?.state==="confirmed"}),await d("status_supplier_ref",async()=>(await a.authorizations.lookup({by:"supplier_transaction_id",supplier_transaction_id:m.supplier_transaction_id,resource_version:m.resource_version,mapping_revision:m.mapping_revision})).resolution==="pending"),await d("trimmed_supplier_ref",async()=>{let o={...i("trimmed"),supplier_transaction_id:` supplier-trim-${c} `};await a.authorizations.create(o,{idempotencyKey:`trimmed-${c}`});let S=await a.authorizations.lookup({by:"supplier_transaction_id",supplier_transaction_id:o.supplier_transaction_id.trim(),resource_version:o.resource_version,mapping_revision:o.mapping_revision});return S.resolution==="pending"&&S.authorization.supplier_transaction_id===o.supplier_transaction_id.trim()}),await d("supplier_namespace_conflict",async()=>{try{return await a.authorizations.create({...i("supplier-conflict"),supplier_transaction_id:m.supplier_transaction_id,mapping_revision:"other-mapping"},{idempotencyKey:`supplier-conflict-${c}`}),!1}catch(o){return ie(o,409,"integrity_conflict")}}),await d("status_idempotency_key",async()=>(await u(y)).resolution==="pending"),await d("status_charge_id",async()=>(await a.authorizations.lookup({by:"charge_id",charge_id:f})).resolution==="pending"),await d("status_not_observed",async()=>(await u(`absent-${c}`)).resolution==="not_observed"),await d("status_failed_receipt",async()=>{let o=`failed-${c}`;if(await a.authorizations.create({...i("failed"),external_card_id:"synthetic-failed-card"},{idempotencyKey:o}),(await u(o)).resolution!=="pending")return!1;let S=await u(o);return S.resolution==="resolved"&&S.authorization.processing_status==="failed"&&S.authorization.final_receipt?.execution_outcome==="failed"&&S.authorization.final_receipt.terminal_action==="cancelReservation"});let O=`sync-${c}`,D=`expired-${c}`,N=`declined-${c}`;return await d("sync_closed",async()=>{let o=await a.authorizations.create({...i("sync"),decision_mode:"synchronous"},{idempotencyKey:O});return"error"in o&&o.error==="sync_approval_admission_closed"}),await d("sync_expired",async()=>{let o=await a.authorizations.create({...i("expired"),decision_mode:"synchronous",deadline_at:"2020-01-01T00:00:00Z"},{idempotencyKey:D});return"error"in o&&o.error==="decision_deadline_exceeded"}),await d("explicit_402",async()=>{try{return await a.authorizations.create({...i("declined"),external_card_id:"synthetic-declined-card"},{idempotencyKey:N}),!1}catch(o){return ie(o,402,"spending_limit_exceeded")}}),await d("status_sync_closed",async()=>{let o=await u(O);return o.resolution==="resolved"&&o.authorization.processing_status==="failed"&&o.authorization.decision==="declined"&&o.authorization.decline_reason_code==="sync_approval_admission_closed"&&o.authorization.charge_id===void 0}),await d("status_sync_expired",async()=>{let o=await u(D);return o.resolution==="resolved"&&o.authorization.processing_status==="failed"&&o.authorization.decision==="self_reversed_timeout"&&o.authorization.decline_reason_code==="decision_deadline_exceeded"&&o.authorization.charge_id===void 0}),await d("status_explicit_402",async()=>{let o=await u(N);return o.resolution==="resolved"&&o.authorization.processing_status==="failed"&&o.authorization.decline_reason_code==="spending_limit_exceeded"}),await d("retry_503",async()=>{let o={...i("retry"),external_card_id:"synthetic-retry-card"},S=`retry-${c}`;try{return await a.authorizations.create(o,{idempotencyKey:S}),!1}catch(l){if(!ie(l,503)||!l||typeof l!="object"||!("retryable"in l)||l.retryable!==!0)return!1}return(await a.authorizations.create(o,{idempotencyKey:S})).status==="processing"}),await d("retry_after_429",async()=>{try{return await a.authorizations.create({...i("rate"),external_card_id:"synthetic-rate-limited-card"},{idempotencyKey:`rate-${c}`}),!1}catch(o){return o instanceof B&&o.status===429&&o.code==="FACTO_ENGINE_REQUEST_FAILED"&&o.outcome==="unknown"&&o.retryable&&o.retryAfterSeconds===2&&Fe(o.details)&&o.details.error.code==="too_many_requests"}}),await d("invalid_502",async()=>{try{return await a.authorizations.create({...i("gateway"),external_card_id:"synthetic-bad-gateway-card"},{idempotencyKey:`gateway-${c}`}),!1}catch(o){return o instanceof B&&o.status===502&&o.code==="FACTO_ENGINE_RESPONSE_INVALID"&&o.outcome==="unknown"&&o.retryable&&o.retryAfterSeconds===2}}),await d("nested_500_hint_false",async()=>{try{return await a.authorizations.create({...i("nested-500"),external_card_id:"synthetic-nested-500-card"},{idempotencyKey:`nested-500-${c}`}),!1}catch(o){return o instanceof B&&o.status===500&&o.code==="FACTO_ENGINE_REQUEST_FAILED"&&o.outcome==="unknown"&&o.retryable&&Fe(o.details)&&o.details.error.retryable===!1}}),await d("bad_signature",async()=>{try{return await n({apiKeySecret:{encoding:"utf8",value:"wrong-synthetic-test-key"}}).deliveries.list({target_revision:ae,selection_id:_e,page_size:1}),!1}catch(o){return ie(o,401)}}),await d("expired_timestamp",async()=>{try{return await n({nowSeconds:()=>Math.floor(Date.now()/1e3)-301}).deliveries.list({target_revision:ae,selection_id:_e,page_size:1}),!1}catch(o){return ie(o,401)}}),await d("nonce_replay",async()=>{let o=n({createNonce:()=>`nonce-${c}`}),S={target_revision:ae,selection_id:_e,page_size:1};await o.deliveries.list(S);try{return await o.deliveries.list(S),!1}catch(l){return ie(l,401)}}),await d("reconciliation",async()=>{let o=await a.deliveries.list({target_revision:ae,selection_id:_e,page_size:1}),S=fe.duplicate.deliveries[0].headers.find(([l])=>l==="facto-event-id")?.[1];return o.complete&&o.items.length===1&&o.items[0]?.event_id===S}),await d("history_replay",async()=>(await a.deliveryReplays.create({selection_id:_e},{idempotencyKey:`replay-${c}`})).status==="accepted"),_}import{randomUUID as _r}from"node:crypto";async function st(e,t,r=console.log,n=!1){r("The tool reports HTTP responses only; it does not verify the recipient\u2019s business processing results."),r(`delivery_verification_config:${JSON.stringify(t.map(c=>me(c).config))}`);let a=!0;for(let c of t){let m=me(c,Math.floor(Date.now()/1e3)+(n?1:0),n?2:1),y=!0,i=new Set;for(let[u,s]of m.deliveries.entries()){let _=s.headers.find(([d])=>d==="facto-event-id")?.[1];if(n&&_&&i.has(_))continue;_&&i.add(_);let f=new Headers(s.headers.map(([d,A])=>[d,A]));f.set("content-type","application/json");try{let d=await fetch(e,{method:"POST",headers:f,body:Buffer.from(s.rawBody),redirect:"error",signal:AbortSignal.timeout(1e4)});r(`delivery_response:${c}:${u+1}:${d.status}`),d.ok||(y=!1)}catch{r(`delivery_response:${c}:${u+1}:network_error`),y=!1}}r(`${y?"vector_passed":"vector_failed"}:${c}`),y||(a=!1)}return a}async function Mt(e,t,r,n=console.log){let a=new URL(e);if(a.protocol!=="http:"||a.hostname!=="127.0.0.1"||a.pathname!=="/"||a.search||a.hash||a.username||a.password)throw new Error("Replay only supports a loopback simulator origin");let c=me(r).config;return(await We({environment:"dev",...U,connectionId:c.connectionId,apiBaseUrl:a.origin}).deliveryReplays.create({selection_id:c.selectionId},{idempotencyKey:`synthetic-replay-${_r()}`})).status!=="accepted"?!1:(n("history_replay_accepted"),st(t,[r],n,!0))}function Vt(e){if(!X.some(t=>t===e))throw new Error("Unknown delivery scenario");return e}async function pr(e){let[t,...r]=e;if(t==="simulator-config"){let n=r.length===0?8787:Number(r[0]);if(!Number.isInteger(n)||n<1||n>65535||r.length>1)throw new Error("Usage: facto-card simulator-config [port]");console.log("Synthetic local test values only; never use these credentials in any real environment."),console.log(JSON.stringify({environment:"dev",apiBaseUrl:`http://127.0.0.1:${n}`,...U},null,2)),console.log(`delivery_verification_config:${JSON.stringify(X.map(ge))}`);return}if(t==="simulator"){let n=r.length===0?8787:Number(r[0]);if(!Number.isInteger(n)||n<1||n>65535||r.length>1)throw new Error("Usage: facto-card simulator [port]");let{url:a}=await It(n);console.log(`simulator_listening:${a}`),console.log("Synthetic local test values only; never use these credentials in any real environment."),console.log(JSON.stringify({environment:"dev",apiBaseUrl:a,...U},null,2)),console.log(`delivery_verification_config:${JSON.stringify(X.map(ge))}`);return}if(t==="vectors"){if(r.length!==1)throw new Error("Usage: facto-card vectors http://127.0.0.1:8787");await jt(r[0])||(process.exitCode=1);return}if(t==="deliveries"||t==="replay"){let n=t==="replay"?r.shift():void 0,a=r[0],c=r.slice(1);if(!a||t==="replay"&&!n)throw new Error("Usage: facto-card deliveries <callback-url> [--allow-non-loopback] [--scenario <name>] | facto-card replay <simulator-origin> <callback-url> --scenario <name> [--allow-non-loopback]");let m=!1,y;for(let u=0;u<c.length;u++)if(c[u]==="--allow-non-loopback"&&!m)m=!0;else if(c[u]==="--scenario"&&y===void 0&&c[u+1])y=Vt(c[++u]);else throw new Error("Usage: facto-card deliveries <callback-url> [--allow-non-loopback] [--scenario <name>]");let i=new URL(a);if(!["http:","https:"].includes(i.protocol)||i.username||i.password||i.hash)throw new Error("Invalid callback URL");if(!["127.0.0.1","localhost","[::1]"].includes(i.hostname)&&!m)throw new Error("Non-loopback callback requires --allow-non-loopback");if(t==="replay"){if(!y)throw new Error("Replay requires --scenario <name>");await Mt(n,i,y)||(process.exitCode=1)}else await st(i,y?[y]:X)||(process.exitCode=1);return}throw new Error("Usage: facto-card <simulator|simulator-config|vectors|deliveries|replay>")}pr(process.argv.slice(2)).catch(e=>{console.error(e instanceof Error?e.message:"Command failed"),process.exitCode=1});
@@ -0,0 +1,9 @@
1
+ # Card integration
2
+
3
+ This integration guide accompanies `@facto-to/card`. The package contains only the Card surface: the server-side Card client, delivery verification, event decoding, inbox and polling helpers, local test helpers and the `facto-card` simulator command. The guide includes local simulation and signed vectors, not proof of production readiness. Runnable shell examples use Node.js 20.9 or later; the standalone quickstart program is JavaScript, while reusable SDK snippets elsewhere are TypeScript for a TypeScript project.
4
+
5
+ Install the published `@facto-to/card@0.0.1-beta.2` from npm. For Test use `environment: 'dev'` with explicit `apiBaseUrl: 'https://test-api.facto.to'`; external dev defaults to `https://dev-api.facto.to`. Production requires an explicitly supplied approved URL; none is established. Credentials, grants and delivery registrations are separate per deployment. See [getting access](getting-access.md) and [authentication](authentication.md), then run the synthetic [quickstart](quickstart.md).
6
+
7
+ For Interlace, follow the [Adapter v1 profile](interlace-adapter-v1.md), [Chinese profile](interlace-adapter-v1.zh.md) and [Chinese integration and results](integration.zh.md). Real Interlace adaptation, complete Test/dev lifecycle UAT and production readiness remain unproved. Source documentation updates do not change published package bytes.
8
+
9
+ Continue with [concepts](concepts.md), [authorization binding](authorization-binding.md), [idempotency](idempotency.md), [authorizations](authorizations.md), [deliveries](deliveries.md), [reconciliation](reconciliation.md), [errors](errors.md), [availability](not-yet-available.md), and [versioning](versioning.md). Use the [integration checklist](integration-checklist.md) before production. Generated references: [API](reference/api.md), [schemas](reference/schemas.md), and [events](reference/events.md).
@@ -0,0 +1,96 @@
1
+ # Request authentication
2
+
3
+ This page shows how to create a server client and verify the exact request-signing rules.
4
+
5
+ ## Configure the client
6
+
7
+ Load credentials from server-side secret storage; never put them in a browser. Use the endpoint supplied for the chosen environment.
8
+
9
+ `apiKeySecret` requires an explicit encoding (`CardApiKeySecret`):
10
+
11
+ - `{ encoding: 'utf8', value: string }` — encodes the exact non-empty string as UTF-8 bytes without trimming or re-encoding. **Use this for the `hmac_secret` issued by Facto.** Engine verifies the request HMAC with the UTF-8 bytes of the stored secret string and never hex- or base64-decodes it. Facto-issued secrets are 43-character base64url strings (32 random bytes, no padding), not hex.
12
+ - `{ encoding: 'hex', value: string }` — validates a non-empty, even-length hexadecimal string and decodes it to raw key bytes before computing HMAC-SHA256. Use this only when your integration contract explicitly provisions the key out-of-band as hex-encoded raw bytes. Do not choose `hex` just because a secret string looks hexadecimal: when Engine stores that string as the secret it verifies the string's UTF-8 bytes, so a `hex`-decoded key produces a signature Engine rejects with HTTP 401.
13
+ - `Uint8Array` — uses the exact non-empty raw key bytes directly.
14
+
15
+ Bare strings are rejected at both compile time and runtime with `CardError` (`outcome: 'config_invalid'`, `code: 'FACTO_CONFIG_INVALID'`) so every integration states the key encoding explicitly instead of relying on a guess.
16
+
17
+ <!-- example:client -->
18
+ ```typescript
19
+ import { createCardClient, type CardApiKeySecret } from '@facto-to/card'
20
+
21
+ export function createConfiguredCardClient(config: {
22
+ environment: 'dev' | 'production'
23
+ apiBaseUrl: string
24
+ connectionId: string
25
+ programId: string
26
+ apiKeyId: string
27
+ apiKeySecret: CardApiKeySecret
28
+ }) {
29
+ // Load these values from your server-side secret manager, never from a browser.
30
+ return createCardClient(config)
31
+ }
32
+ ```
33
+ <!-- /example:client -->
34
+
35
+ ## Required request headers
36
+
37
+ | Header | Value |
38
+ | --- | --- |
39
+ | `x-api-key` | Credential key identifier assigned to the program connection. |
40
+ | `x-api-timestamp` | Current Unix time in seconds. |
41
+ | `x-api-nonce` | Fresh, unique visible-ASCII nonce, at most 128 characters. |
42
+ | `x-api-signature` | Lowercase hexadecimal HMAC-SHA256 signature. |
43
+ | `Idempotency-Key` | Required on specified mutations; separate from and not covered by the signature. |
44
+
45
+ ## Construct the signature
46
+
47
+ 1. Hash the exact request body bytes with SHA-256; use the empty byte string for an absent body.
48
+ 2. Join these six UTF-8 lines with LF and no trailing LF: `FACTO-HMAC-V2`, uppercase method, exact path and query, timestamp, nonce, and lowercase body digest.
49
+ 3. Compute HMAC-SHA256 using the request credential secret and encode the result as lowercase hexadecimal.
50
+ 4. Send the same body bytes and path that were signed. Engine's idempotency record separately binds the key to request bytes.
51
+
52
+ ### Fixed synthetic calculations
53
+
54
+ The SDK signing tests exercise these public test-only vectors; never use these keys as credentials.
55
+
56
+ #### UTF-8 key vector (`{ encoding: 'utf8', value }`) — the encoding Engine uses for issued secrets
57
+
58
+ | Input | Value |
59
+ | --- | --- |
60
+ | Secret | `{ encoding: 'utf8', value: 'PUBLIC-SYNTHETIC-NOT-A-REAL-SECRET' }` |
61
+ | Method and path | `POST` `/api/card/authorizations` |
62
+ | Timestamp and nonce | `1792886400`, `public-synthetic-nonce` |
63
+ | Body | `{"sample":"synthetic"}` |
64
+ | Body SHA-256 | `2c5960ee77e9a75aeb26b4ad368493060f394109c5027776fe84beb422a94a39` |
65
+ | Canonical line 1 | `FACTO-HMAC-V2` |
66
+ | Canonical line 2 | `POST` |
67
+ | Canonical line 3 | `/api/card/authorizations` |
68
+ | Canonical line 4 | `1792886400` |
69
+ | Canonical line 5 | `public-synthetic-nonce` |
70
+ | Canonical line 6 | `2c5960ee77e9a75aeb26b4ad368493060f394109c5027776fe84beb422a94a39` |
71
+ | Signature | `00e3b45ebb5f91dd6139c6f8f11fa6db3ee640534a6026897a9e56f2bf125636` |
72
+
73
+ #### Same 64-character string, two encodings (`hex` versus `utf8`)
74
+
75
+ This vector shows that the two encodings of one 64-character hexadecimal-looking string produce different keys and therefore different signatures. It demonstrates the SDK's decoding behavior; it does not mean that a hexadecimal-looking secret must be passed as `hex`.
76
+
77
+ | Input | Value |
78
+ | --- | --- |
79
+ | Secret string | `00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff` |
80
+ | Method, path, timestamp, nonce, body | Same as the UTF-8 vector above |
81
+ | Signature with `{ encoding: 'utf8', value }` (key = the 64 ASCII bytes of the string; this is what Engine computes when this string is the stored secret) | `b6c763f425910381b55ce74697b5820751332df34b2c189af7cf787a8db6133d` |
82
+ | Signature with `{ encoding: 'hex', value }` (key = the 32 decoded raw bytes, including `0x00`; valid only for a verifier that was provisioned with those raw bytes out-of-band) | `4962033a240ae1d91b80d5e3aab8e47a540a70519fbdc00c953409f3c295a606` |
83
+
84
+ ## Time, replay and failures
85
+
86
+ Synchronize clocks. A timestamp more than 300 seconds from Engine time in either direction is rejected. A nonce is single-use: create a new nonce and timestamp for each retry while keeping the original body and idempotency key. Do not log credentials or signatures. If the signing credential may have been exposed, follow [key compromise, revocation and rotation](getting-access.md#key-compromise-revocation-and-rotation).
87
+
88
+ | Failure | Response | Action |
89
+ | --- | --- | --- |
90
+ | Missing or duplicate authentication header | 401 `authentication_failed` | Send exactly one value for each required header. |
91
+ | Invalid signature | 401 `authentication_failed` | Check key, exact path and body bytes, and canonical input. |
92
+ | Reused nonce | 401 `authentication_failed` | Generate a fresh nonce and sign the retry again. |
93
+ | Valid identity without the required grant | 403 `program_grant_denied` | Confirm the operation and environment grants before retrying. |
94
+ | Stale timestamp | 401 `authentication_failed` | Synchronize the clock and send a newly signed request. |
95
+
96
+ For other responses, inspect the error envelope as described in [errors](errors.md).
@@ -0,0 +1,182 @@
1
+ # Card Authorization Binding Standard
2
+
3
+ This guide specifies the required authorization binding flow for connecting an external Card Program's cards to Facto through `@facto-to/card`.
4
+
5
+ Every external Card Program integration supports hosted binding sessions through `createCardClient().sessions`. Program-owned connect pages (`card.intents`) remain an optional capability for programs that host their own full selection surface; they do not replace the session channel.
6
+
7
+ ## Two entry legs, one hosted session channel
8
+
9
+ Both entry points converge on the same server-to-server binding session routes (`/api/card/connect/sessions*`) and Facto hosted authorization surface (`/card/connect#binding_token=...`).
10
+
11
+ ### Program-initiated leg (P leg)
12
+
13
+ Use the P leg when the cardholder starts from a card inside your own wallet or card app:
14
+
15
+ 1. The cardholder clicks **Connect to Facto** on a specific issued card in your app. Your frontend synchronously opens a popup window inside the click call stack so the browser does not block it.
16
+ 2. Your backend calls `card.sessions.create(...)` with `requested_user_consents`, `return_uri`, and an `Idempotency-Key` (and optional `cardSelection: true` to send `x-facto-card-selection: 1`).
17
+ 3. Facto creates a `pending` session and returns a sensitive one-time `binding_url` plus the server-determined `proof_policy`.
18
+ 4. Your app navigates the pre-opened popup to `binding_url`. The cardholder signs in to Facto and claims the session.
19
+ 5. Your backend obtains the active Facto challenge (via `card.sessions.getProofChallenge(id)` when `proof_policy.challenge_delivery === 'provider_backend'`, or from the browser handoff when `challenge_delivery === 'browser_handoff'`).
20
+ 6. Your backend signs a compact-JWS provider proof containing the cardholder's eligible cards — marking the clicked card with `isEntryCard: true` — and submits it via `card.sessions.submitProof(id, ...)`.
21
+ 7. The cardholder reviews the asserted cards and consents on Facto's hosted page. Facto atomically creates the card binding(s) and redirects the popup back to your pre-registered `return_uri`.
22
+ 8. Poll or read `card.sessions.get(id)` (or consume `card.binding.linked` webhooks) for the authoritative terminal state. Never treat `return_uri` navigation alone as binding proof.
23
+
24
+ ### Facto-initiated leg (F leg)
25
+
26
+ Use the F leg when the cardholder starts from Facto's Connect sheet and selects your Card Program (configured with `connect_entry_url` and no `connect_page_url`):
27
+
28
+ 1. Facto requests `GET <connect_entry_url>?connect_hint=<jws>` with `Accept: application/json`.
29
+ 2. Your backend verifies `connect_hint` locally with `verifyCardIntentToken(...)` against Facto's public JWKS (`CARD_INTENT_JWKS_PATH`) and enforces single-use on the verified `nonce`.
30
+ 3. If the cardholder has not yet chosen which issuer (for multi-issuer programs) and card to bind for this attempt, your entry endpoint answers `403` with `{ "reason": "authorization_required" }`.
31
+ 4. Facto opens `<connect_entry_url>?connect_hint=<fresh-jws>` in a popup window (HTML). Inside your popup, the cardholder authenticates, authorizes the connection, selects the issuer (when your program spans multiple issuers), and selects the card to bind.
32
+ 5. Your popup records the selection and returns control to Facto's origin.
33
+ 6. Facto retries the JSON entry request with a fresh hint. Your backend verifies the new hint, calls `card.sessions.create(...)` (marking the chosen card as the entry card when submitting proof), and responds `201` with `{ "binding_url": "..." }`.
34
+ 7. Facto runs hosted claim, proof submission, review, and consent inside the Cards sheet (same steps 5–8 as the P leg).
35
+
36
+ ## SDK methods on `card.sessions`
37
+
38
+ | Method | HTTP operation | Status | Idempotency | Purpose |
39
+ | --- | --- | --- | --- | --- |
40
+ | `card.sessions.create(input, options)` | `POST /api/card/connect/sessions` | `201` | Required (`Idempotency-Key`) | Create a hosted binding session; returns one-time `binding_url` and server-determined `proof_policy`. |
41
+ | `card.sessions.get(id, options?)` | `GET /api/card/connect/sessions/{id}` | `200` | None | Read the state-safe status projection (`BindingSessionStatus`). |
42
+ | `card.sessions.getProofChallenge(id, options?)` | `GET /api/card/connect/sessions/{id}/proof-challenge` | `200` | None | Read active `facto_challenge` and `session_request_digest` for `provider_backend` connections while `proof_pending` (every other state returns `404`). |
43
+ | `card.sessions.submitProof(id, input, options)` | `POST /api/card/connect/sessions/{id}/provider-proof` | `202` | Required (`Idempotency-Key`) | Submit the challenge-bound compact-JWS provider proof. Accepts either a pre-signed `ProviderProofSubmitPayload` or structured cards + Ed25519 signer. |
44
+ | `card.sessions.cancel(id, options)` | `POST /api/card/connect/sessions/{id}/cancel` | `200` | Required (`Idempotency-Key`) | Cancel a nonterminal session as the partner (sends `{}` by default); already-terminal sessions return unchanged. |
45
+
46
+ All five operations authenticate with the same four-header HMAC V2 credentials as every other `createCardClient()` call. `create` injects `program_ref` from the client's `programId` scope.
47
+
48
+ ## Card selection negotiation and `proof_policy`
49
+
50
+ `proof_policy` is determined exclusively by Facto from your connection's registered configuration and is never declared in the request body:
51
+
52
+ - `allowed_modes`: non-empty unique list of permitted proof modes (`provider_reauthentication`, `provider_second_channel`).
53
+ - `challenge_after_facto_auth`: always `true` (Facto issues a challenge only after the cardholder authenticates in Facto).
54
+ - `challenge_delivery`: either `provider_backend` (fetch challenge via `card.sessions.getProofChallenge(id)`) or `browser_handoff`.
55
+ - `card_selection_supported`: optional `true`, returned only when `card.sessions.create` opted in with `{ cardSelection: true }`, which sends the request header `x-facto-card-selection: 1`.
56
+
57
+ Because `x-facto-card-selection: 1` shapes the response, Facto binds it into the create request's idempotency digest: reusing the same `Idempotency-Key` with a different `cardSelection` flag returns `409 integrity_conflict`.
58
+
59
+ ```ts
60
+ const created = await card.sessions.create(
61
+ {
62
+ requested_user_consents: ['card.metadata.view', 'card.use_for_facto_payments'],
63
+ return_uri: 'https://partner.example/facto/return',
64
+ },
65
+ {
66
+ idempotencyKey: 'bind-session-create-0001',
67
+ cardSelection: true,
68
+ },
69
+ )
70
+
71
+ if (created.proof_policy.challenge_delivery === 'provider_backend') {
72
+ const challenge = await card.sessions.getProofChallenge(created.binding_session_id)
73
+ // Sign and submit proof once the cardholder claims the session.
74
+ }
75
+ ```
76
+
77
+ ## Submitting provider proof and `isEntryCard`
78
+
79
+ `POST /api/card/connect/sessions/{id}/provider-proof` carries a compact EdDSA JWS (`proof_format: 'compact-jws'`, protected header `typ: 'facto-card-binding+jwt'`, `alg: 'EdDSA'`, `kid`) signed by an Ed25519 key certified for your connection.
80
+
81
+ You can pass structured asserted cards directly to `card.sessions.submitProof(...)` (or call `signBindingAssertion(...)` standalone when signing offline or via a KMS callback). Pass your registered provider connection ID (`providerConnectionId: 'pc_...'`), which is distinct from `CardClientOptions.connectionId` (`pconn_...`) and is emitted as the wire JWS `connection_id` claim. The SDK validates contract bounds and maps public card fields to the exact wire JWS claims (`externalCardId` to `card_ref`, `isEntryCard: true` to `is_entry_card: true`, and `display.cardType` to `display.card_type`):
82
+
83
+ ```ts
84
+ await card.sessions.submitProof(
85
+ created.binding_session_id,
86
+ {
87
+ providerConnectionId: 'pc_01JZ9X8K4M2V7R5T3N6P8Q0W',
88
+ issuer: 'https://partner.example/card-assertions',
89
+ subject: pairwiseAccountSubject,
90
+ jti: `jti-${crypto.randomUUID()}`,
91
+ factoChallenge: challenge.facto_challenge,
92
+ sessionRequestDigest: challenge.session_request_digest,
93
+ requestedUserConsents: ['card.metadata.view', 'card.use_for_facto_payments'],
94
+ proof: {
95
+ mode: 'provider_second_channel',
96
+ approvedAtSeconds: Math.floor(Date.now() / 1000),
97
+ approvalRef: grantApprovalId,
98
+ channelType: 'provider_authenticated_app',
99
+ },
100
+ cards: [
101
+ {
102
+ externalCardId: 'card_opaque_0001',
103
+ isEntryCard: true,
104
+ display: { network: 'visa', cardType: 'virtual', last4: '4242' },
105
+ },
106
+ {
107
+ externalCardId: 'card_opaque_0002',
108
+ display: { network: 'visa', cardType: 'physical', last4: '9012' },
109
+ },
110
+ ],
111
+ signingKeyId: 'partner-ed25519-key-01',
112
+ signer: partnerEd25519Jwk,
113
+ },
114
+ { idempotencyKey: 'bind-session-proof-0001' },
115
+ )
116
+ ```
117
+
118
+ Card and timing rules enforced before signing:
119
+
120
+ - `providerConnectionId` must be a `pc_...` provider connection identifier (passing a `pconn_...` program connection identifier is rejected locally with `FACTO_CONFIG_INVALID`).
121
+ - Between 1 and 20 unique `externalCardId` entries (8 to 512 chars; never a PAN).
122
+ - At most one card may set `isEntryCard: true`; cards without `isEntryCard: true` omit `is_entry_card` on the wire.
123
+ - `display` fields (`network`, `cardType`, `last4`) are optional; omit absent fields rather than sending synthetic digits.
124
+ - `exp - iat` must not exceed 300 seconds, and proof evidence (`authenticatedAtSeconds` or `approvedAtSeconds`) must satisfy `evidenceAt <= issuedAtSeconds` and `issuedAtSeconds - evidenceAt <= 600` (600-second proof evidence freshness limit).
125
+
126
+ If your signing key lives in an external HSM or KMS, pass an async callback `(signingInput: Uint8Array) => Promise<Uint8Array>` as `signer`, or pass a pre-signed `{ proof_format: 'compact-jws', binding_assertion }` directly to `card.sessions.submitProof(...)`.
127
+
128
+ ## Verifying entry hints (`verifyCardIntentToken`)
129
+
130
+ For the F leg, verify every `connect_hint` presented to your `connect_entry_url` using `verifyCardIntentToken`:
131
+
132
+ ```ts
133
+ import { verifyCardIntentToken, FactoIntentTokenError } from '@facto-to/card'
134
+
135
+ try {
136
+ const verified = await verifyCardIntentToken({
137
+ intentToken: connectHint,
138
+ environment: 'dev',
139
+ apiBaseUrl: 'https://test-api.facto.to',
140
+ audience: yourRegisteredProgramCode,
141
+ })
142
+ // Enforce single-use on verified.nonce before acting on verified.pairwiseSubject.
143
+ } catch (error) {
144
+ if (error instanceof FactoIntentTokenError) {
145
+ // Reject the token; ask the cardholder to restart from Facto.
146
+ }
147
+ throw error
148
+ }
149
+ ```
150
+
151
+ ## Status projections and error codes
152
+
153
+ `card.sessions.get(id)` and `card.sessions.cancel(id)` return a closed `BindingSessionStatus` projection:
154
+
155
+ - Nonterminal states: `pending`, `proof_pending`, `consent_pending`.
156
+ - `completed` with `outcome: 'bound'`: includes sorted `binding_ids` and optional `completed_at`.
157
+ - `completed` with `outcome: 'declined'`: includes `failure_reason: 'declined_by_user'` and optional `completed_at`.
158
+ - `cancelled`: optional `completed_at` and `failure_reason` (`cancelled_by_user`, `cancelled_by_partner`, `proof_rejected`, `admission_closed`, `no_eligible_cards`, `integrity_conflict`).
159
+ - `expired`: optional `failure_reason` (`expired`, `proof_timeout`).
160
+
161
+ Common HTTP error responses on session routes:
162
+
163
+ | HTTP status | Error code(s) | Meaning |
164
+ | --- | --- | --- |
165
+ | `400` | `invalid_request`, `return_uri_not_registered`, `prohibited_data` | Malformed input, unregistered `return_uri`, or PAN-shaped card reference. |
166
+ | `401` | `authentication_failed` | HMAC V2 verification failed. |
167
+ | `403` | `program_grant_denied` | Credential is not granted to the requested program or capability. |
168
+ | `404` | `not_found` | Session does not exist in scope, or no active `provider_backend` proof challenge is currently available. |
169
+ | `409` | `integrity_conflict`, `assertion_replayed` | Idempotency digest mismatch, immutable session conflict, or replayed assertion `jti`. |
170
+ | `422` | `assertion_rejected`, `tenant_scope_mismatch`, `proof_mode_denied` | Proof signature, claims, scope, or proof mode rejected. |
171
+ | `423` | `binding_admission_closed` | Program binding admission is currently closed. |
172
+ | `428` | `provider_proof_required` | Cardholder has not claimed the hosted session yet, so no active challenge exists. |
173
+ | `429` | `rate_limited` | Bounded rate limit exceeded. |
174
+
175
+ ## Non-negotiable invariants
176
+
177
+ 1. **No pre-selected Facto user:** A Card Program cannot pre-select or assert a Facto user. A binding session attaches to a Facto user only when that user authenticates and claims the hosted session.
178
+ 2. **Signed proof is the only card source:** Candidate cards come exclusively from the partner's signed EdDSA proof assertion, never from browser query parameters or unauthenticated client payloads.
179
+ 3. **Consent happens only on Facto's hosted page:** Selections inside the partner app decide which card(s) to propose; binding consent is granted only by the authenticated Facto user on Facto's hosted surface.
180
+ 4. **Server-owned `proof_policy`:** Callers never declare allowed proof modes or challenge delivery channels.
181
+ 5. **Fail closed without downgrade:** Popup blocks or entry errors must never fall back to same-tab redirects or bypass hosted consent.
182
+ 6. **Issuer selection belongs to the partner:** When one Card Program issues cards across multiple card issuers, issuer selection happens inside the partner's F-leg entry surface, never inside Facto's directory UI.