@openmarketsai/connect-node 0.3.0 → 0.4.1
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/LICENSE +201 -0
- package/NOTICE +5 -0
- 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 +24 -6
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/NOTICE
ADDED
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(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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,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,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACnB;AACJ;AAGO,IAAM,qBAAA,GAAN,cAAoC,KAAA,CAAM;AAAA,EAC7C,YAAY,OAAA,EAAiB;AACzB,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,uBAAA;AAAA,EAChB;AACJ;AA2BA,SAAS,MAAM,IAAA,EAA+B;AAC1C,EAAA,OAAO,OAAO,IAAA,KAAS,QAAA,GAAW,IAAA,GAAO,IAAA,CAAK,SAAS,MAAM,CAAA;AACjE;AAEA,SAAS,qBAAqB,MAAA,EAAkD;AAC5E,EAAA,MAAM,KAAA,GAAQ,OAAO,KAAA,CAAM,GAAG,EAAE,MAAA,CAA+B,CAAC,KAAK,EAAA,KAAO;AACxE,IAAA,MAAM,GAAA,GAAM,EAAA,CAAG,OAAA,CAAQ,GAAG,CAAA;AAC1B,IAAA,IAAI,MAAM,CAAA,EAAG,GAAA,CAAI,EAAA,CAAG,KAAA,CAAM,GA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H,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\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) => verifyWebhook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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,EAAgB,IAAA,EAAc,OAAA,EAAiB,OAAA,EAAmC;AAC1F,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,kBAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACnB;AACJ;AAGO,IAAM,qBAAA,GAAN,cAAoC,KAAA,CAAM;AAAA,EAC7C,YAAY,OAAA,EAAiB;AACzB,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,uBAAA;AAAA,EAChB;AACJ;AA2BA,SAAS,MAAM,IAAA,EAA+B;AAC1C,EAAA,OAAO,OAAO,IAAA,KAAS,QAAA,GAAW,IAAA,GAAO,IAAA,CAAK,SAAS,MAAM,CAAA;AACjE;AAEA,SAAS,qBAAqB,MAAA,EAAkD;AAC5E,EAAA,MAAM,KAAA,GAAQ,OAAO,KAAA,CAAM,GAAG,EAAE,MAAA,CAA+B,CAAC,KAAK,EAAA,KAAO;AACxE,IAAA,MAAM,GAAA,GAAM,EAAA,CAAG,OAAA,CAAQ,GAAG,CAAA;AAC1B,IAAA,IAAI,MAAM,CAAA,EAAG,GAAA,CAAI,EAAA,CAAG,KAAA,CAAM,GAAG,GAAG,CAAA,CAAE,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A,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\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,11 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openmarketsai/connect-node",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Server SDK for OpenMarkets Connect
|
|
5
|
-
"license": "
|
|
3
|
+
"version": "0.4.1",
|
|
4
|
+
"description": "Server SDK for OpenMarkets Connect \u2014 provision users, mint link sessions, verify webhooks, and execute on a user's behalf.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"sideEffects": false,
|
|
8
|
-
"files": [
|
|
8
|
+
"files": [
|
|
9
|
+
"dist",
|
|
10
|
+
"README.md",
|
|
11
|
+
"LICENSE",
|
|
12
|
+
"NOTICE"
|
|
13
|
+
],
|
|
9
14
|
"main": "./dist/index.cjs",
|
|
10
15
|
"module": "./dist/index.js",
|
|
11
16
|
"types": "./dist/index.d.ts",
|
|
@@ -18,10 +23,17 @@
|
|
|
18
23
|
},
|
|
19
24
|
"scripts": {
|
|
20
25
|
"build": "tsup",
|
|
26
|
+
"prepublishOnly": "npm run type-check && npm run build",
|
|
21
27
|
"dev": "tsup --watch",
|
|
22
28
|
"type-check": "tsc --noEmit"
|
|
23
29
|
},
|
|
24
|
-
"keywords": [
|
|
30
|
+
"keywords": [
|
|
31
|
+
"openmarkets",
|
|
32
|
+
"connect",
|
|
33
|
+
"prediction-markets",
|
|
34
|
+
"sdk",
|
|
35
|
+
"server"
|
|
36
|
+
],
|
|
25
37
|
"engines": {
|
|
26
38
|
"node": ">=18"
|
|
27
39
|
},
|
|
@@ -32,5 +44,11 @@
|
|
|
32
44
|
},
|
|
33
45
|
"publishConfig": {
|
|
34
46
|
"access": "public"
|
|
35
|
-
}
|
|
47
|
+
},
|
|
48
|
+
"homepage": "https://app.openmarkets.ai/developers",
|
|
49
|
+
"bugs": {
|
|
50
|
+
"url": "https://app.openmarkets.ai/developers",
|
|
51
|
+
"email": "james@openmarkets.ai"
|
|
52
|
+
},
|
|
53
|
+
"author": "OpenMarkets"
|
|
36
54
|
}
|