@h3tag/sdk
v0.1.6
Published
Official H3Tag Node.js SDK for content authenticity, provenance, and cryptographic verification
Maintainers
Readme
@h3tag/sdk
The official Node.js SDK for H3Tag, a hash-based zero-knowledge proof verification platform. Ship tamper-proof content workflows, validate authenticity without disclosure, and back every verification with immutable blockchain evidence.
Table of Contents
- Features
- Requirements
- Installation
- Quick Start
- Authentication
- Configuration
- Usage Examples
- API Reference
- Error Handling
- Browser Usage
- Security
- Utilities
- TypeScript Support
- Additional Examples
- Contributing
- Support
- License
Features
- Zero-knowledge verification without exposing content
- Immutable blockchain-backed audit trail
- TypeScript-first
- Works across Node.js, serverless, and edge runtimes
- Safe-by-default error handling and logging
Requirements
- Node.js
>= 20.0.0
Installation
npm install @h3tag/sdkor with Yarn:
yarn add @h3tag/sdkQuick Start
import { createH3TagClient } from '@h3tag/sdk';
const client = createH3TagClient({
apiKey: process.env.H3TAG_API_KEY,
});
const result = await client.generateHash({ content: 'Hello, world!' });
console.log('Hash:', result.hash);
console.log('Verification Tag:', result.verificationTag);
const verified = await client.verifyHash({ content: 'Hello, world!' });
if (verified.verified) {
console.log('Content is authentic!');
}Authentication
API Key (Server Environments)
Best for backend services, CLI tooling, and serverless functions:
const client = createH3TagClient({
apiKey: process.env.H3TAG_API_KEY,
});JWT Access Token (User Sessions)
Use in browser or multi-tenant environments with your own user sessions:
const client = createH3TagClient({
accessToken: userSessionToken,
});Never embed API keys in client-side code. See Security for browser-friendly patterns.
Configuration
createH3TagClient accepts the following options:
apiKey?– Server-side API key issued by H3TagaccessToken?– Short-lived JWT token for user sessionsbaseUrl?– Override the API base URL (defaults tohttps://api.h3tag.com)- Note: The API version prefix (
/v1) is included in endpoint paths, not in the baseUrl. For example, requests are made tohttps://api.h3tag.com/api/v1/hash/generate. Only overridebaseUrlif you're using a custom proxy or staging environment.
- Note: The API version prefix (
fetchImpl?– Customfetchimplementation for non-standard runtimesuserAgent?– Custom identifier appended to outbound requests
Usage Examples
Document Verification
import { createH3TagClient, hashContent } from '@h3tag/sdk';
import { readFileSync } from 'fs';
const client = createH3TagClient({ apiKey: process.env.H3TAG_API_KEY });
const document = readFileSync('contract.pdf');
const hash = hashContent(document);
await client.generateHash({
contentHash: hash,
metadata: {
contentType: 'application/pdf',
filename: 'contract.pdf',
contentSize: document.length,
},
});
const currentHash = hashContent(readFileSync('contract.pdf'));
const verified = await client.verifyHash({ contentHash: currentHash });
if (!verified.verified) {
console.error('Document has been modified!');
}Batch Verification
const summary = await client.verifyBatch({
contentHashes: ['hash1...', 'hash2...', 'hash3...'],
context: {
verifierId: 'user123',
platform: 'my-app',
},
});
console.log(`Verified ${summary.verifiedCount} of ${summary.results.length} hashes`);Continuous Integrity Monitoring
const original = await client.generateHash({ content: 'sensitive data' });
const check = await client.verifyHash({ content: 'sensitive data' });
if (!check.verified) {
console.error('Content integrity compromised!');
}API Reference
createH3TagClient(config)
Creates and configures an H3Tag client instance.
config.apiKey?– API key for authenticated operationsconfig.accessToken?– JWT token for delegated accessconfig.baseUrl?– Alternate API base URLconfig.fetchImpl?– Custom fetch implementationconfig.userAgent?– Appends to default user agent header
Returns an H3TagClient.
client.generateHash(options)
Generates an authenticated hash entry.
content?– Raw content (string | Buffer | Uint8Array)contentHash?– Pre-computed double SHA-256 hash (64hex chars)metadata?– Optional metadata:contentType?,contentSize?,filename?,createdAt?customAttributes?(Record<string, string>)
contentHashes?– Optional content hashes for advanced duplicate detection:- If not provided, only exact hash duplicate detection will be performed
- Keys include:
exact(64 hex chars),perceptual(64 hex chars),perceptual_raw(16 hex chars),normalized(64 hex chars),metadata(64 hex chars) - Providing content hashes enables perceptual matching, normalized text detection, and metadata-based duplicate detection
Returns Promise<GenerateHashResponse>.
client.verifyHash(options)
Checks content or a hash without authentication.
content?– Raw content to hash on the flycontentHash?– Existing hash to compareverificationTag?– Optional verification tag
Returns Promise<VerifyHashResponse>.
client.getHashInfo(hash)
Retrieves metadata about a registered hash.
hash–64-character double SHA-256 hash
Returns Promise<HashInfo>.
client.getZkpStatus(hash)
Fetches zero-knowledge proof status for a hash.
hash–64-character double SHA-256 hash value
Returns Promise<ZkpStatus>.
client.verifyBatch(options)
Verify up to eight hashes per request.
contentHashes– Array of hashes (string[], max8)context?– Optional verification context:verifierId(required whencontextis provided)platform?metadata?(Record<string, unknown>)
includeZkpProof?– Return proof artifacts
Returns Promise<VerifyBatchResponse>.
client.retryBlockchain(options)
Retry pending blockchain registrations.
limit?– Maximum hashes to retry (default 50, max100)
Returns Promise<RetryBlockchainResponse>.
client.getBlockchainTokenStatus(options)
Inspect blockchain token health.
chainId?– Optional blockchain identifier
Returns Promise<BlockchainTokenStatusResponse>.
Error Handling
All API failures surface as H3TagApiError instances with sanitized payloads.
import { H3TagApiError } from '@h3tag/sdk';
try {
await client.generateHash({ content: 'test' });
} catch (error) {
if (error instanceof H3TagApiError) {
console.error('API Error:', error.message);
console.error('Status Code:', error.status);
console.error('Request ID:', error.requestId);
if (error.rateLimit) {
console.error('Rate limit:', error.rateLimit);
}
} else {
console.error('Unexpected error:', error);
}
}Browser Usage
The SDK works in browser environments when using JWT access tokens (never use API keys in browser code). For browser applications, you can generate exact hashes using the hashContent utility:
import { createH3TagClient, hashContent } from '@h3tag/sdk';
const client = createH3TagClient({ accessToken: userToken }); // Use JWT in browser
// Generate exact hash from file content
async function handleFileUpload(file: File) {
const fileBuffer = await file.arrayBuffer();
const contentHash = hashContent(fileBuffer);
// Register with H3Tag
const result = await client.generateHash({
contentHash,
metadata: {
contentType: file.type,
filename: file.name,
contentSize: file.size,
},
});
return result;
}Perceptual Hashes (Optional)
For image duplicate detection, you can optionally provide perceptual hashes in the contentHashes field. The SDK does not provide perceptual hash generation utilities - you'll need to implement your own or use a third-party library. If you provide perceptual hashes, they should follow this format:
const result = await client.generateHash({
contentHash: exactHash, // Required: double SHA-256 hash
contentHashes: {
exact: exactHash, // 64 hex chars
perceptual: perceptualHash, // 64 hex chars (double SHA-256 of perceptual hash)
perceptual_raw: perceptualRawBytes, // 16 hex chars (raw perceptual hash bytes)
normalized: normalizedHash, // 64 hex chars (for text normalization)
metadata: metadataHash, // 64 hex chars (for metadata-based matching)
},
});Note: Perceptual hashes are optional. If you don't provide them, the SDK will only perform exact hash duplicate detection.
Security
API Key Hygiene
- Never embed API keys in browser bundles
- Store keys in environment variables or secrets managers
- Rotate and scope keys regularly
- Keep keys out of logs, stack traces, and source control
Browser Access Patterns
If you need to call H3Tag from the browser, prefer:
- Backend Proxy (recommended): Frontend → Your Backend → H3Tag API
- Ephemeral Tokens: Exchange short-lived tokens (
< 60s) from your backend - JWT Access Tokens: Use tokens aligned with your existing auth system
The SDK detects browser environments and warns when an API key is used.
Safe Logging
The SDK masks secrets in all error messages, stack traces, and JSON payloads.
Utilities
hashContent(input)
Computes a double SHA-256 hash locally. This prevents length extension attacks by hashing the content twice.
import { hashContent } from '@h3tag/sdk';
const hash = hashContent('Hello, world!');
// → Double SHA-256 hash (64 hex characters)isValidHash(hash)
Validates H3Tag-compatible hashes.
import { isValidHash } from '@h3tag/sdk';
isValidHash('a'.repeat(64)); // true
isValidHash('abc123'); // falseTypeScript Support
Strict TypeScript typings ship with the package. Import what you need:
import type {
GenerateHashOptions,
GenerateHashResponse,
H3TagApiError,
H3TagClientConfig,
HashInfo,
VerifyHashOptions,
VerifyHashResponse,
ZkpStatus,
} from '@h3tag/sdk';Additional Examples
Working with Files
import { createH3TagClient, hashContent } from '@h3tag/sdk';
import { readFileSync } from 'fs';
const client = createH3TagClient({ apiKey: process.env.H3TAG_API_KEY });
const fileContent = readFileSync('document.pdf');
const contentHash = hashContent(fileContent);
const result = await client.generateHash({
contentHash,
metadata: {
contentType: 'application/pdf',
filename: 'document.pdf',
contentSize: fileContent.length,
},
});
console.log('File hash:', result.hash);Custom Base URL
Point the client at your own proxy or environment-specific endpoint (replace api.example.com with your infrastructure hostname):
const client = createH3TagClient({
apiKey: process.env.H3TAG_API_KEY,
baseUrl: 'https://api.example.com',
});Custom Fetch Implementation
import fetch from 'node-fetch';
const client = createH3TagClient({
apiKey: process.env.H3TAG_API_KEY,
fetchImpl: fetch,
});Contributing
We welcome feedback and bug reports! Please use the following channels:
- Report bugs or issues: Submit a support ticket
- Request features: Submit a support ticket (mention "Feature Request" in your message)
- Documentation: Full Documentation
Support
Need help? We're here for you:
- Support Form: Submit a support ticket
- Documentation: Full Documentation
- Website: h3tag.com/docs/api
License
Proprietary License - See LICENSE file for full terms.
Copyright (c) 2025 H3Tag. All rights reserved.
Made by the Damilare Olaleye
