Server & Mobile · Next.js & Node.js

Server Route Handlers & 2-Phase Hold SDK

For server-authoritative deduction around OpenAI, Anthropic, or Replicate calls, use CreditKitClient.withCrashProofHold. It atomically reserves credits in FIFO expiration order (ORDER BY expires_at ASC NULLS LAST), executes your model call, and settles or refunds the exact credit lots.

1. Copy Standalone lib/creditkit.ts (Zero Dependencies)

Drop this single-file TypeScript client into lib/creditkit.ts in any Next.js, Node.js, Bun, or Cloudflare Workers (nodejs_compat) project:

lib/creditkit.ts
import crypto from 'node:crypto';

export interface GateActionResult<T> {
  allowed: boolean;
  mode?: 'normal' | 'standard' | 'slow_tier';
  data?: T;
  remaining?: number;
  deducted?: number;
  holdId?: string | null;
  refundedOnCrash?: boolean;
  status?: number;
  configError?: boolean;
  error?: string;
}

function readHeader(req: any, name: string): string | undefined {
  const h = req?.headers;
  if (!h) return undefined;
  if (typeof h.get === 'function') return h.get(name) || undefined;
  const raw = h[name] ?? h[name.toLowerCase()];
  return Array.isArray(raw) ? raw[0] : raw || undefined;
}

/** Verifies X-CreditKit-Signature (t=<sec>,v1=<hmac_hex>) against the exact raw HTTP body string */
export function verifyCreditKitWebhook(
  rawBody: string,
  signatureHeader: string | null | undefined,
  secretKey: string,
  toleranceSeconds = 300
): boolean {
  const sig = String(signatureHeader || '').trim();
  const secret = String(secretKey || '').trim();
  if (!sig || !secret) return false;

  const parts: Record<string, string> = {};
  for (const segment of sig.split(',')) {
    const eqIdx = segment.indexOf('=');
    if (eqIdx > 0) parts[segment.slice(0, eqIdx).trim()] = segment.slice(eqIdx + 1).trim();
  }

  const ts = Number(parts.t);
  const v1 = parts.v1;
  if (!Number.isFinite(ts) || !v1) return false;
  if (toleranceSeconds > 0 && Math.abs(Math.floor(Date.now() / 1000) - ts) > toleranceSeconds) {
    return false;
  }

  let effectiveSecret = secret;
  try {
    const parsed = JSON.parse(rawBody);
    if (parsed && typeof parsed.livemode === 'boolean') {
      if (parsed.livemode === false && effectiveSecret.startsWith('sk_live_')) {
        effectiveSecret = effectiveSecret.replace(/^sk_live_/, 'sk_test_');
      } else if (parsed.livemode === true && effectiveSecret.startsWith('sk_test_')) {
        effectiveSecret = effectiveSecret.replace(/^sk_test_/, 'sk_live_');
      }
    }
  } catch {}

  const expected = crypto.createHmac('sha256', effectiveSecret).update(`${parts.t}.${rawBody}`).digest('hex');
  if (v1.length !== expected.length) return false;
  return crypto.timingSafeEqual(Buffer.from(v1, 'utf8'), Buffer.from(expected, 'utf8'));
}

function alignPublicKeyWithSecret(pubKey: string, apiKey: string): string {
  const cleanPub = String(pubKey || '').trim();
  if (!cleanPub || cleanPub.startsWith('sk_')) return cleanPub;
  if (apiKey.startsWith('sk_test_') && cleanPub.startsWith('pk_live_')) {
    return cleanPub.replace(/^pk_live_/, 'pk_test_');
  }
  if (apiKey.startsWith('sk_live_') && cleanPub.startsWith('pk_test_')) {
    return cleanPub.replace(/^pk_test_/, 'pk_live_');
  }
  return cleanPub;
}

export class CreditKitClient {
  private baseUrl: string;
  private apiKey: string;
  private explicitProjectKey: string;
  private projectKey: string;

  constructor(config: {
    baseUrl?: string;
    apiKey?: string;
    secretKey?: string;
    projectKey?: string;
    publicKey?: string;
  }) {
    this.baseUrl = (config.baseUrl || 'https://creditkit.dev').replace(/\/$/, '');
    this.apiKey = (config.apiKey || config.secretKey || '').trim();
    this.explicitProjectKey = alignPublicKeyWithSecret(
      (config.projectKey || config.publicKey || '').trim(),
      this.apiKey
    );
    this.projectKey = this.explicitProjectKey || this.apiKey;
  }

