@scalemule/nextjs 0.1.69 → 0.1.71

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.
@@ -0,0 +1,421 @@
1
+ import { createFetchTransport, ScaleMuleAi } from '@scalemule/ai';
2
+ import 'next/server';
3
+ import 'next/headers';
4
+
5
+ // src/server/ai.ts
6
+
7
+ // src/server/timing.ts
8
+ function constantTimeEqual(a, b) {
9
+ const maxLength = Math.max(a.length, b.length);
10
+ let mismatch = a.length ^ b.length;
11
+ for (let i = 0; i < maxLength; i++) {
12
+ const aCode = i < a.length ? a.charCodeAt(i) : 0;
13
+ const bCode = i < b.length ? b.charCodeAt(i) : 0;
14
+ mismatch |= aCode ^ bCode;
15
+ }
16
+ return mismatch === 0;
17
+ }
18
+
19
+ // src/server/csrf.ts
20
+ var CSRF_COOKIE_NAME = "sm_csrf";
21
+ var CSRF_HEADER_NAME = "x-csrf-token";
22
+ function validateCSRFToken(request) {
23
+ const cookieToken = request.cookies.get(CSRF_COOKIE_NAME)?.value;
24
+ if (!cookieToken) {
25
+ return "Missing CSRF cookie";
26
+ }
27
+ const headerToken = request.headers.get(CSRF_HEADER_NAME);
28
+ if (!headerToken) {
29
+ return "Missing CSRF token header";
30
+ }
31
+ if (!constantTimeEqual(cookieToken, headerToken)) {
32
+ return "CSRF token mismatch";
33
+ }
34
+ return void 0;
35
+ }
36
+ var SESSION_COOKIE_NAME = "sm_session";
37
+ var USER_ID_COOKIE_NAME = "sm_user_id";
38
+ ({
39
+ secure: process.env.NODE_ENV === "production"});
40
+ function sessionFromAuthHeaders(authorization, userId) {
41
+ if (!authorization || !userId) return null;
42
+ const match = /^Bearer\s+(.+)$/i.exec(authorization.trim());
43
+ const token = match?.[1]?.trim();
44
+ if (!token) return null;
45
+ return {
46
+ sessionToken: token,
47
+ userId,
48
+ expiresAt: /* @__PURE__ */ new Date()
49
+ };
50
+ }
51
+ function getSessionFromRequest(request) {
52
+ const cookieHeader = request.headers.get("cookie");
53
+ if (cookieHeader) {
54
+ const cookies3 = Object.fromEntries(
55
+ cookieHeader.split(";").map((c) => {
56
+ const [key, ...rest] = c.trim().split("=");
57
+ return [key, decodeURIComponent(rest.join("="))];
58
+ })
59
+ );
60
+ const sessionToken = cookies3[SESSION_COOKIE_NAME];
61
+ const userId = cookies3[USER_ID_COOKIE_NAME];
62
+ if (sessionToken && userId) {
63
+ return {
64
+ sessionToken,
65
+ userId,
66
+ expiresAt: /* @__PURE__ */ new Date()
67
+ };
68
+ }
69
+ }
70
+ return sessionFromAuthHeaders(
71
+ request.headers.get("authorization"),
72
+ request.headers.get("x-sm-user-id")
73
+ );
74
+ }
75
+
76
+ // src/url-privacy.ts
77
+ function withoutAuthSecrets(value) {
78
+ if (!value) return value;
79
+ try {
80
+ const absolute = /^[a-z][a-z0-9+.-]*:/i.test(value);
81
+ const protocolRelative = value.startsWith("//");
82
+ const url = new URL(value, "https://relative.invalid");
83
+ if (!["http:", "https:"].includes(url.protocol)) return void 0;
84
+ let changed = false;
85
+ for (const name of [...url.searchParams.keys()]) {
86
+ if (/^(token|code|state|password|new_password|access_token|refresh_token|id_token|api_key|client_secret|challenge_token|challenge_code)$/i.test(name)) {
87
+ url.searchParams.delete(name);
88
+ changed = true;
89
+ }
90
+ }
91
+ if (url.hash) {
92
+ url.hash = "";
93
+ changed = true;
94
+ }
95
+ if (!changed) return value;
96
+ if (absolute) return url.toString();
97
+ if (protocolRelative) return url.toString().replace(/^https:/, "");
98
+ return value.split(/[?#]/, 1)[0] + url.search;
99
+ } catch {
100
+ return void 0;
101
+ }
102
+ }
103
+
104
+ // src/server/context.ts
105
+ function validateIP(ip) {
106
+ if (!ip) return void 0;
107
+ const trimmed = ip.trim();
108
+ if (!trimmed) return void 0;
109
+ const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
110
+ const ipv6Regex = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^::(?:[0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4}$|^(?:[0-9a-fA-F]{1,4}:){1,7}:$|^(?:[0-9a-fA-F]{1,4}:){0,6}::(?:[0-9a-fA-F]{1,4}:){0,5}[0-9a-fA-F]{1,4}$/;
111
+ const ipv4MappedRegex = /^::ffff:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/i;
112
+ if (ipv4Regex.test(trimmed) || ipv6Regex.test(trimmed) || ipv4MappedRegex.test(trimmed)) {
113
+ return trimmed;
114
+ }
115
+ return void 0;
116
+ }
117
+ function extractClientContext(request, options = {}) {
118
+ const headers2 = request.headers;
119
+ let ip;
120
+ ip = validateIP(headers2.get("x-real-ip"));
121
+ const cfConnectingIp = headers2.get("cf-connecting-ip");
122
+ if (!ip && cfConnectingIp) {
123
+ ip = validateIP(cfConnectingIp);
124
+ }
125
+ if (!ip) {
126
+ const doConnectingIp = headers2.get("do-connecting-ip");
127
+ if (doConnectingIp) {
128
+ ip = validateIP(doConnectingIp);
129
+ }
130
+ }
131
+ if (!ip) {
132
+ const realIp = headers2.get("x-real-ip");
133
+ if (realIp) {
134
+ ip = validateIP(realIp);
135
+ }
136
+ }
137
+ if (!ip) {
138
+ const forwardedFor = headers2.get("x-forwarded-for");
139
+ if (forwardedFor) {
140
+ const firstIp = forwardedFor.split(",")[0]?.trim();
141
+ ip = validateIP(firstIp);
142
+ }
143
+ }
144
+ if (!ip) {
145
+ const vercelForwarded = headers2.get("x-vercel-forwarded-for");
146
+ if (vercelForwarded) {
147
+ const firstIp = vercelForwarded.split(",")[0]?.trim();
148
+ ip = validateIP(firstIp);
149
+ }
150
+ }
151
+ if (!ip) {
152
+ const trueClientIp = headers2.get("true-client-ip");
153
+ if (trueClientIp) {
154
+ ip = validateIP(trueClientIp);
155
+ }
156
+ }
157
+ if (!ip && request.ip) {
158
+ ip = validateIP(request.ip);
159
+ }
160
+ if (options.trustedIpHeader) {
161
+ const value = headers2.get(options.trustedIpHeader);
162
+ const hop = options.trustedIpHeader === "x-forwarded-for" ? value?.split(",").at(-1)?.trim() : value;
163
+ ip = validateIP(hop);
164
+ }
165
+ const userAgent = headers2.get("user-agent") || void 0;
166
+ const deviceFingerprint = headers2.get("x-device-fingerprint") || void 0;
167
+ const referrer = withoutAuthSecrets(headers2.get("referer") || void 0);
168
+ const anonymousId = headers2.get("x-anonymous-id") || void 0;
169
+ return {
170
+ ip,
171
+ userAgent,
172
+ deviceFingerprint,
173
+ referrer,
174
+ anonymousId
175
+ };
176
+ }
177
+ function buildClientContextHeaders(context) {
178
+ const headers2 = {};
179
+ if (!context) {
180
+ return headers2;
181
+ }
182
+ if (context.ip) {
183
+ headers2["x-sm-forwarded-client-ip"] = context.ip;
184
+ headers2["X-Client-IP"] = context.ip;
185
+ }
186
+ if (context.userAgent) {
187
+ headers2["X-Client-User-Agent"] = context.userAgent;
188
+ }
189
+ if (context.deviceFingerprint) {
190
+ headers2["X-Client-Device-Fingerprint"] = context.deviceFingerprint;
191
+ }
192
+ if (context.referrer) {
193
+ headers2["X-Client-Referrer"] = context.referrer;
194
+ }
195
+ if (context.anonymousId) {
196
+ headers2["x-anonymous-id"] = context.anonymousId;
197
+ }
198
+ return headers2;
199
+ }
200
+
201
+ // src/server/ai.ts
202
+ var RUN_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
203
+ var MAX_BODY_BYTES = 1048576;
204
+ var IDEMPOTENCY_KEY = /^[\x21-\x7e]{1,200}$/;
205
+ var OPERATION_KEY = /^[a-z0-9_-]{1,100}$/;
206
+ function errorResponse(code, message, status) {
207
+ return new Response(JSON.stringify({ success: false, error: { code, message } }), {
208
+ status,
209
+ headers: { "Content-Type": "application/json", "Cache-Control": "no-store" }
210
+ });
211
+ }
212
+ function resolveAiTarget(method, segments) {
213
+ if (segments[0] === "operations") {
214
+ if (segments.length === 1) return method === "GET" ? { kind: "operations" } : null;
215
+ const operation = segments[1];
216
+ if (!operation || !OPERATION_KEY.test(operation) || segments.length !== 3) return null;
217
+ if (segments[2] === "preference" && (method === "PUT" || method === "DELETE")) return { kind: "preference", method, operation };
218
+ if (segments[2] === "settings" && (method === "GET" || method === "PUT")) return { kind: "settings", method, operation };
219
+ return null;
220
+ }
221
+ if (segments[0] !== "runs") return null;
222
+ if (segments.length === 1) return method === "POST" ? { kind: "create" } : null;
223
+ const runId = segments[1];
224
+ if (!runId || !RUN_ID.test(runId)) return null;
225
+ if (segments.length === 2) return method === "GET" ? { kind: "get", runId } : null;
226
+ if (segments.length === 3 && segments[2] === "events" && method === "GET") return { kind: "events", runId };
227
+ if (segments.length === 3 && segments[2] === "cancel" && method === "POST") return { kind: "cancel", runId };
228
+ return null;
229
+ }
230
+ function hasSessionCookie(request) {
231
+ const cookieHeader = request.headers.get("cookie") ?? "";
232
+ return cookieHeader.split(";").some((part) => {
233
+ const [name, ...rest] = part.trim().split("=");
234
+ return name === SESSION_COOKIE_NAME && rest.join("=").length > 0;
235
+ });
236
+ }
237
+ function csrfRequestView(request) {
238
+ const maybe = request;
239
+ if (maybe.cookies && typeof maybe.cookies.get === "function") {
240
+ return request;
241
+ }
242
+ const jar = /* @__PURE__ */ new Map();
243
+ for (const part of (request.headers.get("cookie") ?? "").split(";")) {
244
+ const [name, ...rest] = part.trim().split("=");
245
+ if (name) jar.set(name, decodeURIComponent(rest.join("=")));
246
+ }
247
+ return {
248
+ headers: request.headers,
249
+ cookies: { get: (name) => jar.has(name) ? { value: jar.get(name) } : void 0 }
250
+ };
251
+ }
252
+ async function resolveAccount(config, request, session) {
253
+ if (typeof config.accountId === "function") {
254
+ const value = await config.accountId(request, session);
255
+ return value ? String(value) : null;
256
+ }
257
+ return config.accountId ?? null;
258
+ }
259
+ function createAiRoutes(config) {
260
+ const { apiKey, gatewayUrl, csrf = true } = config;
261
+ const fetcher = config.fetch ?? globalThis.fetch;
262
+ if (!apiKey) throw new Error("createAiRoutes: apiKey is required");
263
+ if (!gatewayUrl) throw new Error("createAiRoutes: gatewayUrl is required");
264
+ const base = gatewayUrl.replace(/\/+$/, "");
265
+ async function readJsonBody(request) {
266
+ const declared = Number(request.headers.get("content-length") ?? "0");
267
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) {
268
+ return { error: errorResponse("INPUT_INVALID", "Request body too large", 413) };
269
+ }
270
+ const body = await request.text();
271
+ if (new TextEncoder().encode(body).byteLength > MAX_BODY_BYTES) {
272
+ return { error: errorResponse("INPUT_INVALID", "Request body too large", 413) };
273
+ }
274
+ if (!body) return { error: errorResponse("INPUT_INVALID", "A JSON body is required", 400) };
275
+ return { body };
276
+ }
277
+ async function proxy(request, method, segments) {
278
+ const target = resolveAiTarget(method, segments);
279
+ if (!target) return errorResponse("NOT_FOUND", "Unknown AI route", 404);
280
+ if (!hasSessionCookie(request)) {
281
+ return errorResponse("SESSION_REQUIRED", "Sign in to use AI features", 401);
282
+ }
283
+ const session = getSessionFromRequest(request);
284
+ if (!session?.sessionToken) {
285
+ return errorResponse("SESSION_REQUIRED", "Sign in to use AI features", 401);
286
+ }
287
+ const headers2 = {
288
+ "x-api-key": apiKey,
289
+ authorization: `Bearer ${session.sessionToken}`,
290
+ accept: target.kind === "events" ? "text/event-stream" : "application/json"
291
+ };
292
+ Object.assign(
293
+ headers2,
294
+ buildClientContextHeaders(
295
+ extractClientContext(request)
296
+ )
297
+ );
298
+ const accountId = await resolveAccount(config, request, session);
299
+ if (accountId) headers2["x-requested-account-id"] = accountId;
300
+ let path;
301
+ const init = { method, headers: headers2, redirect: "error", signal: request.signal };
302
+ switch (target.kind) {
303
+ case "create": {
304
+ const key = request.headers.get("x-idempotency-key")?.trim() ?? "";
305
+ if (!IDEMPOTENCY_KEY.test(key)) {
306
+ return errorResponse(
307
+ "IDEMPOTENCY_KEY_REQUIRED",
308
+ "Send an x-idempotency-key header generated before the first attempt",
309
+ 400
310
+ );
311
+ }
312
+ headers2["x-idempotency-key"] = key;
313
+ const read = await readJsonBody(request);
314
+ if ("error" in read) return read.error;
315
+ headers2["content-type"] = "application/json";
316
+ init.body = read.body;
317
+ path = "/v1/ai/runs";
318
+ break;
319
+ }
320
+ case "operations":
321
+ path = "/v1/ai/operations";
322
+ break;
323
+ case "preference": {
324
+ if (target.method === "PUT") {
325
+ const read = await readJsonBody(request);
326
+ if ("error" in read) return read.error;
327
+ headers2["content-type"] = "application/json";
328
+ init.body = read.body;
329
+ }
330
+ path = `/v1/ai/operations/${encodeURIComponent(target.operation)}/preference`;
331
+ break;
332
+ }
333
+ case "settings": {
334
+ if (target.method === "PUT") {
335
+ const read = await readJsonBody(request);
336
+ if ("error" in read) return read.error;
337
+ headers2["content-type"] = "application/json";
338
+ init.body = read.body;
339
+ }
340
+ path = `/v1/ai/operations/${encodeURIComponent(target.operation)}/settings`;
341
+ break;
342
+ }
343
+ case "get":
344
+ path = `/v1/ai/runs/${encodeURIComponent(target.runId)}`;
345
+ break;
346
+ case "cancel":
347
+ path = `/v1/ai/runs/${encodeURIComponent(target.runId)}/cancel`;
348
+ break;
349
+ case "events": {
350
+ const lastEventId = request.headers.get("last-event-id")?.trim();
351
+ if (lastEventId && /^\d{1,10}$/.test(lastEventId)) headers2["last-event-id"] = lastEventId;
352
+ const after = new URL(request.url).searchParams.get("after");
353
+ path = `/v1/ai/runs/${encodeURIComponent(target.runId)}/events${after && /^\d{1,10}$/.test(after) ? `?after=${after}` : ""}`;
354
+ break;
355
+ }
356
+ }
357
+ let upstream;
358
+ try {
359
+ upstream = await fetcher(`${base}${path}`, init);
360
+ } catch (error) {
361
+ if (request.signal?.aborted) return new Response(null, { status: 499 });
362
+ return errorResponse("UPSTREAM_UNAVAILABLE", `AI facade unreachable: ${String(error)}`, 502);
363
+ }
364
+ if (target.kind === "events" && upstream.ok && upstream.body) {
365
+ return new Response(upstream.body, {
366
+ status: 200,
367
+ headers: {
368
+ "Content-Type": "text/event-stream; charset=utf-8",
369
+ "Cache-Control": "no-cache, no-transform",
370
+ "X-Accel-Buffering": "no"
371
+ }
372
+ });
373
+ }
374
+ const text = await upstream.text();
375
+ const responseHeaders = {
376
+ "Content-Type": upstream.headers.get("content-type") || "application/json",
377
+ "Cache-Control": "no-store"
378
+ };
379
+ const requestId = upstream.headers.get("x-request-id");
380
+ if (requestId) responseHeaders["x-request-id"] = requestId;
381
+ const retryAfter = upstream.headers.get("retry-after");
382
+ if (retryAfter) responseHeaders["Retry-After"] = retryAfter;
383
+ return new Response(text, { status: upstream.status, headers: responseHeaders });
384
+ }
385
+ async function segmentsOf(context) {
386
+ const params = await context?.params;
387
+ return params?.action ?? [];
388
+ }
389
+ const GET = async (request, context) => {
390
+ try {
391
+ return await proxy(request, "GET", await segmentsOf(context));
392
+ } catch (error) {
393
+ return errorResponse("INTERNAL_ERROR", String(error), 500);
394
+ }
395
+ };
396
+ function mutating(method) {
397
+ return async (request, context) => {
398
+ if (csrf) {
399
+ const csrfError = validateCSRFToken(csrfRequestView(request));
400
+ if (csrfError) return errorResponse("CSRF_ERROR", "CSRF validation failed", 403);
401
+ }
402
+ try {
403
+ return await proxy(request, method, await segmentsOf(context));
404
+ } catch (error) {
405
+ return errorResponse("INTERNAL_ERROR", String(error), 500);
406
+ }
407
+ };
408
+ }
409
+ return { GET, POST: mutating("POST"), PUT: mutating("PUT"), DELETE: mutating("DELETE") };
410
+ }
411
+ function createServiceAiClient(config) {
412
+ if (!config.apiKey) throw new Error("createServiceAiClient: apiKey is required");
413
+ const transport = config.transport ?? createFetchTransport({
414
+ baseUrl: config.gatewayUrl,
415
+ fetch: config.fetch,
416
+ headers: () => ({ "x-api-key": config.apiKey })
417
+ });
418
+ return new ScaleMuleAi({ transport, accountId: config.accountId });
419
+ }
420
+
421
+ export { createAiRoutes, createServiceAiClient, resolveAiTarget };
@@ -1,10 +1,13 @@
1
1
  import { S as ServerConfig } from '../webhook-handler-CoASZNi5.mjs';
2
2
  export { a as ScaleMuleServer, V as VideoFailedEvent, b as VideoReadyEvent, c as VideoTranscodedEvent, d as VideoUploadedEvent, W as WebhookEvent, e as WebhookRoutesConfig, f as createServerClient, g as createWebhookHandler, h as createWebhookRoutes, p as parseWebhookEvent, r as registerVideoWebhook, i as resolveGatewayUrl, v as verifyWebhookSignature } from '../webhook-handler-CoASZNi5.mjs';
3
3
  import { q as ClientContext, A as ApiError } from '../index-BOPHR50i.mjs';
4
+ import { S as SessionCookieOptions, a as SessionData } from '../ai-DFsYPvk8.mjs';
5
+ export { A as AiAccountResolver, b as AiRoutesConfig, K as KNOWN_ACCOUNTS_COOKIE_NAME, c as KnownAccountEntry, d as SESSION_COOKIE_NAME, e as ServiceAiClientConfig, U as USER_ID_COOKIE_NAME, f as appendKnownAccountCookie, g as clearKnownAccountsCookie, h as clearSession, i as createAiRoutes, j as createServiceAiClient, k as getKnownAccountsCookieRaw, l as getKnownAccountsFromRequest, m as getSession, n as getSessionFromRequest, o as normalizeKnownAccountsCookie, r as removeKnownAccountFromCookie, p as requireSession, w as withSession } from '../ai-DFsYPvk8.mjs';
4
6
  export { L as LedveryRoutesConfig, a as LedverySessionData, S as SM_LEDVERY_ACCESS_TOKEN_COOKIE, b as SM_LEDVERY_ID_TOKEN_COOKIE, c as SM_LEDVERY_NONCE_COOKIE, d as SM_LEDVERY_PKCE_VERIFIER_COOKIE, e as SM_LEDVERY_STATE_COOKIE, f as createLedveryRoutes, g as getLedverySession } from '../ledvery-CxPzZpxP.mjs';
5
7
  import { NextRequest, NextResponse } from 'next/server';
6
8
  import '@scalemule/sdk';
7
9
  import '@scalemule/money';
10
+ import '@scalemule/ai';
8
11
 
9
12
  /**
10
13
  * Client Context Extraction Utilities (Next.js)
@@ -109,156 +112,6 @@ declare function buildClientContextHeaders(context: ClientContext | undefined):
109
112
  */
110
113
  declare function buildFlagContext(clientContext: Pick<ClientContext, 'ip'> | undefined, extraContext?: Record<string, unknown>): Record<string, unknown>;
111
114
 
112
- /**
113
- * Cookie Utilities for Secure Session Management
114
- *
115
- * Handles HTTP-only secure cookies for authentication.
116
- * Tokens are never exposed to the browser.
117
- */
118
- declare const SESSION_COOKIE_NAME = "sm_session";
119
- declare const USER_ID_COOKIE_NAME = "sm_user_id";
120
- /**
121
- * Known accounts cookie — stores display metadata (email, name, avatar) for
122
- * accounts that have logged in on this device. NOT httpOnly so client JS can
123
- * read it to render the account switcher UI. Contains NO tokens or secrets.
124
- */
125
- declare const KNOWN_ACCOUNTS_COOKIE_NAME = "sm_known_accounts";
126
- interface SessionCookieOptions {
127
- /** Isolate an embedded session in the top-level site cookie partition (CHIPS). */
128
- partitioned?: boolean;
129
- /** Cookie max age in seconds (default: 7 days) */
130
- maxAge?: number;
131
- /** Cookie domain (default: current domain) */
132
- domain?: string;
133
- /** Cookie path (default: '/') */
134
- path?: string;
135
- /** SameSite attribute (default: 'lax') */
136
- sameSite?: 'strict' | 'lax' | 'none';
137
- /** Whether to use secure cookies (default: true in production) */
138
- secure?: boolean;
139
- }
140
- interface SessionData {
141
- sessionToken: string;
142
- userId: string;
143
- expiresAt: Date;
144
- }
145
- /**
146
- * Create a Response with session cookies set
147
- *
148
- * Use this after successful login to set HTTP-only cookies and return user data.
149
- * The session token is stored in cookies, never sent to the browser in JSON.
150
- *
151
- * @example
152
- * ```ts
153
- * const result = await sm.auth.login({ email, password })
154
- * if (result.success) {
155
- * return withSession(result.data, { user: result.data.user })
156
- * }
157
- * ```
158
- */
159
- declare function withSession<T extends Record<string, unknown>>(loginResponse: {
160
- session_token: string;
161
- user: {
162
- id: string;
163
- };
164
- }, responseBody: T, options?: SessionCookieOptions): Response;
165
- /**
166
- * Create a Response that clears session cookies
167
- *
168
- * Use this after logout to clear HTTP-only cookies.
169
- *
170
- * @example
171
- * ```ts
172
- * await sm.auth.logout(sessionToken)
173
- * return clearSession({ message: 'Logged out' })
174
- * ```
175
- */
176
- declare function clearSession<T extends Record<string, unknown>>(responseBody: T, options?: SessionCookieOptions, status?: number): Response;
177
- /**
178
- * Get session data from request cookies
179
- *
180
- * Use this in API routes to get the current session.
181
- * Returns null if no valid session cookie exists.
182
- *
183
- * @example
184
- * ```ts
185
- * const session = await getSession()
186
- * if (!session) {
187
- * return Response.json({ error: 'Not authenticated' }, { status: 401 })
188
- * }
189
- * const user = await sm.auth.me(session.sessionToken)
190
- * ```
191
- */
192
- declare function getSession(options?: {
193
- allowBearer?: boolean;
194
- }): Promise<SessionData | null>;
195
- /**
196
- * Get session from a Request object (for edge/middleware)
197
- *
198
- * Use this when you need to read cookies from a Request directly.
199
- */
200
- declare function getSessionFromRequest(request: Request): SessionData | null;
201
- /**
202
- * Known account entry stored in cookie.
203
- * Contains display metadata ONLY — no tokens, no secrets.
204
- */
205
- interface KnownAccountEntry {
206
- userId: string;
207
- email?: string;
208
- fullName?: string;
209
- avatarUrl?: string;
210
- provider?: string;
211
- lastActiveAt: string;
212
- displayLabel?: string;
213
- colorIndex?: number;
214
- }
215
- type AccountSwitcherPrivacy = 'full' | 'masked' | 'minimal';
216
- /**
217
- * Add an account to the known accounts cookie.
218
- * Called after successful login. The cookie is NOT httpOnly so client JS
219
- * can read it to render the account switcher UI.
220
- *
221
- * Appends Set-Cookie headers to an existing Headers object.
222
- */
223
- declare function appendKnownAccountCookie(headers: Headers, account: KnownAccountEntry, existingCookie: string | null, options?: SessionCookieOptions, privacy?: AccountSwitcherPrivacy): void;
224
- /**
225
- * Remove a specific account from the known accounts cookie.
226
- */
227
- declare function removeKnownAccountFromCookie(headers: Headers, userId: string, existingCookie: string | null, options?: SessionCookieOptions): void;
228
- /**
229
- * Clear the known accounts cookie entirely.
230
- */
231
- declare function clearKnownAccountsCookie(headers: Headers, options?: SessionCookieOptions): void;
232
- /**
233
- * Read known accounts from a Request's cookies.
234
- */
235
- declare function getKnownAccountsFromRequest(request: Request): KnownAccountEntry[];
236
- /**
237
- * Read the raw known accounts cookie value from a Request.
238
- */
239
- declare function getKnownAccountsCookieRaw(request: Request): string | null;
240
- /**
241
- * Normalize all entries in the known accounts cookie to the given privacy level.
242
- * Returns a Set-Cookie header string if any entries changed, or null if nothing changed.
243
- * Used on /me requests to migrate legacy full-PII cookies to the configured privacy level.
244
- */
245
- declare function normalizeKnownAccountsCookie(request: Request, privacy: AccountSwitcherPrivacy | undefined, options?: SessionCookieOptions): string | null;
246
- /**
247
- * Require authentication - throws Response if not authenticated
248
- *
249
- * Use this at the start of protected API routes.
250
- *
251
- * @example
252
- * ```ts
253
- * export async function GET() {
254
- * const session = await requireSession()
255
- * // session is guaranteed to exist here
256
- * const files = await sm.storage.list(session.userId)
257
- * }
258
- * ```
259
- */
260
- declare function requireSession(): Promise<SessionData>;
261
-
262
115
  /**
263
116
  * Ready-Made API Route Handlers
264
117
  *
@@ -1363,4 +1216,4 @@ declare const DEFAULT_PERMISSIONS_POLICY: PermissionsPolicyMap;
1363
1216
  */
1364
1217
  declare function buildSecurityHeaders(opts?: BuildSecurityHeadersOptions): SecurityHeaderEntry[];
1365
1218
 
1366
- export { type AnalyticsRoutesConfig, type AnalyticsTrackingGateConfig, type AuthMiddlewareConfig, type AuthRoutesConfig, type BuildSecurityHeadersOptions, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, type HandlerContext, type HandlerOptions, KNOWN_ACCOUNTS_COOKIE_NAME, type KnownAccountEntry, type MySqlBundle, type NewsletterRoutesConfig, type NotificationRoutesConfig, OAUTH_STATE_COOKIE_NAME, type OAuthBundle, type PermissionsPolicyMap, type PermissionsPolicyValue, type PostgresBundle, type PushRoutesConfig, type RedisBundle, type S3Bundle, SESSION_COOKIE_NAME, type SafeRedirectOptions, ScaleMuleError, type SecurityHeaderEntry, ServerConfig, type SessionCookieOptions, type SessionData, type SmtpBundle, USER_ID_COOKIE_NAME, apiHandler, appendKnownAccountCookie, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearKnownAccountsCookie, clearOAuthState, clearSession, configureBundles, configureSecrets, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createNewsletterRoutes, createNotificationRoutes, createPushRoutes, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getKnownAccountsCookieRaw, getKnownAccountsFromRequest, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSession, getSessionFromRequest, getSmtpBundle, invalidateBundleCache, invalidateSecretCache, isSafeRedirect, newsletterRoute, normalizeKnownAccountsCookie, prefetchBundles, prefetchSecrets, removeKnownAccountFromCookie, requireAppSecret, requireBundle, requireSession, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, withAuth, withCSRFProtection, withCSRFToken, withSession };
1219
+ export { type AnalyticsRoutesConfig, type AnalyticsTrackingGateConfig, type AuthMiddlewareConfig, type AuthRoutesConfig, type BuildSecurityHeadersOptions, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, type HandlerContext, type HandlerOptions, type MySqlBundle, type NewsletterRoutesConfig, type NotificationRoutesConfig, OAUTH_STATE_COOKIE_NAME, type OAuthBundle, type PermissionsPolicyMap, type PermissionsPolicyValue, type PostgresBundle, type PushRoutesConfig, type RedisBundle, type S3Bundle, type SafeRedirectOptions, ScaleMuleError, type SecurityHeaderEntry, ServerConfig, SessionCookieOptions, SessionData, type SmtpBundle, apiHandler, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearOAuthState, configureBundles, configureSecrets, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createNewsletterRoutes, createNotificationRoutes, createPushRoutes, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSmtpBundle, invalidateBundleCache, invalidateSecretCache, isSafeRedirect, newsletterRoute, prefetchBundles, prefetchSecrets, requireAppSecret, requireBundle, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, withAuth, withCSRFProtection, withCSRFToken };