@neus/sdk 1.0.5 → 1.0.6

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/client.js CHANGED
@@ -1,30 +1,30 @@
1
- import { ApiError, ValidationError, NetworkError, ConfigurationError } from './errors.js';
2
- import {
3
- PORTABLE_PROOF_SIGNER_HEADER,
4
- constructVerificationMessage,
5
- validateWalletAddress,
6
- validateUniversalAddress,
7
- signMessage,
8
- NEUS_CONSTANTS
9
- } from './utils.js';
10
-
11
- const FALLBACK_PUBLIC_VERIFIER_CATALOG = {
12
- 'ownership-basic': { supportsDirectApi: true },
13
- 'ownership-pseudonym': { supportsDirectApi: true },
14
- 'ownership-dns-txt': { supportsDirectApi: true },
15
- 'ownership-social': { supportsDirectApi: false },
16
- 'ownership-org-oauth': { supportsDirectApi: false },
17
- 'contract-ownership': { supportsDirectApi: true },
18
- 'nft-ownership': { supportsDirectApi: true },
19
- 'token-holding': { supportsDirectApi: true },
20
- 'wallet-link': { supportsDirectApi: true },
21
- 'wallet-risk': { supportsDirectApi: true },
22
- 'proof-of-human': { supportsDirectApi: false },
23
- 'agent-identity': { supportsDirectApi: true },
24
- 'agent-delegation': { supportsDirectApi: true },
25
- 'ai-content-moderation': { supportsDirectApi: true }
26
- };
27
-
1
+ import { ApiError, ValidationError, NetworkError, ConfigurationError } from './errors.js';
2
+ import {
3
+ PORTABLE_PROOF_SIGNER_HEADER,
4
+ constructVerificationMessage,
5
+ validateWalletAddress,
6
+ validateUniversalAddress,
7
+ signMessage,
8
+ NEUS_CONSTANTS
9
+ } from './utils.js';
10
+
11
+ const FALLBACK_PUBLIC_VERIFIER_CATALOG = {
12
+ 'ownership-basic': { supportsDirectApi: true },
13
+ 'ownership-pseudonym': { supportsDirectApi: true },
14
+ 'ownership-dns-txt': { supportsDirectApi: true },
15
+ 'ownership-social': { supportsDirectApi: false },
16
+ 'ownership-org-oauth': { supportsDirectApi: false },
17
+ 'contract-ownership': { supportsDirectApi: true },
18
+ 'nft-ownership': { supportsDirectApi: true },
19
+ 'token-holding': { supportsDirectApi: true },
20
+ 'wallet-link': { supportsDirectApi: true },
21
+ 'wallet-risk': { supportsDirectApi: true },
22
+ 'proof-of-human': { supportsDirectApi: false },
23
+ 'agent-identity': { supportsDirectApi: true },
24
+ 'agent-delegation': { supportsDirectApi: true },
25
+ 'ai-content-moderation': { supportsDirectApi: true }
26
+ };
27
+
28
28
  const EVM_ADDRESS_RE = /^0x[a-fA-F0-9]{40}$/;
29
29
  const WALLET_LINK_RELATIONSHIP_TYPES = new Set(['primary', 'personal', 'org', 'affiliate', 'agent', 'linked']);
30
30
 
@@ -32,466 +32,489 @@ function normalizeWalletLinkRelationshipType(value) {
32
32
  const normalized = String(value || '').trim().toLowerCase();
33
33
  return WALLET_LINK_RELATIONSHIP_TYPES.has(normalized) ? normalized : 'linked';
34
34
  }
