-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.js
More file actions
2177 lines (1985 loc) · 84.2 KB
/
Copy pathclient.js
File metadata and controls
2177 lines (1985 loc) · 84.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { ApiError, ValidationError, NetworkError, ConfigurationError } from './errors.js';
import { fetchSponsorGrant } from './sponsor.js';
import {
PORTABLE_PROOF_SIGNER_HEADER,
constructVerificationMessage,
validateWalletAddress,
validateUniversalAddress,
signMessage,
PROOFABLE_CONSTANTS
} from './utils.js';
import {
hashGatePolicy,
resolveGateSubjectAccountId,
sanitizeGateRequirements
} from './gates.js';
const FALLBACK_PUBLIC_VERIFIER_CATALOG = {
'ownership-basic': { supportsDirectApi: true },
'ownership-social': { supportsDirectApi: false },
'ownership-pseudonym': { supportsDirectApi: true },
'ownership-dns-txt': { supportsDirectApi: true },
'ownership-org-oauth': { supportsDirectApi: false },
'contract-ownership': { supportsDirectApi: true },
'proof-of-human': { supportsDirectApi: false },
'nft-ownership': { supportsDirectApi: true },
'token-holding': { supportsDirectApi: true },
'wallet-risk': { supportsDirectApi: true },
'wallet-link': { supportsDirectApi: true },
'ai-content-moderation': { supportsDirectApi: true },
'agent-identity': { supportsDirectApi: true },
'agent-delegation': { supportsDirectApi: true }
};
const EVM_ADDRESS_RE = /^0x[a-fA-F0-9]{40}$/;
const WALLET_LINK_RELATIONSHIP_TYPES = new Set(['primary', 'personal', 'org', 'affiliate', 'agent', 'linked']);
function normalizeWalletLinkRelationshipType(value) {
const normalized = String(value || '').trim().toLowerCase();
return WALLET_LINK_RELATIONSHIP_TYPES.has(normalized) ? normalized : 'linked';
}
/**
* @param {unknown} raw
* @returns {string | null} Non-empty trimmed string, or null if the provider value is not a valid string identity.
*/
function normalizeGateCheckResult(response, { gate = null, subject = '', gateId = null } = {}) {
const data = response?.data && typeof response.data === 'object' ? response.data : {};
const gateBlock = data.gate && typeof data.gate === 'object' ? data.gate : null;
const satisfied = gateBlock
? gateBlock.allRequiredSatisfied === true
: data.eligible === true;
const missing = Array.isArray(gateBlock?.missingVerifierIds)
? gateBlock.missingVerifierIds
: [];
const reused = gateBlock?.reusedVerifierProofs && typeof gateBlock.reusedVerifierProofs === 'object'
? gateBlock.reusedVerifierProofs
: {};
const existing = {};
for (const [verifierId, qHashValue] of Object.entries(reused)) {
const qHash = Array.isArray(qHashValue) ? qHashValue[0] : qHashValue;
if (typeof qHash !== 'string' || !qHash.trim()) continue;
existing[verifierId] = {
qHash,
walletAddress: subject,
verifiedVerifiers: [{ verifierId, verified: true }]
};
}
const proofs = Array.isArray(data.matchedQHashes) ? data.matchedQHashes : [];
return {
...response,
satisfied,
policyHash: gateBlock?.policyHash || (gate ? hashGatePolicy(gate) : null),
gateId: gateId || gateBlock?.gateId || null,
subject,
requirements: gate || null,
missing,
proofs,
existing,
expiresAt: gateBlock?.expiresAt || data.expiresAt || null
};
}
function normalizeBrowserSignerString(raw) {
if (raw === null || raw === undefined) {
return null;
}
if (typeof raw === 'string') {
const t = raw.trim();
return t.length > 0 ? t : null;
}
return null;
}
/** Treats SDK placeholder signatures as absent so the protocol can use session or app-link delegation. */
function isPlaceholderSignature(signature) {
const s = typeof signature === 'string' ? signature.trim() : '';
if (!s) return true;
return /^0x0+$/i.test(s);
}
const validateVerifierData = (verifierId, data) => {
if (!data || typeof data !== 'object') {
return { valid: false, error: 'Data object is required' };
}
switch (verifierId) {
case 'ownership-basic':
if (!data.owner || !validateUniversalAddress(data.owner, typeof data.chain === 'string' ? data.chain : undefined)) {
return { valid: false, error: 'owner (universal wallet address) is required' };
}
if (data.content !== undefined && data.content !== null) {
if (typeof data.content !== 'string') {
return { valid: false, error: 'content must be a string when provided' };
}
if (data.content.length > 50000) {
return { valid: false, error: 'content exceeds 50KB inline limit' };
}
}
if (data.contentHash !== undefined && data.contentHash !== null) {
if (typeof data.contentHash !== 'string' || !/^0x[a-fA-F0-9]{64}$/.test(data.contentHash)) {
return { valid: false, error: 'contentHash must be a 32-byte hex string (0x + 64 hex chars) when provided' };
}
}
if (data.contentType !== undefined && data.contentType !== null) {
if (typeof data.contentType !== 'string' || data.contentType.length > 100) {
return { valid: false, error: 'contentType must be a string (max 100 chars) when provided' };
}
const base = String(data.contentType).split(';')[0].trim().toLowerCase();
if (!base || base.includes(' ') || !base.includes('/')) {
return { valid: false, error: 'contentType must be a valid MIME type when provided' };
}
}
if (data.provenance !== undefined && data.provenance !== null) {
if (!data.provenance || typeof data.provenance !== 'object' || Array.isArray(data.provenance)) {
return { valid: false, error: 'provenance must be an object when provided' };
}
const dk = data.provenance.declaredKind;
if (dk !== undefined && dk !== null) {
const allowed = ['human', 'ai', 'mixed', 'unknown'];
if (typeof dk !== 'string' || !allowed.includes(dk)) {
return { valid: false, error: `provenance.declaredKind must be one of: ${allowed.join(', ')}` };
}
}
const ai = data.provenance.aiContext;
if (ai !== undefined && ai !== null) {
if (typeof ai !== 'object' || Array.isArray(ai)) {
return { valid: false, error: 'provenance.aiContext must be an object when provided' };
}
if (ai.generatorType !== undefined && ai.generatorType !== null) {
const allowed = ['local', 'saas', 'agent'];
if (typeof ai.generatorType !== 'string' || !allowed.includes(ai.generatorType)) {
return { valid: false, error: `provenance.aiContext.generatorType must be one of: ${allowed.join(', ')}` };
}
}
if (ai.provider !== undefined && ai.provider !== null) {
if (typeof ai.provider !== 'string' || ai.provider.length > 64) {
return { valid: false, error: 'provenance.aiContext.provider must be a string (max 64 chars) when provided' };
}
}
if (ai.model !== undefined && ai.model !== null) {
if (typeof ai.model !== 'string' || ai.model.length > 128) {
return { valid: false, error: 'provenance.aiContext.model must be a string (max 128 chars) when provided' };
}
}
if (ai.runId !== undefined && ai.runId !== null) {
if (typeof ai.runId !== 'string' || ai.runId.length > 128) {
return { valid: false, error: 'provenance.aiContext.runId must be a string (max 128 chars) when provided' };
}
}
}
}
if (data.reference !== undefined) {
if (!data.reference || typeof data.reference !== 'object') {
return { valid: false, error: 'reference must be an object when provided' };
}
if (!data.reference.type || typeof data.reference.type !== 'string') {
return { valid: false, error: 'reference.type is required when reference is provided' };
}
}
if (!data.content && !data.contentHash) {
if (!data.reference || typeof data.reference !== 'object') {
return { valid: false, error: 'reference is required when neither content nor contentHash is provided' };
}
if (!data.reference.id || typeof data.reference.id !== 'string') {
return { valid: false, error: 'reference.id is required when neither content nor contentHash is provided' };
}
if (!data.reference.type || typeof data.reference.type !== 'string') {
return { valid: false, error: 'reference.type is required when neither content nor contentHash is provided' };
}
}
break;
case 'nft-ownership':
if (
!data.contractAddress ||
data.tokenId === null ||
data.tokenId === undefined ||
typeof data.chainId !== 'number'
) {
return { valid: false, error: 'contractAddress, tokenId, and chainId are required' };
}
if (data.tokenType !== undefined && data.tokenType !== null) {
const tt = String(data.tokenType).toLowerCase();
if (tt !== 'erc721' && tt !== 'erc1155') {
return { valid: false, error: 'tokenType must be one of: erc721, erc1155' };
}
}
if (data.blockNumber !== undefined && data.blockNumber !== null && !Number.isInteger(data.blockNumber)) {
return { valid: false, error: 'blockNumber must be an integer when provided' };
}
if (data.ownerAddress && !validateWalletAddress(data.ownerAddress)) {
return { valid: false, error: 'Invalid ownerAddress' };
}
if (!validateWalletAddress(data.contractAddress)) {
return { valid: false, error: 'Invalid contractAddress' };
}
break;
case 'token-holding':
if (
!data.contractAddress ||
data.minBalance === null ||
data.minBalance === undefined ||
typeof data.chainId !== 'number'
) {
return { valid: false, error: 'contractAddress, minBalance, and chainId are required' };
}
if (data.blockNumber !== undefined && data.blockNumber !== null && !Number.isInteger(data.blockNumber)) {
return { valid: false, error: 'blockNumber must be an integer when provided' };
}
if (data.ownerAddress && !validateWalletAddress(data.ownerAddress)) {
return { valid: false, error: 'Invalid ownerAddress' };
}
if (!validateWalletAddress(data.contractAddress)) {
return { valid: false, error: 'Invalid contractAddress' };
}
break;
case 'ownership-dns-txt':
if (!data.domain || typeof data.domain !== 'string') {
return { valid: false, error: 'domain is required' };
}
if (data.walletAddress && !validateWalletAddress(data.walletAddress)) {
return { valid: false, error: 'Invalid walletAddress' };
}
break;
case 'wallet-link':
if (!data.primaryWalletAddress || !validateUniversalAddress(data.primaryWalletAddress, data.chain)) {
return { valid: false, error: 'primaryWalletAddress is required' };
}
if (!data.secondaryWalletAddress || !validateUniversalAddress(data.secondaryWalletAddress, data.chain)) {
return { valid: false, error: 'secondaryWalletAddress is required' };
}
if (!data.signature || typeof data.signature !== 'string') {
return { valid: false, error: 'signature is required (signed by secondary wallet)' };
}
if (typeof data.chain !== 'string' || !/^[a-z0-9]+:[^\s]+$/.test(data.chain)) {
return { valid: false, error: 'chain is required (namespace:reference)' };
}
if (typeof data.signatureMethod !== 'string' || !data.signatureMethod.trim()) {
return { valid: false, error: 'signatureMethod is required' };
}
if (typeof data.signedTimestamp !== 'number') {
return { valid: false, error: 'signedTimestamp is required' };
}
break;
case 'contract-ownership':
if (!data.contractAddress || !validateWalletAddress(data.contractAddress)) {
return { valid: false, error: 'contractAddress is required' };
}
if (data.walletAddress && !validateWalletAddress(data.walletAddress)) {
return { valid: false, error: 'Invalid walletAddress' };
}
if (typeof data.chainId !== 'number') {
return { valid: false, error: 'chainId is required' };
}
break;
case 'agent-identity':
if (!data.agentId || typeof data.agentId !== 'string' || data.agentId.length < 1 || data.agentId.length > 128) {
return { valid: false, error: 'agentId is required (1-128 chars)' };
}
if (!data.agentWallet || !validateWalletAddress(data.agentWallet)) {
return { valid: false, error: 'agentWallet is required' };
}
if (data.agentType && !['ai', 'bot', 'service', 'automation', 'agent'].includes(data.agentType)) {
return { valid: false, error: 'agentType must be one of: ai, bot, service, automation, agent' };
}
if (data.defaultRuntime && typeof data.defaultRuntime === 'object') {
if (data.defaultRuntime.provider && typeof data.defaultRuntime.provider === 'string' && data.defaultRuntime.provider.length > 64) {
return { valid: false, error: 'defaultRuntime.provider must be 64 chars or less' };
}
if (data.defaultRuntime.model && typeof data.defaultRuntime.model === 'string' && data.defaultRuntime.model.length > 128) {
return { valid: false, error: 'defaultRuntime.model must be 128 chars or less' };
}
if (data.defaultRuntime.mode && typeof data.defaultRuntime.mode === 'string' && data.defaultRuntime.mode.length > 64) {
return { valid: false, error: 'defaultRuntime.mode must be 64 chars or less' };
}
}
break;
case 'agent-delegation':
if (!data.controllerWallet || !validateWalletAddress(data.controllerWallet)) {
return { valid: false, error: 'controllerWallet is required' };
}
if (!data.agentWallet || !validateWalletAddress(data.agentWallet)) {
return { valid: false, error: 'agentWallet is required' };
}
if (data.scope && (typeof data.scope !== 'string' || data.scope.length > 128)) {
return { valid: false, error: 'scope must be a string (max 128 chars)' };
}
if (data.expiresAt && (typeof data.expiresAt !== 'number' || data.expiresAt < Date.now())) {
return { valid: false, error: 'expiresAt must be a future timestamp' };
}
if (data.model && typeof data.model === 'string' && data.model.length > 128) {
return { valid: false, error: 'model must be 128 chars or less' };
}
if (data.provider && typeof data.provider === 'string' && data.provider.length > 64) {
return { valid: false, error: 'provider must be 64 chars or less' };
}
if (data.allowedActions && Array.isArray(data.allowedActions) && data.allowedActions.length > 32) {
return { valid: false, error: 'allowedActions must have 32 items or less' };
}
if (data.deniedActions && Array.isArray(data.deniedActions) && data.deniedActions.length > 32) {
return { valid: false, error: 'deniedActions must have 32 items or less' };
}
break;
case 'ai-content-moderation':
if (!data.content || typeof data.content !== 'string') {
return { valid: false, error: 'content is required' };
}
if (!data.contentType || typeof data.contentType !== 'string') {
return { valid: false, error: 'contentType (MIME type) is required' };
}
{
const contentType = String(data.contentType).split(';')[0].trim().toLowerCase();
const validTypes = [
'image/jpeg',
'image/png',
'image/webp',
'image/gif',
'text/plain',
'text/markdown',
'text/x-markdown',
'application/json',
'application/xml'
];
if (!validTypes.includes(contentType)) {
return { valid: false, error: `contentType must be one of: ${validTypes.join(', ')}` };
}
const isTextual = contentType.startsWith('text/') || contentType.includes('markdown');
if (isTextual) {
try {
const maxBytes = 50 * 1024;
const bytes = (typeof TextEncoder !== 'undefined')
? new TextEncoder().encode(data.content).length
: String(data.content).length;
if (bytes > maxBytes) {
return {
valid: false,
error: `content exceeds ${maxBytes} bytes limit for ai-content-moderation verifier (text)`
};
}
} catch {
void 0;
}
}
}
if (data.content.length > 13653334) {
return { valid: false, error: 'content exceeds 10MB limit' };
}
break;
case 'ownership-pseudonym':
if (!data.pseudonymId || typeof data.pseudonymId !== 'string') {
return { valid: false, error: 'pseudonymId is required' };
}
if (!/^[a-z0-9._-]{3,64}$/.test(data.pseudonymId.trim().toLowerCase())) {
return { valid: false, error: 'pseudonymId must be 3-64 characters, lowercase alphanumeric with dots, underscores, or hyphens' };
}
if (data.namespace && typeof data.namespace === 'string') {
if (!/^[a-z0-9._-]{1,64}$/.test(data.namespace.trim().toLowerCase())) {
return { valid: false, error: 'namespace must be 1-64 characters, lowercase alphanumeric with dots, underscores, or hyphens' };
}
}
break;
case 'wallet-risk':
if (data.walletAddress && !validateUniversalAddress(data.walletAddress, data.chain)) {
return { valid: false, error: 'Invalid walletAddress' };
}
break;
}
return { valid: true };
};
export class ProofableClient {
constructor(config = {}) {
this.config = {
timeout: 30000,
enableLogging: false,
...config
};
this.baseUrl = this.config.apiUrl || 'https://api.proofable.me';
try {
const url = new URL(this.baseUrl);
if (url.hostname.endsWith('proofable.me') && url.protocol === 'http:') {
url.protocol = 'https:';
}
this.baseUrl = url.toString().replace(/\/$/, '');
} catch {
void 0;
}
this.config.apiUrl = this.baseUrl;
this.defaultHeaders = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-Neus-Sdk': 'js'
};
if (typeof this.config.apiKey === 'string' && this.config.apiKey.trim().length > 0) {
this.defaultHeaders['Authorization'] = `Bearer ${this.config.apiKey.trim()}`;
}
if (typeof this.config.appId === 'string' && this.config.appId.trim().length > 0) {
this.defaultHeaders['X-Neus-App'] = this.config.appId.trim();
}
if (typeof this.config.paymentSignature === 'string' && this.config.paymentSignature.trim().length > 0) {
this.defaultHeaders['PAYMENT-SIGNATURE'] = this.config.paymentSignature.trim();
}
if (this.config.extraHeaders && typeof this.config.extraHeaders === 'object') {
for (const [k, v] of Object.entries(this.config.extraHeaders)) {
if (!k || v === undefined || v === null) continue;
const key = String(k).trim();
const value = String(v).trim();
if (!key || !value) continue;
this.defaultHeaders[key] = value;
}
}
try {
if (typeof window !== 'undefined' && window.location && window.location.origin) {
this.defaultHeaders['X-Client-Origin'] = window.location.origin;
} else if (typeof this.config.appOrigin === 'string' && this.config.appOrigin.trim()) {
const origin = this.config.appOrigin.trim();
this.defaultHeaders['Origin'] = origin;
this.defaultHeaders['X-Client-Origin'] = origin;
}
} catch {
void 0;
}
/** @type {{ token: string, expMs: number, key: string } | null} */
this._sponsorGrantCache = null;
}
_getBillingWallet() {
const raw =
this.config.billingWallet ||
this.config.sponsorOrgWallet ||
this.config.orgWallet ||
null;
if (typeof raw !== 'string') return null;
const trimmed = raw.trim().toLowerCase();
return /^0x[a-f0-9]{40}$/.test(trimmed) ? trimmed : null;
}
_resolveIntegratorOrigin() {
if (typeof this.config.appOrigin === 'string' && this.config.appOrigin.trim()) {
return this.config.appOrigin.trim();
}
try {
if (typeof window !== 'undefined' && window.location?.origin) {
return window.location.origin;
}
} catch {
void 0;
}
return null;
}
async _resolveSponsorGrantHeaders(verifierIds = []) {
const appId = typeof this.config.appId === 'string' ? this.config.appId.trim() : '';
const orgWallet = this._getBillingWallet();
if (!appId || !orgWallet) {
return {};
}
const normalizedVerifierIds = Array.isArray(verifierIds)
? verifierIds.map((v) => String(v || '').trim()).filter(Boolean).slice(0, 25)
: [];
const cacheKey = `${appId}:${orgWallet}:${normalizedVerifierIds.join(',')}`;
const now = Date.now();
if (
this._sponsorGrantCache &&
this._sponsorGrantCache.key === cacheKey &&
this._sponsorGrantCache.expMs > now + 30_000
) {
return { 'X-Sponsor-Grant': this._sponsorGrantCache.token };
}
const origin = this._resolveIntegratorOrigin();
const grant = await fetchSponsorGrant({
apiUrl: this.baseUrl,
appId,
orgWallet,
verifierIds: normalizedVerifierIds,
origin
});
const expSeconds = Number(grant?.exp);
const expMs = Number.isFinite(expSeconds) && expSeconds > 0
? expSeconds * 1000
: now + 15 * 60 * 1000;
this._sponsorGrantCache = {
key: cacheKey,
token: grant.sponsorGrant,
expMs
};
return { 'X-Sponsor-Grant': grant.sponsorGrant };
}
_getHubChainId() {
// Canonical identity chain (Base mainnet 8453). Accepts `identityChainId`;
// `hubChainId` remains a deprecated alias for existing integrators.
const configured = Number(this.config?.identityChainId ?? this.config?.hubChainId);
if (Number.isFinite(configured) && configured > 0) return Math.floor(configured);
return PROOFABLE_CONSTANTS.IDENTITY_CHAIN_ID;
}
_normalizeIdentity(value) {
let raw = String(value || '').trim();
if (!raw) return '';
const didMatch = raw.match(/^did:pkh:([^:]+):([^:]+):(.+)$/i);
if (didMatch && didMatch[3]) {
raw = String(didMatch[3]).trim();
}
return EVM_ADDRESS_RE.test(raw) ? raw.toLowerCase() : raw;
}
_inferChainForAddress(address, explicitChain) {
if (typeof explicitChain === 'string' && explicitChain.includes(':')) return explicitChain.trim();
const raw = String(address || '').trim();
const didMatch = raw.match(/^did:pkh:([^:]+):([^:]+):(.+)$/i);
if (didMatch && didMatch[1] && didMatch[2]) {
return `${didMatch[1]}:${didMatch[2]}`;
}
if (EVM_ADDRESS_RE.test(raw)) {
return `eip155:${this._getHubChainId()}`;
}
return 'solana:mainnet';
}
async _resolveWalletSigner(wallet) {
if (!wallet) {
throw new ConfigurationError('No wallet provider available');
}
if (wallet.address !== null && wallet.address !== undefined) {
const s = normalizeBrowserSignerString(
typeof wallet.address === 'string' ? wallet.address : null
);
if (s) {
return { signerWalletAddress: s, provider: wallet };
}
}
if (wallet.publicKey && typeof wallet.publicKey.toBase58 === 'function') {
const b58 = wallet.publicKey.toBase58();
const s = normalizeBrowserSignerString(typeof b58 === 'string' ? b58 : null);
if (s) {
return { signerWalletAddress: s, provider: wallet };
}
}
if (typeof wallet.getAddress === 'function') {
const got = await wallet.getAddress().catch(() => null);
const s = normalizeBrowserSignerString(
got === null || got === undefined ? null : (typeof got === 'string' ? got : null)
);
if (s) {
return { signerWalletAddress: s, provider: wallet };
}
}
if (wallet.selectedAddress || wallet.request) {
const provider = wallet;
if (wallet.selectedAddress) {
const s = normalizeBrowserSignerString(
typeof wallet.selectedAddress === 'string' ? wallet.selectedAddress : null
);
if (s) {
return { signerWalletAddress: s, provider };
}
}
const accounts = await provider.request({ method: 'eth_accounts' });
if (!accounts || accounts.length === 0) {
throw new ConfigurationError('No wallet accounts available');
}
const s = normalizeBrowserSignerString(accounts[0]);
if (!s) {
throw new ConfigurationError('No wallet accounts available');
}
return { signerWalletAddress: s, provider };
}
throw new ConfigurationError('Invalid wallet provider');
}
_getDefaultBrowserWallet() {
if (typeof window === 'undefined') return null;
// EIP-1193 provider detection. Non-EVM wallets must be passed explicitly
// with CAIP-2 chain context so the SDK does not route them through EVM RPC.
return window.ethereum || null;
}
async _buildPrivateGateAuth({ address, wallet, chain, signatureMethod } = {}) {
const providerWallet = wallet || this._getDefaultBrowserWallet();
const { signerWalletAddress, provider } = await this._resolveWalletSigner(providerWallet);
if (!signerWalletAddress || typeof signerWalletAddress !== 'string') {
throw new ConfigurationError('No wallet accounts available');
}
const normalizedSigner = this._normalizeIdentity(signerWalletAddress);
const normalizedAddress = this._normalizeIdentity(address);
if (!normalizedSigner || normalizedSigner !== normalizedAddress) {
throw new ValidationError('wallet must match address when includePrivate=true');
}
const signerIsEvm = EVM_ADDRESS_RE.test(normalizedSigner);
const resolvedChain = this._inferChainForAddress(normalizedSigner, chain);
const resolvedSignatureMethod = (typeof signatureMethod === 'string' && signatureMethod.trim())
? signatureMethod.trim()
: (signerIsEvm ? 'eip191' : 'ed25519');
const signedTimestamp = Date.now();
const message = constructVerificationMessage({
walletAddress: signerWalletAddress,
signedTimestamp,
data: { action: 'gate_check_private_proofs', walletAddress: normalizedAddress },
verifierIds: ['ownership-basic'],
...(signerIsEvm ? { chainId: this._getHubChainId() } : { chain: resolvedChain })
});
let signature;
try {
signature = await signMessage({
provider,
message,
walletAddress: signerWalletAddress,
...(signerIsEvm ? {} : { chain: resolvedChain })
});
} catch (error) {
if (error.code === 4001) {
throw new ValidationError('User rejected signature request');
}
throw new ValidationError(`Failed to sign message: ${error.message}`);
}
return {
walletAddress: signerWalletAddress,
signature,
signedTimestamp,
...(signerIsEvm ? {} : { chain: resolvedChain, signatureMethod: resolvedSignatureMethod })
};
}
async createGatePrivateAuth(params = {}) {
const address = (params.address || '').toString();
if (!validateUniversalAddress(address, params.chain)) {
throw new ValidationError('Valid address is required');
}
return this._buildPrivateGateAuth({
address,
wallet: params.wallet,
chain: params.chain,
signatureMethod: params.signatureMethod
});
}
async createWalletLinkData(params = {}) {
const normalizedPrimary = this._normalizeIdentity(params.primaryWalletAddress);
const normalizedSecondary = this._normalizeIdentity(params.secondaryWalletAddress);
if (!EVM_ADDRESS_RE.test(normalizedPrimary)) {
throw new ValidationError('wallet-link requires a valid primaryWalletAddress');
}
if (!EVM_ADDRESS_RE.test(normalizedSecondary)) {
throw new ValidationError('wallet-link requires a valid secondaryWalletAddress');
}
if (normalizedPrimary === normalizedSecondary) {
throw new ValidationError('wallet-link secondaryWalletAddress must differ from primaryWalletAddress');
}
const providerWallet = params.wallet || this._getDefaultBrowserWallet();
const { signerWalletAddress, provider } = await this._resolveWalletSigner(providerWallet);
const normalizedSigner = this._normalizeIdentity(signerWalletAddress);
if (!EVM_ADDRESS_RE.test(normalizedSigner)) {
throw new ValidationError('wallet-link requires an EVM wallet/provider for the secondary wallet');
}
if (normalizedSigner !== normalizedSecondary) {
throw new ValidationError('wallet-link wallet/provider must be connected to secondaryWalletAddress');
}
const resolvedChain = (() => {
const raw = String(params.chain || '').trim();
if (!raw) return `eip155:${this._getHubChainId()}`;
if (!/^eip155:\d+$/.test(raw)) {
throw new ValidationError('wallet-link requires chain in the form eip155:<chainId>');
}
return raw;
})();
const signedTimestamp = Number.isFinite(Number(params.signedTimestamp)) && Number(params.signedTimestamp) > 0
? Number(params.signedTimestamp)
: Date.now();
const linkData = {
primaryAccountId: `${resolvedChain}:${normalizedPrimary}`,
secondaryAccountId: `${resolvedChain}:${normalizedSecondary}`,
primaryWalletAddress: normalizedPrimary,
secondaryWalletAddress: normalizedSecondary
};
const message = constructVerificationMessage({
walletAddress: normalizedSecondary,
signedTimestamp,
data: linkData,
verifierIds: ['wallet-link'],
chain: resolvedChain
});
let signature;
try {
signature = await signMessage({
provider,
message,
walletAddress: signerWalletAddress
});
} catch (error) {
if (error?.code === 4001) {
throw new ValidationError('User rejected wallet-link signature request');
}
throw new ValidationError(`Failed to sign wallet-link message: ${error?.message || String(error)}`);
}
const label = String(params.label || '').trim().slice(0, 64);
return {
primaryWalletAddress: normalizedPrimary,
secondaryWalletAddress: normalizedSecondary,
signature,
chain: resolvedChain,
signatureMethod: 'eip191',
signedTimestamp,
relationshipType: normalizeWalletLinkRelationshipType(params.relationshipType),
...(label ? { label } : {})
};
}
async verifyFromApp(params) {
if (!params || typeof params !== 'object') {
throw new ValidationError('verifyFromApp requires a params object');
}
const {
user,
verifier = 'ownership-basic',
content,
data: explicitData = null,
options = {}
} = params;
if (!user || typeof user !== 'object') {
throw new ValidationError('verifyFromApp requires user object');
}
const walletAddress =
user.walletAddress ||
user.address ||
user.identity;
if (!walletAddress || typeof walletAddress !== 'string') {
throw new ValidationError('verifyFromApp requires user.walletAddress');
}
const delegationQHash =
this.config.appLinkQHash ||
(typeof process !== 'undefined' && process.env && process.env.PROOFABLE_APP_LINK_QHASH) ||
null;
let data;
if (explicitData && typeof explicitData === 'object') {
data = { owner: walletAddress, ...explicitData };
} else if (content && typeof content === 'object') {
data = {
owner: walletAddress,
content: JSON.stringify(content),
contentType: typeof content.contentType === 'string' ? content.contentType : 'application/json',
reference: content.reference || { type: 'other' }
};
} else if (typeof content === 'string') {
data = {
owner: walletAddress,
content,
reference: { type: 'other' }
};
} else {
data = { owner: walletAddress, reference: { type: 'other' } };
}
const signedTimestamp = Date.now();
const verifierIds = [verifier];
return this.verify({
verifierIds,
data,
walletAddress,
signedTimestamp,
...(delegationQHash ? { delegationQHash } : {}),
options
});
}
async verify(params) {
if (
(isPlaceholderSignature(params?.signature) || !params?.signature || !params?.walletAddress) &&
(params?.verifier || params?.content || params?.data)
) {
const { content, verifier = 'ownership-basic', data = null, wallet = null, options = {} } = params;
if (verifier === 'ownership-basic' && !data && (!content || typeof content !== 'string')) {
throw new ValidationError('content is required and must be a string (or use data param with owner + reference)');
}
let verifierCatalog = FALLBACK_PUBLIC_VERIFIER_CATALOG;
try {
const discovered = await this.getVerifierCatalog();
if (discovered && discovered.metadata && Object.keys(discovered.metadata).length > 0) {
verifierCatalog = discovered.metadata;
}
} catch {
void 0;
}
const validVerifiers = Object.keys(verifierCatalog);
if (!validVerifiers.includes(verifier)) {
throw new ValidationError(`Invalid verifier '${verifier}'. Must be one of: ${validVerifiers.join(', ')}.`);
}
if (verifierCatalog?.[verifier]?.supportsDirectApi === false) {
const hostedCheckoutUrl = options?.hostedCheckoutUrl || 'https://proofable.me/verify';
throw new ValidationError(
`${verifier} requires hosted interactive checkout. Use VerifyGate or redirect to ${hostedCheckoutUrl}.`
);
}
const requiresDataParam = [
'ownership-dns-txt',
'wallet-link',
'contract-ownership',
'ownership-pseudonym',
'wallet-risk',
'agent-identity',
'agent-delegation',
'ai-content-moderation'
];
if (requiresDataParam.includes(verifier)) {
if (!data || typeof data !== 'object') {
throw new ValidationError(`${verifier} requires explicit data parameter. Cannot use auto-path.`);
}
}
let walletAddress, provider;
if (wallet) {
walletAddress =
wallet.address ||
wallet.selectedAddress ||
wallet.walletAddress ||
(typeof wallet.getAddress === 'function' ? await wallet.getAddress().catch(() => null) : null);
provider = wallet.provider || wallet;
if (!walletAddress && provider && typeof provider.request === 'function') {
let accounts = await provider.request({ method: 'eth_accounts' });
walletAddress = Array.isArray(accounts) && accounts.length > 0 ? accounts[0] : null;
if (!walletAddress) {
await provider.request({ method: 'eth_requestAccounts' });
accounts = await provider.request({ method: 'eth_accounts' });
walletAddress = Array.isArray(accounts) && accounts.length > 0 ? accounts[0] : null;
}
}
} else {
if (typeof window === 'undefined' || !window.ethereum) {
throw new ConfigurationError('No EVM browser wallet detected. Provide wallet explicitly for non-EVM flows and include chain as a CAIP-2 value.');
}
await window.ethereum.request({ method: 'eth_requestAccounts' });
provider = window.ethereum;
const accounts = await provider.request({ method: 'eth_accounts' });
walletAddress = accounts[0];
}
{
const normalized = normalizeBrowserSignerString(
typeof walletAddress === 'string' ? walletAddress : null
);
if (!normalized) {
throw new ConfigurationError('No wallet accounts available. Connect a wallet to continue.');
}
walletAddress = normalized;
}
let verificationData;
if (verifier === 'ownership-basic') {
if (data && typeof data === 'object') {
verificationData = {
owner: data.owner || walletAddress,
reference: data.reference,
...(data.content && { content: data.content }),
...(data.contentHash && { contentHash: data.contentHash }),
...(data.contentType && { contentType: data.contentType }),
...(data.provenance && { provenance: data.provenance })
};
} else {
verificationData = {
content: content,
owner: walletAddress,
reference: { type: 'other' }
};
}
} else if (verifier === 'token-holding') {
if (!data?.contractAddress) {
throw new ValidationError('token-holding requires contractAddress in data parameter');
}
if (data?.minBalance === null || data?.minBalance === undefined) {
throw new ValidationError('token-holding requires minBalance in data parameter');
}
if (typeof data?.chainId !== 'number') {
throw new ValidationError('token-holding requires chainId (number) in data parameter');
}
verificationData = {
ownerAddress: walletAddress,
contractAddress: data.contractAddress,
minBalance: data.minBalance,
chainId: data.chainId
};
} else if (verifier === 'nft-ownership') {
if (!data?.contractAddress) {
throw new ValidationError('nft-ownership requires contractAddress in data parameter');
}
if (data?.tokenId === null || data?.tokenId === undefined) {
throw new ValidationError('nft-ownership requires tokenId in data parameter');
}
if (typeof data?.chainId !== 'number') {
throw new ValidationError('nft-ownership requires chainId (number) in data parameter');
}
verificationData = {
ownerAddress: walletAddress,
contractAddress: data.contractAddress,
tokenId: data.tokenId,
chainId: data.chainId,
tokenType: data?.tokenType || 'erc721'
};
} else if (verifier === 'ownership-dns-txt') {
if (!data?.domain) {
throw new ValidationError('ownership-dns-txt requires domain in data parameter');
}
verificationData = {
domain: data.domain,
walletAddress: walletAddress
};
} else if (verifier === 'wallet-link') {
if (!data?.secondaryWalletAddress) {
throw new ValidationError('wallet-link requires secondaryWalletAddress in data parameter');
}
if (!data?.signature) {
throw new ValidationError('wallet-link requires signature in data parameter (signed by secondary wallet)');
}
if (typeof data?.chain !== 'string' || !/^[a-z0-9]+:[^\s]+$/.test(data.chain)) {
throw new ValidationError('wallet-link requires chain (namespace:reference) in data parameter');
}
if (typeof data?.signatureMethod !== 'string' || !data.signatureMethod.trim()) {
throw new ValidationError('wallet-link requires signatureMethod in data parameter');
}
verificationData = {
primaryWalletAddress: walletAddress,
secondaryWalletAddress: data.secondaryWalletAddress,
signature: data.signature,
chain: data.chain,
signatureMethod: data.signatureMethod,
signedTimestamp: data?.signedTimestamp || Date.now()
};
} else if (verifier === 'contract-ownership') {
if (!data?.contractAddress) {
throw new ValidationError('contract-ownership requires contractAddress in data parameter');
}
if (typeof data?.chainId !== 'number') {
throw new ValidationError('contract-ownership requires chainId (number) in data parameter');
}
verificationData = {
contractAddress: data.contractAddress,
walletAddress: walletAddress,
chainId: data.chainId,
...(data?.method && { method: data.method })
};
} else if (verifier === 'agent-identity') {
if (!data?.agentId) {
throw new ValidationError('agent-identity requires agentId in data parameter');
}
verificationData = {
agentId: data.agentId,
agentWallet: data?.agentWallet || walletAddress,
...(data?.agentChainRef && { agentChainRef: data.agentChainRef }),
...(data?.agentAccountId && { agentAccountId: data.agentAccountId }),
...(data?.agentLabel && { agentLabel: data.agentLabel }),