export { c as AdminGuardOptions, d as AssertBillableBalanceOptions, A as AuthGuard, e as AuthGuardOptions, B as BetterAuthSessionCookieMinterOptions, f as BetterAuthSessionCookieSource, g as BillableBalanceState, G as GuardResolution, S as SsoStateConfig, b as TangleSsoAccountStore, a as TangleSsoAuthClient, h as TangleSsoExchangeResult, i as TangleSsoHandlerOptions, T as TangleSsoHandlers, j as TangleSsoSessionCookieArgs, k as TangleSsoUserCreateError, l as assertBillableBalance, m as createAdminGuard, n as createAuthGuard, o as createBetterAuthSessionCookieMinter, p as createSignedSsoState, q as createTangleSsoHandlers, r as guardResolution, s as parseAdminEmails, t as signSessionCookieValue, v as verifySignedSsoState } from '../sso-Cm00S61u.js';
import { a as TangleExecutionEnvironment, b as TangleExecutionKeySource } from '../model-CdCDfBA9.js';
import { PlatformIdentity, PlatformBillingClient } from '../billing/index.js';

/**
 * Integrations-hub proxy routes: the app-side surface that forwards an
 * authenticated user's requests to the platform's `/v1/integrations/*` API
 * using their stored platform key. Auth, key lookup, and the wire client are
 * structural seams (`HubProxyContext`); error detection is by name + shape so
 * it survives bundlers duplicating module instances.
 */

/** Hub bearer provenance mirrors the execution-key source union. */
type TangleHubBearerSource = TangleExecutionKeySource;
/** Represent a resolved bearer token with its associated TangleHub bearer source */
interface ResolvedTangleHubBearer {
    bearer: string;
    source: TangleHubBearerSource;
}
/** Resolve options required to obtain a user's TangleHub bearer token including environment and API key retrieval */
interface ResolveUserTangleHubBearerOptions {
    userId: string;
    /** Deployment context. Only local development may use env credentials. */
    environment?: TangleExecutionEnvironment;
    /** Env to read for the local-development bearer. */
    env?: Record<string, string | undefined>;
    /** App-owned lookup for the caller's linked platform API key. */
    getUserApiKey: () => string | null | undefined | Promise<string | null | undefined>;
}
/** Resolve options for retrieving a TangleHub bearer token for a specified user */
interface ResolveUserTangleHubBearerForUserOptions<UserId = string> {
    userId: UserId;
    environment?: TangleExecutionEnvironment;
    env?: Record<string, string | undefined>;
    getUserApiKey: (userId: UserId) => string | null | undefined | Promise<string | null | undefined>;
}
/** Represent missing Tangle platform link error for a specified user ID */
declare class TangleBearerMissingError extends Error {
    readonly userId: string;
    constructor(userId: string);
}
/**
 * Resolve the Tangle bearer used by the integration hub proxy.
 *
 * Local development may use a server env key so apps can exercise the hub
 * without completing cross-site SSO. Deployed contexts must use the caller's
 * linked platform key; this keeps integration ownership aligned with the user.
 */
declare function resolveUserTangleHubBearer(opts: ResolveUserTangleHubBearerOptions): Promise<ResolvedTangleHubBearer>;
/** Resolve the TangleHub bearer token for a specified user based on provided options */
declare function resolveUserTangleHubBearerForUser<UserId = string>(opts: ResolveUserTangleHubBearerForUserOptions<UserId>): Promise<ResolvedTangleHubBearer>;
/** Structural guard (name + userId shape) — robust when the error class is
 *  constructed in a different module instance than the one checking it. */
