@tokenite/sdk 1.0.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 Eran Broder
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Eran Broder
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,173 +1,173 @@
1
- # @tokenite/sdk
2
-
3
- One wallet for all your AI apps. Users store their Anthropic, OpenAI, and Google API keys in Tokenite, then grant your app metered access via OAuth. You pay nothing for AI usage.
4
-
5
- ## Install
6
-
7
- ```bash
8
- npm install @tokenite/sdk
9
- ```
10
-
11
- ## Quick Start
12
-
13
- ```typescript
14
- import { Tokenite, isProxyError } from '@tokenite/sdk';
15
-
16
- const tw = Tokenite({
17
- clientId: 'your-app-id',
18
- clientSecret: 'your-app-secret',
19
- redirectUri: 'https://yourapp.com/callback',
20
- });
21
-
22
- // 1. Redirect the user to the consent screen
23
- app.get('/login', (req, res) => res.redirect(tk.getAuthorizeUrl()));
24
-
25
- // 2. Exchange the OAuth code for an access token in your callback
26
- app.get('/callback', async (req, res) => {
27
- const { access_token } = await tk.exchangeCode(req.query.code as string);
28
- req.session.tokeniteToken = access_token;
29
- res.redirect('/');
30
- });
31
-
32
- // 3. Call the LLM through the proxy
33
- app.post('/chat', async (req, res) => {
34
- const result = await tk.call({
35
- accessToken: req.session.tokeniteToken,
36
- provider: 'anthropic',
37
- path: '/v1/messages',
38
- body: {
39
- model: 'claude-3-5-sonnet-latest',
40
- max_tokens: 1024,
41
- messages: [{ role: 'user', content: req.body.prompt }],
42
- },
43
- });
44
-
45
- if (isProxyError(result)) {
46
- return res.status(400).json({ error: result.error });
47
- }
48
-
49
- res.json({ model: result.model, usage: result.usage, data: result.data });
50
- });
51
- ```
52
-
53
- The same `tk.call(...)` works for OpenAI and Google — change `provider` and `path`:
54
-
55
- ```typescript
56
- await tk.call({
57
- accessToken,
58
- provider: 'openai',
59
- path: '/v1/chat/completions',
60
- body: { model: 'gpt-4o', messages: [...] },
61
- });
62
-
63
- await tk.call({
64
- accessToken,
65
- provider: 'google',
66
- path: '/v1beta/models/gemini-1.5-pro:generateContent',
67
- body: { contents: [...] },
68
- });
69
- ```
70
-
71
- ### Modal flow (single-page apps)
72
-
73
- If your app is a SPA, open the consent screen in an iframe modal:
74
-
75
- ```typescript
76
- const { code } = await tk.popup({ suggestedBudget: 5 });
77
-
78
- // Send the code to your backend, which calls tk.exchangeCode(code).
79
- // The exchange requires clientSecret and must never run in browser code.
80
- await fetch('/api/auth/exchange', {
81
- method: 'POST',
82
- body: JSON.stringify({ code }),
83
- });
84
- ```
85
-
86
- ### Managed agents (Anthropic)
87
-
88
- Tokenite proxies Anthropic's [Managed Agents](https://platform.claude.com/docs/en/managed-agents/overview) surface — the `/v1/agents`, `/v1/environments`, `/v1/sessions`, `/v1/vaults`, and `/v1/files` endpoints — under the same BYOK model as Messages. The app points the Anthropic SDK at `tk.proxyUrl('anthropic')`; the proxy injects the managed-agents beta header and forwards calls to the user's Anthropic org.
89
-
90
- **Explicit consent required.** Because agent sessions run long-lived, billable server-side work on Anthropic (`$0.08/hr` session runtime on top of tokens), the proxy rejects agent-surface calls unless the app was created with `allowsManagedAgents: true`. The flag sits alongside the other app fields on creation:
91
-
92
- ```typescript
93
- await admin.apps.create({
94
- name: 'Life Coach',
95
- callbackUrl: 'https://lifecoach.ai/callback',
96
- requiredProviders: ['anthropic'],
97
- allowsManagedAgents: true, // ← opt in
98
- });
99
- ```
100
-
101
- Without it, every agent endpoint returns `403 AGENT_SCOPE_MISSING`.
102
-
103
- ```typescript
104
- import Anthropic from '@anthropic-ai/sdk';
105
-
106
- const anthropic = new Anthropic({
107
- apiKey: accessToken,
108
- baseURL: tk.proxyUrl('anthropic'),
109
- });
110
-
111
- // Provision once per user.
112
- const agent = await anthropic.beta.agents.create({
113
- name: 'Life Coach',
114
- model: 'claude-haiku-4-5',
115
- system: 'You are a terse life coach.',
116
- tools: [{ type: 'agent_toolset_20260401' }],
117
- });
118
-
119
- // Spin up a session.
120
- const env = await anthropic.beta.environments.create({ name: 'prod' });
121
- const session = await anthropic.beta.sessions.create({
122
- agent: agent.id,
123
- environment_id: env.id,
124
- });
125
-
126
- // Send events, stream responses — all proxied.
127
- await anthropic.beta.sessions.events.post(session.id, {
128
- type: 'user.message', content: 'What should I focus on today?',
129
- });
130
-
131
- for await (const event of anthropic.beta.sessions.events.stream(session.id)) {
132
- // ...
133
- }
134
-
135
- // Archive when done. This is what triggers Tokenite to pull the final
136
- // usage totals from Anthropic and debit tokens + runtime against the budget.
137
- await anthropic.beta.sessions.archive(session.id);
138
- ```
139
-
140
- Tokenite tracks each session for attribution and auto-terminates running sessions when the user revokes the connection — otherwise Anthropic would keep billing `$0.08/hr` for the session runtime on top of tokens. The proxy bills the user's wallet at archive time using Anthropic's reported cumulative usage and runtime, plus the standard token rate from the model's pricing.
141
-
142
- Budget is checked pre-call but not enforced mid-session: a session that started under budget can run past it. Revoke is the user's hard kill switch.
143
-
144
- ### Streaming responses
145
-
146
- `tk.call()` is for non-streaming requests. Streaming responses bypass the unified envelope and are forwarded as-is, so use any vendor SDK with `baseURL: tk.proxyUrl(...)`:
147
-
148
- ```typescript
149
- import Anthropic from '@anthropic-ai/sdk';
150
-
151
- const anthropic = new Anthropic({
152
- apiKey: accessToken,
153
- baseURL: tk.proxyUrl('anthropic'),
154
- });
155
-
156
- const stream = await anthropic.messages.stream({
157
- model: 'claude-3-5-sonnet-latest',
158
- max_tokens: 1024,
159
- messages: [{ role: 'user', content: 'Tell me a story.' }],
160
- });
161
-
162
- for await (const event of stream) {
163
- if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
164
- process.stdout.write(event.delta.text);
165
- }
166
- }
167
- ```
168
-
169
- ## API
170
-
1
+ # @tokenite/sdk
2
+
3
+ One wallet for all your AI apps. Users store their Anthropic, OpenAI, and Google API keys in Tokenite, then grant your app metered access via OAuth. You pay nothing for AI usage.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @tokenite/sdk
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```typescript
14
+ import { Tokenite, isProxyError } from '@tokenite/sdk';
15
+
16
+ const tw = Tokenite({
17
+ clientId: 'your-app-id',
18
+ clientSecret: 'your-app-secret',
19
+ redirectUri: 'https://yourapp.com/callback',
20
+ });
21
+
22
+ // 1. Redirect the user to the consent screen
23
+ app.get('/login', (req, res) => res.redirect(tk.getAuthorizeUrl()));
24
+
25
+ // 2. Exchange the OAuth code for an access token in your callback
26
+ app.get('/callback', async (req, res) => {
27
+ const { access_token } = await tk.exchangeCode(req.query.code as string);
28
+ req.session.tokeniteToken = access_token;
29
+ res.redirect('/');
30
+ });
31
+
32
+ // 3. Call the LLM through the proxy
33
+ app.post('/chat', async (req, res) => {
34
+ const result = await tk.call({
35
+ accessToken: req.session.tokeniteToken,
36
+ provider: 'anthropic',
37
+ path: '/v1/messages',
38
+ body: {
39
+ model: 'claude-3-5-sonnet-latest',
40
+ max_tokens: 1024,
41
+ messages: [{ role: 'user', content: req.body.prompt }],
42
+ },
43
+ });
44
+
45
+ if (isProxyError(result)) {
46
+ return res.status(400).json({ error: result.error });
47
+ }
48
+
49
+ res.json({ model: result.model, usage: result.usage, data: result.data });
50
+ });
51
+ ```
52
+
53
+ The same `tk.call(...)` works for OpenAI and Google — change `provider` and `path`:
54
+
55
+ ```typescript
56
+ await tk.call({
57
+ accessToken,
58
+ provider: 'openai',
59
+ path: '/v1/chat/completions',
60
+ body: { model: 'gpt-4o', messages: [...] },
61
+ });
62
+
63
+ await tk.call({
64
+ accessToken,
65
+ provider: 'google',
66
+ path: '/v1beta/models/gemini-1.5-pro:generateContent',
67
+ body: { contents: [...] },
68
+ });
69
+ ```
70
+
71
+ ### Modal flow (single-page apps)
72
+
73
+ If your app is a SPA, open the consent screen in an iframe modal:
74
+
75
+ ```typescript
76
+ const { code } = await tk.popup({ suggestedBudget: 5 });
77
+
78
+ // Send the code to your backend, which calls tk.exchangeCode(code).
79
+ // The exchange requires clientSecret and must never run in browser code.
80
+ await fetch('/api/auth/exchange', {
81
+ method: 'POST',
82
+ body: JSON.stringify({ code }),
83
+ });
84
+ ```
85
+
86
+ ### Managed agents (Anthropic)
87
+
88
+ Tokenite proxies Anthropic's [Managed Agents](https://platform.claude.com/docs/en/managed-agents/overview) surface — the `/v1/agents`, `/v1/environments`, `/v1/sessions`, `/v1/vaults`, and `/v1/files` endpoints — under the same BYOK model as Messages. The app points the Anthropic SDK at `tk.proxyUrl('anthropic')`; the proxy injects the managed-agents beta header and forwards calls to the user's Anthropic org.
89
+
90
+ **Explicit consent required.** Because agent sessions run long-lived, billable server-side work on Anthropic (`$0.08/hr` session runtime on top of tokens), the proxy rejects agent-surface calls unless the app was created with `allowsManagedAgents: true`. The flag sits alongside the other app fields on creation:
91
+
92
+ ```typescript
93
+ await admin.apps.create({
94
+ name: 'Life Coach',
95
+ callbackUrl: 'https://lifecoach.ai/callback',
96
+ requiredProviders: ['anthropic'],
97
+ allowsManagedAgents: true, // ← opt in
98
+ });
99
+ ```
100
+
101
+ Without it, every agent endpoint returns `403 AGENT_SCOPE_MISSING`.
102
+
103
+ ```typescript
104
+ import Anthropic from '@anthropic-ai/sdk';
105
+
106
+ const anthropic = new Anthropic({
107
+ apiKey: accessToken,
108
+ baseURL: tk.proxyUrl('anthropic'),
109
+ });
110
+
111
+ // Provision once per user.
112
+ const agent = await anthropic.beta.agents.create({
113
+ name: 'Life Coach',
114
+ model: 'claude-haiku-4-5',
115
+ system: 'You are a terse life coach.',
116
+ tools: [{ type: 'agent_toolset_20260401' }],
117
+ });
118
+
119
+ // Spin up a session.
120
+ const env = await anthropic.beta.environments.create({ name: 'prod' });
121
+ const session = await anthropic.beta.sessions.create({
122
+ agent: agent.id,
123
+ environment_id: env.id,
124
+ });
125
+
126
+ // Send events, stream responses — all proxied.
127
+ await anthropic.beta.sessions.events.post(session.id, {
128
+ type: 'user.message', content: 'What should I focus on today?',
129
+ });
130
+
131
+ for await (const event of anthropic.beta.sessions.events.stream(session.id)) {
132
+ // ...
133
+ }
134
+
135
+ // Archive when done. This is what triggers Tokenite to pull the final
136
+ // usage totals from Anthropic and debit tokens + runtime against the budget.
137
+ await anthropic.beta.sessions.archive(session.id);
138
+ ```
139
+
140
+ Tokenite tracks each session for attribution and auto-terminates running sessions when the user revokes the connection — otherwise Anthropic would keep billing `$0.08/hr` for the session runtime on top of tokens. The proxy bills the user's wallet at archive time using Anthropic's reported cumulative usage and runtime, plus the standard token rate from the model's pricing.
141
+
142
+ Budget is checked pre-call but not enforced mid-session: a session that started under budget can run past it. Revoke is the user's hard kill switch.
143
+
144
+ ### Streaming responses
145
+
146
+ `tk.call()` is for non-streaming requests. Streaming responses bypass the unified envelope and are forwarded as-is, so use any vendor SDK with `baseURL: tk.proxyUrl(...)`:
147
+
148
+ ```typescript
149
+ import Anthropic from '@anthropic-ai/sdk';
150
+
151
+ const anthropic = new Anthropic({
152
+ apiKey: accessToken,
153
+ baseURL: tk.proxyUrl('anthropic'),
154
+ });
155
+
156
+ const stream = await anthropic.messages.stream({
157
+ model: 'claude-3-5-sonnet-latest',
158
+ max_tokens: 1024,
159
+ messages: [{ role: 'user', content: 'Tell me a story.' }],
160
+ });
161
+
162
+ for await (const event of stream) {
163
+ if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
164
+ process.stdout.write(event.delta.text);
165
+ }
166
+ }
167
+ ```
168
+
169
+ ## API
170
+
171
171
  <!-- GEN:API -->
