@dontcode2/backend 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +261 -37
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +196 -3
- package/dist/index.d.ts +196 -3
- package/dist/index.js +253 -36
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
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(
|
|
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
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
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
|
|
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
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/auth.ts","../src/db.ts","../src/errors.ts","../src/http.ts","../src/storage.ts","../src/client.ts"],"sourcesContent":["import { Transport } from './http'\nimport type {\n ForgotPasswordInput,\n LoginInput,\n LoginResult,\n MeResult,\n MfaChallengeInput,\n MfaDisableInput,\n MfaEnrollConfirmInput,\n MfaEnrollResult,\n ResetPasswordInput,\n SignupInput,\n SignupResult,\n SimpleResult,\n VerifyEmailInput,\n} from './types'\n\nconst AUTH_BASE = '/api/v1/auth'\n\n/**\n * MFA is per-user and opt-in. `enroll`/`enrollConfirm`/`disable` act as the\n * signed-in user, so they need the end-user access token. `challenge` does\n * not; it completes a login that returned `mfa_required`, exchanging the\n * short-lived challenge token for real session tokens.\n */\nexport class MfaApi {\n constructor(private readonly transport: Transport) {}\n\n /** Complete an MFA login. Pass the `challenge_token` from `login`, plus\n * either the authenticator `code` or a `recoveryCode`. */\n challenge(input: MfaChallengeInput): Promise<LoginResult> {\n return this.transport.json<LoginResult>(`${AUTH_BASE}/mfa/challenge`, {\n challenge_token: input.challengeToken,\n code: input.code,\n recovery_code: input.recoveryCode,\n })\n }\n\n /** Begin enrollment. Render the returned `otpauth_url` as a QR code.\n * Enrollment stays pending until `enrollConfirm`. */\n enroll(input: { accessToken: string }): Promise<MfaEnrollResult> {\n return this.transport.json<MfaEnrollResult>(\n `${AUTH_BASE}/mfa/enroll`,\n {},\n { accessToken: input.accessToken }\n )\n }\n\n /** Confirm enrollment with the first authenticator code. The returned\n * `recovery_codes` are shown once and never again. */\n enrollConfirm(input: MfaEnrollConfirmInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(\n `${AUTH_BASE}/mfa/enroll/confirm`,\n { code: input.code },\n { accessToken: input.accessToken }\n )\n }\n\n /** Turn MFA off. Proves possession of the second factor via `code` or\n * `recoveryCode`. */\n disable(input: MfaDisableInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(\n `${AUTH_BASE}/mfa/disable`,\n { code: input.code, recovery_code: input.recoveryCode },\n { accessToken: input.accessToken }\n )\n }\n}\n\n/**\n * Fronts DontCode Auth with the same shapes as the gateway. Two behaviours are\n * project settings (not API flags) and your code must handle both states:\n * email verification (signup may not return tokens) and MFA (login may be two\n * steps). Branch on the resolved value; never assume one round-trip.\n */\nexport class AuthApi {\n readonly mfa: MfaApi\n\n constructor(private readonly transport: Transport) {\n this.mfa = new MfaApi(transport)\n }\n\n /** Create an account. If the project requires email verification the\n * response has `verification_required: true` and NO tokens; collect a\n * code and call `verifyEmail`, then `login`. */\n signup(input: SignupInput): Promise<SignupResult> {\n return this.transport.json<SignupResult>(`${AUTH_BASE}/signup`, {\n email: input.email,\n password: input.password,\n name: input.name,\n role: input.role,\n })\n }\n\n /** Authenticate. Branch on `mfa_required`: when true you hold only a\n * challenge (finish via `mfa.challenge`); otherwise `tokens` is your\n * session. A 403 `EmailNotVerified` means the email step isn't done. */\n login(input: LoginInput): Promise<LoginResult> {\n return this.transport.json<LoginResult>(`${AUTH_BASE}/login`, {\n email: input.email,\n password: input.password,\n })\n }\n\n /** Resolve the signed-in user from their access token, or `{ user: null }`. */\n me(input: { accessToken: string }): Promise<MeResult> {\n return this.transport.json<MeResult>(`${AUTH_BASE}/me`, {}, { accessToken: input.accessToken })\n }\n\n /** Confirm the 6-digit code emailed at signup. */\n verifyEmail(input: VerifyEmailInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(`${AUTH_BASE}/verify-email`, {\n code: input.code,\n email: input.email,\n })\n }\n\n forgotPassword(input: ForgotPasswordInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(`${AUTH_BASE}/forgot-password`, {\n email: input.email,\n })\n }\n\n resetPassword(input: ResetPasswordInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(`${AUTH_BASE}/reset-password`, {\n code: input.code,\n password: input.password,\n email: input.email,\n })\n }\n}\n","import { Transport } from './http'\nimport type {\n DeleteInput,\n MigrateInput,\n MigrateResult,\n QueryOptions,\n UpdateInput,\n} from './types'\n\nconst DB_PATH = '/api/v1/db'\nconst MIGRATE_PATH = '/api/v1/db/migrate'\n\n/** The gateway wraps every DB result in `{ data }`; we unwrap it. */\ninterface DbEnvelope<T> {\n data: T\n}\n\n/**\n * A handle to one table. Structured queries only; there is no raw-SQL escape\n * hatch (schema changes go through `db.migrate`). `update` and `delete`\n * require a `where` clause server-side, so the types make it mandatory.\n */\nexport class TableQuery {\n constructor(\n private readonly transport: Transport,\n private readonly tableName: string\n ) {}\n\n private async run<T>(operation: string, options: unknown): Promise<T> {\n const res = await this.transport.json<DbEnvelope<T>>(DB_PATH, {\n operation,\n tableName: this.tableName,\n options,\n })\n return res.data\n }\n\n /** Rows matching the query (max 1000 per call). */\n find<T = Record<string, unknown>>(options: QueryOptions = {}): Promise<T[]> {\n return this.run<T[]>('find', options)\n }\n\n /** Alias of `find`. */\n findMany<T = Record<string, unknown>>(options: QueryOptions = {}): Promise<T[]> {\n return this.run<T[]>('findMany', options)\n }\n\n /** The first matching row, or `null`. */\n findFirst<T = Record<string, unknown>>(options: QueryOptions = {}): Promise<T | null> {\n return this.run<T | null>('findFirst', options)\n }\n\n /** Alias of `findFirst`. */\n findOne<T = Record<string, unknown>>(options: QueryOptions = {}): Promise<T | null> {\n return this.run<T | null>('findOne', options)\n }\n\n /** Insert one row. Returns `{ id }`. Unique/FK conflicts throw a 409\n * DontCodeError, the supported idempotency signal. */\n insert(data: Record<string, unknown>): Promise<{ id: unknown }> {\n return this.run<{ id: unknown }>('insert', { data })\n }\n\n /** Update rows matching `where`. Returns `{ count }`. */\n update(input: UpdateInput): Promise<{ count: number }> {\n return this.run<{ count: number }>('update', { where: input.where, data: input.data })\n }\n\n /** Delete rows matching `where`. Returns `{ count }`. */\n delete(input: DeleteInput): Promise<{ count: number }> {\n return this.run<{ count: number }>('delete', { where: input.where })\n }\n\n /** Count matching rows. */\n count(options: Pick<QueryOptions, 'where'> = {}): Promise<number> {\n return this.run<number>('count', options)\n }\n}\n\n/**\n * `db.users.find()` and `db('users').find()` both work; the bracket/callable\n * form is there for table names that aren't valid identifiers. `db.migrate()`\n * applies schema DDL (the one place migrations enter from outside).\n */\nexport type DbClient = {\n readonly [tableName: string]: TableQuery\n} & {\n (tableName: string): TableQuery\n migrate(input: MigrateInput): Promise<MigrateResult>\n}\n\nexport function createDb(transport: Transport): DbClient {\n const table = (tableName: string): TableQuery => new TableQuery(transport, tableName)\n const migrate = (input: MigrateInput): Promise<MigrateResult> =>\n transport.json<MigrateResult>(MIGRATE_PATH, { sql: input.sql })\n\n return new Proxy(table, {\n get(target, prop, receiver) {\n if (prop === 'migrate') return migrate\n // Don't manufacture a TableQuery for symbols or promise-unwrapping\n // probes (`then`) or the function's own members.\n if (typeof prop !== 'string' || prop === 'then' || prop in target) {\n return Reflect.get(target, prop, receiver)\n }\n return new TableQuery(transport, prop)\n },\n apply(_target, _thisArg, args: [string]) {\n return table(args[0])\n },\n }) as unknown as DbClient\n}\n","/**\n * Every non-2xx response from the gateway surfaces as a DontCodeError. The\n * platform's error envelope is `{ error, ... }`, sometimes with a machine\n * `code` (e.g. `EmailNotVerified`, `ChallengeExpired`, `MfaNotOffered`) or\n * rate-limit fields. We preserve the whole body so callers can branch on it.\n *\n * Note: many \"one more step\" auth states (signup needing email verification,\n * login returning `mfa_required`) are 2xx successes, NOT errors; inspect the\n * resolved value for those. Errors are reserved for actual failures.\n */\nexport interface DontCodeErrorBody {\n error?: string\n /** Stable machine code, when the platform sends one. */\n code?: string\n /** Present on 429 responses. */\n rate_limit?: boolean\n /** Seconds until the rate limit resets, on 429 responses. */\n timeleft?: number\n [key: string]: unknown\n}\n\nexport class DontCodeError extends Error {\n /** HTTP status code of the failing response. */\n readonly status: number\n /** Stable machine code, when present (e.g. `EmailNotVerified`). */\n readonly code?: string\n /** The raw parsed response body. */\n readonly body: DontCodeErrorBody\n\n constructor(status: number, body: DontCodeErrorBody) {\n const message =\n typeof body?.error === 'string' && body.error.length > 0\n ? body.error\n : `DontCode request failed with status ${status}`\n super(message)\n this.name = 'DontCodeError'\n this.status = status\n this.code = typeof body?.code === 'string' ? body.code : undefined\n this.body = body ?? {}\n }\n\n /** True when the request was rejected by the per-key rate limiter. */\n get rateLimited(): boolean {\n return this.status === 429\n }\n}\n\n/** Cross-bundle-safe check; works even if two copies of the SDK are loaded. */\nexport function isDontCodeError(err: unknown): err is DontCodeError {\n if (err instanceof DontCodeError) return true\n return (\n typeof err === 'object' &&\n err !== null &&\n (err as { name?: unknown }).name === 'DontCodeError'\n )\n}\n","import { DontCodeError, type DontCodeErrorBody } from './errors'\n\nexport interface TransportConfig {\n /** Project API key. When absent, no Authorization header is sent and the\n * gateway responds with its own \"Missing API key\" 401. */\n apiKey?: string\n /** Gateway origin, already normalized (no trailing slash). */\n baseUrl: string\n}\n\nexport interface RequestOptions {\n /** End-user access token, sent as `X-Access-Token` (separate from the\n * project API key). Required by signed-in auth calls. */\n accessToken?: string\n}\n\n/**\n * The single place network requests are made. Everything else in the SDK is a\n * typed shape around `json()` / `multipart()`. No retries, no caching, just a\n * faithful proxy of the v1 gateway.\n */\nexport class Transport {\n constructor(private readonly config: TransportConfig) {}\n\n private headers(opts?: RequestOptions): Record<string, string> {\n const headers: Record<string, string> = {}\n if (this.config.apiKey) headers['Authorization'] = `Bearer ${this.config.apiKey}`\n if (opts?.accessToken) headers['X-Access-Token'] = opts.accessToken\n return headers\n }\n\n private url(path: string): string {\n return `${this.config.baseUrl}${path}`\n }\n\n /** POST a JSON body and parse the JSON response. */\n async json<T>(path: string, body?: unknown, opts?: RequestOptions): Promise<T> {\n const res = await fetch(this.url(path), {\n method: 'POST',\n headers: { ...this.headers(opts), 'Content-Type': 'application/json' },\n body: JSON.stringify(body ?? {}),\n })\n return this.parse<T>(res)\n }\n\n /** PUT a multipart form (file uploads). The runtime sets the boundary. */\n async multipart<T>(path: string, form: FormData, opts?: RequestOptions): Promise<T> {\n const res = await fetch(this.url(path), {\n method: 'PUT',\n headers: this.headers(opts),\n body: form,\n })\n return this.parse<T>(res)\n }\n\n private async parse<T>(res: Response): Promise<T> {\n const raw = await res.text()\n let data: unknown = null\n if (raw) {\n try {\n data = JSON.parse(raw)\n } catch {\n data = { error: raw }\n }\n }\n if (!res.ok) {\n const body: DontCodeErrorBody =\n data && typeof data === 'object'\n ? (data as DontCodeErrorBody)\n : { error: res.statusText || 'Request failed' }\n throw new DontCodeError(res.status, body)\n }\n return data as T\n }\n}\n","import { Transport } from './http'\nimport type {\n DownloadResult,\n ListResult,\n PresignResult,\n StorageBucket,\n StorageObject,\n TemporaryUrlResult,\n UploadBody,\n} from './types'\n\nconst STORAGE_PATH = '/api/v1/storage'\n\nconst DEFAULT_CONTENT_TYPE = 'application/octet-stream'\n\n/** Normalize whatever the caller hands us into a Blob for multipart upload. */\nfunction toBlob(body: UploadBody, contentType: string): Blob {\n if (body instanceof Blob) return body\n if (typeof body === 'string') return new Blob([body], { type: contentType })\n if (body instanceof ArrayBuffer) return new Blob([body], { type: contentType })\n if (ArrayBuffer.isView(body)) {\n return new Blob([body as unknown as BlobPart], { type: contentType })\n }\n throw new TypeError('upload expects a Blob, ArrayBuffer, typed array, or string')\n}\n\nfunction fileName(path: string): string {\n return path.split('/').filter(Boolean).pop() ?? path\n}\n\n/** Operations available on both buckets. */\nexport class BucketClient {\n constructor(\n protected readonly transport: Transport,\n protected readonly bucket: StorageBucket\n ) {}\n\n protected op<T>(operation: string, params: Record<string, unknown> = {}): Promise<T> {\n return this.transport.json<T>(STORAGE_PATH, { operation, bucket: this.bucket, ...params })\n }\n\n /** List objects under `prefix`. */\n list(prefix?: string): Promise<ListResult> {\n return this.op<ListResult>('list', { prefix })\n }\n\n /** Delete one or more objects. Returns `{ deleted }`. */\n remove(paths: string[]): Promise<{ deleted: number }> {\n return this.op<{ deleted: number }>('remove', { paths })\n }\n\n /** Move/rename an object within the bucket. */\n move(from: string, to: string): Promise<{ object: StorageObject }> {\n return this.op<{ object: StorageObject }>('move', { from, to })\n }\n\n createFolder(path: string): Promise<{ created: string }> {\n return this.op<{ created: string }>('createFolder', { path })\n }\n\n /** Download an object inline (≤ 8 MB). Use `getTemporaryUrl` for larger files. */\n download(path: string): Promise<DownloadResult> {\n return this.op<DownloadResult>('download', { path })\n }\n\n /** A short-lived signed URL (default 300s, max 7 days). */\n getTemporaryUrl(path: string, expiresIn?: number): Promise<TemporaryUrlResult> {\n return this.op<TemporaryUrlResult>('getTemporaryUrl', { path, expiresIn })\n }\n\n /** A presigned PUT URL for direct, large uploads (≤ no inline limit). */\n presignUpload(path: string, contentType?: string): Promise<PresignResult> {\n return this.op<PresignResult>('presignUpload', { path, contentType })\n }\n\n /** Upload bytes directly (≤ 100 MB). For larger files, `presignUpload`\n * then PUT to the returned URL yourself. */\n upload(\n path: string,\n body: UploadBody,\n contentType: string = DEFAULT_CONTENT_TYPE\n ): Promise<{ object: StorageObject }> {\n const form = new FormData()\n form.append('file', toBlob(body, contentType), fileName(path))\n form.append('bucket', this.bucket)\n form.append('path', path)\n form.append('contentType', contentType)\n return this.transport.multipart<{ object: StorageObject }>(STORAGE_PATH, form)\n }\n}\n\n/** The public bucket additionally exposes stable public URLs. */\nexport class PublicBucketClient extends BucketClient {\n constructor(transport: Transport) {\n super(transport, 'public')\n }\n\n /** The permanent public URL for an object. */\n getUrl(path: string): Promise<{ url: string }> {\n return this.op<{ url: string }>('getUrl', { path })\n }\n}\n\nexport interface StorageClient {\n public: PublicBucketClient\n private: BucketClient\n}\n\nexport function createStorage(transport: Transport): StorageClient {\n return {\n public: new PublicBucketClient(transport),\n private: new BucketClient(transport, 'private'),\n }\n}\n","import { AuthApi } from './auth'\nimport { createDb, type DbClient } from './db'\nimport { Transport } from './http'\nimport { createStorage, type StorageClient } from './storage'\n\nconst DEFAULT_BASE_URL = 'https://backend.dontcode.co'\n\nexport interface DontCodeClientOptions {\n /** Project API key (`dc_…`). Defaults to `process.env.DONTCODE_API_KEY`.\n * If neither is set, requests fail naturally with the gateway's\n * \"Missing API key\" 401. */\n apiKey?: string\n /** Gateway origin. Defaults to `process.env.DONTCODE_API_URL`, then to\n * `https://backend.dontcode.co`. */\n baseUrl?: string\n}\n\nexport interface DontCodeClient {\n auth: AuthApi\n db: DbClient\n storage: StorageClient\n}\n\n/** Read an env var without assuming `process` exists (e.g. in the browser). */\nfunction fromEnv(name: string): string | undefined {\n if (typeof process === 'undefined' || !process.env) return undefined\n return process.env[name]\n}\n\n/**\n * Create a DontCode backend client. A thin, typed proxy over the v1 HTTP\n * gateway: auth, database, and storage. The API key scopes every request to\n * a single project; there is nothing else to configure.\n *\n * ```ts\n * import { dontcode } from '@dontcode2/backend'\n * const client = dontcode() // reads DONTCODE_API_KEY\n * await client.auth.signup({ email, password, role: 'editor' })\n * ```\n */\nexport function dontcode(options: DontCodeClientOptions = {}): DontCodeClient {\n const apiKey = options.apiKey ?? fromEnv('DONTCODE_API_KEY')\n const baseUrl = (options.baseUrl ?? fromEnv('DONTCODE_API_URL') ?? DEFAULT_BASE_URL).replace(\n /\\/+$/,\n ''\n )\n\n const transport = new Transport({ apiKey, baseUrl })\n\n return {\n auth: new AuthApi(transport),\n db: createDb(transport),\n storage: createStorage(transport),\n }\n}\n"],"mappings":";AAiBA,IAAM,YAAY;AAQX,IAAM,SAAN,MAAa;AAAA,EAChB,YAA6B,WAAsB;AAAtB;AAA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,aAAa,WAAW,SAAS;AAAA,EAClD;AACJ;;;AC5GA,IAAM,mBAAmB;AAmBzB,SAAS,QAAQ,MAAkC;AAC/C,MAAI,OAAO,YAAY,eAAe,CAAC,QAAQ,IAAK,QAAO;AAC3D,SAAO,QAAQ,IAAI,IAAI;AAC3B;AAaO,SAAS,SAAS,UAAiC,CAAC,GAAmB;AAC1E,QAAM,SAAS,QAAQ,UAAU,QAAQ,kBAAkB;AAC3D,QAAM,WAAW,QAAQ,WAAW,QAAQ,kBAAkB,KAAK,kBAAkB;AAAA,IACjF;AAAA,IACA;AAAA,EACJ;AAEA,QAAM,YAAY,IAAI,UAAU,EAAE,QAAQ,QAAQ,CAAC;AAEnD,SAAO;AAAA,IACH,MAAM,IAAI,QAAQ,SAAS;AAAA,IAC3B,IAAI,SAAS,SAAS;AAAA,IACtB,SAAS,cAAc,SAAS;AAAA,EACpC;AACJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/cookies.ts","../src/errors.ts","../src/session.ts","../src/auth.ts","../src/db.ts","../src/http.ts","../src/storage.ts","../src/client.ts"],"sourcesContent":["/**\n * Cookie helpers, framework-agnostic by design. They return strings: a\n * `Set-Cookie` header value to write, or a parsed token to read. Your framework\n * applies them (`headers.append('Set-Cookie', …)`, SvelteKit `cookies.set`, a\n * Next `Response` cookie, etc.). The SDK never owns a request or response.\n *\n * Defaults match how DontCode's own apps store the session: an httpOnly cookie\n * so JavaScript can't read the token, `Secure`, `SameSite=Lax`, path `/`, and a\n * 7-day max age. Cross-site setups (your app and the gateway on different sites)\n * need `sameSite: 'none'`, which forces `Secure` on.\n */\n\n/** Default cookie name for the end-user access token. */\nexport const DEFAULT_SESSION_COOKIE_NAME = 'dc_access_token'\n\n/** One week, in seconds. Matches the default session lifetime DontCode issues. */\nconst DEFAULT_MAX_AGE_SECONDS = 60 * 60 * 24 * 7\n\nexport interface SessionCookieOptions {\n /** Cookie name. Default `dc_access_token`. */\n name?: string\n /** Lifetime in seconds. Default one week. Pass the token's `ExpiresIn` to\n * keep the cookie and the token in lockstep. */\n maxAge?: number\n /** Default `/`. */\n path?: string\n domain?: string\n /** Default `true`. */\n secure?: boolean\n /** Default `true`. Keep the token unreadable from client JavaScript. */\n httpOnly?: boolean\n /** Default `'lax'`. Use `'none'` for cross-site (it forces `Secure`). */\n sameSite?: 'lax' | 'strict' | 'none'\n}\n\nfunction serialize(name: string, value: string, options: SessionCookieOptions, maxAge: number): string {\n const sameSite = options.sameSite ?? 'lax'\n // SameSite=None is meaningless without Secure (browsers drop it), so force\n // Secure on there; otherwise it defaults on and the caller can opt out.\n const secure = sameSite === 'none' ? true : (options.secure ?? true)\n const httpOnly = options.httpOnly ?? true\n const path = options.path ?? '/'\n\n const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${path}`, `Max-Age=${maxAge}`]\n if (options.domain) parts.push(`Domain=${options.domain}`)\n parts.push(`SameSite=${sameSite.charAt(0).toUpperCase()}${sameSite.slice(1)}`)\n if (httpOnly) parts.push('HttpOnly')\n if (secure) parts.push('Secure')\n return parts.join('; ')\n}\n\n/** Build a `Set-Cookie` value that stores the access token. */\nexport function serializeSessionCookie(token: string, options: SessionCookieOptions = {}): string {\n const name = options.name ?? DEFAULT_SESSION_COOKIE_NAME\n const maxAge = options.maxAge ?? DEFAULT_MAX_AGE_SECONDS\n return serialize(name, token, options, maxAge)\n}\n\n/** Build a `Set-Cookie` value that clears the access token (logout). */\nexport function clearSessionCookie(options: SessionCookieOptions = {}): string {\n const name = options.name ?? DEFAULT_SESSION_COOKIE_NAME\n return serialize(name, '', options, 0)\n}\n\n/** Read the access token out of a `Cookie` request header, or `null`. Pass the\n * raw header string (`name=value; name2=value2`). */\nexport function readSessionToken(\n cookieHeader: string | null | undefined,\n name: string = DEFAULT_SESSION_COOKIE_NAME\n): string | null {\n if (!cookieHeader) return null\n for (const pair of cookieHeader.split(';')) {\n const eq = pair.indexOf('=')\n if (eq === -1) continue\n if (pair.slice(0, eq).trim() !== name) continue\n const raw = pair.slice(eq + 1).trim()\n if (!raw) return null\n try {\n return decodeURIComponent(raw)\n } catch {\n return raw\n }\n }\n return null\n}\n","/**\n * Every non-2xx response from the gateway surfaces as a DontCodeError. The\n * platform's error envelope is `{ error, ... }`, sometimes with a machine\n * `code` (e.g. `EmailNotVerified`, `ChallengeExpired`, `MfaNotOffered`) or\n * rate-limit fields. We preserve the whole body so callers can branch on it.\n *\n * Note: many \"one more step\" auth states (signup needing email verification,\n * login returning `mfa_required`) are 2xx successes, NOT errors; inspect the\n * resolved value for those. Errors are reserved for actual failures.\n *\n * Transport failures (no HTTP response at all) also surface as a DontCodeError\n * so callers have one error type: a timeout is status 408 / code `Timeout`, and\n * any other network failure is status 0 / code `NetworkError`. Neither is a\n * `401`, so a guard can distinguish \"backend unavailable\" from \"signed out\".\n */\nexport interface DontCodeErrorBody {\n error?: string\n /** Stable machine code, when the platform sends one. */\n code?: string\n /** Present on 429 responses. */\n rate_limit?: boolean\n /** Seconds until the rate limit resets, on 429 responses. */\n timeleft?: number\n [key: string]: unknown\n}\n\nexport class DontCodeError extends Error {\n /** HTTP status code of the failing response. */\n readonly status: number\n /** Stable machine code, when present (e.g. `EmailNotVerified`). */\n readonly code?: string\n /** The raw parsed response body. */\n readonly body: DontCodeErrorBody\n\n constructor(status: number, body: DontCodeErrorBody) {\n const message =\n typeof body?.error === 'string' && body.error.length > 0\n ? body.error\n : `DontCode request failed with status ${status}`\n super(message)\n this.name = 'DontCodeError'\n this.status = status\n this.code = typeof body?.code === 'string' ? body.code : undefined\n this.body = body ?? {}\n }\n\n /** True when the request was rejected by the per-key rate limiter. */\n get rateLimited(): boolean {\n return this.status === 429\n }\n}\n\n/** Cross-bundle-safe check; works even if two copies of the SDK are loaded. */\nexport function isDontCodeError(err: unknown): err is DontCodeError {\n if (err instanceof DontCodeError) return true\n return (\n typeof err === 'object' &&\n err !== null &&\n (err as { name?: unknown }).name === 'DontCodeError'\n )\n}\n","import { isDontCodeError } from './errors'\nimport type { AuthApi } from './auth'\nimport type { CurrentUser } from './types'\n\n/**\n * Session helpers, framework-agnostic by design. They never touch a request or\n * response object; they take a token (or a cookie header) and return plain\n * data, so they slot into any framework's guard (Next middleware, SvelteKit\n * hooks, Express, a worker) without an adapter.\n *\n * The point of the module: an auth guard must not make a network round-trip on\n * every navigation, or a slow gateway stalls the page and a swallowed timeout\n * reads as \"signed out\". So there are two modes:\n *\n * - optimistic — decode the token locally (no signature check, no network)\n * and trust its claims for routing. Instant. Used for the common gate.\n * - verified — call the gateway's `me` once, cache the result for a short\n * TTL, and hard-timeout the request. Used for sensitive actions.\n *\n * The trade-offs (no signature verification, revocation lag) are documented on\n * `getSession` and in the public BYOC docs; read them before choosing a mode.\n */\n\n/** A JWT payload decoded WITHOUT verifying its signature. Trust accordingly. */\nexport interface DecodedSession {\n /** Subject — the user id. */\n sub: string\n email?: string\n role?: string\n claims?: Record<string, unknown>\n /** Expiry, seconds since the epoch (standard JWT `exp`). */\n exp?: number\n /** Issued-at, seconds since the epoch (standard JWT `iat`). */\n iat?: number\n [key: string]: unknown\n}\n\nexport type SessionStatus =\n /** A usable session: a present, unexpired token (verified or optimistic). */\n | 'active'\n /** The token is present but past its `exp`. */\n | 'expired'\n /** No token, or an unparseable one. */\n | 'anonymous'\n /** Verified mode could not reach the gateway (timeout/network/5xx). The\n * optimistically-decoded `user` is still returned so the caller can choose\n * to fail open during an outage instead of logging everyone out. */\n | 'unavailable'\n\nexport interface SessionResult {\n status: SessionStatus\n /** The signed-in user, or `null` when anonymous/expired. In `verified` mode\n * this came from the gateway; in `optimistic` (or `unavailable`) it was\n * decoded from the token's own claims. */\n user: CurrentUser | null\n /** True only when `user` was confirmed by a gateway `me` call this request\n * (or from a fresh cache entry of one). False for optimistic decodes. */\n verified: boolean\n /** The token's `exp` (seconds since epoch), when present. */\n expiresAt?: number\n}\n\nexport interface GetSessionInput {\n accessToken: string\n /** `optimistic` (default): decode locally, zero network. `verified`: confirm\n * against the gateway with caching + a hard timeout. */\n mode?: 'optimistic' | 'verified'\n}\n\n/** A place to cache verified sessions. Swap the default in-memory store for a\n * shared one (Redis, KV) when running multiple instances. */\nexport interface SessionCache {\n get(token: string): SessionResult | undefined\n set(token: string, value: SessionResult, ttlMs: number): void\n delete?(token: string): void\n}\n\nexport interface SessionOptions {\n /** Cache for verified sessions. Defaults to a per-process `InMemorySessionCache`. */\n cache?: SessionCache\n /** How long a verified session stays cached. Default 60_000 (60s). Keep it\n * short: a cached session can outlive a server-side revocation by up to\n * this long. */\n ttlMs?: number\n /** Timeout for the `me` call made by `verified` mode (ms). Default 5_000. */\n verifyTimeoutMs?: number\n}\n\nconst DEFAULT_TTL_MS = 60_000\nconst DEFAULT_VERIFY_TIMEOUT_MS = 5_000\n\n/** Default cache: a `Map` with per-entry TTL. Lives for the life of the process\n * (and is shared across requests on a reused serverless instance). */\nexport class InMemorySessionCache implements SessionCache {\n private readonly store = new Map<string, { value: SessionResult; expiresAtMs: number }>()\n\n get(token: string): SessionResult | undefined {\n const hit = this.store.get(token)\n if (!hit) return undefined\n if (Date.now() >= hit.expiresAtMs) {\n this.store.delete(token)\n return undefined\n }\n return hit.value\n }\n\n set(token: string, value: SessionResult, ttlMs: number): void {\n this.store.set(token, { value, expiresAtMs: Date.now() + ttlMs })\n }\n\n delete(token: string): void {\n this.store.delete(token)\n }\n}\n\nfunction base64UrlDecode(segment: string): string {\n const base64 = segment.replace(/-/g, '+').replace(/_/g, '/')\n const padded = base64.length % 4 === 0 ? base64 : base64 + '='.repeat(4 - (base64.length % 4))\n if (typeof atob === 'function') {\n const binary = atob(padded)\n const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0))\n return new TextDecoder().decode(bytes)\n }\n // Node without a global atob (older runtimes); Buffer is always present there.\n return Buffer.from(padded, 'base64').toString('utf8')\n}\n\n/**\n * Decode a JWT access token's payload WITHOUT verifying its signature, or\n * return `null` if it is not a parseable JWT. This is deliberately cheap and\n * offline; it is not proof the token is genuine. DontCode tokens are signed\n * with a secret the gateway never shares, so the only authority on a token is\n * the gateway's `me` endpoint — use `getSession({ mode: 'verified' })` when you\n * need that authority.\n */\nexport function decodeAccessToken(token: string): DecodedSession | null {\n if (!token || typeof token !== 'string') return null\n const parts = token.split('.')\n if (parts.length < 2) return null\n try {\n const payload = JSON.parse(base64UrlDecode(parts[1])) as Record<string, unknown>\n if (!payload || typeof payload.sub !== 'string') return null\n return payload as DecodedSession\n } catch {\n return null\n }\n}\n\n/** True when a token (or already-decoded payload) is past its `exp`. A token\n * with no `exp` is treated as not expired (the caller cannot prove otherwise\n * offline). `skewSeconds` widens the window to absorb clock drift. */\nexport function isSessionExpired(\n input: string | DecodedSession | null,\n opts: { skewSeconds?: number } = {}\n): boolean {\n const decoded = typeof input === 'string' ? decodeAccessToken(input) : input\n if (!decoded || typeof decoded.exp !== 'number') return false\n const nowSeconds = Date.now() / 1000\n return nowSeconds >= decoded.exp - (opts.skewSeconds ?? 0)\n}\n\nfunction userFromClaims(decoded: DecodedSession): CurrentUser {\n return {\n id: decoded.sub,\n email: typeof decoded.email === 'string' ? decoded.email : '',\n role: decoded.role,\n claims: decoded.claims,\n }\n}\n\n/**\n * Resolves access tokens into sessions for `AuthApi`. Holds the verified-session\n * cache and timeout policy. Not exported directly; reach it via\n * `client.auth.getSession` / `client.auth.sessionFromCookies`.\n */\nexport class SessionVerifier {\n private readonly cache: SessionCache\n private readonly ttlMs: number\n private readonly verifyTimeoutMs: number\n\n constructor(\n private readonly auth: AuthApi,\n options: SessionOptions = {}\n ) {\n this.cache = options.cache ?? new InMemorySessionCache()\n this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS\n this.verifyTimeoutMs = options.verifyTimeoutMs ?? DEFAULT_VERIFY_TIMEOUT_MS\n }\n\n async getSession({ accessToken, mode = 'optimistic' }: GetSessionInput): Promise<SessionResult> {\n const decoded = decodeAccessToken(accessToken)\n if (!decoded) return { status: 'anonymous', user: null, verified: false }\n if (isSessionExpired(decoded)) {\n return { status: 'expired', user: null, verified: false, expiresAt: decoded.exp }\n }\n\n const optimistic: SessionResult = {\n status: 'active',\n user: userFromClaims(decoded),\n verified: false,\n expiresAt: decoded.exp,\n }\n if (mode === 'optimistic') return optimistic\n\n const cached = this.cache.get(accessToken)\n if (cached) return cached\n\n try {\n const { user } = await this.auth.me({\n accessToken,\n timeoutMs: this.verifyTimeoutMs,\n })\n const result: SessionResult = user\n ? { status: 'active', user, verified: true, expiresAt: decoded.exp }\n : { status: 'anonymous', user: null, verified: true }\n this.cache.set(accessToken, result, this.ttlMs)\n return result\n } catch (err) {\n // A real 401 means the gateway rejected the token: the user is out.\n if (isDontCodeError(err) && err.status === 401) {\n return { status: 'anonymous', user: null, verified: true }\n }\n // Timeout / network / 5xx: the backend is unreachable, not a verdict\n // on the user. Hand back the optimistic session marked unavailable so\n // the caller decides whether to fail open. Not cached.\n return { ...optimistic, status: 'unavailable' }\n }\n }\n}\n","import { Transport } from './http'\nimport { readSessionToken } from './cookies'\nimport {\n SessionVerifier,\n decodeAccessToken,\n type DecodedSession,\n type GetSessionInput,\n type SessionOptions,\n type SessionResult,\n} from './session'\nimport type {\n ForgotPasswordInput,\n LoginInput,\n LoginResult,\n MeResult,\n MfaChallengeInput,\n MfaDisableInput,\n MfaEnrollConfirmInput,\n MfaEnrollResult,\n ResetPasswordInput,\n SignupInput,\n SignupResult,\n SimpleResult,\n VerifyEmailInput,\n} from './types'\n\nconst AUTH_BASE = '/api/v1/auth'\n\n/**\n * MFA is per-user and opt-in. `enroll`/`enrollConfirm`/`disable` act as the\n * signed-in user, so they need the end-user access token. `challenge` does\n * not; it completes a login that returned `mfa_required`, exchanging the\n * short-lived challenge token for real session tokens.\n */\nexport class MfaApi {\n constructor(private readonly transport: Transport) {}\n\n /** Complete an MFA login. Pass the `challenge_token` from `login`, plus\n * either the authenticator `code` or a `recoveryCode`. */\n challenge(input: MfaChallengeInput): Promise<LoginResult> {\n return this.transport.json<LoginResult>(`${AUTH_BASE}/mfa/challenge`, {\n challenge_token: input.challengeToken,\n code: input.code,\n recovery_code: input.recoveryCode,\n })\n }\n\n /** Begin enrollment. Render the returned `otpauth_url` as a QR code.\n * Enrollment stays pending until `enrollConfirm`. */\n enroll(input: { accessToken: string }): Promise<MfaEnrollResult> {\n return this.transport.json<MfaEnrollResult>(\n `${AUTH_BASE}/mfa/enroll`,\n {},\n { accessToken: input.accessToken }\n )\n }\n\n /** Confirm enrollment with the first authenticator code. The returned\n * `recovery_codes` are shown once and never again. */\n enrollConfirm(input: MfaEnrollConfirmInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(\n `${AUTH_BASE}/mfa/enroll/confirm`,\n { code: input.code },\n { accessToken: input.accessToken }\n )\n }\n\n /** Turn MFA off. Proves possession of the second factor via `code` or\n * `recoveryCode`. */\n disable(input: MfaDisableInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(\n `${AUTH_BASE}/mfa/disable`,\n { code: input.code, recovery_code: input.recoveryCode },\n { accessToken: input.accessToken }\n )\n }\n}\n\n/**\n * Fronts DontCode Auth with the same shapes as the gateway. Two behaviours are\n * project settings (not API flags) and your code must handle both states:\n * email verification (signup may not return tokens) and MFA (login may be two\n * steps). Branch on the resolved value; never assume one round-trip.\n */\nexport class AuthApi {\n readonly mfa: MfaApi\n private readonly sessions: SessionVerifier\n\n constructor(\n private readonly transport: Transport,\n sessionOptions?: SessionOptions\n ) {\n this.mfa = new MfaApi(transport)\n this.sessions = new SessionVerifier(this, sessionOptions)\n }\n\n /** Create an account. If the project requires email verification the\n * response has `verification_required: true` and NO tokens; collect a\n * code and call `verifyEmail`, then `login`. */\n signup(input: SignupInput): Promise<SignupResult> {\n return this.transport.json<SignupResult>(`${AUTH_BASE}/signup`, {\n email: input.email,\n password: input.password,\n name: input.name,\n role: input.role,\n })\n }\n\n /** Authenticate. Branch on `mfa_required`: when true you hold only a\n * challenge (finish via `mfa.challenge`); otherwise `tokens` is your\n * session. A 403 `EmailNotVerified` means the email step isn't done. */\n login(input: LoginInput): Promise<LoginResult> {\n return this.transport.json<LoginResult>(`${AUTH_BASE}/login`, {\n email: input.email,\n password: input.password,\n })\n }\n\n /** Resolve the signed-in user from their access token, or `{ user: null }`.\n * This is a network round-trip; for a per-navigation guard prefer\n * `getSession`, which can answer offline and caches verified results. */\n me(input: { accessToken: string; timeoutMs?: number }): Promise<MeResult> {\n return this.transport.json<MeResult>(\n `${AUTH_BASE}/me`,\n {},\n { accessToken: input.accessToken, timeoutMs: input.timeoutMs }\n )\n }\n\n /**\n * Resolve an access token into a session for a route guard, the one call\n * that replaces \"hit `me` on every navigation\". Two modes:\n *\n * - `'optimistic'` (default): decode the token locally and trust its\n * claims. Zero network, zero stall. The right default for gating page\n * loads. It does NOT verify the signature and will not notice a\n * server-side revocation until the token's own `exp`.\n * - `'verified'`: confirm against the gateway's `me`, cached for a short\n * TTL with a hard timeout. Use it before sensitive actions. On a\n * timeout/outage it returns `status: 'unavailable'` with the optimistic\n * user, so you choose whether to fail open rather than the SDK guessing.\n *\n * See the BYOC docs (\"Sessions\") for the full reasoning and best practices.\n */\n getSession(input: GetSessionInput): Promise<SessionResult> {\n return this.sessions.getSession(input)\n }\n\n /** Read the access token from a `Cookie` request header and resolve it, in\n * one call. `name` defaults to `dc_access_token`. Returns the anonymous\n * session when no cookie is present. */\n sessionFromCookies(\n cookieHeader: string | null | undefined,\n options: { mode?: GetSessionInput['mode']; cookieName?: string } = {}\n ): Promise<SessionResult> {\n const token = readSessionToken(cookieHeader, options.cookieName)\n if (!token) return Promise.resolve({ status: 'anonymous', user: null, verified: false })\n return this.sessions.getSession({ accessToken: token, mode: options.mode })\n }\n\n /** Decode an access token's claims locally without a network call or any\n * signature check. Convenience re-export of `decodeAccessToken`. */\n decodeToken(token: string): DecodedSession | null {\n return decodeAccessToken(token)\n }\n\n /** Confirm the 6-digit code emailed at signup. */\n verifyEmail(input: VerifyEmailInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(`${AUTH_BASE}/verify-email`, {\n code: input.code,\n email: input.email,\n })\n }\n\n forgotPassword(input: ForgotPasswordInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(`${AUTH_BASE}/forgot-password`, {\n email: input.email,\n })\n }\n\n resetPassword(input: ResetPasswordInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(`${AUTH_BASE}/reset-password`, {\n code: input.code,\n password: input.password,\n email: input.email,\n })\n }\n}\n","import { Transport } from './http'\nimport type {\n DeleteInput,\n MigrateInput,\n MigrateResult,\n QueryOptions,\n UpdateInput,\n} from './types'\n\nconst DB_PATH = '/api/v1/db'\nconst MIGRATE_PATH = '/api/v1/db/migrate'\n\n/** The gateway wraps every DB result in `{ data }`; we unwrap it. */\ninterface DbEnvelope<T> {\n data: T\n}\n\n/**\n * A handle to one table. Structured queries only; there is no raw-SQL escape\n * hatch (schema changes go through `db.migrate`). `update` and `delete`\n * require a `where` clause server-side, so the types make it mandatory.\n */\nexport class TableQuery {\n constructor(\n private readonly transport: Transport,\n private readonly tableName: string\n ) {}\n\n private async run<T>(operation: string, options: unknown): Promise<T> {\n const res = await this.transport.json<DbEnvelope<T>>(DB_PATH, {\n operation,\n tableName: this.tableName,\n options,\n })\n return res.data\n }\n\n /** Rows matching the query (max 1000 per call). */\n find<T = Record<string, unknown>>(options: QueryOptions = {}): Promise<T[]> {\n return this.run<T[]>('find', options)\n }\n\n /** Alias of `find`. */\n findMany<T = Record<string, unknown>>(options: QueryOptions = {}): Promise<T[]> {\n return this.run<T[]>('findMany', options)\n }\n\n /** The first matching row, or `null`. */\n findFirst<T = Record<string, unknown>>(options: QueryOptions = {}): Promise<T | null> {\n return this.run<T | null>('findFirst', options)\n }\n\n /** Alias of `findFirst`. */\n findOne<T = Record<string, unknown>>(options: QueryOptions = {}): Promise<T | null> {\n return this.run<T | null>('findOne', options)\n }\n\n /** Insert one row. Returns `{ id }`. Unique/FK conflicts throw a 409\n * DontCodeError, the supported idempotency signal. */\n insert(data: Record<string, unknown>): Promise<{ id: unknown }> {\n return this.run<{ id: unknown }>('insert', { data })\n }\n\n /** Update rows matching `where`. Returns `{ count }`. */\n update(input: UpdateInput): Promise<{ count: number }> {\n return this.run<{ count: number }>('update', { where: input.where, data: input.data })\n }\n\n /** Delete rows matching `where`. Returns `{ count }`. */\n delete(input: DeleteInput): Promise<{ count: number }> {\n return this.run<{ count: number }>('delete', { where: input.where })\n }\n\n /** Count matching rows. */\n count(options: Pick<QueryOptions, 'where'> = {}): Promise<number> {\n return this.run<number>('count', options)\n }\n}\n\n/**\n * `db.users.find()` and `db('users').find()` both work; the bracket/callable\n * form is there for table names that aren't valid identifiers. `db.migrate()`\n * applies schema DDL (the one place migrations enter from outside).\n */\nexport type DbClient = {\n readonly [tableName: string]: TableQuery\n} & {\n (tableName: string): TableQuery\n migrate(input: MigrateInput): Promise<MigrateResult>\n}\n\nexport function createDb(transport: Transport): DbClient {\n const table = (tableName: string): TableQuery => new TableQuery(transport, tableName)\n const migrate = (input: MigrateInput): Promise<MigrateResult> =>\n transport.json<MigrateResult>(MIGRATE_PATH, { sql: input.sql })\n\n return new Proxy(table, {\n get(target, prop, receiver) {\n if (prop === 'migrate') return migrate\n // Don't manufacture a TableQuery for symbols or promise-unwrapping\n // probes (`then`) or the function's own members.\n if (typeof prop !== 'string' || prop === 'then' || prop in target) {\n return Reflect.get(target, prop, receiver)\n }\n return new TableQuery(transport, prop)\n },\n apply(_target, _thisArg, args: [string]) {\n return table(args[0])\n },\n }) as unknown as DbClient\n}\n","import { DontCodeError, type DontCodeErrorBody } from './errors'\n\n/** Default per-request timeout. Without one, a slow or unreachable gateway can\n * hang a request for the platform's full socket timeout (tens of seconds),\n * which is the single worst failure mode for an auth guard on the hot path. */\nexport const DEFAULT_TIMEOUT_MS = 10_000\n\nexport interface TransportConfig {\n /** Project API key. When absent, no Authorization header is sent and the\n * gateway responds with its own \"Missing API key\" 401. */\n apiKey?: string\n /** Gateway origin, already normalized (no trailing slash). */\n baseUrl: string\n /** Per-request timeout in ms. Defaults to `DEFAULT_TIMEOUT_MS`; `0` (or any\n * non-positive value) disables it. */\n timeoutMs?: number\n}\n\nexport interface RequestOptions {\n /** End-user access token, sent as `X-Access-Token` (separate from the\n * project API key). Required by signed-in auth calls. */\n accessToken?: string\n /** Override the client's timeout for this one call (ms). `0` disables it. */\n timeoutMs?: number\n}\n\n/**\n * The single place network requests are made. Everything else in the SDK is a\n * typed shape around `json()` / `multipart()`. No retries, no caching, just a\n * faithful proxy of the v1 gateway.\n */\nexport class Transport {\n constructor(private readonly config: TransportConfig) {}\n\n private headers(opts?: RequestOptions): Record<string, string> {\n const headers: Record<string, string> = {}\n if (this.config.apiKey) headers['Authorization'] = `Bearer ${this.config.apiKey}`\n if (opts?.accessToken) headers['X-Access-Token'] = opts.accessToken\n return headers\n }\n\n private url(path: string): string {\n return `${this.config.baseUrl}${path}`\n }\n\n private timeout(opts?: RequestOptions): number {\n const value = opts?.timeoutMs ?? this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS\n return value > 0 ? value : 0\n }\n\n /**\n * One fetch, with a timeout that turns \"hung socket\" into a fast, typed\n * failure. A timeout surfaces as `DontCodeError` with status 408 / code\n * `Timeout`; any other transport failure (DNS, refused, offline) as status\n * 0 / code `NetworkError`. Both are distinct from a real `401`, so an auth\n * guard can tell \"backend is down\" apart from \"user is signed out\".\n */\n private async send(path: string, init: RequestInit, opts?: RequestOptions): Promise<Response> {\n const timeoutMs = this.timeout(opts)\n const controller = timeoutMs > 0 ? new AbortController() : undefined\n const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : undefined\n try {\n return await fetch(this.url(path), { ...init, signal: controller?.signal })\n } catch (err) {\n if (controller?.signal.aborted) {\n throw new DontCodeError(408, {\n error: `Request to ${path} timed out after ${timeoutMs}ms`,\n code: 'Timeout',\n })\n }\n throw new DontCodeError(0, {\n error: err instanceof Error ? err.message : 'Network request failed',\n code: 'NetworkError',\n })\n } finally {\n if (timer) clearTimeout(timer)\n }\n }\n\n /** POST a JSON body and parse the JSON response. */\n async json<T>(path: string, body?: unknown, opts?: RequestOptions): Promise<T> {\n const res = await this.send(\n path,\n {\n method: 'POST',\n headers: { ...this.headers(opts), 'Content-Type': 'application/json' },\n body: JSON.stringify(body ?? {}),\n },\n opts\n )\n return this.parse<T>(res)\n }\n\n /** PUT a multipart form (file uploads). The runtime sets the boundary. */\n async multipart<T>(path: string, form: FormData, opts?: RequestOptions): Promise<T> {\n const res = await this.send(path, { method: 'PUT', headers: this.headers(opts), body: form }, opts)\n return this.parse<T>(res)\n }\n\n private async parse<T>(res: Response): Promise<T> {\n const raw = await res.text()\n let data: unknown = null\n if (raw) {\n try {\n data = JSON.parse(raw)\n } catch {\n data = { error: raw }\n }\n }\n if (!res.ok) {\n const body: DontCodeErrorBody =\n data && typeof data === 'object'\n ? (data as DontCodeErrorBody)\n : { error: res.statusText || 'Request failed' }\n throw new DontCodeError(res.status, body)\n }\n return data as T\n }\n}\n","import { Transport } from './http'\nimport type {\n DownloadResult,\n ListResult,\n PresignResult,\n StorageBucket,\n StorageObject,\n TemporaryUrlResult,\n UploadBody,\n} from './types'\n\nconst STORAGE_PATH = '/api/v1/storage'\n\nconst DEFAULT_CONTENT_TYPE = 'application/octet-stream'\n\n/** Normalize whatever the caller hands us into a Blob for multipart upload. */\nfunction toBlob(body: UploadBody, contentType: string): Blob {\n if (body instanceof Blob) return body\n if (typeof body === 'string') return new Blob([body], { type: contentType })\n if (body instanceof ArrayBuffer) return new Blob([body], { type: contentType })\n if (ArrayBuffer.isView(body)) {\n return new Blob([body as unknown as BlobPart], { type: contentType })\n }\n throw new TypeError('upload expects a Blob, ArrayBuffer, typed array, or string')\n}\n\nfunction fileName(path: string): string {\n return path.split('/').filter(Boolean).pop() ?? path\n}\n\n/** Operations available on both buckets. */\nexport class BucketClient {\n constructor(\n protected readonly transport: Transport,\n protected readonly bucket: StorageBucket\n ) {}\n\n protected op<T>(operation: string, params: Record<string, unknown> = {}): Promise<T> {\n return this.transport.json<T>(STORAGE_PATH, { operation, bucket: this.bucket, ...params })\n }\n\n /** List objects under `prefix`. */\n list(prefix?: string): Promise<ListResult> {\n return this.op<ListResult>('list', { prefix })\n }\n\n /** Delete one or more objects. Returns `{ deleted }`. */\n remove(paths: string[]): Promise<{ deleted: number }> {\n return this.op<{ deleted: number }>('remove', { paths })\n }\n\n /** Move/rename an object within the bucket. */\n move(from: string, to: string): Promise<{ object: StorageObject }> {\n return this.op<{ object: StorageObject }>('move', { from, to })\n }\n\n createFolder(path: string): Promise<{ created: string }> {\n return this.op<{ created: string }>('createFolder', { path })\n }\n\n /** Download an object inline (≤ 8 MB). Use `getTemporaryUrl` for larger files. */\n download(path: string): Promise<DownloadResult> {\n return this.op<DownloadResult>('download', { path })\n }\n\n /** A short-lived signed URL (default 300s, max 7 days). */\n getTemporaryUrl(path: string, expiresIn?: number): Promise<TemporaryUrlResult> {\n return this.op<TemporaryUrlResult>('getTemporaryUrl', { path, expiresIn })\n }\n\n /** A presigned PUT URL for direct, large uploads (≤ no inline limit). */\n presignUpload(path: string, contentType?: string): Promise<PresignResult> {\n return this.op<PresignResult>('presignUpload', { path, contentType })\n }\n\n /** Upload bytes directly (≤ 100 MB). For larger files, `presignUpload`\n * then PUT to the returned URL yourself. */\n upload(\n path: string,\n body: UploadBody,\n contentType: string = DEFAULT_CONTENT_TYPE\n ): Promise<{ object: StorageObject }> {\n const form = new FormData()\n form.append('file', toBlob(body, contentType), fileName(path))\n form.append('bucket', this.bucket)\n form.append('path', path)\n form.append('contentType', contentType)\n return this.transport.multipart<{ object: StorageObject }>(STORAGE_PATH, form)\n }\n}\n\n/** The public bucket additionally exposes stable public URLs. */\nexport class PublicBucketClient extends BucketClient {\n constructor(transport: Transport) {\n super(transport, 'public')\n }\n\n /** The permanent public URL for an object. */\n getUrl(path: string): Promise<{ url: string }> {\n return this.op<{ url: string }>('getUrl', { path })\n }\n}\n\nexport interface StorageClient {\n public: PublicBucketClient\n private: BucketClient\n}\n\nexport function createStorage(transport: Transport): StorageClient {\n return {\n public: new PublicBucketClient(transport),\n private: new BucketClient(transport, 'private'),\n }\n}\n","import { AuthApi } from './auth'\nimport { createDb, type DbClient } from './db'\nimport { Transport } from './http'\nimport type { SessionOptions } from './session'\nimport { createStorage, type StorageClient } from './storage'\n\nconst DEFAULT_BASE_URL = 'https://backend.dontcode.co'\n\nexport interface DontCodeClientOptions {\n /** Project API key (`dc_…`). Defaults to `process.env.DONTCODE_API_KEY`.\n * If neither is set, requests fail naturally with the gateway's\n * \"Missing API key\" 401. */\n apiKey?: string\n /** Gateway origin. Defaults to `process.env.DONTCODE_API_URL`, then to\n * `https://backend.dontcode.co`. */\n baseUrl?: string\n /** Per-request network timeout in ms. Defaults to 10_000; `0` disables it.\n * Without one, a slow gateway can hang a request for the full socket\n * timeout, the worst case for an auth guard. */\n timeoutMs?: number\n /** Caching + timeout policy for `auth.getSession` / `auth.sessionFromCookies`. */\n session?: SessionOptions\n}\n\nexport interface DontCodeClient {\n auth: AuthApi\n db: DbClient\n storage: StorageClient\n}\n\n/** Read an env var without assuming `process` exists (e.g. in the browser). */\nfunction fromEnv(name: string): string | undefined {\n if (typeof process === 'undefined' || !process.env) return undefined\n return process.env[name]\n}\n\n/**\n * Create a DontCode backend client. A thin, typed proxy over the v1 HTTP\n * gateway: auth, database, and storage. The API key scopes every request to\n * a single project; there is nothing else to configure.\n *\n * ```ts\n * import { dontcode } from '@dontcode2/backend'\n * const client = dontcode() // reads DONTCODE_API_KEY\n * await client.auth.signup({ email, password, role: 'editor' })\n * ```\n */\nexport function dontcode(options: DontCodeClientOptions = {}): DontCodeClient {\n const apiKey = options.apiKey ?? fromEnv('DONTCODE_API_KEY')\n const baseUrl = (options.baseUrl ?? fromEnv('DONTCODE_API_URL') ?? DEFAULT_BASE_URL).replace(\n /\\/+$/,\n ''\n )\n\n const transport = new Transport({ apiKey, baseUrl, timeoutMs: options.timeoutMs })\n\n return {\n auth: new AuthApi(transport, options.session),\n db: createDb(transport),\n storage: createStorage(transport),\n }\n}\n"],"mappings":";AAaO,IAAM,8BAA8B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