declare function isTangleBearerMissingError(error: unknown): error is TangleBearerMissingError;
/** Structural detection of the platform hub wire error (name + numeric status). */
declare function isPlatformHubErrorLike(error: unknown): error is Error & {
    status: number;
    code?: string;
};
/** Structural subset of the platform hub wire client — extra methods are fine. */
interface HubClientLike {
    catalog(): Promise<unknown>;
    listConnections(): Promise<unknown>;
    revokeConnection(connectionId: string): Promise<unknown>;
    startAuth(input: {
        providerId: string;
        connectorId: string;
        returnUrl: string;
        requestedScopes?: string[];
    }): Promise<{
        authorizationUrl: string;
        state: string;
    }>;
    listHealthchecks(): Promise<unknown>;
}
/** Define methods to require user ID, get bearer token, and create a hub client bound to the bearer */
interface HubProxyContext {
    /** Resolve the authenticated user id. Throw the app's own auth Response /
     *  redirect to reject — it propagates untouched. */
    requireUserId(request: Request): Promise<string>;
    /** The user's platform bearer; throw `TangleBearerMissingError` when unlinked. */
    getBearer(userId: string): Promise<string>;
    /** A hub client bound to the bearer. */
    createHubClient(bearer: string): HubClientLike;
}
/** Define arguments for configuring a proxy route with request and optional parameters */
interface HubProxyRouteArgs {
    request: Request;
    params?: Record<string, string | undefined>;
}
/** Define routes for hub proxy handling catalog, connections, healthchecks, and authorization actions */
interface HubProxyRoutes {
    /** GET → `{ catalog }`. */
    catalog(args: HubProxyRouteArgs): Promise<Response>;
    /** GET → `{ connections }`. */
    connections(args: HubProxyRouteArgs): Promise<Response>;
    /** DELETE → the platform revocation result verbatim; 405 otherwise. */
    connectionDelete(args: {
        request: Request;
        params: {
            connectionId: string;
        };
    }): Promise<Response>;
    /** GET → `{ healthchecks }`. */
    healthchecks(args: HubProxyRouteArgs): Promise<Response>;
    /** POST `{ providerId, connectorId, returnUrl, requestedScopes? }` →
     *  `{ authorizationUrl, state }`; 405 non-POST; 400 on bad JSON / missing fields. */
    authStart(args: HubProxyRouteArgs): Promise<Response>;
}
/** Resolve hub proxy routes with authentication and error handling based on the given context */
declare function createHubProxyRoutes(ctx: HubProxyContext): HubProxyRoutes;

/**
 * Platform billing HTTP transport + tier state for apps on the shared
 * Tangle balance model (id.tangle.tools). Reads authenticate as the user via
 * their per-user platform key (the platform resolves the caller from the
 * key; service or impersonation headers on read routes are rejected). The
 * deduct write authenticates as the product service (`Bearer <serviceToken>`
 * + `X-Service-Name`) and names the target user in the body. Also provides a
 * fetch-backed implementation of the `/billing` module's
 * `PlatformBillingClient` seam (type-only import — no runtime coupling).
 */

/** Define available subscription tiers for the TanglePlan service */
type TanglePlanTier = 'free' | 'pro' | 'enterprise';
/** 'pro' | 'enterprise' pass through; anything else (null, unknown) → 'free'. */
declare function normalizeTanglePlanTier(plan: string | null | undefined): TanglePlanTier;
/** Represent platform billing HTTP errors with status code and detailed message */
declare class PlatformBillingHttpError extends Error {
    readonly status: number;
    constructor(status: number, detail: string);
}
/** Structural guard (name + numeric status) — robust across module instances. */
declare function isPlatformBillingHttpError(error: unknown): error is PlatformBillingHttpError;
/** Define HTTP options for platform billing including base URL, service token, product slug, fetch implementation, and timeout */
interface PlatformBillingHttpOptions {
    /** Platform root, e.g. https://id.tangle.tools (trailing slashes stripped). */
    baseUrl: string;
    /** Used only by `deduct()`; resolved lazily so reads never require it.
     *  Throws at call time when empty. */
    serviceToken: string | (() => string);
    /** Product slug — the `X-Service-Name` header and the deduct `product` field. */
    productSlug: string;
    fetchImpl?: typeof fetch;
    /** Default 10 000. */
    timeoutMs?: number;
}
/** Describe subscription tier and status information for a platform user */
interface PlatformSubscriptionInfo {
    tier: TanglePlanTier;
    status: string | null;
}
/** Describe the platform balance and lifetime spending with an optional update timestamp */
interface PlatformBalanceSnapshot {
    balance: number;
    lifetimeSpent: number;
    updatedAt?: string;
}
/** Describe a product's usage and spending metrics on the platform */
interface PlatformUsageProductRow {
    product: string | null;
    totalSpent: number;
    count: number;
}
/** Lifecycle of a per-product seat subscription, mirroring the Stripe states
 *  the platform persists. 'none' = the user has never held this seat. */