172
172
  ### `.getAuthorizeUrl(options?: AuthorizeOptions) => string`
173
173
 
@@ -196,259 +196,280 @@ The Tokenite dashboard base URL
196
196
  ### `.proxyBase`: `string`
197
197
 
198
198
  The Tokenite proxy base URL
199
- <!-- /GEN:API -->
200
-
201
- ## Types
202
-
199
+ <!-- /GEN:API -->
200
+
201
+ ## Types
202
+
203
203
  <!-- GEN:TYPES -->
204
204
  ```typescript
205
- export type TokeniteConfig = {
206
- /** Your app's client ID (from the Tokenite dashboard) */
207
- readonly clientId: string;
208
- /** Your app's client secret — only needed for server-side code exchange */
209
- readonly clientSecret?: string;
210
- /** The URL Tokenite redirects back to after authorization */
211
- readonly redirectUri: string;
212
- /** Tokenite base URL. Default: https://tokenite.ai */
213
- readonly baseUrl?: string;
214
- /** Tokenite proxy URL. Default: https://api.tokenite.ai */
215
- readonly proxyUrl?: string;
216
- };
217
-
218
- export type AuthorizeOptions = {
219
- /** Custom state parameter for CSRF protection. Auto-generated if not provided. */
220
- readonly state?: string;
221
- /** Suggested budget amount (user can override on consent screen) */
222
- readonly suggestedBudget?: number;
223
- };
224
-
225
- export type PopupOptions = {
226
- /** Suggested budget amount (user can override on consent screen) */
227
- readonly suggestedBudget?: number;
228
- /**
229
- * How to host the consent screen.
230
- *
231
- * - `'iframe'` (default) — overlay an iframe modal in the current
232
- * window. Requires the dashboard to allow being framed by your
233
- * origin (`Content-Security-Policy: frame-ancestors`). Cleaner UX
234
- * but blocked by `X-Frame-Options: DENY`.
235
- * - `'window'` — open a separate browser popup window via
236
- * `window.open`. Works regardless of frame policy, but the user
237
- * may be prompted by their popup blocker.
238
- */
239
- readonly mode?: 'iframe' | 'window';
240
- /** Modal/popup width in pixels. Default: 480 */
241
- readonly width?: number;
242
- /** Modal/popup height in pixels. Default: 620 */
243
- readonly height?: number;
244
- };
245
-
246
- export type PopupResult = {
247
- /**
248
- * OAuth authorization code returned by the consent screen.
249
- * Send this to your backend, which exchanges it for an access token
250
- * via `tk.exchangeCode(code)`. The exchange requires `clientSecret`
251
- * and must never run in browser code.
252
- */
253
- readonly code: string;
254
- };
255
-
256
- export type TokenResponse = {
257
- readonly access_token: string;
258
- readonly token_type: string;
259
- };
260
-
261
- export type Provider = 'anthropic' | 'openai' | 'google' | 'grok' | 'bedrock';
262
-
263
- export type ProxyCallOptions = {
264
- /** The user's Tokenite access token (returned by `tk.exchangeCode()`) */
265
- readonly accessToken: string;
266
- /** Which LLM provider to call */
267
- readonly provider: Provider;
268
- /** Path on the provider's API (e.g. `/v1/messages`, `/v1/chat/completions`) */
269
- readonly path: string;
270
- /** HTTP method. Default: `POST` */
271
- readonly method?: string;
272
- /** Request body — the vendor's request shape, JSON-serialised by the SDK */
273
- readonly body: unknown;
274
- };
275
-
276
- // ─── Unified proxy response types ───
277
- //
278
- // Every non-streaming response from the Tokenite proxy returns one of
279
- // these shapes. SDK consumers can always check for `.error` to distinguish
280
- // success from failure — no vendor-specific parsing required.
281
-
282
- /** Normalised token counts (identical across all providers) */
283
- export type ProxyUsage = {
284
- /** Number of tokens in the prompt / input */
285
- readonly inputTokens: number;
286
- /** Number of tokens in the completion / output */
287
- readonly outputTokens: number;
288
- };
289
-
290
- /**
291
- * Successful proxy response.
292
- *
293
- * `data` contains the original vendor response body (e.g. Anthropic's
294
- * message object, OpenAI's chat completion, etc.). `provider`, `model`,
295
- * and `usage` are extracted and normalised by the proxy so you don't
296
- * need to parse vendor-specific fields.
297
- */
298
- export type ProxySuccess = {
299
- /** Which LLM provider handled the request */
300
- readonly provider: Provider;
301
- /** The model that generated the response */
302
- readonly model: string;
303
- /** Normalised token usage, or null if the provider didn't report it */
304
- readonly usage: ProxyUsage | null;
305
- /** The original, unmodified response body from the LLM provider */
306
- readonly data: unknown;
307
- };
308
-
309
- /**
310
- * Where the error originated.
311
- *
312
- * - `"proxy"` — Tokenite rejected the request (auth, budget, config).
313
- * - `"provider"` — The upstream LLM returned an error (rate limit, overload, etc.).
314
- */
315
- export type ErrorSource = 'proxy' | 'provider';
316
-
317
- /**
318
- * Error response (both proxy-level and provider-level errors share this shape).
319
- *
320
- * **Proxy error codes** (`source: "proxy"`):
321
- * | Code | HTTP | Description |
322
- * |---|---|---|
323
- * | `TOKEN_INVALID` | 401 | Missing or invalid bearer token |
324
- * | `TOKEN_REVOKED` | 401 | Access token was revoked by the user |
325
- * | `TOKEN_SUSPENDED` | 403 | Access suspended by the user |
326
- * | `TOKEN_EXPIRED` | 401 | Access token past its expiration date |
327
- * | `BUDGET_EXCEEDED` | 402 | Spending reached the user-defined budget limit |
328
- * | `PROVIDER_KEY_MISSING` | 402 | No API key or credits available for the provider |
329
- * | `CREDITS_DEPLETED` | 402 | Insufficient platform credits |
330
- * | `APP_NOT_FOUND` | 404 | Application not found |
331
- * | `MODEL_NOT_ALLOWED` | 403 | Model not in the app's allowed models list |
332
- *
333
- * **Provider error codes** (`source: "provider"`):
334
- * | Code | HTTP | Description |
335
- * |---|---|---|
336
- * | `RATE_LIMITED` | 429 | Upstream rate limit hit — retry after backoff |
337
- * | `CONTEXT_LENGTH_EXCEEDED` | 400 | Request exceeds model's context window |
338
- * | `INVALID_REQUEST` | 400 | Provider rejected the request as malformed |
339
- * | `AUTHENTICATION_FAILED` | 401 | Provider rejected the API key |
340
- * | `PROVIDER_OVERLOADED` | 503 | Provider temporarily overloaded |
341
- * | `CONTENT_FILTERED` | 400 | Content blocked by safety filter |
342
- * | `PROVIDER_TIMEOUT` | 504 | Provider did not respond in time |
343
- * | `PROVIDER_ERROR` | 502 | Catch-all for other provider errors |
344
- */
345
- export type ProxyError = {
346
- readonly error: {
347
- /** Machine-readable error code */
348
- readonly code: string;
349
- /** Human-readable description */
350
- readonly message: string;
351
- /** Where the error originated */
352
- readonly source: ErrorSource;
353
- /** Optional structured context (e.g. `retryAfter`, `provider`, `providerMessage`) */
354
- readonly details?: Record<string, unknown>;
355
- };
356
- };
357
-
358
- /** Discriminated union for all non-streaming proxy responses */
359
- export type ProxyResponse = ProxySuccess | ProxyError;
360
-
361
- /** Type guard: returns true if the response is an error */
362
- export const isProxyError = (response: ProxyResponse): response is ProxyError =>
363
- 'error' in response;
364
-
365
- /** Type guard: returns true if the response is a success */
366
- export const isProxySuccess = (response: ProxyResponse): response is ProxySuccess =>
367
- 'provider' in response;
368
-
369
- // ─── Access context (tk.getAllowedProviders) ───
370
-
371
- /** Visual + identity metadata for a single provider */
372
- export type ProviderInfo = {
373
- /** Stable provider id (same value as the `Provider` union) */
374
- readonly id: Provider;
375
- /** Human-readable name, e.g. "Anthropic" */
376
- readonly displayName: string;
377
- /** Brand colour (hex string, e.g. "#d97706") */
378
- readonly color: string;
379
- /** Absolute URL to the provider's logo (PNG or SVG) */
380
- readonly logoUrl: string;
381
- /** Whether the logo is a glyph/symbol or a full wordmark */
382
- readonly logoStyle: 'symbol' | 'wordmark';
383
- };
384
-
385
- /** Summary of the app the access token belongs to */
386
- export type AppInfo = {
387
- readonly id: string;
388
- readonly name: string;
389
- readonly description: string | null;
390
- readonly websiteUrl: string | null;
391
- /** Absolute URL to the app's icon (PNG/SVG). null when the developer hasn't set one — render initials or a generic glyph. */
392
- readonly iconUrl: string | null;
393
- /** Providers the app declares it needs */
394
- readonly requiredProviders: readonly Provider[];
395
- /** Fallback order when `allowSubstitution` is true */
396
- readonly preferredProviders: readonly Provider[];
397
- /** Whether the app accepts substitute providers when a required one isn't available */
398
- readonly allowSubstitution: boolean;
399
- };
400
-
401
- /**
402
- * Full access context for a single access token.
403
- *
404
- * `providers` lists only the providers the user has an active key for —
405
- * exactly the set that will succeed through `tk.call()` (budget permitting).
406
- */
407
- export type AllowedProvidersResponse = {
408
- readonly app: AppInfo;
409
- readonly providers: readonly ProviderInfo[];
205
+ export type TokeniteConfig = {
206
+ /** Your app's client ID (from the Tokenite dashboard) */
207
+ readonly clientId: string;
208
+ /** Your app's client secret — only needed for server-side code exchange */
209
+ readonly clientSecret?: string;
210
+ /** The URL Tokenite redirects back to after authorization */
211
+ readonly redirectUri: string;
212
+ /** Tokenite base URL. Default: https://tokenite.ai */
213
+ readonly baseUrl?: string;
214
+ /** Tokenite proxy URL. Default: https://api.tokenite.ai */
215
+ readonly proxyUrl?: string;
216
+ };
217
+
218
+ export type AuthorizeOptions = {
219
+ /** Custom state parameter for CSRF protection. Auto-generated if not provided. */
220
+ readonly state?: string;
221
+ /** Suggested budget amount (user can override on consent screen) */
222
+ readonly suggestedBudget?: number;
223
+ };
224
+
225
+ export type PopupOptions = {
226
+ /** Suggested budget amount (user can override on consent screen) */
227
+ readonly suggestedBudget?: number;
228
+ /**
229
+ * How to host the consent screen.
230
+ *
231
+ * - `'iframe'` (default) — overlay an iframe modal in the current
232
+ * window. Requires the dashboard to allow being framed by your
233
+ * origin (`Content-Security-Policy: frame-ancestors`). Cleaner UX
234
+ * but blocked by `X-Frame-Options: DENY`.
235
+ * - `'window'` — open a separate browser popup window via
236
+ * `window.open`. Works regardless of frame policy, but the user
237
+ * may be prompted by their popup blocker.
238
+ */
239
+ readonly mode?: 'iframe' | 'window';
240
+ /** Modal/popup width in pixels. Default: 480 */
241
+ readonly width?: number;
242
+ /** Modal/popup height in pixels. Default: 620 */
243
+ readonly height?: number;
244
+ };
245
+
246
+ export type PopupResult = {
247
+ /**
248
+ * OAuth authorization code returned by the consent screen.
249
+ * Send this to your backend, which exchanges it for an access token
250
+ * via `tk.exchangeCode(code)`. The exchange requires `clientSecret`
251
+ * and must never run in browser code.
252
+ */
253
+ readonly code: string;
254
+ };
255
+
256
+ export type TokenResponse = {
257
+ readonly access_token: string;
258
+ readonly token_type: string;
259
+ };
260
+
261
+ export type Provider = 'anthropic' | 'openai' | 'google' | 'grok' | 'bedrock';
262
+
263
+ export type ProxyCallOptions = {
264
+ /** The user's Tokenite access token (returned by `tk.exchangeCode()`) */
265
+ readonly accessToken: string;
266
+ /** Which LLM provider to call */
267
+ readonly provider: Provider;
268
+ /** Path on the provider's API (e.g. `/v1/messages`, `/v1/chat/completions`) */
269
+ readonly path: string;
270
+ /** HTTP method. Default: `POST` */
271
+ readonly method?: string;
272
+ /** Request body — the vendor's request shape, JSON-serialised by the SDK */
273
+ readonly body: unknown;
274
+ };
275
+
276
+ // ─── Unified proxy response types ───
277
+ //
278
+ // Every non-streaming response from the Tokenite proxy returns one of
279
+ // these shapes. SDK consumers can always check for `.error` to distinguish
280
+ // success from failure — no vendor-specific parsing required.
281
+
282
+ /** Normalised token counts (identical across all providers) */
283
+ export type ProxyUsage = {
284
+ /** Number of tokens in the prompt / input */
285
+ readonly inputTokens: number;
286
+ /** Number of tokens in the completion / output */
287
+ readonly outputTokens: number;
288
+ };
289
+
290
+ /**
291
+ * Successful proxy response.
292
+ *
293
+ * `data` contains the original vendor response body (e.g. Anthropic's
294
+ * message object, OpenAI's chat completion, etc.). `provider`, `model`,
295
+ * and `usage` are extracted and normalised by the proxy so you don't
296
+ * need to parse vendor-specific fields.
297
+ */
298
+ export type ProxySuccess = {
299
+ /** Which LLM provider handled the request */
300
+ readonly provider: Provider;
301
+ /** The model that generated the response */
302
+ readonly model: string;
303
+ /** Normalised token usage, or null if the provider didn't report it */
304
+ readonly usage: ProxyUsage | null;
305
+ /** The original, unmodified response body from the LLM provider */
306
+ readonly data: unknown;
307
+ };
308
+
309
+ /**
310
+ * Where the error originated.
311
+ *
312
+ * - `"proxy"` — Tokenite rejected the request (auth, budget, config).
313
+ * - `"provider"` — The upstream LLM returned an error (rate limit, overload, etc.).
314
+ */
315
+ export type ErrorSource = 'proxy' | 'provider';
316
+
317
+ /**
318
+ * Error response (both proxy-level and provider-level errors share this shape).
319
+ *
320
+ * **Proxy error codes** (`source: "proxy"`):
321
+ * | Code | HTTP | Description |
322
+ * |---|---|---|
323
+ * | `TOKEN_INVALID` | 401 | Missing or invalid bearer token |
324
+ * | `TOKEN_REVOKED` | 401 | Access token was revoked by the user |
325
+ * | `TOKEN_SUSPENDED` | 403 | Access suspended by the user |
326
+ * | `TOKEN_EXPIRED` | 401 | Access token past its expiration date |
327
+ * | `BUDGET_EXCEEDED` | 402 | Spending reached the user-defined budget limit |
328
+ * | `PROVIDER_KEY_MISSING` | 402 | No API key or credits available for the provider |
329
+ * | `CREDITS_DEPLETED` | 402 | Insufficient platform credits |
330
+ * | `APP_NOT_FOUND` | 404 | Application not found |
331
+ * | `MODEL_NOT_ALLOWED` | 403 | Model not in the app's allowed models list |
332
+ *
333
+ * **Provider error codes** (`source: "provider"`):
334
+ * | Code | HTTP | Description |
335
+ * |---|---|---|
336
+ * | `RATE_LIMITED` | 429 | Upstream rate limit hit — retry after backoff |
337
+ * | `CONTEXT_LENGTH_EXCEEDED` | 400 | Request exceeds model's context window |
338
+ * | `INVALID_REQUEST` | 400 | Provider rejected the request as malformed |
339
+ * | `AUTHENTICATION_FAILED` | 401 | Provider rejected the API key |
340
+ * | `PROVIDER_OVERLOADED` | 503 | Provider temporarily overloaded |
341
+ * | `CONTENT_FILTERED` | 400 | Content blocked by safety filter |
342
+ * | `PROVIDER_TIMEOUT` | 504 | Provider did not respond in time |
343
+ * | `PROVIDER_ERROR` | 502 | Catch-all for other provider errors |
344
+ */
345
+ export type ProxyError = {
346
+ readonly error: {
347
+ /** Machine-readable error code */
348
+ readonly code: string;
349
+ /** Human-readable description */
350
+ readonly message: string;
351
+ /** Where the error originated */
352
+ readonly source: ErrorSource;
353
+ /** Optional structured context (e.g. `retryAfter`, `provider`, `providerMessage`) */
354
+ readonly details?: Record<string, unknown>;
355
+ };
356
+ };
357
+
358
+ /** Discriminated union for all non-streaming proxy responses */
359
+ export type ProxyResponse = ProxySuccess | ProxyError;
360
+
361
+ /** Type guard: returns true if the response is an error */
362
+ export const isProxyError = (response: ProxyResponse): response is ProxyError =>
363
+ 'error' in response;
364
+
365
+ /** Type guard: returns true if the response is a success */
366
+ export const isProxySuccess = (response: ProxyResponse): response is ProxySuccess =>
367
+ 'provider' in response;
368
+
369
+ // ─── Access context (tk.getAccessContext) ───
370
+
371
+ /**
372
+ * Identity of the user who holds this access token.
373
+ *
374
+ * Use `id` as the stable key for per-user state in your app — it survives
375
+ * token refreshes, re-logins, and device switches. `email` is suitable for
376
+ * display in your UI; treat it as user-controlled and re-fetch on each
377
+ * session if you cache it.
378
+ */
379
+ export type UserInfo = {
380
+ /** Stable Tokenite user id (UUID) */
381
+ readonly id: string;
382
+ /** The user's email address as registered with Tokenite */
383
+ readonly email: string;
384
+ };
385
+
386
+ /** Visual + identity metadata for a single provider */
387
+ export type ProviderInfo = {
388
+ /** Stable provider id (same value as the `Provider` union) */
389
+ readonly id: Provider;
390
+ /** Human-readable name, e.g. "Anthropic" */
391
+ readonly displayName: string;
392
+ /** Brand colour (hex string, e.g. "#d97706") */
393
+ readonly color: string;
394
+ /** Absolute URL to the provider's logo (PNG or SVG) */
395
+ readonly logoUrl: string;
396
+ /** Whether the logo is a glyph/symbol or a full wordmark */
397
+ readonly logoStyle: 'symbol' | 'wordmark';
398
+ };
399
+
400
+ /** Summary of the app the access token belongs to */
401
+ export type AppInfo = {
402
+ readonly id: string;
403
+ readonly name: string;
404
+ readonly description: string | null;
405
+ readonly websiteUrl: string | null;
406
+ /** Absolute URL to the app's icon (PNG/SVG). null when the developer hasn't set one — render initials or a generic glyph. */
407
+ readonly iconUrl: string | null;
408
+ /** Providers the app declares it needs */
409
+ readonly requiredProviders: readonly Provider[];
410
+ /** Fallback order when `allowSubstitution` is true */
411
+ readonly preferredProviders: readonly Provider[];
412
+ /** Whether the app accepts substitute providers when a required one isn't available */
413
+ readonly allowSubstitution: boolean;
414
+ };
415
+
416
+ /**
417
+ * Full access context for a single access token: the app it belongs to,
418
+ * the user who holds it, and the providers it can call.
419
+ *
420
+ * `providers` lists only the providers the user has an active key for —
421
+ * exactly the set that will succeed through `tk.call()` (budget permitting).
422
+ *
423
+ * `user` identifies the human who holds the token. Use `user.id` as the
424
+ * stable key for any per-user state in your app — it survives token
425
+ * refreshes and re-logins, unlike the access token itself.
426
+ */
427
+ export type AccessContext = {
428
+ readonly app: AppInfo;
429
+ readonly user: UserInfo;
430
+ readonly providers: readonly ProviderInfo[];
410
431
  };
411
432
  ```
