@bsv/sdk 2.1.1 → 2.1.3
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/dist/cjs/package.json +1 -1
- package/dist/cjs/src/auth/Peer.js +21 -18
- package/dist/cjs/src/auth/Peer.js.map +1 -1
- package/dist/cjs/src/auth/SessionManager.js.map +1 -1
- package/dist/cjs/src/auth/clients/AuthFetch.js +4 -1
- package/dist/cjs/src/auth/clients/AuthFetch.js.map +1 -1
- package/dist/cjs/src/identity/ContactsManager.js +44 -6
- package/dist/cjs/src/identity/ContactsManager.js.map +1 -1
- package/dist/cjs/src/identity/IdentityClient.js +106 -37
- package/dist/cjs/src/identity/IdentityClient.js.map +1 -1
- package/dist/cjs/src/overlay-tools/LookupResolver.js +180 -82
- package/dist/cjs/src/overlay-tools/LookupResolver.js.map +1 -1
- package/dist/cjs/src/primitives/Hash.js +173 -50
- package/dist/cjs/src/primitives/Hash.js.map +1 -1
- package/dist/cjs/src/primitives/SymmetricKey.js +123 -1
- package/dist/cjs/src/primitives/SymmetricKey.js.map +1 -1
- package/dist/cjs/src/transaction/MerklePath.js +1 -1
- package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -1
- package/dist/esm/src/auth/Peer.js +28 -18
- package/dist/esm/src/auth/Peer.js.map +1 -1
- package/dist/esm/src/auth/SessionManager.js.map +1 -1
- package/dist/esm/src/auth/clients/AuthFetch.js +4 -1
- package/dist/esm/src/auth/clients/AuthFetch.js.map +1 -1
- package/dist/esm/src/identity/ContactsManager.js +44 -6
- package/dist/esm/src/identity/ContactsManager.js.map +1 -1
- package/dist/esm/src/identity/IdentityClient.js +106 -37
- package/dist/esm/src/identity/IdentityClient.js.map +1 -1
- package/dist/esm/src/overlay-tools/LookupResolver.js +180 -82
- package/dist/esm/src/overlay-tools/LookupResolver.js.map +1 -1
- package/dist/esm/src/primitives/Hash.js +177 -50
- package/dist/esm/src/primitives/Hash.js.map +1 -1
- package/dist/esm/src/primitives/SymmetricKey.js +123 -1
- package/dist/esm/src/primitives/SymmetricKey.js.map +1 -1
- package/dist/esm/src/transaction/MerklePath.js +1 -1
- package/dist/esm/tsconfig.esm.tsbuildinfo +1 -1
- package/dist/types/src/auth/Peer.d.ts +3 -3
- package/dist/types/src/auth/Peer.d.ts.map +1 -1
- package/dist/types/src/auth/SessionManager.d.ts +21 -0
- package/dist/types/src/auth/SessionManager.d.ts.map +1 -1
- package/dist/types/src/auth/clients/AuthFetch.d.ts +2 -2
- package/dist/types/src/auth/clients/AuthFetch.d.ts.map +1 -1
- package/dist/types/src/identity/ContactsManager.d.ts +13 -2
- package/dist/types/src/identity/ContactsManager.d.ts.map +1 -1
- package/dist/types/src/identity/IdentityClient.d.ts +50 -24
- package/dist/types/src/identity/IdentityClient.d.ts.map +1 -1
- package/dist/types/src/overlay-tools/LookupResolver.d.ts +15 -1
- package/dist/types/src/overlay-tools/LookupResolver.d.ts.map +1 -1
- package/dist/types/src/primitives/Hash.d.ts +21 -16
- package/dist/types/src/primitives/Hash.d.ts.map +1 -1
- package/dist/types/src/primitives/SymmetricKey.d.ts.map +1 -1
- package/dist/types/src/wallet/Wallet.interfaces.d.ts +16 -1
- package/dist/types/src/wallet/Wallet.interfaces.d.ts.map +1 -1
- package/dist/types/src/wallet/WalletClient.d.ts +1 -1
- package/dist/types/src/wallet/WalletClient.d.ts.map +1 -1
- package/dist/types/src/wallet/substrates/window.CWI.d.ts +1 -1
- package/dist/types/src/wallet/substrates/window.CWI.d.ts.map +1 -1
- package/dist/types/tsconfig.types.tsbuildinfo +1 -1
- package/dist/umd/bundle.js +4 -4
- package/package.json +1 -1
- package/src/auth/Peer.ts +30 -20
- package/src/auth/SessionManager.ts +22 -0
- package/src/auth/__tests/Peer.test.ts +47 -1
- package/src/auth/clients/AuthFetch.ts +6 -3
- package/src/identity/ContactsManager.ts +47 -6
- package/src/identity/IdentityClient.ts +137 -53
- package/src/identity/__tests/IdentityClient.additional.test.ts +150 -1
- package/src/identity/__tests/IdentityClient.test.ts +4 -4
- package/src/overlay-tools/LookupResolver.ts +191 -77
- package/src/overlay-tools/__tests/LookupResolver.additional.test.ts +90 -0
- package/src/primitives/Hash.ts +232 -96
- package/src/primitives/SymmetricKey.ts +145 -1
- package/src/primitives/__tests/Hash.additional.test.ts +65 -0
- package/src/primitives/__tests/Hash.test.ts +6 -1
- package/src/script/__tests/Spend.test.ts +45 -4
- package/src/transaction/MerklePath.ts +1 -1
- package/src/transaction/__tests/Transaction.test.ts +17 -0
- package/src/wallet/Wallet.interfaces.ts +16 -1
- package/src/wallet/WalletClient.ts +1 -1
- package/src/wallet/substrates/window.CWI.ts +1 -1
package/package.json
CHANGED
package/src/auth/Peer.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { SessionManager } from './SessionManager.js'
|
|
1
|
+
import { SessionManager, AsyncSessionManager } from './SessionManager.js'
|
|
2
2
|
import {
|
|
3
3
|
createNonce,
|
|
4
4
|
verifyNonce,
|
|
@@ -28,6 +28,13 @@ const BufferCtor =
|
|
|
28
28
|
* This version supports multiple concurrent sessions per peer identityKey.
|
|
29
29
|
*/
|
|
30
30
|
export class Peer {
|
|
31
|
+
// Declared as the synchronous {@link SessionManager} for back-compat with
|
|
32
|
+
// pre-existing consumers that read `peer.sessionManager.getSession(...)`
|
|
33
|
+
// and friends as synchronous calls. The constructor also accepts an
|
|
34
|
+
// {@link AsyncSessionManager}; in that case the runtime value's methods
|
|
35
|
+
// return Promises. Peer always awaits internal calls so both work, but
|
|
36
|
+
// external code that reaches in directly should match the implementation
|
|
37
|
+
// it injected. See `AsyncSessionManager` for the opt-in async contract.
|
|
31
38
|
public sessionManager: SessionManager
|
|
32
39
|
private readonly transport: Transport
|
|
33
40
|
private readonly wallet: WalletInterface
|
|
@@ -97,7 +104,7 @@ export class Peer {
|
|
|
97
104
|
* @param {WalletInterface} wallet - The wallet instance used for cryptographic operations.
|
|
98
105
|
* @param {Transport} transport - The transport mechanism used for sending and receiving messages.
|
|
99
106
|
* @param {RequestedCertificateSet} [certificatesToRequest] - Optional set of certificates to request from a peer during the initial handshake.
|
|
100
|
-
* @param {SessionManager} [sessionManager] - Optional
|
|
107
|
+
* @param {SessionManager | AsyncSessionManager} [sessionManager] - Optional session store. Pass an {@link AsyncSessionManager} for shared/durable storage in load-balanced deployments; otherwise the default in-process {@link SessionManager} is used.
|
|
101
108
|
* @param {boolean} [autoPersistLastSession] - Whether to auto-persist the session with the last-interacted-with peer. Defaults to true.
|
|
102
109
|
* @param {OriginatorDomainNameStringUnder250Bytes} [originator] - Optional originator domain name.
|
|
103
110
|
*/
|
|
@@ -105,7 +112,7 @@ export class Peer {
|
|
|
105
112
|
wallet: WalletInterface,
|
|
106
113
|
transport: Transport,
|
|
107
114
|
certificatesToRequest?: RequestedCertificateSet,
|
|
108
|
-
sessionManager?: SessionManager,
|
|
115
|
+
sessionManager?: SessionManager | AsyncSessionManager,
|
|
109
116
|
autoPersistLastSession?: boolean,
|
|
110
117
|
originator?: OriginatorDomainNameStringUnder250Bytes
|
|
111
118
|
) {
|
|
@@ -117,8 +124,11 @@ export class Peer {
|
|
|
117
124
|
types: {}
|
|
118
125
|
}
|
|
119
126
|
this.ready = this.transport.onData(this.handleIncomingMessage.bind(this)) // NOSONAR(typescript:S7059): listener must register synchronously — see ready field comment
|
|
127
|
+
// Cast keeps the public field typed as the synchronous `SessionManager`
|
|
128
|
+
// for back-compat. When an `AsyncSessionManager` is injected, the actual
|
|
129
|
+
// runtime methods return Promises — Peer awaits them internally below.
|
|
120
130
|
this.sessionManager =
|
|
121
|
-
sessionManager ?? new SessionManager()
|
|
131
|
+
(sessionManager ?? new SessionManager()) as SessionManager
|
|
122
132
|
if (autoPersistLastSession === false) {
|
|
123
133
|
this.autoPersistLastSession = false
|
|
124
134
|
} else {
|
|
@@ -178,7 +188,7 @@ export class Peer {
|
|
|
178
188
|
}
|
|
179
189
|
|
|
180
190
|
peerSession.lastUpdate = Date.now()
|
|
181
|
-
this.sessionManager.updateSession(peerSession)
|
|
191
|
+
await this.sessionManager.updateSession(peerSession)
|
|
182
192
|
|
|
183
193
|
try {
|
|
184
194
|
await this.transport.send(generalMessage)
|
|
@@ -233,7 +243,7 @@ export class Peer {
|
|
|
233
243
|
|
|
234
244
|
// Update last-used timestamp
|
|
235
245
|
peerSession.lastUpdate = Date.now()
|
|
236
|
-
this.sessionManager.updateSession(peerSession)
|
|
246
|
+
await this.sessionManager.updateSession(peerSession)
|
|
237
247
|
|
|
238
248
|
try {
|
|
239
249
|
await this.transport.send(certRequestMessage)
|
|
@@ -262,7 +272,7 @@ export class Peer {
|
|
|
262
272
|
|
|
263
273
|
let peerSession: PeerSession | undefined
|
|
264
274
|
if (typeof identityKey === 'string') {
|
|
265
|
-
peerSession = this.sessionManager.getSession(identityKey)
|
|
275
|
+
peerSession = await this.sessionManager.getSession(identityKey)
|
|
266
276
|
}
|
|
267
277
|
|
|
268
278
|
// If that session doesn't exist or isn't authenticated, initiate handshake
|
|
@@ -270,7 +280,7 @@ export class Peer {
|
|
|
270
280
|
// This will create a brand-new session
|
|
271
281
|
const sessionNonce = await this.initiateHandshake(identityKey)
|
|
272
282
|
// Now retrieve it by the sessionNonce
|
|
273
|
-
peerSession = this.sessionManager.getSession(sessionNonce)
|
|
283
|
+
peerSession = await this.sessionManager.getSession(sessionNonce)
|
|
274
284
|
if (peerSession?.isAuthenticated !== true) {
|
|
275
285
|
throw new Error('Unable to establish mutual authentication with peer!')
|
|
276
286
|
}
|
|
@@ -367,7 +377,7 @@ export class Peer {
|
|
|
367
377
|
const certificatesRequired =
|
|
368
378
|
this.certificatesToRequest.certifiers.length > 0
|
|
369
379
|
|
|
370
|
-
this.sessionManager.addSession({
|
|
380
|
+
await this.sessionManager.addSession({
|
|
371
381
|
isAuthenticated: false,
|
|
372
382
|
sessionNonce,
|
|
373
383
|
peerIdentityKey: identityKey,
|
|
@@ -511,7 +521,7 @@ export class Peer {
|
|
|
511
521
|
Array.isArray(this.certificatesToRequest?.certifiers) &&
|
|
512
522
|
this.certificatesToRequest.certifiers.length > 0
|
|
513
523
|
|
|
514
|
-
this.sessionManager.addSession({
|
|
524
|
+
await this.sessionManager.addSession({
|
|
515
525
|
isAuthenticated: true,
|
|
516
526
|
sessionNonce,
|
|
517
527
|
peerNonce: message.initialNonce,
|
|
@@ -588,7 +598,7 @@ export class Peer {
|
|
|
588
598
|
)
|
|
589
599
|
}
|
|
590
600
|
|
|
591
|
-
const peerSession = this.sessionManager.getSession(message.yourNonce as string)
|
|
601
|
+
const peerSession = await this.sessionManager.getSession(message.yourNonce as string)
|
|
592
602
|
if (peerSession == null) {
|
|
593
603
|
throw new Error(`Peer session not found for peer: ${message.identityKey}`)
|
|
594
604
|
}
|
|
@@ -624,7 +634,7 @@ export class Peer {
|
|
|
624
634
|
peerSession.certificatesValidated = !peerSession.certificatesRequired
|
|
625
635
|
|
|
626
636
|
peerSession.lastUpdate = Date.now()
|
|
627
|
-
this.sessionManager.updateSession(peerSession)
|
|
637
|
+
await this.sessionManager.updateSession(peerSession)
|
|
628
638
|
|
|
629
639
|
// --- Validate certificates if provided ---
|
|
630
640
|
if (
|
|
@@ -641,7 +651,7 @@ export class Peer {
|
|
|
641
651
|
|
|
642
652
|
peerSession.certificatesValidated = true
|
|
643
653
|
peerSession.lastUpdate = Date.now()
|
|
644
|
-
this.sessionManager.updateSession(peerSession)
|
|
654
|
+
await this.sessionManager.updateSession(peerSession)
|
|
645
655
|
|
|
646
656
|
// Resolve any promises waiting for certificate validation
|
|
647
657
|
if (peerSession.sessionNonce != null) {
|
|
@@ -711,7 +721,7 @@ export class Peer {
|
|
|
711
721
|
`Unable to verify nonce for certificate request message from: ${message.identityKey}`
|
|
712
722
|
)
|
|
713
723
|
}
|
|
714
|
-
const peerSession = this.sessionManager.getSession(message.yourNonce as string)
|
|
724
|
+
const peerSession = await this.sessionManager.getSession(message.yourNonce as string)
|
|
715
725
|
if (peerSession == null) {
|
|
716
726
|
throw new Error(`Session not found for nonce: ${message.yourNonce as string}`)
|
|
717
727
|
}
|
|
@@ -731,7 +741,7 @@ export class Peer {
|
|
|
731
741
|
|
|
732
742
|
// Update usage
|
|
733
743
|
peerSession.lastUpdate = Date.now()
|
|
734
|
-
this.sessionManager.updateSession(peerSession)
|
|
744
|
+
await this.sessionManager.updateSession(peerSession)
|
|
735
745
|
|
|
736
746
|
if (
|
|
737
747
|
(message.requestedCertificates != null) &&
|
|
@@ -789,7 +799,7 @@ export class Peer {
|
|
|
789
799
|
|
|
790
800
|
// Update usage
|
|
791
801
|
peerSession.lastUpdate = Date.now()
|
|
792
|
-
this.sessionManager.updateSession(peerSession)
|
|
802
|
+
await this.sessionManager.updateSession(peerSession)
|
|
793
803
|
|
|
794
804
|
try {
|
|
795
805
|
await this.transport.send(certificateResponse)
|
|
@@ -813,7 +823,7 @@ export class Peer {
|
|
|
813
823
|
)
|
|
814
824
|
}
|
|
815
825
|
|
|
816
|
-
const peerSession = this.sessionManager.getSession(message.yourNonce as string)
|
|
826
|
+
const peerSession = await this.sessionManager.getSession(message.yourNonce as string)
|
|
817
827
|
if (peerSession == null) {
|
|
818
828
|
throw new Error(`Session not found for nonce: ${message.yourNonce as string}`)
|
|
819
829
|
}
|
|
@@ -843,7 +853,7 @@ export class Peer {
|
|
|
843
853
|
|
|
844
854
|
peerSession.certificatesValidated = true
|
|
845
855
|
peerSession.lastUpdate = Date.now()
|
|
846
|
-
this.sessionManager.updateSession(peerSession)
|
|
856
|
+
await this.sessionManager.updateSession(peerSession)
|
|
847
857
|
|
|
848
858
|
// Resolve any promises waiting for certificate validation
|
|
849
859
|
if (peerSession.sessionNonce != null) {
|
|
@@ -878,7 +888,7 @@ export class Peer {
|
|
|
878
888
|
)
|
|
879
889
|
}
|
|
880
890
|
|
|
881
|
-
const peerSession = this.sessionManager.getSession(message.yourNonce as string)
|
|
891
|
+
const peerSession = await this.sessionManager.getSession(message.yourNonce as string)
|
|
882
892
|
if (peerSession == null) {
|
|
883
893
|
throw new Error(`Session not found for nonce: ${message.yourNonce as string}`)
|
|
884
894
|
}
|
|
@@ -942,7 +952,7 @@ export class Peer {
|
|
|
942
952
|
|
|
943
953
|
// Mark last usage
|
|
944
954
|
peerSession.lastUpdate = Date.now()
|
|
945
|
-
this.sessionManager.updateSession(peerSession)
|
|
955
|
+
await this.sessionManager.updateSession(peerSession)
|
|
946
956
|
|
|
947
957
|
// Update lastInteractedWithPeer
|
|
948
958
|
this.lastInteractedWithPeer = message.identityKey
|
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
import { PeerSession } from './types.js'
|
|
2
2
|
|
|
3
|
+
/**
|
|
4
|
+
* Opt-in async session-manager contract for horizontally scaled deployments.
|
|
5
|
+
*
|
|
6
|
+
* The default in-process {@link SessionManager} stores BRC-103 nonce/session
|
|
7
|
+
* state in memory and is synchronous. Multi-instance HTTP servers that need
|
|
8
|
+
* every instance to resolve the same handshake state — e.g. behind a load
|
|
9
|
+
* balancer without sticky routing — can implement `AsyncSessionManager`
|
|
10
|
+
* against a shared store such as Redis or SQL and pass it to {@link Peer}
|
|
11
|
+
* or `createAuthMiddleware` instead.
|
|
12
|
+
*
|
|
13
|
+
* {@link Peer} accepts `SessionManager | AsyncSessionManager` and awaits every
|
|
14
|
+
* call internally, so sync stores incur no extra latency while async stores
|
|
15
|
+
* work transparently.
|
|
16
|
+
*/
|
|
17
|
+
export interface AsyncSessionManager {
|
|
18
|
+
addSession: (session: PeerSession) => Promise<void>
|
|
19
|
+
updateSession: (session: PeerSession) => Promise<void>
|
|
20
|
+
getSession: (identifier: string) => Promise<PeerSession | undefined>
|
|
21
|
+
removeSession: (session: PeerSession) => Promise<void>
|
|
22
|
+
hasSession: (identifier: string) => Promise<boolean>
|
|
23
|
+
}
|
|
24
|
+
|
|
3
25
|
/**
|
|
4
26
|
* Manages sessions for peers, allowing multiple concurrent sessions
|
|
5
27
|
* per identity key. Primary lookup is always by `sessionNonce`.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Peer } from '../../auth/Peer.js'
|
|
2
|
-
import { AuthMessage, Transport } from '../../auth/types.js'
|
|
2
|
+
import { AuthMessage, PeerSession, Transport } from '../../auth/types.js'
|
|
3
3
|
import { jest } from '@jest/globals'
|
|
4
4
|
import { WalletInterface } from '../../wallet/Wallet.interfaces.js'
|
|
5
5
|
import { Utils, PrivateKey } from '../../primitives/index.js'
|
|
@@ -8,6 +8,7 @@ import { MasterCertificate } from '../../auth/certificates/MasterCertificate.js'
|
|
|
8
8
|
import { getVerifiableCertificates } from '../../auth/utils/getVerifiableCertificates.js'
|
|
9
9
|
import { CompletedProtoWallet } from '../certificates/__tests/CompletedProtoWallet.js'
|
|
10
10
|
import { SimplifiedFetchTransport } from '../../auth/transports/SimplifiedFetchTransport.js'
|
|
11
|
+
import { SessionManager, AsyncSessionManager } from '../../auth/SessionManager.js'
|
|
11
12
|
|
|
12
13
|
const certifierPrivKey = new PrivateKey(21)
|
|
13
14
|
const alicePrivKey = new PrivateKey(22)
|
|
@@ -51,6 +52,35 @@ class LocalTransport implements Transport {
|
|
|
51
52
|
}
|
|
52
53
|
}
|
|
53
54
|
|
|
55
|
+
class AsyncSessionStore implements AsyncSessionManager {
|
|
56
|
+
private readonly sessions = new SessionManager()
|
|
57
|
+
|
|
58
|
+
async addSession(session: PeerSession): Promise<void> {
|
|
59
|
+
await Promise.resolve()
|
|
60
|
+
this.sessions.addSession(session)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async updateSession(session: PeerSession): Promise<void> {
|
|
64
|
+
await Promise.resolve()
|
|
65
|
+
this.sessions.updateSession(session)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async getSession(identifier: string): Promise<PeerSession | undefined> {
|
|
69
|
+
await Promise.resolve()
|
|
70
|
+
return this.sessions.getSession(identifier)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async removeSession(session: PeerSession): Promise<void> {
|
|
74
|
+
await Promise.resolve()
|
|
75
|
+
this.sessions.removeSession(session)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async hasSession(identifier: string): Promise<boolean> {
|
|
79
|
+
await Promise.resolve()
|
|
80
|
+
return this.sessions.hasSession(identifier)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
54
84
|
function waitForNextGeneralMessage(
|
|
55
85
|
peer: Peer,
|
|
56
86
|
handler?: (senderPublicKey: string, payload: number[]) => void
|
|
@@ -290,6 +320,22 @@ describe('Peer class mutual authentication and certificate exchange', () => {
|
|
|
290
320
|
expect(certificatesReceivedByBob).toEqual([])
|
|
291
321
|
}, 15000)
|
|
292
322
|
|
|
323
|
+
it('supports asynchronous shared session managers', async () => {
|
|
324
|
+
alice = new Peer(walletA, transportA, undefined, new AsyncSessionStore())
|
|
325
|
+
bob = new Peer(walletB, transportB, undefined, new AsyncSessionStore())
|
|
326
|
+
|
|
327
|
+
const bobReceivedGeneralMessage = waitForNextGeneralMessage(bob)
|
|
328
|
+
const aliceReceivedGeneralMessage = waitForNextGeneralMessage(alice)
|
|
329
|
+
|
|
330
|
+
bob.listenForGeneralMessages((senderPublicKey) => {
|
|
331
|
+
void bob.toPeer(Utils.toArray('Hello Alice!'), senderPublicKey)
|
|
332
|
+
})
|
|
333
|
+
|
|
334
|
+
await alice.toPeer(Utils.toArray('Hello Bob!'))
|
|
335
|
+
await bobReceivedGeneralMessage
|
|
336
|
+
await aliceReceivedGeneralMessage
|
|
337
|
+
}, 15000)
|
|
338
|
+
|
|
293
339
|
it('Alice talks to Bob across two devices, Bob can respond across both sessions', async () => {
|
|
294
340
|
const transportA1 = new LocalTransport()
|
|
295
341
|
const transportA2 = new LocalTransport()
|
|
@@ -7,7 +7,7 @@ import { OriginatorDomainNameStringUnder250Bytes, WalletInterface } from '../../
|
|
|
7
7
|
import { createNonce } from '../utils/createNonce.js'
|
|
8
8
|
import { Peer } from '../Peer.js'
|
|
9
9
|
import { SimplifiedFetchTransport } from '../transports/SimplifiedFetchTransport.js'
|
|
10
|
-
import { SessionManager } from '../SessionManager.js'
|
|
10
|
+
import { SessionManager, AsyncSessionManager } from '../SessionManager.js'
|
|
11
11
|
import { RequestedCertificateSet } from '../types.js'
|
|
12
12
|
import { VerifiableCertificate } from '../certificates/VerifiableCertificate.js'
|
|
13
13
|
import { Writer } from '../../primitives/utils.js'
|
|
@@ -79,10 +79,13 @@ export class AuthFetch {
|
|
|
79
79
|
* @param wallet - The wallet instance for signing and authentication.
|
|
80
80
|
* @param requestedCertificates - Optional set of certificates to request from peers.
|
|
81
81
|
*/
|
|
82
|
-
constructor(wallet: WalletInterface, requestedCertificates?: RequestedCertificateSet, sessionManager?: SessionManager, originator?: OriginatorDomainNameStringUnder250Bytes) {
|
|
82
|
+
constructor(wallet: WalletInterface, requestedCertificates?: RequestedCertificateSet, sessionManager?: SessionManager | AsyncSessionManager, originator?: OriginatorDomainNameStringUnder250Bytes) {
|
|
83
83
|
this.wallet = wallet
|
|
84
84
|
this.requestedCertificates = requestedCertificates
|
|
85
|
-
|
|
85
|
+
// See `Peer.sessionManager`: field stays typed as the synchronous
|
|
86
|
+
// `SessionManager` for back-compat; if an `AsyncSessionManager` is
|
|
87
|
+
// injected, the underlying Peer awaits all calls internally.
|
|
88
|
+
this.sessionManager = (sessionManager ?? new SessionManager()) as SessionManager
|
|
86
89
|
this.originator = originator
|
|
87
90
|
}
|
|
88
91
|
|
|
@@ -34,38 +34,74 @@ export class ContactsManager {
|
|
|
34
34
|
private readonly CONTACTS_CACHE_KEY = 'metanet-contacts'
|
|
35
35
|
private readonly originator?: string
|
|
36
36
|
|
|
37
|
+
// Performance state — prevents thundering herd of concurrent contact loads and
|
|
38
|
+
// short-circuits the overlay path entirely when we've previously observed an
|
|
39
|
+
// empty contacts basket. Both are invalidated by saveContact/removeContact and
|
|
40
|
+
// by an explicit forceRefresh.
|
|
41
|
+
private inFlightLoad: Promise<Contact[]> | null = null
|
|
42
|
+
private knownEmpty = false
|
|
43
|
+
|
|
37
44
|
constructor (wallet?: WalletInterface, originator?: string) {
|
|
38
45
|
this.wallet = wallet ?? new WalletClient()
|
|
39
46
|
this.originator = originator
|
|
40
47
|
}
|
|
41
48
|
|
|
42
49
|
/**
|
|
43
|
-
* Load all records from the contacts basket
|
|
50
|
+
* Load all records from the contacts basket.
|
|
51
|
+
*
|
|
52
|
+
* Concurrent calls share a single in-flight load (no thundering herd). After
|
|
53
|
+
* the basket has been observed empty once, subsequent calls return `[]`
|
|
54
|
+
* synchronously without hitting the wallet — until `forceRefresh` is passed
|
|
55
|
+
* or a contact is saved/removed.
|
|
56
|
+
*
|
|
44
57
|
* @param identityKey Optional specific identity key to fetch
|
|
45
58
|
* @param forceRefresh Whether to force a check for new contact data
|
|
46
59
|
* @param limit Maximum number of contacts to return
|
|
47
|
-
* @returns A promise that resolves with an array of contacts
|
|
48
60
|
*/
|
|
49
61
|
async getContacts (identityKey?: PubKeyHex, forceRefresh = false, limit = 1000): Promise<Contact[]> {
|
|
62
|
+
if (forceRefresh) this.invalidate()
|
|
63
|
+
|
|
64
|
+
if (this.knownEmpty) return []
|
|
65
|
+
|
|
50
66
|
if (!forceRefresh) {
|
|
51
67
|
const fromCache = this.loadCachedContacts(identityKey)
|
|
52
68
|
if (fromCache !== null) return fromCache
|
|
53
69
|
}
|
|
54
70
|
|
|
55
|
-
|
|
71
|
+
// Coalesce concurrent loads onto a single Promise so a fan-out of N
|
|
72
|
+
// identity calls produces ONE listOutputs + decrypt batch, not N.
|
|
73
|
+
this.inFlightLoad ??= this.loadContactsFromWallet(limit).finally(() => {
|
|
74
|
+
this.inFlightLoad = null
|
|
75
|
+
})
|
|
76
|
+
const all = await this.inFlightLoad
|
|
77
|
+
return identityKey == null ? all : all.filter(c => c.identityKey === identityKey)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Reset cached state. Call after writes. */
|
|
81
|
+
private invalidate (): void {
|
|
82
|
+
this.cache.removeItem(this.CONTACTS_CACHE_KEY)
|
|
83
|
+
this.knownEmpty = false
|
|
84
|
+
this.inFlightLoad = null
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Underlying wallet load — invoked at most once concurrently via `inFlightLoad`. */
|
|
88
|
+
private async loadContactsFromWallet (limit: number): Promise<Contact[]> {
|
|
89
|
+
// Always load the full basket so subsequent filters (by identityKey) hit cache.
|
|
90
|
+
// Tag filtering is reserved for explicit per-key write paths.
|
|
56
91
|
const outputs = await this.wallet.listOutputs(
|
|
57
|
-
{ basket: 'contacts', include: 'locking scripts', includeCustomInstructions: true, tags, limit },
|
|
92
|
+
{ basket: 'contacts', include: 'locking scripts', includeCustomInstructions: true, tags: [], limit },
|
|
58
93
|
this.originator
|
|
59
94
|
)
|
|
60
95
|
|
|
61
96
|
if (outputs.outputs == null || outputs.outputs.length === 0) {
|
|
62
97
|
this.cache.setItem(this.CONTACTS_CACHE_KEY, JSON.stringify([]))
|
|
98
|
+
this.knownEmpty = true
|
|
63
99
|
return []
|
|
64
100
|
}
|
|
65
101
|
|
|
66
102
|
const contacts = await this.decryptContactOutputs(outputs.outputs)
|
|
67
103
|
this.cache.setItem(this.CONTACTS_CACHE_KEY, JSON.stringify(contacts))
|
|
68
|
-
return
|
|
104
|
+
return contacts
|
|
69
105
|
}
|
|
70
106
|
|
|
71
107
|
/** Returns cached contacts (optionally filtered) or null if cache is missing/invalid. */
|
|
@@ -158,6 +194,8 @@ export class ContactsManager {
|
|
|
158
194
|
await this.createContactOutput(lockingScript, keyID, hashedIdentityKey, contact)
|
|
159
195
|
}
|
|
160
196
|
this.cache.setItem(this.CONTACTS_CACHE_KEY, JSON.stringify(contacts))
|
|
197
|
+
this.knownEmpty = false
|
|
198
|
+
this.inFlightLoad = null
|
|
161
199
|
}
|
|
162
200
|
|
|
163
201
|
/** Computes the HMAC-based hash of an identity key for tag indexing. */
|
|
@@ -265,11 +303,14 @@ export class ContactsManager {
|
|
|
265
303
|
if (cached != null && cached !== '') {
|
|
266
304
|
try {
|
|
267
305
|
const contacts: Contact[] = JSON.parse(cached)
|
|
268
|
-
|
|
306
|
+
const remaining = contacts.filter(c => c.identityKey !== identityKey)
|
|
307
|
+
this.cache.setItem(this.CONTACTS_CACHE_KEY, JSON.stringify(remaining))
|
|
308
|
+
this.knownEmpty = remaining.length === 0
|
|
269
309
|
} catch (e) {
|
|
270
310
|
console.warn('Failed to update cache after contact removal:', e)
|
|
271
311
|
}
|
|
272
312
|
}
|
|
313
|
+
this.inFlightLoad = null
|
|
273
314
|
|
|
274
315
|
const tags = await this.buildIdentityKeyTags(identityKey)
|
|
275
316
|
const outputs = await this.wallet.listOutputs(
|