@deepkey/sdk 1.1.0 → 1.2.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/README.md CHANGED
@@ -209,7 +209,7 @@ const { data } = await deepkey.connections.list({ userId })
209
209
  await deepkey.connections.revoke(connectionId)
210
210
  ```
211
211
 
212
- **How a connection is tied to the user.** `connections.connect()` sends the current DeepKey session as the bearer, so DeepKey binds the new connection to the signed-in `user.id` (the id is signed into the OAuth state and re-checked on the callback; nothing from the browser chooses the user). On your server, correlate with the same id you get from `getUser(jwt)`:
212
+ **How a connection is tied to the user.** `connections.connect()` sends the current DeepKey session as the bearer, so DeepKey binds the new connection to the signed-in `user.id` (the id is kept on DeepKey with the single-use OAuth state and re-checked on the callback; nothing from the browser chooses the user). On your server, correlate with the same id you get from `getUser(jwt)`:
213
213
 
214
214
  ```ts
215
215
  const { data: { user } } = await deepkey.auth.getUser(jwt) // your authenticated user
@@ -246,6 +246,46 @@ const { payload } = await jwtVerify(jwt, jwks) // payload.sub = user id
246
246
 
247
247
  Use `getUser()` when you need revocation-awareness (a signed-out session fails immediately); use JWKS verification when latency matters (tokens remain valid until expiry).
248
248
 
249
+ ## User API keys (long-lived credentials for your users)
250
+
251
+ Issue keys to your own users for CLIs, integrations, and automations that cannot hold a browser session. A key always belongs to **one user of your project**. These are not your project keys: a user API key looks like `bt_ak_…`, and every method below runs on your server with the **secret key**.
252
+
253
+ ```ts
254
+ import { createServerClient } from '@deepkey/sdk/server'
255
+
256
+ const deepkey = createServerClient(process.env.DEEPKEY_SECRET_KEY) // bt_secret_...
257
+
258
+ // Create — `key` is the plaintext. Show it to the user now: it is returned once and can never be read again.
259
+ const { data: { apiKey, key }, error } = await deepkey.apiKeys.create({ userId: user.id, name: 'CI deploy' })
260
+ // apiKey: { id, user_id, name, last4, last_used_at, revoked_at, created_at }
261
+
262
+ // List — metadata only (active and revoked), newest first. Never the plaintext.
263
+ const { data: { apiKeys } } = await deepkey.apiKeys.list({ userId: user.id })
264
+
265
+ // Revoke — immediate and idempotent. The key stays listed with `revoked_at` set.
266
+ await deepkey.apiKeys.revoke(apiKey.id)
267
+ ```
268
+
269
+ **Validating a key** is the API-key counterpart of `auth.getUser(jwt)` and returns the same `User`:
270
+
271
+ ```ts
272
+ // In your request handler:
273
+ const presented = request.headers.get('x-api-key')
274
+ const { data: { user, apiKey }, error } = await deepkey.apiKeys.verify(presented)
275
+ if (error || !user) return new Response('Unauthorized', { status: 401 })
276
+ // user.id is the same stable UUID you get from getUser(jwt); apiKey tells you which key was used.
277
+ ```
278
+
279
+ | `error.code` | Meaning |
280
+ |---|---|
281
+ | `invalid_user_api_key` (401) | Unknown, malformed, revoked, or issued by another project. Deliberately indistinguishable. |
282
+ | `user_banned` (401) | The key is intact but its owner is banned. |
283
+ | `secret_key_required` (403) | The client was created with a publishable key. |
284
+ | `user_not_found` (404) | `create` received a `userId` that is not a user of this project. |
285
+ | `api_key_not_found` (404) | `revoke` received an id that is not a key of this project. |
286
+
287
+ `verify` sends the key in the request body, never in a URL. A successful `verify` updates `last_used_at`; a rejected one does not. DeepKey stores only a SHA-256 hash and the last four characters, so a lost key cannot be recovered: revoke it and create a new one. Only trust an `apiKey.id` sent by your frontend if it appears in `apiKeys.list({ userId })` for your authenticated user.
288
+
249
289
  ## Types (full public surface)
250
290
 
251
291
  ```ts
@@ -327,8 +367,24 @@ function createServerClient(secretKey: string, options?: ServerClientOptions): {
327
367
  issueAccessToken(connectionId: string): Promise<AuthResponse<ProviderAccessToken | null>>
328
368
  revoke(connectionId: string): Promise<{ error: AuthError | null }>
329
369
  }
370
+ apiKeys: {
371
+ create(params: { userId: string; name?: string }): Promise<AuthResponse<{ apiKey: UserApiKey | null; key: string | null }>>
372
+ list(params: { userId: string }): Promise<AuthResponse<{ apiKeys: UserApiKey[] }>>
373
+ revoke(apiKeyId: string): Promise<{ error: AuthError | null }>
374
+ verify(apiKey: string): Promise<AuthResponse<{ user: User | null; apiKey: UserApiKey | null }>>
375
+ }
330
376
  }
331
377
  interface ServerClientOptions { fetch?: typeof fetch }
378
+
379
+ interface UserApiKey {
380
+ id: string
381
+ user_id: string // same id as User.id
382
+ name: string | null
383
+ last4: string // last four characters of the plaintext, for display
384
+ last_used_at: string | null // last successful apiKeys.verify
385
+ revoked_at: string | null // set once revoked; a revoked key never verifies again
386
+ created_at: string
387
+ }
332
388
  ```
333
389
 
334
390
  ## HTTP endpoints used (for debugging)
@@ -348,12 +404,17 @@ All calls send the API key as the `apikey` header against `https://deepkey.dev/a
348
404
  | `connections.list` | `GET /connections` (bearer) or `GET /connections?user_id=…` (secret key) |
349
405
  | server `connections.issueAccessToken` | `POST /connections/:id/token` (secret key) |
350
406
  | `connections.revoke` | `DELETE /connections/:id` |
407
+ | server `apiKeys.create` | `POST /api-keys` with `{ user_id, name? }` (secret key) |
408
+ | server `apiKeys.list` | `GET /api-keys?user_id=…` (secret key) |
409
+ | server `apiKeys.verify` | `POST /api-keys/verify` with `{ api_key }` (secret key) |
410
+ | server `apiKeys.revoke` | `DELETE /api-keys/:id` (secret key) |
351
411
 
352
412
  ## Gotchas & troubleshooting
353
413
 
354
414
  - **Login redirects to the wrong URL** → your `redirectTo`/`emailRedirectTo` is not on the project's redirect allow-list; the service silently fell back to the Site URL. Add the URL (with wildcards if needed) in the console.
355
415
  - **Session not restored after redirect** → the tokens arrive in the URL *fragment* (`#access_token=…`). Make sure the client is constructed on the page the user lands on, before anything rewrites `location`, and that `detectSessionInUrl` isn't disabled. The fragment is stripped from the address bar immediately after being read.
356
416
  - **Using the secret key in the browser (or the publishable key on the server)** → key types are not interchangeable: `bt_pub_…` for the browser client, `bt_secret_…` for `createServerClient`.
417
+ - **`apiKeys.*` returns `secret_key_required`** → user API keys are server-only. Call them from `createServerClient(bt_secret_…)`, never from the browser client.
357
418
  - **`getUser()` returns `Auth session missing!`** (`code: 'session_missing'`) → no active session and no `jwt` argument was passed.
358
419
  - **SSR** → the default storage falls back to in-memory when `localStorage` is unavailable, so importing the client on the server is safe, but sessions only persist in the browser. Do sign-in flows client-side; validate tokens server-side with `@deepkey/sdk/server`.
359
420
  - **Multiple tabs** → handled: sessions sync via storage events, and refresh-token rotation has a grace window on the service to absorb concurrent refreshes.
@@ -58,4 +58,4 @@ export {
58
58
  DEEPKEY_API_URL,
59
59
  resolveBaseUrl
60
60
  };
61
- //# sourceMappingURL=chunk-A2CRUXTA.js.map
61
+ //# sourceMappingURL=chunk-J4IK2N4V.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types.ts","../src/fetch.ts","../src/constants.ts"],"sourcesContent":["export interface UserIdentity {\n identity_id: string\n id: string\n user_id: string\n provider: string\n identity_data: Record<string, unknown>\n last_sign_in_at: string | null\n created_at: string\n updated_at: string\n}\n\nexport interface User {\n id: string\n aud: string\n role: string\n email: string | null\n email_confirmed_at: string | null\n app_metadata: { provider?: string | null; providers?: string[]; [key: string]: unknown }\n user_metadata: {\n name?: string\n full_name?: string\n avatar_url?: string\n picture?: string\n email?: string\n [key: string]: unknown\n }\n identities?: UserIdentity[]\n created_at: string\n updated_at?: string\n last_sign_in_at?: string | null\n}\n\nexport interface Session {\n access_token: string\n refresh_token: string\n token_type: 'bearer'\n expires_in: number\n expires_at: number\n user: User\n}\n\nexport class AuthError extends Error {\n status?: number\n code?: string\n\n constructor(message: string, status?: number, code?: string) {\n super(message)\n this.name = 'AuthError'\n this.status = status\n this.code = code\n }\n}\n\nexport type AuthChangeEvent = 'INITIAL_SESSION' | 'SIGNED_IN' | 'SIGNED_OUT' | 'TOKEN_REFRESHED'\n\nexport interface Subscription {\n id: string\n unsubscribe: () => void\n}\n\nexport interface StorageAdapter {\n getItem(key: string): string | null\n setItem(key: string, value: string): void\n removeItem(key: string): void\n}\n\nexport interface AuthClientOptions {\n /**\n * @internal Replaces the hosted DeepKey API origin. Used only by DeepKey's own\n * console and test suites; not supported for consumers and stripped from the\n * published type declarations.\n */\n __internalBaseUrl?: string\n storageKey?: string\n autoRefreshToken?: boolean\n detectSessionInUrl?: boolean\n persistSession?: boolean\n storage?: StorageAdapter\n fetch?: typeof fetch\n}\n\nexport interface ServerClientOptions {\n /**\n * @internal Replaces the hosted DeepKey API origin. Used only by DeepKey's own\n * console and test suites; not supported for consumers and stripped from the\n * published type declarations.\n */\n __internalBaseUrl?: string\n fetch?: typeof fetch\n}\n\nexport interface SignInWithOtpCredentials {\n email: string\n options?: {\n emailRedirectTo?: string\n shouldCreateUser?: boolean\n data?: Record<string, unknown>\n }\n}\n\nexport interface VerifyOtpParams {\n email: string\n token: string\n type: 'email' | 'magiclink'\n}\n\nexport interface ConnectProviderCredentials {\n provider: string\n options?: {\n redirectTo?: string\n skipBrowserRedirect?: boolean\n }\n}\n\n// Metadata only: provider tokens never appear in browser responses.\nexport interface ProviderConnection {\n id: string\n // The DeepKey user that granted the connection: the same `user.id` your server gets from getUser(jwt).\n user_id: string\n provider: string\n provider_user_id: string\n identity_data: Record<string, unknown>\n scope: string | null\n status: 'active' | 'reauthorization_required'\n created_at: string\n updated_at: string\n}\n\n// Issued to consumer servers through the secret key; short-lived and refreshed by DeepKey.\nexport interface ProviderAccessToken {\n access_token: string\n token_type: 'bearer'\n expires_at: number | null\n scope: string | null\n}\n\n// A long-lived credential your application issues to one of its users. Not the project\n// key: the plaintext is returned once by `apiKeys.create` and is never readable again.\nexport interface UserApiKey {\n id: string\n // The DeepKey user the key acts for: the same `user.id` your server gets from getUser(jwt).\n user_id: string\n name: string | null\n // Last four characters of the plaintext, for display.\n last4: string\n // Last successful `apiKeys.verify`; null until the key is used.\n last_used_at: string | null\n // Set once the key is revoked; a revoked key never verifies again.\n revoked_at: string | null\n created_at: string\n}\n\nexport interface SignInWithOAuthCredentials {\n provider: string\n options?: {\n redirectTo?: string\n scopes?: string\n queryParams?: Record<string, string>\n skipBrowserRedirect?: boolean\n }\n}\n\nexport interface AuthResponse<T> {\n data: T\n error: AuthError | null\n}\n","import { AuthError } from './types'\n\nexport interface RequestOptions {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE'\n path: string\n apikey: string\n baseUrl: string\n accessToken?: string\n body?: unknown\n fetchImpl?: typeof fetch\n}\n\nexport interface RequestResult<T> {\n data: T | null\n error: AuthError | null\n}\n\n// All service errors are shaped { error: { code, message } }.\nexport const request = async <T>(options: RequestOptions): Promise<RequestResult<T>> => {\n const fetchImpl = options.fetchImpl ?? fetch\n try {\n const headers: Record<string, string> = { apikey: options.apikey }\n if (options.body !== undefined) headers['Content-Type'] = 'application/json'\n if (options.accessToken) headers.Authorization = `Bearer ${options.accessToken}`\n\n const response = await fetchImpl(`${options.baseUrl}${options.path}`, {\n method: options.method,\n headers,\n body: options.body !== undefined ? JSON.stringify(options.body) : undefined,\n })\n\n if (response.status === 204) return { data: {} as T, error: null }\n\n let payload: unknown\n try {\n payload = await response.json()\n } catch {\n payload = null\n }\n\n if (!response.ok) {\n const errorBody = (payload as { error?: { code?: string; message?: string } } | null)?.error\n return {\n data: null,\n error: new AuthError(\n errorBody?.message ?? `Request failed with status ${response.status}`,\n response.status,\n errorBody?.code,\n ),\n }\n }\n\n return { data: payload as T, error: null }\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Network request failed'\n return { data: null, error: new AuthError(message, 0, 'network_error') }\n }\n}\n","// The hosted DeepKey API. Every client talks to this origin; only DeepKey's own\n// console and test suites replace it through the internal override.\nexport const DEEPKEY_API_URL = 'https://deepkey.dev/api'\n\n// Resolves the base URL used for every request. An absent or blank internal\n// override keeps the hosted API; a provided value has any trailing slash removed\n// so path joins stay predictable.\nexport const resolveBaseUrl = (url?: string | null): string => {\n const candidate = typeof url === 'string' ? url.trim() : ''\n return (candidate || DEEPKEY_API_URL).replace(/\\/+$/, '')\n}\n"],"mappings":";AAyCO,IAAM,YAAN,cAAwB,MAAM;AAAA,EAInC,YAAY,SAAiB,QAAiB,MAAe;AAC3D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EACd;AACF;;;ACjC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103
  expires_at: number | null;
104
104
  scope: string | null;
105
105
  }
