@dontcode2/backend 0.1.0 → 0.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/dist/index.d.ts CHANGED
@@ -4,11 +4,16 @@ interface TransportConfig {
4
4
  apiKey?: string;
5
5
  /** Gateway origin, already normalized (no trailing slash). */
6
6
  baseUrl: string;
7
+ /** Per-request timeout in ms. Defaults to `DEFAULT_TIMEOUT_MS`; `0` (or any
8
+ * non-positive value) disables it. */
9
+ timeoutMs?: number;
7
10
  }
8
11
  interface RequestOptions {
9
12
  /** End-user access token, sent as `X-Access-Token` (separate from the
10
13
  * project API key). Required by signed-in auth calls. */
11
14
  accessToken?: string;
15
+ /** Override the client's timeout for this one call (ms). `0` disables it. */
16
+ timeoutMs?: number;
12
17
  }
13
18
  /**
14
19
  * The single place network requests are made. Everything else in the SDK is a
@@ -20,6 +25,15 @@ declare class Transport {
20
25
  constructor(config: TransportConfig);
21
26
  private headers;
22
27
  private url;
28
+ private timeout;
29
+ /**
30
+ * One fetch, with a timeout that turns "hung socket" into a fast, typed
31
+ * failure. A timeout surfaces as `DontCodeError` with status 408 / code
32
+ * `Timeout`; any other transport failure (DNS, refused, offline) as status
33
+ * 0 / code `NetworkError`. Both are distinct from a real `401`, so an auth
34
+ * guard can tell "backend is down" apart from "user is signed out".
35
+ */
36
+ private send;
23
37
  /** POST a JSON body and parse the JSON response. */
24
38
  json<T>(path: string, body?: unknown, opts?: RequestOptions): Promise<T>;
25
39
  /** PUT a multipart form (file uploads). The runtime sets the boundary. */
