npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@qidcloud/sdk

v1.5.0

Published

The official JavaScript/TypeScript SDK for QidCloud Identity and Enclave Services.

Readme

@qidcloud/sdk (v1.5.0 - Production Readiness)

The official JavaScript/TypeScript SDK for QidCloud — Building Enclave-Native, Zero-Knowledge applications with Identity Sovereignty.


🛠️ What's Fixed & Modernized in v1.5.0 (Infrastructure Stabilization)

  • Edge Computing Modernization: Fully replaced deprecated Node.js 20.x with Node.js 22.x and Python 3.12. Added support for 15+ modern runtimes including Java 21, .NET 8, and AL2023.
  • Edge Deployment Lifecycle: Resolved a critical ReferenceError in the deployment worker and fixed the identity persistence bug where lambdaArn was lost during function updates.
  • Resource Guardrails: Standardized default edge execution timeout to 3 seconds to encourage performant, cost-effective serverless code.
  • Platform-wide INR (₹) Support: Updated all billing telemetry, transaction history, and documentation to prioritize Indian Rupee (₹) for local developers.
  • Session Stability: Relaxed the strict User-Agent pinning to allow browser/device updates while maintaining robust IP-based hardening for enclave sessions.

🚀 What's New in v1.4.8 (Standardized Governance)

  • Automated API Governance: All headers (api-key, tenant-id, identity-scope) are now injected automatically via global Axios interceptors. NO manual header injection required.
  • Unified Method Signatures: Standardized parameter ordering across all 11 service modules (Auth, Vault, Db, Edge, etc.). Consistent (requiredData, optionalUserToken) pattern.
  • Improved Error Handlers: Standardized QidError (extending native Error) now includes status codes, error codes, and rich metadata for all failures.
  • Vault Fixes: Resolved critical binary multipart boundary generation issues for large file uploads.
  • Logs & Observability: Programmatic access to audit, security, and application logs.

🚀 What's New in v1.4.5 (Compliance & Governance)

  • Regulatory Compliance Modules: Full support for HIPAA, SOC 2, and GDPR/DPA activation. Projects can now enforce strict infrastructure guarantees.
  • Automated Agreement Signing: Integrated BAA (for HIPAA) and DPA (for GDPR) execution logic. Activating these modules programmatically binds the project infrastructure to regulatory requirements.
  • Professional Security Branding: Replaced speculative terminology with standardized cryptographic and enclave security naming across all SDK components.
  • Optimized Resource Quotas: Updated default plan quotas for more predictable enterprise scaling and cost governance.

Installation

npm install @qidcloud/sdk

📖 End-to-End Developer Guide

Looking for a pin-to-pin tutorial on how to build a full application from scratch? Check out the End-to-End Developer Guide for a walkthrough spanning Authentication, Database, File Storage, Edge Functions, and Billing.

🚀 Showcase (Demo Project)

Check out CrinzPing, a social media demo app built entirely with this SDK.

  • Location: DemoProjects/CrinzPing
  • Features: Secure Auth handshakes, background chunked uploads, and isolated enclave database queries.

🚀 Quick Start (v1.4.4+)

import { QidCloud } from '@qidcloud/sdk';

const qid = new QidCloud({
  apiKey: 'your-api-key',       // From QidCloud Console → Project → Settings
  tenantId: 'your-tenant-id',   // From QidCloud Console → Project → Overview
  baseUrl: 'https://api.qidcloud.com' // Optional, defaults to production
});

Constructor — QidConfig

| Param | Type | Required | Default | Description | |-------|------|----------|---------|-------------| | apiKey | string | ✅ | — | Your project's API key. Found in QidCloud Console → Project → Settings. | | tenantId | string | ❌ | — | Your project's Tenant ID. Required for all data operations (DB, Edge, Vault). Found in Console → Project → Overview. | | baseUrl | string | ❌ | https://api.qidcloud.com | API server URL. Use http://localhost:5000 for local development. |

Environment Variables (Vite / React)

VITE_QID_API_KEY=your-api-key
VITE_QID_TENANT_ID=your-tenant-id
VITE_QID_BASE_URL=http://localhost:5000
const qid = new QidCloud({
  apiKey: import.meta.env.VITE_QID_API_KEY,
  tenantId: import.meta.env.VITE_QID_TENANT_ID,
  baseUrl: import.meta.env.VITE_QID_BASE_URL,
});

Modules

After initialization, the SDK exposes the following modules on the qid instance:

| Module | Accessor | Purpose | |--------|----------|---------| | Authentication | qid.auth | Login, sessions, MFA, account recovery | | Database | qid.db | SQL queries, schema setup, migrations | | Edge Computing | qid.edge | Deploy & invoke serverless functions | | Secure Vault | qid.vault | Encrypted file storage with recycle bin | | Billing | qid.billing | Plans, transactions, usage analytics | | Projects | qid.projects | Create projects, manage members, service keys | | Resources | qid.resources | Provision databases, storage, edge runtimes | | Logs | qid.logs | Write & retrieve application logs | | SDK Config | qid.sdk | Manage allowed origins for CORS | | Compliance | qid.projects | Manage HIPAA, SOC 2, and GDPR modules |


⚖️ Regulatory & Compliance

QidCloud provides automated infrastructure hardening for projects governed by strict regulatory frameworks. These modules are available for Elite and Enterprise projects.

updateCompliance(tenantId, modules, userToken)

Activate or deactivate regulatory modules. Activating a module triggers infrastructure guarantees (e.g., encryption at rest, data residency locks).