106
+ interface UserApiKey {
107
+ id: string;
108
+ user_id: string;
109
+ name: string | null;
110
+ last4: string;
111
+ last_used_at: string | null;
112
+ revoked_at: string | null;
113
+ created_at: string;
114
+ }
106
115
  interface SignInWithOAuthCredentials {
107
116
  provider: string;
108
117
  options?: {
@@ -119,4 +128,4 @@ interface AuthResponse<T> {
119
128
 
120
129
  declare const DEEPKEY_API_URL = "https://deepkey.dev/api";
121
130
 
122
- export { type AuthResponse as A, type ConnectProviderCredentials as C, DEEPKEY_API_URL as D, type ProviderConnection as P, type SignInWithOtpCredentials as S, type User as U, type VerifyOtpParams as V, AuthError as a, type AuthClientOptions as b, type Session as c, type SignInWithOAuthCredentials as d, type AuthChangeEvent as e, type Subscription as f, type ProviderAccessToken as g, type ServerClientOptions as h, type StorageAdapter as i, type UserIdentity as j };
131
+ export { type AuthResponse as A, type ConnectProviderCredentials as C, DEEPKEY_API_URL as D, type ProviderConnection as P, type SignInWithOtpCredentials as S, type User as U, type VerifyOtpParams as V, AuthError as a, type AuthClientOptions as b, type Session as c, type SignInWithOAuthCredentials as d, type AuthChangeEvent as e, type Subscription as f, type ProviderAccessToken as g, type ServerClientOptions as h, type StorageAdapter as i, type UserApiKey as j, type UserIdentity as k };
@@ -103,6 +103,15 @@ interface ProviderAccessToken {
103
103
  expires_at: number | null;
104
104
  scope: string | null;
105
105
  }
106
+ interface UserApiKey {
107
+ id: string;
108
+ user_id: string;
109
+ name: string | null;
110
+ last4: string;
111
+ last_used_at: string | null;
112
+ revoked_at: string | null;
113
+ created_at: string;
114
+ }
106
115
  interface SignInWithOAuthCredentials {
107
116
  provider: string;
108
117
  options?: {
@@ -119,4 +128,4 @@ interface AuthResponse<T> {
119
128
 
120
129
  declare const DEEPKEY_API_URL = "https://deepkey.dev/api";
121
130
 
122
- export { type AuthResponse as A, type ConnectProviderCredentials as C, DEEPKEY_API_URL as D, type ProviderConnection as P, type SignInWithOtpCredentials as S, type User as U, type VerifyOtpParams as V, AuthError as a, type AuthClientOptions as b, type Session as c, type SignInWithOAuthCredentials as d, type AuthChangeEvent as e, type Subscription as f, type ProviderAccessToken as g, type ServerClientOptions as h, type StorageAdapter as i, type UserIdentity as j };
131
+ export { type AuthResponse as A, type ConnectProviderCredentials as C, DEEPKEY_API_URL as D, type ProviderConnection as P, type SignInWithOtpCredentials as S, type User as U, type VerifyOtpParams as V, AuthError as a, type AuthClientOptions as b, type Session as c, type SignInWithOAuthCredentials as d, type AuthChangeEvent as e, type Subscription as f, type ProviderAccessToken as g, type ServerClientOptions as h, type StorageAdapter as i, type UserApiKey as j, type UserIdentity as k };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/types.ts","../src/fetch.ts","../src/connections.ts","../src/constants.ts","../src/storage.ts","../src/url.ts","../src/client.ts"],"sourcesContent":["export { createAuthClient, Auth, type AuthClient } from './client'\nexport { Connections } from './connections'\nexport { DEEPKEY_API_URL } from './constants'\nexport {\n AuthError,\n type AuthChangeEvent,\n type AuthClientOptions,\n type AuthResponse,\n type ConnectProviderCredentials,\n type ServerClientOptions,\n type ProviderAccessToken,\n type ProviderConnection,\n type Session,\n type SignInWithOAuthCredentials,\n type SignInWithOtpCredentials,\n type StorageAdapter,\n type Subscription,\n type User,\n type UserIdentity,\n type VerifyOtpParams,\n} from './types'\n","export interface UserIdentity {\n identity_id: string\n id: string\n user_id: string\n provider: string\n identity_data: Record<string, unknown>\n last_sign_in_at: string | null\n created_at: string\n updated_at: string\n}\n\nexport interface User {\n id: string\n aud: string\n role: string\n email: string | null\n email_confirmed_at: string | null\n app_metadata: { provider?: string | null; providers?: string[]; [key: string]: unknown }\n user_metadata: {\n name?: string\n full_name?: string\n avatar_url?: string\n picture?: string\n email?: string\n [key: string]: unknown\n }\n identities?: UserIdentity[]\n created_at: string\n updated_at?: string\n last_sign_in_at?: string | null\n}\n\nexport interface Session {\n access_token: string\n refresh_token: string\n token_type: 'bearer'\n expires_in: number\n expires_at: number\n user: User\n}\n\nexport class AuthError extends Error {\n status?: number\n code?: string\n\n constructor(message: string, status?: number, code?: string) {\n super(message)\n this.name = 'AuthError'\n this.status = status\n this.code = code\n }\n}\n\nexport type AuthChangeEvent = 'INITIAL_SESSION' | 'SIGNED_IN' | 'SIGNED_OUT' | 'TOKEN_REFRESHED'\n\nexport interface Subscription {\n id: string\n unsubscribe: () => void\n}\n\nexport interface StorageAdapter {\n getItem(key: string): string | null\n setItem(key: string, value: string): void\n removeItem(key: string): void\n}\n\nexport interface AuthClientOptions {\n /**\n * @internal Replaces the hosted DeepKey API origin. Used only by DeepKey's own\n * console and test suites; not supported for consumers and stripped from the\n * published type declarations.\n */\n __internalBaseUrl?: string\n storageKey?: string\n autoRefreshToken?: boolean\n detectSessionInUrl?: boolean\n persistSession?: boolean\n storage?: StorageAdapter\n fetch?: typeof fetch\n}\n\nexport interface ServerClientOptions {\n /**\n * @internal Replaces the hosted DeepKey API origin. Used only by DeepKey's own\n * console and test suites; not supported for consumers and stripped from the\n * published type declarations.\n */\n __internalBaseUrl?: string\n fetch?: typeof fetch\n}\n\nexport interface SignInWithOtpCredentials {\n email: string\n options?: {\n emailRedirectTo?: string\n shouldCreateUser?: boolean\n data?: Record<string, unknown>\n }\n}\n\nexport interface VerifyOtpParams {\n email: string\n token: string\n type: 'email' | 'magiclink'\n}\n\nexport interface ConnectProviderCredentials {\n provider: string\n options?: {\n redirectTo?: string\n skipBrowserRedirect?: boolean\n }\n}\n\n// Metadata only: provider tokens never appear in browser responses.\nexport interface ProviderConnection {\n id: string\n // The DeepKey user that granted the connection: the same `user.id` your server gets from getUser(jwt).\n user_id: string\n provider: string\n provider_user_id: string\n identity_data: Record<string, unknown>\n scope: string | null\n status: 'active' | 'reauthorization_required'\n created_at: string\n updated_at: string\n}\n\n// Issued to consumer servers through the secret key; short-lived and refreshed by DeepKey.\nexport interface ProviderAccessToken {\n access_token: string\n token_type: 'bearer'\n expires_at: number | null\n scope: string | null\n}\n\nexport interface SignInWithOAuthCredentials {\n provider: string\n options?: {\n redirectTo?: string\n scopes?: string\n queryParams?: Record<string, string>\n skipBrowserRedirect?: boolean\n }\n}\n\nexport interface AuthResponse<T> {\n data: T\n error: AuthError | null\n}\n","import { AuthError } from './types'\n\nexport interface RequestOptions {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE'\n path: string\n apikey: string\n baseUrl: string\n accessToken?: string\n body?: unknown\n fetchImpl?: typeof fetch\n}\n\nexport interface RequestResult<T> {\n data: T | null\n error: AuthError | null\n}\n\n// All service errors are shaped { error: { code, message } }.\nexport const request = async <T>(options: RequestOptions): Promise<RequestResult<T>> => {\n const fetchImpl = options.fetchImpl ?? fetch\n try {\n const headers: Record<string, string> = { apikey: options.apikey }\n if (options.body !== undefined) headers['Content-Type'] = 'application/json'\n if (options.accessToken) headers.Authorization = `Bearer ${options.accessToken}`\n\n const response = await fetchImpl(`${options.baseUrl}${options.path}`, {\n method: options.method,\n headers,\n body: options.body !== undefined ? JSON.stringify(options.body) : undefined,\n })\n\n if (response.status === 204) return { data: {} as T, error: null }\n\n let payload: unknown\n try {\n payload = await response.json()\n } catch {\n payload = null\n }\n\n if (!response.ok) {\n const errorBody = (payload as { error?: { code?: string; message?: string } } | null)?.error\n return {\n data: null,\n error: new AuthError(\n errorBody?.message ?? `Request failed with status ${response.status}`,\n response.status,\n errorBody?.code,\n ),\n }\n }\n\n return { data: payload as T, error: null }\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Network request failed'\n return { data: null, error: new AuthError(message, 0, 'network_error') }\n }\n}\n","import type { Auth } from './client'\nimport { request } from './fetch'\nimport { AuthError, type AuthResponse, type ConnectProviderCredentials, type ProviderConnection } from './types'\n\nexport interface ConnectionsOptions {\n apikey: string\n baseUrl: string\n fetchImpl?: typeof fetch\n}\n\n// Durable provider access for the signed-in user, kept apart from login identities:\n// a user who signed in with Google can connect several X accounts. Provider refresh\n// tokens stay on DeepKey; browsers only ever see connection metadata.\nexport class Connections {\n constructor(\n private auth: Auth,\n private options: ConnectionsOptions,\n ) {}\n\n async connect(\n credentials: ConnectProviderCredentials,\n ): Promise<AuthResponse<{ provider: string; url: string | null }>> {\n const { data, error } = await this.request<{ provider: string; url: string }>(\n 'POST',\n '/auth/v1/connections/authorize',\n { provider: credentials.provider, redirect_to: credentials.options?.redirectTo },\n )\n if (error || !data) return { data: { provider: credentials.provider, url: null }, error }\n\n if (!credentials.options?.skipBrowserRedirect && typeof window !== 'undefined') {\n window.location.assign(data.url)\n }\n return { data: { provider: credentials.provider, url: data.url }, error: null }\n }\n\n async list(): Promise<AuthResponse<{ connections: ProviderConnection[] }>> {\n const { data, error } = await this.request<{ connections: ProviderConnection[] }>('GET', '/auth/v1/connections')\n return { data: { connections: data?.connections ?? [] }, error }\n }\n\n async revoke(connectionId: string): Promise<{ error: AuthError | null }> {\n const { error } = await this.request('DELETE', `/auth/v1/connections/${encodeURIComponent(connectionId)}`)\n return { error }\n }\n\n private async request<T>(method: 'GET' | 'POST' | 'DELETE', path: string, body?: unknown) {\n const {\n data: { session },\n } = await this.auth.getSession()\n if (!session) {\n return { data: null, error: new AuthError('Auth session missing!', 400, 'session_missing') }\n }\n return request<T>({ method, path, body, accessToken: session.access_token, ...this.options })\n }\n}\n","// The hosted DeepKey API. Every client talks to this origin; only DeepKey's own\n// console and test suites replace it through the internal override.\nexport const DEEPKEY_API_URL = 'https://deepkey.dev/api'\n\n// Resolves the base URL used for every request. An absent or blank internal\n// override keeps the hosted API; a provided value has any trailing slash removed\n// so path joins stay predictable.\nexport const resolveBaseUrl = (url?: string | null): string => {\n const candidate = typeof url === 'string' ? url.trim() : ''\n return (candidate || DEEPKEY_API_URL).replace(/\\/+$/, '')\n}\n","import type { StorageAdapter } from './types'\n\nclass MemoryStorage implements StorageAdapter {\n private store = new Map<string, string>()\n getItem(key: string) {\n return this.store.get(key) ?? null\n }\n setItem(key: string, value: string) {\n this.store.set(key, value)\n }\n removeItem(key: string) {\n this.store.delete(key)\n }\n}\n\n// localStorage when available, in-memory fallback (SSR, tests, restricted contexts).\nexport const defaultStorage = (): StorageAdapter => {\n try {\n if (typeof window !== 'undefined' && window.localStorage) {\n const probe = '__bt_auth_probe__'\n window.localStorage.setItem(probe, '1')\n window.localStorage.removeItem(probe)\n return window.localStorage\n }\n } catch {\n // fall through to memory storage\n }\n return new MemoryStorage()\n}\n\n// Publishable keys look like `bt_pub_<project-slug>_<random>`; the slug namespaces the\n// persisted session per project (mirrors supabase's `sb-<ref>-auth-token`).\nexport const deriveStorageKey = (publishableKey: string | undefined): string => {\n const match = publishableKey?.match(/^bt_pub_([a-z0-9-]+)_[A-Za-z0-9_-]+$/)\n return match ? `bt-${match[1]}-auth-token` : 'bt-auth-token'\n}\n","export interface FragmentTokens {\n access_token: string\n refresh_token: string\n expires_in: number\n expires_at: number\n token_type: 'bearer'\n type?: string\n}\n\nexport interface FragmentError {\n error: string\n error_code?: string\n error_description?: string\n}\n\nexport type ParsedFragment = { tokens: FragmentTokens } | { authError: FragmentError } | null\n\n// Parses the implicit-flow return fragment (`#access_token=...` or `#error=...`).\nexport const parseFragment = (hash: string): ParsedFragment => {\n if (!hash || hash.length < 2) return null\n const params = new URLSearchParams(hash.startsWith('#') ? hash.slice(1) : hash)\n\n const error = params.get('error')\n if (error) {\n return {\n authError: {\n error,\n error_code: params.get('error_code') ?? undefined,\n error_description: params.get('error_description') ?? undefined,\n },\n }\n }\n\n const accessToken = params.get('access_token')\n const refreshToken = params.get('refresh_token')\n if (!accessToken || !refreshToken) return null\n\n const expiresIn = Number(params.get('expires_in') ?? 3600)\n const expiresAt = Number(params.get('expires_at') ?? Math.floor(Date.now() / 1000) + expiresIn)\n\n return {\n tokens: {\n access_token: accessToken,\n refresh_token: refreshToken,\n expires_in: expiresIn,\n expires_at: expiresAt,\n token_type: 'bearer',\n type: params.get('type') ?? undefined,\n },\n }\n}\n\n// Removes the auth fragment from the address bar (before any await, so tokens never\n// linger in history).\nexport const cleanFragmentFromUrl = () => {\n if (typeof window === 'undefined' || typeof history === 'undefined') return\n history.replaceState(null, '', window.location.pathname + window.location.search)\n}\n","import { Connections } from './connections'\nimport { resolveBaseUrl } from './constants'\nimport { request } from './fetch'\nimport { defaultStorage, deriveStorageKey } from './storage'\nimport {\n AuthError,\n type AuthChangeEvent,\n type AuthClientOptions,\n type AuthResponse,\n type Session,\n type SignInWithOAuthCredentials,\n type SignInWithOtpCredentials,\n type StorageAdapter,\n type Subscription,\n type User,\n type VerifyOtpParams,\n} from './types'\nimport { cleanFragmentFromUrl, parseFragment } from './url'\n\nconst REFRESH_TICK_MS = 30_000\n// Refresh when the access token is within this margin of expiry.\nconst EXPIRY_MARGIN_SECONDS = 90\n\ntype Listener = (event: AuthChangeEvent, session: Session | null) => void\n\nexport class Auth {\n private baseUrl: string\n private apikey: string\n private storage: StorageAdapter\n private storageKey: string\n private persistSession: boolean\n private autoRefreshToken: boolean\n private detectSessionInUrl: boolean\n private fetchImpl?: typeof fetch\n\n private session: Session | null = null\n private listeners = new Map<string, Listener>()\n private listenerSeq = 0\n private initializePromise: Promise<void> | null = null\n private refreshPromise: Promise<AuthResponse<{ session: Session | null; user: User | null }>> | null = null\n private refreshTimer: ReturnType<typeof setInterval> | null = null\n\n constructor(publishableKey: string, options: AuthClientOptions = {}) {\n // Lazy by design: an empty key must not throw at construction time (CI builds\n // with empty envs import this module transitively). Failures surface on first call.\n // The hosted DeepKey API is the only supported origin. The internal override\n // exists for DeepKey's console and tests and is not part of the public contract.\n this.baseUrl = resolveBaseUrl(options.__internalBaseUrl)\n this.apikey = publishableKey ?? ''\n this.persistSession = options.persistSession ?? true\n this.autoRefreshToken = options.autoRefreshToken ?? true\n this.detectSessionInUrl = options.detectSessionInUrl ?? true\n this.storage = options.storage ?? defaultStorage()\n this.storageKey = options.storageKey ?? deriveStorageKey(publishableKey)\n this.fetchImpl = options.fetch\n\n this.setupCrossTabSync()\n }\n\n // ---- public API (supabase-js compatible) ----\n\n async signInWithOtp(credentials: SignInWithOtpCredentials): Promise<AuthResponse<{ user: null; session: null }>> {\n const { error } = await this.request<Record<string, never>>('POST', '/auth/v1/otp', {\n email: credentials.email,\n create_user: credentials.options?.shouldCreateUser,\n redirect_to: credentials.options?.emailRedirectTo,\n })\n return { data: { user: null, session: null }, error }\n }\n\n async verifyOtp(params: VerifyOtpParams): Promise<AuthResponse<{ user: User | null; session: Session | null }>> {\n const { data, error } = await this.request<Session>('POST', '/auth/v1/verify', {\n type: 'email',\n email: params.email,\n token: params.token,\n })\n if (error || !data) return { data: { user: null, session: null }, error }\n\n await this.saveSession(data)\n this.emit('SIGNED_IN', data)\n return { data: { user: data.user, session: data }, error: null }\n }\n\n async signInWithOAuth(\n credentials: SignInWithOAuthCredentials,\n ): Promise<AuthResponse<{ provider: string; url: string }>> {\n const url = new URL(`${this.baseUrl}/auth/v1/authorize`)\n url.searchParams.set('provider', credentials.provider)\n url.searchParams.set('apikey', this.apikey)\n if (credentials.options?.redirectTo) url.searchParams.set('redirect_to', credentials.options.redirectTo)\n if (credentials.options?.scopes) url.searchParams.set('scopes', credentials.options.scopes)\n for (const [key, value] of Object.entries(credentials.options?.queryParams ?? {})) {\n url.searchParams.set(key, value)\n }\n\n if (!credentials.options?.skipBrowserRedirect && typeof window !== 'undefined') {\n window.location.assign(url.toString())\n }\n return { data: { provider: credentials.provider, url: url.toString() }, error: null }\n }\n\n onAuthStateChange(callback: Listener): { data: { subscription: Subscription } } {\n const id = `listener-${++this.listenerSeq}`\n this.listeners.set(id, callback)\n\n // Every subscriber receives INITIAL_SESSION asynchronously once initialization\n // settles — the supabase-js contract that AuthProviders rely on to resolve loading.\n this.initialize().then(() => {\n if (this.listeners.has(id)) callback('INITIAL_SESSION', this.session)\n })\n\n return {\n data: {\n subscription: {\n id,\n unsubscribe: () => {\n this.listeners.delete(id)\n },\n },\n },\n }\n }\n\n async signOut(): Promise<{ error: AuthError | null }> {\n await this.initialize()\n const session = this.session\n if (session) {\n // Best-effort server-side revocation; local sign-out always succeeds.\n await this.request('POST', '/auth/v1/logout', {}, session.access_token)\n }\n this.clearSession()\n this.emit('SIGNED_OUT', null)\n return { error: null }\n }\n\n async getSession(): Promise<AuthResponse<{ session: Session | null }>> {\n await this.initialize()\n\n if (this.session && this.isExpired(this.session) && this.autoRefreshToken) {\n const { error } = await this.refreshWithLock()\n if (error && error.code !== 'network_error') {\n return { data: { session: null }, error: null }\n }\n }\n\n return { data: { session: this.session }, error: null }\n }\n\n async getUser(jwt?: string): Promise<AuthResponse<{ user: User | null }>> {\n let token = jwt\n if (!token) {\n const {\n data: { session },\n } = await this.getSession()\n token = session?.access_token\n }\n if (!token) {\n return { data: { user: null }, error: new AuthError('Auth session missing!', 400, 'session_missing') }\n }\n\n const { data, error } = await this.request<User>('GET', '/auth/v1/user', undefined, token)\n return { data: { user: data }, error }\n }\n\n async refreshSession(currentSession?: {\n refresh_token: string\n }): Promise<AuthResponse<{ session: Session | null; user: User | null }>> {\n await this.initialize()\n const refreshToken = currentSession?.refresh_token ?? this.session?.refresh_token\n if (!refreshToken) {\n return {\n data: { session: null, user: null },\n error: new AuthError('Auth session missing!', 400, 'session_missing'),\n }\n }\n return this.refreshWithLock(refreshToken)\n }\n\n // ---- internals ----\n\n private async request<T>(method: 'GET' | 'POST', path: string, body?: unknown, accessToken?: string) {\n return request<T>({\n method,\n path,\n body,\n accessToken,\n apikey: this.apikey,\n baseUrl: this.baseUrl,\n fetchImpl: this.fetchImpl,\n })\n }\n\n private initialize(): Promise<void> {\n this.initializePromise ??= this.doInitialize()\n return this.initializePromise\n }\n\n private async doInitialize(): Promise<void> {\n if (this.detectSessionInUrl && typeof window !== 'undefined') {\n const parsed = parseFragment(window.location.hash)\n if (parsed) {\n // Strip tokens from the address bar synchronously, before any await.\n cleanFragmentFromUrl()\n\n if ('authError' in parsed) {\n console.warn(\n `[deepkey] Auth redirect returned an error: ${parsed.authError.error_code ?? parsed.authError.error}`,\n parsed.authError.error_description ?? '',\n )\n } else {\n const { data: user } = await this.request<User>('GET', '/auth/v1/user', undefined, parsed.tokens.access_token)\n if (user) {\n const session: Session = { ...parsed.tokens, token_type: 'bearer', user }\n await this.saveSession(session)\n this.emit('SIGNED_IN', session)\n return\n }\n }\n }\n }\n\n const stored = this.loadStoredSession()\n if (!stored) return\n\n if (this.isExpired(stored)) {\n if (!this.autoRefreshToken) return\n this.session = stored\n const { error } = await this.refreshWithLock()\n if (error && error.code !== 'network_error') this.clearSession()\n return\n }\n\n this.session = stored\n this.startRefreshTimer()\n }\n\n private isExpired(session: Session): boolean {\n return session.expires_at <= Math.floor(Date.now() / 1000) + EXPIRY_MARGIN_SECONDS\n }\n\n private async refreshWithLock(\n refreshToken?: string,\n ): Promise<AuthResponse<{ session: Session | null; user: User | null }>> {\n this.refreshPromise ??= this.doRefresh(refreshToken).finally(() => {\n this.refreshPromise = null\n })\n return this.refreshPromise\n }\n\n private async doRefresh(\n refreshToken?: string,\n ): Promise<AuthResponse<{ session: Session | null; user: User | null }>> {\n const token = refreshToken ?? this.session?.refresh_token\n if (!token) {\n return {\n data: { session: null, user: null },\n error: new AuthError('Auth session missing!', 400, 'session_missing'),\n }\n }\n\n const { data, error } = await this.request<Session>('POST', '/auth/v1/token?grant_type=refresh_token', {\n refresh_token: token,\n })\n\n if (error) {\n // Network failures keep the session (retry next tick); auth failures clear it.\n if (error.code !== 'network_error') {\n this.clearSession()\n this.emit('SIGNED_OUT', null)\n }\n return { data: { session: null, user: null }, error }\n }\n\n if (data) {\n await this.saveSession(data)\n this.emit('TOKEN_REFRESHED', data)\n return { data: { session: data, user: data.user }, error: null }\n }\n return { data: { session: null, user: null }, error: new AuthError('Empty refresh response') }\n }\n\n private async saveSession(session: Session) {\n this.session = session\n if (this.persistSession) {\n try {\n this.storage.setItem(this.storageKey, JSON.stringify(session))\n } catch {\n // Persistence is best-effort (private mode, quota).\n }\n }\n this.startRefreshTimer()\n }\n\n private clearSession() {\n this.session = null\n try {\n this.storage.removeItem(this.storageKey)\n } catch {\n // ignore\n }\n this.stopRefreshTimer()\n }\n\n private loadStoredSession(): Session | null {\n if (!this.persistSession) return null\n try {\n const raw = this.storage.getItem(this.storageKey)\n if (!raw) return null\n const parsed = JSON.parse(raw) as Session\n if (!parsed.access_token || !parsed.refresh_token) return null\n return parsed\n } catch {\n return null\n }\n }\n\n private startRefreshTimer() {\n if (!this.autoRefreshToken || this.refreshTimer || typeof setInterval === 'undefined') return\n this.refreshTimer = setInterval(() => {\n if (this.session && this.isExpired(this.session)) void this.refreshWithLock()\n }, REFRESH_TICK_MS)\n // Do not keep node processes alive because of the timer (no-op in browsers).\n const timer = this.refreshTimer as unknown as { unref?: () => void }\n if (typeof timer === 'object' && typeof timer.unref === 'function') timer.unref()\n }\n\n private stopRefreshTimer() {\n if (this.refreshTimer) {\n clearInterval(this.refreshTimer)\n this.refreshTimer = null\n }\n }\n\n private setupCrossTabSync() {\n if (typeof window === 'undefined' || !this.persistSession) return\n window.addEventListener('storage', event => {\n if (event.key !== this.storageKey) return\n if (!event.newValue) {\n if (this.session) {\n this.session = null\n this.stopRefreshTimer()\n this.emit('SIGNED_OUT', null)\n }\n return\n }\n try {\n const next = JSON.parse(event.newValue) as Session\n const changed = next.access_token !== this.session?.access_token\n this.session = next\n this.startRefreshTimer()\n if (changed) this.emit('TOKEN_REFRESHED', next)\n } catch {\n // ignore malformed writes\n }\n })\n }\n\n private emit(event: AuthChangeEvent, session: Session | null) {\n for (const listener of this.listeners.values()) {\n try {\n listener(event, session)\n } catch (err) {\n console.error('[deepkey] onAuthStateChange listener threw', err)\n }\n }\n }\n}\n\nexport interface AuthClient {\n auth: Auth\n connections: Connections\n}\n\nexport const createAuthClient = (publishableKey: string, options?: AuthClientOptions): AuthClient => {\n const auth = new Auth(publishableKey, options)\n const connections = new Connections(auth, {\n apikey: publishableKey ?? '',\n baseUrl: resolveBaseUrl(options?.__internalBaseUrl),\n fetchImpl: options?.fetch,\n })\n return { auth, connections }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;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7C,QAAM,cAAc,IAAI,YAAY,MAAM;AAAA,IACxC,QAAQ,kBAAkB;AAAA,IAC1B,SAAS,eAAe,SAAS,iBAAiB;AAAA,IAClD,WAAW,SAAS;AAAA,EACtB,CAAC;AACD,SAAO,EAAE,MAAM,YAAY;AAC7B;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts","../src/types.ts","../src/fetch.ts","../src/connections.ts","../src/constants.ts","../src/storage.ts","../src/url.ts","../src/client.ts"],"sourcesContent":["export { createAuthClient, Auth, type AuthClient } from './client'\nexport { Connections } from './connections'\nexport { DEEPKEY_API_URL } from './constants'\nexport {\n AuthError,\n type AuthChangeEvent,\n type AuthClientOptions,\n type AuthResponse,\n type ConnectProviderCredentials,\n type ServerClientOptions,\n type ProviderAccessToken,\n type ProviderConnection,\n type Session,\n type SignInWithOAuthCredentials,\n type SignInWithOtpCredentials,\n type StorageAdapter,\n type Subscription,\n type User,\n type UserApiKey,\n type UserIdentity,\n type VerifyOtpParams,\n} from './types'\n","export interface UserIdentity {\n identity_id: string\n id: string\n user_id: string\n provider: string\n identity_data: Record<string, unknown>\n last_sign_in_at: string | null\n created_at: string\n updated_at: string\n}\n\nexport interface User {\n id: string\n aud: string\n role: string\n email: string | null\n email_confirmed_at: string | null\n app_metadata: { provider?: string | null; providers?: string[]; [key: string]: unknown }\n user_metadata: {\n name?: string\n full_name?: string\n avatar_url?: string\n picture?: string\n email?: string\n [key: string]: unknown\n }\n identities?: UserIdentity[]\n created_at: string\n updated_at?: string\n last_sign_in_at?: string | null\n}\n\nexport interface Session {\n access_token: string\n refresh_token: string\n token_type: 'bearer'\n expires_in: number\n expires_at: number\n user: User\n}\n\nexport class AuthError extends Error {\n status?: number\n code?: string\n\n constructor(message: string, status?: number, code?: string) {\n super(message)\n this.name = 'AuthError'\n this.status = status\n this.code = code\n }\n}\n\nexport type AuthChangeEvent = 'INITIAL_SESSION' | 'SIGNED_IN' | 'SIGNED_OUT' | 'TOKEN_REFRESHED'\n\nexport interface Subscription {\n id: string\n unsubscribe: () => void\n}\n\nexport interface StorageAdapter {\n getItem(key: string): string | null\n setItem(key: string, value: string): void\n removeItem(key: string): void\n}\n\nexport interface AuthClientOptions {\n /**\n * @internal Replaces the hosted DeepKey API origin. Used only by DeepKey's own\n * console and test suites; not supported for consumers and stripped from the\n * published type declarations.\n */\n __internalBaseUrl?: string\n storageKey?: string\n autoRefreshToken?: boolean\n detectSessionInUrl?: boolean\n persistSession?: boolean\n storage?: StorageAdapter\n fetch?: typeof fetch\n}\n\nexport interface ServerClientOptions {\n /**\n * @internal Replaces the hosted DeepKey API origin. Used only by DeepKey's own\n * console and test suites; not supported for consumers and stripped from the\n * published type declarations.\n */\n __internalBaseUrl?: string\n fetch?: typeof fetch\n}\n\nexport interface SignInWithOtpCredentials {\n email: string\n options?: {\n emailRedirectTo?: string\n shouldCreateUser?: boolean\n data?: Record<string, unknown>\n }\n}\n\nexport interface VerifyOtpParams {\n email: string\n token: string\n type: 'email' | 'magiclink'\n}\n\nexport interface ConnectProviderCredentials {\n provider: string\n options?: {\n redirectTo?: string\n skipBrowserRedirect?: boolean\n }\n}\n\n// Metadata only: provider tokens never appear in browser responses.\nexport interface ProviderConnection {\n id: string\n // The DeepKey user that granted the connection: the same `user.id` your server gets from getUser(jwt).\n user_id: string\n provider: string\n provider_user_id: string\n identity_data: Record<string, unknown>\n scope: string | null\n status: 'active' | 'reauthorization_required'\n created_at: string\n updated_at: string\n}\n\n// Issued to consumer servers through the secret key; short-lived and refreshed by DeepKey.\nexport interface ProviderAccessToken {\n access_token: string\n token_type: 'bearer'\n expires_at: number | null\n scope: string | null\n}\n\n// A long-lived credential your application issues to one of its users. Not the project\n// key: the plaintext is returned once by `apiKeys.create` and is never readable again.\nexport interface UserApiKey {\n id: string\n // The DeepKey user the key acts for: the same `user.id` your server gets from getUser(jwt).\n user_id: string\n name: string | null\n // Last four characters of the plaintext, for display.\n last4: string\n // Last successful `apiKeys.verify`; null until the key is used.\n last_used_at: string | null\n // Set once the key is revoked; a revoked key never verifies again.\n revoked_at: string | null\n created_at: string\n}\n\nexport interface SignInWithOAuthCredentials {\n provider: string\n options?: {\n redirectTo?: string\n scopes?: string\n queryParams?: Record<string, string>\n skipBrowserRedirect?: boolean\n }\n}\n\nexport interface AuthResponse<T> {\n data: T\n error: AuthError | null\n}\n","import { AuthError } from './types'\n\nexport interface RequestOptions {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE'\n path: string\n apikey: string\n baseUrl: string\n accessToken?: string\n body?: unknown\n fetchImpl?: typeof fetch\n}\n\nexport interface RequestResult<T> {\n data: T | null\n error: AuthError | null\n}\n\n// All service errors are shaped { error: { code, message } }.\nexport const request = async <T>(options: RequestOptions): Promise<RequestResult<T>> => {\n const fetchImpl = options.fetchImpl ?? fetch\n try {\n const headers: Record<string, string> = { apikey: options.apikey }\n if (options.body !== undefined) headers['Content-Type'] = 'application/json'\n if (options.accessToken) headers.Authorization = `Bearer ${options.accessToken}`\n\n const response = await fetchImpl(`${options.baseUrl}${options.path}`, {\n method: options.method,\n headers,\n body: options.body !== undefined ? JSON.stringify(options.body) : undefined,\n })\n\n if (response.status === 204) return { data: {} as T, error: null }\n\n let payload: unknown\n try {\n payload = await response.json()\n } catch {\n payload = null\n }\n\n if (!response.ok) {\n const errorBody = (payload as { error?: { code?: string; message?: string } } | null)?.error\n return {\n data: null,\n error: new AuthError(\n errorBody?.message ?? `Request failed with status ${response.status}`,\n response.status,\n errorBody?.code,\n ),\n }\n }\n\n return { data: payload as T, error: null }\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Network request failed'\n return { data: null, error: new AuthError(message, 0, 'network_error') }\n }\n}\n","import type { Auth } from './client'\nimport { request } from './fetch'\nimport { AuthError, type AuthResponse, type ConnectProviderCredentials, type ProviderConnection } from './types'\n\nexport interface ConnectionsOptions {\n apikey: string\n baseUrl: string\n fetchImpl?: typeof fetch\n}\n\n// Durable provider access for the signed-in user, kept apart from login identities:\n// a user who signed in with Google can connect several X accounts. Provider refresh\n// tokens stay on DeepKey; browsers only ever see connection metadata.\nexport class Connections {\n constructor(\n private auth: Auth,\n private options: ConnectionsOptions,\n ) {}\n\n async connect(\n credentials: ConnectProviderCredentials,\n ): Promise<AuthResponse<{ provider: string; url: string | null }>> {\n const { data, error } = await this.request<{ provider: string; url: string }>(\n 'POST',\n '/auth/v1/connections/authorize',\n { provider: credentials.provider, redirect_to: credentials.options?.redirectTo },\n )\n if (error || !data) return { data: { provider: credentials.provider, url: null }, error }\n\n if (!credentials.options?.skipBrowserRedirect && typeof window !== 'undefined') {\n window.location.assign(data.url)\n }\n return { data: { provider: credentials.provider, url: data.url }, error: null }\n }\n\n async list(): Promise<AuthResponse<{ connections: ProviderConnection[] }>> {\n const { data, error } = await this.request<{ connections: ProviderConnection[] }>('GET', '/auth/v1/connections')\n return { data: { connections: data?.connections ?? [] }, error }\n }\n\n async revoke(connectionId: string): Promise<{ error: AuthError | null }> {\n const { error } = await this.request('DELETE', `/auth/v1/connections/${encodeURIComponent(connectionId)}`)\n return { error }\n }\n\n private async request<T>(method: 'GET' | 'POST' | 'DELETE', path: string, body?: unknown) {\n const {\n data: { session },\n } = await this.auth.getSession()\n if (!session) {\n return { data: null, error: new AuthError('Auth session missing!', 400, 'session_missing') }\n }\n return request<T>({ method, path, body, accessToken: session.access_token, ...this.options })\n }\n}\n","// The hosted DeepKey API. Every client talks to this origin; only DeepKey's own\n// console and test suites replace it through the internal override.\nexport const DEEPKEY_API_URL = 'https://deepkey.dev/api'\n\n// Resolves the base URL used for every request. An absent or blank internal\n// override keeps the hosted API; a provided value has any trailing slash removed\n// so path joins stay predictable.\nexport const resolveBaseUrl = (url?: string | null): string => {\n const candidate = typeof url === 'string' ? url.trim() : ''\n return (candidate || DEEPKEY_API_URL).replace(/\\/+$/, '')\n}\n","import type { StorageAdapter } from './types'\n\nclass MemoryStorage implements StorageAdapter {\n private store = new Map<string, string>()\n getItem(key: string) {\n return this.store.get(key) ?? null\n }\n setItem(key: string, value: string) {\n this.store.set(key, value)\n }\n removeItem(key: string) {\n this.store.delete(key)\n }\n}\n\n// localStorage when available, in-memory fallback (SSR, tests, restricted contexts).\nexport const defaultStorage = (): StorageAdapter => {\n try {\n if (typeof window !== 'undefined' && window.localStorage) {\n const probe = '__bt_auth_probe__'\n window.localStorage.setItem(probe, '1')\n window.localStorage.removeItem(probe)\n return window.localStorage\n }\n } catch {\n // fall through to memory storage\n }\n return new MemoryStorage()\n}\n\n// Publishable keys look like `bt_pub_<project-slug>_<random>`; the slug namespaces the\n// persisted session per project (mirrors supabase's `sb-<ref>-auth-token`).\nexport const deriveStorageKey = (publishableKey: string | undefined): string => {\n const match = publishableKey?.match(/^bt_pub_([a-z0-9-]+)_[A-Za-z0-9_-]+$/)\n return match ? `bt-${match[1]}-auth-token` : 'bt-auth-token'\n}\n","export interface FragmentTokens {\n access_token: string\n refresh_token: string\n expires_in: number\n expires_at: number\n token_type: 'bearer'\n type?: string\n}\n\nexport interface FragmentError {\n error: string\n error_code?: string\n error_description?: string\n}\n\nexport type ParsedFragment = { tokens: FragmentTokens } | { authError: FragmentError } | null\n\n// Parses the implicit-flow return fragment (`#access_token=...` or `#error=...`).\nexport const parseFragment = (hash: string): ParsedFragment => {\n if (!hash || hash.length < 2) return null\n const params = new URLSearchParams(hash.startsWith('#') ? hash.slice(1) : hash)\n\n const error = params.get('error')\n if (error) {\n return {\n authError: {\n error,\n error_code: params.get('error_code') ?? undefined,\n error_description: params.get('error_description') ?? undefined,\n },\n }\n }\n\n const accessToken = params.get('access_token')\n const refreshToken = params.get('refresh_token')\n if (!accessToken || !refreshToken) return null\n\n const expiresIn = Number(params.get('expires_in') ?? 3600)\n const expiresAt = Number(params.get('expires_at') ?? Math.floor(Date.now() / 1000) + expiresIn)\n\n return {\n tokens: {\n access_token: accessToken,\n refresh_token: refreshToken,\n expires_in: expiresIn,\n expires_at: expiresAt,\n token_type: 'bearer',\n type: params.get('type') ?? undefined,\n },\n }\n}\n\n// Removes the auth fragment from the address bar (before any await, so tokens never\n// linger in history).\nexport const cleanFragmentFromUrl = () => {\n if (typeof window === 'undefined' || typeof history === 'undefined') return\n history.replaceState(null, '', window.location.pathname + window.location.search)\n}\n","import { Connections } from './connections'\nimport { resolveBaseUrl } from './constants'\nimport { request } from './fetch'\nimport { defaultStorage, deriveStorageKey } from './storage'\nimport {\n AuthError,\n type AuthChangeEvent,\n type AuthClientOptions,\n type AuthResponse,\n type Session,\n type SignInWithOAuthCredentials,\n type SignInWithOtpCredentials,\n type StorageAdapter,\n type Subscription,\n type User,\n type VerifyOtpParams,\n} from './types'\nimport { cleanFragmentFromUrl, parseFragment } from './url'\n\nconst REFRESH_TICK_MS = 30_000\n// Refresh when the access token is within this margin of expiry.\nconst EXPIRY_MARGIN_SECONDS = 90\n\ntype Listener = (event: AuthChangeEvent, session: Session | null) => void\n\nexport class Auth {\n private baseUrl: string\n private apikey: string\n private storage: StorageAdapter\n private storageKey: string\n private persistSession: boolean\n private autoRefreshToken: boolean\n private detectSessionInUrl: boolean\n private fetchImpl?: typeof fetch\n\n private session: Session | null = null\n private listeners = new Map<string, Listener>()\n private listenerSeq = 0\n private initializePromise: Promise<void> | null = null\n private refreshPromise: Promise<AuthResponse<{ session: Session | null; user: User | null }>> | null = null\n private refreshTimer: ReturnType<typeof setInterval> | null = null\n\n constructor(publishableKey: string, options: AuthClientOptions = {}) {\n // Lazy by design: an empty key must not throw at construction time (CI builds\n // with empty envs import this module transitively). Failures surface on first call.\n // The hosted DeepKey API is the only supported origin. The internal override\n // exists for DeepKey's console and tests and is not part of the public contract.\n this.baseUrl = resolveBaseUrl(options.__internalBaseUrl)\n this.apikey = publishableKey ?? ''\n this.persistSession = options.persistSession ?? true\n this.autoRefreshToken = options.autoRefreshToken ?? true\n this.detectSessionInUrl = options.detectSessionInUrl ?? true\n this.storage = options.storage ?? defaultStorage()\n this.storageKey = options.storageKey ?? deriveStorageKey(publishableKey)\n this.fetchImpl = options.fetch\n\n this.setupCrossTabSync()\n }\n\n // ---- public API (supabase-js compatible) ----\n\n async signInWithOtp(credentials: SignInWithOtpCredentials): Promise<AuthResponse<{ user: null; session: null }>> {\n const { error } = await this.request<Record<string, never>>('POST', '/auth/v1/otp', {\n email: credentials.email,\n create_user: credentials.options?.shouldCreateUser,\n redirect_to: credentials.options?.emailRedirectTo,\n })\n return { data: { user: null, session: null }, error }\n }\n\n async verifyOtp(params: VerifyOtpParams): Promise<AuthResponse<{ user: User | null; session: Session | null }>> {\n const { data, error } = await this.request<Session>('POST', '/auth/v1/verify', {\n type: 'email',\n email: params.email,\n token: params.token,\n })\n if (error || !data) return { data: { user: null, session: null }, error }\n\n await this.saveSession(data)\n this.emit('SIGNED_IN', data)\n return { data: { user: data.user, session: data }, error: null }\n }\n\n async signInWithOAuth(\n credentials: SignInWithOAuthCredentials,\n ): Promise<AuthResponse<{ provider: string; url: string }>> {\n const url = new URL(`${this.baseUrl}/auth/v1/authorize`)\n url.searchParams.set('provider', credentials.provider)\n url.searchParams.set('apikey', this.apikey)\n if (credentials.options?.redirectTo) url.searchParams.set('redirect_to', credentials.options.redirectTo)\n if (credentials.options?.scopes) url.searchParams.set('scopes', credentials.options.scopes)\n for (const [key, value] of Object.entries(credentials.options?.queryParams ?? {})) {\n url.searchParams.set(key, value)\n }\n\n if (!credentials.options?.skipBrowserRedirect && typeof window !== 'undefined') {\n window.location.assign(url.toString())\n }\n return { data: { provider: credentials.provider, url: url.toString() }, error: null }\n }\n\n onAuthStateChange(callback: Listener): { data: { subscription: Subscription } } {\n const id = `listener-${++this.listenerSeq}`\n this.listeners.set(id, callback)\n\n // Every subscriber receives INITIAL_SESSION asynchronously once initialization\n // settles — the supabase-js contract that AuthProviders rely on to resolve loading.\n this.initialize().then(() => {\n if (this.listeners.has(id)) callback('INITIAL_SESSION', this.session)\n })\n\n return {\n data: {\n subscription: {\n id,\n unsubscribe: () => {\n this.listeners.delete(id)\n },\n },\n },\n }\n }\n\n async signOut(): Promise<{ error: AuthError | null }> {\n await this.initialize()\n const session = this.session\n if (session) {\n // Best-effort server-side revocation; local sign-out always succeeds.\n await this.request('POST', '/auth/v1/logout', {}, session.access_token)\n }\n this.clearSession()\n this.emit('SIGNED_OUT', null)\n return { error: null }\n }\n\n async getSession(): Promise<AuthResponse<{ session: Session | null }>> {\n await this.initialize()\n\n if (this.session && this.isExpired(this.session) && this.autoRefreshToken) {\n const { error } = await this.refreshWithLock()\n if (error && error.code !== 'network_error') {\n return { data: { session: null }, error: null }\n }\n }\n\n return { data: { session: this.session }, error: null }\n }\n\n async getUser(jwt?: string): Promise<AuthResponse<{ user: User | null }>> {\n let token = jwt\n if (!token) {\n const {\n data: { session },\n } = await this.getSession()\n token = session?.access_token\n }\n if (!token) {\n return { data: { user: null }, error: new AuthError('Auth session missing!', 400, 'session_missing') }\n }\n\n const { data, error } = await this.request<User>('GET', '/auth/v1/user', undefined, token)\n return { data: { user: data }, error }\n }\n\n async refreshSession(currentSession?: {\n refresh_token: string\n }): Promise<AuthResponse<{ session: Session | null; user: User | null }>> {\n await this.initialize()\n const refreshToken = currentSession?.refresh_token ?? this.session?.refresh_token\n if (!refreshToken) {\n return {\n data: { session: null, user: null },\n error: new AuthError('Auth session missing!', 400, 'session_missing'),\n }\n }\n return this.refreshWithLock(refreshToken)\n }\n\n // ---- internals ----\n\n private async request<T>(method: 'GET' | 'POST', path: string, body?: unknown, accessToken?: string) {\n return request<T>({\n method,\n path,\n body,\n accessToken,\n apikey: this.apikey,\n baseUrl: this.baseUrl,\n fetchImpl: this.fetchImpl,\n })\n }\n\n private initialize(): Promise<void> {\n this.initializePromise ??= this.doInitialize()\n return this.initializePromise\n }\n\n private async doInitialize(): Promise<void> {\n if (this.detectSessionInUrl && typeof window !== 'undefined') {\n const parsed = parseFragment(window.location.hash)\n if (parsed) {\n // Strip tokens from the address bar synchronously, before any await.\n cleanFragmentFromUrl()\n\n if ('authError' in parsed) {\n console.warn(\n `[deepkey] Auth redirect returned an error: ${parsed.authError.error_code ?? parsed.authError.error}`,\n parsed.authError.error_description ?? '',\n )\n } else {\n const { data: user } = await this.request<User>('GET', '/auth/v1/user', undefined, parsed.tokens.access_token)\n if (user) {\n const session: Session = { ...parsed.tokens, token_type: 'bearer', user }\n await this.saveSession(session)\n this.emit('SIGNED_IN', session)\n return\n }\n }\n }\n }\n\n const stored = this.loadStoredSession()\n if (!stored) return\n\n if (this.isExpired(stored)) {\n if (!this.autoRefreshToken) return\n this.session = stored\n const { error } = await this.refreshWithLock()\n if (error && error.code !== 'network_error') this.clearSession()\n return\n }\n\n this.session = stored\n this.startRefreshTimer()\n }\n\n private isExpired(session: Session): boolean {\n return session.expires_at <= Math.floor(Date.now() / 1000) + EXPIRY_MARGIN_SECONDS\n }\n\n private async refreshWithLock(\n refreshToken?: string,\n ): Promise<AuthResponse<{ session: Session | null; user: User | null }>> {\n this.refreshPromise ??= this.doRefresh(refreshToken).finally(() => {\n this.refreshPromise = null\n })\n return this.refreshPromise\n }\n\n private async doRefresh(\n refreshToken?: string,\n ): Promise<AuthResponse<{ session: Session | null; user: User | null }>> {\n const token = refreshToken ?? this.session?.refresh_token\n if (!token) {\n return {\n data: { session: null, user: null },\n error: new AuthError('Auth session missing!', 400, 'session_missing'),\n }\n }\n\n const { data, error } = await this.request<Session>('POST', '/auth/v1/token?grant_type=refresh_token', {\n refresh_token: token,\n })\n\n if (error) {\n // Network failures keep the session (retry next tick); auth failures clear it.\n if (error.code !== 'network_error') {\n this.clearSession()\n this.emit('SIGNED_OUT', null)\n }\n return { data: { session: null, user: null }, error }\n }\n\n if (data) {\n await this.saveSession(data)\n this.emit('TOKEN_REFRESHED', data)\n return { data: { session: data, user: data.user }, error: null }\n }\n return { data: { session: null, user: null }, error: new AuthError('Empty refresh response') }\n }\n\n private async saveSession(session: Session) {\n this.session = session\n if (this.persistSession) {\n try {\n this.storage.setItem(this.storageKey, JSON.stringify(session))\n } catch {\n // Persistence is best-effort (private mode, quota).\n }\n }\n this.startRefreshTimer()\n }\n\n private clearSession() {\n this.session = null\n try {\n this.storage.removeItem(this.storageKey)\n } catch {\n // ignore\n }\n this.stopRefreshTimer()\n }\n\n private loadStoredSession(): Session | null {\n if (!this.persistSession) return null\n try {\n const raw = this.storage.getItem(this.storageKey)\n if (!raw) return null\n const parsed = JSON.parse(raw) as Session\n if (!parsed.access_token || !parsed.refresh_token) return null\n return parsed\n } catch {\n return null\n }\n }\n\n private startRefreshTimer() {\n if (!this.autoRefreshToken || this.refreshTimer || typeof setInterval === 'undefined') return\n this.refreshTimer = setInterval(() => {\n if (this.session && this.isExpired(this.session)) void this.refreshWithLock()\n }, REFRESH_TICK_MS)\n // Do not keep node processes alive because of the timer (no-op in browsers).\n const timer = this.refreshTimer as unknown as { unref?: () => void }\n if (typeof timer === 'object' && typeof timer.unref === 'function') timer.unref()\n }\n\n private stopRefreshTimer() {\n if (this.refreshTimer) {\n clearInterval(this.refreshTimer)\n this.refreshTimer = null\n }\n }\n\n private setupCrossTabSync() {\n if (typeof window === 'undefined' || !this.persistSession) return\n window.addEventListener('storage', event => {\n if (event.key !== this.storageKey) return\n if (!event.newValue) {\n if (this.session) {\n this.session = null\n this.stopRefreshTimer()\n this.emit('SIGNED_OUT', null)\n }\n return\n }\n try {\n const next = JSON.parse(event.newValue) as Session\n const changed = next.access_token !== this.session?.access_token\n this.session = next\n this.startRefreshTimer()\n if (changed) this.emit('TOKEN_REFRESHED', next)\n } catch {\n // ignore malformed writes\n }\n })\n }\n\n private emit(event: AuthChangeEvent, session: Session | null) {\n for (const listener of this.listeners.values()) {\n try {\n listener(event, session)\n } catch (err) {\n console.error('[deepkey] onAuthStateChange listener threw', err)\n }\n }\n }\n}\n\nexport interface AuthClient {\n auth: Auth\n connections: Connections\n}\n\nexport const createAuthClient = (publishableKey: string, options?: AuthClientOptions): AuthClient => {\n const auth = new Auth(publishableKey, options)\n const connections = new Connections(auth, {\n apikey: publishableKey ?? '',\n baseUrl: resolveBaseUrl(options?.__internalBaseUrl),\n fetchImpl: options?.fetch,\n })\n return { auth, connections }\n}\n"],"m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B,YAA4C;AACnG,QAAM,OAAO,IAAI,KAAK,gBAAgB,OAAO;AAC7C,QAAM,cAAc,IAAI,YAAY,MAAM;AAAA,IACxC,QAAQ,kBAAkB;AAAA,IAC1B,SAAS,eAAe,SAAS,iBAAiB;AAAA,IAClD,WAAW,SAAS;AAAA,EACtB,CAAC;AACD,SAAO,EAAE,MAAM,YAAY;AAC7B;","names":[]}
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { C as ConnectProviderCredentials, A as AuthResponse, P as ProviderConnection, a as AuthError, b as AuthClientOptions, S as SignInWithOtpCredentials, V as VerifyOtpParams, U as User, c as Session, d as SignInWithOAuthCredentials, e as AuthChangeEvent, f as Subscription } from './constants-DgChFH24.cjs';
2
- export { D as DEEPKEY_API_URL, g as ProviderAccessToken, h as ServerClientOptions, i as StorageAdapter, j as UserIdentity } from './constants-DgChFH24.cjs';
1
+ import { C as ConnectProviderCredentials, A as AuthResponse, P as ProviderConnection, a as AuthError, b as AuthClientOptions, S as SignInWithOtpCredentials, V as VerifyOtpParams, U as User, c as Session, d as SignInWithOAuthCredentials, e as AuthChangeEvent, f as Subscription } from './constants-ByCalul7.cjs';
2
+ export { D as DEEPKEY_API_URL, g as ProviderAccessToken, h as ServerClientOptions, i as StorageAdapter, j as UserApiKey, k as UserIdentity } from './constants-ByCalul7.cjs';
3
3
 
4
4
  interface ConnectionsOptions {
5
5
  apikey: string;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { C as ConnectProviderCredentials, A as AuthResponse, P as ProviderConnection, a as AuthError, b as AuthClientOptions, S as SignInWithOtpCredentials, V as VerifyOtpParams, U as User, c as Session, d as SignInWithOAuthCredentials, e as AuthChangeEvent, f as Subscription } from './constants-DgChFH24.js';
2
- export { D as DEEPKEY_API_URL, g as ProviderAccessToken, h as ServerClientOptions, i as StorageAdapter, j as UserIdentity } from './constants-DgChFH24.js';
1
+ import { C as ConnectProviderCredentials, A as AuthResponse, P as ProviderConnection, a as AuthError, b as AuthClientOptions, S as SignInWithOtpCredentials, V as VerifyOtpParams, U as User, c as Session, d as SignInWithOAuthCredentials, e as AuthChangeEvent, f as Subscription } from './constants-ByCalul7.js';
2
+ export { D as DEEPKEY_API_URL, g as ProviderAccessToken, h as ServerClientOptions, i as StorageAdapter, j as UserApiKey, k as UserIdentity } from './constants-ByCalul7.js';
3
3
 
4
4
  interface ConnectionsOptions {
5
5
  apikey: string;
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  DEEPKEY_API_URL,
4
4
  request,
5
5
  resolveBaseUrl
6
- } from "./chunk-A2CRUXTA.js";
6
+ } from "./chunk-J4IK2N4V.js";
7
7
 
8
8
  // src/connections.ts
9
9
  var Connections = class {
package/dist/server.cjs CHANGED
@@ -112,6 +112,43 @@ var createServerClient = (secretKey, options = {}) => {
112
112
  const { error } = await request({ ...base, method: "DELETE", path: connection(connectionId) });
113
113
  return { error };
114
114
  }
115
+ },
116
+ apiKeys: {
117
+ async create({ userId, name }) {
118
+ const { data, error } = await request({
119
+ ...base,
120
+ method: "POST",
121
+ path: "/auth/v1/api-keys",
122
+ body: { user_id: userId, name }
123
+ });
124
+ return { data: { apiKey: data?.api_key ?? null, key: data?.key ?? null }, error };
125
+ },
126
+ async list({ userId }) {
127
+ const { data, error } = await request({
128
+ ...base,
129
+ method: "GET",
130
+ path: `/auth/v1/api-keys?user_id=${encodeURIComponent(userId)}`
131
+ });
132
+ return { data: { apiKeys: data?.api_keys ?? [] }, error };
133
+ },
134
+ async revoke(apiKeyId) {
135
+ const { error } = await request({
136
+ ...base,
137
+ method: "DELETE",
138
+ path: `/auth/v1/api-keys/${encodeURIComponent(apiKeyId)}`
139
+ });
140
+ return { error };
141
+ },
142
+ // The key travels in the request body so it never reaches a URL or an access log.
143
+ async verify(apiKey) {
144
+ const { data, error } = await request({
145
+ ...base,
146
+ method: "POST",
147
+ path: "/auth/v1/api-keys/verify",
148
+ body: { api_key: apiKey }
149
+ });
150
+ return { data: { user: data?.user ?? null, apiKey: data?.api_key ?? null }, error };
151
+ }
115
152
  }
116
153
  };
117
154
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server.ts","../src/constants.ts","../src/types.ts","../src/fetch.ts"],"sourcesContent":["import { resolveBaseUrl } from './constants'\nimport { request } from './fetch'\nimport type {\n AuthError,\n AuthResponse,\n ProviderAccessToken,\n ProviderConnection,\n ServerClientOptions,\n User,\n} from './types'\n\nexport interface ServerAuthClient {\n auth: {\n // Mirrors `supabase.auth.getUser(jwt)` server-side: validates the access token\n // against the auth service and returns the user.\n getUser(jwt: string): Promise<AuthResponse<{ user: User | null }>>\n }\n // Provider connections a user granted through the browser SDK. The secret key acts\n // for the whole project; provider access tokens are issued only here, never to browsers.\n connections: {\n list(params: { userId: string }): Promise<AuthResponse<{ connections: ProviderConnection[] }>>\n issueAccessToken(connectionId: string): Promise<AuthResponse<ProviderAccessToken | null>>\n revoke(connectionId: string): Promise<{ error: AuthError | null }>\n }\n}\n\n// Runs anywhere with global fetch (Bun, Node >= 18). `secretKey` is the project's\n// bt_secret_... key. Requests target the hosted DeepKey API; the internal\n// override is reserved for DeepKey's console and tests.\nexport const createServerClient = (secretKey: string, options: ServerClientOptions = {}): ServerAuthClient => {\n const base = { apikey: secretKey, baseUrl: resolveBaseUrl(options.__internalBaseUrl), fetchImpl: options.fetch }\n const connection = (id: string) => `/auth/v1/connections/${encodeURIComponent(id)}`\n\n return {\n auth: {\n async getUser(jwt: string) {\n const { data, error } = await request<User>({ ...base, method: 'GET', path: '/auth/v1/user', accessToken: jwt })\n return { data: { user: data }, error }\n },\n },\n connections: {\n async list({ userId }) {\n const { data, error } = await request<{ connections: ProviderConnection[] }>({\n ...base,\n method: 'GET',\n path: `/auth/v1/connections?user_id=${encodeURIComponent(userId)}`,\n })\n return { data: { connections: data?.connections ?? [] }, error }\n },\n async issueAccessToken(connectionId) {\n return request<ProviderAccessToken>({\n ...base,\n method: 'POST',\n path: `${connection(connectionId)}/token`,\n body: {},\n })\n },\n async revoke(connectionId) {\n const { error } = await request({ ...base, method: 'DELETE', path: connection(connectionId) })\n return { error }\n },\n },\n }\n}\n\nexport { DEEPKEY_API_URL } from './constants'\nexport {\n AuthError,\n type AuthResponse,\n type ProviderAccessToken,\n type ProviderConnection,\n type ServerClientOptions,\n type User,\n} from './types'\n","// The hosted DeepKey API. Every client talks to this origin; only DeepKey's own\n// console and test suites replace it through the internal override.\nexport const DEEPKEY_API_URL = 'https://deepkey.dev/api'\n\n// Resolves the base URL used for every request. An absent or blank internal\n// override keeps the hosted API; a provided value has any trailing slash removed\n// so path joins stay predictable.\nexport const resolveBaseUrl = (url?: string | null): string => {\n const candidate = typeof url === 'string' ? url.trim() : ''\n return (candidate || DEEPKEY_API_URL).replace(/\\/+$/, '')\n}\n","export interface UserIdentity {\n identity_id: string\n id: string\n user_id: string\n provider: string\n identity_data: Record<string, unknown>\n last_sign_in_at: string | null\n created_at: string\n updated_at: string\n}\n\nexport interface User {\n id: string\n aud: string\n role: string\n email: string | null\n email_confirmed_at: string | null\n app_metadata: { provider?: string | null; providers?: string[]; [key: string]: unknown }\n user_metadata: {\n name?: string\n full_name?: string\n avatar_url?: string\n picture?: string\n email?: string\n [key: string]: unknown\n }\n identities?: UserIdentity[]\n created_at: string\n updated_at?: string\n last_sign_in_at?: string | null\n}\n\nexport interface Session {\n access_token: string\n refresh_token: string\n token_type: 'bearer'\n expires_in: number\n expires_at: number\n user: User\n}\n\nexport class AuthError extends Error {\n status?: number\n code?: string\n\n constructor(message: string, status?: number, code?: string) {\n super(message)\n this.name = 'AuthError'\n this.status = status\n this.code = code\n }\n}\n\nexport type AuthChangeEvent = 'INITIAL_SESSION' | 'SIGNED_IN' | 'SIGNED_OUT' | 'TOKEN_REFRESHED'\n\nexport interface Subscription {\n id: string\n unsubscribe: () => void\n}\n\nexport interface StorageAdapter {\n getItem(key: string): string | null\n setItem(key: string, value: string): void\n removeItem(key: string): void\n}\n\nexport interface AuthClientOptions {\n /**\n * @internal Replaces the hosted DeepKey API origin. Used only by DeepKey's own\n * console and test suites; not supported for consumers and stripped from the\n * published type declarations.\n */\n __internalBaseUrl?: string\n storageKey?: string\n autoRefreshToken?: boolean\n detectSessionInUrl?: boolean\n persistSession?: boolean\n storage?: StorageAdapter\n fetch?: typeof fetch\n}\n\nexport interface ServerClientOptions {\n /**\n * @internal Replaces the hosted DeepKey API origin. Used only by DeepKey's own\n * console and test suites; not supported for consumers and stripped from the\n * published type declarations.\n */\n __internalBaseUrl?: string\n fetch?: typeof fetch\n}\n\nexport interface SignInWithOtpCredentials {\n email: string\n options?: {\n emailRedirectTo?: string\n shouldCreateUser?: boolean\n data?: Record<string, unknown>\n }\n}\n\nexport interface VerifyOtpParams {\n email: string\n token: string\n type: 'email' | 'magiclink'\n}\n\nexport interface ConnectProviderCredentials {\n provider: string\n options?: {\n redirectTo?: string\n skipBrowserRedirect?: boolean\n }\n}\n\n// Metadata only: provider tokens never appear in browser responses.\nexport interface ProviderConnection {\n id: string\n // The DeepKey user that granted the connection: the same `user.id` your server gets from getUser(jwt).\n user_id: string\n provider: string\n provider_user_id: string\n identity_data: Record<string, unknown>\n scope: string | null\n status: 'active' | 'reauthorization_required'\n created_at: string\n updated_at: string\n}\n\n// Issued to consumer servers through the secret key; short-lived and refreshed by DeepKey.\nexport interface ProviderAccessToken {\n access_token: string\n token_type: 'bearer'\n expires_at: number | null\n scope: string | null\n}\n\nexport interface SignInWithOAuthCredentials {\n provider: string\n options?: {\n redirectTo?: string\n scopes?: string\n queryParams?: Record<string, string>\n skipBrowserRedirect?: boolean\n }\n}\n\nexport interface AuthResponse<T> {\n data: T\n error: AuthError | null\n}\n","import { AuthError } from './types'\n\nexport interface RequestOptions {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE'\n path: string\n apikey: string\n baseUrl: string\n accessToken?: string\n body?: unknown\n fetchImpl?: typeof fetch\n}\n\nexport interface RequestResult<T> {\n data: T | null\n error: AuthError | null\n}\n\n// All service errors are shaped { error: { code, message } }.\nexport const request = async <T>(options: RequestOptions): Promise<RequestResult<T>> => {\n const fetchImpl = options.fetchImpl ?? fetch\n try {\n const headers: Record<string, string> = { apikey: options.apikey }\n if (options.body !== undefined) headers['Content-Type'] = 'application/json'\n if (options.accessToken) headers.Authorization = `Bearer ${options.accessToken}`\n\n const response = await fetchImpl(`${options.baseUrl}${options.path}`, {\n method: options.method,\n headers,\n body: options.body !== undefined ? JSON.stringify(options.body) : undefined,\n })\n\n if (response.status === 204) return { data: {} as T, error: null }\n\n let payload: unknown\n try {\n payload = await response.json()\n } catch {\n payload = null\n }\n\n if (!response.ok) {\n const errorBody = (payload as { error?: { code?: string; message?: string } } | null)?.error\n return {\n data: null,\n error: new AuthError(\n errorBody?.message ?? `Request failed with status ${response.status}`,\n response.status,\n errorBody?.code,\n ),\n }\n }\n\n return { data: payload as T, error: null }\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Network request failed'\n return { data: null, error: new AuthError(message, 0, 'network_error') }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,IAAM,kBAAkB;AAKxB,IAAM,iBAAiB,CAAC,QAAgC;AAC7D,QAAM,YAAY,OAAO,QAAQ,WAAW,IAAI,KAAK,IAAI;AACzD,UAAQ,aAAa,iBAAiB,QAAQ,QAAQ,EAAE;AAC1D;;;AC+BO,IAAM,YAAN,cAAwB,MAAM;AAAA,EAInC,YAAY,SAAiB,QAAiB,MAAe;AAC3D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EACd;AACF;;;ACjCO,IAAM,UAAU,OAAU,YAAuD;AACtF,QAAM,YAAY,QAAQ,aAAa;AACvC,MAAI;AACF,UAAM,UAAkC,EAAE,QAAQ,QAAQ,OAAO;AACjE,QAAI,QAAQ,SAAS,OAAW,SAAQ,cAAc,IAAI;AAC1D,QAAI,QAAQ,YAAa,SAAQ,gBAAgB,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,GAAG,MAAM;AAAA,MACvC;AAAA,IACF;AAAA,IACA,aAAa;AAAA,MACX,MAAM,KAAK,EAAE,OAAO,GAAG;AACrB,cAAM,EAAE,MAAM,MAAM,IAAI,MAAM,QAA+C;AAAA,UAC3E,GAAG;AAAA,UACH,QAAQ;AAAA,UACR,MAAM,gCAAgC,mBAAmB,MAAM,CAAC;AAAA,QAClE,CAAC;AACD,eAAO,EAAE,MAAM,EAAE,aAAa,MAAM,eAAe,CAAC,EAAE,GAAG,MAAM;AAAA,MACjE;AAAA,MACA,MAAM,iBAAiB,cAAc;AACnC,eAAO,QAA6B;AAAA,UAClC,GAAG;AAAA,UACH,QAAQ;AAAA,UACR,MAAM,GAAG,WAAW,YAAY,CAAC;AAAA,UACjC,MAAM,CAAC;AAAA,QACT,CAAC;AAAA,MACH;AAAA,MACA,MAAM,OAAO,cAAc;AACzB,cAAM,EAAE,MAAM,IAAI,MAAM,QAAQ,EAAE,GAAG,MAAM,QAAQ,UAAU,MAAM,WAAW,YAAY,EAAE,CAAC;AAC7F,eAAO,EAAE,MAAM;AAAA,MACjB;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/server.ts","../src/constants.ts","../src/types.ts","../src/fetch.ts"],"sourcesContent":["import { resolveBaseUrl } from './constants'\nimport { request } from './fetch'\nimport type {\n AuthError,\n AuthResponse,\n ProviderAccessToken,\n ProviderConnection,\n ServerClientOptions,\n User,\n UserApiKey,\n} from './types'\n\nexport interface ServerAuthClient {\n auth: {\n // Mirrors `supabase.auth.getUser(jwt)` server-side: validates the access token\n // against the auth service and returns the user.\n getUser(jwt: string): Promise<AuthResponse<{ user: User | null }>>\n }\n // Provider connections a user granted through the browser SDK. The secret key acts\n // for the whole project; provider access tokens are issued only here, never to browsers.\n connections: {\n list(params: { userId: string }): Promise<AuthResponse<{ connections: ProviderConnection[] }>>\n issueAccessToken(connectionId: string): Promise<AuthResponse<ProviderAccessToken | null>>\n revoke(connectionId: string): Promise<{ error: AuthError | null }>\n }\n // Long-lived keys your application issues to its own users. Every call uses the secret\n // key; `verify` is the API-key counterpart of `auth.getUser(jwt)` and returns the same user.\n apiKeys: {\n // `key` is the plaintext. It is returned here once and cannot be read again.\n create(params: {\n userId: string\n name?: string\n }): Promise<AuthResponse<{ apiKey: UserApiKey | null; key: string | null }>>\n list(params: { userId: string }): Promise<AuthResponse<{ apiKeys: UserApiKey[] }>>\n revoke(apiKeyId: string): Promise<{ error: AuthError | null }>\n verify(apiKey: string): Promise<AuthResponse<{ user: User | null; apiKey: UserApiKey | null }>>\n }\n}\n\n// Runs anywhere with global fetch (Bun, Node >= 18). `secretKey` is the project's\n// bt_secret_... key. Requests target the hosted DeepKey API; the internal\n// override is reserved for DeepKey's console and tests.\nexport const createServerClient = (secretKey: string, options: ServerClientOptions = {}): ServerAuthClient => {\n const base = { apikey: secretKey, baseUrl: resolveBaseUrl(options.__internalBaseUrl), fetchImpl: options.fetch }\n const connection = (id: string) => `/auth/v1/connections/${encodeURIComponent(id)}`\n\n return {\n auth: {\n async getUser(jwt: string) {\n const { data, error } = await request<User>({ ...base, method: 'GET', path: '/auth/v1/user', accessToken: jwt })\n return { data: { user: data }, error }\n },\n },\n connections: {\n async list({ userId }) {\n const { data, error } = await request<{ connections: ProviderConnection[] }>({\n ...base,\n method: 'GET',\n path: `/auth/v1/connections?user_id=${encodeURIComponent(userId)}`,\n })\n return { data: { connections: data?.connections ?? [] }, error }\n },\n async issueAccessToken(connectionId) {\n return request<ProviderAccessToken>({\n ...base,\n method: 'POST',\n path: `${connection(connectionId)}/token`,\n body: {},\n })\n },\n async revoke(connectionId) {\n const { error } = await request({ ...base, method: 'DELETE', path: connection(connectionId) })\n return { error }\n },\n },\n apiKeys: {\n async create({ userId, name }) {\n const { data, error } = await request<{ api_key: UserApiKey; key: string }>({\n ...base,\n method: 'POST',\n path: '/auth/v1/api-keys',\n body: { user_id: userId, name },\n })\n return { data: { apiKey: data?.api_key ?? null, key: data?.key ?? null }, error }\n },\n async list({ userId }) {\n const { data, error } = await request<{ api_keys: UserApiKey[] }>({\n ...base,\n method: 'GET',\n path: `/auth/v1/api-keys?user_id=${encodeURIComponent(userId)}`,\n })\n return { data: { apiKeys: data?.api_keys ?? [] }, error }\n },\n async revoke(apiKeyId) {\n const { error } = await request({\n ...base,\n method: 'DELETE',\n path: `/auth/v1/api-keys/${encodeURIComponent(apiKeyId)}`,\n })\n return { error }\n },\n // The key travels in the request body so it never reaches a URL or an access log.\n async verify(apiKey) {\n const { data, error } = await request<{ user: User; api_key: UserApiKey }>({\n ...base,\n method: 'POST',\n path: '/auth/v1/api-keys/verify',\n body: { api_key: apiKey },\n })\n return { data: { user: data?.user ?? null, apiKey: data?.api_key ?? null }, error }\n },\n },\n }\n}\n\nexport { DEEPKEY_API_URL } from './constants'\nexport {\n AuthError,\n type AuthResponse,\n type ProviderAccessToken,\n type ProviderConnection,\n type ServerClientOptions,\n type User,\n type UserApiKey,\n} from './types'\n","// The hosted DeepKey API. Every client talks to this origin; only DeepKey's own\n// console and test suites replace it through the internal override.\nexport const DEEPKEY_API_URL = 'https://deepkey.dev/api'\n\n// Resolves the base URL used for every request. An absent or blank internal\n// override keeps the hosted API; a provided value has any trailing slash removed\n// so path joins stay predictable.\nexport const resolveBaseUrl = (url?: string | null): string => {\n const candidate = typeof url === 'string' ? url.trim() : ''\n return (candidate || DEEPKEY_API_URL).replace(/\\/+$/, '')\n}\n","export interface UserIdentity {\n identity_id: string\n id: string\n user_id: string\n provider: string\n identity_data: Record<string, unknown>\n last_sign_in_at: string | null\n created_at: string\n updated_at: string\n}\n\nexport interface User {\n id: string\n aud: string\n role: string\n email: string | null\n email_confirmed_at: string | null\n app_metadata: { provider?: string | null; providers?: string[]; [key: string]: unknown }\n user_metadata: {\n name?: string\n full_name?: string\n avatar_url?: string\n picture?: string\n email?: string\n [key: string]: unknown\n }\n identities?: UserIdentity[]\n created_at: string\n updated_at?: string\n last_sign_in_at?: string | null\n}\n\nexport interface Session {\n access_token: string\n refresh_token: string\n token_type: 'bearer'\n expires_in: number\n expires_at: number\n user: User\n}\n\nexport class AuthError extends Error {\n status?: number\n code?: string\n\n constructor(message: string, status?: number, code?: string) {\n super(message)\n this.name = 'AuthError'\n this.status = status\n this.code = code\n }\n}\n\nexport type AuthChangeEvent = 'INITIAL_SESSION' | 'SIGNED_IN' | 'SIGNED_OUT' | 'TOKEN_REFRESHED'\n\nexport interface Subscription {\n id: string\n unsubscribe: () => void\n}\n\nexport interface StorageAdapter {\n getItem(key: string): string | null\n setItem(key: string, value: string): void\n removeItem(key: string): void\n}\n\nexport interface AuthClientOptions {\n /**\n * @internal Replaces the hosted DeepKey API origin. Used only by DeepKey's own\n * console and test suites; not supported for consumers and stripped from the\n * published type declarations.\n */\n __internalBaseUrl?: string\n storageKey?: string\n autoRefreshToken?: boolean\n detectSessionInUrl?: boolean\n persistSession?: boolean\n storage?: StorageAdapter\n fetch?: typeof fetch\n}\n\nexport interface ServerClientOptions {\n /**\n * @internal Replaces the hosted DeepKey API origin. Used only by DeepKey's own\n * console and test suites; not supported for consumers and stripped from the\n * published type declarations.\n */\n __internalBaseUrl?: string\n fetch?: typeof fetch\n}\n\nexport interface SignInWithOtpCredentials {\n email: string\n options?: {\n emailRedirectTo?: string\n shouldCreateUser?: boolean\n data?: Record<string, unknown>\n }\n}\n\nexport interface VerifyOtpParams {\n email: string\n token: string\n type: 'email' | 'magiclink'\n}\n\nexport interface ConnectProviderCredentials {\n provider: string\n options?: {\n redirectTo?: string\n skipBrowserRedirect?: boolean\n }\n}\n\n// Metadata only: provider tokens never appear in browser responses.\nexport interface ProviderConnection {\n id: string\n // The DeepKey user that granted the connection: the same `user.id` your server gets from getUser(jwt).\n user_id: string\n provider: string\n provider_user_id: string\n identity_data: Record<string, unknown>\n scope: string | null\n status: 'active' | 'reauthorization_required'\n created_at: string\n updated_at: string\n}\n\n// Issued to consumer servers through the secret key; short-lived and refreshed by DeepKey.\nexport interface ProviderAccessToken {\n access_token: string\n token_type: 'bearer'\n expires_at: number | null\n scope: string | null\n}\n\n// A long-lived credential your application issues to one of its users. Not the project\n// key: the plaintext is returned once by `apiKeys.create` and is never readable again.\nexport interface UserApiKey {\n id: string\n // The DeepKey user the key acts for: the same `user.id` your server gets from getUser(jwt).\n user_id: string\n name: string | null\n // Last four characters of the plaintext, for display.\n last4: string\n // Last successful `apiKeys.verify`; null until the key is used.\n last_used_at: string | null\n // Set once the key is revoked; a revoked key never verifies again.\n revoked_at: string | null\n created_at: string\n}\n\nexport interface SignInWithOAuthCredentials {\n provider: string\n options?: {\n redirectTo?: string\n scopes?: string\n queryParams?: Record<string, string>\n skipBrowserRedirect?: boolean\n }\n}\n\nexport interface AuthResponse<T> {\n data: T\n error: AuthError | null\n}\n","import { AuthError } from './types'\n\nexport interface RequestOptions {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE'\n path: string\n apikey: string\n baseUrl: string\n accessToken?: string\n body?: unknown\n fetchImpl?: typeof fetch\n}\n\nexport interface RequestResult<T> {\n data: T | null\n error: AuthError | null\n}\n\n// All service errors are shaped { error: { code, message } }.\nexport const request = async <T>(options: RequestOptions): Promise<RequestResult<T>> => {\n const fetchImpl = options.fetchImpl ?? fetch\n try {\n const headers: Record<string, string> = { apikey: options.apikey }\n if (options.body !== undefined) headers['Content-Type'] = 'application/json'\n if (options.accessToken) headers.Authorization = `Bearer ${options.accessToken}`\n\n const response = await fetchImpl(`${options.baseUrl}${options.path}`, {\n method: options.method,\n headers,\n body: options.body !== undefined ? JSON.stringify(options.body) : undefined,\n })\n\n if (response.status === 204) return { data: {} as T, error: null }\n\n let payload: unknown\n try {\n payload = await response.json()\n } catch {\n payload = null\n }\n\n if (!response.ok) {\n const errorBody = (payload as { error?: { code?: string; message?: string } } | null)?.error\n return {\n data: null,\n error: new AuthError(\n errorBody?.message ?? `Request failed with status ${response.status}`,\n response.status,\n errorBody?.code,\n ),\n }\n }\n\n return { data: payload as T, error: null }\n } catch (err) {\n const message = err instanceof Error ? err.message : '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,MACpF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
package/dist/server.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as AuthResponse, U as User, P as ProviderConnection, g as ProviderAccessToken, a as AuthError, h as ServerClientOptions } from './constants-DgChFH24.cjs';
2
- export { D as DEEPKEY_API_URL } from './constants-DgChFH24.cjs';
1
+ import { A as AuthResponse, U as User, P as ProviderConnection, g as ProviderAccessToken, a as AuthError, j as UserApiKey, h as ServerClientOptions } from './constants-ByCalul7.cjs';
2
+ export { D as DEEPKEY_API_URL } from './constants-ByCalul7.cjs';
3
3
 
4
4
  interface ServerAuthClient {
5
5
  auth: {
@@ -18,7 +18,28 @@ interface ServerAuthClient {
18
18
  error: AuthError | null;
19
19
  }>;
20
20
  };
21
+ apiKeys: {
22
+ create(params: {
23
+ userId: string;
24
+ name?: string;
25
+ }): Promise<AuthResponse<{
26
+ apiKey: UserApiKey | null;
27
+ key: string | null;
28
+ }>>;
29
+ list(params: {
30
+ userId: string;
31
+ }): Promise<AuthResponse<{
32
+ apiKeys: UserApiKey[];
33
+ }>>;
34
+ revoke(apiKeyId: string): Promise<{
35
+ error: AuthError | null;
36
+ }>;
37
+ verify(apiKey: string): Promise<AuthResponse<{
38
+ user: User | null;
39
+ apiKey: UserApiKey | null;
40
+ }>>;
41
+ };
21
42
  }
22
43
  declare const createServerClient: (secretKey: string, options?: ServerClientOptions) => ServerAuthClient;
23
44
 
24
- export { AuthError, AuthResponse, ProviderAccessToken, ProviderConnection, type ServerAuthClient, ServerClientOptions, User, createServerClient };
45
+ export { AuthError, AuthResponse, ProviderAccessToken, ProviderConnection, type ServerAuthClient, ServerClientOptions, User, UserApiKey, createServerClient };
package/dist/server.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as AuthResponse, U as User, P as ProviderConnection, g as ProviderAccessToken, a as AuthError, h as ServerClientOptions } from './constants-DgChFH24.js';
2
- export { D as DEEPKEY_API_URL } from './constants-DgChFH24.js';
1
+ import { A as AuthResponse, U as User, P as ProviderConnection, g as ProviderAccessToken, a as AuthError, j as UserApiKey, h as ServerClientOptions } from './constants-ByCalul7.js';
2
+ export { D as DEEPKEY_API_URL } from './constants-ByCalul7.js';
3
3
 
4
4
  interface ServerAuthClient {
5
5
  auth: {
@@ -18,7 +18,28 @@ interface ServerAuthClient {
18
18
  error: AuthError | null;
19
19
  }>;
20
20
  };
21
+ apiKeys: {
22
+ create(params: {
23
+ userId: string;
24
+ name?: string;
25
+ }): Promise<AuthResponse<{
26
+ apiKey: UserApiKey | null;
27
+ key: string | null;
28
+ }>>;
29
+ list(params: {
30
+ userId: string;
31
+ }): Promise<AuthResponse<{
32
+ apiKeys: UserApiKey[];
33
+ }>>;
34
+ revoke(apiKeyId: string): Promise<{
35
+ error: AuthError | null;
36
+ }>;
37
+ verify(apiKey: string): Promise<AuthResponse<{
38
+ user: User | null;
39
+ apiKey: UserApiKey | null;
40
+ }>>;
41
+ };
21
42
  }
22
43
  declare const createServerClient: (secretKey: string, options?: ServerClientOptions) => ServerAuthClient;
23
44
 
24
- export { AuthError, AuthResponse, ProviderAccessToken, ProviderConnection, type ServerAuthClient, ServerClientOptions, User, createServerClient };
45
+ export { AuthError, AuthResponse, ProviderAccessToken, ProviderConnection, type ServerAuthClient, ServerClientOptions, User, UserApiKey, createServerClient };
package/dist/server.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  DEEPKEY_API_URL,
4
4
  request,
5
5
  resolveBaseUrl
6
- } from "./chunk-A2CRUXTA.js";
6
+ } from "./chunk-J4IK2N4V.js";
7
7
 
8
8
  // src/server.ts
9
9
  var createServerClient = (secretKey, options = {}) => {
@@ -37,6 +37,43 @@ var createServerClient = (secretKey, options = {}) => {
37
37
  const { error } = await request({ ...base, method: "DELETE", path: connection(connectionId) });
38
38
  return { error };
39
39
  }
40
+ },
41
+ apiKeys: {
42
+ async create({ userId, name }) {
43
+ const { data, error } = await request({
44
+ ...base,
45
+ method: "POST",
46
+ path: "/auth/v1/api-keys",
47
+ body: { user_id: userId, name }
48
+ });
49
+ return { data: { apiKey: data?.api_key ?? null, key: data?.key ?? null }, error };
50
+ },
51
+ async list({ userId }) {
52
+ const { data, error } = await request({
53
+ ...base,
54
+ method: "GET",
55
+ path: `/auth/v1/api-keys?user_id=${encodeURIComponent(userId)}`
56
+ });
57
+ return { data: { apiKeys: data?.api_keys ?? [] }, error };
58
+ },
59
+ async revoke(apiKeyId) {
60
+ const { error } = await request({
61
+ ...base,
62
+ method: "DELETE",
63
+ path: `/auth/v1/api-keys/${encodeURIComponent(apiKeyId)}`
64
+ });
65
+ return { error };
66
+ },
67
+ // The key travels in the request body so it never reaches a URL or an access log.
68
+ async verify(apiKey) {
69
+ const { data, error } = await request({
70
+ ...base,
71
+ method: "POST",
72
+ path: "/auth/v1/api-keys/verify",
73
+ body: { api_key: apiKey }
74
+ });
75
+ return { data: { user: data?.user ?? null, apiKey: data?.api_key ?? null }, error };
76
+ }
40
77
  }
41
78
  };
42
79
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server.ts"],"sourcesContent":["import { resolveBaseUrl } from './constants'\nimport { request } from './fetch'\nimport type {\n AuthError,\n AuthResponse,\n ProviderAccessToken,\n ProviderConnection,\n ServerClientOptions,\n User,\n} from './types'\n\nexport interface ServerAuthClient {\n auth: {\n // Mirrors `supabase.auth.getUser(jwt)` server-side: validates the access token\n // against the auth service and returns the user.\n getUser(jwt: string): Promise<AuthResponse<{ user: User | null }>>\n }\n // Provider connections a user granted through the browser SDK. The secret key acts\n // for the whole project; provider access tokens are issued only here, never to browsers.\n connections: {\n list(params: { userId: string }): Promise<AuthResponse<{ connections: ProviderConnection[] }>>\n issueAccessToken(connectionId: string): Promise<AuthResponse<ProviderAccessToken | null>>\n revoke(connectionId: string): Promise<{ error: AuthError | null }>\n }\n}\n\n// Runs anywhere with global fetch (Bun, Node >= 18). `secretKey` is the project's\n// bt_secret_... key. Requests target the hosted DeepKey API; the internal\n// override is reserved for DeepKey's console and tests.\nexport const createServerClient = (secretKey: string, options: ServerClientOptions = {}): ServerAuthClient => {\n const base = { apikey: secretKey, baseUrl: resolveBaseUrl(options.__internalBaseUrl), fetchImpl: options.fetch }\n const connection = (id: string) => `/auth/v1/connections/${encodeURIComponent(id)}`\n\n return {\n auth: {\n async getUser(jwt: string) {\n const { data, error } = await request<User>({ ...base, method: 'GET', path: '/auth/v1/user', accessToken: jwt })\n return { data: { user: data }, error }\n },\n },\n connections: {\n async list({ userId }) {\n const { data, error } = await request<{ connections: ProviderConnection[] }>({\n ...base,\n method: 'GET',\n path: `/auth/v1/connections?user_id=${encodeURIComponent(userId)}`,\n })\n return { data: { connections: data?.connections ?? [] }, error }\n },\n async issueAccessToken(connectionId) {\n return request<ProviderAccessToken>({\n ...base,\n method: 'POST',\n path: `${connection(connectionId)}/token`,\n body: {},\n })\n },\n async revoke(connectionId) {\n const { error } = await request({ ...base, method: 'DELETE', path: connection(connectionId) })\n return { error }\n },\n },\n }\n}\n\nexport { DEEPKEY_API_URL } from './constants'\nexport {\n AuthError,\n type AuthResponse,\n type ProviderAccessToken,\n type ProviderConnection,\n type ServerClientOptions,\n type User,\n} from './types'\n"],"mappings":";;;;;;;;AA6BO,IAAM,qBAAqB,CAAC,WAAmB,UAA+B,CAAC,MAAwB;AAC5G,QAAM,OAAO,EAAE,QAAQ,WAAW,SAAS,eAAe,QAAQ,iBAAiB,GAAG,WAAW,QAAQ,MAAM;AAC/G,QAAM,aAAa,CAAC,OAAe,wBAAwB,mBAAmB,EAAE,CAAC;AAEjF,SAAO;AAAA,IACL,MAAM;AAAA,MACJ,MAAM,QAAQ,KAAa;AACzB,cAAM,EAAE,MAAM,MAAM,IAAI,MAAM,QAAc,EAAE,GAAG,MAAM,QAAQ,OAAO,MAAM,iBAAiB,aAAa,IAAI,CAAC;AAC/G,eAAO,EAAE,MAAM,EAAE,MAAM,KAAK,GAAG,MAAM;AAAA,MACvC;AAAA,IACF;AAAA,IACA,aAAa;AAAA,MACX,MAAM,KAAK,EAAE,OAAO,GAAG;AACrB,cAAM,EAAE,MAAM,MAAM,IAAI,MAAM,QAA+C;AAAA,UAC3E,GAAG;AAAA,UACH,QAAQ;AAAA,UACR,MAAM,gCAAgC,mBAAmB,MAAM,CAAC;AAAA,QAClE,CAAC;AACD,eAAO,EAAE,MAAM,EAAE,aAAa,MAAM,eAAe,CAAC,EAAE,GAAG,MAAM;AAAA,MACjE;AAAA,MACA,MAAM,iBAAiB,cAAc;AACnC,eAAO,QAA6B;AAAA,UAClC,GAAG;AAAA,UACH,QAAQ;AAAA,UACR,MAAM,GAAG,WAAW,YAAY,CAAC;AAAA,UACjC,MAAM,CAAC;AAAA,QACT,CAAC;AAAA,MACH;AAAA,MACA,MAAM,OAAO,cAAc;AACzB,cAAM,EAAE,MAAM,IAAI,MAAM,QAAQ,EAAE,GAAG,MAAM,QAAQ,UAAU,MAAM,WAAW,YAAY,EAAE,CAAC;AAC7F,eAAO,EAAE,MAAM;AAAA,MACjB;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/server.ts"],"sourcesContent":["import { resolveBaseUrl } from './constants'\nimport { request } from './fetch'\nimport type {\n AuthError,\n AuthResponse,\n ProviderAccessToken,\n ProviderConnection,\n ServerClientOptions,\n User,\n UserApiKey,\n} from './types'\n\nexport interface ServerAuthClient {\n auth: {\n // Mirrors `supabase.auth.getUser(jwt)` server-side: validates the access token\n // against the auth service and returns the user.\n getUser(jwt: string): Promise<AuthResponse<{ user: User | null }>>\n }\n // Provider connections a user granted through the browser SDK. The secret key acts\n // for the whole project; provider access tokens are issued only here, never to browsers.\n connections: {\n list(params: { userId: string }): Promise<AuthResponse<{ connections: ProviderConnection[] }>>\n issueAccessToken(connectionId: string): Promise<AuthResponse<ProviderAccessToken | null>>\n revoke(connectionId: string): Promise<{ error: AuthError | null }>\n }\n // Long-lived keys your application issues to its own users. Every call uses the secret\n // key; `verify` is the API-key counterpart of `auth.getUser(jwt)` and returns the same user.\n apiKeys: {\n // `key` is the plaintext. It is returned here once and cannot be read again.\n create(params: {\n userId: string\n name?: string\n }): Promise<AuthResponse<{ apiKey: UserApiKey | null; key: string | null }>>\n list(params: { userId: string }): Promise<AuthResponse<{ apiKeys: UserApiKey[] }>>\n revoke(apiKeyId: string): Promise<{ error: AuthError | null }>\n verify(apiKey: string): Promise<AuthResponse<{ user: User | null; apiKey: UserApiKey | null }>>\n }\n}\n\n// Runs anywhere with global fetch (Bun, Node >= 18). `secretKey` is the project's\n// bt_secret_... key. Requests target the hosted DeepKey API; the internal\n// override is reserved for DeepKey's console and tests.\nexport const createServerClient = (secretKey: string, options: ServerClientOptions = {}): ServerAuthClient => {\n const base = { apikey: secretKey, baseUrl: resolveBaseUrl(options.__internalBaseUrl), fetchImpl: options.fetch }\n const connection = (id: string) => `/auth/v1/connections/${encodeURIComponent(id)}`\n\n return {\n auth: {\n async getUser(jwt: string) {\n const { data, error } = await request<User>({ ...base, method: 'GET', path: '/auth/v1/user', accessToken: jwt })\n return { data: { user: data }, error }\n },\n },\n connections: {\n async list({ userId }) {\n const { data, error } = await request<{ connections: ProviderConnection[] }>({\n ...base,\n method: 'GET',\n path: `/auth/v1/connections?user_id=${encodeURIComponent(userId)}`,\n })\n return { data: { connections: data?.connections ?? [] }, error }\n },\n async issueAccessToken(connectionId) {\n return request<ProviderAccessToken>({\n ...base,\n method: 'POST',\n path: `${connection(connectionId)}/token`,\n body: {},\n })\n },\n async revoke(connectionId) {\n const { error } = await request({ ...base, method: 'DELETE', path: connection(connectionId) })\n return { error }\n },\n },\n apiKeys: {\n async create({ userId, name }) {\n const { data, error } = await request<{ api_key: UserApiKey; key: string }>({\n ...base,\n method: 'POST',\n path: '/auth/v1/api-keys',\n body: { user_id: userId, name },\n })\n return { data: { apiKey: data?.api_key ?? null, key: data?.key ?? null }, error }\n },\n async list({ userId }) {\n const { data, error } = await request<{ api_keys: UserApiKey[] }>({\n ...base,\n method: 'GET',\n path: `/auth/v1/api-keys?user_id=${encodeURIComponent(userId)}`,\n })\n return { data: { apiKeys: data?.api_keys ?? [] }, error }\n },\n async revoke(apiKeyId) {\n const { error } = await request({\n ...base,\n method: 'DELETE',\n path: `/auth/v1/api-keys/${encodeURIComponent(apiKeyId)}`,\n })\n return { error }\n },\n // The key travels in the request body so it never reaches a URL or an access log.\n async verify(apiKey) {\n const { data, error } = await request<{ user: User; api_key: UserApiKey }>({\n ...base,\n method: 'POST',\n path: '/auth/v1/api-keys/verify',\n body: { api_key: apiKey },\n })\n return { data: { user: data?.user ?? null, apiKey: data?.api_key ?? null }, error }\n },\n },\n }\n}\n\nexport { DEEPKEY_API_URL } from './constants'\nexport {\n AuthError,\n type AuthResponse,\n type ProviderAccessToken,\n type ProviderConnection,\n type ServerClientOptions,\n type User,\n type UserApiKey,\n} from './types'\n"],"mappings":";;;;;;;;AA0CO,IAAM,qBAAqB,CAAC,WAAmB,UAA+B,CAAC,MAAwB;AAC5G,QAAM,OAAO,EAAE,QAAQ,WAAW,SAAS,eAAe,QAAQ,iBAAiB,GAAG,WAAW,QAAQ,MAAM;AAC/G,QAAM,aAAa,CAAC,OAAe,wBAAwB,mBAAmB,EAAE,CAAC;AAEjF,SAAO;AAAA,IACL,MAAM;AAAA,MACJ,MAAM,QAAQ,KAAa;AACzB,cAAM,EAAE,MAAM,MAAM,IAAI,MAAM,QAAc,EAAE,GAAG,MAAM,QAAQ,OAAO,MAAM,iBAAiB,aAAa,IAAI,CAAC;AAC/G,eAAO,EAAE,MAAM,EAAE,MAAM,KAAK,GAAG,MAAM;AAAA,MACvC;AAAA,IACF;AAAA,IACA,aAAa;AAAA,MACX,MAAM,KAAK,EAAE,OAAO,GAAG;AACrB,cAAM,EAAE,MAAM,MAAM,IAAI,MAAM,QAA+C;AAAA,UAC3E,GAAG;AAAA,UACH,QAAQ;AAAA,UACR,MAAM,gCAAgC,mBAAmB,MAAM,CAAC;AAAA,QAClE,CAAC;AACD,eAAO,EAAE,MAAM,EAAE,aAAa,MAAM,eAAe,CAAC,EAAE,GAAG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;AACnB,cAAM,EAAE,MAAM,MAAM,IAAI,MAAM,QAA6C;AAAA,UACzE,GAAG;AAAA,UACH,QAAQ;AAAA,UACR,MAAM;AAAA,UACN,MAAM,EAAE,SAAS,OAAO;AAAA,QAC1B,CAAC;AACD,eAAO,EAAE,MAAM,EAAE,MAAM,MAAM,QAAQ,MAAM,QAAQ,MAAM,WAAW,KAAK,GAAG,MAAM;AAAA,MACpF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepkey/sdk",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "DeepKey authentication SDK for the browser and server — a supabase-js compatible auth surface",
5
5
  "homepage": "https://deepkey.dev/sdk",
6
6
  "keywords": [
@@ -31,6 +31,12 @@
31
31
  "main": "./dist/index.cjs",
32
32
  "module": "./dist/index.js",
33
33
  "types": "./dist/index.d.ts",
34
+ "scripts": {
35
+ "build": "tsup",
36
+ "typecheck": "tsc --noEmit",
37
+ "test": "vitest run",
38
+ "prepublishOnly": "pnpm build"
39
+ },
34
40
  "publishConfig": {
35
41
  "access": "public"
36
42
  },
@@ -39,10 +45,5 @@
39
45
  "tsup": "^8.5.0",
40
46
  "typescript": "^5.9.3",
41
47
  "vitest": "^4.0.18"
42
- },
43
- "scripts": {
44
- "build": "tsup",
45
- "typecheck": "tsc --noEmit",
46
- "test": "vitest run"
47
48
  }
48
- }
49
+ }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/types.ts","../src/fetch.ts","../src/constants.ts"],"sourcesContent":["export interface UserIdentity {\n identity_id: string\n id: string\n user_id: string\n provider: string\n identity_data: Record<string, unknown>\n last_sign_in_at: string | null\n created_at: string\n updated_at: string\n}\n\nexport interface User {\n id: string\n aud: string\n role: string\n email: string | null\n email_confirmed_at: string | null\n app_metadata: { provider?: string | null; providers?: string[]; [key: string]: unknown }\n user_metadata: {\n name?: string\n full_name?: string\n avatar_url?: string\n picture?: string\n email?: string\n [key: string]: unknown\n }\n identities?: UserIdentity[]\n created_at: string\n updated_at?: string\n last_sign_in_at?: string | null\n}\n\nexport interface Session {\n access_token: string\n refresh_token: string\n token_type: 'bearer'\n expires_in: number\n expires_at: number\n user: User\n}\n\nexport class AuthError extends Error {\n status?: number\n code?: string\n\n constructor(message: string, status?: number, code?: string) {\n super(message)\n this.name = 'AuthError'\n this.status = status\n this.code = code\n }\n}\n\nexport type AuthChangeEvent = 'INITIAL_SESSION' | 'SIGNED_IN' | 'SIGNED_OUT' | 'TOKEN_REFRESHED'\n\nexport interface Subscription {\n id: string\n unsubscribe: () => void\n}\n\nexport interface StorageAdapter {\n getItem(key: string): string | null\n setItem(key: string, value: string): void\n removeItem(key: string): void\n}\n\nexport interface AuthClientOptions {\n /**\n * @internal Replaces the hosted DeepKey API origin. Used only by DeepKey's own\n * console and test suites; not supported for consumers and stripped from the\n * published type declarations.\n */\n __internalBaseUrl?: string\n storageKey?: string\n autoRefreshToken?: boolean\n detectSessionInUrl?: boolean\n persistSession?: boolean\n storage?: StorageAdapter\n fetch?: typeof fetch\n}\n\nexport interface ServerClientOptions {\n /**\n * @internal Replaces the hosted DeepKey API origin. Used only by DeepKey's own\n * console and test suites; not supported for consumers and stripped from the\n * published type declarations.\n */\n __internalBaseUrl?: string\n fetch?: typeof fetch\n}\n\nexport interface SignInWithOtpCredentials {\n email: string\n options?: {\n emailRedirectTo?: string\n shouldCreateUser?: boolean\n data?: Record<string, unknown>\n }\n}\n\nexport interface VerifyOtpParams {\n email: string\n token: string\n type: 'email' | 'magiclink'\n}\n\nexport interface ConnectProviderCredentials {\n provider: string\n options?: {\n redirectTo?: string\n skipBrowserRedirect?: boolean\n }\n}\n\n// Metadata only: provider tokens never appear in browser responses.\nexport interface ProviderConnection {\n id: string\n // The DeepKey user that granted the connection: the same `user.id` your server gets from getUser(jwt).\n user_id: string\n provider: string\n provider_user_id: string\n identity_data: Record<string, unknown>\n scope: string | null\n status: 'active' | 'reauthorization_required'\n created_at: string\n updated_at: string\n}\n\n// Issued to consumer servers through the secret key; short-lived and refreshed by DeepKey.\nexport interface ProviderAccessToken {\n access_token: string\n token_type: 'bearer'\n expires_at: number | null\n scope: string | null\n}\n\nexport interface SignInWithOAuthCredentials {\n provider: string\n options?: {\n redirectTo?: string\n scopes?: string\n queryParams?: Record<string, string>\n skipBrowserRedirect?: boolean\n }\n}\n\nexport interface AuthResponse<T> {\n data: T\n error: AuthError | null\n}\n","import { AuthError } from './types'\n\nexport interface RequestOptions {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE'\n path: string\n apikey: string\n baseUrl: string\n accessToken?: string\n body?: unknown\n fetchImpl?: typeof fetch\n}\n\nexport interface RequestResult<T> {\n data: T | null\n error: AuthError | null\n}\n\n// All service errors are shaped { error: { code, message } }.\nexport const request = async <T>(options: RequestOptions): Promise<RequestResult<T>> => {\n const fetchImpl = options.fetchImpl ?? fetch\n try {\n const headers: Record<string, string> = { apikey: options.apikey }\n if (options.body !== undefined) headers['Content-Type'] = 'application/json'\n if (options.accessToken) headers.Authorization = `Bearer ${options.accessToken}`\n\n const response = await fetchImpl(`${options.baseUrl}${options.path}`, {\n method: options.method,\n headers,\n body: options.body !== undefined ? JSON.stringify(options.body) : undefined,\n })\n\n if (response.status === 204) return { data: {} as T, error: null }\n\n let payload: unknown\n try {\n payload = await response.json()\n } catch {\n payload = null\n }\n\n if (!response.ok) {\n const errorBody = (payload as { error?: { code?: string; message?: string } } | null)?.error\n return {\n data: null,\n error: new AuthError(\n errorBody?.message ?? `Request failed with status ${response.status}`,\n response.status,\n errorBody?.code,\n ),\n }\n }\n\n return { data: payload as T, error: null }\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Network request failed'\n return { data: null, error: new AuthError(message, 0, 'network_error') }\n }\n}\n","// The hosted DeepKey API. Every client talks to this origin; only DeepKey's own\n// console and test suites replace it through the internal override.\nexport const DEEPKEY_API_URL = 'https://deepkey.dev/api'\n\n// Resolves the base URL used for every request. An absent or blank internal\n// override keeps the hosted API; a provided value has any trailing slash removed\n// so path joins stay predictable.\nexport const resolveBaseUrl = (url?: string | null): string => {\n const candidate = typeof url === 'string' ? url.trim() : ''\n return (candidate || DEEPKEY_API_URL).replace(/\\/+$/, '')\n}\n"],"mappings":";AAyCO,IAAM,YAAN,cAAwB,MAAM;AAAA,EAInC,YAAY,SAAiB,QAAiB,MAAe;AAC3D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EACd;AACF;;;ACjCO,IAAM,UAAU,OAAU,YAAuD;AACtF,QAAM,YAAY,QAAQ,aAAa;AACvC,MAAI;AACF,UAAM,UAAkC,EAAE,QAAQ,QAAQ,OAAO;AACjE,QAAI,QAAQ,SAAS,OAAW,SAAQ,cAAc,IAAI;AAC1D,QAAI,QAAQ,YAAa,SAAQ,gBAAgB,UAAU,QAAQ,WAAW;AAE9E,UAAM,WAAW,MAAM,UAAU,GAAG,QAAQ,OAAO,GAAG,QAAQ,IAAI,IAAI;AAAA,MACpE,QAAQ,QAAQ;AAAA,MAChB;AAAA,MACA,MAAM,QAAQ,SAAS,SAAY,KAAK,UAAU,QAAQ,IAAI,IAAI;AAAA,IACpE,CAAC;AAED,QAAI,SAAS,WAAW,IAAK,QAAO,EAAE,MAAM,CAAC,GAAQ,OAAO,KAAK;AAEjE,QAAI;AACJ,QAAI;AACF,gBAAU,MAAM,SAAS,KAAK;AAAA,IAChC,QAAQ;AACN,gBAAU;AAAA,IACZ;AAEA,QAAI,CAAC,SAAS,IAAI;AAChB,YAAM,YAAa,SAAoE;AACvF,aAAO;AAAA,QACL,MAAM;AAAA,QACN,OAAO,IAAI;AAAA,UACT,WAAW,WAAW,8BAA8B,SAAS,MAAM;AAAA,UACnE,SAAS;AAAA,UACT,WAAW;AAAA,QACb;AAAA,MACF;AAAA,IACF;AAEA,WAAO,EAAE,MAAM,SAAc,OAAO,KAAK;AAAA,EAC3C,SAAS,KAAK;AACZ,UAAM,U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