type SeatStatus = 'none' | 'active' | 'trialing' | 'past_due' | 'canceled';
/**
 * Per-product entitlement snapshot from the platform — the single read that
 * tells a product whether to show its workspace or the seat paywall. Shape
 * matches `GET /v1/billing/product-entitlement?product=<id>`.
 *
 * `hasSeat` and `onFreeTier` are computed platform-side from the raw seat row
 * + cumulative spend so the gate is identical across all five products:
 * - `hasSeat`     — an active/trialing seat whose period has not lapsed.
 * - `onFreeTier`  — no active seat AND cumulative spend below the free cap
 *                   ($2 / 200¢ lifetime). Keys off lifetime spend, not wallet
 *                   balance, so a router top-up never re-opens free access.
 */
interface ProductEntitlement {
    seatStatus: SeatStatus;
    /** ISO timestamp the active seat's paid period runs until; null when none. */
    currentPeriodEnd: string | null;
    /** Cumulative inference spend across the whole suite, in dollars. */
    lifetimeSpentUsd: number;
    hasSeat: boolean;
    onFreeTier: boolean;
}
/** Define methods to interact with platform billing endpoints using user or service authentication */
interface PlatformBillingHttp {
    /** GET /v1/plans/current (user bearer). */
    getSubscription(userApiKey: string): Promise<PlatformSubscriptionInfo>;
    /** GET /v1/billing/balance (user bearer). */
    getBalance(userApiKey: string): Promise<PlatformBalanceSnapshot>;
    /** GET /v1/billing/usage (user bearer). */
    getUsageByProduct(userApiKey: string): Promise<PlatformUsageProductRow[]>;
    /** GET /v1/billing/product-entitlement?product=<id> (user bearer). */
    getProductEntitlement(userApiKey: string, productId: string): Promise<ProductEntitlement>;
    /** POST /v1/billing/deduct (service token). */
    deduct(input: {
        platformUserId: string;
        amountUsd: number;
        type: string;
        description: string;
        referenceId: string;
    }): Promise<void>;
    /** Absolute URL of the platform's billing-management surface. */
    billingUrl(): string;
    /** Absolute URL of the $100/mo seat checkout for `productId`. */
    seatCheckoutUrl(productId: string): string;
}
/** Create a PlatformBillingHttp instance configured with given options and default behaviors */
declare function createPlatformBillingHttp(opts: PlatformBillingHttpOptions): PlatformBillingHttp;
/**
 * Platform Stripe checkout URL for a product's $100/mo seat. One shared price
 * carries `metadata.productId`; the platform distinguishes the product from
 * the `product` query param (not five distinct prices). Mirrors the
 * `billingUrl()` shape — a deterministic platform-rooted URL, no network call.
 */
declare function seatCheckoutUrl(baseUrl: string, productId: string): string;
/** Define policy settings for concurrency and overage allowance in a tangle tier */
interface TangleTierPolicy {
    concurrency: number;
    overageAllowed: boolean;
}
/** Define default concurrency and overage policies for each TanglePlanTier level */
declare const DEFAULT_TANGLE_TIER_POLICY: Record<TanglePlanTier, TangleTierPolicy>;
/** Describe the state of a Tangle plan tier including subscription, balance, spending, and concurrency details */
interface TangleTierState {
    tier: TanglePlanTier;
    subscriptionStatus: string | null;
    remainingBalanceUsd: number;
    lifetimeSpentUsd: number;
    concurrency: number;
    overageAllowed: boolean;
}
/**
 * Read subscription + balance and project them onto the tier policy. A
 * null/absent key fails CLOSED (free tier, zero balance) — a billable run is
 * never started against an unknown balance. Platform errors throw; callers
 * on the billable path choose their posture explicitly.
 */