35
-
36
- const validateVerifierData = (verifierId, data) => {
37
- if (!data || typeof data !== 'object') {
38
- return { valid: false, error: 'Data object is required' };
39
- }
40
-
41
- switch (verifierId) {
42
- case 'ownership-basic':
43
- if (!data.owner || !validateUniversalAddress(data.owner, typeof data.chain === 'string' ? data.chain : undefined)) {
44
- return { valid: false, error: 'owner (universal wallet address) is required' };
45
- }
46
- if (data.content !== undefined && data.content !== null) {
47
- if (typeof data.content !== 'string') {
48
- return { valid: false, error: 'content must be a string when provided' };
49
- }
50
- if (data.content.length > 50000) {
51
- return { valid: false, error: 'content exceeds 50KB inline limit' };
52
- }
53
- }
54
- if (data.contentHash !== undefined && data.contentHash !== null) {
55
- if (typeof data.contentHash !== 'string' || !/^0x[a-fA-F0-9]{64}$/.test(data.contentHash)) {
56
- return { valid: false, error: 'contentHash must be a 32-byte hex string (0x + 64 hex chars) when provided' };
57
- }
58
- }
59
- if (data.contentType !== undefined && data.contentType !== null) {
60
- if (typeof data.contentType !== 'string' || data.contentType.length > 100) {
61
- return { valid: false, error: 'contentType must be a string (max 100 chars) when provided' };
62
- }
63
- const base = String(data.contentType).split(';')[0].trim().toLowerCase();
64
- // Minimal MIME sanity check (server validates more precisely).
65
- if (!base || base.includes(' ') || !base.includes('/')) {
66
- return { valid: false, error: 'contentType must be a valid MIME type when provided' };
67
- }
68
- }
69
- if (data.provenance !== undefined && data.provenance !== null) {
70
- if (!data.provenance || typeof data.provenance !== 'object' || Array.isArray(data.provenance)) {
71
- return { valid: false, error: 'provenance must be an object when provided' };
72
- }
73
- const dk = data.provenance.declaredKind;
74
- if (dk !== undefined && dk !== null) {
75
- const allowed = ['human', 'ai', 'mixed', 'unknown'];
76
- if (typeof dk !== 'string' || !allowed.includes(dk)) {
77
- return { valid: false, error: `provenance.declaredKind must be one of: ${allowed.join(', ')}` };
78
- }
79
- }
80
- const ai = data.provenance.aiContext;
81
- if (ai !== undefined && ai !== null) {
82
- if (typeof ai !== 'object' || Array.isArray(ai)) {
83
- return { valid: false, error: 'provenance.aiContext must be an object when provided' };
84
- }
85
- if (ai.generatorType !== undefined && ai.generatorType !== null) {
86
- const allowed = ['local', 'saas', 'agent'];
87
- if (typeof ai.generatorType !== 'string' || !allowed.includes(ai.generatorType)) {
88
- return { valid: false, error: `provenance.aiContext.generatorType must be one of: ${allowed.join(', ')}` };
89
- }
90
- }
91
- if (ai.provider !== undefined && ai.provider !== null) {
92
- if (typeof ai.provider !== 'string' || ai.provider.length > 64) {
93
- return { valid: false, error: 'provenance.aiContext.provider must be a string (max 64 chars) when provided' };
94
- }
95
- }
96
- if (ai.model !== undefined && ai.model !== null) {
97
- if (typeof ai.model !== 'string' || ai.model.length > 128) {
98
- return { valid: false, error: 'provenance.aiContext.model must be a string (max 128 chars) when provided' };
99
- }
100
- }
101
- if (ai.runId !== undefined && ai.runId !== null) {
102
- if (typeof ai.runId !== 'string' || ai.runId.length > 128) {
103
- return { valid: false, error: 'provenance.aiContext.runId must be a string (max 128 chars) when provided' };
104
- }
105
- }
106
- }
107
- }
108
- if (data.reference !== undefined) {
109
- if (!data.reference || typeof data.reference !== 'object') {
110
- return { valid: false, error: 'reference must be an object when provided' };
111
- }
112
- if (!data.reference.type || typeof data.reference.type !== 'string') {
113
- // Only required when reference object is present (or when doing reference-only proofs).
114
- // Server requires reference.type when reference is used for traceability.
115
- return { valid: false, error: 'reference.type is required when reference is provided' };
116
- }
117
- }
118
- if (!data.content && !data.contentHash) {
119
- if (!data.reference || typeof data.reference !== 'object') {
120
- return { valid: false, error: 'reference is required when neither content nor contentHash is provided' };
121
- }
122
- if (!data.reference.id || typeof data.reference.id !== 'string') {
123
- return { valid: false, error: 'reference.id is required when neither content nor contentHash is provided' };
124
- }
125
- if (!data.reference.type || typeof data.reference.type !== 'string') {
126
- return { valid: false, error: 'reference.type is required when neither content nor contentHash is provided' };
127
- }
128
- }
129
- break;
130
- case 'nft-ownership':
131
- // ownerAddress is optional; server injects from request walletAddress when omitted.
132
- if (
133
- !data.contractAddress ||
134
- data.tokenId === null ||
135
- data.tokenId === undefined ||
136
- typeof data.chainId !== 'number'
137
- ) {
138
- return { valid: false, error: 'contractAddress, tokenId, and chainId are required' };
139
- }
140
- if (data.tokenType !== undefined && data.tokenType !== null) {
141
- const tt = String(data.tokenType).toLowerCase();
142
- if (tt !== 'erc721' && tt !== 'erc1155') {
143
- return { valid: false, error: 'tokenType must be one of: erc721, erc1155' };
144
- }
145
- }
146
- if (data.blockNumber !== undefined && data.blockNumber !== null && !Number.isInteger(data.blockNumber)) {
147
- return { valid: false, error: 'blockNumber must be an integer when provided' };
148
- }
149
- if (data.ownerAddress && !validateWalletAddress(data.ownerAddress)) {
150
- return { valid: false, error: 'Invalid ownerAddress' };
151
- }
152
- if (!validateWalletAddress(data.contractAddress)) {
153
- return { valid: false, error: 'Invalid contractAddress' };
154
- }
155
- break;
156
- case 'token-holding':
157
- // ownerAddress is optional; server injects from request walletAddress when omitted.
158
- if (
159
- !data.contractAddress ||
160
- data.minBalance === null ||
161
- data.minBalance === undefined ||
162
- typeof data.chainId !== 'number'
163
- ) {
164
- return { valid: false, error: 'contractAddress, minBalance, and chainId are required' };
165
- }
166
- if (data.blockNumber !== undefined && data.blockNumber !== null && !Number.isInteger(data.blockNumber)) {
167
- return { valid: false, error: 'blockNumber must be an integer when provided' };
168
- }
169
- if (data.ownerAddress && !validateWalletAddress(data.ownerAddress)) {
170
- return { valid: false, error: 'Invalid ownerAddress' };
171
- }
172
- if (!validateWalletAddress(data.contractAddress)) {
173
- return { valid: false, error: 'Invalid contractAddress' };
174
- }
175
- break;
176
- case 'ownership-dns-txt':
177
- if (!data.domain || typeof data.domain !== 'string') {
178
- return { valid: false, error: 'domain is required' };
179
- }
180
- if (data.walletAddress && !validateWalletAddress(data.walletAddress)) {
181
- return { valid: false, error: 'Invalid walletAddress' };
182
- }
183
- break;
184
- case 'wallet-link':
185
- if (!data.primaryWalletAddress || !validateUniversalAddress(data.primaryWalletAddress, data.chain)) {
186
- return { valid: false, error: 'primaryWalletAddress is required' };
187
- }
188
- if (!data.secondaryWalletAddress || !validateUniversalAddress(data.secondaryWalletAddress, data.chain)) {
189
- return { valid: false, error: 'secondaryWalletAddress is required' };
190
- }
191
- if (!data.signature || typeof data.signature !== 'string') {
192
- return { valid: false, error: 'signature is required (signed by secondary wallet)' };
193
- }
194
- if (typeof data.chain !== 'string' || !/^[a-z0-9]+:[^\s]+$/.test(data.chain)) {
195
- return { valid: false, error: 'chain is required (namespace:reference)' };
196
- }
197
- if (typeof data.signatureMethod !== 'string' || !data.signatureMethod.trim()) {
198
- return { valid: false, error: 'signatureMethod is required' };
199
- }
200
- if (typeof data.signedTimestamp !== 'number') {
201
- return { valid: false, error: 'signedTimestamp is required' };
202
- }
203
- break;
204
- case 'contract-ownership':
205
- if (!data.contractAddress || !validateWalletAddress(data.contractAddress)) {
206
- return { valid: false, error: 'contractAddress is required' };
207
- }
208
- if (data.walletAddress && !validateWalletAddress(data.walletAddress)) {
209
- return { valid: false, error: 'Invalid walletAddress' };
210
- }
211
- if (typeof data.chainId !== 'number') {
212
- return { valid: false, error: 'chainId is required' };
213
- }
214
- break;
215
- case 'agent-identity':
216
- if (!data.agentId || typeof data.agentId !== 'string' || data.agentId.length < 1 || data.agentId.length > 128) {
217
- return { valid: false, error: 'agentId is required (1-128 chars)' };
218
- }
219
- if (!data.agentWallet || !validateWalletAddress(data.agentWallet)) {
220
- return { valid: false, error: 'agentWallet is required' };
221
- }
222
- if (data.agentType && !['ai', 'bot', 'service', 'automation', 'agent'].includes(data.agentType)) {
223
- return { valid: false, error: 'agentType must be one of: ai, bot, service, automation, agent' };
224
- }
225
- break;
226
- case 'agent-delegation':
227
- if (!data.controllerWallet || !validateWalletAddress(data.controllerWallet)) {
228
- return { valid: false, error: 'controllerWallet is required' };
229
- }
230
- if (!data.agentWallet || !validateWalletAddress(data.agentWallet)) {
231
- return { valid: false, error: 'agentWallet is required' };
232
- }
233
- if (data.scope && (typeof data.scope !== 'string' || data.scope.length > 128)) {
234
- return { valid: false, error: 'scope must be a string (max 128 chars)' };
235
- }
236
- if (data.expiresAt && (typeof data.expiresAt !== 'number' || data.expiresAt < Date.now())) {
237
- return { valid: false, error: 'expiresAt must be a future timestamp' };
238
- }
239
- break;
240
- case 'ai-content-moderation':
241
- if (!data.content || typeof data.content !== 'string') {
242
- return { valid: false, error: 'content is required' };
243
- }
244
- if (!data.contentType || typeof data.contentType !== 'string') {
245
- return { valid: false, error: 'contentType (MIME type) is required' };
246
- }
247
- {
248
- // Only allow content types that are actually moderated (no "verified but skipped" bypass).
249
- const contentType = String(data.contentType).split(';')[0].trim().toLowerCase();
250
- const validTypes = [
251
- 'image/jpeg',
252
- 'image/png',
253
- 'image/webp',
254
- 'image/gif',
255
- 'text/plain',
256
- 'text/markdown',
257
- 'text/x-markdown',
258
- 'application/json',
259
- 'application/xml'
260
- ];
261
- if (!validTypes.includes(contentType)) {
262
- return { valid: false, error: `contentType must be one of: ${validTypes.join(', ')}` };
263
- }
264
- const isTextual = contentType.startsWith('text/') || contentType.includes('markdown');
265
- if (isTextual) {
266
- // Backend enforces 50KB UTF-8 limit for textual moderation payloads.
267
- try {
268
- const maxBytes = 50 * 1024;
269
- const bytes = (typeof TextEncoder !== 'undefined')
270
- ? new TextEncoder().encode(data.content).length
271
- : String(data.content).length;
272
- if (bytes > maxBytes) {
273
- return {
274
- valid: false,
275
- error: `content exceeds ${maxBytes} bytes limit for ai-content-moderation verifier (text)`
276
- };
277
- }
278
- } catch {
279
- // If encoding fails, defer to server.
280
- }
281
- }
282
- }
283
- if (data.content.length > 13653334) {
284
- return { valid: false, error: 'content exceeds 10MB limit' };
285
- }
286
- break;
287
- case 'ownership-pseudonym':
288
- if (!data.pseudonymId || typeof data.pseudonymId !== 'string') {
289
- return { valid: false, error: 'pseudonymId is required' };
290
- }
291
- // Validate handle format (3-64 chars, lowercase alphanumeric with ._-)
292
- if (!/^[a-z0-9._-]{3,64}$/.test(data.pseudonymId.trim().toLowerCase())) {
293
- return { valid: false, error: 'pseudonymId must be 3-64 characters, lowercase alphanumeric with dots, underscores, or hyphens' };
294
- }
295
- // Validate namespace if provided (1-64 chars)
296
- if (data.namespace && typeof data.namespace === 'string') {
297
- if (!/^[a-z0-9._-]{1,64}$/.test(data.namespace.trim().toLowerCase())) {
298
- return { valid: false, error: 'namespace must be 1-64 characters, lowercase alphanumeric with dots, underscores, or hyphens' };
299
- }
300
- }
301
- // Note: signature is not required - envelope signature provides authentication
302
- break;
303
- case 'wallet-risk':
304
- if (data.walletAddress && !validateUniversalAddress(data.walletAddress, data.chain)) {
305
- return { valid: false, error: 'Invalid walletAddress' };
306
- }
307
- break;
308
- }
309
-
310
- return { valid: true };
311
- };
312
-
313
- export class NeusClient {
314
- constructor(config = {}) {
315
- this.config = {
316
- timeout: 30000,
317
- enableLogging: false,
318
- ...config
319
- };
320
-
321
- this.baseUrl = this.config.apiUrl || 'https://api.neus.network';
322
- // Enforce HTTPS for neus.network domains to satisfy CSP and normalize URLs
323
- try {
324
- const url = new URL(this.baseUrl);
325
- if (url.hostname.endsWith('neus.network') && url.protocol === 'http:') {
326
- url.protocol = 'https:';
327
- }
328
- // Always remove trailing slash for consistency
329
- this.baseUrl = url.toString().replace(/\/$/, '');
330
- } catch {
331
- // If invalid URL string, leave as-is
332
- }
333
- this.config.apiUrl = this.baseUrl;
334
-
335
- // Default headers
336
-
337
- this.defaultHeaders = {
338
- 'Content-Type': 'application/json',
339
- 'Accept': 'application/json',
340
- 'X-Neus-Sdk': 'js'
341
- };
342
-
343
- if (typeof this.config.apiKey === 'string' && this.config.apiKey.trim().length > 0) {
344
- this.defaultHeaders['Authorization'] = `Bearer ${this.config.apiKey.trim()}`;
345
- }
346
- if (typeof this.config.appId === 'string' && this.config.appId.trim().length > 0) {
347
- this.defaultHeaders['X-Neus-App'] = this.config.appId.trim();
348
- }
35
+
36
+ /**
37
+ * @param {unknown} raw
38
+ * @returns {string | null} Non-empty trimmed string, or null if the provider value is not a valid string identity.
39
+ */
40
+ function normalizeBrowserSignerString(raw) {
41
+ if (raw === null || raw === undefined) {
42
+ return null;
43
+ }
44
+ if (typeof raw === 'string') {
45
+ const t = raw.trim();
46
+ return t.length > 0 ? t : null;
47
+ }
48
+ return null;
49
+ }
50
+
51
+ const validateVerifierData = (verifierId, data) => {
52
+ if (!data || typeof data !== 'object') {
53
+ return { valid: false, error: 'Data object is required' };
54
+ }
55
+
56
+ switch (verifierId) {
57
+ case 'ownership-basic':
58
+ if (!data.owner || !validateUniversalAddress(data.owner, typeof data.chain === 'string' ? data.chain : undefined)) {
59
+ return { valid: false, error: 'owner (universal wallet address) is required' };
60
+ }
61
+ if (data.content !== undefined && data.content !== null) {
62
+ if (typeof data.content !== 'string') {
63
+ return { valid: false, error: 'content must be a string when provided' };
64
+ }
65
+ if (data.content.length > 50000) {
66
+ return { valid: false, error: 'content exceeds 50KB inline limit' };
67
+ }
68
+ }
69
+ if (data.contentHash !== undefined && data.contentHash !== null) {
70
+ if (typeof data.contentHash !== 'string' || !/^0x[a-fA-F0-9]{64}$/.test(data.contentHash)) {
71
+ return { valid: false, error: 'contentHash must be a 32-byte hex string (0x + 64 hex chars) when provided' };
72
+ }
73
+ }
74
+ if (data.contentType !== undefined && data.contentType !== null) {
75
+ if (typeof data.contentType !== 'string' || data.contentType.length > 100) {
76
+ return { valid: false, error: 'contentType must be a string (max 100 chars) when provided' };
77
+ }
78
+ const base = String(data.contentType).split(';')[0].trim().toLowerCase();
79
+ if (!base || base.includes(' ') || !base.includes('/')) {
80
+ return { valid: false, error: 'contentType must be a valid MIME type when provided' };
81
+ }
82
+ }
83
+ if (data.provenance !== undefined && data.provenance !== null) {
84
+ if (!data.provenance || typeof data.provenance !== 'object' || Array.isArray(data.provenance)) {
85
+ return { valid: false, error: 'provenance must be an object when provided' };
86
+ }
87
+ const dk = data.provenance.declaredKind;
88
+ if (dk !== undefined && dk !== null) {
89
+ const allowed = ['human', 'ai', 'mixed', 'unknown'];
90
+ if (typeof dk !== 'string' || !allowed.includes(dk)) {
91
+ return { valid: false, error: `provenance.declaredKind must be one of: ${allowed.join(', ')}` };
92
+ }
93
+ }
94
+ const ai = data.provenance.aiContext;
95
+ if (ai !== undefined && ai !== null) {
96
+ if (typeof ai !== 'object' || Array.isArray(ai)) {
97
+ return { valid: false, error: 'provenance.aiContext must be an object when provided' };
98
+ }
99
+ if (ai.generatorType !== undefined && ai.generatorType !== null) {
100
+ const allowed = ['local', 'saas', 'agent'];
101
+ if (typeof ai.generatorType !== 'string' || !allowed.includes(ai.generatorType)) {
102
+ return { valid: false, error: `provenance.aiContext.generatorType must be one of: ${allowed.join(', ')}` };
103
+ }
104
+ }
105
+ if (ai.provider !== undefined && ai.provider !== null) {
106
+ if (typeof ai.provider !== 'string' || ai.provider.length > 64) {
107
+ return { valid: false, error: 'provenance.aiContext.provider must be a string (max 64 chars) when provided' };
108
+ }
109
+ }
110
+ if (ai.model !== undefined && ai.model !== null) {
111
+ if (typeof ai.model !== 'string' || ai.model.length > 128) {
112
+ return { valid: false, error: 'provenance.aiContext.model must be a string (max 128 chars) when provided' };
113
+ }
114
+ }
115
+ if (ai.runId !== undefined && ai.runId !== null) {
116
+ if (typeof ai.runId !== 'string' || ai.runId.length > 128) {
117
+ return { valid: false, error: 'provenance.aiContext.runId must be a string (max 128 chars) when provided' };
118
+ }
119
+ }
120
+ }
121
+ }
122
+ if (data.reference !== undefined) {
123
+ if (!data.reference || typeof data.reference !== 'object') {
124
+ return { valid: false, error: 'reference must be an object when provided' };
125
+ }
126
+ if (!data.reference.type || typeof data.reference.type !== 'string') {
127
+ return { valid: false, error: 'reference.type is required when reference is provided' };
128
+ }
129
+ }
130
+ if (!data.content && !data.contentHash) {
131
+ if (!data.reference || typeof data.reference !== 'object') {
132
+ return { valid: false, error: 'reference is required when neither content nor contentHash is provided' };
133
+ }
134
+ if (!data.reference.id || typeof data.reference.id !== 'string') {
135
+ return { valid: false, error: 'reference.id is required when neither content nor contentHash is provided' };
136
+ }
137
+ if (!data.reference.type || typeof data.reference.type !== 'string') {
138
+ return { valid: false, error: 'reference.type is required when neither content nor contentHash is provided' };
139
+ }
140
+ }
141
+ break;
142
+ case 'nft-ownership':
143
+ if (
144
+ !data.contractAddress ||
145
+ data.tokenId === null ||
146
+ data.tokenId === undefined ||
147
+ typeof data.chainId !== 'number'
148
+ ) {
149
+ return { valid: false, error: 'contractAddress, tokenId, and chainId are required' };
150
+ }
151
+ if (data.tokenType !== undefined && data.tokenType !== null) {
152
+ const tt = String(data.tokenType).toLowerCase();
153
+ if (tt !== 'erc721' && tt !== 'erc1155') {
154
+ return { valid: false, error: 'tokenType must be one of: erc721, erc1155' };
155
+ }
156
+ }
157
+ if (data.blockNumber !== undefined && data.blockNumber !== null && !Number.isInteger(data.blockNumber)) {
158
+ return { valid: false, error: 'blockNumber must be an integer when provided' };
159
+ }
160
+ if (data.ownerAddress && !validateWalletAddress(data.ownerAddress)) {
161
+ return { valid: false, error: 'Invalid ownerAddress' };
162
+ }
163
+ if (!validateWalletAddress(data.contractAddress)) {
164
+ return { valid: false, error: 'Invalid contractAddress' };
165
+ }
166
+ break;
167
+ case 'token-holding':
168
+ if (
169
+ !data.contractAddress ||
170
+ data.minBalance === null ||
171
+ data.minBalance === undefined ||
172
+ typeof data.chainId !== 'number'
173
+ ) {
174
+ return { valid: false, error: 'contractAddress, minBalance, and chainId are required' };
175
+ }
176
+ if (data.blockNumber !== undefined && data.blockNumber !== null && !Number.isInteger(data.blockNumber)) {
177
+ return { valid: false, error: 'blockNumber must be an integer when provided' };
178
+ }
179
+ if (data.ownerAddress && !validateWalletAddress(data.ownerAddress)) {
180
+ return { valid: false, error: 'Invalid ownerAddress' };
181
+ }
182
+ if (!validateWalletAddress(data.contractAddress)) {
183
+ return { valid: false, error: 'Invalid contractAddress' };
184
+ }
185
+ break;
186
+ case 'ownership-dns-txt':
187
+ if (!data.domain || typeof data.domain !== 'string') {
188
+ return { valid: false, error: 'domain is required' };
189
+ }
190
+ if (data.walletAddress && !validateWalletAddress(data.walletAddress)) {
191
+ return { valid: false, error: 'Invalid walletAddress' };
192
+ }
193
+ break;
194
+ case 'wallet-link':
195
+ if (!data.primaryWalletAddress || !validateUniversalAddress(data.primaryWalletAddress, data.chain)) {
196
+ return { valid: false, error: 'primaryWalletAddress is required' };
197
+ }
198
+ if (!data.secondaryWalletAddress || !validateUniversalAddress(data.secondaryWalletAddress, data.chain)) {
199
+ return { valid: false, error: 'secondaryWalletAddress is required' };
200
+ }
201
+ if (!data.signature || typeof data.signature !== 'string') {
202
+ return { valid: false, error: 'signature is required (signed by secondary wallet)' };
203
+ }
204
+ if (typeof data.chain !== 'string' || !/^[a-z0-9]+:[^\s]+$/.test(data.chain)) {
205
+ return { valid: false, error: 'chain is required (namespace:reference)' };
206
+ }
207
+ if (typeof data.signatureMethod !== 'string' || !data.signatureMethod.trim()) {
208
+ return { valid: false, error: 'signatureMethod is required' };
209
+ }
210
+ if (typeof data.signedTimestamp !== 'number') {
211
+ return { valid: false, error: 'signedTimestamp is required' };
212
+ }
213
+ break;
214
+ case 'contract-ownership':
215
+ if (!data.contractAddress || !validateWalletAddress(data.contractAddress)) {
216
+ return { valid: false, error: 'contractAddress is required' };
217
+ }
218
+ if (data.walletAddress && !validateWalletAddress(data.walletAddress)) {
219
+ return { valid: false, error: 'Invalid walletAddress' };
220
+ }
221
+ if (typeof data.chainId !== 'number') {
222
+ return { valid: false, error: 'chainId is required' };
223
+ }
224
+ break;
225
+ case 'agent-identity':
226
+ if (!data.agentId || typeof data.agentId !== 'string' || data.agentId.length < 1 || data.agentId.length > 128) {
227
+ return { valid: false, error: 'agentId is required (1-128 chars)' };
228
+ }
229
+ if (!data.agentWallet || !validateWalletAddress(data.agentWallet)) {
230
+ return { valid: false, error: 'agentWallet is required' };
231
+ }
232
+ if (data.agentType && !['ai', 'bot', 'service', 'automation', 'agent'].includes(data.agentType)) {
233
+ return { valid: false, error: 'agentType must be one of: ai, bot, service, automation, agent' };
234
+ }
235
+ break;
236
+ case 'agent-delegation':
237
+ if (!data.controllerWallet || !validateWalletAddress(data.controllerWallet)) {
238
+ return { valid: false, error: 'controllerWallet is required' };
239
+ }
240
+ if (!data.agentWallet || !validateWalletAddress(data.agentWallet)) {
241
+ return { valid: false, error: 'agentWallet is required' };
242
+ }
243
+ if (data.scope && (typeof data.scope !== 'string' || data.scope.length > 128)) {
244
+ return { valid: false, error: 'scope must be a string (max 128 chars)' };
245
+ }
246
+ if (data.expiresAt && (typeof data.expiresAt !== 'number' || data.expiresAt < Date.now())) {
247
+ return { valid: false, error: 'expiresAt must be a future timestamp' };
248
+ }
249
+ break;
250
+ case 'ai-content-moderation':
251
+ if (!data.content || typeof data.content !== 'string') {
252
+ return { valid: false, error: 'content is required' };
253
+ }
254
+ if (!data.contentType || typeof data.contentType !== 'string') {
255
+ return { valid: false, error: 'contentType (MIME type) is required' };
256
+ }
257
+ {
258
+ const contentType = String(data.contentType).split(';')[0].trim().toLowerCase();
259
+ const validTypes = [
260
+ 'image/jpeg',
261
+ 'image/png',
262
+ 'image/webp',
263
+ 'image/gif',
264
+ 'text/plain',
265
+ 'text/markdown',
266
+ 'text/x-markdown',
267
+ 'application/json',
268
+ 'application/xml'
269
+ ];
270
+ if (!validTypes.includes(contentType)) {
271
+ return { valid: false, error: `contentType must be one of: ${validTypes.join(', ')}` };
272
+ }
273
+ const isTextual = contentType.startsWith('text/') || contentType.includes('markdown');
274
+ if (isTextual) {
275
+ try {
276
+ const maxBytes = 50 * 1024;
277
+ const bytes = (typeof TextEncoder !== 'undefined')
278
+ ? new TextEncoder().encode(data.content).length
279
+ : String(data.content).length;
280
+ if (bytes > maxBytes) {
281
+ return {
282
+ valid: false,
283
+ error: `content exceeds ${maxBytes} bytes limit for ai-content-moderation verifier (text)`
284
+ };
285
+ }
286
+ } catch {
287
+ void 0;
288
+ }
289
+ }
290
+ }
291
+ if (data.content.length > 13653334) {
292
+ return { valid: false, error: 'content exceeds 10MB limit' };
293
+ }
294
+ break;
295
+ case 'ownership-pseudonym':
296
+ if (!data.pseudonymId || typeof data.pseudonymId !== 'string') {
297
+ return { valid: false, error: 'pseudonymId is required' };
298
+ }
299
+ if (!/^[a-z0-9._-]{3,64}$/.test(data.pseudonymId.trim().toLowerCase())) {
300
+ return { valid: false, error: 'pseudonymId must be 3-64 characters, lowercase alphanumeric with dots, underscores, or hyphens' };
301
+ }
302
+ if (data.namespace && typeof data.namespace === 'string') {
303
+ if (!/^[a-z0-9._-]{1,64}$/.test(data.namespace.trim().toLowerCase())) {
304
+ return { valid: false, error: 'namespace must be 1-64 characters, lowercase alphanumeric with dots, underscores, or hyphens' };
305
+ }
306
+ }
307
+ break;
308
+ case 'wallet-risk':
309
+ if (data.walletAddress && !validateUniversalAddress(data.walletAddress, data.chain)) {
310
+ return { valid: false, error: 'Invalid walletAddress' };
311
+ }
312
+ break;
313
+ }
314
+
315
+ return { valid: true };
316
+ };
317
+
318
+ export class NeusClient {
319
+ constructor(config = {}) {
320
+ this.config = {
321
+ timeout: 30000,
322
+ enableLogging: false,
323
+ ...config
324
+ };
325
+
326
+ this.baseUrl = this.config.apiUrl || 'https://api.neus.network';
327
+ try {
328
+ const url = new URL(this.baseUrl);
329
+ if (url.hostname.endsWith('neus.network') && url.protocol === 'http:') {
330
+ url.protocol = 'https:';
331
+ }
332
+ this.baseUrl = url.toString().replace(/\/$/, '');
333
+ } catch {
334
+ void 0;
335
+ }
336
+ this.config.apiUrl = this.baseUrl;
337
+
338
+ this.defaultHeaders = {
339
+ 'Content-Type': 'application/json',
340
+ 'Accept': 'application/json',
341
+ 'X-Neus-Sdk': 'js'
342
+ };
343
+
344
+ if (typeof this.config.apiKey === 'string' && this.config.apiKey.trim().length > 0) {
345
+ this.defaultHeaders['Authorization'] = `Bearer ${this.config.apiKey.trim()}`;
346
+ }
347
+ if (typeof this.config.appId === 'string' && this.config.appId.trim().length > 0) {
348
+ this.defaultHeaders['X-Neus-App'] = this.config.appId.trim();
349
+ }
349
350
  if (typeof this.config.paymentSignature === 'string' && this.config.paymentSignature.trim().length > 0) {
350
351
  this.defaultHeaders['PAYMENT-SIGNATURE'] = this.config.paymentSignature.trim();
351
352
  }
352
- if (this.config.extraHeaders && typeof this.config.extraHeaders === 'object') {
353
- for (const [k, v] of Object.entries(this.config.extraHeaders)) {
354
- if (!k || v === undefined || v === null) continue;
355
- const key = String(k).trim();
356
- const value = String(v).trim();
357
- if (!key || !value) continue;
358
- this.defaultHeaders[key] = value;
359
- }
360
- }
361
- try {
362
- if (typeof window !== 'undefined' && window.location && window.location.origin) {
363
- this.defaultHeaders['X-Client-Origin'] = window.location.origin;
364
- }
365
- } catch {
366
- // ignore: optional browser metadata header
367
- }
368
- }
369
-
370
- _getHubChainId() {
371
- const configured = Number(this.config?.hubChainId);
372
- if (Number.isFinite(configured) && configured > 0) return Math.floor(configured);
373
- return NEUS_CONSTANTS.HUB_CHAIN_ID;
374
- }
375
-
376
- _normalizeIdentity(value) {
377
- let raw = String(value || '').trim();
378
- if (!raw) return '';
379
- const didMatch = raw.match(/^did:pkh:([^:]+):([^:]+):(.+)$/i);
380
- if (didMatch && didMatch[3]) {
381
- raw = String(didMatch[3]).trim();
382
- }
383
- return EVM_ADDRESS_RE.test(raw) ? raw.toLowerCase() : raw;
384
- }
385
-
386
- _inferChainForAddress(address, explicitChain) {
387
- if (typeof explicitChain === 'string' && explicitChain.includes(':')) return explicitChain.trim();
388
- const raw = String(address || '').trim();
389
- const didMatch = raw.match(/^did:pkh:([^:]+):([^:]+):(.+)$/i);
390
- if (didMatch && didMatch[1] && didMatch[2]) {
391
- return `${didMatch[1]}:${didMatch[2]}`;
392
- }
393
- if (EVM_ADDRESS_RE.test(raw)) {
394
- return `eip155:${this._getHubChainId()}`;
395
- }
396
- // Default non-EVM chain for universal wallet paths when caller omits chain.
397
- return 'solana:mainnet';
398
- }
399
-
400
- async _resolveWalletSigner(wallet) {
401
- if (!wallet) {
402
- throw new ConfigurationError('No wallet provider available');
403
- }
404
-
405
- if (wallet.address) {
406
- return { signerWalletAddress: wallet.address, provider: wallet };
407
- }
408
- if (wallet.publicKey && typeof wallet.publicKey.toBase58 === 'function') {
409
- return { signerWalletAddress: wallet.publicKey.toBase58(), provider: wallet };
410
- }
411
- if (typeof wallet.getAddress === 'function') {
412
- const signerWalletAddress = await wallet.getAddress().catch(() => null);
413
- return { signerWalletAddress, provider: wallet };
414
- }
415
- if (wallet.selectedAddress || wallet.request) {
416
- const provider = wallet;
417
- if (wallet.selectedAddress) {
418
- return { signerWalletAddress: wallet.selectedAddress, provider };
419
- }
420
- const accounts = await provider.request({ method: 'eth_accounts' });
421
- if (!accounts || accounts.length === 0) {
422
- throw new ConfigurationError('No wallet accounts available');
423
- }
424
- return { signerWalletAddress: accounts[0], provider };
425
- }
426
-
427
- throw new ConfigurationError('Invalid wallet provider');
428
- }
429
-
430
- _getDefaultBrowserWallet() {
431
- if (typeof window === 'undefined') return null;
432
- return window.ethereum || window.solana || (window.phantom && window.phantom.solana) || null;
433
- }
434
-
435
- async _buildPrivateGateAuth({ address, wallet, chain, signatureMethod } = {}) {
436
- const providerWallet = wallet || this._getDefaultBrowserWallet();
437
- const { signerWalletAddress, provider } = await this._resolveWalletSigner(providerWallet);
438
- if (!signerWalletAddress || typeof signerWalletAddress !== 'string') {
439
- throw new ConfigurationError('No wallet accounts available');
440
- }
441
-
442
- const normalizedSigner = this._normalizeIdentity(signerWalletAddress);
443
- const normalizedAddress = this._normalizeIdentity(address);
444
- if (!normalizedSigner || normalizedSigner !== normalizedAddress) {
445
- throw new ValidationError('wallet must match address when includePrivate=true');
446
- }
447
-
448
- const signerIsEvm = EVM_ADDRESS_RE.test(normalizedSigner);
449
- const resolvedChain = this._inferChainForAddress(normalizedSigner, chain);
450
- const resolvedSignatureMethod = (typeof signatureMethod === 'string' && signatureMethod.trim())
451
- ? signatureMethod.trim()
452
- : (signerIsEvm ? 'eip191' : 'ed25519');
453
-
454
- const signedTimestamp = Date.now();
455
- const message = constructVerificationMessage({
456
- walletAddress: signerWalletAddress,
457
- signedTimestamp,
458
- data: { action: 'gate_check_private_proofs', walletAddress: normalizedAddress },
459
- verifierIds: ['ownership-basic'],
460
- ...(signerIsEvm ? { chainId: this._getHubChainId() } : { chain: resolvedChain })
461
- });
462
-
463
- let signature;
464
- try {
465
- signature = await signMessage({
466
- provider,
467
- message,
468
- walletAddress: signerWalletAddress,
469
- ...(signerIsEvm ? {} : { chain: resolvedChain })
470
- });
471
- } catch (error) {
472
- if (error.code === 4001) {
473
- throw new ValidationError('User rejected signature request');
474
- }
475
- throw new ValidationError(`Failed to sign message: ${error.message}`);
476
- }
477
-
478
- return {
479
- walletAddress: signerWalletAddress,
480
- signature,
481
- signedTimestamp,
482
- ...(signerIsEvm ? {} : { chain: resolvedChain, signatureMethod: resolvedSignatureMethod })
483
- };
484
- }
485
-
353
+ if (this.config.extraHeaders && typeof this.config.extraHeaders === 'object') {
354
+ for (const [k, v] of Object.entries(this.config.extraHeaders)) {
355
+ if (!k || v === undefined || v === null) continue;
356
+ const key = String(k).trim();
357
+ const value = String(v).trim();
358
+ if (!key || !value) continue;
359
+ this.defaultHeaders[key] = value;
360
+ }
361
+ }
362
+ try {
363
+ if (typeof window !== 'undefined' && window.location && window.location.origin) {
364
+ this.defaultHeaders['X-Client-Origin'] = window.location.origin;
365
+ }
366
+ } catch {
367
+ void 0;
368
+ }
369
+ }
370
+
371
+ _getHubChainId() {
372
+ const configured = Number(this.config?.hubChainId);
373
+ if (Number.isFinite(configured) && configured > 0) return Math.floor(configured);
374
+ return NEUS_CONSTANTS.HUB_CHAIN_ID;
375
+ }
376
+
377
+ _normalizeIdentity(value) {
378
+ let raw = String(value || '').trim();
379
+ if (!raw) return '';
380
+ const didMatch = raw.match(/^did:pkh:([^:]+):([^:]+):(.+)$/i);
381
+ if (didMatch && didMatch[3]) {
382
+ raw = String(didMatch[3]).trim();
383
+ }
384
+ return EVM_ADDRESS_RE.test(raw) ? raw.toLowerCase() : raw;
385
+ }
386
+
387
+ _inferChainForAddress(address, explicitChain) {
388
+ if (typeof explicitChain === 'string' && explicitChain.includes(':')) return explicitChain.trim();
389
+ const raw = String(address || '').trim();
390
+ const didMatch = raw.match(/^did:pkh:([^:]+):([^:]+):(.+)$/i);
391
+ if (didMatch && didMatch[1] && didMatch[2]) {
392
+ return `${didMatch[1]}:${didMatch[2]}`;
393
+ }
394
+ if (EVM_ADDRESS_RE.test(raw)) {
395
+ return `eip155:${this._getHubChainId()}`;
396
+ }
397
+ return 'solana:mainnet';
398
+ }
399
+
400
+ async _resolveWalletSigner(wallet) {
401
+ if (!wallet) {
402
+ throw new ConfigurationError('No wallet provider available');
403
+ }
404
+
405
+ if (wallet.address !== null && wallet.address !== undefined) {
406
+ const s = normalizeBrowserSignerString(
407
+ typeof wallet.address === 'string' ? wallet.address : null
408
+ );
409
+ if (s) {
410
+ return { signerWalletAddress: s, provider: wallet };
411
+ }
412
+ }
413
+ if (wallet.publicKey && typeof wallet.publicKey.toBase58 === 'function') {
414
+ const b58 = wallet.publicKey.toBase58();
415
+ const s = normalizeBrowserSignerString(typeof b58 === 'string' ? b58 : null);
416
+ if (s) {
417
+ return { signerWalletAddress: s, provider: wallet };
418
+ }
419
+ }
420
+ if (typeof wallet.getAddress === 'function') {
421
+ const got = await wallet.getAddress().catch(() => null);
422
+ const s = normalizeBrowserSignerString(
423
+ got === null || got === undefined ? null : (typeof got === 'string' ? got : null)
424
+ );
425
+ if (s) {
426
+ return { signerWalletAddress: s, provider: wallet };
427
+ }
428
+ }
429
+ if (wallet.selectedAddress || wallet.request) {
430
+ const provider = wallet;
431
+ if (wallet.selectedAddress) {
432
+ const s = normalizeBrowserSignerString(
433
+ typeof wallet.selectedAddress === 'string' ? wallet.selectedAddress : null
434
+ );
435
+ if (s) {
436
+ return { signerWalletAddress: s, provider };
437
+ }
438
+ }
439
+ const accounts = await provider.request({ method: 'eth_accounts' });
440
+ if (!accounts || accounts.length === 0) {
441
+ throw new ConfigurationError('No wallet accounts available');
442
+ }
443
+ const s = normalizeBrowserSignerString(accounts[0]);
444
+ if (!s) {
445
+ throw new ConfigurationError('No wallet accounts available');
446
+ }
447
+ return { signerWalletAddress: s, provider };
448
+ }
449
+
450
+ throw new ConfigurationError('Invalid wallet provider');
451
+ }
452
+
453
+ _getDefaultBrowserWallet() {
454
+ if (typeof window === 'undefined') return null;
455
+ return window.ethereum || window.solana || (window.phantom && window.phantom.solana) || null;
456
+ }
457
+
458
+ async _buildPrivateGateAuth({ address, wallet, chain, signatureMethod } = {}) {
459
+ const providerWallet = wallet || this._getDefaultBrowserWallet();
460
+ const { signerWalletAddress, provider } = await this._resolveWalletSigner(providerWallet);
461
+ if (!signerWalletAddress || typeof signerWalletAddress !== 'string') {
462
+ throw new ConfigurationError('No wallet accounts available');
463
+ }
464
+
465
+ const normalizedSigner = this._normalizeIdentity(signerWalletAddress);
466
+ const normalizedAddress = this._normalizeIdentity(address);
467
+ if (!normalizedSigner || normalizedSigner !== normalizedAddress) {
468
+ throw new ValidationError('wallet must match address when includePrivate=true');
469
+ }
470
+
471
+ const signerIsEvm = EVM_ADDRESS_RE.test(normalizedSigner);
472
+ const resolvedChain = this._inferChainForAddress(normalizedSigner, chain);
473
+ const resolvedSignatureMethod = (typeof signatureMethod === 'string' && signatureMethod.trim())
474
+ ? signatureMethod.trim()
475
+ : (signerIsEvm ? 'eip191' : 'ed25519');
476
+
477
+ const signedTimestamp = Date.now();
478
+ const message = constructVerificationMessage({
479
+ walletAddress: signerWalletAddress,
480
+ signedTimestamp,
481
+ data: { action: 'gate_check_private_proofs', walletAddress: normalizedAddress },
482
+ verifierIds: ['ownership-basic'],
483
+ ...(signerIsEvm ? { chainId: this._getHubChainId() } : { chain: resolvedChain })
484
+ });
485
+
486
+ let signature;
487
+ try {
488
+ signature = await signMessage({
489
+ provider,
490
+ message,
491
+ walletAddress: signerWalletAddress,
492
+ ...(signerIsEvm ? {} : { chain: resolvedChain })
493
+ });
494
+ } catch (error) {
495
+ if (error.code === 4001) {
496
+ throw new ValidationError('User rejected signature request');
497
+ }
498
+ throw new ValidationError(`Failed to sign message: ${error.message}`);
499
+ }
500
+
501
+ return {
502
+ walletAddress: signerWalletAddress,
503
+ signature,
504
+ signedTimestamp,
505
+ ...(signerIsEvm ? {} : { chain: resolvedChain, signatureMethod: resolvedSignatureMethod })
506
+ };
507
+ }
508
+
486
509
  async createGatePrivateAuth(params = {}) {
487
510
  const address = (params.address || '').toString();
488
511
  if (!validateUniversalAddress(address, params.chain)) {
489
512
  throw new ValidationError('Valid address is required');
490
513
  }
491
- return this._buildPrivateGateAuth({
492
- address,
493
- wallet: params.wallet,
494
- chain: params.chain,
514
+ return this._buildPrivateGateAuth({
515
+ address,
516
+ wallet: params.wallet,
517
+ chain: params.chain,
495
518
  signatureMethod: params.signatureMethod
496
519
  });
497
520
  }
@@ -572,1469 +595,1243 @@ export class NeusClient {
572
595
  };
573
596
  }
574
597
 
575
- /**
576
- * Create a verification proof.
577
- *
578
- * Supports two paths:
579
- * - **Auto:** Supply `verifier`, `content`, and/or `data` with an optional
580
- * `wallet` provider. The SDK performs signing in the client.
581
- * - **Manual:** Supply pre-signed `verifierIds`, `data`, `walletAddress`,
582
- * `signature`, and `signedTimestamp`.
583
- *
584
- * @param {Object} params - Verification parameters
585
- * @param {string} [params.verifier] - Verifier ID (auto path, e.g. 'ownership-basic')
586
- * @param {string} [params.content] - Content to verify (auto path)
587
- * @param {Object} [params.data] - Structured verification data
588
- * @param {Object} [params.wallet] - Wallet provider (auto path)
589
- * @param {Object} [params.options] - Additional options
590
- * @param {Array<string>} [params.verifierIds] - Array of verifier IDs (manual path)
591
- * @param {string} [params.walletAddress] - Wallet address that signed the request (manual path)
592
- * @param {string} [params.signature] - EIP-191 signature (manual path)
593
- * @param {number} [params.signedTimestamp] - Unix timestamp when signature was created (manual path)
594
- * @param {number} [params.chainId] - EVM signing-context hint; when omitted, resolved to the NEUS protocol primary chain for signing
595
- * @returns {Promise<Object>} Verification result with proofId
596
- *
597
- * @example
598
- * // Auto path
599
- * const proof = await client.verify({
600
- * verifier: 'ownership-basic',
601
- * content: 'Hello World',
602
- * wallet: window.ethereum
603
- * });
604
- *
605
- * @example
606
- * // Manual path
607
- * const proof = await client.verify({
608
- * verifierIds: ['ownership-basic'],
609
- * data: { content: "My content", owner: walletAddress },
610
- * walletAddress: '0x...',
611
- * signature: '0x...',
612
- * signedTimestamp: Date.now(),
613
- * options: { targetChains: [421614, 11155111] }
614
- * });
615
- */
616
- async verify(params) {
617
- // Auto path: if no manual signature fields but auto fields are provided, perform inline wallet flow
618
- if ((!params?.signature || !params?.walletAddress) && (params?.verifier || params?.content || params?.data)) {
619
- const { content, verifier = 'ownership-basic', data = null, wallet = null, options = {} } = params;
620
-
621
- // ownership-basic: content required for simple mode, but data param mode allows contentHash or reference
622
- if (verifier === 'ownership-basic' && !data && (!content || typeof content !== 'string')) {
623
- throw new ValidationError('content is required and must be a string (or use data param with owner + reference)');
624
- }
625
-
626
- let verifierCatalog = FALLBACK_PUBLIC_VERIFIER_CATALOG;
627
- try {
628
- const discovered = await this.getVerifierCatalog();
629
- if (discovered && discovered.metadata && Object.keys(discovered.metadata).length > 0) {
630
- verifierCatalog = discovered.metadata;
631
- }
632
- } catch {
633
- // Fallback keeps SDK usable if verifier catalog endpoint is temporarily unavailable.
634
- }
635
- const validVerifiers = Object.keys(verifierCatalog);
636
- if (!validVerifiers.includes(verifier)) {
637
- throw new ValidationError(`Invalid verifier '${verifier}'. Must be one of: ${validVerifiers.join(', ')}.`);
638
- }
639
-
640
- if (verifierCatalog?.[verifier]?.supportsDirectApi === false) {
641
- const hostedCheckoutUrl = options?.hostedCheckoutUrl || 'https://neus.network/verify';
642
- throw new ValidationError(
643
- `${verifier} requires hosted interactive checkout. Use VerifyGate or redirect to ${hostedCheckoutUrl}.`
644
- );
645
- }
646
-
647
- // These verifiers require explicit data parameter (no auto-path)
648
- const requiresDataParam = [
649
- 'ownership-dns-txt',
650
- 'wallet-link',
651
- 'contract-ownership',
652
- 'ownership-pseudonym',
653
- 'wallet-risk',
654
- 'agent-identity',
655
- 'agent-delegation',
656
- 'ai-content-moderation'
657
- ];
658
- if (requiresDataParam.includes(verifier)) {
659
- if (!data || typeof data !== 'object') {
660
- throw new ValidationError(`${verifier} requires explicit data parameter. Cannot use auto-path.`);
661
- }
662
- }
663
-
664
- // Auto-detect wallet and get address
665
- let walletAddress, provider;
666
- if (wallet) {
667
- walletAddress =
668
- wallet.address ||
669
- wallet.selectedAddress ||
670
- wallet.walletAddress ||
671
- (typeof wallet.getAddress === 'function' ? await wallet.getAddress() : null);
672
- provider = wallet.provider || wallet;
673
- if (!walletAddress && provider && typeof provider.request === 'function') {
674
- const accounts = await provider.request({ method: 'eth_accounts' });
675
- walletAddress = Array.isArray(accounts) ? accounts[0] : null;
676
- }
677
- } else {
678
- if (typeof window === 'undefined' || !window.ethereum) {
679
- throw new ConfigurationError('No Web3 wallet detected. Please install MetaMask or provide wallet parameter.');
680
- }
681
- await window.ethereum.request({ method: 'eth_requestAccounts' });
682
- provider = window.ethereum;
683
- const accounts = await provider.request({ method: 'eth_accounts' });
684
- walletAddress = accounts[0];
685
- }
686
-
687
- // Prepare verification data based on verifier type
688
- let verificationData;
689
- if (verifier === 'ownership-basic') {
690
- if (data && typeof data === 'object') {
691
- // Data param mode: use provided data, inject owner if missing
692
- verificationData = {
693
- owner: data.owner || walletAddress,
694
- reference: data.reference,
695
- ...(data.content && { content: data.content }),
696
- ...(data.contentHash && { contentHash: data.contentHash }),
697
- ...(data.contentType && { contentType: data.contentType }),
698
- ...(data.provenance && { provenance: data.provenance })
699
- };
700
- } else {
701
- // Simple content mode: derive reference from content
702
- verificationData = {
703
- content: content,
704
- owner: walletAddress,
705
- reference: { type: 'other' }
706
- };
707
- }
708
- } else if (verifier === 'token-holding') {
709
- if (!data?.contractAddress) {
710
- throw new ValidationError('token-holding requires contractAddress in data parameter');
711
- }
712
- if (data?.minBalance === null || data?.minBalance === undefined) {
713
- throw new ValidationError('token-holding requires minBalance in data parameter');
714
- }
715
- if (typeof data?.chainId !== 'number') {
716
- throw new ValidationError('token-holding requires chainId (number) in data parameter');
717
- }
718
- verificationData = {
719
- ownerAddress: walletAddress,
720
- contractAddress: data.contractAddress,
721
- minBalance: data.minBalance,
722
- chainId: data.chainId
723
- };
724
- } else if (verifier === 'nft-ownership') {
725
- if (!data?.contractAddress) {
726
- throw new ValidationError('nft-ownership requires contractAddress in data parameter');
727
- }
728
- if (data?.tokenId === null || data?.tokenId === undefined) {
729
- throw new ValidationError('nft-ownership requires tokenId in data parameter');
730
- }
731
- if (typeof data?.chainId !== 'number') {
732
- throw new ValidationError('nft-ownership requires chainId (number) in data parameter');
733
- }
734
- verificationData = {
735
- ownerAddress: walletAddress,
736
- contractAddress: data.contractAddress,
737
- tokenId: data.tokenId,
738
- chainId: data.chainId,
739
- tokenType: data?.tokenType || 'erc721'
740
- };
741
- } else if (verifier === 'ownership-dns-txt') {
742
- if (!data?.domain) {
743
- throw new ValidationError('ownership-dns-txt requires domain in data parameter');
744
- }
745
- verificationData = {
746
- domain: data.domain,
747
- walletAddress: walletAddress
748
- };
749
- } else if (verifier === 'wallet-link') {
750
- if (!data?.secondaryWalletAddress) {
751
- throw new ValidationError('wallet-link requires secondaryWalletAddress in data parameter');
752
- }
753
- if (!data?.signature) {
754
- throw new ValidationError('wallet-link requires signature in data parameter (signed by secondary wallet)');
755
- }
756
- if (typeof data?.chain !== 'string' || !/^[a-z0-9]+:[^\s]+$/.test(data.chain)) {
757
- throw new ValidationError('wallet-link requires chain (namespace:reference) in data parameter');
758
- }
759
- if (typeof data?.signatureMethod !== 'string' || !data.signatureMethod.trim()) {
760
- throw new ValidationError('wallet-link requires signatureMethod in data parameter');
761
- }
762
- verificationData = {
763
- primaryWalletAddress: walletAddress,
764
- secondaryWalletAddress: data.secondaryWalletAddress,
765
- signature: data.signature,
766
- chain: data.chain,
767
- signatureMethod: data.signatureMethod,
768
- signedTimestamp: data?.signedTimestamp || Date.now()
769
- };
770
- } else if (verifier === 'contract-ownership') {
771
- if (!data?.contractAddress) {
772
- throw new ValidationError('contract-ownership requires contractAddress in data parameter');
773
- }
774
- if (typeof data?.chainId !== 'number') {
775
- throw new ValidationError('contract-ownership requires chainId (number) in data parameter');
776
- }
777
- verificationData = {
778
- contractAddress: data.contractAddress,
779
- walletAddress: walletAddress,
780
- chainId: data.chainId,
781
- ...(data?.method && { method: data.method })
782
- };
783
- } else if (verifier === 'agent-identity') {
784
- if (!data?.agentId) {
785
- throw new ValidationError('agent-identity requires agentId in data parameter');
786
- }
787
- verificationData = {
788
- agentId: data.agentId,
789
- agentWallet: data?.agentWallet || walletAddress,
790
- ...(data?.agentLabel && { agentLabel: data.agentLabel }),
791
- ...(data?.agentType && { agentType: data.agentType }),
792
- ...(data?.description && { description: data.description }),
793
- ...(data?.capabilities && { capabilities: data.capabilities }),
794
- ...(data?.instructions && { instructions: data.instructions }),
795
- ...(data?.skills && { skills: data.skills }),
796
- ...(data?.services && { services: data.services })
797
- };
798
- } else if (verifier === 'agent-delegation') {
799
- if (!data?.agentWallet) {
800
- throw new ValidationError('agent-delegation requires agentWallet in data parameter');
801
- }
802
- verificationData = {
803
- controllerWallet: data?.controllerWallet || walletAddress,
804
- agentWallet: data.agentWallet,
805
- ...(data?.agentId && { agentId: data.agentId }),
806
- ...(data?.scope && { scope: data.scope }),
807
- ...(data?.permissions && { permissions: data.permissions }),
808
- ...(data?.maxSpend && { maxSpend: data.maxSpend }),
809
- ...(data?.allowedPaymentTypes && { allowedPaymentTypes: data.allowedPaymentTypes }),
810
- ...(data?.receiptDisclosure && { receiptDisclosure: data.receiptDisclosure }),
811
- ...(data?.expiresAt && { expiresAt: data.expiresAt }),
812
- ...(data?.instructions && { instructions: data.instructions }),
813
- ...(data?.skills && { skills: data.skills })
814
- };
815
- } else if (verifier === 'ai-content-moderation') {
816
- if (!data?.content) {
817
- throw new ValidationError('ai-content-moderation requires content (base64) in data parameter');
818
- }
819
- if (!data?.contentType) {
820
- throw new ValidationError('ai-content-moderation requires contentType (MIME type) in data parameter');
821
- }
822
- verificationData = {
823
- content: data.content,
824
- contentType: data.contentType,
825
- ...(data?.provider && { provider: data.provider })
826
- };
827
- } else if (verifier === 'ownership-pseudonym') {
828
- if (!data?.pseudonymId) {
829
- throw new ValidationError('ownership-pseudonym requires pseudonymId in data parameter');
830
- }
831
- verificationData = {
832
- pseudonymId: data.pseudonymId,
833
- ...(data?.namespace && { namespace: data.namespace }),
834
- ...(data?.displayName && { displayName: data.displayName }),
835
- ...(data?.metadata && { metadata: data.metadata })
836
- };
837
- } else if (verifier === 'wallet-risk') {
838
- // wallet-risk defaults to verifying the connected wallet
839
- verificationData = {
840
- walletAddress: data?.walletAddress || walletAddress,
841
- ...(data?.provider && { provider: data.provider }),
842
- // Mainnet-first semantics: if caller doesn't provide chainId, default to Ethereum mainnet (1).
843
- // This avoids accidental testnet semantics for risk providers.
844
- chainId: (typeof data?.chainId === 'number' && Number.isFinite(data.chainId)) ? data.chainId : 1,
845
- ...(data?.includeDetails !== undefined && { includeDetails: data.includeDetails })
846
- };
847
- } else {
848
- verificationData = data ? {
849
- content,
850
- owner: walletAddress,
851
- ...data
852
- } : {
853
- content,
854
- owner: walletAddress
855
- };
856
- }
857
-
858
- const signedTimestamp = Date.now();
859
- const verifierIds = [verifier];
860
- const message = constructVerificationMessage({
861
- walletAddress,
862
- signedTimestamp,
863
- data: verificationData,
864
- verifierIds,
865
- chainId: this._getHubChainId() // Protocol-managed chain
866
- });
867
-
868
- let signature;
869
- try {
870
- const toHexUtf8 = (s) => {
871
- try {
872
- const enc = new TextEncoder();
873
- const bytes = enc.encode(s);
874
- let hex = '0x';
875
- for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, '0');
876
- return hex;
877
- } catch {
878
- let hex = '0x';
879
- for (let i = 0; i < s.length; i++) hex += s.charCodeAt(i).toString(16).padStart(2, '0');
880
- return hex;
881
- }
882
- };
883
-
884
- // Detect Farcaster wallet - requires hex-encoded messages FIRST
885
- const isFarcasterWallet = (() => {
886
- if (typeof window === 'undefined') return false;
887
- try {
888
- const w = window;
889
- const fc = w.farcaster;
890
- if (!fc || !fc.context) return false;
891
- const fcProvider = fc.provider || fc.walletProvider || (fc.context && fc.context.walletProvider);
892
- if (fcProvider === provider) return true;
893
- if (w.mini && w.mini.wallet === provider && fc && fc.context) return true;
894
- if (w.ethereum === provider && fc && fc.context) return true;
895
- } catch {
896
- // ignore: optional Farcaster detection
897
- }
898
- return false;
899
- })();
900
-
901
- if (isFarcasterWallet) {
902
- try {
903
- const hexMsg = toHexUtf8(message);
904
- signature = await provider.request({ method: 'personal_sign', params: [hexMsg, walletAddress] });
905
- } catch (e) {
906
- // Fall through
907
- }
908
- }
909
-
910
- if (!signature) {
911
- try {
912
- signature = await provider.request({ method: 'personal_sign', params: [message, walletAddress] });
913
- } catch (e) {
914
- const msg = String(e && (e.message || e.reason) || e || '').toLowerCase();
915
- const errCode = (e && (e.code || (e.error && e.error.code))) || null;
916
- const needsHex = /byte|bytes|invalid byte sequence|encoding|non-hex/i.test(msg);
917
-
918
- const unsupportedRe =
919
- /method.*not.*supported|unsupported|not implemented|method not found|unknown method|does not support/i;
920
- const methodUnsupported = (
921
- unsupportedRe.test(msg) ||
922
- errCode === -32601 ||
923
- errCode === 4200 ||
924
- (msg.includes('personal_sign') && msg.includes('not')) ||
925
- (msg.includes('request method') && msg.includes('not supported'))
926
- );
927
-
928
- if (methodUnsupported) {
929
- this._log('personal_sign not supported; attempting eth_sign fallback');
930
- try {
931
- const enc = new TextEncoder();
932
- const bytes = enc.encode(message);
933
- const prefix = `\x19Ethereum Signed Message:\n${bytes.length}`;
934
- const full = new Uint8Array(prefix.length + bytes.length);
935
- for (let i = 0; i < prefix.length; i++) full[i] = prefix.charCodeAt(i);
936
- full.set(bytes, prefix.length);
937
- let payloadHex = '0x';
938
- for (let i = 0; i < full.length; i++) payloadHex += full[i].toString(16).padStart(2, '0');
939
- try {
940
- if (typeof window !== 'undefined') window.__NEUS_ALLOW_ETH_SIGN__ = true;
941
- } catch {
942
- // ignore
943
- }
944
- signature = await provider.request({ method: 'eth_sign', params: [walletAddress, payloadHex], neusAllowEthSign: true });
945
- try {
946
- if (typeof window !== 'undefined') delete window.__NEUS_ALLOW_ETH_SIGN__;
947
- } catch {
948
- // ignore
949
- }
950
- } catch (fallbackErr) {
951
- this._log('eth_sign fallback failed', { message: fallbackErr?.message || String(fallbackErr) });
952
- try {
953
- if (typeof window !== 'undefined') delete window.__NEUS_ALLOW_ETH_SIGN__;
954
- } catch {
955
- // ignore
956
- }
957
- throw e;
958
- }
959
- } else if (needsHex) {
960
- this._log('Retrying personal_sign with hex-encoded message');
961
- const hexMsg = toHexUtf8(message);
962
- signature = await provider.request({ method: 'personal_sign', params: [hexMsg, walletAddress] });
963
- } else {
964
- throw e;
965
- }
966
- }
967
- }
968
- } catch (error) {
969
- if (error.code === 4001) {
970
- throw new ValidationError('User rejected the signature request. Signature is required to create proofs.');
971
- }
972
- throw new ValidationError(`Failed to sign verification message: ${error.message}`);
973
- }
974
-
975
- return this.verify({
976
- verifierIds,
977
- data: verificationData,
978
- walletAddress,
979
- signature,
980
- signedTimestamp,
981
- options
982
- });
983
- }
984
-
985
- const {
986
- verifierIds,
987
- data,
988
- walletAddress,
989
- signature,
990
- signedTimestamp,
991
- chainId,
992
- chain,
993
- signatureMethod,
994
- options = {}
995
- } = params;
996
-
997
- const resolvedChainId = chainId || (chain ? null : NEUS_CONSTANTS.HUB_CHAIN_ID);
998
-
999
- // Normalize verifier IDs
1000
- const normalizeVerifierId = (id) => {
1001
- if (typeof id !== 'string') return id;
1002
- const match = id.match(/^(.*)@\d+$/);
1003
- return match ? match[1] : id;
1004
- };
1005
- const normalizedVerifierIds = Array.isArray(verifierIds) ? verifierIds.map(normalizeVerifierId) : [];
1006
-
1007
- // Validate required parameters
1008
- if (!normalizedVerifierIds || normalizedVerifierIds.length === 0) {
1009
- throw new ValidationError('verifierIds array is required');
1010
- }
1011
- if (!data || typeof data !== 'object') {
1012
- throw new ValidationError('data object is required');
1013
- }
1014
- if (!walletAddress || typeof walletAddress !== 'string') {
1015
- throw new ValidationError('walletAddress is required');
1016
- }
1017
- if (!signature) {
1018
- throw new ValidationError('signature is required');
1019
- }
1020
- if (!signedTimestamp || typeof signedTimestamp !== 'number') {
1021
- throw new ValidationError('signedTimestamp is required');
1022
- }
1023
- if (resolvedChainId !== null && typeof resolvedChainId !== 'number') {
1024
- throw new ValidationError('chainId must be a number');
1025
- }
1026
-
1027
- // Validate verifier data
1028
- for (const verifierId of normalizedVerifierIds) {
1029
- const validation = validateVerifierData(verifierId, data);
1030
- if (!validation.valid) {
1031
- throw new ValidationError(`Validation failed for verifier '${verifierId}': ${validation.error}`);
1032
- }
1033
- }
1034
-
1035
- // Build options payload.
1036
- const optionsPayload = {
1037
- ...(options && typeof options === 'object' ? options : {}),
1038
- targetChains: Array.isArray(options?.targetChains) ? options.targetChains : [],
1039
- // Privacy and storage options (defaults)
1040
- privacyLevel: options?.privacyLevel || 'private',
1041
- publicDisplay: options?.publicDisplay || false,
1042
- storeOriginalContent:
1043
- typeof options?.storeOriginalContent === 'boolean' ? options.storeOriginalContent : true
1044
- };
1045
- if (typeof options?.enableIpfs === 'boolean') optionsPayload.enableIpfs = options.enableIpfs;
1046
-
1047
- const requestData = {
1048
- verifierIds: normalizedVerifierIds,
1049
- data,
1050
- walletAddress,
1051
- signature,
1052
- signedTimestamp,
1053
- ...(resolvedChainId !== null && { chainId: resolvedChainId }),
1054
- ...(chain && { chain }),
1055
- ...(signatureMethod && { signatureMethod }),
1056
- options: optionsPayload
1057
- };
1058
-
1059
- const response = await this._makeRequest('POST', '/api/v1/verification', requestData);
1060
-
1061
- if (!response.success) {
1062
- throw new ApiError(`Verification failed: ${response.error?.message || 'Unknown error'}`, response.error);
1063
- }
1064
-
1065
- return this._formatResponse(response);
1066
- }
1067
-
1068
- /**
1069
- * Get proof record by proof receipt id.
1070
- *
1071
- * @param {string} proofId - Proof receipt ID (0x + 64 hex).
1072
- * @returns {Promise<Object>} Proof record and verification state
1073
- *
1074
- * @example
1075
- * const result = await client.getProof('0x...');
1076
- * console.log('Status:', result.status);
1077
- */
1078
- async getProof(proofId) {
1079
- if (!proofId || typeof proofId !== 'string') {
1080
- throw new ValidationError('proofId is required');
1081
- }
1082
- const response = await this._makeRequest('GET', `/api/v1/proofs/${proofId}`);
1083
-
1084
- if (!response.success) {
1085
- throw new ApiError(`Failed to get proof: ${response.error?.message || 'Unknown error'}`, response.error);
1086
- }
1087
-
1088
- return this._formatResponse(response);
1089
- }
1090
-
1091
- /**
1092
- * Get private proof record with wallet signature
1093
- *
1094
- * @param {string} proofId - Proof receipt ID.
1095
- * @param {Object} wallet - Wallet provider (window.ethereum or ethers Wallet)
1096
- * @returns {Promise<Object>} Private proof record and verification state
1097
- *
1098
- * @example
1099
- * const privateData = await client.getPrivateProof(proofId, window.ethereum);
1100
- */
1101
- async getPrivateProof(proofId, wallet = null) {
1102
- if (!proofId || typeof proofId !== 'string') {
1103
- throw new ValidationError('proofId is required');
1104
- }
1105
-
1106
- const isPreSignedAuth = wallet &&
1107
- typeof wallet === 'object' &&
1108
- typeof wallet.walletAddress === 'string' &&
1109
- typeof wallet.signature === 'string' &&
1110
- typeof wallet.signedTimestamp === 'number';
1111
- if (isPreSignedAuth) {
1112
- const auth = wallet;
1113
- const headers = {
1114
- 'x-wallet-address': String(auth.walletAddress),
1115
- 'x-signature': String(auth.signature),
1116
- 'x-signed-timestamp': String(auth.signedTimestamp),
1117
- ...(typeof auth.chain === 'string' && auth.chain.trim() ? { 'x-chain': auth.chain.trim() } : {}),
1118
- ...(typeof auth.signatureMethod === 'string' && auth.signatureMethod.trim() ? { 'x-signature-method': auth.signatureMethod.trim() } : {})
1119
- };
1120
- const response = await this._makeRequest('GET', `/api/v1/proofs/${proofId}`, null, headers);
1121
- if (!response.success) {
1122
- throw new ApiError(
1123
- `Failed to access private proof: ${response.error?.message || 'Unauthorized'}`,
1124
- response.error
1125
- );
1126
- }
1127
- return this._formatResponse(response);
1128
- }
1129
-
1130
- const providerWallet = wallet || this._getDefaultBrowserWallet();
1131
- const { signerWalletAddress: walletAddress, provider } = await this._resolveWalletSigner(providerWallet);
1132
- if (!walletAddress || typeof walletAddress !== 'string') {
1133
- throw new ConfigurationError('No wallet accounts available');
1134
- }
1135
- const signerIsEvm = EVM_ADDRESS_RE.test(this._normalizeIdentity(walletAddress));
1136
- const chain = this._inferChainForAddress(walletAddress);
1137
- const signatureMethod = signerIsEvm ? 'eip191' : 'ed25519';
1138
-
1139
- const signedTimestamp = Date.now();
1140
-
1141
- const message = constructVerificationMessage({
1142
- walletAddress,
1143
- signedTimestamp,
1144
- data: { action: 'access_private_proof', qHash: proofId },
1145
- verifierIds: ['ownership-basic'],
1146
- ...(signerIsEvm ? { chainId: this._getHubChainId() } : { chain })
1147
- });
1148
-
1149
- let signature;
1150
- try {
1151
- signature = await signMessage({
1152
- provider,
1153
- message,
1154
- walletAddress,
1155
- ...(signerIsEvm ? {} : { chain })
1156
- });
1157
- } catch (error) {
1158
- if (error.code === 4001) {
1159
- throw new ValidationError('User rejected signature request');
1160
- }
1161
- throw new ValidationError(`Failed to sign message: ${error.message}`);
1162
- }
1163
-
1164
- const response = await this._makeRequest('GET', `/api/v1/proofs/${proofId}`, null, {
1165
- 'x-wallet-address': walletAddress,
1166
- 'x-signature': signature,
1167
- 'x-signed-timestamp': signedTimestamp.toString(),
1168
- ...(signerIsEvm ? {} : { 'x-chain': chain, 'x-signature-method': signatureMethod })
1169
- });
1170
-
1171
- if (!response.success) {
1172
- throw new ApiError(
1173
- `Failed to access private proof: ${response.error?.message || 'Unauthorized'}`,
1174
- response.error
1175
- );
1176
- }
1177
-
1178
- return this._formatResponse(response);
1179
- }
1180
-
1181
- /**
1182
- * Check API health
1183
- *
1184
- * @returns {Promise<boolean>} True if API is healthy
1185
- */
1186
- async isHealthy() {
1187
- try {
1188
- const response = await this._makeRequest('GET', '/api/v1/health');
1189
- return response.success === true;
1190
- } catch {
1191
- return false;
1192
- }
1193
- }
1194
-
1195
- /**
1196
- * List available verifiers
1197
- *
1198
- * @returns {Promise<string[]>} Array of verifier IDs
1199
- */
1200
- async getVerifiers() {
1201
- const catalog = await this.getVerifierCatalog();
1202
- return Array.isArray(catalog?.data) ? catalog.data : [];
1203
- }
1204
-
1205
- /**
1206
- * Get the public verifier catalog with per-verifier capabilities.
1207
- * @returns {Promise<{data: string[], metadata: Record<string, { supportsDirectApi?: boolean }>, meta?: object}>}
1208
- */
1209
- async getVerifierCatalog() {
1210
- const response = await this._makeRequest('GET', '/api/v1/verification/verifiers');
1211
- if (!response.success) {
1212
- throw new ApiError(`Failed to get verifiers: ${response.error?.message || 'Unknown error'}`, response.error);
1213
- }
1214
- return {
1215
- data: Array.isArray(response.data) ? response.data : [],
1216
- metadata:
1217
- response.metadata && typeof response.metadata === 'object' && !Array.isArray(response.metadata)
1218
- ? response.metadata
1219
- : {},
1220
- meta:
1221
- response.meta && typeof response.meta === 'object' && !Array.isArray(response.meta)
1222
- ? response.meta
1223
- : {}
1224
- };
1225
- }
1226
-
1227
- /**
1228
- * POLL PROOF STATUS - Wait for verification completion
1229
- *
1230
- * Polls the verification status until it reaches a terminal state (completed or failed).
1231
- * Useful for providing real-time feedback to users during verification.
1232
- *
1233
- * @param {string} proofId - Proof ID to poll.
1234
- * @param {Object} [options] - Polling options
1235
- * @param {number} [options.interval=5000] - Polling interval in ms
1236
- * @param {number} [options.timeout=120000] - Total timeout in ms
1237
- * @param {Function} [options.onProgress] - Progress callback function
1238
- * @returns {Promise<Object>} Final verification status
1239
- *
1240
- * @example
1241
- * const finalStatus = await client.pollProofStatus(proofId, {
1242
- * interval: 3000,
1243
- * timeout: 60000,
1244
- * onProgress: (status) => {
1245
- * console.log('Current status:', status.status);
1246
- * if (status.crosschain) {
1247
- * console.log(`Cross-chain: ${status.crosschain.finalized}/${status.crosschain.totalChains}`);
1248
- * }
1249
- * }
1250
- * });
1251
- */
1252
- async pollProofStatus(proofId, options = {}) {
1253
- const {
1254
- interval = 5000,
1255
- timeout = 120000,
1256
- onProgress
1257
- } = options;
1258
-
1259
- if (!proofId || typeof proofId !== 'string') {
1260
- throw new ValidationError('proofId is required');
1261
- }
1262
-
1263
- const startTime = Date.now();
1264
- let consecutiveRateLimits = 0;
1265
-
1266
- while (Date.now() - startTime < timeout) {
1267
- try {
1268
- const status = await this.getProof(proofId);
1269
- consecutiveRateLimits = 0;
1270
-
1271
- // Call progress callback if provided
1272
- if (onProgress && typeof onProgress === 'function') {
1273
- onProgress(status.data || status);
1274
- }
1275
-
1276
- // Check for terminal states
1277
- const currentStatus = status.data?.status || status.status;
1278
- if (this._isTerminalStatus(currentStatus)) {
1279
- this._log('Verification completed', { status: currentStatus, duration: Date.now() - startTime });
1280
- return status;
1281
- }
1282
-
1283
- // Wait before next poll
1284
- await new Promise(resolve => setTimeout(resolve, interval));
1285
-
1286
- } catch (error) {
1287
- this._log('Status poll error', error.message);
1288
- // Continue polling unless it's a validation error
1289
- if (error instanceof ValidationError) {
1290
- throw error;
1291
- }
1292
-
1293
- let nextDelay = interval;
1294
- if (error instanceof ApiError && Number(error.statusCode) === 429) {
1295
- consecutiveRateLimits += 1;
1296
- const exp = Math.min(6, consecutiveRateLimits); // cap growth
1297
- const base = Math.max(500, Number(interval) || 0);
1298
- const max = 30000; // 30s cap to keep UX responsive
1299
- const backoff = Math.min(max, base * Math.pow(2, exp));
1300
- const jitter = Math.floor(backoff * (0.5 + Math.random() * 0.5)); // 50-100%
1301
- nextDelay = jitter;
1302
- }
1303
-
1304
- await new Promise(resolve => setTimeout(resolve, nextDelay));
1305
- }
1306
- }
1307
-
1308
- throw new NetworkError(`Polling timeout after ${timeout}ms`, 'POLLING_TIMEOUT');
1309
- }
1310
-
1311
- /**
1312
- * DETECT CHAIN ID - Get current wallet chain
1313
- *
1314
- * @returns {Promise<number>} Current chain ID
1315
- */
1316
- async detectChainId() {
1317
- if (typeof window === 'undefined' || !window.ethereum) {
1318
- throw new ConfigurationError('No Web3 wallet detected');
1319
- }
1320
-
1321
- try {
1322
- const chainId = await window.ethereum.request({ method: 'eth_chainId' });
1323
- return parseInt(chainId, 16);
1324
- } catch (error) {
1325
- throw new NetworkError(`Failed to detect chain ID: ${error.message}`);
1326
- }
1327
- }
1328
-
1329
- /** Revoke your own proof (owner-signed) */
1330
- async revokeOwnProof(proofId, wallet) {
1331
- if (!proofId || typeof proofId !== 'string') {
1332
- throw new ValidationError('proofId is required');
1333
- }
1334
- const providerWallet = wallet || this._getDefaultBrowserWallet();
1335
- const { signerWalletAddress: address, provider } = await this._resolveWalletSigner(providerWallet);
1336
- if (!address || typeof address !== 'string') {
1337
- throw new ConfigurationError('No wallet accounts available');
1338
- }
1339
- const signerIsEvm = EVM_ADDRESS_RE.test(this._normalizeIdentity(address));
1340
- const chain = this._inferChainForAddress(address);
1341
- const signatureMethod = signerIsEvm ? 'eip191' : 'ed25519';
1342
- const signedTimestamp = Date.now();
1343
-
1344
- const message = constructVerificationMessage({
1345
- walletAddress: address,
1346
- signedTimestamp,
1347
- data: { action: 'revoke_proof', qHash: proofId },
1348
- verifierIds: ['ownership-basic'],
1349
- ...(signerIsEvm ? { chainId: this._getHubChainId() } : { chain })
1350
- });
1351
-
1352
- let signature;
1353
- try {
1354
- signature = await signMessage({
1355
- provider,
1356
- message,
1357
- walletAddress: address,
1358
- ...(signerIsEvm ? {} : { chain })
1359
- });
1360
- } catch (error) {
1361
- if (error.code === 4001) {
1362
- throw new ValidationError('User rejected revocation signature');
1363
- }
1364
- throw new ValidationError(`Failed to sign revocation: ${error.message}`);
1365
- }
1366
-
1367
- const res = await fetch(`${this.config.apiUrl}/api/v1/proofs/revoke-self/${proofId}`, {
1368
- method: 'POST',
1369
- headers: { 'Content-Type': 'application/json' },
1370
- body: JSON.stringify({
1371
- walletAddress: address,
1372
- signature,
1373
- signedTimestamp,
1374
- ...(signerIsEvm ? {} : { chain, signatureMethod })
1375
- })
1376
- });
1377
- const json = await res.json();
1378
- if (!json.success) {
1379
- throw new ApiError(json.error?.message || 'Failed to revoke proof', json.error);
1380
- }
1381
- return true;
1382
- }
1383
-
1384
- /**
1385
- * GET PROOFS BY WALLET - Fetch proofs for a wallet address
1386
- *
1387
- * @param {string} walletAddress - Wallet identity (EVM/Solana/DID)
1388
- * @param {Object} [options] - Filter options
1389
- * @param {number} [options.limit] - Max results (default: 50; higher limits require owner access)
1390
- * @param {number} [options.offset] - Pagination offset (default: 0)
1391
- * @param {string} [options.qHash] - Filter to single proof by qHash
1392
- * @returns {Promise<Object>} Proofs result
1393
- *
1394
- * @example
1395
- * const result = await client.getProofsByWallet('0x...', {
1396
- * limit: 50,
1397
- * offset: 0
1398
- * });
1399
- */
1400
- async getProofsByWallet(walletAddress, options = {}) {
1401
- if (!walletAddress || typeof walletAddress !== 'string') {
1402
- throw new ValidationError('walletAddress is required');
1403
- }
1404
-
1405
- const id = walletAddress.trim();
1406
- const pathId = /^0x[a-fA-F0-9]{40}$/i.test(id) ? id.toLowerCase() : id;
1407
-
1408
- const qs = [];
1409
- if (options.limit) qs.push(`limit=${encodeURIComponent(String(options.limit))}`);
1410
- if (options.offset) qs.push(`offset=${encodeURIComponent(String(options.offset))}`);
1411
- if (options.qHash) qs.push(`qHash=${encodeURIComponent(options.qHash.toLowerCase())}`);
1412
-
1413
- const query = qs.length ? `?${qs.join('&')}` : '';
1414
- const response = await this._makeRequest(
1415
- 'GET',
1416
- `/api/v1/proofs/by-wallet/${encodeURIComponent(pathId)}${query}`
1417
- );
1418
-
1419
- if (!response.success) {
1420
- throw new ApiError(`Failed to get proofs: ${response.error?.message || 'Unknown error'}`, response.error);
1421
- }
1422
-
1423
- // Normalize response structure
1424
- const proofs = response.data?.proofs || response.data || response.proofs || [];
1425
- return {
1426
- success: true,
1427
- proofs: Array.isArray(proofs) ? proofs : [],
1428
- totalCount: response.data?.totalCount ?? proofs.length,
1429
- hasMore: Boolean(response.data?.hasMore),
1430
- nextOffset: response.data?.nextOffset ?? null
1431
- };
1432
- }
1433
-
1434
- /**
1435
- * Get proofs by wallet (owner access)
1436
- *
1437
- * Signs an owner-access intent and requests private proofs via signature headers.
1438
- *
1439
- * @param {string} walletAddress - Wallet identity (EVM/Solana/DID)
1440
- * @param {Object} [options]
1441
- * @param {number} [options.limit] - Max results (server enforces caps)
1442
- * @param {number} [options.offset] - Pagination offset
1443
- * @param {string} [options.qHash] - Filter to single proof by qHash
1444
- * @param {Object} [wallet] - Optional injected wallet/provider (MetaMask/ethers Wallet)
1445
- */
1446
- async getPrivateProofsByWallet(walletAddress, options = {}, wallet = null) {
1447
- if (!walletAddress || typeof walletAddress !== 'string') {
1448
- throw new ValidationError('walletAddress is required');
1449
- }
1450
-
1451
- const id = walletAddress.trim();
1452
- const pathId = /^0x[a-fA-F0-9]{40}$/i.test(id) ? id.toLowerCase() : id;
1453
-
1454
- const requestedIdentity = this._normalizeIdentity(id);
1455
-
1456
- // Auto-detect wallet if not provided
1457
- if (!wallet) {
1458
- const defaultWallet = this._getDefaultBrowserWallet();
1459
- if (!defaultWallet) {
1460
- throw new ConfigurationError('No wallet provider available');
1461
- }
1462
- wallet = defaultWallet;
1463
- }
1464
-
1465
- const { signerWalletAddress, provider } = await this._resolveWalletSigner(wallet);
1466
-
1467
- if (!signerWalletAddress || typeof signerWalletAddress !== 'string') {
1468
- throw new ConfigurationError('No wallet accounts available');
1469
- }
1470
-
1471
- const normalizedSigner = this._normalizeIdentity(signerWalletAddress);
1472
- if (!normalizedSigner || normalizedSigner !== requestedIdentity) {
1473
- throw new ValidationError('wallet must match walletAddress for private proof access');
1474
- }
1475
-
1476
- const signerIsEvm = EVM_ADDRESS_RE.test(normalizedSigner);
1477
- const chain = this._inferChainForAddress(normalizedSigner, options?.chain);
1478
- const signatureMethod = (typeof options?.signatureMethod === 'string' && options.signatureMethod.trim())
1479
- ? options.signatureMethod.trim()
1480
- : (signerIsEvm ? 'eip191' : 'ed25519');
1481
-
1482
- const signedTimestamp = Date.now();
1483
- const message = constructVerificationMessage({
1484
- walletAddress: signerWalletAddress,
1485
- signedTimestamp,
1486
- data: { action: 'access_private_proofs_by_wallet', walletAddress: normalizedSigner },
1487
- verifierIds: ['ownership-basic'],
1488
- ...(signerIsEvm ? { chainId: this._getHubChainId() } : { chain })
1489
- });
1490
-
1491
- let signature;
1492
- try {
1493
- signature = await signMessage({
1494
- provider,
1495
- message,
1496
- walletAddress: signerWalletAddress,
1497
- ...(signerIsEvm ? {} : { chain })
1498
- });
1499
- } catch (error) {
1500
- if (error.code === 4001) {
1501
- throw new ValidationError('User rejected signature request');
1502
- }
1503
- throw new ValidationError(`Failed to sign message: ${error.message}`);
1504
- }
1505
-
1506
- const qs = [];
1507
- if (options.limit) qs.push(`limit=${encodeURIComponent(String(options.limit))}`);
1508
- if (options.offset) qs.push(`offset=${encodeURIComponent(String(options.offset))}`);
1509
- if (options.qHash) qs.push(`qHash=${encodeURIComponent(options.qHash.toLowerCase())}`);
1510
- const query = qs.length ? `?${qs.join('&')}` : '';
1511
-
1512
- const response = await this._makeRequest('GET', `/api/v1/proofs/by-wallet/${encodeURIComponent(pathId)}${query}`, null, {
1513
- 'x-wallet-address': signerWalletAddress,
1514
- 'x-signature': signature,
1515
- 'x-signed-timestamp': signedTimestamp.toString(),
1516
- ...(signerIsEvm ? {} : { 'x-chain': chain, 'x-signature-method': signatureMethod })
1517
- });
1518
-
1519
- if (!response.success) {
1520
- throw new ApiError(`Failed to get proofs: ${response.error?.message || 'Unauthorized'}`, response.error);
1521
- }
1522
-
1523
- const proofs = response.data?.proofs || response.data || response.proofs || [];
1524
- return {
1525
- success: true,
1526
- proofs: Array.isArray(proofs) ? proofs : [],
1527
- totalCount: response.data?.totalCount ?? proofs.length,
1528
- hasMore: Boolean(response.data?.hasMore),
1529
- nextOffset: response.data?.nextOffset ?? null
1530
- };
1531
- }
1532
-
1533
- /**
1534
- * Gate check (HTTP API) minimal eligibility response.
1535
- *
1536
- * Calls the gate endpoint and returns a **minimal** yes/no response.
1537
- * By default this checks **public + unlisted** proofs.
1538
- *
1539
- * When `includePrivate=true`, this can perform owner-signed private checks
1540
- * (no full proof payloads returned) by providing a wallet/provider.
1541
- *
1542
- * Prefer this over `checkGate()` when you need the smallest, most stable
1543
- * response shape and do not need full proof payloads.
1544
- *
1545
- * @param {Object} params - Gate check query params
1546
- * @param {string} params.address - Wallet identity to check (EVM/Solana/DID)
1547
- * @param {Array<string>|string} [params.verifierIds] - Verifier IDs to match (array or comma-separated)
1548
- * @param {boolean} [params.requireAll] - Require all verifierIds on a single proof
1549
- * @param {number} [params.minCount] - Minimum number of matching proofs
1550
- * @param {number} [params.sinceDays] - Optional time window in days
1551
- * @param {number} [params.since] - Optional unix timestamp in ms (lower bound)
1552
- * @param {number} [params.limit] - Max rows to scan (server may clamp)
1553
- * @param {boolean} [params.includePrivate] - Include private proofs for owner-authenticated requests
1554
- * @param {boolean} [params.includeQHashes] - Include matched qHashes in response (minimal IDs only)
1555
- * @param {Object} [params.wallet] - Optional wallet/provider used to sign includePrivate owner checks
1556
- * @returns {Promise<Object>} API response ({ success, data })
1557
- */
1558
- async gateCheck(params = {}) {
1559
- const address = (params.address || '').toString();
1560
- if (!validateUniversalAddress(address, params.chain)) {
1561
- throw new ValidationError('Valid address is required');
1562
- }
1563
-
1564
- // Build query string safely (stringify all values; allow arrays for common fields)
1565
- const qs = new URLSearchParams();
1566
- qs.set('address', address);
1567
-
1568
- const setIfPresent = (key, value) => {
1569
- if (value === undefined || value === null) return;
1570
- const str = typeof value === 'string' ? value : String(value);
1571
- if (str.length === 0) return;
1572
- qs.set(key, str);
1573
- };
1574
-
1575
- const setBoolIfPresent = (key, value) => {
1576
- if (value === undefined || value === null) return;
1577
- qs.set(key, value ? 'true' : 'false');
1578
- };
1579
-
1580
- const setCsvIfPresent = (key, value) => {
1581
- if (value === undefined || value === null) return;
1582
- if (Array.isArray(value)) {
1583
- const items = value.map(v => String(v).trim()).filter(Boolean);
1584
- if (items.length) qs.set(key, items.join(','));
1585
- return;
1586
- }
1587
- setIfPresent(key, value);
1588
- };
1589
-
1590
- // Common filters
1591
- setCsvIfPresent('verifierIds', params.verifierIds);
1592
- setBoolIfPresent('requireAll', params.requireAll);
1593
- setIfPresent('minCount', params.minCount);
1594
- setIfPresent('sinceDays', params.sinceDays);
1595
- setIfPresent('since', params.since);
1596
- setIfPresent('limit', params.limit);
1597
- setBoolIfPresent('includePrivate', params.includePrivate);
1598
- setBoolIfPresent('includeQHashes', params.includeQHashes);
1599
-
1600
- // Common match filters (optional)
1601
- setIfPresent('referenceType', params.referenceType);
1602
- setIfPresent('referenceId', params.referenceId);
1603
- setIfPresent('tag', params.tag);
1604
- setCsvIfPresent('tags', params.tags);
1605
- setIfPresent('contentType', params.contentType);
1606
- setIfPresent('content', params.content);
1607
- setIfPresent('contentHash', params.contentHash);
1608
-
1609
- // Asset/ownership filters
1610
- setIfPresent('contractAddress', params.contractAddress);
1611
- setIfPresent('tokenId', params.tokenId);
1612
- setIfPresent('chainId', params.chainId);
1613
- setIfPresent('domain', params.domain);
1614
- setIfPresent('minBalance', params.minBalance);
1615
-
1616
- // Wallet filters
1617
- setIfPresent('provider', params.provider);
1618
- setIfPresent('handle', params.handle);
1619
- setIfPresent('namespace', params.namespace);
1620
- setIfPresent('ownerAddress', params.ownerAddress);
1621
- setIfPresent('riskLevel', params.riskLevel);
1622
- setBoolIfPresent('sanctioned', params.sanctioned);
1623
- setBoolIfPresent('poisoned', params.poisoned);
1624
- setIfPresent('primaryWalletAddress', params.primaryWalletAddress);
1625
- setIfPresent('secondaryWalletAddress', params.secondaryWalletAddress);
1626
- setIfPresent('verificationMethod', params.verificationMethod);
1627
-
1628
- let headersOverride = null;
1629
- if (params.includePrivate === true) {
1630
- const provided = params.privateAuth && typeof params.privateAuth === 'object' ? params.privateAuth : null;
1631
- let auth = provided;
1632
- if (!auth) {
1633
- const walletCandidate = params.wallet || this._getDefaultBrowserWallet();
1634
- if (walletCandidate) {
1635
- auth = await this._buildPrivateGateAuth({
1636
- address,
1637
- wallet: walletCandidate,
1638
- chain: params.chain,
1639
- signatureMethod: params.signatureMethod
1640
- });
1641
- }
1642
- }
1643
- if (!auth) {
1644
- // Without a signer: public and unlisted proofs only.
1645
- } else {
1646
- const normalizedAuthWallet = this._normalizeIdentity(auth.walletAddress);
1647
- const normalizedAddress = this._normalizeIdentity(address);
1648
- if (!normalizedAuthWallet || normalizedAuthWallet !== normalizedAddress) {
1649
- throw new ValidationError('privateAuth.walletAddress must match address when includePrivate=true');
1650
- }
1651
- const authChain = (typeof auth.chain === 'string' && auth.chain.includes(':')) ? auth.chain.trim() : null;
1652
- const authSignatureMethod = (typeof auth.signatureMethod === 'string' && auth.signatureMethod.trim())
1653
- ? auth.signatureMethod.trim()
1654
- : null;
1655
- headersOverride = {
1656
- 'x-wallet-address': String(auth.walletAddress),
1657
- 'x-signature': String(auth.signature),
1658
- 'x-signed-timestamp': String(auth.signedTimestamp),
1659
- ...(authChain ? { 'x-chain': authChain } : {}),
1660
- ...(authSignatureMethod ? { 'x-signature-method': authSignatureMethod } : {})
1661
- };
1662
- }
1663
- }
1664
-
1665
- const response = await this._makeRequest('GET', `/api/v1/proofs/check?${qs.toString()}`, null, headersOverride);
1666
- if (!response.success) {
1667
- throw new ApiError(`Gate check failed: ${response.error?.message || 'Unknown error'}`, response.error);
1668
- }
1669
- return response;
1670
- }
1671
-
1672
- /**
1673
- * CHECK GATE — Local preview against proofs you already have in memory or from `getProofsByWallet`.
1674
- *
1675
- * **Not authoritative for access control.** For production allow/deny, use {@link NeusClient#gateCheck}
1676
- * (`GET /api/v1/proofs/check`), which applies the same rules as the NEUS API. This method is useful for
1677
- * UI previews, offline-ish flows, or when you already fetched proofs and want a quick match without
1678
- * another round trip — but it can disagree with the server (e.g. `contentHash` matching uses a local
1679
- * approximation when proof data only has inline `content`; the API uses the standard server-side hash).
1680
- *
1681
- * Gate-first verification: checks if wallet has valid proofs satisfying requirements.
1682
- * Returns which requirements are missing/expired.
1683
- *
1684
- * @param {Object} params - Gate check parameters
1685
- * @param {string} params.walletAddress - Target wallet
1686
- * @param {Array<Object>} params.requirements - Array of gate requirements
1687
- * @param {string} params.requirements[].verifierId - Required verifier ID
1688
- * @param {number} [params.requirements[].maxAgeMs] - Max proof age in ms (TTL)
1689
- * @param {boolean} [params.requirements[].optional] - If true, not required for gate satisfaction
1690
- * @param {number} [params.requirements[].minCount] - Minimum proofs needed (default: 1)
1691
- * @param {Object} [params.requirements[].match] - Verifier data match criteria
1692
- * Supports nested fields: 'reference.type', 'reference.id', 'content', 'contentHash', 'input.*', 'license.*'
1693
- * Supports verifier-specific:
1694
- * - NFT/Token: 'contractAddress', 'tokenId', 'chainId', 'ownerAddress', 'minBalance'
1695
- * - DNS: 'domain', 'walletAddress'
1696
- * - Wallet-link: 'primaryWalletAddress', 'secondaryWalletAddress', 'chain', 'signatureMethod'
1697
- * - Contract-ownership: 'contractAddress', 'chainId', 'owner', 'verificationMethod'
1698
- * Note: contentHash matching uses approximation in SDK; for exact SHA-256 matching, use backend API
1699
- * @param {Array} [params.proofs] - Pre-fetched proofs (skip API call)
1700
- * @returns {Promise<Object>} Gate result with satisfied, missing, existing
1701
- *
1702
- * @example
1703
- * // Basic gate check
1704
- * const result = await client.checkGate({
1705
- * walletAddress: '0x...',
1706
- * requirements: [
1707
- * { verifierId: 'nft-ownership', match: { contractAddress: '0x...' } }
1708
- * ]
1709
- * });
1710
- */
1711
- async checkGate(params) {
1712
- const { walletAddress, requirements, proofs: preloadedProofs } = params;
1713
-
1714
- if (!validateUniversalAddress(walletAddress)) {
1715
- throw new ValidationError('Valid walletAddress is required');
1716
- }
1717
- if (!Array.isArray(requirements) || requirements.length === 0) {
1718
- throw new ValidationError('requirements array is required and must not be empty');
1719
- }
1720
-
1721
- // Use preloaded proofs or fetch from API
1722
- let proofs = preloadedProofs;
1723
- if (!proofs) {
1724
- const result = await this.getProofsByWallet(walletAddress, { limit: 100 });
1725
- proofs = result.proofs;
1726
- }
1727
-
1728
- const now = Date.now();
1729
- const existing = {};
1730
- const missing = [];
1731
-
1732
- for (const req of requirements) {
1733
- const { verifierId, maxAgeMs, optional = false, minCount = 1, match } = req;
1734
-
1735
- // Find matching proofs for this verifier
1736
- const matchingProofs = (proofs || []).filter(proof => {
1737
- // Must have this verifier and be verified
1738
- const verifiedVerifiers = proof.verifiedVerifiers || [];
1739
- const verifier = verifiedVerifiers.find(
1740
- v => v.verifierId === verifierId && v.verified === true
1741
- );
1742
- if (!verifier) return false;
1743
-
1744
- // Check proof is not revoked
1745
- if (proof.revokedAt) return false;
1746
-
1747
- // Check TTL if specified
1748
- if (maxAgeMs) {
1749
- const proofTimestamp = proof.createdAt || proof.signedTimestamp || 0;
1750
- const proofAge = now - proofTimestamp;
1751
- if (proofAge > maxAgeMs) return false;
1752
- }
1753
-
1754
- // Check custom match criteria if specified
1755
- if (match && typeof match === 'object') {
1756
- const data = verifier.data || {};
1757
- const input = data.input || {}; // NFT/token verifiers store fields in input
1758
- // Gate format: match as array [{path, op, value}]. Convert to {path: value} for iteration.
1759
- const matchObj = Array.isArray(match)
1760
- ? Object.fromEntries(
1761
- match
1762
- .filter((m) => m && m.path && String(m.value ?? '').trim() !== '')
1763
- .map((m) => [String(m.path).trim(), m.value])
1764
- )
1765
- : match;
1766
-
1767
- for (const [key, expected] of Object.entries(matchObj)) {
1768
- let actualValue = null;
1769
-
1770
- // Handle nested field access
1771
- if (key.includes('.')) {
1772
- const parts = key.split('.');
1773
- let current = data;
1774
-
1775
- if (parts[0] === 'input' && input) {
1776
- current = input;
1777
- parts.shift();
1778
- }
1779
-
1780
- for (const part of parts) {
1781
- if (current && typeof current === 'object' && part in current) {
1782
- current = current[part];
1783
- } else {
1784
- current = undefined;
1785
- break;
1786
- }
1787
- }
1788
- actualValue = current;
1789
- } else {
1790
- actualValue = input[key] || data[key];
1791
- }
1792
-
1793
- if (key === 'content' && actualValue === undefined) {
1794
- actualValue = data.reference?.id || data.content;
1795
- }
1796
-
1797
- // Special handling for verifier-specific fields (claim-based, aligns with proofs/check)
1798
- if (actualValue === undefined) {
1799
- const claims = data.claims || {};
1800
- if (key === 'contractAddress') {
1801
- actualValue = input.contractAddress || data.contractAddress;
1802
- } else if (key === 'tokenId') {
1803
- actualValue = input.tokenId || data.tokenId;
1804
- } else if (key === 'chainId') {
1805
- actualValue = input.chainId || data.chainId;
1806
- } else if (key === 'ownerAddress') {
1807
- actualValue = input.ownerAddress || data.owner || data.walletAddress;
1808
- } else if (key === 'minBalance') {
1809
- actualValue = input.minBalance || data.onChainData?.requiredMinBalance || data.minBalance;
1810
- } else if (key === 'primaryWalletAddress') {
1811
- actualValue = data.primaryWalletAddress;
1812
- } else if (key === 'secondaryWalletAddress') {
1813
- actualValue = data.secondaryWalletAddress;
1814
- } else if (key === 'verificationMethod') {
1815
- actualValue = data.verificationMethod;
1816
- } else if (key === 'domain') {
1817
- actualValue = data.domain;
1818
- } else if (key === 'handle') {
1819
- actualValue = data.handle || data.pseudonymId;
1820
- } else if (key === 'namespace') {
1821
- actualValue =
1822
- data.namespace !== undefined && data.namespace !== null && data.namespace !== ''
1823
- ? data.namespace
1824
- : 'neus';
1825
- } else if (key === 'claims.sanctions_passed') {
1826
- actualValue = claims.sanctions_passed ?? claims.sanctionsPassed;
1827
- } else if (key === 'claims.age_min') {
1828
- actualValue = claims.age_min ?? claims.ageMin;
1829
- } else if (key === 'neusPersonhoodId') {
1830
- actualValue = data.neusPersonhoodId;
1831
- } else if (key === 'riskLevel') {
1832
- actualValue = data.riskLevel;
1833
- } else if (key === 'sanctioned') {
1834
- actualValue = data.sanctioned;
1835
- } else if (key === 'poisoned') {
1836
- actualValue = data.poisoned;
1837
- }
1838
- }
1839
-
1840
- // Content hash check (approximation)
1841
- if (key === 'contentHash' && actualValue === undefined && data.content) {
1842
- try {
1843
- // Simple hash approximation for non-crypto envs
1844
- let hash = 0;
1845
- const str = String(data.content);
1846
- for (let i = 0; i < str.length; i++) {
1847
- const char = str.charCodeAt(i);
1848
- hash = ((hash << 5) - hash) + char;
1849
- hash = hash & hash;
1850
- }
1851
- actualValue = `0x${ Math.abs(hash).toString(16).padStart(64, '0').substring(0, 66)}`;
1852
- } catch {
1853
- actualValue = String(data.content);
1854
- }
1855
- }
1856
-
1857
- let normalizedActual = actualValue;
1858
- let normalizedExpected = expected;
1859
-
1860
- if (actualValue === undefined || actualValue === null) {
1861
- return false;
1862
- }
1863
-
1864
- // Boolean claims (sanctions_passed, sanctioned, poisoned)
1865
- if (typeof actualValue === 'boolean' || (key && (key.includes('sanctions') || key.includes('sanctioned') || key.includes('poisoned')))) {
1866
- const bActual = Boolean(actualValue);
1867
- const bExpected = expected === true || expected === 'true' || String(expected).toLowerCase() === 'true';
1868
- if (bActual !== bExpected) return false;
1869
- continue;
1870
- }
1871
-
1872
- if (key === 'chainId' || (key === 'tokenId' && (typeof actualValue === 'number' || !isNaN(Number(actualValue))))) {
1873
- normalizedActual = Number(actualValue);
1874
- normalizedExpected = Number(expected);
1875
- if (isNaN(normalizedActual) || isNaN(normalizedExpected)) return false;
1876
- }
1877
- else if (typeof actualValue === 'string' && (actualValue.startsWith('0x') || actualValue.length > 20)) {
1878
- normalizedActual = actualValue.toLowerCase();
1879
- normalizedExpected = typeof expected === 'string' ? String(expected).toLowerCase() : expected;
1880
- }
1881
- else {
1882
- normalizedActual = actualValue;
1883
- normalizedExpected = expected;
1884
- }
1885
-
1886
- if (normalizedActual !== normalizedExpected) {
1887
- return false;
1888
- }
1889
- }
1890
- }
1891
-
1892
- return true;
1893
- });
1894
-
1895
- if (matchingProofs.length >= minCount) {
1896
- const sorted = matchingProofs.sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));
1897
- existing[verifierId] = sorted[0];
1898
- } else if (!optional) {
1899
- missing.push(req);
1900
- }
1901
- }
1902
-
1903
- return {
1904
- satisfied: missing.length === 0,
1905
- missing,
1906
- existing,
1907
- allProofs: proofs
1908
- };
1909
- }
1910
-
1911
- async _getWalletAddress() {
1912
- if (typeof window === 'undefined' || !window.ethereum) {
1913
- throw new ConfigurationError('No Web3 wallet detected');
1914
- }
1915
-
1916
- const accounts = await window.ethereum.request({ method: 'eth_accounts' });
1917
- if (!accounts || accounts.length === 0) {
1918
- throw new ConfigurationError('No wallet accounts available');
1919
- }
1920
-
1921
- return accounts[0];
1922
- }
1923
-
1924
- async _makeRequest(method, endpoint, data = null, headersOverride = null) {
1925
- const url = `${this.baseUrl}${endpoint}`;
1926
-
1927
- const controller = new AbortController();
1928
- const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
1929
-
1930
- const options = {
1931
- method,
1932
- headers: { ...this.defaultHeaders, ...(headersOverride || {}) },
1933
- signal: controller.signal
1934
- };
1935
-
1936
- if (data && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
1937
- options.body = JSON.stringify(data);
1938
- }
1939
-
1940
- this._log(`${method} ${endpoint}`, data ? { requestBodyKeys: Object.keys(data) } : {});
1941
-
1942
- try {
1943
- const response = await fetch(url, options);
1944
- clearTimeout(timeoutId);
1945
-
1946
- let responseData;
1947
- try {
1948
- responseData = await response.json();
1949
- } catch {
1950
- responseData = { error: { message: 'Invalid JSON response' } };
1951
- }
1952
-
1953
- if (!response.ok) {
1954
- throw ApiError.fromResponse(response, responseData);
1955
- }
1956
-
1957
- return responseData;
1958
-
1959
- } catch (error) {
1960
- clearTimeout(timeoutId);
1961
-
1962
- if (error.name === 'AbortError') {
1963
- throw new NetworkError(`Request timeout after ${this.config.timeout}ms`);
1964
- }
1965
-
1966
- if (error instanceof ApiError) {
1967
- throw error;
1968
- }
1969
-
1970
- throw new NetworkError(`Network error: ${error.message}`);
1971
- }
1972
- }
1973
-
1974
- _formatResponse(response) {
1975
- const proofId = response?.data?.proofId ||
1976
- response?.proofId ||
1977
- response?.data?.resource?.proofId ||
1978
- response?.data?.qHash ||
1979
- response?.qHash ||
1980
- response?.data?.resource?.qHash ||
1981
- response?.data?.id;
1982
- const qHash = response?.data?.qHash ||
1983
- response?.qHash ||
1984
- response?.data?.resource?.qHash ||
1985
- proofId ||
1986
- response?.data?.id;
1987
- const finalProofId = proofId || qHash || null;
1988
- const finalQHash = qHash || proofId || finalProofId;
1989
-
1990
- const status = response?.data?.status ||
1991
- response?.status ||
1992
- response?.data?.resource?.status ||
1993
- (response?.success ? 'completed' : 'unknown');
1994
-
1995
- return {
1996
- success: response.success,
1997
- proofId: finalProofId,
1998
- qHash: finalQHash,
1999
- status,
2000
- data: response.data,
2001
- message: response.message,
2002
- timestamp: Date.now(),
2003
- proofUrl: finalProofId ? `${this.baseUrl}/api/v1/proofs/${finalProofId}` : null
2004
- };
2005
- }
2006
-
2007
- _isTerminalStatus(status) {
2008
- const terminalStates = [
2009
- 'verified',
2010
- 'verified_crosschain_propagated',
2011
- 'completed_all_successful',
2012
- 'failed',
2013
- 'error',
2014
- 'rejected',
2015
- 'cancelled'
2016
- ];
2017
- return typeof status === 'string' && terminalStates.some(state => status.includes(state));
2018
- }
2019
-
2020
- /** SDK logging (opt-in via config.enableLogging) */
2021
- _log(message, data = {}) {
2022
- if (this.config.enableLogging) {
2023
- try {
2024
- const prefix = '[neus/sdk]';
2025
- if (data && Object.keys(data).length > 0) {
2026
- // eslint-disable-next-line no-console
2027
- console.log(prefix, message, data);
2028
- } else {
2029
- // eslint-disable-next-line no-console
2030
- console.log(prefix, message);
2031
- }
2032
- } catch {
2033
- // ignore logging failures
2034
- }
2035
- }
2036
- }
2037
- }
2038
-
2039
- // Export signing helpers for advanced use
2040
- export { PORTABLE_PROOF_SIGNER_HEADER, constructVerificationMessage };
598
+ async verify(params) {
599
+ if ((!params?.signature || !params?.walletAddress) && (params?.verifier || params?.content || params?.data)) {
600
+ const { content, verifier = 'ownership-basic', data = null, wallet = null, options = {} } = params;
601
+
602
+ if (verifier === 'ownership-basic' && !data && (!content || typeof content !== 'string')) {
603
+ throw new ValidationError('content is required and must be a string (or use data param with owner + reference)');
604
+ }
605
+
606
+ let verifierCatalog = FALLBACK_PUBLIC_VERIFIER_CATALOG;
607
+ try {
608
+ const discovered = await this.getVerifierCatalog();
609
+ if (discovered && discovered.metadata && Object.keys(discovered.metadata).length > 0) {
610
+ verifierCatalog = discovered.metadata;
611
+ }
612
+ } catch {
613
+ void 0;
614
+ }
615
+ const validVerifiers = Object.keys(verifierCatalog);
616
+ if (!validVerifiers.includes(verifier)) {
617
+ throw new ValidationError(`Invalid verifier '${verifier}'. Must be one of: ${validVerifiers.join(', ')}.`);
618
+ }
619
+
620
+ if (verifierCatalog?.[verifier]?.supportsDirectApi === false) {
621
+ const hostedCheckoutUrl = options?.hostedCheckoutUrl || 'https://neus.network/verify';
622
+ throw new ValidationError(
623
+ `${verifier} requires hosted interactive checkout. Use VerifyGate or redirect to ${hostedCheckoutUrl}.`
624
+ );
625
+ }
626
+
627
+ const requiresDataParam = [
628
+ 'ownership-dns-txt',
629
+ 'wallet-link',
630
+ 'contract-ownership',
631
+ 'ownership-pseudonym',
632
+ 'wallet-risk',
633
+ 'agent-identity',
634
+ 'agent-delegation',
635
+ 'ai-content-moderation'
636
+ ];
637
+ if (requiresDataParam.includes(verifier)) {
638
+ if (!data || typeof data !== 'object') {
639
+ throw new ValidationError(`${verifier} requires explicit data parameter. Cannot use auto-path.`);
640
+ }
641
+ }
642
+
643
+ let walletAddress, provider;
644
+ if (wallet) {
645
+ walletAddress =
646
+ wallet.address ||
647
+ wallet.selectedAddress ||
648
+ wallet.walletAddress ||
649
+ (typeof wallet.getAddress === 'function' ? await wallet.getAddress().catch(() => null) : null);
650
+ provider = wallet.provider || wallet;
651
+ if (!walletAddress && provider && typeof provider.request === 'function') {
652
+ let accounts = await provider.request({ method: 'eth_accounts' });
653
+ walletAddress = Array.isArray(accounts) && accounts.length > 0 ? accounts[0] : null;
654
+ if (!walletAddress) {
655
+ await provider.request({ method: 'eth_requestAccounts' });
656
+ accounts = await provider.request({ method: 'eth_accounts' });
657
+ walletAddress = Array.isArray(accounts) && accounts.length > 0 ? accounts[0] : null;
658
+ }
659
+ }
660
+ } else {
661
+ if (typeof window === 'undefined' || !window.ethereum) {
662
+ throw new ConfigurationError('No Web3 wallet detected. Please install MetaMask or provide wallet parameter.');
663
+ }
664
+ await window.ethereum.request({ method: 'eth_requestAccounts' });
665
+ provider = window.ethereum;
666
+ const accounts = await provider.request({ method: 'eth_accounts' });
667
+ walletAddress = accounts[0];
668
+ }
669
+
670
+ {
671
+ const normalized = normalizeBrowserSignerString(
672
+ typeof walletAddress === 'string' ? walletAddress : null
673
+ );
674
+ if (!normalized) {
675
+ throw new ConfigurationError('No wallet accounts available. Connect a wallet to continue.');
676
+ }
677
+ walletAddress = normalized;
678
+ }
679
+
680
+ let verificationData;
681
+ if (verifier === 'ownership-basic') {
682
+ if (data && typeof data === 'object') {
683
+ verificationData = {
684
+ owner: data.owner || walletAddress,
685
+ reference: data.reference,
686
+ ...(data.content && { content: data.content }),
687
+ ...(data.contentHash && { contentHash: data.contentHash }),
688
+ ...(data.contentType && { contentType: data.contentType }),
689
+ ...(data.provenance && { provenance: data.provenance })
690
+ };
691
+ } else {
692
+ verificationData = {
693
+ content: content,
694
+ owner: walletAddress,
695
+ reference: { type: 'other' }
696
+ };
697
+ }
698
+ } else if (verifier === 'token-holding') {
699
+ if (!data?.contractAddress) {
700
+ throw new ValidationError('token-holding requires contractAddress in data parameter');
701
+ }
702
+ if (data?.minBalance === null || data?.minBalance === undefined) {
703
+ throw new ValidationError('token-holding requires minBalance in data parameter');
704
+ }
705
+ if (typeof data?.chainId !== 'number') {
706
+ throw new ValidationError('token-holding requires chainId (number) in data parameter');
707
+ }
708
+ verificationData = {
709
+ ownerAddress: walletAddress,
710
+ contractAddress: data.contractAddress,
711
+ minBalance: data.minBalance,
712
+ chainId: data.chainId
713
+ };
714
+ } else if (verifier === 'nft-ownership') {
715
+ if (!data?.contractAddress) {
716
+ throw new ValidationError('nft-ownership requires contractAddress in data parameter');
717
+ }
718
+ if (data?.tokenId === null || data?.tokenId === undefined) {
719
+ throw new ValidationError('nft-ownership requires tokenId in data parameter');
720
+ }
721
+ if (typeof data?.chainId !== 'number') {
722
+ throw new ValidationError('nft-ownership requires chainId (number) in data parameter');
723
+ }
724
+ verificationData = {
725
+ ownerAddress: walletAddress,
726
+ contractAddress: data.contractAddress,
727
+ tokenId: data.tokenId,
728
+ chainId: data.chainId,
729
+ tokenType: data?.tokenType || 'erc721'
730
+ };
731
+ } else if (verifier === 'ownership-dns-txt') {
732
+ if (!data?.domain) {
733
+ throw new ValidationError('ownership-dns-txt requires domain in data parameter');
734
+ }
735
+ verificationData = {
736
+ domain: data.domain,
737
+ walletAddress: walletAddress
738
+ };
739
+ } else if (verifier === 'wallet-link') {
740
+ if (!data?.secondaryWalletAddress) {
741
+ throw new ValidationError('wallet-link requires secondaryWalletAddress in data parameter');
742
+ }
743
+ if (!data?.signature) {
744
+ throw new ValidationError('wallet-link requires signature in data parameter (signed by secondary wallet)');
745
+ }
746
+ if (typeof data?.chain !== 'string' || !/^[a-z0-9]+:[^\s]+$/.test(data.chain)) {
747
+ throw new ValidationError('wallet-link requires chain (namespace:reference) in data parameter');
748
+ }
749
+ if (typeof data?.signatureMethod !== 'string' || !data.signatureMethod.trim()) {
750
+ throw new ValidationError('wallet-link requires signatureMethod in data parameter');
751
+ }
752
+ verificationData = {
753
+ primaryWalletAddress: walletAddress,
754
+ secondaryWalletAddress: data.secondaryWalletAddress,
755
+ signature: data.signature,
756
+ chain: data.chain,
757
+ signatureMethod: data.signatureMethod,
758
+ signedTimestamp: data?.signedTimestamp || Date.now()
759
+ };
760
+ } else if (verifier === 'contract-ownership') {
761
+ if (!data?.contractAddress) {
762
+ throw new ValidationError('contract-ownership requires contractAddress in data parameter');
763
+ }
764
+ if (typeof data?.chainId !== 'number') {
765
+ throw new ValidationError('contract-ownership requires chainId (number) in data parameter');
766
+ }
767
+ verificationData = {
768
+ contractAddress: data.contractAddress,
769
+ walletAddress: walletAddress,
770
+ chainId: data.chainId,
771
+ ...(data?.method && { method: data.method })
772
+ };
773
+ } else if (verifier === 'agent-identity') {
774
+ if (!data?.agentId) {
775
+ throw new ValidationError('agent-identity requires agentId in data parameter');
776
+ }
777
+ verificationData = {
778
+ agentId: data.agentId,
779
+ agentWallet: data?.agentWallet || walletAddress,
780
+ ...(data?.agentLabel && { agentLabel: data.agentLabel }),
781
+ ...(data?.agentType && { agentType: data.agentType }),
782
+ ...(data?.description && { description: data.description }),
783
+ ...(data?.capabilities && { capabilities: data.capabilities }),
784
+ ...(data?.instructions && { instructions: data.instructions }),
785
+ ...(data?.skills && { skills: data.skills }),
786
+ ...(data?.services && { services: data.services })
787
+ };
788
+ } else if (verifier === 'agent-delegation') {
789
+ if (!data?.agentWallet) {
790
+ throw new ValidationError('agent-delegation requires agentWallet in data parameter');
791
+ }
792
+ verificationData = {
793
+ controllerWallet: data?.controllerWallet || walletAddress,
794
+ agentWallet: data.agentWallet,
795
+ ...(data?.agentId && { agentId: data.agentId }),
796
+ ...(data?.scope && { scope: data.scope }),
797
+ ...(data?.permissions && { permissions: data.permissions }),
798
+ ...(data?.maxSpend && { maxSpend: data.maxSpend }),
799
+ ...(data?.allowedPaymentTypes && { allowedPaymentTypes: data.allowedPaymentTypes }),
800
+ ...(data?.receiptDisclosure && { receiptDisclosure: data.receiptDisclosure }),
801
+ ...(data?.expiresAt && { expiresAt: data.expiresAt }),
802
+ ...(data?.instructions && { instructions: data.instructions }),
803
+ ...(data?.skills && { skills: data.skills })
804
+ };
805
+ } else if (verifier === 'ai-content-moderation') {
806
+ if (!data?.content) {
807
+ throw new ValidationError('ai-content-moderation requires content (base64) in data parameter');
808
+ }
809
+ if (!data?.contentType) {
810
+ throw new ValidationError('ai-content-moderation requires contentType (MIME type) in data parameter');
811
+ }
812
+ verificationData = {
813
+ content: data.content,
814
+ contentType: data.contentType,
815
+ ...(data?.provider && { provider: data.provider })
816
+ };
817
+ } else if (verifier === 'ownership-pseudonym') {
818
+ if (!data?.pseudonymId) {
819
+ throw new ValidationError('ownership-pseudonym requires pseudonymId in data parameter');
820
+ }
821
+ verificationData = {
822
+ pseudonymId: data.pseudonymId,
823
+ ...(data?.namespace && { namespace: data.namespace }),
824
+ ...(data?.displayName && { displayName: data.displayName }),
825
+ ...(data?.metadata && { metadata: data.metadata })
826
+ };
827
+ } else if (verifier === 'wallet-risk') {
828
+ verificationData = {
829
+ walletAddress: data?.walletAddress || walletAddress,
830
+ ...(data?.provider && { provider: data.provider }),
831
+ chainId: (typeof data?.chainId === 'number' && Number.isFinite(data.chainId)) ? data.chainId : 1,
832
+ ...(data?.includeDetails !== undefined && { includeDetails: data.includeDetails })
833
+ };
834
+ } else {
835
+ verificationData = data ? {
836
+ content,
837
+ owner: walletAddress,
838
+ ...data
839
+ } : {
840
+ content,
841
+ owner: walletAddress
842
+ };
843
+ }
844
+
845
+ const signedTimestamp = Date.now();
846
+ const verifierIds = [verifier];
847
+ const message = constructVerificationMessage({
848
+ walletAddress,
849
+ signedTimestamp,
850
+ data: verificationData,
851
+ verifierIds,
852
+ chainId: this._getHubChainId()
853
+ });
854
+
855
+ let signature;
856
+ try {
857
+ const toHexUtf8 = (s) => {
858
+ try {
859
+ const enc = new TextEncoder();
860
+ const bytes = enc.encode(s);
861
+ let hex = '0x';
862
+ for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, '0');
863
+ return hex;
864
+ } catch {
865
+ let hex = '0x';
866
+ for (let i = 0; i < s.length; i++) hex += s.charCodeAt(i).toString(16).padStart(2, '0');
867
+ return hex;
868
+ }
869
+ };
870
+
871
+ const isFarcasterWallet = (() => {
872
+ if (typeof window === 'undefined') return false;
873
+ try {
874
+ const w = window;
875
+ const fc = w.farcaster;
876
+ if (!fc || !fc.context) return false;
877
+ const fcProvider = fc.provider || fc.walletProvider || (fc.context && fc.context.walletProvider);
878
+ if (fcProvider === provider) return true;
879
+ if (w.mini && w.mini.wallet === provider && fc && fc.context) return true;
880
+ if (w.ethereum === provider && fc && fc.context) return true;
881
+ } catch {
882
+ void 0;
883
+ }
884
+ return false;
885
+ })();
886
+
887
+ if (isFarcasterWallet) {
888
+ try {
889
+ const hexMsg = toHexUtf8(message);
890
+ signature = await provider.request({ method: 'personal_sign', params: [hexMsg, walletAddress] });
891
+ } catch (e) {
892
+ void e;
893
+ }
894
+ }
895
+
896
+ if (!signature) {
897
+ try {
898
+ signature = await provider.request({ method: 'personal_sign', params: [message, walletAddress] });
899
+ } catch (e) {
900
+ const msg = String(e && (e.message || e.reason) || e || '').toLowerCase();
901
+ const errCode = (e && (e.code || (e.error && e.error.code))) || null;
902
+ const needsHex = /byte|bytes|invalid byte sequence|encoding|non-hex/i.test(msg);
903
+
904
+ const unsupportedRe =
905
+ /method.*not.*supported|unsupported|not implemented|method not found|unknown method|does not support/i;
906
+ const methodUnsupported = (
907
+ unsupportedRe.test(msg) ||
908
+ errCode === -32601 ||
909
+ errCode === 4200 ||
910
+ (msg.includes('personal_sign') && msg.includes('not')) ||
911
+ (msg.includes('request method') && msg.includes('not supported'))
912
+ );
913
+
914
+ if (methodUnsupported) {
915
+ this._log('personal_sign not supported; attempting eth_sign fallback');
916
+ try {
917
+ const enc = new TextEncoder();
918
+ const bytes = enc.encode(message);
919
+ const prefix = `\x19Ethereum Signed Message:\n${bytes.length}`;
920
+ const full = new Uint8Array(prefix.length + bytes.length);
921
+ for (let i = 0; i < prefix.length; i++) full[i] = prefix.charCodeAt(i);
922
+ full.set(bytes, prefix.length);
923
+ let payloadHex = '0x';
924
+ for (let i = 0; i < full.length; i++) payloadHex += full[i].toString(16).padStart(2, '0');
925
+ try {
926
+ if (typeof window !== 'undefined') window.__NEUS_ALLOW_ETH_SIGN__ = true;
927
+ } catch {
928
+ void 0;
929
+ }
930
+ signature = await provider.request({ method: 'eth_sign', params: [walletAddress, payloadHex], neusAllowEthSign: true });
931
+ try {
932
+ if (typeof window !== 'undefined') delete window.__NEUS_ALLOW_ETH_SIGN__;
933
+ } catch {
934
+ void 0;
935
+ }
936
+ } catch (fallbackErr) {
937
+ this._log('eth_sign fallback failed', { message: fallbackErr?.message || String(fallbackErr) });
938
+ try {
939
+ if (typeof window !== 'undefined') delete window.__NEUS_ALLOW_ETH_SIGN__;
940
+ } catch {
941
+ void 0;
942
+ }
943
+ throw e;
944
+ }
945
+ } else if (needsHex) {
946
+ this._log('Retrying personal_sign with hex-encoded message');
947
+ const hexMsg = toHexUtf8(message);
948
+ signature = await provider.request({ method: 'personal_sign', params: [hexMsg, walletAddress] });
949
+ } else {
950
+ throw e;
951
+ }
952
+ }
953
+ }
954
+ } catch (error) {
955
+ if (error.code === 4001) {
956
+ throw new ValidationError('User rejected the signature request. Signature is required to create proofs.');
957
+ }
958
+ throw new ValidationError(`Failed to sign verification message: ${error.message}`);
959
+ }
960
+
961
+ return this.verify({
962
+ verifierIds,
963
+ data: verificationData,
964
+ walletAddress,
965
+ signature,
966
+ signedTimestamp,
967
+ options
968
+ });
969
+ }
970
+
971
+ const {
972
+ verifierIds,
973
+ data,
974
+ walletAddress,
975
+ signature,
976
+ signedTimestamp,
977
+ chainId,
978
+ chain,
979
+ signatureMethod,
980
+ options = {}
981
+ } = params;
982
+
983
+ const resolvedChainId = chainId || (chain ? null : NEUS_CONSTANTS.HUB_CHAIN_ID);
984
+
985
+ const normalizeVerifierId = (id) => {
986
+ if (typeof id !== 'string') return id;
987
+ const match = id.match(/^(.*)@\d+$/);
988
+ return match ? match[1] : id;
989
+ };
990
+ const normalizedVerifierIds = Array.isArray(verifierIds) ? verifierIds.map(normalizeVerifierId) : [];
991
+
992
+ if (!normalizedVerifierIds || normalizedVerifierIds.length === 0) {
993
+ throw new ValidationError('verifierIds array is required');
994
+ }
995
+ if (!data || typeof data !== 'object') {
996
+ throw new ValidationError('data object is required');
997
+ }
998
+ if (!walletAddress || typeof walletAddress !== 'string') {
999
+ throw new ValidationError('walletAddress is required');
1000
+ }
1001
+ if (!signature) {
1002
+ throw new ValidationError('signature is required');
1003
+ }
1004
+ if (!signedTimestamp || typeof signedTimestamp !== 'number') {
1005
+ throw new ValidationError('signedTimestamp is required');
1006
+ }
1007
+ if (resolvedChainId !== null && typeof resolvedChainId !== 'number') {
1008
+ throw new ValidationError('chainId must be a number');
1009
+ }
1010
+
1011
+ for (const verifierId of normalizedVerifierIds) {
1012
+ const validation = validateVerifierData(verifierId, data);
1013
+ if (!validation.valid) {
1014
+ throw new ValidationError(`Validation failed for verifier '${verifierId}': ${validation.error}`);
1015
+ }
1016
+ }
1017
+
1018
+ const optionsPayload = {
1019
+ ...(options && typeof options === 'object' ? options : {}),
1020
+ targetChains: Array.isArray(options?.targetChains) ? options.targetChains : [],
1021
+ privacyLevel: options?.privacyLevel || 'private',
1022
+ publicDisplay: options?.publicDisplay || false,
1023
+ storeOriginalContent:
1024
+ typeof options?.storeOriginalContent === 'boolean' ? options.storeOriginalContent : true
1025
+ };
1026
+ if (typeof options?.enableIpfs === 'boolean') optionsPayload.enableIpfs = options.enableIpfs;
1027
+
1028
+ const requestData = {
1029
+ verifierIds: normalizedVerifierIds,
1030
+ data,
1031
+ walletAddress,
1032
+ signature,
1033
+ signedTimestamp,
1034
+ ...(resolvedChainId !== null && { chainId: resolvedChainId }),
1035
+ ...(chain && { chain }),
1036
+ ...(signatureMethod && { signatureMethod }),
1037
+ options: optionsPayload
1038
+ };
1039
+
1040
+ const response = await this._makeRequest('POST', '/api/v1/verification', requestData);
1041
+
1042
+ if (!response.success) {
1043
+ throw new ApiError(`Verification failed: ${response.error?.message || 'Unknown error'}`, response.error);
1044
+ }
1045
+
1046
+ return this._formatResponse(response);
1047
+ }
1048
+
1049
+ async getProof(proofId) {
1050
+ if (!proofId || typeof proofId !== 'string') {
1051
+ throw new ValidationError('proofId is required');
1052
+ }
1053
+ const response = await this._makeRequest('GET', `/api/v1/proofs/${proofId}`);
1054
+
1055
+ if (!response.success) {
1056
+ throw new ApiError(`Failed to get proof: ${response.error?.message || 'Unknown error'}`, response.error);
1057
+ }
1058
+
1059
+ return this._formatResponse(response);
1060
+ }
1061
+
1062
+ async getPrivateProof(proofId, wallet = null) {
1063
+ if (!proofId || typeof proofId !== 'string') {
1064
+ throw new ValidationError('proofId is required');
1065
+ }
1066
+
1067
+ const isPreSignedAuth = wallet &&
1068
+ typeof wallet === 'object' &&
1069
+ typeof wallet.walletAddress === 'string' &&
1070
+ typeof wallet.signature === 'string' &&
1071
+ typeof wallet.signedTimestamp === 'number';
1072
+ if (isPreSignedAuth) {
1073
+ const auth = wallet;
1074
+ const headers = {
1075
+ 'x-wallet-address': String(auth.walletAddress),
1076
+ 'x-signature': String(auth.signature),
1077
+ 'x-signed-timestamp': String(auth.signedTimestamp),
1078
+ ...(typeof auth.chain === 'string' && auth.chain.trim() ? { 'x-chain': auth.chain.trim() } : {}),
1079
+ ...(typeof auth.signatureMethod === 'string' && auth.signatureMethod.trim() ? { 'x-signature-method': auth.signatureMethod.trim() } : {})
1080
+ };
1081
+ const response = await this._makeRequest('GET', `/api/v1/proofs/${proofId}`, null, headers);
1082
+ if (!response.success) {
1083
+ throw new ApiError(
1084
+ `Failed to access private proof: ${response.error?.message || 'Unauthorized'}`,
1085
+ response.error
1086
+ );
1087
+ }
1088
+ return this._formatResponse(response);
1089
+ }
1090
+
1091
+ const providerWallet = wallet || this._getDefaultBrowserWallet();
1092
+ const { signerWalletAddress: walletAddress, provider } = await this._resolveWalletSigner(providerWallet);
1093
+ if (!walletAddress || typeof walletAddress !== 'string') {
1094
+ throw new ConfigurationError('No wallet accounts available');
1095
+ }
1096
+ const signerIsEvm = EVM_ADDRESS_RE.test(this._normalizeIdentity(walletAddress));
1097
+ const chain = this._inferChainForAddress(walletAddress);
1098
+ const signatureMethod = signerIsEvm ? 'eip191' : 'ed25519';
1099
+
1100
+ const signedTimestamp = Date.now();
1101
+
1102
+ const message = constructVerificationMessage({
1103
+ walletAddress,
1104
+ signedTimestamp,
1105
+ data: { action: 'access_private_proof', qHash: proofId },
1106
+ verifierIds: ['ownership-basic'],
1107
+ ...(signerIsEvm ? { chainId: this._getHubChainId() } : { chain })
1108
+ });
1109
+
1110
+ let signature;
1111
+ try {
1112
+ signature = await signMessage({
1113
+ provider,
1114
+ message,
1115
+ walletAddress,
1116
+ ...(signerIsEvm ? {} : { chain })
1117
+ });
1118
+ } catch (error) {
1119
+ if (error.code === 4001) {
1120
+ throw new ValidationError('User rejected signature request');
1121
+ }
1122
+ throw new ValidationError(`Failed to sign message: ${error.message}`);
1123
+ }
1124
+
1125
+ const response = await this._makeRequest('GET', `/api/v1/proofs/${proofId}`, null, {
1126
+ 'x-wallet-address': walletAddress,
1127
+ 'x-signature': signature,
1128
+ 'x-signed-timestamp': signedTimestamp.toString(),
1129
+ ...(signerIsEvm ? {} : { 'x-chain': chain, 'x-signature-method': signatureMethod })
1130
+ });
1131
+
1132
+ if (!response.success) {
1133
+ throw new ApiError(
1134
+ `Failed to access private proof: ${response.error?.message || 'Unauthorized'}`,
1135
+ response.error
1136
+ );
1137
+ }
1138
+
1139
+ return this._formatResponse(response);
1140
+ }
1141
+
1142
+ async isHealthy() {
1143
+ try {
1144
+ const response = await this._makeRequest('GET', '/api/v1/health');
1145
+ return response.success === true;
1146
+ } catch {
1147
+ return false;
1148
+ }
1149
+ }
1150
+
1151
+ async getVerifiers() {
1152
+ const catalog = await this.getVerifierCatalog();
1153
+ return Array.isArray(catalog?.data) ? catalog.data : [];
1154
+ }
1155
+
1156
+ async getVerifierCatalog() {
1157
+ const response = await this._makeRequest('GET', '/api/v1/verification/verifiers');
1158
+ if (!response.success) {
1159
+ throw new ApiError(`Failed to get verifiers: ${response.error?.message || 'Unknown error'}`, response.error);
1160
+ }
1161
+ return {
1162
+ data: Array.isArray(response.data) ? response.data : [],
1163
+ metadata:
1164
+ response.metadata && typeof response.metadata === 'object' && !Array.isArray(response.metadata)
1165
+ ? response.metadata
1166
+ : {},
1167
+ meta:
1168
+ response.meta && typeof response.meta === 'object' && !Array.isArray(response.meta)
1169
+ ? response.meta
1170
+ : {}
1171
+ };
1172
+ }
1173
+
1174
+ async pollProofStatus(proofId, options = {}) {
1175
+ const {
1176
+ interval = 5000,
1177
+ timeout = 120000,
1178
+ onProgress
1179
+ } = options;
1180
+
1181
+ if (!proofId || typeof proofId !== 'string') {
1182
+ throw new ValidationError('proofId is required');
1183
+ }
1184
+
1185
+ const startTime = Date.now();
1186
+ let consecutiveRateLimits = 0;
1187
+
1188
+ while (Date.now() - startTime < timeout) {
1189
+ try {
1190
+ const status = await this.getProof(proofId);
1191
+ consecutiveRateLimits = 0;
1192
+
1193
+ if (onProgress && typeof onProgress === 'function') {
1194
+ onProgress(status.data || status);
1195
+ }
1196
+
1197
+ const currentStatus = status.data?.status || status.status;
1198
+ if (this._isTerminalStatus(currentStatus)) {
1199
+ this._log('Verification completed', { status: currentStatus, duration: Date.now() - startTime });
1200
+ return status;
1201
+ }
1202
+
1203
+ await new Promise(resolve => setTimeout(resolve, interval));
1204
+
1205
+ } catch (error) {
1206
+ this._log('Status poll error', error.message);
1207
+ if (error instanceof ValidationError) {
1208
+ throw error;
1209
+ }
1210
+
1211
+ let nextDelay = interval;
1212
+ if (error instanceof ApiError && Number(error.statusCode) === 429) {
1213
+ consecutiveRateLimits += 1;
1214
+ const exp = Math.min(6, consecutiveRateLimits);
1215
+ const base = Math.max(500, Number(interval) || 0);
1216
+ const max = 30000;
1217
+ const backoff = Math.min(max, base * Math.pow(2, exp));
1218
+ const jitter = Math.floor(backoff * (0.5 + Math.random() * 0.5));
1219
+ nextDelay = jitter;
1220
+ }
1221
+
1222
+ await new Promise(resolve => setTimeout(resolve, nextDelay));
1223
+ }
1224
+ }
1225
+
1226
+ throw new NetworkError(`Polling timeout after ${timeout}ms`, 'POLLING_TIMEOUT');
1227
+ }
1228
+
1229
+ async detectChainId() {
1230
+ if (typeof window === 'undefined' || !window.ethereum) {
1231
+ throw new ConfigurationError('No Web3 wallet detected');
1232
+ }
1233
+
1234
+ try {
1235
+ const chainId = await window.ethereum.request({ method: 'eth_chainId' });
1236
+ return parseInt(chainId, 16);
1237
+ } catch (error) {
1238
+ throw new NetworkError(`Failed to detect chain ID: ${error.message}`);
1239
+ }
1240
+ }
1241
+
1242
+ async revokeOwnProof(proofId, wallet) {
1243
+ if (!proofId || typeof proofId !== 'string') {
1244
+ throw new ValidationError('proofId is required');
1245
+ }
1246
+ const providerWallet = wallet || this._getDefaultBrowserWallet();
1247
+ const { signerWalletAddress: address, provider } = await this._resolveWalletSigner(providerWallet);
1248
+ if (!address || typeof address !== 'string') {
1249
+ throw new ConfigurationError('No wallet accounts available');
1250
+ }
1251
+ const signerIsEvm = EVM_ADDRESS_RE.test(this._normalizeIdentity(address));
1252
+ const chain = this._inferChainForAddress(address);
1253
+ const signatureMethod = signerIsEvm ? 'eip191' : 'ed25519';
1254
+ const signedTimestamp = Date.now();
1255
+
1256
+ const message = constructVerificationMessage({
1257
+ walletAddress: address,
1258
+ signedTimestamp,
1259
+ data: { action: 'revoke_proof', qHash: proofId },
1260
+ verifierIds: ['ownership-basic'],
1261
+ ...(signerIsEvm ? { chainId: this._getHubChainId() } : { chain })
1262
+ });
1263
+
1264
+ let signature;
1265
+ try {
1266
+ signature = await signMessage({
1267
+ provider,
1268
+ message,
1269
+ walletAddress: address,
1270
+ ...(signerIsEvm ? {} : { chain })
1271
+ });
1272
+ } catch (error) {
1273
+ if (error.code === 4001) {
1274
+ throw new ValidationError('User rejected revocation signature');
1275
+ }
1276
+ throw new ValidationError(`Failed to sign revocation: ${error.message}`);
1277
+ }
1278
+
1279
+ const res = await fetch(`${this.config.apiUrl}/api/v1/proofs/revoke-self/${proofId}`, {
1280
+ method: 'POST',
1281
+ headers: { 'Content-Type': 'application/json' },
1282
+ body: JSON.stringify({
1283
+ walletAddress: address,
1284
+ signature,
1285
+ signedTimestamp,
1286
+ ...(signerIsEvm ? {} : { chain, signatureMethod })
1287
+ })
1288
+ });
1289
+ const json = await res.json();
1290
+ if (!json.success) {
1291
+ throw new ApiError(json.error?.message || 'Failed to revoke proof', json.error);
1292
+ }
1293
+ return true;
1294
+ }
1295
+
1296
+ async getProofsByWallet(walletAddress, options = {}) {
1297
+ if (!walletAddress || typeof walletAddress !== 'string') {
1298
+ throw new ValidationError('walletAddress is required');
1299
+ }
1300
+
1301
+ const id = walletAddress.trim();
1302
+ const pathId = /^0x[a-fA-F0-9]{40}$/i.test(id) ? id.toLowerCase() : id;
1303
+
1304
+ const qs = [];
1305
+ if (options.limit) qs.push(`limit=${encodeURIComponent(String(options.limit))}`);
1306
+ if (options.offset) qs.push(`offset=${encodeURIComponent(String(options.offset))}`);
1307
+ if (options.qHash) qs.push(`qHash=${encodeURIComponent(options.qHash.toLowerCase())}`);
1308
+
1309
+ const query = qs.length ? `?${qs.join('&')}` : '';
1310
+ const response = await this._makeRequest(
1311
+ 'GET',
1312
+ `/api/v1/proofs/by-wallet/${encodeURIComponent(pathId)}${query}`
1313
+ );
1314
+
1315
+ if (!response.success) {
1316
+ throw new ApiError(`Failed to get proofs: ${response.error?.message || 'Unknown error'}`, response.error);
1317
+ }
1318
+
1319
+ const proofs = response.data?.proofs || response.data || response.proofs || [];
1320
+ return {
1321
+ success: true,
1322
+ proofs: Array.isArray(proofs) ? proofs : [],
1323
+ totalCount: response.data?.totalCount ?? proofs.length,
1324
+ hasMore: Boolean(response.data?.hasMore),
1325
+ nextOffset: response.data?.nextOffset ?? null
1326
+ };
1327
+ }
1328
+
1329
+ async getPrivateProofsByWallet(walletAddress, options = {}, wallet = null) {
1330
+ if (!walletAddress || typeof walletAddress !== 'string') {
1331
+ throw new ValidationError('walletAddress is required');
1332
+ }
1333
+
1334
+ const id = walletAddress.trim();
1335
+ const pathId = /^0x[a-fA-F0-9]{40}$/i.test(id) ? id.toLowerCase() : id;
1336
+
1337
+ const requestedIdentity = this._normalizeIdentity(id);
1338
+
1339
+ if (!wallet) {
1340
+ const defaultWallet = this._getDefaultBrowserWallet();
1341
+ if (!defaultWallet) {
1342
+ throw new ConfigurationError('No wallet provider available');
1343
+ }
1344
+ wallet = defaultWallet;
1345
+ }
1346
+
1347
+ const { signerWalletAddress, provider } = await this._resolveWalletSigner(wallet);
1348
+
1349
+ if (!signerWalletAddress || typeof signerWalletAddress !== 'string') {
1350
+ throw new ConfigurationError('No wallet accounts available');
1351
+ }
1352
+
1353
+ const normalizedSigner = this._normalizeIdentity(signerWalletAddress);
1354
+ if (!normalizedSigner || normalizedSigner !== requestedIdentity) {
1355
+ throw new ValidationError('wallet must match walletAddress for private proof access');
1356
+ }
1357
+
1358
+ const signerIsEvm = EVM_ADDRESS_RE.test(normalizedSigner);
1359
+ const chain = this._inferChainForAddress(normalizedSigner, options?.chain);
1360
+ const signatureMethod = (typeof options?.signatureMethod === 'string' && options.signatureMethod.trim())
1361
+ ? options.signatureMethod.trim()
1362
+ : (signerIsEvm ? 'eip191' : 'ed25519');
1363
+
1364
+ const signedTimestamp = Date.now();
1365
+ const message = constructVerificationMessage({
1366
+ walletAddress: signerWalletAddress,
1367
+ signedTimestamp,
1368
+ data: { action: 'access_private_proofs_by_wallet', walletAddress: normalizedSigner },
1369
+ verifierIds: ['ownership-basic'],
1370
+ ...(signerIsEvm ? { chainId: this._getHubChainId() } : { chain })
1371
+ });
1372
+
1373
+ let signature;
1374
+ try {
1375
+ signature = await signMessage({
1376
+ provider,
1377
+ message,
1378
+ walletAddress: signerWalletAddress,
1379
+ ...(signerIsEvm ? {} : { chain })
1380
+ });
1381
+ } catch (error) {
1382
+ if (error.code === 4001) {
1383
+ throw new ValidationError('User rejected signature request');
1384
+ }
1385
+ throw new ValidationError(`Failed to sign message: ${error.message}`);
1386
+ }
1387
+
1388
+ const qs = [];
1389
+ if (options.limit) qs.push(`limit=${encodeURIComponent(String(options.limit))}`);
1390
+ if (options.offset) qs.push(`offset=${encodeURIComponent(String(options.offset))}`);
1391
+ if (options.qHash) qs.push(`qHash=${encodeURIComponent(options.qHash.toLowerCase())}`);
1392
+ const query = qs.length ? `?${qs.join('&')}` : '';
1393
+
1394
+ const response = await this._makeRequest('GET', `/api/v1/proofs/by-wallet/${encodeURIComponent(pathId)}${query}`, null, {
1395
+ 'x-wallet-address': signerWalletAddress,
1396
+ 'x-signature': signature,
1397
+ 'x-signed-timestamp': signedTimestamp.toString(),
1398
+ ...(signerIsEvm ? {} : { 'x-chain': chain, 'x-signature-method': signatureMethod })
1399
+ });
1400
+
1401
+ if (!response.success) {
1402
+ throw new ApiError(`Failed to get proofs: ${response.error?.message || 'Unauthorized'}`, response.error);
1403
+ }
1404
+
1405
+ const proofs = response.data?.proofs || response.data || response.proofs || [];
1406
+ return {
1407
+ success: true,
1408
+ proofs: Array.isArray(proofs) ? proofs : [],
1409
+ totalCount: response.data?.totalCount ?? proofs.length,
1410
+ hasMore: Boolean(response.data?.hasMore),
1411
+ nextOffset: response.data?.nextOffset ?? null
1412
+ };
1413
+ }
1414
+
1415
+ async gateCheck(params = {}) {
1416
+ const address = (params.address || '').toString();
1417
+ if (!validateUniversalAddress(address, params.chain)) {
1418
+ throw new ValidationError('Valid address is required');
1419
+ }
1420
+
1421
+ const qs = new URLSearchParams();
1422
+ qs.set('address', address);
1423
+
1424
+ const setIfPresent = (key, value) => {
1425
+ if (value === undefined || value === null) return;
1426
+ const str = typeof value === 'string' ? value : String(value);
1427
+ if (str.length === 0) return;
1428
+ qs.set(key, str);
1429
+ };
1430
+
1431
+ const setBoolIfPresent = (key, value) => {
1432
+ if (value === undefined || value === null) return;
1433
+ qs.set(key, value ? 'true' : 'false');
1434
+ };
1435
+
1436
+ const setCsvIfPresent = (key, value) => {
1437
+ if (value === undefined || value === null) return;
1438
+ if (Array.isArray(value)) {
1439
+ const items = value.map(v => String(v).trim()).filter(Boolean);
1440
+ if (items.length) qs.set(key, items.join(','));
1441
+ return;
1442
+ }
1443
+ setIfPresent(key, value);
1444
+ };
1445
+
1446
+ setCsvIfPresent('verifierIds', params.verifierIds);
1447
+ setBoolIfPresent('requireAll', params.requireAll);
1448
+ setIfPresent('minCount', params.minCount);
1449
+ setIfPresent('sinceDays', params.sinceDays);
1450
+ setIfPresent('since', params.since);
1451
+ setIfPresent('limit', params.limit);
1452
+ setBoolIfPresent('includePrivate', params.includePrivate);
1453
+ setBoolIfPresent('includeQHashes', params.includeQHashes);
1454
+
1455
+ setIfPresent('referenceType', params.referenceType);
1456
+ setIfPresent('referenceId', params.referenceId);
1457
+ setIfPresent('tag', params.tag);
1458
+ setCsvIfPresent('tags', params.tags);
1459
+ setIfPresent('contentType', params.contentType);
1460
+ setIfPresent('content', params.content);
1461
+ setIfPresent('contentHash', params.contentHash);
1462
+
1463
+ setIfPresent('contractAddress', params.contractAddress);
1464
+ setIfPresent('tokenId', params.tokenId);
1465
+ setIfPresent('chainId', params.chainId);
1466
+ setIfPresent('domain', params.domain);
1467
+ setIfPresent('minBalance', params.minBalance);
1468
+
1469
+ setIfPresent('provider', params.provider);
1470
+ setIfPresent('handle', params.handle);
1471
+ setIfPresent('namespace', params.namespace);
1472
+ setIfPresent('ownerAddress', params.ownerAddress);
1473
+ setIfPresent('riskLevel', params.riskLevel);
1474
+ setBoolIfPresent('sanctioned', params.sanctioned);
1475
+ setBoolIfPresent('poisoned', params.poisoned);
1476
+ setIfPresent('primaryWalletAddress', params.primaryWalletAddress);
1477
+ setIfPresent('secondaryWalletAddress', params.secondaryWalletAddress);
1478
+ setIfPresent('verificationMethod', params.verificationMethod);
1479
+
1480
+ let headersOverride = null;
1481
+ if (params.includePrivate === true) {
1482
+ const provided = params.privateAuth && typeof params.privateAuth === 'object' ? params.privateAuth : null;
1483
+ let auth = provided;
1484
+ if (!auth) {
1485
+ const walletCandidate = params.wallet || this._getDefaultBrowserWallet();
1486
+ if (walletCandidate) {
1487
+ auth = await this._buildPrivateGateAuth({
1488
+ address,
1489
+ wallet: walletCandidate,
1490
+ chain: params.chain,
1491
+ signatureMethod: params.signatureMethod
1492
+ });
1493
+ }
1494
+ }
1495
+ if (auth) {
1496
+ const normalizedAuthWallet = this._normalizeIdentity(auth.walletAddress);
1497
+ const normalizedAddress = this._normalizeIdentity(address);
1498
+ if (!normalizedAuthWallet || normalizedAuthWallet !== normalizedAddress) {
1499
+ throw new ValidationError('privateAuth.walletAddress must match address when includePrivate=true');
1500
+ }
1501
+ const authChain = (typeof auth.chain === 'string' && auth.chain.includes(':')) ? auth.chain.trim() : null;
1502
+ const authSignatureMethod = (typeof auth.signatureMethod === 'string' && auth.signatureMethod.trim())
1503
+ ? auth.signatureMethod.trim()
1504
+ : null;
1505
+ headersOverride = {
1506
+ 'x-wallet-address': String(auth.walletAddress),
1507
+ 'x-signature': String(auth.signature),
1508
+ 'x-signed-timestamp': String(auth.signedTimestamp),
1509
+ ...(authChain ? { 'x-chain': authChain } : {}),
1510
+ ...(authSignatureMethod ? { 'x-signature-method': authSignatureMethod } : {})
1511
+ };
1512
+ }
1513
+ }
1514
+
1515
+ const response = await this._makeRequest('GET', `/api/v1/proofs/check?${qs.toString()}`, null, headersOverride);
1516
+ if (!response.success) {
1517
+ throw new ApiError(`Gate check failed: ${response.error?.message || 'Unknown error'}`, response.error);
1518
+ }
1519
+ return response;
1520
+ }
1521
+
1522
+ async checkGate(params) {
1523
+ const { walletAddress, requirements, proofs: preloadedProofs } = params;
1524
+
1525
+ if (!validateUniversalAddress(walletAddress)) {
1526
+ throw new ValidationError('Valid walletAddress is required');
1527
+ }
1528
+ if (!Array.isArray(requirements) || requirements.length === 0) {
1529
+ throw new ValidationError('requirements array is required and must not be empty');
1530
+ }
1531
+
1532
+ let proofs = preloadedProofs;
1533
+ if (!proofs) {
1534
+ const result = await this.getProofsByWallet(walletAddress, { limit: 100 });
1535
+ proofs = result.proofs;
1536
+ }
1537
+
1538
+ const now = Date.now();
1539
+ const existing = {};
1540
+ const missing = [];
1541
+
1542
+ for (const req of requirements) {
1543
+ const { verifierId, maxAgeMs, optional = false, minCount = 1, match } = req;
1544
+
1545
+ const matchingProofs = (proofs || []).filter(proof => {
1546
+ const verifiedVerifiers = proof.verifiedVerifiers || [];
1547
+ const verifier = verifiedVerifiers.find(
1548
+ v => v.verifierId === verifierId && v.verified === true
1549
+ );
1550
+ if (!verifier) return false;
1551
+
1552
+ if (proof.revokedAt) return false;
1553
+
1554
+ if (maxAgeMs) {
1555
+ const proofTimestamp = proof.createdAt || proof.signedTimestamp || 0;
1556
+ const proofAge = now - proofTimestamp;
1557
+ if (proofAge > maxAgeMs) return false;
1558
+ }
1559
+
1560
+ if (match && typeof match === 'object') {
1561
+ const data = verifier.data || {};
1562
+ const input = data.input || {};
1563
+ const matchObj = Array.isArray(match)
1564
+ ? Object.fromEntries(
1565
+ match
1566
+ .filter((m) => m && m.path && String(m.value ?? '').trim() !== '')
1567
+ .map((m) => [String(m.path).trim(), m.value])
1568
+ )
1569
+ : match;
1570
+
1571
+ for (const [key, expected] of Object.entries(matchObj)) {
1572
+ let actualValue = null;
1573
+
1574
+ if (key.includes('.')) {
1575
+ const parts = key.split('.');
1576
+ let current = data;
1577
+
1578
+ if (parts[0] === 'input' && input) {
1579
+ current = input;
1580
+ parts.shift();
1581
+ }
1582
+
1583
+ for (const part of parts) {
1584
+ if (current && typeof current === 'object' && part in current) {
1585
+ current = current[part];
1586
+ } else {
1587
+ current = undefined;
1588
+ break;
1589
+ }
1590
+ }
1591
+ actualValue = current;
1592
+ } else {
1593
+ actualValue = input[key] || data[key];
1594
+ }
1595
+
1596
+ if (key === 'content' && actualValue === undefined) {
1597
+ actualValue = data.reference?.id || data.content;
1598
+ }
1599
+
1600
+ if (actualValue === undefined) {
1601
+ const claims = data.claims || {};
1602
+ if (key === 'contractAddress') {
1603
+ actualValue = input.contractAddress || data.contractAddress;
1604
+ } else if (key === 'tokenId') {
1605
+ actualValue = input.tokenId || data.tokenId;
1606
+ } else if (key === 'chainId') {
1607
+ actualValue = input.chainId || data.chainId;
1608
+ } else if (key === 'ownerAddress') {
1609
+ actualValue = input.ownerAddress || data.owner || data.walletAddress;
1610
+ } else if (key === 'minBalance') {
1611
+ actualValue = input.minBalance || data.onChainData?.requiredMinBalance || data.minBalance;
1612
+ } else if (key === 'primaryWalletAddress') {
1613
+ actualValue = data.primaryWalletAddress;
1614
+ } else if (key === 'secondaryWalletAddress') {
1615
+ actualValue = data.secondaryWalletAddress;
1616
+ } else if (key === 'verificationMethod') {
1617
+ actualValue = data.verificationMethod;
1618
+ } else if (key === 'domain') {
1619
+ actualValue = data.domain;
1620
+ } else if (key === 'handle') {
1621
+ actualValue = data.handle || data.pseudonymId;
1622
+ } else if (key === 'namespace') {
1623
+ actualValue =
1624
+ data.namespace !== undefined && data.namespace !== null && data.namespace !== ''
1625
+ ? data.namespace
1626
+ : 'neus';
1627
+ } else if (key === 'claims.sanctions_passed') {
1628
+ actualValue = claims.sanctions_passed ?? claims.sanctionsPassed;
1629
+ } else if (key === 'claims.age_min') {
1630
+ actualValue = claims.age_min ?? claims.ageMin;
1631
+ } else if (key === 'neusPersonhoodId') {
1632
+ actualValue = data.neusPersonhoodId;
1633
+ } else if (key === 'riskLevel') {
1634
+ actualValue = data.riskLevel;
1635
+ } else if (key === 'sanctioned') {
1636
+ actualValue = data.sanctioned;
1637
+ } else if (key === 'poisoned') {
1638
+ actualValue = data.poisoned;
1639
+ }
1640
+ }
1641
+
1642
+ if (key === 'contentHash' && actualValue === undefined && data.content) {
1643
+ try {
1644
+ let hash = 0;
1645
+ const str = String(data.content);
1646
+ for (let i = 0; i < str.length; i++) {
1647
+ const char = str.charCodeAt(i);
1648
+ hash = ((hash << 5) - hash) + char;
1649
+ hash = hash & hash;
1650
+ }
1651
+ actualValue = `0x${ Math.abs(hash).toString(16).padStart(64, '0').substring(0, 66)}`;
1652
+ } catch {
1653
+ actualValue = String(data.content);
1654
+ }
1655
+ }
1656
+
1657
+ let normalizedActual = actualValue;
1658
+ let normalizedExpected = expected;
1659
+
1660
+ if (actualValue === undefined || actualValue === null) {
1661
+ return false;
1662
+ }
1663
+
1664
+ if (typeof actualValue === 'boolean' || (key && (key.includes('sanctions') || key.includes('sanctioned') || key.includes('poisoned')))) {
1665
+ const bActual = Boolean(actualValue);
1666
+ const bExpected = expected === true || expected === 'true' || String(expected).toLowerCase() === 'true';
1667
+ if (bActual !== bExpected) return false;
1668
+ continue;
1669
+ }
1670
+
1671
+ if (key === 'chainId' || (key === 'tokenId' && (typeof actualValue === 'number' || !isNaN(Number(actualValue))))) {
1672
+ normalizedActual = Number(actualValue);
1673
+ normalizedExpected = Number(expected);
1674
+ if (isNaN(normalizedActual) || isNaN(normalizedExpected)) return false;
1675
+ }
1676
+ else if (typeof actualValue === 'string' && (actualValue.startsWith('0x') || actualValue.length > 20)) {
1677
+ normalizedActual = actualValue.toLowerCase();
1678
+ normalizedExpected = typeof expected === 'string' ? String(expected).toLowerCase() : expected;
1679
+ }
1680
+ else {
1681
+ normalizedActual = actualValue;
1682
+ normalizedExpected = expected;
1683
+ }
1684
+
1685
+ if (normalizedActual !== normalizedExpected) {
1686
+ return false;
1687
+ }
1688
+ }
1689
+ }
1690
+
1691
+ return true;
1692
+ });
1693
+
1694
+ if (matchingProofs.length >= minCount) {
1695
+ const sorted = matchingProofs.sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));
1696
+ existing[verifierId] = sorted[0];
1697
+ } else if (!optional) {
1698
+ missing.push(req);
1699
+ }
1700
+ }
1701
+
1702
+ return {
1703
+ satisfied: missing.length === 0,
1704
+ missing,
1705
+ existing,
1706
+ allProofs: proofs
1707
+ };
1708
+ }
1709
+
1710
+ async _getWalletAddress() {
1711
+ if (typeof window === 'undefined' || !window.ethereum) {
1712
+ throw new ConfigurationError('No Web3 wallet detected');
1713
+ }
1714
+
1715
+ const accounts = await window.ethereum.request({ method: 'eth_accounts' });
1716
+ if (!accounts || accounts.length === 0) {
1717
+ throw new ConfigurationError('No wallet accounts available');
1718
+ }
1719
+
1720
+ return accounts[0];
1721
+ }
1722
+
1723
+ async _makeRequest(method, endpoint, data = null, headersOverride = null) {
1724
+ const url = `${this.baseUrl}${endpoint}`;
1725
+
1726
+ const controller = new AbortController();
1727
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
1728
+
1729
+ const options = {
1730
+ method,
1731
+ headers: { ...this.defaultHeaders, ...(headersOverride || {}) },
1732
+ signal: controller.signal
1733
+ };
1734
+
1735
+ if (data && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
1736
+ options.body = JSON.stringify(data);
1737
+ }
1738
+
1739
+ this._log(`${method} ${endpoint}`, data ? { requestBodyKeys: Object.keys(data) } : {});
1740
+
1741
+ try {
1742
+ const response = await fetch(url, options);
1743
+ clearTimeout(timeoutId);
1744
+
1745
+ let responseData;
1746
+ try {
1747
+ responseData = await response.json();
1748
+ } catch {
1749
+ responseData = { error: { message: 'Invalid JSON response' } };
1750
+ }
1751
+
1752
+ if (!response.ok) {
1753
+ throw ApiError.fromResponse(response, responseData);
1754
+ }
1755
+
1756
+ return responseData;
1757
+
1758
+ } catch (error) {
1759
+ clearTimeout(timeoutId);
1760
+
1761
+ if (error.name === 'AbortError') {
1762
+ throw new NetworkError(`Request timeout after ${this.config.timeout}ms`);
1763
+ }
1764
+
1765
+ if (error instanceof ApiError) {
1766
+ throw error;
1767
+ }
1768
+
1769
+ throw new NetworkError(`Network error: ${error.message}`);
1770
+ }
1771
+ }
1772
+
1773
+ _formatResponse(response) {
1774
+ const proofId = response?.data?.proofId ||
1775
+ response?.proofId ||
1776
+ response?.data?.resource?.proofId ||
1777
+ response?.data?.qHash ||
1778
+ response?.qHash ||
1779
+ response?.data?.resource?.qHash ||
1780
+ response?.data?.id;
1781
+ const qHash = response?.data?.qHash ||
1782
+ response?.qHash ||
1783
+ response?.data?.resource?.qHash ||
1784
+ proofId ||
1785
+ response?.data?.id;
1786
+ const finalProofId = proofId || qHash || null;
1787
+ const finalQHash = qHash || proofId || finalProofId;
1788
+
1789
+ const status = response?.data?.status ||
1790
+ response?.status ||
1791
+ response?.data?.resource?.status ||
1792
+ (response?.success ? 'completed' : 'unknown');
1793
+
1794
+ return {
1795
+ success: response.success,
1796
+ proofId: finalProofId,
1797
+ qHash: finalQHash,
1798
+ status,
1799
+ data: response.data,
1800
+ message: response.message,
1801
+ timestamp: Date.now(),
1802
+ proofUrl: finalProofId ? `${this.baseUrl}/api/v1/proofs/${finalProofId}` : null
1803
+ };
1804
+ }
1805
+
1806
+ _isTerminalStatus(status) {
1807
+ const terminalStates = [
1808
+ 'verified',
1809
+ 'verified_crosschain_propagated',
1810
+ 'completed_all_successful',
1811
+ 'failed',
1812
+ 'error',
1813
+ 'rejected',
1814
+ 'cancelled'
1815
+ ];
1816
+ return typeof status === 'string' && terminalStates.some(state => status.includes(state));
1817
+ }
1818
+
1819
+ _log(message, data = {}) {
1820
+ if (this.config.enableLogging) {
1821
+ try {
1822
+ const prefix = '[neus/sdk]';
1823
+ if (data && Object.keys(data).length > 0) {
1824
+ // eslint-disable-next-line no-console -- gated debug logging
1825
+ console.log(prefix, message, data);
1826
+ } else {
1827
+ // eslint-disable-next-line no-console -- gated debug logging
1828
+ console.log(prefix, message);
1829
+ }
1830
+ } catch {
1831
+ void 0;
1832
+ }
1833
+ }
1834
+ }
1835
+ }
1836
+
1837
+ export { PORTABLE_PROOF_SIGNER_HEADER, constructVerificationMessage };