| Module | Purpose | Infrastructure Impact | |--------|---------|-----------------------| | hipaa | Healthcare Compliance | BAA signed, PHI isolation enabled, log encryption enforced. | | soc2 | Operational Security | Audit-ready logs enabled, access control review exports active. | | gdpr | Data Sovereignty | DPA signed, 100% regional data residency lock (Sovereign Pin). |

// Activate HIPAA and GDPR compliance for an Elite project
await qid.projects.updateCompliance('my-tenant-id', {
  hipaa: true,
  gdpr: true,
  soc2: false
}, adminToken);

Note: Activating these modules requires an active Elite or Enterprise subscription. For GDPR, note that once data residency is locked to a region, it cannot be migrated outside of that region's jurisdiction.


🔐 Authentication (qid.auth)

QidCloud supports Advanced Cryptographic authentication via QR scanning, as well as traditional username/password login.

createSession()

Create a new handshake session. Returns a QR code payload for the mobile app to scan.

const session = await qid.auth.createSession();
// session.sessionId  → unique session identifier
// session.qrData     → stringified QR code data for the mobile app
// session.expiresAt  → expiry timestamp (ms since epoch)

Returns: QidAuthSession


listen(sessionId, onAuthorized, onDenied?)

Listen for mobile app authorization on a specific session via WebSocket.

| Param | Type | Required | Description | |-------|------|----------|-------------| | sessionId | string | ✅ | The session ID from createSession() | | onAuthorized | (token: string) => void | ✅ | Called when the user authorizes. Receives a JWT session token. | | onDenied | (msg: string) => void | ❌ | Called if the user denies or the session expires. |

qid.auth.listen(
  session.sessionId,
  (token) => console.log('Logged in! Token:', token),
  (err) => console.error('Denied:', err)
);

login(credentials)

Traditional login with username/email and password.

| Param | Type | Required | Description | |-------|------|----------|-------------| | credentials.username | string | ❌ | Login username (either username or email required) | | credentials.email | string | ❌ | Login email | | credentials.password | string | ✅ | Account password |

const { token, user } = await qid.auth.login({
  username: 'jdoe',
  password: 'my-secure-password'
});

Returns: { token: string; user: QidUser }


register(data)

Register a new user identity.

| Param | Type | Required | Description | |-------|------|----------|-------------| | data.username | string | ✅ | Desired username | | data.email | string | ✅ | User email address | | data.password | string | ✅ | Password | | data.fullName | string | ❌ | Full display name |

const result = await qid.auth.register({
  username: 'jdoe',
  email: '[email protected]',
  password: 'secure-password',
  fullName: 'John Doe'
});
// result.success → true
// result.message → 'Registration successful'

Returns: { success: boolean; message: string }


initiateRegistration(email)

Initiate an OTP-based registration flow.

| Param | Type | Required | Description | |-------|------|----------|-------------| | email | string | ✅ | Email to send OTP to |

Returns: { success: boolean; message: string }


verify(data)

Verify an OTP or mobile verification code.

| Param | Type | Required | Description | |-------|------|----------|-------------| | data.email | string | ❌ | Email for OTP verification | | data.otp | string | ❌ | The OTP code | | data.token | string | ❌ | Verification token (for mobile flows) |

Returns: { success: boolean; token?: string }


getProfile(token)

Fetch the current user's profile using their session token.

| Param | Type | Required | Description | |-------|------|----------|-------------| | token | string | ✅ | JWT session token from login or listen() |

const user = await qid.auth.getProfile(token);
// user.username → 'jdoe'
// user.email    → '[email protected]'

Returns: QidUser


getSamlLoginUrl(tenantId)

Generate the SSO login URL for an enterprise project. Redirect your users to this URL to initiate authentication via SAML.

| Param | Type | Required | Description | |-------|------|----------|-------------| | tenantId | string | ✅ | The Project's Tenant ID |

const ssoUrl = qid.auth.getSamlLoginUrl('my-org-tenant');
window.location.href = ssoUrl;

Returns: string (SSO Endpoint URL)


logout(token)

Terminate the active session on the server and disconnect WebSocket.

| Param | Type | Required | Description | |-------|------|----------|-------------| | token | string | ✅ | JWT session token |

await qid.auth.logout(token);

disconnect()

Stop listening on the WebSocket and disconnect. Does not invalidate the session server-side.

qid.auth.disconnect();

refreshSession(token)

Refresh/extend the current JWT session.

| Param | Type | Required | Description | |-------|------|----------|-------------| | token | string | ✅ | Current JWT session token |

const { token: newToken } = await qid.auth.refreshSession(token);

Returns: { token: string }


getSessions(token)

List all active sessions (devices) for the current user.

| Param | Type | Required | Description | |-------|------|----------|-------------| | token | string | ✅ | JWT session token |

const sessions = await qid.auth.getSessions(token);
// sessions[0].token, sessions[0].lastActive, sessions[0].ip, sessions[0].userAgent

Returns: QidSession[]


revokeSession(token, sessionToken)

Revoke (force-logout) a specific session.

| Param | Type | Required | Description | |-------|------|----------|-------------| | token | string | ✅ | Your current JWT session token | | sessionToken | string | ✅ | The session token to revoke (from getSessions()) |

await qid.auth.revokeSession(myToken, 'target-session-token');

Returns: { success: boolean }


requestPasswordReset(email)

Send a password reset OTP to the user's email.

| Param | Type | Required | Description | |-------|------|----------|-------------| | email | string | ✅ | Registered email address |

