diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..1b1f5e13 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,32 @@ +# AGENTS.md + +## Cursor Cloud specific instructions + +This is a JavaScript SDK + docs monorepo. There is no database, Docker, or local backend; the SDK is a client for the remote NEUS API (`https://api.neus.network`). + +### Repository layout + +| Directory | Purpose | +|-----------|---------| +| `sdk/` | Main `@neus/sdk` package (JS, ESM). All lint/test/build commands run here. | +| `docs/` | Mintlify-powered documentation site + OpenAPI spec | +| `contracts/` | Reference Solidity contracts (no Hardhat/Foundry tooling) | +| `examples/` | Node.js, React, curl usage examples | +| `spec/` | Verifier JSON schemas | + +### Key commands + +- **SDK dependencies:** `cd sdk && npm install` (uses `package-lock.json`) +- **SDK lint:** `cd sdk && npm run lint` (ESLint 8; the repo has pre-existing warnings/errors in committed code — this is expected) +- **SDK test:** `cd sdk && npm test` (Vitest — 73 unit tests, all mocked, no network needed) +- **SDK build:** `cd sdk && npm run build` (esbuild: widgets + CJS bundles) +- **Docs validation:** `npm run docs:validate` (from repo root; runs markdownlint + Redocly OpenAPI lint) +- **Docs dev server:** `npm run docs:dev` (from repo root; starts Mintlify dev server — optional) + +### Notes + +- The root `package.json` only has docs scripts; the SDK has its own `package.json` in `sdk/`. +- ESLint reports warnings and errors on committed code. This is the repo's baseline state — do not try to fix pre-existing lint issues unless specifically asked. +- Live integration tests are opt-in via `NEUS_SDK_LIVE_TESTS=1`. Unit tests mock `fetch` and run fully offline. +- `constructVerificationMessage()` requires a `chainId` parameter (not just `walletAddress` and `verifierIds`). +- Node.js >= 20 is required (CI uses 20.19.0). diff --git a/README.md b/README.md index 88516035..2c2dd459 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,27 @@ -# NEUS Network +# NEUS [![npm](https://img.shields.io/npm/v/%40neus%2Fsdk?logo=npm&label=@neus/sdk)](https://www.npmjs.com/package/@neus/sdk) [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](./LICENSE) -**Verify once. Prove everywhere.** +**Verify once. Reuse everywhere.** -NEUS replaces fragmented verification with one reusable proof receipt. +NEUS gives apps, APIs, and agents a reusable proof receipt for identity, ownership, risk, and access. Run a check once, get a portable receipt, and use it to gate, share, or automate anywhere. -## Quick Start +## Use NEUS to + +- **Verify users once** and reuse the result across your product +- **Gate access** by proof instead of custom auth logic +- **Attach proof to content**, listings, and agent actions +- **Register agents** and give them scoped permissions +- **Share verification results** without exposing raw private data + +## How it works + +1. **Verify** — User completes a check (wallet, social, identity, or risk). +2. **Get a receipt** — You receive a portable proof ID. +3. **Reuse it** — Gate content, check eligibility, share badges, or automate with it. + +## Quick start ```bash npm install @neus/sdk @@ -24,46 +38,63 @@ const proof = await client.verify({ wallet: window.ethereum, }); -// Save this ID — reuse it everywhere -const proofId = proof.proofId; +const proofId = proof.proofId; // save this — reuse it everywhere ``` -## What NEUS Does +## What you can build -| Problem | Solution | -|---------|----------| -| Verification built per feature | One proof, many uses | -| No reusable identity | Portable proof receipts | -| Custom verification infrastructure | Hosted UI + API | +| Use case | How | +|----------|-----| +| Human-only signup or access | `proof-of-human` verifier | +| Token / NFT gated products | `nft-ownership`, `token-holding` | +| Verified creator or org badges | `ownership-basic`, `ownership-org-oauth` | +| Proof-backed content and posts | Attach `proofId` to any content | +| Agent identity and delegation | `agent-identity`, `agent-delegation` | +| Domain-verified organizations | `ownership-dns-txt` | -## Integration paths +## Start here -**Builders:** [Get started](https://docs.neus.network/get-started) (platform, app link, credits), then [choose an integration path](https://docs.neus.network/choose-an-integration-path). +| I want to… | Go to | +|-------------|-------| +| Try it in 5 minutes | [Quickstart](https://docs.neus.network/quickstart) | +| Use hosted UI (no wallet code) | [Hosted Verify](https://docs.neus.network/cookbook/auth-hosted-verify) | +| Gate content in React | [Widgets](https://docs.neus.network/widgets/overview) | +| Check proofs from my server | [API](https://docs.neus.network/api/overview) | +| Add verification to AI agents | [MCP](https://docs.neus.network/mcp/overview) | +| Set up billing and apps | [Get started](https://docs.neus.network/get-started) | -| Path | Best For | +## Integration paths + +| Path | Best for | |------|----------| -| [Hosted Verify](https://docs.neus.network/cookbook/auth-hosted-verify) | Login, social linking | -| [Widgets](https://docs.neus.network/widgets/overview) | React gating | -| [SDK](https://docs.neus.network/sdks/overview) | Custom flows | -| [API](https://docs.neus.network/api/overview) | Server checks | -| [MCP](https://docs.neus.network/mcp/overview) | AI agents | +| [Hosted Verify](https://docs.neus.network/cookbook/auth-hosted-verify) | Login, social linking — no custom UI needed | +| [Widgets](https://docs.neus.network/widgets/overview) | React gating and badges | +| [SDK](https://docs.neus.network/sdks/overview) | Custom browser or server flows | +| [API](https://docs.neus.network/api/overview) | Server-side checks | +| [MCP](https://docs.neus.network/mcp/overview) | AI agents (Cursor, Claude, etc.) | + +## AI agents (MCP) + +Add NEUS to any MCP-compatible agent with one URL: -## AI assistants (MCP) +``` +https://mcp.neus.network/mcp +``` -**`https://mcp.neus.network/mcp`** — [setup](https://docs.neus.network/mcp/setup) is one JSON block; users verify via **hosted links** tools return. +[Setup guide](https://docs.neus.network/mcp/setup) — one JSON block, then agents verify users via hosted links. ## Documentation | Resource | Description | |----------|-------------| | [Quickstart](https://docs.neus.network/quickstart) | First proof in 5 minutes | -| [Verifier Catalog](https://docs.neus.network/verification/verifiers) | All capabilities | -| [API Reference](https://docs.neus.network/api/overview) | HTTP endpoints | +| [Verifier catalog](https://docs.neus.network/verification/verifiers) | All verification types | +| [API reference](https://docs.neus.network/api/overview) | HTTP endpoints | | [Examples](./examples/) | React, Node.js, curl | ## Support -| Channel | Use For | +| Channel | Use for | |---------|---------| | [GitHub Discussions](https://github.com/neus/network/discussions) | Questions | | [GitHub Issues](https://github.com/neus/network/issues) | Bug reports | @@ -71,5 +102,5 @@ const proofId = proof.proofId; ## License -- **Smart Contracts:** BUSL-1.1 → Apache-2.0 (Aug 2028) -- **SDK & Tools:** Apache-2.0 \ No newline at end of file +- **SDK & tools:** Apache-2.0 +- **Smart contracts:** BUSL-1.1 → Apache-2.0 (Aug 2028) diff --git a/docs/docs.json b/docs/docs.json index 07f462ca..857c71e8 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -81,9 +81,9 @@ "group": "Essentials", "icon": "compass", "pages": [ - "get-started", "index", "quickstart", + "get-started", "choose-an-integration-path", "integration", "examples" diff --git a/docs/index.mdx b/docs/index.mdx index d8cdc70e..09cf340d 100644 --- a/docs/index.mdx +++ b/docs/index.mdx @@ -1,63 +1,67 @@ --- -title: Overview -description: Verify once. Prove everywhere. Portable proof receipts for login, trust, access, and agent workflows. +title: NEUS Documentation +description: Verify once. Reuse everywhere. Portable proof receipts for apps, APIs, and agents. icon: house --- -**One proof receipt** — reusable across apps, APIs, and agents. +**Verify once. Reuse everywhere.** -## Start here - -**Building a product?** **[Get started](./get-started)** — platform profile, link app, credits, `appId`, sponsor grants, then **[choose an integration path](./choose-an-integration-path)**. - -**Choosing an integration path?** **[Choose an integration path](./choose-an-integration-path)** — Hosted Verify, Widgets, SDK, API, or MCP. - -## How it works +NEUS gives your app a reusable proof receipt for identity, ownership, risk, and access. Run a check once, get a receipt, and use it to gate, share, or automate anywhere. -1. **Verify** — User completes verification (hosted UI, wallet, or social). -2. **Save** — You store the proof receipt ID. -3. **Reuse** — Same proof for login, gating, policy, and agents. +## Start here - - - Builders: platform, app link, billing, first integration. - - - Pick Hosted Verify, Widgets, SDK, API, or MCP. - + - First proof with the SDK (code). - - - No custom verification UI — redirect or popup. + First proof in 5 minutes. - - What you can verify. + + Platform setup, billing, app linking. - - Who pays — deep reference. + + No-code verification UI. -## Integration paths +## What you can build + +| Use case | Verifier | +|----------|----------| +| Human-only signup or access | `proof-of-human` | +| Token / NFT gated products | `nft-ownership`, `token-holding` | +| Verified creator or org badges | `ownership-basic`, `ownership-org-oauth` | +| Proof-backed content and posts | `ownership-basic` | +| Agent identity and delegation | `agent-identity`, `agent-delegation` | +| Domain-verified organizations | `ownership-dns-txt` | + +[Full verifier catalog →](./verification/verifiers) + +## How it works + +1. **Verify** — User completes a check (wallet, social, identity, or risk). +2. **Get a receipt** — You receive a portable proof ID. +3. **Reuse it** — Gate content, check eligibility, share badges, or automate with it. + +## Choose your integration | Path | Best for | |------|----------| -| [Hosted Verify](./cookbook/auth-hosted-verify) | Login, guided verification, least UI work | +| [Hosted Verify](./cookbook/auth-hosted-verify) | Login, social linking — no custom UI | | [Widgets](./widgets/overview) | React gating and badges | | [SDK](./sdks/overview) | Custom browser or server flows | -| [API](./api/overview) | HTTP from your servers | -| [MCP](./mcp/overview) | Cursor, Claude, agents — browser links first | +| [API](./api/overview) | Server-side checks | +| [MCP](./mcp/overview) | AI agents (Cursor, Claude, etc.) | + +Not sure? [Choose an integration path →](./choose-an-integration-path) -## URLs you’ll use +## URLs | What | URL | |------|-----| | Hosted verification | `https://neus.network/verify` | -| Platform (`/hub`) | `https://neus.network/hub` | +| Platform | `https://neus.network/hub` | | API | `https://api.neus.network` | | MCP | `https://mcp.neus.network/mcp` | ## Examples -[Examples](./examples) — React, Node, curl. +[React, Node.js, curl →](./examples) diff --git a/docs/quickstart.mdx b/docs/quickstart.mdx index 2f6ffa01..4e0f7f24 100644 --- a/docs/quickstart.mdx +++ b/docs/quickstart.mdx @@ -4,24 +4,24 @@ description: Create your first proof in under 5 minutes. icon: rocket --- -**~5 min:** install SDK → verify → save receipt ID → optional gate. +Install the SDK, create a proof, and reuse it. - **Shipping an app?** Do **[Get started](./get-started)** first (platform → Apps → credits → `appId` / sponsor). Then come back here for code. + **Shipping an app?** Do **[Get started](./get-started)** first (platform → app link → credits → `appId`). Then come back here for code. -## 1. Install +## 1. Install the SDK ```bash npm install @neus/sdk ``` -## 2. Client + proof +## 2. Create a proof ```javascript import { NeusClient } from '@neus/sdk'; -const client = new NeusClient({ appId: 'my-app' }); +const client = new NeusClient(); const proof = await client.verify({ verifier: 'ownership-basic', @@ -33,7 +33,7 @@ const proofId = proof.proofId; // save this ``` - **No in-app wallet?** Use [Hosted Verify](./cookbook/auth-hosted-verify) + session instead of `window.ethereum`. + **No in-app wallet?** Use [Hosted Verify](./cookbook/auth-hosted-verify) — redirect or popup, no wallet code needed. ## 3. Wait for completion @@ -45,7 +45,7 @@ const status = await client.pollProofStatus(proofId, { }); ``` -## 4. Optional: Gate in React +## 4. Reuse: gate content in React ```jsx import { VerifyGate } from '@neus/sdk/widgets'; @@ -55,12 +55,25 @@ import { VerifyGate } from '@neus/sdk/widgets'; ``` -## Next +## 5. Reuse: check eligibility from your server -| I want… | Go to | -|---------|--------| -| Platform + billing setup | [Get started](./get-started) | -| Hosted UI | [Hosted Verify](./cookbook/auth-hosted-verify) | -| Pick integration | [Choose your path](./choose-an-integration-path) | -| Verifier list | [Verifier catalog](./verification/verifiers) | -| Production | [Integration](./integration) | +```javascript +const result = await client.gateCheck({ + address: '0x...', + verifierIds: ['ownership-basic'], +}); + +if (result.data?.eligible) { + // allow access +} +``` + +## Next steps + +| I want to… | Go to | +|-------------|-------| +| Set up platform and billing | [Get started](./get-started) | +| Use hosted UI (no wallet code) | [Hosted Verify](./cookbook/auth-hosted-verify) | +| Pick an integration path | [Choose your path](./choose-an-integration-path) | +| See all verification types | [Verifier catalog](./verification/verifiers) | +| Go to production | [Integration checklist](./integration) | diff --git a/funding.json b/funding.json index ecabc019..281f9514 100644 --- a/funding.json +++ b/funding.json @@ -1,5 +1,5 @@ { "opRetro": { - "projectId": "0x42c02a0db1888dae5c82e31ddf707d7d3bc6018a9dd45931b6d4f146550faa10" + "projectId": "0x42c02a0db1888dae5c82e31ddf707d7d3bc6018a9dd45931b6d4f146550faa10" } } diff --git a/sdk/.eslintrc.json b/sdk/.eslintrc.json index 95ac4340..5da3a967 100644 --- a/sdk/.eslintrc.json +++ b/sdk/.eslintrc.json @@ -31,7 +31,7 @@ "object-curly-spacing": ["warn", "always"], "array-bracket-spacing": ["warn", "never"], "comma-dangle": ["warn", "never"], - "max-len": ["warn", { "code": 120, "ignoreComments": true }], + "max-len": ["warn", { "code": 120, "ignoreComments": true, "ignoreUrls": true, "ignoreStrings": true }], "eqeqeq": ["error", "always"], "no-trailing-spaces": "warn", "no-multiple-empty-lines": ["warn", { "max": 1 }], @@ -40,9 +40,23 @@ "require-await": "off", "no-return-await": "warn" }, + "overrides": [ + { + "files": ["widgets/verify-gate/standalone.js"], + "parserOptions": { + "sourceType": "script" + }, + "rules": { + "no-var": "off", + "prefer-const": "off", + "prefer-template": "off" + } + } + ], "ignorePatterns": [ "node_modules/", "dist/", + "cjs/", "build/", "*.min.js" ] diff --git a/sdk/README.md b/sdk/README.md index f2d34410..433a165c 100644 --- a/sdk/README.md +++ b/sdk/README.md @@ -1,6 +1,6 @@ -# NEUS SDK +# @neus/sdk -JavaScript client for NEUS verification. +JavaScript SDK for NEUS — verify once, reuse everywhere. ## Install @@ -8,7 +8,7 @@ JavaScript client for NEUS verification. npm install @neus/sdk ``` -## Quick Start +## Quick start ```javascript import { NeusClient } from '@neus/sdk'; @@ -22,59 +22,61 @@ const proof = await client.verify({ wallet: window.ethereum, }); +// Save this ID — reuse it anywhere const proofId = proof.proofId; ``` -## Key Methods +**No in-app wallet?** Use [Hosted Verify](https://docs.neus.network/cookbook/auth-hosted-verify) instead — redirect or popup, no wallet code needed. -| Method | Purpose | -|--------|---------| +## Core methods + +| Method | What it does | +|--------|-------------| | `client.verify()` | Create a proof | -| `client.pollProofStatus()` | Check async status | -| `client.gateCheck()` | Server-side eligibility | -| `getHostedCheckoutUrl()` | Generate hosted URL | +| `client.getStatus()` | Check proof status | +| `client.pollProofStatus()` | Wait for async completion | +| `client.gateCheck()` | Server-side eligibility check | +| `client.checkGate()` | Evaluate requirements against proofs | +| `getHostedCheckoutUrl()` | Generate a hosted verify URL | ## Configuration ```javascript const client = new NeusClient({ - apiUrl: 'https://api.neus.network', - appId: 'my-app', + apiUrl: 'https://api.neus.network', // default + appId: 'my-app', // links to your platform app timeout: 30000, }); ``` -## Hosted Verify +## Gate content in React -```javascript -import { getHostedCheckoutUrl } from '@neus/sdk'; - -const url = getHostedCheckoutUrl({ - verifiers: ['ownership-basic'], - mode: 'popup', - origin: window.location.origin, - returnUrl: 'https://myapp.com/callback', - intent: 'login', -}); -``` +```jsx +import { VerifyGate } from '@neus/sdk/widgets'; -- [Get started](https://docs.neus.network/get-started) (platform, app, credits) -- [Choose your path](https://docs.neus.network/choose-an-integration-path) -- [Hosted Verify](https://docs.neus.network/cookbook/auth-hosted-verify) + + + +``` -## Gate Check +## Check eligibility from your server ```javascript const result = await client.gateCheck({ address: '0x...', verifierIds: ['ownership-basic'], }); + +if (result.data?.eligible) { + // allow access +} ``` ## Documentation -- [Get started](https://docs.neus.network/get-started) -- [SDK Overview](https://docs.neus.network/sdks/overview) -- [JavaScript SDK](https://docs.neus.network/sdks/javascript) -- [Widgets](https://docs.neus.network/widgets/overview) -- [API Reference](https://docs.neus.network/api/overview) \ No newline at end of file +- [Quickstart](https://docs.neus.network/quickstart) — first proof in 5 minutes +- [SDK overview](https://docs.neus.network/sdks/overview) — full SDK guide +- [JavaScript SDK](https://docs.neus.network/sdks/javascript) — detailed reference +- [Widgets](https://docs.neus.network/widgets/overview) — React components +- [API reference](https://docs.neus.network/api/overview) — HTTP endpoints +- [Hosted Verify](https://docs.neus.network/cookbook/auth-hosted-verify) — no-code verification UI diff --git a/sdk/client.js b/sdk/client.js index a1a1ec13..3bbd59ab 100644 --- a/sdk/client.js +++ b/sdk/client.js @@ -5,7 +5,13 @@ */ import { ApiError, ValidationError, NetworkError, ConfigurationError } from './errors.js'; -import { constructVerificationMessage, validateWalletAddress, validateUniversalAddress, signMessage, NEUS_CONSTANTS } from './utils.js'; +import { + constructVerificationMessage, + validateWalletAddress, + validateUniversalAddress, + signMessage, + NEUS_CONSTANTS +} from './utils.js'; const FALLBACK_PUBLIC_VERIFIERS = [ 'ownership-basic', @@ -32,282 +38,280 @@ const INTERACTIVE_VERIFIERS = new Set([ const EVM_ADDRESS_RE = /^0x[a-fA-F0-9]{40}$/; -// Validation for supported verifiers const validateVerifierData = (verifierId, data) => { if (!data || typeof data !== 'object') { return { valid: false, error: 'Data object is required' }; } - - // Format validation for supported verifiers + switch (verifierId) { - case 'ownership-basic': - // Required: owner (must match request walletAddress). - // Reference is optional when content/contentHash is provided. - // If neither content nor contentHash is provided, reference.id is required (reference-only proof). - if (!data.owner || !validateUniversalAddress(data.owner, typeof data.chain === 'string' ? data.chain : undefined)) { - return { valid: false, error: 'owner (universal wallet address) is required' }; + case 'ownership-basic': + if (!data.owner || !validateUniversalAddress(data.owner, typeof data.chain === 'string' ? data.chain : undefined)) { + return { valid: false, error: 'owner (universal wallet address) is required' }; + } + if (data.content !== undefined && data.content !== null) { + if (typeof data.content !== 'string') { + return { valid: false, error: 'content must be a string when provided' }; } - if (data.content !== undefined && data.content !== null) { - if (typeof data.content !== 'string') { - return { valid: false, error: 'content must be a string when provided' }; - } - if (data.content.length > 50000) { - return { valid: false, error: 'content exceeds 50KB inline limit' }; - } + if (data.content.length > 50000) { + return { valid: false, error: 'content exceeds 50KB inline limit' }; } - if (data.contentHash !== undefined && data.contentHash !== null) { - if (typeof data.contentHash !== 'string' || !/^0x[a-fA-F0-9]{64}$/.test(data.contentHash)) { - return { valid: false, error: 'contentHash must be a 32-byte hex string (0x + 64 hex chars) when provided' }; - } + } + if (data.contentHash !== undefined && data.contentHash !== null) { + if (typeof data.contentHash !== 'string' || !/^0x[a-fA-F0-9]{64}$/.test(data.contentHash)) { + return { valid: false, error: 'contentHash must be a 32-byte hex string (0x + 64 hex chars) when provided' }; } - if (data.contentType !== undefined && data.contentType !== null) { - if (typeof data.contentType !== 'string' || data.contentType.length > 100) { - return { valid: false, error: 'contentType must be a string (max 100 chars) when provided' }; - } - const base = String(data.contentType).split(';')[0].trim().toLowerCase(); - // Minimal MIME sanity check (server validates more precisely). - if (!base || base.includes(' ') || !base.includes('/')) { - return { valid: false, error: 'contentType must be a valid MIME type when provided' }; + } + if (data.contentType !== undefined && data.contentType !== null) { + if (typeof data.contentType !== 'string' || data.contentType.length > 100) { + return { valid: false, error: 'contentType must be a string (max 100 chars) when provided' }; + } + const base = String(data.contentType).split(';')[0].trim().toLowerCase(); + // Minimal MIME sanity check (server validates more precisely). + if (!base || base.includes(' ') || !base.includes('/')) { + return { valid: false, error: 'contentType must be a valid MIME type when provided' }; + } + } + if (data.provenance !== undefined && data.provenance !== null) { + if (!data.provenance || typeof data.provenance !== 'object' || Array.isArray(data.provenance)) { + return { valid: false, error: 'provenance must be an object when provided' }; + } + const dk = data.provenance.declaredKind; + if (dk !== undefined && dk !== null) { + const allowed = ['human', 'ai', 'mixed', 'unknown']; + if (typeof dk !== 'string' || !allowed.includes(dk)) { + return { valid: false, error: `provenance.declaredKind must be one of: ${allowed.join(', ')}` }; } } - if (data.provenance !== undefined && data.provenance !== null) { - if (!data.provenance || typeof data.provenance !== 'object' || Array.isArray(data.provenance)) { - return { valid: false, error: 'provenance must be an object when provided' }; + const ai = data.provenance.aiContext; + if (ai !== undefined && ai !== null) { + if (typeof ai !== 'object' || Array.isArray(ai)) { + return { valid: false, error: 'provenance.aiContext must be an object when provided' }; } - const dk = data.provenance.declaredKind; - if (dk !== undefined && dk !== null) { - const allowed = ['human', 'ai', 'mixed', 'unknown']; - if (typeof dk !== 'string' || !allowed.includes(dk)) { - return { valid: false, error: `provenance.declaredKind must be one of: ${allowed.join(', ')}` }; + if (ai.generatorType !== undefined && ai.generatorType !== null) { + const allowed = ['local', 'saas', 'agent']; + if (typeof ai.generatorType !== 'string' || !allowed.includes(ai.generatorType)) { + return { valid: false, error: `provenance.aiContext.generatorType must be one of: ${allowed.join(', ')}` }; } } - const ai = data.provenance.aiContext; - if (ai !== undefined && ai !== null) { - if (typeof ai !== 'object' || Array.isArray(ai)) { - return { valid: false, error: 'provenance.aiContext must be an object when provided' }; - } - if (ai.generatorType !== undefined && ai.generatorType !== null) { - const allowed = ['local', 'saas', 'agent']; - if (typeof ai.generatorType !== 'string' || !allowed.includes(ai.generatorType)) { - return { valid: false, error: `provenance.aiContext.generatorType must be one of: ${allowed.join(', ')}` }; - } - } - if (ai.provider !== undefined && ai.provider !== null) { - if (typeof ai.provider !== 'string' || ai.provider.length > 64) { - return { valid: false, error: 'provenance.aiContext.provider must be a string (max 64 chars) when provided' }; - } - } - if (ai.model !== undefined && ai.model !== null) { - if (typeof ai.model !== 'string' || ai.model.length > 128) { - return { valid: false, error: 'provenance.aiContext.model must be a string (max 128 chars) when provided' }; - } - } - if (ai.runId !== undefined && ai.runId !== null) { - if (typeof ai.runId !== 'string' || ai.runId.length > 128) { - return { valid: false, error: 'provenance.aiContext.runId must be a string (max 128 chars) when provided' }; - } + if (ai.provider !== undefined && ai.provider !== null) { + if (typeof ai.provider !== 'string' || ai.provider.length > 64) { + return { valid: false, error: 'provenance.aiContext.provider must be a string (max 64 chars) when provided' }; } } - } - if (data.reference !== undefined) { - if (!data.reference || typeof data.reference !== 'object') { - return { valid: false, error: 'reference must be an object when provided' }; + if (ai.model !== undefined && ai.model !== null) { + if (typeof ai.model !== 'string' || ai.model.length > 128) { + return { valid: false, error: 'provenance.aiContext.model must be a string (max 128 chars) when provided' }; + } } - if (!data.reference.type || typeof data.reference.type !== 'string') { - // Only required when reference object is present (or when doing reference-only proofs). - // Server requires reference.type when reference is used for traceability. - return { valid: false, error: 'reference.type is required when reference is provided' }; + if (ai.runId !== undefined && ai.runId !== null) { + if (typeof ai.runId !== 'string' || ai.runId.length > 128) { + return { valid: false, error: 'provenance.aiContext.runId must be a string (max 128 chars) when provided' }; + } } } - if (!data.content && !data.contentHash) { - if (!data.reference || typeof data.reference !== 'object') { - return { valid: false, error: 'reference is required when neither content nor contentHash is provided' }; - } - if (!data.reference.id || typeof data.reference.id !== 'string') { - return { valid: false, error: 'reference.id is required when neither content nor contentHash is provided' }; - } - if (!data.reference.type || typeof data.reference.type !== 'string') { - return { valid: false, error: 'reference.type is required when neither content nor contentHash is provided' }; - } + } + if (data.reference !== undefined) { + if (!data.reference || typeof data.reference !== 'object') { + return { valid: false, error: 'reference must be an object when provided' }; } - break; - case 'nft-ownership': - // ownerAddress is optional; server injects from request walletAddress when omitted. - if ( - !data.contractAddress || - data.tokenId === null || - data.tokenId === undefined || - typeof data.chainId !== 'number' - ) { - return { valid: false, error: 'contractAddress, tokenId, and chainId are required' }; + if (!data.reference.type || typeof data.reference.type !== 'string') { + // Only required when reference object is present (or when doing reference-only proofs). + // Server requires reference.type when reference is used for traceability. + return { valid: false, error: 'reference.type is required when reference is provided' }; } - if (data.tokenType !== undefined && data.tokenType !== null) { - const tt = String(data.tokenType).toLowerCase(); - if (tt !== 'erc721' && tt !== 'erc1155') { - return { valid: false, error: 'tokenType must be one of: erc721, erc1155' }; - } + } + if (!data.content && !data.contentHash) { + if (!data.reference || typeof data.reference !== 'object') { + return { valid: false, error: 'reference is required when neither content nor contentHash is provided' }; } - if (data.blockNumber !== undefined && data.blockNumber !== null && !Number.isInteger(data.blockNumber)) { - return { valid: false, error: 'blockNumber must be an integer when provided' }; + if (!data.reference.id || typeof data.reference.id !== 'string') { + return { valid: false, error: 'reference.id is required when neither content nor contentHash is provided' }; } - if (data.ownerAddress && !validateWalletAddress(data.ownerAddress)) { - return { valid: false, error: 'Invalid ownerAddress' }; + if (!data.reference.type || typeof data.reference.type !== 'string') { + return { valid: false, error: 'reference.type is required when neither content nor contentHash is provided' }; } - if (!validateWalletAddress(data.contractAddress)) { - return { valid: false, error: 'Invalid contractAddress' }; + } + break; + case 'nft-ownership': + // ownerAddress is optional; server injects from request walletAddress when omitted. + if ( + !data.contractAddress || + data.tokenId === null || + data.tokenId === undefined || + typeof data.chainId !== 'number' + ) { + return { valid: false, error: 'contractAddress, tokenId, and chainId are required' }; + } + if (data.tokenType !== undefined && data.tokenType !== null) { + const tt = String(data.tokenType).toLowerCase(); + if (tt !== 'erc721' && tt !== 'erc1155') { + return { valid: false, error: 'tokenType must be one of: erc721, erc1155' }; } - break; - case 'token-holding': - // ownerAddress is optional; server injects from request walletAddress when omitted. - if ( - !data.contractAddress || + } + if (data.blockNumber !== undefined && data.blockNumber !== null && !Number.isInteger(data.blockNumber)) { + return { valid: false, error: 'blockNumber must be an integer when provided' }; + } + if (data.ownerAddress && !validateWalletAddress(data.ownerAddress)) { + return { valid: false, error: 'Invalid ownerAddress' }; + } + if (!validateWalletAddress(data.contractAddress)) { + return { valid: false, error: 'Invalid contractAddress' }; + } + break; + case 'token-holding': + // ownerAddress is optional; server injects from request walletAddress when omitted. + if ( + !data.contractAddress || data.minBalance === null || data.minBalance === undefined || typeof data.chainId !== 'number' - ) { - return { valid: false, error: 'contractAddress, minBalance, and chainId are required' }; - } - if (data.blockNumber !== undefined && data.blockNumber !== null && !Number.isInteger(data.blockNumber)) { - return { valid: false, error: 'blockNumber must be an integer when provided' }; - } - if (data.ownerAddress && !validateWalletAddress(data.ownerAddress)) { - return { valid: false, error: 'Invalid ownerAddress' }; - } - if (!validateWalletAddress(data.contractAddress)) { - return { valid: false, error: 'Invalid contractAddress' }; - } - break; - case 'ownership-dns-txt': - if (!data.domain || typeof data.domain !== 'string') { - return { valid: false, error: 'domain is required' }; - } - if (data.walletAddress && !validateWalletAddress(data.walletAddress)) { - return { valid: false, error: 'Invalid walletAddress' }; - } - break; - case 'wallet-link': - if (!data.primaryWalletAddress || !validateUniversalAddress(data.primaryWalletAddress, data.chain)) { - return { valid: false, error: 'primaryWalletAddress is required' }; - } - if (!data.secondaryWalletAddress || !validateUniversalAddress(data.secondaryWalletAddress, data.chain)) { - return { valid: false, error: 'secondaryWalletAddress is required' }; - } - if (!data.signature || typeof data.signature !== 'string') { - return { valid: false, error: 'signature is required (signed by secondary wallet)' }; - } - if (typeof data.chain !== 'string' || !/^[a-z0-9]+:[^\s]+$/.test(data.chain)) { - return { valid: false, error: 'chain is required (namespace:reference)' }; - } - if (typeof data.signatureMethod !== 'string' || !data.signatureMethod.trim()) { - return { valid: false, error: 'signatureMethod is required' }; - } - if (typeof data.signedTimestamp !== 'number') { - return { valid: false, error: 'signedTimestamp is required' }; - } - break; - case 'contract-ownership': - if (!data.contractAddress || !validateWalletAddress(data.contractAddress)) { - return { valid: false, error: 'contractAddress is required' }; - } - if (data.walletAddress && !validateWalletAddress(data.walletAddress)) { - return { valid: false, error: 'Invalid walletAddress' }; - } - if (typeof data.chainId !== 'number') { - return { valid: false, error: 'chainId is required' }; - } - break; - case 'agent-identity': - if (!data.agentId || typeof data.agentId !== 'string' || data.agentId.length < 1 || data.agentId.length > 128) { - return { valid: false, error: 'agentId is required (1-128 chars)' }; - } - if (!data.agentWallet || !validateWalletAddress(data.agentWallet)) { - return { valid: false, error: 'agentWallet is required' }; - } - if (data.agentType && !['ai', 'bot', 'service', 'automation', 'agent'].includes(data.agentType)) { - return { valid: false, error: 'agentType must be one of: ai, bot, service, automation, agent' }; - } - break; - case 'agent-delegation': - if (!data.controllerWallet || !validateWalletAddress(data.controllerWallet)) { - return { valid: false, error: 'controllerWallet is required' }; - } - if (!data.agentWallet || !validateWalletAddress(data.agentWallet)) { - return { valid: false, error: 'agentWallet is required' }; - } - if (data.scope && (typeof data.scope !== 'string' || data.scope.length > 128)) { - return { valid: false, error: 'scope must be a string (max 128 chars)' }; - } - if (data.expiresAt && (typeof data.expiresAt !== 'number' || data.expiresAt < Date.now())) { - return { valid: false, error: 'expiresAt must be a future timestamp' }; - } - break; - case 'ai-content-moderation': - if (!data.content || typeof data.content !== 'string') { - return { valid: false, error: 'content is required' }; - } - if (!data.contentType || typeof data.contentType !== 'string') { - return { valid: false, error: 'contentType (MIME type) is required' }; - } - { - // Only allow content types that are actually moderated (no "verified but skipped" bypass). - const contentType = String(data.contentType).split(';')[0].trim().toLowerCase(); - const validTypes = [ - 'image/jpeg', - 'image/png', - 'image/webp', - 'image/gif', - 'text/plain', - 'text/markdown', - 'text/x-markdown', - 'application/json', - 'application/xml' - ]; - if (!validTypes.includes(contentType)) { - return { valid: false, error: `contentType must be one of: ${validTypes.join(', ')}` }; - } - const isTextual = contentType.startsWith('text/') || contentType.includes('markdown'); - if (isTextual) { - // Backend enforces 50KB UTF-8 limit for textual moderation payloads. - try { - const maxBytes = 50 * 1024; - const bytes = (typeof TextEncoder !== 'undefined') - ? new TextEncoder().encode(data.content).length - : String(data.content).length; - if (bytes > maxBytes) { - return { valid: false, error: `content exceeds ${maxBytes} bytes limit for ai-content-moderation verifier (text)` }; - } - } catch { - // If encoding fails, defer to server. + ) { + return { valid: false, error: 'contractAddress, minBalance, and chainId are required' }; + } + if (data.blockNumber !== undefined && data.blockNumber !== null && !Number.isInteger(data.blockNumber)) { + return { valid: false, error: 'blockNumber must be an integer when provided' }; + } + if (data.ownerAddress && !validateWalletAddress(data.ownerAddress)) { + return { valid: false, error: 'Invalid ownerAddress' }; + } + if (!validateWalletAddress(data.contractAddress)) { + return { valid: false, error: 'Invalid contractAddress' }; + } + break; + case 'ownership-dns-txt': + if (!data.domain || typeof data.domain !== 'string') { + return { valid: false, error: 'domain is required' }; + } + if (data.walletAddress && !validateWalletAddress(data.walletAddress)) { + return { valid: false, error: 'Invalid walletAddress' }; + } + break; + case 'wallet-link': + if (!data.primaryWalletAddress || !validateUniversalAddress(data.primaryWalletAddress, data.chain)) { + return { valid: false, error: 'primaryWalletAddress is required' }; + } + if (!data.secondaryWalletAddress || !validateUniversalAddress(data.secondaryWalletAddress, data.chain)) { + return { valid: false, error: 'secondaryWalletAddress is required' }; + } + if (!data.signature || typeof data.signature !== 'string') { + return { valid: false, error: 'signature is required (signed by secondary wallet)' }; + } + if (typeof data.chain !== 'string' || !/^[a-z0-9]+:[^\s]+$/.test(data.chain)) { + return { valid: false, error: 'chain is required (namespace:reference)' }; + } + if (typeof data.signatureMethod !== 'string' || !data.signatureMethod.trim()) { + return { valid: false, error: 'signatureMethod is required' }; + } + if (typeof data.signedTimestamp !== 'number') { + return { valid: false, error: 'signedTimestamp is required' }; + } + break; + case 'contract-ownership': + if (!data.contractAddress || !validateWalletAddress(data.contractAddress)) { + return { valid: false, error: 'contractAddress is required' }; + } + if (data.walletAddress && !validateWalletAddress(data.walletAddress)) { + return { valid: false, error: 'Invalid walletAddress' }; + } + if (typeof data.chainId !== 'number') { + return { valid: false, error: 'chainId is required' }; + } + break; + case 'agent-identity': + if (!data.agentId || typeof data.agentId !== 'string' || data.agentId.length < 1 || data.agentId.length > 128) { + return { valid: false, error: 'agentId is required (1-128 chars)' }; + } + if (!data.agentWallet || !validateWalletAddress(data.agentWallet)) { + return { valid: false, error: 'agentWallet is required' }; + } + if (data.agentType && !['ai', 'bot', 'service', 'automation', 'agent'].includes(data.agentType)) { + return { valid: false, error: 'agentType must be one of: ai, bot, service, automation, agent' }; + } + break; + case 'agent-delegation': + if (!data.controllerWallet || !validateWalletAddress(data.controllerWallet)) { + return { valid: false, error: 'controllerWallet is required' }; + } + if (!data.agentWallet || !validateWalletAddress(data.agentWallet)) { + return { valid: false, error: 'agentWallet is required' }; + } + if (data.scope && (typeof data.scope !== 'string' || data.scope.length > 128)) { + return { valid: false, error: 'scope must be a string (max 128 chars)' }; + } + if (data.expiresAt && (typeof data.expiresAt !== 'number' || data.expiresAt < Date.now())) { + return { valid: false, error: 'expiresAt must be a future timestamp' }; + } + break; + case 'ai-content-moderation': + if (!data.content || typeof data.content !== 'string') { + return { valid: false, error: 'content is required' }; + } + if (!data.contentType || typeof data.contentType !== 'string') { + return { valid: false, error: 'contentType (MIME type) is required' }; + } + { + // Only allow content types that are actually moderated (no "verified but skipped" bypass). + const contentType = String(data.contentType).split(';')[0].trim().toLowerCase(); + const validTypes = [ + 'image/jpeg', + 'image/png', + 'image/webp', + 'image/gif', + 'text/plain', + 'text/markdown', + 'text/x-markdown', + 'application/json', + 'application/xml' + ]; + if (!validTypes.includes(contentType)) { + return { valid: false, error: `contentType must be one of: ${validTypes.join(', ')}` }; + } + const isTextual = contentType.startsWith('text/') || contentType.includes('markdown'); + if (isTextual) { + // Backend enforces 50KB UTF-8 limit for textual moderation payloads. + try { + const maxBytes = 50 * 1024; + const bytes = (typeof TextEncoder !== 'undefined') + ? new TextEncoder().encode(data.content).length + : String(data.content).length; + if (bytes > maxBytes) { + return { + valid: false, + error: `content exceeds ${maxBytes} bytes limit for ai-content-moderation verifier (text)` + }; } + } catch { + // If encoding fails, defer to server. } } - if (data.content.length > 13653334) { - return { valid: false, error: 'content exceeds 10MB limit' }; - } - break; - case 'ownership-pseudonym': - if (!data.pseudonymId || typeof data.pseudonymId !== 'string') { - return { valid: false, error: 'pseudonymId is required' }; - } - // Validate handle format (3-64 chars, lowercase alphanumeric with ._-) - if (!/^[a-z0-9._-]{3,64}$/.test(data.pseudonymId.trim().toLowerCase())) { - return { valid: false, error: 'pseudonymId must be 3-64 characters, lowercase alphanumeric with dots, underscores, or hyphens' }; - } - // Validate namespace if provided (1-64 chars) - if (data.namespace && typeof data.namespace === 'string') { - if (!/^[a-z0-9._-]{1,64}$/.test(data.namespace.trim().toLowerCase())) { - return { valid: false, error: 'namespace must be 1-64 characters, lowercase alphanumeric with dots, underscores, or hyphens' }; - } - } - // Note: signature is not required - envelope signature provides authentication - break; - case 'wallet-risk': - if (data.walletAddress && !validateUniversalAddress(data.walletAddress, data.chain)) { - return { valid: false, error: 'Invalid walletAddress' }; + } + if (data.content.length > 13653334) { + return { valid: false, error: 'content exceeds 10MB limit' }; + } + break; + case 'ownership-pseudonym': + if (!data.pseudonymId || typeof data.pseudonymId !== 'string') { + return { valid: false, error: 'pseudonymId is required' }; + } + // Validate handle format (3-64 chars, lowercase alphanumeric with ._-) + if (!/^[a-z0-9._-]{3,64}$/.test(data.pseudonymId.trim().toLowerCase())) { + return { valid: false, error: 'pseudonymId must be 3-64 characters, lowercase alphanumeric with dots, underscores, or hyphens' }; + } + // Validate namespace if provided (1-64 chars) + if (data.namespace && typeof data.namespace === 'string') { + if (!/^[a-z0-9._-]{1,64}$/.test(data.namespace.trim().toLowerCase())) { + return { valid: false, error: 'namespace must be 1-64 characters, lowercase alphanumeric with dots, underscores, or hyphens' }; } - break; + } + // Note: signature is not required - envelope signature provides authentication + break; + case 'wallet-risk': + if (data.walletAddress && !validateUniversalAddress(data.walletAddress, data.chain)) { + return { valid: false, error: 'Invalid walletAddress' }; + } + break; } - + return { valid: true }; }; @@ -319,7 +323,6 @@ export class NeusClient { ...config }; - // NEUS Network API this.baseUrl = this.config.apiUrl || 'https://api.neus.network'; // Enforce HTTPS for neus.network domains to satisfy CSP and normalize URLs try { @@ -332,32 +335,28 @@ export class NeusClient { } catch { // If invalid URL string, leave as-is } - // Normalize apiUrl on config this.config.apiUrl = this.baseUrl; - // Default headers for API requests + + // Default headers + this.defaultHeaders = { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-Neus-Sdk': 'js' }; - // Optional API key (server-side only; do not embed in browser apps) if (typeof this.config.apiKey === 'string' && this.config.apiKey.trim().length > 0) { this.defaultHeaders['Authorization'] = `Bearer ${this.config.apiKey.trim()}`; } - // Public app attribution header (non-secret) if (typeof this.config.appId === 'string' && this.config.appId.trim().length > 0) { this.defaultHeaders['X-Neus-App'] = this.config.appId.trim(); } - // Ephemeral sponsor capability token if (typeof this.config.sponsorGrant === 'string' && this.config.sponsorGrant.trim().length > 0) { this.defaultHeaders['X-Sponsor-Grant'] = this.config.sponsorGrant.trim(); } - // x402 retry receipt header if (typeof this.config.paymentSignature === 'string' && this.config.paymentSignature.trim().length > 0) { this.defaultHeaders['PAYMENT-SIGNATURE'] = this.config.paymentSignature.trim(); } - // Optional caller-supplied passthrough headers. if (this.config.extraHeaders && typeof this.config.extraHeaders === 'object') { for (const [k, v] of Object.entries(this.config.extraHeaders)) { if (!k || v === undefined || v === null) continue; @@ -368,7 +367,6 @@ export class NeusClient { } } try { - // Attach origin in browser environments if (typeof window !== 'undefined' && window.location && window.location.origin) { this.defaultHeaders['X-Client-Origin'] = window.location.origin; } @@ -511,58 +509,46 @@ export class NeusClient { // ============================================================================ /** - * VERIFY - Standard verification (auto or manual) - * - * Create proofs with complete control over the verification process. - * If signature and walletAddress are omitted but verifier/content are provided, - * this method performs the wallet flow inline (no aliases, no secondary methods). - * + * Create a verification proof. + * + * Supports two paths: + * - **Auto:** Supply `verifier`, `content`, and/or `data` with an optional + * `wallet` provider. The SDK handles signing internally. + * - **Manual:** Supply pre-signed `verifierIds`, `data`, `walletAddress`, + * `signature`, and `signedTimestamp`. + * * @param {Object} params - Verification parameters + * @param {string} [params.verifier] - Verifier ID (auto path, e.g. 'ownership-basic') + * @param {string} [params.content] - Content to verify (auto path) + * @param {Object} [params.data] - Structured verification data + * @param {Object} [params.wallet] - Wallet provider (auto path) + * @param {Object} [params.options] - Additional options * @param {Array} [params.verifierIds] - Array of verifier IDs (manual path) - * @param {Object} [params.data] - Verification data object (manual path) * @param {string} [params.walletAddress] - Wallet address that signed the request (manual path) * @param {string} [params.signature] - EIP-191 signature (manual path) * @param {number} [params.signedTimestamp] - Unix timestamp when signature was created (manual path) - * @param {number} [params.chainId] - Advanced/optional. EVM signing-context hint; auto-resolved to protocol hub chain when omitted. For asset verifiers, set chainId inside data instead. - * @param {Object} [params.options] - Additional options - * @param {string} [params.verifier] - Verifier ID (auto path) - * @param {string} [params.content] - Content/description (auto path) - * @param {Object} [params.wallet] - Optional injected wallet/provider (auto path) - * @returns {Promise} Verification result with proofId (qHash is a deprecated alias) - * + * @param {number} [params.chainId] - EVM signing-context hint; auto-resolved to protocol hub chain when omitted + * @returns {Promise} Verification result with proofId + * * @example + * // Auto path + * const proof = await client.verify({ + * verifier: 'ownership-basic', + * content: 'Hello World', + * wallet: window.ethereum + * }); + * + * @example + * // Manual path * const proof = await client.verify({ * verifierIds: ['ownership-basic'], - * data: { - * content: "My content", - * owner: walletAddress, // or ownerAddress for nft-ownership/token-holding - * reference: { type: 'other', id: 'my-unique-identifier' } - * }, + * data: { content: "My content", owner: walletAddress }, * walletAddress: '0x...', * signature: '0x...', * signedTimestamp: Date.now(), * options: { targetChains: [421614, 11155111] } * }); */ - /** - * Create a verification proof - * - * @param {Object} params - Verification parameters - * @param {string} [params.verifier] - Verifier ID (e.g., 'ownership-basic') - * @param {string} [params.content] - Content to verify - * @param {Object} [params.data] - Structured verification data - * @param {Object} [params.wallet] - Wallet provider - * @param {Object} [params.options] - Additional options - * @returns {Promise} Verification result with proofId (qHash is a deprecated alias) - * - * @example - * // Simple ownership proof - * const proof = await client.verify({ - * verifier: 'ownership-basic', - * content: 'Hello World', - * wallet: window.ethereum - * }); - */ async verify(params) { // Auto path: if no manual signature fields but auto fields are provided, perform inline wallet flow if ((!params?.signature || !params?.walletAddress) && (params?.verifier || params?.content || params?.data)) { @@ -592,11 +578,11 @@ export class NeusClient { `${verifier} requires hosted interactive checkout. Use VerifyGate or redirect to ${hostedCheckoutUrl}.` ); } - + // These verifiers require explicit data parameter (no auto-path) const requiresDataParam = [ - 'ownership-dns-txt', - 'wallet-link', + 'ownership-dns-txt', + 'wallet-link', 'contract-ownership', 'ownership-pseudonym', 'wallet-risk', @@ -794,7 +780,6 @@ export class NeusClient { ...(data?.includeDetails !== undefined && { includeDetails: data.includeDetails }) }; } else { - // Default structure for unknown verifiers (should not reach here with validVerifiers check) verificationData = data ? { content, owner: walletAddress, @@ -817,7 +802,6 @@ export class NeusClient { let signature; try { - // UNIFIED SIGNING: Matches utils/core.ts personalSignUniversal exactly const toHexUtf8 = (s) => { try { const enc = new TextEncoder(); @@ -831,7 +815,7 @@ export class NeusClient { return hex; } }; - + // Detect Farcaster wallet - requires hex-encoded messages FIRST const isFarcasterWallet = (() => { if (typeof window === 'undefined') return false; @@ -848,7 +832,7 @@ export class NeusClient { } return false; })(); - + if (isFarcasterWallet) { try { const hexMsg = toHexUtf8(message); @@ -857,7 +841,7 @@ export class NeusClient { // Fall through } } - + if (!signature) { try { signature = await provider.request({ method: 'personal_sign', params: [message, walletAddress] }); @@ -865,15 +849,17 @@ export class NeusClient { const msg = String(e && (e.message || e.reason) || e || '').toLowerCase(); const errCode = (e && (e.code || (e.error && e.error.code))) || null; const needsHex = /byte|bytes|invalid byte sequence|encoding|non-hex/i.test(msg); - + + const unsupportedRe = + /method.*not.*supported|unsupported|not implemented|method not found|unknown method|does not support/i; const methodUnsupported = ( - /method.*not.*supported|unsupported|not implemented|method not found|unknown method|does not support/i.test(msg) || + unsupportedRe.test(msg) || errCode === -32601 || errCode === 4200 || (msg.includes('personal_sign') && msg.includes('not')) || (msg.includes('request method') && msg.includes('not supported')) ); - + if (methodUnsupported) { this._log('personal_sign not supported; attempting eth_sign fallback'); try { @@ -1004,8 +990,6 @@ export class NeusClient { options: optionsPayload }; - // SECURITY: Do not send proof signatures in Authorization headers. - // Signatures belong in the request body only (they are not bearer tokens). const response = await this._makeRequest('POST', '/api/v1/verification', requestData); if (!response.success) { @@ -1094,8 +1078,6 @@ export class NeusClient { const signedTimestamp = Date.now(); - // IMPORTANT: This must match the server's Standard Signing String owner-access check. - // Keep wire payload key `qHash` for backwards compatibility. const message = constructVerificationMessage({ walletAddress, signedTimestamp, @@ -1119,7 +1101,6 @@ export class NeusClient { throw new ValidationError(`Failed to sign message: ${error.message}`); } - // Make request with signature headers (server reads x-wallet-address/x-signature/x-signed-timestamp) const response = await this._makeRequest('GET', `/api/v1/verification/status/${proofId}`, null, { 'x-wallet-address': walletAddress, 'x-signature': signature, @@ -1166,17 +1147,17 @@ export class NeusClient { /** * POLL PROOF STATUS - Wait for verification completion - * + * * Polls the verification status until it reaches a terminal state (completed or failed). * Useful for providing real-time feedback to users during verification. - * + * * @param {string} proofId - Proof ID to poll (standard). `qHash` is a deprecated alias (same value). * @param {Object} [options] - Polling options * @param {number} [options.interval=5000] - Polling interval in ms * @param {number} [options.timeout=120000] - Total timeout in ms * @param {Function} [options.onProgress] - Progress callback function * @returns {Promise} Final verification status - * + * * @example * const finalStatus = await client.pollProofStatus(proofId, { * interval: 3000, @@ -1202,34 +1183,34 @@ export class NeusClient { const startTime = Date.now(); let consecutiveRateLimits = 0; - + while (Date.now() - startTime < timeout) { try { const status = await this.getStatus(proofId); consecutiveRateLimits = 0; - + // Call progress callback if provided if (onProgress && typeof onProgress === 'function') { onProgress(status.data || status); } - + // Check for terminal states const currentStatus = status.data?.status || status.status; if (this._isTerminalStatus(currentStatus)) { this._log('Verification completed', { status: currentStatus, duration: Date.now() - startTime }); return status; } - + // Wait before next poll await new Promise(resolve => setTimeout(resolve, interval)); - + } catch (error) { this._log('Status poll error', error.message); // Continue polling unless it's a validation error if (error instanceof ValidationError) { throw error; } - + let nextDelay = interval; if (error instanceof ApiError && Number(error.statusCode) === 429) { consecutiveRateLimits += 1; @@ -1240,17 +1221,17 @@ export class NeusClient { const jitter = Math.floor(backoff * (0.5 + Math.random() * 0.5)); // 50-100% nextDelay = jitter; } - + await new Promise(resolve => setTimeout(resolve, nextDelay)); } } - + throw new NetworkError(`Polling timeout after ${timeout}ms`, 'POLLING_TIMEOUT'); } /** * DETECT CHAIN ID - Get current wallet chain - * + * * @returns {Promise} Current chain ID */ async detectChainId() { @@ -1284,7 +1265,6 @@ export class NeusClient { const message = constructVerificationMessage({ walletAddress: address, signedTimestamp, - // Keep wire payload key `qHash` for backwards compatibility. data: { action: 'revoke_proof', qHash: proofId }, verifierIds: ['ownership-basic'], ...(signerIsEvm ? { chainId: this._getHubChainId() } : { chain }) @@ -1307,7 +1287,6 @@ export class NeusClient { const res = await fetch(`${this.config.apiUrl}/api/v1/proofs/revoke-self/${proofId}`, { method: 'POST', - // SECURITY: Do not put proof signatures into Authorization headers. headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ walletAddress: address, @@ -1615,10 +1594,10 @@ export class NeusClient { /** * CHECK GATE - Evaluate requirements against existing proofs - * + * * Gate-first verification: checks if wallet has valid proofs satisfying requirements. * Returns which requirements are missing/expired. - * + * * @param {Object} params - Gate check parameters * @param {string} params.walletAddress - Target wallet * @param {Array} params.requirements - Array of gate requirements @@ -1636,7 +1615,7 @@ export class NeusClient { * Note: contentHash matching uses approximation in SDK; for exact SHA-256 matching, use backend API * @param {Array} [params.proofs] - Pre-fetched proofs (skip API call) * @returns {Promise} Gate result with satisfied, missing, existing - * + * * @example * // Basic gate check * const result = await client.checkGate({ @@ -1696,25 +1675,25 @@ export class NeusClient { // Gate format: match as array [{path, op, value}]. Convert to {path: value} for iteration. const matchObj = Array.isArray(match) ? Object.fromEntries( - match - .filter((m) => m && m.path && String(m.value ?? '').trim() !== '') - .map((m) => [String(m.path).trim(), m.value]) - ) + match + .filter((m) => m && m.path && String(m.value ?? '').trim() !== '') + .map((m) => [String(m.path).trim(), m.value]) + ) : match; for (const [key, expected] of Object.entries(matchObj)) { let actualValue = null; - + // Handle nested field access if (key.includes('.')) { const parts = key.split('.'); let current = data; - + if (parts[0] === 'input' && input) { current = input; parts.shift(); } - + for (const part of parts) { if (current && typeof current === 'object' && part in current) { current = current[part]; @@ -1727,11 +1706,11 @@ export class NeusClient { } else { actualValue = input[key] || data[key]; } - + if (key === 'content' && actualValue === undefined) { actualValue = data.reference?.id || data.content; } - + // Special handling for verifier-specific fields (claim-based, aligns with proofs/check) if (actualValue === undefined) { const claims = data.claims || {}; @@ -1767,7 +1746,7 @@ export class NeusClient { actualValue = data.poisoned; } } - + // Content hash check (approximation) if (key === 'contentHash' && actualValue === undefined && data.content) { try { @@ -1779,12 +1758,12 @@ export class NeusClient { hash = ((hash << 5) - hash) + char; hash = hash & hash; } - actualValue = '0x' + Math.abs(hash).toString(16).padStart(64, '0').substring(0, 66); + actualValue = `0x${ Math.abs(hash).toString(16).padStart(64, '0').substring(0, 66)}`; } catch { actualValue = String(data.content); } } - + let normalizedActual = actualValue; let normalizedExpected = expected; @@ -1813,7 +1792,7 @@ export class NeusClient { normalizedActual = actualValue; normalizedExpected = expected; } - + if (normalizedActual !== normalizedExpected) { return false; } @@ -1866,10 +1845,10 @@ export class NeusClient { */ async _makeRequest(method, endpoint, data = null, headersOverride = null) { const url = `${this.baseUrl}${endpoint}`; - + const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), this.config.timeout); - + const options = { method, headers: { ...this.defaultHeaders, ...(headersOverride || {}) }, @@ -1885,7 +1864,7 @@ export class NeusClient { try { const response = await fetch(url, options); clearTimeout(timeoutId); - + let responseData; try { responseData = await response.json(); @@ -1901,15 +1880,15 @@ export class NeusClient { } catch (error) { clearTimeout(timeoutId); - + if (error.name === 'AbortError') { throw new NetworkError(`Request timeout after ${this.config.timeout}ms`); } - + if (error instanceof ApiError) { throw error; } - + throw new NetworkError(`Network error: ${error.message}`); } } @@ -1933,9 +1912,9 @@ export class NeusClient { response?.data?.id; const finalProofId = proofId || qHash || null; const finalQHash = qHash || proofId || finalProofId; - - const status = response?.data?.status || - response?.status || + + const status = response?.data?.status || + response?.status || response?.data?.resource?.status || (response?.success ? 'completed' : 'unknown'); diff --git a/sdk/errors.js b/sdk/errors.js index d17b1027..919af1d6 100644 --- a/sdk/errors.js +++ b/sdk/errors.js @@ -12,7 +12,7 @@ export class SDKError extends Error { this.code = code; this.details = details; this.timestamp = Date.now(); - + // Ensure proper prototype chain if (Error.captureStackTrace) { Error.captureStackTrace(this, SDKError); @@ -39,7 +39,7 @@ export class ApiError extends SDKError { this.name = 'ApiError'; this.statusCode = statusCode; this.response = response; - + // Additional classification this.isClientError = statusCode >= 400 && statusCode < 500; this.isServerError = statusCode >= 500; @@ -48,11 +48,11 @@ export class ApiError extends SDKError { static fromResponse(response, responseData) { const statusCode = response.status; - const message = responseData?.error?.message || - responseData?.message || + const message = responseData?.error?.message || + responseData?.message || `API request failed with status ${statusCode}`; const code = responseData?.error?.code || 'API_ERROR'; - + return new ApiError(message, statusCode, code, responseData); } diff --git a/sdk/gates.js b/sdk/gates.js index 5813216a..e1818f61 100644 --- a/sdk/gates.js +++ b/sdk/gates.js @@ -1,9 +1,9 @@ /** * NEUS SDK Gate Recipes - * + * * These are EXAMPLES, not defaults. * Pick or copy-paste what fits your use case. - * + * * @license Apache-2.0 */ @@ -23,7 +23,7 @@ export const YEAR = 365 * DAY; * Integrator should add match: { contractAddress: '0x...' } when using */ export const GATE_NFT_HOLDER = [ - { verifierId: 'nft-ownership' }, + { verifierId: 'nft-ownership' } ]; /** @@ -31,7 +31,7 @@ export const GATE_NFT_HOLDER = [ * Integrator should add match: { contractAddress: '0x...', minBalance: '...' } */ export const GATE_TOKEN_HOLDER = [ - { verifierId: 'token-holding' }, + { verifierId: 'token-holding' } ]; /** @@ -39,7 +39,7 @@ export const GATE_TOKEN_HOLDER = [ * Short TTL (1h) because ownership can transfer (point-in-time proof) */ export const GATE_CONTRACT_ADMIN = [ - { verifierId: 'contract-ownership', maxAgeMs: HOUR }, + { verifierId: 'contract-ownership', maxAgeMs: HOUR } ]; /** @@ -47,7 +47,7 @@ export const GATE_CONTRACT_ADMIN = [ * For verified organization badges, creator platforms */ export const GATE_DOMAIN_OWNER = [ - { verifierId: 'ownership-dns-txt' }, + { verifierId: 'ownership-dns-txt' } ]; /** @@ -55,7 +55,7 @@ export const GATE_DOMAIN_OWNER = [ * For multi-wallet identity features */ export const GATE_LINKED_WALLETS = [ - { verifierId: 'wallet-link' }, + { verifierId: 'wallet-link' } ]; /** @@ -63,7 +63,7 @@ export const GATE_LINKED_WALLETS = [ * For agent/bot verification features */ export const GATE_AGENT_IDENTITY = [ - { verifierId: 'agent-identity' }, + { verifierId: 'agent-identity' } ]; /** @@ -71,7 +71,7 @@ export const GATE_AGENT_IDENTITY = [ * With recommended 7-day TTL for security */ export const GATE_AGENT_DELEGATION = [ - { verifierId: 'agent-delegation', maxAgeMs: 7 * DAY }, + { verifierId: 'agent-delegation', maxAgeMs: 7 * DAY } ]; /** @@ -79,7 +79,7 @@ export const GATE_AGENT_DELEGATION = [ * Proof is permanent (policy snapshot); re-run only if your policy/provider requirements change. */ export const GATE_CONTENT_MODERATION = [ - { verifierId: 'ai-content-moderation' }, + { verifierId: 'ai-content-moderation' } ]; /** @@ -87,7 +87,7 @@ export const GATE_CONTENT_MODERATION = [ * Provider-backed risk signal */ export const GATE_WALLET_RISK = [ - { verifierId: 'wallet-risk' }, + { verifierId: 'wallet-risk' } ]; /** @@ -95,7 +95,7 @@ export const GATE_WALLET_RISK = [ * For anonymous reputation systems */ export const GATE_PSEUDONYM = [ - { verifierId: 'ownership-pseudonym' }, + { verifierId: 'ownership-pseudonym' } ]; // ============================================================================ @@ -106,11 +106,11 @@ export const GATE_PSEUDONYM = [ * Create a custom gate from verifier IDs * @param {Array} requirements - Array of verifier IDs or requirement objects * @returns {Array} Gate requirements array - * + * * @example * // Simple: just verifier IDs * const gate = createGate(['nft-ownership', 'token-holding']); - * + * * // With options * const gate = createGate([ * { verifierId: 'nft-ownership', match: { contractAddress: '0x...' } }, @@ -130,14 +130,14 @@ export function createGate(requirements) { * Combine multiple gates (union of requirements) * @param {...Array} gates - Gate arrays to combine * @returns {Array} Combined gate requirements - * + * * @example * const strictGate = combineGates(GATE_NFT_HOLDER, GATE_TOKEN_HOLDER); */ export function combineGates(...gates) { const combined = []; const seen = new Set(); - + for (const gate of gates) { for (const req of gate) { const key = req.verifierId + JSON.stringify(req.match || {}); @@ -147,7 +147,7 @@ export function combineGates(...gates) { } } } - + return combined; } @@ -171,5 +171,5 @@ export default { GATE_PSEUDONYM, // Helpers createGate, - combineGates, + combineGates }; diff --git a/sdk/index.js b/sdk/index.js index 44898d11..431ccce5 100644 --- a/sdk/index.js +++ b/sdk/index.js @@ -58,7 +58,7 @@ export { GATE_PSEUDONYM, // Helpers createGate, - combineGates, + combineGates } from './gates.js'; // Error classes diff --git a/sdk/test/client.test.js b/sdk/test/client.test.js index d32bff5b..6a8babcf 100644 --- a/sdk/test/client.test.js +++ b/sdk/test/client.test.js @@ -11,7 +11,7 @@ global.fetch = vi.fn(); describe('NeusClient', () => { let client; - + beforeEach(() => { client = new NeusClient({ enableLogging: false }); vi.clearAllMocks(); @@ -90,14 +90,14 @@ describe('NeusClient', () => { }); const result = await client.getStatus('0xtest123'); - + expect(fetch).toHaveBeenCalledWith( 'https://api.neus.network/api/v1/verification/status/0xtest123', expect.objectContaining({ method: 'GET' }) ); - + expect(result.success).toBe(true); expect(result.proofId).toBe('0xtest123'); expect(result.qHash).toBe('0xtest123'); @@ -145,7 +145,7 @@ describe('NeusClient', () => { }); const verifiers = await client.getVerifiers(); - + expect(Array.isArray(verifiers)).toBe(true); expect(verifiers).toContain('ownership-basic'); expect(verifiers).toContain('nft-ownership'); diff --git a/sdk/test/integration.test.js b/sdk/test/integration.test.js index 28092369..f6336a90 100644 --- a/sdk/test/integration.test.js +++ b/sdk/test/integration.test.js @@ -37,17 +37,17 @@ describe('NEUS SDK Integration', () => { if (!LIVE) return; const verifiers = await client.getVerifiers(); - + expect(Array.isArray(verifiers)).toBe(true); expect(verifiers.length).toBeGreaterThan(0); - + // Verify Day 1 verifiers are present const expectedVerifiers = [ 'ownership-basic', - 'nft-ownership', + 'nft-ownership', 'token-holding' ]; - + expectedVerifiers.forEach(verifier => { expect(verifiers).toContain(verifier); }); @@ -59,7 +59,7 @@ describe('NEUS SDK Integration', () => { if (!LIVE) return; const fakeQHash = '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef'; - + // Should throw ApiError for 404, not crash try { await client.getStatus(fakeQHash); @@ -95,7 +95,7 @@ describe('NEUS SDK Integration', () => { const clients = [ new NeusClient({ apiUrl: 'https://api.neus.network/' }), new NeusClient({ apiUrl: 'https://api.neus.network' }), - new NeusClient({ apiUrl: 'http://localhost:3000' }), + new NeusClient({ apiUrl: 'http://localhost:3000' }) ]; expect(clients[0].baseUrl).toBe('https://api.neus.network'); @@ -113,18 +113,18 @@ describe('NEUS SDK Integration', () => { it('should demonstrate typical usage pattern', async () => { // This test demonstrates the typical SDK usage without actually // creating proofs (since that requires wallet interaction) - + // 1. Check API health const healthy = await client.isHealthy().catch(() => false); expect(typeof healthy).toBe('boolean'); - + // 2. Get available verifiers if (healthy && LIVE) { const verifiers = await client.getVerifiers(); expect(Array.isArray(verifiers)).toBe(true); expect(verifiers.length).toBeGreaterThan(0); } - + // 3. Input validation works (detectChainId requires browser environment) expect(() => client.isHealthy()).not.toThrow(); }); diff --git a/sdk/test/utils.test.js b/sdk/test/utils.test.js index 73d17053..d0d3e30b 100644 --- a/sdk/test/utils.test.js +++ b/sdk/test/utils.test.js @@ -28,7 +28,7 @@ import { } from '../utils.js'; describe('Utils', () => { - + describe('constructVerificationMessage()', () => { it('should create consistent message format', () => { const params = { @@ -40,7 +40,7 @@ describe('Utils', () => { }; const message = constructVerificationMessage(params); - + expect(typeof message).toBe('string'); expect(message).toContain('NEUS Verification Request'); expect(message).toContain('0x742d35Cc6634C0532925a3b8D82AB78c0D73C3Db'); @@ -58,7 +58,7 @@ describe('Utils', () => { }; const message = constructVerificationMessage(params); - + expect(message).toContain('ownership-basic'); expect(message).toContain('nft-ownership'); }); @@ -104,7 +104,7 @@ describe('Utils', () => { it('should respect custom max age', () => { const now = Date.now(); const tenMinutesAgo = now - 600000; - + expect(validateTimestamp(tenMinutesAgo, 300000)).toBe(false); // 5min max expect(validateTimestamp(tenMinutesAgo, 900000)).toBe(true); // 15min max }); @@ -120,7 +120,7 @@ describe('Utils', () => { describe('createVerificationData()', () => { it('should create basic verification data', () => { const data = createVerificationData( - 'test content', + 'test content', '0x742d35Cc6634C0532925a3b8D82AB78c0D73C3Db' ); @@ -218,12 +218,12 @@ describe('Utils', () => { describe('formatVerificationStatus()', () => { it('should format status objects correctly', () => { const formatted = formatVerificationStatus('verified'); - + expect(formatted).toHaveProperty('label'); expect(formatted).toHaveProperty('description'); expect(formatted).toHaveProperty('color'); expect(formatted).toHaveProperty('category'); - + expect(typeof formatted.label).toBe('string'); expect(typeof formatted.description).toBe('string'); expect(typeof formatted.color).toBe('string'); @@ -232,7 +232,7 @@ describe('Utils', () => { it('should handle unknown statuses', () => { const formatted = formatVerificationStatus('unknown_status'); - + expect(formatted.label).toBe('Unknown Status'); // Actual implementation capitalizes and formats expect(formatted.category).toBe('unknown'); }); @@ -243,7 +243,7 @@ describe('Utils', () => { const start = Date.now(); await delay(50); const elapsed = Date.now() - start; - + expect(elapsed).toBeGreaterThanOrEqual(45); // Account for timing variance expect(elapsed).toBeLessThan(100); }); @@ -253,7 +253,7 @@ describe('Utils', () => { it('should generate consistent hashes', async () => { const hash1 = await computeContentHash('test content'); const hash2 = await computeContentHash('test content'); - + expect(hash1).toBe(hash2); expect(typeof hash1).toBe('string'); expect(hash1.length).toBeGreaterThan(0); @@ -262,7 +262,7 @@ describe('Utils', () => { it('should generate different hashes for different content', async () => { const hash1 = await computeContentHash('content 1'); const hash2 = await computeContentHash('content 2'); - + expect(hash1).not.toBe(hash2); }); }); @@ -296,7 +296,7 @@ describe('Utils', () => { it('should format timestamp to readable string', () => { const timestamp = 1678886400000; const formatted = formatTimestamp(timestamp); - + expect(typeof formatted).toBe('string'); expect(formatted.length).toBeGreaterThan(0); }); @@ -369,7 +369,7 @@ describe('Utils', () => { it('should return immediately on success', async () => { const fn = async () => 'immediate success'; - + const result = await withRetry(fn); expect(result).toBe('immediate success'); }); @@ -443,7 +443,7 @@ describe('Utils', () => { it('should have default verifiers', () => { expect(NEUS_CONSTANTS.DEFAULT_VERIFIERS).toEqual([ 'ownership-basic', - 'nft-ownership', + 'nft-ownership', 'token-holding' ]); }); diff --git a/sdk/types.d.ts b/sdk/types.d.ts index d86df16a..6461582f 100644 --- a/sdk/types.d.ts +++ b/sdk/types.d.ts @@ -577,12 +577,6 @@ declare module '@neus/sdk' { backoffFactor?: number; }): Promise; - /** - * Proof status - */ - // Use NeusClient.getStatus(proofId) for status checks (`qHash` remains as deprecated alias). - - // ============================================================================ // CONSTANTS & REGISTRY // ============================================================================ @@ -676,12 +670,6 @@ declare module '@neus/sdk' { */ export class AuthenticationError extends SDKError {} - // ============================================================================ - // SCHEMA ACCESS - // ============================================================================ - - - // ============================================================================ // PROOFS & GATING TYPES // ============================================================================ diff --git a/sdk/utils.js b/sdk/utils.js index 3519c037..a230641c 100644 --- a/sdk/utils.js +++ b/sdk/utils.js @@ -65,22 +65,22 @@ function deterministicStringify(obj) { if (obj === null || obj === undefined) { return JSON.stringify(obj); } - + if (typeof obj !== 'object') { return JSON.stringify(obj); } - + if (Array.isArray(obj)) { - return '[' + obj.map(item => deterministicStringify(item)).join(',') + ']'; + return `[${ obj.map(item => deterministicStringify(item)).join(',') }]`; } - + // Sort object keys for deterministic output const sortedKeys = Object.keys(obj).sort(); - const pairs = sortedKeys.map(key => - JSON.stringify(key) + ':' + deterministicStringify(obj[key]) + const pairs = sortedKeys.map(key => + `${JSON.stringify(key) }:${ deterministicStringify(obj[key])}` ); - - return '{' + pairs.join(',') + '}'; + + return `{${ pairs.join(',') }}`; } /** @@ -125,12 +125,9 @@ export function constructVerificationMessage({ walletAddress, signedTimestamp, d // Address normalization: EVM (`eip155`) is lowercased; non-EVM namespaces preserve the original string. const namespace = (typeof chain === 'string' && chain.includes(':')) ? chain.split(':')[0] : 'eip155'; const normalizedWalletAddress = namespace === 'eip155' ? walletAddress.toLowerCase() : walletAddress; - - // IMPORTANT: Deterministic JSON serialization is required for signature verification. - // The message must match what the API verifies. + const dataString = deterministicStringify(data); - - // Create standard message format - EXACT format expected by the API + const messageComponents = [ 'NEUS Verification Request', `Wallet: ${normalizedWalletAddress}`, @@ -139,14 +136,13 @@ export function constructVerificationMessage({ walletAddress, signedTimestamp, d `Data: ${dataString}`, `Timestamp: ${signedTimestamp}` ]; - - // Join with newlines - this is the message that gets signed + return messageComponents.join('\n'); } /** * Validate Ethereum wallet address format - * + * * @param {string} address - Address to validate * @returns {boolean} True if valid Ethereum address */ @@ -154,7 +150,7 @@ export function validateWalletAddress(address) { if (!address || typeof address !== 'string') { return false; } - + // Basic Ethereum address validation return /^0x[a-fA-F0-9]{40}$/.test(address); } @@ -183,7 +179,8 @@ export function validateUniversalAddress(address, chain) { } if (namespace === 'bip122') { - return /^(bc1|tb1|bcrt1)[a-z0-9]{11,87}$/.test(value.toLowerCase()) || /^[13mn2][a-km-zA-HJ-NP-Z1-9]{25,62}$/.test(value); + return /^(bc1|tb1|bcrt1)[a-z0-9]{11,87}$/.test(value.toLowerCase()) || + /^[13mn2][a-km-zA-HJ-NP-Z1-9]{25,62}$/.test(value); } if (namespace === 'near') { @@ -196,7 +193,7 @@ export function validateUniversalAddress(address, chain) { /** * Validate timestamp freshness - * + * * @param {number} timestamp - Timestamp to validate * @param {number} maxAgeMs - Maximum age in milliseconds (default: 5 minutes) * @returns {boolean} True if timestamp is valid and recent @@ -205,17 +202,17 @@ export function validateTimestamp(timestamp, maxAgeMs = 5 * 60 * 1000) { if (!timestamp || typeof timestamp !== 'number') { return false; } - + const now = Date.now(); const age = now - timestamp; - + // Check if timestamp is in the past and within allowed age return age >= 0 && age <= maxAgeMs; } /** * Create formatted verification data object - * + * * @param {string} content - Content to verify * @param {string} owner - Owner wallet address * @param {Object} reference - Reference object @@ -254,10 +251,10 @@ export function deriveDid(address, chainIdOrChain) { if (!address || typeof address !== 'string') { throw new SDKError('deriveDid: address is required', 'INVALID_ARGUMENT'); } - + const chainContext = chainIdOrChain || NEUS_CONSTANTS.HUB_CHAIN_ID; const isCAIP = typeof chainContext === 'string' && chainContext.includes(':'); - + if (isCAIP) { const [namespace, segment] = chainContext.split(':'); const normalized = (namespace === 'eip155') ? address.toLowerCase() : address; @@ -505,7 +502,7 @@ export async function signMessage({ provider, message, walletAddress, chain } = return null; } if (typeof resolvedProvider.address === 'string' && resolvedProvider.address) return resolvedProvider.address; - if (typeof resolvedProvider.getAddress === 'function') return await resolvedProvider.getAddress(); + if (typeof resolvedProvider.getAddress === 'function') return resolvedProvider.getAddress(); if (typeof resolvedProvider.request === 'function') { let accounts = await resolvedProvider.request({ method: 'eth_accounts' }).catch(() => []); if (!Array.isArray(accounts) || accounts.length === 0) { @@ -594,7 +591,7 @@ export async function signMessage({ provider, message, walletAddress, chain } = */ export function isTerminalStatus(status) { if (!status || typeof status !== 'string') return false; - + // Success states const successStates = [ 'verified', @@ -603,7 +600,7 @@ export function isTerminalStatus(status) { 'partially_verified', 'verified_propagation_failed' ]; - + // Failure states const failureStates = [ 'rejected', @@ -615,7 +612,7 @@ export function isTerminalStatus(status) { 'error_storage_query', 'not_found' ]; - + return successStates.includes(status) || failureStates.includes(status); } @@ -626,7 +623,7 @@ export function isTerminalStatus(status) { */ export function isSuccessStatus(status) { if (!status || typeof status !== 'string') return false; - + const successStates = [ 'verified', 'verified_no_verifiers', @@ -634,7 +631,7 @@ export function isSuccessStatus(status) { 'partially_verified', 'verified_propagation_failed' ]; - + return successStates.includes(status); } @@ -645,7 +642,7 @@ export function isSuccessStatus(status) { */ export function isFailureStatus(status) { if (!status || typeof status !== 'string') return false; - + const failureStates = [ 'rejected', 'rejected_verifier_failure', @@ -656,7 +653,7 @@ export function isFailureStatus(status) { 'error_storage_query', 'not_found' ]; - + return failureStates.includes(status); } @@ -821,9 +818,9 @@ export class StatusPoller { const pollAttempt = async () => { try { this.attempt++; - + const response = await this.client.getStatus(this.qHash); - + // Check if verification is complete using the terminal status utility if (isTerminalStatus(response.status)) { resolve(response); @@ -887,7 +884,7 @@ export class StatusPoller { export const NEUS_CONSTANTS = { // Hub chain (where all verifications occur) HUB_CHAIN_ID: 84532, - + // Supported target chains for cross-chain propagation TESTNET_CHAINS: [ 11155111, // Ethereum Sepolia @@ -895,15 +892,15 @@ export const NEUS_CONSTANTS = { 421614, // Arbitrum Sepolia 80002 // Polygon Amoy ], - + // API endpoints API_BASE_URL: 'https://api.neus.network', API_VERSION: 'v1', - + // Timeouts and limits SIGNATURE_MAX_AGE_MS: 5 * 60 * 1000, // 5 minutes REQUEST_TIMEOUT_MS: 30 * 1000, // 30 seconds - + // Default verifier set for quick starts DEFAULT_VERIFIERS: [ 'ownership-basic', @@ -1079,24 +1076,24 @@ export async function withRetry(fn, options = {}) { } = options; let lastError; - + for (let attempt = 1; attempt <= maxAttempts; attempt++) { try { return await fn(); } catch (error) { lastError = error; - + if (attempt === maxAttempts) break; - + const delayMs = Math.min( baseDelay * Math.pow(backoffFactor, attempt - 1), maxDelay ); - + await delay(delayMs); } } - + throw lastError; } @@ -1211,7 +1208,7 @@ export function toAgentDelegationMaxSpend(humanAmount, decimals) { throw new ValidationError( 'humanAmount must be a decimal string (e.g. "100" or "100.50")', 'humanAmount', - humanAmount, + humanAmount ); } const dot = s0.indexOf('.'); @@ -1221,9 +1218,9 @@ export function toAgentDelegationMaxSpend(humanAmount, decimals) { intPart === '' ? '0' : (() => { - const s = intPart.replace(/^0+/, ''); - return s === '' ? '0' : s; - })(); + const s = intPart.replace(/^0+/, ''); + return s === '' ? '0' : s; + })(); if (!/^\d+$/.test(intNormalized)) { throw new ValidationError('humanAmount has an invalid integer part', 'humanAmount', humanAmount); } diff --git a/sdk/vitest.config.js b/sdk/vitest.config.js index c2662735..1dd91e92 100644 --- a/sdk/vitest.config.js +++ b/sdk/vitest.config.js @@ -4,13 +4,13 @@ export default defineConfig({ test: { // Test environment environment: 'node', - + // Global test timeout testTimeout: 10000, - + // Hook timeout hookTimeout: 10000, - + // Coverage configuration coverage: { provider: 'v8', @@ -21,30 +21,22 @@ export default defineConfig({ '*.config.js' ] }, - + // Test file patterns include: ['test/**/*.test.js'], - + // Files to exclude exclude: [ 'node_modules/**', 'dist/**' ], - + // Global setup globals: true, - + // Mock configuration mockReset: true, clearMocks: true, restoreMocks: true - }, - - // Resolve configuration - resolve: { - alias: { - '@': './src', - '@test': './test' - } } }); \ No newline at end of file diff --git a/sdk/widgets/index.js b/sdk/widgets/index.js index d54edf7a..b16af17d 100644 --- a/sdk/widgets/index.js +++ b/sdk/widgets/index.js @@ -1,6 +1,6 @@ /** * NEUS Widgets - * + * * Core Widgets: * - VerifyGate: Universal verification gate component * - ProofBadge: Display verification status diff --git a/sdk/widgets/verify-gate/index.js b/sdk/widgets/verify-gate/index.js index dfd52c66..e1a4c0d1 100644 --- a/sdk/widgets/verify-gate/index.js +++ b/sdk/widgets/verify-gate/index.js @@ -1,13 +1,13 @@ -"use client"; +'use client'; /** * NEUS Widgets (VerifyGate + ProofBadge) */ export { VerifyGate } from './dist/VerifyGate.js'; -export { - ProofBadge, - SimpleProofBadge, +export { + ProofBadge, + SimpleProofBadge, NeusPillLink, - VerifiedIcon + VerifiedIcon } from './dist/ProofBadge.js'; diff --git a/sdk/widgets/verify-gate/standalone.js b/sdk/widgets/verify-gate/standalone.js index ae8318b5..3e4def74 100644 --- a/sdk/widgets/verify-gate/standalone.js +++ b/sdk/widgets/verify-gate/standalone.js @@ -5,7 +5,7 @@ * * Embed: * - *
+ *
* * Optional data attributes (per element): * data-neus-proof qHash / proofId (required) @@ -62,7 +62,6 @@ // ------------------------------------------------------------------------- // Badge DOM — matches NeusProofBadgePill (bg-accent-blue/10, border-accent-blue/20, text-accent-blue-light). - // Design tokens: --neus-rgb-accent-primary 152 192 239 // ------------------------------------------------------------------------- var ACCENT_BG = 'rgba(152,192,239,0.1)'; var ACCENT_BORD = 'rgba(152,192,239,0.2)'; @@ -71,7 +70,7 @@ verified: { text: ACCENT_TEXT, label: 'Verified' }, pending: { text: 'rgb(234,179,8)', label: 'Verifying…' }, failed: { text: 'rgb(239,68,68)', label: 'Unverified' }, - unknown: { text: 'rgba(255,255,255,0.68)', label: 'Unknown' }, + unknown: { text: 'rgba(255,255,255,0.68)', label: 'Unknown' } }; function buildBadge(opts) { @@ -103,7 +102,7 @@ 'white-space:nowrap', 'cursor:pointer', 'transition:opacity 0.15s ease', - 'box-sizing:border-box', + 'box-sizing:border-box' ].join(';'); var img = document.createElement('img'); @@ -150,8 +149,8 @@ var json = JSON.parse(xhr.responseText); var st = (json && json.data && json.data.status) ? String(json.data.status).toLowerCase() : ''; var status = st.indexOf('verified') !== -1 ? 'verified' - : (st.indexOf('processing') !== -1 || st.indexOf('pending') !== -1) ? 'pending' - : 'failed'; + : (st.indexOf('processing') !== -1 || st.indexOf('pending') !== -1) ? 'pending' + : 'failed'; var cc = json && json.data && json.data.crosschain; var chains = cc ? (cc.totalChains || 0) : 0; callback(status, chains); @@ -184,8 +183,8 @@ var uiBase = (opts.uiBase || el.getAttribute(ATTR_UI_BASE) || DEFAULT_UI).replace(/\/$/, ''); var size = opts.size || el.getAttribute(ATTR_SIZE) || 'sm'; var showChains = typeof opts.showChains === 'boolean' - ? opts.showChains - : el.getAttribute(ATTR_CHAINS) === 'true'; + ? opts.showChains + : el.getAttribute(ATTR_CHAINS) === 'true'; if (!proofId) return; markMounted(el);