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

authtara-sdk

v1.1.15

Published

SDK Client untuk integrasi dengan DigitalSolution Platform - SSO, Billing, dan Metering

Readme

authtara-sdk

SDK Client untuk integrasi dengan DigitalSolution Platform - SSO Authentication, Billing/Entitlement Check, dan Usage Metering untuk aplikasi external.

npm version CI License: MIT

🚀 Features

  • 🔐 SSO Authentication - Offline JWT verification dengan HS256 + App Secret
  • 💳 Billing & Entitlement - Check tenant access rights dan feature availability
  • 📊 Usage Metering - Track usage untuk usage-based billing
  • 🎯 Type-Safe - Full TypeScript support dengan comprehensive types
  • ⚡ Modern - Built dengan ES Modules, CommonJS, dan TypeScript definitions
  • 🧪 Tested - Comprehensive unit tests dengan 80%+ coverage

📦 Installation

# Menggunakan Bun (recommended)
bun add authtara-sdk

# Menggunakan npm
npm install authtara-sdk

# Menggunakan yarn
yarn add authtara-sdk

🔧 Quick Start

1. Initialize SDK

import { Authtara } from "authtara-sdk";

const ds = new Authtara({
  apiKey: process.env.DS_APP_SECRET!, // Get from Developer Dashboard
  endpoint: "https://api.digitalsolution.com", // Optional, defaults to production
});

2. Verify SSO Token (Offline)

// Di callback endpoint setelah SSO
const code = searchParams.get("code");
const result = await ds.auth.exchangeCode(code!);

// Simpan token ke session
session.set("ds_token", result.token);

// Verify token (offline, no network call)
const session = await ds.auth.verifySession(result.token);

console.log("User:", session.user);
console.log("Tenant:", session.tenant);
console.log("Plan:", session.subscription.plan);

3. Check Entitlement

// Basic access check
const access = await ds.billing.checkEntitlement({
  tenantId: session.tenant!.id,
});

if (!access.granted) {
  return redirect("/upgrade", { reason: access.reason });
}

// Feature-specific check
const canUseAI = await ds.billing.checkEntitlement({
  tenantId: session.tenant!.id,
  featureKey: "ai_generator",
});

if (!canUseAI.granted) {
  throw new Error("AI feature not available in your plan");
}

4. Record Usage

// Record API call
await ds.metering.recordUsage({
  tenantId: session.tenant!.id,
  metricSlug: "api_call",
  amount: 1,
});

// Batch recording
await ds.metering.recordUsage({
  tenantId: session.tenant!.id,
  metricSlug: "message_sent",
  amount: 50,
});

📚 API Reference

Authtara Constructor

new Authtara(config: AuthtaraConfig)

Config Options:

| Option | Type | Required | Default | Description | | ---------- | -------- | -------- | --------------------------------- | ----------------------------------- | | apiKey | string | ✅ Yes | - | App Secret dari Developer Dashboard | | endpoint | string | No | https://api.digitalsolution.com | Base URL Platform API | | timeout | number | No | 30000 | Request timeout dalam milliseconds |

Auth Module

auth.verifySession(token: string)

Verify JWT token secara offline menggunakan App Secret.

Returns: Promise<SessionVerifyResult>

interface SessionVerifyResult {
  isValid: boolean;
  user?: {
    id: string;
    email: string;
    name: string | null;
  };
  tenant?: {
    id: string;
    name: string;
    subdomain: string;
    role: string;
  };
  subscription?: {
    plan: string;
    status: string;
  };
}

Throws:

  • InvalidTokenError - Token invalid atau expired

auth.exchangeCode(code: string)

Exchange authorization code untuk JWT token (server-to-server).

Returns: Promise<ExchangeResult>

interface ExchangeResult {
  token: string;
  expiresIn: number;
  user: { id: string; email: string; name: string | null };
  tenant: { id: string; name: string; subdomain: string; role: string };
  subscription: { plan: string; status: string };
}

Throws:

  • ConfigurationError - Code tidak disediakan
  • ApiError - Network atau API error

Billing Module

billing.checkEntitlement(params: CheckEntitlementParams)

Check apakah tenant memiliki akses ke aplikasi atau fitur spesifik.

Params:

interface CheckEntitlementParams {
  tenantId: string; // Required
  featureKey?: string; // Optional: untuk cek fitur spesifik
}

Returns: Promise<EntitlementResult>

interface EntitlementResult {
  granted: boolean;
  reason?: string;
  entitlement?: {
    status: string;
    subscription?: {
      plan: string;
      status: string;
    };
  };
}

Metering Module

metering.recordUsage(params: RecordUsageParams)

