@openmarketsai/connect-node 0.3.0 → 0.4.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.cjs +11 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +64 -1
- package/dist/index.d.ts +64 -1
- package/dist/index.js +11 -0
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
package/dist/index.cjs
CHANGED
|
@@ -129,6 +129,17 @@ function createClient(options) {
|
|
|
129
129
|
create: (params) => request("POST", "/flow/v1/connect/link-sessions", { body: params }),
|
|
130
130
|
get: (linkSessionId) => request("GET", `/flow/v1/connect/link-sessions/${encodeURIComponent(linkSessionId)}`)
|
|
131
131
|
},
|
|
132
|
+
configs: {
|
|
133
|
+
get: (workspaceId) => request(
|
|
134
|
+
"GET",
|
|
135
|
+
`/flow/v1/workspaces/${encodeURIComponent(workspaceId)}/connect-config`
|
|
136
|
+
),
|
|
137
|
+
update: (workspaceId, config) => request(
|
|
138
|
+
"PUT",
|
|
139
|
+
`/flow/v1/workspaces/${encodeURIComponent(workspaceId)}/connect-config`,
|
|
140
|
+
{ body: { config } }
|
|
141
|
+
)
|
|
142
|
+
},
|
|
132
143
|
webhooks: {
|
|
133
144
|
getConfig: () => request("GET", "/flow/v1/connect/webhook-config"),
|
|
134
145
|
verify: (rawBody, sig, opts) => verifyWebhookSignature(requireSecret(), rawBody, sig, opts),
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"names":["crypto"],"mappings":";;;;;;;;;AAkBO,IAAM,gBAAA,GAAmB;AAOzB,IAAM,gBAAA,GAAN,cAA+B,KAAA,CAAM;AAAA,EAIxC,WAAA,CAAY,MAAA,EAAgB,IAAA,EAAc,OAAA,EAAiB,OAAA,EAAmC;AAC1F,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,kBAAA;AACZ,I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E,KACJ;AAAA,IACA,OAAA,EAAS;AAAA,MACL,QAAA,EAAU,CAAC,cAAA,KACP,OAAA,CAAQ,OAAO,gCAAA,EAAkC,EAAE,KAAA,EAAO,cAAA,EAAgB,CAAA;AAAA,MAC9E,QAAA,EAAU,CAAC,cAAA,KACP,OAAA,CAAQ,OAAO,gCAAA,EAAkC,EAAE,KAAA,EAAO,cAAA,EAAgB;AAAA,KAClF;AAAA,IACA,MAAA,EAAQ;AAAA,MACJ,IAAA,EAAM,CAAC,cAAA,KACH,OAAA,CAAQ,OAAO,sBAAA,EAAwB,EAAE,KAAA,EAAO,cAAA,EAAgB,CAAA;AAAA,MACpE,KAAK,CAAC,MAAA,EAAQ,IAAA,KACV,OAAA,CAAmB,QAAQ,0BAAA,EAA4B;AAAA,QACnD,IAAA,EAAM,EAAE,MAAA,EAAO;AAAA,QACf,OAAO,IAAA,CAAK;AAAA,OACf;AAAA,KACT;AAAA,IACA,IAAA,EAAM;AAAA,MACF,OAAA,EAAS,MAAM,OAAA,CAAQ,KAAA,EAAO,kBAAkB,CAAA;AAAA,MAChD,gBAAA,EAAkB,CAAC,SAAA,KACf,OAAA,CAAQ,OAAO,CAAA,kBAAA,EAAqB,kBAAA,CAAmB,SAAS,CAAC,CAAA,UAAA,CAAY;AAAA;AACrF,GACJ;AACJ","file":"index.cjs","sourcesContent":["/**\n * @openmarketsai/connect-node\n *\n * Server SDK for OpenMarkets Connect. A thin, typed wrapper over the Flow API:\n * provision your users, mint hosted link sessions, verify webhook deliveries,\n * read on a user's behalf, and execute orders on their account.\n *\n * import { createClient } from '@openmarketsai/connect-node'\n * const om = createClient({ apiKey: process.env.OM_API_KEY! })\n *\n * await om.connect.users.provision({ external_user_id: 'user-123' })\n * const { token } = await om.connect.linkSessions.create({ external_user_id: 'user-123' })\n * await om.orders.buy([leg], { actAs: 'user-123' })\n *\n * Pairs with @openmarketsai/connect-web (the in-app launcher).\n */\nimport crypto from 'node:crypto'\n\nexport const DEFAULT_BASE_URL = 'https://api.openmarkets.ai'\n\n// ──────────────────────────────────────────────────────────────────────────\n// Errors\n// ──────────────────────────────────────────────────────────────────────────\n\n/** Thrown when the API returns a non-2xx response. Mirrors the Flow error envelope. */\nexport class OpenMarketsError extends Error {\n readonly status: number\n readonly code: string\n readonly details?: Record<string, unknown>\n constructor(status: number, code: string, message: string, details?: Record<string, unknown>) {\n super(message)\n this.name = 'OpenMarketsError'\n this.status = status\n this.code = code\n this.details = details\n }\n}\n\n/** Thrown by `constructWebhookEvent` when a signature is missing, stale, or invalid. */\nexport class WebhookSignatureError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'WebhookSignatureError'\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Webhook verification (matches src/utils/webhook-signature.ts byte-for-byte)\n//\n// Header: X-OpenMarkets-Signature: t=<unix_seconds>,v1=<hex hmac>\n// Signed string: `${t}.${rawBody}`, HMAC-SHA256 with your whsec_ secret.\n// IMPORTANT: verify over the EXACT raw request body, not a re-serialized object.\n// ──────────────────────────────────────────────────────────────────────────\n\nexport type ConnectWebhookEventType =\n | 'user.partners_connected'\n | 'user.permissions_changed'\n | (string & {})\n\nexport interface ConnectWebhookEvent {\n type: ConnectWebhookEventType\n [key: string]: unknown\n}\n\nexport interface VerifyWebhookOptions {\n /** Max age of the signature timestamp, in seconds. Default 300 (5 min). 0 disables. */\n toleranceSec?: number\n /** Injectable clock for testing. */\n nowSec?: number\n}\n\nfunction toRaw(body: string | Buffer): string {\n return typeof body === 'string' ? body : body.toString('utf8')\n}\n\nfunction parseSignatureHeader(header: string): { t: number; v1: string } | null {\n const parts = header.split(',').reduce<Record<string, string>>((acc, kv) => {\n const idx = kv.indexOf('=')\n if (idx > 0) acc[kv.slice(0, idx).trim()] = kv.slice(idx + 1).trim()\n return acc\n }, {})\n const t = Number(parts.t)\n if (!parts.v1 || !isFinite(t)) return null\n return { t, v1: parts.v1 }\n}\n\nfunction timingSafeEqualHex(a: string, b: string): boolean {\n const ab = Buffer.from(a, 'hex')\n const bb = Buffer.from(b, 'hex')\n if (ab.length === 0 || ab.length !== bb.length) return false\n return crypto.timingSafeEqual(ab, bb)\n}\n\n/** Verify a webhook signature. Returns false on any failure (never throws). */\nexport function verifyWebhookSignature(\n secret: string,\n rawBody: string | Buffer,\n signatureHeader: string | null | undefined,\n opts: VerifyWebhookOptions = {},\n): boolean {\n if (!secret || !signatureHeader) return false\n const parsed = parseSignatureHeader(signatureHeader)\n if (!parsed) return false\n const toleranceSec = opts.toleranceSec ?? 300\n const nowSec = opts.nowSec ?? Math.floor(Date.now() / 1000)\n if (toleranceSec > 0 && Math.abs(nowSec - parsed.t) > toleranceSec) return false\n const expected = crypto\n .createHmac('sha256', secret)\n .update(`${parsed.t}.${toRaw(rawBody)}`)\n .digest('hex')\n return timingSafeEqualHex(expected, parsed.v1)\n}\n\n/** Verify the signature and return the parsed event, or throw `WebhookSignatureError`. */\nexport function constructWebhookEvent(\n secret: string,\n rawBody: string | Buffer,\n signatureHeader: string | null | undefined,\n opts: VerifyWebhookOptions = {},\n): ConnectWebhookEvent {\n if (!verifyWebhookSignature(secret, rawBody, signatureHeader, opts)) {\n throw new WebhookSignatureError('Invalid or expired webhook signature')\n }\n try {\n return JSON.parse(toRaw(rawBody)) as ConnectWebhookEvent\n } catch {\n throw new WebhookSignatureError('Webhook body is not valid JSON')\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Client\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface OpenMarketsClientOptions {\n /** Your Connect org API key. Sent as `X-API-Key`. */\n apiKey: string\n /** API base URL. Defaults to https://api.openmarkets.ai. */\n baseUrl?: string\n /** Your webhook signing secret (`whsec_…`), enabling `client.webhooks.*`. */\n webhookSecret?: string\n /** Custom fetch (defaults to global fetch; Node 18+). */\n fetch?: typeof fetch\n /** Per-request timeout in ms. Default 30000. */\n timeoutMs?: number\n}\n\nexport type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'\n\nexport interface RequestOptions {\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown\n /** Act on this user's behalf — sets the `X-OpenMarkets-Account` header. */\n actAs?: string\n}\n\n// Inputs (snake_case to match the API — buy legs map 1:1 from liquidity entries).\nexport interface ProvisionUserParams {\n external_user_id: string\n email?: string\n name?: string\n}\nexport type LinkSessionMode = 'connect' | 'manage'\nexport interface CreateLinkSessionParams {\n external_user_id: string\n return_url?: string\n mode?: LinkSessionMode\n allowed_partners?: string[]\n /** Pick a specific org Connect config; omit to use the org's default (if any). */\n connect_config_id?: string\n}\nexport interface BuyOrder {\n /** What to buy — set exactly one of position_hash or liquidity_hash. */\n position_hash?: string\n liquidity_hash?: string\n /** Size — set exactly one of amount or shares. */\n amount?: number // stake, notional USD\n shares?: number // contract count (each pays $1 on win)\n /** Price ceiling, 0..1 exclusive — won't fill above this. */\n max_price: number\n /** Optional — pin a venue; omit to route to the best price. */\n partner_id?: string\n /** Optional — 'real' (default) or 'paper' (practice book). */\n mode?: 'real' | 'paper'\n}\n\n// Outputs (light — partners can pass a type param for stricter typing).\n/**\n * `POST /flow/v1/connect/users`. Idempotent — safe to call on every login.\n *\n * `om_account_id` is the field an integration actually needs (it addresses the\n * user in later calls) and was previously absent, so it typed as `unknown` via\n * the index signature.\n */\nexport interface ProvisionResult {\n /** Our id for this user. Pass as `actAs` when trading on their behalf. */\n om_account_id: string\n external_user_id: string\n /** false when the user already existed. */\n created: boolean\n [key: string]: unknown\n}\n/**\n * The response of `POST /flow/v1/connect/link-sessions`.\n *\n * These names are the API's, verified against the route rather than assumed:\n * it returns `link_token`, NOT `token`. The previous declaration named `token`,\n * `external_user_id` and `mode` — none of which the endpoint sends — so the one\n * field an integration actually needs type-checked as a string and arrived\n * `undefined`, opening the hosted flow with `token=undefined`. The index\n * signature below is what kept that quiet; keep these names in step with\n * `CreateLinkSessionResult` in LinkSessionOrchestrator.\n */\nexport interface LinkSession {\n link_session_id: string\n /** Single-use, expires in 15 minutes. Hand to `createConnect().open()`. */\n link_token: string\n /** The hosted flow URL, for redirect mode or a native in-app browser. */\n hosted_url: string\n expires_at: string\n [key: string]: unknown\n}\n/**\n * The status of one leg, mirroring `flowLegStatus` in the API.\n *\n * ALL FIVE values are reachable. This union previously listed only three, so a\n * `switch` written against the SDK's types compiled clean and silently fell\n * through for a resting or pending order — an order that IS live, sitting on a\n * venue book, treated as if it had never been placed. Any change here must\n * follow the API, not the other way round.\n */\nexport type BuyLegStatus =\n /** Filled or partially filled. */\n | 'completed'\n /** Live on the venue's book, unfilled. Not a failure — check back. */\n | 'resting'\n /** Accepted by the venue, fill not yet confirmed (async venues). */\n | 'pending'\n /** The venue or a pre-trade gate rejected it. */\n | 'failed'\n /** No viable venue was found; nothing was sent. */\n | 'rejected'\n\nexport interface BuyResult {\n results: Array<{\n index: number\n status: BuyLegStatus\n /** NULL when the leg was rejected before routing — no decision was made. */\n sor_decision_id: string | null\n filled_notional: number\n filled_shares: number\n /** The un-buyable remainder of the requested stake. */\n unfilled_notional: number\n avg_price: number | null\n rejected_reason: string | null\n venues: Array<{\n partner_id: string\n success: boolean\n router_order_id: string | null\n error: string | null\n }>\n }>\n}\n\ninterface FlowEnvelope<T> {\n data?: T\n error?: { code: string; message: string; details?: Record<string, unknown> }\n}\n\nexport interface OpenMarketsClient {\n /** Generic typed request — escape hatch for endpoints without a helper. */\n request<T = unknown>(method: HttpMethod, path: string, opts?: RequestOptions): Promise<T>\n connect: {\n users: {\n provision(params: ProvisionUserParams): Promise<ProvisionResult>\n get<T = unknown>(externalUserId: string): Promise<T>\n getPolicy<T = unknown>(externalUserId: string): Promise<T>\n }\n linkSessions: {\n create(params: CreateLinkSessionParams): Promise<LinkSession>\n get<T = unknown>(linkSessionId: string): Promise<T>\n }\n webhooks: {\n getConfig<T = unknown>(): Promise<T>\n /** Verify a delivery using the configured `webhookSecret`. */\n verify(rawBody: string | Buffer, signatureHeader: string | null | undefined, opts?: VerifyWebhookOptions): boolean\n /** Verify + parse, or throw. Uses the configured `webhookSecret`. */\n constructEvent(rawBody: string | Buffer, signatureHeader: string | null | undefined, opts?: VerifyWebhookOptions): ConnectWebhookEvent\n }\n }\n account: {\n partners<T = unknown>(externalUserId: string): Promise<T>\n balances<T = unknown>(externalUserId: string): Promise<T>\n }\n orders: {\n list<T = unknown>(externalUserId: string): Promise<T>\n buy(orders: BuyOrder[], opts: { actAs: string }): Promise<BuyResult>\n }\n data: {\n leagues<T = unknown>(): Promise<T>\n contestLiquidity<T = unknown>(contestId: string): Promise<T>\n }\n}\n\nexport function createClient(options: OpenMarketsClientOptions): OpenMarketsClient {\n if (!options.apiKey) throw new Error('createClient: apiKey is required')\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '')\n const doFetch = options.fetch ?? globalThis.fetch\n if (!doFetch) throw new Error('No fetch available — pass options.fetch (Node < 18)')\n const timeoutMs = options.timeoutMs ?? 30_000\n\n async function request<T = unknown>(\n method: HttpMethod,\n path: string,\n opts: RequestOptions = {},\n ): Promise<T> {\n const url = new URL(baseUrl + path)\n for (const [k, v] of Object.entries(opts.query ?? {})) {\n if (v !== undefined) url.searchParams.set(k, String(v))\n }\n const headers: Record<string, string> = {\n 'X-API-Key': options.apiKey,\n Accept: 'application/json',\n }\n if (opts.body !== undefined) headers['Content-Type'] = 'application/json'\n if (opts.actAs) headers['X-OpenMarkets-Account'] = opts.actAs\n\n const ctrl = new AbortController()\n const timer = setTimeout(() => ctrl.abort(), timeoutMs)\n let res: Response\n try {\n res = await doFetch(url.toString(), {\n method,\n headers,\n body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,\n signal: ctrl.signal,\n })\n } finally {\n clearTimeout(timer)\n }\n\n let envelope: FlowEnvelope<T> | undefined\n const text = await res.text()\n if (text) {\n try {\n envelope = JSON.parse(text) as FlowEnvelope<T>\n } catch {\n /* non-JSON body */\n }\n }\n\n if (!res.ok) {\n const err = envelope?.error\n throw new OpenMarketsError(\n res.status,\n err?.code ?? 'http_error',\n err?.message ?? `Request failed with status ${res.status}`,\n err?.details,\n )\n }\n return (envelope?.data ?? (undefined as unknown)) as T\n }\n\n function requireSecret(): string {\n if (!options.webhookSecret) {\n throw new Error('webhookSecret was not provided to createClient()')\n }\n return options.webhookSecret\n }\n\n return {\n request,\n connect: {\n users: {\n provision: (params) =>\n request<ProvisionResult>('POST', '/flow/v1/connect/users', { body: params }),\n get: (externalUserId) =>\n request('GET', `/flow/v1/connect/users/${encodeURIComponent(externalUserId)}`),\n getPolicy: (externalUserId) =>\n request('GET', `/flow/v1/connect/users/${encodeURIComponent(externalUserId)}/policy`),\n },\n linkSessions: {\n create: (params) =>\n request<LinkSession>('POST', '/flow/v1/connect/link-sessions', { body: params }),\n get: (linkSessionId) =>\n request('GET', `/flow/v1/connect/link-sessions/${encodeURIComponent(linkSessionId)}`),\n },\n webhooks: {\n getConfig: () => request('GET', '/flow/v1/connect/webhook-config'),\n verify: (rawBody, sig, opts) =>\n verifyWebhookSignature(requireSecret(), rawBody, sig, opts),\n constructEvent: (rawBody, sig, opts) =>\n constructWebhookEvent(requireSecret(), rawBody, sig, opts),\n },\n },\n account: {\n partners: (externalUserId) =>\n request('GET', '/flow/v1/auth/account/partners', { actAs: externalUserId }),\n balances: (externalUserId) =>\n request('GET', '/flow/v1/auth/account/balances', { actAs: externalUserId }),\n },\n orders: {\n list: (externalUserId) =>\n request('GET', '/flow/v1/auth/orders', { actAs: externalUserId }),\n buy: (orders, opts) =>\n request<BuyResult>('POST', '/flow/v1/auth/orders/buy', {\n body: { orders },\n actAs: opts.actAs,\n }),\n },\n data: {\n leagues: () => request('GET', '/flow/v1/leagues'),\n contestLiquidity: (contestId) =>\n request('GET', `/flow/v1/contests/${encodeURIComponent(contestId)}/liquidity`),\n },\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":["crypto"],"mappings":";;;;;;;;;AAkBO,IAAM,gBAAA,GAAmB;AAOzB,IAAM,gBAAA,GAAN,cAA+B,KAAA,CAAM;AAAA,EA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AAkB,CAAC,SAAA,KACf,OAAA,CAAQ,OAAO,CAAA,kBAAA,EAAqB,kBAAA,CAAmB,SAAS,CAAC,CAAA,UAAA,CAAY;AAAA;AACrF,GACJ;AACJ","file":"index.cjs","sourcesContent":["/**\n * @openmarketsai/connect-node\n *\n * Server SDK for OpenMarkets Connect. A thin, typed wrapper over the Flow API:\n * provision your users, mint hosted link sessions, verify webhook deliveries,\n * read on a user's behalf, and execute orders on their account.\n *\n * import { createClient } from '@openmarketsai/connect-node'\n * const om = createClient({ apiKey: process.env.OM_API_KEY! })\n *\n * await om.connect.users.provision({ external_user_id: 'user-123' })\n * const { token } = await om.connect.linkSessions.create({ external_user_id: 'user-123' })\n * await om.orders.buy([leg], { actAs: 'user-123' })\n *\n * Pairs with @openmarketsai/connect-web (the in-app launcher).\n */\nimport crypto from 'node:crypto'\n\nexport const DEFAULT_BASE_URL = 'https://api.openmarkets.ai'\n\n// ──────────────────────────────────────────────────────────────────────────\n// Errors\n// ──────────────────────────────────────────────────────────────────────────\n\n/** Thrown when the API returns a non-2xx response. Mirrors the Flow error envelope. */\nexport class OpenMarketsError extends Error {\n readonly status: number\n readonly code: string\n readonly details?: Record<string, unknown>\n constructor(status: number, code: string, message: string, details?: Record<string, unknown>) {\n super(message)\n this.name = 'OpenMarketsError'\n this.status = status\n this.code = code\n this.details = details\n }\n}\n\n/** Thrown by `constructWebhookEvent` when a signature is missing, stale, or invalid. */\nexport class WebhookSignatureError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'WebhookSignatureError'\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Webhook verification (matches src/utils/webhook-signature.ts byte-for-byte)\n//\n// Header: X-OpenMarkets-Signature: t=<unix_seconds>,v1=<hex hmac>\n// Signed string: `${t}.${rawBody}`, HMAC-SHA256 with your whsec_ secret.\n// IMPORTANT: verify over the EXACT raw request body, not a re-serialized object.\n// ──────────────────────────────────────────────────────────────────────────\n\nexport type ConnectWebhookEventType =\n | 'user.partners_connected'\n | 'user.permissions_changed'\n | (string & {})\n\nexport interface ConnectWebhookEvent {\n type: ConnectWebhookEventType\n [key: string]: unknown\n}\n\nexport interface VerifyWebhookOptions {\n /** Max age of the signature timestamp, in seconds. Default 300 (5 min). 0 disables. */\n toleranceSec?: number\n /** Injectable clock for testing. */\n nowSec?: number\n}\n\nfunction toRaw(body: string | Buffer): string {\n return typeof body === 'string' ? body : body.toString('utf8')\n}\n\nfunction parseSignatureHeader(header: string): { t: number; v1: string } | null {\n const parts = header.split(',').reduce<Record<string, string>>((acc, kv) => {\n const idx = kv.indexOf('=')\n if (idx > 0) acc[kv.slice(0, idx).trim()] = kv.slice(idx + 1).trim()\n return acc\n }, {})\n const t = Number(parts.t)\n if (!parts.v1 || !isFinite(t)) return null\n return { t, v1: parts.v1 }\n}\n\nfunction timingSafeEqualHex(a: string, b: string): boolean {\n const ab = Buffer.from(a, 'hex')\n const bb = Buffer.from(b, 'hex')\n if (ab.length === 0 || ab.length !== bb.length) return false\n return crypto.timingSafeEqual(ab, bb)\n}\n\n/** Verify a webhook signature. Returns false on any failure (never throws). */\nexport function verifyWebhookSignature(\n secret: string,\n rawBody: string | Buffer,\n signatureHeader: string | null | undefined,\n opts: VerifyWebhookOptions = {},\n): boolean {\n if (!secret || !signatureHeader) return false\n const parsed = parseSignatureHeader(signatureHeader)\n if (!parsed) return false\n const toleranceSec = opts.toleranceSec ?? 300\n const nowSec = opts.nowSec ?? Math.floor(Date.now() / 1000)\n if (toleranceSec > 0 && Math.abs(nowSec - parsed.t) > toleranceSec) return false\n const expected = crypto\n .createHmac('sha256', secret)\n .update(`${parsed.t}.${toRaw(rawBody)}`)\n .digest('hex')\n return timingSafeEqualHex(expected, parsed.v1)\n}\n\n/** Verify the signature and return the parsed event, or throw `WebhookSignatureError`. */\nexport function constructWebhookEvent(\n secret: string,\n rawBody: string | Buffer,\n signatureHeader: string | null | undefined,\n opts: VerifyWebhookOptions = {},\n): ConnectWebhookEvent {\n if (!verifyWebhookSignature(secret, rawBody, signatureHeader, opts)) {\n throw new WebhookSignatureError('Invalid or expired webhook signature')\n }\n try {\n return JSON.parse(toRaw(rawBody)) as ConnectWebhookEvent\n } catch {\n throw new WebhookSignatureError('Webhook body is not valid JSON')\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Client\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface OpenMarketsClientOptions {\n /** Your Connect org API key. Sent as `X-API-Key`. */\n apiKey: string\n /** API base URL. Defaults to https://api.openmarkets.ai. */\n baseUrl?: string\n /** Your webhook signing secret (`whsec_…`), enabling `client.webhooks.*`. */\n webhookSecret?: string\n /** Custom fetch (defaults to global fetch; Node 18+). */\n fetch?: typeof fetch\n /** Per-request timeout in ms. Default 30000. */\n timeoutMs?: number\n}\n\nexport type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'\n\nexport interface RequestOptions {\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown\n /** Act on this user's behalf — sets the `X-OpenMarkets-Account` header. */\n actAs?: string\n}\n\n// Inputs (snake_case to match the API — buy legs map 1:1 from liquidity entries).\nexport interface ProvisionUserParams {\n external_user_id: string\n email?: string\n name?: string\n}\nexport type LinkSessionMode = 'connect' | 'manage'\nexport interface CreateLinkSessionParams {\n external_user_id: string\n return_url?: string\n mode?: LinkSessionMode\n allowed_partners?: string[]\n /** Pick a specific org Connect config; omit to use the org's default (if any). */\n connect_config_id?: string\n}\nexport interface BuyOrder {\n /** What to buy — set exactly one of position_hash or liquidity_hash. */\n position_hash?: string\n liquidity_hash?: string\n /** Size — set exactly one of amount or shares. */\n amount?: number // stake, notional USD\n shares?: number // contract count (each pays $1 on win)\n /** Price ceiling, 0..1 exclusive — won't fill above this. */\n max_price: number\n /** Optional — pin a venue; omit to route to the best price. */\n partner_id?: string\n /** Optional — 'real' (default) or 'paper' (practice book). */\n mode?: 'real' | 'paper'\n}\n\n// Outputs (light — partners can pass a type param for stricter typing).\n/**\n * `POST /flow/v1/connect/users`. Idempotent — safe to call on every login.\n *\n * `om_account_id` is the field an integration actually needs (it addresses the\n * user in later calls) and was previously absent, so it typed as `unknown` via\n * the index signature.\n */\nexport interface ProvisionResult {\n /** Our id for this user. Pass as `actAs` when trading on their behalf. */\n om_account_id: string\n external_user_id: string\n /** false when the user already existed. */\n created: boolean\n [key: string]: unknown\n}\n/**\n * The response of `POST /flow/v1/connect/link-sessions`.\n *\n * These names are the API's, verified against the route rather than assumed:\n * it returns `link_token`, NOT `token`. The previous declaration named `token`,\n * `external_user_id` and `mode` — none of which the endpoint sends — so the one\n * field an integration actually needs type-checked as a string and arrived\n * `undefined`, opening the hosted flow with `token=undefined`. The index\n * signature below is what kept that quiet; keep these names in step with\n * `CreateLinkSessionResult` in LinkSessionOrchestrator.\n */\nexport interface LinkSession {\n link_session_id: string\n /** Single-use, expires in 15 minutes. Hand to `createConnect().open()`. */\n link_token: string\n /** The hosted flow URL, for redirect mode or a native in-app browser. */\n hosted_url: string\n expires_at: string\n [key: string]: unknown\n}\n/**\n * The status of one leg, mirroring `flowLegStatus` in the API.\n *\n * ALL FIVE values are reachable. This union previously listed only three, so a\n * `switch` written against the SDK's types compiled clean and silently fell\n * through for a resting or pending order — an order that IS live, sitting on a\n * venue book, treated as if it had never been placed. Any change here must\n * follow the API, not the other way round.\n */\nexport type BuyLegStatus =\n /** Filled or partially filled. */\n | 'completed'\n /** Live on the venue's book, unfilled. Not a failure — check back. */\n | 'resting'\n /** Accepted by the venue, fill not yet confirmed (async venues). */\n | 'pending'\n /** The venue or a pre-trade gate rejected it. */\n | 'failed'\n /** No viable venue was found; nothing was sent. */\n | 'rejected'\n\n/**\n * What an organization's END USERS see and may do in the hosted flow. Mirrors\n * `ConnectConfigBody` server-side.\n *\n * A `null` field means \"no restriction / use the default\" throughout, so an\n * organization with no config behaves exactly as Connect did before configs\n * existed. Read that as permissive, not as unset.\n */\nexport interface ConnectConfig {\n version: number\n /** Partner ids or names offered in the picker. null = every venue we support. */\n venue_allowlist: string[] | null\n /** Surface the OpenMarkets practice book as a credential-less venue. */\n offer_internal_book: boolean\n /**\n * Currencies users may trade. `['ATLAS']` is practice-only and is ENFORCED\n * on every order path, not merely hidden in the UI — users can still link\n * venues, read balances and sync history; only real-money orders are\n * refused.\n */\n allowed_currencies: string[]\n /** DERIVED from allowed_currencies server-side. Sending it has no effect. */\n allow_real_money: boolean\n /** Permissions the user is asked to grant. null = all of them. */\n available_scopes: ConnectScope[] | null\n branding: { display_name?: string; logo_url?: string; primary_color?: string } | null\n allowed_return_urls: string[] | null\n default_link_mode: LinkSessionMode\n [key: string]: unknown\n}\n\n/** Permissions an end user grants per connected venue. */\nexport type ConnectScope = 'history:read' | 'trade:execute' | 'balance:read'\n\nexport interface ConnectConfigResult {\n /** null when the organization has never saved one — `config` is the defaults. */\n connect_config_id: string | null\n config: ConnectConfig\n /**\n * Present on update: how many EXISTING users the change was applied to.\n * A funding-mode change reaches users already provisioned, not just future\n * ones, so this reports what actually happened.\n */\n reconcile?: { scanned: number; reconciled: number; failed: number } | null\n}\n\nexport interface BuyResult {\n results: Array<{\n index: number\n status: BuyLegStatus\n /** NULL when the leg was rejected before routing — no decision was made. */\n sor_decision_id: string | null\n filled_notional: number\n filled_shares: number\n /** The un-buyable remainder of the requested stake. */\n unfilled_notional: number\n avg_price: number | null\n rejected_reason: string | null\n venues: Array<{\n partner_id: string\n success: boolean\n router_order_id: string | null\n error: string | null\n }>\n }>\n}\n\ninterface FlowEnvelope<T> {\n data?: T\n error?: { code: string; message: string; details?: Record<string, unknown> }\n}\n\nexport interface OpenMarketsClient {\n /** Generic typed request — escape hatch for endpoints without a helper. */\n request<T = unknown>(method: HttpMethod, path: string, opts?: RequestOptions): Promise<T>\n connect: {\n users: {\n provision(params: ProvisionUserParams): Promise<ProvisionResult>\n get<T = unknown>(externalUserId: string): Promise<T>\n getPolicy<T = unknown>(externalUserId: string): Promise<T>\n }\n linkSessions: {\n create(params: CreateLinkSessionParams): Promise<LinkSession>\n get<T = unknown>(linkSessionId: string): Promise<T>\n }\n /**\n * The organization's Connect config — which venues appear, whether real\n * money is allowed, and how the hosted flow is branded.\n *\n * Requires a PLAYER JWT with workspace admin, not an API key: this is\n * account governance rather than a data-API capability. `update` sends a\n * whole body (it is normalized server-side), so read, change, write.\n */\n configs: {\n get(workspaceId: string): Promise<ConnectConfigResult>\n update(workspaceId: string, config: Partial<ConnectConfig>): Promise<ConnectConfigResult>\n }\n webhooks: {\n getConfig<T = unknown>(): Promise<T>\n /** Verify a delivery using the configured `webhookSecret`. */\n verify(rawBody: string | Buffer, signatureHeader: string | null | undefined, opts?: VerifyWebhookOptions): boolean\n /** Verify + parse, or throw. Uses the configured `webhookSecret`. */\n constructEvent(rawBody: string | Buffer, signatureHeader: string | null | undefined, opts?: VerifyWebhookOptions): ConnectWebhookEvent\n }\n }\n account: {\n partners<T = unknown>(externalUserId: string): Promise<T>\n balances<T = unknown>(externalUserId: string): Promise<T>\n }\n orders: {\n list<T = unknown>(externalUserId: string): Promise<T>\n buy(orders: BuyOrder[], opts: { actAs: string }): Promise<BuyResult>\n }\n data: {\n leagues<T = unknown>(): Promise<T>\n contestLiquidity<T = unknown>(contestId: string): Promise<T>\n }\n}\n\nexport function createClient(options: OpenMarketsClientOptions): OpenMarketsClient {\n if (!options.apiKey) throw new Error('createClient: apiKey is required')\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '')\n const doFetch = options.fetch ?? globalThis.fetch\n if (!doFetch) throw new Error('No fetch available — pass options.fetch (Node < 18)')\n const timeoutMs = options.timeoutMs ?? 30_000\n\n async function request<T = unknown>(\n method: HttpMethod,\n path: string,\n opts: RequestOptions = {},\n ): Promise<T> {\n const url = new URL(baseUrl + path)\n for (const [k, v] of Object.entries(opts.query ?? {})) {\n if (v !== undefined) url.searchParams.set(k, String(v))\n }\n const headers: Record<string, string> = {\n 'X-API-Key': options.apiKey,\n Accept: 'application/json',\n }\n if (opts.body !== undefined) headers['Content-Type'] = 'application/json'\n if (opts.actAs) headers['X-OpenMarkets-Account'] = opts.actAs\n\n const ctrl = new AbortController()\n const timer = setTimeout(() => ctrl.abort(), timeoutMs)\n let res: Response\n try {\n res = await doFetch(url.toString(), {\n method,\n headers,\n body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,\n signal: ctrl.signal,\n })\n } finally {\n clearTimeout(timer)\n }\n\n let envelope: FlowEnvelope<T> | undefined\n const text = await res.text()\n if (text) {\n try {\n envelope = JSON.parse(text) as FlowEnvelope<T>\n } catch {\n /* non-JSON body */\n }\n }\n\n if (!res.ok) {\n const err = envelope?.error\n throw new OpenMarketsError(\n res.status,\n err?.code ?? 'http_error',\n err?.message ?? `Request failed with status ${res.status}`,\n err?.details,\n )\n }\n return (envelope?.data ?? (undefined as unknown)) as T\n }\n\n function requireSecret(): string {\n if (!options.webhookSecret) {\n throw new Error('webhookSecret was not provided to createClient()')\n }\n return options.webhookSecret\n }\n\n return {\n request,\n connect: {\n users: {\n provision: (params) =>\n request<ProvisionResult>('POST', '/flow/v1/connect/users', { body: params }),\n get: (externalUserId) =>\n request('GET', `/flow/v1/connect/users/${encodeURIComponent(externalUserId)}`),\n getPolicy: (externalUserId) =>\n request('GET', `/flow/v1/connect/users/${encodeURIComponent(externalUserId)}/policy`),\n },\n linkSessions: {\n create: (params) =>\n request<LinkSession>('POST', '/flow/v1/connect/link-sessions', { body: params }),\n get: (linkSessionId) =>\n request('GET', `/flow/v1/connect/link-sessions/${encodeURIComponent(linkSessionId)}`),\n },\n configs: {\n get: (workspaceId: string) =>\n request<ConnectConfigResult>(\n 'GET', `/flow/v1/workspaces/${encodeURIComponent(workspaceId)}/connect-config`,\n ),\n update: (workspaceId: string, config: Partial<ConnectConfig>) =>\n request<ConnectConfigResult>(\n 'PUT', `/flow/v1/workspaces/${encodeURIComponent(workspaceId)}/connect-config`,\n { body: { config } },\n ),\n },\n webhooks: {\n getConfig: () => request('GET', '/flow/v1/connect/webhook-config'),\n verify: (rawBody, sig, opts) =>\n verifyWebhookSignature(requireSecret(), rawBody, sig, opts),\n constructEvent: (rawBody, sig, opts) =>\n constructWebhookEvent(requireSecret(), rawBody, sig, opts),\n },\n },\n account: {\n partners: (externalUserId) =>\n request('GET', '/flow/v1/auth/account/partners', { actAs: externalUserId }),\n balances: (externalUserId) =>\n request('GET', '/flow/v1/auth/account/balances', { actAs: externalUserId }),\n },\n orders: {\n list: (externalUserId) =>\n request('GET', '/flow/v1/auth/orders', { actAs: externalUserId }),\n buy: (orders, opts) =>\n request<BuyResult>('POST', '/flow/v1/auth/orders/buy', {\n body: { orders },\n actAs: opts.actAs,\n }),\n },\n data: {\n leagues: () => request('GET', '/flow/v1/leagues'),\n contestLiquidity: (contestId) =>\n request('GET', `/flow/v1/contests/${encodeURIComponent(contestId)}/liquidity`),\n },\n }\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -127,6 +127,57 @@ type BuyLegStatus =
|
|
|
127
127
|
| 'failed'
|
|
128
128
|
/** No viable venue was found; nothing was sent. */
|
|
129
129
|
| 'rejected';
|
|
130
|
+
/**
|
|
131
|
+
* What an organization's END USERS see and may do in the hosted flow. Mirrors
|
|
132
|
+
* `ConnectConfigBody` server-side.
|
|
133
|
+
*
|
|
134
|
+
* A `null` field means "no restriction / use the default" throughout, so an
|
|
135
|
+
* organization with no config behaves exactly as Connect did before configs
|
|
136
|
+
* existed. Read that as permissive, not as unset.
|
|
137
|
+
*/
|
|
138
|
+
interface ConnectConfig {
|
|
139
|
+
version: number;
|
|
140
|
+
/** Partner ids or names offered in the picker. null = every venue we support. */
|
|
141
|
+
venue_allowlist: string[] | null;
|
|
142
|
+
/** Surface the OpenMarkets practice book as a credential-less venue. */
|
|
143
|
+
offer_internal_book: boolean;
|
|
144
|
+
/**
|
|
145
|
+
* Currencies users may trade. `['ATLAS']` is practice-only and is ENFORCED
|
|
146
|
+
* on every order path, not merely hidden in the UI — users can still link
|
|
147
|
+
* venues, read balances and sync history; only real-money orders are
|
|
148
|
+
* refused.
|
|
149
|
+
*/
|
|
150
|
+
allowed_currencies: string[];
|
|
151
|
+
/** DERIVED from allowed_currencies server-side. Sending it has no effect. */
|
|
152
|
+
allow_real_money: boolean;
|
|
153
|
+
/** Permissions the user is asked to grant. null = all of them. */
|
|
154
|
+
available_scopes: ConnectScope[] | null;
|
|
155
|
+
branding: {
|
|
156
|
+
display_name?: string;
|
|
157
|
+
logo_url?: string;
|
|
158
|
+
primary_color?: string;
|
|
159
|
+
} | null;
|
|
160
|
+
allowed_return_urls: string[] | null;
|
|
161
|
+
default_link_mode: LinkSessionMode;
|
|
162
|
+
[key: string]: unknown;
|
|
163
|
+
}
|
|
164
|
+
/** Permissions an end user grants per connected venue. */
|
|
165
|
+
type ConnectScope = 'history:read' | 'trade:execute' | 'balance:read';
|
|
166
|
+
interface ConnectConfigResult {
|
|
167
|
+
/** null when the organization has never saved one — `config` is the defaults. */
|
|
168
|
+
connect_config_id: string | null;
|
|
169
|
+
config: ConnectConfig;
|
|
170
|
+
/**
|
|
171
|
+
* Present on update: how many EXISTING users the change was applied to.
|
|
172
|
+
* A funding-mode change reaches users already provisioned, not just future
|
|
173
|
+
* ones, so this reports what actually happened.
|
|
174
|
+
*/
|
|
175
|
+
reconcile?: {
|
|
176
|
+
scanned: number;
|
|
177
|
+
reconciled: number;
|
|
178
|
+
failed: number;
|
|
179
|
+
} | null;
|
|
180
|
+
}
|
|
130
181
|
interface BuyResult {
|
|
131
182
|
results: Array<{
|
|
132
183
|
index: number;
|
|
@@ -160,6 +211,18 @@ interface OpenMarketsClient {
|
|
|
160
211
|
create(params: CreateLinkSessionParams): Promise<LinkSession>;
|
|
161
212
|
get<T = unknown>(linkSessionId: string): Promise<T>;
|
|
162
213
|
};
|
|
214
|
+
/**
|
|
215
|
+
* The organization's Connect config — which venues appear, whether real
|
|
216
|
+
* money is allowed, and how the hosted flow is branded.
|
|
217
|
+
*
|
|
218
|
+
* Requires a PLAYER JWT with workspace admin, not an API key: this is
|
|
219
|
+
* account governance rather than a data-API capability. `update` sends a
|
|
220
|
+
* whole body (it is normalized server-side), so read, change, write.
|
|
221
|
+
*/
|
|
222
|
+
configs: {
|
|
223
|
+
get(workspaceId: string): Promise<ConnectConfigResult>;
|
|
224
|
+
update(workspaceId: string, config: Partial<ConnectConfig>): Promise<ConnectConfigResult>;
|
|
225
|
+
};
|
|
163
226
|
webhooks: {
|
|
164
227
|
getConfig<T = unknown>(): Promise<T>;
|
|
165
228
|
/** Verify a delivery using the configured `webhookSecret`. */
|
|
@@ -185,4 +248,4 @@ interface OpenMarketsClient {
|
|
|
185
248
|
}
|
|
186
249
|
declare function createClient(options: OpenMarketsClientOptions): OpenMarketsClient;
|
|
187
250
|
|
|
188
|
-
export { type BuyLegStatus, type BuyOrder, type BuyResult, type ConnectWebhookEvent, type ConnectWebhookEventType, type CreateLinkSessionParams, DEFAULT_BASE_URL, type HttpMethod, type LinkSession, type LinkSessionMode, type OpenMarketsClient, type OpenMarketsClientOptions, OpenMarketsError, type ProvisionResult, type ProvisionUserParams, type RequestOptions, type VerifyWebhookOptions, WebhookSignatureError, constructWebhookEvent, createClient, verifyWebhookSignature };
|
|
251
|
+
export { type BuyLegStatus, type BuyOrder, type BuyResult, type ConnectConfig, type ConnectConfigResult, type ConnectScope, type ConnectWebhookEvent, type ConnectWebhookEventType, type CreateLinkSessionParams, DEFAULT_BASE_URL, type HttpMethod, type LinkSession, type LinkSessionMode, type OpenMarketsClient, type OpenMarketsClientOptions, OpenMarketsError, type ProvisionResult, type ProvisionUserParams, type RequestOptions, type VerifyWebhookOptions, WebhookSignatureError, constructWebhookEvent, createClient, verifyWebhookSignature };
|
package/dist/index.d.ts
CHANGED
|
@@ -127,6 +127,57 @@ type BuyLegStatus =
|
|
|
127
127
|
| 'failed'
|
|
128
128
|
/** No viable venue was found; nothing was sent. */
|
|
129
129
|
| 'rejected';
|
|
130
|
+
/**
|
|
131
|
+
* What an organization's END USERS see and may do in the hosted flow. Mirrors
|
|
132
|
+
* `ConnectConfigBody` server-side.
|
|
133
|
+
*
|
|
134
|
+
* A `null` field means "no restriction / use the default" throughout, so an
|
|
135
|
+
* organization with no config behaves exactly as Connect did before configs
|
|
136
|
+
* existed. Read that as permissive, not as unset.
|
|
137
|
+
*/
|
|
138
|
+
interface ConnectConfig {
|
|
139
|
+
version: number;
|
|
140
|
+
/** Partner ids or names offered in the picker. null = every venue we support. */
|
|
141
|
+
venue_allowlist: string[] | null;
|
|
142
|
+
/** Surface the OpenMarkets practice book as a credential-less venue. */
|
|
143
|
+
offer_internal_book: boolean;
|
|
144
|
+
/**
|
|
145
|
+
* Currencies users may trade. `['ATLAS']` is practice-only and is ENFORCED
|
|
146
|
+
* on every order path, not merely hidden in the UI — users can still link
|
|
147
|
+
* venues, read balances and sync history; only real-money orders are
|
|
148
|
+
* refused.
|
|
149
|
+
*/
|
|
150
|
+
allowed_currencies: string[];
|
|
151
|
+
/** DERIVED from allowed_currencies server-side. Sending it has no effect. */
|
|
152
|
+
allow_real_money: boolean;
|
|
153
|
+
/** Permissions the user is asked to grant. null = all of them. */
|
|
154
|
+
available_scopes: ConnectScope[] | null;
|
|
155
|
+
branding: {
|
|
156
|
+
display_name?: string;
|
|
157
|
+
logo_url?: string;
|
|
158
|
+
primary_color?: string;
|
|
159
|
+
} | null;
|
|
160
|
+
allowed_return_urls: string[] | null;
|
|
161
|
+
default_link_mode: LinkSessionMode;
|
|
162
|
+
[key: string]: unknown;
|
|
163
|
+
}
|
|
164
|
+
/** Permissions an end user grants per connected venue. */
|
|
165
|
+
type ConnectScope = 'history:read' | 'trade:execute' | 'balance:read';
|
|
166
|
+
interface ConnectConfigResult {
|
|
167
|
+
/** null when the organization has never saved one — `config` is the defaults. */
|
|
168
|
+
connect_config_id: string | null;
|
|
169
|
+
config: ConnectConfig;
|
|
170
|
+
/**
|
|
171
|
+
* Present on update: how many EXISTING users the change was applied to.
|
|
172
|
+
* A funding-mode change reaches users already provisioned, not just future
|
|
173
|
+
* ones, so this reports what actually happened.
|
|
174
|
+
*/
|
|
175
|
+
reconcile?: {
|
|
176
|
+
scanned: number;
|
|
177
|
+
reconciled: number;
|
|
178
|
+
failed: number;
|
|
179
|
+
} | null;
|
|
180
|
+
}
|
|
130
181
|
interface BuyResult {
|
|
131
182
|
results: Array<{
|
|
132
183
|
index: number;
|
|
@@ -160,6 +211,18 @@ interface OpenMarketsClient {
|
|
|
160
211
|
create(params: CreateLinkSessionParams): Promise<LinkSession>;
|
|
161
212
|
get<T = unknown>(linkSessionId: string): Promise<T>;
|
|
162
213
|
};
|
|
214
|
+
/**
|
|
215
|
+
* The organization's Connect config — which venues appear, whether real
|
|
216
|
+
* money is allowed, and how the hosted flow is branded.
|
|
217
|
+
*
|
|
218
|
+
* Requires a PLAYER JWT with workspace admin, not an API key: this is
|
|
219
|
+
* account governance rather than a data-API capability. `update` sends a
|
|
220
|
+
* whole body (it is normalized server-side), so read, change, write.
|
|
221
|
+
*/
|
|
222
|
+
configs: {
|
|
223
|
+
get(workspaceId: string): Promise<ConnectConfigResult>;
|
|
224
|
+
update(workspaceId: string, config: Partial<ConnectConfig>): Promise<ConnectConfigResult>;
|
|
225
|
+
};
|
|
163
226
|
webhooks: {
|
|
164
227
|
getConfig<T = unknown>(): Promise<T>;
|
|
165
228
|
/** Verify a delivery using the configured `webhookSecret`. */
|
|
@@ -185,4 +248,4 @@ interface OpenMarketsClient {
|
|
|
185
248
|
}
|
|
186
249
|
declare function createClient(options: OpenMarketsClientOptions): OpenMarketsClient;
|
|
187
250
|
|
|
188
|
-
export { type BuyLegStatus, type BuyOrder, type BuyResult, type ConnectWebhookEvent, type ConnectWebhookEventType, type CreateLinkSessionParams, DEFAULT_BASE_URL, type HttpMethod, type LinkSession, type LinkSessionMode, type OpenMarketsClient, type OpenMarketsClientOptions, OpenMarketsError, type ProvisionResult, type ProvisionUserParams, type RequestOptions, type VerifyWebhookOptions, WebhookSignatureError, constructWebhookEvent, createClient, verifyWebhookSignature };
|
|
251
|
+
export { type BuyLegStatus, type BuyOrder, type BuyResult, type ConnectConfig, type ConnectConfigResult, type ConnectScope, type ConnectWebhookEvent, type ConnectWebhookEventType, type CreateLinkSessionParams, DEFAULT_BASE_URL, type HttpMethod, type LinkSession, type LinkSessionMode, type OpenMarketsClient, type OpenMarketsClientOptions, OpenMarketsError, type ProvisionResult, type ProvisionUserParams, type RequestOptions, type VerifyWebhookOptions, WebhookSignatureError, constructWebhookEvent, createClient, verifyWebhookSignature };
|
package/dist/index.js
CHANGED
|
@@ -123,6 +123,17 @@ function createClient(options) {
|
|
|
123
123
|
create: (params) => request("POST", "/flow/v1/connect/link-sessions", { body: params }),
|
|
124
124
|
get: (linkSessionId) => request("GET", `/flow/v1/connect/link-sessions/${encodeURIComponent(linkSessionId)}`)
|
|
125
125
|
},
|
|
126
|
+
configs: {
|
|
127
|
+
get: (workspaceId) => request(
|
|
128
|
+
"GET",
|
|
129
|
+
`/flow/v1/workspaces/${encodeURIComponent(workspaceId)}/connect-config`
|
|
130
|
+
),
|
|
131
|
+
update: (workspaceId, config) => request(
|
|
132
|
+
"PUT",
|
|
133
|
+
`/flow/v1/workspaces/${encodeURIComponent(workspaceId)}/connect-config`,
|
|
134
|
+
{ body: { config } }
|
|
135
|
+
)
|
|
136
|
+
},
|
|
126
137
|
webhooks: {
|
|
127
138
|
getConfig: () => request("GET", "/flow/v1/connect/webhook-config"),
|
|
128
139
|
verify: (rawBody, sig, opts) => verifyWebhookSignature(requireSecret(), rawBody, sig, opts),
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;AAkBO,IAAM,gBAAA,GAAmB;AAOzB,IAAM,gBAAA,GAAN,cAA+B,KAAA,CAAM;AAAA,EAIxC,WAAA,CAAY,MAAA,EAAgB,IAAA,EAAc,OAAA,EAAiB,OAAA,EAAmC;AAC1F,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,kBAAA;AACZ,IAA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;AAAA,IACA,OAAA,EAAS;AAAA,MACL,QAAA,EAAU,CAAC,cAAA,KACP,OAAA,CAAQ,OAAO,gCAAA,EAAkC,EAAE,KAAA,EAAO,cAAA,EAAgB,CAAA;AAAA,MAC9E,QAAA,EAAU,CAAC,cAAA,KACP,OAAA,CAAQ,OAAO,gCAAA,EAAkC,EAAE,KAAA,EAAO,cAAA,EAAgB;AAAA,KAClF;AAAA,IACA,MAAA,EAAQ;AAAA,MACJ,IAAA,EAAM,CAAC,cAAA,KACH,OAAA,CAAQ,OAAO,sBAAA,EAAwB,EAAE,KAAA,EAAO,cAAA,EAAgB,CAAA;AAAA,MACpE,KAAK,CAAC,MAAA,EAAQ,IAAA,KACV,OAAA,CAAmB,QAAQ,0BAAA,EAA4B;AAAA,QACnD,IAAA,EAAM,EAAE,MAAA,EAAO;AAAA,QACf,OAAO,IAAA,CAAK;AAAA,OACf;AAAA,KACT;AAAA,IACA,IAAA,EAAM;AAAA,MACF,OAAA,EAAS,MAAM,OAAA,CAAQ,KAAA,EAAO,kBAAkB,CAAA;AAAA,MAChD,gBAAA,EAAkB,CAAC,SAAA,KACf,OAAA,CAAQ,OAAO,CAAA,kBAAA,EAAqB,kBAAA,CAAmB,SAAS,CAAC,CAAA,UAAA,CAAY;AAAA;AACrF,GACJ;AACJ","file":"index.js","sourcesContent":["/**\n * @openmarketsai/connect-node\n *\n * Server SDK for OpenMarkets Connect. A thin, typed wrapper over the Flow API:\n * provision your users, mint hosted link sessions, verify webhook deliveries,\n * read on a user's behalf, and execute orders on their account.\n *\n * import { createClient } from '@openmarketsai/connect-node'\n * const om = createClient({ apiKey: process.env.OM_API_KEY! })\n *\n * await om.connect.users.provision({ external_user_id: 'user-123' })\n * const { token } = await om.connect.linkSessions.create({ external_user_id: 'user-123' })\n * await om.orders.buy([leg], { actAs: 'user-123' })\n *\n * Pairs with @openmarketsai/connect-web (the in-app launcher).\n */\nimport crypto from 'node:crypto'\n\nexport const DEFAULT_BASE_URL = 'https://api.openmarkets.ai'\n\n// ──────────────────────────────────────────────────────────────────────────\n// Errors\n// ──────────────────────────────────────────────────────────────────────────\n\n/** Thrown when the API returns a non-2xx response. Mirrors the Flow error envelope. */\nexport class OpenMarketsError extends Error {\n readonly status: number\n readonly code: string\n readonly details?: Record<string, unknown>\n constructor(status: number, code: string, message: string, details?: Record<string, unknown>) {\n super(message)\n this.name = 'OpenMarketsError'\n this.status = status\n this.code = code\n this.details = details\n }\n}\n\n/** Thrown by `constructWebhookEvent` when a signature is missing, stale, or invalid. */\nexport class WebhookSignatureError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'WebhookSignatureError'\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Webhook verification (matches src/utils/webhook-signature.ts byte-for-byte)\n//\n// Header: X-OpenMarkets-Signature: t=<unix_seconds>,v1=<hex hmac>\n// Signed string: `${t}.${rawBody}`, HMAC-SHA256 with your whsec_ secret.\n// IMPORTANT: verify over the EXACT raw request body, not a re-serialized object.\n// ──────────────────────────────────────────────────────────────────────────\n\nexport type ConnectWebhookEventType =\n | 'user.partners_connected'\n | 'user.permissions_changed'\n | (string & {})\n\nexport interface ConnectWebhookEvent {\n type: ConnectWebhookEventType\n [key: string]: unknown\n}\n\nexport interface VerifyWebhookOptions {\n /** Max age of the signature timestamp, in seconds. Default 300 (5 min). 0 disables. */\n toleranceSec?: number\n /** Injectable clock for testing. */\n nowSec?: number\n}\n\nfunction toRaw(body: string | Buffer): string {\n return typeof body === 'string' ? body : body.toString('utf8')\n}\n\nfunction parseSignatureHeader(header: string): { t: number; v1: string } | null {\n const parts = header.split(',').reduce<Record<string, string>>((acc, kv) => {\n const idx = kv.indexOf('=')\n if (idx > 0) acc[kv.slice(0, idx).trim()] = kv.slice(idx + 1).trim()\n return acc\n }, {})\n const t = Number(parts.t)\n if (!parts.v1 || !isFinite(t)) return null\n return { t, v1: parts.v1 }\n}\n\nfunction timingSafeEqualHex(a: string, b: string): boolean {\n const ab = Buffer.from(a, 'hex')\n const bb = Buffer.from(b, 'hex')\n if (ab.length === 0 || ab.length !== bb.length) return false\n return crypto.timingSafeEqual(ab, bb)\n}\n\n/** Verify a webhook signature. Returns false on any failure (never throws). */\nexport function verifyWebhookSignature(\n secret: string,\n rawBody: string | Buffer,\n signatureHeader: string | null | undefined,\n opts: VerifyWebhookOptions = {},\n): boolean {\n if (!secret || !signatureHeader) return false\n const parsed = parseSignatureHeader(signatureHeader)\n if (!parsed) return false\n const toleranceSec = opts.toleranceSec ?? 300\n const nowSec = opts.nowSec ?? Math.floor(Date.now() / 1000)\n if (toleranceSec > 0 && Math.abs(nowSec - parsed.t) > toleranceSec) return false\n const expected = crypto\n .createHmac('sha256', secret)\n .update(`${parsed.t}.${toRaw(rawBody)}`)\n .digest('hex')\n return timingSafeEqualHex(expected, parsed.v1)\n}\n\n/** Verify the signature and return the parsed event, or throw `WebhookSignatureError`. */\nexport function constructWebhookEvent(\n secret: string,\n rawBody: string | Buffer,\n signatureHeader: string | null | undefined,\n opts: VerifyWebhookOptions = {},\n): ConnectWebhookEvent {\n if (!verifyWebhookSignature(secret, rawBody, signatureHeader, opts)) {\n throw new WebhookSignatureError('Invalid or expired webhook signature')\n }\n try {\n return JSON.parse(toRaw(rawBody)) as ConnectWebhookEvent\n } catch {\n throw new WebhookSignatureError('Webhook body is not valid JSON')\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Client\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface OpenMarketsClientOptions {\n /** Your Connect org API key. Sent as `X-API-Key`. */\n apiKey: string\n /** API base URL. Defaults to https://api.openmarkets.ai. */\n baseUrl?: string\n /** Your webhook signing secret (`whsec_…`), enabling `client.webhooks.*`. */\n webhookSecret?: string\n /** Custom fetch (defaults to global fetch; Node 18+). */\n fetch?: typeof fetch\n /** Per-request timeout in ms. Default 30000. */\n timeoutMs?: number\n}\n\nexport type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'\n\nexport interface RequestOptions {\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown\n /** Act on this user's behalf — sets the `X-OpenMarkets-Account` header. */\n actAs?: string\n}\n\n// Inputs (snake_case to match the API — buy legs map 1:1 from liquidity entries).\nexport interface ProvisionUserParams {\n external_user_id: string\n email?: string\n name?: string\n}\nexport type LinkSessionMode = 'connect' | 'manage'\nexport interface CreateLinkSessionParams {\n external_user_id: string\n return_url?: string\n mode?: LinkSessionMode\n allowed_partners?: string[]\n /** Pick a specific org Connect config; omit to use the org's default (if any). */\n connect_config_id?: string\n}\nexport interface BuyOrder {\n /** What to buy — set exactly one of position_hash or liquidity_hash. */\n position_hash?: string\n liquidity_hash?: string\n /** Size — set exactly one of amount or shares. */\n amount?: number // stake, notional USD\n shares?: number // contract count (each pays $1 on win)\n /** Price ceiling, 0..1 exclusive — won't fill above this. */\n max_price: number\n /** Optional — pin a venue; omit to route to the best price. */\n partner_id?: string\n /** Optional — 'real' (default) or 'paper' (practice book). */\n mode?: 'real' | 'paper'\n}\n\n// Outputs (light — partners can pass a type param for stricter typing).\n/**\n * `POST /flow/v1/connect/users`. Idempotent — safe to call on every login.\n *\n * `om_account_id` is the field an integration actually needs (it addresses the\n * user in later calls) and was previously absent, so it typed as `unknown` via\n * the index signature.\n */\nexport interface ProvisionResult {\n /** Our id for this user. Pass as `actAs` when trading on their behalf. */\n om_account_id: string\n external_user_id: string\n /** false when the user already existed. */\n created: boolean\n [key: string]: unknown\n}\n/**\n * The response of `POST /flow/v1/connect/link-sessions`.\n *\n * These names are the API's, verified against the route rather than assumed:\n * it returns `link_token`, NOT `token`. The previous declaration named `token`,\n * `external_user_id` and `mode` — none of which the endpoint sends — so the one\n * field an integration actually needs type-checked as a string and arrived\n * `undefined`, opening the hosted flow with `token=undefined`. The index\n * signature below is what kept that quiet; keep these names in step with\n * `CreateLinkSessionResult` in LinkSessionOrchestrator.\n */\nexport interface LinkSession {\n link_session_id: string\n /** Single-use, expires in 15 minutes. Hand to `createConnect().open()`. */\n link_token: string\n /** The hosted flow URL, for redirect mode or a native in-app browser. */\n hosted_url: string\n expires_at: string\n [key: string]: unknown\n}\n/**\n * The status of one leg, mirroring `flowLegStatus` in the API.\n *\n * ALL FIVE values are reachable. This union previously listed only three, so a\n * `switch` written against the SDK's types compiled clean and silently fell\n * through for a resting or pending order — an order that IS live, sitting on a\n * venue book, treated as if it had never been placed. Any change here must\n * follow the API, not the other way round.\n */\nexport type BuyLegStatus =\n /** Filled or partially filled. */\n | 'completed'\n /** Live on the venue's book, unfilled. Not a failure — check back. */\n | 'resting'\n /** Accepted by the venue, fill not yet confirmed (async venues). */\n | 'pending'\n /** The venue or a pre-trade gate rejected it. */\n | 'failed'\n /** No viable venue was found; nothing was sent. */\n | 'rejected'\n\nexport interface BuyResult {\n results: Array<{\n index: number\n status: BuyLegStatus\n /** NULL when the leg was rejected before routing — no decision was made. */\n sor_decision_id: string | null\n filled_notional: number\n filled_shares: number\n /** The un-buyable remainder of the requested stake. */\n unfilled_notional: number\n avg_price: number | null\n rejected_reason: string | null\n venues: Array<{\n partner_id: string\n success: boolean\n router_order_id: string | null\n error: string | null\n }>\n }>\n}\n\ninterface FlowEnvelope<T> {\n data?: T\n error?: { code: string; message: string; details?: Record<string, unknown> }\n}\n\nexport interface OpenMarketsClient {\n /** Generic typed request — escape hatch for endpoints without a helper. */\n request<T = unknown>(method: HttpMethod, path: string, opts?: RequestOptions): Promise<T>\n connect: {\n users: {\n provision(params: ProvisionUserParams): Promise<ProvisionResult>\n get<T = unknown>(externalUserId: string): Promise<T>\n getPolicy<T = unknown>(externalUserId: string): Promise<T>\n }\n linkSessions: {\n create(params: CreateLinkSessionParams): Promise<LinkSession>\n get<T = unknown>(linkSessionId: string): Promise<T>\n }\n webhooks: {\n getConfig<T = unknown>(): Promise<T>\n /** Verify a delivery using the configured `webhookSecret`. */\n verify(rawBody: string | Buffer, signatureHeader: string | null | undefined, opts?: VerifyWebhookOptions): boolean\n /** Verify + parse, or throw. Uses the configured `webhookSecret`. */\n constructEvent(rawBody: string | Buffer, signatureHeader: string | null | undefined, opts?: VerifyWebhookOptions): ConnectWebhookEvent\n }\n }\n account: {\n partners<T = unknown>(externalUserId: string): Promise<T>\n balances<T = unknown>(externalUserId: string): Promise<T>\n }\n orders: {\n list<T = unknown>(externalUserId: string): Promise<T>\n buy(orders: BuyOrder[], opts: { actAs: string }): Promise<BuyResult>\n }\n data: {\n leagues<T = unknown>(): Promise<T>\n contestLiquidity<T = unknown>(contestId: string): Promise<T>\n }\n}\n\nexport function createClient(options: OpenMarketsClientOptions): OpenMarketsClient {\n if (!options.apiKey) throw new Error('createClient: apiKey is required')\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '')\n const doFetch = options.fetch ?? globalThis.fetch\n if (!doFetch) throw new Error('No fetch available — pass options.fetch (Node < 18)')\n const timeoutMs = options.timeoutMs ?? 30_000\n\n async function request<T = unknown>(\n method: HttpMethod,\n path: string,\n opts: RequestOptions = {},\n ): Promise<T> {\n const url = new URL(baseUrl + path)\n for (const [k, v] of Object.entries(opts.query ?? {})) {\n if (v !== undefined) url.searchParams.set(k, String(v))\n }\n const headers: Record<string, string> = {\n 'X-API-Key': options.apiKey,\n Accept: 'application/json',\n }\n if (opts.body !== undefined) headers['Content-Type'] = 'application/json'\n if (opts.actAs) headers['X-OpenMarkets-Account'] = opts.actAs\n\n const ctrl = new AbortController()\n const timer = setTimeout(() => ctrl.abort(), timeoutMs)\n let res: Response\n try {\n res = await doFetch(url.toString(), {\n method,\n headers,\n body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,\n signal: ctrl.signal,\n })\n } finally {\n clearTimeout(timer)\n }\n\n let envelope: FlowEnvelope<T> | undefined\n const text = await res.text()\n if (text) {\n try {\n envelope = JSON.parse(text) as FlowEnvelope<T>\n } catch {\n /* non-JSON body */\n }\n }\n\n if (!res.ok) {\n const err = envelope?.error\n throw new OpenMarketsError(\n res.status,\n err?.code ?? 'http_error',\n err?.message ?? `Request failed with status ${res.status}`,\n err?.details,\n )\n }\n return (envelope?.data ?? (undefined as unknown)) as T\n }\n\n function requireSecret(): string {\n if (!options.webhookSecret) {\n throw new Error('webhookSecret was not provided to createClient()')\n }\n return options.webhookSecret\n }\n\n return {\n request,\n connect: {\n users: {\n provision: (params) =>\n request<ProvisionResult>('POST', '/flow/v1/connect/users', { body: params }),\n get: (externalUserId) =>\n request('GET', `/flow/v1/connect/users/${encodeURIComponent(externalUserId)}`),\n getPolicy: (externalUserId) =>\n request('GET', `/flow/v1/connect/users/${encodeURIComponent(externalUserId)}/policy`),\n },\n linkSessions: {\n create: (params) =>\n request<LinkSession>('POST', '/flow/v1/connect/link-sessions', { body: params }),\n get: (linkSessionId) =>\n request('GET', `/flow/v1/connect/link-sessions/${encodeURIComponent(linkSessionId)}`),\n },\n webhooks: {\n getConfig: () => request('GET', '/flow/v1/connect/webhook-config'),\n verify: (rawBody, sig, opts) =>\n verifyWebhookSignature(requireSecret(), rawBody, sig, opts),\n constructEvent: (rawBody, sig, opts) =>\n constructWebhookEvent(requireSecret(), rawBody, sig, opts),\n },\n },\n account: {\n partners: (externalUserId) =>\n request('GET', '/flow/v1/auth/account/partners', { actAs: externalUserId }),\n balances: (externalUserId) =>\n request('GET', '/flow/v1/auth/account/balances', { actAs: externalUserId }),\n },\n orders: {\n list: (externalUserId) =>\n request('GET', '/flow/v1/auth/orders', { actAs: externalUserId }),\n buy: (orders, opts) =>\n request<BuyResult>('POST', '/flow/v1/auth/orders/buy', {\n body: { orders },\n actAs: opts.actAs,\n }),\n },\n data: {\n leagues: () => request('GET', '/flow/v1/leagues'),\n contestLiquidity: (contestId) =>\n request('GET', `/flow/v1/contests/${encodeURIComponent(contestId)}/liquidity`),\n },\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;AAkBO,IAAM,gBAAA,GAAmB;AAOzB,IAAM,gBAAA,GAAN,cAA+B,KAAA,CAAM;AAAA,EAIxC,WAAA,CAAY,MAAA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A,CAAQ,OAAO,CAAA,kBAAA,EAAqB,kBAAA,CAAmB,SAAS,CAAC,CAAA,UAAA,CAAY;AAAA;AACrF,GACJ;AACJ","file":"index.js","sourcesContent":["/**\n * @openmarketsai/connect-node\n *\n * Server SDK for OpenMarkets Connect. A thin, typed wrapper over the Flow API:\n * provision your users, mint hosted link sessions, verify webhook deliveries,\n * read on a user's behalf, and execute orders on their account.\n *\n * import { createClient } from '@openmarketsai/connect-node'\n * const om = createClient({ apiKey: process.env.OM_API_KEY! })\n *\n * await om.connect.users.provision({ external_user_id: 'user-123' })\n * const { token } = await om.connect.linkSessions.create({ external_user_id: 'user-123' })\n * await om.orders.buy([leg], { actAs: 'user-123' })\n *\n * Pairs with @openmarketsai/connect-web (the in-app launcher).\n */\nimport crypto from 'node:crypto'\n\nexport const DEFAULT_BASE_URL = 'https://api.openmarkets.ai'\n\n// ──────────────────────────────────────────────────────────────────────────\n// Errors\n// ──────────────────────────────────────────────────────────────────────────\n\n/** Thrown when the API returns a non-2xx response. Mirrors the Flow error envelope. */\nexport class OpenMarketsError extends Error {\n readonly status: number\n readonly code: string\n readonly details?: Record<string, unknown>\n constructor(status: number, code: string, message: string, details?: Record<string, unknown>) {\n super(message)\n this.name = 'OpenMarketsError'\n this.status = status\n this.code = code\n this.details = details\n }\n}\n\n/** Thrown by `constructWebhookEvent` when a signature is missing, stale, or invalid. */\nexport class WebhookSignatureError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'WebhookSignatureError'\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Webhook verification (matches src/utils/webhook-signature.ts byte-for-byte)\n//\n// Header: X-OpenMarkets-Signature: t=<unix_seconds>,v1=<hex hmac>\n// Signed string: `${t}.${rawBody}`, HMAC-SHA256 with your whsec_ secret.\n// IMPORTANT: verify over the EXACT raw request body, not a re-serialized object.\n// ──────────────────────────────────────────────────────────────────────────\n\nexport type ConnectWebhookEventType =\n | 'user.partners_connected'\n | 'user.permissions_changed'\n | (string & {})\n\nexport interface ConnectWebhookEvent {\n type: ConnectWebhookEventType\n [key: string]: unknown\n}\n\nexport interface VerifyWebhookOptions {\n /** Max age of the signature timestamp, in seconds. Default 300 (5 min). 0 disables. */\n toleranceSec?: number\n /** Injectable clock for testing. */\n nowSec?: number\n}\n\nfunction toRaw(body: string | Buffer): string {\n return typeof body === 'string' ? body : body.toString('utf8')\n}\n\nfunction parseSignatureHeader(header: string): { t: number; v1: string } | null {\n const parts = header.split(',').reduce<Record<string, string>>((acc, kv) => {\n const idx = kv.indexOf('=')\n if (idx > 0) acc[kv.slice(0, idx).trim()] = kv.slice(idx + 1).trim()\n return acc\n }, {})\n const t = Number(parts.t)\n if (!parts.v1 || !isFinite(t)) return null\n return { t, v1: parts.v1 }\n}\n\nfunction timingSafeEqualHex(a: string, b: string): boolean {\n const ab = Buffer.from(a, 'hex')\n const bb = Buffer.from(b, 'hex')\n if (ab.length === 0 || ab.length !== bb.length) return false\n return crypto.timingSafeEqual(ab, bb)\n}\n\n/** Verify a webhook signature. Returns false on any failure (never throws). */\nexport function verifyWebhookSignature(\n secret: string,\n rawBody: string | Buffer,\n signatureHeader: string | null | undefined,\n opts: VerifyWebhookOptions = {},\n): boolean {\n if (!secret || !signatureHeader) return false\n const parsed = parseSignatureHeader(signatureHeader)\n if (!parsed) return false\n const toleranceSec = opts.toleranceSec ?? 300\n const nowSec = opts.nowSec ?? Math.floor(Date.now() / 1000)\n if (toleranceSec > 0 && Math.abs(nowSec - parsed.t) > toleranceSec) return false\n const expected = crypto\n .createHmac('sha256', secret)\n .update(`${parsed.t}.${toRaw(rawBody)}`)\n .digest('hex')\n return timingSafeEqualHex(expected, parsed.v1)\n}\n\n/** Verify the signature and return the parsed event, or throw `WebhookSignatureError`. */\nexport function constructWebhookEvent(\n secret: string,\n rawBody: string | Buffer,\n signatureHeader: string | null | undefined,\n opts: VerifyWebhookOptions = {},\n): ConnectWebhookEvent {\n if (!verifyWebhookSignature(secret, rawBody, signatureHeader, opts)) {\n throw new WebhookSignatureError('Invalid or expired webhook signature')\n }\n try {\n return JSON.parse(toRaw(rawBody)) as ConnectWebhookEvent\n } catch {\n throw new WebhookSignatureError('Webhook body is not valid JSON')\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Client\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface OpenMarketsClientOptions {\n /** Your Connect org API key. Sent as `X-API-Key`. */\n apiKey: string\n /** API base URL. Defaults to https://api.openmarkets.ai. */\n baseUrl?: string\n /** Your webhook signing secret (`whsec_…`), enabling `client.webhooks.*`. */\n webhookSecret?: string\n /** Custom fetch (defaults to global fetch; Node 18+). */\n fetch?: typeof fetch\n /** Per-request timeout in ms. Default 30000. */\n timeoutMs?: number\n}\n\nexport type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'\n\nexport interface RequestOptions {\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown\n /** Act on this user's behalf — sets the `X-OpenMarkets-Account` header. */\n actAs?: string\n}\n\n// Inputs (snake_case to match the API — buy legs map 1:1 from liquidity entries).\nexport interface ProvisionUserParams {\n external_user_id: string\n email?: string\n name?: string\n}\nexport type LinkSessionMode = 'connect' | 'manage'\nexport interface CreateLinkSessionParams {\n external_user_id: string\n return_url?: string\n mode?: LinkSessionMode\n allowed_partners?: string[]\n /** Pick a specific org Connect config; omit to use the org's default (if any). */\n connect_config_id?: string\n}\nexport interface BuyOrder {\n /** What to buy — set exactly one of position_hash or liquidity_hash. */\n position_hash?: string\n liquidity_hash?: string\n /** Size — set exactly one of amount or shares. */\n amount?: number // stake, notional USD\n shares?: number // contract count (each pays $1 on win)\n /** Price ceiling, 0..1 exclusive — won't fill above this. */\n max_price: number\n /** Optional — pin a venue; omit to route to the best price. */\n partner_id?: string\n /** Optional — 'real' (default) or 'paper' (practice book). */\n mode?: 'real' | 'paper'\n}\n\n// Outputs (light — partners can pass a type param for stricter typing).\n/**\n * `POST /flow/v1/connect/users`. Idempotent — safe to call on every login.\n *\n * `om_account_id` is the field an integration actually needs (it addresses the\n * user in later calls) and was previously absent, so it typed as `unknown` via\n * the index signature.\n */\nexport interface ProvisionResult {\n /** Our id for this user. Pass as `actAs` when trading on their behalf. */\n om_account_id: string\n external_user_id: string\n /** false when the user already existed. */\n created: boolean\n [key: string]: unknown\n}\n/**\n * The response of `POST /flow/v1/connect/link-sessions`.\n *\n * These names are the API's, verified against the route rather than assumed:\n * it returns `link_token`, NOT `token`. The previous declaration named `token`,\n * `external_user_id` and `mode` — none of which the endpoint sends — so the one\n * field an integration actually needs type-checked as a string and arrived\n * `undefined`, opening the hosted flow with `token=undefined`. The index\n * signature below is what kept that quiet; keep these names in step with\n * `CreateLinkSessionResult` in LinkSessionOrchestrator.\n */\nexport interface LinkSession {\n link_session_id: string\n /** Single-use, expires in 15 minutes. Hand to `createConnect().open()`. */\n link_token: string\n /** The hosted flow URL, for redirect mode or a native in-app browser. */\n hosted_url: string\n expires_at: string\n [key: string]: unknown\n}\n/**\n * The status of one leg, mirroring `flowLegStatus` in the API.\n *\n * ALL FIVE values are reachable. This union previously listed only three, so a\n * `switch` written against the SDK's types compiled clean and silently fell\n * through for a resting or pending order — an order that IS live, sitting on a\n * venue book, treated as if it had never been placed. Any change here must\n * follow the API, not the other way round.\n */\nexport type BuyLegStatus =\n /** Filled or partially filled. */\n | 'completed'\n /** Live on the venue's book, unfilled. Not a failure — check back. */\n | 'resting'\n /** Accepted by the venue, fill not yet confirmed (async venues). */\n | 'pending'\n /** The venue or a pre-trade gate rejected it. */\n | 'failed'\n /** No viable venue was found; nothing was sent. */\n | 'rejected'\n\n/**\n * What an organization's END USERS see and may do in the hosted flow. Mirrors\n * `ConnectConfigBody` server-side.\n *\n * A `null` field means \"no restriction / use the default\" throughout, so an\n * organization with no config behaves exactly as Connect did before configs\n * existed. Read that as permissive, not as unset.\n */\nexport interface ConnectConfig {\n version: number\n /** Partner ids or names offered in the picker. null = every venue we support. */\n venue_allowlist: string[] | null\n /** Surface the OpenMarkets practice book as a credential-less venue. */\n offer_internal_book: boolean\n /**\n * Currencies users may trade. `['ATLAS']` is practice-only and is ENFORCED\n * on every order path, not merely hidden in the UI — users can still link\n * venues, read balances and sync history; only real-money orders are\n * refused.\n */\n allowed_currencies: string[]\n /** DERIVED from allowed_currencies server-side. Sending it has no effect. */\n allow_real_money: boolean\n /** Permissions the user is asked to grant. null = all of them. */\n available_scopes: ConnectScope[] | null\n branding: { display_name?: string; logo_url?: string; primary_color?: string } | null\n allowed_return_urls: string[] | null\n default_link_mode: LinkSessionMode\n [key: string]: unknown\n}\n\n/** Permissions an end user grants per connected venue. */\nexport type ConnectScope = 'history:read' | 'trade:execute' | 'balance:read'\n\nexport interface ConnectConfigResult {\n /** null when the organization has never saved one — `config` is the defaults. */\n connect_config_id: string | null\n config: ConnectConfig\n /**\n * Present on update: how many EXISTING users the change was applied to.\n * A funding-mode change reaches users already provisioned, not just future\n * ones, so this reports what actually happened.\n */\n reconcile?: { scanned: number; reconciled: number; failed: number } | null\n}\n\nexport interface BuyResult {\n results: Array<{\n index: number\n status: BuyLegStatus\n /** NULL when the leg was rejected before routing — no decision was made. */\n sor_decision_id: string | null\n filled_notional: number\n filled_shares: number\n /** The un-buyable remainder of the requested stake. */\n unfilled_notional: number\n avg_price: number | null\n rejected_reason: string | null\n venues: Array<{\n partner_id: string\n success: boolean\n router_order_id: string | null\n error: string | null\n }>\n }>\n}\n\ninterface FlowEnvelope<T> {\n data?: T\n error?: { code: string; message: string; details?: Record<string, unknown> }\n}\n\nexport interface OpenMarketsClient {\n /** Generic typed request — escape hatch for endpoints without a helper. */\n request<T = unknown>(method: HttpMethod, path: string, opts?: RequestOptions): Promise<T>\n connect: {\n users: {\n provision(params: ProvisionUserParams): Promise<ProvisionResult>\n get<T = unknown>(externalUserId: string): Promise<T>\n getPolicy<T = unknown>(externalUserId: string): Promise<T>\n }\n linkSessions: {\n create(params: CreateLinkSessionParams): Promise<LinkSession>\n get<T = unknown>(linkSessionId: string): Promise<T>\n }\n /**\n * The organization's Connect config — which venues appear, whether real\n * money is allowed, and how the hosted flow is branded.\n *\n * Requires a PLAYER JWT with workspace admin, not an API key: this is\n * account governance rather than a data-API capability. `update` sends a\n * whole body (it is normalized server-side), so read, change, write.\n */\n configs: {\n get(workspaceId: string): Promise<ConnectConfigResult>\n update(workspaceId: string, config: Partial<ConnectConfig>): Promise<ConnectConfigResult>\n }\n webhooks: {\n getConfig<T = unknown>(): Promise<T>\n /** Verify a delivery using the configured `webhookSecret`. */\n verify(rawBody: string | Buffer, signatureHeader: string | null | undefined, opts?: VerifyWebhookOptions): boolean\n /** Verify + parse, or throw. Uses the configured `webhookSecret`. */\n constructEvent(rawBody: string | Buffer, signatureHeader: string | null | undefined, opts?: VerifyWebhookOptions): ConnectWebhookEvent\n }\n }\n account: {\n partners<T = unknown>(externalUserId: string): Promise<T>\n balances<T = unknown>(externalUserId: string): Promise<T>\n }\n orders: {\n list<T = unknown>(externalUserId: string): Promise<T>\n buy(orders: BuyOrder[], opts: { actAs: string }): Promise<BuyResult>\n }\n data: {\n leagues<T = unknown>(): Promise<T>\n contestLiquidity<T = unknown>(contestId: string): Promise<T>\n }\n}\n\nexport function createClient(options: OpenMarketsClientOptions): OpenMarketsClient {\n if (!options.apiKey) throw new Error('createClient: apiKey is required')\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '')\n const doFetch = options.fetch ?? globalThis.fetch\n if (!doFetch) throw new Error('No fetch available — pass options.fetch (Node < 18)')\n const timeoutMs = options.timeoutMs ?? 30_000\n\n async function request<T = unknown>(\n method: HttpMethod,\n path: string,\n opts: RequestOptions = {},\n ): Promise<T> {\n const url = new URL(baseUrl + path)\n for (const [k, v] of Object.entries(opts.query ?? {})) {\n if (v !== undefined) url.searchParams.set(k, String(v))\n }\n const headers: Record<string, string> = {\n 'X-API-Key': options.apiKey,\n Accept: 'application/json',\n }\n if (opts.body !== undefined) headers['Content-Type'] = 'application/json'\n if (opts.actAs) headers['X-OpenMarkets-Account'] = opts.actAs\n\n const ctrl = new AbortController()\n const timer = setTimeout(() => ctrl.abort(), timeoutMs)\n let res: Response\n try {\n res = await doFetch(url.toString(), {\n method,\n headers,\n body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,\n signal: ctrl.signal,\n })\n } finally {\n clearTimeout(timer)\n }\n\n let envelope: FlowEnvelope<T> | undefined\n const text = await res.text()\n if (text) {\n try {\n envelope = JSON.parse(text) as FlowEnvelope<T>\n } catch {\n /* non-JSON body */\n }\n }\n\n if (!res.ok) {\n const err = envelope?.error\n throw new OpenMarketsError(\n res.status,\n err?.code ?? 'http_error',\n err?.message ?? `Request failed with status ${res.status}`,\n err?.details,\n )\n }\n return (envelope?.data ?? (undefined as unknown)) as T\n }\n\n function requireSecret(): string {\n if (!options.webhookSecret) {\n throw new Error('webhookSecret was not provided to createClient()')\n }\n return options.webhookSecret\n }\n\n return {\n request,\n connect: {\n users: {\n provision: (params) =>\n request<ProvisionResult>('POST', '/flow/v1/connect/users', { body: params }),\n get: (externalUserId) =>\n request('GET', `/flow/v1/connect/users/${encodeURIComponent(externalUserId)}`),\n getPolicy: (externalUserId) =>\n request('GET', `/flow/v1/connect/users/${encodeURIComponent(externalUserId)}/policy`),\n },\n linkSessions: {\n create: (params) =>\n request<LinkSession>('POST', '/flow/v1/connect/link-sessions', { body: params }),\n get: (linkSessionId) =>\n request('GET', `/flow/v1/connect/link-sessions/${encodeURIComponent(linkSessionId)}`),\n },\n configs: {\n get: (workspaceId: string) =>\n request<ConnectConfigResult>(\n 'GET', `/flow/v1/workspaces/${encodeURIComponent(workspaceId)}/connect-config`,\n ),\n update: (workspaceId: string, config: Partial<ConnectConfig>) =>\n request<ConnectConfigResult>(\n 'PUT', `/flow/v1/workspaces/${encodeURIComponent(workspaceId)}/connect-config`,\n { body: { config } },\n ),\n },\n webhooks: {\n getConfig: () => request('GET', '/flow/v1/connect/webhook-config'),\n verify: (rawBody, sig, opts) =>\n verifyWebhookSignature(requireSecret(), rawBody, sig, opts),\n constructEvent: (rawBody, sig, opts) =>\n constructWebhookEvent(requireSecret(), rawBody, sig, opts),\n },\n },\n account: {\n partners: (externalUserId) =>\n request('GET', '/flow/v1/auth/account/partners', { actAs: externalUserId }),\n balances: (externalUserId) =>\n request('GET', '/flow/v1/auth/account/balances', { actAs: externalUserId }),\n },\n orders: {\n list: (externalUserId) =>\n request('GET', '/flow/v1/auth/orders', { actAs: externalUserId }),\n buy: (orders, opts) =>\n request<BuyResult>('POST', '/flow/v1/auth/orders/buy', {\n body: { orders },\n actAs: opts.actAs,\n }),\n },\n data: {\n leagues: () => request('GET', '/flow/v1/leagues'),\n contestLiquidity: (contestId) =>\n request('GET', `/flow/v1/contests/${encodeURIComponent(contestId)}/liquidity`),\n },\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openmarketsai/connect-node",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Server SDK for OpenMarkets Connect — provision users, mint link sessions, verify webhooks, and execute on a user's behalf.",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"type": "module",
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
},
|
|
19
19
|
"scripts": {
|
|
20
20
|
"build": "tsup",
|
|
21
|
+
"prepublishOnly": "npm run type-check && npm run build",
|
|
21
22
|
"dev": "tsup --watch",
|
|
22
23
|
"type-check": "tsc --noEmit"
|
|
23
24
|
},
|