@seclai/handlers 0.0.14 → 0.0.16

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 CHANGED
@@ -70,7 +70,7 @@ The `attachmentReferences` handler always looks up afresh, and a successful look
70
70
  | `keepReadingAfterDisconnect` | `false` | Keep reading a run after the browser leaves, so `onRunEnd` gets its real outcome. See [Saving replies after a disconnect](#saving-replies-after-a-disconnect) |
71
71
  | `context` | None | `(req)`: your per-request context, such as the signed-in user, passed to every hook. See [Access control](#access-control) |
72
72
  | `authorizeRun` | None | `(req, body, ctx)`: refuse or rewrite a run. See [Access control](#access-control) |
73
- | `authorizeUpload` | None | `(req, file, ctx)`: refuse an upload before it reaches Seclai |
73
+ | `authorizeUpload` | None | `(req, file, ctx, params)`: refuse an upload before it reaches Seclai. See [Upload params](#upload-params) |
74
74
  | `authorizeDownload` | None | `(req, { runId, attachmentId }, ctx)`: return `true` to serve the file |
75
75
  | `upload` | None | Size limit, content-type check and hook for `upload`, below |
76
76
  | `logger` | None | `{ debug, info, warn, error }`, such as `console`: gets a line for each step of a run, upload and download. See [Logging](#logging) |
@@ -95,13 +95,42 @@ const seclai = createSeclaiHandlers({
95
95
  |---|---|---|
96
96
  | `maxBytes` | No limit | Largest file accepted, in bytes. A bigger one gets a 413 |
97
97
  | `checkContentType` | `false` | Give a 415 to a file whose type none of the agent's attachment slots accepts |
98
- | `onUpload(file, result, req, context)` | None | Called after a successful upload. Return a `Response` to replace the default JSON |
98
+ | `onUpload(file, result, req, context, params)` | None | Called after a successful upload. Return a `Response` to replace the default JSON |
99
99
 
100
100
  The size checks and the content-type check refuse a file before it reaches the API, and `onUpload` runs only after the API has accepted one. In order, `upload` checks the size, then calls [`authorizeUpload`](#access-control), then checks the content type, so a refused caller never triggers the slot lookup.
101
101
 
102
102
  - **`maxBytes`** is checked against `content-length` first, so a request that declares an oversized body is refused before it's read. Without `content-length`, as with a chunked body, the bytes are counted as they stream and reading stops with a 413 once they pass the limit. Both checks allow 64 KB for the multipart envelope, and the file's own size is checked once the form is read.
103
103
  - **`checkContentType`** reads the slots with `getAgentAttachmentReferences` and reuses them for 60 seconds, sharing them with [`getAttachmentReferences`](#attachment-references-on-the-server), so an edit to the agent's slots takes up to a minute to apply. A slot type is exact, like `application/pdf`, or a wildcard, like `image/*`. A slot with no types accepts every file. A file of unknown type isn't checked and goes on to the API, which decides: browsers send no type for `.md`, some `.csv` files or HEIC on Windows, and such a file arrives as `application/octet-stream`. An agent with no slots takes no typed files, so they all get a 415. If the lookup fails, the upload is refused with the error from the API, usually a 502, and the next upload tries again. Slots' `name_pattern` isn't checked here: the API checks it when the run starts. The slots are kept per `createSeclaiHandlers` instance, so where the handlers are created per request, as on Cloudflare Workers, every upload makes its own lookup.
104
- - **`onUpload`** receives the `File`, the `{ id, status, filename, content_type, file_size }` the handler would return, the `Request`, whose body has already been read, and the app's [context](#access-control), the same value the access-control hooks get. The context is resolved before the file is uploaded, so a `context` that refuses does so before the file reaches Seclai. Returning nothing keeps the default response. If it throws, the browser gets a 500 with a generic message. The file is already on Seclai by then.
104
+ - **`onUpload`** receives the `File`, the `{ id, status, filename, content_type, file_size }` the handler would return, the `Request`, whose body has already been read, and the app's [context](#access-control), the same value the access-control hooks get, and the [upload params](#upload-params). The context is resolved before the file is uploaded, so a `context` that refuses does so before the file reaches Seclai. Returning nothing keeps the default response. If it throws, the browser gets a 500 with a generic message. The file is already on Seclai by then.
105
+
106
+ ### Upload params
107
+
108
+ The browser can send a little app data with an upload, such as the session the file belongs to or its role, with `uploadFile`'s `params` option in `@seclai/react`. They arrive in the upload URL's query string, and `authorizeUpload` and `onUpload` get them parsed, as their last argument:
109
+
110
+ ```ts
111
+ const seclai = createSeclaiHandlers({
112
+ apiKey: process.env.SECLAI_API_KEY!,
113
+ agentId: process.env.SECLAI_AGENT_ID!,
114
+ context: async (req) => ({ user: await getUser(req) }),
115
+
116
+ async authorizeUpload(req, file, { user }, { sessionId, kind }) {
117
+ if (!sessionId || !(await db.sessionBelongsTo(sessionId, user.id))) return false;
118
+ if (kind !== "headshot" && kind !== "style") return deny(400, "Unknown kind of upload.");
119
+ },
120
+
121
+ upload: {
122
+ // Return your own record instead of the default JSON.
123
+ async onUpload(file, result, req, { user }, { sessionId, kind }) {
124
+ const record = await db.saveUpload({ userId: user.id, sessionId, kind, uploadId: result.id });
125
+ return Response.json(record);
126
+ },
127
+ },
128
+ });
129
+ ```
130
+
131
+ - **They come from the browser.** The handler doesn't check them and doesn't use them itself: validate them, and check that the user may use them, in `authorizeUpload`. `onUpload` gets the same values.
132
+ - **Strings only.** `params` is a `Record<string, string | undefined>`: a key the browser didn't send reads as `undefined`, and TypeScript makes you check for it. When a key is repeated, the last value wins. Without a query string it's an empty object, with no prototype. `authorizeUpload` and `onUpload` get the same object.
133
+ - **Visible.** They're in the URL, so they show up in server logs. Keep secrets out of them.
105
134
 
106
135
  ### Access control
107
136
 
package/dist/index.cjs CHANGED
@@ -700,6 +700,11 @@ async function readLimitedForm(req, limit) {
700
700
  throw err;
701
701
  }
702
702
  }
703
+ function uploadParams(req) {
704
+ const params = /* @__PURE__ */ Object.create(null);
705
+ for (const [key, value] of new URL(req.url).searchParams) params[key] = value;
706
+ return params;
707
+ }
703
708
  var ROUTES = {
704
709
  "attachment-references": "attachmentReferences",
705
710
  upload: "upload",
@@ -863,12 +868,13 @@ function createSeclaiHandlers(options) {
863
868
  const fileFields = { name: file.name, type: file.type || void 0, size: file.size };
864
869
  logger?.info("upload received", fileFields);
865
870
  if (maxBytes !== void 0 && file.size > maxBytes) return refused("upload", tooLarge(), fileFields);
871
+ const params = authorizeUpload || onUpload ? uploadParams(req) : {};
866
872
  if (authorizeUpload) {
867
873
  const result2 = await callHook(
868
874
  "authorizeUpload",
869
875
  req,
870
876
  resolve,
871
- (ctx) => authorizeUpload(req, file, ctx)
877
+ (ctx) => authorizeUpload(req, file, ctx, params)
872
878
  );
873
879
  if ("response" in result2) return refused("upload", result2.response, fileFields);
874
880
  const allowed = result2.value;
@@ -926,7 +932,7 @@ function createSeclaiHandlers(options) {
926
932
  }
927
933
  if (onUpload) {
928
934
  try {
929
- const replacement = await onUpload(file, result, req, uploadContext);
935
+ const replacement = await onUpload(file, result, req, uploadContext, params);
930
936
  if (replacement instanceof Response) return replacement;
931
937
  } catch (err) {
932
938
  reportError("onUpload threw, so the request got a 500.", err);
package/dist/index.d.cts CHANGED
@@ -127,8 +127,12 @@ interface SeclaiUploadOptions<Ctx = undefined> {
127
127
  * `context` is the app's context for this request, the same value the
128
128
  * access-control hooks get. It is resolved before the file is uploaded, so a
129
129
  * `context` that refuses does so before the file reaches Seclai.
130
+ *
131
+ * `params` is the upload URL's query string, as sent by `uploadFile`'s
132
+ * `params` option. See {@link AuthorizeUpload} for how it is parsed. It comes
133
+ * from the browser: validate it before you use it.
130
134
  */
131
- onUpload?(file: File, result: UploadResult, req: Request, context: Ctx): void | Response | Promise<void | Response>;
135
+ onUpload?(file: File, result: UploadResult, req: Request, context: Ctx, params: UploadParams): void | Response | Promise<void | Response>;
132
136
  }
133
137
  interface SeclaiHandlersOptions<Ctx = undefined> {
134
138
  /** Seclai API key. Server-side only: never expose it to the browser. */
@@ -206,6 +210,9 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
206
210
  * Called after `upload` has read the form, before the file is sent to Seclai.
207
211
  * Return nothing (or `true`) to upload it, or `false` or a `Response` to
208
212
  * refuse. `false` sends a 403.
213
+ *
214
+ * Its last argument is the upload URL's query parameters (see
215
+ * {@link UploadParams}), for example a `sessionId` to check against your data.
209
216
  */
210
217
  authorizeUpload?: AuthorizeUpload<Ctx>;
211
218
  /**
@@ -220,8 +227,22 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
220
227
  }
221
228
  /** See {@link SeclaiHandlersOptions.authorizeRun}. */
222
229
  type AuthorizeRun<Ctx = undefined> = (req: Request, body: RunRequestBody, ctx: Ctx) => RunRequestBody | boolean | Response | void | Promise<RunRequestBody | boolean | Response | void>;
223
- /** See {@link SeclaiHandlersOptions.authorizeUpload}. */
224
- type AuthorizeUpload<Ctx = undefined> = (req: Request, file: File, ctx: Ctx) => boolean | Response | void | Promise<boolean | Response | void>;
230
+ /**
231
+ * The query parameters of an upload request, for example the `sessionId` or
232
+ * the role of the file the browser sent with `uploadFile`'s `params` option.
233
+ * When a key is repeated, the last value wins. The object has no prototype, so
234
+ * a key the browser didn't send reads as `undefined`.
235
+ *
236
+ * They come from the browser and the handler doesn't check them: validate them
237
+ * (and check that the user may use them) in your hooks. The handler itself
238
+ * doesn't read them.
239
+ */
240
+ type UploadParams = Record<string, string | undefined>;
241
+ /**
242
+ * See {@link SeclaiHandlersOptions.authorizeUpload}. `params` is the upload
243
+ * URL's query string: see {@link UploadParams}.
244
+ */
245
+ type AuthorizeUpload<Ctx = undefined> = (req: Request, file: File, ctx: Ctx, params: UploadParams) => boolean | Response | void | Promise<boolean | Response | void>;
225
246
  /** The ids a `download` request asks for. */
226
247
  interface DownloadIds {
227
248
  runId: string;
@@ -320,4 +341,4 @@ declare function createSeclaiHandlers<Ctx = undefined>(options: SeclaiHandlersOp
320
341
  context?: undefined;
321
342
  }): UnboundSeclaiHandlers<Ctx>;
322
343
 
323
- export { ATTACHMENT_SLOTS_TTL_MS, type AttachmentReferences, type AuthorizeDownload, type AuthorizeRun, type AuthorizeUpload, DEFAULT_API_VERSION, type DownloadIds, MIN_API_VERSION, type RunCallbackContext, type RunEndCallback, type RunEvent, type RunEventCallback, type RunOutcome, type RunOutcomeAttachment, type RunOutcomeStatus, type RunRequestBody, type SeclaiHandler, type SeclaiHandlers, type SeclaiHandlersOptions, type SeclaiLogFields, type SeclaiLogLevel, type SeclaiLogger, type SeclaiLookups, type SeclaiUploadOptions, type UnboundSeclaiHandlers, type UploadResult, type WithContext, consoleLogger, createSeclaiHandlers, deny };
344
+ export { ATTACHMENT_SLOTS_TTL_MS, type AttachmentReferences, type AuthorizeDownload, type AuthorizeRun, type AuthorizeUpload, DEFAULT_API_VERSION, type DownloadIds, MIN_API_VERSION, type RunCallbackContext, type RunEndCallback, type RunEvent, type RunEventCallback, type RunOutcome, type RunOutcomeAttachment, type RunOutcomeStatus, type RunRequestBody, type SeclaiHandler, type SeclaiHandlers, type SeclaiHandlersOptions, type SeclaiLogFields, type SeclaiLogLevel, type SeclaiLogger, type SeclaiLookups, type SeclaiUploadOptions, type UnboundSeclaiHandlers, type UploadParams, type UploadResult, type WithContext, consoleLogger, createSeclaiHandlers, deny };
package/dist/index.d.ts CHANGED
@@ -127,8 +127,12 @@ interface SeclaiUploadOptions<Ctx = undefined> {
127
127
  * `context` is the app's context for this request, the same value the
128
128
  * access-control hooks get. It is resolved before the file is uploaded, so a
129
129
  * `context` that refuses does so before the file reaches Seclai.
130
+ *
131
+ * `params` is the upload URL's query string, as sent by `uploadFile`'s
132
+ * `params` option. See {@link AuthorizeUpload} for how it is parsed. It comes
133
+ * from the browser: validate it before you use it.
130
134
  */
131
- onUpload?(file: File, result: UploadResult, req: Request, context: Ctx): void | Response | Promise<void | Response>;
135
+ onUpload?(file: File, result: UploadResult, req: Request, context: Ctx, params: UploadParams): void | Response | Promise<void | Response>;
132
136
  }
133
137
  interface SeclaiHandlersOptions<Ctx = undefined> {
134
138
  /** Seclai API key. Server-side only: never expose it to the browser. */
@@ -206,6 +210,9 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
206
210
  * Called after `upload` has read the form, before the file is sent to Seclai.
207
211
  * Return nothing (or `true`) to upload it, or `false` or a `Response` to
208
212
  * refuse. `false` sends a 403.
213
+ *
214
+ * Its last argument is the upload URL's query parameters (see
215
+ * {@link UploadParams}), for example a `sessionId` to check against your data.
209
216
  */
210
217
  authorizeUpload?: AuthorizeUpload<Ctx>;
211
218
  /**
@@ -220,8 +227,22 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
220
227
  }
221
228
  /** See {@link SeclaiHandlersOptions.authorizeRun}. */
222
229
  type AuthorizeRun<Ctx = undefined> = (req: Request, body: RunRequestBody, ctx: Ctx) => RunRequestBody | boolean | Response | void | Promise<RunRequestBody | boolean | Response | void>;
223
- /** See {@link SeclaiHandlersOptions.authorizeUpload}. */
224
- type AuthorizeUpload<Ctx = undefined> = (req: Request, file: File, ctx: Ctx) => boolean | Response | void | Promise<boolean | Response | void>;
230
+ /**
231
+ * The query parameters of an upload request, for example the `sessionId` or
232
+ * the role of the file the browser sent with `uploadFile`'s `params` option.
233
+ * When a key is repeated, the last value wins. The object has no prototype, so
234
+ * a key the browser didn't send reads as `undefined`.
235
+ *
236
+ * They come from the browser and the handler doesn't check them: validate them
237
+ * (and check that the user may use them) in your hooks. The handler itself
238
+ * doesn't read them.
239
+ */
240
+ type UploadParams = Record<string, string | undefined>;
241
+ /**
242
+ * See {@link SeclaiHandlersOptions.authorizeUpload}. `params` is the upload
243
+ * URL's query string: see {@link UploadParams}.
244
+ */
245
+ type AuthorizeUpload<Ctx = undefined> = (req: Request, file: File, ctx: Ctx, params: UploadParams) => boolean | Response | void | Promise<boolean | Response | void>;
225
246
  /** The ids a `download` request asks for. */
226
247
  interface DownloadIds {
227
248
  runId: string;
@@ -320,4 +341,4 @@ declare function createSeclaiHandlers<Ctx = undefined>(options: SeclaiHandlersOp
320
341
  context?: undefined;
321
342
  }): UnboundSeclaiHandlers<Ctx>;
322
343
 
323
- export { ATTACHMENT_SLOTS_TTL_MS, type AttachmentReferences, type AuthorizeDownload, type AuthorizeRun, type AuthorizeUpload, DEFAULT_API_VERSION, type DownloadIds, MIN_API_VERSION, type RunCallbackContext, type RunEndCallback, type RunEvent, type RunEventCallback, type RunOutcome, type RunOutcomeAttachment, type RunOutcomeStatus, type RunRequestBody, type SeclaiHandler, type SeclaiHandlers, type SeclaiHandlersOptions, type SeclaiLogFields, type SeclaiLogLevel, type SeclaiLogger, type SeclaiLookups, type SeclaiUploadOptions, type UnboundSeclaiHandlers, type UploadResult, type WithContext, consoleLogger, createSeclaiHandlers, deny };
344
+ export { ATTACHMENT_SLOTS_TTL_MS, type AttachmentReferences, type AuthorizeDownload, type AuthorizeRun, type AuthorizeUpload, DEFAULT_API_VERSION, type DownloadIds, MIN_API_VERSION, type RunCallbackContext, type RunEndCallback, type RunEvent, type RunEventCallback, type RunOutcome, type RunOutcomeAttachment, type RunOutcomeStatus, type RunRequestBody, type SeclaiHandler, type SeclaiHandlers, type SeclaiHandlersOptions, type SeclaiLogFields, type SeclaiLogLevel, type SeclaiLogger, type SeclaiLookups, type SeclaiUploadOptions, type UnboundSeclaiHandlers, type UploadParams, type UploadResult, type WithContext, consoleLogger, createSeclaiHandlers, deny };
package/dist/index.js CHANGED
@@ -676,6 +676,11 @@ async function readLimitedForm(req, limit) {
676
676
  throw err;
677
677
  }
678
678
  }
679
+ function uploadParams(req) {
680
+ const params = /* @__PURE__ */ Object.create(null);
681
+ for (const [key, value] of new URL(req.url).searchParams) params[key] = value;
682
+ return params;
683
+ }
679
684
  var ROUTES = {
680
685
  "attachment-references": "attachmentReferences",
681
686
  upload: "upload",
@@ -839,12 +844,13 @@ function createSeclaiHandlers(options) {
839
844
  const fileFields = { name: file.name, type: file.type || void 0, size: file.size };
840
845
  logger?.info("upload received", fileFields);
841
846
  if (maxBytes !== void 0 && file.size > maxBytes) return refused("upload", tooLarge(), fileFields);
847
+ const params = authorizeUpload || onUpload ? uploadParams(req) : {};
842
848
  if (authorizeUpload) {
843
849
  const result2 = await callHook(
844
850
  "authorizeUpload",
845
851
  req,
846
852
  resolve,
847
- (ctx) => authorizeUpload(req, file, ctx)
853
+ (ctx) => authorizeUpload(req, file, ctx, params)
848
854
  );
849
855
  if ("response" in result2) return refused("upload", result2.response, fileFields);
850
856
  const allowed = result2.value;
@@ -902,7 +908,7 @@ function createSeclaiHandlers(options) {
902
908
  }
903
909
  if (onUpload) {
904
910
  try {
905
- const replacement = await onUpload(file, result, req, uploadContext);
911
+ const replacement = await onUpload(file, result, req, uploadContext, params);
906
912
  if (replacement instanceof Response) return replacement;
907
913
  } catch (err) {
908
914
  reportError("onUpload threw, so the request got a 500.", err);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seclai/handlers",
3
- "version": "0.0.14",
3
+ "version": "0.0.16",
4
4
  "description": "Framework-free server handlers for running Seclai agents from a web app: upload, run with SSE relay, and download proxy.",
5
5
  "license": "MIT",
6
6
  "type": "module",