@orangecheck/me-client 0.15.0 → 0.16.0
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.d.mts +11 -2
- package/dist/index.d.ts +11 -2
- package/dist/index.js +16 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +16 -3
- package/dist/index.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/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/index.ts"],"names":["scope","React","jsxs","event","jsx","config","verify","scopes","origin"],"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;AAQA,eAAsB,GAA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A,IACzB,MAAA,EAAQ,KAAA;AAAA,IACR,WAAA,EAAa,SAAA;AAAA,IACb,QAAQ,OAAA,EAAS;AAAA,GACpB,CAAA;AACD,EAAA,IAAI,CAAC,IAAI,EAAA,EAAI;AACT,IAAA,MAAM,MAAM,MAAM,GAAA,CAAI,MAAK,CAAE,KAAA,CAAM,MAAM,EAAE,CAAA;AAC3C,IAAA,MAAM,IAAI,MAAM,CAAA,kBAAA,EAAqB,GAAA,CAAI,MAAM,CAAA,CAAA,EAAI,GAAA,IAAO,GAAA,CAAI,UAAU,CAAA,CAAE,CAAA;AAAA,EAC9E;AACA,EAAA,MAAM,IAAA,GAAQ,MAAM,GAAA,CAAI,IAAA,EAAK;AAC7B,EAAA,OAAO;AAAA,IACH,KAAK,IAAA,CAAK,GAAA;AAAA,IACV,gBAAgB,IAAA,CAAK,cAAA;AAAA,IACrB,gBAAgB,IAAA,CAAK,cAAA;AAAA,IACrB,QAAQ,IAAA,CAAK;AAAA,GACjB;AACJ;AAEO,IAAM,MAAA,GAAS,EAAE,MAAA;;;ACGjB,IAAM,EAAA,GAAK,EAAE,OAAA,EAAS,OAAA,EAAS,OAAO,MAAA,EAAQ,OAAA,EAAS,WAAA,EAAa,KAAA,EAAO,MAAA","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}\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 };\n if (bearerToken) headers['authorization'] = `Bearer ${bearerToken}`;\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/** Invalidate a session. Free, telemetry-only. */\nasync function invalidate(sessionId: string): Promise<void> {\n emitTelemetry('session.intra_signin', 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/** Anti-spam price floor. No integrator can configure a per-event price\n * below this. */\nexport const MIN_INTEGRATOR_PRICE_SATS = 5;\n\n// ── event taxonomy ────────────────────────────────────────────────────────\n\nexport type EventClass = 'A' | 'B' | 'C';\n\nexport type ClassASubtype =\n | 'account_creation'\n | 'account_recovery'\n | 'kyc_tier_upgrade'\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\nexport type AttestTier = 'anonymous' | 'bonded' | 'kyc_light' | 'kyc_strong';\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/** 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 post-platform-fee that flows to the user (0–0.8 since\n * platform_fee is 20%). The remainder is a rebate to the site's OC\n * project balance. */\n user_share_pct: number;\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-subtype configs. Subtypes not listed are disabled by default. */\n events: Partial<Record<EventSubtype, 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.\n *\n * Invariants (verified by tests in oc-me-web/src/lib/events/types.test.ts):\n * 1. gross_fee_sats >= MIN_INTEGRATOR_PRICE_SATS\n * 2. platform_fee_sats >= PLATFORM_FEE_POLICY.min_floor_sats\n * 3. user_share_pct is clamped to [0, 0.8]\n * 4. site_rebate_sats >= 0\n * 5. gross == platform + user + rebate (exact, modulo rounding into rebate)\n */\nexport function computeFees(\n cfg: IntegratorEventConfig,\n payment_amount_sats?: number\n): ComputedFees {\n let gross = 0;\n if (cfg.site_pays.kind === 'fixed_sats') {\n gross = Math.max(MIN_INTEGRATOR_PRICE_SATS, Math.round(cfg.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 * cfg.site_pays.pct)\n );\n }\n const platform_fee_sats = Math.max(\n PLATFORM_FEE_POLICY.min_floor_sats,\n Math.round(gross * PLATFORM_FEE_POLICY.pct)\n );\n const user_share = Math.min(0.8, Math.max(0, cfg.user_share_pct));\n const user_earned_sats = Math.round(gross * user_share);\n const site_rebate_sats = Math.max(0, 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?: EventSubtype; 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 EventSubtype;\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: EventSubtype;\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}\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 | '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 EventSubtype,\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 /** Canonical billable subtype. Class is inferred by the server. */\n subtype: EventSubtype;\n /** Human-readable action label that appears on the envelope.\n * Optional but encouraged — it's what the user sees in their\n * /me/earn 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 /** Override the user identity the envelope is credited to. Default\n * is the currently-authenticated user (cookie / Bearer). Pass\n * this only when firing on a user's behalf in a server-to-server\n * flow — the project must have an explicit allowlist. */\n user_address?: string;\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}\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 return api<BillableEvent>('/api/integrator/event', {\n method: 'POST',\n body: options,\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 /** Canonical billable subtype. */\n subtype: EventSubtype;\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}\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 return api<FireBatchResponse>('/api/integrator/event/batch', {\n method: 'POST',\n body: options,\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 * const cfg = await oc.config.fetch({ project_key: env.site.domain });\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 * `oc.config.validate` — local IntegratorPriceConfig validator, no\n * network call. Mirrors the server-side validation rules the\n * configurator at me.ochk.io/integrate enforces.\n *\n * import { oc } from '@orangecheck/me-client';\n * import type { IntegratorPriceConfig } from '@orangecheck/me-client';\n *\n * const cfg: IntegratorPriceConfig = { … };\n * const result = oc.config.validate(cfg);\n * if (!result.ok) console.error(result.errors);\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 operator UI.\n */\n\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 = { validate };\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 JWKS at\n * `https://ochk.io/.well-known/jwks.json` for 1h. Pass `{ jwk }` to\n * skip the network round-trip if you've embedded the key.\n */\n\nimport { importJWK, type CryptoKey, type KeyObject } from 'jose';\n\nconst DEFAULT_ISSUER = 'https://ochk.io';\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(/\\/$/, '')}/.well-known/jwks.json`;\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. */\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\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];\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 };\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';\n\nconst VALID_VERBS: ReadonlyArray<FamilyVerb> = [\n 'oc-vote',\n 'oc-stamp',\n 'oc-agent',\n 'oc-attest',\n 'oc-lock',\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 * @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.addr });\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 } from './scope';\nexport type { Scope, GrantedOptions, GrantedResult, RequestOptions } from './scope';\nexport { family } from './family';\nexport type { FamilyVerb, FamilyScopesOptions, FamilyScopesResult } from './family';\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 computeFees,\n validateIntegratorConfig,\n} from './types';\n\nexport type {\n EventClass,\n EventSubtype,\n ClassASubtype,\n ClassBSubtype,\n ClassCSubtype,\n AttestTier,\n SiteFeeShape,\n IntegratorEventConfig,\n IntegratorPriceConfig,\n ComputedFees,\n ValidationResult,\n BillableEvent,\n Session,\n SessionPolicy,\n SignInOptions,\n PaymentAuthorizeOptions,\n PaymentResult,\n TelemetryEvent,\n Federation,\n FederationStatus,\n SigningMethod,\n} from './types';\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';\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()`. */\nexport const oc = { session, payment, event, config, webhook, federations, scope, family };\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/transport.ts","../src/session.ts","../src/SignInButton.tsx","../src/payment.ts","../src/types.ts","../src/event.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/index.ts"],"names":["scope","React","jsxs","event","jsx","config","verify","scopes","origin"],"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;AAQA,eAAsB,GAAA,CAAO,IAAA,EAAc,IAAA,GAAqB,EAAC,EAAe;AAC5E,EAAA,MAAM,OAAA,GAAkC;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AAE,MAAA;;;ACSjB,IAAM,EAAA,GAAK,EAAE,OAAA,EAAS,OAAA,EAAS,OAAO,MAAA,EAAQ,OAAA,EAAS,WAAA,EAAa,KAAA,EAAO,MAAA","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}\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 };\n if (bearerToken) headers['authorization'] = `Bearer ${bearerToken}`;\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/** Invalidate a session. Free, telemetry-only. */\nasync function invalidate(sessionId: string): Promise<void> {\n emitTelemetry('session.intra_signin', 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/** Anti-spam price floor. No integrator can configure a per-event price\n * below this. */\nexport const MIN_INTEGRATOR_PRICE_SATS = 5;\n\n// ── event taxonomy ────────────────────────────────────────────────────────\n\nexport type EventClass = 'A' | 'B' | 'C';\n\nexport type ClassASubtype =\n | 'account_creation'\n | 'account_recovery'\n | 'kyc_tier_upgrade'\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\nexport type AttestTier = 'anonymous' | 'bonded' | 'kyc_light' | 'kyc_strong';\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/** 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 post-platform-fee that flows to the user (0–0.8 since\n * platform_fee is 20%). The remainder is a rebate to the site's OC\n * project balance. */\n user_share_pct: number;\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-subtype configs. Subtypes not listed are disabled by default. */\n events: Partial<Record<EventSubtype, 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.\n *\n * Invariants (verified by tests in oc-me-web/src/lib/events/types.test.ts):\n * 1. gross_fee_sats >= MIN_INTEGRATOR_PRICE_SATS\n * 2. platform_fee_sats >= PLATFORM_FEE_POLICY.min_floor_sats\n * 3. user_share_pct is clamped to [0, 0.8]\n * 4. site_rebate_sats >= 0\n * 5. gross == platform + user + rebate (exact, modulo rounding into rebate)\n */\nexport function computeFees(\n cfg: IntegratorEventConfig,\n payment_amount_sats?: number\n): ComputedFees {\n let gross = 0;\n if (cfg.site_pays.kind === 'fixed_sats') {\n gross = Math.max(MIN_INTEGRATOR_PRICE_SATS, Math.round(cfg.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 * cfg.site_pays.pct)\n );\n }\n const platform_fee_sats = Math.max(\n PLATFORM_FEE_POLICY.min_floor_sats,\n Math.round(gross * PLATFORM_FEE_POLICY.pct)\n );\n const user_share = Math.min(0.8, Math.max(0, cfg.user_share_pct));\n const user_earned_sats = Math.round(gross * user_share);\n const site_rebate_sats = Math.max(0, 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?: EventSubtype; 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 EventSubtype;\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: EventSubtype;\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}\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 | '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 EventSubtype,\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 /** Canonical billable subtype. Class is inferred by the server. */\n subtype: EventSubtype;\n /** Human-readable action label that appears on the envelope.\n * Optional but encouraged — it's what the user sees in their\n * /me/earn 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 /** Override the user identity the envelope is credited to. Default\n * is the currently-authenticated user (cookie / Bearer). Pass\n * this only when firing on a user's behalf in a server-to-server\n * flow — the project must have an explicit allowlist. */\n user_address?: string;\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}\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 return api<BillableEvent>('/api/integrator/event', {\n method: 'POST',\n body: options,\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 /** Canonical billable subtype. */\n subtype: EventSubtype;\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}\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 return api<FireBatchResponse>('/api/integrator/event/batch', {\n method: 'POST',\n body: options,\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 * const cfg = await oc.config.fetch({ project_key: env.site.domain });\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 * `oc.config.validate` — local IntegratorPriceConfig validator, no\n * network call. Mirrors the server-side validation rules the\n * configurator at me.ochk.io/integrate enforces.\n *\n * import { oc } from '@orangecheck/me-client';\n * import type { IntegratorPriceConfig } from '@orangecheck/me-client';\n *\n * const cfg: IntegratorPriceConfig = { … };\n * const result = oc.config.validate(cfg);\n * if (!result.ok) console.error(result.errors);\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 operator UI.\n */\n\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 = { validate };\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 JWKS at\n * `https://ochk.io/.well-known/jwks.json` for 1h. Pass `{ jwk }` to\n * skip the network round-trip if you've embedded the key.\n */\n\nimport { importJWK, type CryptoKey, type KeyObject } from 'jose';\n\nconst DEFAULT_ISSUER = 'https://ochk.io';\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(/\\/$/, '')}/.well-known/jwks.json`;\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';\n\nconst VALID_VERBS: ReadonlyArray<FamilyVerb> = [\n 'oc-vote',\n 'oc-stamp',\n 'oc-agent',\n 'oc-attest',\n 'oc-lock',\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 * @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.addr });\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 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 computeFees,\n validateIntegratorConfig,\n} from './types';\n\nexport type {\n EventClass,\n EventSubtype,\n ClassASubtype,\n ClassBSubtype,\n ClassCSubtype,\n AttestTier,\n SiteFeeShape,\n IntegratorEventConfig,\n IntegratorPriceConfig,\n ComputedFees,\n ValidationResult,\n BillableEvent,\n Session,\n SessionPolicy,\n SignInOptions,\n PaymentAuthorizeOptions,\n PaymentResult,\n TelemetryEvent,\n Federation,\n FederationStatus,\n SigningMethod,\n} from './types';\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';\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()`. */\nexport const oc = { session, payment, event, config, webhook, federations, scope, family };\n"]}
|
package/dist/index.mjs
CHANGED
|
@@ -793,8 +793,21 @@ var VALID_SCOPES = [
|
|
|
793
793
|
"attest_tier",
|
|
794
794
|
"display_name",
|
|
795
795
|
"cross_integrator_event_count",
|
|
796
|
-
"cross_integrator_human_event_count"
|
|
796
|
+
"cross_integrator_human_event_count",
|
|
797
|
+
"trust_attestation_count"
|
|
797
798
|
];
|
|
799
|
+
function parseTrustAttestationCount(value) {
|
|
800
|
+
const parts = value.split(",");
|
|
801
|
+
if (parts.length !== 4) return null;
|
|
802
|
+
const ints = parts.map((p) => Number.parseInt(p, 10));
|
|
803
|
+
if (ints.some((n) => !Number.isInteger(n) || n < 0)) return null;
|
|
804
|
+
return {
|
|
805
|
+
total: ints[0],
|
|
806
|
+
good: ints[1],
|
|
807
|
+
distinct_good_issuers: ints[2],
|
|
808
|
+
caution: ints[3]
|
|
809
|
+
};
|
|
810
|
+
}
|
|
798
811
|
async function granted(options) {
|
|
799
812
|
if (!options.project_key) {
|
|
800
813
|
throw new Error("oc.scope.granted: project_key is required");
|
|
@@ -837,7 +850,7 @@ function request(scopes2, options) {
|
|
|
837
850
|
window.location.assign(url.toString());
|
|
838
851
|
throw new Error("oc.scope.request: redirected to consent prompt");
|
|
839
852
|
}
|
|
840
|
-
var scope = { granted, request };
|
|
853
|
+
var scope = { granted, request, parseTrustAttestationCount };
|
|
841
854
|
|
|
842
855
|
// src/family.ts
|
|
843
856
|
var VALID_VERBS = [
|
|
@@ -877,6 +890,6 @@ var family = { scopes };
|
|
|
877
890
|
// src/index.ts
|
|
878
891
|
var oc = { session, payment, event, config, webhook, federations, scope, family };
|
|
879
892
|
|
|
880
|
-
export { MIN_INTEGRATOR_PRICE_SATS, MeClientError, OcSignInButton, PLATFORM_FEE_POLICY, clearBearerToken, computeFees, config, event, family, federations, getBearerToken, getOrigin, oc, onTelemetry, payment, scope, session, setBearerToken, setOrigin, validateIntegratorConfig, webhook, withRateLimitRetry };
|
|
893
|
+
export { MIN_INTEGRATOR_PRICE_SATS, MeClientError, OcSignInButton, PLATFORM_FEE_POLICY, clearBearerToken, computeFees, config, event, family, federations, getBearerToken, getOrigin, oc, onTelemetry, parseTrustAttestationCount, payment, scope, session, setBearerToken, setOrigin, validateIntegratorConfig, webhook, withRateLimitRetry };
|
|
881
894
|
//# sourceMappingURL=index.mjs.map
|
|
882
895
|
//# sourceMappingURL=index.mjs.map
|