@@ -188,6 +202,107 @@ interface TemporaryUrlResult {
188
202
  /** Bytes the SDK can turn into an upload body. */
189
203
  type UploadBody = Blob | ArrayBuffer | ArrayBufferView | string;
190
204
 
205
+ /**
206
+ * Session helpers, framework-agnostic by design. They never touch a request or
207
+ * response object; they take a token (or a cookie header) and return plain
208
+ * data, so they slot into any framework's guard (Next middleware, SvelteKit
209
+ * hooks, Express, a worker) without an adapter.
210
+ *
211
+ * The point of the module: an auth guard must not make a network round-trip on
212
+ * every navigation, or a slow gateway stalls the page and a swallowed timeout
213
+ * reads as "signed out". So there are two modes:
214
+ *
215
+ * - optimistic — decode the token locally (no signature check, no network)
216
+ * and trust its claims for routing. Instant. Used for the common gate.
217
+ * - verified — call the gateway's `me` once, cache the result for a short
218
+ * TTL, and hard-timeout the request. Used for sensitive actions.
219
+ *
220
+ * The trade-offs (no signature verification, revocation lag) are documented on
221
+ * `getSession` and in the public BYOC docs; read them before choosing a mode.
222
+ */
223
+ /** A JWT payload decoded WITHOUT verifying its signature. Trust accordingly. */
224
+ interface DecodedSession {
225
+ /** Subject — the user id. */
226
+ sub: string;
227
+ email?: string;
228
+ role?: string;
229
+ claims?: Record<string, unknown>;
230
+ /** Expiry, seconds since the epoch (standard JWT `exp`). */
231
+ exp?: number;
232
+ /** Issued-at, seconds since the epoch (standard JWT `iat`). */
233
+ iat?: number;
234
+ [key: string]: unknown;
235
+ }
236
+ type SessionStatus =
237
+ /** A usable session: a present, unexpired token (verified or optimistic). */
238
+ 'active'
239
+ /** The token is present but past its `exp`. */
240
+ | 'expired'
241
+ /** No token, or an unparseable one. */
242
+ | 'anonymous'
243
+ /** Verified mode could not reach the gateway (timeout/network/5xx). The
244
+ * optimistically-decoded `user` is still returned so the caller can choose
245
+ * to fail open during an outage instead of logging everyone out. */
246
+ | 'unavailable';
247
+ interface SessionResult {
248
+ status: SessionStatus;
249
+ /** The signed-in user, or `null` when anonymous/expired. In `verified` mode
250
+ * this came from the gateway; in `optimistic` (or `unavailable`) it was
251
+ * decoded from the token's own claims. */
252
+ user: CurrentUser | null;
253
+ /** True only when `user` was confirmed by a gateway `me` call this request
254
+ * (or from a fresh cache entry of one). False for optimistic decodes. */
255
+ verified: boolean;
256
+ /** The token's `exp` (seconds since epoch), when present. */
257
+ expiresAt?: number;
258
+ }
259
+ interface GetSessionInput {
260
+ accessToken: string;
261
+ /** `optimistic` (default): decode locally, zero network. `verified`: confirm
262
+ * against the gateway with caching + a hard timeout. */
263
+ mode?: 'optimistic' | 'verified';
264
+ }
265
+ /** A place to cache verified sessions. Swap the default in-memory store for a
266
+ * shared one (Redis, KV) when running multiple instances. */
267
+ interface SessionCache {
268
+ get(token: string): SessionResult | undefined;
269
+ set(token: string, value: SessionResult, ttlMs: number): void;
270
+ delete?(token: string): void;
271
+ }
272
+ interface SessionOptions {
273
+ /** Cache for verified sessions. Defaults to a per-process `InMemorySessionCache`. */
274
+ cache?: SessionCache;
275
+ /** How long a verified session stays cached. Default 60_000 (60s). Keep it
276
+ * short: a cached session can outlive a server-side revocation by up to
277
+ * this long. */
278
+ ttlMs?: number;
279
+ /** Timeout for the `me` call made by `verified` mode (ms). Default 5_000. */
280
+ verifyTimeoutMs?: number;
281
+ }
282
+ /** Default cache: a `Map` with per-entry TTL. Lives for the life of the process
283
+ * (and is shared across requests on a reused serverless instance). */
284
+ declare class InMemorySessionCache implements SessionCache {
285
+ private readonly store;
286
+ get(token: string): SessionResult | undefined;
287
+ set(token: string, value: SessionResult, ttlMs: number): void;
288
+ delete(token: string): void;
289
+ }
290
+ /**
291
+ * Decode a JWT access token's payload WITHOUT verifying its signature, or
292
+ * return `null` if it is not a parseable JWT. This is deliberately cheap and
293
+ * offline; it is not proof the token is genuine. DontCode tokens are signed
294
+ * with a secret the gateway never shares, so the only authority on a token is
295
+ * the gateway's `me` endpoint — use `getSession({ mode: 'verified' })` when you
296
+ * need that authority.
297
+ */
298
+ declare function decodeAccessToken(token: string): DecodedSession | null;
299
+ /** True when a token (or already-decoded payload) is past its `exp`. A token
300
+ * with no `exp` is treated as not expired (the caller cannot prove otherwise
301
+ * offline). `skewSeconds` widens the window to absorb clock drift. */
302
+ declare function isSessionExpired(input: string | DecodedSession | null, opts?: {
303
+ skewSeconds?: number;
304
+ }): boolean;
305
+
191
306
  /**
192
307
  * MFA is per-user and opt-in. `enroll`/`enrollConfirm`/`disable` act as the
193
308
  * signed-in user, so they need the end-user access token. `challenge` does
@@ -221,7 +336,8 @@ declare class MfaApi {
221
336
  declare class AuthApi {
222
337
  private readonly transport;
223
338
  readonly mfa: MfaApi;
224
- constructor(transport: Transport);
339
+ private readonly sessions;
340
+ constructor(transport: Transport, sessionOptions?: SessionOptions);
225
341
  /** Create an account. If the project requires email verification the
226
342
  * response has `verification_required: true` and NO tokens; collect a
227
343
  * code and call `verifyEmail`, then `login`. */
@@ -230,10 +346,39 @@ declare class AuthApi {
230
346
  * challenge (finish via `mfa.challenge`); otherwise `tokens` is your
231
347
  * session. A 403 `EmailNotVerified` means the email step isn't done. */
232
348
  login(input: LoginInput): Promise<LoginResult>;
233
- /** Resolve the signed-in user from their access token, or `{ user: null }`. */
349
+ /** Resolve the signed-in user from their access token, or `{ user: null }`.
350
+ * This is a network round-trip; for a per-navigation guard prefer
351
+ * `getSession`, which can answer offline and caches verified results. */
234
352
  me(input: {
235
353
  accessToken: string;
354
+ timeoutMs?: number;
236
355
  }): Promise<MeResult>;
356
+ /**
357
+ * Resolve an access token into a session for a route guard, the one call
358
+ * that replaces "hit `me` on every navigation". Two modes:
359
+ *
360
+ * - `'optimistic'` (default): decode the token locally and trust its
361
+ * claims. Zero network, zero stall. The right default for gating page
362
+ * loads. It does NOT verify the signature and will not notice a
363
+ * server-side revocation until the token's own `exp`.
364
+ * - `'verified'`: confirm against the gateway's `me`, cached for a short
365
+ * TTL with a hard timeout. Use it before sensitive actions. On a
366
+ * timeout/outage it returns `status: 'unavailable'` with the optimistic
367
+ * user, so you choose whether to fail open rather than the SDK guessing.
368
+ *
369
+ * See the BYOC docs ("Sessions") for the full reasoning and best practices.
370
+ */
371
+ getSession(input: GetSessionInput): Promise<SessionResult>;
372
+ /** Read the access token from a `Cookie` request header and resolve it, in
373
+ * one call. `name` defaults to `dc_access_token`. Returns the anonymous
374
+ * session when no cookie is present. */
375
+ sessionFromCookies(cookieHeader: string | null | undefined, options?: {
376
+ mode?: GetSessionInput['mode'];
377
+ cookieName?: string;
378
+ }): Promise<SessionResult>;
379
+ /** Decode an access token's claims locally without a network call or any
380
+ * signature check. Convenience re-export of `decodeAccessToken`. */
381
+ decodeToken(token: string): DecodedSession | null;
237
382
  /** Confirm the 6-digit code emailed at signup. */
238
383
  verifyEmail(input: VerifyEmailInput): Promise<SimpleResult>;
239
384
  forgotPassword(input: ForgotPasswordInput): Promise<SimpleResult>;
@@ -339,6 +484,12 @@ interface DontCodeClientOptions {
339
484
  /** Gateway origin. Defaults to `process.env.DONTCODE_API_URL`, then to
340
485
  * `https://backend.dontcode.co`. */
341
486
  baseUrl?: string;
487
+ /** Per-request network timeout in ms. Defaults to 10_000; `0` disables it.
488
+ * Without one, a slow gateway can hang a request for the full socket
489
+ * timeout, the worst case for an auth guard. */
490
+ timeoutMs?: number;
491
+ /** Caching + timeout policy for `auth.getSession` / `auth.sessionFromCookies`. */
492
+ session?: SessionOptions;
342
493
  }
343
494
  interface DontCodeClient {
344
495
  auth: AuthApi;
@@ -367,6 +518,11 @@ declare function dontcode(options?: DontCodeClientOptions): DontCodeClient;
367
518
  * Note: many "one more step" auth states (signup needing email verification,
368
519
  * login returning `mfa_required`) are 2xx successes, NOT errors; inspect the
369
520
  * resolved value for those. Errors are reserved for actual failures.
521
+ *
522
+ * Transport failures (no HTTP response at all) also surface as a DontCodeError
523
+ * so callers have one error type: a timeout is status 408 / code `Timeout`, and
524
+ * any other network failure is status 0 / code `NetworkError`. Neither is a
525
+ * `401`, so a guard can distinguish "backend unavailable" from "signed out".
370
526
  */
371
527
  interface DontCodeErrorBody {
372
528
  error?: string;
@@ -392,4 +548,41 @@ declare class DontCodeError extends Error {
392
548
  /** Cross-bundle-safe check; works even if two copies of the SDK are loaded. */
393
549
  declare function isDontCodeError(err: unknown): err is DontCodeError;
394
550
 
395
- export { AuthApi, type AuthTokens, BucketClient, type CurrentUser, type DbClient, type DeleteInput, type DontCodeClient, type DontCodeClientOptions, DontCodeError, type DontCodeErrorBody, type DownloadResult, type ForgotPasswordInput, type ListResult, type LoginInput, type LoginResult, type MeResult, MfaApi, type MfaChallengeInput, type MfaDisableInput, type MfaEnrollConfirmInput, type MfaEnrollResult, type MigrateInput, type MigrateResult, type OrderByClause, type PresignResult, PublicBucketClient, type QueryOptions, type ResetPasswordInput, type SignupInput, type SignupResult, type SimpleResult, type StorageBucket, type StorageClient, type StorageObject, TableQuery, type TemporaryUrlResult, type UpdateInput, type UploadBody, type VerifyEmailInput, type WhereClause, type WhereOperator, createStorage, dontcode, isDontCodeError };
551
+ /**
552
+ * Cookie helpers, framework-agnostic by design. They return strings: a
553
+ * `Set-Cookie` header value to write, or a parsed token to read. Your framework
554
+ * applies them (`headers.append('Set-Cookie', …)`, SvelteKit `cookies.set`, a
555
+ * Next `Response` cookie, etc.). The SDK never owns a request or response.
556
+ *
557
+ * Defaults match how DontCode's own apps store the session: an httpOnly cookie
558
+ * so JavaScript can't read the token, `Secure`, `SameSite=Lax`, path `/`, and a
559
+ * 7-day max age. Cross-site setups (your app and the gateway on different sites)
560
+ * need `sameSite: 'none'`, which forces `Secure` on.
561
+ */
562
+ /** Default cookie name for the end-user access token. */
563
+ declare const DEFAULT_SESSION_COOKIE_NAME = "dc_access_token";
564
+ interface SessionCookieOptions {
565
+ /** Cookie name. Default `dc_access_token`. */
566
+ name?: string;
567
+ /** Lifetime in seconds. Default one week. Pass the token's `ExpiresIn` to
568
+ * keep the cookie and the token in lockstep. */
569
+ maxAge?: number;
570
+ /** Default `/`. */
571
+ path?: string;
572
+ domain?: string;
573
+ /** Default `true`. */
574
+ secure?: boolean;
575
+ /** Default `true`. Keep the token unreadable from client JavaScript. */
576
+ httpOnly?: boolean;
577
+ /** Default `'lax'`. Use `'none'` for cross-site (it forces `Secure`). */
578
+ sameSite?: 'lax' | 'strict' | 'none';
579
+ }
580
+ /** Build a `Set-Cookie` value that stores the access token. */
581
+ declare function serializeSessionCookie(token: string, options?: SessionCookieOptions): string;
582
+ /** Build a `Set-Cookie` value that clears the access token (logout). */
583
+ declare function clearSessionCookie(options?: SessionCookieOptions): string;
584
+ /** Read the access token out of a `Cookie` request header, or `null`. Pass the
585
+ * raw header string (`name=value; name2=value2`). */
586
+ declare function readSessionToken(cookieHeader: string | null | undefined, name?: string): string | null;
587
+
588
+ export { AuthApi, type AuthTokens, BucketClient, type CurrentUser, DEFAULT_SESSION_COOKIE_NAME, type DbClient, type DecodedSession, type DeleteInput, type DontCodeClient, type DontCodeClientOptions, DontCodeError, type DontCodeErrorBody, type DownloadResult, type ForgotPasswordInput, type GetSessionInput, InMemorySessionCache, type ListResult, type LoginInput, type LoginResult, type MeResult, MfaApi, type MfaChallengeInput, type MfaDisableInput, type MfaEnrollConfirmInput, type MfaEnrollResult, type MigrateInput, type MigrateResult, type OrderByClause, type PresignResult, PublicBucketClient, type QueryOptions, type ResetPasswordInput, type SessionCache, type SessionCookieOptions, type SessionOptions, type SessionResult, type SessionStatus, type SignupInput, type SignupResult, type SimpleResult, type StorageBucket, type StorageClient, type StorageObject, TableQuery, type TemporaryUrlResult, type UpdateInput, type UploadBody, type VerifyEmailInput, type WhereClause, type WhereOperator, clearSessionCookie, createStorage, decodeAccessToken, dontcode, isDontCodeError, isSessionExpired, readSessionToken, serializeSessionCookie };
package/dist/index.js CHANGED
@@ -1,3 +1,162 @@
1
+ // src/cookies.ts
2
+ var DEFAULT_SESSION_COOKIE_NAME = "dc_access_token";
3
+ var DEFAULT_MAX_AGE_SECONDS = 60 * 60 * 24 * 7;
4
+ function serialize(name, value, options, maxAge) {
5
+ const sameSite = options.sameSite ?? "lax";
6
+ const secure = sameSite === "none" ? true : options.secure ?? true;
7
+ const httpOnly = options.httpOnly ?? true;
8
+ const path = options.path ?? "/";
9
+ const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${path}`, `Max-Age=${maxAge}`];
10
+ if (options.domain) parts.push(`Domain=${options.domain}`);
11
+ parts.push(`SameSite=${sameSite.charAt(0).toUpperCase()}${sameSite.slice(1)}`);
12
+ if (httpOnly) parts.push("HttpOnly");
13
+ if (secure) parts.push("Secure");
14
+ return parts.join("; ");
15
+ }
16
+ function serializeSessionCookie(token, options = {}) {
17
+ const name = options.name ?? DEFAULT_SESSION_COOKIE_NAME;
18
+ const maxAge = options.maxAge ?? DEFAULT_MAX_AGE_SECONDS;
19
+ return serialize(name, token, options, maxAge);
20
+ }
21
+ function clearSessionCookie(options = {}) {
22
+ const name = options.name ?? DEFAULT_SESSION_COOKIE_NAME;
23
+ return serialize(name, "", options, 0);
24
+ }
25
+ function readSessionToken(cookieHeader, name = DEFAULT_SESSION_COOKIE_NAME) {
26
+ if (!cookieHeader) return null;
27
+ for (const pair of cookieHeader.split(";")) {
28
+ const eq = pair.indexOf("=");
29
+ if (eq === -1) continue;
30
+ if (pair.slice(0, eq).trim() !== name) continue;
31
+ const raw = pair.slice(eq + 1).trim();
32
+ if (!raw) return null;
33
+ try {
34
+ return decodeURIComponent(raw);
35
+ } catch {
36
+ return raw;
37
+ }
38
+ }
39
+ return null;
40
+ }
41
+
42
+ // src/errors.ts
43
+ var DontCodeError = class extends Error {
44
+ constructor(status, body) {
45
+ const message = typeof body?.error === "string" && body.error.length > 0 ? body.error : `DontCode request failed with status ${status}`;
46
+ super(message);
47
+ this.name = "DontCodeError";
48
+ this.status = status;
49
+ this.code = typeof body?.code === "string" ? body.code : void 0;
50
+ this.body = body ?? {};
51
+ }
52
+ /** True when the request was rejected by the per-key rate limiter. */
53
+ get rateLimited() {
54
+ return this.status === 429;
55
+ }
56
+ };
57
+ function isDontCodeError(err) {
58
+ if (err instanceof DontCodeError) return true;
59
+ return typeof err === "object" && err !== null && err.name === "DontCodeError";
60
+ }
61
+
62
+ // src/session.ts
63
+ var DEFAULT_TTL_MS = 6e4;
64
+ var DEFAULT_VERIFY_TIMEOUT_MS = 5e3;
65
+ var InMemorySessionCache = class {
66
+ constructor() {
67
+ this.store = /* @__PURE__ */ new Map();
68
+ }
69
+ get(token) {
70
+ const hit = this.store.get(token);
71
+ if (!hit) return void 0;
72
+ if (Date.now() >= hit.expiresAtMs) {
73
+ this.store.delete(token);
74
+ return void 0;
75
+ }
76
+ return hit.value;
77
+ }
78
+ set(token, value, ttlMs) {
79
+ this.store.set(token, { value, expiresAtMs: Date.now() + ttlMs });
80
+ }
81
+ delete(token) {
82
+ this.store.delete(token);
83
+ }
84
+ };
85
+ function base64UrlDecode(segment) {
86
+ const base64 = segment.replace(/-/g, "+").replace(/_/g, "/");
87
+ const padded = base64.length % 4 === 0 ? base64 : base64 + "=".repeat(4 - base64.length % 4);
88
+ if (typeof atob === "function") {
89
+ const binary = atob(padded);
90
+ const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
91
+ return new TextDecoder().decode(bytes);
92
+ }
93
+ return Buffer.from(padded, "base64").toString("utf8");
94
+ }
95
+ function decodeAccessToken(token) {
96
+ if (!token || typeof token !== "string") return null;
97
+ const parts = token.split(".");
98
+ if (parts.length < 2) return null;
99
+ try {
100
+ const payload = JSON.parse(base64UrlDecode(parts[1]));
101
+ if (!payload || typeof payload.sub !== "string") return null;
102
+ return payload;
103
+ } catch {
104
+ return null;
105
+ }
106
+ }
107
+ function isSessionExpired(input, opts = {}) {
108
+ const decoded = typeof input === "string" ? decodeAccessToken(input) : input;
109
+ if (!decoded || typeof decoded.exp !== "number") return false;
110
+ const nowSeconds = Date.now() / 1e3;
111
+ return nowSeconds >= decoded.exp - (opts.skewSeconds ?? 0);
112
+ }
113
+ function userFromClaims(decoded) {
114
+ return {
115
+ id: decoded.sub,
116
+ email: typeof decoded.email === "string" ? decoded.email : "",
117
+ role: decoded.role,
118
+ claims: decoded.claims
119
+ };
120
+ }
121
+ var SessionVerifier = class {
122
+ constructor(auth, options = {}) {
123
+ this.auth = auth;
124
+ this.cache = options.cache ?? new InMemorySessionCache();
125
+ this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
126
+ this.verifyTimeoutMs = options.verifyTimeoutMs ?? DEFAULT_VERIFY_TIMEOUT_MS;
127
+ }
128
+ async getSession({ accessToken, mode = "optimistic" }) {
129
+ const decoded = decodeAccessToken(accessToken);
130
+ if (!decoded) return { status: "anonymous", user: null, verified: false };
131
+ if (isSessionExpired(decoded)) {
132
+ return { status: "expired", user: null, verified: false, expiresAt: decoded.exp };
133
+ }
134
+ const optimistic = {
135
+ status: "active",
136
+ user: userFromClaims(decoded),
137
+ verified: false,
138
+ expiresAt: decoded.exp
139
+ };
140
+ if (mode === "optimistic") return optimistic;
141
+ const cached = this.cache.get(accessToken);
142
+ if (cached) return cached;
143
+ try {
144
+ const { user } = await this.auth.me({
145
+ accessToken,
146
+ timeoutMs: this.verifyTimeoutMs
147
+ });
148
+ const result = user ? { status: "active", user, verified: true, expiresAt: decoded.exp } : { status: "anonymous", user: null, verified: true };
149
+ this.cache.set(accessToken, result, this.ttlMs);
150
+ return result;
151
+ } catch (err) {
152
+ if (isDontCodeError(err) && err.status === 401) {
153
+ return { status: "anonymous", user: null, verified: true };
154
+ }
155
+ return { ...optimistic, status: "unavailable" };
156
+ }
157
+ }
158
+ };
159
+
1
160
  // src/auth.ts
2
161
  var AUTH_BASE = "/api/v1/auth";
3
162
  var MfaApi = class {
@@ -42,9 +201,10 @@ var MfaApi = class {
42
201
  }
43
202
  };
44
203
  var AuthApi = class {
45
- constructor(transport) {
204
+ constructor(transport, sessionOptions) {
46
205
  this.transport = transport;
47
206
  this.mfa = new MfaApi(transport);
207
+ this.sessions = new SessionVerifier(this, sessionOptions);
48
208
  }
49
209
  /** Create an account. If the project requires email verification the
50
210
  * response has `verification_required: true` and NO tokens; collect a
@@ -66,9 +226,46 @@ var AuthApi = class {
66
226
  password: input.password
67
227
  });
68
228
  }
69
- /** Resolve the signed-in user from their access token, or `{ user: null }`. */
229
+ /** Resolve the signed-in user from their access token, or `{ user: null }`.
230
+ * This is a network round-trip; for a per-navigation guard prefer
231
+ * `getSession`, which can answer offline and caches verified results. */
70
232
  me(input) {
71
- return this.transport.json(`${AUTH_BASE}/me`, {}, { accessToken: input.accessToken });
233
+ return this.transport.json(
234
+ `${AUTH_BASE}/me`,
235
+ {},
236
+ { accessToken: input.accessToken, timeoutMs: input.timeoutMs }
237
+ );
238
+ }
239
+ /**
240
+ * Resolve an access token into a session for a route guard, the one call
241
+ * that replaces "hit `me` on every navigation". Two modes:
242
+ *
243
+ * - `'optimistic'` (default): decode the token locally and trust its
244
+ * claims. Zero network, zero stall. The right default for gating page
245
+ * loads. It does NOT verify the signature and will not notice a
246
+ * server-side revocation until the token's own `exp`.
247
+ * - `'verified'`: confirm against the gateway's `me`, cached for a short
248
+ * TTL with a hard timeout. Use it before sensitive actions. On a
249
+ * timeout/outage it returns `status: 'unavailable'` with the optimistic
250
+ * user, so you choose whether to fail open rather than the SDK guessing.
251
+ *
252
+ * See the BYOC docs ("Sessions") for the full reasoning and best practices.
253
+ */
254
+ getSession(input) {
255
+ return this.sessions.getSession(input);
256
+ }
257
+ /** Read the access token from a `Cookie` request header and resolve it, in
258
+ * one call. `name` defaults to `dc_access_token`. Returns the anonymous
259
+ * session when no cookie is present. */
260
+ sessionFromCookies(cookieHeader, options = {}) {
261
+ const token = readSessionToken(cookieHeader, options.cookieName);
262
+ if (!token) return Promise.resolve({ status: "anonymous", user: null, verified: false });
263
+ return this.sessions.getSession({ accessToken: token, mode: options.mode });
264
+ }
265
+ /** Decode an access token's claims locally without a network call or any
266
+ * signature check. Convenience re-export of `decodeAccessToken`. */
267
+ decodeToken(token) {
268
+ return decodeAccessToken(token);
72
269
  }
73
270
  /** Confirm the 6-digit code emailed at signup. */
74
271
  verifyEmail(input) {
@@ -158,27 +355,8 @@ function createDb(transport) {
158
355
  });
159
356
  }
160
357
 
161
- // src/errors.ts
162
- var DontCodeError = class extends Error {
163
- constructor(status, body) {
164
- const message = typeof body?.error === "string" && body.error.length > 0 ? body.error : `DontCode request failed with status ${status}`;
165
- super(message);
166
- this.name = "DontCodeError";
167
- this.status = status;
168
- this.code = typeof body?.code === "string" ? body.code : void 0;
169
- this.body = body ?? {};
170
- }
171
- /** True when the request was rejected by the per-key rate limiter. */
172
- get rateLimited() {
173
- return this.status === 429;
174
- }
175
- };
176
- function isDontCodeError(err) {
177
- if (err instanceof DontCodeError) return true;
178
- return typeof err === "object" && err !== null && err.name === "DontCodeError";
179
- }
180
-
181
358
  // src/http.ts
359
+ var DEFAULT_TIMEOUT_MS = 1e4;
182
360
  var Transport = class {
183
361
  constructor(config) {
184
362
  this.config = config;
@@ -192,22 +370,54 @@ var Transport = class {
192
370
  url(path) {
193
371
  return `${this.config.baseUrl}${path}`;
194
372
  }
373
+ timeout(opts) {
374
+ const value = opts?.timeoutMs ?? this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
375
+ return value > 0 ? value : 0;
376
+ }
377
+ /**
378
+ * One fetch, with a timeout that turns "hung socket" into a fast, typed
379
+ * failure. A timeout surfaces as `DontCodeError` with status 408 / code
380
+ * `Timeout`; any other transport failure (DNS, refused, offline) as status
381
+ * 0 / code `NetworkError`. Both are distinct from a real `401`, so an auth
382
+ * guard can tell "backend is down" apart from "user is signed out".
383
+ */
384
+ async send(path, init, opts) {
385
+ const timeoutMs = this.timeout(opts);
386
+ const controller = timeoutMs > 0 ? new AbortController() : void 0;
387
+ const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : void 0;
388
+ try {
389
+ return await fetch(this.url(path), { ...init, signal: controller?.signal });
390
+ } catch (err) {
391
+ if (controller?.signal.aborted) {
392
+ throw new DontCodeError(408, {
393
+ error: `Request to ${path} timed out after ${timeoutMs}ms`,
394
+ code: "Timeout"
395
+ });
396
+ }
397
+ throw new DontCodeError(0, {
398
+ error: err instanceof Error ? err.message : "Network request failed",
399
+ code: "NetworkError"
400
+ });
401
+ } finally {
402
+ if (timer) clearTimeout(timer);
403
+ }
404
+ }
195
405
  /** POST a JSON body and parse the JSON response. */
196
406
  async json(path, body, opts) {
197
- const res = await fetch(this.url(path), {
198
- method: "POST",
199
- headers: { ...this.headers(opts), "Content-Type": "application/json" },
200
- body: JSON.stringify(body ?? {})
201
- });
407
+ const res = await this.send(
408
+ path,
409
+ {
410
+ method: "POST",
411
+ headers: { ...this.headers(opts), "Content-Type": "application/json" },
412
+ body: JSON.stringify(body ?? {})
413
+ },
414
+ opts
415
+ );
202
416
  return this.parse(res);
203
417
  }
204
418
  /** PUT a multipart form (file uploads). The runtime sets the boundary. */
205
419
  async multipart(path, form, opts) {
206
- const res = await fetch(this.url(path), {
207
- method: "PUT",
208
- headers: this.headers(opts),
209
- body: form
210
- });
420
+ const res = await this.send(path, { method: "PUT", headers: this.headers(opts), body: form }, opts);
211
421
  return this.parse(res);
212
422
  }
213
423
  async parse(res) {
@@ -317,9 +527,9 @@ function dontcode(options = {}) {
317
527
  /\/+$/,
318
528
  ""
319
529
  );
320
- const transport = new Transport({ apiKey, baseUrl });
530
+ const transport = new Transport({ apiKey, baseUrl, timeoutMs: options.timeoutMs });
321
531
  return {
322
- auth: new AuthApi(transport),
532
+ auth: new AuthApi(transport, options.session),
323
533
  db: createDb(transport),
324
534
  storage: createStorage(transport)
325
535
  };
@@ -327,12 +537,19 @@ function dontcode(options = {}) {
327
537
  export {
328
538
  AuthApi,
329
539
  BucketClient,
540
+ DEFAULT_SESSION_COOKIE_NAME,
330
541
  DontCodeError,
542
+ InMemorySessionCache,
331
543
  MfaApi,
332
544
  PublicBucketClient,
333
545
  TableQuery,
546
+ clearSessionCookie,
334
547
  createStorage,
548
+ decodeAccessToken,
335
549
  dontcode,
336
- isDontCodeError
550
+ isDontCodeError,
551
+ isSessionExpired,
552
+ readSessionToken,
553
+ serializeSessionCookie
337
554
  };
338
555
  //# sourceMappingURL=index.js.map