412
- <!-- /GEN:TYPES -->
413
-
414
- ## Error Codes
415
-
416
- Non-streaming proxy responses return a unified error envelope:
417
-
418
- ```json
419
- { "error": { "code": "...", "message": "...", "source": "proxy" | "provider", "details": { } } }
420
- ```
421
-
422
- `source` distinguishes errors raised by the Tokenite proxy from errors forwarded from the upstream LLM. Use the `isProxyError` type guard to narrow a `ProxyResponse` before reading `error.code`.
423
-
424
- ### Proxy errors (`source: "proxy"`)
425
-
426
- | Code | Status | Meaning |
427
- |------|--------|---------|
428
- | `TOKEN_INVALID` | 401 | Missing or unrecognized access token |
429
- | `TOKEN_REVOKED` | 401 | User revoked access |
430
- | `TOKEN_EXPIRED` | 401 | Token expired (30-day lifetime) |
431
- | `TOKEN_SUSPENDED` | 403 | User temporarily suspended access |
432
- | `BUDGET_EXCEEDED` | 402 | Spending limit reached |
433
- | `PROVIDER_KEY_MISSING` | 402 | No API key or credits available for the provider |
434
- | `CREDITS_DEPLETED` | 402 | Insufficient platform credits |
435
- | `MODEL_NOT_ALLOWED` | 403 | Model not in your app's allowed list |
436
- | `AGENT_SCOPE_MISSING` | 403 | App doesn't have the managed-agents scope (set `allowsManagedAgents: true` at app creation) |
437
- | `APP_NOT_FOUND` | 404 | Application not found |
438
-
439
- ### Provider errors (`source: "provider"`)
440
-
441
- | Code | Status | Meaning |
442
- |------|--------|---------|
443
- | `RATE_LIMITED` | 429 | Upstream rate limit hit — retry after backoff |
444
- | `CONTEXT_LENGTH_EXCEEDED` | 400 | Request exceeds the model's context window |
445
- | `INVALID_REQUEST` | 400 | Provider rejected the request as malformed |
446
- | `CONTENT_FILTERED` | 400 | Content blocked by the provider's safety filter |
447
- | `AUTHENTICATION_FAILED` | 401 | Provider rejected the API key |
448
- | `PROVIDER_OVERLOADED` | 503 | Provider temporarily overloaded |
449
- | `PROVIDER_TIMEOUT` | 504 | Provider did not respond in time |
450
- | `PROVIDER_ERROR` | 502 | Catch-all for other provider errors |
451
-
452
- ## License
453
-
454
- MIT
433
+ <!-- /GEN:TYPES -->
434
+
435
+ ## Error Codes
436
+
437
+ Non-streaming proxy responses return a unified error envelope:
438
+
439
+ ```json
440
+ { "error": { "code": "...", "message": "...", "source": "proxy" | "provider", "details": { } } }
441
+ ```
442
+
443
+ `source` distinguishes errors raised by the Tokenite proxy from errors forwarded from the upstream LLM. Use the `isProxyError` type guard to narrow a `ProxyResponse` before reading `error.code`.
444
+
445
+ ### Proxy errors (`source: "proxy"`)
446
+
447
+ | Code | Status | Meaning |
448
+ |------|--------|---------|
449
+ | `TOKEN_INVALID` | 401 | Missing or unrecognized access token |
450
+ | `TOKEN_REVOKED` | 401 | User revoked access |
451
+ | `TOKEN_EXPIRED` | 401 | Token expired (30-day lifetime) |
452
+ | `TOKEN_SUSPENDED` | 403 | User temporarily suspended access |
453
+ | `BUDGET_EXCEEDED` | 402 | Spending limit reached |
454
+ | `PROVIDER_KEY_MISSING` | 402 | No API key or credits available for the provider |
455
+ | `CREDITS_DEPLETED` | 402 | Insufficient platform credits |
456
+ | `MODEL_NOT_ALLOWED` | 403 | Model not in your app's allowed list |
457
+ | `AGENT_SCOPE_MISSING` | 403 | App doesn't have the managed-agents scope (set `allowsManagedAgents: true` at app creation) |
458
+ | `APP_NOT_FOUND` | 404 | Application not found |
459
+
460
+ ### Provider errors (`source: "provider"`)
461
+
462
+ | Code | Status | Meaning |
463
+ |------|--------|---------|
464
+ | `RATE_LIMITED` | 429 | Upstream rate limit hit — retry after backoff |
465
+ | `CONTEXT_LENGTH_EXCEEDED` | 400 | Request exceeds the model's context window |
466
+ | `INVALID_REQUEST` | 400 | Provider rejected the request as malformed |
467
+ | `CONTENT_FILTERED` | 400 | Content blocked by the provider's safety filter |
468
+ | `AUTHENTICATION_FAILED` | 401 | Provider rejected the API key |
469
+ | `PROVIDER_OVERLOADED` | 503 | Provider temporarily overloaded |
470
+ | `PROVIDER_TIMEOUT` | 504 | Provider did not respond in time |
471
+ | `PROVIDER_ERROR` | 502 | Catch-all for other provider errors |
472
+
473
+ ## License
474
+
475
+ MIT
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { TokeniteConfig, AuthorizeOptions, PopupOptions, PopupResult, TokenResponse, Provider, ProxyCallOptions, ProxyResponse, AllowedProvidersResponse } from './types.js';
1
+ import type { TokeniteConfig, AuthorizeOptions, PopupOptions, PopupResult, TokenResponse, Provider, ProxyCallOptions, ProxyResponse, AccessContext } from './types.js';
2
2
  /**
3
3
  * Tokenite client.
4
4
  *
@@ -91,21 +91,26 @@ export declare const Tokenite: (config: TokeniteConfig) => {
91
91
  */
