@scalemule/nextjs 0.1.70 → 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.
@@ -163,7 +163,7 @@ declare function requireSession(): Promise<SessionData>;
163
163
  * // app/api/ai/[...action]/route.ts
164
164
  * import { createAiRoutes } from '@scalemule/nextjs/server/ai'
165
165
  *
166
- * export const { GET, POST } = createAiRoutes({
166
+ * export const { GET, POST, PUT, DELETE } = createAiRoutes({
167
167
  * apiKey: process.env.SCALEMULE_API_KEY!,
168
168
  * gatewayUrl: process.env.SCALEMULE_API_URL!,
169
169
  * accountId: process.env.SCALEMULE_ACCOUNT_ID!,
@@ -181,13 +181,18 @@ declare function requireSession(): Promise<SessionData>;
181
181
  * })
182
182
  * ```
183
183
  *
184
- * Rules (ADR-2026-11-08 D4/D7):
184
+ * Rules (ADR-2026-11-08 D4/D7, ADR-2026-11-09 D4/D5):
185
185
  * - no session cookie → 401, nothing is forwarded
186
- * - only `runs`, `runs/{id}`, `runs/{id}/events`, `runs/{id}/cancel`
186
+ * - only `runs`, `runs/{id}`, `runs/{id}/events`, `runs/{id}/cancel`,
187
+ * `operations`, `operations/{op}/preference` (PUT/DELETE) and
188
+ * `operations/{op}/settings` (GET/PUT); the upstream path is built from
189
+ * the validated key only, never from the browser URL
187
190
  * - the account comes from server config, never from the browser
188
191
  * - forwarded from the browser: body, `x-idempotency-key`, `last-event-id`
189
- * - never forwarded: `Origin`, `x-sm-workspace-id`, `x-requested-account-id`,
190
- * any `x-app-*` / `x-sm-*` / internal header
192
+ * - never forwarded: `Origin`, cookies, `Authorization`, `x-sm-workspace-id`,
193
+ * `x-requested-account-id`, any `x-app-*` or internal header. The only
194
+ * `x-sm-*` header added is the gateway's own client-IP hint
195
+ * (`x-sm-forwarded-client-ip`, derived server-side for trust scoring).
191
196
  */
192
197
 
193
198
  type AiAccountResolver = (request: Request, session: SessionData) => string | null | undefined | Promise<string | null | undefined>;
@@ -203,7 +208,7 @@ interface AiRoutesConfig {
203
208
  * account-bound (workspace-site key).
204
209
  */
205
210
  accountId?: string | AiAccountResolver;
206
- /** Enable CSRF validation on POST (default: true) */
211
+ /** Enable CSRF validation on POST, PUT and DELETE (default: true) */
207
212
  csrf?: boolean;
208
213
  /** Custom fetch (tests). Defaults to `globalThis.fetch`. */
209
214
  fetch?: typeof fetch;
@@ -224,12 +229,24 @@ type Target = {
224
229
  } | {
225
230
  kind: 'cancel';
226
231
  runId: string;
232
+ } | {
233
+ kind: 'operations';
234
+ } | {
235
+ kind: 'preference';
236
+ method: 'PUT' | 'DELETE';
237
+ operation: string;
238
+ } | {
239
+ kind: 'settings';
240
+ method: 'GET' | 'PUT';
241
+ operation: string;
227
242
  };
228
243
  /** Allow-list the proxied surface. Anything else is a 404, never forwarded. */
229
244
  declare function resolveAiTarget(method: string, segments: string[]): Target | null;
230
245
  declare function createAiRoutes(config: AiRoutesConfig): {
231
246
  GET: RouteHandler;
232
247
  POST: RouteHandler;
248
+ PUT: RouteHandler;
249
+ DELETE: RouteHandler;
233
250
  };
234
251
  interface ServiceAiClientConfig {
235
252
  /** Server-side secret API key (service mode; account-bound keys need no accountId). */
@@ -163,7 +163,7 @@ declare function requireSession(): Promise<SessionData>;
163
163
  * // app/api/ai/[...action]/route.ts
164
164
  * import { createAiRoutes } from '@scalemule/nextjs/server/ai'
165
165
  *
166
- * export const { GET, POST } = createAiRoutes({
166
+ * export const { GET, POST, PUT, DELETE } = createAiRoutes({
167
167
  * apiKey: process.env.SCALEMULE_API_KEY!,
168
168
  * gatewayUrl: process.env.SCALEMULE_API_URL!,
169
169
  * accountId: process.env.SCALEMULE_ACCOUNT_ID!,
@@ -181,13 +181,18 @@ declare function requireSession(): Promise<SessionData>;
181
181
  * })
182
182
  * ```
183
183
  *
184
- * Rules (ADR-2026-11-08 D4/D7):
184
+ * Rules (ADR-2026-11-08 D4/D7, ADR-2026-11-09 D4/D5):
185
185
  * - no session cookie → 401, nothing is forwarded
186
- * - only `runs`, `runs/{id}`, `runs/{id}/events`, `runs/{id}/cancel`
186
+ * - only `runs`, `runs/{id}`, `runs/{id}/events`, `runs/{id}/cancel`,
187
+ * `operations`, `operations/{op}/preference` (PUT/DELETE) and
188
+ * `operations/{op}/settings` (GET/PUT); the upstream path is built from
189
+ * the validated key only, never from the browser URL
187
190
  * - the account comes from server config, never from the browser
188
191
  * - forwarded from the browser: body, `x-idempotency-key`, `last-event-id`
189
- * - never forwarded: `Origin`, `x-sm-workspace-id`, `x-requested-account-id`,
190
- * any `x-app-*` / `x-sm-*` / internal header
192
+ * - never forwarded: `Origin`, cookies, `Authorization`, `x-sm-workspace-id`,
193
+ * `x-requested-account-id`, any `x-app-*` or internal header. The only
194
+ * `x-sm-*` header added is the gateway's own client-IP hint
195
+ * (`x-sm-forwarded-client-ip`, derived server-side for trust scoring).
191
196
  */
192
197
 
193
198
  type AiAccountResolver = (request: Request, session: SessionData) => string | null | undefined | Promise<string | null | undefined>;
@@ -203,7 +208,7 @@ interface AiRoutesConfig {
203
208
  * account-bound (workspace-site key).
204
209
  */
205
210
  accountId?: string | AiAccountResolver;
206
- /** Enable CSRF validation on POST (default: true) */
211
+ /** Enable CSRF validation on POST, PUT and DELETE (default: true) */
207
212
  csrf?: boolean;
208
213
  /** Custom fetch (tests). Defaults to `globalThis.fetch`. */
209
214
  fetch?: typeof fetch;
@@ -224,12 +229,24 @@ type Target = {
224
229
  } | {
225
230
  kind: 'cancel';
226
231
  runId: string;
232
+ } | {
233
+ kind: 'operations';
234
+ } | {
235
+ kind: 'preference';
236
+ method: 'PUT' | 'DELETE';
237
+ operation: string;
238
+ } | {
239
+ kind: 'settings';
240
+ method: 'GET' | 'PUT';
241
+ operation: string;
227
242
  };
228
243
  /** Allow-list the proxied surface. Anything else is a 404, never forwarded. */
229
244
  declare function resolveAiTarget(method: string, segments: string[]): Target | null;
230
245
  declare function createAiRoutes(config: AiRoutesConfig): {
231
246
  GET: RouteHandler;
232
247
  POST: RouteHandler;
248
+ PUT: RouteHandler;
249
+ DELETE: RouteHandler;
233
250
  };
234
251
  interface ServiceAiClientConfig {
235
252
  /** Server-side secret API key (service mode; account-bound keys need no accountId). */
@@ -1,2 +1,2 @@
1
1
  export { ScaleMuleAi } from '@scalemule/ai';
2
- export { A as AiAccountResolver, b as AiRoutesConfig, e as ServiceAiClientConfig, i as createAiRoutes, j as createServiceAiClient, q as resolveAiTarget } from '../ai-Ccz-erh_.mjs';
2
+ export { A as AiAccountResolver, b as AiRoutesConfig, e as ServiceAiClientConfig, i as createAiRoutes, j as createServiceAiClient, q as resolveAiTarget } from '../ai-DFsYPvk8.mjs';
@@ -1,2 +1,2 @@
1
1
  export { ScaleMuleAi } from '@scalemule/ai';
2
- export { A as AiAccountResolver, b as AiRoutesConfig, e as ServiceAiClientConfig, i as createAiRoutes, j as createServiceAiClient, q as resolveAiTarget } from '../ai-Ccz-erh_.js';
2
+ export { A as AiAccountResolver, b as AiRoutesConfig, e as ServiceAiClientConfig, i as createAiRoutes, j as createServiceAiClient, q as resolveAiTarget } from '../ai-DFsYPvk8.js';
package/dist/server/ai.js CHANGED
@@ -204,6 +204,7 @@ function buildClientContextHeaders(context) {
204
204
  var RUN_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
205
205
  var MAX_BODY_BYTES = 1048576;
206
206
  var IDEMPOTENCY_KEY = /^[\x21-\x7e]{1,200}$/;
207
+ var OPERATION_KEY = /^[a-z0-9_-]{1,100}$/;
207
208
  function errorResponse(code, message, status) {
208
209
  return new Response(JSON.stringify({ success: false, error: { code, message } }), {
209
210
  status,
@@ -211,6 +212,14 @@ function errorResponse(code, message, status) {
211
212
  });
212
213
  }
213
214
  function resolveAiTarget(method, segments) {
215
+ if (segments[0] === "operations") {
216
+ if (segments.length === 1) return method === "GET" ? { kind: "operations" } : null;
217
+ const operation = segments[1];
218
+ if (!operation || !OPERATION_KEY.test(operation) || segments.length !== 3) return null;
219
+ if (segments[2] === "preference" && (method === "PUT" || method === "DELETE")) return { kind: "preference", method, operation };
220
+ if (segments[2] === "settings" && (method === "GET" || method === "PUT")) return { kind: "settings", method, operation };
221
+ return null;
222
+ }
214
223
  if (segments[0] !== "runs") return null;
215
224
  if (segments.length === 1) return method === "POST" ? { kind: "create" } : null;
216
225
  const runId = segments[1];
@@ -220,6 +229,13 @@ function resolveAiTarget(method, segments) {
220
229
  if (segments.length === 3 && segments[2] === "cancel" && method === "POST") return { kind: "cancel", runId };
221
230
  return null;
222
231
  }
232
+ function hasSessionCookie(request) {
233
+ const cookieHeader = request.headers.get("cookie") ?? "";
234
+ return cookieHeader.split(";").some((part) => {
235
+ const [name, ...rest] = part.trim().split("=");
236
+ return name === SESSION_COOKIE_NAME && rest.join("=").length > 0;
237
+ });
238
+ }
223
239
  function csrfRequestView(request) {
224
240
  const maybe = request;
225
241
  if (maybe.cookies && typeof maybe.cookies.get === "function") {
@@ -248,9 +264,24 @@ function createAiRoutes(config) {
248
264
  if (!apiKey) throw new Error("createAiRoutes: apiKey is required");
249
265
  if (!gatewayUrl) throw new Error("createAiRoutes: gatewayUrl is required");
250
266
  const base = gatewayUrl.replace(/\/+$/, "");
267
+ async function readJsonBody(request) {
268
+ const declared = Number(request.headers.get("content-length") ?? "0");
269
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) {
270
+ return { error: errorResponse("INPUT_INVALID", "Request body too large", 413) };
271
+ }
272
+ const body = await request.text();
273
+ if (new TextEncoder().encode(body).byteLength > MAX_BODY_BYTES) {
274
+ return { error: errorResponse("INPUT_INVALID", "Request body too large", 413) };
275
+ }
276
+ if (!body) return { error: errorResponse("INPUT_INVALID", "A JSON body is required", 400) };
277
+ return { body };
278
+ }
251
279
  async function proxy(request, method, segments) {
252
280
  const target = resolveAiTarget(method, segments);
253
281
  if (!target) return errorResponse("NOT_FOUND", "Unknown AI route", 404);
282
+ if (!hasSessionCookie(request)) {
283
+ return errorResponse("SESSION_REQUIRED", "Sign in to use AI features", 401);
284
+ }
254
285
  const session = getSessionFromRequest(request);
255
286
  if (!session?.sessionToken) {
256
287
  return errorResponse("SESSION_REQUIRED", "Sign in to use AI features", 401);
@@ -281,14 +312,36 @@ function createAiRoutes(config) {
281
312
  );
282
313
  }
283
314
  headers2["x-idempotency-key"] = key;
284
- const body = await request.text();
285
- if (body.length > MAX_BODY_BYTES) return errorResponse("INPUT_INVALID", "Request body too large", 413);
286
- if (!body) return errorResponse("INPUT_INVALID", "A JSON body is required", 400);
315
+ const read = await readJsonBody(request);
316
+ if ("error" in read) return read.error;
287
317
  headers2["content-type"] = "application/json";
288
- init.body = body;
318
+ init.body = read.body;
289
319
  path = "/v1/ai/runs";
290
320
  break;
291
321
  }
322
+ case "operations":
323
+ path = "/v1/ai/operations";
324
+ break;
325
+ case "preference": {
326
+ if (target.method === "PUT") {
327
+ const read = await readJsonBody(request);
328
+ if ("error" in read) return read.error;
329
+ headers2["content-type"] = "application/json";
330
+ init.body = read.body;
331
+ }
332
+ path = `/v1/ai/operations/${encodeURIComponent(target.operation)}/preference`;
333
+ break;
334
+ }
335
+ case "settings": {
336
+ if (target.method === "PUT") {
337
+ const read = await readJsonBody(request);
338
+ if ("error" in read) return read.error;
339
+ headers2["content-type"] = "application/json";
340
+ init.body = read.body;
341
+ }
342
+ path = `/v1/ai/operations/${encodeURIComponent(target.operation)}/settings`;
343
+ break;
344
+ }
292
345
  case "get":
293
346
  path = `/v1/ai/runs/${encodeURIComponent(target.runId)}`;
294
347
  break;
@@ -316,7 +369,6 @@ function createAiRoutes(config) {
316
369
  headers: {
317
370
  "Content-Type": "text/event-stream; charset=utf-8",
318
371
  "Cache-Control": "no-cache, no-transform",
319
- Connection: "keep-alive",
320
372
  "X-Accel-Buffering": "no"
321
373
  }
322
374
  });
@@ -343,18 +395,20 @@ function createAiRoutes(config) {
343
395
  return errorResponse("INTERNAL_ERROR", String(error), 500);
344
396
  }
345
397
  };
346
- const POST = async (request, context) => {
347
- if (csrf) {
348
- const csrfError = validateCSRFToken(csrfRequestView(request));
349
- if (csrfError) return errorResponse("CSRF_ERROR", "CSRF validation failed", 403);
350
- }
351
- try {
352
- return await proxy(request, "POST", await segmentsOf(context));
353
- } catch (error) {
354
- return errorResponse("INTERNAL_ERROR", String(error), 500);
355
- }
356
- };
357
- return { GET, POST };
398
+ function mutating(method) {
399
+ return async (request, context) => {
400
+ if (csrf) {
401
+ const csrfError = validateCSRFToken(csrfRequestView(request));
402
+ if (csrfError) return errorResponse("CSRF_ERROR", "CSRF validation failed", 403);
403
+ }
404
+ try {
405
+ return await proxy(request, method, await segmentsOf(context));
406
+ } catch (error) {
407
+ return errorResponse("INTERNAL_ERROR", String(error), 500);
408
+ }
409
+ };
410
+ }
411
+ return { GET, POST: mutating("POST"), PUT: mutating("PUT"), DELETE: mutating("DELETE") };
358
412
  }
359
413
  function createServiceAiClient(config) {
360
414
  if (!config.apiKey) throw new Error("createServiceAiClient: apiKey is required");
@@ -202,6 +202,7 @@ function buildClientContextHeaders(context) {
202
202
  var RUN_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
203
203
  var MAX_BODY_BYTES = 1048576;
204
204
  var IDEMPOTENCY_KEY = /^[\x21-\x7e]{1,200}$/;
205
+ var OPERATION_KEY = /^[a-z0-9_-]{1,100}$/;
205
206
  function errorResponse(code, message, status) {
206
207
  return new Response(JSON.stringify({ success: false, error: { code, message } }), {
207
208
  status,
@@ -209,6 +210,14 @@ function errorResponse(code, message, status) {
209
210
  });
210
211
  }
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
+ }
212
221
  if (segments[0] !== "runs") return null;
213
222
  if (segments.length === 1) return method === "POST" ? { kind: "create" } : null;
214
223
  const runId = segments[1];
@@ -218,6 +227,13 @@ function resolveAiTarget(method, segments) {
218
227
  if (segments.length === 3 && segments[2] === "cancel" && method === "POST") return { kind: "cancel", runId };
219
228
  return null;
220
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
+ }
221
237
  function csrfRequestView(request) {
222
238
  const maybe = request;
223
239
  if (maybe.cookies && typeof maybe.cookies.get === "function") {
@@ -246,9 +262,24 @@ function createAiRoutes(config) {
246
262
  if (!apiKey) throw new Error("createAiRoutes: apiKey is required");
247
263
  if (!gatewayUrl) throw new Error("createAiRoutes: gatewayUrl is required");
248
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
+ }
249
277
  async function proxy(request, method, segments) {
250
278
  const target = resolveAiTarget(method, segments);
251
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
+ }
252
283
  const session = getSessionFromRequest(request);
253
284
  if (!session?.sessionToken) {
254
285
  return errorResponse("SESSION_REQUIRED", "Sign in to use AI features", 401);
@@ -279,14 +310,36 @@ function createAiRoutes(config) {
279
310
  );
280
311
  }
281
312
  headers2["x-idempotency-key"] = key;
282
- const body = await request.text();
283
- if (body.length > MAX_BODY_BYTES) return errorResponse("INPUT_INVALID", "Request body too large", 413);
284
- if (!body) return errorResponse("INPUT_INVALID", "A JSON body is required", 400);
313
+ const read = await readJsonBody(request);
314
+ if ("error" in read) return read.error;
285
315
  headers2["content-type"] = "application/json";
286
- init.body = body;
316
+ init.body = read.body;
287
317
  path = "/v1/ai/runs";
288
318
  break;
289
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
+ }
290
343
  case "get":
291
344
  path = `/v1/ai/runs/${encodeURIComponent(target.runId)}`;
292
345
  break;
@@ -314,7 +367,6 @@ function createAiRoutes(config) {
314
367
  headers: {
315
368
  "Content-Type": "text/event-stream; charset=utf-8",
316
369
  "Cache-Control": "no-cache, no-transform",
317
- Connection: "keep-alive",
318
370
  "X-Accel-Buffering": "no"
319
371
  }
320
372
  });
@@ -341,18 +393,20 @@ function createAiRoutes(config) {
341
393
  return errorResponse("INTERNAL_ERROR", String(error), 500);
342
394
  }
343
395
  };
344
- const POST = async (request, context) => {
345
- if (csrf) {
346
- const csrfError = validateCSRFToken(csrfRequestView(request));
347
- if (csrfError) return errorResponse("CSRF_ERROR", "CSRF validation failed", 403);
348
- }
349
- try {
350
- return await proxy(request, "POST", await segmentsOf(context));
351
- } catch (error) {
352
- return errorResponse("INTERNAL_ERROR", String(error), 500);
353
- }
354
- };
355
- return { GET, POST };
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") };
356
410
  }
357
411
  function createServiceAiClient(config) {
358
412
  if (!config.apiKey) throw new Error("createServiceAiClient: apiKey is required");
@@ -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 };