  /** Computes the spoof-proof HMAC stamp for data-identity-signature / mobile ?sig= */
  signUser(userIdOrEmail: string): string {
    if (!this.apiKey || !this.apiKey.startsWith('sk_')) {
      throw new Error(
        'CreditKitClient.signUser() requires CREDITKIT_SECRET_KEY (sk_test_... or sk_live_...)'
      );
    }
    return crypto
      .createHmac('sha256', this.apiKey)
      .update(String(userIdOrEmail || '').trim().toLowerCase())
      .digest('hex');
  }

  /** Verifies an outbound CreditKit webhook (X-CreditKit-Signature) against the raw HTTP body */
  verifyWebhookSignature(
    rawBody: string,
    signatureHeader: string | null | undefined,
    options?: { secretKey?: string; toleranceSeconds?: number }
  ): boolean {
    return verifyCreditKitWebhook(
      rawBody,
      signatureHeader,
      (options?.secretKey || this.apiKey).trim(),
      options?.toleranceSeconds ?? 300
    );
  }

  /** Builds a signed hosted mobile top-up sheet URL (/p/pk_...?user_id=...&sig=...) */
  getMobileTopUpUrl(
    returnUrl = 'myapp://credits-unlocked',
    options?: {
      publicKey?: string;
      visitorToken?: string;
      userId?: string;
      email?: string;
      identitySignature?: string;
    }
  ): string {
    const pubKey =
      options?.publicKey?.trim() ||
      (!this.projectKey.startsWith('sk_') ? this.projectKey : '');
    if (!pubKey || pubKey.startsWith('sk_')) {
      throw new Error(
        'CreditKitClient.getMobileTopUpUrl() requires a publicKey (pk_test_... or pk_live_...)'
      );
    }
    const qs = new URLSearchParams({ return_url: returnUrl });
    if (options?.visitorToken) qs.set('token', options.visitorToken);
    if (options?.userId) qs.set('user_id', options.userId);
    if (options?.email) qs.set('email', options.email);
    const signingSecret =
      pubKey.startsWith('pk_test_') && this.apiKey.startsWith('sk_live_')
        ? this.apiKey.replace(/^sk_live_/, 'sk_test_')
        : pubKey.startsWith('pk_live_') && this.apiKey.startsWith('sk_test_')
        ? this.apiKey.replace(/^sk_test_/, 'sk_live_')
        : this.apiKey;
    const sig =
      options?.identitySignature ||
      (signingSecret.startsWith('sk_') && (options?.userId || options?.email)
        ? crypto
            .createHmac('sha256', signingSecret)
            .update(String((options.userId || options.email)!).trim().toLowerCase())
            .digest('hex')
        : '');
    if (sig) qs.set('sig', sig);
    return `${this.baseUrl}/p/${encodeURIComponent(pubKey)}?${qs.toString()}`;
  }

  async getStatus(params?: { visitorToken?: string; fingerprint?: string }) {
    const headers: Record<string, string> = {};
    if (this.apiKey.startsWith('sk_')) headers.Authorization = `Bearer ${this.apiKey}`;
    if (params?.visitorToken) headers['X-CreditKit-Token'] = params.visitorToken;
    if (params?.fingerprint) headers['X-CreditKit-Fingerprint'] = params.fingerprint;
    const qs = new URLSearchParams();
    if (this.explicitProjectKey && !this.explicitProjectKey.startsWith('sk_')) {
      qs.set('projectKey', this.explicitProjectKey);
    } else if (!this.apiKey.startsWith('sk_') && this.projectKey) {
      qs.set('projectKey', this.projectKey);
    }
    const querySuffix = qs.toString() ? `?${qs.toString()}` : '';
    const res = await fetch(`${this.baseUrl}/api/v1/status${querySuffix}`, { headers });
    return res.json().catch(() => ({ ok: false, status: res.status }));
  }

