@seclai/handlers 0.0.0 → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +68 -2
- package/dist/index.cjs +201 -116
- package/dist/index.d.cts +85 -3
- package/dist/index.d.ts +85 -3
- package/dist/index.js +199 -115
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -52,6 +52,72 @@ export const ALL: APIRoute = ({ request }) => seclai.handle(request);
|
|
|
52
52
|
| `agentId` | Required | The agent to run |
|
|
53
53
|
| `apiVersion` | `2026-10-28` | Dated API version. Must be `2026-10-16` or later |
|
|
54
54
|
| `runTimeoutMs` | 11 minutes | How long a streaming run may take |
|
|
55
|
+
| `context` | None | `(req)`: your per-request context, such as the signed-in user, passed to every hook. See [Access control](#access-control) |
|
|
56
|
+
| `authorizeRun` | None | `(req, body, ctx)`: refuse or rewrite a run. See [Access control](#access-control) |
|
|
57
|
+
| `authorizeUpload` | None | `(req, file, ctx)`: refuse an upload before it reaches Seclai |
|
|
58
|
+
| `authorizeDownload` | None | `(req, { runId, attachmentId }, ctx)`: return `true` to serve the file |
|
|
59
|
+
|
|
60
|
+
### Access control
|
|
61
|
+
|
|
62
|
+
Three hooks check requests against your own data before they reach the API. They apply to the individual handlers and to `handle`, and may be sync or async.
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
import { createSeclaiHandlers, deny } from "@seclai/handlers";
|
|
66
|
+
|
|
67
|
+
const seclai = createSeclaiHandlers({
|
|
68
|
+
apiKey: process.env.SECLAI_API_KEY!,
|
|
69
|
+
agentId: process.env.SECLAI_AGENT_ID!,
|
|
70
|
+
|
|
71
|
+
// Runs once per hooked request, only when a hook needs it.
|
|
72
|
+
async context(req) {
|
|
73
|
+
const user = await getUser(req);
|
|
74
|
+
if (!user) throw deny(401, "Sign in first.");
|
|
75
|
+
return { user };
|
|
76
|
+
},
|
|
77
|
+
|
|
78
|
+
async authorizeRun(req, body, { user }) {
|
|
79
|
+
if (body.sessionId && !(await db.sessionBelongsTo(body.sessionId, user.id))) {
|
|
80
|
+
return deny(403, "That isn't your conversation.");
|
|
81
|
+
}
|
|
82
|
+
// Returning nothing runs the body as it is.
|
|
83
|
+
},
|
|
84
|
+
|
|
85
|
+
authorizeUpload: (req, file, { user }) => user.canUpload,
|
|
86
|
+
|
|
87
|
+
async authorizeDownload(req, { runId }, { user }) {
|
|
88
|
+
return db.runBelongsTo(runId, user.id);
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
**Allowing and refusing**
|
|
94
|
+
|
|
95
|
+
| Hook | Allow | Refuse |
|
|
96
|
+
|---|---|---|
|
|
97
|
+
| `authorizeRun` | Return nothing or `true`, or a rewritten body to run instead | `false` (403), or a `Response` |
|
|
98
|
+
| `authorizeUpload` | Return nothing or `true` | `false` (403), or a `Response` |
|
|
99
|
+
| `authorizeDownload` | Return `true` | `false` (404), or a `Response`. Returning nothing also refuses, and logs a warning |
|
|
100
|
+
|
|
101
|
+
- **Any hook can refuse by throwing a `Response`**, or by returning one, so a check deep in your data layer can `throw deny(...)`. The `context` function can too, which refuses every hooked request at once.
|
|
102
|
+
- **`deny(status, message)`** builds the same `{ error, status }` JSON the handlers use for their own errors. `@seclai/react` shows the `error` text to the user.
|
|
103
|
+
- **`authorizeDownload` fails closed** because it guards stored files: anything but `true` or a `Response` is a 404, the same as a missing file, so a refusal doesn't confirm the file exists.
|
|
104
|
+
- **Rewrites.** `authorizeRun` gets the body after `run` has validated it. It may return a rewritten body, for example to add context to `input` or swap in server-side `uploadIds`. The rewrite is validated again.
|
|
105
|
+
- **Errors.** If a hook or `context` throws anything other than a `Response`, the browser gets a 500 with a generic message, and the error is logged with `console.error`. A rewrite that fails validation is also a logged 500, with the reason.
|
|
106
|
+
|
|
107
|
+
**Context your framework already has**
|
|
108
|
+
|
|
109
|
+
When your framework has already resolved the user, pass it with `withContext` instead of the `context` option. It returns the same handlers with that context bound, so they keep the `(req) => Response` shape:
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
// React Router: app/routes/api.seclai.$action.ts
|
|
113
|
+
const seclai = createSeclaiHandlers<{ userId: string }>({ apiKey, agentId, authorizeRun, authorizeDownload });
|
|
114
|
+
|
|
115
|
+
export const loader = ({ request, context }: Route.LoaderArgs) =>
|
|
116
|
+
seclai.withContext({ userId: context.get(userContext).id }).handle(request);
|
|
117
|
+
export const action = loader;
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
The context's type is inferred from the `context` option, or set as the type parameter. Without a `context` option, a typed context is only reachable through `withContext`: TypeScript doesn't offer `seclai.handle` on its own, so a route can't call the hooks without the context. A context type that includes `undefined` keeps the plain handlers.
|
|
55
121
|
|
|
56
122
|
## The run stream
|
|
57
123
|
|
|
@@ -63,8 +129,8 @@ export const ALL: APIRoute = ({ request }) => seclai.handle(request);
|
|
|
63
129
|
|
|
64
130
|
## Limits to know before deploying
|
|
65
131
|
|
|
66
|
-
- **The endpoints have no auth.** Anyone who can reach them can run your agent on your credits.
|
|
67
|
-
- **The API key is account-wide.** `download` checks that ids are well formed, but the API only checks that a run belongs to the account, not to this agent.
|
|
132
|
+
- **The endpoints have no auth by default.** Anyone who can reach them can run your agent on your credits. Use the [access-control hooks](#access-control) to check the caller, and put rate limiting in front of a public deployment. `attachment-references` has no hook, so guard that route yourself if the agent's accepted files are sensitive.
|
|
133
|
+
- **The API key is account-wide.** `download` checks that ids are well formed, but the API only checks that a run belongs to the account, not to this agent. Without [`authorizeDownload`](#access-control), anyone holding a run's id and a file's id from the same account could fetch that file. Run ids are random UUIDs, so they can't be guessed, but only your app knows which runs a caller may read.
|
|
68
134
|
- **Uploads pass through your function**, so your platform's body limit applies, not the API's 200 MB: about 4.5 MB on Vercel and 6 MB on Netlify. The API has no CORS, so the browser can't upload to it directly.
|
|
69
135
|
- **Your platform's function duration limit** may end a long run before `runTimeoutMs` does.
|
|
70
136
|
|
package/dist/index.cjs
CHANGED
|
@@ -22,7 +22,8 @@ var index_exports = {};
|
|
|
22
22
|
__export(index_exports, {
|
|
23
23
|
DEFAULT_API_VERSION: () => DEFAULT_API_VERSION,
|
|
24
24
|
MIN_API_VERSION: () => MIN_API_VERSION,
|
|
25
|
-
createSeclaiHandlers: () => createSeclaiHandlers
|
|
25
|
+
createSeclaiHandlers: () => createSeclaiHandlers,
|
|
26
|
+
deny: () => deny
|
|
26
27
|
});
|
|
27
28
|
module.exports = __toCommonJS(index_exports);
|
|
28
29
|
|
|
@@ -171,6 +172,10 @@ var ROUTES = {
|
|
|
171
172
|
function wrongMethod(allow) {
|
|
172
173
|
return jsonError(405, "Method not allowed.", { allow });
|
|
173
174
|
}
|
|
175
|
+
var NOT_AUTHORIZED = "Could not authorize this request.";
|
|
176
|
+
function deny(status, message, headers) {
|
|
177
|
+
return jsonError(status, message, headers);
|
|
178
|
+
}
|
|
174
179
|
function parseRunBody(body) {
|
|
175
180
|
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
176
181
|
return "The request body must be a JSON object.";
|
|
@@ -195,7 +200,11 @@ function createSeclaiHandlers(options) {
|
|
|
195
200
|
apiKey,
|
|
196
201
|
agentId,
|
|
197
202
|
apiVersion = DEFAULT_API_VERSION,
|
|
198
|
-
runTimeoutMs = DEFAULT_RUN_TIMEOUT_MS
|
|
203
|
+
runTimeoutMs = DEFAULT_RUN_TIMEOUT_MS,
|
|
204
|
+
context,
|
|
205
|
+
authorizeRun,
|
|
206
|
+
authorizeUpload,
|
|
207
|
+
authorizeDownload
|
|
199
208
|
} = options;
|
|
200
209
|
if (!apiKey) throw new Error("createSeclaiHandlers: `apiKey` is required.");
|
|
201
210
|
if (!agentId) throw new Error("createSeclaiHandlers: `agentId` is required.");
|
|
@@ -211,128 +220,204 @@ function createSeclaiHandlers(options) {
|
|
|
211
220
|
// when called with any `this` but the global, so it can't be passed bare.
|
|
212
221
|
fetch: (input, init) => globalThis.fetch(input, init)
|
|
213
222
|
});
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
223
|
+
let warnedDownloadResult = false;
|
|
224
|
+
async function callHook(name, req, resolveCtx, hook) {
|
|
225
|
+
let ctx;
|
|
226
|
+
try {
|
|
227
|
+
ctx = await resolveCtx(req);
|
|
228
|
+
return { value: await hook(ctx) };
|
|
229
|
+
} catch (err) {
|
|
230
|
+
if (err instanceof Response) return { response: err };
|
|
231
|
+
const hint = ctx === void 0 && err instanceof TypeError ? " No context was passed: set the `context` option, or call `withContext(ctx)`." : "";
|
|
232
|
+
console.error(`[seclai] ${name} threw, so the request got a 500.${hint}`, err);
|
|
233
|
+
return { response: jsonError(500, NOT_AUTHORIZED) };
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
const build = (resolveCtx) => {
|
|
237
|
+
const handlers = {
|
|
238
|
+
async attachmentReferences(req) {
|
|
239
|
+
if (req.method !== "GET") return wrongMethod("GET");
|
|
240
|
+
try {
|
|
241
|
+
return json(await client.getAgentAttachmentReferences(agentId));
|
|
242
|
+
} catch (err) {
|
|
243
|
+
return toErrorResponse(err);
|
|
244
|
+
}
|
|
245
|
+
},
|
|
246
|
+
async upload(req) {
|
|
247
|
+
if (req.method !== "POST") return wrongMethod("POST");
|
|
248
|
+
let form;
|
|
249
|
+
try {
|
|
250
|
+
form = await req.formData();
|
|
251
|
+
} catch {
|
|
252
|
+
return jsonError(400, "The request body must be multipart form data.");
|
|
253
|
+
}
|
|
254
|
+
const file = form.get("file");
|
|
255
|
+
if (file === null || typeof file === "string") {
|
|
256
|
+
return jsonError(400, "The form must include a `file` field holding a file.");
|
|
257
|
+
}
|
|
258
|
+
if (authorizeUpload) {
|
|
259
|
+
const result = await callHook(
|
|
260
|
+
"authorizeUpload",
|
|
261
|
+
req,
|
|
262
|
+
resolveCtx,
|
|
263
|
+
(ctx) => authorizeUpload(req, file, ctx)
|
|
264
|
+
);
|
|
265
|
+
if ("response" in result) return result.response;
|
|
266
|
+
const allowed = result.value;
|
|
267
|
+
if (allowed instanceof Response) return allowed;
|
|
268
|
+
if (allowed === false) return jsonError(403, "This upload isn't allowed.");
|
|
269
|
+
if (allowed !== void 0 && allowed !== true) {
|
|
270
|
+
console.error("[seclai] authorizeUpload returned something other than true, false, nothing or a Response, so the request got a 500.", allowed);
|
|
271
|
+
return jsonError(500, NOT_AUTHORIZED);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
try {
|
|
275
|
+
const upload = await client.uploadAgentInput(agentId, {
|
|
276
|
+
file,
|
|
277
|
+
fileName: file.name,
|
|
278
|
+
mimeType: file.type || void 0
|
|
279
|
+
});
|
|
280
|
+
return json({
|
|
281
|
+
id: upload.id,
|
|
282
|
+
status: upload.status,
|
|
283
|
+
filename: upload.filename,
|
|
284
|
+
content_type: upload.content_type,
|
|
285
|
+
file_size: upload.file_size
|
|
286
|
+
});
|
|
287
|
+
} catch (err) {
|
|
288
|
+
return toErrorResponse(err);
|
|
289
|
+
}
|
|
290
|
+
},
|
|
291
|
+
async run(req) {
|
|
292
|
+
if (req.method !== "POST") return wrongMethod("POST");
|
|
293
|
+
let raw;
|
|
294
|
+
try {
|
|
295
|
+
raw = await req.json();
|
|
296
|
+
} catch {
|
|
297
|
+
return jsonError(400, "The request body must be JSON.");
|
|
298
|
+
}
|
|
299
|
+
const parsed = parseRunBody(raw);
|
|
300
|
+
if (typeof parsed === "string") return jsonError(400, parsed);
|
|
301
|
+
let body = parsed;
|
|
302
|
+
if (authorizeRun) {
|
|
303
|
+
const result = await callHook(
|
|
304
|
+
"authorizeRun",
|
|
305
|
+
req,
|
|
306
|
+
resolveCtx,
|
|
307
|
+
(ctx) => authorizeRun(req, parsed, ctx)
|
|
308
|
+
);
|
|
309
|
+
if ("response" in result) return result.response;
|
|
310
|
+
const verdict = result.value;
|
|
311
|
+
if (verdict instanceof Response) return verdict;
|
|
312
|
+
if (verdict === false) return jsonError(403, "This request isn't allowed.");
|
|
313
|
+
const kept = verdict === void 0 || verdict === true;
|
|
314
|
+
const rewritten = parseRunBody(kept ? parsed : verdict);
|
|
315
|
+
if (typeof rewritten === "string") {
|
|
316
|
+
console.error(
|
|
317
|
+
kept ? `[seclai] authorizeRun changed the body in place to one that isn't valid, so the request got a 500: ${rewritten}` : `[seclai] authorizeRun returned a body that isn't valid, so the request got a 500: ${rewritten}`
|
|
318
|
+
);
|
|
319
|
+
return jsonError(500, NOT_AUTHORIZED);
|
|
320
|
+
}
|
|
321
|
+
body = rewritten;
|
|
322
|
+
}
|
|
323
|
+
const upstream = new AbortController();
|
|
324
|
+
const abort = () => upstream.abort();
|
|
325
|
+
req.signal?.addEventListener("abort", abort, { once: true });
|
|
326
|
+
const events = client.runStreamingAgent(
|
|
327
|
+
agentId,
|
|
328
|
+
{
|
|
329
|
+
...body.input ? { input: body.input } : {},
|
|
330
|
+
...body.uploadIds?.length ? { input_upload_ids: body.uploadIds } : {},
|
|
331
|
+
...body.sessionId ? { metadata: { session_id: body.sessionId } } : {}
|
|
332
|
+
},
|
|
333
|
+
{ timeoutMs: runTimeoutMs, signal: upstream.signal }
|
|
279
334
|
);
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
const attachmentId = params.get("attachmentId") ?? "";
|
|
289
|
-
const name = params.get("name") ?? void 0;
|
|
290
|
-
if (!UUID.test(runId)) return jsonError(400, "`runId` must be a UUID.");
|
|
291
|
-
if (!ATTACHMENT_ID.test(attachmentId)) {
|
|
292
|
-
return jsonError(400, "`attachmentId` is not valid.");
|
|
293
|
-
}
|
|
294
|
-
if (name !== void 0 && name.length > MAX_DOWNLOAD_NAME_LENGTH) {
|
|
295
|
-
return jsonError(400, `\`name\` must be ${MAX_DOWNLOAD_NAME_LENGTH} characters or fewer.`);
|
|
296
|
-
}
|
|
297
|
-
try {
|
|
298
|
-
const upstream = await client.downloadAgentRunAttachment(runId, attachmentId, {
|
|
299
|
-
...name ? { downloadName: name } : {},
|
|
300
|
-
signal: req.signal
|
|
301
|
-
});
|
|
302
|
-
const contentType = upstream.headers.get("content-type") ?? "application/octet-stream";
|
|
303
|
-
const headers = new Headers({
|
|
304
|
-
"content-type": contentType,
|
|
305
|
-
"cache-control": "private, no-store",
|
|
306
|
-
"x-content-type-options": "nosniff"
|
|
307
|
-
});
|
|
308
|
-
const disposition = upstream.headers.get("content-disposition");
|
|
309
|
-
if (disposition) headers.set("content-disposition", disposition);
|
|
310
|
-
const length = upstream.headers.get("content-length");
|
|
311
|
-
if (length && !upstream.headers.has("content-encoding")) {
|
|
312
|
-
headers.set("content-length", length);
|
|
335
|
+
try {
|
|
336
|
+
const first = await events.next();
|
|
337
|
+
return new Response(
|
|
338
|
+
relayRunEvents(first.done ? void 0 : first.value, events, abort),
|
|
339
|
+
{ headers: SSE_HEADERS }
|
|
340
|
+
);
|
|
341
|
+
} catch (err) {
|
|
342
|
+
return toErrorResponse(err);
|
|
313
343
|
}
|
|
314
|
-
|
|
315
|
-
|
|
344
|
+
},
|
|
345
|
+
async download(req) {
|
|
346
|
+
if (req.method !== "GET") return wrongMethod("GET");
|
|
347
|
+
const params = new URL(req.url).searchParams;
|
|
348
|
+
const runId = params.get("runId") ?? "";
|
|
349
|
+
const attachmentId = params.get("attachmentId") ?? "";
|
|
350
|
+
const name = params.get("name") ?? void 0;
|
|
351
|
+
if (!UUID.test(runId)) return jsonError(400, "`runId` must be a UUID.");
|
|
352
|
+
if (!ATTACHMENT_ID.test(attachmentId)) {
|
|
353
|
+
return jsonError(400, "`attachmentId` is not valid.");
|
|
354
|
+
}
|
|
355
|
+
if (name !== void 0 && name.length > MAX_DOWNLOAD_NAME_LENGTH) {
|
|
356
|
+
return jsonError(400, `\`name\` must be ${MAX_DOWNLOAD_NAME_LENGTH} characters or fewer.`);
|
|
357
|
+
}
|
|
358
|
+
if (authorizeDownload) {
|
|
359
|
+
const result = await callHook(
|
|
360
|
+
"authorizeDownload",
|
|
361
|
+
req,
|
|
362
|
+
resolveCtx,
|
|
363
|
+
(ctx) => authorizeDownload(req, { runId, attachmentId }, ctx)
|
|
364
|
+
);
|
|
365
|
+
if ("response" in result) return result.response;
|
|
366
|
+
const allowed = result.value;
|
|
367
|
+
if (allowed instanceof Response) return allowed;
|
|
368
|
+
if (allowed !== true && allowed !== false && !warnedDownloadResult) {
|
|
369
|
+
warnedDownloadResult = true;
|
|
370
|
+
console.warn(
|
|
371
|
+
`[seclai] authorizeDownload returned ${String(allowed)}, not true or false, so the download was refused with a 404. Return true to serve the file.`
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
if (allowed !== true) return jsonError(404, "Not found.");
|
|
375
|
+
}
|
|
376
|
+
try {
|
|
377
|
+
const upstream = await client.downloadAgentRunAttachment(runId, attachmentId, {
|
|
378
|
+
...name ? { downloadName: name } : {},
|
|
379
|
+
signal: req.signal
|
|
380
|
+
});
|
|
381
|
+
const contentType = upstream.headers.get("content-type") ?? "application/octet-stream";
|
|
382
|
+
const headers = new Headers({
|
|
383
|
+
"content-type": contentType,
|
|
384
|
+
"cache-control": "private, no-store",
|
|
385
|
+
"x-content-type-options": "nosniff"
|
|
386
|
+
});
|
|
387
|
+
const disposition = upstream.headers.get("content-disposition");
|
|
388
|
+
if (disposition) headers.set("content-disposition", disposition);
|
|
389
|
+
const length = upstream.headers.get("content-length");
|
|
390
|
+
if (length && !upstream.headers.has("content-encoding")) {
|
|
391
|
+
headers.set("content-length", length);
|
|
392
|
+
}
|
|
393
|
+
if (!contentType.toLowerCase().startsWith("application/pdf")) {
|
|
394
|
+
headers.set("content-security-policy", "sandbox; default-src 'none'");
|
|
395
|
+
}
|
|
396
|
+
return new Response(upstream.body, { status: upstream.status, headers });
|
|
397
|
+
} catch (err) {
|
|
398
|
+
return toErrorResponse(err);
|
|
316
399
|
}
|
|
317
|
-
return new Response(upstream.body, { status: upstream.status, headers });
|
|
318
|
-
} catch (err) {
|
|
319
|
-
return toErrorResponse(err);
|
|
320
400
|
}
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
}
|
|
401
|
+
};
|
|
402
|
+
return {
|
|
403
|
+
...handlers,
|
|
404
|
+
async handle(req) {
|
|
405
|
+
const segment = new URL(req.url).pathname.replace(/\/+$/, "").split("/").pop() ?? "";
|
|
406
|
+
const name = Object.hasOwn(ROUTES, segment) ? ROUTES[segment] : void 0;
|
|
407
|
+
if (!name) return jsonError(404, "Not found.");
|
|
408
|
+
return handlers[name](req);
|
|
409
|
+
}
|
|
410
|
+
};
|
|
331
411
|
};
|
|
412
|
+
const unbound = build(
|
|
413
|
+
context ? async (req) => context(req) : async () => void 0
|
|
414
|
+
);
|
|
415
|
+
return { ...unbound, withContext: (ctx) => build(async () => ctx) };
|
|
332
416
|
}
|
|
333
417
|
// Annotate the CommonJS export names for ESM import in node:
|
|
334
418
|
0 && (module.exports = {
|
|
335
419
|
DEFAULT_API_VERSION,
|
|
336
420
|
MIN_API_VERSION,
|
|
337
|
-
createSeclaiHandlers
|
|
421
|
+
createSeclaiHandlers,
|
|
422
|
+
deny
|
|
338
423
|
});
|
package/dist/index.d.cts
CHANGED
|
@@ -10,7 +10,7 @@ declare const MIN_API_VERSION: "2026-10-16";
|
|
|
10
10
|
* and could change response shapes underneath a deployed app.
|
|
11
11
|
*/
|
|
12
12
|
declare const DEFAULT_API_VERSION: "2026-10-28";
|
|
13
|
-
interface SeclaiHandlersOptions {
|
|
13
|
+
interface SeclaiHandlersOptions<Ctx = undefined> {
|
|
14
14
|
/** Seclai API key. Server-side only: never expose it to the browser. */
|
|
15
15
|
apiKey: string;
|
|
16
16
|
/** The agent these handlers run. */
|
|
@@ -19,7 +19,51 @@ interface SeclaiHandlersOptions {
|
|
|
19
19
|
apiVersion?: ApiVersion;
|
|
20
20
|
/** How long a streaming run may take, in milliseconds. Defaults to 11 minutes. */
|
|
21
21
|
runTimeoutMs?: number;
|
|
22
|
+
/**
|
|
23
|
+
* Your app's per-request context (for example the signed-in user), passed to
|
|
24
|
+
* each hook as its last argument. Called only when a hook is about to run.
|
|
25
|
+
* Throw `deny(401, …)` here to refuse every hooked request at once. To pass
|
|
26
|
+
* context your framework already has instead, use
|
|
27
|
+
* {@link WithContext.withContext}.
|
|
28
|
+
*/
|
|
29
|
+
context?: (req: Request) => Ctx | Promise<Ctx>;
|
|
30
|
+
/**
|
|
31
|
+
* Called after the `run` body has been validated, before the agent runs. Check
|
|
32
|
+
* `sessionId` and `uploadIds` against your own data here.
|
|
33
|
+
*
|
|
34
|
+
* Return nothing (or `true`) to run the body as it is, a rewritten body to run
|
|
35
|
+
* that instead (it is validated again), or `false` or a `Response` to refuse.
|
|
36
|
+
* `false` sends a 403. A rewritten body that fails validation gets a 500, and
|
|
37
|
+
* the reason is logged.
|
|
38
|
+
*/
|
|
39
|
+
authorizeRun?: AuthorizeRun<Ctx>;
|
|
40
|
+
/**
|
|
41
|
+
* Called after `upload` has read the form, before the file is sent to Seclai.
|
|
42
|
+
* Return nothing (or `true`) to upload it, or `false` or a `Response` to
|
|
43
|
+
* refuse. `false` sends a 403.
|
|
44
|
+
*/
|
|
45
|
+
authorizeUpload?: AuthorizeUpload<Ctx>;
|
|
46
|
+
/**
|
|
47
|
+
* Called after `download` has checked the ids' format, before the API call.
|
|
48
|
+
* Return `true` to serve the file, or `false` or a `Response` to refuse.
|
|
49
|
+
* `false` sends a 404, so a refusal doesn't confirm the file exists.
|
|
50
|
+
*
|
|
51
|
+
* Unlike the other hooks this one fails closed: returning nothing also
|
|
52
|
+
* refuses with a 404, and logs a warning, because it guards stored files.
|
|
53
|
+
*/
|
|
54
|
+
authorizeDownload?: AuthorizeDownload<Ctx>;
|
|
55
|
+
}
|
|
56
|
+
/** See {@link SeclaiHandlersOptions.authorizeRun}. */
|
|
57
|
+
type AuthorizeRun<Ctx = undefined> = (req: Request, body: RunRequestBody, ctx: Ctx) => RunRequestBody | boolean | Response | void | Promise<RunRequestBody | boolean | Response | void>;
|
|
58
|
+
/** See {@link SeclaiHandlersOptions.authorizeUpload}. */
|
|
59
|
+
type AuthorizeUpload<Ctx = undefined> = (req: Request, file: File, ctx: Ctx) => boolean | Response | void | Promise<boolean | Response | void>;
|
|
60
|
+
/** The ids a `download` request asks for. */
|
|
61
|
+
interface DownloadIds {
|
|
62
|
+
runId: string;
|
|
63
|
+
attachmentId: string;
|
|
22
64
|
}
|
|
65
|
+
/** See {@link SeclaiHandlersOptions.authorizeDownload}. */
|
|
66
|
+
type AuthorizeDownload<Ctx = undefined> = (req: Request, ids: DownloadIds, ctx: Ctx) => boolean | Response | Promise<boolean | Response>;
|
|
23
67
|
/** JSON body accepted by the `run` handler. */
|
|
24
68
|
interface RunRequestBody {
|
|
25
69
|
/** The prompt text. */
|
|
@@ -46,13 +90,51 @@ interface SeclaiHandlers {
|
|
|
46
90
|
*/
|
|
47
91
|
handle: SeclaiHandler;
|
|
48
92
|
}
|
|
93
|
+
/** What {@link createSeclaiHandlers} adds to the handlers. */
|
|
94
|
+
interface WithContext<Ctx> {
|
|
95
|
+
/**
|
|
96
|
+
* The same handlers, with `ctx` passed to the hooks instead of calling the
|
|
97
|
+
* `context` option. Use it when your framework already knows the user:
|
|
98
|
+
*
|
|
99
|
+
* ```ts
|
|
100
|
+
* export const action = ({ request, context }) =>
|
|
101
|
+
* seclai.withContext({ userId: context.get(user).id }).handle(request);
|
|
102
|
+
* ```
|
|
103
|
+
*/
|
|
104
|
+
withContext(ctx: Ctx): SeclaiHandlers;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* A refusal for a hook to return or throw: the `{ error, status }` JSON the
|
|
108
|
+
* handlers use for their own errors, which `@seclai/react` shows to the user.
|
|
109
|
+
*
|
|
110
|
+
* ```ts
|
|
111
|
+
* authorizeRun(req, body, { userId }) {
|
|
112
|
+
* if (!ownsSession(userId, body.sessionId)) return deny(403, "That isn't your conversation.");
|
|
113
|
+
* }
|
|
114
|
+
* ```
|
|
115
|
+
*/
|
|
116
|
+
declare function deny(status: number, message: string, headers?: HeadersInit): Response;
|
|
117
|
+
/**
|
|
118
|
+
* The handlers {@link createSeclaiHandlers} returns without a `context` option.
|
|
119
|
+
* When the hooks need a context (`Ctx` doesn't include `undefined`), only
|
|
120
|
+
* `withContext` is offered, so a route can't call the hooks without one.
|
|
121
|
+
*/
|
|
122
|
+
type UnboundSeclaiHandlers<Ctx> = undefined extends Ctx ? SeclaiHandlers & WithContext<Ctx> : WithContext<Ctx>;
|
|
49
123
|
/**
|
|
50
124
|
* Create the server handlers for one agent. Each takes a Web `Request` and
|
|
51
125
|
* returns a Web `Response`, so they mount on any runtime with those APIs. Routing
|
|
52
126
|
* is left to the host framework.
|
|
53
127
|
*
|
|
128
|
+
* With a `context` option, the handlers resolve the hooks' context from each
|
|
129
|
+
* request. Without one, a typed context is passed with `withContext(ctx)`.
|
|
130
|
+
*
|
|
54
131
|
* @throws If `apiKey` or `agentId` is missing, or `apiVersion` is too old.
|
|
55
132
|
*/
|
|
56
|
-
declare function createSeclaiHandlers(options: SeclaiHandlersOptions
|
|
133
|
+
declare function createSeclaiHandlers<Ctx>(options: SeclaiHandlersOptions<Ctx> & {
|
|
134
|
+
context: (req: Request) => Ctx | Promise<Ctx>;
|
|
135
|
+
}): SeclaiHandlers & WithContext<Ctx>;
|
|
136
|
+
declare function createSeclaiHandlers<Ctx = undefined>(options: SeclaiHandlersOptions<Ctx> & {
|
|
137
|
+
context?: undefined;
|
|
138
|
+
}): UnboundSeclaiHandlers<Ctx>;
|
|
57
139
|
|
|
58
|
-
export { DEFAULT_API_VERSION, MIN_API_VERSION, type RunRequestBody, type SeclaiHandler, type SeclaiHandlers, type SeclaiHandlersOptions, createSeclaiHandlers };
|
|
140
|
+
export { type AuthorizeDownload, type AuthorizeRun, type AuthorizeUpload, DEFAULT_API_VERSION, type DownloadIds, MIN_API_VERSION, type RunRequestBody, type SeclaiHandler, type SeclaiHandlers, type SeclaiHandlersOptions, type UnboundSeclaiHandlers, type WithContext, createSeclaiHandlers, deny };
|
package/dist/index.d.ts
CHANGED
|
@@ -10,7 +10,7 @@ declare const MIN_API_VERSION: "2026-10-16";
|
|
|
10
10
|
* and could change response shapes underneath a deployed app.
|
|
11
11
|
*/
|
|
12
12
|
declare const DEFAULT_API_VERSION: "2026-10-28";
|
|
13
|
-
interface SeclaiHandlersOptions {
|
|
13
|
+
interface SeclaiHandlersOptions<Ctx = undefined> {
|
|
14
14
|
/** Seclai API key. Server-side only: never expose it to the browser. */
|
|
15
15
|
apiKey: string;
|
|
16
16
|
/** The agent these handlers run. */
|
|
@@ -19,7 +19,51 @@ interface SeclaiHandlersOptions {
|
|
|
19
19
|
apiVersion?: ApiVersion;
|
|
20
20
|
/** How long a streaming run may take, in milliseconds. Defaults to 11 minutes. */
|
|
21
21
|
runTimeoutMs?: number;
|
|
22
|
+
/**
|
|
23
|
+
* Your app's per-request context (for example the signed-in user), passed to
|
|
24
|
+
* each hook as its last argument. Called only when a hook is about to run.
|
|
25
|
+
* Throw `deny(401, …)` here to refuse every hooked request at once. To pass
|
|
26
|
+
* context your framework already has instead, use
|
|
27
|
+
* {@link WithContext.withContext}.
|
|
28
|
+
*/
|
|
29
|
+
context?: (req: Request) => Ctx | Promise<Ctx>;
|
|
30
|
+
/**
|
|
31
|
+
* Called after the `run` body has been validated, before the agent runs. Check
|
|
32
|
+
* `sessionId` and `uploadIds` against your own data here.
|
|
33
|
+
*
|
|
34
|
+
* Return nothing (or `true`) to run the body as it is, a rewritten body to run
|
|
35
|
+
* that instead (it is validated again), or `false` or a `Response` to refuse.
|
|
36
|
+
* `false` sends a 403. A rewritten body that fails validation gets a 500, and
|
|
37
|
+
* the reason is logged.
|
|
38
|
+
*/
|
|
39
|
+
authorizeRun?: AuthorizeRun<Ctx>;
|
|
40
|
+
/**
|
|
41
|
+
* Called after `upload` has read the form, before the file is sent to Seclai.
|
|
42
|
+
* Return nothing (or `true`) to upload it, or `false` or a `Response` to
|
|
43
|
+
* refuse. `false` sends a 403.
|
|
44
|
+
*/
|
|
45
|
+
authorizeUpload?: AuthorizeUpload<Ctx>;
|
|
46
|
+
/**
|
|
47
|
+
* Called after `download` has checked the ids' format, before the API call.
|
|
48
|
+
* Return `true` to serve the file, or `false` or a `Response` to refuse.
|
|
49
|
+
* `false` sends a 404, so a refusal doesn't confirm the file exists.
|
|
50
|
+
*
|
|
51
|
+
* Unlike the other hooks this one fails closed: returning nothing also
|
|
52
|
+
* refuses with a 404, and logs a warning, because it guards stored files.
|
|
53
|
+
*/
|
|
54
|
+
authorizeDownload?: AuthorizeDownload<Ctx>;
|
|
55
|
+
}
|
|
56
|
+
/** See {@link SeclaiHandlersOptions.authorizeRun}. */
|
|
57
|
+
type AuthorizeRun<Ctx = undefined> = (req: Request, body: RunRequestBody, ctx: Ctx) => RunRequestBody | boolean | Response | void | Promise<RunRequestBody | boolean | Response | void>;
|
|
58
|
+
/** See {@link SeclaiHandlersOptions.authorizeUpload}. */
|
|
59
|
+
type AuthorizeUpload<Ctx = undefined> = (req: Request, file: File, ctx: Ctx) => boolean | Response | void | Promise<boolean | Response | void>;
|
|
60
|
+
/** The ids a `download` request asks for. */
|
|
61
|
+
interface DownloadIds {
|
|
62
|
+
runId: string;
|
|
63
|
+
attachmentId: string;
|
|
22
64
|
}
|
|
65
|
+
/** See {@link SeclaiHandlersOptions.authorizeDownload}. */
|
|
66
|
+
type AuthorizeDownload<Ctx = undefined> = (req: Request, ids: DownloadIds, ctx: Ctx) => boolean | Response | Promise<boolean | Response>;
|
|
23
67
|
/** JSON body accepted by the `run` handler. */
|
|
24
68
|
interface RunRequestBody {
|
|
25
69
|
/** The prompt text. */
|
|
@@ -46,13 +90,51 @@ interface SeclaiHandlers {
|
|
|
46
90
|
*/
|
|
47
91
|
handle: SeclaiHandler;
|
|
48
92
|
}
|
|
93
|
+
/** What {@link createSeclaiHandlers} adds to the handlers. */
|
|
94
|
+
interface WithContext<Ctx> {
|
|
95
|
+
/**
|
|
96
|
+
* The same handlers, with `ctx` passed to the hooks instead of calling the
|
|
97
|
+
* `context` option. Use it when your framework already knows the user:
|
|
98
|
+
*
|
|
99
|
+
* ```ts
|
|
100
|
+
* export const action = ({ request, context }) =>
|
|
101
|
+
* seclai.withContext({ userId: context.get(user).id }).handle(request);
|
|
102
|
+
* ```
|
|
103
|
+
*/
|
|
104
|
+
withContext(ctx: Ctx): SeclaiHandlers;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* A refusal for a hook to return or throw: the `{ error, status }` JSON the
|
|
108
|
+
* handlers use for their own errors, which `@seclai/react` shows to the user.
|
|
109
|
+
*
|
|
110
|
+
* ```ts
|
|
111
|
+
* authorizeRun(req, body, { userId }) {
|
|
112
|
+
* if (!ownsSession(userId, body.sessionId)) return deny(403, "That isn't your conversation.");
|
|
113
|
+
* }
|
|
114
|
+
* ```
|
|
115
|
+
*/
|
|
116
|
+
declare function deny(status: number, message: string, headers?: HeadersInit): Response;
|
|
117
|
+
/**
|
|
118
|
+
* The handlers {@link createSeclaiHandlers} returns without a `context` option.
|
|
119
|
+
* When the hooks need a context (`Ctx` doesn't include `undefined`), only
|
|
120
|
+
* `withContext` is offered, so a route can't call the hooks without one.
|
|
121
|
+
*/
|
|
122
|
+
type UnboundSeclaiHandlers<Ctx> = undefined extends Ctx ? SeclaiHandlers & WithContext<Ctx> : WithContext<Ctx>;
|
|
49
123
|
/**
|
|
50
124
|
* Create the server handlers for one agent. Each takes a Web `Request` and
|
|
51
125
|
* returns a Web `Response`, so they mount on any runtime with those APIs. Routing
|
|
52
126
|
* is left to the host framework.
|
|
53
127
|
*
|
|
128
|
+
* With a `context` option, the handlers resolve the hooks' context from each
|
|
129
|
+
* request. Without one, a typed context is passed with `withContext(ctx)`.
|
|
130
|
+
*
|
|
54
131
|
* @throws If `apiKey` or `agentId` is missing, or `apiVersion` is too old.
|
|
55
132
|
*/
|
|
56
|
-
declare function createSeclaiHandlers(options: SeclaiHandlersOptions
|
|
133
|
+
declare function createSeclaiHandlers<Ctx>(options: SeclaiHandlersOptions<Ctx> & {
|
|
134
|
+
context: (req: Request) => Ctx | Promise<Ctx>;
|
|
135
|
+
}): SeclaiHandlers & WithContext<Ctx>;
|
|
136
|
+
declare function createSeclaiHandlers<Ctx = undefined>(options: SeclaiHandlersOptions<Ctx> & {
|
|
137
|
+
context?: undefined;
|
|
138
|
+
}): UnboundSeclaiHandlers<Ctx>;
|
|
57
139
|
|
|
58
|
-
export { DEFAULT_API_VERSION, MIN_API_VERSION, type RunRequestBody, type SeclaiHandler, type SeclaiHandlers, type SeclaiHandlersOptions, createSeclaiHandlers };
|
|
140
|
+
export { type AuthorizeDownload, type AuthorizeRun, type AuthorizeUpload, DEFAULT_API_VERSION, type DownloadIds, MIN_API_VERSION, type RunRequestBody, type SeclaiHandler, type SeclaiHandlers, type SeclaiHandlersOptions, type UnboundSeclaiHandlers, type WithContext, createSeclaiHandlers, deny };
|
package/dist/index.js
CHANGED
|
@@ -147,6 +147,10 @@ var ROUTES = {
|
|
|
147
147
|
function wrongMethod(allow) {
|
|
148
148
|
return jsonError(405, "Method not allowed.", { allow });
|
|
149
149
|
}
|
|
150
|
+
var NOT_AUTHORIZED = "Could not authorize this request.";
|
|
151
|
+
function deny(status, message, headers) {
|
|
152
|
+
return jsonError(status, message, headers);
|
|
153
|
+
}
|
|
150
154
|
function parseRunBody(body) {
|
|
151
155
|
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
152
156
|
return "The request body must be a JSON object.";
|
|
@@ -171,7 +175,11 @@ function createSeclaiHandlers(options) {
|
|
|
171
175
|
apiKey,
|
|
172
176
|
agentId,
|
|
173
177
|
apiVersion = DEFAULT_API_VERSION,
|
|
174
|
-
runTimeoutMs = DEFAULT_RUN_TIMEOUT_MS
|
|
178
|
+
runTimeoutMs = DEFAULT_RUN_TIMEOUT_MS,
|
|
179
|
+
context,
|
|
180
|
+
authorizeRun,
|
|
181
|
+
authorizeUpload,
|
|
182
|
+
authorizeDownload
|
|
175
183
|
} = options;
|
|
176
184
|
if (!apiKey) throw new Error("createSeclaiHandlers: `apiKey` is required.");
|
|
177
185
|
if (!agentId) throw new Error("createSeclaiHandlers: `agentId` is required.");
|
|
@@ -187,127 +195,203 @@ function createSeclaiHandlers(options) {
|
|
|
187
195
|
// when called with any `this` but the global, so it can't be passed bare.
|
|
188
196
|
fetch: (input, init) => globalThis.fetch(input, init)
|
|
189
197
|
});
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
198
|
+
let warnedDownloadResult = false;
|
|
199
|
+
async function callHook(name, req, resolveCtx, hook) {
|
|
200
|
+
let ctx;
|
|
201
|
+
try {
|
|
202
|
+
ctx = await resolveCtx(req);
|
|
203
|
+
return { value: await hook(ctx) };
|
|
204
|
+
} catch (err) {
|
|
205
|
+
if (err instanceof Response) return { response: err };
|
|
206
|
+
const hint = ctx === void 0 && err instanceof TypeError ? " No context was passed: set the `context` option, or call `withContext(ctx)`." : "";
|
|
207
|
+
console.error(`[seclai] ${name} threw, so the request got a 500.${hint}`, err);
|
|
208
|
+
return { response: jsonError(500, NOT_AUTHORIZED) };
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
const build = (resolveCtx) => {
|
|
212
|
+
const handlers = {
|
|
213
|
+
async attachmentReferences(req) {
|
|
214
|
+
if (req.method !== "GET") return wrongMethod("GET");
|
|
215
|
+
try {
|
|
216
|
+
return json(await client.getAgentAttachmentReferences(agentId));
|
|
217
|
+
} catch (err) {
|
|
218
|
+
return toErrorResponse(err);
|
|
219
|
+
}
|
|
220
|
+
},
|
|
221
|
+
async upload(req) {
|
|
222
|
+
if (req.method !== "POST") return wrongMethod("POST");
|
|
223
|
+
let form;
|
|
224
|
+
try {
|
|
225
|
+
form = await req.formData();
|
|
226
|
+
} catch {
|
|
227
|
+
return jsonError(400, "The request body must be multipart form data.");
|
|
228
|
+
}
|
|
229
|
+
const file = form.get("file");
|
|
230
|
+
if (file === null || typeof file === "string") {
|
|
231
|
+
return jsonError(400, "The form must include a `file` field holding a file.");
|
|
232
|
+
}
|
|
233
|
+
if (authorizeUpload) {
|
|
234
|
+
const result = await callHook(
|
|
235
|
+
"authorizeUpload",
|
|
236
|
+
req,
|
|
237
|
+
resolveCtx,
|
|
238
|
+
(ctx) => authorizeUpload(req, file, ctx)
|
|
239
|
+
);
|
|
240
|
+
if ("response" in result) return result.response;
|
|
241
|
+
const allowed = result.value;
|
|
242
|
+
if (allowed instanceof Response) return allowed;
|
|
243
|
+
if (allowed === false) return jsonError(403, "This upload isn't allowed.");
|
|
244
|
+
if (allowed !== void 0 && allowed !== true) {
|
|
245
|
+
console.error("[seclai] authorizeUpload returned something other than true, false, nothing or a Response, so the request got a 500.", allowed);
|
|
246
|
+
return jsonError(500, NOT_AUTHORIZED);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
try {
|
|
250
|
+
const upload = await client.uploadAgentInput(agentId, {
|
|
251
|
+
file,
|
|
252
|
+
fileName: file.name,
|
|
253
|
+
mimeType: file.type || void 0
|
|
254
|
+
});
|
|
255
|
+
return json({
|
|
256
|
+
id: upload.id,
|
|
257
|
+
status: upload.status,
|
|
258
|
+
filename: upload.filename,
|
|
259
|
+
content_type: upload.content_type,
|
|
260
|
+
file_size: upload.file_size
|
|
261
|
+
});
|
|
262
|
+
} catch (err) {
|
|
263
|
+
return toErrorResponse(err);
|
|
264
|
+
}
|
|
265
|
+
},
|
|
266
|
+
async run(req) {
|
|
267
|
+
if (req.method !== "POST") return wrongMethod("POST");
|
|
268
|
+
let raw;
|
|
269
|
+
try {
|
|
270
|
+
raw = await req.json();
|
|
271
|
+
} catch {
|
|
272
|
+
return jsonError(400, "The request body must be JSON.");
|
|
273
|
+
}
|
|
274
|
+
const parsed = parseRunBody(raw);
|
|
275
|
+
if (typeof parsed === "string") return jsonError(400, parsed);
|
|
276
|
+
let body = parsed;
|
|
277
|
+
if (authorizeRun) {
|
|
278
|
+
const result = await callHook(
|
|
279
|
+
"authorizeRun",
|
|
280
|
+
req,
|
|
281
|
+
resolveCtx,
|
|
282
|
+
(ctx) => authorizeRun(req, parsed, ctx)
|
|
283
|
+
);
|
|
284
|
+
if ("response" in result) return result.response;
|
|
285
|
+
const verdict = result.value;
|
|
286
|
+
if (verdict instanceof Response) return verdict;
|
|
287
|
+
if (verdict === false) return jsonError(403, "This request isn't allowed.");
|
|
288
|
+
const kept = verdict === void 0 || verdict === true;
|
|
289
|
+
const rewritten = parseRunBody(kept ? parsed : verdict);
|
|
290
|
+
if (typeof rewritten === "string") {
|
|
291
|
+
console.error(
|
|
292
|
+
kept ? `[seclai] authorizeRun changed the body in place to one that isn't valid, so the request got a 500: ${rewritten}` : `[seclai] authorizeRun returned a body that isn't valid, so the request got a 500: ${rewritten}`
|
|
293
|
+
);
|
|
294
|
+
return jsonError(500, NOT_AUTHORIZED);
|
|
295
|
+
}
|
|
296
|
+
body = rewritten;
|
|
297
|
+
}
|
|
298
|
+
const upstream = new AbortController();
|
|
299
|
+
const abort = () => upstream.abort();
|
|
300
|
+
req.signal?.addEventListener("abort", abort, { once: true });
|
|
301
|
+
const events = client.runStreamingAgent(
|
|
302
|
+
agentId,
|
|
303
|
+
{
|
|
304
|
+
...body.input ? { input: body.input } : {},
|
|
305
|
+
...body.uploadIds?.length ? { input_upload_ids: body.uploadIds } : {},
|
|
306
|
+
...body.sessionId ? { metadata: { session_id: body.sessionId } } : {}
|
|
307
|
+
},
|
|
308
|
+
{ timeoutMs: runTimeoutMs, signal: upstream.signal }
|
|
255
309
|
);
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
const attachmentId = params.get("attachmentId") ?? "";
|
|
265
|
-
const name = params.get("name") ?? void 0;
|
|
266
|
-
if (!UUID.test(runId)) return jsonError(400, "`runId` must be a UUID.");
|
|
267
|
-
if (!ATTACHMENT_ID.test(attachmentId)) {
|
|
268
|
-
return jsonError(400, "`attachmentId` is not valid.");
|
|
269
|
-
}
|
|
270
|
-
if (name !== void 0 && name.length > MAX_DOWNLOAD_NAME_LENGTH) {
|
|
271
|
-
return jsonError(400, `\`name\` must be ${MAX_DOWNLOAD_NAME_LENGTH} characters or fewer.`);
|
|
272
|
-
}
|
|
273
|
-
try {
|
|
274
|
-
const upstream = await client.downloadAgentRunAttachment(runId, attachmentId, {
|
|
275
|
-
...name ? { downloadName: name } : {},
|
|
276
|
-
signal: req.signal
|
|
277
|
-
});
|
|
278
|
-
const contentType = upstream.headers.get("content-type") ?? "application/octet-stream";
|
|
279
|
-
const headers = new Headers({
|
|
280
|
-
"content-type": contentType,
|
|
281
|
-
"cache-control": "private, no-store",
|
|
282
|
-
"x-content-type-options": "nosniff"
|
|
283
|
-
});
|
|
284
|
-
const disposition = upstream.headers.get("content-disposition");
|
|
285
|
-
if (disposition) headers.set("content-disposition", disposition);
|
|
286
|
-
const length = upstream.headers.get("content-length");
|
|
287
|
-
if (length && !upstream.headers.has("content-encoding")) {
|
|
288
|
-
headers.set("content-length", length);
|
|
310
|
+
try {
|
|
311
|
+
const first = await events.next();
|
|
312
|
+
return new Response(
|
|
313
|
+
relayRunEvents(first.done ? void 0 : first.value, events, abort),
|
|
314
|
+
{ headers: SSE_HEADERS }
|
|
315
|
+
);
|
|
316
|
+
} catch (err) {
|
|
317
|
+
return toErrorResponse(err);
|
|
289
318
|
}
|
|
290
|
-
|
|
291
|
-
|
|
319
|
+
},
|
|
320
|
+
async download(req) {
|
|
321
|
+
if (req.method !== "GET") return wrongMethod("GET");
|
|
322
|
+
const params = new URL(req.url).searchParams;
|
|
323
|
+
const runId = params.get("runId") ?? "";
|
|
324
|
+
const attachmentId = params.get("attachmentId") ?? "";
|
|
325
|
+
const name = params.get("name") ?? void 0;
|
|
326
|
+
if (!UUID.test(runId)) return jsonError(400, "`runId` must be a UUID.");
|
|
327
|
+
if (!ATTACHMENT_ID.test(attachmentId)) {
|
|
328
|
+
return jsonError(400, "`attachmentId` is not valid.");
|
|
329
|
+
}
|
|
330
|
+
if (name !== void 0 && name.length > MAX_DOWNLOAD_NAME_LENGTH) {
|
|
331
|
+
return jsonError(400, `\`name\` must be ${MAX_DOWNLOAD_NAME_LENGTH} characters or fewer.`);
|
|
332
|
+
}
|
|
333
|
+
if (authorizeDownload) {
|
|
334
|
+
const result = await callHook(
|
|
335
|
+
"authorizeDownload",
|
|
336
|
+
req,
|
|
337
|
+
resolveCtx,
|
|
338
|
+
(ctx) => authorizeDownload(req, { runId, attachmentId }, ctx)
|
|
339
|
+
);
|
|
340
|
+
if ("response" in result) return result.response;
|
|
341
|
+
const allowed = result.value;
|
|
342
|
+
if (allowed instanceof Response) return allowed;
|
|
343
|
+
if (allowed !== true && allowed !== false && !warnedDownloadResult) {
|
|
344
|
+
warnedDownloadResult = true;
|
|
345
|
+
console.warn(
|
|
346
|
+
`[seclai] authorizeDownload returned ${String(allowed)}, not true or false, so the download was refused with a 404. Return true to serve the file.`
|
|
347
|
+
);
|
|
348
|
+
}
|
|
349
|
+
if (allowed !== true) return jsonError(404, "Not found.");
|
|
350
|
+
}
|
|
351
|
+
try {
|
|
352
|
+
const upstream = await client.downloadAgentRunAttachment(runId, attachmentId, {
|
|
353
|
+
...name ? { downloadName: name } : {},
|
|
354
|
+
signal: req.signal
|
|
355
|
+
});
|
|
356
|
+
const contentType = upstream.headers.get("content-type") ?? "application/octet-stream";
|
|
357
|
+
const headers = new Headers({
|
|
358
|
+
"content-type": contentType,
|
|
359
|
+
"cache-control": "private, no-store",
|
|
360
|
+
"x-content-type-options": "nosniff"
|
|
361
|
+
});
|
|
362
|
+
const disposition = upstream.headers.get("content-disposition");
|
|
363
|
+
if (disposition) headers.set("content-disposition", disposition);
|
|
364
|
+
const length = upstream.headers.get("content-length");
|
|
365
|
+
if (length && !upstream.headers.has("content-encoding")) {
|
|
366
|
+
headers.set("content-length", length);
|
|
367
|
+
}
|
|
368
|
+
if (!contentType.toLowerCase().startsWith("application/pdf")) {
|
|
369
|
+
headers.set("content-security-policy", "sandbox; default-src 'none'");
|
|
370
|
+
}
|
|
371
|
+
return new Response(upstream.body, { status: upstream.status, headers });
|
|
372
|
+
} catch (err) {
|
|
373
|
+
return toErrorResponse(err);
|
|
292
374
|
}
|
|
293
|
-
return new Response(upstream.body, { status: upstream.status, headers });
|
|
294
|
-
} catch (err) {
|
|
295
|
-
return toErrorResponse(err);
|
|
296
375
|
}
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
}
|
|
376
|
+
};
|
|
377
|
+
return {
|
|
378
|
+
...handlers,
|
|
379
|
+
async handle(req) {
|
|
380
|
+
const segment = new URL(req.url).pathname.replace(/\/+$/, "").split("/").pop() ?? "";
|
|
381
|
+
const name = Object.hasOwn(ROUTES, segment) ? ROUTES[segment] : void 0;
|
|
382
|
+
if (!name) return jsonError(404, "Not found.");
|
|
383
|
+
return handlers[name](req);
|
|
384
|
+
}
|
|
385
|
+
};
|
|
307
386
|
};
|
|
387
|
+
const unbound = build(
|
|
388
|
+
context ? async (req) => context(req) : async () => void 0
|
|
389
|
+
);
|
|
390
|
+
return { ...unbound, withContext: (ctx) => build(async () => ctx) };
|
|
308
391
|
}
|
|
309
392
|
export {
|
|
310
393
|
DEFAULT_API_VERSION,
|
|
311
394
|
MIN_API_VERSION,
|
|
312
|
-
createSeclaiHandlers
|
|
395
|
+
createSeclaiHandlers,
|
|
396
|
+
deny
|
|
313
397
|
};
|
package/package.json
CHANGED