@orangecheck/me-client 0.27.3 → 0.27.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/popup.js.map +1 -1
- package/dist/popup.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/transport.ts","../src/session.ts","../src/SignInButton.tsx","../src/payment.ts","../src/types.ts","../src/event.ts","../src/templates.ts","../src/config.ts","../node_modules/jose/dist/webapi/lib/buffer_utils.js","../node_modules/jose/dist/webapi/lib/base64.js","../node_modules/jose/dist/webapi/util/base64url.js","../node_modules/jose/dist/webapi/util/errors.js","../node_modules/jose/dist/webapi/lib/type_checks.js","../node_modules/jose/dist/webapi/lib/jwk_to_key.js","../node_modules/jose/dist/webapi/key/import.js","../src/webhook.ts","../src/federations.ts","../src/scope.ts","../src/family.ts","../src/identity.ts","../src/subtypes.ts","../src/index.ts"],"names":["scope","React","jsxs","event","jsx","config","identity","verify","scopes","origin","DEFAULT_ISSUER","DEFAULT_TTL_MS","jwksCache","inflight","hexToBytes","toArrayBuffer","verifyEd25519"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,IAAI,MAAA,GAAS,oBAAA;AACb,IAAI,WAAA,GAA6B,IAAA;AAE1B,SAAS,UAAU,GAAA,EAAmB;AACzC,EAAA,MAAA,GAAS,GAAA,CAAI,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AAClC;AAEO,SAAS,SAAA,GAAoB;AAChC,EAAA,OAAO,MAAA;AACX;AAKO,SAAS,eAAe,KAAA,EAA4B;AACvD,EAAA,WAAA,GAAc,KAAA,IAAS,KAAA,CAAM,MAAA,GAAS,CAAA,GAAI,KAAA,GAAQ,IAAA;AACtD;AAEO,SAAS,cAAA,GAAgC;AAC5C,EAAA,OAAO,WAAA;AACX;AAE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AAG;AAC3B;;;AChCO,IAAM,EAAA,GAAK;AAAA,EACd,OAAA;AAAA,EACA,OAAA;AAAA,EACA,KAAA;AAAA,EACA,MAAA;AAAA,EACA,OAAA;AAAA,EACA,WAAA;AAAA,EACA,KAAA;AAAA,EACA,MAAA;AAAA,EACA;AACJ","file":"index.js","sourcesContent":["/**\n * Tiny HTTP transport layer. The me.ochk.io origin is configurable so\n * staging deployments and self-hosted me-equivalents can swap it.\n *\n * Two auth paths, picked transparently:\n * - Same-origin / family integrators (*.ochk.io): the browser ships\n * the `oc_session` cookie automatically because we set\n * `credentials: 'include'`. Nothing to configure.\n * - Cross-domain integrators: after popup signin, call\n * `setBearerToken(result.token)` once. Subsequent SDK calls add\n * `Authorization: Bearer <token>`. Cookies still ride too — the\n * server accepts whichever arrives.\n */\n\nlet origin = 'https://me.ochk.io';\nlet bearerToken: string | null = null;\n\nexport function setOrigin(url: string): void {\n origin = url.replace(/\\/$/, '');\n}\n\nexport function getOrigin(): string {\n return origin;\n}\n\n/** Cross-domain integrators: store the JWT returned by `signInWithOc()`\n * here so subsequent SDK calls can authenticate via Authorization\n * header. Same-origin integrators don't need this (the cookie rides). */\nexport function setBearerToken(token: string | null): void {\n bearerToken = token && token.length > 0 ? token : null;\n}\n\nexport function getBearerToken(): string | null {\n return bearerToken;\n}\n\nexport function clearBearerToken(): void {\n bearerToken = null;\n}\n\nexport interface FetchOptions {\n method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';\n body?: unknown;\n signal?: AbortSignal;\n /** Extra request headers merged over the defaults · e.g. X-OC-Signature\n * (integrator HMAC) or Idempotency-Key. */\n headers?: Record<string, string>;\n /** Per-call bearer token · overrides the process-global setBearerToken for\n * THIS request only. Use it for stateless server-side firing so concurrent\n * requests for different users never race on one shared module-level token\n * (the setBearerToken global is fine for a single-user browser session). */\n bearerToken?: string;\n}\n\nexport async function api<T>(path: string, opts: FetchOptions = {}): Promise<T> {\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n accept: 'application/json',\n ...(opts.headers ?? {}),\n };\n const token = opts.bearerToken ?? bearerToken;\n if (token) headers['authorization'] = `Bearer ${token}`;\n const res = await fetch(`${origin}${path}`, {\n method: opts.method ?? 'GET',\n credentials: 'include',\n headers,\n body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,\n signal: opts.signal,\n });\n if (!res.ok) {\n let message = `me.ochk.io ${res.status}`;\n let errorCode: string | undefined;\n let body: Record<string, unknown> | undefined;\n try {\n const data = (await res.json()) as {\n error?: string;\n reason?: string;\n [k: string]: unknown;\n };\n body = data;\n if (data?.error) {\n errorCode = data.error;\n message = data.reason ?? data.error;\n }\n } catch {\n /* response body wasn't JSON; carry the bare status */\n }\n // 429 → carry Retry-After so callers (or the small\n // withRateLimitRetry helper) can back off correctly. The header\n // is in seconds per RFC 7231; we surface it as a number on the\n // error rather than asking the caller to re-parse.\n let retryAfterSeconds: number | undefined;\n if (res.status === 429) {\n const headerValue = res.headers.get('retry-after');\n if (headerValue) {\n const parsed = Number.parseInt(headerValue, 10);\n if (Number.isFinite(parsed) && parsed >= 0) retryAfterSeconds = parsed;\n }\n // Server bodies on 429 often also carry the hint as\n // `retry_after_seconds` (see /api/integrator/event/batch's\n // applyProjectRateLimit response). Honor it as a fallback\n // when no header is present — some intermediaries strip\n // Retry-After from CORS responses.\n if (retryAfterSeconds == null && typeof body?.retry_after_seconds === 'number') {\n retryAfterSeconds = body.retry_after_seconds as number;\n }\n }\n throw new MeClientError(message, res.status, { errorCode, retryAfterSeconds });\n }\n return (await res.json()) as T;\n}\n\nexport class MeClientError extends Error {\n public readonly status: number;\n /** Server-side error code (the `error` field on the JSON body, e.g.\n * `project_rate_limit_exceeded`). Stable across versions; safe to\n * match on. The human-readable `message` may change. */\n public readonly errorCode: string | undefined;\n /** Seconds to wait before retrying. Set when the server responded\n * 429 with a Retry-After header (or a `retry_after_seconds` body\n * field). Undefined for any other status. Use with\n * `withRateLimitRetry()` or your own backoff loop. */\n public readonly retryAfterSeconds: number | undefined;\n constructor(\n message: string,\n status: number,\n opts?: { errorCode?: string; retryAfterSeconds?: number }\n ) {\n super(message);\n this.name = 'MeClientError';\n this.status = status;\n this.errorCode = opts?.errorCode;\n this.retryAfterSeconds = opts?.retryAfterSeconds;\n }\n /** True for the 429 surface · convenience boolean so callers don't\n * have to compare status === 429 every time. */\n get isRateLimited(): boolean {\n return this.status === 429;\n }\n}\n\nexport interface WithRateLimitRetryOptions {\n /** Maximum retry attempts on 429. Default 2 (= up to 3 total\n * invocations of the wrapped function). */\n maxRetries?: number;\n /** Cap on Retry-After we'll actually honor in seconds. Some server\n * configs return very large values; the SDK refuses to sleep\n * beyond this and re-throws the original error so the caller\n * decides. Default 30. */\n maxRetryAfterSeconds?: number;\n /** Floor backoff in milliseconds when no Retry-After is present.\n * Multiplied by 2^attempt for exponential growth. Default 250ms. */\n baseBackoffMs?: number;\n}\n\n/**\n * Wrap a transport call with automatic 429 retry, honoring Retry-After.\n *\n * import { oc, withRateLimitRetry } from '@orangecheck/me-client';\n *\n * const res = await withRateLimitRetry(() =>\n * oc.event.fireBatch({ project_key, events })\n * );\n *\n * Retries ONLY on 429 (rate-limit) responses. All other errors throw\n * immediately so the caller can handle them. Sleeps for `Retry-After`\n * seconds when present (capped at `maxRetryAfterSeconds`); otherwise\n * uses exponential backoff from `baseBackoffMs`.\n *\n * Per OCHK-V3-PLAN §12.6 — backpressure protocol. The server emits\n * 429 + Retry-After when a project crosses its 1000 events/sec sustained\n * cap; this helper honors it without integrators having to write the\n * sleep loop.\n *\n * Idempotency note: integrators using `event.fireBatch` should pass an\n * `idempotency_key` per event so a retry doesn't double-record. The\n * server collapses retried events to a `duplicate` status with the\n * prior payload.\n */\nexport async function withRateLimitRetry<T>(\n fn: () => Promise<T>,\n opts: WithRateLimitRetryOptions = {}\n): Promise<T> {\n const maxRetries = opts.maxRetries ?? 2;\n const maxRetryAfter = opts.maxRetryAfterSeconds ?? 30;\n const baseBackoff = opts.baseBackoffMs ?? 250;\n let attempt = 0;\n while (true) {\n try {\n return await fn();\n } catch (err) {\n if (!(err instanceof MeClientError) || !err.isRateLimited) throw err;\n if (attempt >= maxRetries) throw err;\n let waitMs: number;\n if (err.retryAfterSeconds != null) {\n if (err.retryAfterSeconds > maxRetryAfter) throw err;\n waitMs = err.retryAfterSeconds * 1000;\n } else {\n waitMs = baseBackoff * 2 ** attempt;\n }\n await new Promise((resolve) => setTimeout(resolve, waitMs));\n attempt++;\n }\n }\n}\n","import type { Session, SessionPolicy, SignInOptions, TelemetryEvent } from './types';\n\nimport { api } from './transport';\n\nconst DEFAULT_POLICY: SessionPolicy = {\n duration_seconds: 7 * 24 * 60 * 60, // 7 days, standard SaaS shape\n refresh: 'sliding',\n sensitive_actions: 're-auth',\n};\n\nconst telemetrySubscribers = new Set<(e: TelemetryEvent) => void>();\n\n/** Subscribe to non-billable developer telemetry events. Call the returned\n * function to unsubscribe. */\nexport function onTelemetry(listener: (e: TelemetryEvent) => void): () => void {\n telemetrySubscribers.add(listener);\n return () => {\n telemetrySubscribers.delete(listener);\n };\n}\n\nfunction emitTelemetry(code: TelemetryEvent['code'], session_id?: string): void {\n const e: TelemetryEvent = {\n code,\n timestamp: new Date().toISOString(),\n ...(session_id ? { session_id } : {}),\n };\n for (const fn of telemetrySubscribers) {\n try {\n fn(e);\n } catch {\n /* listener errors must not break the session flow */\n }\n }\n}\n\n/**\n * Open a sign-in flow at me.ochk.io. Returns the resulting Session once\n * the user consents (Class C billable event for the integrating site,\n * cashback for the user). Internally this opens the OC consent UI in a\n * popup; v1 implementations may also redirect.\n */\nasync function create(opts: SignInOptions): Promise<Session> {\n const policy: SessionPolicy = { ...DEFAULT_POLICY, ...(opts.sessionPolicy ?? {}) };\n return api<Session>('/api/session/create', {\n method: 'POST',\n body: {\n scope: opts.scope,\n policy,\n return_to: opts.returnTo ?? (typeof window !== 'undefined' ? window.location.href : undefined),\n },\n });\n}\n\n/**\n * Refresh a still-valid session inside its policy window. Free for the\n * integrating site (does NOT instantiate a billable event); emits a\n * `session.token_refresh` telemetry record.\n */\nasync function refresh(sessionId: string): Promise<Session> {\n emitTelemetry('session.token_refresh', sessionId);\n return api<Session>('/api/session/refresh', {\n method: 'POST',\n body: { session_id: sessionId },\n });\n}\n\n/**\n * Tear a session down. Free, and telemetry-only in a literal sense: OC sessions\n * are stateless — derived from the `oc_session` JWT — so there is no server-side\n * record to delete and the endpoint acknowledges without revoking anything.\n * Dropping your own copy of the token IS the logout; this call is the signal.\n */\nasync function invalidate(sessionId: string): Promise<void> {\n emitTelemetry('session.teardown', sessionId);\n await api<{ ok: true }>('/api/session/invalidate', {\n method: 'POST',\n body: { session_id: sessionId },\n });\n}\n\nexport const session = { create, refresh, invalidate };\n","import * as React from 'react';\n\nimport { session } from './session';\nimport type { Session, SessionPolicy } from './types';\n\nexport interface OcSignInButtonProps\n extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'onError'> {\n scope: string[];\n sessionPolicy?: Partial<SessionPolicy>;\n returnTo?: string;\n onSignin?: (session: Session) => void;\n /** Called when the sign-in flow fails. Renamed from `onError` to avoid\n * shadowing the native button error handler. */\n onSignInError?: (error: Error) => void;\n /** Custom button text. Defaults to \"sign in with oc\". */\n label?: string;\n}\n\n/**\n * Drop-in Sign-in-with-OC button. Triggers the me.ochk.io consent flow\n * for the requested scope, opens (or refreshes) a session, and calls\n * onSignin(session) on success. Class C billable event for the\n * integrating site; cashback flows to the user.\n *\n * Mounting requires <OcSessionProvider> from @orangecheck/auth-client\n * somewhere up the React tree so the resulting session can be read by\n * useOcSession() across the rest of the app.\n */\nexport function OcSignInButton({\n scope,\n sessionPolicy,\n returnTo,\n onSignin,\n onSignInError,\n label = 'sign in with oc',\n children,\n onClick,\n style,\n ...rest\n}: OcSignInButtonProps) {\n const [pending, setPending] = React.useState(false);\n\n return (\n <button\n type=\"button\"\n onClick={async (event) => {\n onClick?.(event);\n if (event.defaultPrevented) return;\n setPending(true);\n try {\n const result = await session.create({ scope, sessionPolicy, returnTo });\n onSignin?.(result);\n } catch (err) {\n onSignInError?.(err instanceof Error ? err : new Error(String(err)));\n } finally {\n setPending(false);\n }\n }}\n style={{\n display: 'inline-flex',\n alignItems: 'center',\n gap: 8,\n padding: '10px 16px',\n fontSize: 13,\n fontWeight: 600,\n fontFamily: 'ui-monospace, \"JetBrains Mono\", \"SF Mono\", Menlo, monospace',\n letterSpacing: '0.18em',\n textTransform: 'uppercase',\n background: '#f97316',\n color: '#0b0909',\n border: '1px solid #f97316',\n borderRadius: 4,\n cursor: pending ? 'progress' : 'pointer',\n opacity: pending ? 0.7 : 1,\n ...(style ?? {}),\n }}\n disabled={pending || rest.disabled}\n data-oc-signin\n {...rest}\n >\n {/* compact OC mark */}\n <span\n aria-hidden\n style={{\n display: 'inline-block',\n width: 12,\n height: 12,\n background: '#0b0909',\n }}\n />\n {children ?? (pending ? 'opening…' : label)}\n </button>\n );\n}\n","import type { PaymentAuthorizeOptions, PaymentResult } from './types';\n\nimport { api } from './transport';\n\n/**\n * Authorize a payment through the user's OC identity. Class B billable\n * event for the integrating site (sub-Stripe rate, percentage-based);\n * cashback flows to the user as Lightning credit on /me/earn.\n *\n * The user is prompted by me.ochk.io to consent to the specific payment\n * before this resolves. If the user declines or cancels, the result has\n * status `'cancelled'`, a non-billable telemetry record is emitted, and\n * NO billable event is created.\n */\nasync function authorize(opts: PaymentAuthorizeOptions): Promise<PaymentResult> {\n if (opts.amount_sats == null && opts.usd_cents == null) {\n throw new Error('payment.authorize requires amount_sats or usd_cents');\n }\n return api<PaymentResult>('/api/payment/authorize', {\n method: 'POST',\n body: opts,\n });\n}\n\nexport const payment = { authorize };\n","/**\n * Canonical types for me.ochk.io integrators.\n *\n * Mirrors the source of truth at oc-me-web/src/lib/events/types.ts. Two\n * layers:\n * - Platform-level (PLATFORM_FEE_POLICY, MIN_INTEGRATOR_PRICE_SATS) —\n * fixed by OC, surfaced as constants here so integrators can validate\n * their config client-side before posting it.\n * - Integrator-level (IntegratorPriceConfig) — every integrator declares\n * their own per-event prices and user-share splits.\n *\n * Per Addendum 01: every chargeable event is in exactly one of three\n * classes. Sites pay for sessions and actions, not for clicks. Free\n * events never instantiate a BillableEvent.\n */\n\n// ── platform constants (fixed by OC) ──────────────────────────────────────\n\nexport const PLATFORM_FEE_POLICY = {\n /** Fraction of every gross_fee that OC retains. */\n pct: 0.2,\n /** Absolute minimum platform fee, in sats. */\n min_floor_sats: 1,\n /** Date this policy was last ratified. Changes require a versioned\n * @orangecheck/me-client release. */\n ratified: '2026-04-30',\n} as const;\n\n/** Per-event price floor. 1 sat — the natural atomic Bitcoin unit.\n * Integrators choose their own per-event prices above this; OC does\n * not impose sybil-resistance opinions on integrators (that's their\n * call, from their own threat model). The 1-sat floor is purely\n * mechanical — fees can't be fractional sats. Mirrors the canonical\n * value at oc-me-web/src/lib/events/types.ts (a previous SDK release\n * drifted to 5 while the platform ratified 1). */\nexport const MIN_INTEGRATOR_PRICE_SATS = 1;\n\n/**\n * Hard per-event ceiling, mirroring the server's own bound.\n *\n * The server clamps gross to this before splitting it; this package did not,\n * so `verify()` re-derived 99,000,000 for an envelope the server had recorded\n * at 10,000,000 and rejected a correct receipt. It also over-reported what a\n * misconfigured site would be charged, by the ratio of the two numbers.\n *\n * 10,000,000 sats = 0.1 BTC: orders of magnitude above any real per-event\n * price, low enough that a misconfiguration cannot mint an unbounded number\n * of sats in one event. Found by the cross-package vector test in oc-me-web\n * on its first run.\n */\nexport const MAX_INTEGRATOR_PRICE_SATS = 10_000_000;\n\n/** Platform ceiling on drop-period windows: no integrator schedule may\n * hold a user's earned share open longer than this, regardless of\n * cadence. Published in ABUSE_LIMITS on me.ochk.io /trust + /security. */\nexport const MAX_DROP_WINDOW_DAYS = 92;\n\n// ── event taxonomy ────────────────────────────────────────────────────────\n\nexport type EventClass = 'A' | 'B' | 'C';\n\nexport type ClassASubtype =\n | 'account_creation'\n | 'account_recovery'\n | 'attest_bond_increased'\n | 'payment_method_connected'\n | 'agent_delegation_issued'\n | 'recovery_method_updated';\n\nexport type ClassBSubtype =\n | 'payment_authorization'\n | 'scoped_action_authorization'\n | 'attest_verification_at_gate'\n | 'stamp_signing'\n | 'pledge_resolution';\n\nexport type ClassCSubtype = 'session_creation';\n\nexport type EventSubtype = ClassASubtype | ClassBSubtype | ClassCSubtype;\n\n/**\n * Any billable event key. A project's catalog is OPEN: alongside the built-in\n * subtypes above, an integrator can define their own event keys (with their own\n * label + class + price) on the project config. `EventKey` keeps autocomplete\n * for the built-ins while accepting any custom string — the `(string & {})`\n * arm preserves the literal union in editors instead of collapsing it to\n * `string`. The server resolves class/label off the project's catalog for\n * custom keys.\n */\nexport type EventKey = EventSubtype | (string & {});\n\n/** AttestTier · what an integrator's gate can read about an oc identity.\n *\n * me.ochk does NOT do KYC. Sybil resistance is bounded by three\n * composable mechanisms, none of which involve OC handling PII:\n * 1. paid-action history · billable events cost real sats\n * 2. BIP-322 sat-bonding · bond size + age via signed attestation\n * 3. integrator-defined gates · per-site threat-model overlays\n *\n * Tier itself is intentionally simple — anonymous | bonded.\n * Granularity (bond_sats, bond_locked_at, etc) carried separately. */\nexport type AttestTier = 'anonymous' | 'bonded';\n\n/** The shape of a per-event fee — either a fixed sats amount or a percent\n * of the underlying transaction amount (used for payments + pledges). */\nexport type SiteFeeShape =\n | { kind: 'fixed_sats'; sats: number }\n | { kind: 'percent_of_amount'; pct: number };\n\n/** Optional per-class pricing overrides · per OCHK-V3-PLAN §7 phase-1.\n * Agents acting under a scoped oc-agent delegation may bill\n * differently than humans firing the same subtype. When `agent` is\n * unset on a subtype, agent traffic bills at the human rate. `refuse:\n * true` makes the subtype human-only — the endpoint returns 422\n * agent_refused for is_agent=true requests. */\nexport interface AgentClassOverride {\n /** Override site_pays for agent-fired events. */\n site_pays?: SiteFeeShape;\n /** Override user_share_pct. Same default-fallback as site_pays. */\n user_share_pct?: number;\n /** When true, agent traffic is refused for this subtype. */\n refuse?: boolean;\n}\n\n/** What an integrator declares for a single event subtype. */\nexport interface IntegratorEventConfig {\n /** Whether this site bills this event subtype at all. */\n enabled: boolean;\n /** The per-event fee the site pays. */\n site_pays: SiteFeeShape;\n /** Fraction of GROSS that flows to the user (0–0.8 since the\n * platform fee is 20%). The remainder is a rebate to the site's\n * OC project balance. */\n user_share_pct: number;\n /** Optional per-agent-class pricing override applied when an event\n * fires with is_agent=true. */\n agent?: AgentClassOverride;\n}\n\n/** A complete integrator pricing config. Posted to me.ochk.io once at\n * integration time, mutable via the configurator UI or this SDK any time\n * after. */\nexport interface IntegratorPriceConfig {\n project_key: string;\n display_name: string;\n domain: string;\n /** ISO-8601 timestamp the config was last updated. */\n updated_at: string;\n /** Per-event configs, keyed by event key. Open catalog: built-in subtypes\n * AND your own custom keys. Keys not listed are disabled by default. */\n events: Partial<Record<EventKey, IntegratorEventConfig>>;\n}\n\n/** A computed fee breakdown for a single event. site_rebate_sats is what\n * flows back to the integrator's OC balance after OC's platform fee and\n * the user's cashback. */\nexport interface ComputedFees {\n gross_fee_sats: number;\n platform_fee_sats: number;\n user_earned_sats: number;\n site_rebate_sats: number;\n}\n\n/** Compute the four-way fee split for an event given an integrator's\n * config and (for percent_of_amount events) the underlying payment\n * amount. MIRRORS oc-me-web/src/lib/events/types.ts computeFees()\n * EXACTLY — the SDK-side replay (oc.event.verify) re-runs this against\n * envelopes the server billed, so any drift is a false \"divergence\".\n *\n * Invariants:\n * 1. gross_fee_sats >= MIN_INTEGRATOR_PRICE_SATS (1-sat atomic floor)\n * 2. platform_fee_sats = min(gross, max(min_floor, round(gross × pct)))\n * — bounded above by gross so a 1-sat event can't owe more\n * platform fee than it grossed\n * 3. user_earned_sats = min(gross − platform, round(gross × share)),\n * share clamped to [0, 0.8]\n * 4. site_rebate_sats = gross − platform − user (exact remainder)\n * 5. gross == platform + user + rebate exactly\n *\n * When `opts.is_agent` is true AND the config has an `agent` override,\n * the agent's site_pays / user_share_pct apply. `agent.refuse: true`\n * throws 'agent_refused' (the server maps it to 422). */\nexport function computeFees(\n cfg: IntegratorEventConfig,\n payment_amount_sats?: number,\n opts?: { is_agent?: boolean }\n): ComputedFees {\n const is_agent = opts?.is_agent === true;\n if (is_agent && cfg.agent?.refuse) {\n throw new Error('agent_refused');\n }\n const effective_site_pays =\n is_agent && cfg.agent?.site_pays ? cfg.agent.site_pays : cfg.site_pays;\n const effective_user_share_pct =\n is_agent && typeof cfg.agent?.user_share_pct === 'number'\n ? cfg.agent.user_share_pct\n : cfg.user_share_pct;\n\n let gross = 0;\n if (effective_site_pays.kind === 'fixed_sats') {\n gross = Math.max(MIN_INTEGRATOR_PRICE_SATS, Math.round(effective_site_pays.sats));\n } else {\n if (payment_amount_sats == null) {\n throw new Error('percent_of_amount config requires payment_amount_sats');\n }\n gross = Math.max(\n MIN_INTEGRATOR_PRICE_SATS,\n Math.round(payment_amount_sats * effective_site_pays.pct)\n );\n }\n // Hard ceiling · no single event mints more than MAX_INTEGRATOR_PRICE_SATS.\n // The server applies this before splitting; omitting it here made verify()\n // reject correct envelopes priced above the bound.\n gross = Math.min(gross, MAX_INTEGRATOR_PRICE_SATS);\n const platform_fee_sats = Math.min(\n gross,\n Math.max(PLATFORM_FEE_POLICY.min_floor_sats, Math.round(gross * PLATFORM_FEE_POLICY.pct))\n );\n const user_share = Math.min(0.8, Math.max(0, effective_user_share_pct));\n const user_earned_sats = Math.min(gross - platform_fee_sats, Math.round(gross * user_share));\n const site_rebate_sats = gross - platform_fee_sats - user_earned_sats;\n return { gross_fee_sats: gross, platform_fee_sats, user_earned_sats, site_rebate_sats };\n}\n\n/** Result of validating an IntegratorPriceConfig. */\nexport interface ValidationResult {\n ok: boolean;\n errors: { subtype?: EventKey; message: string }[];\n}\n\n/**\n * Validate an integrator's pricing config against the platform's\n * non-negotiable rules. Run client-side before posting; the server runs\n * the same checks and rejects anything that fails.\n */\nexport function validateIntegratorConfig(cfg: IntegratorPriceConfig): ValidationResult {\n const errors: ValidationResult['errors'] = [];\n\n if (!cfg.project_key) errors.push({ message: 'project_key is required' });\n if (!cfg.display_name) errors.push({ message: 'display_name is required' });\n if (!cfg.domain) errors.push({ message: 'domain is required' });\n\n for (const [key, eventCfg] of Object.entries(cfg.events)) {\n if (!eventCfg) continue;\n const subtype = key as EventKey;\n if (!eventCfg.enabled) continue;\n\n if (eventCfg.site_pays.kind === 'fixed_sats') {\n if (eventCfg.site_pays.sats < MIN_INTEGRATOR_PRICE_SATS) {\n errors.push({\n subtype,\n message: `site_pays.sats (${eventCfg.site_pays.sats}) is below MIN_INTEGRATOR_PRICE_SATS (${MIN_INTEGRATOR_PRICE_SATS})`,\n });\n }\n } else {\n const pct = eventCfg.site_pays.pct;\n if (!(pct > 0 && pct <= 1)) {\n errors.push({\n subtype,\n message: `site_pays.pct (${pct}) must be in (0, 1]`,\n });\n }\n }\n\n const u = eventCfg.user_share_pct;\n if (u < 0 || u > 0.8) {\n errors.push({\n subtype,\n message: `user_share_pct (${u}) must be in [0, 0.8]; max is 0.8 because platform_fee is ${PLATFORM_FEE_POLICY.pct}`,\n });\n }\n }\n\n return { ok: errors.length === 0, errors };\n}\n\n// ── canonical envelope ────────────────────────────────────────────────────\n\nexport interface BillableEvent {\n id: string;\n occurred_at: string;\n class: EventClass;\n subtype: EventKey;\n site: { domain: string; display_name: string };\n gross_fee_sats: number;\n platform_fee_sats: number;\n user_earned_sats: number;\n site_rebate_sats: number;\n verify_url: string;\n /** Per OCHK-V3-PLAN §7 phase-1 · true when the event was fired by\n * an oc-agent delegation rather than a human session. The\n * integrator's IntegratorEventConfig.agent block may price\n * these differently or refuse them. Optional · canonical encoder\n * branches to v=3 only when present, so legacy human-fired\n * events keep their v=2 hash + signature. */\n is_agent?: boolean;\n /** Drop-period stamp · present when the project covers this\n * subtype with a drop schedule. The user-share of a stamped event\n * MATURES until the window's boundary, then vests as one batch\n * (the drop). Billing is untouched. Part of the SIGNED canonical\n * bytes (encoder branches to v=4 when present). No clawback\n * exists — vesting is unconditional, and an open window's\n * boundary can only ever move earlier. */\n drop?: {\n /** Deterministic window id · the window's signed manifest is\n * verifiable at me.ochk.io/verify/<manifest_id> after close. */\n window_id: string;\n /** Block-denominated vesting boundary; null when no chain tip\n * was observable at window open (wallclock + the published\n * 24h safety valve then govern). */\n close_height_target: number | null;\n } | null;\n}\n\n// ── drop periods · integrator-scheduled payout windows ───────────────────\n\n/** A drop schedule's cadence. Weekly/monthly close at a fixed UTC\n * boundary; manual closes when the integrator says (Drop now), with a\n * hard auto-close at max_open_days (≤ MAX_DROP_WINDOW_DAYS). */\nexport type DropCadence =\n | { kind: 'weekly'; day: number; hour: number }\n | { kind: 'monthly'; day: number; hour: number }\n | { kind: 'manual'; max_open_days: number };\n\n/** Public shape of an enabled drop schedule, as returned in the\n * `drops` array of GET /api/integrator/config — part of the project's\n * public payout contract (earners can see when covered subtypes pay\n * out before earning under them). */\nexport interface DropScheduleSummary {\n schedule_id: string;\n label: string;\n subtypes: EventSubtype[];\n cadence: DropCadence;\n}\n\n/** Drop-period context on event-ingest responses (single route:\n * top-level `drop`; batch route: per-result `drop`). `state` flips\n * from 'open' to 'closing' once the scheduled boundary passes and the\n * window awaits its sweep (~15 min) — render \"processing\", never a\n * negative countdown. */\nexport interface DropResponseBlock {\n window_id: string;\n label: string;\n state: 'open' | 'closing';\n closes_at_target: string;\n close_height_target: number | null;\n}\n\n// ── webhook payload ───────────────────────────────────────────────────────\n\n/**\n * The exact JSON body delivered to a registered webhook endpoint when\n * a billable event fires. Imported by integrator backends so the\n * receive handler is type-checked end-to-end without re-declaring the\n * shape.\n *\n * import type { WebhookPayload } from '@orangecheck/me-client';\n *\n * export async function POST(req: Request) {\n * const payload = (await req.json()) as WebhookPayload;\n * if (payload.subtype === 'payment_authorization') {\n * creditUser(payload.sub, payload.user_earned_sats);\n * }\n * }\n *\n * Headers carry the signature and metadata (see WebhookHeaders below).\n * Verify the signature with `oc.webhook.verify({ body, headers, jwks })`.\n *\n * Privacy contract · the master oc identity is NEVER in the payload.\n * Integrators see `sub` (per-integrator anonymous id) plus any\n * `scopes` the user explicitly granted. See PRIVACY-ARCHITECTURE.md.\n */\nexport interface WebhookPayload extends BillableEvent {\n /** Discriminator · identifies the payload kind for routing on\n * the integrator's side. Always 'oc-billable-event' today; future\n * webhook payload kinds (refunds, charters, etc) will use\n * distinct discriminator values. */\n kind: 'oc-billable-event';\n /** Per-integrator anonymous subject id · stable across events for\n * the same (oc_identity, project_key) pair. Key your user records\n * on this; OC will never give you the master address unless the\n * user explicitly grants `bitcoin_address` or `email` scope. */\n sub: string;\n /** Resolved scoped fields · only present for scopes the user has\n * granted to this project. Wire format is string-keyed (every\n * value is stringified · ints stringified, addresses as-is). */\n scopes?: Partial<\n Record<\n | 'bitcoin_address'\n | 'email'\n | 'attest_tier'\n | 'display_name'\n | 'cross_integrator_event_count'\n | 'cross_integrator_human_event_count'\n | 'trust_attestation_count'\n | 'trust_attestations_bundle',\n string\n >\n >;\n}\n\n/**\n * Non-billable SYSTEM webhook deliveries — project-level operational\n * signals (escrow.low, escrow.depleted, escrow.recovered, drop.closed).\n * Same signing + headers as billable deliveries; receivers subscribe\n * via the same `subscribed` list ('*' or the explicit subtype string).\n * Carries no user identity. Discriminate on `kind` first, then\n * `subtype`:\n *\n * const payload = JSON.parse(body) as WebhookPayload | SystemWebhookPayload;\n * if (payload.kind === 'oc-system-event' && payload.subtype === 'drop.closed') { … }\n */\nexport interface SystemWebhookPayload {\n kind: 'oc-system-event';\n subtype: string;\n project_key: string;\n [extra: string]: unknown;\n}\n\n/** The `drop.closed` system event — one per closed drop window. The\n * manifest is the signed, content-addressed record (Merkle commitments\n * over member events + recipients); verify_url renders + live-verifies\n * it, and /api/envelope/<manifest_id> serves the raw canonical bytes. */\nexport interface DropClosedWebhookPayload extends SystemWebhookPayload {\n subtype: 'drop.closed';\n window_id: string;\n schedule_id: string;\n label: string;\n manifest_id: string;\n verify_url: string;\n sealed_at: string;\n sealed_height: number | null;\n event_count: number;\n recipient_count: number;\n gross_fee_sats: number;\n user_share_sats: number;\n}\n\n/**\n * HTTP headers OC sends with every webhook delivery. Capture these in\n * the receive handler · `OC-Signature` is what verifies the body.\n */\nexport interface WebhookHeaders {\n /** Ed25519 signature over the raw response body, hex-encoded. */\n 'OC-Signature': string;\n /** Stable kid of the signing key · resolves against\n * ochk.io/.well-known/jwks.json. */\n 'OC-Key-Id': string;\n /** Envelope id · matches payload.id; useful for idempotent\n * receive handlers that dedupe on this header without parsing\n * the body. */\n 'OC-Envelope-Id': string;\n /** Subtype · matches payload.subtype (built-in or a custom event key);\n * lets routers branch on the header before parsing. */\n 'OC-Subtype': EventKey;\n /** Class · matches payload.class. */\n 'OC-Class': EventClass;\n /** 1-indexed delivery attempt count. >1 means the prior attempt\n * did not return a 2xx within the timeout · idempotency key on\n * payload.id is critical. */\n 'OC-Delivery-Attempt': string;\n}\n\n// ── session lifecycle ────────────────────────────────────────────────────\n\nexport interface SessionPolicy {\n duration_seconds: number;\n refresh: 'sliding' | 'rolling' | 'none';\n sensitive_actions?: 're-auth' | 'none';\n}\n\nexport interface Session {\n id: string;\n identity: string;\n opens_at: string;\n expires_at: string;\n policy: SessionPolicy;\n scope: string[];\n}\n\nexport interface SignInOptions {\n scope: string[];\n sessionPolicy?: Partial<SessionPolicy>;\n returnTo?: string;\n}\n\nexport interface PaymentAuthorizeOptions {\n identity: string;\n amount_sats?: number;\n usd_cents?: number;\n description: string;\n external_ref?: string;\n}\n\nexport interface PaymentResult {\n id: string;\n status: 'authorized' | 'failed' | 'cancelled';\n sats_charged?: number;\n user_envelope_id?: string;\n verify_url?: string;\n}\n\nexport interface TelemetryEvent {\n code:\n | 'session.intra_signin'\n | 'session.token_refresh'\n | 'session.navigation'\n /** Emitted by `session.invalidate()`. Was `session.intra_signin`, which\n * means the opposite thing — \"user pressed sign-in while a valid\n * session was already open\" — so a subscriber saw a sign-in event\n * every time the integrator tore a session down. Non-billable. */\n | 'session.teardown'\n | 'auth.signin_failed'\n | 'auth.signin_cancelled'\n | 'auth.signin_rejected'\n | 'verify.passive_check';\n timestamp: string;\n session_id?: string;\n}\n\n// ── federation directory ───────────────────────────────────────────────\n//\n// The SDK consumes the federation directory at runtime so multi-federation\n// routing is a directory write, not a code change. v1 has one live\n// federation; the directory is plural-shaped so federation #2 lights up\n// without an SDK release.\n\nexport type FederationStatus = 'recruiting' | 'forming' | 'binding' | 'live';\n\n/** Federation directory entry. Mirrors `oc-me-web/src/lib/federations/registry.ts`\n * field-for-field; this package is the public consumption shape. */\nexport interface Federation {\n slug: string;\n name: string;\n status: FederationStatus;\n threshold: string;\n target_guardian_count: number;\n /** Fedimint invite code; null until status === 'live'. */\n invite: string | null;\n /** SHA-256 of the canonical federation charter, hex-encoded. */\n charter_hash: string | null;\n /** ISO-8601 of the most recent ongoing-attestation envelope. */\n last_attestation_at: string | null;\n geography_hint: string;\n // Operator-recruiting fields (present on slots in 'recruiting' /\n // 'forming' / 'binding' state). Nullable so one shape spans the\n // lifecycle.\n geography_requirements?: string;\n charter_status?: string;\n ceremony_window?: string;\n why_this_one?: string;\n apply_cta?: string;\n apply_href?: string;\n}\n\n/** SigningMethod discriminator on the user identity. Federation-agnostic\n * by construction — the OC identity (did:email or BIP-322 address)\n * remains stable across all three states. Transitions are recorded as\n * anchored \"rebind\" envelopes on the canonical event log. Graduation\n * is the product thesis; this discriminator is the structural primitive\n * that records where a user is on the custody-state graph. */\nexport type SigningMethod = 'fedimint_threshold' | 'fedimint_client' | 'bip322';\n","/**\n * `oc.event.fire` — escape hatch for firing a billable envelope under\n * any subtype that isn't already covered by `oc.session.create` or\n * `oc.payment.authorize`. Useful for `stamp_signing`,\n * `attest_verification_at_gate`, `scoped_action_authorization`,\n * `kyc_tier_upgrade`, etc.\n *\n * import { oc } from '@orangecheck/me-client';\n *\n * const env = await oc.event.fire({\n * project_key: 'pk_live_yourcompany',\n * subtype: 'stamp_signing',\n * action_label: 'review · march invoice',\n * });\n * // env.id, env.gross_fee_sats, env.user_earned_sats, env.verify_url\n *\n * // For percent_of_amount-priced subtypes, include the underlying amount:\n * const verify = await oc.event.fire({\n * project_key: 'pk_live_yourcompany',\n * subtype: 'attest_verification_at_gate',\n * payment_amount_sats: 50_000,\n * });\n *\n * The class is determined by SUBTYPE_CLASS server-side; cashback is\n * computed via computeFees(); the envelope is recorded under the\n * project_key and shows up in /developer/projects/[id]/events.\n */\n\nimport {\n computeFees,\n type BillableEvent,\n type EventKey,\n type IntegratorEventConfig,\n type IntegratorPriceConfig,\n} from './types';\nimport { api } from './transport';\n\nexport interface FireEventOptions {\n /** Your project_key (e.g. `pk_live_yourcompany`). Required. */\n project_key: string;\n /** Billable event key · a built-in subtype OR a custom key defined on your\n * project catalog. Class + label are resolved server-side from the catalog. */\n subtype: EventKey;\n /** Human-readable action label that appears on the envelope.\n * Optional but encouraged — it's what the user sees in their\n * /me/activity ledger. */\n action_label?: string;\n /** For percent_of_amount-priced subtypes, the underlying amount\n * the fee is computed against. Required for those subtypes. */\n payment_amount_sats?: number;\n /** Free-form metadata stored on the envelope. Public — anyone who\n * GETs /api/envelope/<id> sees it. Don't put secrets here. */\n metadata?: Record<string, unknown>;\n /** Per OCHK-V3-PLAN §7 phase-1 · when true, the event was fired\n * by an oc-agent delegation rather than a human acting under their\n * own session. The integrator's IntegratorEventConfig.agent block\n * applies the override (or refuses · 422 agent_refused).\n *\n * Set this when an autonomous agent (oc-agent kind 30084 action\n * envelope) is the source of the event. Don't set it for events\n * the human user clicked themselves. */\n is_agent?: boolean;\n /** The project's HMAC signing secret. When provided, the SDK signs the\n * request with X-OC-Signature, authenticating the call as the INTEGRATOR.\n * REQUIRED in test mode as well as live — without it the server 401s,\n * because a user session alone proves a user, never the paying project.\n * The one exception is a session that owns the project (the CLI\n * test-fire path), which is not a shape a backend should rely on.\n * SERVER-SIDE\n * ONLY: never ship this secret to a browser. Find/rotate it on the project\n * Keys tab (/me/projects/<id>/keys). */\n signingSecret?: string;\n /** Who earns, as their `did:oc` — the value `/api/auth/me` returns as\n * `did_oc`.\n *\n * This is the BACKEND path, and it is the one to prefer. Your server\n * signs the request with `signingSecret`, the signature covers these\n * bytes, and the earner rides inside them — so the signature is your\n * project asserting \"this identity did this on my site\". No browser, no\n * user cookie, and no reason for your backend to be holding your users'\n * session tokens at all.\n *\n * REQUIRES `signingSecret`. A session alone may never name an earner: it\n * proves a user, not a project, and that would let any signed-in caller\n * credit anybody. */\n userAddress?: string;\n /** The forwarded user oc_session JWT (the `token` from the sign-in popup\n * result). Identifies which user earns the cashback when `userAddress` is\n * not given. Pass it per-call for stateless, concurrency-safe server-side\n * firing — preferred over the process-global setBearerToken when your\n * backend serves many users. A same-origin family integrator (*.ochk.io)\n * can omit it; the oc_session cookie rides automatically. */\n bearerToken?: string;\n /** Idempotency key (e.g. a UUID v7 per logical event). A retry with the\n * same key returns the prior event rather than double-billing. */\n idempotencyKey?: string;\n}\n\n/** HMAC-SHA256 hex via Web Crypto — works in Node 20+ and the browser with no\n * node:crypto import (keeps this package isomorphic). Signing only ever runs\n * server-side because it needs the project secret. */\nasync function hmacSha256Hex(secret: string, message: string): Promise<string> {\n const enc = new TextEncoder();\n const key = await crypto.subtle.importKey(\n 'raw',\n enc.encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign']\n );\n const sig = await crypto.subtle.sign('HMAC', key, enc.encode(message));\n return Array.from(new Uint8Array(sig))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/** Build the X-OC-Signature header for a request body, byte-matching the\n * server's event-signature.ts contract: `t=<unix>,v1=hmac_sha256(secret,\n * `${t}.${body}`)`. The `body` MUST be the exact JSON string the transport\n * transmits (the server re-derives it as JSON.stringify(req.body)). */\nasync function signBody(secret: string, serializedBody: string): Promise<string> {\n const t = Math.floor(Date.now() / 1000);\n const mac = await hmacSha256Hex(secret, `${t}.${serializedBody}`);\n return `t=${t},v1=${mac}`;\n}\n\nasync function fire(options: FireEventOptions): Promise<BillableEvent> {\n if (!options.project_key) {\n throw new Error('event.fire requires project_key');\n }\n if (!options.subtype) {\n throw new Error('event.fire requires subtype');\n }\n // Fail here rather than letting the server 401 — the mistake is always the\n // same one (naming an earner from a browser or an unsigned backend call),\n // and the round-trip tells you less than this sentence does.\n if (options.userAddress && !options.signingSecret) {\n throw new Error(\n 'event.fire: userAddress names who earns, so it requires signingSecret — ' +\n 'the signature over the request body is what authorises that earner. ' +\n 'Without the secret, pass bearerToken (or rely on the oc_session cookie) ' +\n 'and the caller earns instead.'\n );\n }\n\n // Build the request body from server-recognized fields ONLY — never let the\n // signing secret or bearer token leak into the transmitted payload.\n const requestBody: Record<string, unknown> = {\n project_key: options.project_key,\n subtype: options.subtype,\n };\n if (options.payment_amount_sats !== undefined)\n requestBody.payment_amount_sats = options.payment_amount_sats;\n if (options.action_label !== undefined) requestBody.action_label = options.action_label;\n if (options.metadata !== undefined) requestBody.metadata = options.metadata;\n if (options.is_agent !== undefined) requestBody.is_agent = options.is_agent;\n // Inside the signed bytes on purpose — see `userAddress` above.\n if (options.userAddress !== undefined) requestBody.user_address = options.userAddress;\n\n const headers: Record<string, string> = {};\n if (options.idempotencyKey) headers['idempotency-key'] = options.idempotencyKey;\n if (options.signingSecret) {\n // Sign the exact bytes the transport sends: it JSON.stringify's the same\n // object reference, so this string is byte-identical to what lands.\n headers['x-oc-signature'] = await signBody(\n options.signingSecret,\n JSON.stringify(requestBody)\n );\n }\n\n return api<BillableEvent>('/api/integrator/event', {\n method: 'POST',\n body: requestBody,\n headers,\n bearerToken: options.bearerToken,\n });\n}\n\n/** One event in a batch · same shape as the per-event request minus\n * project_key (which is hoisted to the batch level). */\nexport interface BatchEventInput {\n /** Billable event key · built-in subtype or a custom project key. */\n subtype: EventKey;\n /** For percent_of_amount-priced subtypes, the underlying amount. */\n payment_amount_sats?: number;\n /** Human-readable label that appears in /me/earn. */\n action_label?: string;\n /** Free-form note stored on the envelope. Public. */\n note?: string;\n /** Per-event idempotency key. Distinct from the batch-level retry —\n * if the SDK retries the same batch, events that already landed\n * collapse to a `duplicate` status with the prior payload. */\n idempotency_key?: string;\n /** Per OCHK-V3-PLAN §7 phase-1 · per-event agent flag. A single\n * batch can mix agent + human events when a backend interleaves\n * them. The integrator's per-subtype agent override applies per\n * event independently. */\n is_agent?: boolean;\n}\n\n/** Per-event result inside the batch response. Status codes:\n * - `recorded` · the event landed; `event` is the canonical billable\n * payload exactly as a per-event POST would return.\n * - `duplicate` · idempotency-key matched a prior event; `event` is\n * the prior payload.\n * - `rejected` · validation or site-cap failure; `reason` is human-\n * readable. The other events in the batch are unaffected. */\nexport type BatchEventResult =\n | {\n index: number;\n status: 'recorded';\n event: BillableEvent;\n }\n | {\n index: number;\n status: 'duplicate';\n event: BillableEvent;\n }\n | {\n index: number;\n status: 'rejected';\n reason: string;\n };\n\nexport interface FireBatchOptions {\n /** Your project_key. Required. All events in the batch bill against\n * this project_key + the authenticated session. */\n project_key: string;\n /** 1 to 100 events. Larger batches must be split client-side. */\n events: BatchEventInput[];\n /** The project's HMAC signing secret · REQUIRED in live mode (same\n * contract as event.fire). Server-side only. */\n signingSecret?: string;\n /** The forwarded user oc_session JWT · pass per-call for stateless\n * server-side firing (see FireEventOptions.bearerToken). */\n bearerToken?: string;\n}\n\nexport interface FireBatchResponse {\n ok: boolean;\n results: BatchEventResult[];\n escrow_mode: 'simulation' | 'live';\n simulation_mode_note?: string;\n}\n\n/**\n * `oc.event.fireBatch` — bulk-ingest up to 100 billable envelopes\n * under one project_key in a single HTTP round-trip.\n *\n * Wins amortize across the batch: one auth roundtrip, one project\n * lookup, one scope-grants resolve, parallel KV writes via Promise.all.\n * For a 50-event batch the server-side processing time drops from\n * ~3-4.5 seconds (50 sequential per-event POSTs) to ~100-200ms.\n *\n * import { oc } from '@orangecheck/me-client';\n *\n * const res = await oc.event.fireBatch({\n * project_key: 'pk_live_yourcompany',\n * events: [\n * { subtype: 'session_creation' },\n * { subtype: 'page_view', action_label: 'home' },\n * { subtype: 'page_view', action_label: 'pricing' },\n * ],\n * });\n * for (const r of res.results) {\n * if (r.status === 'recorded') console.log('+', r.event.id, r.event.gross_fee_sats);\n * else if (r.status === 'duplicate') console.log('~ idempotent replay', r.event.id);\n * else console.log('!', r.reason);\n * }\n *\n * Failure modes:\n * - 400 if events.length === 0 or > 100, or events[].subtype missing\n * - 403 if the project is frozen or the domain is unverified\n * - 429 if the project's rate limit (1000 events/sec sustained) is\n * exceeded; Retry-After header indicates backoff.\n *\n * Per OCHK-V3-PLAN §12.2.\n */\nasync function fireBatch(options: FireBatchOptions): Promise<FireBatchResponse> {\n if (!options.project_key) {\n throw new Error('event.fireBatch requires project_key');\n }\n if (!Array.isArray(options.events) || options.events.length === 0) {\n throw new Error('event.fireBatch requires at least one event');\n }\n if (options.events.length > 100) {\n throw new Error(\n `event.fireBatch · max 100 events per call (got ${options.events.length}). Split client-side.`\n );\n }\n\n // Body excludes the secret/token — only project_key + events go on the wire.\n const requestBody = { project_key: options.project_key, events: options.events };\n const headers: Record<string, string> = {};\n if (options.signingSecret) {\n headers['x-oc-signature'] = await signBody(\n options.signingSecret,\n JSON.stringify(requestBody)\n );\n }\n\n return api<FireBatchResponse>('/api/integrator/event/batch', {\n method: 'POST',\n body: requestBody,\n headers,\n bearerToken: options.bearerToken,\n });\n}\n\n/** Result of replay-verifying a billable envelope against the\n * integrator's price config. Every field returned tells the caller\n * WHY a divergence happened — they can render it directly. */\nexport interface VerifyEventResult {\n /** True iff every expected fee equals the recorded fee. */\n ok: boolean;\n /** Issues found during verification, with field-level granularity\n * so callers can highlight exactly which line is off. */\n issues: Array<{\n field:\n | 'gross_fee_sats'\n | 'platform_fee_sats'\n | 'user_earned_sats'\n | 'site_rebate_sats'\n | 'subtype_disabled'\n | 'subtype_unconfigured'\n | 'percent_amount_missing';\n expected: number | null;\n actual: number | null;\n message: string;\n }>;\n /** What computeFees() returned for the envelope's subtype + amount,\n * given the integrator's current price config. Useful for the\n * /audit divergence tracker — render expected vs actual side by\n * side. Null when the subtype isn't enabled for this integrator. */\n expected: {\n gross_fee_sats: number;\n platform_fee_sats: number;\n user_earned_sats: number;\n site_rebate_sats: number;\n } | null;\n}\n\n/**\n * Replay-verify a billable envelope against the integrator's current\n * price config. Re-runs computeFees() with the same inputs and\n * compares against the four-way split recorded on the envelope.\n *\n * Anyone — the integrator, a user, OC, an auditor — can run this\n * function and reach the same answer. The integrator-side replay is\n * what keeps OC honest: a divergence means OC's billing engine\n * computed differently than the published price config says it should\n * have, and the integrator can flag it on /audit.\n *\n * For percent_of_amount-priced subtypes, the underlying payment\n * amount must be passed explicitly (it isn't stored on the envelope\n * top-level — only inside the context payload — so callers should\n * pass `envelope.context.payment_amount_sats`).\n *\n * import { oc } from '@orangecheck/me-client';\n *\n * const env = await fetch(`https://me.ochk.io/api/envelope/${id}`).then(r => r.json());\n * // Your project's config, by its key. A project can move domains, so\n * // `env.site.domain` names where it was, not which project it is.\n * const cfg = await fetch(\n * `https://me.ochk.io/api/integrator-config?project_key=${PROJECT_KEY}`\n * ).then(r => r.json());\n * const result = oc.event.verify(env, cfg);\n * if (!result.ok) reportDivergence(result.issues);\n */\nfunction verify(\n envelope: BillableEvent,\n config: IntegratorPriceConfig,\n payment_amount_sats?: number\n): VerifyEventResult {\n const issues: VerifyEventResult['issues'] = [];\n\n const eventCfg: IntegratorEventConfig | undefined = config.events[envelope.subtype];\n if (!eventCfg) {\n return {\n ok: false,\n expected: null,\n issues: [\n {\n field: 'subtype_unconfigured',\n expected: null,\n actual: null,\n message: `subtype ${envelope.subtype} is not configured on integrator ${config.project_key}`,\n },\n ],\n };\n }\n if (!eventCfg.enabled) {\n return {\n ok: false,\n expected: null,\n issues: [\n {\n field: 'subtype_disabled',\n expected: null,\n actual: null,\n message: `subtype ${envelope.subtype} is disabled on integrator ${config.project_key} but the envelope was billed`,\n },\n ],\n };\n }\n if (eventCfg.site_pays.kind === 'percent_of_amount' && payment_amount_sats == null) {\n return {\n ok: false,\n expected: null,\n issues: [\n {\n field: 'percent_amount_missing',\n expected: null,\n actual: null,\n message: `subtype ${envelope.subtype} is percent_of_amount-priced; payment_amount_sats is required to verify`,\n },\n ],\n };\n }\n\n const expected = computeFees(eventCfg, payment_amount_sats);\n\n if (envelope.gross_fee_sats !== expected.gross_fee_sats) {\n issues.push({\n field: 'gross_fee_sats',\n expected: expected.gross_fee_sats,\n actual: envelope.gross_fee_sats,\n message: `gross_fee_sats mismatch · expected ${expected.gross_fee_sats}, recorded ${envelope.gross_fee_sats}`,\n });\n }\n if (envelope.platform_fee_sats !== expected.platform_fee_sats) {\n issues.push({\n field: 'platform_fee_sats',\n expected: expected.platform_fee_sats,\n actual: envelope.platform_fee_sats,\n message: `platform_fee_sats mismatch · expected ${expected.platform_fee_sats}, recorded ${envelope.platform_fee_sats}`,\n });\n }\n if (envelope.user_earned_sats !== expected.user_earned_sats) {\n issues.push({\n field: 'user_earned_sats',\n expected: expected.user_earned_sats,\n actual: envelope.user_earned_sats,\n message: `user_earned_sats mismatch · expected ${expected.user_earned_sats}, recorded ${envelope.user_earned_sats}`,\n });\n }\n if (envelope.site_rebate_sats !== expected.site_rebate_sats) {\n issues.push({\n field: 'site_rebate_sats',\n expected: expected.site_rebate_sats,\n actual: envelope.site_rebate_sats,\n message: `site_rebate_sats mismatch · expected ${expected.site_rebate_sats}, recorded ${envelope.site_rebate_sats}`,\n });\n }\n\n return {\n ok: issues.length === 0,\n expected,\n issues,\n };\n}\n\nexport const event = { fire, fireBatch, verify };\n","/**\n * Archetype templates for `oc.config.fromTemplate(useCase, ...)`.\n *\n * A new integrator with a 30-second decision shouldn't have to fill\n * 12 IntegratorEventConfig entries by hand. Pick the archetype that\n * matches your site, get a sensible starting config, tweak whatever\n * you want, submit:\n *\n * import { oc } from '@orangecheck/me-client';\n *\n * const config = oc.config.fromTemplate('saas-paywall', {\n * project_key: 'pk_live_yourcompany',\n * domain: 'yoursite.com',\n * display_name: 'Your Site',\n * });\n * await oc.config.save(config);\n *\n * Templates differ on which subtypes are enabled (a content platform\n * doesn't need payment_authorization; a marketplace does) and on the\n * sat price + user_share_pct per subtype. Every template's prices\n * anchor at $1 ≈ 1052 sats. user_share_pct=0.65 means the user gets\n * 65% of gross — the platform fee is 20% (fixed), the integrator\n * rebate is the remainder (15% with 0.65 user share).\n *\n * To customize after picking a template:\n *\n * const config = oc.config.fromTemplate('marketplace', { ... });\n * config.events.payment_authorization!.site_pays = {\n * kind: 'percent_of_amount',\n * pct: 0.005, // 0.5% instead of the template's 0.75%\n * };\n */\n\nimport type {\n EventSubtype,\n IntegratorEventConfig,\n IntegratorPriceConfig,\n} from './types';\n\nexport type IntegratorArchetype =\n | 'saas-paywall'\n | 'marketplace'\n | 'content-platform'\n | 'gaming'\n | 'agent-only';\n\ninterface ProjectIdentity {\n project_key: string;\n domain: string;\n display_name: string;\n}\n\n/** Template descriptor · what each archetype enables and prices.\n * Exposed so dashboards can render \"you're using the X template\"\n * state and offer one-click swaps. */\nexport interface ArchetypeTemplate {\n id: IntegratorArchetype;\n label: string;\n /** One-sentence summary shown next to the picker. */\n summary: string;\n /** Concrete examples of sites this archetype fits. */\n examples: readonly string[];\n /** Per-subtype config the template emits. Subtypes not listed are\n * emitted as `enabled: false` (the SDK fills them with a\n * conservative default to keep the type happy without firing). */\n events: Partial<Record<EventSubtype, IntegratorEventConfig>>;\n}\n\nconst FIXED = (sats: number): IntegratorEventConfig['site_pays'] => ({\n kind: 'fixed_sats',\n sats,\n});\nconst PCT = (pct: number): IntegratorEventConfig['site_pays'] => ({\n kind: 'percent_of_amount',\n pct,\n});\n\n/**\n * The full archetype catalog. Add new templates here · one record per\n * common integrator pattern. Keep the list curated (≤8 archetypes) —\n * if there are too many, none feel like the obvious default and\n * integrators stall on the picker.\n */\nexport const ARCHETYPE_TEMPLATES: readonly ArchetypeTemplate[] = [\n {\n id: 'saas-paywall',\n label: 'SaaS · paywall',\n summary:\n 'Subscription product · users sign up, sign in, sometimes pay for premium tiers. Default cashback to encourage signup + retention.',\n examples: ['Notion-like notes app', 'Linear-like project tracker', 'Figma-like editor'],\n events: {\n account_creation: {\n enabled: true,\n site_pays: FIXED(1300),\n user_share_pct: 0.65,\n },\n session_creation: {\n enabled: true,\n site_pays: FIXED(55),\n user_share_pct: 0.65,\n },\n payment_authorization: {\n enabled: true,\n site_pays: PCT(0.0075),\n user_share_pct: 0.65,\n },\n payment_method_connected: {\n enabled: true,\n site_pays: FIXED(320),\n user_share_pct: 0.65,\n },\n },\n },\n {\n id: 'marketplace',\n label: 'marketplace',\n summary:\n 'Two-sided marketplace · buyers + sellers transact. Heavy on payment_authorization and scoped_action_authorization for listings.',\n examples: ['Stripe-like checkout', 'Etsy-like marketplace', 'Uber-like ride-hailing'],\n events: {\n account_creation: {\n enabled: true,\n site_pays: FIXED(1300),\n user_share_pct: 0.65,\n },\n session_creation: {\n enabled: true,\n site_pays: FIXED(55),\n user_share_pct: 0.65,\n },\n payment_authorization: {\n enabled: true,\n site_pays: PCT(0.0075),\n user_share_pct: 0.65,\n },\n scoped_action_authorization: {\n enabled: true,\n site_pays: FIXED(100),\n user_share_pct: 0.65,\n },\n payment_method_connected: {\n enabled: true,\n site_pays: FIXED(320),\n user_share_pct: 0.65,\n },\n attest_verification_at_gate: {\n enabled: true,\n site_pays: FIXED(280),\n user_share_pct: 0.65,\n },\n },\n },\n {\n id: 'content-platform',\n label: 'content platform',\n summary:\n 'User-generated content · posts, reviews, votes, comments. Each meaningful action is scoped_action_authorization; stamp_signing for credentialed reviews.',\n examples: ['Reddit-like forum', 'YouTube-like video host', 'Substack-like publishing'],\n events: {\n account_creation: {\n enabled: true,\n site_pays: FIXED(1300),\n user_share_pct: 0.7,\n },\n session_creation: {\n enabled: true,\n site_pays: FIXED(55),\n user_share_pct: 0.7,\n },\n scoped_action_authorization: {\n enabled: true,\n site_pays: FIXED(100),\n user_share_pct: 0.7,\n },\n stamp_signing: {\n enabled: true,\n site_pays: FIXED(55),\n user_share_pct: 0.7,\n },\n },\n },\n {\n id: 'gaming',\n label: 'gaming',\n summary:\n 'Game with monetized actions · pledges + scoped actions are core. Higher cashback ratios reward in-game engagement.',\n examples: [\n 'on-chain prediction markets',\n 'skill-staking tournaments',\n 'PvP wager games',\n ],\n events: {\n account_creation: {\n enabled: true,\n site_pays: FIXED(1300),\n user_share_pct: 0.7,\n },\n session_creation: {\n enabled: true,\n site_pays: FIXED(55),\n user_share_pct: 0.7,\n },\n scoped_action_authorization: {\n enabled: true,\n site_pays: FIXED(100),\n user_share_pct: 0.7,\n },\n payment_authorization: {\n enabled: true,\n site_pays: PCT(0.005),\n user_share_pct: 0.7,\n },\n pledge_resolution: {\n enabled: true,\n site_pays: PCT(0.01),\n user_share_pct: 0.7,\n },\n attest_verification_at_gate: {\n enabled: true,\n site_pays: FIXED(280),\n user_share_pct: 0.7,\n },\n },\n },\n {\n id: 'agent-only',\n label: 'agent-only',\n summary:\n 'AI-agent surface · oc-agent delegations are the primary auth pattern. Session_creation off (delegations replace sessions); agent_delegation_issued + scoped_action_authorization carry the activity.',\n examples: [\n 'AI assistant calling APIs on user behalf',\n 'autonomous trading bot',\n 'agent-driven customer support',\n ],\n events: {\n account_creation: {\n enabled: true,\n site_pays: FIXED(1300),\n user_share_pct: 0.65,\n },\n agent_delegation_issued: {\n enabled: true,\n site_pays: FIXED(320),\n user_share_pct: 0.65,\n },\n scoped_action_authorization: {\n enabled: true,\n site_pays: FIXED(100),\n user_share_pct: 0.65,\n },\n },\n },\n];\n\nconst ARCHETYPES_BY_ID: Record<IntegratorArchetype, ArchetypeTemplate> = Object.fromEntries(\n ARCHETYPE_TEMPLATES.map((t) => [t.id, t])\n) as Record<IntegratorArchetype, ArchetypeTemplate>;\n\n/** All 12 subtypes — used to fill `enabled: false` defaults for any\n * subtype the chosen archetype doesn't list. */\nconst ALL_SUBTYPES: readonly EventSubtype[] = [\n 'account_creation',\n 'account_recovery',\n 'attest_bond_increased',\n 'payment_method_connected',\n 'agent_delegation_issued',\n 'recovery_method_updated',\n 'payment_authorization',\n 'scoped_action_authorization',\n 'attest_verification_at_gate',\n 'stamp_signing',\n 'pledge_resolution',\n 'session_creation',\n];\n\nconst DEFAULT_DISABLED: IntegratorEventConfig = {\n enabled: false,\n site_pays: { kind: 'fixed_sats', sats: 100 },\n user_share_pct: 0.65,\n};\n\n/**\n * Build a complete IntegratorPriceConfig from an archetype id + the\n * project's identity fields. Every subtype gets an entry — the\n * archetype's listed subtypes get the template's pricing; everything\n * else gets `enabled: false` with conservative defaults so the config\n * is type-complete and the integrator can flip-on later subtypes\n * without re-deriving prices.\n *\n * Throws synchronously if `useCase` isn't a known archetype id.\n */\nexport function fromTemplate(\n useCase: IntegratorArchetype,\n identity: ProjectIdentity\n): IntegratorPriceConfig {\n const template = ARCHETYPES_BY_ID[useCase];\n if (!template) {\n throw new Error(\n `oc.config.fromTemplate: unknown archetype \"${useCase}\". Valid: ${Object.keys(\n ARCHETYPES_BY_ID\n ).join(', ')}`\n );\n }\n const events: IntegratorPriceConfig['events'] = {};\n for (const sub of ALL_SUBTYPES) {\n events[sub] = template.events[sub] ?? DEFAULT_DISABLED;\n }\n return {\n project_key: identity.project_key,\n domain: identity.domain,\n display_name: identity.display_name,\n updated_at: new Date().toISOString(),\n events,\n };\n}\n\n/** Look up a template's metadata · used by config-editor UIs to render\n * \"you're on the X template · here's what it enables\" copy. */\nexport function getArchetypeTemplate(id: IntegratorArchetype): ArchetypeTemplate {\n return ARCHETYPES_BY_ID[id];\n}\n","/**\n * `oc.config` — IntegratorPriceConfig helpers.\n *\n * oc.config.fromTemplate(useCase, identity) · build a complete\n * config from one of the curated archetypes (\"saas-paywall\",\n * \"marketplace\", \"content-platform\", \"gaming\", \"agent-only\").\n * Returns a type-complete config you can submit, or tweak before\n * submitting.\n *\n * oc.config.validate(cfg) · local validator, no network call.\n * Mirrors the server-side rules; run before posting to catch\n * shape errors at edit time.\n *\n * oc.config.archetypes · the catalog of available templates with\n * metadata. Useful for rendering an archetype picker in your\n * own UI before calling fromTemplate().\n *\n * Example · zero-to-config in three lines:\n *\n * import { oc } from '@orangecheck/me-client';\n *\n * const cfg = oc.config.fromTemplate('saas-paywall', {\n * project_key: 'pk_live_yourcompany',\n * domain: 'yoursite.com',\n * display_name: 'Your Site',\n * });\n * const result = oc.config.validate(cfg);\n * // → submit cfg via the project upsert API\n *\n * Per-project read/write of the config is owner-gated and lives at\n * /api/me/projects/[id] (POST to update). See me.ochk.io/me/projects/\n * for the dashboard UI.\n */\n\nimport {\n ARCHETYPE_TEMPLATES,\n fromTemplate,\n getArchetypeTemplate,\n type ArchetypeTemplate,\n type IntegratorArchetype,\n} from './templates';\nimport { validateIntegratorConfig } from './types';\nimport type { IntegratorPriceConfig, ValidationResult } from './types';\n\nfunction validate(cfg: IntegratorPriceConfig): ValidationResult {\n return validateIntegratorConfig(cfg);\n}\n\nexport const config = {\n validate,\n fromTemplate,\n /** Look up a template's metadata · for rendering \"you picked X\"\n * state and offering one-click swaps in your own UI. */\n getArchetype: getArchetypeTemplate,\n /** All available archetypes · render in a picker. */\n archetypes: ARCHETYPE_TEMPLATES,\n};\n\nexport type { ArchetypeTemplate, IntegratorArchetype };\n","export const encoder = new TextEncoder();\nexport const decoder = new TextDecoder();\nconst MAX_INT32 = 2 ** 32;\nexport function concat(...buffers) {\n const size = buffers.reduce((acc, { length }) => acc + length, 0);\n const buf = new Uint8Array(size);\n let i = 0;\n for (const buffer of buffers) {\n buf.set(buffer, i);\n i += buffer.length;\n }\n return buf;\n}\nfunction writeUInt32BE(buf, value, offset) {\n if (value < 0 || value >= MAX_INT32) {\n throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);\n }\n buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset);\n}\nexport function uint64be(value) {\n const high = Math.floor(value / MAX_INT32);\n const low = value % MAX_INT32;\n const buf = new Uint8Array(8);\n writeUInt32BE(buf, high, 0);\n writeUInt32BE(buf, low, 4);\n return buf;\n}\nexport function uint32be(value) {\n const buf = new Uint8Array(4);\n writeUInt32BE(buf, value);\n return buf;\n}\nexport function encode(string) {\n const bytes = new Uint8Array(string.length);\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code > 127) {\n throw new TypeError('non-ASCII string encountered in encode()');\n }\n bytes[i] = code;\n }\n return bytes;\n}\n","export function encodeBase64(input) {\n if (Uint8Array.prototype.toBase64) {\n return input.toBase64();\n }\n const CHUNK_SIZE = 0x8000;\n const arr = [];\n for (let i = 0; i < input.length; i += CHUNK_SIZE) {\n arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));\n }\n return btoa(arr.join(''));\n}\nexport function decodeBase64(encoded) {\n if (Uint8Array.fromBase64) {\n return Uint8Array.fromBase64(encoded);\n }\n const binary = atob(encoded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n","import { encoder, decoder } from '../lib/buffer_utils.js';\nimport { encodeBase64, decodeBase64 } from '../lib/base64.js';\nexport function decode(input) {\n if (Uint8Array.fromBase64) {\n return Uint8Array.fromBase64(typeof input === 'string' ? input : decoder.decode(input), {\n alphabet: 'base64url',\n });\n }\n let encoded = input;\n if (encoded instanceof Uint8Array) {\n encoded = decoder.decode(encoded);\n }\n encoded = encoded.replace(/-/g, '+').replace(/_/g, '/');\n try {\n return decodeBase64(encoded);\n }\n catch {\n throw new TypeError('The input to be decoded is not correctly encoded.');\n }\n}\nexport function encode(input) {\n let unencoded = input;\n if (typeof unencoded === 'string') {\n unencoded = encoder.encode(unencoded);\n }\n if (Uint8Array.prototype.toBase64) {\n return unencoded.toBase64({ alphabet: 'base64url', omitPadding: true });\n }\n return encodeBase64(unencoded).replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n","export class JOSEError extends Error {\n static code = 'ERR_JOSE_GENERIC';\n code = 'ERR_JOSE_GENERIC';\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class JWTClaimValidationFailed extends JOSEError {\n static code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n claim;\n reason;\n payload;\n constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n super(message, { cause: { claim, reason, payload } });\n this.claim = claim;\n this.reason = reason;\n this.payload = payload;\n }\n}\nexport class JWTExpired extends JOSEError {\n static code = 'ERR_JWT_EXPIRED';\n code = 'ERR_JWT_EXPIRED';\n claim;\n reason;\n payload;\n constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n super(message, { cause: { claim, reason, payload } });\n this.claim = claim;\n this.reason = reason;\n this.payload = payload;\n }\n}\nexport class JOSEAlgNotAllowed extends JOSEError {\n static code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n}\nexport class JOSENotSupported extends JOSEError {\n static code = 'ERR_JOSE_NOT_SUPPORTED';\n code = 'ERR_JOSE_NOT_SUPPORTED';\n}\nexport class JWEDecryptionFailed extends JOSEError {\n static code = 'ERR_JWE_DECRYPTION_FAILED';\n code = 'ERR_JWE_DECRYPTION_FAILED';\n constructor(message = 'decryption operation failed', options) {\n super(message, options);\n }\n}\nexport class JWEInvalid extends JOSEError {\n static code = 'ERR_JWE_INVALID';\n code = 'ERR_JWE_INVALID';\n}\nexport class JWSInvalid extends JOSEError {\n static code = 'ERR_JWS_INVALID';\n code = 'ERR_JWS_INVALID';\n}\nexport class JWTInvalid extends JOSEError {\n static code = 'ERR_JWT_INVALID';\n code = 'ERR_JWT_INVALID';\n}\nexport class JWKInvalid extends JOSEError {\n static code = 'ERR_JWK_INVALID';\n code = 'ERR_JWK_INVALID';\n}\nexport class JWKSInvalid extends JOSEError {\n static code = 'ERR_JWKS_INVALID';\n code = 'ERR_JWKS_INVALID';\n}\nexport class JWKSNoMatchingKey extends JOSEError {\n static code = 'ERR_JWKS_NO_MATCHING_KEY';\n code = 'ERR_JWKS_NO_MATCHING_KEY';\n constructor(message = 'no applicable key found in the JSON Web Key Set', options) {\n super(message, options);\n }\n}\nexport class JWKSMultipleMatchingKeys extends JOSEError {\n [Symbol.asyncIterator];\n static code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n constructor(message = 'multiple matching keys found in the JSON Web Key Set', options) {\n super(message, options);\n }\n}\nexport class JWKSTimeout extends JOSEError {\n static code = 'ERR_JWKS_TIMEOUT';\n code = 'ERR_JWKS_TIMEOUT';\n constructor(message = 'request timed out', options) {\n super(message, options);\n }\n}\nexport class JWSSignatureVerificationFailed extends JOSEError {\n static code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n constructor(message = 'signature verification failed', options) {\n super(message, options);\n }\n}\n","const isObjectLike = (value) => typeof value === 'object' && value !== null;\nexport function isObject(input) {\n if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') {\n return false;\n }\n if (Object.getPrototypeOf(input) === null) {\n return true;\n }\n let proto = input;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n return Object.getPrototypeOf(input) === proto;\n}\nexport function isDisjoint(...headers) {\n const sources = headers.filter(Boolean);\n if (sources.length === 0 || sources.length === 1) {\n return true;\n }\n let acc;\n for (const header of sources) {\n const parameters = Object.keys(header);\n if (!acc || acc.size === 0) {\n acc = new Set(parameters);\n continue;\n }\n for (const parameter of parameters) {\n if (acc.has(parameter)) {\n return false;\n }\n acc.add(parameter);\n }\n }\n return true;\n}\nexport const isJWK = (key) => isObject(key) && typeof key.kty === 'string';\nexport const isPrivateJWK = (key) => key.kty !== 'oct' &&\n ((key.kty === 'AKP' && typeof key.priv === 'string') || typeof key.d === 'string');\nexport const isPublicJWK = (key) => key.kty !== 'oct' && key.d === undefined && key.priv === undefined;\nexport const isSecretJWK = (key) => key.kty === 'oct' && typeof key.k === 'string';\n","import { JOSENotSupported } from '../util/errors.js';\nconst unsupportedAlg = 'Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value';\nfunction subtleMapping(jwk) {\n let algorithm;\n let keyUsages;\n switch (jwk.kty) {\n case 'AKP': {\n switch (jwk.alg) {\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n algorithm = { name: jwk.alg };\n keyUsages = jwk.priv ? ['sign'] : ['verify'];\n break;\n default:\n throw new JOSENotSupported(unsupportedAlg);\n }\n break;\n }\n case 'RSA': {\n switch (jwk.alg) {\n case 'PS256':\n case 'PS384':\n case 'PS512':\n algorithm = { name: 'RSA-PSS', hash: `SHA-${jwk.alg.slice(-3)}` };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'RS256':\n case 'RS384':\n case 'RS512':\n algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${jwk.alg.slice(-3)}` };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512':\n algorithm = {\n name: 'RSA-OAEP',\n hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`,\n };\n keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey'];\n break;\n default:\n throw new JOSENotSupported(unsupportedAlg);\n }\n break;\n }\n case 'EC': {\n switch (jwk.alg) {\n case 'ES256':\n case 'ES384':\n case 'ES512':\n algorithm = {\n name: 'ECDSA',\n namedCurve: { ES256: 'P-256', ES384: 'P-384', ES512: 'P-521' }[jwk.alg],\n };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW':\n algorithm = { name: 'ECDH', namedCurve: jwk.crv };\n keyUsages = jwk.d ? ['deriveBits'] : [];\n break;\n default:\n throw new JOSENotSupported(unsupportedAlg);\n }\n break;\n }\n case 'OKP': {\n switch (jwk.alg) {\n case 'Ed25519':\n case 'EdDSA':\n algorithm = { name: 'Ed25519' };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW':\n algorithm = { name: jwk.crv };\n keyUsages = jwk.d ? ['deriveBits'] : [];\n break;\n default:\n throw new JOSENotSupported(unsupportedAlg);\n }\n break;\n }\n default:\n throw new JOSENotSupported('Invalid or unsupported JWK \"kty\" (Key Type) Parameter value');\n }\n return { algorithm, keyUsages };\n}\nexport async function jwkToKey(jwk) {\n if (!jwk.alg) {\n throw new TypeError('\"alg\" argument is required when \"jwk.alg\" is not present');\n }\n const { algorithm, keyUsages } = subtleMapping(jwk);\n const keyData = { ...jwk };\n if (keyData.kty !== 'AKP') {\n delete keyData.alg;\n }\n delete keyData.use;\n return crypto.subtle.importKey('jwk', keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);\n}\n","import { decode as decodeBase64URL } from '../util/base64url.js';\nimport { fromSPKI, fromPKCS8, fromX509 } from '../lib/asn1.js';\nimport { jwkToKey } from '../lib/jwk_to_key.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport { isObject } from '../lib/type_checks.js';\nexport async function importSPKI(spki, alg, options) {\n if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) {\n throw new TypeError('\"spki\" must be SPKI formatted string');\n }\n return fromSPKI(spki, alg, options);\n}\nexport async function importX509(x509, alg, options) {\n if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) {\n throw new TypeError('\"x509\" must be X.509 formatted string');\n }\n return fromX509(x509, alg, options);\n}\nexport async function importPKCS8(pkcs8, alg, options) {\n if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) {\n throw new TypeError('\"pkcs8\" must be PKCS#8 formatted string');\n }\n return fromPKCS8(pkcs8, alg, options);\n}\nexport async function importJWK(jwk, alg, options) {\n if (!isObject(jwk)) {\n throw new TypeError('JWK must be an object');\n }\n let ext;\n alg ??= jwk.alg;\n ext ??= options?.extractable ?? jwk.ext;\n switch (jwk.kty) {\n case 'oct':\n if (typeof jwk.k !== 'string' || !jwk.k) {\n throw new TypeError('missing \"k\" (Key Value) Parameter value');\n }\n return decodeBase64URL(jwk.k);\n case 'RSA':\n if ('oth' in jwk && jwk.oth !== undefined) {\n throw new JOSENotSupported('RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported');\n }\n return jwkToKey({ ...jwk, alg, ext });\n case 'AKP': {\n if (typeof jwk.alg !== 'string' || !jwk.alg) {\n throw new TypeError('missing \"alg\" (Algorithm) Parameter value');\n }\n if (alg !== undefined && alg !== jwk.alg) {\n throw new TypeError('JWK alg and alg option value mismatch');\n }\n return jwkToKey({ ...jwk, ext });\n }\n case 'EC':\n case 'OKP':\n return jwkToKey({ ...jwk, alg, ext });\n default:\n throw new JOSENotSupported('Unsupported \"kty\" (Key Type) Parameter value');\n }\n}\n","/**\n * `oc.webhook.verify` — Ed25519 signature verification for me.ochk.io\n * webhook deliveries.\n *\n * Webhook envelopes are signed with the auth host's Ed25519 key. The\n * signature is sent as a hex string in the `OC-Signature` header, and\n * the kid is in the `OC-Key-Id` header.\n *\n * import { oc } from '@orangecheck/me-client';\n *\n * // In your webhook handler — pass RAW BODY BYTES, not the parsed\n * // JSON. Frameworks that re-serialize before your handler will\n * // produce a different byte sequence and the signature will not\n * // validate.\n * const result = await oc.webhook.verify(\n * rawBody, // string | Uint8Array\n * req.headers['oc-signature'], // hex\n * req.headers['oc-key-id'] // kid\n * );\n * if (!result.ok) return res.status(401).send(result.reason);\n *\n * The verifier auto-fetches and caches the webhook-signing JWKS at\n * `https://me.ochk.io/api/dev-jwks` for 1h. Pass `{ jwk }` to skip the\n * network round-trip if you've embedded the key.\n *\n * It used to fetch `https://ochk.io/.well-known/jwks.json` — the family\n * SESSION key, a different key for a different job — so every verification\n * that did not pass `{ jwk }` failed with `kid … not in JWKS` before it could\n * check anything.\n */\n\nimport { importJWK, type CryptoKey, type KeyObject } from 'jose';\n\n/** me.ochk.io signs its own webhook deliveries; the family auth host does not.\n * Its published key lives at /api/dev-jwks (the path is historical — the note\n * in that document names it as the production webhook-signing key). */\nconst DEFAULT_ISSUER = 'https://me.ochk.io';\nconst JWKS_PATH = '/api/dev-jwks';\nconst DEFAULT_TTL_MS = 60 * 60 * 1000;\n\nexport interface VerifyResult {\n ok: boolean;\n reason?: string;\n}\n\nexport interface OcPublicJwk {\n kty: 'OKP';\n crv: 'Ed25519';\n x: string;\n kid: string;\n alg?: 'EdDSA';\n use?: 'sig';\n}\n\nexport interface VerifyOptions {\n /** Override the auth host issuer. Defaults to https://ochk.io. */\n issuer?: string;\n /** Pass a JWK directly to skip the network fetch entirely. Useful\n * for tests, edge runtimes that can't fetch, or integrators that\n * ship the public key alongside their webhook handler. */\n jwk?: OcPublicJwk;\n /** JWKS cache TTL in ms. Defaults to 1 hour. Stale-on-error: a\n * transient JWKS outage falls back to the previous cached value\n * rather than rejecting every webhook. */\n jwksCacheTtlMs?: number;\n}\n\ntype AuthKey = CryptoKey | KeyObject;\n\ninterface JwksCacheEntry {\n keys: Record<string, AuthKey>;\n fetchedAt: number;\n}\n\nconst jwksCache = new Map<string, JwksCacheEntry>();\nconst inflight = new Map<string, Promise<JwksCacheEntry>>();\n\nasync function fetchJwks(issuer: string, ttlMs: number): Promise<JwksCacheEntry> {\n const cached = jwksCache.get(issuer);\n if (cached && Date.now() - cached.fetchedAt < ttlMs) return cached;\n const existing = inflight.get(issuer);\n if (existing) return existing;\n const p = (async (): Promise<JwksCacheEntry> => {\n try {\n const url = `${issuer.replace(/\\/$/, '')}${JWKS_PATH}`;\n const res = await fetch(url, { headers: { Accept: 'application/json' } });\n if (!res.ok) throw new Error(`JWKS fetch ${url} returned ${res.status}`);\n const json = (await res.json()) as { keys: OcPublicJwk[] };\n if (!json || !Array.isArray(json.keys)) {\n throw new Error(`JWKS at ${url} did not return {keys:[…]}`);\n }\n const keys: Record<string, AuthKey> = {};\n for (const k of json.keys) {\n if (typeof k.kid !== 'string') continue;\n try {\n keys[k.kid] = (await importJWK(k, 'EdDSA')) as AuthKey;\n } catch {\n /* skip keys that won't import */\n }\n }\n const entry: JwksCacheEntry = { keys, fetchedAt: Date.now() };\n jwksCache.set(issuer, entry);\n return entry;\n } catch (err) {\n const stale = jwksCache.get(issuer);\n if (stale) return stale;\n throw err;\n }\n })().finally(() => {\n inflight.delete(issuer);\n });\n inflight.set(issuer, p);\n return p;\n}\n\nfunction hexToBytes(hex: string): Uint8Array | null {\n if (typeof hex !== 'string') return null;\n const s = hex.trim();\n if (s.length === 0 || s.length % 2 !== 0) return null;\n const out = new Uint8Array(s.length / 2);\n for (let i = 0; i < out.length; i++) {\n const b = parseInt(s.slice(i * 2, i * 2 + 2), 16);\n if (Number.isNaN(b)) return null;\n out[i] = b;\n }\n return out;\n}\n\nfunction toBytes(input: string | Uint8Array): Uint8Array {\n if (typeof input === 'string') return new TextEncoder().encode(input);\n return input;\n}\n\nfunction toArrayBuffer(view: Uint8Array): ArrayBuffer {\n // SubtleCrypto's BufferSource type requires Uint8Array<ArrayBuffer>\n // (not ArrayBufferLike). Copy into a fresh ArrayBuffer so the\n // resulting buffer is statically typed as ArrayBuffer (slicing a\n // SharedArrayBuffer would yield SharedArrayBuffer which the type\n // system rejects).\n const buf = new ArrayBuffer(view.byteLength);\n new Uint8Array(buf).set(view);\n return buf;\n}\n\nasync function verifyEd25519(\n key: AuthKey,\n sig: Uint8Array,\n msg: Uint8Array\n): Promise<boolean> {\n // jose normalizes the key into a CryptoKey under WebCrypto-capable\n // runtimes (Node 20+, Vercel Edge, modern browsers); fall through\n // to subtle.verify for the actual signature check.\n const subtle =\n typeof globalThis.crypto !== 'undefined' && globalThis.crypto.subtle\n ? globalThis.crypto.subtle\n : null;\n if (!subtle) return false;\n try {\n return await subtle.verify(\n 'Ed25519',\n key as CryptoKey,\n toArrayBuffer(sig),\n toArrayBuffer(msg)\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Verify a webhook signature. Pass the raw body bytes (not parsed\n * JSON), the hex-encoded signature from the `OC-Signature` header, and\n * the kid from the `OC-Key-Id` header.\n *\n * Returns `{ ok: true }` on success, `{ ok: false, reason }` on any\n * failure (bad signature, kid not in JWKS, malformed signature,\n * network-only JWKS fetch failed without prior cache, etc.). Never\n * throws.\n */\nexport async function verify(\n rawBody: string | Uint8Array,\n sigHex: string,\n kid: string,\n options: VerifyOptions = {}\n): Promise<VerifyResult> {\n if (!sigHex) return { ok: false, reason: 'missing signature' };\n if (!kid) return { ok: false, reason: 'missing kid' };\n const sig = hexToBytes(sigHex);\n if (!sig) return { ok: false, reason: 'malformed signature (expected hex)' };\n const msg = toBytes(rawBody);\n\n let key: AuthKey | undefined;\n if (options.jwk) {\n if (options.jwk.kid !== kid) {\n return { ok: false, reason: `kid mismatch (header=${kid}, jwk=${options.jwk.kid})` };\n }\n try {\n key = (await importJWK(options.jwk, 'EdDSA')) as AuthKey;\n } catch {\n return { ok: false, reason: 'could not import provided jwk' };\n }\n } else {\n const issuer = options.issuer ?? DEFAULT_ISSUER;\n const ttl = options.jwksCacheTtlMs ?? DEFAULT_TTL_MS;\n try {\n let entry = await fetchJwks(issuer, ttl);\n key = entry.keys[kid];\n if (!key) {\n jwksCache.delete(issuer);\n entry = await fetchJwks(issuer, ttl);\n key = entry.keys[kid];\n }\n } catch (err) {\n return { ok: false, reason: `jwks unavailable: ${(err as Error).message}` };\n }\n if (!key) return { ok: false, reason: `kid ${kid} not in JWKS` };\n }\n\n const ok = await verifyEd25519(key, sig, msg);\n return ok ? { ok: true } : { ok: false, reason: 'signature does not match' };\n}\n\n/** Force-refresh the JWKS cache. Useful after a key rotation event\n * if you don't want to wait for the TTL to expire. */\nexport async function fetchJwksForce(issuer = DEFAULT_ISSUER): Promise<void> {\n jwksCache.delete(issuer);\n await fetchJwks(issuer, DEFAULT_TTL_MS);\n}\n\nexport const webhook = { verify, fetchJwks: fetchJwksForce };\n","/**\n * Federation directory · runtime discovery for the SDK.\n *\n * Consumes /api/federations from the configured origin (defaults to\n * me.ochk.io; override via `setOrigin()` for staging or self-hosted).\n * Multi-federation routing reads from this directory; v1 has one live\n * entry, but the SDK's shape is already plural so federation #2 is a\n * directory write rather than an SDK release.\n */\n\nimport { api } from './transport';\nimport type { Federation } from './types';\n\ninterface ListResponse {\n ok: boolean;\n federations: Federation[];\n}\n\n/** List every federation in the directory — recruiting, forming,\n * binding, and live. Consumers filter by status as needed. */\nasync function list(): Promise<Federation[]> {\n const res = await api<ListResponse>('/api/federations');\n return res.federations ?? [];\n}\n\n/** Return only federations currently accepting bindings — i.e.\n * status === 'live' with a non-null invite. The set the consumer\n * wallet provider can route a user wallet to. */\nasync function live(): Promise<Federation[]> {\n const all = await list();\n return all.filter((f) => f.status === 'live' && typeof f.invite === 'string' && f.invite.length > 0);\n}\n\n/** Look up a single federation by slug. Returns null if the slug\n * isn't in the directory. */\nasync function get(slug: string): Promise<Federation | null> {\n const all = await list();\n return all.find((f) => f.slug === slug) ?? null;\n}\n\n/** Default federation a fresh user/integrator should bind to when no\n * explicit policy exists yet. v1: the first live federation in the\n * directory; falls back to null if none live yet. v2+: routing\n * policy (geography, capacity, explicit choice) consults the\n * directory directly. */\nasync function defaultLive(): Promise<Federation | null> {\n const all = await live();\n return all[0] ?? null;\n}\n\nexport const federations = { list, live, get, defaultLive };\n","/**\n * `oc.scope` — privacy-preserving scope grants.\n *\n * Background:\n * By default, signing into your site via OC reveals only an anonymous\n * per-integrator subject (`sub`). The user's master identity (BIP-322\n * address or email) stays private; you cannot correlate users across\n * sites via OC. To read additional fields (their email, attest tier,\n * bitcoin address, display name), you must explicitly request the\n * matching scope and the user must explicitly consent.\n *\n * Full architecture: https://github.com/orangecheck/oc-me-web/blob/main/PRIVACY-ARCHITECTURE.md\n *\n * Two functions:\n *\n * oc.scope.granted(project_key) — read what the currently-signed-in\n * user has already granted. Returns sub + per-scope values they've\n * consented to.\n *\n * const { sub, scopes } = await oc.scope.granted({ project_key: 'pk_live_yourcompany' });\n * console.log(sub); // \"sub_3K7xQ2mN1pYwB8tRvE…\"\n * console.log(scopes.email); // \"user@example.com\" or undefined\n *\n * oc.scope.request(scopes, opts) — redirect the user to me.ochk.io's\n * consent prompt. After they grant or deny, browser returns to\n * return_to. Subsequent oc.scope.granted() calls reflect their\n * decisions.\n *\n * await oc.scope.request(['email', 'attest_tier'], {\n * project_key: 'pk_live_yourcompany',\n * return_to: window.location.href,\n * });\n */\n\nimport { api, getOrigin } from './transport';\n\n/** Catalog of valid scopes · keep in sync with SCOPE_IDS in\n * oc-me-web/src/lib/privacy/scopes.ts.\n *\n * cross_integrator_event_count · per OCHK-V2-PLAN §7 · low-info\n * sybil signal aggregating event count across every integrator.\n * cross_integrator_human_event_count · per OCHK-V3-PLAN §7 · same\n * aggregate filtered to is_agent !== true (human-fired only).\n * Use when you want to gate on real human activity rather than\n * bot-padded counts.\n * trust_attestation_count · per OCHK-V3-PLAN §6 phase-2 · four-int\n * selective-disclosure quad summarizing reputation-graph attestations.\n * Use parseTrustAttestationCount() to decode the wire-format string. */\nexport type Scope =\n | 'bitcoin_address'\n | 'email'\n | 'attest_tier'\n | 'display_name'\n | 'cross_integrator_event_count'\n | 'cross_integrator_human_event_count'\n | 'trust_attestation_count';\n\nconst VALID_SCOPES: ReadonlyArray<Scope> = [\n 'bitcoin_address',\n 'email',\n 'attest_tier',\n 'display_name',\n 'cross_integrator_event_count',\n 'cross_integrator_human_event_count',\n 'trust_attestation_count',\n];\n\n/** Decoded shape of the `trust_attestation_count` scope value. The wire\n * format is a comma-separated quad: total,good,distinct_good_issuers,caution.\n * Block-status counts are intentionally omitted from the disclosure\n * surface — block flags belong to the pseudonymous-issuer side, not\n * the subject's public score. */\nexport interface TrustAttestationCount {\n total: number;\n good: number;\n distinct_good_issuers: number;\n caution: number;\n}\n\n/** Decode the `trust_attestation_count` scope's wire-format string into\n * a typed quad. Returns null if the input is malformed (defensive ·\n * the resolver always emits well-formed strings, but third-party\n * consumers may hand us anything). */\nexport function parseTrustAttestationCount(value: string): TrustAttestationCount | null {\n const parts = value.split(',');\n if (parts.length !== 4) return null;\n const ints = parts.map((p) => Number.parseInt(p, 10));\n if (ints.some((n) => !Number.isInteger(n) || n < 0)) return null;\n return {\n total: ints[0]!,\n good: ints[1]!,\n distinct_good_issuers: ints[2]!,\n caution: ints[3]!,\n };\n}\n\nexport interface GrantedOptions {\n /** Your project_key. Required. */\n project_key: string;\n signal?: AbortSignal;\n}\n\nexport interface GrantedResult {\n /** Per-integrator stable subject for the currently-signed-in user.\n * This is what your backend should key user records on (NOT the\n * master addr · which OC doesn't reveal). */\n sub: string;\n /** Scopes the user has actively granted to this project. Subset of\n * the requested scopes, filtered for not-revoked + not-expired. */\n scopes_granted: Scope[];\n /** Resolved values for the granted scopes. Only fields whose scope\n * is in `scopes_granted` are present. */\n scopes: Partial<Record<Scope, string>>;\n}\n\nasync function granted(options: GrantedOptions): Promise<GrantedResult> {\n if (!options.project_key) {\n throw new Error('oc.scope.granted: project_key is required');\n }\n const r = await api<{ ok: boolean; sub: string; scopes_granted: Scope[]; scopes: Partial<Record<Scope, string>> }>(\n `/api/integrator/scopes/${encodeURIComponent(options.project_key)}`,\n { method: 'GET', signal: options.signal }\n );\n return {\n sub: r.sub,\n scopes_granted: r.scopes_granted,\n scopes: r.scopes,\n };\n}\n\nexport interface RequestOptions {\n /** Your project_key. Required. */\n project_key: string;\n /** Where to bounce the user after they decide. Required.\n * Same-origin only — me.ochk.io rejects cross-origin redirects to\n * prevent the consent prompt from being weaponized in phishing. */\n return_to: string;\n /** Override the OC origin (only useful for staging deployments;\n * defaults to https://me.ochk.io via getOrigin()). */\n origin?: string;\n}\n\n/** Redirect the user to me.ochk.io's consent prompt. After they decide,\n * browser returns to `return_to`. The scope grants are persisted\n * server-side; subsequent calls to oc.scope.granted() reflect their\n * decisions.\n *\n * This function does NOT return a promise that resolves to the user's\n * decisions. The redirect leaves your page; the user lands back at\n * return_to and your code re-reads granted state on mount.\n *\n * Consent flow:\n * 1. Your code: oc.scope.request(['email'], { ... })\n * 2. Browser navigates to me.ochk.io/me/scope-grant?…\n * 3. User decides per-scope (grant once / always / deny)\n * 4. Browser redirects back to return_to\n * 5. Your code re-runs oc.scope.granted(...) on mount\n *\n * Throws synchronously if the inputs are invalid (so the redirect is\n * never issued with malformed params). */\nexport function request(scopes: Scope[], options: RequestOptions): never {\n if (!options.project_key) {\n throw new Error('oc.scope.request: project_key is required');\n }\n if (!options.return_to) {\n throw new Error('oc.scope.request: return_to is required');\n }\n if (!Array.isArray(scopes) || scopes.length === 0) {\n throw new Error('oc.scope.request: scopes must be a non-empty array');\n }\n for (const s of scopes) {\n if (!VALID_SCOPES.includes(s)) {\n throw new Error(\n `oc.scope.request: unknown scope \"${s}\" · valid: ${VALID_SCOPES.join(', ')}`\n );\n }\n }\n if (typeof window === 'undefined') {\n throw new Error('oc.scope.request: must be called in a browser environment');\n }\n const origin = options.origin ?? getOrigin();\n const url = new URL('/me/scope-grant', origin);\n url.searchParams.set('project_key', options.project_key);\n url.searchParams.set('scopes', scopes.join(','));\n url.searchParams.set('return_to', options.return_to);\n window.location.assign(url.toString());\n // assign() doesn't return synchronously in a way TS can encode, but\n // by the time anything else runs, navigation is in flight. Throw to\n // make the never-returning behavior explicit.\n throw new Error('oc.scope.request: redirected to consent prompt');\n}\n\nexport const scope = { granted, request, parseTrustAttestationCount };\n","/**\n * `oc.family` — cross-family scope grants.\n *\n * Per OCHK-V3-PLAN §10 phase-1. The OrangeCheck family is one auth host\n * (ochk.io) and a set of sibling products (vote.ochk.io, stamp.ochk.io,\n * agent.ochk.io, attest.ochk.io, lock.ochk.io). When a user grants a\n * cross-family scope to a sibling, that grant is stored on me.ochk.io\n * under a reserved `family:<verb>` project_key.\n *\n * Sibling-side surfaces use `oc.family.scopes('oc-vote')` to consult\n * the active grants the user has issued for their product. The helper\n * is structurally identical to `oc.scope.granted({ project_key })`\n * except that the project_key is implied from the verb.\n *\n * const { sub, scopes } = await oc.family.scopes('oc-vote');\n * if (scopes.cross_integrator_human_event_count) {\n * gateBallot(parseInt(scopes.cross_integrator_human_event_count, 10));\n * }\n *\n * Auth: the user's `oc_session` cookie (Domain=.ochk.io) carries\n * authenticate-once-anywhere across the family. The fetch goes against\n * the me.ochk.io origin with credentials.\n *\n * Same auto-renew behavior as the integrator-side `oc.scope.granted`:\n * a sibling consulting cross-family scopes counts as use, so a granting\n * user who interacts with a sibling regularly won't see their grant\n * expire from under them (per V3-PLAN §5).\n */\n\nimport type { Scope } from './scope';\n\nexport type FamilyVerb = 'oc-vote' | 'oc-stamp' | 'oc-agent' | 'oc-attest' | 'oc-lock' | 'oc-pledge';\n\nconst VALID_VERBS: ReadonlyArray<FamilyVerb> = [\n 'oc-vote',\n 'oc-stamp',\n 'oc-agent',\n 'oc-attest',\n 'oc-lock',\n 'oc-pledge',\n];\n\nexport interface FamilyScopesOptions {\n /** Override the OC family origin · only useful for staging.\n * Defaults to https://me.ochk.io · the family-side scope reads\n * always go to me.ochk regardless of which sibling is calling. */\n origin?: string;\n signal?: AbortSignal;\n}\n\nexport interface FamilyScopesResult {\n /** Per-sibling stable subject for the currently-signed-in user.\n * Anonymous · derived from master_addr + the family:<verb>\n * project_key. Sibling backends key on this. */\n sub: string;\n /** Sibling product the grants are scoped to (echoed for logging /\n * debug). */\n family_product: {\n verb: FamilyVerb;\n name: string;\n origin: string;\n };\n /** Scopes the user has actively granted to this sibling. Subset of\n * the requested set, filtered for not-revoked + not-expired. */\n scopes_granted: Scope[];\n /** Resolved values for the granted scopes. Only fields whose scope\n * is in `scopes_granted` are present. */\n scopes: Partial<Record<Scope, string>>;\n}\n\n/**\n * Read the cross-family scope grants the user has issued to the named\n * sibling product. Browser-side · uses cookie credentials.\n *\n * Errors thrown:\n * - `unknown_family_verb` if `verb` is not in the family allowlist\n * - `sign in required` (401) if no oc_session cookie present\n * - `unknown_family_verb` (404) if me.ochk doesn't recognize the verb\n *\n * If you need to drive a consent prompt for a verb the user hasn't\n * granted yet, use `oc.scope.request(scopes, { project_key:\n * 'family:<verb>', return_to })` — the consent prompt page detects the\n * `family:` prefix and renders the sibling-product chrome.\n */\nasync function scopes(verb: FamilyVerb, options?: FamilyScopesOptions): Promise<FamilyScopesResult> {\n if (!VALID_VERBS.includes(verb)) {\n throw new Error(\n `oc.family.scopes: unknown verb \"${verb}\" · valid: ${VALID_VERBS.join(', ')}`\n );\n }\n const origin = options?.origin ?? 'https://me.ochk.io';\n const url = `${origin}/api/family/scopes/${encodeURIComponent(verb)}`;\n const res = await fetch(url, {\n method: 'GET',\n credentials: 'include',\n signal: options?.signal,\n });\n if (!res.ok) {\n const txt = await res.text().catch(() => '');\n throw new Error(`oc.family.scopes: ${res.status} ${txt || res.statusText}`);\n }\n const json = (await res.json()) as FamilyScopesResult & { ok?: boolean };\n return {\n sub: json.sub,\n family_product: json.family_product,\n scopes_granted: json.scopes_granted,\n scopes: json.scopes,\n };\n}\n\nexport const family = { scopes };\n","/**\n * `oc.identity.verifyActivityAttestation` — one-call ed25519 verifier\n * for a /api/me/activity-attestation bundle.\n *\n * Cashes the \"trivially to verify\" strategic claim: an integrator\n * receiving a signed attestation JSON from a user calls one function,\n * gets a typed result with per-check detail, never reaches into\n * @noble/curves or jose themselves.\n *\n * import { oc } from '@orangecheck/me-client';\n *\n * const result = await oc.identity.verifyActivityAttestation(bundle);\n * if (!result.ok) return res.status(401).send(result.reason);\n * // result.attestation is typed · safe to gate on lifetime_sats etc.\n *\n * The JWKS issuer is me.ochk.io (the envelope key), DISTINCT from\n * the auth host's ochk.io JWKS that signs webhooks. Same Ed25519\n * curve, same kid lookup pattern, fetched + cached separately.\n */\n\nimport { importJWK, type CryptoKey, type KeyObject } from 'jose';\n\nconst DEFAULT_ISSUER = 'https://me.ochk.io';\nconst DEFAULT_TTL_MS = 60 * 60 * 1000;\nconst ENVELOPE_JWKS_PATH = '/.well-known/oc-envelope-jwks.json';\n\nexport interface ActivityAttestation {\n id: string;\n v: 1;\n kind: 'oc-me-activity';\n did_oc: string;\n event_count: number;\n human_event_count: number;\n lifetime_sats: number;\n distinct_integrator_count: number;\n oldest_event_at: string | null;\n active_days: number;\n computed_at: string;\n expires_at: string;\n}\n\nexport interface ActivityAttestationBundle {\n attestation: ActivityAttestation;\n sig: string;\n kid: string;\n canonical_b64: string;\n}\n\nexport interface ActivityVerifyCheck {\n ok: boolean;\n label: string;\n detail?: string;\n}\n\nexport interface ActivityVerifyResult {\n ok: boolean;\n reason?: string;\n attestation?: ActivityAttestation;\n checks: ActivityVerifyCheck[];\n}\n\ninterface OcEnvelopePublicJwk {\n kty: 'OKP';\n crv: 'Ed25519';\n x: string;\n kid: string;\n alg?: 'EdDSA';\n use?: 'sig';\n}\n\nexport interface VerifyActivityOptions {\n /** Override the me.ochk.io issuer (defaults to https://me.ochk.io).\n * Useful for staging / self-hosted dev. */\n issuer?: string;\n /** Pass a JWK directly to skip the network fetch · convenient when\n * embedding the public key in your service for air-gapped or\n * edge-runtime deployments. */\n jwk?: OcEnvelopePublicJwk;\n /** JWKS cache TTL in ms. Defaults to 1h. Stale-on-error falls back\n * to the previous cached value. */\n jwksCacheTtlMs?: number;\n /** Optional · override \"now\" for deterministic tests. */\n now?: Date;\n}\n\ntype AuthKey = CryptoKey | KeyObject;\n\ninterface JwksCacheEntry {\n keys: Record<string, AuthKey>;\n fetchedAt: number;\n}\n\nconst jwksCache = new Map<string, JwksCacheEntry>();\nconst inflight = new Map<string, Promise<JwksCacheEntry>>();\n\nasync function fetchEnvelopeJwks(issuer: string, ttlMs: number): Promise<JwksCacheEntry> {\n const cached = jwksCache.get(issuer);\n if (cached && Date.now() - cached.fetchedAt < ttlMs) return cached;\n const existing = inflight.get(issuer);\n if (existing) return existing;\n const p = (async (): Promise<JwksCacheEntry> => {\n try {\n const url = `${issuer.replace(/\\/$/, '')}${ENVELOPE_JWKS_PATH}`;\n const res = await fetch(url, { headers: { Accept: 'application/json' } });\n if (!res.ok) throw new Error(`envelope JWKS fetch ${url} returned ${res.status}`);\n const json = (await res.json()) as { keys: OcEnvelopePublicJwk[] };\n if (!json || !Array.isArray(json.keys)) {\n throw new Error(`envelope JWKS at ${url} did not return {keys:[…]}`);\n }\n const keys: Record<string, AuthKey> = {};\n for (const k of json.keys) {\n if (typeof k.kid !== 'string') continue;\n try {\n keys[k.kid] = (await importJWK(k, 'EdDSA')) as AuthKey;\n } catch {\n /* skip keys that won't import */\n }\n }\n const entry: JwksCacheEntry = { keys, fetchedAt: Date.now() };\n jwksCache.set(issuer, entry);\n return entry;\n } catch (err) {\n const stale = jwksCache.get(issuer);\n if (stale) return stale;\n throw err;\n }\n })().finally(() => {\n inflight.delete(issuer);\n });\n inflight.set(issuer, p);\n return p;\n}\n\nfunction hexToBytes(hex: string): Uint8Array | null {\n if (typeof hex !== 'string') return null;\n const s = hex.trim();\n if (s.length === 0 || s.length % 2 !== 0) return null;\n const out = new Uint8Array(s.length / 2);\n for (let i = 0; i < out.length; i++) {\n const b = parseInt(s.slice(i * 2, i * 2 + 2), 16);\n if (Number.isNaN(b)) return null;\n out[i] = b;\n }\n return out;\n}\n\nfunction base64ToBytes(b64: string): Uint8Array | null {\n try {\n const bin =\n typeof atob === 'function'\n ? atob(b64)\n : Buffer.from(b64, 'base64').toString('binary');\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n } catch {\n return null;\n }\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n let out = '';\n for (const b of bytes) out += b.toString(16).padStart(2, '0');\n return out;\n}\n\nasync function sha256(bytes: Uint8Array): Promise<Uint8Array> {\n const subtle =\n typeof globalThis.crypto !== 'undefined' && globalThis.crypto.subtle\n ? globalThis.crypto.subtle\n : null;\n if (!subtle) {\n throw new Error('crypto.subtle unavailable · need Node 20+ / modern browser / Edge runtime');\n }\n const buf = await subtle.digest('SHA-256', bytes as unknown as ArrayBuffer);\n return new Uint8Array(buf);\n}\n\nfunction toArrayBuffer(view: Uint8Array): ArrayBuffer {\n const buf = new ArrayBuffer(view.byteLength);\n new Uint8Array(buf).set(view);\n return buf;\n}\n\nasync function verifyEd25519(\n key: AuthKey,\n sig: Uint8Array,\n msg: Uint8Array\n): Promise<boolean> {\n const subtle =\n typeof globalThis.crypto !== 'undefined' && globalThis.crypto.subtle\n ? globalThis.crypto.subtle\n : null;\n if (!subtle) return false;\n try {\n return await subtle.verify(\n 'Ed25519',\n key as CryptoKey,\n toArrayBuffer(sig),\n toArrayBuffer(msg)\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Verify a signed activity attestation bundle. Returns a typed\n * ActivityVerifyResult with per-check detail · never throws (network\n * + parse failures surface as ok=false rows in the checks array, so\n * the caller can log them without try/catch).\n *\n * Five checks, in order: bundle shape, canonical-bytes hash matches\n * id, JWK with matching kid present, ed25519 signature, freshness.\n */\nexport async function verifyActivityAttestation(\n bundle: ActivityAttestationBundle,\n options: VerifyActivityOptions = {}\n): Promise<ActivityVerifyResult> {\n const checks: ActivityVerifyCheck[] = [];\n\n // 1. Bundle shape\n const shapeOk =\n !!bundle &&\n typeof bundle === 'object' &&\n typeof bundle.sig === 'string' &&\n typeof bundle.kid === 'string' &&\n typeof bundle.canonical_b64 === 'string' &&\n !!bundle.attestation &&\n typeof bundle.attestation.id === 'string' &&\n typeof bundle.attestation.expires_at === 'string';\n checks.push({\n ok: shapeOk,\n label: 'bundle shape · sig / kid / canonical_b64 / attestation',\n });\n if (!shapeOk) {\n return { ok: false, reason: 'bundle shape invalid', checks };\n }\n\n const a = bundle.attestation;\n\n // 2. canonical_b64 decodes\n const canonical = base64ToBytes(bundle.canonical_b64);\n checks.push({\n ok: canonical !== null,\n label: 'canonical_b64 decodes',\n detail: canonical ? `${canonical.length} bytes` : 'invalid base64',\n });\n if (!canonical) return { ok: false, reason: 'canonical_b64 invalid base64', checks, attestation: a };\n\n // 3. sha256 === id\n const digest = await sha256(canonical);\n const computedId = bytesToHex(digest);\n const idOk = computedId === a.id;\n checks.push({\n ok: idOk,\n label: 'sha256(canonical_bytes) === id',\n detail: idOk ? a.id : `expected ${a.id}, got ${computedId}`,\n });\n if (!idOk) return { ok: false, reason: 'id does not match canonical-bytes hash', checks, attestation: a };\n\n // 4. JWK lookup + ed25519 verify\n let key: AuthKey | null = null;\n if (options.jwk) {\n if (options.jwk.kid !== bundle.kid) {\n checks.push({\n ok: false,\n label: 'JWK with matching kid present',\n detail: `provided jwk.kid=${options.jwk.kid} but bundle.kid=${bundle.kid}`,\n });\n return { ok: false, reason: 'kid mismatch with provided jwk', checks, attestation: a };\n }\n try {\n key = (await importJWK(options.jwk, 'EdDSA')) as AuthKey;\n checks.push({ ok: true, label: 'JWK with matching kid present', detail: `kid ${bundle.kid} (provided)` });\n } catch (err) {\n checks.push({\n ok: false,\n label: 'JWK with matching kid present',\n detail: `provided jwk failed import: ${(err as Error).message}`,\n });\n return { ok: false, reason: 'provided jwk failed import', checks, attestation: a };\n }\n } else {\n const issuer = options.issuer ?? DEFAULT_ISSUER;\n const ttl = options.jwksCacheTtlMs ?? DEFAULT_TTL_MS;\n try {\n let entry = await fetchEnvelopeJwks(issuer, ttl);\n key = entry.keys[bundle.kid] ?? null;\n if (!key) {\n // Cache miss · likely a rotation. Force-refresh once.\n jwksCache.delete(issuer);\n entry = await fetchEnvelopeJwks(issuer, ttl);\n key = entry.keys[bundle.kid] ?? null;\n }\n checks.push({\n ok: !!key,\n label: 'JWK with matching kid present',\n detail: key ? `kid ${bundle.kid}` : `no JWK with kid ${bundle.kid} at ${issuer}${ENVELOPE_JWKS_PATH}`,\n });\n if (!key) {\n return { ok: false, reason: `kid ${bundle.kid} not in envelope JWKS`, checks, attestation: a };\n }\n } catch (err) {\n checks.push({\n ok: false,\n label: 'JWK with matching kid present',\n detail: `envelope JWKS unavailable: ${(err as Error).message}`,\n });\n return {\n ok: false,\n reason: `envelope JWKS unavailable: ${(err as Error).message}`,\n checks,\n attestation: a,\n };\n }\n }\n\n const sigBytes = hexToBytes(bundle.sig);\n if (!sigBytes) {\n checks.push({\n ok: false,\n label: 'ed25519.verify(sig, canonical_bytes, jwk.public)',\n detail: 'malformed sig (expected hex)',\n });\n return { ok: false, reason: 'malformed sig', checks, attestation: a };\n }\n const sigOk = await verifyEd25519(key, sigBytes, canonical);\n checks.push({\n ok: sigOk,\n label: 'ed25519.verify(sig, canonical_bytes, jwk.public)',\n detail: sigOk ? 'signature valid' : 'signature does not match',\n });\n if (!sigOk) return { ok: false, reason: 'signature does not match', checks, attestation: a };\n\n // 5. Freshness\n const now = options.now ?? new Date();\n const expiresMs = Date.parse(a.expires_at);\n const freshOk = Number.isFinite(expiresMs) && expiresMs > now.getTime();\n checks.push({\n ok: freshOk,\n label: 'now < attestation.expires_at',\n detail: freshOk\n ? `expires ${new Date(expiresMs).toISOString()}`\n : 'attestation has expired',\n });\n if (!freshOk) return { ok: false, reason: 'attestation has expired', checks, attestation: a };\n\n return { ok: true, attestation: a, checks };\n}\n\n/** Force-refresh the envelope-JWKS cache · useful after a key rotation\n * if you don't want to wait for the TTL to expire. */\nexport async function refreshEnvelopeJwks(issuer = DEFAULT_ISSUER): Promise<void> {\n jwksCache.delete(issuer);\n await fetchEnvelopeJwks(issuer, DEFAULT_TTL_MS);\n}\n\nexport const identity = {\n verifyActivityAttestation,\n refreshEnvelopeJwks,\n};\n","/**\n * Rich metadata for every billable event subtype.\n *\n * The SDK already exports the `EventSubtype` union (closed enum, type-\n * checked), but a new integrator picking between\n * `'scoped_action_authorization'` and `'stamp_signing'` and\n * `'attest_verification_at_gate'` has no inline guidance on which fits\n * their flow. This file is the canonical \"when do I use this subtype\"\n * reference, programmatically accessible:\n *\n * import { oc, EVENT_SUBTYPES } from '@orangecheck/me-client';\n *\n * for (const meta of Object.values(EVENT_SUBTYPES)) {\n * console.log(`${meta.id} (class ${meta.class}) — ${meta.fires_when}`);\n * }\n *\n * Or per-subtype:\n *\n * const meta = EVENT_SUBTYPES.account_creation;\n * console.log(meta.example); // → \"user signed up via email-OTP and the account row was inserted\"\n *\n * Used by `oc.config.fromTemplate()` to assemble archetype configs and\n * by /me/projects/* dashboards to drive consent prompts and config\n * editor labels from a single source.\n */\n\nimport type { EventClass, EventSubtype } from './types';\n\nexport interface EventSubtypeMetadata {\n id: EventSubtype;\n class: EventClass;\n /** Short label · matches SUBTYPE_LABELS on the server. */\n label: string;\n /** When this fires · imperative-mood plain English. The integrator\n * reads this to know which event in their codebase should call\n * `oc.event.fire()` with this subtype. */\n fires_when: string;\n /** A concrete example from a typical SaaS · helps integrators map\n * an unfamiliar subtype name to a real flow they recognize. */\n example: string;\n /** Common use cases · lets integrators search their own product\n * for matching flows. Two-three terms each, lowercase. */\n common_use_cases: readonly string[];\n /** What an integrator typically pays for this subtype, anchored at\n * $1 ≈ 1052 sats. Returns null for percent-of-amount subtypes\n * where the price scales with the underlying transaction. */\n typical_price_hint: string;\n}\n\nexport const EVENT_SUBTYPES: Record<EventSubtype, EventSubtypeMetadata> = {\n // ── Class A · durable state transitions ──\n account_creation: {\n id: 'account_creation',\n class: 'A',\n label: 'account creation',\n fires_when:\n 'a new oc identity creates a durable account record on your surface (first sign-in, profile row inserted)',\n example: 'user signed up via email-OTP and your account row was inserted in your DB',\n common_use_cases: ['onboarding', 'signup', 'registration', 'first-login'],\n typical_price_hint: '~1300 sats (~$1.24)',\n },\n account_recovery: {\n id: 'account_recovery',\n class: 'A',\n label: 'account recovery',\n fires_when:\n 'a user re-binds an existing account to a new device or recovery method',\n example: 'user lost their device and recovered the account via email OTP + recovery code',\n common_use_cases: ['recovery', 'device-rebind', 'restore-access'],\n typical_price_hint: '~650 sats (~$0.62)',\n },\n attest_bond_increased: {\n id: 'attest_bond_increased',\n class: 'A',\n label: 'attest bond increased',\n fires_when:\n 'a user upgrades their bond size (locks more sats to attest_tier=bonded with higher cap)',\n example: 'user moved from 10k-sat bond to 100k-sat bond to clear your higher-trust gate',\n common_use_cases: ['bond-upgrade', 'tier-promotion', 'sybil-resistance'],\n typical_price_hint: '~1600 sats (~$1.52) · OFF by default',\n },\n payment_method_connected: {\n id: 'payment_method_connected',\n class: 'A',\n label: 'payment method connected',\n fires_when:\n 'a user connects a Lightning address, BIP-322 wallet, or payment-routing channel to their account',\n example: 'user pasted a lightning@address.com receive address into their profile',\n common_use_cases: ['payment-setup', 'wallet-connect', 'payout-config'],\n typical_price_hint: '~320 sats (~$0.30)',\n },\n agent_delegation_issued: {\n id: 'agent_delegation_issued',\n class: 'A',\n label: 'agent delegation issued',\n fires_when:\n 'a user signs an oc-agent delegation envelope authorizing an AI agent to act on their behalf',\n example: 'user delegated a \"summarize my emails\" agent for 24 hours with scope email:read',\n common_use_cases: ['agent-grant', 'ai-delegation', 'scoped-authorization'],\n typical_price_hint: '~320 sats · OFF by default (power-user)',\n },\n recovery_method_updated: {\n id: 'recovery_method_updated',\n class: 'A',\n label: 'recovery method updated',\n fires_when:\n 'a user changes their recovery email, recovery key, or social-recovery contacts',\n example: 'user rotated their recovery email after a phone change',\n common_use_cases: ['recovery-rotation', 'security-update'],\n typical_price_hint: '~160 sats (~$0.15)',\n },\n\n // ── Class B · action-bound ──\n payment_authorization: {\n id: 'payment_authorization',\n class: 'B',\n label: 'payment authorized',\n fires_when:\n 'a user authorizes a payment of underlying value (Lightning, on-chain BTC, or fiat-quoted)',\n example: 'user paid $5.00 (≈5260 sats) for a premium feature on your site',\n common_use_cases: ['payment', 'checkout', 'paywall', 'subscription'],\n typical_price_hint: '0.75% of payment amount (percent_of_amount)',\n },\n scoped_action_authorization: {\n id: 'scoped_action_authorization',\n class: 'B',\n label: 'scoped action authorized',\n fires_when:\n 'a user takes a specific action your site bills on (post, vote, comment, claim) where each instance is meaningful',\n example: 'user posted a long-form review that earns them sats from your editorial budget',\n common_use_cases: ['post', 'vote', 'comment', 'claim', 'submit'],\n typical_price_hint: '~100 sats (~$0.10)',\n },\n attest_verification_at_gate: {\n id: 'attest_verification_at_gate',\n class: 'B',\n label: 'attest verification',\n fires_when:\n \"your site's gate consulted the user's attest_tier and admitted them (counted only when admitted)\",\n example: 'admin gate checked attest_tier=bonded with bond≥10k sats and granted access',\n common_use_cases: ['gate-check', 'tier-gate', 'sybil-filter'],\n typical_price_hint: '~280 sats (~$0.27) · OFF by default',\n },\n stamp_signing: {\n id: 'stamp_signing',\n class: 'B',\n label: 'stamp signed',\n fires_when:\n 'a user signs an oc-stamp envelope (provenance attestation, review credential, content stamp)',\n example: 'user stamped their published recipe with their oc identity for downstream verification',\n common_use_cases: ['provenance', 'review', 'credential', 'attestation'],\n typical_price_hint: '~55 sats (~$0.05) · OFF by default',\n },\n pledge_resolution: {\n id: 'pledge_resolution',\n class: 'B',\n label: 'pledge resolved',\n fires_when:\n 'an oc-pledge bonded commitment resolves on your surface (kept / broken / disputed / expired_unresolved). pledge bonds never move — any sat payout is an integrator-composed flow on top of pledge (e.g., HTLC), not a pledge primitive (oc-pledge-protocol WHY.md H7)',\n example:\n 'user staked sats × days-unspent on a prediction; the pledge resolved kept and the integrator paid out per its own composed terms',\n common_use_cases: ['pledge', 'staking', 'resolution', 'commit-reveal'],\n typical_price_hint: '1% of pledge bond amount (percent_of_amount) · OFF by default',\n },\n\n // ── Class C · session ──\n session_creation: {\n id: 'session_creation',\n class: 'C',\n label: 'session opened',\n fires_when:\n 'a fresh authenticated session is opened for a returning user (sign-in within an existing session is FREE)',\n example: 'user signed in after their last session expired; new session token issued',\n common_use_cases: ['sign-in', 'session', 'authenticate'],\n typical_price_hint: '~55 sats (~$0.05)',\n },\n};\n\n/** All subtypes for a given class · convenience accessor. */\nexport function subtypesForClass(cls: EventClass): EventSubtypeMetadata[] {\n return Object.values(EVENT_SUBTYPES).filter((m) => m.class === cls);\n}\n\n/** All subtypes as a flat list, ordered class A → B → C. */\nexport const ALL_EVENT_SUBTYPES: readonly EventSubtypeMetadata[] = [\n ...subtypesForClass('A'),\n ...subtypesForClass('B'),\n ...subtypesForClass('C'),\n];\n","/**\n * @orangecheck/me-client\n *\n * Drop-in client for me.ochk.io. Sign-in-with-OC. You pay for sessions\n * and actions, not for clicks.\n *\n * Three entry points for three audiences:\n *\n * import { ... } from '@orangecheck/me-client' // React surface\n * import { ... } from '@orangecheck/me-client/server' // server-side\n * verification\n * (Next.js, Express,\n * Hono — all without\n * env vars or JWK\n * handling)\n * import { signInWithOc } from '@orangecheck/me-client/popup'\n * // browser-only popup\n * orchestrator\n *\n * Server-side verification example:\n *\n * // pages/api/me.ts\n * import { withOcAuth } from '@orangecheck/me-client/server';\n *\n * export default withOcAuth(async (req, res) => {\n * if (!req.ocSession) return res.status(401).json({ ok: false });\n * res.status(200).json({ address: req.ocSession.did_oc });\n * });\n *\n * Popup signin example:\n *\n * import { signInWithOc } from '@orangecheck/me-client/popup';\n *\n * button.addEventListener('click', async () => {\n * const result = await signInWithOc();\n * if (!result) return; // user cancelled\n * localStorage.setItem('oc-token', result.token);\n * location.assign('/dashboard');\n * });\n */\n\nexport { OcSignInButton } from './SignInButton';\nexport type { OcSignInButtonProps } from './SignInButton';\n\nexport { session, onTelemetry } from './session';\nexport { payment } from './payment';\nexport { event } from './event';\nexport type { FireEventOptions, VerifyEventResult } from './event';\nexport { config } from './config';\nexport { webhook } from './webhook';\nexport type { OcPublicJwk, VerifyOptions, VerifyResult } from './webhook';\nexport { federations } from './federations';\nexport { scope, parseTrustAttestationCount } from './scope';\nexport type {\n Scope,\n GrantedOptions,\n GrantedResult,\n RequestOptions,\n TrustAttestationCount,\n} from './scope';\nexport { family } from './family';\nexport type { FamilyVerb, FamilyScopesOptions, FamilyScopesResult } from './family';\nexport {\n identity,\n verifyActivityAttestation,\n refreshEnvelopeJwks,\n} from './identity';\nexport type {\n ActivityAttestation,\n ActivityAttestationBundle,\n ActivityVerifyCheck,\n ActivityVerifyResult,\n VerifyActivityOptions,\n} from './identity';\nexport {\n setOrigin,\n getOrigin,\n setBearerToken,\n getBearerToken,\n clearBearerToken,\n MeClientError,\n withRateLimitRetry,\n} from './transport';\nexport type { WithRateLimitRetryOptions } from './transport';\n\nexport {\n PLATFORM_FEE_POLICY,\n MIN_INTEGRATOR_PRICE_SATS,\n MAX_DROP_WINDOW_DAYS,\n computeFees,\n validateIntegratorConfig,\n} from './types';\n\nexport type {\n EventClass,\n EventSubtype,\n EventKey,\n ClassASubtype,\n ClassBSubtype,\n ClassCSubtype,\n AttestTier,\n SiteFeeShape,\n AgentClassOverride,\n IntegratorEventConfig,\n IntegratorPriceConfig,\n ComputedFees,\n ValidationResult,\n BillableEvent,\n DropCadence,\n DropScheduleSummary,\n DropResponseBlock,\n WebhookPayload,\n SystemWebhookPayload,\n DropClosedWebhookPayload,\n WebhookHeaders,\n Session,\n SessionPolicy,\n SignInOptions,\n PaymentAuthorizeOptions,\n PaymentResult,\n TelemetryEvent,\n Federation,\n FederationStatus,\n SigningMethod,\n} from './types';\n\nexport {\n EVENT_SUBTYPES,\n ALL_EVENT_SUBTYPES,\n subtypesForClass,\n type EventSubtypeMetadata,\n} from './subtypes';\n\nexport {\n ARCHETYPE_TEMPLATES,\n fromTemplate as configFromTemplate,\n getArchetypeTemplate,\n type ArchetypeTemplate,\n type IntegratorArchetype,\n} from './templates';\n\nimport { session } from './session';\nimport { payment } from './payment';\nimport { event } from './event';\nimport { config } from './config';\nimport { webhook } from './webhook';\nimport { federations } from './federations';\nimport { scope } from './scope';\nimport { family } from './family';\nimport { identity } from './identity';\n\n/** Convenience namespace mirroring the public API surface in /integrate\n * code samples — `oc.session.create()`, `oc.payment.authorize()`,\n * `oc.event.fire()`, `oc.config.validate()`, `oc.webhook.verify()`,\n * `oc.federations.live()`, `oc.scope.granted()` / `oc.scope.request()`,\n * `oc.family.scopes()`, `oc.identity.verifyActivityAttestation()`. */\nexport const oc = {\n session,\n payment,\n event,\n config,\n webhook,\n federations,\n scope,\n family,\n identity,\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/transport.ts","../src/session.ts","../src/SignInButton.tsx","../src/payment.ts","../src/types.ts","../src/event.ts","../src/templates.ts","../src/config.ts","../node_modules/jose/dist/webapi/lib/buffer_utils.js","../node_modules/jose/dist/webapi/lib/base64.js","../node_modules/jose/dist/webapi/util/base64url.js","../node_modules/jose/dist/webapi/util/errors.js","../node_modules/jose/dist/webapi/lib/type_checks.js","../node_modules/jose/dist/webapi/lib/jwk_to_key.js","../node_modules/jose/dist/webapi/key/import.js","../src/webhook.ts","../src/federations.ts","../src/scope.ts","../src/family.ts","../src/identity.ts","../src/subtypes.ts","../src/index.ts"],"names":["scope","React","jsxs","event","jsx","config","identity","verify","scopes","origin","DEFAULT_ISSUER","DEFAULT_TTL_MS","jwksCache","inflight","hexToBytes","toArrayBuffer","verifyEd25519"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,IAAI,MAAA,GAAS,oBAAA;AACb,IAAI,WAAA,GAA6B,IAAA;AAE1B,SAAS,UAAU,GAAA,EAAmB;AACzC,EAAA,MAAA,GAAS,GAAA,CAAI,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AAClC;AAEO,SAAS,SAAA,GAAoB;AAChC,EAAA,OAAO,MAAA;AACX;AAKO,SAAS,eAAe,KAAA,EAA4B;AACvD,EAAA,WAAA,GAAc,KAAA,IAAS,KAAA,CAAM,MAAA,GAAS,CAAA,GAAI,KAAA,GAAQ,IAAA;AACtD;AAEO,SAAS,cAAA,GAAgC;AAC5C,EAAA,OAAO,WAAA;AACX;AAEO,SAAS,gBAAA,GAAyB;AACrC,EAAA,WAAA,GAAc,IAAA;AAClB;AAgBA,eAAsB,GAAA,CAAO,IAAA,EAAc,IAAA,GAAqB,EAAC,EAAe;AAC5E,EAAA,MAAM,OAAA,GAAkC;AAAA,IACpC,cAAA,EAAgB,kBAAA;AAAA,IAChB,MAAA,EAAQ,kBAAA;AAAA,IACR,GAAI,IAAA,CAAK,OAAA,IAAW;AAAC,GACzB;AACA,EAAA,MAAM,KAAA,GAAQ,KAAK,WAAA,IAAe,WAAA;AAClC,EAAA,IAAI,KAAA,EAA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AAAA,GACxB;AAAA,EACA,iBAAA,EAAmB;AAAA,IACf,EAAA,EAAI,mBAAA;AAAA,IACJ,KAAA,EAAO,GAAA;AAAA,IACP,KAAA,EAAO,iBAAA;AAAA,IACP,UAAA,EACI,4QAAA;AAAA,IACJ,OAAA,EACI,qIAAA;AAAA,IACJ,gBAAA,EAAkB,CAAC,QAAA,EAAU,SAAA,EAAW,cAAc,eAAe,CAAA;AAAA,IACrE,kBAAA,EAAoB;AAAA,GACxB;AAAA;AAAA,EAGA,gBAAA,EAAkB;AAAA,IACd,EAAA,EAAI,kBAAA;AAAA,IACJ,KAAA,EAAO,GAAA;AAAA,IACP,KAAA,EAAO,gBAAA;AAAA,IACP,UAAA,EACI,2GAAA;AAAA,IACJ,OAAA,EAAS,2EAAA;AAAA,IACT,gBAAA,EAAkB,CAAC,SAAA,EAAW,SAAA,EAAW,cAAc,CAAA;AAAA,IACvD,kBAAA,EAAoB;AAAA;AAE5B;AAGO,SAAS,iBAAiB,GAAA,EAAyC;AACtE,EAAA,OAAO,MAAA,CAAO,OAAO,cAAc,CAAA,CAAE,OAAO,CAAC,CAAA,KAAM,CAAA,CAAE,KAAA,KAAU,GAAG,CAAA;AACtE;AAGO,IAAM,kBAAA,GAAsD;AAAA,EAC/D,GAAG,iBAAiB,GAAG,CAAA;AAAA,EACvB,GAAG,iBAAiB,GAAG,CAAA;AAAA,EACvB,GAAG,iBAAiB,GAAG;AAC3B;;;AChCO,IAAM,EAAA,GAAK;AAAA,EACd,OAAA;AAAA,EACA,OAAA;AAAA,EACA,KAAA;AAAA,EACA,MAAA;AAAA,EACA,OAAA;AAAA,EACA,WAAA;AAAA,EACA,KAAA;AAAA,EACA,MAAA;AAAA,EACA;AACJ","file":"index.js","sourcesContent":["/**\n * Tiny HTTP transport layer. The me.ochk.io origin is configurable so\n * staging deployments and self-hosted me-equivalents can swap it.\n *\n * Two auth paths, picked transparently:\n * - Same-origin / family integrators (*.ochk.io): the browser ships\n * the `oc_session` cookie automatically because we set\n * `credentials: 'include'`. Nothing to configure.\n * - Cross-domain integrators: after popup signin, call\n * `setBearerToken(result.token)` once. Subsequent SDK calls add\n * `Authorization: Bearer <token>`. Cookies still ride too — the\n * server accepts whichever arrives.\n */\n\nlet origin = 'https://me.ochk.io';\nlet bearerToken: string | null = null;\n\nexport function setOrigin(url: string): void {\n origin = url.replace(/\\/$/, '');\n}\n\nexport function getOrigin(): string {\n return origin;\n}\n\n/** Cross-domain integrators: store the JWT returned by `signInWithOc()`\n * here so subsequent SDK calls can authenticate via Authorization\n * header. Same-origin integrators don't need this (the cookie rides). */\nexport function setBearerToken(token: string | null): void {\n bearerToken = token && token.length > 0 ? token : null;\n}\n\nexport function getBearerToken(): string | null {\n return bearerToken;\n}\n\nexport function clearBearerToken(): void {\n bearerToken = null;\n}\n\nexport interface FetchOptions {\n method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';\n body?: unknown;\n signal?: AbortSignal;\n /** Extra request headers merged over the defaults · e.g. X-OC-Signature\n * (integrator HMAC) or Idempotency-Key. */\n headers?: Record<string, string>;\n /** Per-call bearer token · overrides the process-global setBearerToken for\n * THIS request only. Use it for stateless server-side firing so concurrent\n * requests for different users never race on one shared module-level token\n * (the setBearerToken global is fine for a single-user browser session). */\n bearerToken?: string;\n}\n\nexport async function api<T>(path: string, opts: FetchOptions = {}): Promise<T> {\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n accept: 'application/json',\n ...(opts.headers ?? {}),\n };\n const token = opts.bearerToken ?? bearerToken;\n if (token) headers['authorization'] = `Bearer ${token}`;\n const res = await fetch(`${origin}${path}`, {\n method: opts.method ?? 'GET',\n credentials: 'include',\n headers,\n body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,\n signal: opts.signal,\n });\n if (!res.ok) {\n let message = `me.ochk.io ${res.status}`;\n let errorCode: string | undefined;\n let body: Record<string, unknown> | undefined;\n try {\n const data = (await res.json()) as {\n error?: string;\n reason?: string;\n [k: string]: unknown;\n };\n body = data;\n if (data?.error) {\n errorCode = data.error;\n message = data.reason ?? data.error;\n }\n } catch {\n /* response body wasn't JSON; carry the bare status */\n }\n // 429 → carry Retry-After so callers (or the small\n // withRateLimitRetry helper) can back off correctly. The header\n // is in seconds per RFC 7231; we surface it as a number on the\n // error rather than asking the caller to re-parse.\n let retryAfterSeconds: number | undefined;\n if (res.status === 429) {\n const headerValue = res.headers.get('retry-after');\n if (headerValue) {\n const parsed = Number.parseInt(headerValue, 10);\n if (Number.isFinite(parsed) && parsed >= 0) retryAfterSeconds = parsed;\n }\n // Server bodies on 429 often also carry the hint as\n // `retry_after_seconds` (see /api/integrator/event/batch's\n // applyProjectRateLimit response). Honor it as a fallback\n // when no header is present — some intermediaries strip\n // Retry-After from CORS responses.\n if (retryAfterSeconds == null && typeof body?.retry_after_seconds === 'number') {\n retryAfterSeconds = body.retry_after_seconds as number;\n }\n }\n throw new MeClientError(message, res.status, { errorCode, retryAfterSeconds });\n }\n return (await res.json()) as T;\n}\n\nexport class MeClientError extends Error {\n public readonly status: number;\n /** Server-side error code (the `error` field on the JSON body, e.g.\n * `project_rate_limit_exceeded`). Stable across versions; safe to\n * match on. The human-readable `message` may change. */\n public readonly errorCode: string | undefined;\n /** Seconds to wait before retrying. Set when the server responded\n * 429 with a Retry-After header (or a `retry_after_seconds` body\n * field). Undefined for any other status. Use with\n * `withRateLimitRetry()` or your own backoff loop. */\n public readonly retryAfterSeconds: number | undefined;\n constructor(\n message: string,\n status: number,\n opts?: { errorCode?: string; retryAfterSeconds?: number }\n ) {\n super(message);\n this.name = 'MeClientError';\n this.status = status;\n this.errorCode = opts?.errorCode;\n this.retryAfterSeconds = opts?.retryAfterSeconds;\n }\n /** True for the 429 surface · convenience boolean so callers don't\n * have to compare status === 429 every time. */\n get isRateLimited(): boolean {\n return this.status === 429;\n }\n}\n\nexport interface WithRateLimitRetryOptions {\n /** Maximum retry attempts on 429. Default 2 (= up to 3 total\n * invocations of the wrapped function). */\n maxRetries?: number;\n /** Cap on Retry-After we'll actually honor in seconds. Some server\n * configs return very large values; the SDK refuses to sleep\n * beyond this and re-throws the original error so the caller\n * decides. Default 30. */\n maxRetryAfterSeconds?: number;\n /** Floor backoff in milliseconds when no Retry-After is present.\n * Multiplied by 2^attempt for exponential growth. Default 250ms. */\n baseBackoffMs?: number;\n}\n\n/**\n * Wrap a transport call with automatic 429 retry, honoring Retry-After.\n *\n * import { oc, withRateLimitRetry } from '@orangecheck/me-client';\n *\n * const res = await withRateLimitRetry(() =>\n * oc.event.fireBatch({ project_key, events })\n * );\n *\n * Retries ONLY on 429 (rate-limit) responses. All other errors throw\n * immediately so the caller can handle them. Sleeps for `Retry-After`\n * seconds when present (capped at `maxRetryAfterSeconds`); otherwise\n * uses exponential backoff from `baseBackoffMs`.\n *\n * Per OCHK-V3-PLAN §12.6 — backpressure protocol. The server emits\n * 429 + Retry-After when a project crosses its 1000 events/sec sustained\n * cap; this helper honors it without integrators having to write the\n * sleep loop.\n *\n * Idempotency note: integrators using `event.fireBatch` should pass an\n * `idempotency_key` per event so a retry doesn't double-record. The\n * server collapses retried events to a `duplicate` status with the\n * prior payload.\n */\nexport async function withRateLimitRetry<T>(\n fn: () => Promise<T>,\n opts: WithRateLimitRetryOptions = {}\n): Promise<T> {\n const maxRetries = opts.maxRetries ?? 2;\n const maxRetryAfter = opts.maxRetryAfterSeconds ?? 30;\n const baseBackoff = opts.baseBackoffMs ?? 250;\n let attempt = 0;\n while (true) {\n try {\n return await fn();\n } catch (err) {\n if (!(err instanceof MeClientError) || !err.isRateLimited) throw err;\n if (attempt >= maxRetries) throw err;\n let waitMs: number;\n if (err.retryAfterSeconds != null) {\n if (err.retryAfterSeconds > maxRetryAfter) throw err;\n waitMs = err.retryAfterSeconds * 1000;\n } else {\n waitMs = baseBackoff * 2 ** attempt;\n }\n await new Promise((resolve) => setTimeout(resolve, waitMs));\n attempt++;\n }\n }\n}\n","import type { Session, SessionPolicy, SignInOptions, TelemetryEvent } from './types';\n\nimport { api } from './transport';\n\nconst DEFAULT_POLICY: SessionPolicy = {\n duration_seconds: 7 * 24 * 60 * 60, // 7 days, standard SaaS shape\n refresh: 'sliding',\n sensitive_actions: 're-auth',\n};\n\nconst telemetrySubscribers = new Set<(e: TelemetryEvent) => void>();\n\n/** Subscribe to non-billable developer telemetry events. Call the returned\n * function to unsubscribe. */\nexport function onTelemetry(listener: (e: TelemetryEvent) => void): () => void {\n telemetrySubscribers.add(listener);\n return () => {\n telemetrySubscribers.delete(listener);\n };\n}\n\nfunction emitTelemetry(code: TelemetryEvent['code'], session_id?: string): void {\n const e: TelemetryEvent = {\n code,\n timestamp: new Date().toISOString(),\n ...(session_id ? { session_id } : {}),\n };\n for (const fn of telemetrySubscribers) {\n try {\n fn(e);\n } catch {\n /* listener errors must not break the session flow */\n }\n }\n}\n\n/**\n * Open a sign-in flow at me.ochk.io. Returns the resulting Session once\n * the user consents (Class C billable event for the integrating site,\n * cashback for the user). Internally this opens the OC consent UI in a\n * popup; v1 implementations may also redirect.\n */\nasync function create(opts: SignInOptions): Promise<Session> {\n const policy: SessionPolicy = { ...DEFAULT_POLICY, ...(opts.sessionPolicy ?? {}) };\n return api<Session>('/api/session/create', {\n method: 'POST',\n body: {\n scope: opts.scope,\n policy,\n return_to: opts.returnTo ?? (typeof window !== 'undefined' ? window.location.href : undefined),\n },\n });\n}\n\n/**\n * Refresh a still-valid session inside its policy window. Free for the\n * integrating site (does NOT instantiate a billable event); emits a\n * `session.token_refresh` telemetry record.\n */\nasync function refresh(sessionId: string): Promise<Session> {\n emitTelemetry('session.token_refresh', sessionId);\n return api<Session>('/api/session/refresh', {\n method: 'POST',\n body: { session_id: sessionId },\n });\n}\n\n/**\n * Tear a session down. Free, and telemetry-only in a literal sense: OC sessions\n * are stateless — derived from the `oc_session` JWT — so there is no server-side\n * record to delete and the endpoint acknowledges without revoking anything.\n * Dropping your own copy of the token IS the logout; this call is the signal.\n */\nasync function invalidate(sessionId: string): Promise<void> {\n emitTelemetry('session.teardown', sessionId);\n await api<{ ok: true }>('/api/session/invalidate', {\n method: 'POST',\n body: { session_id: sessionId },\n });\n}\n\nexport const session = { create, refresh, invalidate };\n","import * as React from 'react';\n\nimport { session } from './session';\nimport type { Session, SessionPolicy } from './types';\n\nexport interface OcSignInButtonProps\n extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'onError'> {\n scope: string[];\n sessionPolicy?: Partial<SessionPolicy>;\n returnTo?: string;\n onSignin?: (session: Session) => void;\n /** Called when the sign-in flow fails. Renamed from `onError` to avoid\n * shadowing the native button error handler. */\n onSignInError?: (error: Error) => void;\n /** Custom button text. Defaults to \"sign in with oc\". */\n label?: string;\n}\n\n/**\n * Opens (or refreshes) a me.ochk.io session for an account already signed\n * in on *.ochk.io, and calls onSignin(session). It rides the family cookie,\n * so it works only on orangecheck's own sites: a third-party site signs\n * people in with `signInWithOc()` from `@orangecheck/me-client/popup` and\n * verifies the token with `withOcAuth` from `/server`.\n *\n * Mounting requires <OcSessionProvider> from @orangecheck/auth-client\n * somewhere up the React tree so the resulting session can be read by\n * useOcSession() across the rest of the app.\n */\nexport function OcSignInButton({\n scope,\n sessionPolicy,\n returnTo,\n onSignin,\n onSignInError,\n label = 'sign in with oc',\n children,\n onClick,\n style,\n ...rest\n}: OcSignInButtonProps) {\n const [pending, setPending] = React.useState(false);\n\n return (\n <button\n type=\"button\"\n onClick={async (event) => {\n onClick?.(event);\n if (event.defaultPrevented) return;\n setPending(true);\n try {\n const result = await session.create({ scope, sessionPolicy, returnTo });\n onSignin?.(result);\n } catch (err) {\n onSignInError?.(err instanceof Error ? err : new Error(String(err)));\n } finally {\n setPending(false);\n }\n }}\n style={{\n display: 'inline-flex',\n alignItems: 'center',\n gap: 8,\n padding: '10px 16px',\n fontSize: 13,\n fontWeight: 600,\n fontFamily: 'ui-monospace, \"JetBrains Mono\", \"SF Mono\", Menlo, monospace',\n letterSpacing: '0.18em',\n textTransform: 'uppercase',\n background: '#f97316',\n color: '#0b0909',\n border: '1px solid #f97316',\n borderRadius: 4,\n cursor: pending ? 'progress' : 'pointer',\n opacity: pending ? 0.7 : 1,\n ...(style ?? {}),\n }}\n disabled={pending || rest.disabled}\n data-oc-signin\n {...rest}\n >\n {/* compact OC mark */}\n <span\n aria-hidden\n style={{\n display: 'inline-block',\n width: 12,\n height: 12,\n background: '#0b0909',\n }}\n />\n {children ?? (pending ? 'opening…' : label)}\n </button>\n );\n}\n","import type { PaymentAuthorizeOptions, PaymentResult } from './types';\n\nimport { api } from './transport';\n\n/**\n * Authorize a payment through the user's OC identity. Class B billable\n * event for the integrating site (sub-Stripe rate, percentage-based);\n * cashback flows to the user as Lightning credit on /me/earn.\n *\n * The user is prompted by me.ochk.io to consent to the specific payment\n * before this resolves. If the user declines or cancels, the result has\n * status `'cancelled'`, a non-billable telemetry record is emitted, and\n * NO billable event is created.\n */\nasync function authorize(opts: PaymentAuthorizeOptions): Promise<PaymentResult> {\n if (opts.amount_sats == null && opts.usd_cents == null) {\n throw new Error('payment.authorize requires amount_sats or usd_cents');\n }\n return api<PaymentResult>('/api/payment/authorize', {\n method: 'POST',\n body: opts,\n });\n}\n\nexport const payment = { authorize };\n","/**\n * Canonical types for me.ochk.io integrators.\n *\n * Mirrors the source of truth at oc-me-web/src/lib/events/types.ts. Two\n * layers:\n * - Platform-level (PLATFORM_FEE_POLICY, MIN_INTEGRATOR_PRICE_SATS) —\n * fixed by OC, surfaced as constants here so integrators can validate\n * their config client-side before posting it.\n * - Integrator-level (IntegratorPriceConfig) — every integrator declares\n * their own per-event prices and user-share splits.\n *\n * Per Addendum 01: every chargeable event is in exactly one of three\n * classes. Sites pay for sessions and actions, not for clicks. Free\n * events never instantiate a BillableEvent.\n */\n\n// ── platform constants (fixed by OC) ──────────────────────────────────────\n\nexport const PLATFORM_FEE_POLICY = {\n /** Fraction of every gross_fee that OC retains. */\n pct: 0.2,\n /** Absolute minimum platform fee, in sats. */\n min_floor_sats: 1,\n /** Date this policy was last ratified. Changes require a versioned\n * @orangecheck/me-client release. */\n ratified: '2026-04-30',\n} as const;\n\n/** Per-event price floor. 1 sat — the natural atomic Bitcoin unit.\n * Integrators choose their own per-event prices above this; OC does\n * not impose sybil-resistance opinions on integrators (that's their\n * call, from their own threat model). The 1-sat floor is purely\n * mechanical — fees can't be fractional sats. Mirrors the canonical\n * value at oc-me-web/src/lib/events/types.ts (a previous SDK release\n * drifted to 5 while the platform ratified 1). */\nexport const MIN_INTEGRATOR_PRICE_SATS = 1;\n\n/**\n * Hard per-event ceiling, mirroring the server's own bound.\n *\n * The server clamps gross to this before splitting it; this package did not,\n * so `verify()` re-derived 99,000,000 for an envelope the server had recorded\n * at 10,000,000 and rejected a correct receipt. It also over-reported what a\n * misconfigured site would be charged, by the ratio of the two numbers.\n *\n * 10,000,000 sats = 0.1 BTC: orders of magnitude above any real per-event\n * price, low enough that a misconfiguration cannot mint an unbounded number\n * of sats in one event. Found by the cross-package vector test in oc-me-web\n * on its first run.\n */\nexport const MAX_INTEGRATOR_PRICE_SATS = 10_000_000;\n\n/** Platform ceiling on drop-period windows: no integrator schedule may\n * hold a user's earned share open longer than this, regardless of\n * cadence. Published in ABUSE_LIMITS on me.ochk.io /trust + /security. */\nexport const MAX_DROP_WINDOW_DAYS = 92;\n\n// ── event taxonomy ────────────────────────────────────────────────────────\n\nexport type EventClass = 'A' | 'B' | 'C';\n\nexport type ClassASubtype =\n | 'account_creation'\n | 'account_recovery'\n | 'attest_bond_increased'\n | 'payment_method_connected'\n | 'agent_delegation_issued'\n | 'recovery_method_updated';\n\nexport type ClassBSubtype =\n | 'payment_authorization'\n | 'scoped_action_authorization'\n | 'attest_verification_at_gate'\n | 'stamp_signing'\n | 'pledge_resolution';\n\nexport type ClassCSubtype = 'session_creation';\n\nexport type EventSubtype = ClassASubtype | ClassBSubtype | ClassCSubtype;\n\n/**\n * Any billable event key. A project's catalog is OPEN: alongside the built-in\n * subtypes above, an integrator can define their own event keys (with their own\n * label + class + price) on the project config. `EventKey` keeps autocomplete\n * for the built-ins while accepting any custom string — the `(string & {})`\n * arm preserves the literal union in editors instead of collapsing it to\n * `string`. The server resolves class/label off the project's catalog for\n * custom keys.\n */\nexport type EventKey = EventSubtype | (string & {});\n\n/** AttestTier · what an integrator's gate can read about an oc identity.\n *\n * me.ochk does NOT do KYC. Sybil resistance is bounded by three\n * composable mechanisms, none of which involve OC handling PII:\n * 1. paid-action history · billable events cost real sats\n * 2. BIP-322 sat-bonding · bond size + age via signed attestation\n * 3. integrator-defined gates · per-site threat-model overlays\n *\n * Tier itself is intentionally simple — anonymous | bonded.\n * Granularity (bond_sats, bond_locked_at, etc) carried separately. */\nexport type AttestTier = 'anonymous' | 'bonded';\n\n/** The shape of a per-event fee — either a fixed sats amount or a percent\n * of the underlying transaction amount (used for payments + pledges). */\nexport type SiteFeeShape =\n | { kind: 'fixed_sats'; sats: number }\n | { kind: 'percent_of_amount'; pct: number };\n\n/** Optional per-class pricing overrides · per OCHK-V3-PLAN §7 phase-1.\n * Agents acting under a scoped oc-agent delegation may bill\n * differently than humans firing the same subtype. When `agent` is\n * unset on a subtype, agent traffic bills at the human rate. `refuse:\n * true` makes the subtype human-only — the endpoint returns 422\n * agent_refused for is_agent=true requests. */\nexport interface AgentClassOverride {\n /** Override site_pays for agent-fired events. */\n site_pays?: SiteFeeShape;\n /** Override user_share_pct. Same default-fallback as site_pays. */\n user_share_pct?: number;\n /** When true, agent traffic is refused for this subtype. */\n refuse?: boolean;\n}\n\n/** What an integrator declares for a single event subtype. */\nexport interface IntegratorEventConfig {\n /** Whether this site bills this event subtype at all. */\n enabled: boolean;\n /** The per-event fee the site pays. */\n site_pays: SiteFeeShape;\n /** Fraction of GROSS that flows to the user (0–0.8 since the\n * platform fee is 20%). The remainder is a rebate to the site's\n * OC project balance. */\n user_share_pct: number;\n /** Optional per-agent-class pricing override applied when an event\n * fires with is_agent=true. */\n agent?: AgentClassOverride;\n}\n\n/** A complete integrator pricing config. Posted to me.ochk.io once at\n * integration time, mutable via the configurator UI or this SDK any time\n * after. */\nexport interface IntegratorPriceConfig {\n project_key: string;\n display_name: string;\n domain: string;\n /** ISO-8601 timestamp the config was last updated. */\n updated_at: string;\n /** Per-event configs, keyed by event key. Open catalog: built-in subtypes\n * AND your own custom keys. Keys not listed are disabled by default. */\n events: Partial<Record<EventKey, IntegratorEventConfig>>;\n}\n\n/** A computed fee breakdown for a single event. site_rebate_sats is what\n * flows back to the integrator's OC balance after OC's platform fee and\n * the user's cashback. */\nexport interface ComputedFees {\n gross_fee_sats: number;\n platform_fee_sats: number;\n user_earned_sats: number;\n site_rebate_sats: number;\n}\n\n/** Compute the four-way fee split for an event given an integrator's\n * config and (for percent_of_amount events) the underlying payment\n * amount. MIRRORS oc-me-web/src/lib/events/types.ts computeFees()\n * EXACTLY — the SDK-side replay (oc.event.verify) re-runs this against\n * envelopes the server billed, so any drift is a false \"divergence\".\n *\n * Invariants:\n * 1. gross_fee_sats >= MIN_INTEGRATOR_PRICE_SATS (1-sat atomic floor)\n * 2. platform_fee_sats = min(gross, max(min_floor, round(gross × pct)))\n * — bounded above by gross so a 1-sat event can't owe more\n * platform fee than it grossed\n * 3. user_earned_sats = min(gross − platform, round(gross × share)),\n * share clamped to [0, 0.8]\n * 4. site_rebate_sats = gross − platform − user (exact remainder)\n * 5. gross == platform + user + rebate exactly\n *\n * When `opts.is_agent` is true AND the config has an `agent` override,\n * the agent's site_pays / user_share_pct apply. `agent.refuse: true`\n * throws 'agent_refused' (the server maps it to 422). */\nexport function computeFees(\n cfg: IntegratorEventConfig,\n payment_amount_sats?: number,\n opts?: { is_agent?: boolean }\n): ComputedFees {\n const is_agent = opts?.is_agent === true;\n if (is_agent && cfg.agent?.refuse) {\n throw new Error('agent_refused');\n }\n const effective_site_pays =\n is_agent && cfg.agent?.site_pays ? cfg.agent.site_pays : cfg.site_pays;\n const effective_user_share_pct =\n is_agent && typeof cfg.agent?.user_share_pct === 'number'\n ? cfg.agent.user_share_pct\n : cfg.user_share_pct;\n\n let gross = 0;\n if (effective_site_pays.kind === 'fixed_sats') {\n gross = Math.max(MIN_INTEGRATOR_PRICE_SATS, Math.round(effective_site_pays.sats));\n } else {\n if (payment_amount_sats == null) {\n throw new Error('percent_of_amount config requires payment_amount_sats');\n }\n gross = Math.max(\n MIN_INTEGRATOR_PRICE_SATS,\n Math.round(payment_amount_sats * effective_site_pays.pct)\n );\n }\n // Hard ceiling · no single event mints more than MAX_INTEGRATOR_PRICE_SATS.\n // The server applies this before splitting; omitting it here made verify()\n // reject correct envelopes priced above the bound.\n gross = Math.min(gross, MAX_INTEGRATOR_PRICE_SATS);\n const platform_fee_sats = Math.min(\n gross,\n Math.max(PLATFORM_FEE_POLICY.min_floor_sats, Math.round(gross * PLATFORM_FEE_POLICY.pct))\n );\n const user_share = Math.min(0.8, Math.max(0, effective_user_share_pct));\n const user_earned_sats = Math.min(gross - platform_fee_sats, Math.round(gross * user_share));\n const site_rebate_sats = gross - platform_fee_sats - user_earned_sats;\n return { gross_fee_sats: gross, platform_fee_sats, user_earned_sats, site_rebate_sats };\n}\n\n/** Result of validating an IntegratorPriceConfig. */\nexport interface ValidationResult {\n ok: boolean;\n errors: { subtype?: EventKey; message: string }[];\n}\n\n/**\n * Validate an integrator's pricing config against the platform's\n * non-negotiable rules. Run client-side before posting; the server runs\n * the same checks and rejects anything that fails.\n */\nexport function validateIntegratorConfig(cfg: IntegratorPriceConfig): ValidationResult {\n const errors: ValidationResult['errors'] = [];\n\n if (!cfg.project_key) errors.push({ message: 'project_key is required' });\n if (!cfg.display_name) errors.push({ message: 'display_name is required' });\n if (!cfg.domain) errors.push({ message: 'domain is required' });\n\n for (const [key, eventCfg] of Object.entries(cfg.events)) {\n if (!eventCfg) continue;\n const subtype = key as EventKey;\n if (!eventCfg.enabled) continue;\n\n if (eventCfg.site_pays.kind === 'fixed_sats') {\n if (eventCfg.site_pays.sats < MIN_INTEGRATOR_PRICE_SATS) {\n errors.push({\n subtype,\n message: `site_pays.sats (${eventCfg.site_pays.sats}) is below MIN_INTEGRATOR_PRICE_SATS (${MIN_INTEGRATOR_PRICE_SATS})`,\n });\n }\n } else {\n const pct = eventCfg.site_pays.pct;\n if (!(pct > 0 && pct <= 1)) {\n errors.push({\n subtype,\n message: `site_pays.pct (${pct}) must be in (0, 1]`,\n });\n }\n }\n\n const u = eventCfg.user_share_pct;\n if (u < 0 || u > 0.8) {\n errors.push({\n subtype,\n message: `user_share_pct (${u}) must be in [0, 0.8]; max is 0.8 because platform_fee is ${PLATFORM_FEE_POLICY.pct}`,\n });\n }\n }\n\n return { ok: errors.length === 0, errors };\n}\n\n// ── canonical envelope ────────────────────────────────────────────────────\n\nexport interface BillableEvent {\n id: string;\n occurred_at: string;\n class: EventClass;\n subtype: EventKey;\n site: { domain: string; display_name: string };\n gross_fee_sats: number;\n platform_fee_sats: number;\n user_earned_sats: number;\n site_rebate_sats: number;\n verify_url: string;\n /** Per OCHK-V3-PLAN §7 phase-1 · true when the event was fired by\n * an oc-agent delegation rather than a human session. The\n * integrator's IntegratorEventConfig.agent block may price\n * these differently or refuse them. Optional · canonical encoder\n * branches to v=3 only when present, so legacy human-fired\n * events keep their v=2 hash + signature. */\n is_agent?: boolean;\n /** Drop-period stamp · present when the project covers this\n * subtype with a drop schedule. The user-share of a stamped event\n * MATURES until the window's boundary, then vests as one batch\n * (the drop). Billing is untouched. Part of the SIGNED canonical\n * bytes (encoder branches to v=4 when present). No clawback\n * exists — vesting is unconditional, and an open window's\n * boundary can only ever move earlier. */\n drop?: {\n /** Deterministic window id · the window's signed manifest is\n * verifiable at me.ochk.io/verify/<manifest_id> after close. */\n window_id: string;\n /** Block-denominated vesting boundary; null when no chain tip\n * was observable at window open (wallclock + the published\n * 24h safety valve then govern). */\n close_height_target: number | null;\n } | null;\n}\n\n// ── drop periods · integrator-scheduled payout windows ───────────────────\n\n/** A drop schedule's cadence. Weekly/monthly close at a fixed UTC\n * boundary; manual closes when the integrator says (Drop now), with a\n * hard auto-close at max_open_days (≤ MAX_DROP_WINDOW_DAYS). */\nexport type DropCadence =\n | { kind: 'weekly'; day: number; hour: number }\n | { kind: 'monthly'; day: number; hour: number }\n | { kind: 'manual'; max_open_days: number };\n\n/** Public shape of an enabled drop schedule, as returned in the\n * `drops` array of GET /api/integrator/config — part of the project's\n * public payout contract (earners can see when covered subtypes pay\n * out before earning under them). */\nexport interface DropScheduleSummary {\n schedule_id: string;\n label: string;\n subtypes: EventSubtype[];\n cadence: DropCadence;\n}\n\n/** Drop-period context on event-ingest responses (single route:\n * top-level `drop`; batch route: per-result `drop`). `state` flips\n * from 'open' to 'closing' once the scheduled boundary passes and the\n * window awaits its sweep (~15 min) — render \"processing\", never a\n * negative countdown. */\nexport interface DropResponseBlock {\n window_id: string;\n label: string;\n state: 'open' | 'closing';\n closes_at_target: string;\n close_height_target: number | null;\n}\n\n// ── webhook payload ───────────────────────────────────────────────────────\n\n/**\n * The exact JSON body delivered to a registered webhook endpoint when\n * a billable event fires. Imported by integrator backends so the\n * receive handler is type-checked end-to-end without re-declaring the\n * shape.\n *\n * import type { WebhookPayload } from '@orangecheck/me-client';\n *\n * export async function POST(req: Request) {\n * const payload = (await req.json()) as WebhookPayload;\n * if (payload.subtype === 'payment_authorization') {\n * creditUser(payload.sub, payload.user_earned_sats);\n * }\n * }\n *\n * Headers carry the signature and metadata (see WebhookHeaders below).\n * Verify the signature with `oc.webhook.verify({ body, headers, jwks })`.\n *\n * Privacy contract · the master oc identity is NEVER in the payload.\n * Integrators see `sub` (per-integrator anonymous id) plus any\n * `scopes` the user explicitly granted. See PRIVACY-ARCHITECTURE.md.\n */\nexport interface WebhookPayload extends BillableEvent {\n /** Discriminator · identifies the payload kind for routing on\n * the integrator's side. Always 'oc-billable-event' today; future\n * webhook payload kinds (refunds, charters, etc) will use\n * distinct discriminator values. */\n kind: 'oc-billable-event';\n /** Per-integrator anonymous subject id · stable across events for\n * the same (oc_identity, project_key) pair. Key your user records\n * on this; OC will never give you the master address unless the\n * user explicitly grants `bitcoin_address` or `email` scope. */\n sub: string;\n /** Resolved scoped fields · only present for scopes the user has\n * granted to this project. Wire format is string-keyed (every\n * value is stringified · ints stringified, addresses as-is). */\n scopes?: Partial<\n Record<\n | 'bitcoin_address'\n | 'email'\n | 'attest_tier'\n | 'display_name'\n | 'cross_integrator_event_count'\n | 'cross_integrator_human_event_count'\n | 'trust_attestation_count'\n | 'trust_attestations_bundle',\n string\n >\n >;\n}\n\n/**\n * Non-billable SYSTEM webhook deliveries — project-level operational\n * signals (escrow.low, escrow.depleted, escrow.recovered, drop.closed).\n * Same signing + headers as billable deliveries; receivers subscribe\n * via the same `subscribed` list ('*' or the explicit subtype string).\n * Carries no user identity. Discriminate on `kind` first, then\n * `subtype`:\n *\n * const payload = JSON.parse(body) as WebhookPayload | SystemWebhookPayload;\n * if (payload.kind === 'oc-system-event' && payload.subtype === 'drop.closed') { … }\n */\nexport interface SystemWebhookPayload {\n kind: 'oc-system-event';\n subtype: string;\n project_key: string;\n [extra: string]: unknown;\n}\n\n/** The `drop.closed` system event — one per closed drop window. The\n * manifest is the signed, content-addressed record (Merkle commitments\n * over member events + recipients); verify_url renders + live-verifies\n * it, and /api/envelope/<manifest_id> serves the raw canonical bytes. */\nexport interface DropClosedWebhookPayload extends SystemWebhookPayload {\n subtype: 'drop.closed';\n window_id: string;\n schedule_id: string;\n label: string;\n manifest_id: string;\n verify_url: string;\n sealed_at: string;\n sealed_height: number | null;\n event_count: number;\n recipient_count: number;\n gross_fee_sats: number;\n user_share_sats: number;\n}\n\n/**\n * HTTP headers OC sends with every webhook delivery. Capture these in\n * the receive handler · `OC-Signature` is what verifies the body.\n */\nexport interface WebhookHeaders {\n /** Ed25519 signature over the raw response body, hex-encoded. */\n 'OC-Signature': string;\n /** Stable kid of the signing key · resolves against\n * ochk.io/.well-known/jwks.json. */\n 'OC-Key-Id': string;\n /** Envelope id · matches payload.id; useful for idempotent\n * receive handlers that dedupe on this header without parsing\n * the body. */\n 'OC-Envelope-Id': string;\n /** Subtype · matches payload.subtype (built-in or a custom event key);\n * lets routers branch on the header before parsing. */\n 'OC-Subtype': EventKey;\n /** Class · matches payload.class. */\n 'OC-Class': EventClass;\n /** 1-indexed delivery attempt count. >1 means the prior attempt\n * did not return a 2xx within the timeout · idempotency key on\n * payload.id is critical. */\n 'OC-Delivery-Attempt': string;\n}\n\n// ── session lifecycle ────────────────────────────────────────────────────\n\nexport interface SessionPolicy {\n duration_seconds: number;\n refresh: 'sliding' | 'rolling' | 'none';\n sensitive_actions?: 're-auth' | 'none';\n}\n\nexport interface Session {\n id: string;\n identity: string;\n opens_at: string;\n expires_at: string;\n policy: SessionPolicy;\n scope: string[];\n}\n\nexport interface SignInOptions {\n scope: string[];\n sessionPolicy?: Partial<SessionPolicy>;\n returnTo?: string;\n}\n\nexport interface PaymentAuthorizeOptions {\n identity: string;\n amount_sats?: number;\n usd_cents?: number;\n description: string;\n external_ref?: string;\n}\n\nexport interface PaymentResult {\n id: string;\n status: 'authorized' | 'failed' | 'cancelled';\n sats_charged?: number;\n user_envelope_id?: string;\n verify_url?: string;\n}\n\nexport interface TelemetryEvent {\n code:\n | 'session.intra_signin'\n | 'session.token_refresh'\n | 'session.navigation'\n /** Emitted by `session.invalidate()`. Was `session.intra_signin`, which\n * means the opposite thing — \"user pressed sign-in while a valid\n * session was already open\" — so a subscriber saw a sign-in event\n * every time the integrator tore a session down. Non-billable. */\n | 'session.teardown'\n | 'auth.signin_failed'\n | 'auth.signin_cancelled'\n | 'auth.signin_rejected'\n | 'verify.passive_check';\n timestamp: string;\n session_id?: string;\n}\n\n// ── federation directory ───────────────────────────────────────────────\n//\n// The SDK consumes the federation directory at runtime so multi-federation\n// routing is a directory write, not a code change. v1 has one live\n// federation; the directory is plural-shaped so federation #2 lights up\n// without an SDK release.\n\nexport type FederationStatus = 'recruiting' | 'forming' | 'binding' | 'live';\n\n/** Federation directory entry. Mirrors `oc-me-web/src/lib/federations/registry.ts`\n * field-for-field; this package is the public consumption shape. */\nexport interface Federation {\n slug: string;\n name: string;\n status: FederationStatus;\n threshold: string;\n target_guardian_count: number;\n /** Fedimint invite code; null until status === 'live'. */\n invite: string | null;\n /** SHA-256 of the canonical federation charter, hex-encoded. */\n charter_hash: string | null;\n /** ISO-8601 of the most recent ongoing-attestation envelope. */\n last_attestation_at: string | null;\n geography_hint: string;\n // Operator-recruiting fields (present on slots in 'recruiting' /\n // 'forming' / 'binding' state). Nullable so one shape spans the\n // lifecycle.\n geography_requirements?: string;\n charter_status?: string;\n ceremony_window?: string;\n why_this_one?: string;\n apply_cta?: string;\n apply_href?: string;\n}\n\n/** SigningMethod discriminator on the user identity. Federation-agnostic\n * by construction — the OC identity (did:email or BIP-322 address)\n * remains stable across all three states. Transitions are recorded as\n * anchored \"rebind\" envelopes on the canonical event log. Graduation\n * is the product thesis; this discriminator is the structural primitive\n * that records where a user is on the custody-state graph. */\nexport type SigningMethod = 'fedimint_threshold' | 'fedimint_client' | 'bip322';\n","/**\n * `oc.event.fire` — escape hatch for firing a billable envelope under\n * any subtype that isn't already covered by `oc.session.create` or\n * `oc.payment.authorize`. Useful for `stamp_signing`,\n * `attest_verification_at_gate`, `scoped_action_authorization`,\n * `kyc_tier_upgrade`, etc.\n *\n * import { oc } from '@orangecheck/me-client';\n *\n * const env = await oc.event.fire({\n * project_key: 'pk_live_yourcompany',\n * subtype: 'stamp_signing',\n * action_label: 'review · march invoice',\n * });\n * // env.id, env.gross_fee_sats, env.user_earned_sats, env.verify_url\n *\n * // For percent_of_amount-priced subtypes, include the underlying amount:\n * const verify = await oc.event.fire({\n * project_key: 'pk_live_yourcompany',\n * subtype: 'attest_verification_at_gate',\n * payment_amount_sats: 50_000,\n * });\n *\n * The class is determined by SUBTYPE_CLASS server-side; cashback is\n * computed via computeFees(); the envelope is recorded under the\n * project_key and shows up in /developer/projects/[id]/events.\n */\n\nimport {\n computeFees,\n type BillableEvent,\n type EventKey,\n type IntegratorEventConfig,\n type IntegratorPriceConfig,\n} from './types';\nimport { api } from './transport';\n\nexport interface FireEventOptions {\n /** Your project_key (e.g. `pk_live_yourcompany`). Required. */\n project_key: string;\n /** Billable event key · a built-in subtype OR a custom key defined on your\n * project catalog. Class + label are resolved server-side from the catalog. */\n subtype: EventKey;\n /** Human-readable action label that appears on the envelope.\n * Optional but encouraged — it's what the user sees in their\n * /me/activity ledger. */\n action_label?: string;\n /** For percent_of_amount-priced subtypes, the underlying amount\n * the fee is computed against. Required for those subtypes. */\n payment_amount_sats?: number;\n /** Free-form metadata stored on the envelope. Public — anyone who\n * GETs /api/envelope/<id> sees it. Don't put secrets here. */\n metadata?: Record<string, unknown>;\n /** Per OCHK-V3-PLAN §7 phase-1 · when true, the event was fired\n * by an oc-agent delegation rather than a human acting under their\n * own session. The integrator's IntegratorEventConfig.agent block\n * applies the override (or refuses · 422 agent_refused).\n *\n * Set this when an autonomous agent (oc-agent kind 30084 action\n * envelope) is the source of the event. Don't set it for events\n * the human user clicked themselves. */\n is_agent?: boolean;\n /** The project's HMAC signing secret. When provided, the SDK signs the\n * request with X-OC-Signature, authenticating the call as the INTEGRATOR.\n * REQUIRED in test mode as well as live — without it the server 401s,\n * because a user session alone proves a user, never the paying project.\n * The one exception is a session that owns the project (the CLI\n * test-fire path), which is not a shape a backend should rely on.\n * SERVER-SIDE\n * ONLY: never ship this secret to a browser. Find/rotate it on the project\n * Keys tab (/me/projects/<id>/keys). */\n signingSecret?: string;\n /** Who earns, as their `did:oc` — the value `/api/auth/me` returns as\n * `did_oc`.\n *\n * This is the BACKEND path, and it is the one to prefer. Your server\n * signs the request with `signingSecret`, the signature covers these\n * bytes, and the earner rides inside them — so the signature is your\n * project asserting \"this identity did this on my site\". No browser, no\n * user cookie, and no reason for your backend to be holding your users'\n * session tokens at all.\n *\n * REQUIRES `signingSecret`. A session alone may never name an earner: it\n * proves a user, not a project, and that would let any signed-in caller\n * credit anybody. */\n userAddress?: string;\n /** The forwarded user oc_session JWT (the `token` from the sign-in popup\n * result). Identifies which user earns the cashback when `userAddress` is\n * not given. Pass it per-call for stateless, concurrency-safe server-side\n * firing — preferred over the process-global setBearerToken when your\n * backend serves many users. A same-origin family integrator (*.ochk.io)\n * can omit it; the oc_session cookie rides automatically. */\n bearerToken?: string;\n /** Idempotency key (e.g. a UUID v7 per logical event). A retry with the\n * same key returns the prior event rather than double-billing. */\n idempotencyKey?: string;\n}\n\n/** HMAC-SHA256 hex via Web Crypto — works in Node 20+ and the browser with no\n * node:crypto import (keeps this package isomorphic). Signing only ever runs\n * server-side because it needs the project secret. */\nasync function hmacSha256Hex(secret: string, message: string): Promise<string> {\n const enc = new TextEncoder();\n const key = await crypto.subtle.importKey(\n 'raw',\n enc.encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign']\n );\n const sig = await crypto.subtle.sign('HMAC', key, enc.encode(message));\n return Array.from(new Uint8Array(sig))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/** Build the X-OC-Signature header for a request body, byte-matching the\n * server's event-signature.ts contract: `t=<unix>,v1=hmac_sha256(secret,\n * `${t}.${body}`)`. The `body` MUST be the exact JSON string the transport\n * transmits (the server re-derives it as JSON.stringify(req.body)). */\nasync function signBody(secret: string, serializedBody: string): Promise<string> {\n const t = Math.floor(Date.now() / 1000);\n const mac = await hmacSha256Hex(secret, `${t}.${serializedBody}`);\n return `t=${t},v1=${mac}`;\n}\n\nasync function fire(options: FireEventOptions): Promise<BillableEvent> {\n if (!options.project_key) {\n throw new Error('event.fire requires project_key');\n }\n if (!options.subtype) {\n throw new Error('event.fire requires subtype');\n }\n // Fail here rather than letting the server 401 — the mistake is always the\n // same one (naming an earner from a browser or an unsigned backend call),\n // and the round-trip tells you less than this sentence does.\n if (options.userAddress && !options.signingSecret) {\n throw new Error(\n 'event.fire: userAddress names who earns, so it requires signingSecret — ' +\n 'the signature over the request body is what authorises that earner. ' +\n 'Without the secret, pass bearerToken (or rely on the oc_session cookie) ' +\n 'and the caller earns instead.'\n );\n }\n\n // Build the request body from server-recognized fields ONLY — never let the\n // signing secret or bearer token leak into the transmitted payload.\n const requestBody: Record<string, unknown> = {\n project_key: options.project_key,\n subtype: options.subtype,\n };\n if (options.payment_amount_sats !== undefined)\n requestBody.payment_amount_sats = options.payment_amount_sats;\n if (options.action_label !== undefined) requestBody.action_label = options.action_label;\n if (options.metadata !== undefined) requestBody.metadata = options.metadata;\n if (options.is_agent !== undefined) requestBody.is_agent = options.is_agent;\n // Inside the signed bytes on purpose — see `userAddress` above.\n if (options.userAddress !== undefined) requestBody.user_address = options.userAddress;\n\n const headers: Record<string, string> = {};\n if (options.idempotencyKey) headers['idempotency-key'] = options.idempotencyKey;\n if (options.signingSecret) {\n // Sign the exact bytes the transport sends: it JSON.stringify's the same\n // object reference, so this string is byte-identical to what lands.\n headers['x-oc-signature'] = await signBody(\n options.signingSecret,\n JSON.stringify(requestBody)\n );\n }\n\n return api<BillableEvent>('/api/integrator/event', {\n method: 'POST',\n body: requestBody,\n headers,\n bearerToken: options.bearerToken,\n });\n}\n\n/** One event in a batch · same shape as the per-event request minus\n * project_key (which is hoisted to the batch level). */\nexport interface BatchEventInput {\n /** Billable event key · built-in subtype or a custom project key. */\n subtype: EventKey;\n /** For percent_of_amount-priced subtypes, the underlying amount. */\n payment_amount_sats?: number;\n /** Human-readable label that appears in /me/earn. */\n action_label?: string;\n /** Free-form note stored on the envelope. Public. */\n note?: string;\n /** Per-event idempotency key. Distinct from the batch-level retry —\n * if the SDK retries the same batch, events that already landed\n * collapse to a `duplicate` status with the prior payload. */\n idempotency_key?: string;\n /** Per OCHK-V3-PLAN §7 phase-1 · per-event agent flag. A single\n * batch can mix agent + human events when a backend interleaves\n * them. The integrator's per-subtype agent override applies per\n * event independently. */\n is_agent?: boolean;\n}\n\n/** Per-event result inside the batch response. Status codes:\n * - `recorded` · the event landed; `event` is the canonical billable\n * payload exactly as a per-event POST would return.\n * - `duplicate` · idempotency-key matched a prior event; `event` is\n * the prior payload.\n * - `rejected` · validation or site-cap failure; `reason` is human-\n * readable. The other events in the batch are unaffected. */\nexport type BatchEventResult =\n | {\n index: number;\n status: 'recorded';\n event: BillableEvent;\n }\n | {\n index: number;\n status: 'duplicate';\n event: BillableEvent;\n }\n | {\n index: number;\n status: 'rejected';\n reason: string;\n };\n\nexport interface FireBatchOptions {\n /** Your project_key. Required. All events in the batch bill against\n * this project_key + the authenticated session. */\n project_key: string;\n /** 1 to 100 events. Larger batches must be split client-side. */\n events: BatchEventInput[];\n /** The project's HMAC signing secret · REQUIRED in live mode (same\n * contract as event.fire). Server-side only. */\n signingSecret?: string;\n /** The forwarded user oc_session JWT · pass per-call for stateless\n * server-side firing (see FireEventOptions.bearerToken). */\n bearerToken?: string;\n}\n\nexport interface FireBatchResponse {\n ok: boolean;\n results: BatchEventResult[];\n escrow_mode: 'simulation' | 'live';\n simulation_mode_note?: string;\n}\n\n/**\n * `oc.event.fireBatch` — bulk-ingest up to 100 billable envelopes\n * under one project_key in a single HTTP round-trip.\n *\n * Wins amortize across the batch: one auth roundtrip, one project\n * lookup, one scope-grants resolve, parallel KV writes via Promise.all.\n * For a 50-event batch the server-side processing time drops from\n * ~3-4.5 seconds (50 sequential per-event POSTs) to ~100-200ms.\n *\n * import { oc } from '@orangecheck/me-client';\n *\n * const res = await oc.event.fireBatch({\n * project_key: 'pk_live_yourcompany',\n * events: [\n * { subtype: 'session_creation' },\n * { subtype: 'page_view', action_label: 'home' },\n * { subtype: 'page_view', action_label: 'pricing' },\n * ],\n * });\n * for (const r of res.results) {\n * if (r.status === 'recorded') console.log('+', r.event.id, r.event.gross_fee_sats);\n * else if (r.status === 'duplicate') console.log('~ idempotent replay', r.event.id);\n * else console.log('!', r.reason);\n * }\n *\n * Failure modes:\n * - 400 if events.length === 0 or > 100, or events[].subtype missing\n * - 403 if the project is frozen or the domain is unverified\n * - 429 if the project's rate limit (1000 events/sec sustained) is\n * exceeded; Retry-After header indicates backoff.\n *\n * Per OCHK-V3-PLAN §12.2.\n */\nasync function fireBatch(options: FireBatchOptions): Promise<FireBatchResponse> {\n if (!options.project_key) {\n throw new Error('event.fireBatch requires project_key');\n }\n if (!Array.isArray(options.events) || options.events.length === 0) {\n throw new Error('event.fireBatch requires at least one event');\n }\n if (options.events.length > 100) {\n throw new Error(\n `event.fireBatch · max 100 events per call (got ${options.events.length}). Split client-side.`\n );\n }\n\n // Body excludes the secret/token — only project_key + events go on the wire.\n const requestBody = { project_key: options.project_key, events: options.events };\n const headers: Record<string, string> = {};\n if (options.signingSecret) {\n headers['x-oc-signature'] = await signBody(\n options.signingSecret,\n JSON.stringify(requestBody)\n );\n }\n\n return api<FireBatchResponse>('/api/integrator/event/batch', {\n method: 'POST',\n body: requestBody,\n headers,\n bearerToken: options.bearerToken,\n });\n}\n\n/** Result of replay-verifying a billable envelope against the\n * integrator's price config. Every field returned tells the caller\n * WHY a divergence happened — they can render it directly. */\nexport interface VerifyEventResult {\n /** True iff every expected fee equals the recorded fee. */\n ok: boolean;\n /** Issues found during verification, with field-level granularity\n * so callers can highlight exactly which line is off. */\n issues: Array<{\n field:\n | 'gross_fee_sats'\n | 'platform_fee_sats'\n | 'user_earned_sats'\n | 'site_rebate_sats'\n | 'subtype_disabled'\n | 'subtype_unconfigured'\n | 'percent_amount_missing';\n expected: number | null;\n actual: number | null;\n message: string;\n }>;\n /** What computeFees() returned for the envelope's subtype + amount,\n * given the integrator's current price config. Useful for the\n * /audit divergence tracker — render expected vs actual side by\n * side. Null when the subtype isn't enabled for this integrator. */\n expected: {\n gross_fee_sats: number;\n platform_fee_sats: number;\n user_earned_sats: number;\n site_rebate_sats: number;\n } | null;\n}\n\n/**\n * Replay-verify a billable envelope against the integrator's current\n * price config. Re-runs computeFees() with the same inputs and\n * compares against the four-way split recorded on the envelope.\n *\n * Anyone — the integrator, a user, OC, an auditor — can run this\n * function and reach the same answer. The integrator-side replay is\n * what keeps OC honest: a divergence means OC's billing engine\n * computed differently than the published price config says it should\n * have, and the integrator can flag it on /audit.\n *\n * For percent_of_amount-priced subtypes, the underlying payment\n * amount must be passed explicitly (it isn't stored on the envelope\n * top-level — only inside the context payload — so callers should\n * pass `envelope.context.payment_amount_sats`).\n *\n * import { oc } from '@orangecheck/me-client';\n *\n * const env = await fetch(`https://me.ochk.io/api/envelope/${id}`).then(r => r.json());\n * // Your project's config, by its key. A project can move domains, so\n * // `env.site.domain` names where it was, not which project it is.\n * const cfg = await fetch(\n * `https://me.ochk.io/api/integrator-config?project_key=${PROJECT_KEY}`\n * ).then(r => r.json());\n * const result = oc.event.verify(env, cfg);\n * if (!result.ok) reportDivergence(result.issues);\n */\nfunction verify(\n envelope: BillableEvent,\n config: IntegratorPriceConfig,\n payment_amount_sats?: number\n): VerifyEventResult {\n const issues: VerifyEventResult['issues'] = [];\n\n const eventCfg: IntegratorEventConfig | undefined = config.events[envelope.subtype];\n if (!eventCfg) {\n return {\n ok: false,\n expected: null,\n issues: [\n {\n field: 'subtype_unconfigured',\n expected: null,\n actual: null,\n message: `subtype ${envelope.subtype} is not configured on integrator ${config.project_key}`,\n },\n ],\n };\n }\n if (!eventCfg.enabled) {\n return {\n ok: false,\n expected: null,\n issues: [\n {\n field: 'subtype_disabled',\n expected: null,\n actual: null,\n message: `subtype ${envelope.subtype} is disabled on integrator ${config.project_key} but the envelope was billed`,\n },\n ],\n };\n }\n if (eventCfg.site_pays.kind === 'percent_of_amount' && payment_amount_sats == null) {\n return {\n ok: false,\n expected: null,\n issues: [\n {\n field: 'percent_amount_missing',\n expected: null,\n actual: null,\n message: `subtype ${envelope.subtype} is percent_of_amount-priced; payment_amount_sats is required to verify`,\n },\n ],\n };\n }\n\n const expected = computeFees(eventCfg, payment_amount_sats);\n\n if (envelope.gross_fee_sats !== expected.gross_fee_sats) {\n issues.push({\n field: 'gross_fee_sats',\n expected: expected.gross_fee_sats,\n actual: envelope.gross_fee_sats,\n message: `gross_fee_sats mismatch · expected ${expected.gross_fee_sats}, recorded ${envelope.gross_fee_sats}`,\n });\n }\n if (envelope.platform_fee_sats !== expected.platform_fee_sats) {\n issues.push({\n field: 'platform_fee_sats',\n expected: expected.platform_fee_sats,\n actual: envelope.platform_fee_sats,\n message: `platform_fee_sats mismatch · expected ${expected.platform_fee_sats}, recorded ${envelope.platform_fee_sats}`,\n });\n }\n if (envelope.user_earned_sats !== expected.user_earned_sats) {\n issues.push({\n field: 'user_earned_sats',\n expected: expected.user_earned_sats,\n actual: envelope.user_earned_sats,\n message: `user_earned_sats mismatch · expected ${expected.user_earned_sats}, recorded ${envelope.user_earned_sats}`,\n });\n }\n if (envelope.site_rebate_sats !== expected.site_rebate_sats) {\n issues.push({\n field: 'site_rebate_sats',\n expected: expected.site_rebate_sats,\n actual: envelope.site_rebate_sats,\n message: `site_rebate_sats mismatch · expected ${expected.site_rebate_sats}, recorded ${envelope.site_rebate_sats}`,\n });\n }\n\n return {\n ok: issues.length === 0,\n expected,\n issues,\n };\n}\n\nexport const event = { fire, fireBatch, verify };\n","/**\n * Archetype templates for `oc.config.fromTemplate(useCase, ...)`.\n *\n * A new integrator with a 30-second decision shouldn't have to fill\n * 12 IntegratorEventConfig entries by hand. Pick the archetype that\n * matches your site, get a sensible starting config, tweak whatever\n * you want, submit:\n *\n * import { oc } from '@orangecheck/me-client';\n *\n * const config = oc.config.fromTemplate('saas-paywall', {\n * project_key: 'pk_live_yourcompany',\n * domain: 'yoursite.com',\n * display_name: 'Your Site',\n * });\n * await oc.config.save(config);\n *\n * Templates differ on which subtypes are enabled (a content platform\n * doesn't need payment_authorization; a marketplace does) and on the\n * sat price + user_share_pct per subtype. Every template's prices\n * anchor at $1 ≈ 1052 sats. user_share_pct=0.65 means the user gets\n * 65% of gross — the platform fee is 20% (fixed), the integrator\n * rebate is the remainder (15% with 0.65 user share).\n *\n * To customize after picking a template:\n *\n * const config = oc.config.fromTemplate('marketplace', { ... });\n * config.events.payment_authorization!.site_pays = {\n * kind: 'percent_of_amount',\n * pct: 0.005, // 0.5% instead of the template's 0.75%\n * };\n */\n\nimport type {\n EventSubtype,\n IntegratorEventConfig,\n IntegratorPriceConfig,\n} from './types';\n\nexport type IntegratorArchetype =\n | 'saas-paywall'\n | 'marketplace'\n | 'content-platform'\n | 'gaming'\n | 'agent-only';\n\ninterface ProjectIdentity {\n project_key: string;\n domain: string;\n display_name: string;\n}\n\n/** Template descriptor · what each archetype enables and prices.\n * Exposed so dashboards can render \"you're using the X template\"\n * state and offer one-click swaps. */\nexport interface ArchetypeTemplate {\n id: IntegratorArchetype;\n label: string;\n /** One-sentence summary shown next to the picker. */\n summary: string;\n /** Concrete examples of sites this archetype fits. */\n examples: readonly string[];\n /** Per-subtype config the template emits. Subtypes not listed are\n * emitted as `enabled: false` (the SDK fills them with a\n * conservative default to keep the type happy without firing). */\n events: Partial<Record<EventSubtype, IntegratorEventConfig>>;\n}\n\nconst FIXED = (sats: number): IntegratorEventConfig['site_pays'] => ({\n kind: 'fixed_sats',\n sats,\n});\nconst PCT = (pct: number): IntegratorEventConfig['site_pays'] => ({\n kind: 'percent_of_amount',\n pct,\n});\n\n/**\n * The full archetype catalog. Add new templates here · one record per\n * common integrator pattern. Keep the list curated (≤8 archetypes) —\n * if there are too many, none feel like the obvious default and\n * integrators stall on the picker.\n */\nexport const ARCHETYPE_TEMPLATES: readonly ArchetypeTemplate[] = [\n {\n id: 'saas-paywall',\n label: 'SaaS · paywall',\n summary:\n 'Subscription product · users sign up, sign in, sometimes pay for premium tiers. Default cashback to encourage signup + retention.',\n examples: ['Notion-like notes app', 'Linear-like project tracker', 'Figma-like editor'],\n events: {\n account_creation: {\n enabled: true,\n site_pays: FIXED(1300),\n user_share_pct: 0.65,\n },\n session_creation: {\n enabled: true,\n site_pays: FIXED(55),\n user_share_pct: 0.65,\n },\n payment_authorization: {\n enabled: true,\n site_pays: PCT(0.0075),\n user_share_pct: 0.65,\n },\n payment_method_connected: {\n enabled: true,\n site_pays: FIXED(320),\n user_share_pct: 0.65,\n },\n },\n },\n {\n id: 'marketplace',\n label: 'marketplace',\n summary:\n 'Two-sided marketplace · buyers + sellers transact. Heavy on payment_authorization and scoped_action_authorization for listings.',\n examples: ['Stripe-like checkout', 'Etsy-like marketplace', 'Uber-like ride-hailing'],\n events: {\n account_creation: {\n enabled: true,\n site_pays: FIXED(1300),\n user_share_pct: 0.65,\n },\n session_creation: {\n enabled: true,\n site_pays: FIXED(55),\n user_share_pct: 0.65,\n },\n payment_authorization: {\n enabled: true,\n site_pays: PCT(0.0075),\n user_share_pct: 0.65,\n },\n scoped_action_authorization: {\n enabled: true,\n site_pays: FIXED(100),\n user_share_pct: 0.65,\n },\n payment_method_connected: {\n enabled: true,\n site_pays: FIXED(320),\n user_share_pct: 0.65,\n },\n attest_verification_at_gate: {\n enabled: true,\n site_pays: FIXED(280),\n user_share_pct: 0.65,\n },\n },\n },\n {\n id: 'content-platform',\n label: 'content platform',\n summary:\n 'User-generated content · posts, reviews, votes, comments. Each meaningful action is scoped_action_authorization; stamp_signing for credentialed reviews.',\n examples: ['Reddit-like forum', 'YouTube-like video host', 'Substack-like publishing'],\n events: {\n account_creation: {\n enabled: true,\n site_pays: FIXED(1300),\n user_share_pct: 0.7,\n },\n session_creation: {\n enabled: true,\n site_pays: FIXED(55),\n user_share_pct: 0.7,\n },\n scoped_action_authorization: {\n enabled: true,\n site_pays: FIXED(100),\n user_share_pct: 0.7,\n },\n stamp_signing: {\n enabled: true,\n site_pays: FIXED(55),\n user_share_pct: 0.7,\n },\n },\n },\n {\n id: 'gaming',\n label: 'gaming',\n summary:\n 'Game with monetized actions · pledges + scoped actions are core. Higher cashback ratios reward in-game engagement.',\n examples: [\n 'on-chain prediction markets',\n 'skill-staking tournaments',\n 'PvP wager games',\n ],\n events: {\n account_creation: {\n enabled: true,\n site_pays: FIXED(1300),\n user_share_pct: 0.7,\n },\n session_creation: {\n enabled: true,\n site_pays: FIXED(55),\n user_share_pct: 0.7,\n },\n scoped_action_authorization: {\n enabled: true,\n site_pays: FIXED(100),\n user_share_pct: 0.7,\n },\n payment_authorization: {\n enabled: true,\n site_pays: PCT(0.005),\n user_share_pct: 0.7,\n },\n pledge_resolution: {\n enabled: true,\n site_pays: PCT(0.01),\n user_share_pct: 0.7,\n },\n attest_verification_at_gate: {\n enabled: true,\n site_pays: FIXED(280),\n user_share_pct: 0.7,\n },\n },\n },\n {\n id: 'agent-only',\n label: 'agent-only',\n summary:\n 'AI-agent surface · oc-agent delegations are the primary auth pattern. Session_creation off (delegations replace sessions); agent_delegation_issued + scoped_action_authorization carry the activity.',\n examples: [\n 'AI assistant calling APIs on user behalf',\n 'autonomous trading bot',\n 'agent-driven customer support',\n ],\n events: {\n account_creation: {\n enabled: true,\n site_pays: FIXED(1300),\n user_share_pct: 0.65,\n },\n agent_delegation_issued: {\n enabled: true,\n site_pays: FIXED(320),\n user_share_pct: 0.65,\n },\n scoped_action_authorization: {\n enabled: true,\n site_pays: FIXED(100),\n user_share_pct: 0.65,\n },\n },\n },\n];\n\nconst ARCHETYPES_BY_ID: Record<IntegratorArchetype, ArchetypeTemplate> = Object.fromEntries(\n ARCHETYPE_TEMPLATES.map((t) => [t.id, t])\n) as Record<IntegratorArchetype, ArchetypeTemplate>;\n\n/** All 12 subtypes — used to fill `enabled: false` defaults for any\n * subtype the chosen archetype doesn't list. */\nconst ALL_SUBTYPES: readonly EventSubtype[] = [\n 'account_creation',\n 'account_recovery',\n 'attest_bond_increased',\n 'payment_method_connected',\n 'agent_delegation_issued',\n 'recovery_method_updated',\n 'payment_authorization',\n 'scoped_action_authorization',\n 'attest_verification_at_gate',\n 'stamp_signing',\n 'pledge_resolution',\n 'session_creation',\n];\n\nconst DEFAULT_DISABLED: IntegratorEventConfig = {\n enabled: false,\n site_pays: { kind: 'fixed_sats', sats: 100 },\n user_share_pct: 0.65,\n};\n\n/**\n * Build a complete IntegratorPriceConfig from an archetype id + the\n * project's identity fields. Every subtype gets an entry — the\n * archetype's listed subtypes get the template's pricing; everything\n * else gets `enabled: false` with conservative defaults so the config\n * is type-complete and the integrator can flip-on later subtypes\n * without re-deriving prices.\n *\n * Throws synchronously if `useCase` isn't a known archetype id.\n */\nexport function fromTemplate(\n useCase: IntegratorArchetype,\n identity: ProjectIdentity\n): IntegratorPriceConfig {\n const template = ARCHETYPES_BY_ID[useCase];\n if (!template) {\n throw new Error(\n `oc.config.fromTemplate: unknown archetype \"${useCase}\". Valid: ${Object.keys(\n ARCHETYPES_BY_ID\n ).join(', ')}`\n );\n }\n const events: IntegratorPriceConfig['events'] = {};\n for (const sub of ALL_SUBTYPES) {\n events[sub] = template.events[sub] ?? DEFAULT_DISABLED;\n }\n return {\n project_key: identity.project_key,\n domain: identity.domain,\n display_name: identity.display_name,\n updated_at: new Date().toISOString(),\n events,\n };\n}\n\n/** Look up a template's metadata · used by config-editor UIs to render\n * \"you're on the X template · here's what it enables\" copy. */\nexport function getArchetypeTemplate(id: IntegratorArchetype): ArchetypeTemplate {\n return ARCHETYPES_BY_ID[id];\n}\n","/**\n * `oc.config` — IntegratorPriceConfig helpers.\n *\n * oc.config.fromTemplate(useCase, identity) · build a complete\n * config from one of the curated archetypes (\"saas-paywall\",\n * \"marketplace\", \"content-platform\", \"gaming\", \"agent-only\").\n * Returns a type-complete config you can submit, or tweak before\n * submitting.\n *\n * oc.config.validate(cfg) · local validator, no network call.\n * Mirrors the server-side rules; run before posting to catch\n * shape errors at edit time.\n *\n * oc.config.archetypes · the catalog of available templates with\n * metadata. Useful for rendering an archetype picker in your\n * own UI before calling fromTemplate().\n *\n * Example · zero-to-config in three lines:\n *\n * import { oc } from '@orangecheck/me-client';\n *\n * const cfg = oc.config.fromTemplate('saas-paywall', {\n * project_key: 'pk_live_yourcompany',\n * domain: 'yoursite.com',\n * display_name: 'Your Site',\n * });\n * const result = oc.config.validate(cfg);\n * // → submit cfg via the project upsert API\n *\n * Per-project read/write of the config is owner-gated and lives at\n * /api/me/projects/[id] (POST to update). See me.ochk.io/me/projects/\n * for the dashboard UI.\n */\n\nimport {\n ARCHETYPE_TEMPLATES,\n fromTemplate,\n getArchetypeTemplate,\n type ArchetypeTemplate,\n type IntegratorArchetype,\n} from './templates';\nimport { validateIntegratorConfig } from './types';\nimport type { IntegratorPriceConfig, ValidationResult } from './types';\n\nfunction validate(cfg: IntegratorPriceConfig): ValidationResult {\n return validateIntegratorConfig(cfg);\n}\n\nexport const config = {\n validate,\n fromTemplate,\n /** Look up a template's metadata · for rendering \"you picked X\"\n * state and offering one-click swaps in your own UI. */\n getArchetype: getArchetypeTemplate,\n /** All available archetypes · render in a picker. */\n archetypes: ARCHETYPE_TEMPLATES,\n};\n\nexport type { ArchetypeTemplate, IntegratorArchetype };\n","export const encoder = new TextEncoder();\nexport const decoder = new TextDecoder();\nconst MAX_INT32 = 2 ** 32;\nexport function concat(...buffers) {\n const size = buffers.reduce((acc, { length }) => acc + length, 0);\n const buf = new Uint8Array(size);\n let i = 0;\n for (const buffer of buffers) {\n buf.set(buffer, i);\n i += buffer.length;\n }\n return buf;\n}\nfunction writeUInt32BE(buf, value, offset) {\n if (value < 0 || value >= MAX_INT32) {\n throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);\n }\n buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset);\n}\nexport function uint64be(value) {\n const high = Math.floor(value / MAX_INT32);\n const low = value % MAX_INT32;\n const buf = new Uint8Array(8);\n writeUInt32BE(buf, high, 0);\n writeUInt32BE(buf, low, 4);\n return buf;\n}\nexport function uint32be(value) {\n const buf = new Uint8Array(4);\n writeUInt32BE(buf, value);\n return buf;\n}\nexport function encode(string) {\n const bytes = new Uint8Array(string.length);\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code > 127) {\n throw new TypeError('non-ASCII string encountered in encode()');\n }\n bytes[i] = code;\n }\n return bytes;\n}\n","export function encodeBase64(input) {\n if (Uint8Array.prototype.toBase64) {\n return input.toBase64();\n }\n const CHUNK_SIZE = 0x8000;\n const arr = [];\n for (let i = 0; i < input.length; i += CHUNK_SIZE) {\n arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));\n }\n return btoa(arr.join(''));\n}\nexport function decodeBase64(encoded) {\n if (Uint8Array.fromBase64) {\n return Uint8Array.fromBase64(encoded);\n }\n const binary = atob(encoded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n","import { encoder, decoder } from '../lib/buffer_utils.js';\nimport { encodeBase64, decodeBase64 } from '../lib/base64.js';\nexport function decode(input) {\n if (Uint8Array.fromBase64) {\n return Uint8Array.fromBase64(typeof input === 'string' ? input : decoder.decode(input), {\n alphabet: 'base64url',\n });\n }\n let encoded = input;\n if (encoded instanceof Uint8Array) {\n encoded = decoder.decode(encoded);\n }\n encoded = encoded.replace(/-/g, '+').replace(/_/g, '/');\n try {\n return decodeBase64(encoded);\n }\n catch {\n throw new TypeError('The input to be decoded is not correctly encoded.');\n }\n}\nexport function encode(input) {\n let unencoded = input;\n if (typeof unencoded === 'string') {\n unencoded = encoder.encode(unencoded);\n }\n if (Uint8Array.prototype.toBase64) {\n return unencoded.toBase64({ alphabet: 'base64url', omitPadding: true });\n }\n return encodeBase64(unencoded).replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n","export class JOSEError extends Error {\n static code = 'ERR_JOSE_GENERIC';\n code = 'ERR_JOSE_GENERIC';\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class JWTClaimValidationFailed extends JOSEError {\n static code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n claim;\n reason;\n payload;\n constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n super(message, { cause: { claim, reason, payload } });\n this.claim = claim;\n this.reason = reason;\n this.payload = payload;\n }\n}\nexport class JWTExpired extends JOSEError {\n static code = 'ERR_JWT_EXPIRED';\n code = 'ERR_JWT_EXPIRED';\n claim;\n reason;\n payload;\n constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n super(message, { cause: { claim, reason, payload } });\n this.claim = claim;\n this.reason = reason;\n this.payload = payload;\n }\n}\nexport class JOSEAlgNotAllowed extends JOSEError {\n static code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n}\nexport class JOSENotSupported extends JOSEError {\n static code = 'ERR_JOSE_NOT_SUPPORTED';\n code = 'ERR_JOSE_NOT_SUPPORTED';\n}\nexport class JWEDecryptionFailed extends JOSEError {\n static code = 'ERR_JWE_DECRYPTION_FAILED';\n code = 'ERR_JWE_DECRYPTION_FAILED';\n constructor(message = 'decryption operation failed', options) {\n super(message, options);\n }\n}\nexport class JWEInvalid extends JOSEError {\n static code = 'ERR_JWE_INVALID';\n code = 'ERR_JWE_INVALID';\n}\nexport class JWSInvalid extends JOSEError {\n static code = 'ERR_JWS_INVALID';\n code = 'ERR_JWS_INVALID';\n}\nexport class JWTInvalid extends JOSEError {\n static code = 'ERR_JWT_INVALID';\n code = 'ERR_JWT_INVALID';\n}\nexport class JWKInvalid extends JOSEError {\n static code = 'ERR_JWK_INVALID';\n code = 'ERR_JWK_INVALID';\n}\nexport class JWKSInvalid extends JOSEError {\n static code = 'ERR_JWKS_INVALID';\n code = 'ERR_JWKS_INVALID';\n}\nexport class JWKSNoMatchingKey extends JOSEError {\n static code = 'ERR_JWKS_NO_MATCHING_KEY';\n code = 'ERR_JWKS_NO_MATCHING_KEY';\n constructor(message = 'no applicable key found in the JSON Web Key Set', options) {\n super(message, options);\n }\n}\nexport class JWKSMultipleMatchingKeys extends JOSEError {\n [Symbol.asyncIterator];\n static code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n constructor(message = 'multiple matching keys found in the JSON Web Key Set', options) {\n super(message, options);\n }\n}\nexport class JWKSTimeout extends JOSEError {\n static code = 'ERR_JWKS_TIMEOUT';\n code = 'ERR_JWKS_TIMEOUT';\n constructor(message = 'request timed out', options) {\n super(message, options);\n }\n}\nexport class JWSSignatureVerificationFailed extends JOSEError {\n static code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n constructor(message = 'signature verification failed', options) {\n super(message, options);\n }\n}\n","const isObjectLike = (value) => typeof value === 'object' && value !== null;\nexport function isObject(input) {\n if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') {\n return false;\n }\n if (Object.getPrototypeOf(input) === null) {\n return true;\n }\n let proto = input;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n return Object.getPrototypeOf(input) === proto;\n}\nexport function isDisjoint(...headers) {\n const sources = headers.filter(Boolean);\n if (sources.length === 0 || sources.length === 1) {\n return true;\n }\n let acc;\n for (const header of sources) {\n const parameters = Object.keys(header);\n if (!acc || acc.size === 0) {\n acc = new Set(parameters);\n continue;\n }\n for (const parameter of parameters) {\n if (acc.has(parameter)) {\n return false;\n }\n acc.add(parameter);\n }\n }\n return true;\n}\nexport const isJWK = (key) => isObject(key) && typeof key.kty === 'string';\nexport const isPrivateJWK = (key) => key.kty !== 'oct' &&\n ((key.kty === 'AKP' && typeof key.priv === 'string') || typeof key.d === 'string');\nexport const isPublicJWK = (key) => key.kty !== 'oct' && key.d === undefined && key.priv === undefined;\nexport const isSecretJWK = (key) => key.kty === 'oct' && typeof key.k === 'string';\n","import { JOSENotSupported } from '../util/errors.js';\nconst unsupportedAlg = 'Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value';\nfunction subtleMapping(jwk) {\n let algorithm;\n let keyUsages;\n switch (jwk.kty) {\n case 'AKP': {\n switch (jwk.alg) {\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n algorithm = { name: jwk.alg };\n keyUsages = jwk.priv ? ['sign'] : ['verify'];\n break;\n default:\n throw new JOSENotSupported(unsupportedAlg);\n }\n break;\n }\n case 'RSA': {\n switch (jwk.alg) {\n case 'PS256':\n case 'PS384':\n case 'PS512':\n algorithm = { name: 'RSA-PSS', hash: `SHA-${jwk.alg.slice(-3)}` };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'RS256':\n case 'RS384':\n case 'RS512':\n algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${jwk.alg.slice(-3)}` };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512':\n algorithm = {\n name: 'RSA-OAEP',\n hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`,\n };\n keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey'];\n break;\n default:\n throw new JOSENotSupported(unsupportedAlg);\n }\n break;\n }\n case 'EC': {\n switch (jwk.alg) {\n case 'ES256':\n case 'ES384':\n case 'ES512':\n algorithm = {\n name: 'ECDSA',\n namedCurve: { ES256: 'P-256', ES384: 'P-384', ES512: 'P-521' }[jwk.alg],\n };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW':\n algorithm = { name: 'ECDH', namedCurve: jwk.crv };\n keyUsages = jwk.d ? ['deriveBits'] : [];\n break;\n default:\n throw new JOSENotSupported(unsupportedAlg);\n }\n break;\n }\n case 'OKP': {\n switch (jwk.alg) {\n case 'Ed25519':\n case 'EdDSA':\n algorithm = { name: 'Ed25519' };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW':\n algorithm = { name: jwk.crv };\n keyUsages = jwk.d ? ['deriveBits'] : [];\n break;\n default:\n throw new JOSENotSupported(unsupportedAlg);\n }\n break;\n }\n default:\n throw new JOSENotSupported('Invalid or unsupported JWK \"kty\" (Key Type) Parameter value');\n }\n return { algorithm, keyUsages };\n}\nexport async function jwkToKey(jwk) {\n if (!jwk.alg) {\n throw new TypeError('\"alg\" argument is required when \"jwk.alg\" is not present');\n }\n const { algorithm, keyUsages } = subtleMapping(jwk);\n const keyData = { ...jwk };\n if (keyData.kty !== 'AKP') {\n delete keyData.alg;\n }\n delete keyData.use;\n return crypto.subtle.importKey('jwk', keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);\n}\n","import { decode as decodeBase64URL } from '../util/base64url.js';\nimport { fromSPKI, fromPKCS8, fromX509 } from '../lib/asn1.js';\nimport { jwkToKey } from '../lib/jwk_to_key.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport { isObject } from '../lib/type_checks.js';\nexport async function importSPKI(spki, alg, options) {\n if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) {\n throw new TypeError('\"spki\" must be SPKI formatted string');\n }\n return fromSPKI(spki, alg, options);\n}\nexport async function importX509(x509, alg, options) {\n if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) {\n throw new TypeError('\"x509\" must be X.509 formatted string');\n }\n return fromX509(x509, alg, options);\n}\nexport async function importPKCS8(pkcs8, alg, options) {\n if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) {\n throw new TypeError('\"pkcs8\" must be PKCS#8 formatted string');\n }\n return fromPKCS8(pkcs8, alg, options);\n}\nexport async function importJWK(jwk, alg, options) {\n if (!isObject(jwk)) {\n throw new TypeError('JWK must be an object');\n }\n let ext;\n alg ??= jwk.alg;\n ext ??= options?.extractable ?? jwk.ext;\n switch (jwk.kty) {\n case 'oct':\n if (typeof jwk.k !== 'string' || !jwk.k) {\n throw new TypeError('missing \"k\" (Key Value) Parameter value');\n }\n return decodeBase64URL(jwk.k);\n case 'RSA':\n if ('oth' in jwk && jwk.oth !== undefined) {\n throw new JOSENotSupported('RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported');\n }\n return jwkToKey({ ...jwk, alg, ext });\n case 'AKP': {\n if (typeof jwk.alg !== 'string' || !jwk.alg) {\n throw new TypeError('missing \"alg\" (Algorithm) Parameter value');\n }\n if (alg !== undefined && alg !== jwk.alg) {\n throw new TypeError('JWK alg and alg option value mismatch');\n }\n return jwkToKey({ ...jwk, ext });\n }\n case 'EC':\n case 'OKP':\n return jwkToKey({ ...jwk, alg, ext });\n default:\n throw new JOSENotSupported('Unsupported \"kty\" (Key Type) Parameter value');\n }\n}\n","/**\n * `oc.webhook.verify` — Ed25519 signature verification for me.ochk.io\n * webhook deliveries.\n *\n * Webhook envelopes are signed with the auth host's Ed25519 key. The\n * signature is sent as a hex string in the `OC-Signature` header, and\n * the kid is in the `OC-Key-Id` header.\n *\n * import { oc } from '@orangecheck/me-client';\n *\n * // In your webhook handler — pass RAW BODY BYTES, not the parsed\n * // JSON. Frameworks that re-serialize before your handler will\n * // produce a different byte sequence and the signature will not\n * // validate.\n * const result = await oc.webhook.verify(\n * rawBody, // string | Uint8Array\n * req.headers['oc-signature'], // hex\n * req.headers['oc-key-id'] // kid\n * );\n * if (!result.ok) return res.status(401).send(result.reason);\n *\n * The verifier auto-fetches and caches the webhook-signing JWKS at\n * `https://me.ochk.io/api/dev-jwks` for 1h. Pass `{ jwk }` to skip the\n * network round-trip if you've embedded the key.\n *\n * It used to fetch `https://ochk.io/.well-known/jwks.json` — the family\n * SESSION key, a different key for a different job — so every verification\n * that did not pass `{ jwk }` failed with `kid … not in JWKS` before it could\n * check anything.\n */\n\nimport { importJWK, type CryptoKey, type KeyObject } from 'jose';\n\n/** me.ochk.io signs its own webhook deliveries; the family auth host does not.\n * Its published key lives at /api/dev-jwks (the path is historical — the note\n * in that document names it as the production webhook-signing key). */\nconst DEFAULT_ISSUER = 'https://me.ochk.io';\nconst JWKS_PATH = '/api/dev-jwks';\nconst DEFAULT_TTL_MS = 60 * 60 * 1000;\n\nexport interface VerifyResult {\n ok: boolean;\n reason?: string;\n}\n\nexport interface OcPublicJwk {\n kty: 'OKP';\n crv: 'Ed25519';\n x: string;\n kid: string;\n alg?: 'EdDSA';\n use?: 'sig';\n}\n\nexport interface VerifyOptions {\n /** Override the auth host issuer. Defaults to https://ochk.io. */\n issuer?: string;\n /** Pass a JWK directly to skip the network fetch entirely. Useful\n * for tests, edge runtimes that can't fetch, or integrators that\n * ship the public key alongside their webhook handler. */\n jwk?: OcPublicJwk;\n /** JWKS cache TTL in ms. Defaults to 1 hour. Stale-on-error: a\n * transient JWKS outage falls back to the previous cached value\n * rather than rejecting every webhook. */\n jwksCacheTtlMs?: number;\n}\n\ntype AuthKey = CryptoKey | KeyObject;\n\ninterface JwksCacheEntry {\n keys: Record<string, AuthKey>;\n fetchedAt: number;\n}\n\nconst jwksCache = new Map<string, JwksCacheEntry>();\nconst inflight = new Map<string, Promise<JwksCacheEntry>>();\n\nasync function fetchJwks(issuer: string, ttlMs: number): Promise<JwksCacheEntry> {\n const cached = jwksCache.get(issuer);\n if (cached && Date.now() - cached.fetchedAt < ttlMs) return cached;\n const existing = inflight.get(issuer);\n if (existing) return existing;\n const p = (async (): Promise<JwksCacheEntry> => {\n try {\n const url = `${issuer.replace(/\\/$/, '')}${JWKS_PATH}`;\n const res = await fetch(url, { headers: { Accept: 'application/json' } });\n if (!res.ok) throw new Error(`JWKS fetch ${url} returned ${res.status}`);\n const json = (await res.json()) as { keys: OcPublicJwk[] };\n if (!json || !Array.isArray(json.keys)) {\n throw new Error(`JWKS at ${url} did not return {keys:[…]}`);\n }\n const keys: Record<string, AuthKey> = {};\n for (const k of json.keys) {\n if (typeof k.kid !== 'string') continue;\n try {\n keys[k.kid] = (await importJWK(k, 'EdDSA')) as AuthKey;\n } catch {\n /* skip keys that won't import */\n }\n }\n const entry: JwksCacheEntry = { keys, fetchedAt: Date.now() };\n jwksCache.set(issuer, entry);\n return entry;\n } catch (err) {\n const stale = jwksCache.get(issuer);\n if (stale) return stale;\n throw err;\n }\n })().finally(() => {\n inflight.delete(issuer);\n });\n inflight.set(issuer, p);\n return p;\n}\n\nfunction hexToBytes(hex: string): Uint8Array | null {\n if (typeof hex !== 'string') return null;\n const s = hex.trim();\n if (s.length === 0 || s.length % 2 !== 0) return null;\n const out = new Uint8Array(s.length / 2);\n for (let i = 0; i < out.length; i++) {\n const b = parseInt(s.slice(i * 2, i * 2 + 2), 16);\n if (Number.isNaN(b)) return null;\n out[i] = b;\n }\n return out;\n}\n\nfunction toBytes(input: string | Uint8Array): Uint8Array {\n if (typeof input === 'string') return new TextEncoder().encode(input);\n return input;\n}\n\nfunction toArrayBuffer(view: Uint8Array): ArrayBuffer {\n // SubtleCrypto's BufferSource type requires Uint8Array<ArrayBuffer>\n // (not ArrayBufferLike). Copy into a fresh ArrayBuffer so the\n // resulting buffer is statically typed as ArrayBuffer (slicing a\n // SharedArrayBuffer would yield SharedArrayBuffer which the type\n // system rejects).\n const buf = new ArrayBuffer(view.byteLength);\n new Uint8Array(buf).set(view);\n return buf;\n}\n\nasync function verifyEd25519(\n key: AuthKey,\n sig: Uint8Array,\n msg: Uint8Array\n): Promise<boolean> {\n // jose normalizes the key into a CryptoKey under WebCrypto-capable\n // runtimes (Node 20+, Vercel Edge, modern browsers); fall through\n // to subtle.verify for the actual signature check.\n const subtle =\n typeof globalThis.crypto !== 'undefined' && globalThis.crypto.subtle\n ? globalThis.crypto.subtle\n : null;\n if (!subtle) return false;\n try {\n return await subtle.verify(\n 'Ed25519',\n key as CryptoKey,\n toArrayBuffer(sig),\n toArrayBuffer(msg)\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Verify a webhook signature. Pass the raw body bytes (not parsed\n * JSON), the hex-encoded signature from the `OC-Signature` header, and\n * the kid from the `OC-Key-Id` header.\n *\n * Returns `{ ok: true }` on success, `{ ok: false, reason }` on any\n * failure (bad signature, kid not in JWKS, malformed signature,\n * network-only JWKS fetch failed without prior cache, etc.). Never\n * throws.\n */\nexport async function verify(\n rawBody: string | Uint8Array,\n sigHex: string,\n kid: string,\n options: VerifyOptions = {}\n): Promise<VerifyResult> {\n if (!sigHex) return { ok: false, reason: 'missing signature' };\n if (!kid) return { ok: false, reason: 'missing kid' };\n const sig = hexToBytes(sigHex);\n if (!sig) return { ok: false, reason: 'malformed signature (expected hex)' };\n const msg = toBytes(rawBody);\n\n let key: AuthKey | undefined;\n if (options.jwk) {\n if (options.jwk.kid !== kid) {\n return { ok: false, reason: `kid mismatch (header=${kid}, jwk=${options.jwk.kid})` };\n }\n try {\n key = (await importJWK(options.jwk, 'EdDSA')) as AuthKey;\n } catch {\n return { ok: false, reason: 'could not import provided jwk' };\n }\n } else {\n const issuer = options.issuer ?? DEFAULT_ISSUER;\n const ttl = options.jwksCacheTtlMs ?? DEFAULT_TTL_MS;\n try {\n let entry = await fetchJwks(issuer, ttl);\n key = entry.keys[kid];\n if (!key) {\n jwksCache.delete(issuer);\n entry = await fetchJwks(issuer, ttl);\n key = entry.keys[kid];\n }\n } catch (err) {\n return { ok: false, reason: `jwks unavailable: ${(err as Error).message}` };\n }\n if (!key) return { ok: false, reason: `kid ${kid} not in JWKS` };\n }\n\n const ok = await verifyEd25519(key, sig, msg);\n return ok ? { ok: true } : { ok: false, reason: 'signature does not match' };\n}\n\n/** Force-refresh the JWKS cache. Useful after a key rotation event\n * if you don't want to wait for the TTL to expire. */\nexport async function fetchJwksForce(issuer = DEFAULT_ISSUER): Promise<void> {\n jwksCache.delete(issuer);\n await fetchJwks(issuer, DEFAULT_TTL_MS);\n}\n\nexport const webhook = { verify, fetchJwks: fetchJwksForce };\n","/**\n * Federation directory · runtime discovery for the SDK.\n *\n * Consumes /api/federations from the configured origin (defaults to\n * me.ochk.io; override via `setOrigin()` for staging or self-hosted).\n * Multi-federation routing reads from this directory; v1 has one live\n * entry, but the SDK's shape is already plural so federation #2 is a\n * directory write rather than an SDK release.\n */\n\nimport { api } from './transport';\nimport type { Federation } from './types';\n\ninterface ListResponse {\n ok: boolean;\n federations: Federation[];\n}\n\n/** List every federation in the directory — recruiting, forming,\n * binding, and live. Consumers filter by status as needed. */\nasync function list(): Promise<Federation[]> {\n const res = await api<ListResponse>('/api/federations');\n return res.federations ?? [];\n}\n\n/** Return only federations currently accepting bindings — i.e.\n * status === 'live' with a non-null invite. The set the consumer\n * wallet provider can route a user wallet to. */\nasync function live(): Promise<Federation[]> {\n const all = await list();\n return all.filter((f) => f.status === 'live' && typeof f.invite === 'string' && f.invite.length > 0);\n}\n\n/** Look up a single federation by slug. Returns null if the slug\n * isn't in the directory. */\nasync function get(slug: string): Promise<Federation | null> {\n const all = await list();\n return all.find((f) => f.slug === slug) ?? null;\n}\n\n/** Default federation a fresh user/integrator should bind to when no\n * explicit policy exists yet. v1: the first live federation in the\n * directory; falls back to null if none live yet. v2+: routing\n * policy (geography, capacity, explicit choice) consults the\n * directory directly. */\nasync function defaultLive(): Promise<Federation | null> {\n const all = await live();\n return all[0] ?? null;\n}\n\nexport const federations = { list, live, get, defaultLive };\n","/**\n * `oc.scope` — privacy-preserving scope grants.\n *\n * Background:\n * By default, signing into your site via OC reveals only an anonymous\n * per-integrator subject (`sub`). The user's master identity (BIP-322\n * address or email) stays private; you cannot correlate users across\n * sites via OC. To read additional fields (their email, attest tier,\n * bitcoin address, display name), you must explicitly request the\n * matching scope and the user must explicitly consent.\n *\n * Full architecture: https://github.com/orangecheck/oc-me-web/blob/main/PRIVACY-ARCHITECTURE.md\n *\n * Two functions:\n *\n * oc.scope.granted(project_key) — read what the currently-signed-in\n * user has already granted. Returns sub + per-scope values they've\n * consented to.\n *\n * const { sub, scopes } = await oc.scope.granted({ project_key: 'pk_live_yourcompany' });\n * console.log(sub); // \"sub_3K7xQ2mN1pYwB8tRvE…\"\n * console.log(scopes.email); // \"user@example.com\" or undefined\n *\n * oc.scope.request(scopes, opts) — redirect the user to me.ochk.io's\n * consent prompt. After they grant or deny, browser returns to\n * return_to. Subsequent oc.scope.granted() calls reflect their\n * decisions.\n *\n * await oc.scope.request(['email', 'attest_tier'], {\n * project_key: 'pk_live_yourcompany',\n * return_to: window.location.href,\n * });\n */\n\nimport { api, getOrigin } from './transport';\n\n/** Catalog of valid scopes · keep in sync with SCOPE_IDS in\n * oc-me-web/src/lib/privacy/scopes.ts.\n *\n * cross_integrator_event_count · per OCHK-V2-PLAN §7 · low-info\n * sybil signal aggregating event count across every integrator.\n * cross_integrator_human_event_count · per OCHK-V3-PLAN §7 · same\n * aggregate filtered to is_agent !== true (human-fired only).\n * Use when you want to gate on real human activity rather than\n * bot-padded counts.\n * trust_attestation_count · per OCHK-V3-PLAN §6 phase-2 · four-int\n * selective-disclosure quad summarizing reputation-graph attestations.\n * Use parseTrustAttestationCount() to decode the wire-format string. */\nexport type Scope =\n | 'bitcoin_address'\n | 'email'\n | 'attest_tier'\n | 'display_name'\n | 'cross_integrator_event_count'\n | 'cross_integrator_human_event_count'\n | 'trust_attestation_count';\n\nconst VALID_SCOPES: ReadonlyArray<Scope> = [\n 'bitcoin_address',\n 'email',\n 'attest_tier',\n 'display_name',\n 'cross_integrator_event_count',\n 'cross_integrator_human_event_count',\n 'trust_attestation_count',\n];\n\n/** Decoded shape of the `trust_attestation_count` scope value. The wire\n * format is a comma-separated quad: total,good,distinct_good_issuers,caution.\n * Block-status counts are intentionally omitted from the disclosure\n * surface — block flags belong to the pseudonymous-issuer side, not\n * the subject's public score. */\nexport interface TrustAttestationCount {\n total: number;\n good: number;\n distinct_good_issuers: number;\n caution: number;\n}\n\n/** Decode the `trust_attestation_count` scope's wire-format string into\n * a typed quad. Returns null if the input is malformed (defensive ·\n * the resolver always emits well-formed strings, but third-party\n * consumers may hand us anything). */\nexport function parseTrustAttestationCount(value: string): TrustAttestationCount | null {\n const parts = value.split(',');\n if (parts.length !== 4) return null;\n const ints = parts.map((p) => Number.parseInt(p, 10));\n if (ints.some((n) => !Number.isInteger(n) || n < 0)) return null;\n return {\n total: ints[0]!,\n good: ints[1]!,\n distinct_good_issuers: ints[2]!,\n caution: ints[3]!,\n };\n}\n\nexport interface GrantedOptions {\n /** Your project_key. Required. */\n project_key: string;\n signal?: AbortSignal;\n}\n\nexport interface GrantedResult {\n /** Per-integrator stable subject for the currently-signed-in user.\n * This is what your backend should key user records on (NOT the\n * master addr · which OC doesn't reveal). */\n sub: string;\n /** Scopes the user has actively granted to this project. Subset of\n * the requested scopes, filtered for not-revoked + not-expired. */\n scopes_granted: Scope[];\n /** Resolved values for the granted scopes. Only fields whose scope\n * is in `scopes_granted` are present. */\n scopes: Partial<Record<Scope, string>>;\n}\n\nasync function granted(options: GrantedOptions): Promise<GrantedResult> {\n if (!options.project_key) {\n throw new Error('oc.scope.granted: project_key is required');\n }\n const r = await api<{ ok: boolean; sub: string; scopes_granted: Scope[]; scopes: Partial<Record<Scope, string>> }>(\n `/api/integrator/scopes/${encodeURIComponent(options.project_key)}`,\n { method: 'GET', signal: options.signal }\n );\n return {\n sub: r.sub,\n scopes_granted: r.scopes_granted,\n scopes: r.scopes,\n };\n}\n\nexport interface RequestOptions {\n /** Your project_key. Required. */\n project_key: string;\n /** Where to bounce the user after they decide. Required.\n * Same-origin only — me.ochk.io rejects cross-origin redirects to\n * prevent the consent prompt from being weaponized in phishing. */\n return_to: string;\n /** Override the OC origin (only useful for staging deployments;\n * defaults to https://me.ochk.io via getOrigin()). */\n origin?: string;\n}\n\n/** Redirect the user to me.ochk.io's consent prompt. After they decide,\n * browser returns to `return_to`. The scope grants are persisted\n * server-side; subsequent calls to oc.scope.granted() reflect their\n * decisions.\n *\n * This function does NOT return a promise that resolves to the user's\n * decisions. The redirect leaves your page; the user lands back at\n * return_to and your code re-reads granted state on mount.\n *\n * Consent flow:\n * 1. Your code: oc.scope.request(['email'], { ... })\n * 2. Browser navigates to me.ochk.io/me/scope-grant?…\n * 3. User decides per-scope (grant once / always / deny)\n * 4. Browser redirects back to return_to\n * 5. Your code re-runs oc.scope.granted(...) on mount\n *\n * Throws synchronously if the inputs are invalid (so the redirect is\n * never issued with malformed params). */\nexport function request(scopes: Scope[], options: RequestOptions): never {\n if (!options.project_key) {\n throw new Error('oc.scope.request: project_key is required');\n }\n if (!options.return_to) {\n throw new Error('oc.scope.request: return_to is required');\n }\n if (!Array.isArray(scopes) || scopes.length === 0) {\n throw new Error('oc.scope.request: scopes must be a non-empty array');\n }\n for (const s of scopes) {\n if (!VALID_SCOPES.includes(s)) {\n throw new Error(\n `oc.scope.request: unknown scope \"${s}\" · valid: ${VALID_SCOPES.join(', ')}`\n );\n }\n }\n if (typeof window === 'undefined') {\n throw new Error('oc.scope.request: must be called in a browser environment');\n }\n const origin = options.origin ?? getOrigin();\n const url = new URL('/me/scope-grant', origin);\n url.searchParams.set('project_key', options.project_key);\n url.searchParams.set('scopes', scopes.join(','));\n url.searchParams.set('return_to', options.return_to);\n window.location.assign(url.toString());\n // assign() doesn't return synchronously in a way TS can encode, but\n // by the time anything else runs, navigation is in flight. Throw to\n // make the never-returning behavior explicit.\n throw new Error('oc.scope.request: redirected to consent prompt');\n}\n\nexport const scope = { granted, request, parseTrustAttestationCount };\n","/**\n * `oc.family` — cross-family scope grants.\n *\n * Per OCHK-V3-PLAN §10 phase-1. The OrangeCheck family is one auth host\n * (ochk.io) and a set of sibling products (vote.ochk.io, stamp.ochk.io,\n * agent.ochk.io, attest.ochk.io, lock.ochk.io). When a user grants a\n * cross-family scope to a sibling, that grant is stored on me.ochk.io\n * under a reserved `family:<verb>` project_key.\n *\n * Sibling-side surfaces use `oc.family.scopes('oc-vote')` to consult\n * the active grants the user has issued for their product. The helper\n * is structurally identical to `oc.scope.granted({ project_key })`\n * except that the project_key is implied from the verb.\n *\n * const { sub, scopes } = await oc.family.scopes('oc-vote');\n * if (scopes.cross_integrator_human_event_count) {\n * gateBallot(parseInt(scopes.cross_integrator_human_event_count, 10));\n * }\n *\n * Auth: the user's `oc_session` cookie (Domain=.ochk.io) carries\n * authenticate-once-anywhere across the family. The fetch goes against\n * the me.ochk.io origin with credentials.\n *\n * Same auto-renew behavior as the integrator-side `oc.scope.granted`:\n * a sibling consulting cross-family scopes counts as use, so a granting\n * user who interacts with a sibling regularly won't see their grant\n * expire from under them (per V3-PLAN §5).\n */\n\nimport type { Scope } from './scope';\n\nexport type FamilyVerb = 'oc-vote' | 'oc-stamp' | 'oc-agent' | 'oc-attest' | 'oc-lock' | 'oc-pledge';\n\nconst VALID_VERBS: ReadonlyArray<FamilyVerb> = [\n 'oc-vote',\n 'oc-stamp',\n 'oc-agent',\n 'oc-attest',\n 'oc-lock',\n 'oc-pledge',\n];\n\nexport interface FamilyScopesOptions {\n /** Override the OC family origin · only useful for staging.\n * Defaults to https://me.ochk.io · the family-side scope reads\n * always go to me.ochk regardless of which sibling is calling. */\n origin?: string;\n signal?: AbortSignal;\n}\n\nexport interface FamilyScopesResult {\n /** Per-sibling stable subject for the currently-signed-in user.\n * Anonymous · derived from master_addr + the family:<verb>\n * project_key. Sibling backends key on this. */\n sub: string;\n /** Sibling product the grants are scoped to (echoed for logging /\n * debug). */\n family_product: {\n verb: FamilyVerb;\n name: string;\n origin: string;\n };\n /** Scopes the user has actively granted to this sibling. Subset of\n * the requested set, filtered for not-revoked + not-expired. */\n scopes_granted: Scope[];\n /** Resolved values for the granted scopes. Only fields whose scope\n * is in `scopes_granted` are present. */\n scopes: Partial<Record<Scope, string>>;\n}\n\n/**\n * Read the cross-family scope grants the user has issued to the named\n * sibling product. Browser-side · uses cookie credentials.\n *\n * Errors thrown:\n * - `unknown_family_verb` if `verb` is not in the family allowlist\n * - `sign in required` (401) if no oc_session cookie present\n * - `unknown_family_verb` (404) if me.ochk doesn't recognize the verb\n *\n * If you need to drive a consent prompt for a verb the user hasn't\n * granted yet, use `oc.scope.request(scopes, { project_key:\n * 'family:<verb>', return_to })` — the consent prompt page detects the\n * `family:` prefix and renders the sibling-product chrome.\n */\nasync function scopes(verb: FamilyVerb, options?: FamilyScopesOptions): Promise<FamilyScopesResult> {\n if (!VALID_VERBS.includes(verb)) {\n throw new Error(\n `oc.family.scopes: unknown verb \"${verb}\" · valid: ${VALID_VERBS.join(', ')}`\n );\n }\n const origin = options?.origin ?? 'https://me.ochk.io';\n const url = `${origin}/api/family/scopes/${encodeURIComponent(verb)}`;\n const res = await fetch(url, {\n method: 'GET',\n credentials: 'include',\n signal: options?.signal,\n });\n if (!res.ok) {\n const txt = await res.text().catch(() => '');\n throw new Error(`oc.family.scopes: ${res.status} ${txt || res.statusText}`);\n }\n const json = (await res.json()) as FamilyScopesResult & { ok?: boolean };\n return {\n sub: json.sub,\n family_product: json.family_product,\n scopes_granted: json.scopes_granted,\n scopes: json.scopes,\n };\n}\n\nexport const family = { scopes };\n","/**\n * `oc.identity.verifyActivityAttestation` — one-call ed25519 verifier\n * for a /api/me/activity-attestation bundle.\n *\n * Cashes the \"trivially to verify\" strategic claim: an integrator\n * receiving a signed attestation JSON from a user calls one function,\n * gets a typed result with per-check detail, never reaches into\n * @noble/curves or jose themselves.\n *\n * import { oc } from '@orangecheck/me-client';\n *\n * const result = await oc.identity.verifyActivityAttestation(bundle);\n * if (!result.ok) return res.status(401).send(result.reason);\n * // result.attestation is typed · safe to gate on lifetime_sats etc.\n *\n * The JWKS issuer is me.ochk.io (the envelope key), DISTINCT from\n * the auth host's ochk.io JWKS that signs webhooks. Same Ed25519\n * curve, same kid lookup pattern, fetched + cached separately.\n */\n\nimport { importJWK, type CryptoKey, type KeyObject } from 'jose';\n\nconst DEFAULT_ISSUER = 'https://me.ochk.io';\nconst DEFAULT_TTL_MS = 60 * 60 * 1000;\nconst ENVELOPE_JWKS_PATH = '/.well-known/oc-envelope-jwks.json';\n\nexport interface ActivityAttestation {\n id: string;\n v: 1;\n kind: 'oc-me-activity';\n did_oc: string;\n event_count: number;\n human_event_count: number;\n lifetime_sats: number;\n distinct_integrator_count: number;\n oldest_event_at: string | null;\n active_days: number;\n computed_at: string;\n expires_at: string;\n}\n\nexport interface ActivityAttestationBundle {\n attestation: ActivityAttestation;\n sig: string;\n kid: string;\n canonical_b64: string;\n}\n\nexport interface ActivityVerifyCheck {\n ok: boolean;\n label: string;\n detail?: string;\n}\n\nexport interface ActivityVerifyResult {\n ok: boolean;\n reason?: string;\n attestation?: ActivityAttestation;\n checks: ActivityVerifyCheck[];\n}\n\ninterface OcEnvelopePublicJwk {\n kty: 'OKP';\n crv: 'Ed25519';\n x: string;\n kid: string;\n alg?: 'EdDSA';\n use?: 'sig';\n}\n\nexport interface VerifyActivityOptions {\n /** Override the me.ochk.io issuer (defaults to https://me.ochk.io).\n * Useful for staging / self-hosted dev. */\n issuer?: string;\n /** Pass a JWK directly to skip the network fetch · convenient when\n * embedding the public key in your service for air-gapped or\n * edge-runtime deployments. */\n jwk?: OcEnvelopePublicJwk;\n /** JWKS cache TTL in ms. Defaults to 1h. Stale-on-error falls back\n * to the previous cached value. */\n jwksCacheTtlMs?: number;\n /** Optional · override \"now\" for deterministic tests. */\n now?: Date;\n}\n\ntype AuthKey = CryptoKey | KeyObject;\n\ninterface JwksCacheEntry {\n keys: Record<string, AuthKey>;\n fetchedAt: number;\n}\n\nconst jwksCache = new Map<string, JwksCacheEntry>();\nconst inflight = new Map<string, Promise<JwksCacheEntry>>();\n\nasync function fetchEnvelopeJwks(issuer: string, ttlMs: number): Promise<JwksCacheEntry> {\n const cached = jwksCache.get(issuer);\n if (cached && Date.now() - cached.fetchedAt < ttlMs) return cached;\n const existing = inflight.get(issuer);\n if (existing) return existing;\n const p = (async (): Promise<JwksCacheEntry> => {\n try {\n const url = `${issuer.replace(/\\/$/, '')}${ENVELOPE_JWKS_PATH}`;\n const res = await fetch(url, { headers: { Accept: 'application/json' } });\n if (!res.ok) throw new Error(`envelope JWKS fetch ${url} returned ${res.status}`);\n const json = (await res.json()) as { keys: OcEnvelopePublicJwk[] };\n if (!json || !Array.isArray(json.keys)) {\n throw new Error(`envelope JWKS at ${url} did not return {keys:[…]}`);\n }\n const keys: Record<string, AuthKey> = {};\n for (const k of json.keys) {\n if (typeof k.kid !== 'string') continue;\n try {\n keys[k.kid] = (await importJWK(k, 'EdDSA')) as AuthKey;\n } catch {\n /* skip keys that won't import */\n }\n }\n const entry: JwksCacheEntry = { keys, fetchedAt: Date.now() };\n jwksCache.set(issuer, entry);\n return entry;\n } catch (err) {\n const stale = jwksCache.get(issuer);\n if (stale) return stale;\n throw err;\n }\n })().finally(() => {\n inflight.delete(issuer);\n });\n inflight.set(issuer, p);\n return p;\n}\n\nfunction hexToBytes(hex: string): Uint8Array | null {\n if (typeof hex !== 'string') return null;\n const s = hex.trim();\n if (s.length === 0 || s.length % 2 !== 0) return null;\n const out = new Uint8Array(s.length / 2);\n for (let i = 0; i < out.length; i++) {\n const b = parseInt(s.slice(i * 2, i * 2 + 2), 16);\n if (Number.isNaN(b)) return null;\n out[i] = b;\n }\n return out;\n}\n\nfunction base64ToBytes(b64: string): Uint8Array | null {\n try {\n const bin =\n typeof atob === 'function'\n ? atob(b64)\n : Buffer.from(b64, 'base64').toString('binary');\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n } catch {\n return null;\n }\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n let out = '';\n for (const b of bytes) out += b.toString(16).padStart(2, '0');\n return out;\n}\n\nasync function sha256(bytes: Uint8Array): Promise<Uint8Array> {\n const subtle =\n typeof globalThis.crypto !== 'undefined' && globalThis.crypto.subtle\n ? globalThis.crypto.subtle\n : null;\n if (!subtle) {\n throw new Error('crypto.subtle unavailable · need Node 20+ / modern browser / Edge runtime');\n }\n const buf = await subtle.digest('SHA-256', bytes as unknown as ArrayBuffer);\n return new Uint8Array(buf);\n}\n\nfunction toArrayBuffer(view: Uint8Array): ArrayBuffer {\n const buf = new ArrayBuffer(view.byteLength);\n new Uint8Array(buf).set(view);\n return buf;\n}\n\nasync function verifyEd25519(\n key: AuthKey,\n sig: Uint8Array,\n msg: Uint8Array\n): Promise<boolean> {\n const subtle =\n typeof globalThis.crypto !== 'undefined' && globalThis.crypto.subtle\n ? globalThis.crypto.subtle\n : null;\n if (!subtle) return false;\n try {\n return await subtle.verify(\n 'Ed25519',\n key as CryptoKey,\n toArrayBuffer(sig),\n toArrayBuffer(msg)\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Verify a signed activity attestation bundle. Returns a typed\n * ActivityVerifyResult with per-check detail · never throws (network\n * + parse failures surface as ok=false rows in the checks array, so\n * the caller can log them without try/catch).\n *\n * Five checks, in order: bundle shape, canonical-bytes hash matches\n * id, JWK with matching kid present, ed25519 signature, freshness.\n */\nexport async function verifyActivityAttestation(\n bundle: ActivityAttestationBundle,\n options: VerifyActivityOptions = {}\n): Promise<ActivityVerifyResult> {\n const checks: ActivityVerifyCheck[] = [];\n\n // 1. Bundle shape\n const shapeOk =\n !!bundle &&\n typeof bundle === 'object' &&\n typeof bundle.sig === 'string' &&\n typeof bundle.kid === 'string' &&\n typeof bundle.canonical_b64 === 'string' &&\n !!bundle.attestation &&\n typeof bundle.attestation.id === 'string' &&\n typeof bundle.attestation.expires_at === 'string';\n checks.push({\n ok: shapeOk,\n label: 'bundle shape · sig / kid / canonical_b64 / attestation',\n });\n if (!shapeOk) {\n return { ok: false, reason: 'bundle shape invalid', checks };\n }\n\n const a = bundle.attestation;\n\n // 2. canonical_b64 decodes\n const canonical = base64ToBytes(bundle.canonical_b64);\n checks.push({\n ok: canonical !== null,\n label: 'canonical_b64 decodes',\n detail: canonical ? `${canonical.length} bytes` : 'invalid base64',\n });\n if (!canonical) return { ok: false, reason: 'canonical_b64 invalid base64', checks, attestation: a };\n\n // 3. sha256 === id\n const digest = await sha256(canonical);\n const computedId = bytesToHex(digest);\n const idOk = computedId === a.id;\n checks.push({\n ok: idOk,\n label: 'sha256(canonical_bytes) === id',\n detail: idOk ? a.id : `expected ${a.id}, got ${computedId}`,\n });\n if (!idOk) return { ok: false, reason: 'id does not match canonical-bytes hash', checks, attestation: a };\n\n // 4. JWK lookup + ed25519 verify\n let key: AuthKey | null = null;\n if (options.jwk) {\n if (options.jwk.kid !== bundle.kid) {\n checks.push({\n ok: false,\n label: 'JWK with matching kid present',\n detail: `provided jwk.kid=${options.jwk.kid} but bundle.kid=${bundle.kid}`,\n });\n return { ok: false, reason: 'kid mismatch with provided jwk', checks, attestation: a };\n }\n try {\n key = (await importJWK(options.jwk, 'EdDSA')) as AuthKey;\n checks.push({ ok: true, label: 'JWK with matching kid present', detail: `kid ${bundle.kid} (provided)` });\n } catch (err) {\n checks.push({\n ok: false,\n label: 'JWK with matching kid present',\n detail: `provided jwk failed import: ${(err as Error).message}`,\n });\n return { ok: false, reason: 'provided jwk failed import', checks, attestation: a };\n }\n } else {\n const issuer = options.issuer ?? DEFAULT_ISSUER;\n const ttl = options.jwksCacheTtlMs ?? DEFAULT_TTL_MS;\n try {\n let entry = await fetchEnvelopeJwks(issuer, ttl);\n key = entry.keys[bundle.kid] ?? null;\n if (!key) {\n // Cache miss · likely a rotation. Force-refresh once.\n jwksCache.delete(issuer);\n entry = await fetchEnvelopeJwks(issuer, ttl);\n key = entry.keys[bundle.kid] ?? null;\n }\n checks.push({\n ok: !!key,\n label: 'JWK with matching kid present',\n detail: key ? `kid ${bundle.kid}` : `no JWK with kid ${bundle.kid} at ${issuer}${ENVELOPE_JWKS_PATH}`,\n });\n if (!key) {\n return { ok: false, reason: `kid ${bundle.kid} not in envelope JWKS`, checks, attestation: a };\n }\n } catch (err) {\n checks.push({\n ok: false,\n label: 'JWK with matching kid present',\n detail: `envelope JWKS unavailable: ${(err as Error).message}`,\n });\n return {\n ok: false,\n reason: `envelope JWKS unavailable: ${(err as Error).message}`,\n checks,\n attestation: a,\n };\n }\n }\n\n const sigBytes = hexToBytes(bundle.sig);\n if (!sigBytes) {\n checks.push({\n ok: false,\n label: 'ed25519.verify(sig, canonical_bytes, jwk.public)',\n detail: 'malformed sig (expected hex)',\n });\n return { ok: false, reason: 'malformed sig', checks, attestation: a };\n }\n const sigOk = await verifyEd25519(key, sigBytes, canonical);\n checks.push({\n ok: sigOk,\n label: 'ed25519.verify(sig, canonical_bytes, jwk.public)',\n detail: sigOk ? 'signature valid' : 'signature does not match',\n });\n if (!sigOk) return { ok: false, reason: 'signature does not match', checks, attestation: a };\n\n // 5. Freshness\n const now = options.now ?? new Date();\n const expiresMs = Date.parse(a.expires_at);\n const freshOk = Number.isFinite(expiresMs) && expiresMs > now.getTime();\n checks.push({\n ok: freshOk,\n label: 'now < attestation.expires_at',\n detail: freshOk\n ? `expires ${new Date(expiresMs).toISOString()}`\n : 'attestation has expired',\n });\n if (!freshOk) return { ok: false, reason: 'attestation has expired', checks, attestation: a };\n\n return { ok: true, attestation: a, checks };\n}\n\n/** Force-refresh the envelope-JWKS cache · useful after a key rotation\n * if you don't want to wait for the TTL to expire. */\nexport async function refreshEnvelopeJwks(issuer = DEFAULT_ISSUER): Promise<void> {\n jwksCache.delete(issuer);\n await fetchEnvelopeJwks(issuer, DEFAULT_TTL_MS);\n}\n\nexport const identity = {\n verifyActivityAttestation,\n refreshEnvelopeJwks,\n};\n","/**\n * Rich metadata for every billable event subtype.\n *\n * The SDK already exports the `EventSubtype` union (closed enum, type-\n * checked), but a new integrator picking between\n * `'scoped_action_authorization'` and `'stamp_signing'` and\n * `'attest_verification_at_gate'` has no inline guidance on which fits\n * their flow. This file is the canonical \"when do I use this subtype\"\n * reference, programmatically accessible:\n *\n * import { oc, EVENT_SUBTYPES } from '@orangecheck/me-client';\n *\n * for (const meta of Object.values(EVENT_SUBTYPES)) {\n * console.log(`${meta.id} (class ${meta.class}) — ${meta.fires_when}`);\n * }\n *\n * Or per-subtype:\n *\n * const meta = EVENT_SUBTYPES.account_creation;\n * console.log(meta.example); // → \"user signed up via email-OTP and the account row was inserted\"\n *\n * Used by `oc.config.fromTemplate()` to assemble archetype configs and\n * by /me/projects/* dashboards to drive consent prompts and config\n * editor labels from a single source.\n */\n\nimport type { EventClass, EventSubtype } from './types';\n\nexport interface EventSubtypeMetadata {\n id: EventSubtype;\n class: EventClass;\n /** Short label · matches SUBTYPE_LABELS on the server. */\n label: string;\n /** When this fires · imperative-mood plain English. The integrator\n * reads this to know which event in their codebase should call\n * `oc.event.fire()` with this subtype. */\n fires_when: string;\n /** A concrete example from a typical SaaS · helps integrators map\n * an unfamiliar subtype name to a real flow they recognize. */\n example: string;\n /** Common use cases · lets integrators search their own product\n * for matching flows. Two-three terms each, lowercase. */\n common_use_cases: readonly string[];\n /** What an integrator typically pays for this subtype, anchored at\n * $1 ≈ 1052 sats. Returns null for percent-of-amount subtypes\n * where the price scales with the underlying transaction. */\n typical_price_hint: string;\n}\n\nexport const EVENT_SUBTYPES: Record<EventSubtype, EventSubtypeMetadata> = {\n // ── Class A · durable state transitions ──\n account_creation: {\n id: 'account_creation',\n class: 'A',\n label: 'account creation',\n fires_when:\n 'a new oc identity creates a durable account record on your surface (first sign-in, profile row inserted)',\n example: 'user signed up via email-OTP and your account row was inserted in your DB',\n common_use_cases: ['onboarding', 'signup', 'registration', 'first-login'],\n typical_price_hint: '~1300 sats (~$1.24)',\n },\n account_recovery: {\n id: 'account_recovery',\n class: 'A',\n label: 'account recovery',\n fires_when:\n 'a user re-binds an existing account to a new device or recovery method',\n example: 'user lost their device and recovered the account via email OTP + recovery code',\n common_use_cases: ['recovery', 'device-rebind', 'restore-access'],\n typical_price_hint: '~650 sats (~$0.62)',\n },\n attest_bond_increased: {\n id: 'attest_bond_increased',\n class: 'A',\n label: 'attest bond increased',\n fires_when:\n 'a user upgrades their bond size (locks more sats to attest_tier=bonded with higher cap)',\n example: 'user moved from 10k-sat bond to 100k-sat bond to clear your higher-trust gate',\n common_use_cases: ['bond-upgrade', 'tier-promotion', 'sybil-resistance'],\n typical_price_hint: '~1600 sats (~$1.52) · OFF by default',\n },\n payment_method_connected: {\n id: 'payment_method_connected',\n class: 'A',\n label: 'payment method connected',\n fires_when:\n 'a user connects a Lightning address, BIP-322 wallet, or payment-routing channel to their account',\n example: 'user pasted a lightning@address.com receive address into their profile',\n common_use_cases: ['payment-setup', 'wallet-connect', 'payout-config'],\n typical_price_hint: '~320 sats (~$0.30)',\n },\n agent_delegation_issued: {\n id: 'agent_delegation_issued',\n class: 'A',\n label: 'agent delegation issued',\n fires_when:\n 'a user signs an oc-agent delegation envelope authorizing an AI agent to act on their behalf',\n example: 'user delegated a \"summarize my emails\" agent for 24 hours with scope email:read',\n common_use_cases: ['agent-grant', 'ai-delegation', 'scoped-authorization'],\n typical_price_hint: '~320 sats · OFF by default (power-user)',\n },\n recovery_method_updated: {\n id: 'recovery_method_updated',\n class: 'A',\n label: 'recovery method updated',\n fires_when:\n 'a user changes their recovery email, recovery key, or social-recovery contacts',\n example: 'user rotated their recovery email after a phone change',\n common_use_cases: ['recovery-rotation', 'security-update'],\n typical_price_hint: '~160 sats (~$0.15)',\n },\n\n // ── Class B · action-bound ──\n payment_authorization: {\n id: 'payment_authorization',\n class: 'B',\n label: 'payment authorized',\n fires_when:\n 'a user authorizes a payment of underlying value (Lightning, on-chain BTC, or fiat-quoted)',\n example: 'user paid $5.00 (≈5260 sats) for a premium feature on your site',\n common_use_cases: ['payment', 'checkout', 'paywall', 'subscription'],\n typical_price_hint: '0.75% of payment amount (percent_of_amount)',\n },\n scoped_action_authorization: {\n id: 'scoped_action_authorization',\n class: 'B',\n label: 'scoped action authorized',\n fires_when:\n 'a user takes a specific action your site bills on (post, vote, comment, claim) where each instance is meaningful',\n example: 'user posted a long-form review that earns them sats from your editorial budget',\n common_use_cases: ['post', 'vote', 'comment', 'claim', 'submit'],\n typical_price_hint: '~100 sats (~$0.10)',\n },\n attest_verification_at_gate: {\n id: 'attest_verification_at_gate',\n class: 'B',\n label: 'attest verification',\n fires_when:\n \"your site's gate consulted the user's attest_tier and admitted them (counted only when admitted)\",\n example: 'admin gate checked attest_tier=bonded with bond≥10k sats and granted access',\n common_use_cases: ['gate-check', 'tier-gate', 'sybil-filter'],\n typical_price_hint: '~280 sats (~$0.27) · OFF by default',\n },\n stamp_signing: {\n id: 'stamp_signing',\n class: 'B',\n label: 'stamp signed',\n fires_when:\n 'a user signs an oc-stamp envelope (provenance attestation, review credential, content stamp)',\n example: 'user stamped their published recipe with their oc identity for downstream verification',\n common_use_cases: ['provenance', 'review', 'credential', 'attestation'],\n typical_price_hint: '~55 sats (~$0.05) · OFF by default',\n },\n pledge_resolution: {\n id: 'pledge_resolution',\n class: 'B',\n label: 'pledge resolved',\n fires_when:\n 'an oc-pledge bonded commitment resolves on your surface (kept / broken / disputed / expired_unresolved). pledge bonds never move — any sat payout is an integrator-composed flow on top of pledge (e.g., HTLC), not a pledge primitive (oc-pledge-protocol WHY.md H7)',\n example:\n 'user staked sats × days-unspent on a prediction; the pledge resolved kept and the integrator paid out per its own composed terms',\n common_use_cases: ['pledge', 'staking', 'resolution', 'commit-reveal'],\n typical_price_hint: '1% of pledge bond amount (percent_of_amount) · OFF by default',\n },\n\n // ── Class C · session ──\n session_creation: {\n id: 'session_creation',\n class: 'C',\n label: 'session opened',\n fires_when:\n 'a fresh authenticated session is opened for a returning user (sign-in within an existing session is FREE)',\n example: 'user signed in after their last session expired; new session token issued',\n common_use_cases: ['sign-in', 'session', 'authenticate'],\n typical_price_hint: '~55 sats (~$0.05)',\n },\n};\n\n/** All subtypes for a given class · convenience accessor. */\nexport function subtypesForClass(cls: EventClass): EventSubtypeMetadata[] {\n return Object.values(EVENT_SUBTYPES).filter((m) => m.class === cls);\n}\n\n/** All subtypes as a flat list, ordered class A → B → C. */\nexport const ALL_EVENT_SUBTYPES: readonly EventSubtypeMetadata[] = [\n ...subtypesForClass('A'),\n ...subtypesForClass('B'),\n ...subtypesForClass('C'),\n];\n","/**\n * @orangecheck/me-client\n *\n * Drop-in client for me.ochk.io. Sign-in-with-OC. You pay for sessions\n * and actions, not for clicks.\n *\n * Three entry points for three audiences:\n *\n * import { ... } from '@orangecheck/me-client' // React surface\n * import { ... } from '@orangecheck/me-client/server' // server-side\n * verification\n * (Next.js, Express,\n * Hono — all without\n * env vars or JWK\n * handling)\n * import { signInWithOc } from '@orangecheck/me-client/popup'\n * // browser-only popup\n * orchestrator\n *\n * Server-side verification example:\n *\n * // pages/api/me.ts\n * import { withOcAuth } from '@orangecheck/me-client/server';\n *\n * export default withOcAuth(async (req, res) => {\n * if (!req.ocSession) return res.status(401).json({ ok: false });\n * res.status(200).json({ address: req.ocSession.did_oc });\n * });\n *\n * Popup signin example:\n *\n * import { signInWithOc } from '@orangecheck/me-client/popup';\n *\n * button.addEventListener('click', async () => {\n * const result = await signInWithOc();\n * if (!result) return; // user cancelled\n * localStorage.setItem('oc-token', result.token);\n * location.assign('/dashboard');\n * });\n */\n\nexport { OcSignInButton } from './SignInButton';\nexport type { OcSignInButtonProps } from './SignInButton';\n\nexport { session, onTelemetry } from './session';\nexport { payment } from './payment';\nexport { event } from './event';\nexport type { FireEventOptions, VerifyEventResult } from './event';\nexport { config } from './config';\nexport { webhook } from './webhook';\nexport type { OcPublicJwk, VerifyOptions, VerifyResult } from './webhook';\nexport { federations } from './federations';\nexport { scope, parseTrustAttestationCount } from './scope';\nexport type {\n Scope,\n GrantedOptions,\n GrantedResult,\n RequestOptions,\n TrustAttestationCount,\n} from './scope';\nexport { family } from './family';\nexport type { FamilyVerb, FamilyScopesOptions, FamilyScopesResult } from './family';\nexport {\n identity,\n verifyActivityAttestation,\n refreshEnvelopeJwks,\n} from './identity';\nexport type {\n ActivityAttestation,\n ActivityAttestationBundle,\n ActivityVerifyCheck,\n ActivityVerifyResult,\n VerifyActivityOptions,\n} from './identity';\nexport {\n setOrigin,\n getOrigin,\n setBearerToken,\n getBearerToken,\n clearBearerToken,\n MeClientError,\n withRateLimitRetry,\n} from './transport';\nexport type { WithRateLimitRetryOptions } from './transport';\n\nexport {\n PLATFORM_FEE_POLICY,\n MIN_INTEGRATOR_PRICE_SATS,\n MAX_DROP_WINDOW_DAYS,\n computeFees,\n validateIntegratorConfig,\n} from './types';\n\nexport type {\n EventClass,\n EventSubtype,\n EventKey,\n ClassASubtype,\n ClassBSubtype,\n ClassCSubtype,\n AttestTier,\n SiteFeeShape,\n AgentClassOverride,\n IntegratorEventConfig,\n IntegratorPriceConfig,\n ComputedFees,\n ValidationResult,\n BillableEvent,\n DropCadence,\n DropScheduleSummary,\n DropResponseBlock,\n WebhookPayload,\n SystemWebhookPayload,\n DropClosedWebhookPayload,\n WebhookHeaders,\n Session,\n SessionPolicy,\n SignInOptions,\n PaymentAuthorizeOptions,\n PaymentResult,\n TelemetryEvent,\n Federation,\n FederationStatus,\n SigningMethod,\n} from './types';\n\nexport {\n EVENT_SUBTYPES,\n ALL_EVENT_SUBTYPES,\n subtypesForClass,\n type EventSubtypeMetadata,\n} from './subtypes';\n\nexport {\n ARCHETYPE_TEMPLATES,\n fromTemplate as configFromTemplate,\n getArchetypeTemplate,\n type ArchetypeTemplate,\n type IntegratorArchetype,\n} from './templates';\n\nimport { session } from './session';\nimport { payment } from './payment';\nimport { event } from './event';\nimport { config } from './config';\nimport { webhook } from './webhook';\nimport { federations } from './federations';\nimport { scope } from './scope';\nimport { family } from './family';\nimport { identity } from './identity';\n\n/** Convenience namespace mirroring the public API surface in /integrate\n * code samples — `oc.session.create()`, `oc.payment.authorize()`,\n * `oc.event.fire()`, `oc.config.validate()`, `oc.webhook.verify()`,\n * `oc.federations.live()`, `oc.scope.granted()` / `oc.scope.request()`,\n * `oc.family.scopes()`, `oc.identity.verifyActivityAttestation()`. */\nexport const oc = {\n session,\n payment,\n event,\n config,\n webhook,\n federations,\n scope,\n family,\n identity,\n};\n"]}
|