Returns: { success: boolean; message: string }


confirmPasswordReset(data)

Confirm a password reset using the OTP.

| Param | Type | Required | Description | |-------|------|----------|-------------| | data.email | string | ✅ | Registered email | | data.otp | string | ✅ | OTP from email | | data.newPassword | string | ✅ | New password |

Returns: { success: boolean; message: string }


changePassword(token, data)

Change password for the currently logged-in user.

| Param | Type | Required | Description | |-------|------|----------|-------------| | token | string | ✅ | JWT session token | | data.currentPassword | string | ✅ | Current password | | data.newPassword | string | ✅ | New password |

Returns: { success: boolean }


deleteAccount(token)

Permanently delete the user's account.

| Param | Type | Required | Description | |-------|------|----------|-------------| | token | string | ✅ | JWT session token |

Returns: { success: boolean }


toggleMFA(token, data)

Enable or disable Multi-Factor Authentication.

| Param | Type | Required | Description | |-------|------|----------|-------------| | token | string | ✅ | JWT session token | | data.enabled | boolean | ✅ | true to enable, false to disable | | data.type | 'email' \| 'totp' \| 'mobile' | ✅ | MFA method |

await qid.auth.toggleMFA(token, { enabled: true, type: 'email' });

Returns: { success: boolean; message: string }


verifyMFA(token, otp)

Verify an MFA toggle request with the OTP sent to the user.

| Param | Type | Required | Description | |-------|------|----------|-------------| | token | string | ✅ | JWT session token | | otp | string | ✅ | OTP code |

Returns: { success: boolean }


initiateRecovery(email)

Initiate account recovery (password reset).

| Param | Type | Required | Description | |-------|------|----------|-------------| | email | string | ✅ | Registered email |

Returns: { success: boolean; message: string }


verifyRecovery(data)

Complete recovery with OTP and set a new password.

| Param | Type | Required | Description | |-------|------|----------|-------------| | data.email | string | ✅ | Registered email | | data.otp | string | ✅ | OTP from recovery email | | data.newPassword | string | ✅ | New password |

Returns: { success: boolean; token: string }


exportUserData(token)

Export all user data (GDPR compliance).

| Param | Type | Required | Description | |-------|------|----------|-------------| | token | string | ✅ | JWT session token |

const data = await qid.auth.exportUserData(token);

Returns: Full user data export object.


🗄️ Database (qid.db)

Execute SQL queries against your project's isolated PostgreSQL enclave.

query(sql, params?, userToken?)

Execute a parameterized SQL query.

| Param | Type | Required | Default | Description | |-------|------|----------|---------|-------------| | sql | string | ✅ | — | SQL query string. Supports $1, $2 placeholders. | | params | any[] | ❌ | [] | Parameterized values (prevents SQL injection) | | userToken | string | ❌ | — | JWT session token for user-scoped access |

// SELECT
const posts = await qid.db.query('SELECT * FROM posts WHERE user_id = $1', [userId]);
// posts.success → true
// posts.data    → [{ id: '...', title: '...' }, ...]
// posts.count   → number of rows

// INSERT
await qid.db.query(
  'INSERT INTO posts (title, body) VALUES ($1, $2)',
  ['Hello World', 'My first post']
);

// CREATE TABLE
await qid.db.query(`
  CREATE TABLE IF NOT EXISTS users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    email VARCHAR(255) UNIQUE NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  )
`);

Returns: QidDbResponse<T>


setup(userToken?)

Initialize the project's enclave database schema. Useful for first-time project setup — creates the isolated schema for your tenant.

| Param | Type | Required | Description | |-------|------|----------|-------------| | userToken | string | ❌ | JWT session token |

const { success, schemaName } = await qid.db.setup();

Returns: { success: boolean; schemaName: string }


migrate(migrations, userToken?)

Run versioned migrations (Django-inspired). Only applies migrations that haven't been run yet. Tracks applied migrations in a _qid_migrations table that is automatically created.

| Param | Type | Required | Description | |-------|------|----------|-------------| | migrations | QidMigration[] | ✅ | Ordered array of versioned migrations | | userToken | string | ❌ | JWT session token |

How it works:

  1. Creates _qid_migrations tracking table if it doesn't exist
  2. Queries already-applied migrations
  3. Runs only new migrations in order
  4. Records each successful migration in the tracking table
  5. Stops on first failure (like Django)
import { QidMigration } from '@qidcloud/sdk';

const migrations: QidMigration[] = [
  {
    version: '001',
    name: 'create_users_table',
    up: async () => {
      await qid.db.query(`
        CREATE TABLE IF NOT EXISTS users (
          id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
          email VARCHAR(255) UNIQUE NOT NULL,
          name VARCHAR(255),
          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
      `);
    }
  },
  {
    version: '002',
    name: 'add_avatar_column',
    up: async () => {
      await qid.db.query(`ALTER TABLE users ADD COLUMN IF NOT EXISTS avatar_url TEXT`);
    }
  },
  {
    version: '003',
    name: 'create_posts_table',
    up: async () => {
      await qid.db.query(`
        CREATE TABLE IF NOT EXISTS posts (
          id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
          user_id UUID REFERENCES users(id),
          title TEXT NOT NULL,
          body TEXT,
          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
      `);
    }
  }
];

// Run on app startup — safe to call every time
const result = await qid.db.migrate(migrations);

