@neus/sdk 1.0.12 → 1.1.1

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/cjs/client.cjs CHANGED
@@ -129,6 +129,83 @@ var ConfigurationError = class extends SDKError {
129
129
  }
130
130
  };
131
131
 
132
+ // sponsor.js
133
+ async function fetchSponsorGrant(params = {}) {
134
+ const {
135
+ apiUrl = "https://api.neus.network",
136
+ appId,
137
+ orgWallet,
138
+ verifierIds = [],
139
+ targetChains = [],
140
+ origin,
141
+ expiresInSeconds = 900,
142
+ fetchImpl = fetch
143
+ } = params;
144
+ const normalizedAppId = typeof appId === "string" ? appId.trim() : "";
145
+ const normalizedOrg = typeof orgWallet === "string" ? orgWallet.trim().toLowerCase() : "";
146
+ if (!normalizedAppId) {
147
+ throw new ValidationError("appId is required for sponsor grant");
148
+ }
149
+ if (!normalizedOrg || !/^0x[a-f0-9]{40}$/.test(normalizedOrg)) {
150
+ throw new ValidationError("orgWallet must be a valid EVM address");
151
+ }
152
+ let base = String(apiUrl || "https://api.neus.network").replace(/\/+$/, "");
153
+ try {
154
+ const url = new URL(base);
155
+ if (url.hostname.endsWith("neus.network") && url.protocol === "http:") {
156
+ url.protocol = "https:";
157
+ }
158
+ base = url.toString().replace(/\/+$/, "");
159
+ } catch {
160
+ }
161
+ const headers = {
162
+ "Content-Type": "application/json",
163
+ Accept: "application/json",
164
+ "X-Neus-App": normalizedAppId,
165
+ "X-Neus-Sdk": "js"
166
+ };
167
+ if (typeof origin === "string" && origin.trim()) {
168
+ headers.Origin = origin.trim();
169
+ }
170
+ const body = {
171
+ orgWallet: normalizedOrg,
172
+ scope: "sponsored-verification",
173
+ expiresInSeconds,
174
+ ...Array.isArray(verifierIds) && verifierIds.length > 0 ? { verifierIds: verifierIds.map((v) => String(v).trim()).filter(Boolean).slice(0, 25) } : {},
175
+ ...Array.isArray(targetChains) && targetChains.length > 0 ? { targetChains: targetChains.filter((n) => Number.isFinite(Number(n))).slice(0, 25) } : {}
176
+ };
177
+ let response;
178
+ try {
179
+ response = await fetchImpl(`${base}/api/v1/sponsor/grant`, {
180
+ method: "POST",
181
+ headers,
182
+ body: JSON.stringify(body)
183
+ });
184
+ } catch (error) {
185
+ throw new NetworkError(`Sponsor grant request failed: ${error?.message || String(error)}`);
186
+ }
187
+ let payload;
188
+ try {
189
+ payload = await response.json();
190
+ } catch {
191
+ payload = { success: false, error: { message: "Invalid JSON response" } };
192
+ }
193
+ if (!response.ok || payload?.success !== true) {
194
+ throw ApiError.fromResponse(response, payload);
195
+ }
196
+ const token = payload?.data?.sponsorGrant;
197
+ if (!token || typeof token !== "string") {
198
+ throw new ApiError("Sponsor grant response missing sponsorGrant token", payload?.error);
199
+ }
200
+ return {
201
+ sponsorGrant: token,
202
+ exp: payload?.data?.exp,
203
+ orgWallet: payload?.data?.orgWallet || normalizedOrg,
204
+ appId: payload?.data?.appId || normalizedAppId,
205
+ maxCredits: payload?.data?.maxCredits
206
+ };
207
+ }
208
+
132
209
  // utils.js
133
210
  var PORTABLE_PROOF_SIGNER_HEADER = "Portable Proof Verification Request";
134
211
  var BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
