@guren/server 2.14.0 → 2.15.0
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/dist/{Hash-CzrwKeDp.js → Hash-C8aejmi8.js} +5 -0
- package/dist/agent/AgentApprovalRequested.d.ts +59 -0
- package/dist/agent/approval.d.ts +295 -0
- package/dist/agent/audit-emitter.d.ts +64 -0
- package/dist/agent/audit.d.ts +103 -0
- package/dist/agent/dispatch.d.ts +50 -8
- package/dist/agent/meta-tools.d.ts +62 -0
- package/dist/agent/public.d.ts +33 -0
- package/dist/agent/public.js +2 -0
- package/dist/auth/index.js +1 -1
- package/dist/auth/password/DefaultHasher.d.ts +18 -5
- package/dist/auth/password/PasswordHasher.d.ts +15 -0
- package/dist/auth/password/hash-format.d.ts +19 -0
- package/dist/{auth-BSUc14CD.js → auth-DkYoAPVn.js} +121 -32
- package/dist/broadcasting/index.js +1 -1
- package/dist/{broadcasting-BxU-LIfF.js → broadcasting-BwodCA4q.js} +1 -1
- package/dist/container/bindings.d.ts +19 -0
- package/dist/dispatch-erOS9epZ.js +285 -0
- package/dist/encryption/index.js +2 -2
- package/dist/{encryption-DJtkkhiw.js → encryption-D99Vmls3.js} +4 -1
- package/dist/http/dev-assets.d.ts +16 -0
- package/dist/http/public-assets.d.ts +10 -0
- package/dist/http/request.d.ts +88 -1
- package/dist/http/static-documents.d.ts +31 -0
- package/dist/index.d.ts +11 -3
- package/dist/index.js +586 -333
- package/dist/internal/request.d.ts +15 -9
- package/dist/internal/request.js +2 -2
- package/dist/logging/channels/DailyFileChannel.d.ts +0 -2
- package/dist/logging/daily-file-path.d.ts +24 -0
- package/dist/logging/index.d.ts +1 -0
- package/dist/logging/index.js +2 -2
- package/dist/{logging-CPaRMuPP.js → logging-B-kngi3q.js} +61 -18
- package/dist/mvc/Controller.d.ts +0 -26
- package/dist/{request-CRVuIiQr.js → request-CVQwpu2J.js} +56 -5
- package/dist/runtime/index.js +90 -14
- package/dist/{vite-manifest-BGfWbPYp.js → vite-manifest-w_RSOvQW.js} +1 -1
- package/package.json +6 -2
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
import { PATH_PARAM_PATTERN } from "./internal/route-path.js";
|
|
2
|
+
//#region src/internal/agent-preflight.ts
|
|
3
|
+
/**
|
|
4
|
+
* The wire protocol of an agent preflight (RFC 0016 §5.4), in a leaf module
|
|
5
|
+
* so the two halves can share it without depending on each other.
|
|
6
|
+
*
|
|
7
|
+
* `Router` mounts the seam that answers a preflight; `agent/dispatch` builds
|
|
8
|
+
* the request that asks for one and reads the answer back. Putting the names
|
|
9
|
+
* in either of those would make one import the other — today only
|
|
10
|
+
* `dispatch → Router` exists, and the day `Router` needs anything from
|
|
11
|
+
* `agent/` that becomes a cycle.
|
|
12
|
+
*
|
|
13
|
+
* Not exported from the package index: an external dispatcher asks for a
|
|
14
|
+
* preflight through `BuildToolRequestOptions.preflight`, and the header
|
|
15
|
+
* spelling is this seam's business, not published API.
|
|
16
|
+
*/
|
|
17
|
+
/** Request header asking the route for a verdict instead of an execution. */
|
|
18
|
+
const AGENT_PREFLIGHT_HEADER = "X-Guren-Agent-Preflight";
|
|
19
|
+
/**
|
|
20
|
+
* Response header marking a body as a preflight verdict rather than the
|
|
21
|
+
* route's own output.
|
|
22
|
+
*
|
|
23
|
+
* Load-bearing in two places that would otherwise mistake one for the other:
|
|
24
|
+
* a route's `output` schema validation (which would reject the verdict and
|
|
25
|
+
* turn it into a 500) and the MCP response mapping (which would advertise the
|
|
26
|
+
* verdict as the tool's `structuredContent`, so an SDK client validates it
|
|
27
|
+
* against the tool's output schema and throws). Both are answering the same
|
|
28
|
+
* question — "is this the route's result?" — so both read the same marker.
|
|
29
|
+
*/
|
|
30
|
+
const AGENT_PREFLIGHT_VERDICT_HEADER = "X-Guren-Agent-Preflight-Verdict";
|
|
31
|
+
//#endregion
|
|
32
|
+
//#region src/agent/dispatch.ts
|
|
33
|
+
/** How many characters of a non-JSON response body survive into the result. */
|
|
34
|
+
const TEXT_RESPONSE_CAP = 5e4;
|
|
35
|
+
/**
|
|
36
|
+
* The argument-level spelling of a preflight request (RFC 0016 §5.4), for a
|
|
37
|
+
* surface whose callers pass flat arguments rather than dispatch options.
|
|
38
|
+
*
|
|
39
|
+
* No adapter strips it today, because none accepts it. Every surface that
|
|
40
|
+
* reaches the seam asks through `BuildToolRequestOptions.preflight` instead:
|
|
41
|
+
* `guren tool:call` and `@guren/testing` from their own flags, and MCP from
|
|
42
|
+
* the `guren.preflight` companion tool, which takes the target tool's name
|
|
43
|
+
* and arguments rather than smuggling a directive through them (RFC 0016
|
|
44
|
+
* §5.4 — a verdict conforms to no route's output schema, so it needs a tool
|
|
45
|
+
* of its own). A surface that adopts this key owns the stripping — it is an
|
|
46
|
+
* instruction to the adapter, not a field of any route's contract, and
|
|
47
|
+
* forwarding it would fail the very validation the caller asked to rehearse.
|
|
48
|
+
*/
|
|
49
|
+
const PREFLIGHT_ARGUMENT = "_preflight";
|
|
50
|
+
/**
|
|
51
|
+
* The agent-facing diagnosis of a {@link ToolRequestBuildFailure}.
|
|
52
|
+
*
|
|
53
|
+
* One function rather than a string per adapter: the same tool is reachable
|
|
54
|
+
* from several surfaces (App MCP, WebMCP, `guren tool:call`), and an agent
|
|
55
|
+
* that reads a different diagnosis depending on which one it reached would
|
|
56
|
+
* be debugging the client instead of its own call.
|
|
57
|
+
*/
|
|
58
|
+
function describeBuildFailure(failure) {
|
|
59
|
+
if ("missing" in failure) return `Missing required path parameter(s): ${failure.missing.join(", ")}.`;
|
|
60
|
+
return `Path parameter(s) ${failure.invalidPath.join(", ")} may not be "." or ".." — a dot-segment would resolve to a different route than the one authorized.`;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Rebuild the HTTP request a tool call describes.
|
|
64
|
+
*
|
|
65
|
+
* The flat argument object is taken apart along `tool.inputSources` — the
|
|
66
|
+
* derivation's own record of which contract each property came from — so a
|
|
67
|
+
* POST route's `query` keys land in the query string where `validateQuery`
|
|
68
|
+
* reads them, not in the body. Keys the derivation never advertised are
|
|
69
|
+
* forwarded anyway (body for body-carrying methods, query otherwise): the
|
|
70
|
+
* route's validator is the one place that rejects them, and dropping them
|
|
71
|
+
* here would make this a second, quieter validator.
|
|
72
|
+
*
|
|
73
|
+
* GET and HEAD force everything into the query string whatever its source —
|
|
74
|
+
* `Request` refuses a body on those methods, and a `body` schema on a GET
|
|
75
|
+
* route is a contract defect this adapter cannot repair.
|
|
76
|
+
*/
|
|
77
|
+
function buildToolRequest(tool, args, options = {}) {
|
|
78
|
+
const origin = options.origin ?? "http://localhost";
|
|
79
|
+
const missing = [];
|
|
80
|
+
const invalidPath = [];
|
|
81
|
+
const pathOnly = /* @__PURE__ */ new Set();
|
|
82
|
+
const path = tool.path.replace(PATH_PARAM_PATTERN, (_match, lead, name) => {
|
|
83
|
+
const value = args[name];
|
|
84
|
+
if (value === void 0) {
|
|
85
|
+
missing.push(name);
|
|
86
|
+
return `${lead}:${name}`;
|
|
87
|
+
}
|
|
88
|
+
const stringified = String(value);
|
|
89
|
+
if (stringified === "." || stringified === "..") {
|
|
90
|
+
invalidPath.push(name);
|
|
91
|
+
return `${lead}:${name}`;
|
|
92
|
+
}
|
|
93
|
+
const source = sourceOf(tool, name);
|
|
94
|
+
if (source === void 0 || source === "params" || source === "path") pathOnly.add(name);
|
|
95
|
+
return `${lead}${encodeURIComponent(stringified)}`;
|
|
96
|
+
});
|
|
97
|
+
if (missing.length > 0) return { missing };
|
|
98
|
+
if (invalidPath.length > 0) return { invalidPath };
|
|
99
|
+
const method = tool.method;
|
|
100
|
+
const bodyless = method === "GET" || method === "HEAD";
|
|
101
|
+
const query = new URLSearchParams();
|
|
102
|
+
const bodyEntries = [];
|
|
103
|
+
for (const [key, value] of Object.entries(args)) {
|
|
104
|
+
if (pathOnly.has(key) || value === void 0) continue;
|
|
105
|
+
const source = sourceOf(tool, key);
|
|
106
|
+
if (bodyless || source === "query" || source === "params" || source === "path" || tool.inputBodyNested && key !== "body") appendQueryValue(query, key, value);
|
|
107
|
+
else bodyEntries.push([key, value]);
|
|
108
|
+
}
|
|
109
|
+
const headers = new Headers({
|
|
110
|
+
Accept: "application/json",
|
|
111
|
+
"X-Guren-Agent-Surface": options.surface ?? "mcp"
|
|
112
|
+
});
|
|
113
|
+
if (options.authorization) headers.set("Authorization", options.authorization);
|
|
114
|
+
if (options.preflight) headers.set(AGENT_PREFLIGHT_HEADER, "1");
|
|
115
|
+
let body;
|
|
116
|
+
if (!bodyless) {
|
|
117
|
+
if (tool.inputBodyNested) {
|
|
118
|
+
if (Object.hasOwn(args, "body")) body = JSON.stringify(args.body);
|
|
119
|
+
} else if (bodyEntries.length > 0) body = JSON.stringify(accumulate(bodyEntries));
|
|
120
|
+
}
|
|
121
|
+
if (body !== void 0) headers.set("Content-Type", "application/json");
|
|
122
|
+
const qs = query.toString();
|
|
123
|
+
const url = `${origin}${path}${qs ? `?${qs}` : ""}`;
|
|
124
|
+
return { request: new Request(url, {
|
|
125
|
+
method,
|
|
126
|
+
headers,
|
|
127
|
+
body
|
|
128
|
+
}) };
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* The contract a property was declared under, or undefined if the derivation
|
|
132
|
+
* never advertised it. `Object.hasOwn` rather than a plain read: a JSON
|
|
133
|
+
* argument may legally be named `__proto__`, and `inputSources['__proto__']`
|
|
134
|
+
* would otherwise resolve to `Object.prototype`, not undefined.
|
|
135
|
+
*/
|
|
136
|
+
function sourceOf(tool, name) {
|
|
137
|
+
return Object.hasOwn(tool.inputSources, name) ? tool.inputSources[name] : void 0;
|
|
138
|
+
}
|
|
139
|
+
/** Primitives stringify; anything structured rides as JSON text. */
|
|
140
|
+
function appendQueryValue(query, key, value) {
|
|
141
|
+
if (Array.isArray(value)) {
|
|
142
|
+
for (const element of value) query.append(key, serializeQueryScalar(element));
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
query.append(key, serializeQueryScalar(value));
|
|
146
|
+
}
|
|
147
|
+
function serializeQueryScalar(value) {
|
|
148
|
+
if (value === null || typeof value !== "object") return String(value);
|
|
149
|
+
return JSON.stringify(value);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Null-prototype accumulator, spread back to plain: a JSON argument may
|
|
153
|
+
* legally be named `__proto__`, and assigning that key on `{}` invokes the
|
|
154
|
+
* prototype setter instead of defining the property — the same rule the
|
|
155
|
+
* derivation and the redaction walk apply.
|
|
156
|
+
*/
|
|
157
|
+
function accumulate(entries) {
|
|
158
|
+
const record = Object.create(null);
|
|
159
|
+
for (const [key, value] of entries) record[key] = value;
|
|
160
|
+
return { ...record };
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Whether the tool advertises an object output schema — the only kind MCP
|
|
164
|
+
* lists, and therefore the only kind that obliges a success result to carry
|
|
165
|
+
* `structuredContent`. A route whose `output` is an array or primitive is not
|
|
166
|
+
* advertised as structured (MCP `outputSchema` must be an object), so its
|
|
167
|
+
* results ride as text. `describeTool` and `mapToolResponse` must agree on
|
|
168
|
+
* this exact predicate, or one advertises a schema the other cannot satisfy.
|
|
169
|
+
*/
|
|
170
|
+
function advertisesStructuredOutput(tool) {
|
|
171
|
+
return tool.outputSchema?.type === "object";
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Map the application's response onto an MCP tool result (RFC 0016 §3.4).
|
|
175
|
+
*
|
|
176
|
+
* - 2xx JSON object → serialized text, plus `structuredContent` when the tool
|
|
177
|
+
* advertises an object `outputSchema` (the one shape the route validated).
|
|
178
|
+
* - 2xx Inertia page JSON → unwrapped to `page.props`, only for a tool with
|
|
179
|
+
* no `outputSchema` — unwrap and schema are mutually exclusive by
|
|
180
|
+
* derivation, so the advertised shape can never disagree with the result.
|
|
181
|
+
* - 204 / 3xx → a status line naming the Location; not an error.
|
|
182
|
+
* - 4xx / 5xx → `isError: true` carrying the exception handler's JSON body:
|
|
183
|
+
* a 422's `{ message, errors }` is an application-level failure the agent
|
|
184
|
+
* should read, not a protocol error.
|
|
185
|
+
* - non-JSON → capped text.
|
|
186
|
+
*
|
|
187
|
+
* One MCP invariant overrides the table: a *non-error* result for a tool that
|
|
188
|
+
* advertises an object `outputSchema` must carry `structuredContent`, or the
|
|
189
|
+
* SDK client rejects it after the route has already run. A success response
|
|
190
|
+
* that yields no object to put there (204, 3xx, non-JSON, a non-object body)
|
|
191
|
+
* contradicts the route's own declared output, so it becomes an `isError`
|
|
192
|
+
* result naming the mismatch — which the SDK exempts from the rule — rather
|
|
193
|
+
* than a protocol fault the agent cannot interpret.
|
|
194
|
+
*/
|
|
195
|
+
async function mapToolResponse(tool, response) {
|
|
196
|
+
const status = response.status;
|
|
197
|
+
const structured = advertisesStructuredOutput(tool);
|
|
198
|
+
if (status === 204 || status >= 300 && status < 400) {
|
|
199
|
+
const location = response.headers.get("Location");
|
|
200
|
+
const text = location ? `HTTP ${status} (Location: ${location})` : `HTTP ${status}`;
|
|
201
|
+
if (structured) return inconsistentOutput(tool, text, status);
|
|
202
|
+
return {
|
|
203
|
+
content: [{
|
|
204
|
+
type: "text",
|
|
205
|
+
text
|
|
206
|
+
}],
|
|
207
|
+
status
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
const raw = await response.text();
|
|
211
|
+
if (status >= 400) return {
|
|
212
|
+
content: [{
|
|
213
|
+
type: "text",
|
|
214
|
+
text: raw || `HTTP ${status}`
|
|
215
|
+
}],
|
|
216
|
+
isError: true,
|
|
217
|
+
status
|
|
218
|
+
};
|
|
219
|
+
const parsed = parseJsonBody(response, raw);
|
|
220
|
+
if (parsed === void 0) {
|
|
221
|
+
const text = raw.length > TEXT_RESPONSE_CAP ? `${raw.slice(0, TEXT_RESPONSE_CAP)}… [truncated ${raw.length - TEXT_RESPONSE_CAP} characters]` : raw;
|
|
222
|
+
if (structured) return inconsistentOutput(tool, `a non-JSON body (${text.slice(0, 200)})`, status);
|
|
223
|
+
return {
|
|
224
|
+
content: [{
|
|
225
|
+
type: "text",
|
|
226
|
+
text
|
|
227
|
+
}],
|
|
228
|
+
status
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
if (response.headers.get("X-Guren-Agent-Preflight-Verdict") !== null) return {
|
|
232
|
+
content: [{
|
|
233
|
+
type: "text",
|
|
234
|
+
text: JSON.stringify(parsed)
|
|
235
|
+
}],
|
|
236
|
+
status,
|
|
237
|
+
preflightVerdict: true
|
|
238
|
+
};
|
|
239
|
+
const payload = unwrapInertiaProps(tool, response, parsed);
|
|
240
|
+
if (structured && !isRecord(payload)) return inconsistentOutput(tool, `a ${Array.isArray(payload) ? "JSON array" : typeof payload} body`, status);
|
|
241
|
+
const outcome = {
|
|
242
|
+
content: [{
|
|
243
|
+
type: "text",
|
|
244
|
+
text: JSON.stringify(payload)
|
|
245
|
+
}],
|
|
246
|
+
status
|
|
247
|
+
};
|
|
248
|
+
if (structured && isRecord(payload)) outcome.structuredContent = payload;
|
|
249
|
+
return outcome;
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* A success response that cannot satisfy the tool's advertised object output
|
|
253
|
+
* schema. Returned as an error result — the honest signal that the route and
|
|
254
|
+
* its declared `output` disagree — which also sidesteps the SDK's
|
|
255
|
+
* structuredContent requirement (errors are exempt).
|
|
256
|
+
*/
|
|
257
|
+
function inconsistentOutput(tool, detail, status) {
|
|
258
|
+
return {
|
|
259
|
+
content: [{
|
|
260
|
+
type: "text",
|
|
261
|
+
text: `The tool "${tool.toolName}" advertises an output schema, but the route returned ${detail} (HTTP ${status}) — no structured result could be produced.`
|
|
262
|
+
}],
|
|
263
|
+
isError: true,
|
|
264
|
+
status
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
function parseJsonBody(response, raw) {
|
|
268
|
+
if (!(response.headers.get("Content-Type") ?? "").includes("json") || raw === "") return void 0;
|
|
269
|
+
try {
|
|
270
|
+
return JSON.parse(raw);
|
|
271
|
+
} catch {
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
function unwrapInertiaProps(tool, response, parsed) {
|
|
276
|
+
if (tool.outputSchema) return parsed;
|
|
277
|
+
if (response.headers.get("X-Inertia") !== "true") return parsed;
|
|
278
|
+
if (!isRecord(parsed) || !("props" in parsed)) return parsed;
|
|
279
|
+
return parsed.props;
|
|
280
|
+
}
|
|
281
|
+
function isRecord(value) {
|
|
282
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
283
|
+
}
|
|
284
|
+
//#endregion
|
|
285
|
+
export { mapToolResponse as a, describeBuildFailure as i, advertisesStructuredOutput as n, AGENT_PREFLIGHT_HEADER as o, buildToolRequest as r, AGENT_PREFLIGHT_VERDICT_HEADER as s, PREFLIGHT_ARGUMENT as t };
|
package/dist/encryption/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as generateAppKey, c as parseAppKey, i as encodeDerivedKey, l as parsePreviousAppKeys, n as deriveAppKey, o as getAppKeyringFromEnv, r as deriveAppKeyring, s as normalizeAppKey, t as MessageSigner } from "../MessageSigner-Bd25ZJAV.js";
|
|
2
|
-
import { a as md5, c as sha256, d as verifyPassword, i as hmac, l as sha512, n as hash, o as needsRehash, r as hashPassword, s as secureCompare, t as check, u as verifyHmac } from "../Hash-
|
|
2
|
+
import { a as md5, c as sha256, d as verifyPassword, i as hmac, l as sha512, n as hash, o as needsRehash, r as hashPassword, s as secureCompare, t as check, u as verifyHmac } from "../Hash-C8aejmi8.js";
|
|
3
3
|
import { a as random, c as randomHex, d as sample, f as shuffle, i as pick, l as randomInt, m as uuid, n as generatePassword, o as randomBase64, p as urlSafeToken, r as generateSlug, s as randomBase64Url, t as generateOtp, u as randomString } from "../Random-DbIJ22KQ.js";
|
|
4
|
-
import { a as decrypt, c as getEncrypter, i as createEncrypter, l as setEncrypter, n as verifySignedUrl, o as encrypt, r as Encrypter, s as generateKey, t as signUrl } from "../encryption-
|
|
4
|
+
import { a as decrypt, c as getEncrypter, i as createEncrypter, l as setEncrypter, n as verifySignedUrl, o as encrypt, r as Encrypter, s as generateKey, t as signUrl } from "../encryption-D99Vmls3.js";
|
|
5
5
|
export { Encrypter, MessageSigner, check, createEncrypter, decrypt, deriveAppKey, deriveAppKeyring, encodeDerivedKey, encrypt, generateAppKey, generateKey, generateOtp, generatePassword, generateSlug, getAppKeyringFromEnv, getEncrypter, hash, hashPassword, hmac, md5, needsRehash, normalizeAppKey, parseAppKey, parsePreviousAppKeys, pick, random, randomBase64, randomBase64Url, randomHex, randomInt, randomString, sample, secureCompare, setEncrypter, sha256, sha512, shuffle, signUrl, urlSafeToken, uuid, verifyHmac, verifyPassword, verifySignedUrl };
|
|
@@ -218,11 +218,14 @@ const PURPOSE = "signed-url";
|
|
|
218
218
|
const SIGNATURE_PARAM = "signature";
|
|
219
219
|
const EXPIRES_PARAM = "expires";
|
|
220
220
|
const RELATIVE_BASE = "https://relative.invalid";
|
|
221
|
+
const RELATIVE_ORIGIN = new URL(RELATIVE_BASE).origin;
|
|
221
222
|
const EXPIRES_SHAPE = /^[0-9]{1,15}$/;
|
|
222
223
|
function parseUrl(value) {
|
|
223
224
|
const relative = value.startsWith("/");
|
|
225
|
+
const url = relative ? new URL(value, RELATIVE_BASE) : new URL(value);
|
|
226
|
+
if (relative && (url.origin !== RELATIVE_ORIGIN || url.pathname.startsWith("//"))) throw new TypeError(`signed-url: an app-relative URL must not begin with an authority, got ${value}`);
|
|
224
227
|
return {
|
|
225
|
-
url
|
|
228
|
+
url,
|
|
226
229
|
relative
|
|
227
230
|
};
|
|
228
231
|
}
|
|
@@ -41,6 +41,22 @@ export interface DevAssetsOptions {
|
|
|
41
41
|
favicon?: boolean;
|
|
42
42
|
/** Serve selected files from the public directory without the `/public` prefix. */
|
|
43
43
|
rootPublicAssets?: RootPublicAssetsConfig;
|
|
44
|
+
/**
|
|
45
|
+
* Serve document types (`.svg`, `.html`, XML) from `/public/*` and
|
|
46
|
+
* `/resources/css/*` inline instead of forcing them to download. Defaults to
|
|
47
|
+
* false.
|
|
48
|
+
*
|
|
49
|
+
* Off by default because `public/` is also where an app's uploads land, and
|
|
50
|
+
* a stored `.html` or `.svg` served inline is script in the app's own
|
|
51
|
+
* origin. Turn it on for a public directory holding nothing user-supplied —
|
|
52
|
+
* a static microsite under `public/docs/index.html`, say, which Hono resolves
|
|
53
|
+
* from a directory request and would otherwise hand back as a download.
|
|
54
|
+
*
|
|
55
|
+
* The root-level allowlist route has its own switch,
|
|
56
|
+
* `rootPublicAssets: { inlineDocuments: true }`; an app serving documents
|
|
57
|
+
* both ways sets both.
|
|
58
|
+
*/
|
|
59
|
+
inlineDocuments?: boolean;
|
|
44
60
|
}
|
|
45
61
|
/**
|
|
46
62
|
* Absolute path to `@guren/inertia-client`'s build output, the directory
|
|
@@ -11,5 +11,15 @@ export interface RootPublicAssetsOptions {
|
|
|
11
11
|
routePrefix?: string;
|
|
12
12
|
/** Override content types per extension. */
|
|
13
13
|
contentTypeMap?: Record<string, string>;
|
|
14
|
+
/**
|
|
15
|
+
* Serve document types (`.svg`, `.html`, XML) inline instead of forcing them
|
|
16
|
+
* to download. Defaults to false.
|
|
17
|
+
*
|
|
18
|
+
* The default exists because this directory is also where an app's uploads
|
|
19
|
+
* land — `.svg` is in the default extension list, and an SVG navigated to
|
|
20
|
+
* directly is script in the app's own origin. Turn it on only for a
|
|
21
|
+
* directory holding nothing user-supplied.
|
|
22
|
+
*/
|
|
23
|
+
inlineDocuments?: boolean;
|
|
14
24
|
}
|
|
15
25
|
export declare function registerRootPublicAssets(app: Application, publicDir: string, config?: RootPublicAssetsConfig): void;
|
package/dist/http/request.d.ts
CHANGED
|
@@ -43,6 +43,63 @@ export interface RequestBodyContext {
|
|
|
43
43
|
* a record exactly as {@link parseRequestPayload} does.
|
|
44
44
|
*/
|
|
45
45
|
export declare function parseRequestBody(ctx: RequestBodyContext): Promise<unknown>;
|
|
46
|
+
/**
|
|
47
|
+
* What {@link parseRequestUploads} reads: one member off `ctx.req`, not a whole
|
|
48
|
+
* Hono context — the same narrowing, and for the same caller, as
|
|
49
|
+
* {@link RequestBodyContext}.
|
|
50
|
+
*
|
|
51
|
+
* `parseBody` is required here where the body parser makes it optional. That
|
|
52
|
+
* parser has a fallback for a context without one; this has none, because
|
|
53
|
+
* there is no second way to read an upload. A caller that cannot supply
|
|
54
|
+
* `parseBody` should fail to compile rather than silently answer "no files".
|
|
55
|
+
*/
|
|
56
|
+
export interface RequestUploadsContext {
|
|
57
|
+
req: Pick<HonoRequest, 'parseBody'>;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* The shape an upload read answers with: Hono's `{ all: true }` record, where a
|
|
61
|
+
* field repeated in the body is an array and a single one is not.
|
|
62
|
+
*/
|
|
63
|
+
export type RequestUploads = Record<string, string | File | (string | File)[]>;
|
|
64
|
+
/**
|
|
65
|
+
* The one multipart read behind `Controller.file()` and `Controller.files()`,
|
|
66
|
+
* guarded so a body the parser cannot decode carries no files rather than
|
|
67
|
+
* crashing the request: it reads as `{}`, which is the same answer both helpers
|
|
68
|
+
* already give for a field that is simply absent — `null` and `[]`. Left to
|
|
69
|
+
* throw, the parser's `TypeError` escaped as a 500 reporting the exception and
|
|
70
|
+
* a stack, the defect {@link parseRequestBody} fixes for the validation paths.
|
|
71
|
+
*
|
|
72
|
+
* Deliberately *not* routed through {@link parseRequestBody}, which looks like
|
|
73
|
+
* the same rule and is not: it parses without `{ all: true }` and flattens a
|
|
74
|
+
* repeated field to its first value, so sharing it would silently reduce
|
|
75
|
+
* `files()` to one file per field. `{ all: true }` is the contract here, and a
|
|
76
|
+
* malformed-body test cannot see its loss — hence the separate function.
|
|
77
|
+
*
|
|
78
|
+
* There is no media-type gate, deliberately: Hono decides the media type inside
|
|
79
|
+
* `parseBody()`, having lowercased it first. A caller that gates before calling
|
|
80
|
+
* — or that reads uploads through `Request.formData()`, whose handling of the
|
|
81
|
+
* media type is not Hono's — answers `null` for an uppercase
|
|
82
|
+
* `MULTIPART/FORM-DATA` body this returns the file for.
|
|
83
|
+
*
|
|
84
|
+
* That was measured on Bun 1.3.14, and the host half of it has already moved:
|
|
85
|
+
* Bun 1.4.0 accepts the same header `1.3.14` rejects, and Node always did. The
|
|
86
|
+
* divergence is therefore a property of *where the media type is decided*, not
|
|
87
|
+
* of any one runtime — which is the argument for deciding it in one place, and
|
|
88
|
+
* why `@guren/testing`'s controller mock reaches this function rather than
|
|
89
|
+
* restating it.
|
|
90
|
+
*
|
|
91
|
+
* try/catch rather than `.catch()`, for the reason given on the shared
|
|
92
|
+
* fallback: `parseBody` may throw synchronously as well as reject, and only one
|
|
93
|
+
* of those two shapes reaches a `.catch()`.
|
|
94
|
+
*
|
|
95
|
+
* It fails open in one direction, deliberately and for the same reason
|
|
96
|
+
* {@link parseRequestBody} does: a body already consumed upstream reads as
|
|
97
|
+
* "no upload" rather than throwing, so a middleware-ordering bug loses the 500
|
|
98
|
+
* that used to announce it. Telling that apart from a client's malformed body
|
|
99
|
+
* means matching runtime-specific error codes, which answer differently on Bun,
|
|
100
|
+
* Node and Workers.
|
|
101
|
+
*/
|
|
102
|
+
export declare function parseRequestUploads(ctx: RequestUploadsContext): Promise<RequestUploads>;
|
|
46
103
|
/**
|
|
47
104
|
* The record-shaped view of {@link parseRequestBody}, for callers that read the
|
|
48
105
|
* payload field by field (`payload.channel`, per-field validation rules,
|
|
@@ -53,13 +110,43 @@ export declare function parseRequestBody(ctx: RequestBodyContext): Promise<unkno
|
|
|
53
110
|
export declare function parseRequestPayload(ctx: Context): Promise<Record<string, unknown>>;
|
|
54
111
|
/** Narrow a parsed body to the record view described on {@link parseRequestPayload}. */
|
|
55
112
|
export declare function asRecord(body: unknown): Record<string, unknown>;
|
|
113
|
+
/**
|
|
114
|
+
* What {@link flattenRequestQueries} actually reads: one no-arg `queries()` off
|
|
115
|
+
* `ctx.req`, not a whole Hono context.
|
|
116
|
+
*
|
|
117
|
+
* Spelled as the call shape rather than as `Pick<HonoRequest, 'queries'>` — the
|
|
118
|
+
* one place this departs from {@link RequestBodyContext} above, and not by
|
|
119
|
+
* preference. `HonoRequest.queries` is *overloaded* (`queries(key)` returning
|
|
120
|
+
* `string[] | undefined`, `queries()` returning the record), and a `Pick` keeps
|
|
121
|
+
* both signatures, so the plain `() => Record<string, string[]>` that
|
|
122
|
+
* `@guren/testing`'s `ControllerContext` declares cannot satisfy it. Naming the
|
|
123
|
+
* one signature this function calls admits both: an overloaded member is
|
|
124
|
+
* assignable to any of its own signatures, so a real `HonoRequest` still passes.
|
|
125
|
+
*
|
|
126
|
+
* Narrowing a parameter accepts strictly more callers, so every existing one
|
|
127
|
+
* keeps passing a real `Context` unchanged.
|
|
128
|
+
*/
|
|
129
|
+
export interface RequestQueryContext {
|
|
130
|
+
req: {
|
|
131
|
+
queries(): Record<string, string[]>;
|
|
132
|
+
};
|
|
133
|
+
}
|
|
56
134
|
/**
|
|
57
135
|
* Collects query parameters preserving repeated keys as arrays while keeping
|
|
58
136
|
* single occurrences as plain strings (`?tag=a&tag=b` → `{ tag: ['a', 'b'] }`,
|
|
59
137
|
* `?page=2` → `{ page: '2' }`). Use this instead of `ctx.req.query()` when
|
|
60
138
|
* feeding query data into validation schemas.
|
|
139
|
+
*
|
|
140
|
+
* Materialized with `Object.fromEntries`, never by assigning into an object
|
|
141
|
+
* literal — the same rule, and for the same reason, as the form branch of
|
|
142
|
+
* {@link parseRequestBody} above. Query keys are attacker-controlled, and
|
|
143
|
+
* `flat['__proto__'] = …` hits `Object.prototype`'s inherited setter instead
|
|
144
|
+
* of defining a field: `?__proto__=one` silently vanished before reaching the
|
|
145
|
+
* schema, and `?__proto__=one&__proto__=two` set the returned record's own
|
|
146
|
+
* prototype to that array. Hono hands over a null-prototype object, so the
|
|
147
|
+
* key arrives here intact; only this last step could lose it.
|
|
61
148
|
*/
|
|
62
|
-
export declare function flattenRequestQueries(ctx:
|
|
149
|
+
export declare function flattenRequestQueries(ctx: RequestQueryContext): Record<string, unknown>;
|
|
63
150
|
export interface ValidationIssueLike {
|
|
64
151
|
path: PropertyKey[];
|
|
65
152
|
message: string;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
/**
|
|
3
|
+
* Judged on the media type alone. Both inputs this module reads are
|
|
4
|
+
* parameterised — Hono's `getMimeType` returns `text/html; charset=utf-8`, and
|
|
5
|
+
* so does a hand-written `contentTypeMap` entry — so comparing the header
|
|
6
|
+
* verbatim is precisely how the check stops matching while still looking
|
|
7
|
+
* present.
|
|
8
|
+
*/
|
|
9
|
+
export declare function rendersAsDocument(contentType: string | undefined | null): boolean;
|
|
10
|
+
/**
|
|
11
|
+
* Neutralizes a served document by turning it into a download.
|
|
12
|
+
*
|
|
13
|
+
* `Content-Disposition: attachment` is honoured for navigations and ignored
|
|
14
|
+
* for subresource loads, which is what makes it usable on a general asset
|
|
15
|
+
* route: `<img src="/logo.svg">`, `<link rel="icon">` and CSS `url()` keep
|
|
16
|
+
* working unchanged, while `/logo.svg` opened directly is downloaded instead
|
|
17
|
+
* of rendered. An `<iframe>` or `<object>` *is* a navigation, so an SVG or
|
|
18
|
+
* HTML page embedded that way stops rendering — which is the same mechanism
|
|
19
|
+
* as the fix, not an exception to it. `nosniff` rides along for the types a
|
|
20
|
+
* browser would otherwise promote on its own.
|
|
21
|
+
*/
|
|
22
|
+
export declare function applyDocumentDisposition(headers: Headers, contentType: string | undefined | null): void;
|
|
23
|
+
/**
|
|
24
|
+
* The {@link import('hono/bun').serveStatic} form of
|
|
25
|
+
* {@link applyDocumentDisposition}, for use as its `onFound` hook.
|
|
26
|
+
*
|
|
27
|
+
* Keyed on the same `getMimeType(path)` the middleware itself used a line
|
|
28
|
+
* earlier to set `Content-Type`, rather than on the extension: the two agree
|
|
29
|
+
* by construction only while they read the same function.
|
|
30
|
+
*/
|
|
31
|
+
export declare function guardStaticDocument(path: string, ctx: Context): void;
|
package/dist/index.d.ts
CHANGED
|
@@ -12,13 +12,21 @@ export { Router } from './mvc/Router.js';
|
|
|
12
12
|
export type { BindableModel, AgentRouteMetadata, RouteBuilder, RouteContractOptions, RouteDefinition, RouteMiddlewareInput, RouteModelBinding, RouteOpenApiMetadata, ResourceAction as RouteResourceAction, ResourceResponseHint, ResourceResponseShape, ResourceRouteOptions, } from './mvc/Router.js';
|
|
13
13
|
export { deriveAgentTools } from './agent/derive.js';
|
|
14
14
|
export type { AgentToolInputSource, AgentToolSchema, DeriveAgentToolsResult, DerivedAgentTool, DerivedAgentToolAnnotations, DerivedAgentToolExposure, } from './agent/derive.js';
|
|
15
|
-
export { advertisesStructuredOutput, buildToolRequest, mapToolResponse, PREFLIGHT_ARGUMENT, } from './agent/dispatch.js';
|
|
16
|
-
export type { BuildToolRequestOptions, BuiltToolRequest, ToolCallOutcome, } from './agent/dispatch.js';
|
|
15
|
+
export { advertisesStructuredOutput, buildToolRequest, describeBuildFailure, mapToolResponse, PREFLIGHT_ARGUMENT, } from './agent/dispatch.js';
|
|
16
|
+
export type { BuildToolRequestOptions, BuiltToolRequest, ToolCallOutcome, ToolRequestBuildFailure, } from './agent/dispatch.js';
|
|
17
|
+
export { APPROVAL_STATUS_TOOL_NAME, isReservedAgentToolName, PREFLIGHT_TOOL_NAME, RESERVED_AGENT_TOOL_NAMES, } from './agent/meta-tools.js';
|
|
17
18
|
export { AGENT_TOOL_NAME_PATTERN, expandToolScopes, parseToolScope, scopesAllowTool, } from './agent/scopes.js';
|
|
18
19
|
export type { ParsedToolScope, ScopedTool } from './agent/scopes.js';
|
|
19
20
|
export { AgentToolDenied, AgentToolInvoked } from './agent/events.js';
|
|
20
21
|
export type { AgentPrincipal, AgentSurface, AgentToolDenialReason } from './agent/events.js';
|
|
21
22
|
export { AGENT_REDACTED, redactAgentArguments } from './agent/redact.js';
|
|
23
|
+
export { DEFAULT_AGENT_AUDIT_PATH, parseAuditRecord, toAuditRecord } from './agent/audit.js';
|
|
24
|
+
export type { AgentAuditDeniedRecord, AgentAuditInvokedRecord, AgentAuditRecord, } from './agent/audit.js';
|
|
25
|
+
export { AGENT_AUDIT_BINDING, createAuditEmitter } from './agent/audit-emitter.js';
|
|
26
|
+
export type { AgentAuditEmitter, AgentAuditSink } from './agent/audit-emitter.js';
|
|
27
|
+
export { AGENT_APPROVAL_CONFIG_KEY, agentApprovalExpiredAt, agentApprovalFingerprint, agentApprovalPrincipalKey, agentApprovalStatusAt, agentApprovalUsableAt, agentApprovalVisibleTo, buildAgentApprovalRequest, canonicalizeAgentApprovalInput, DEFAULT_AGENT_APPROVAL_TTL_MS, } from './agent/approval.js';
|
|
28
|
+
export type { AgentApprovalMatch, AgentApprovalRequest, AgentApprovalRequestInput, AgentApprovalStatus, AgentApprovalStore, } from './agent/approval.js';
|
|
29
|
+
export { AgentApprovalRequested } from './agent/AgentApprovalRequested.js';
|
|
22
30
|
export { ViewEngine } from './mvc/ViewEngine.js';
|
|
23
31
|
export { inertia, setInertiaSsrRenderer, setInertiaDocument } from './mvc/inertia/InertiaEngine.js';
|
|
24
32
|
export { setInertiaSharedProps, getInertiaSharedPropsResolver, shareInertiaProps } from './mvc/inertia/shared.js';
|
|
@@ -45,7 +53,7 @@ export { StorageManager, LocalDriver as LocalStorageDriver, MemoryDriver as Memo
|
|
|
45
53
|
export type { StorageDriver, StorageConfig, DiskConfig, StorageDriverFactory, PutOptions, FileMetadata, TemporaryUrlOptions, GetStreamOptions, StorageDriverCapabilities, } from './storage/index.js';
|
|
46
54
|
export { Scheduler, Schedule, PendingSchedule, ScheduledTask, parseCron, matchesCron, getNextOccurrence, getNextOccurrences, isDue, isDueInTimezone, toTimezone, createScheduler, } from './scheduling/index.js';
|
|
47
55
|
export type { TaskCallback, TaskDefinition, SchedulerOptions, ParsedCron, JobClass as ScheduledJobClass, } from './scheduling/index.js';
|
|
48
|
-
export { Logger, filterSensitiveData, LogManager, ConsoleChannel, FileChannel, DailyFileChannel, LOG_LEVEL_PRIORITY, createLogManager, setLogManager, getLogManager, } from './logging/index.js';
|
|
56
|
+
export { Logger, filterSensitiveData, LogManager, ConsoleChannel, FileChannel, DailyFileChannel, dailyFileDateStamp, dailyFilePath, matchDailyFileDate, LOG_LEVEL_PRIORITY, createLogManager, setLogManager, getLogManager, } from './logging/index.js';
|
|
49
57
|
export type { LogLevel, LogContext, LogEntry, LogChannel, LogChannelFactory, LogChannelConfig, ConsoleChannelConfig, FileChannelConfig, DailyFileChannelConfig, StackChannelConfig, LogConfig, LogFormatter, LoggerOptions, } from './logging/index.js';
|
|
50
58
|
export { Translator, I18nManager, JsonLoader, MemoryLoader, pluralizationRules, getPluralizationRule, selectPluralForm, createI18n, setI18n, getI18n, tryGetI18n, t, tc, } from './i18n/index.js';
|
|
51
59
|
export type { TranslationMessages, ReplacementValues, PluralizationRule, TranslationLoader, TranslatorOptions, I18nConfig, TranslationLoaderFactory, GurenTranslationKeys, RegisteredTranslationKey, } from './i18n/index.js';
|