Sellers can turn on checkout tax in settings (label, own country and tax ID, legal name, per-country rates, default rate, EU reverse charge). Sessions add tax on top of the net price after any promo, so onchain verification expects the tax-inclusive total. Buyers set billing country and VAT ID via the API (billingCountry, vatId) or on the hosted checkout until a payment is recorded; EU cross-border B2B with a VAT ID of the right shape is zero-rated. Settled checkouts get a PDF receipt (pdfkit) with the seller's tax ID, buyer country / VAT ID, tax rate and the settlement transaction, linked from the success page, the receipt email and the customer portal. packages/tax calculateTax is now used at checkout. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
400 lines
16 KiB
TypeScript
400 lines
16 KiB
TypeScript
/**
|
|
* Environment-driven configuration for the SettleKit background worker.
|
|
*
|
|
* All values are read once at boot and validated. Missing required secrets fail
|
|
* fast with a precise message rather than surfacing as opaque runtime errors
|
|
* deep inside a job. Numeric intervals are bounded so a bad env var cannot turn
|
|
* a sweep into a tight CPU loop.
|
|
*/
|
|
|
|
import { isArcAddress, type ArcAddress } from "@settlekit/arc";
|
|
import {
|
|
ChainConfigError,
|
|
loadEvmChains,
|
|
loadZcashConfig,
|
|
type EvmChainsConfig,
|
|
type ZcashConfig,
|
|
} from "@settlekit/chains";
|
|
import { loadHyperCoreConfig, type HyperCoreConfig } from "@settlekit/hyperliquid";
|
|
import { loadRoutingConfig, type RoutingConfig } from "@settlekit/routing";
|
|
import {
|
|
getSolanaCluster,
|
|
isSolanaAddress,
|
|
parseSolanaCluster,
|
|
type SolanaCluster,
|
|
} from "@settlekit/solana";
|
|
|
|
/** A single recurring job's cadence, in milliseconds. */
|
|
export interface JobIntervals {
|
|
/** How often pending delivery runs are executed. */
|
|
deliveryRunnerMs: number;
|
|
/** How often pending payments are polled for on-chain confirmation. */
|
|
paymentConfirmMs: number;
|
|
/** How often GitHub/Discord access is reconciled and expired grants revoked. */
|
|
accessSyncMs: number;
|
|
/** How often subscriptions are advanced/graced/expired. */
|
|
renewalSweepMs: number;
|
|
/** How often failed webhooks are redelivered. */
|
|
webhookRetryMs: number;
|
|
/** How often confirmed payments are swept for an unsent receipt email. */
|
|
receiptEmailMs: number;
|
|
/** How often upcoming renewals are swept for a reminder email. */
|
|
renewalReminderMs: number;
|
|
/** How often grace/past-due subscriptions are swept for a dunning email. */
|
|
dunningEmailMs: number;
|
|
/** How often succeeded delivery runs are swept for an access-granted email. */
|
|
accessEmailMs: number;
|
|
/** How often executed-but-unsettled payouts are reconciled against Circle. */
|
|
payoutReconcileMs: number;
|
|
/** How often open Zcash sessions' addresses are checked for payments. */
|
|
zcashWatchMs: number;
|
|
/** How often in-flight any-token routes are polled and their fills verified. */
|
|
routeWatchMs: number;
|
|
/** How often pending GitHub entitlements from checkout are re-delivered. */
|
|
githubDeliveryRetryMs: number;
|
|
/** How often due onchain subscription periods are charged. */
|
|
subscriptionChargeMs: number;
|
|
}
|
|
|
|
/** Circle developer-controlled wallets used to reconcile executed payouts. */
|
|
export interface CircleWalletsConfig {
|
|
apiKey: string;
|
|
walletId: string;
|
|
baseUrl?: string;
|
|
entitySecretCiphertext?: string;
|
|
}
|
|
|
|
/** Arc (EVM USDC) settlement reader configuration. */
|
|
export interface ArcConfig {
|
|
rpcUrl: string;
|
|
usdcAddress: ArcAddress;
|
|
chainId: number;
|
|
/** Confirmations required before a payment is treated as settled. */
|
|
minConfirmations: number;
|
|
}
|
|
|
|
/**
|
|
* Solana USDC reader for confirming Solana payments. Optional: enabled by
|
|
* SOLANA_CLUSTER; without it Solana payments stay pending (fail closed).
|
|
*/
|
|
export interface SolanaWorkerConfig {
|
|
cluster: SolanaCluster;
|
|
rpcUrl: string;
|
|
usdcMint: string;
|
|
}
|
|
|
|
/**
|
|
* Which settlement provider the Lepton settlement jobs use to move funds.
|
|
* `local` (the default) keeps the worker's historical behavior: no live
|
|
* provider is wired, so the settlement jobs no-op. `arc` opts into the live
|
|
* Circle App Kit provider over viem (see {@link ArcSettlementConfig}).
|
|
*/
|
|
export type SettlementProviderKind = "local" | "arc";
|
|
|
|
/**
|
|
* Live Arc settlement signer configuration. Assembled only when
|
|
* `SETTLEMENT_PROVIDER=arc` and `ARC_SETTLER_PRIVATE_KEY` is present; the RPC
|
|
* url is shared with {@link ArcConfig.rpcUrl}. The private key is a secret and
|
|
* is never logged.
|
|
*/
|
|
export interface ArcSettlementConfig {
|
|
/** JSON-RPC endpoint used to submit settlement transfers (shared with arc.rpcUrl). */
|
|
rpcUrl: string;
|
|
/** 0x-prefixed settler EOA private key used to sign transfers. Never logged. */
|
|
privateKey: string;
|
|
/** Optional Circle kit key (only needed by swap; settle uses send). */
|
|
circleKitKey?: string;
|
|
}
|
|
|
|
/** Transactional email sender configuration (Resend). */
|
|
export interface EmailConfig {
|
|
apiKey: string;
|
|
from: string;
|
|
}
|
|
|
|
/** GitHub App credentials used to mint installation-scoped clients. */
|
|
export interface GithubConfig {
|
|
appId: number;
|
|
privateKey: string;
|
|
/** Default installation id the worker authenticates as for sync/automation. */
|
|
installationId: number;
|
|
/**
|
|
* True when an installation id was explicitly configured
|
|
* (GITHUB_INSTALLATION_ID or GITHUB_APP_INSTALLATION_ID). Jobs that act on
|
|
* the merchant's behalf without a per-run installation require it.
|
|
*/
|
|
installationConfigured: boolean;
|
|
}
|
|
|
|
/** Discord bot credentials used for role automation. */
|
|
export interface DiscordConfig {
|
|
/** Empty when DISCORD_BOT_TOKEN is unset: Discord roles stay "pending setup". */
|
|
botToken: string;
|
|
configured: boolean;
|
|
}
|
|
|
|
/** File-delivery signed-URL configuration. */
|
|
export interface FileDeliveryConfig {
|
|
baseUrl: string;
|
|
secret: string;
|
|
defaultExpiresInSec: number;
|
|
defaultMaxDownloads: number;
|
|
}
|
|
|
|
/** License token signing configuration. */
|
|
export interface LicenseConfig {
|
|
tokenSecret: string;
|
|
}
|
|
|
|
/** Fully-resolved worker configuration. */
|
|
export interface WorkerConfig {
|
|
intervals: JobIntervals;
|
|
arc: ArcConfig;
|
|
/** Solana payment verification; null when SOLANA_CLUSTER is unset. */
|
|
solana: SolanaWorkerConfig | null;
|
|
/**
|
|
* Enabled EVM chains (SETTLEKIT_CHAIN_ENV, ENABLED_EVM_CHAINS, per-chain
|
|
* overrides; ARC_CHAIN_ID / BASE_RPC_URL aliases). Payments on any other
|
|
* EVM chain stay pending (fail closed).
|
|
*/
|
|
evm: EvmChainsConfig;
|
|
/** Transparent Zcash verification + watching; null unless ZCASH_ENABLED. */
|
|
zcash: ZcashConfig | null;
|
|
/** HyperCore (Hyperliquid L1) USDC verification; null unless HYPERCORE_ENABLED. */
|
|
hypercore: HyperCoreConfig | null;
|
|
/** Any-token route watching (Relay / LI.FI); null unless ROUTING_ENABLED. */
|
|
routing: RoutingConfig | null;
|
|
email: EmailConfig;
|
|
github: GithubConfig;
|
|
discord: DiscordConfig;
|
|
fileDelivery: FileDeliveryConfig;
|
|
license: LicenseConfig;
|
|
/** Circle wallets for payout reconciliation; null when unconfigured. */
|
|
circleWallets: CircleWalletsConfig | null;
|
|
/**
|
|
* Selected settlement provider. Defaults to `local` (no live provider →
|
|
* settlement jobs no-op). `arc` requests the live Circle App Kit provider; the
|
|
* runtime falls back to local (with a logged warning) when {@link arcSettlement}
|
|
* could not be assembled, so a misconfigured `arc` never crashes boot.
|
|
*/
|
|
settlementProvider: SettlementProviderKind;
|
|
/**
|
|
* Live Arc settlement signer config; non-null only when
|
|
* `SETTLEMENT_PROVIDER=arc` AND `ARC_SETTLER_PRIVATE_KEY` is present. The raw
|
|
* {@link settlementProvider} selection is kept separately so the runtime can
|
|
* detect "arc requested but incomplete" and warn + fall back.
|
|
*/
|
|
arcSettlement: ArcSettlementConfig | null;
|
|
/** Default grace window (days) applied when a renewal is missed. */
|
|
graceDays: number;
|
|
/** HMAC secret used to sign outbound webhooks dispatched by delivery actions. */
|
|
webhookSigningSecret: string;
|
|
/** Send a renewal reminder when currentPeriodEnd is within this many days. */
|
|
renewalReminderDays: number;
|
|
/** Hosted checkout public URL (receipt PDF links in receipt emails); optional. */
|
|
checkoutPublicUrl?: string;
|
|
/**
|
|
* Postgres connection. When set, the worker persists to (and reads) the shared
|
|
* database; when unset it runs against a process-local in-memory store.
|
|
*/
|
|
database?: { url: string };
|
|
}
|
|
|
|
/** Raised when a required environment variable is absent or malformed. */
|
|
export class ConfigError extends Error {
|
|
constructor(message: string) {
|
|
super(message);
|
|
this.name = "ConfigError";
|
|
}
|
|
}
|
|
|
|
type Env = Record<string, string | undefined>;
|
|
|
|
function requireString(env: Env, key: string): string {
|
|
const value = env[key];
|
|
if (value === undefined || value.trim().length === 0) {
|
|
throw new ConfigError(`Missing required environment variable: ${key}`);
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function optionalString(env: Env, key: string, fallback: string): string {
|
|
const value = env[key];
|
|
return value === undefined || value.trim().length === 0 ? fallback : value;
|
|
}
|
|
|
|
function intInRange(env: Env, key: string, fallback: number, min: number, max: number): number {
|
|
const raw = env[key];
|
|
if (raw === undefined || raw.trim().length === 0) return fallback;
|
|
const parsed = Number(raw);
|
|
if (!Number.isInteger(parsed)) {
|
|
throw new ConfigError(`Environment variable ${key} must be an integer, got "${raw}"`);
|
|
}
|
|
if (parsed < min || parsed > max) {
|
|
throw new ConfigError(`Environment variable ${key} must be between ${min} and ${max}, got ${parsed}`);
|
|
}
|
|
return parsed;
|
|
}
|
|
|
|
function requireArcAddress(env: Env, key: string): ArcAddress {
|
|
const value = requireString(env, key);
|
|
if (!isArcAddress(value)) {
|
|
throw new ConfigError(`Environment variable ${key} must be a 0x-prefixed 20-byte address`);
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function loadChains(env: Env): {
|
|
evm: EvmChainsConfig;
|
|
zcash: ZcashConfig | null;
|
|
hypercore: HyperCoreConfig | null;
|
|
routing: RoutingConfig | null;
|
|
} {
|
|
try {
|
|
return {
|
|
evm: loadEvmChains(env),
|
|
zcash: loadZcashConfig(env),
|
|
hypercore: loadHyperCoreConfig(env),
|
|
routing: loadRoutingConfig(env),
|
|
};
|
|
} catch (error) {
|
|
if (error instanceof ChainConfigError) throw new ConfigError(error.message);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
function loadSolana(env: Env): SolanaWorkerConfig | null {
|
|
const clusterRaw = env.SOLANA_CLUSTER?.trim();
|
|
if (clusterRaw === undefined || clusterRaw.length === 0) return null;
|
|
const cluster = parseSolanaCluster(clusterRaw);
|
|
if (cluster === undefined) {
|
|
throw new ConfigError(`Environment variable SOLANA_CLUSTER must be mainnet or devnet, got "${clusterRaw}"`);
|
|
}
|
|
const known = getSolanaCluster(cluster);
|
|
const usdcMint = optionalString(env, "SOLANA_USDC_MINT", known.usdcMint);
|
|
if (!isSolanaAddress(usdcMint)) {
|
|
throw new ConfigError("Environment variable SOLANA_USDC_MINT must be a base58 Solana address");
|
|
}
|
|
return { cluster, rpcUrl: optionalString(env, "SOLANA_RPC_URL", known.rpcUrl), usdcMint };
|
|
}
|
|
|
|
/**
|
|
* Build {@link WorkerConfig} from a process environment. Defaults to
|
|
* `process.env` but accepts an explicit env map for tests.
|
|
*/
|
|
export function loadConfig(env: Env = process.env): WorkerConfig {
|
|
// Fail closed in production: a worker without a shared database runs on a
|
|
// process-local in-memory store, isolated from the API's Postgres — it would
|
|
// "succeed" while delivering and settling nothing durable.
|
|
const hasDatabase = Boolean(env.DATABASE_URL && env.DATABASE_URL.length > 0);
|
|
if (env.NODE_ENV === "production" && !hasDatabase) {
|
|
throw new ConfigError(
|
|
"DATABASE_URL must be set in production: an in-memory worker is isolated from the API database and processes nothing durable.",
|
|
);
|
|
}
|
|
|
|
const intervals: JobIntervals = {
|
|
deliveryRunnerMs: intInRange(env, "WORKER_DELIVERY_INTERVAL_MS", 5_000, 250, 3_600_000),
|
|
paymentConfirmMs: intInRange(env, "WORKER_PAYMENT_INTERVAL_MS", 10_000, 250, 3_600_000),
|
|
accessSyncMs: intInRange(env, "WORKER_ACCESS_SYNC_INTERVAL_MS", 300_000, 1_000, 86_400_000),
|
|
renewalSweepMs: intInRange(env, "WORKER_RENEWAL_INTERVAL_MS", 600_000, 1_000, 86_400_000),
|
|
webhookRetryMs: intInRange(env, "WORKER_WEBHOOK_RETRY_INTERVAL_MS", 30_000, 1_000, 86_400_000),
|
|
receiptEmailMs: intInRange(env, "WORKER_RECEIPT_EMAIL_INTERVAL_MS", 60_000, 1_000, 86_400_000),
|
|
renewalReminderMs: intInRange(env, "WORKER_RENEWAL_REMINDER_INTERVAL_MS", 3_600_000, 1_000, 86_400_000),
|
|
dunningEmailMs: intInRange(env, "WORKER_DUNNING_EMAIL_INTERVAL_MS", 3_600_000, 1_000, 86_400_000),
|
|
accessEmailMs: intInRange(env, "WORKER_ACCESS_EMAIL_INTERVAL_MS", 60_000, 1_000, 86_400_000),
|
|
payoutReconcileMs: intInRange(env, "WORKER_PAYOUT_RECONCILE_INTERVAL_MS", 60_000, 1_000, 86_400_000),
|
|
zcashWatchMs: intInRange(env, "WORKER_ZCASH_WATCH_INTERVAL_MS", 90_000, 30_000, 3_600_000),
|
|
routeWatchMs: intInRange(env, "WORKER_ROUTE_WATCH_INTERVAL_MS", 20_000, 5_000, 3_600_000),
|
|
githubDeliveryRetryMs: intInRange(env, "WORKER_GITHUB_RETRY_INTERVAL_MS", 120_000, 10_000, 86_400_000),
|
|
subscriptionChargeMs: intInRange(env, "WORKER_SUBSCRIPTION_CHARGE_INTERVAL_MS", 300_000, 10_000, 86_400_000),
|
|
};
|
|
|
|
const circleWallets: CircleWalletsConfig | null =
|
|
env.CIRCLE_WALLETS_API_KEY && env.CIRCLE_WALLETS_WALLET_ID
|
|
? {
|
|
apiKey: env.CIRCLE_WALLETS_API_KEY,
|
|
walletId: env.CIRCLE_WALLETS_WALLET_ID,
|
|
...(env.CIRCLE_WALLETS_BASE_URL ? { baseUrl: env.CIRCLE_WALLETS_BASE_URL } : {}),
|
|
...(env.CIRCLE_WALLETS_ENTITY_SECRET_CIPHERTEXT
|
|
? { entitySecretCiphertext: env.CIRCLE_WALLETS_ENTITY_SECRET_CIPHERTEXT }
|
|
: {}),
|
|
}
|
|
: null;
|
|
|
|
// Settlement provider selection. `local` (the default) leaves the live
|
|
// provider unwired so the Lepton settlement jobs no-op exactly as before.
|
|
// When `arc` is selected we assemble the signer config ONLY if the private
|
|
// key is present; we never throw here (loadConfig has no logger) so the
|
|
// runtime — where the Logger lives — can warn and fall back to local.
|
|
const settlementProvider: SettlementProviderKind =
|
|
optionalString(env, "SETTLEMENT_PROVIDER", "local") === "arc" ? "arc" : "local";
|
|
const arcSettlerKey = env.ARC_SETTLER_PRIVATE_KEY;
|
|
const arcSettlement: ArcSettlementConfig | null =
|
|
settlementProvider === "arc" && arcSettlerKey !== undefined && arcSettlerKey.trim().length > 0
|
|
? {
|
|
rpcUrl: requireString(env, "ARC_RPC_URL"),
|
|
privateKey: arcSettlerKey,
|
|
...(env.CIRCLE_KIT_KEY && env.CIRCLE_KIT_KEY.trim().length > 0
|
|
? { circleKitKey: env.CIRCLE_KIT_KEY }
|
|
: {}),
|
|
}
|
|
: null;
|
|
|
|
return {
|
|
intervals,
|
|
circleWallets,
|
|
settlementProvider,
|
|
arcSettlement,
|
|
arc: {
|
|
rpcUrl: requireString(env, "ARC_RPC_URL"),
|
|
usdcAddress: requireArcAddress(env, "ARC_USDC_ADDRESS"),
|
|
chainId: intInRange(env, "ARC_CHAIN_ID", 1, 1, 2_147_483_647),
|
|
minConfirmations: intInRange(env, "ARC_MIN_CONFIRMATIONS", 3, 1, 1_000),
|
|
},
|
|
solana: loadSolana(env),
|
|
...loadChains(env),
|
|
email: {
|
|
// Optional: without it, buyer emails (receipts, renewal links, dunning) are skipped and logged.
|
|
apiKey: (env.RESEND_API_KEY ?? "").trim(),
|
|
from: optionalString(env, "EMAIL_FROM", "SettleKit <receipts@settlekit.dev>"),
|
|
},
|
|
github: {
|
|
appId: intInRange(env, "GITHUB_APP_ID", 1, 1, 2_147_483_647),
|
|
// Optional: without the GitHub App, GitHub deliveries stay "pending setup".
|
|
privateKey: (env.GITHUB_APP_PRIVATE_KEY ?? "").replace(/\\n/g, "\n").trim(),
|
|
// GITHUB_APP_INSTALLATION_ID is the name the checkout app reads.
|
|
installationId: intInRange(
|
|
{ ...env, GITHUB_INSTALLATION_ID: env.GITHUB_INSTALLATION_ID ?? env.GITHUB_APP_INSTALLATION_ID },
|
|
"GITHUB_INSTALLATION_ID",
|
|
1,
|
|
1,
|
|
2_147_483_647,
|
|
),
|
|
installationConfigured:
|
|
Boolean((env.GITHUB_INSTALLATION_ID ?? env.GITHUB_APP_INSTALLATION_ID ?? "").trim()) &&
|
|
Boolean((env.GITHUB_APP_PRIVATE_KEY ?? "").trim()),
|
|
},
|
|
discord: {
|
|
botToken: (env.DISCORD_BOT_TOKEN ?? "").trim(),
|
|
configured: (env.DISCORD_BOT_TOKEN ?? "").trim().length > 0,
|
|
},
|
|
fileDelivery: {
|
|
baseUrl: requireString(env, "FILE_DELIVERY_BASE_URL"),
|
|
secret: requireString(env, "FILE_DELIVERY_SECRET"),
|
|
defaultExpiresInSec: intInRange(env, "FILE_DELIVERY_EXPIRES_SEC", 3_600, 60, 2_592_000),
|
|
defaultMaxDownloads: intInRange(env, "FILE_DELIVERY_MAX_DOWNLOADS", 5, 1, 10_000),
|
|
},
|
|
license: {
|
|
tokenSecret: requireString(env, "LICENSE_TOKEN_SECRET"),
|
|
},
|
|
graceDays: intInRange(env, "SUBSCRIPTION_GRACE_DAYS", 3, 1, 365),
|
|
webhookSigningSecret: requireString(env, "WEBHOOK_SIGNING_SECRET"),
|
|
renewalReminderDays: intInRange(env, "SUBSCRIPTION_RENEWAL_REMINDER_DAYS", 7, 1, 365),
|
|
...((env.CHECKOUT_PUBLIC_URL ?? env.NEXT_PUBLIC_CHECKOUT_URL)?.trim()
|
|
? { checkoutPublicUrl: (env.CHECKOUT_PUBLIC_URL ?? env.NEXT_PUBLIC_CHECKOUT_URL)!.trim().replace(/\/+$/, "") }
|
|
: {}),
|
|
...(env.DATABASE_URL && env.DATABASE_URL.length > 0 ? { database: { url: env.DATABASE_URL } } : {}),
|
|
};
|
|
}
|