@@ -599,6 +676,17 @@ var validateVerifierData = (verifierId, data) => {
599
676
  if (data.agentType && !["ai", "bot", "service", "automation", "agent"].includes(data.agentType)) {
600
677
  return { valid: false, error: "agentType must be one of: ai, bot, service, automation, agent" };
601
678
  }
679
+ if (data.defaultRuntime && typeof data.defaultRuntime === "object") {
680
+ if (data.defaultRuntime.provider && typeof data.defaultRuntime.provider === "string" && data.defaultRuntime.provider.length > 64) {
681
+ return { valid: false, error: "defaultRuntime.provider must be 64 chars or less" };
682
+ }
683
+ if (data.defaultRuntime.model && typeof data.defaultRuntime.model === "string" && data.defaultRuntime.model.length > 128) {
684
+ return { valid: false, error: "defaultRuntime.model must be 128 chars or less" };
685
+ }
686
+ if (data.defaultRuntime.mode && typeof data.defaultRuntime.mode === "string" && data.defaultRuntime.mode.length > 64) {
687
+ return { valid: false, error: "defaultRuntime.mode must be 64 chars or less" };
688
+ }
689
+ }
602
690
  break;
603
691
  case "agent-delegation":
604
692
  if (!data.controllerWallet || !validateWalletAddress(data.controllerWallet)) {
@@ -613,6 +701,18 @@ var validateVerifierData = (verifierId, data) => {
613
701
  if (data.expiresAt && (typeof data.expiresAt !== "number" || data.expiresAt < Date.now())) {
614
702
  return { valid: false, error: "expiresAt must be a future timestamp" };
615
703
  }
704
+ if (data.model && typeof data.model === "string" && data.model.length > 128) {
705
+ return { valid: false, error: "model must be 128 chars or less" };
706
+ }
707
+ if (data.provider && typeof data.provider === "string" && data.provider.length > 64) {
708
+ return { valid: false, error: "provider must be 64 chars or less" };
709
+ }
710
+ if (data.allowedActions && Array.isArray(data.allowedActions) && data.allowedActions.length > 32) {
711
+ return { valid: false, error: "allowedActions must have 32 items or less" };
712
+ }
713
+ if (data.deniedActions && Array.isArray(data.deniedActions) && data.deniedActions.length > 32) {
714
+ return { valid: false, error: "deniedActions must have 32 items or less" };
715
+ }
616
716
  break;
617
717
  case "ai-content-moderation":
618
718
  if (!data.content || typeof data.content !== "string") {
@@ -723,6 +823,54 @@ var NeusClient = class {
723
823
  }
724
824
  } catch {
725
825
  }
826
+ this._sponsorGrantCache = null;
827
+ }
828
+ _getBillingWallet() {
829
+ const raw = this.config.billingWallet || this.config.sponsorOrgWallet || this.config.orgWallet || null;
830
+ if (typeof raw !== "string") return null;
831
+ const trimmed = raw.trim().toLowerCase();
832
+ return /^0x[a-f0-9]{40}$/.test(trimmed) ? trimmed : null;
833
+ }
834
+ _resolveIntegratorOrigin() {
835
+ if (typeof this.config.appOrigin === "string" && this.config.appOrigin.trim()) {
836
+ return this.config.appOrigin.trim();
837
+ }
838
+ try {
839
+ if (typeof window !== "undefined" && window.location?.origin) {
840
+ return window.location.origin;
841
+ }
842
+ } catch {
843
+ }
844
+ return null;
845
+ }
846
+ async _resolveSponsorGrantHeaders(verifierIds = []) {
847
+ const appId = typeof this.config.appId === "string" ? this.config.appId.trim() : "";
848
+ const orgWallet = this._getBillingWallet();
849
+ if (!appId || !orgWallet) {
850
+ return {};
851
+ }
852
+ const normalizedVerifierIds = Array.isArray(verifierIds) ? verifierIds.map((v) => String(v || "").trim()).filter(Boolean).slice(0, 25) : [];
853
+ const cacheKey = `${appId}:${orgWallet}:${normalizedVerifierIds.join(",")}`;
854
+ const now = Date.now();
855
+ if (this._sponsorGrantCache && this._sponsorGrantCache.key === cacheKey && this._sponsorGrantCache.expMs > now + 3e4) {
856
+ return { "X-Sponsor-Grant": this._sponsorGrantCache.token };
857
+ }
858
+ const origin = this._resolveIntegratorOrigin();
859
+ const grant = await fetchSponsorGrant({
860
+ apiUrl: this.baseUrl,
861
+ appId,
862
+ orgWallet,
863
+ verifierIds: normalizedVerifierIds,
864
+ origin
865
+ });
866
+ const expSeconds = Number(grant?.exp);
867
+ const expMs = Number.isFinite(expSeconds) && expSeconds > 0 ? expSeconds * 1e3 : now + 15 * 60 * 1e3;
868
+ this._sponsorGrantCache = {
869
+ key: cacheKey,
870
+ token: grant.sponsorGrant,
871
+ expMs
872
+ };
873
+ return { "X-Sponsor-Grant": grant.sponsorGrant };
726
874
  }
727
875
  _getHubChainId() {
728
876
  const configured = Number(this.config?.hubChainId);
@@ -1146,9 +1294,13 @@ var NeusClient = class {
1146
1294
  verificationData = {
1147
1295
  agentId: data2.agentId,
1148
1296
  agentWallet: data2?.agentWallet || walletAddress2,
1297
+ ...data2?.agentChainRef && { agentChainRef: data2.agentChainRef },
1298
+ ...data2?.agentAccountId && { agentAccountId: data2.agentAccountId },
1149
1299
  ...data2?.agentLabel && { agentLabel: data2.agentLabel },
1150
1300
  ...data2?.agentType && { agentType: data2.agentType },
1301
+ ...data2?.avatar && { avatar: data2.avatar },
1151
1302
  ...data2?.description && { description: data2.description },
1303
+ ...data2?.defaultRuntime && { defaultRuntime: data2.defaultRuntime },
1152
1304
  ...data2?.capabilities && { capabilities: data2.capabilities },
1153
1305
  ...data2?.instructions && { instructions: data2.instructions },
1154
1306
  ...data2?.skills && { skills: data2.skills },
@@ -1160,7 +1312,11 @@ var NeusClient = class {
1160
1312
  }
1161
1313
  verificationData = {
1162
1314
  controllerWallet: data2?.controllerWallet || walletAddress2,
1315
+ ...data2?.controllerChainRef && { controllerChainRef: data2.controllerChainRef },
1163
1316
  agentWallet: data2.agentWallet,
1317
+ ...data2?.agentChainRef && { agentChainRef: data2.agentChainRef },
1318
+ ...data2?.controllerAccountId && { controllerAccountId: data2.controllerAccountId },
1319
+ ...data2?.agentAccountId && { agentAccountId: data2.agentAccountId },
1164
1320
  ...data2?.agentId && { agentId: data2.agentId },
1165
1321
  ...data2?.scope && { scope: data2.scope },
1166
1322
  ...data2?.permissions && { permissions: data2.permissions },
@@ -1169,7 +1325,13 @@ var NeusClient = class {
1169
1325
  ...data2?.receiptDisclosure && { receiptDisclosure: data2.receiptDisclosure },
1170
1326
  ...data2?.expiresAt && { expiresAt: data2.expiresAt },
1171
1327
  ...data2?.instructions && { instructions: data2.instructions },
1172
- ...data2?.skills && { skills: data2.skills }
1328
+ ...data2?.skills && { skills: data2.skills },
1329
+ ...data2?.model && { model: data2.model },
1330
+ ...data2?.provider && { provider: data2.provider },
1331
+ ...data2?.runtimePolicy && { runtimePolicy: data2.runtimePolicy },
1332
+ ...data2?.allowedActions && { allowedActions: data2.allowedActions },
1333
+ ...data2?.deniedActions && { deniedActions: data2.deniedActions },
1334
+ ...data2?.approvalPolicy && { approvalPolicy: data2.approvalPolicy }
1173
1335
  };
1174
1336
  } else if (verifier === "ai-content-moderation") {
1175
1337
  if (!data2?.content) {
@@ -1381,26 +1543,25 @@ ${bytes.length}`;
1381
1543
  ...delegationQHash && { delegationQHash },
1382
1544
  options: optionsPayload
1383
1545
  };
1384
- const response = await this._makeRequest("POST", "/api/v1/verification", requestData);
1546
+ const sponsorHeaders = await this._resolveSponsorGrantHeaders(normalizedVerifierIds);
1547
+ const response = await this._makeRequest("POST", "/api/v1/verification", requestData, sponsorHeaders);
1385
1548
  if (!response.success) {
1386
1549
  throw new ApiError(`Verification failed: ${response.error?.message || "Unknown error"}`, response.error);
1387
1550
  }
1388
1551
  return this._formatResponse(response);
1389
1552
  }
1390
1553
  async getProof(qHash) {
1391
- const resolvedQHash = qHash;
1392
- if (!resolvedQHash || typeof resolvedQHash !== "string") {
1554
+ if (!qHash || typeof qHash !== "string") {
1393
1555
  throw new ValidationError("qHash is required");
1394
1556
  }
1395
- const response = await this._makeRequest("GET", `/api/v1/proofs/${resolvedQHash}`);
1557
+ const response = await this._makeRequest("GET", `/api/v1/proofs/${qHash}`);
1396
1558
  if (!response.success) {
1397
1559
  throw new ApiError(`Failed to get proof: ${response.error?.message || "Unknown error"}`, response.error);
1398
1560
  }
1399
1561
  return this._formatResponse(response);
1400
1562
  }
1401
1563
  async getPrivateProof(qHash, wallet = null) {
1402
- const resolvedQHash = qHash;
1403
- if (!resolvedQHash || typeof resolvedQHash !== "string") {
1564
+ if (!qHash || typeof qHash !== "string") {
1404
1565
  throw new ValidationError("qHash is required");
1405
1566
  }
1406
1567
  const isPreSignedAuth = wallet && typeof wallet === "object" && typeof wallet.walletAddress === "string" && typeof wallet.signature === "string" && typeof wallet.signedTimestamp === "number";
@@ -1413,7 +1574,7 @@ ${bytes.length}`;
1413
1574
  ...typeof auth.chain === "string" && auth.chain.trim() ? { "x-chain": auth.chain.trim() } : {},
1414
1575
  ...typeof auth.signatureMethod === "string" && auth.signatureMethod.trim() ? { "x-signature-method": auth.signatureMethod.trim() } : {}
1415
1576
  };
1416
- const response2 = await this._makeRequest("GET", `/api/v1/proofs/${resolvedQHash}`, null, headers);
1577
+ const response2 = await this._makeRequest("GET", `/api/v1/proofs/${qHash}`, null, headers);
1417
1578
  if (!response2.success) {
1418
1579
  throw new ApiError(
1419
1580
  `Failed to access private proof: ${response2.error?.message || "Unauthorized"}`,
@@ -1434,7 +1595,7 @@ ${bytes.length}`;
1434
1595
  const message = constructVerificationMessage({
1435
1596
  walletAddress,
1436
1597
  signedTimestamp,
1437
- data: { action: "access_private_proof", qHash: resolvedQHash },
1598
+ data: { action: "access_private_proof", qHash },
1438
1599
  verifierIds: ["ownership-basic"],
1439
1600
  ...signerIsEvm ? { chainId: this._getHubChainId() } : { chain }
1440
1601
  });
@@ -1452,7 +1613,7 @@ ${bytes.length}`;
1452
1613
  }
1453
1614
  throw new ValidationError(`Failed to sign message: ${error.message}`);
1454
1615
  }
1455
- const response = await this._makeRequest("GET", `/api/v1/proofs/${resolvedQHash}`, null, {
1616
+ const response = await this._makeRequest("GET", `/api/v1/proofs/${qHash}`, null, {
1456
1617
  "x-wallet-address": walletAddress,
1457
1618
  "x-signature": signature,
1458
1619
  "x-signed-timestamp": signedTimestamp.toString(),
@@ -1490,20 +1651,19 @@ ${bytes.length}`;
1490
1651
  };
1491
1652
  }
1492
1653
  async pollProofStatus(qHash, options = {}) {
1493
- const resolvedQHash = qHash;
1494
1654
  const {
1495
1655
  interval = 5e3,
1496
1656
  timeout = 12e4,
1497
1657
  onProgress
1498
1658
  } = options;
1499
- if (!resolvedQHash || typeof resolvedQHash !== "string") {
1659
+ if (!qHash || typeof qHash !== "string") {
1500
1660
  throw new ValidationError("qHash is required");
1501
1661
  }
1502
1662
  const startTime = Date.now();
1503
1663
  let consecutiveRateLimits = 0;
1504
1664
  while (Date.now() - startTime < timeout) {
1505
1665
  try {
1506
- const status = await this.getProof(resolvedQHash);
1666
+ const status = await this.getProof(qHash);
1507
1667
  consecutiveRateLimits = 0;
1508
1668
  if (onProgress && typeof onProgress === "function") {
1509
1669
  onProgress(status.data || status);
@@ -1546,8 +1706,7 @@ ${bytes.length}`;
1546
1706
  }
1547
1707
  }
1548
1708
  async revokeOwnProof(qHash, wallet) {
1549
- const resolvedQHash = qHash;
1550
- if (!resolvedQHash || typeof resolvedQHash !== "string") {
1709
+ if (!qHash || typeof qHash !== "string") {
1551
1710
  throw new ValidationError("qHash is required");
1552
1711
  }
1553
1712
  const providerWallet = wallet || this._getDefaultBrowserWallet();
@@ -1562,7 +1721,7 @@ ${bytes.length}`;
1562
1721
  const message = constructVerificationMessage({
1563
1722
  walletAddress: address,
1564
1723
  signedTimestamp,
1565
- data: { action: "revoke_proof", qHash: resolvedQHash },
1724
+ data: { action: "revoke_proof", qHash },
1566
1725
  verifierIds: ["ownership-basic"],
1567
1726
  ...signerIsEvm ? { chainId: this._getHubChainId() } : { chain }
1568
1727
  });
@@ -1580,7 +1739,7 @@ ${bytes.length}`;
1580
1739
  }
1581
1740
  throw new ValidationError(`Failed to sign revocation: ${error.message}`);
1582
1741
  }
1583
- const res = await this._makeRequest("POST", `/api/v1/proofs/revoke-self/${resolvedQHash}`, {
1742
+ const res = await this._makeRequest("POST", `/api/v1/proofs/revoke-self/${qHash}`, {
1584
1743
  walletAddress: address,
1585
1744
  signature,
1586
1745
  signedTimestamp,
@@ -1778,7 +1937,20 @@ ${bytes.length}`;
1778
1937
  };
1779
1938
  }
1780
1939
  }
1781
- const response = await this._makeRequest("GET", `/api/v1/proofs/check?${qs.toString()}`, null, headersOverride);
1940
+ let mergedHeaders = headersOverride;
1941
+ if (!mergedHeaders) {
1942
+ try {
1943
+ const sponsorHeaders = await this._resolveSponsorGrantHeaders(
1944
+ Array.isArray(params.verifierIds) ? params.verifierIds : params.verifierIds ? [params.verifierIds] : []
1945
+ );
1946
+ if (sponsorHeaders && Object.keys(sponsorHeaders).length > 0) {
1947
+ mergedHeaders = sponsorHeaders;
1948
+ }
1949
+ } catch (error) {
1950
+ this._log("Sponsor grant unavailable for gateCheck (continuing without)", error?.message || String(error));
1951
+ }
1952
+ }
1953
+ const response = await this._makeRequest("GET", `/api/v1/proofs/check?${qs.toString()}`, null, mergedHeaders);
1782
1954
  if (!response.success) {
1783
1955
  throw new ApiError(`Gate check failed: ${response.error?.message || "Unknown error"}`, response.error);
1784
1956
  }
@@ -1987,10 +2159,7 @@ ${bytes.length}`;
1987
2159
  }
1988
2160
  }
1989
2161
  _formatResponse(response) {
1990
- const qHash = response?.data?.qHash || response?.qHash || response?.data?.resource?.qHash || response?.data?.proofId || // Legacy input compatibility only. Do not expose or store proofId.
1991
- response?.proofId || // Legacy input compatibility only. Do not expose or store proofId.
1992
- response?.data?.resource?.proofId || // Legacy input compatibility only. Do not expose or store proofId.
1993
- response?.data?.id;
2162
+ const qHash = response?.data?.qHash || response?.qHash || response?.data?.resource?.qHash || response?.data?.id;
1994
2163
  const status = response?.data?.status || response?.status || response?.data?.resource?.status || (response?.success ? "completed" : "unknown");
1995
2164
  return {
1996
2165
  success: response.success,
package/cjs/errors.cjs CHANGED
@@ -26,9 +26,7 @@ __export(errors_exports, {
26
26
  NetworkError: () => NetworkError,
27
27
  SDKError: () => SDKError,
28
28
  ValidationError: () => ValidationError,
29
- VerificationError: () => VerificationError,
30
- createErrorFromGeneric: () => createErrorFromGeneric,
31
- default: () => errors_default
29
+ VerificationError: () => VerificationError
32
30
  });
33
31
  module.exports = __toCommonJS(errors_exports);
34
32
  var SDKError = class _SDKError extends Error {
@@ -160,36 +158,6 @@ var AuthenticationError = class extends SDKError {
160
158
  };
161
159
  }
162
160
  };
163
- function createErrorFromGeneric(error, context = {}) {
164
- if (error instanceof SDKError) {
165
- return error;
166
- }
167
- if (NetworkError.isNetworkError(error)) {
168
- return new NetworkError(
169
- error.message || "Network error occurred",
170
- error.code || "NETWORK_ERROR",
171
- error
172
- );
173
- }
174
- if (error.name === "AbortError" || error.message.includes("timeout")) {
175
- return new NetworkError("Request timeout", "TIMEOUT", error);
176
- }
177
- return new SDKError(
178
- error.message || "Unknown error occurred",
179
- error.code || "UNKNOWN_ERROR",
180
- { originalError: error, context }
181
- );
182
- }
183
- var errors_default = {
184
- SDKError,
185
- ApiError,
186
- ValidationError,
187
- NetworkError,
188
- ConfigurationError,
189
- VerificationError,
190
- AuthenticationError,
191
- createErrorFromGeneric
192
- };
193
161
  // Annotate the CommonJS export names for ESM import in node:
194
162
  0 && (module.exports = {
195
163
  ApiError,
@@ -198,6 +166,5 @@ var errors_default = {
198
166
  NetworkError,
199
167
  SDKError,
200
168
  ValidationError,
201
- VerificationError,
202
- createErrorFromGeneric
169
+ VerificationError
203
170
  });
package/cjs/gates.cjs CHANGED
@@ -36,8 +36,7 @@ __export(gates_exports, {
36
36
  WEEK: () => WEEK,
37
37
  YEAR: () => YEAR,
38
38
  combineGates: () => combineGates,
39
- createGate: () => createGate,
40
- default: () => gates_default
39
+ createGate: () => createGate
41
40
  });
42
41
  module.exports = __toCommonJS(gates_exports);
43
42
  var HOUR = 60 * 60 * 1e3;
@@ -77,25 +76,6 @@ function combineGates(...gates) {
77
76
  }
78
77
  return combined;
79
78
  }
80
- var gates_default = {
81
- HOUR,
82
- DAY,
83
- WEEK,
84
- MONTH,
85
- YEAR,
86
- GATE_NFT_HOLDER,
87
- GATE_TOKEN_HOLDER,
88
- GATE_CONTRACT_ADMIN,
89
- GATE_DOMAIN_OWNER,
90
- GATE_LINKED_WALLETS,
91
- GATE_AGENT_IDENTITY,
92
- GATE_AGENT_DELEGATION,
93
- GATE_CONTENT_MODERATION,
94
- GATE_WALLET_RISK,
95
- GATE_PSEUDONYM,
96
- createGate,
97
- combineGates
98
- };
99
79
  // Annotate the CommonJS export names for ESM import in node:
100
80
  0 && (module.exports = {
101
81
  DAY,