Catat penggunaan untuk usage-based billing.

Params:

interface RecordUsageParams {
  tenantId: string;
  metricSlug: string; // e.g., 'api_call', 'message_sent'
  amount: number; // Harus positif
  timestamp?: string; // Optional ISO timestamp
}

Available Metrics:

  • message_sent - Pesan yang dikirim (agregasi bulanan)
  • api_call - API calls (agregasi harian)
  • connection_active - Koneksi aktif (agregasi harian)
  • websocket_connection - WebSocket connections (agregasi harian)

Returns: Promise<RecordUsageResult>

interface RecordUsageResult {
  success: boolean;
  recordId?: string;
}

🔒 Error Handling

SDK menyediakan custom error classes untuk memudahkan error handling:

import { AuthtaraError, InvalidTokenError, EntitlementDeniedError, ApiError, ConfigurationError } from "authtara-sdk";

try {
  const session = await ds.auth.verifySession(token);
} catch (error) {
  if (error instanceof InvalidTokenError) {
    // Token invalid atau expired - redirect ke login
    return redirect("/login");
  }

  if (error instanceof ApiError) {
    console.error("API Error:", error.statusCode, error.message);
  }

  if (error instanceof ConfigurationError) {
    console.error("Configuration Error:", error.message);
  }
}

Error Hierarchy:

  • AuthtaraError (base class)
    • InvalidTokenError - Token validation errors
    • EntitlementDeniedError - Access denied errors
    • ApiError - API communication errors
    • ConfigurationError - SDK misconfiguration

🛠️ Advanced Usage

Custom Timeout

const ds = new Authtara({
  apiKey: process.env.DS_APP_SECRET!,
  timeout: 10000, // 10 seconds
});

Environment Variables

Recommended .env setup:

DS_APP_SECRET=your_app_secret_here
DS_API_URL=https://api.digitalsolution.com

TypeScript Configuration

SDK mendukung TypeScript dengan strict mode. Pastikan tsconfig.json Anda memiliki:

{
  "compilerOptions": {
    "moduleResolution": "bundler",
    "esModuleInterop": true
  }
}

🧪 Testing

Untuk testing aplikasi Anda dengan SDK:

import { vi } from "vitest";

// Mock Authtara SDK
vi.mock("authtara-sdk", () => ({
  Authtara: vi.fn().mockImplementation(() => ({
    auth: {
      verifySession: vi.fn().mockResolvedValue({
        isValid: true,
        user: { id: "1", email: "[email protected]", name: "Test" },
        tenant: { id: "1", name: "Test Tenant", subdomain: "test", role: "OWNER" },
      }),
    },
  })),
}));

📖 Integration Examples

Next.js App Router

// app/api/sso/callback/route.ts
import { Authtara } from "authtara-sdk";

const ds = new Authtara({
  apiKey: process.env.DS_APP_SECRET!,
});

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const code = searchParams.get("code");

  if (!code) {
    return Response.json({ error: "Missing code" }, { status: 400 });
  }

  const result = await ds.auth.exchangeCode(code);

  // Set session cookie
  // ... your session logic

  return Response.redirect("/dashboard");
}

Express.js

import express from "express";
import { Authtara } from "authtara-sdk";

const app = express();
const ds = new Authtara({
  apiKey: process.env.DS_APP_SECRET!,
});

app.get("/api/sso/callback", async (req, res) => {
  const { code } = req.query;
  const result = await ds.auth.exchangeCode(code as string);

  req.session.token = result.token;
  res.redirect("/dashboard");
});

app.use(async (req, res, next) => {
  if (!req.session.token) return next();

  try {
    const session = await ds.auth.verifySession(req.session.token);
    req.user = session.user;
    req.tenant = session.tenant;
    next();
  } catch (error) {
    req.session.destroy();
    res.redirect("/login");
  }
});

🔄 Migration Guide

From v0.x to v1.x

Tidak ada breaking changes - v1.0.0 adalah initial stable release.

📝 Changelog

See CHANGELOG.md for release history.

🤝 Contributing

SDK ini di-maintain oleh DigitalSolution Team. Untuk bug reports atau feature requests:

  1. Check existing GitHub Issues
  2. Create new issue dengan detail yang lengkap
  3. Atau hubungi support di [email protected]

📄 License

MIT License - see LICENSE file for details.

🔗 Links

  • NPM Package: https://www.npmjs.com/package/authtara-sdk
  • GitHub Repository: https://github.com/digitalsolution/authtara-sdk
  • Documentation: https://docs.digitalsolution.com/sdk
  • Developer Dashboard: https://digitalsolution.com/dashboard/developer

Built with ❤️ by DigitalSolution Team