@seclai/handlers 0.0.13 → 0.0.15
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 +36 -4
- package/dist/index.cjs +65 -29
- package/dist/index.d.cts +36 -8
- package/dist/index.d.ts +36 -8
- package/dist/index.js +65 -29
- package/package.json +1 -1
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
|
|
|
@@ -204,7 +233,7 @@ const seclai = createSeclaiHandlers({
|
|
|
204
233
|
|
|
205
234
|
**`onEvent(event, ctx)`** gets each event as `{ event, data }`, with `data` parsed from JSON, in order. Each call is awaited before its event is relayed. It also sees the `error` event the handler sends when the upstream connection fails. The one event it can miss is a first event the browser never received because it disconnected straight away; that event still counts toward the outcome.
|
|
206
235
|
|
|
207
|
-
**`onRunEnd(outcome, ctx)`** is called exactly once for each run
|
|
236
|
+
**`onRunEnd(outcome, ctx)`** is called exactly once for each run, including one the API refuses before it streams (see below). For a run that streams, it is awaited before the final `done`, `error` or `timeout` event is relayed, so **whatever it stores is in place by the time the browser sees `done`**, and the browser can reload history right away. For `done`, `onEvent` runs first, then `onRunEnd`, then the event is relayed.
|
|
208
237
|
|
|
209
238
|
| `outcome` field | |
|
|
210
239
|
|---|---|
|
|
@@ -221,9 +250,12 @@ const seclai = createSeclaiHandlers({
|
|
|
221
250
|
| Sends `timeout`: the API stopped streaming before the run ended | `failed` | `Stopped waiting for the run. It may still finish on Seclai.` |
|
|
222
251
|
| Ends with none of these | `failed` | `The stream ended without a result.` |
|
|
223
252
|
| Is cancelled by the browser | `cancelled`, unless `keepReadingAfterDisconnect` is on | `null` |
|
|
253
|
+
| Is refused by the API before it streams, for example for no credits or a file the agent doesn't accept, or fails before its first event because the API can't be reached or `runTimeoutMs` runs out | `failed` | The `error` the browser gets in the error response |
|
|
224
254
|
|
|
225
255
|
`cancelled` means the browser left. The run itself keeps going on Seclai. If the upstream connection fails or ends after the browser has left, that is reported as `cancelled` too, but an `error` or `timeout` event from the API is still `failed`. If the browser leaves while a callback is handling `done`, `error` or `timeout`, that event's outcome is reported.
|
|
226
256
|
|
|
257
|
+
When the API refuses a run up front, or the run fails before its first event, `onRunEnd` is awaited before the handler returns the error response, so what it stores is in place by the time the browser sees the error. The outcome has `runId: null`, empty `output` and no `attachments`, and `onEvent` isn't called. After a timeout, the run may still have started and may still finish on Seclai, so the error says so: `Timed out waiting for the Seclai API. The run may still finish on Seclai.` If the browser left while the stream was connecting, the outcome is `cancelled` instead, with `error: null`, unless `keepReadingAfterDisconnect` is on. That includes a browser that left while `authorizeRun` or `context` ran: the run is then cancelled before it's sent to Seclai. If `onRunEnd` throws or rejects here, the error is logged like any other callback error (see below), and the browser still gets the original error response. A refusal from `authorizeRun`, `context` or the body check is your app's own decision, before the run is sent to the API, and doesn't call `onRunEnd`.
|
|
258
|
+
|
|
227
259
|
When `runTimeoutMs` runs out, the stream gets an `error` event, `Timed out waiting for the agent run to finish.`, not `timeout`. The time spent awaiting your callbacks counts against `runTimeoutMs`.
|
|
228
260
|
|
|
229
261
|
If `onEvent` or `onRunEnd` throws or rejects, the handler logs the error, with `logger.error` if you set a [`logger`](#logging) and `console.error` otherwise, closes the upstream, and ends the stream with `event: error` carrying `{ "error": "The server could not process the run." }`, in place of the event it was handling. If `onRunEnd` hadn't been called yet, it is called once with `status: "failed"`, unless the browser had already disconnected, in which case the outcome is `cancelled` (with `keepReadingAfterDisconnect` on, it is `failed` either way). A throw during a cancel is only logged. A callback that never settles holds up the stream, and a cancel waits for a callback still running, so put a timeout on slow writes.
|
package/dist/index.cjs
CHANGED
|
@@ -58,37 +58,45 @@ function upstreamMessage(responseText) {
|
|
|
58
58
|
}
|
|
59
59
|
return void 0;
|
|
60
60
|
}
|
|
61
|
-
function
|
|
61
|
+
function toErrorBody(err) {
|
|
62
62
|
if (err instanceof import_sdk.SeclaiAPIValidationError) {
|
|
63
|
-
return
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
},
|
|
69
|
-
422
|
|
70
|
-
);
|
|
63
|
+
return {
|
|
64
|
+
error: "The Seclai API rejected this request as invalid.",
|
|
65
|
+
status: 422,
|
|
66
|
+
details: err.validationError
|
|
67
|
+
};
|
|
71
68
|
}
|
|
72
69
|
if (err instanceof import_sdk.SeclaiAPIStatusError) {
|
|
73
70
|
const { statusCode } = err;
|
|
74
71
|
if (statusCode === 401 || statusCode === 403) {
|
|
75
|
-
return
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
72
|
+
return {
|
|
73
|
+
error: "The Seclai API rejected the server's credentials. Check SECLAI_API_KEY.",
|
|
74
|
+
status: 502
|
|
75
|
+
};
|
|
79
76
|
}
|
|
80
77
|
if (statusCode >= 400 && statusCode < 500) {
|
|
81
|
-
return
|
|
82
|
-
statusCode
|
|
83
|
-
|
|
84
|
-
|
|
78
|
+
return {
|
|
79
|
+
error: upstreamMessage(err.responseText) ?? `The Seclai API returned status ${statusCode}.`,
|
|
80
|
+
status: statusCode
|
|
81
|
+
};
|
|
85
82
|
}
|
|
86
|
-
return
|
|
83
|
+
return { error: `The Seclai API returned status ${statusCode}.`, status: 502 };
|
|
84
|
+
}
|
|
85
|
+
if (err instanceof import_sdk.SeclaiStreamingError) {
|
|
86
|
+
return { error: "Timed out waiting for the Seclai API.", status: 504 };
|
|
87
87
|
}
|
|
88
|
+
return { error: "Could not reach the Seclai API.", status: 502 };
|
|
89
|
+
}
|
|
90
|
+
function runErrorBody(err) {
|
|
91
|
+
const body = toErrorBody(err);
|
|
88
92
|
if (err instanceof import_sdk.SeclaiStreamingError) {
|
|
89
|
-
|
|
93
|
+
body.error = "Timed out waiting for the Seclai API. The run may still finish on Seclai.";
|
|
90
94
|
}
|
|
91
|
-
return
|
|
95
|
+
return body;
|
|
96
|
+
}
|
|
97
|
+
function toErrorResponse(err) {
|
|
98
|
+
const body = toErrorBody(err);
|
|
99
|
+
return json(body, body.status);
|
|
92
100
|
}
|
|
93
101
|
function streamErrorMessage(err) {
|
|
94
102
|
if (err instanceof import_sdk.SeclaiStreamingError) {
|
|
@@ -379,6 +387,20 @@ function toAttachments(raw) {
|
|
|
379
387
|
] : []
|
|
380
388
|
);
|
|
381
389
|
}
|
|
390
|
+
function reportCallbackError(log, err) {
|
|
391
|
+
if (log) log.callbackError(err);
|
|
392
|
+
else console.error("@seclai/handlers: an onEvent or onRunEnd callback threw.", err);
|
|
393
|
+
}
|
|
394
|
+
async function reportRefusedRun(callbacks, ctx, how) {
|
|
395
|
+
const { onRunEnd, log } = callbacks;
|
|
396
|
+
if (!onRunEnd) return;
|
|
397
|
+
const outcome = "error" in how ? { runId: null, status: "failed", output: "", attachments: [], error: how.error } : { runId: null, status: "cancelled", output: "", attachments: [], error: null };
|
|
398
|
+
try {
|
|
399
|
+
await onRunEnd(outcome, ctx);
|
|
400
|
+
} catch (err) {
|
|
401
|
+
reportCallbackError(log, err);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
382
404
|
function createRunObserver(callbacks, ctx, { keepReading = false } = {}) {
|
|
383
405
|
const { onEvent, onRunEnd, log } = callbacks;
|
|
384
406
|
const browserStoppedUpstream = () => !keepReading && !!ctx.request.signal?.aborted;
|
|
@@ -470,8 +492,7 @@ function createRunObserver(callbacks, ctx, { keepReading = false } = {}) {
|
|
|
470
492
|
}
|
|
471
493
|
},
|
|
472
494
|
onError(err) {
|
|
473
|
-
|
|
474
|
-
else console.error("@seclai/handlers: an onEvent or onRunEnd callback threw.", err);
|
|
495
|
+
reportCallbackError(log, err);
|
|
475
496
|
},
|
|
476
497
|
onKeepalive: log && (() => log.keepalive()),
|
|
477
498
|
onDisconnect: log && (() => log.readingOn()),
|
|
@@ -679,6 +700,11 @@ async function readLimitedForm(req, limit) {
|
|
|
679
700
|
throw err;
|
|
680
701
|
}
|
|
681
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
|
+
}
|
|
682
708
|
var ROUTES = {
|
|
683
709
|
"attachment-references": "attachmentReferences",
|
|
684
710
|
upload: "upload",
|
|
@@ -842,12 +868,13 @@ function createSeclaiHandlers(options) {
|
|
|
842
868
|
const fileFields = { name: file.name, type: file.type || void 0, size: file.size };
|
|
843
869
|
logger?.info("upload received", fileFields);
|
|
844
870
|
if (maxBytes !== void 0 && file.size > maxBytes) return refused("upload", tooLarge(), fileFields);
|
|
871
|
+
const params = authorizeUpload || onUpload ? uploadParams(req) : {};
|
|
845
872
|
if (authorizeUpload) {
|
|
846
873
|
const result2 = await callHook(
|
|
847
874
|
"authorizeUpload",
|
|
848
875
|
req,
|
|
849
876
|
resolve,
|
|
850
|
-
(ctx) => authorizeUpload(req, file, ctx)
|
|
877
|
+
(ctx) => authorizeUpload(req, file, ctx, params)
|
|
851
878
|
);
|
|
852
879
|
if ("response" in result2) return refused("upload", result2.response, fileFields);
|
|
853
880
|
const allowed = result2.value;
|
|
@@ -905,7 +932,7 @@ function createSeclaiHandlers(options) {
|
|
|
905
932
|
}
|
|
906
933
|
if (onUpload) {
|
|
907
934
|
try {
|
|
908
|
-
const replacement = await onUpload(file, result, req, uploadContext);
|
|
935
|
+
const replacement = await onUpload(file, result, req, uploadContext, params);
|
|
909
936
|
if (replacement instanceof Response) return replacement;
|
|
910
937
|
} catch (err) {
|
|
911
938
|
reportError("onUpload threw, so the request got a 500.", err);
|
|
@@ -955,7 +982,10 @@ function createSeclaiHandlers(options) {
|
|
|
955
982
|
const upstream = new AbortController();
|
|
956
983
|
const abort = () => upstream.abort();
|
|
957
984
|
const keepReading = keepReadingAfterDisconnect && !!(onEvent || onRunEnd);
|
|
958
|
-
if (!keepReading)
|
|
985
|
+
if (!keepReading) {
|
|
986
|
+
if (req.signal?.aborted) abort();
|
|
987
|
+
else req.signal?.addEventListener("abort", abort, { once: true });
|
|
988
|
+
}
|
|
959
989
|
const log = logger && startRunLog(logger, {
|
|
960
990
|
sessionId: body.sessionId,
|
|
961
991
|
uploads: body.uploadIds?.length ?? 0,
|
|
@@ -992,10 +1022,16 @@ function createSeclaiHandlers(options) {
|
|
|
992
1022
|
{ headers: SSE_HEADERS }
|
|
993
1023
|
);
|
|
994
1024
|
} catch (err) {
|
|
995
|
-
const
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
1025
|
+
const error = runErrorBody(err);
|
|
1026
|
+
const browserLeft = upstream.signal.aborted;
|
|
1027
|
+
await reportRefusedRun(
|
|
1028
|
+
{ onRunEnd, log },
|
|
1029
|
+
{ body, request: req, context: runContext },
|
|
1030
|
+
browserLeft ? { cancelled: true } : { error: error.error }
|
|
1031
|
+
);
|
|
1032
|
+
if (browserLeft) log?.disconnected();
|
|
1033
|
+
else log?.rejected(err, error.status);
|
|
1034
|
+
return json(error, error.status);
|
|
999
1035
|
}
|
|
1000
1036
|
},
|
|
1001
1037
|
async download(req) {
|
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. */
|
|
@@ -148,10 +152,17 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
|
|
|
148
152
|
*/
|
|
149
153
|
onEvent?: RunEventCallback<Ctx>;
|
|
150
154
|
/**
|
|
151
|
-
* Called exactly once for each run
|
|
152
|
-
*
|
|
153
|
-
*
|
|
154
|
-
*
|
|
155
|
+
* Called exactly once for each run, with how it ended. Awaited before the
|
|
156
|
+
* final `done`, `error` or `timeout` event is relayed, so whatever it stores
|
|
157
|
+
* is in place when the browser sees the run end. If it throws, the browser
|
|
158
|
+
* gets an `error` event instead.
|
|
159
|
+
*
|
|
160
|
+
* Also called, with `status: "failed"`, when the API refuses the run before
|
|
161
|
+
* it streams, or it fails before its first event (the API can't be reached,
|
|
162
|
+
* or `runTimeoutMs` runs out), and awaited before the error response is
|
|
163
|
+
* returned. The status is `cancelled` instead if the browser left while the
|
|
164
|
+
* stream was connecting. A throw there is only logged. Not called when
|
|
165
|
+
* `authorizeRun`, `context` or the body check refuses the run.
|
|
155
166
|
*/
|
|
156
167
|
onRunEnd?: RunEndCallback<Ctx>;
|
|
157
168
|
/**
|
|
@@ -199,6 +210,9 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
|
|
|
199
210
|
* Called after `upload` has read the form, before the file is sent to Seclai.
|
|
200
211
|
* Return nothing (or `true`) to upload it, or `false` or a `Response` to
|
|
201
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.
|
|
202
216
|
*/
|
|
203
217
|
authorizeUpload?: AuthorizeUpload<Ctx>;
|
|
204
218
|
/**
|
|
@@ -213,8 +227,22 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
|
|
|
213
227
|
}
|
|
214
228
|
/** See {@link SeclaiHandlersOptions.authorizeRun}. */
|
|
215
229
|
type AuthorizeRun<Ctx = undefined> = (req: Request, body: RunRequestBody, ctx: Ctx) => RunRequestBody | boolean | Response | void | Promise<RunRequestBody | boolean | Response | void>;
|
|
216
|
-
/**
|
|
217
|
-
|
|
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>;
|
|
218
246
|
/** The ids a `download` request asks for. */
|
|
219
247
|
interface DownloadIds {
|
|
220
248
|
runId: string;
|
|
@@ -313,4 +341,4 @@ declare function createSeclaiHandlers<Ctx = undefined>(options: SeclaiHandlersOp
|
|
|
313
341
|
context?: undefined;
|
|
314
342
|
}): UnboundSeclaiHandlers<Ctx>;
|
|
315
343
|
|
|
316
|
-
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. */
|
|
@@ -148,10 +152,17 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
|
|
|
148
152
|
*/
|
|
149
153
|
onEvent?: RunEventCallback<Ctx>;
|
|
150
154
|
/**
|
|
151
|
-
* Called exactly once for each run
|
|
152
|
-
*
|
|
153
|
-
*
|
|
154
|
-
*
|
|
155
|
+
* Called exactly once for each run, with how it ended. Awaited before the
|
|
156
|
+
* final `done`, `error` or `timeout` event is relayed, so whatever it stores
|
|
157
|
+
* is in place when the browser sees the run end. If it throws, the browser
|
|
158
|
+
* gets an `error` event instead.
|
|
159
|
+
*
|
|
160
|
+
* Also called, with `status: "failed"`, when the API refuses the run before
|
|
161
|
+
* it streams, or it fails before its first event (the API can't be reached,
|
|
162
|
+
* or `runTimeoutMs` runs out), and awaited before the error response is
|
|
163
|
+
* returned. The status is `cancelled` instead if the browser left while the
|
|
164
|
+
* stream was connecting. A throw there is only logged. Not called when
|
|
165
|
+
* `authorizeRun`, `context` or the body check refuses the run.
|
|
155
166
|
*/
|
|
156
167
|
onRunEnd?: RunEndCallback<Ctx>;
|
|
157
168
|
/**
|
|
@@ -199,6 +210,9 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
|
|
|
199
210
|
* Called after `upload` has read the form, before the file is sent to Seclai.
|
|
200
211
|
* Return nothing (or `true`) to upload it, or `false` or a `Response` to
|
|
201
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.
|
|
202
216
|
*/
|
|
203
217
|
authorizeUpload?: AuthorizeUpload<Ctx>;
|
|
204
218
|
/**
|
|
@@ -213,8 +227,22 @@ interface SeclaiHandlersOptions<Ctx = undefined> {
|
|
|
213
227
|
}
|
|
214
228
|
/** See {@link SeclaiHandlersOptions.authorizeRun}. */
|
|
215
229
|
type AuthorizeRun<Ctx = undefined> = (req: Request, body: RunRequestBody, ctx: Ctx) => RunRequestBody | boolean | Response | void | Promise<RunRequestBody | boolean | Response | void>;
|
|
216
|
-
/**
|
|
217
|
-
|
|
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>;
|
|
218
246
|
/** The ids a `download` request asks for. */
|
|
219
247
|
interface DownloadIds {
|
|
220
248
|
runId: string;
|
|
@@ -313,4 +341,4 @@ declare function createSeclaiHandlers<Ctx = undefined>(options: SeclaiHandlersOp
|
|
|
313
341
|
context?: undefined;
|
|
314
342
|
}): UnboundSeclaiHandlers<Ctx>;
|
|
315
343
|
|
|
316
|
-
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
|
@@ -34,37 +34,45 @@ function upstreamMessage(responseText) {
|
|
|
34
34
|
}
|
|
35
35
|
return void 0;
|
|
36
36
|
}
|
|
37
|
-
function
|
|
37
|
+
function toErrorBody(err) {
|
|
38
38
|
if (err instanceof SeclaiAPIValidationError) {
|
|
39
|
-
return
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
},
|
|
45
|
-
422
|
|
46
|
-
);
|
|
39
|
+
return {
|
|
40
|
+
error: "The Seclai API rejected this request as invalid.",
|
|
41
|
+
status: 422,
|
|
42
|
+
details: err.validationError
|
|
43
|
+
};
|
|
47
44
|
}
|
|
48
45
|
if (err instanceof SeclaiAPIStatusError) {
|
|
49
46
|
const { statusCode } = err;
|
|
50
47
|
if (statusCode === 401 || statusCode === 403) {
|
|
51
|
-
return
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
48
|
+
return {
|
|
49
|
+
error: "The Seclai API rejected the server's credentials. Check SECLAI_API_KEY.",
|
|
50
|
+
status: 502
|
|
51
|
+
};
|
|
55
52
|
}
|
|
56
53
|
if (statusCode >= 400 && statusCode < 500) {
|
|
57
|
-
return
|
|
58
|
-
statusCode
|
|
59
|
-
|
|
60
|
-
|
|
54
|
+
return {
|
|
55
|
+
error: upstreamMessage(err.responseText) ?? `The Seclai API returned status ${statusCode}.`,
|
|
56
|
+
status: statusCode
|
|
57
|
+
};
|
|
61
58
|
}
|
|
62
|
-
return
|
|
59
|
+
return { error: `The Seclai API returned status ${statusCode}.`, status: 502 };
|
|
60
|
+
}
|
|
61
|
+
if (err instanceof SeclaiStreamingError) {
|
|
62
|
+
return { error: "Timed out waiting for the Seclai API.", status: 504 };
|
|
63
63
|
}
|
|
64
|
+
return { error: "Could not reach the Seclai API.", status: 502 };
|
|
65
|
+
}
|
|
66
|
+
function runErrorBody(err) {
|
|
67
|
+
const body = toErrorBody(err);
|
|
64
68
|
if (err instanceof SeclaiStreamingError) {
|
|
65
|
-
|
|
69
|
+
body.error = "Timed out waiting for the Seclai API. The run may still finish on Seclai.";
|
|
66
70
|
}
|
|
67
|
-
return
|
|
71
|
+
return body;
|
|
72
|
+
}
|
|
73
|
+
function toErrorResponse(err) {
|
|
74
|
+
const body = toErrorBody(err);
|
|
75
|
+
return json(body, body.status);
|
|
68
76
|
}
|
|
69
77
|
function streamErrorMessage(err) {
|
|
70
78
|
if (err instanceof SeclaiStreamingError) {
|
|
@@ -355,6 +363,20 @@ function toAttachments(raw) {
|
|
|
355
363
|
] : []
|
|
356
364
|
);
|
|
357
365
|
}
|
|
366
|
+
function reportCallbackError(log, err) {
|
|
367
|
+
if (log) log.callbackError(err);
|
|
368
|
+
else console.error("@seclai/handlers: an onEvent or onRunEnd callback threw.", err);
|
|
369
|
+
}
|
|
370
|
+
async function reportRefusedRun(callbacks, ctx, how) {
|
|
371
|
+
const { onRunEnd, log } = callbacks;
|
|
372
|
+
if (!onRunEnd) return;
|
|
373
|
+
const outcome = "error" in how ? { runId: null, status: "failed", output: "", attachments: [], error: how.error } : { runId: null, status: "cancelled", output: "", attachments: [], error: null };
|
|
374
|
+
try {
|
|
375
|
+
await onRunEnd(outcome, ctx);
|
|
376
|
+
} catch (err) {
|
|
377
|
+
reportCallbackError(log, err);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
358
380
|
function createRunObserver(callbacks, ctx, { keepReading = false } = {}) {
|
|
359
381
|
const { onEvent, onRunEnd, log } = callbacks;
|
|
360
382
|
const browserStoppedUpstream = () => !keepReading && !!ctx.request.signal?.aborted;
|
|
@@ -446,8 +468,7 @@ function createRunObserver(callbacks, ctx, { keepReading = false } = {}) {
|
|
|
446
468
|
}
|
|
447
469
|
},
|
|
448
470
|
onError(err) {
|
|
449
|
-
|
|
450
|
-
else console.error("@seclai/handlers: an onEvent or onRunEnd callback threw.", err);
|
|
471
|
+
reportCallbackError(log, err);
|
|
451
472
|
},
|
|
452
473
|
onKeepalive: log && (() => log.keepalive()),
|
|
453
474
|
onDisconnect: log && (() => log.readingOn()),
|
|
@@ -655,6 +676,11 @@ async function readLimitedForm(req, limit) {
|
|
|
655
676
|
throw err;
|
|
656
677
|
}
|
|
657
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
|
+
}
|
|
658
684
|
var ROUTES = {
|
|
659
685
|
"attachment-references": "attachmentReferences",
|
|
660
686
|
upload: "upload",
|
|
@@ -818,12 +844,13 @@ function createSeclaiHandlers(options) {
|
|
|
818
844
|
const fileFields = { name: file.name, type: file.type || void 0, size: file.size };
|
|
819
845
|
logger?.info("upload received", fileFields);
|
|
820
846
|
if (maxBytes !== void 0 && file.size > maxBytes) return refused("upload", tooLarge(), fileFields);
|
|
847
|
+
const params = authorizeUpload || onUpload ? uploadParams(req) : {};
|
|
821
848
|
if (authorizeUpload) {
|
|
822
849
|
const result2 = await callHook(
|
|
823
850
|
"authorizeUpload",
|
|
824
851
|
req,
|
|
825
852
|
resolve,
|
|
826
|
-
(ctx) => authorizeUpload(req, file, ctx)
|
|
853
|
+
(ctx) => authorizeUpload(req, file, ctx, params)
|
|
827
854
|
);
|
|
828
855
|
if ("response" in result2) return refused("upload", result2.response, fileFields);
|
|
829
856
|
const allowed = result2.value;
|
|
@@ -881,7 +908,7 @@ function createSeclaiHandlers(options) {
|
|
|
881
908
|
}
|
|
882
909
|
if (onUpload) {
|
|
883
910
|
try {
|
|
884
|
-
const replacement = await onUpload(file, result, req, uploadContext);
|
|
911
|
+
const replacement = await onUpload(file, result, req, uploadContext, params);
|
|
885
912
|
if (replacement instanceof Response) return replacement;
|
|
886
913
|
} catch (err) {
|
|
887
914
|
reportError("onUpload threw, so the request got a 500.", err);
|
|
@@ -931,7 +958,10 @@ function createSeclaiHandlers(options) {
|
|
|
931
958
|
const upstream = new AbortController();
|
|
932
959
|
const abort = () => upstream.abort();
|
|
933
960
|
const keepReading = keepReadingAfterDisconnect && !!(onEvent || onRunEnd);
|
|
934
|
-
if (!keepReading)
|
|
961
|
+
if (!keepReading) {
|
|
962
|
+
if (req.signal?.aborted) abort();
|
|
963
|
+
else req.signal?.addEventListener("abort", abort, { once: true });
|
|
964
|
+
}
|
|
935
965
|
const log = logger && startRunLog(logger, {
|
|
936
966
|
sessionId: body.sessionId,
|
|
937
967
|
uploads: body.uploadIds?.length ?? 0,
|
|
@@ -968,10 +998,16 @@ function createSeclaiHandlers(options) {
|
|
|
968
998
|
{ headers: SSE_HEADERS }
|
|
969
999
|
);
|
|
970
1000
|
} catch (err) {
|
|
971
|
-
const
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
1001
|
+
const error = runErrorBody(err);
|
|
1002
|
+
const browserLeft = upstream.signal.aborted;
|
|
1003
|
+
await reportRefusedRun(
|
|
1004
|
+
{ onRunEnd, log },
|
|
1005
|
+
{ body, request: req, context: runContext },
|
|
1006
|
+
browserLeft ? { cancelled: true } : { error: error.error }
|
|
1007
|
+
);
|
|
1008
|
+
if (browserLeft) log?.disconnected();
|
|
1009
|
+
else log?.rejected(err, error.status);
|
|
1010
|
+
return json(error, error.status);
|
|
975
1011
|
}
|
|
976
1012
|
},
|
|
977
1013
|
async download(req) {
|
package/package.json
CHANGED