92
92
  call: (options: ProxyCallOptions) => Promise<ProxyResponse>;
93
93
  /**
94
- * Fetch the access context for an access token: which app it belongs
95
- * to and which providers the user has authorised it to call.
94
+ * Fetch the full access context for an access token: which app it
95
+ * belongs to, who holds the token, and which providers it can call.
96
96
  *
97
97
  * The returned `providers` list is exactly the set that will succeed
98
98
  * through `tk.call()` (budget permitting). Use it to render a picker,
99
99
  * gate UI, or detect that the user is missing a required provider.
100
100
  *
101
+ * The returned `user` identifies the token holder. Use `user.id` as
102
+ * the stable key for any per-user state in your app — it survives
103
+ * token refreshes and re-logins, unlike the access token itself.
104
+ *
101
105
  * ```typescript
102
- * const { app, providers } = await tk.getAllowedProviders(accessToken);
106
+ * const { app, user, providers } = await tk.getAccessContext(accessToken);
107
+ * console.log(`Signed in as ${user.email}`);
103
108
  * for (const p of providers) {
104
109
  * console.log(p.displayName, p.logoUrl);
105
110
  * }
106
111
  * ```
107
112
  */
108
- getAllowedProviders: (accessToken: string) => Promise<AllowedProvidersResponse>;
113
+ getAccessContext: (accessToken: string) => Promise<AccessContext>;
109
114
  /**
110
115
  * Get the proxy URL for a specific provider.
111
116
  * Use as `baseURL` in a vendor SDK for streaming requests, which
package/dist/client.js CHANGED
@@ -156,27 +156,32 @@ export const Tokenite = (config) => {
156
156
  return (await response.json());
157
157
  },
158
158
  /**
159
- * Fetch the access context for an access token: which app it belongs
160
- * to and which providers the user has authorised it to call.
159
+ * Fetch the full access context for an access token: which app it
160
+ * belongs to, who holds the token, and which providers it can call.
161
161
  *
162
162
  * The returned `providers` list is exactly the set that will succeed
163
163
  * through `tk.call()` (budget permitting). Use it to render a picker,
164
164
  * gate UI, or detect that the user is missing a required provider.
165
165
  *
166
+ * The returned `user` identifies the token holder. Use `user.id` as
167
+ * the stable key for any per-user state in your app — it survives
168
+ * token refreshes and re-logins, unlike the access token itself.
169
+ *
166
170
  * ```typescript
167
- * const { app, providers } = await tk.getAllowedProviders(accessToken);
171
+ * const { app, user, providers } = await tk.getAccessContext(accessToken);
172
+ * console.log(`Signed in as ${user.email}`);
168
173
  * for (const p of providers) {
169
174
  * console.log(p.displayName, p.logoUrl);
170
175
  * }
171
176
  * ```
172
177
  */
