@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.
- package/CHANGELOG.md +20 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +63 -2
- package/dist/card-inbox-DzsHFRPT.d.cts +312 -0
- package/dist/card-inbox-DzsHFRPT.d.ts +312 -0
- package/dist/chunk-KBS2PWM4.js +2 -0
- package/dist/cli/index.js +6 -0
- package/dist/docs/README.md +9 -0
- package/dist/docs/authentication.md +96 -0
- package/dist/docs/authorization-binding.md +182 -0
- package/dist/docs/authorizations.md +182 -0
- package/dist/docs/concepts.md +36 -0
- package/dist/docs/deliveries.md +170 -0
- package/dist/docs/errors.md +100 -0
- package/dist/docs/getting-access.md +56 -0
- package/dist/docs/idempotency.md +78 -0
- package/dist/docs/integration-checklist.md +15 -0
- package/dist/docs/integration.zh.md +59 -0
- package/dist/docs/interlace-adapter-v1.md +87 -0
- package/dist/docs/interlace-adapter-v1.zh.md +87 -0
- package/dist/docs/not-yet-available.md +13 -0
- package/dist/docs/quickstart.md +126 -0
- package/dist/docs/reconciliation.md +86 -0
- package/dist/docs/reference/api.md +2541 -0
- package/dist/docs/reference/events.md +639 -0
- package/dist/docs/reference/schemas.json +6603 -0
- package/dist/docs/reference/schemas.md +1001 -0
- package/dist/docs/simulator.md +235 -0
- package/dist/docs/versioning.md +9 -0
- package/dist/index.cjs +3 -0
- package/dist/index.d.cts +987 -0
- package/dist/index.d.ts +987 -0
- package/dist/index.js +2 -0
- package/dist/source/build.mjs +5 -0
- package/dist/source/package.json +16 -0
- package/dist/source/src/connect/cli/deliveries.ts +48 -0
- package/dist/source/src/connect/cli/index.ts +57 -0
- package/dist/source/src/connect/server/card-binding-assertion.ts +312 -0
- package/dist/source/src/connect/server/card-client.ts +1018 -0
- package/dist/source/src/connect/server/card-delivery.ts +301 -0
- package/dist/source/src/connect/server/card-events.ts +473 -0
- package/dist/source/src/connect/server/card-idempotency.ts +27 -0
- package/dist/source/src/connect/server/card-inbox.ts +82 -0
- package/dist/source/src/connect/server/card-intent-token.ts +588 -0
- package/dist/source/src/connect/server/card-polling.ts +69 -0
- package/dist/source/src/connect/server/card-signing.ts +115 -0
- package/dist/source/src/connect/server/card-transport.ts +282 -0
- package/dist/source/src/connect/server/errors.ts +280 -0
- package/dist/source/src/connect/server/fixtures/engine/card-events.synthetic.ts +84 -0
- package/dist/source/src/connect/server/retry-after.ts +12 -0
- package/dist/source/src/connect/testing/card-inbox.ts +124 -0
- package/dist/source/src/connect/testing/card-scenarios.ts +243 -0
- package/dist/source/src/connect/testing/card-simulator-vectors.ts +262 -0
- package/dist/source/src/connect/testing/card-simulator.ts +531 -0
- package/dist/source/src/connect/testing/interlace-card-transactions.ts +704 -0
- package/dist/source/src/connect/testing/pure-sha256.ts +123 -0
- package/dist/source/src/connect/wire.d.ts +544 -0
- package/dist/source/src/index.ts +163 -0
- package/dist/source/src/testing-browser.ts +24 -0
- package/dist/source/src/testing.ts +26 -0
- package/dist/source/tsconfig.json +20 -0
- package/dist/testing-browser.d.ts +220 -0
- package/dist/testing-browser.js +5 -0
- package/dist/testing.cjs +6 -0
- package/dist/testing.d.cts +199 -0
- package/dist/testing.d.ts +199 -0
- package/dist/testing.js +5 -0
- package/package.json +60 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as H,b as le,c as ue,d as _e,e as ye,f as pe,g as fe,i as ge}from"./chunk-KBS2PWM4.js";var J="/.well-known/facto/card/connect/jwks.json",a=class extends Error{code;details;constructor(t,n,r={}){super(n),this.name="FactoIntentTokenError",this.code=t,this.details=r.details}},ve="facto",me={dev:"https://dev-api.facto.to",sandbox:"https://dev-api.facto.to",production:"https://api.facto.to"},Ie=["dev","production"];function he(e){return Ee(e,Ie)}async function Ee(e,t){if(e===null||typeof e!="object")throw new a("FACTO_INTENT_TOKEN_INPUT_INVALID","verifyCardIntentToken requires an input object");let n=U(e.intentToken,"intentToken"),r=U(e.audience,"audience"),i=e.issuer===void 0?ve:U(e.issuer,"issuer"),o=xe(e.clockToleranceSeconds),s=Math.floor(Oe(e.nowMs)/1e3),{headerB64:d,payloadB64:c,signature:g}=be(n),I=P(Y(d,"header"),"FACTO_INTENT_TOKEN_MALFORMED","intent token header");if(I.alg!=="EdDSA")throw new a("FACTO_INTENT_TOKEN_UNSUPPORTED_ALG","intent token JWS alg must be EdDSA",{details:{alg:I.alg}});let f=typeof I.kid=="string"?I.kid:void 0,T=Te(e,t),b=await we(T),l=ke(b,f),E=Ke(`${d}.${c}`);if(!await De(E,g,l))throw new a("FACTO_INTENT_TOKEN_SIGNATURE_INVALID","intent token signature does not verify against the Facto JWKS");let p=Se(Y(c,"payload"));if(p.iss!==i)throw new a("FACTO_INTENT_TOKEN_ISSUER_MISMATCH","intent token issuer mismatch",{details:{expected:i,actual:p.iss}});if(p.aud!==r)throw new a("FACTO_INTENT_TOKEN_AUDIENCE_MISMATCH","intent token audience mismatch",{details:{expected:r,actual:p.aud}});if(s>p.exp+o)throw new a("FACTO_INTENT_TOKEN_EXPIRED","intent token has expired",{details:{exp:p.exp,now:s}});return{programId:p.program_id,pairwiseSubject:p.sub,nonce:p.nonce,expiresAt:new Date(p.exp*1e3).toISOString()}}function Te(e,t){if(e.jwks!==void 0&&e.jwks!==null)return e.jwks;if(typeof e.apiBaseUrl=="string"&&e.apiBaseUrl.length>0){let n;try{n=new URL(e.apiBaseUrl)}catch{throw new a("FACTO_INTENT_TOKEN_JWKS_INVALID",`apiBaseUrl is not a valid URL: ${e.apiBaseUrl}`)}if(n.username||n.password||n.search||n.hash||n.pathname!=="/"&&n.pathname!=="")throw new a("FACTO_INTENT_TOKEN_JWKS_INVALID","apiBaseUrl must be a bare origin without path, query, or credentials");return`${n.origin}${J}`}if(e.environment!==void 0){let n=t.find(r=>r===e.environment);if(n===void 0)throw new a("FACTO_INTENT_TOKEN_INPUT_INVALID",`environment must be one of ${t.map(r=>`'${r}'`).join(", ")}`);return`${me[n]}${J}`}throw new a("FACTO_INTENT_TOKEN_INPUT_INVALID","jwks, apiBaseUrl, or environment is required")}function be(e){let t=e.split(".");if(t.length!==3)throw new a("FACTO_INTENT_TOKEN_MALFORMED","intent token is not a compact JWS (expected three segments)");let[n,r,i]=t;if(!n||!r||!i)throw new a("FACTO_INTENT_TOKEN_MALFORMED","intent token has an empty JWS segment");return{headerB64:n,payloadB64:r,signature:X(i,"signature")}}function Y(e,t){let n=new TextDecoder().decode(X(e,t));try{return JSON.parse(n)}catch(r){throw new a("FACTO_INTENT_TOKEN_MALFORMED",`intent token ${t} is not valid JSON`,{details:r})}}async function we(e){return L(typeof e=="function"?await e():typeof e=="string"?await Ae(e):e)}var Ne=5e3,R=64*1024;async function Ae(e){let t;try{t=new URL(e)}catch{throw new a("FACTO_INTENT_TOKEN_JWKS_INVALID",`JWKS url is not a valid URL: ${e}`)}if(t.protocol!=="https:")throw new a("FACTO_INTENT_TOKEN_JWKS_INVALID",`JWKS url must use https: (got ${t.protocol})`,{details:{protocol:t.protocol}});let n=new AbortController,r=setTimeout(()=>n.abort(),Ne),i,o;try{try{i=await fetch(e,{method:"GET",headers:{accept:"application/json"},redirect:"follow",signal:n.signal})}catch(d){throw new a("FACTO_INTENT_TOKEN_JWKS_INVALID",`failed to fetch Facto JWKS from ${e}`,{details:d})}if(!i.ok)throw new a("FACTO_INTENT_TOKEN_JWKS_INVALID",`Facto JWKS request failed with status ${i.status}`,{details:{status:i.status}});let s=Number(i.headers.get("content-length"));if(Number.isFinite(s)&&s>R)throw new a("FACTO_INTENT_TOKEN_JWKS_INVALID",`Facto JWKS response exceeds ${R} bytes`,{details:{contentLength:s}});try{o=await i.text()}catch(d){throw new a("FACTO_INTENT_TOKEN_JWKS_INVALID","Facto JWKS response could not be read",{details:d})}}finally{clearTimeout(r)}if(o.length>R)throw new a("FACTO_INTENT_TOKEN_JWKS_INVALID",`Facto JWKS response exceeds ${R} bytes`,{details:{bytes:o.length}});try{return JSON.parse(o)}catch(s){throw new a("FACTO_INTENT_TOKEN_JWKS_INVALID","Facto JWKS response was not valid JSON",{details:s})}}function L(e){let t=P(e,"FACTO_INTENT_TOKEN_JWKS_INVALID","JWKS");if(!Array.isArray(t.keys))throw new a("FACTO_INTENT_TOKEN_JWKS_INVALID",'JWKS "keys" must be an array');return{keys:t.keys.map(Ce)}}function Ce(e){let t=typeof e=="object"&&e!==null?e:{};return{kty:typeof t.kty=="string"?t.kty:"",crv:typeof t.crv=="string"?t.crv:"",x:typeof t.x=="string"?t.x:"",...typeof t.kid=="string"?{kid:t.kid}:{},...typeof t.alg=="string"?{alg:t.alg}:{},...typeof t.use=="string"?{use:t.use}:{}}}function ke(e,t){let n=e.keys.filter(r=>r.kty==="OKP"&&r.crv==="Ed25519"&&r.x.length>0);if(n.length===0)throw new a("FACTO_INTENT_TOKEN_JWKS_INVALID","Facto JWKS has no usable Ed25519 signing key");if(t!==void 0){let r=n.filter(i=>i.kid===t);if(r.length>0)return r}return n}async function De(e,t,n){let r=Fe();for(let i of n){let o;try{o=await r.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:i.x},{name:"Ed25519"},!1,["verify"])}catch{continue}try{if(await r.verify({name:"Ed25519"},o,t,e))return!0}catch{continue}}return!1}function Se(e){let t=P(e,"FACTO_INTENT_TOKEN_CLAIMS_INVALID","intent token claims"),n=t.program_id,r=t.program_ref;if(typeof n=="string"&&n.length>0&&typeof r=="string"&&r.length>0&&n!==r)throw new a("FACTO_INTENT_TOKEN_CLAIMS_INVALID",'intent token claims "program_id" and "program_ref" must match when both are present');let i=typeof n=="string"&&n.length>0?n:x(t,"program_ref");return{iss:x(t,"iss"),aud:x(t,"aud"),sub:x(t,"sub"),program_id:i,nonce:x(t,"nonce"),iat:Z(t,"iat"),exp:Z(t,"exp")}}function U(e,t){if(typeof e!="string"||e.length===0)throw new a("FACTO_INTENT_TOKEN_INPUT_INVALID",`${t} must be a non-empty string`);return e}function xe(e){if(e===void 0)return 0;if(typeof e!="number"||!Number.isFinite(e)||e<0)throw new a("FACTO_INTENT_TOKEN_INPUT_INVALID","clockToleranceSeconds must be a non-negative finite number");return e}function Oe(e){if(e===void 0)return Date.now();if(e instanceof Date){let t=e.getTime();if(Number.isNaN(t))throw new a("FACTO_INTENT_TOKEN_INPUT_INVALID","nowMs is an invalid Date");return t}if(typeof e=="number"&&Number.isFinite(e))return e;throw new a("FACTO_INTENT_TOKEN_INPUT_INVALID","nowMs must be a Date or unix milliseconds number")}function P(e,t,n){if(typeof e!="object"||e===null||Array.isArray(e))throw new a(t,`${n} must be a JSON object`);return e}function x(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new a("FACTO_INTENT_TOKEN_CLAIMS_INVALID",`intent token claim "${t}" must be a non-empty string`);return n}function Z(e,t){let n=e[t];if(typeof n!="number"||!Number.isFinite(n))throw new a("FACTO_INTENT_TOKEN_CLAIMS_INVALID",`intent token claim "${t}" must be a finite number`);return n}function X(e,t){if(!/^[A-Za-z0-9_-]*$/.test(e))throw new a("FACTO_INTENT_TOKEN_MALFORMED",`intent token ${t} is not valid base64url`);let n=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4);return Re(n,t)}function Re(e,t){let n=globalThis.atob;if(n){let i;try{i=n(e)}catch(s){throw new a("FACTO_INTENT_TOKEN_MALFORMED",`intent token ${t} is not valid base64url`,{details:s})}let o=new Uint8Array(i.length);for(let s=0;s<i.length;s+=1)o[s]=i.charCodeAt(s);return o}let r=globalThis.Buffer;if(r)return new Uint8Array(r.from(e,"base64"));throw new a("FACTO_INTENT_TOKEN_INPUT_INVALID","No base64 decoder is available in this runtime")}function Ke(e){let t=new TextEncoder().encode(e),n=new Uint8Array(t.length);return n.set(t),n}function Fe(){let e=globalThis.crypto;if(e?.subtle)return e.subtle;throw new a("FACTO_INTENT_TOKEN_INPUT_INVALID","Web Crypto (crypto.subtle) is not available in this runtime")}import{createHash as ie,createHmac as qe,timingSafeEqual as je}from"node:crypto";var ne=["card.binding.linked","card.binding.relinked","card.binding.revoked","card.binding.route_changed","card.binding.limits_changed","card.binding.ownership_transferred","card.charge.finalized","card.charge.facts_updated","card.authorization.updated"],Ve=["card_program_id","program_connection_id","connect_intent_id","binding_session_id","card_type","envelope_expires_at","authorization_ref","redelivery"],ze=new Set(Ve);function k(e){if(e===null||typeof e!="object")return!1;if(Array.isArray(e))return e.some(t=>k(t));for(let[t,n]of Object.entries(e))if(ze.has(t)||k(n))return!0;return!1}var Le=new Set(["envelope_version","event_id","event_kind","environment","program_id","origin_connection_id","binding_id","binding_revision","connection_sequence","occurred_at","data"]),Ue=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Je=/^cprog_[A-Za-z0-9_-]{8,}$/,Pe=/^pconn_[A-Za-z0-9_-]{16,}$/,Be=/^cb_[A-Za-z0-9_-]{16,}$/;function y(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function A(e){return typeof e=="string"&&e.length>0}function K(e){return e===null||typeof e=="string"}function u(e,t){return t.every(n=>A(e[n]))}function _(e){return Number.isSafeInteger(e)}function Q(e){return Array.isArray(e)&&e.every(t=>y(t)&&u(t,["kind","state","recorded_at","source_system"])&&(t.observed_at===void 0||typeof t.observed_at=="string")&&(t.safe_code===void 0||typeof t.safe_code=="string"))}function v(e,t){return t.every(n=>e[n]===void 0||typeof e[n]=="string")}function ee(e,t){return t.every(n=>e[n]===void 0||e[n]===null||typeof e[n]=="string")}function B(e){return y(e)&&Object.hasOwn(e,"network")&&Object.hasOwn(e,"type")&&Object.hasOwn(e,"last4")&&K(e.network)&&K(e.type)&&K(e.last4)}function Me(e){if(!_(e.lifecycle_revision)||e.lifecycle_revision<1||!u(e,["operation_type","resource_version","external_authorization_id","mapping_revision"]))return!1;let{authorization:t,charge:n,issuer:r,refunds:i,change:o}=e;if(!y(t)||!u(t,["amount","currency"])||!v(t,["supplier_transaction_id","decision"])||!y(r)||!u(r,["state","cleared_amount","reversed_amount","refunded_amount"])||!v(r,["last_recorded_at"])||!_(r.entry_count)||r.entry_count<0||!_(r.unlinked_count)||r.unlinked_count<0||!y(i)||!_(i.case_count)||i.case_count<0||!u(i,["total_amount","total_paid_amount","total_excess_amount"])||!v(i,["last_updated_at"])||!y(i.status_counts)||!y(o)||!u(o,["type","at"])||!v(o,["ref"]))return!1;let s=i.status_counts;if(!["awaiting_charge_final","awaiting_funds","payable","paid","failed","not_payable"].every(d=>_(s[d])&&s[d]>=0)||o.type==="issuer_fact.recorded"&&o.issuer_fact===void 0||["refund_case.awaiting_charge_final","refund_case.awaiting_funds","refund_case.payable","refund_case.paid","refund_case.failed","refund_case.not_payable"].includes(String(o.type))&&o.refund_case===void 0||o.type==="refund_case.paid"&&(!y(o.refund_case)||!y(o.refund_case.refund_payment))||n!==null&&(!y(n)||!u(n,["charge_id","status","amount","fee_total","total_debited","currency","updated_at"])||!v(n,["failure_code"])||n.user_payment!==void 0&&(!y(n.user_payment)||!_(n.user_payment.chain_id)||!u(n.user_payment,["tx_hash"])||!v(n.user_payment,["asset_symbol"])))||o.issuer_fact!==void 0&&(!y(o.issuer_fact)||!u(o.issuer_fact,["operation_type","resource_version","amount","currency","recorded_at","link_status"])||!v(o.issuer_fact,["unlinked_reason"])))return!1;if(o.refund_case!==void 0){let d=o.refund_case;if(!y(d)||!u(d,["case_id","source_operation_type","status","amount","excess_amount","updated_at"])||!v(d,["paid_amount","not_payable_reason"])||d.refund_payment!==void 0&&(!y(d.refund_payment)||!_(d.refund_payment.chain_id)||!u(d.refund_payment,["tx_hash","paid_amount","recorded_by"])))return!1}return!0}function M(e){let t=JSON.parse(e.eventJson);if(!y(t)||t.event_id!==e.eventId||t.event_kind!==e.eventKind)throw new Error("invalid_card_event");if(!ne.includes(e.eventKind)){if(y(t.data)&&k(t.data))throw new Error("invalid_card_event");return{type:"unknown",eventKind:e.eventKind,rawJson:e.eventJson,event:t}}if(Object.keys(t).some(n=>!Le.has(n))||t.envelope_version!==2||!u(t,["event_id","event_kind","environment","program_id","occurred_at"])||!Ue.test(t.event_id)||!Je.test(t.program_id)||t.environment!=="dev"&&t.environment!=="production"||t.origin_connection_id!==void 0&&(!A(t.origin_connection_id)||!Pe.test(t.origin_connection_id))||!(t.connection_sequence===null||_(t.connection_sequence)&&t.connection_sequence>=1)||!y(t.data)||k(t.data))throw new Error("invalid_card_event");if(e.eventKind.startsWith("card.binding.")){if(!A(t.binding_id)||!Be.test(t.binding_id)||!_(t.binding_revision)||t.binding_revision<1)throw new Error("invalid_card_event");let n=t.data,r=e.eventKind;if(r==="card.binding.linked"||r==="card.binding.relinked"){if(!u(n,["external_card_id","binding_id"])||!B(n.card)||!ee(n,["intent_id"])||n.ownership_transfer!==void 0&&typeof n.ownership_transfer!="boolean"||!v(n,["environment","subject_link_id","consent_revision","previous_binding_id"])||n.environment!==void 0&&n.environment!=="dev"&&n.environment!=="production"||n.approved_scopes!==void 0&&(!Array.isArray(n.approved_scopes)||!n.approved_scopes.every(i=>typeof i=="string")))throw new Error("invalid_card_event")}else if(r==="card.binding.revoked"){if(!u(n,["external_card_id","binding_id"])||!B(n.card)||!(A(n.reason_code)||A(n.revocation_source))||!ee(n,["intent_id"])||!v(n,["reason_code","revocation_source","environment"])||n.environment!==void 0&&n.environment!=="dev"&&n.environment!=="production"||n.binding_revision!==void 0&&(!_(n.binding_revision)||n.binding_revision<1)||n.payable_projections_closed!==void 0&&(!_(n.payable_projections_closed)||n.payable_projections_closed<0)||n.route_associations_detached!==void 0&&(!_(n.route_associations_detached)||n.route_associations_detached<0)||n.routes_detached!==void 0&&(!_(n.routes_detached)||n.routes_detached<0))throw new Error("invalid_card_event")}else if(r==="card.binding.route_changed"){if(!u(n,["binding_id"])||!(n.association_status==="associated"||n.association_status==="unassociated")||!v(n,["environment"])||n.environment!==void 0&&n.environment!=="dev"&&n.environment!=="production"||n.binding_revision!==void 0&&(!_(n.binding_revision)||n.binding_revision<1))throw new Error("invalid_card_event")}else if(r==="card.binding.limits_changed"){if(!u(n,["binding_id","per_tx_limit","period_limit","period"])||!Object.hasOwn(n,"expires_at")||!K(n.expires_at)||!v(n,["environment"])||n.environment!==void 0&&n.environment!=="dev"&&n.environment!=="production"||n.binding_revision!==void 0&&(!_(n.binding_revision)||n.binding_revision<1))throw new Error("invalid_card_event")}else if(r==="card.binding.ownership_transferred"&&(!u(n,["previous_binding_id","new_binding_id","external_card_id","transferred_at"])||!B(n.card)))throw new Error("invalid_card_event")}else if(e.eventKind==="card.authorization.updated"){if(t.binding_id!==void 0||t.binding_revision!==void 0||!_(t.connection_sequence)||t.connection_sequence<1||!A(t.origin_connection_id)||!Me(t.data))throw new Error("invalid_card_event")}else{let n=t.data;if(t.binding_id!==void 0||t.binding_revision!==void 0||!_(t.connection_sequence)||t.connection_sequence<1||!A(t.origin_connection_id)||!_(n.authorization_revision)||n.authorization_revision<1||!u(n,["operation_type","resource_version","external_authorization_id","mapping_revision"]))throw new Error("invalid_card_event");if(e.eventKind==="card.charge.finalized"){if(!y(n.final_receipt))throw new Error("invalid_card_event");let r=n.final_receipt;if(!u(r,["receipt_event_id","charge_id","external_authorization_id","mapping_revision","operation_type","resource_version","execution_outcome","terminal_action","finalized_at"])||!Q(r.facts_at_finality))throw new Error("invalid_card_event")}else if(!u(n,["charge_id","final_receipt_event_id"])||!_(n.previous_authorization_revision)||n.previous_authorization_revision<1||!Q(n.facts))throw new Error("invalid_card_event")}return{type:"known",event:t}}var oe=["retry","approved_replay","sandbox_replay","dead_letter_replay"],te=["facto-signature","facto-signature-key-id","facto-event-id","facto-event-kind","facto-delivery-attempt"],$e=["facto-event-timestamp-seconds","facto-event-timestamp"],We="facto-redelivery-reason",Ge=new Set(oe),He=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,re=/^[^\r\n\x00-\x1f\x7f]+$/;function m(e){return{verified:!1,reason:e}}function F(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var ae=new WeakSet;function j(e){return typeof e=="object"&&e!==null&&ae.has(e)}function se(e){let t=new Map,n,r,i=0;for(let[S,N]of e.headers){let C=S.toLowerCase();if(C===We){i+=1,typeof N=="string"&&re.test(N)?r=N.trim():r=void 0;continue}let G=$e.includes(C),ce=te.includes(C);if(!(!G&&!ce)){if(typeof N!="string"||!re.test(N))return m("header_invalid");if(G){if(n!==void 0)return m("header_invalid");n=C,t.set("facto-event-timestamp-seconds",N);continue}if(t.has(C))return m("header_invalid");t.set(C,N)}}if(te.some(S=>!t.has(S))||!t.has("facto-event-timestamp-seconds"))return m("missing_header");let o=t.get("facto-signature"),s=t.get("facto-signature-key-id"),d=t.get("facto-event-id"),c=t.get("facto-event-kind"),g=t.get("facto-event-timestamp-seconds"),I=t.get("facto-delivery-attempt");if(!/^v1=[0-9a-f]{64}$/.test(o)||s.length>255||s.trim()!==s||!He.test(d)||c.length>120||c.trim()!==c||!/^(0|[1-9][0-9]{0,19})$/.test(g)||!Number.isSafeInteger(Number(g))||!/^[1-9][0-9]{0,9}$/.test(I)||Number(I)>2147483647)return m("header_invalid");let f=e.nowSeconds??Date.now()/1e3,T=e.toleranceSeconds??300;if(!Number.isFinite(f)||!Number.isFinite(T)||T<0||Math.abs(f-Number(g))>T)return m("timestamp_out_of_window");let b=e.registry.filter(S=>S.keyId===s);if(b.length!==1)return m("key_not_allowed");let l=b[0],E=Date.parse(l.notBefore)/1e3,w=Date.parse(l.expiresAt)/1e3;if(l.status!=="active"&&l.status!=="overlap"||!Number.isFinite(E)||!Number.isFinite(w)||E>=w||f<E||f>=w||Number(g)<E||Number(g)>=w||!(l.secret instanceof Uint8Array)||l.secret.byteLength===0||!Number.isSafeInteger(l.signerKeyVersion)||l.signerKeyVersion<1)return m("key_not_allowed");let p=ie("sha256").update(e.rawBody).digest("hex"),D=["facto:card:outbound-delivery-signature","v1",d,c,g,p].join(`
|
|
2
|
+
`),V=qe("sha256",l.secret).update(D).digest();if(!je(V,Buffer.from(o.slice(3),"hex")))return m("signature_invalid");let z,h;try{z=new TextDecoder("utf-8",{fatal:!0}).decode(e.rawBody),h=JSON.parse(z)}catch{return m("envelope_mismatch")}if(!F(h)||h.envelope_version!==2||h.event_id!==d||h.event_kind!==c||!F(h.data))return m("envelope_mismatch");let O=e.expectedScope,de=c==="card.charge.finalized"||c==="card.charge.facts_updated"||c==="card.authorization.updated";if(!l.eventKinds.includes(c)||l.connectionId!==O.connectionId||l.environment!==O.environment||l.programId!==O.programId||l.targetRevision!==O.targetRevision||h.environment!==l.environment||h.program_id!==l.programId||de&&h.origin_connection_id===void 0||h.origin_connection_id!==void 0&&h.origin_connection_id!==l.connectionId)return m("scope_mismatch");let $=i===1&&r!==void 0&&Ge.has(r)?r:void 0,W=Object.freeze({verified:!0,scope:Object.freeze({connectionId:l.connectionId,environment:l.environment,programId:l.programId,targetRevision:l.targetRevision}),eventId:d,eventKind:c,bodyDigest:p,eventJson:z,...$!==void 0?{redeliveryReason:$}:{}});return ae.add(W),W}function Ye(e){let t=[...e.registry],n={...e.expectedScope};return r=>se({rawBody:r.rawBody,headers:r.headers,registry:t,expectedScope:n,nowSeconds:r.nowSeconds??e.nowSeconds?.(),toleranceSeconds:r.toleranceSeconds??e.toleranceSeconds})}function q(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(n=>q(n)).join(",")}]`:`{${Object.entries(e).filter(([,n])=>n!==void 0).sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>`${JSON.stringify(n)}:${q(r)}`).join(",")}}`}function Ze(e){if(!j(e))throw new Error("delivery_not_verified");let t=JSON.parse(e.eventJson);if(!F(t)||!F(t.data)||k(t.data))throw new Error("invalid_card_event");return ie("sha256").update(q(t.data),"utf8").digest("hex")}async function Xe(e,t){if(!j(e))throw new Error("delivery_not_verified");let n=M(e),r=n.event.connection_sequence,i=r===void 0&&n.type==="unknown"?null:r;if(!(i===null||typeof i=="number"&&Number.isSafeInteger(i)&&i>0))throw new Error("invalid_connection_sequence");let o=n.type!=="known"?null:"binding_revision"in n.event?{field:"binding_revision",value:n.event.binding_revision}:n.event.event_kind==="card.authorization.updated"?{field:"lifecycle_revision",value:n.event.data.lifecycle_revision}:{field:"authorization_revision",value:n.event.data.authorization_revision};return t.store.withConnection(e.scope,async s=>{let d=await s.getDigest(e.eventId);if(d!==void 0){if(d!==e.bodyDigest)throw new Error("event_id_conflict");return{status:"duplicate_ignored",connectionSequence:i,observedSequenceGap:null}}let c=await s.getObservedMaxSequence();if(c!==null&&(!Number.isSafeInteger(c)||c<1))throw new Error("invalid_observed_max_sequence");let g=i!==null&&c!==null&&i>c+1?{previousMaxSequence:c,currentSequence:i}:null;return await t.handle(n,s,{connectionSequence:i,eventRevision:o}),await s.markProcessed(e.eventId,e.bodyDigest,i),{status:"processed",connectionSequence:i,observedSequenceGap:g}})}function Qe(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason);return}let i=()=>{clearTimeout(o),r(t.reason)},o=setTimeout(()=>{t?.removeEventListener("abort",i),n()},e);t?.addEventListener("abort",i,{once:!0})})}async function en(e,t,n){let{deadlineEpochMs:r,intervalMs:i,maxIntervalMs:o,backoffFactor:s,signal:d}=n;if(!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(s)||i<1||o<i||o>2147483647||s<1||s>10)throw new RangeError("invalid_polling_options");let c=n.nowMs??Date.now,g=n.sleep??Qe;if(r-c()>2147483647)throw new RangeError("invalid_polling_deadline");let I=i;for(;;){if(d?.throwIfAborted(),c()>=r)return{status:"poll_deadline_exceeded"};let f=new AbortController,T=Symbol("poll_deadline_exceeded"),b=()=>f.abort(d?.reason);d?.addEventListener("abort",b,{once:!0});let l=setTimeout(()=>f.abort(T),Math.min(r-c(),2147483647)),E,w=new Promise((D,V)=>{E=()=>V(f.signal.reason),f.signal.addEventListener("abort",E,{once:!0})}),p;try{p=await Promise.race([e.authorizations.lookup(t,{signal:f.signal}),w])}catch(D){if(D===T)return{status:"poll_deadline_exceeded"};throw D}finally{clearTimeout(l),f.signal.removeEventListener("abort",E),d?.removeEventListener("abort",b)}if(d?.throwIfAborted(),c()>=r)return{status:"poll_deadline_exceeded"};if(p.resolution==="resolved")return{status:"resolved",result:p};await g(Math.min(I,r-c()),d),I=Math.min(o,I*s)}}import{createHash as nn}from"node:crypto";function tn(e){let t=[e.connectionId,e.externalAuthorizationId,e.supplierTransactionId,e.clientTransactionId];if(typeof t[0]!="string"||t[0].trim()===""||typeof t[1]!="string"||t[1].trim()===""||t.some(r=>r!==void 0&&typeof r!="string"))throw new TypeError("Connection and authorization identity must be strings");let n=nn("sha256").update("facto.card.authorization-idempotency.v1\0");for(let r of t)r===void 0?n.update("u;"):n.update(`s${Buffer.byteLength(r,"utf8")}:`).update(r);return`card_auth_${n.digest("hex")}`}export{ye as CARD_BINDING_ASSERTION_TYP,ne as CARD_EVENT_KINDS,J as CARD_INTENT_JWKS_PATH,oe as CARD_REDELIVERY_REASONS,H as CardError,H as FactoConnectServerError,a as FactoIntentTokenError,ge as createCardClient,Ye as createDeliveryVerifier,M as decodeDeliveryEvent,tn as deriveAuthorizationIdempotencyKey,Ze as getBusinessPayloadDigest,ue as isCardErrorEnvelope,_e as isCardNestedErrorEnvelope,en as pollAuthorization,Xe as receiveEventDelivery,pe as signBindingAssertion,fe as signCardRequest,he as verifyCardIntentToken,se as verifyEventDelivery,le as withServerRetry};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { build } from 'tsup'
|
|
2
|
+
const common = { removeNodeProtocol: false, external: [/^node:/], target: 'es2022', platform: 'neutral', minify: true, sourcemap: false }
|
|
3
|
+
await build({ ...common, entry: { index: 'src/index.ts', testing: 'src/testing.ts' }, format: ['esm', 'cjs'], clean: true, dts: true })
|
|
4
|
+
await build({ ...common, entry: { 'testing-browser': 'src/testing-browser.ts' }, format: ['esm'], clean: false, dts: true })
|
|
5
|
+
await build({ ...common, entry: { 'cli/index': 'src/connect/cli/index.ts' }, format: ['esm'], clean: false })
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "card-source-build",
|
|
3
|
+
"private": true,
|
|
4
|
+
"type": "module",
|
|
5
|
+
"scripts": {
|
|
6
|
+
"build": "node build.mjs"
|
|
7
|
+
},
|
|
8
|
+
"devDependencies": {
|
|
9
|
+
"@types/node": "^22.0.0",
|
|
10
|
+
"tsup": "^8.5.0",
|
|
11
|
+
"typescript": "^5.9.0"
|
|
12
|
+
},
|
|
13
|
+
"overrides": {
|
|
14
|
+
"rollup": "4.61.1"
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { createCardClient } from '../server/card-client'
|
|
3
|
+
import { simulatorIdentity } from '../testing/card-simulator'
|
|
4
|
+
import { simulatorDeliveryKinds, simulatorDeliveryScenario, type SimulatorDeliveryKind } from '../testing/card-scenarios'
|
|
5
|
+
|
|
6
|
+
/** Send only synthetic events; HTTP status does not establish business processing. */
|
|
7
|
+
export async function sendSimulatorDeliveries(url: URL, names: readonly SimulatorDeliveryKind[], report: (line: string) => void = console.log, replay = false): Promise<boolean> {
|
|
8
|
+
report('The tool reports HTTP responses only; it does not verify the recipient’s business processing results.')
|
|
9
|
+
report(`delivery_verification_config:${JSON.stringify(names.map((name) => simulatorDeliveryScenario(name).config))}`)
|
|
10
|
+
let allPassed = true
|
|
11
|
+
for (const name of names) {
|
|
12
|
+
const vector = simulatorDeliveryScenario(name, Math.floor(Date.now() / 1000) + (replay ? 1 : 0), replay ? 2 : 1)
|
|
13
|
+
let passed = true
|
|
14
|
+
const seen = new Set<string>()
|
|
15
|
+
for (const [index, delivery] of vector.deliveries.entries()) {
|
|
16
|
+
const eventId = delivery.headers.find(([key]) => key === 'facto-event-id')?.[1]
|
|
17
|
+
if (replay && eventId && seen.has(eventId)) continue
|
|
18
|
+
if (eventId) seen.add(eventId)
|
|
19
|
+
const headers = new Headers(delivery.headers.map(([key, value]) => [key, value]))
|
|
20
|
+
headers.set('content-type', 'application/json')
|
|
21
|
+
try {
|
|
22
|
+
const response = await fetch(url, { method: 'POST', headers, body: Buffer.from(delivery.rawBody), redirect: 'error', signal: AbortSignal.timeout(10000) })
|
|
23
|
+
report(`delivery_response:${name}:${index + 1}:${response.status}`)
|
|
24
|
+
if (!response.ok) passed = false
|
|
25
|
+
} catch { report(`delivery_response:${name}:${index + 1}:network_error`); passed = false }
|
|
26
|
+
}
|
|
27
|
+
report(`${passed ? 'vector_passed' : 'vector_failed'}:${name}`)
|
|
28
|
+
if (!passed) allPassed = false
|
|
29
|
+
}
|
|
30
|
+
return allPassed
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Accept a synthetic history request, then model its later delivery through HTTP. */
|
|
34
|
+
export async function replaySimulatorDeliveries(simulatorOrigin: string, callback: URL, name: SimulatorDeliveryKind, report: (line: string) => void = console.log): Promise<boolean> {
|
|
35
|
+
const endpoint = new URL(simulatorOrigin)
|
|
36
|
+
if (endpoint.protocol !== 'http:' || endpoint.hostname !== '127.0.0.1' || endpoint.pathname !== '/' || endpoint.search || endpoint.hash || endpoint.username || endpoint.password) throw new Error('Replay only supports a loopback simulator origin')
|
|
37
|
+
const config = simulatorDeliveryScenario(name).config
|
|
38
|
+
const client = createCardClient({ environment: 'dev', ...simulatorIdentity, connectionId: config.connectionId, apiBaseUrl: endpoint.origin })
|
|
39
|
+
const result = await client.deliveryReplays.create({ selection_id: config.selectionId }, { idempotencyKey: `synthetic-replay-${randomUUID()}` })
|
|
40
|
+
if (result.status !== 'accepted') return false
|
|
41
|
+
report('history_replay_accepted')
|
|
42
|
+
return sendSimulatorDeliveries(callback, [name], report, true)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function parseSimulatorDeliveryKind(value: string): SimulatorDeliveryKind {
|
|
46
|
+
if (!simulatorDeliveryKinds.some((name) => name === value)) throw new Error('Unknown delivery scenario')
|
|
47
|
+
return value as SimulatorDeliveryKind
|
|
48
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { simulatorIdentity, startCardSimulator } from '../testing/card-simulator'
|
|
3
|
+
import { simulatorDeliveryConfig, simulatorDeliveryKinds, type SimulatorDeliveryKind } from '../testing/card-scenarios'
|
|
4
|
+
import { runCardSimulatorVectors } from '../testing/card-simulator-vectors'
|
|
5
|
+
import { parseSimulatorDeliveryKind, replaySimulatorDeliveries, sendSimulatorDeliveries } from './deliveries'
|
|
6
|
+
|
|
7
|
+
async function main(args: string[]): Promise<void> {
|
|
8
|
+
const [command, ...rest] = args
|
|
9
|
+
if (command === 'simulator-config') {
|
|
10
|
+
const port = rest.length === 0 ? 8787 : Number(rest[0])
|
|
11
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535 || rest.length > 1) throw new Error('Usage: facto-card simulator-config [port]')
|
|
12
|
+
console.log('Synthetic local test values only; never use these credentials in any real environment.')
|
|
13
|
+
console.log(JSON.stringify({ environment: 'dev', apiBaseUrl: `http://127.0.0.1:${port}`, ...simulatorIdentity }, null, 2))
|
|
14
|
+
console.log(`delivery_verification_config:${JSON.stringify(simulatorDeliveryKinds.map(simulatorDeliveryConfig))}`)
|
|
15
|
+
return
|
|
16
|
+
}
|
|
17
|
+
if (command === 'simulator') {
|
|
18
|
+
const port = rest.length === 0 ? 8787 : Number(rest[0])
|
|
19
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535 || rest.length > 1) throw new Error('Usage: facto-card simulator [port]')
|
|
20
|
+
const { url } = await startCardSimulator(port)
|
|
21
|
+
console.log(`simulator_listening:${url}`)
|
|
22
|
+
console.log('Synthetic local test values only; never use these credentials in any real environment.')
|
|
23
|
+
console.log(JSON.stringify({ environment: 'dev', apiBaseUrl: url, ...simulatorIdentity }, null, 2))
|
|
24
|
+
console.log(`delivery_verification_config:${JSON.stringify(simulatorDeliveryKinds.map(simulatorDeliveryConfig))}`)
|
|
25
|
+
return
|
|
26
|
+
}
|
|
27
|
+
if (command === 'vectors') {
|
|
28
|
+
if (rest.length !== 1) throw new Error('Usage: facto-card vectors http://127.0.0.1:8787')
|
|
29
|
+
if (!await runCardSimulatorVectors(rest[0]!)) process.exitCode = 1
|
|
30
|
+
return
|
|
31
|
+
}
|
|
32
|
+
if (command === 'deliveries' || command === 'replay') {
|
|
33
|
+
const simulatorOrigin = command === 'replay' ? rest.shift() : undefined
|
|
34
|
+
const target = rest[0]
|
|
35
|
+
const args = rest.slice(1)
|
|
36
|
+
if (!target || (command === 'replay' && !simulatorOrigin)) {
|
|
37
|
+
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]')
|
|
38
|
+
}
|
|
39
|
+
let allowNonLoopback = false
|
|
40
|
+
let selected: SimulatorDeliveryKind | undefined
|
|
41
|
+
for (let i = 0; i < args.length; i++) {
|
|
42
|
+
if (args[i] === '--allow-non-loopback' && !allowNonLoopback) allowNonLoopback = true
|
|
43
|
+
else if (args[i] === '--scenario' && selected === undefined && args[i + 1]) selected = parseSimulatorDeliveryKind(args[++i]!)
|
|
44
|
+
else throw new Error('Usage: facto-card deliveries <callback-url> [--allow-non-loopback] [--scenario <name>]')
|
|
45
|
+
}
|
|
46
|
+
const url = new URL(target)
|
|
47
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.hash) throw new Error('Invalid callback URL')
|
|
48
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname) && !allowNonLoopback) throw new Error('Non-loopback callback requires --allow-non-loopback')
|
|
49
|
+
if (command === 'replay') {
|
|
50
|
+
if (!selected) throw new Error('Replay requires --scenario <name>')
|
|
51
|
+
if (!await replaySimulatorDeliveries(simulatorOrigin!, url, selected)) process.exitCode = 1
|
|
52
|
+
} else if (!await sendSimulatorDeliveries(url, selected ? [selected] : simulatorDeliveryKinds)) process.exitCode = 1
|
|
53
|
+
return
|
|
54
|
+
}
|
|
55
|
+
throw new Error('Usage: facto-card <simulator|simulator-config|vectors|deliveries|replay>')
|
|
56
|
+
}
|
|
57
|
+
main(process.argv.slice(2)).catch((error: unknown) => { console.error(error instanceof Error ? error.message : 'Command failed'); process.exitCode = 1 })
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
import { createPrivateKey, sign as cryptoSign } from 'node:crypto'
|
|
2
|
+
import {
|
|
3
|
+
closed, config, digestPattern, object, text,
|
|
4
|
+
type CardEnvironment,
|
|
5
|
+
} from './card-transport'
|
|
6
|
+
import { CardError } from './errors'
|
|
7
|
+
|
|
8
|
+
/** JOSE `typ` header required for compact-JWS binding proof assertions. */
|
|
9
|
+
export const CARD_BINDING_ASSERTION_TYP = 'facto-card-binding+jwt' as const
|
|
10
|
+
|
|
11
|
+
const PROVIDER_CONNECTION_ID_PATTERN = /^pc_[A-Za-z0-9_-]{16,}$/
|
|
12
|
+
const BINDING_SESSION_ID_PATTERN = /^cbs_[A-Za-z0-9_-]{16,}$/
|
|
13
|
+
const COMPACT_JWS_PATTERN = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/
|
|
14
|
+
const BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/
|
|
15
|
+
const LAST4_PATTERN = /^[0-9]{4}$/
|
|
16
|
+
const MAX_ASSERTION_LIFETIME_SECONDS = 300
|
|
17
|
+
const PROOF_EVIDENCE_MAX_AGE_SECONDS = 600
|
|
18
|
+
const ALLOWED_CONSENTS = ['card.metadata.view', 'card.use_for_facto_payments'] as const
|
|
19
|
+
const ALLOWED_ASSURANCES = ['passkey', 'mfa', 'reauthenticated_session'] as const
|
|
20
|
+
const ALLOWED_SECOND_CHANNELS = ['provider_authenticated_app', 'device_bound_confirmation'] as const
|
|
21
|
+
|
|
22
|
+
const ASSERTION_AUDIENCES: Readonly<Record<CardEnvironment, string>> = {
|
|
23
|
+
dev: 'urn:facto:sandbox:card-program-connect:binding-proof',
|
|
24
|
+
production: 'urn:facto:production:card-program-connect:binding-proof',
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export type BindingUserConsentPurpose = (typeof ALLOWED_CONSENTS)[number]
|
|
28
|
+
export type BindingProofAssurance = (typeof ALLOWED_ASSURANCES)[number]
|
|
29
|
+
export type BindingSecondChannelType = (typeof ALLOWED_SECOND_CHANNELS)[number]
|
|
30
|
+
|
|
31
|
+
export type BindingAssertionProofInput =
|
|
32
|
+
| {
|
|
33
|
+
readonly mode: 'provider_reauthentication'
|
|
34
|
+
readonly authenticatedAtSeconds: number
|
|
35
|
+
readonly assurance: BindingProofAssurance
|
|
36
|
+
}
|
|
37
|
+
| {
|
|
38
|
+
readonly mode: 'provider_second_channel'
|
|
39
|
+
readonly approvedAtSeconds: number
|
|
40
|
+
readonly approvalRef: string
|
|
41
|
+
readonly channelType: BindingSecondChannelType
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface BindingAssertionCardDisplay {
|
|
45
|
+
readonly network?: string
|
|
46
|
+
readonly cardType?: string
|
|
47
|
+
readonly last4?: string
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface BindingAssertionCardInput {
|
|
51
|
+
/** Opaque partner-side card identifier (8 to 512 chars; never a PAN). */
|
|
52
|
+
readonly externalCardId: string
|
|
53
|
+
/** Marks the card the cardholder selected as the default entry card. At most one card may set this to true. */
|
|
54
|
+
readonly isEntryCard?: boolean
|
|
55
|
+
readonly display?: BindingAssertionCardDisplay
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface BindingAssertionEd25519Jwk {
|
|
59
|
+
readonly kty: 'OKP'
|
|
60
|
+
readonly crv: 'Ed25519'
|
|
61
|
+
readonly x: string
|
|
62
|
+
readonly d: string
|
|
63
|
+
readonly kid?: string
|
|
64
|
+
readonly alg?: 'EdDSA' | 'Ed25519'
|
|
65
|
+
readonly use?: 'sig'
|
|
66
|
+
readonly key_ops?: readonly string[]
|
|
67
|
+
readonly ext?: boolean
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export type BindingAssertionSigner =
|
|
71
|
+
| BindingAssertionEd25519Jwk
|
|
72
|
+
| ((signingInput: Uint8Array) => Uint8Array | Promise<Uint8Array>)
|
|
73
|
+
|
|
74
|
+
export interface SignBindingAssertionInput {
|
|
75
|
+
readonly environment: CardEnvironment
|
|
76
|
+
/**
|
|
77
|
+
* Provider connection identifier (`^pc_[A-Za-z0-9_-]{16,}$`) emitted as the
|
|
78
|
+
* wire JWS `connection_id` claim. Distinct from `CardClientOptions.connectionId`
|
|
79
|
+
* (`pconn_...`).
|
|
80
|
+
*/
|
|
81
|
+
readonly providerConnectionId: string
|
|
82
|
+
readonly programId: string
|
|
83
|
+
readonly bindingSessionId: string
|
|
84
|
+
readonly issuer: string
|
|
85
|
+
readonly subject: string
|
|
86
|
+
readonly jti: string
|
|
87
|
+
readonly factoChallenge: string
|
|
88
|
+
readonly sessionRequestDigest: string
|
|
89
|
+
readonly requestedUserConsents: readonly [BindingUserConsentPurpose, ...BindingUserConsentPurpose[]]
|
|
90
|
+
readonly proof: BindingAssertionProofInput
|
|
91
|
+
readonly cards: readonly [BindingAssertionCardInput, ...BindingAssertionCardInput[]]
|
|
92
|
+
readonly signingKeyId: string
|
|
93
|
+
readonly signer: BindingAssertionSigner
|
|
94
|
+
readonly issuedAtSeconds?: number
|
|
95
|
+
readonly notBeforeSeconds?: number
|
|
96
|
+
readonly expiresAtSeconds?: number
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function encodeBase64UrlJson(value: unknown): string {
|
|
100
|
+
return Buffer.from(JSON.stringify(value), 'utf8').toString('base64url')
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function isUnixSeconds(value: unknown): value is number {
|
|
104
|
+
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 1_000_000_000 && value <= 9_999_999_999
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function isBase64Url32Bytes(value: unknown): value is string {
|
|
108
|
+
return typeof value === 'string' && BASE64URL_PATTERN.test(value) && Buffer.from(value, 'base64url').byteLength === 32
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function looksLikePan(value: string): boolean {
|
|
112
|
+
return /^[0-9]{12,19}$/.test(value) || /[0-9]{13}/.test(value)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function buildWireProof(proof: unknown, issuedAtSeconds: number): Record<string, unknown> {
|
|
116
|
+
config(object(proof), 'Binding assertion proof claim is required')
|
|
117
|
+
if (proof.mode === 'provider_reauthentication') {
|
|
118
|
+
config(
|
|
119
|
+
closed(proof, ['mode', 'authenticatedAtSeconds', 'assurance'])
|
|
120
|
+
&& isUnixSeconds(proof.authenticatedAtSeconds)
|
|
121
|
+
&& proof.authenticatedAtSeconds <= issuedAtSeconds
|
|
122
|
+
&& issuedAtSeconds - proof.authenticatedAtSeconds <= PROOF_EVIDENCE_MAX_AGE_SECONDS
|
|
123
|
+
&& ALLOWED_ASSURANCES.includes(proof.assurance as BindingProofAssurance),
|
|
124
|
+
'Reauthentication proof requires valid authenticatedAtSeconds (within 600 seconds before issuedAtSeconds) and assurance',
|
|
125
|
+
)
|
|
126
|
+
return {
|
|
127
|
+
mode: 'provider_reauthentication',
|
|
128
|
+
authenticated_at: proof.authenticatedAtSeconds,
|
|
129
|
+
assurance: proof.assurance,
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
config(
|
|
133
|
+
proof.mode === 'provider_second_channel'
|
|
134
|
+
&& closed(proof, ['mode', 'approvedAtSeconds', 'approvalRef', 'channelType'])
|
|
135
|
+
&& isUnixSeconds(proof.approvedAtSeconds)
|
|
136
|
+
&& proof.approvedAtSeconds <= issuedAtSeconds
|
|
137
|
+
&& issuedAtSeconds - proof.approvedAtSeconds <= PROOF_EVIDENCE_MAX_AGE_SECONDS
|
|
138
|
+
&& text(proof.approvalRef, 16, 255)
|
|
139
|
+
&& ALLOWED_SECOND_CHANNELS.includes(proof.channelType as BindingSecondChannelType),
|
|
140
|
+
'Second-channel proof requires valid approvedAtSeconds (within 600 seconds before issuedAtSeconds), approvalRef (16-255 chars), and channelType',
|
|
141
|
+
)
|
|
142
|
+
return {
|
|
143
|
+
mode: 'provider_second_channel',
|
|
144
|
+
approved_at: proof.approvedAtSeconds,
|
|
145
|
+
approval_ref: proof.approvalRef,
|
|
146
|
+
channel_type: proof.channelType,
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function buildWireCards(cards: unknown): Array<Record<string, unknown>> {
|
|
151
|
+
config(Array.isArray(cards) && cards.length >= 1 && cards.length <= 20, 'Binding assertion requires 1 to 20 asserted cards')
|
|
152
|
+
const seenIds = new Set<string>()
|
|
153
|
+
let entryCardCount = 0
|
|
154
|
+
return cards.map((card) => {
|
|
155
|
+
config(
|
|
156
|
+
closed(card, ['externalCardId'], ['isEntryCard', 'display'])
|
|
157
|
+
&& text(card.externalCardId, 8, 512)
|
|
158
|
+
&& !looksLikePan(card.externalCardId)
|
|
159
|
+
&& (card.isEntryCard === undefined || typeof card.isEntryCard === 'boolean'),
|
|
160
|
+
'Each asserted card requires an opaque externalCardId (8-512 non-PAN chars) and optional boolean isEntryCard',
|
|
161
|
+
)
|
|
162
|
+
config(!seenIds.has(card.externalCardId), 'Asserted cards must have unique externalCardId values')
|
|
163
|
+
seenIds.add(card.externalCardId)
|
|
164
|
+
if (card.isEntryCard === true) {
|
|
165
|
+
entryCardCount += 1
|
|
166
|
+
config(entryCardCount <= 1, 'At most one asserted card may set isEntryCard to true')
|
|
167
|
+
}
|
|
168
|
+
let wireDisplay: Record<string, string> | undefined
|
|
169
|
+
if (card.display !== undefined) {
|
|
170
|
+
config(closed(card.display, [], ['network', 'cardType', 'last4']), 'Asserted card display accepts only network, cardType, and last4')
|
|
171
|
+
const display = card.display as BindingAssertionCardDisplay
|
|
172
|
+
config(
|
|
173
|
+
(display.network === undefined || text(display.network, 1, 32))
|
|
174
|
+
&& (display.cardType === undefined || text(display.cardType, 1, 32))
|
|
175
|
+
&& (display.last4 === undefined || (typeof display.last4 === 'string' && LAST4_PATTERN.test(display.last4))),
|
|
176
|
+
'Asserted card display fields are out of contract bounds',
|
|
177
|
+
)
|
|
178
|
+
const built: Record<string, string> = {}
|
|
179
|
+
if (display.network !== undefined) built.network = display.network
|
|
180
|
+
if (display.cardType !== undefined) built.card_type = display.cardType
|
|
181
|
+
if (display.last4 !== undefined) built.last4 = display.last4
|
|
182
|
+
if (Object.keys(built).length > 0) wireDisplay = built
|
|
183
|
+
}
|
|
184
|
+
return {
|
|
185
|
+
card_ref: card.externalCardId,
|
|
186
|
+
relationship_type: 'owner',
|
|
187
|
+
...(card.isEntryCard === true ? { is_entry_card: true } : {}),
|
|
188
|
+
...(wireDisplay !== undefined ? { display: wireDisplay } : {}),
|
|
189
|
+
}
|
|
190
|
+
})
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async function signBytes(signer: unknown, signingInput: Uint8Array, signingKeyId: string): Promise<Uint8Array> {
|
|
194
|
+
if (typeof signer === 'function') {
|
|
195
|
+
const signature = await (signer as (bytes: Uint8Array) => Uint8Array | Promise<Uint8Array>)(signingInput)
|
|
196
|
+
config(signature instanceof Uint8Array && signature.byteLength === 64, 'Binding assertion signer must return a 64-byte Ed25519 signature')
|
|
197
|
+
return signature
|
|
198
|
+
}
|
|
199
|
+
config(
|
|
200
|
+
closed(signer, ['kty', 'crv', 'x', 'd'], ['kid', 'alg', 'use', 'key_ops', 'ext'])
|
|
201
|
+
&& signer.kty === 'OKP'
|
|
202
|
+
&& signer.crv === 'Ed25519'
|
|
203
|
+
&& (signer.alg === undefined || signer.alg === 'EdDSA' || signer.alg === 'Ed25519')
|
|
204
|
+
&& (signer.use === undefined || signer.use === 'sig')
|
|
205
|
+
&& (signer.key_ops === undefined || (Array.isArray(signer.key_ops) && signer.key_ops.every((op) => typeof op === 'string') && signer.key_ops.includes('sign')))
|
|
206
|
+
&& (signer.ext === undefined || typeof signer.ext === 'boolean')
|
|
207
|
+
&& (signer.kid === undefined || signer.kid === signingKeyId)
|
|
208
|
+
&& isBase64Url32Bytes(signer.x)
|
|
209
|
+
&& isBase64Url32Bytes(signer.d),
|
|
210
|
+
'Binding assertion signer must be a valid Ed25519 private JWK (matching signingKeyId when kid is present) or async signing callback',
|
|
211
|
+
)
|
|
212
|
+
try {
|
|
213
|
+
const key = createPrivateKey({
|
|
214
|
+
key: { kty: 'OKP', crv: 'Ed25519', x: signer.x as string, d: signer.d as string },
|
|
215
|
+
format: 'jwk',
|
|
216
|
+
})
|
|
217
|
+
return new Uint8Array(cryptoSign(null, signingInput, key))
|
|
218
|
+
} catch {
|
|
219
|
+
throw new CardError('FACTO_CONFIG_INVALID', 'Invalid Ed25519 private JWK for binding assertion signing', { retryable: false })
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Build and sign a challenge-bound EdDSA compact-JWS provider proof assertion
|
|
225
|
+
* whose wire claims match the Facto Card binding-session contract.
|
|
226
|
+
*/
|
|
227
|
+
export async function signBindingAssertion(input: SignBindingAssertionInput): Promise<string> {
|
|
228
|
+
config(
|
|
229
|
+
closed(
|
|
230
|
+
input,
|
|
231
|
+
[
|
|
232
|
+
'environment', 'providerConnectionId', 'programId', 'bindingSessionId', 'issuer', 'subject', 'jti',
|
|
233
|
+
'factoChallenge', 'sessionRequestDigest', 'requestedUserConsents', 'proof', 'cards',
|
|
234
|
+
'signingKeyId', 'signer',
|
|
235
|
+
],
|
|
236
|
+
['issuedAtSeconds', 'notBeforeSeconds', 'expiresAtSeconds'],
|
|
237
|
+
),
|
|
238
|
+
'Binding assertion input contains missing or unknown fields',
|
|
239
|
+
)
|
|
240
|
+
config(input.environment === 'dev' || input.environment === 'production', 'environment must be dev or production')
|
|
241
|
+
config(
|
|
242
|
+
typeof input.providerConnectionId === 'string' && PROVIDER_CONNECTION_ID_PATTERN.test(input.providerConnectionId),
|
|
243
|
+
'providerConnectionId must be a pc_ provider connection identifier (not a pconn_ program connection identifier)',
|
|
244
|
+
)
|
|
245
|
+
config(text(input.programId, 1, 255), 'programId must be 1 to 255 characters')
|
|
246
|
+
config(typeof input.bindingSessionId === 'string' && BINDING_SESSION_ID_PATTERN.test(input.bindingSessionId), 'bindingSessionId must be a cbs_ identifier')
|
|
247
|
+
config(text(input.issuer, 1, 512), 'issuer is required')
|
|
248
|
+
config(text(input.subject, 16, 512), 'subject must be a pairwise opaque identifier of 16 to 512 characters')
|
|
249
|
+
config(text(input.jti, 16, 255), 'jti must be 16 to 255 characters')
|
|
250
|
+
config(text(input.factoChallenge, 1, 512), 'factoChallenge is required')
|
|
251
|
+
config(typeof input.sessionRequestDigest === 'string' && digestPattern.test(input.sessionRequestDigest), 'sessionRequestDigest must be a sha256:<hex> digest')
|
|
252
|
+
config(
|
|
253
|
+
text(input.signingKeyId, 1, 255) && input.signingKeyId.trim() === input.signingKeyId && !input.signingKeyId.includes('\0'),
|
|
254
|
+
'signingKeyId must be a non-empty trimmed identifier without NUL bytes',
|
|
255
|
+
)
|
|
256
|
+
const consents = input.requestedUserConsents
|
|
257
|
+
config(
|
|
258
|
+
Array.isArray(consents)
|
|
259
|
+
&& consents.length > 0
|
|
260
|
+
&& new Set(consents).size === consents.length
|
|
261
|
+
&& consents.every((item) => ALLOWED_CONSENTS.includes(item)),
|
|
262
|
+
'requestedUserConsents must be a non-empty unique set of supported consent purposes',
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
const issuedAtSeconds = input.issuedAtSeconds ?? Math.floor(Date.now() / 1000)
|
|
266
|
+
const notBeforeSeconds = input.notBeforeSeconds ?? issuedAtSeconds
|
|
267
|
+
const expiresAtSeconds = input.expiresAtSeconds ?? (issuedAtSeconds + MAX_ASSERTION_LIFETIME_SECONDS)
|
|
268
|
+
config(
|
|
269
|
+
isUnixSeconds(issuedAtSeconds)
|
|
270
|
+
&& isUnixSeconds(notBeforeSeconds)
|
|
271
|
+
&& isUnixSeconds(expiresAtSeconds)
|
|
272
|
+
&& notBeforeSeconds <= issuedAtSeconds
|
|
273
|
+
&& issuedAtSeconds <= expiresAtSeconds
|
|
274
|
+
&& expiresAtSeconds - issuedAtSeconds <= MAX_ASSERTION_LIFETIME_SECONDS,
|
|
275
|
+
'Binding assertion timestamps must satisfy nbf <= iat <= exp with lifetime <= 300 seconds',
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
const wireProof = buildWireProof(input.proof, issuedAtSeconds)
|
|
279
|
+
const wireCards = buildWireCards(input.cards)
|
|
280
|
+
|
|
281
|
+
const headerSegment = encodeBase64UrlJson({
|
|
282
|
+
typ: CARD_BINDING_ASSERTION_TYP,
|
|
283
|
+
alg: 'EdDSA',
|
|
284
|
+
kid: input.signingKeyId,
|
|
285
|
+
})
|
|
286
|
+
const payloadSegment = encodeBase64UrlJson({
|
|
287
|
+
iss: input.issuer,
|
|
288
|
+
aud: ASSERTION_AUDIENCES[input.environment],
|
|
289
|
+
sub: input.subject,
|
|
290
|
+
iat: issuedAtSeconds,
|
|
291
|
+
nbf: notBeforeSeconds,
|
|
292
|
+
exp: expiresAtSeconds,
|
|
293
|
+
jti: input.jti,
|
|
294
|
+
binding_session_id: input.bindingSessionId,
|
|
295
|
+
facto_challenge: input.factoChallenge,
|
|
296
|
+
session_request_digest: input.sessionRequestDigest,
|
|
297
|
+
connection_id: input.providerConnectionId,
|
|
298
|
+
environment: input.environment,
|
|
299
|
+
program_ref: input.programId,
|
|
300
|
+
proof: wireProof,
|
|
301
|
+
cards: wireCards,
|
|
302
|
+
requested_user_consents: [...consents],
|
|
303
|
+
})
|
|
304
|
+
const signingInput = new TextEncoder().encode(`${headerSegment}.${payloadSegment}`)
|
|
305
|
+
const signature = await signBytes(input.signer, signingInput, input.signingKeyId)
|
|
306
|
+
const compactJws = `${headerSegment}.${payloadSegment}.${Buffer.from(signature).toString('base64url')}`
|
|
307
|
+
config(
|
|
308
|
+
compactJws.length >= 128 && compactJws.length <= 16384 && COMPACT_JWS_PATTERN.test(compactJws),
|
|
309
|
+
'Signed binding assertion exceeds compact JWS bounds',
|
|
310
|
+
)
|
|
311
|
+
return compactJws
|
|
312
|
+
}
|