if (result.success) {
  console.log(`Applied: ${result.applied.length}, Skipped: ${result.skipped.length}`);
} else {
  console.error(`Migration ${result.failed?.version} failed:`, result.failed?.error);
}

Returns: QidMigrateResult


migrateStatus(migrations, userToken?)

Check which migrations have been applied and which are pending — without running anything.

| Param | Type | Required | Description | |-------|------|----------|-------------| | migrations | QidMigration[] | ✅ | Your full migration list | | userToken | string | ❌ | JWT session token |

const status = await qid.db.migrateStatus(migrations);
// status.applied → ['001', '002']
// status.pending → ['003']
// status.total   → 3

Returns: { applied: string[]; pending: string[]; total: number }


⚡ Edge Computing (qid.edge)

Deploy and invoke serverless functions inside your project's enclave.

invoke(name, params?, userToken?)

Invoke a deployed edge function by name.

| Param | Type | Required | Default | Description | |-------|------|----------|---------|-------------| | name | string | ✅ | — | Function name (as deployed) | | params | any | ❌ | {} | Arguments passed to the function's event.params | | userToken | string | ❌ | — | JWT session token |

const result = await qid.edge.invoke('calculate-tax', {
  amount: 1000,
  region: 'US'
}, userToken);
// result.success     → true
// result.result      → { tax: 80, total: 1080 }
// result.computeTime → '12ms'
// result.logs        → ['Tax calculated for region US']

Returns: QidEdgeResponse


deploy(data, userToken?)

Deploy a new edge function or update an existing one.

| Param | Type | Required | Default | Description | |-------|------|----------|---------|-------------| | data.name | string | ✅ | — | Function name (lowercase, hyphens allowed) | | data.code | string | ✅ | — | JavaScript source code with exports.handler | | data.runtime | string | ❌ | — | Runtime (e.g. 'nodejs18.x'). See getRuntimes() | | data.envVars | object | ❌ | — | Environment variables for the function | | data.overwrite | boolean | ❌ | false | If true, replaces existing function with same name | | userToken | string | ❌ | — | JWT session token |

await qid.edge.deploy({
  name: 'send-welcome-email',
  code: `
    exports.handler = async (event) => {
      const { email, name } = event.params;
      return { success: true, message: 'Email sent to ' + email };
    };
  `,
  runtime: 'nodejs22.x',
  overwrite: true
}, userToken);

🛠️ Available Runtimes:

  • Node.js: nodejs22.x, nodejs18.x
  • Python: python3.12, python3.11, python3.10, python3.9
  • Java: java21, java17, java11 (Corretto)
  • .NET: dotnet8, dotnet6
  • Ruby: ruby3.3, ruby3.2
  • Custom: provided.al2023, provided.al2 (AL2023 recommended)

**Returns:** `{ success: boolean; message: string }`

---

### `list()`

List all deployed edge functions in the project.