173
- getAllowedProviders: async (accessToken) => {
174
- const response = await fetch(`${proxyBase}/me/providers`, {
178
+ getAccessContext: async (accessToken) => {
179
+ const response = await fetch(`${proxyBase}/me`, {
175
180
  headers: { 'authorization': `Bearer ${accessToken}` },
176
181
  });
177
182
  if (!response.ok) {
178
183
  const body = await response.json().catch(() => null);
179
- throw new Error(extractErrorMessage(body, `Failed to fetch allowed providers (${response.status})`));
184
+ throw new Error(extractErrorMessage(body, `Failed to fetch access context (${response.status})`));
180
185
  }
181
186
  const data = (await response.json());
182
187
  return {
@@ -203,25 +208,33 @@ const generateState = () => Array.from(crypto.getRandomValues(new Uint8Array(16)
203
208
  .map((b) => b.toString(16).padStart(2, '0'))
204
209
  .join('');
205
210
  const absoluteUrl = (maybeRelative, base) => /^https?:\/\//i.test(maybeRelative) ? maybeRelative : `${base}${maybeRelative}`;
206
- // ─── Popup hosts ───
207
- //
208
- // Two transports for the consent screen, sharing the same postMessage
209
- // protocol with the dashboard:
210
- // { type: 'tokenite:auth-success', code }
211
- // { type: 'tokenite:auth-error', error }
211
+ const handleAuthMessage = (event, baseUrl, resolve, reject, cleanup) => {
212
+ if (event.origin !== baseUrl)
213
+ return;
214
+ const data = event.data;
215
+ if (data.type === 'tokenite:auth-success' && data.code) {
216
+ cleanup();
217
+ resolve({ code: data.code });
218
+ return;
219
+ }
220
+ if (data.type === 'tokenite:auth-error') {
221
+ cleanup();
222
+ reject(new Error(data.error ?? 'Authorization denied'));
223
+ }
224
+ };
212
225
  const openIframeModal = (url, width, height, baseUrl) => {
213
226
  const overlay = document.createElement('div');
214
- overlay.style.cssText = `
215
- position: fixed; inset: 0; z-index: 999999;
216
- background: rgba(0,0,0,0.5); backdrop-filter: blur(2px);
217
- display: flex; align-items: center; justify-content: center;
227
+ overlay.style.cssText = `
228
+ position: fixed; inset: 0; z-index: 999999;
229
+ background: rgba(0,0,0,0.5); backdrop-filter: blur(2px);
230
+ display: flex; align-items: center; justify-content: center;
218
231
  `;
219
232
  const container = document.createElement('div');
220
- container.style.cssText = `
221
- background: white; border-radius: 12px; overflow: hidden;
222
- box-shadow: 0 20px 60px rgba(0,0,0,0.3);
223
- width: ${width}px; max-width: calc(100vw - 32px);
224
- height: ${height}px; max-height: calc(100vh - 32px);
233
+ container.style.cssText = `
234
+ background: white; border-radius: 12px; overflow: hidden;
235
+ box-shadow: 0 20px 60px rgba(0,0,0,0.3);
236
+ width: ${width}px; max-width: calc(100vw - 32px);
237
+ height: ${height}px; max-height: calc(100vh - 32px);
225
238
  `;
226
239
  const iframe = document.createElement('iframe');
227
240
  iframe.src = url;
@@ -231,23 +244,11 @@ const openIframeModal = (url, width, height, baseUrl) => {
231
244
  overlay.appendChild(container);
232
245
  document.body.appendChild(overlay);
233
246
  return new Promise((resolve, reject) => {
234
- const onMessage = (event) => {
235
- if (event.origin !== baseUrl)
236
- return;
237
- const data = event.data;
238
- if (data.type === 'tokenite:auth-success' && data.code) {
239
- cleanup();
240
- resolve({ code: data.code });
241
- }
242
- if (data.type === 'tokenite:auth-error') {
243
- cleanup();
244
- reject(new Error(data.error ?? 'Authorization denied'));
245
- }
246
- };
247
247
  const cleanup = () => {
248
248
  window.removeEventListener('message', onMessage);
249
249
  overlay.remove();
250
250
  };
251
+ const onMessage = (event) => handleAuthMessage(event, baseUrl, resolve, reject, cleanup);
251
252
  overlay.addEventListener('click', (e) => {
252
253
  if (e.target === overlay) {
253
254
  cleanup();
@@ -264,23 +265,13 @@ const openWindowPopup = (url, width, height, baseUrl, redirectUri) => {
264
265
  if (!popup)
265
266
  return Promise.reject(new Error('Popup blocked'));
266
267
  return new Promise((resolve, reject) => {
267
- const onMessage = (event) => {
268
- if (event.origin !== baseUrl)
269
- return;
270
- const data = event.data;
271
- if (data.type === 'tokenite:auth-success' && data.code) {
272
- cleanup();
273
- resolve({ code: data.code });
274
- }
275
- if (data.type === 'tokenite:auth-error') {
276
- cleanup();
277
- reject(new Error(data.error ?? 'Authorization denied'));
278
- }
268
+ const cleanup = () => {
269
+ window.removeEventListener('message', onMessage);
270
+ clearInterval(poll);
271
+ if (!popup.closed)
272
+ popup.close();
279
273
  };
280
- // Cross-origin popups can't postMessage until they navigate back to
281
- // our origin (the redirect URI). As a fallback, poll for that
282
- // navigation by trying to read the popup's URL — same-origin reads
283
- // succeed, cross-origin throws and we keep polling.
274
+ const onMessage = (event) => handleAuthMessage(event, baseUrl, resolve, reject, cleanup);
284
275
  const poll = setInterval(() => {
285
276
  if (popup.closed) {
286
277
  cleanup();
@@ -297,16 +288,8 @@ const openWindowPopup = (url, width, height, baseUrl, redirectUri) => {
297
288
  }
298
289
  }
299
290
  }
300
- catch {
301
- // cross-origin — keep polling
302
- }
291
+ catch { /* cross-origin until navigation back to redirectUri */ }
303
292
  }, 300);
304
- const cleanup = () => {
305
- window.removeEventListener('message', onMessage);
306
- clearInterval(poll);
307
- if (!popup.closed)
308
- popup.close();
309
- };
310
293
  window.addEventListener('message', onMessage);
311
294
  });
312
295
  };
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=client.test.d.ts.map
@@ -0,0 +1,66 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { TokenWallet } from './client.js';
3
+ const tw = TokenWallet({
4
+ clientId: 'test-app-id',
5
+ clientSecret: 'test-secret',
6
+ redirectUri: 'https://myapp.com/callback',
7
+ baseUrl: 'https://tokenwallet.ai',
8
+ proxyUrl: 'https://api.tokenwallet.ai',
9
+ });
10
+ describe('TokenWallet', () => {
11
+ describe('getAuthorizeUrl', () => {
12
+ it('builds correct OAuth URL', () => {
13
+ const url = tw.getAuthorizeUrl({ state: 'abc123' });
14
+ expect(url).toBe('https://tokenwallet.ai/oauth/authorize?client_id=test-app-id&redirect_uri=https%3A%2F%2Fmyapp.com%2Fcallback&response_type=code&state=abc123');
15
+ });
16
+ it('auto-generates state if not provided', () => {
17
+ const url = tw.getAuthorizeUrl();
18
+ expect(url).toContain('state=');
19
+ expect(url).toContain('client_id=test-app-id');
20
+ });
21
+ it('generates different state each time', () => {
22
+ const url1 = tw.getAuthorizeUrl();
23
+ const url2 = tw.getAuthorizeUrl();
24
+ const state1 = new URL(url1).searchParams.get('state');
25
+ const state2 = new URL(url2).searchParams.get('state');
26
+ expect(state1).not.toBe(state2);
27
+ });
28
+ it('includes suggested budget and period when provided', () => {
29
+ const url = tw.getAuthorizeUrl({ state: 's1', suggestedBudget: 10, suggestedPeriod: 'weekly' });
30
+ const parsed = new URL(url);
31
+ expect(parsed.searchParams.get('suggested_budget')).toBe('10');
32
+ expect(parsed.searchParams.get('suggested_period')).toBe('weekly');
33
+ });
34
+ it('omits budget params when not provided', () => {
35
+ const url = tw.getAuthorizeUrl({ state: 's2' });
36
+ const parsed = new URL(url);
37
+ expect(parsed.searchParams.has('suggested_budget')).toBe(false);
38
+ expect(parsed.searchParams.has('suggested_period')).toBe(false);
39
+ });
40
+ });
41
+ describe('proxyUrl', () => {
42
+ it('returns correct URL for anthropic', () => {
43
+ expect(tw.proxyUrl('anthropic')).toBe('https://api.tokenwallet.ai/anthropic');
44
+ });
45
+ it('returns correct URL for openai', () => {
46
+ expect(tw.proxyUrl('openai')).toBe('https://api.tokenwallet.ai/openai');
47
+ });
48
+ it('returns correct URL for google', () => {
49
+ expect(tw.proxyUrl('google')).toBe('https://api.tokenwallet.ai/google');
50
+ });
51
+ });
52
+ describe('exchangeCode', () => {
53
+ it('throws if clientSecret is not set', async () => {
54
+ const noSecret = TokenWallet({ clientId: 'x', redirectUri: 'http://x.com/cb' });
55
+ await expect(noSecret.exchangeCode('code123')).rejects.toThrow('clientSecret is required');
56
+ });
57
+ });
58
+ describe('defaults', () => {
59
+ it('uses default base URL', () => {
60
+ const client = TokenWallet({ clientId: 'x', redirectUri: 'http://x.com/cb' });
61
+ expect(client.baseUrl).toBe('https://tokenwallet.ai');
62
+ expect(client.proxyBase).toBe('https://api.tokenwallet.ai');
63
+ });
64
+ });
65
+ });
66
+ //# sourceMappingURL=client.test.js.map
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { Tokenite } from './client.js';
2
- export type { TokeniteConfig, AuthorizeOptions, PopupOptions, PopupResult, TokenResponse, Provider, ProxyCallOptions, ProxyUsage, ProxySuccess, ProxyError, ProxyResponse, ErrorSource, ProviderInfo, AppInfo, AllowedProvidersResponse, } from './types.js';
2
+ export type { TokeniteConfig, AuthorizeOptions, PopupOptions, PopupResult, TokenResponse, Provider, ProxyCallOptions, ProxyUsage, ProxySuccess, ProxyError, ProxyResponse, ErrorSource, ProviderInfo, AppInfo, UserInfo, AccessContext, } from './types.js';
3
3
  export { isProxyError, isProxySuccess } from './types.js';
4
4
  export { extractErrorMessage } from './error.js';
5
5
  //# sourceMappingURL=index.d.ts.map
package/dist/types.d.ts CHANGED
@@ -140,6 +140,20 @@ export type ProxyResponse = ProxySuccess | ProxyError;
140
140
  export declare const isProxyError: (response: ProxyResponse) => response is ProxyError;
141
141
  /** Type guard: returns true if the response is a success */
142
142
  export declare const isProxySuccess: (response: ProxyResponse) => response is ProxySuccess;
143
+ /**
144
+ * Identity of the user who holds this access token.
145
+ *
146
+ * Use `id` as the stable key for per-user state in your app — it survives
147
+ * token refreshes, re-logins, and device switches. `email` is suitable for
148
+ * display in your UI; treat it as user-controlled and re-fetch on each
149
+ * session if you cache it.
150
+ */
151
+ export type UserInfo = {
152
+ /** Stable Tokenite user id (UUID) */
153
+ readonly id: string;
154
+ /** The user's email address as registered with Tokenite */
155
+ readonly email: string;
156
+ };
143
157
  /** Visual + identity metadata for a single provider */
144
158
  export type ProviderInfo = {
145
159
  /** Stable provider id (same value as the `Provider` union) */
@@ -169,13 +183,19 @@ export type AppInfo = {
169
183
  readonly allowSubstitution: boolean;
170
184
  };
171
185
  /**
172
- * Full access context for a single access token.
186
+ * Full access context for a single access token: the app it belongs to,
187
+ * the user who holds it, and the providers it can call.
173
188
  *
174
189
  * `providers` lists only the providers the user has an active key for —
175
190
  * exactly the set that will succeed through `tk.call()` (budget permitting).
191
+ *
192
+ * `user` identifies the human who holds the token. Use `user.id` as the
193
+ * stable key for any per-user state in your app — it survives token
194
+ * refreshes and re-logins, unlike the access token itself.
176
195
  */
177
- export type AllowedProvidersResponse = {
196
+ export type AccessContext = {
178
197
  readonly app: AppInfo;
198
+ readonly user: UserInfo;
179
199
  readonly providers: readonly ProviderInfo[];
180
200
  };
181
201
  //# sourceMappingURL=types.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenite/sdk",
3
- "version": "1.0.1",
3
+ "version": "2.0.0",
4
4
  "description": "SDK for integrating \"Login with Tokenite\" into your app. Your users bring their own AI tokens — you pay nothing.",
5
5
  "type": "module",
6
6
  "exports": {