  async identify(params: {
    userId?: string;
    email?: string;
    visitorToken?: string;
    identitySignature?: string;
  }) {
    const isSecret = this.apiKey.startsWith('sk_');
    const effectivePubKey = this.explicitProjectKey || (!isSecret ? this.apiKey : '');
    const sig =
      params.identitySignature ||
      (isSecret && (params.userId || params.email)
        ? this.signUser((params.userId || params.email)!)
        : '');
    const res = await fetch(`${this.baseUrl}/api/v1/identify`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...(isSecret ? { Authorization: `Bearer ${this.apiKey}` } : {}),
        ...(!isSecret && this.apiKey ? { 'X-CreditKit-Key': this.apiKey } : {}),
        ...(params.visitorToken ? { 'X-CreditKit-Token': params.visitorToken } : {}),
        ...(sig ? { 'X-CreditKit-Identity-Signature': sig } : {}),
      },
      body: JSON.stringify({
        ...(effectivePubKey && !effectivePubKey.startsWith('sk_') ? { projectKey: effectivePubKey } : {}),
        userId: params.userId,
        email: params.email,
        visitorToken: params.visitorToken,
        ...(sig ? { identitySignature: sig } : {}),
      }),
    });
    return res.json().catch(() => ({
      ok: false,
      merged: false,
      walletId: '',
      visitorToken: params.visitorToken || '',
      email: params.email || null,
      transferredLotsCount: 0,
      balance: 0,
    }));
  }

  async consume(options: {
    placementKey: string;
    visitorToken?: string;
    walletId?: string;
    userId?: string;
    email?: string;
    amount?: number;
    units?: number;
    idempotencyKey?: string;
  }) {
    if (!this.apiKey && !this.explicitProjectKey) {
      return {
        ok: false,
        allowed: false,
        configError: true,
        status: 401,
        error: 'MISSING_SECRET_KEY: Set CREDITKIT_SECRET_KEY (sk_test_... or sk_live_...) in .env.local',
      };
    }
    const isPublishableKey = this.apiKey.startsWith('pk_');
    if (isPublishableKey && (options.userId || options.email || options.walletId)) {
      return {
        ok: false,
        allowed: false,
        configError: true,
        status: 401,
        error: 'INVALID_SECRET_KEY: Server-side userId/email/walletId operations require CREDITKIT_SECRET_KEY (sk_test_... or sk_live_...), not a publishable key (pk_...).',
      };
    }
    const effectivePubKey = this.explicitProjectKey || (isPublishableKey ? this.apiKey : '');
    const res = await fetch(`${this.baseUrl}/api/v1/consume`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...(this.apiKey && !isPublishableKey ? { Authorization: `Bearer ${this.apiKey}` } : {}),
        ...(options.visitorToken ? { 'X-CreditKit-Token': options.visitorToken } : {}),
        ...(options.idempotencyKey ? { 'Idempotency-Key': options.idempotencyKey } : {}),
      },
      body: JSON.stringify({
        ...(effectivePubKey ? { projectKey: effectivePubKey } : {}),
        placementKey: options.placementKey,
        walletId: options.walletId,
        userId: options.userId,
        email: options.email,
        amount: options.amount,
        units: options.units ?? 1,
        idempotencyKey: options.idempotencyKey,
      }),
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok && res.status !== 402) {
      return { ...data, ok: false, allowed: false, status: res.status, configError: true };
    }
    return { ...data, status: res.status };
  }

  async withCrashProofHold<T>(
    options: {
      placementKey: string;
      req?: { headers?: any };
      visitorToken?: string;
      walletId?: string;
      userId?: string;
      email?: string;
      amount?: number;
      units?: number;
      idempotencyKey?: string;
    },
    fn: (hold: {
      holdId: string;
      deducted: number;
      remaining: number;
      mode?: 'normal' | 'standard' | 'slow_tier';
    }) => Promise<T>
  ): Promise<GateActionResult<T>> {
    if (!this.apiKey && !this.explicitProjectKey) {
      return {
        allowed: false,
        configError: true,
        status: 401,
        remaining: 0,
        error: 'MISSING_SECRET_KEY: Set CREDITKIT_SECRET_KEY (sk_test_... or sk_live_...) in .env.local',
      };
    }
    const isPublishableKey = this.apiKey.startsWith('pk_');
    if (isPublishableKey && (options.userId || options.email || options.walletId)) {
      return {
        allowed: false,
        configError: true,
        status: 401,
        remaining: 0,
        error: 'INVALID_SECRET_KEY: Server-side userId/email/walletId operations require CREDITKIT_SECRET_KEY (sk_test_... or sk_live_...), not a publishable key (pk_...).',
      };
    }
    const token = options.visitorToken || readHeader(options.req, 'x-creditkit-token');
    const fp = readHeader(options.req, 'x-creditkit-fingerprint');
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      ...(this.apiKey && !isPublishableKey ? { Authorization: `Bearer ${this.apiKey}` } : {}),
      ...(token ? { 'X-CreditKit-Token': token } : {}),
      ...(fp ? { 'X-CreditKit-Fingerprint': fp } : {}),
      ...(options.idempotencyKey ? { 'Idempotency-Key': options.idempotencyKey } : {}),
    };

    const effectivePubKey = this.explicitProjectKey || (isPublishableKey ? this.apiKey : '');
    const res = await fetch(`${this.baseUrl}/api/v1/holds`, {
      method: 'POST',
      headers,
      body: JSON.stringify({
        ...(effectivePubKey ? { projectKey: effectivePubKey } : {}),
        placementKey: options.placementKey,
        walletId: options.walletId,
        userId: options.userId,
        email: options.email,
        amount: options.amount,
        units: options.units ?? 1,
        idempotencyKey: options.idempotencyKey,
      }),
    });
    const reserve = await res.json().catch(() => ({}));
    if (!res.ok || !reserve.allowed) {
      const configError = res.status !== 402 && !res.ok;
      return {
        allowed: false,
        status: res.status,
        configError: configError || undefined,
        remaining: reserve.remaining ?? 0,
        error: configError
          ? reserve.error || reserve.code || `CREDITKIT_HTTP_${res.status}`
          : reserve.code || 'INSUFFICIENT_CREDITS',
      };
    }

    const holdId: string = reserve.holdId;
    const holdVisitorToken = token || reserve.visitorToken;
    if (holdVisitorToken) headers['X-CreditKit-Token'] = holdVisitorToken;
    try {
      const data = await fn({
        holdId,
        deducted: reserve.deducted,
        remaining: reserve.remaining,
        mode: reserve.mode,
      });
      if (holdId) {
        await fetch(`${this.baseUrl}/api/v1/holds`, {
          method: 'PUT',
          headers,
          body: JSON.stringify({ holdId, action: 'settle' }),
        });
      }
      return {
        allowed: true,
        mode: reserve.mode,
        data,
        deducted: reserve.deducted,
        remaining: reserve.remaining,
        holdId,
      };
    } catch (err: any) {
      if (holdId) {
        await fetch(`${this.baseUrl}/api/v1/holds`, {
          method: 'PUT',
          headers,
          body: JSON.stringify({
            holdId,
            action: 'refund',
            reason: err?.message || 'upstream_5xx_exception',
          }),
        });
      }
      return {
        allowed: false,
        refundedOnCrash: true,
        holdId,
        error: err?.message || 'UPSTREAM_EXECUTION_FAILED',
      };
    }
  }

  async grantCredits(params: {
    amount: number;
    walletId?: string;
    userId?: string;
    email?: string;
    visitorToken?: string;
    projectKey?: string;
    publicKey?: string;
    reason?: string;
  }) {
    if (!this.apiKey) {
      return {
        ok: false,
        configError: true,
        status: 401,
        error: 'MISSING_SECRET_KEY: Set CREDITKIT_SECRET_KEY (sk_test_... or sk_live_...) in .env.local',
      };
    }
    const explicitKey = alignPublicKeyWithSecret(
      params.projectKey || params.publicKey || this.explicitProjectKey,
      this.apiKey
    );
    const res = await fetch(`${this.baseUrl}/api/v1/growth`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${this.apiKey}`,
        ...(params.visitorToken ? { 'X-CreditKit-Token': params.visitorToken } : {}),
      },
      body: JSON.stringify({
        action: 'manual_grant',
        ...(explicitKey && !explicitKey.startsWith('sk_') ? { projectKey: explicitKey } : {}),
        targetWalletId: params.walletId,
        userId: params.userId,
        email: params.email,
        visitorToken: params.visitorToken,
        creditsAmount: params.amount,
        reason: params.reason || 'server_grant',
      }),
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) {
      return {
        ...data,
        ok: false,
        configError: true,
        status: res.status,
        error: data.error || `CREDITKIT_HTTP_${res.status}`,
      };
    }
    return { ...data, status: res.status };
  }
}

2. Wrap Your AI Route Handler

Pass your authenticated userId from your session middleware alongside req so server holds always resolve and debit the signed-in user's wallet:

app/api/generate/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { CreditKitClient } from '@/lib/creditkit';

export const credits = new CreditKitClient({
  baseUrl: process.env.CREDITKIT_URL || 'https://creditkit.dev',
  apiKey: process.env.CREDITKIT_SECRET_KEY!, // sk_test_... locally, sk_live_... in prod
});

// Replace with your own auth session helper (Clerk auth(), Supabase, Better Auth, NextAuth)
async function getSession(_req: NextRequest): Promise<{ user: { id: string; email?: string } } | null> {
  return { user: { id: 'usr_demo_123', email: 'dev@example.com' } };
}

export async function POST(req: NextRequest) {
  const session = await getSession(req);
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  const hold = await credits.withCrashProofHold(
    {
      req, // Forwards x-creditkit-token header from browser automatically
      userId: session.user.id,
      email: session.user.email,
      placementKey: 'run_action', // Costs 10 credits by default (configure in Pricing & Gates)
      units: 1,
    },
    async ({ remaining }) => {
      // Call your model, API, or compute job here.
      // If this throws a 5xx/timeout, CreditKit refunds the hold automatically!
      return { outputUrl: 'https://cdn.example.com/result.png', remaining };
    }
  );

  if (!hold.allowed) {
    return NextResponse.json(hold, {
      status: hold.configError ? 500 : hold.refundedOnCrash ? 502 : 402,
    });
  }

  return NextResponse.json(hold.data);
}