```typescript
const functions = await qid.edge.list();

Returns: any[] — Array of function metadata objects.


delete(name, userToken?)

Delete a deployed function.

| Param | Type | Required | Description | |-------|------|----------|-------------| | name | string | ✅ | Function name to delete | | userToken | string | ❌ | JWT session token |

await qid.edge.delete('old-function', userToken);

Returns: { success: boolean }


getLogs(name, userToken?)

Get execution logs for a specific function.

| Param | Type | Required | Description | |-------|------|----------|-------------| | name | string | ✅ | Function name | | userToken | string | ❌ | JWT session token |

Returns: any[]


getProjectLogs(userToken?)

Get all edge function logs across the entire project.

Returns: any[]


getRuntimes()

List available serverless runtimes.

const runtimes = await qid.edge.getRuntimes();
// ['nodejs18.x', 'nodejs22.x', ...]

Returns: string[]


toggleLogging(enabled, userToken?)

Enable or disable centralized logging for all edge functions in the project.

| Param | Type | Required | Description | |-------|------|----------|-------------| | enabled | boolean | ✅ | true to enable, false to disable | | userToken | string | ❌ | JWT session token |

Returns: { success: boolean; loggingEnabled: boolean }


🔒 Secure Vault (qid.vault)

Encrypted file storage within your project's enclave. Supports upload, download, soft delete with recycle bin, restore, and permanent purge.

upload(file, fileName, metadata?, userToken?, options?)

Upload a file to the project's secure storage. Automatically uses chunked upload for files ≥ 10MB to support large files (up to 2GB) and progress tracking.

| Param | Type | Required | Default | Description | |-------|------|----------|---------|-------------| | file | Blob \| Buffer | ✅ | — | File data | | fileName | string | ✅ | — | File name (e.g. 'photo.jpg') | | metadata | object | ❌ | {} | Custom metadata or E2EE tags | | userToken | string | ❌ | — | JWT session token | | options | QidUploadOptions | ❌ | — | Upload options (progress tracking, chunk size) |

// Single-shot upload (< 10MB)
const result = await qid.vault.upload(fileBlob, 'secret.pdf');

// Chunked upload (Automatic for >= 10MB)
const result = await qid.vault.upload(largeVideo, 'lecture.mp4', {}, token, {
  onProgress: (p) => {
    console.log(`Progress: ${p.percent}%`);
    console.log(`Uploaded ${p.uploadedChunks} of ${p.totalChunks} chunks`);
  }
});

Returns: QidUploadResponse


getUploadStatus(uploadId, userToken?)

Query the status of an ongoing or interrupted chunked upload. Useful for implementing resumable uploads.

| Param | Type | Required | Description | |-------|------|----------|-------------| | uploadId | string | ✅ | The ID returned by the upload init phase | | userToken | string | ❌ | JWT session token |

Returns: any — Object containing status, receivedChunks, missingChunks, and progress.


resumeUpload(uploadId, file, userToken?, options?)

Resume a previously interrupted chunked upload session.

| Param | Type | Required | Description | |-------|------|----------|-------------| | uploadId | string | ✅ | Session ID to resume | | file | Blob \| Buffer | ✅ | The SAME file data used in the initial upload | | userToken | string | ❌ | JWT session token | | options | QidUploadOptions | ❌ | Upload options |

await qid.vault.resumeUpload(uploadId, file, token, {
  onProgress: (p) => console.log(`Resuming: ${p.percent}%`)
});

Returns: QidUploadResponse


list(userToken?)

List all files in the project enclave.

const files = await qid.vault.list(userToken);
// files[0].fileId, files[0].originalName, files[0].mimeType, files[0].size

Returns: QidFile[]


download(fileId, userToken?)

Download a file by its ID. Returns raw binary data.

| Param | Type | Required | Description | |-------|------|----------|-------------| | fileId | string | ✅ | File ID from upload() or list() | | userToken | string | ❌ | JWT session token |

const data = await qid.vault.download('abc-123', userToken);
const blob = new Blob([data]);
const url = URL.createObjectURL(blob);

Returns: ArrayBuffer


delete(fileId, userToken?)

Soft delete a file. Moves it to the recycle bin — can be restored later.

| Param | Type | Required | Description | |-------|------|----------|-------------| | fileId | string | ✅ | File ID | | userToken | string | ❌ | JWT session token |

Returns: { success: boolean; message: string }


listDeleted(userToken?)

List files in the recycle bin.

const deletedFiles = await qid.vault.listDeleted(userToken);

Returns: QidFile[]


restore(fileId, userToken?)

Restore a file from the recycle bin.

| Param | Type | Required | Description | |-------|------|----------|-------------| | fileId | string | ✅ | File ID of the deleted file | | userToken | string | ❌ | JWT session token |

Returns: { success: boolean; message: string }


purge(fileId, userToken?)

Permanently delete a file from the recycle bin. This action is irreversible.

| Param | Type | Required | Description | |-------|------|----------|-------------| | fileId | string | ✅ | File ID of the deleted file | | userToken | string | ❌ | JWT session token |

Returns: { success: boolean; message: string }


💳 Billing & Analytics (qid.billing)

Manage plans, transactions, usage analytics, and billing alerts.

getPlans()

Retrieve all available plans and their pricing tiers.

const plans = await qid.billing.getPlans();

Returns: Plan objects with tier details, pricing, and feature limits.


getProjectBillingInfo(userToken, tenantId)

Get detailed billing and resource usage info for a specific project.

| Param | Type | Required | Description | |-------|------|----------|-------------| | userToken | string | ✅ | JWT session token | | tenantId | string | ✅ | Project tenant ID |

const billing = await qid.billing.getProjectBillingInfo(token, tenantId);
// billing.plan             → 'pro'
// billing.estimatedMonthly → 29.99
// billing.activeEnclaves   → ['database', 'storage', 'edge']

Returns: QidBillingInfo


syncPaymentStatus(userToken, paymentId)

Sync payment status after a successful Razorpay transaction.

| Param | Type | Required | Description | |-------|------|----------|-------------| | userToken | string | ✅ | JWT session token | | paymentId | string | ✅ | Razorpay payment ID |

Returns: { success: boolean; message: string }


getTransactions(userToken)

Get transaction history for the current user.

const transactions = await qid.billing.getTransactions(token);
// transactions[0].transactionId, .amount, .date, .status, .planId

Returns: QidTransaction[]


getUsageAnalytics(userToken)

Get usage analytics and resource consumption history.

Returns: Usage analytics data.


getBillingAlerts(userToken, tenantId)

Get all billing alerts for a project.

Returns: any[]


createBillingAlert(userToken, tenantId, data)

Create a billing threshold alert.

| Param | Type | Required | Description | |-------|------|----------|-------------| | userToken | string | ✅ | JWT session token | | tenantId | string | ✅ | Project tenant ID | | data.resource | string | ✅ | Resource type (e.g. 'egress', 'storage', 'compute') | | data.threshold | number | ✅ | Alert threshold in USD |

await qid.billing.createBillingAlert(token, tenantId, {
  resource: 'egress',
  threshold: 50  // Alert at $50
});

Returns: { success: boolean }


deleteBillingAlert(userToken, alertId)

Delete a billing alert.

| Param | Type | Required | Description | |-------|------|----------|-------------| | userToken | string | ✅ | JWT session token | | alertId | string | ✅ | Alert ID from getBillingAlerts() |

Returns: { success: boolean }


getConsolidatedReport(userToken, query?)

Generate a consolidated financial report.

| Param | Type | Required | Description | |-------|------|----------|-------------| | userToken | string | ✅ | JWT session token | | query.year | number | ❌ | Filter by year (e.g. 2026) | | query.startDate | string | ❌ | Start date (ISO format) | | query.endDate | string | ❌ | End date (ISO format) |

const report = await qid.billing.getConsolidatedReport(token, { year: 2026 });

🏗️ Project Management (qid.projects)

Create and manage projects, invite team members, rotate API keys, and manage service keys.

getMyProjects(userToken)

List all projects owned by the currently authenticated user.

const projects = await qid.projects.getMyProjects(token);
// projects[0].name, .tenantId, .apiKey, .tier, .status

Returns: QidProject[]


createProject(userToken, data)

Create a new project.

| Param | Type | Required | Default | Description | |-------|------|----------|---------|-------------| | userToken | string | ✅ | — | JWT session token | | data.name | string | ✅ | — | Project name | | data.tier | string | ❌ | 'free' | Plan tier: 'free', 'pro', 'elite', 'enterprise' |

const project = await qid.projects.createProject(token, {
  name: 'My Social App',
  tier: 'pro'
});
// project.tenantId → 'abc-123'
// project.apiKey   → 'qid_...'

Returns: QidProject


updateProject(userToken, tenantId, data)

Update project details (e.g. rename).

| Param | Type | Required | Description | |-------|------|----------|-------------| | data.name | string | ✅ | New project name |

Returns: { success: boolean }


rotateApiKey(userToken, tenantId)

Rotate the API key for a project. The old key is immediately invalidated.

const { apiKey } = await qid.projects.rotateApiKey(token, tenantId);
// apiKey → new API key string

Returns: { success: boolean; apiKey: string }


getSettings(userToken, tenantId)

Get project-specific settings.

Returns: QidProjectSettings


updateSettings(userToken, tenantId, settings)

Update project settings.

| Param | Type | Required | Description | |-------|------|----------|-------------| | settings | QidProjectSettings | ✅ | Settings object |

Returns: { success: boolean }


inviteMember(userToken, tenantId, data)

Invite a new member to the project.

| Param | Type | Required | Description | |-------|------|----------|-------------| | data.email | string | ✅ | Invitee's email | | data.role | string | ✅ | Role: 'developer', 'admin', 'viewer' |

await qid.projects.inviteMember(token, tenantId, {
  email: '[email protected]',
  role: 'developer'
});

Returns: { success: boolean }


removeMember(userToken, tenantId, userId)

Remove a member from the project.

Returns: { success: boolean }


getProjectUsers(userToken, tenantId)

Get all users/members associated with a project.

Returns: any[]


getMyInvitations(userToken)

Get all pending project invitations for the current user.

Returns: any[]


handleInvitationAction(userToken, tenantId, action)

Accept or reject a project invitation.

| Param | Type | Required | Description | |-------|------|----------|-------------| | action | 'accept' \| 'reject' | ✅ | Invitation action |

Returns: { success: boolean }


updateMemberPermissions(userToken, tenantId, userId, permissions)

Update a member's permissions within a project.

Returns: { success: boolean }


updateProjectUserStatus(userToken, tenantId, regUserId, status)

Update a project user's status ('active' or 'suspended').

Returns: { success: boolean }


unlinkProjectUser(userToken, tenantId, regUserId)

Remove a user from the project's identity enclave.

Returns: { success: boolean }


generateServiceKey(userToken, tenantId, data)

Generate a service key for server-to-server authentication.

| Param | Type | Required | Description | |-------|------|----------|-------------| | data.name | string | ✅ | Key name/label | | data.permissions | object | ✅ | Permission scopes |

Returns: Service key object with the generated key.


revokeServiceKey(userToken, tenantId, keyId)

Revoke an existing service key.

Returns: { success: boolean }


wipeProjectEnclave(userToken, tenantId)

⚠️ DANGER: Permanently erases all identity data within the project enclave. This action is irreversible.

await qid.projects.wipeProjectEnclave(token, tenantId);

Returns: { success: boolean }


getProjectSecurityLogs(userToken, tenantId)

Retrieve security and audit logs for the project.

Returns: any[]


🚀 Resource Provisioning (qid.resources)

Provision and manage infrastructure resources (database, storage, edge runtime) for your project.

getStatus(userToken, tenantId)

Get the status of all provisioned resources.

const resources = await qid.resources.getStatus(token, tenantId);
// resources[0].resourceType → 'database'
// resources[0].status       → 'active'
// resources[0].endpoint     → 'db-endpoint.qidcloud.com'

Returns: QidResourceStatus[]


provision(userToken, tenantId, resourceType)

Provision a new resource for the project.

| Param | Type | Required | Description | |-------|------|----------|-------------| | resourceType | string | ✅ | 'database', 'storage', or 'edge' |

await qid.resources.provision(token, tenantId, 'database');

Returns: { success: boolean; message: string }


dissolve(userToken, tenantId, resourceType)

Dissolve (permanently delete) a provisioned resource.

| Param | Type | Required | Description | |-------|------|----------|-------------| | resourceType | string | ✅ | 'database', 'storage', or 'edge' |

Returns: { success: boolean; message: string }


📊 Observability (qid.logs)

Write and retrieve structured application logs.

write(message, source?, level?, metadata?)

Write a custom application log entry.

| Param | Type | Required | Default | Description | |-------|------|----------|---------|-------------| | message | string | ✅ | — | Log message | | source | string | ❌ | 'app' | Source label (e.g. 'auth-service', 'payment') | | level | string | ❌ | 'info' | Log level: 'info', 'warn', 'error' | | metadata | object | ❌ | {} | Structured data for searching/filtering |

await qid.logs.write('User signed up', 'auth-service', 'info', {
  userId: 'abc-123',
  method: 'email'
});

await qid.logs.write('Payment failed', 'billing', 'error', {
  orderId: 'ord-789',
  reason: 'insufficient_funds'
});

Returns: { success: boolean }


fetch(query?)

Retrieve application logs with optional filters.

| Param | Type | Required | Default | Description | |-------|------|----------|---------|-------------| | query.limit | number | ❌ | — | Max number of logs to return | | query.level | string | ❌ | — | Filter by level |

const logs = await qid.logs.fetch({ level: 'error', limit: 50 });

Returns: any[]


🌐 SDK Configuration (qid.sdk)

Manage allowed origins for CORS — control which domains can make SDK requests to your project.

getOrigins(userToken, tenantId)

List all allowed origins for the project.

const origins = await qid.sdk.getOrigins(token, tenantId);
// ['http://localhost:5173', 'https://myapp.com']

Returns: string[]


addOrigin(userToken, tenantId, domain)

Add an allowed origin.

| Param | Type | Required | Description | |-------|------|----------|-------------| | domain | string | ✅ | Origin URL (e.g. 'https://myapp.com') |

Returns: { success: boolean; message: string }


removeOrigin(userToken, tenantId, domain)

Remove an allowed origin.

| Param | Type | Required | Description | |-------|------|----------|-------------| | domain | string | ✅ | Origin URL to remove |

Returns: { success: boolean; message: string }


testOrigin(userToken, tenantId, domain)

Test if a specific origin is allowed.

| Param | Type | Required | Description | |-------|------|----------|-------------| | domain | string | ✅ | Origin URL to test |

const { allowed } = await qid.sdk.testOrigin(token, tenantId, 'https://myapp.com');

Returns: { allowed: boolean }


⚛️ React Components

The SDK ships with pre-built React components for Post-Quantum authentication.

<QidCloudLogin />

A complete, styled login modal with QR scanning.

import { QidCloudLogin } from '@qidcloud/sdk';

<QidCloudLogin
  sdk={qid}
  onSuccess={(user, token) => {
    console.log('Logged in as', user.username);
    localStorage.setItem('token', token);
  }}
  onError={(error) => console.error(error)}
  className="my-login-wrapper"
/>

| Prop | Type | Required | Description | |------|------|----------|-------------| | sdk | QidCloud | ✅ | Your initialized SDK instance | | onSuccess | (user: QidUser, token: string) => void | ✅ | Called on successful login | | onRegisterRequested | () => void | ❌ | Triggered when the user clicks 'Create Account' in conventional mode | | allowPassword | boolean | ❌ | Set to true to enable username/password login fallback | | className | string | ❌ | CSS class for the wrapper div |

Security Note: By default, this component only supports QR scanning (Mobile App Coming Soon). Enable allowPassword only if you need a transitionary login for users without the mobile app.


<QidSignInButton />

A minimal sign-in button that opens a QR modal when clicked.

import { QidSignInButton } from '@qidcloud/sdk';

<QidSignInButton
  sdk={qid}
  onSuccess={(user, token) => { /* handle login */ }}
  onError={(err) => console.error(err)}
  buttonText="Sign in with QidCloud"
  className="my-btn"
/>

| Prop | Type | Required | Default | Description | |------|------|----------|---------|-------------| | sdk | QidCloud | ✅ | — | SDK instance | | onSuccess | (user: QidUser, token: string) => void | ✅ | — | Success callback | | onError | (error: string) => void | ❌ | — | Error callback | | buttonText | string | ❌ | 'LOGIN WITH QIDCLOUD' | Button label | | className | string | ❌ | — | CSS class |


useQidAuth(sdk)

A React hook for managing the full authentication lifecycle — handshake initialization, WebSocket listeners, session persistence, and auto-restore from localStorage.

import { useQidAuth } from '@qidcloud/sdk';

function App() {
  const {
    user,           // QidUser | null
    token,          // string | null
    loading,        // boolean — fetching profile
    error,          // string | null
    session,        // QidAuthSession | null — active QR session
    initializing,   // boolean — creating handshake
    isExpired,      // boolean — QR session expired
    timeLeft,       // number — seconds until QR expires
    login,          // () => Promise<void> — start handshake
    logout,         // () => void — terminate session
    cancel,         // () => void — cancel handshake
    setAuthenticated // (user, token) => void — manual auth set
  } = useQidAuth(qid);

  if (user) return <div>Welcome, {user.username}!</div>;

  return (
    <div>
      <button onClick={login}>Login</button>
      {session && <p>Scan QR... {timeLeft}s remaining</p>}
      {isExpired && <p>Session expired. <button onClick={login}>Retry</button></p>}
      {error && <p>Error: {error}</p>}
    </div>
  );
}

| Return Field | Type | Description | |-------------|------|-------------| | user | QidUser \| null | Current authenticated user, or null | | token | string \| null | JWT session token | | loading | boolean | true while fetching user profile | | error | string \| null | Error message if login failed | | session | QidAuthSession \| null | Active QR handshake session | | initializing | boolean | true while creating handshake | | isExpired | boolean | true if QR session expired | | timeLeft | number | Seconds until QR session expires | | login() | () => Promise<void> | Start a new handshake session | | logout() | () => void | Terminate session and clear state | | cancel() | () => void | Cancel in-progress handshake | | setAuthenticated() | (user, token) => void | Manually set auth state (e.g. traditional login) |


📋 Type Reference

QidConfig

interface QidConfig {
  apiKey: string;
  tenantId?: string;
  baseUrl?: string;   // Default: 'https://api.qidcloud.com'
}

QidUser

interface QidUser {
  username: string;
  email?: string;
}

QidSession

interface QidSession {
  token: string;
  lastActive: Date;
  ip?: string;
  userAgent?: string;
}

QidAuthSession

interface QidAuthSession {
  sessionId: string;
  qrData: string;      // Stringified QR data for mobile app scanning
  expiresAt: number;    // Milliseconds since epoch
}

QidDbResponse<T = any>

interface QidDbResponse<T = any> {
  success: boolean;
  data?: T;
  error?: string;
  count?: number;
  meta?: any;
}

QidEdgeResponse

interface QidEdgeResponse {
  success: boolean;
  result: any;          // Return value from exports.handler
  computeTime: string;  // e.g. '12ms'
  logs?: string[];      // Console output from the function
}

QidFile

interface QidFile {
  fileId: string;
  originalName: string;
  mimeType: string;
  size: number;           // bytes
  createdAt: string;
  clientMetadata?: any;
}

QidUploadResponse

interface QidUploadResponse {
  success: boolean;
  message: string;
  file: {
    id: string;
    name: string;
    url: string;          // Relative URL, prefix with baseUrl to access
  };
}

QidProject

interface QidProject {
  _id: string;
  name: string;
  tenantId: string;
  apiKey: string;
  owner: string;
  tier: 'free' | 'pro' | 'elite' | 'enterprise';
  status: 'active' | 'suspended' | 'pending';
}

QidProjectSettings

interface QidProjectSettings {
  displayName?: string;
  allowedOrigins?: string[];
  enclaveConfig?: any;
}

QidResourceStatus

interface QidResourceStatus {
  resourceType: string;
  status: 'active' | 'provisioning' | 'failed' | 'dissolved';
  endpoint?: string;
  details?: any;
}

QidBillingInfo

interface QidBillingInfo {
  plan: string;
  profile: string;
  estimatedMonthly: number;
  estimatedHourly: string;
  infraValueUSD: string;
  currency: string;
  activeEnclaves: string[];
  billingNote?: string;
}

QidTransaction

interface QidTransaction {
  transactionId: string;
  amount: number;
  date: string;
  status: string;
  planId: string;
  currency?: string;
}

QidBillingAlert

interface QidBillingAlert {
  _id: string;
  resource: string;
  threshold: number;
  status: string;
}

QidMigration

interface QidMigration {
  version: string;              // Unique version identifier (e.g. '001', '002')
  name: string;                 // Human-readable name (e.g. 'create_users_table')
  up: () => Promise<void>;      // Async function that applies the migration
}

QidMigrateResult

interface QidMigrateResult {
  success: boolean;
  applied: string[];            // Versions applied this run
  skipped: string[];            // Versions already applied previously
  failed?: {
    version: string;
    error: string;
  };
  total: number;                // Total migrations in the registry
}

❌ Error Handling

All SDK methods throw on network errors. Catch them with try/catch:

try {
  const result = await qid.db.query('SELECT * FROM users');
} catch (err) {
  // Network error, 401 Unauthorized, 403 Forbidden, etc.
  console.error(err.response?.status, err.response?.data);
}

For methods that return { success, error }, check the success field:

const result = await qid.db.query('SELECT * FROM nonexistent');
if (!result.success) {
  console.error('Query failed:', result.error);
}

📄 License

ISC License — © 2026 QidCloud Enclave Security.

💸 Billing & Analytics (qid.billing)

Manage project plans, monitor usage, and handle payments.

getProjectBillingInfo(userToken?)

Get detailed plan information, status, and quotas.

const info = await qid.billing.getProjectBillingInfo(token);
// info.plan -> 'pro', info.infraValueUSD -> '150.00'

syncPaymentStatus(paymentId, userToken?)

Sync a Razorpay payment status with the QidCloud enclave.

await qid.billing.syncPaymentStatus('pay_123', token);

🏗️ Project Management (qid.projects)

Manage project lifecycle, members, and service keys.

createProject(data, userToken?)

Create a new project.

const project = await qid.projects.createProject({ name: 'My New App' }, token);

generateServiceKey(tenantId, data, userToken?)

Generate a new scoped service key for the project.

const { serviceKey } = await qid.projects.generateServiceKey(tenantId, {
  name: 'Mobile App Key',
  permissions: { 'res:db:Query': 'allow' }
}, token);

🪵 Observability & Logs (qid.logs)

Programmatic access to application and system logs.

write(message, source?, level?, metadata?, userToken?)

Write a custom application log to the project enclave.

await qid.logs.write('User signed in', 'auth-service', 'info', { userId }, token);

getAuditLogs(query?, userToken?)

Retrieve high-level audit logs for security and compliance.

const logs = await qid.logs.getAuditLogs({ limit: 50 }, token);

🛠️ Resource Provisioning (qid.resources)

Enable or disable project-level enclave resources.

provision(resourceType, userToken?)

Provision a new resource (e.g., 'database', 'storage', 'edge').

await qid.resources.provision('database', token);

dissolve(resourceType, userToken?)

Permanently dissolve a resource and its associated data.

await qid.resources.dissolve('database', token);

⚙️ SDK Setup & CORS (qid.sdk)

Manage allowed origins and security negotiation.

addOrigin(tenantId, domain, environment?, userToken?)

Whitelist a domain for SDK access (CORS).

await qid.sdk.addOrigin(tenantId, 'https://myapp.com', 'production', token);

📝 Type Definitions

QidError

All methods reject with a QidError on failure.

interface QidError extends Error {
  status?: number; // HTTP Status (e.g. 401)
  code: string;    // Qid Error Code (e.g. 'VAULT_NOT_FOUND')
  details?: any;   // Rich error context
}

📄 License

ISC License — © 2026 QidCloud Enclave Security.