@johnhenry/browsermesh-apps 0.2.0 → 0.4.0
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/README.md +232 -1
- package/package.json +7 -3
- package/src/agent-runtime.mjs +342 -0
- package/src/chunk-replication.mjs +751 -0
- package/src/cloud-storage-backend.mjs +932 -0
- package/src/cloud-storage.mjs +859 -0
- package/src/compat.mjs +98 -0
- package/src/grant-log.mjs +840 -0
- package/src/index.mjs +34 -2
- package/src/key-distribution.mjs +525 -0
- package/src/manifest-sync.mjs +363 -0
- package/src/mesh-agent-swarm.mjs +376 -0
- package/src/mesh-bootstrap.mjs +1131 -12
- package/src/mesh-compute.mjs +397 -0
- package/src/mesh-dht.mjs +182 -0
- package/src/mesh-fetch.mjs +246 -0
- package/src/mesh-hardening.mjs +226 -0
- package/src/mesh-health.mjs +282 -0
- package/src/mesh-keepalive.mjs +353 -0
- package/src/mesh-kv.mjs +673 -0
- package/src/mesh-orchestrator-tools.mjs +251 -0
- package/src/mesh-orchestrator.mjs +343 -0
- package/src/mesh-rpc.mjs +300 -0
- package/src/mesh-service.mjs +403 -0
- package/src/mesh-swarm.mjs +677 -0
- package/src/mesh-timestamp.mjs +265 -0
- package/src/mesh-torrent.mjs +683 -0
- package/src/mesh-verification.mjs +367 -0
- package/src/mesh-websocket.mjs +722 -0
- package/src/observability-bridge.mjs +453 -0
- package/src/orchestrator.mjs +18 -5
- package/src/peer-agent-swarm.mjs +12 -1
- package/src/peer-chat.mjs +230 -61
- package/src/peer-compute.mjs +66 -3
- package/src/peer-escrow.mjs +350 -1
- package/src/peer-files.mjs +362 -168
- package/src/peer-ipfs.mjs +205 -10
- package/src/peer-node.mjs +33 -2
- package/src/peer-routing.mjs +369 -5
- package/src/peer-terminal.mjs +400 -130
- package/src/serverless-executor-andbox.mjs +136 -0
- package/src/serverless-fetch.mjs +70 -0
- package/src/serverless-functions.mjs +67 -0
- package/src/serverless-peer-select.mjs +69 -0
- package/src/serverless-proxy.mjs +127 -0
- package/src/serverless-router.mjs +115 -0
- package/src/serverless-sites.mjs +116 -0
- package/src/serverless-static.mjs +202 -0
- package/src/serverless-wire.mjs +87 -0
- package/src/peer-session.mjs +0 -937
package/src/peer-escrow.mjs
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
|
-
// STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
|
|
3
2
|
* clawser-peer-escrow.js — Hold credits in escrow until consensus confirms delivery.
|
|
4
3
|
*
|
|
5
4
|
* Enables trustless compute marketplace, dispute resolution, and
|
|
6
5
|
* guaranteed payment for services.
|
|
7
6
|
*
|
|
7
|
+
* `EscrowManager` itself is plain and dependency-injected (`{creditLedger,
|
|
8
|
+
* onLog}`), with no `PeerNode`/mesh-transport awareness of its own -- see
|
|
9
|
+
* `createEscrowService()` below (issue #117, `mesh-service.mjs`'s `MeshService`
|
|
10
|
+
* convention) for the wrapper that wires it onto a real `PeerNode`'s
|
|
11
|
+
* `ctx.sendTo()`/`ctx.onIncomingData()`/`ctx.registry.checkAccess()`.
|
|
12
|
+
*
|
|
8
13
|
* Run tests:
|
|
9
14
|
* node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-escrow.test.mjs
|
|
10
15
|
*/
|
|
@@ -571,3 +576,347 @@ export class EscrowManager {
|
|
|
571
576
|
return contract
|
|
572
577
|
}
|
|
573
578
|
}
|
|
579
|
+
|
|
580
|
+
// ---------------------------------------------------------------------------
|
|
581
|
+
// createEscrowService -- MeshService wiring (issue #117)
|
|
582
|
+
// ---------------------------------------------------------------------------
|
|
583
|
+
|
|
584
|
+
/** Default `envelope.type` used to route escrow request/response envelopes. */
|
|
585
|
+
const DEFAULT_ESCROW_ENVELOPE_TYPE = 'escrow'
|
|
586
|
+
/** How long `requestCreate()`/`requestRelease()`/`requestRefund()`/`requestDispute()` wait for a response. Mirrors `mesh-rpc.mjs`'s/`peer-routing.mjs`'s own default. */
|
|
587
|
+
const DEFAULT_ESCROW_REQUEST_TIMEOUT_MS = 10000
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* Build a `MeshService` descriptor (`mesh-service.mjs`) that wires
|
|
591
|
+
* `EscrowManager` onto a real `PeerNode`, so a peer can ask ANOTHER peer's
|
|
592
|
+
* node (the one holding `creditLedger`, e.g. a compute-marketplace hub) to
|
|
593
|
+
* create, release, refund, or dispute an escrow contract.
|
|
594
|
+
*
|
|
595
|
+
* ---------------------------------------------------------------------------
|
|
596
|
+
* AUTHORIZATION MODEL -- read before changing this function. This wraps
|
|
597
|
+
* real credit/payment semantics (`EscrowManager.create()` immediately debits
|
|
598
|
+
* `creditLedger`, `release()`/`refund()`/`expire` immediately credit it) --
|
|
599
|
+
* `EscrowManager` itself has NO caller-identity awareness at all (any code
|
|
600
|
+
* that can call `.release(contractId)` succeeds, full stop), so every
|
|
601
|
+
* security boundary here is added by this wrapper, not inherited.
|
|
602
|
+
*
|
|
603
|
+
* Two entirely separate op classes:
|
|
604
|
+
*
|
|
605
|
+
* 1. LOCAL/ADMIN ops -- `getContract`, `listContracts`, `getStats`,
|
|
606
|
+
* `checkExpired` -- are NEVER exposed over the wire at all: no
|
|
607
|
+
* `ctx.onIncomingData()` dispatch branch answers them, and no
|
|
608
|
+
* `requestX()` client method exists for them either. These are read-only
|
|
609
|
+
* (or, for `checkExpired`, a maintenance sweep an operator/scheduler runs
|
|
610
|
+
* locally) and leak contract/ledger details a remote peer has no
|
|
611
|
+
* inherent right to see (e.g. every contract another peer is party to).
|
|
612
|
+
* Only reachable via `api.getContract()`/`api.listContracts()`/
|
|
613
|
+
* `api.getStats()`/`api.checkExpired()`, i.e. in-process code on the node
|
|
614
|
+
* that owns this service.
|
|
615
|
+
*
|
|
616
|
+
* 2. PEER-INITIATED ops -- `create`, `release`, `refund`, `dispute` -- DO
|
|
617
|
+
* arrive over the wire (`ctx.onIncomingData(envelopeType, ...)`) and are
|
|
618
|
+
* real value-transfer/state-transition operations, each individually
|
|
619
|
+
* authorized:
|
|
620
|
+
*
|
|
621
|
+
* - `create`: gated by `ctx.registry.checkAccess(fromPubKey, 'escrow', 'create')`
|
|
622
|
+
* -- a coarse, admin-granted scope (`registry.grantCapabilities(peerPubKey,
|
|
623
|
+
* ['escrow:create'])`) deciding "is this peer allowed to open escrow
|
|
624
|
+
* contracts against MY credit ledger at all". `PeerRegistry`/`MeshACL`
|
|
625
|
+
* default-deny any non-owner peer with no roster entry (see
|
|
626
|
+
* `MeshACL.check()`), so a peer gets NOTHING here until the node
|
|
627
|
+
* operator explicitly opts them in -- this is a deliberate, real gate,
|
|
628
|
+
* not a formality. On top of that ACL gate, the payer identity itself
|
|
629
|
+
* is NEVER taken from the wire payload: the host always uses
|
|
630
|
+
* `payerPodId = fromPubKey` (the cryptographically-authenticated sender
|
|
631
|
+
* of the envelope), so a remote peer can only ever fund a contract with
|
|
632
|
+
* THEIR OWN balance, never spoof another pod as the payer and drain
|
|
633
|
+
* someone else's credits. Only `payeePodId`/`amount`/`description`/
|
|
634
|
+
* `conditions`/`timeoutMs` are taken from the payload.
|
|
635
|
+
*
|
|
636
|
+
* - `release`/`refund`/`dispute`: gated by
|
|
637
|
+
* `ctx.registry.checkAccess(fromPubKey, 'escrow:<contractId>', '<op>')`
|
|
638
|
+
* -- the SAME 3-segment `namespace:resource:action` scope grammar
|
|
639
|
+
* `mesh-relay-host.mjs` already established
|
|
640
|
+
* (`mesh-relay:<service>:connect`), specialized per-CONTRACT rather
|
|
641
|
+
* than per-service. These scopes are never manually granted by an
|
|
642
|
+
* operator (a contract id doesn't exist until `create()` runs, so
|
|
643
|
+
* there is nothing to pre-grant) -- instead, `create()` ITSELF
|
|
644
|
+
* auto-grants `escrow:<contractId>:release`, `escrow:<contractId>:refund`,
|
|
645
|
+
* and `escrow:<contractId>:dispute` to BOTH `contract.payer` and
|
|
646
|
+
* `contract.payee` the moment the contract is created (mirrors
|
|
647
|
+
* `cloud-storage.mjs`'s own "grant() also drives visibility, not just
|
|
648
|
+
* the raw mutation" precedent -- see that file's design-decision #4).
|
|
649
|
+
* Nobody else -- a peer who is neither this contract's payer nor payee
|
|
650
|
+
* -- ever receives this scope, so `checkAccess()`'s existing
|
|
651
|
+
* default-deny does the real work: an unrelated peer's `release`/
|
|
652
|
+
* `refund`/`dispute` request against a contract THEY don't own is
|
|
653
|
+
* denied by the exact same mechanism `mesh-relay-host.mjs` uses for
|
|
654
|
+
* "who can relay to this service", not a bespoke ownership `if` this
|
|
655
|
+
* file invents separately. This auto-grant runs for EVERY `create()`
|
|
656
|
+
* call, wire-triggered or local/admin (`api.create()`), so a
|
|
657
|
+
* locally-created contract's real payer/payee can still act on it
|
|
658
|
+
* remotely later.
|
|
659
|
+
*
|
|
660
|
+
* `api.create`/`api.release`/`api.refund`/`api.dispute` (the LOCAL, in-process
|
|
661
|
+
* surface) are intentionally UNRESTRICTED -- exactly like
|
|
662
|
+
* `mesh-relay-host.mjs`'s `exposeService()`/`hideService()` have no ACL
|
|
663
|
+
* check of their own (only the inbound wire path does): local code already
|
|
664
|
+
* running inside this node's own process is trusted the same way any other
|
|
665
|
+
* direct method call on an in-process object is. The wire protocol is what
|
|
666
|
+
* adds a security boundary for a REMOTE, cryptographically-distinct caller;
|
|
667
|
+
* it does not additionally restrict local callers.
|
|
668
|
+
*
|
|
669
|
+
* ---------------------------------------------------------------------------
|
|
670
|
+
* WIRE PROTOCOL -- one `envelope.type` (`escrow` by default) carries both
|
|
671
|
+
* directions, correlated by `requestId` (modeled directly on
|
|
672
|
+
* `peer-routing.mjs`'s `requestProxy`/`mesh-rpc.mjs`'s request/response
|
|
673
|
+
* pattern):
|
|
674
|
+
*
|
|
675
|
+
* Request (client -> host): `{ type, kind: 'request', requestId, op, payload }`
|
|
676
|
+
* Response (host -> client): `{ type, kind: 'response', requestId, ok, result }`
|
|
677
|
+
* or `{ type, kind: 'response', requestId, ok: false, error }`
|
|
678
|
+
*
|
|
679
|
+
* `op` is one of `'create' | 'release' | 'refund' | 'dispute'`. `payload`
|
|
680
|
+
* shapes:
|
|
681
|
+
* - `create`: `{ payeePodId, amount, description?, conditions?, timeoutMs? }`
|
|
682
|
+
* (NOT `payerPodId` -- see AUTHORIZATION MODEL above, always `fromPubKey`).
|
|
683
|
+
* - `release`: `{ contractId, proof? }`
|
|
684
|
+
* - `refund`: `{ contractId, reason? }`
|
|
685
|
+
* - `dispute`: `{ contractId, evidence? }`
|
|
686
|
+
*
|
|
687
|
+
* Any node can act as BOTH host (answering inbound requests against its own
|
|
688
|
+
* `creditLedger`) and client (`requestCreate`/`requestRelease`/
|
|
689
|
+
* `requestRefund`/`requestDispute`, sending requests to another peer's
|
|
690
|
+
* escrow service) -- there is no separate "client-only" descriptor, mirroring
|
|
691
|
+
* `peer-routing.mjs`'s single combined `createMeshRoutingService()`.
|
|
692
|
+
*
|
|
693
|
+
* ---------------------------------------------------------------------------
|
|
694
|
+
* EVENTS (`ctx.emit()`, see `mesh-service.mjs`'s "Observability events"
|
|
695
|
+
* section) -- `EscrowManager`'s own pre-existing `on`/`off` surface
|
|
696
|
+
* (`'created' | 'released' | 'refunded' | 'disputed' | 'expired'`) is bridged
|
|
697
|
+
* through verbatim, prefixed `escrow:`, payload always the plain-object
|
|
698
|
+
* `EscrowContract.toJSON()` (or, for `disputed`, `{ contract, disputeId,
|
|
699
|
+
* evidence }` with `contract` also serialized) -- never the live class
|
|
700
|
+
* instance, so a subscriber can never mutate manager-internal state via the
|
|
701
|
+
* event payload:
|
|
702
|
+
*
|
|
703
|
+
* - `escrow:created` -- a new contract was funded (`create()`, either origin).
|
|
704
|
+
* - `escrow:released` -- funds released to the payee.
|
|
705
|
+
* - `escrow:refunded` -- funds refunded to the payer.
|
|
706
|
+
* - `escrow:disputed` -- `{ contract, disputeId, evidence }`.
|
|
707
|
+
* - `escrow:expired` -- a contract auto-refunded by `checkExpired()`.
|
|
708
|
+
*
|
|
709
|
+
* These fire for EVERY `EscrowManager` mutation regardless of whether it was
|
|
710
|
+
* triggered locally (`api.create()`/etc.) or over the wire -- `EscrowManager`
|
|
711
|
+
* itself has no notion of "origin", and this wrapper doesn't add one to the
|
|
712
|
+
* event payload either, matching every other bridged-event service in this
|
|
713
|
+
* family (e.g. `peer-routing.mjs`'s `mesh-routing:*` events).
|
|
714
|
+
*
|
|
715
|
+
* No browser-only imports at module level.
|
|
716
|
+
*/
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* @param {object} opts
|
|
720
|
+
* @param {object} opts.creditLedger - Must have charge(), credit(), getBalance() -- forwarded to `new EscrowManager()`.
|
|
721
|
+
* @param {Function} [opts.onLog] - Logging callback (level, msg) -- forwarded to `EscrowManager`'s own `onLog`, PLUS this wrapper's own wire-level logging (send/handling failures, denied requests).
|
|
722
|
+
* @param {string} [opts.envelopeType='escrow'] - `envelope.type` used for request/response traffic.
|
|
723
|
+
* @param {number} [opts.requestTimeoutMs=10000] - How long `requestCreate()`/`requestRelease()`/`requestRefund()`/`requestDispute()` wait for a response.
|
|
724
|
+
* @returns {import('./mesh-service.mjs').MeshService}
|
|
725
|
+
*/
|
|
726
|
+
export function createEscrowService(opts = {}) {
|
|
727
|
+
const {
|
|
728
|
+
creditLedger,
|
|
729
|
+
onLog,
|
|
730
|
+
envelopeType = DEFAULT_ESCROW_ENVELOPE_TYPE,
|
|
731
|
+
requestTimeoutMs = DEFAULT_ESCROW_REQUEST_TIMEOUT_MS,
|
|
732
|
+
} = opts
|
|
733
|
+
const log = onLog || (() => {})
|
|
734
|
+
|
|
735
|
+
return {
|
|
736
|
+
name: 'escrow',
|
|
737
|
+
|
|
738
|
+
attach(peerNode, ctx) {
|
|
739
|
+
const manager = new EscrowManager({
|
|
740
|
+
creditLedger,
|
|
741
|
+
onLog: (level, msg) => log('escrow:manager-log', { level, message: msg }),
|
|
742
|
+
})
|
|
743
|
+
|
|
744
|
+
// -- Bridge EscrowManager's own on()/off() events through ctx.emit() --
|
|
745
|
+
// See module doc comment's "EVENTS" section. Contract payloads are
|
|
746
|
+
// always serialized via toJSON() -- never the live class instance.
|
|
747
|
+
const serializeContract = (contract) => (contract && typeof contract.toJSON === 'function' ? contract.toJSON() : contract)
|
|
748
|
+
const onCreated = (contract) => ctx.emit('escrow:created', serializeContract(contract))
|
|
749
|
+
const onReleased = (contract) => ctx.emit('escrow:released', serializeContract(contract))
|
|
750
|
+
const onRefunded = (contract) => ctx.emit('escrow:refunded', serializeContract(contract))
|
|
751
|
+
const onDisputed = ({ contract, disputeId, evidence }) => ctx.emit('escrow:disputed', { contract: serializeContract(contract), disputeId, evidence })
|
|
752
|
+
const onExpired = (contract) => ctx.emit('escrow:expired', serializeContract(contract))
|
|
753
|
+
manager.on('created', onCreated)
|
|
754
|
+
manager.on('released', onReleased)
|
|
755
|
+
manager.on('refunded', onRefunded)
|
|
756
|
+
manager.on('disputed', onDisputed)
|
|
757
|
+
manager.on('expired', onExpired)
|
|
758
|
+
|
|
759
|
+
// -- Auto-grant per-contract release/refund/dispute scopes to the
|
|
760
|
+
// contract's real payer/payee -- see module doc comment's
|
|
761
|
+
// AUTHORIZATION MODEL section (point 2). Runs for every create(),
|
|
762
|
+
// regardless of origin.
|
|
763
|
+
function grantContractAccess(contract) {
|
|
764
|
+
if (!ctx.registry || typeof ctx.registry.grantCapabilities !== 'function') return
|
|
765
|
+
const scopes = [
|
|
766
|
+
`escrow:${contract.id}:release`,
|
|
767
|
+
`escrow:${contract.id}:refund`,
|
|
768
|
+
`escrow:${contract.id}:dispute`,
|
|
769
|
+
]
|
|
770
|
+
ctx.registry.grantCapabilities(contract.payer, scopes)
|
|
771
|
+
if (contract.payee !== contract.payer) {
|
|
772
|
+
ctx.registry.grantCapabilities(contract.payee, scopes)
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
function doCreate(createOpts) {
|
|
777
|
+
const contract = manager.create(createOpts)
|
|
778
|
+
grantContractAccess(contract)
|
|
779
|
+
return contract
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
// -- Local/admin api surface -- unrestricted, see module doc comment. --
|
|
783
|
+
const api = {
|
|
784
|
+
create: (createOpts) => doCreate(createOpts),
|
|
785
|
+
release: (contractId, proof) => manager.release(contractId, proof),
|
|
786
|
+
refund: (contractId, reason) => manager.refund(contractId, reason),
|
|
787
|
+
dispute: (contractId, evidence) => manager.dispute(contractId, evidence),
|
|
788
|
+
checkExpired: (now) => manager.checkExpired(now),
|
|
789
|
+
getContract: (id) => manager.getContract(id),
|
|
790
|
+
listContracts: (filter) => manager.listContracts(filter),
|
|
791
|
+
getStats: () => manager.getStats(),
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
// -----------------------------------------------------------------
|
|
795
|
+
// Host side -- answer inbound peer requests. See module doc comment's
|
|
796
|
+
// AUTHORIZATION MODEL / WIRE PROTOCOL sections.
|
|
797
|
+
// -----------------------------------------------------------------
|
|
798
|
+
async function handleRequest(fromPubKey, msg) {
|
|
799
|
+
const { requestId, op, payload } = msg
|
|
800
|
+
let result
|
|
801
|
+
let error
|
|
802
|
+
try {
|
|
803
|
+
if (op === 'create') {
|
|
804
|
+
const { allowed } = ctx.registry.checkAccess(fromPubKey, 'escrow', 'create')
|
|
805
|
+
if (!allowed) throw new Error('access denied')
|
|
806
|
+
const contract = doCreate({
|
|
807
|
+
payerPodId: fromPubKey,
|
|
808
|
+
payeePodId: payload?.payeePodId,
|
|
809
|
+
amount: payload?.amount,
|
|
810
|
+
description: payload?.description,
|
|
811
|
+
conditions: payload?.conditions,
|
|
812
|
+
timeoutMs: payload?.timeoutMs,
|
|
813
|
+
})
|
|
814
|
+
result = contract.toJSON()
|
|
815
|
+
} else if (op === 'release' || op === 'refund' || op === 'dispute') {
|
|
816
|
+
const contractId = payload?.contractId
|
|
817
|
+
if (!contractId || typeof contractId !== 'string') {
|
|
818
|
+
throw new Error('contractId is required')
|
|
819
|
+
}
|
|
820
|
+
const { allowed } = ctx.registry.checkAccess(fromPubKey, `escrow:${contractId}`, op)
|
|
821
|
+
if (!allowed) throw new Error('access denied')
|
|
822
|
+
if (op === 'release') result = manager.release(contractId, payload?.proof)
|
|
823
|
+
else if (op === 'refund') result = manager.refund(contractId, payload?.reason)
|
|
824
|
+
else result = manager.dispute(contractId, payload?.evidence)
|
|
825
|
+
} else {
|
|
826
|
+
throw new Error(`unknown op: ${op}`)
|
|
827
|
+
}
|
|
828
|
+
} catch (err) {
|
|
829
|
+
error = err?.message || String(err)
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
if (error === 'access denied') {
|
|
833
|
+
log('escrow:request-denied', { fromPubKey, op, requestId })
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
try {
|
|
837
|
+
await ctx.sendTo(fromPubKey, envelopeType, {
|
|
838
|
+
kind: 'response', requestId, ok: !error, result, error,
|
|
839
|
+
})
|
|
840
|
+
} catch (err) {
|
|
841
|
+
log('escrow:response-send-failed', { to: fromPubKey, requestId, error: err?.message || String(err) })
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
// -----------------------------------------------------------------
|
|
846
|
+
// Client side -- send requests to another peer's escrow service.
|
|
847
|
+
// -----------------------------------------------------------------
|
|
848
|
+
/** @type {Map<string, {resolve: Function, reject: Function, timer: ReturnType<typeof setTimeout>}>} */
|
|
849
|
+
const pendingRequests = new Map()
|
|
850
|
+
let reqSeq = 0
|
|
851
|
+
const nextRequestId = () => `${peerNode.podId}:${Date.now()}:${++reqSeq}`
|
|
852
|
+
|
|
853
|
+
async function sendRequest(targetPubKey, op, payload) {
|
|
854
|
+
const requestId = nextRequestId()
|
|
855
|
+
const promise = new Promise((resolve, reject) => {
|
|
856
|
+
const timer = setTimeout(() => {
|
|
857
|
+
pendingRequests.delete(requestId)
|
|
858
|
+
reject(new Error(`escrow: ${op} request to ${targetPubKey} timed out after ${requestTimeoutMs}ms`))
|
|
859
|
+
}, requestTimeoutMs)
|
|
860
|
+
pendingRequests.set(requestId, { resolve, reject, timer })
|
|
861
|
+
})
|
|
862
|
+
|
|
863
|
+
try {
|
|
864
|
+
await ctx.sendTo(targetPubKey, envelopeType, { kind: 'request', requestId, op, payload })
|
|
865
|
+
} catch (err) {
|
|
866
|
+
const pending = pendingRequests.get(requestId)
|
|
867
|
+
if (pending) {
|
|
868
|
+
clearTimeout(pending.timer)
|
|
869
|
+
pendingRequests.delete(requestId)
|
|
870
|
+
}
|
|
871
|
+
throw err
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
return promise
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
api.requestCreate = (targetPubKey, { payeePodId, amount, description, conditions, timeoutMs } = {}) =>
|
|
878
|
+
sendRequest(targetPubKey, 'create', { payeePodId, amount, description, conditions, timeoutMs })
|
|
879
|
+
api.requestRelease = (targetPubKey, contractId, proof) =>
|
|
880
|
+
sendRequest(targetPubKey, 'release', { contractId, proof })
|
|
881
|
+
api.requestRefund = (targetPubKey, contractId, reason) =>
|
|
882
|
+
sendRequest(targetPubKey, 'refund', { contractId, reason })
|
|
883
|
+
api.requestDispute = (targetPubKey, contractId, evidence) =>
|
|
884
|
+
sendRequest(targetPubKey, 'dispute', { contractId, evidence })
|
|
885
|
+
|
|
886
|
+
const unsubscribe = ctx.onIncomingData(envelopeType, (fromPubKey, msg) => {
|
|
887
|
+
if (!msg || typeof msg.kind !== 'string') return
|
|
888
|
+
if (msg.kind === 'request') {
|
|
889
|
+
handleRequest(fromPubKey, msg).catch((err) => {
|
|
890
|
+
log('escrow:request-handling-failed', { from: fromPubKey, requestId: msg.requestId, error: err?.message || String(err) })
|
|
891
|
+
})
|
|
892
|
+
} else if (msg.kind === 'response') {
|
|
893
|
+
const pending = pendingRequests.get(msg.requestId)
|
|
894
|
+
if (!pending) return // no longer waiting (already timed out, or not ours) -- ignore
|
|
895
|
+
pendingRequests.delete(msg.requestId)
|
|
896
|
+
clearTimeout(pending.timer)
|
|
897
|
+
if (msg.ok) pending.resolve(msg.result)
|
|
898
|
+
else pending.reject(new Error(msg.error || 'escrow request failed'))
|
|
899
|
+
}
|
|
900
|
+
})
|
|
901
|
+
|
|
902
|
+
return {
|
|
903
|
+
api,
|
|
904
|
+
teardown() {
|
|
905
|
+
manager.off('created', onCreated)
|
|
906
|
+
manager.off('released', onReleased)
|
|
907
|
+
manager.off('refunded', onRefunded)
|
|
908
|
+
manager.off('disputed', onDisputed)
|
|
909
|
+
manager.off('expired', onExpired)
|
|
910
|
+
unsubscribe()
|
|
911
|
+
for (const pending of pendingRequests.values()) {
|
|
912
|
+
clearTimeout(pending.timer)
|
|
913
|
+
pending.reject(new Error('escrow: service torn down while a request was still in flight'))
|
|
914
|
+
}
|
|
915
|
+
pendingRequests.clear()
|
|
916
|
+
},
|
|
917
|
+
}
|
|
918
|
+
},
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
export { DEFAULT_ESCROW_ENVELOPE_TYPE, DEFAULT_ESCROW_REQUEST_TIMEOUT_MS }
|