declare function readTangleTierState(http: PlatformBillingHttp, userApiKey: string | null | undefined, policy?: Record<TanglePlanTier, TangleTierPolicy>): Promise<TangleTierState>;
/** Lifetime free-tier cap: $2 (200¢) cumulative inference spend, expressed in
 *  dollars. Free product access ends once cumulative spend crosses this. */
declare const FREE_TIER_SPEND_CAP_USD = 2;
/**
 * Default name of the per-app feature flag gating seat billing. While OFF the
 * entitlement read is skipped and access fails OPEN (entitled) so nothing
 * changes live until a product flips the flag.
 */
declare const DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR = "SEAT_BILLING_ENABLED";
/** Define options to configure seat billing flag environment variables and override flag name */
interface SeatBillingFlagOptions {
    env?: Record<string, string | undefined>;
    /** Override the flag name; default {@link DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR}. */
    flagEnvVar?: string;
}
/**
 * Seat billing is OFF unless the flag is explicitly truthy ('true'/'1'/'on'/
 * 'enabled'). Default OFF — pre-rollout, the paywall never engages. Returns
 * false when no env is available (browser bundles) so the client stays
 * fail-open there too.
 */
declare function isSeatBillingEnabled(opts?: SeatBillingFlagOptions): boolean;
/**
 * Read a user's entitlement for one product. Fails OPEN: an absent key,
 * disabled flag, or unreachable seat endpoint all return a permissive snapshot
 * (`hasSeat: true`) so consumers never break pre-rollout. The platform owns the
 * `hasSeat`/`onFreeTier` computation; this client only transports + degrades
 * safely.
 *
 * @param flag — pass {@link isSeatBillingEnabled} (or your own boolean) so the
 *   product owns when the gate engages. When false, no network call is made.
 */
declare function getProductEntitlement(http: Pick<PlatformBillingHttp, 'getProductEntitlement'>, userApiKey: string | null | undefined, productId: string, flag?: boolean): Promise<ProductEntitlement>;
/** Entitled = holds an active seat OR is still inside the free tier. The one
 *  predicate all five products gate on. */
declare function isProductEntitled(ent: ProductEntitlement): boolean;
/** Define a contract for resolving platform identities based on user identifiers */
interface PlatformIdentityStore {
    resolveIdentity(userId: string): Promise<PlatformIdentity | null>;
}
/** Concrete fetch-backed `PlatformBillingClient<TanglePlanTier>` for
 *  `createPlatformBalanceManager` (from `/billing`). */
declare function createTanglePlatformBillingClient(http: PlatformBillingHttp, identity: PlatformIdentityStore): PlatformBillingClient<TanglePlanTier>;

export { DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR, DEFAULT_TANGLE_TIER_POLICY, FREE_TIER_SPEND_CAP_USD, type HubClientLike, type HubProxyContext, type HubProxyRouteArgs, type HubProxyRoutes, type PlatformBalanceSnapshot, type PlatformBillingHttp, PlatformBillingHttpError, type PlatformBillingHttpOptions, type PlatformIdentityStore, type PlatformSubscriptionInfo, type PlatformUsageProductRow, type ProductEntitlement, type ResolveUserTangleHubBearerForUserOptions, type ResolveUserTangleHubBearerOptions, type ResolvedTangleHubBearer, type SeatBillingFlagOptions, type SeatStatus, TangleBearerMissingError, type TangleHubBearerSource, type TanglePlanTier, type TangleTierPolicy, type TangleTierState, createHubProxyRoutes, createPlatformBillingHttp, createTanglePlatformBillingClient, getProductEntitlement, isPlatformBillingHttpError, isPlatformHubErrorLike, isProductEntitled, isSeatBillingEnabled, isTangleBearerMissingError, normalizeTanglePlanTier, readTangleTierState, resolveUserTangleHubBearer, resolveUserTangleHubBearerForUser, seatCheckoutUrl };
