@valbuild/server 0.154.0 → 0.154.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +49 -0
- package/browser/dist/valbuild-server-browser.cjs.dev.js +6 -3
- package/browser/dist/valbuild-server-browser.cjs.prod.js +6 -3
- package/browser/dist/valbuild-server-browser.esm.js +6 -3
- package/dist/{ValRouterCore-fe985e4c.esm.js → ValOpsMemory-611f33d2.esm.js} +44 -1988
- package/dist/{ValRouterCore-4be8eaf1.cjs.prod.js → ValOpsMemory-6ebbb3ba.cjs.prod.js} +53 -2009
- package/dist/{ValRouterCore-0c088c9e.cjs.dev.js → ValOpsMemory-d8bf9f5d.cjs.dev.js} +53 -2009
- package/dist/ValPatchStore-2f92eced.cjs.prod.js +1128 -0
- package/dist/ValPatchStore-df8cdbe7.cjs.dev.js +1128 -0
- package/dist/ValPatchStore-e23070df.esm.js +1119 -0
- package/dist/ValRouterCore-5b747abb.cjs.prod.js +612 -0
- package/dist/ValRouterCore-73eb843d.esm.js +608 -0
- package/dist/ValRouterCore-86757d56.cjs.dev.js +612 -0
- package/dist/createPrettierFormatter-05ad7480.cjs.prod.js +692 -0
- package/dist/createPrettierFormatter-1edca494.esm.js +673 -0
- package/dist/createPrettierFormatter-851fcf99.cjs.dev.js +692 -0
- package/dist/createValRuntime-2dc83070.cjs.prod.js +47 -0
- package/dist/createValRuntime-62836dbe.esm.js +45 -0
- package/dist/createValRuntime-fd9b673d.cjs.dev.js +47 -0
- package/dist/declarations/src/ValOpsMemory.d.ts +3 -73
- package/dist/declarations/src/ValPatchStore.d.ts +92 -0
- package/dist/declarations/src/ValRouter.d.ts +1 -11
- package/dist/declarations/src/createPrettierFormatter.d.ts +18 -3
- package/dist/declarations/src/createValRuntime.d.ts +12 -0
- package/dist/declarations/src/draftReads.d.ts +11 -3
- package/dist/declarations/src/index.d.ts +4 -2
- package/dist/declarations/src/internal/index.d.ts +28 -6
- package/dist/declarations/src/proposal.d.ts +13 -25
- package/dist/declarations/src/proposalJsonEntries.d.ts +30 -0
- package/dist/declarations/src/serverMode.d.ts +31 -0
- package/dist/{draftReads-0dcddf72.cjs.prod.js → draftReads-3f7dcda5.cjs.prod.js} +10 -2
- package/dist/{draftReads-df44e629.cjs.dev.js → draftReads-a300a02f.cjs.dev.js} +10 -2
- package/dist/{draftReads-1f29aedd.esm.js → draftReads-bca0d49c.esm.js} +10 -2
- package/dist/{inTabFetch-f6694ad2.cjs.prod.js → inTabFetch-0124da2e.cjs.prod.js} +5 -4
- package/dist/{inTabFetch-c8966e73.cjs.dev.js → inTabFetch-d0c9c58a.cjs.dev.js} +5 -4
- package/dist/{inTabFetch-877e7d11.esm.js → inTabFetch-e48a801e.esm.js} +2 -1
- package/dist/jsonValuesPatch-13acc674.esm.js +276 -0
- package/dist/jsonValuesPatch-88bc661d.cjs.dev.js +281 -0
- package/dist/jsonValuesPatch-92798812.cjs.prod.js +281 -0
- package/dist/proposalJsonEntries-0669f027.esm.js +480 -0
- package/dist/proposalJsonEntries-26f397bd.cjs.dev.js +500 -0
- package/dist/proposalJsonEntries-9e537244.cjs.prod.js +500 -0
- package/dist/{publishKit-cfe1273d.cjs.dev.js → publishKit-96522d5a.cjs.prod.js} +20 -22
- package/dist/{publishKit-e7f7db7c.cjs.prod.js → publishKit-b06031dc.cjs.dev.js} +20 -22
- package/dist/{publishKit-0709423c.esm.js → publishKit-b8929fe8.esm.js} +8 -9
- package/dist/{ValRouter-1f427c38.cjs.dev.js → valRuntime-ba8ff718.cjs.prod.js} +158 -6038
- package/dist/{ValRouter-cd6e854a.cjs.prod.js → valRuntime-c8c82b24.cjs.dev.js} +158 -6038
- package/dist/{ValRouter-558dc66d.esm.js → valRuntime-ccbbbfad.esm.js} +107 -5937
- package/dist/valbuild-server.cjs.dev.js +5146 -352
- package/dist/valbuild-server.cjs.prod.js +5146 -352
- package/dist/valbuild-server.esm.js +4902 -132
- package/internal/browser/dist/valbuild-server-internal-browser.cjs.dev.js +7 -4
- package/internal/browser/dist/valbuild-server-internal-browser.cjs.prod.js +7 -4
- package/internal/browser/dist/valbuild-server-internal-browser.esm.js +7 -4
- package/internal/dist/valbuild-server-internal.cjs.dev.js +47 -31
- package/internal/dist/valbuild-server-internal.cjs.prod.js +47 -31
- package/internal/dist/valbuild-server-internal.esm.js +38 -22
- package/package.json +4 -4
|
@@ -0,0 +1,612 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var core = require('@valbuild/core');
|
|
4
|
+
var internal = require('@valbuild/shared/internal');
|
|
5
|
+
var zodValidationError = require('zod-validation-error');
|
|
6
|
+
var z = require('zod');
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* What `redirect_to` may be on Val's routes (`/enable`, `/disable`,
|
|
10
|
+
* `/authorize`, `/draft/enable`, ...): a path on the site that was asked,
|
|
11
|
+
* which is made absolute against the request's own origin, or an absolute
|
|
12
|
+
* URL on that same site.
|
|
13
|
+
*
|
|
14
|
+
* A path used to go through as it was, and two things downstream need an
|
|
15
|
+
* absolute URL: `/authorize` reads the origin off it to build the callback,
|
|
16
|
+
* and Next's `NextResponse.redirect` refuses anything else. Both threw, so
|
|
17
|
+
* `/api/val/enable?redirect_to=/` answered 500 in a Next app.
|
|
18
|
+
*
|
|
19
|
+
* `//host/path` is a URL on another host, not a path on this one, and
|
|
20
|
+
* anything that is neither is refused with what is accepted instead. An
|
|
21
|
+
* empty value is not resolved at all: the router leaves it to the route, as
|
|
22
|
+
* it always was (`/logout` reads it as absent).
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
const REDIRECT_TO_ACCEPTS = "redirect_to must be a path on this site starting with / (/page), or an absolute URL on this site (https://this-site.example/page).";
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* `siteHosts` are the other names the request knows this site by (`Host`,
|
|
29
|
+
* `X-Forwarded-Host`), for a server behind a proxy whose own URL is internal.
|
|
30
|
+
*/
|
|
31
|
+
function resolveRedirectTo(value, requestOrigin, siteHosts = []) {
|
|
32
|
+
if (value.startsWith("/") && !value.startsWith("//")) {
|
|
33
|
+
// A path stays on this origin. `/\host/x` also starts with one slash,
|
|
34
|
+
// and a URL parser reads the backslash as a second one: another host,
|
|
35
|
+
// not a path here.
|
|
36
|
+
const resolved = parsed(value, requestOrigin);
|
|
37
|
+
return resolved !== null && resolved.origin === new URL(requestOrigin).origin ? {
|
|
38
|
+
ok: true,
|
|
39
|
+
href: resolved.href
|
|
40
|
+
} : {
|
|
41
|
+
ok: false,
|
|
42
|
+
message: REDIRECT_TO_ACCEPTS
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
// An absolute URL, on this site only. Any URL used to pass, which made
|
|
46
|
+
// `/logout` and `/enable` redirect wherever a link said, and `/authorize`
|
|
47
|
+
// send the sign-in's code to that host: it reads the callback's origin off
|
|
48
|
+
// this. http(s) only: `javascript:` parses as a URL too.
|
|
49
|
+
const url = parsed(value);
|
|
50
|
+
if (url === null || url.protocol !== "https:" && url.protocol !== "http:") {
|
|
51
|
+
return {
|
|
52
|
+
ok: false,
|
|
53
|
+
message: REDIRECT_TO_ACCEPTS
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
const hosts = [new URL(requestOrigin).host, ...siteHosts].filter(host => typeof host === "string" && host !== "").map(host => host.toLowerCase());
|
|
57
|
+
return hosts.includes(url.host.toLowerCase()) ? {
|
|
58
|
+
ok: true,
|
|
59
|
+
href: value
|
|
60
|
+
} : {
|
|
61
|
+
ok: false,
|
|
62
|
+
message: REDIRECT_TO_ACCEPTS
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* `value` as a URL, or null. Not `URL.canParse`: this runs in the browser
|
|
68
|
+
* too (demo mode), where it is missing before Safari 17 and Chrome 120.
|
|
69
|
+
*/
|
|
70
|
+
function parsed(value, base) {
|
|
71
|
+
try {
|
|
72
|
+
return new URL(value, base);
|
|
73
|
+
} catch {
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Which requests Val's API answers in fs mode, where there is no session.
|
|
80
|
+
*
|
|
81
|
+
* fs mode reads and writes a working tree and asks nobody who they are: it is
|
|
82
|
+
* a developer's own machine. That holds only while the request really comes
|
|
83
|
+
* from that developer's Studio, and three kinds do not:
|
|
84
|
+
*
|
|
85
|
+
* - **A deployed site.** fs is the mode an app falls into when it has no
|
|
86
|
+
* `VAL_API_KEY` and `VAL_SECRET`, so a site deployed without them served
|
|
87
|
+
* this API, unauthenticated, to the internet.
|
|
88
|
+
* - **Another site's page**, in the developer's browser. A `text/plain` POST
|
|
89
|
+
* needs no preflight, and the router reads its body as JSON, so any page
|
|
90
|
+
* open in another tab could write to the working tree.
|
|
91
|
+
* - **A name that resolves to 127.0.0.1** (DNS rebinding), which makes such a
|
|
92
|
+
* page same-origin with the dev server as far as the browser can tell.
|
|
93
|
+
*
|
|
94
|
+
* The MCP endpoint has refused all three since it was written
|
|
95
|
+
* (`refuseUnsafeRequest` in `@valbuild/mcp`); this is the same rule for the
|
|
96
|
+
* API the Studio uses. Nothing here needs Node: `ValRouterCore` runs in a
|
|
97
|
+
* browser tab too, where no server is registered and nothing is refused.
|
|
98
|
+
*/
|
|
99
|
+
|
|
100
|
+
const guards = new WeakMap();
|
|
101
|
+
|
|
102
|
+
/** Say how `server`'s requests are to be checked. Without it, none are. */
|
|
103
|
+
function setRequestGuard(server, guard) {
|
|
104
|
+
guards.set(server, guard);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** `VAL_ALLOWED_HOSTS`: comma separated host names, without a port. */
|
|
108
|
+
function parseAllowedHosts(value) {
|
|
109
|
+
return (value ?? "").split(",").map(host => host.trim().toLowerCase()).filter(host => host !== "");
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The refusal, or `null` when the request may go on to its route. */
|
|
113
|
+
function refuseUnsafeRequest(server, req, apiPath) {
|
|
114
|
+
var _req$method;
|
|
115
|
+
const guard = guards.get(server);
|
|
116
|
+
if (guard === undefined || guard.mode !== "fs") {
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
// Beacons are not refused: in fs mode one is checked and dropped, nothing
|
|
120
|
+
// is written or forwarded, and a deployed site with analytics on would fill
|
|
121
|
+
// every visitor's console with errors.
|
|
122
|
+
if (apiPath === "/analytics") {
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
if (guard.production) {
|
|
126
|
+
return refusal("Val is not set up for a deployed site here: without VAL_API_KEY and VAL_SECRET it runs in local filesystem mode, which has no sign-in and is only served by a development server. Set both (and VAL_PROJECT) on this deployment to use Val on it.");
|
|
127
|
+
}
|
|
128
|
+
const host = hostOf(req);
|
|
129
|
+
const forwardedHost = firstOf(req.headers.get("x-forwarded-host"));
|
|
130
|
+
const origin = req.headers.get("origin");
|
|
131
|
+
if (origin !== null) {
|
|
132
|
+
// `null` is the opaque origin (a sandboxed frame, a `file:` page). It
|
|
133
|
+
// cannot be compared with anything, so it is refused.
|
|
134
|
+
const originHost = origin === "null" ? null : hostOfUrl(origin);
|
|
135
|
+
if (originHost === null || originHost !== host && originHost !== forwardedHost) {
|
|
136
|
+
return refusal(`Val refused a request from another site (${origin}). In local filesystem mode the API only answers the Studio on its own address.`);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
// A request with no `Origin` can still come from another site: an `<img>`,
|
|
140
|
+
// a script. Following a link here is not refused: sign-in comes back as
|
|
141
|
+
// one. A link is a GET; a form posted from another site navigates too.
|
|
142
|
+
const followedLink = ((_req$method = req.method) === null || _req$method === void 0 ? void 0 : _req$method.toUpperCase()) === "GET" && req.headers.get("sec-fetch-mode") === "navigate";
|
|
143
|
+
if (req.headers.get("sec-fetch-site") === "cross-site" && !followedLink) {
|
|
144
|
+
return refusal("Val refused a request from another site. In local filesystem mode the API only answers the Studio on its own address.");
|
|
145
|
+
}
|
|
146
|
+
const hostname = host === null ? null : hostnameOf(host);
|
|
147
|
+
if (hostname === null || !isLocalName(hostname, guard.allowedHosts)) {
|
|
148
|
+
return refusal(`Val refused a request addressed to ${host ?? "an unknown host"}. In local filesystem mode the API answers on localhost and on IP addresses, because any other name can be made to point at this machine by the site that owns it. If this is the address you develop on, add its host name to the VAL_ALLOWED_HOSTS environment variable (comma separated) and restart the dev server.`);
|
|
149
|
+
}
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
function refusal(message) {
|
|
153
|
+
return {
|
|
154
|
+
status: 403,
|
|
155
|
+
json: {
|
|
156
|
+
message
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
function firstOf(header) {
|
|
161
|
+
var _header$split$;
|
|
162
|
+
const first = header === null || header === void 0 || (_header$split$ = header.split(",")[0]) === null || _header$split$ === void 0 ? void 0 : _header$split$.trim().toLowerCase();
|
|
163
|
+
return first ? first : null;
|
|
164
|
+
}
|
|
165
|
+
function hostOf(req) {
|
|
166
|
+
const header = firstOf(req.headers.get("host"));
|
|
167
|
+
if (header !== null) {
|
|
168
|
+
return header;
|
|
169
|
+
}
|
|
170
|
+
// No Host header: the URL the framework built the request from.
|
|
171
|
+
return hostOfUrl(req.url);
|
|
172
|
+
}
|
|
173
|
+
function hostOfUrl(url) {
|
|
174
|
+
try {
|
|
175
|
+
return new URL(url).host.toLowerCase();
|
|
176
|
+
} catch {
|
|
177
|
+
return null;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** A host without its port. An IPv6 literal keeps its brackets. */
|
|
182
|
+
function hostnameOf(host) {
|
|
183
|
+
if (host.startsWith("[")) {
|
|
184
|
+
const end = host.indexOf("]");
|
|
185
|
+
return end === -1 ? host : host.slice(0, end + 1);
|
|
186
|
+
}
|
|
187
|
+
const colon = host.indexOf(":");
|
|
188
|
+
return colon === -1 ? host : host.slice(0, colon);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* localhost, an IP address, or a name the developer listed.
|
|
193
|
+
*
|
|
194
|
+
* An IP address is allowed because it cannot be rebound: a page that reaches
|
|
195
|
+
* this server by address is on another origin, and the `Origin` check above
|
|
196
|
+
* has already refused it. A phone on the same network uses one.
|
|
197
|
+
*/
|
|
198
|
+
function isLocalName(hostname, allowedHosts) {
|
|
199
|
+
return hostname === "localhost" || hostname.endsWith(".localhost") || /^\d{1,3}(\.\d{1,3}){3}$/.test(hostname) || hostname.startsWith("[") && hostname.endsWith("]") || allowedHosts.includes(hostname);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Val's API as a web-standard handler: a `Request` in, a converted result out.
|
|
204
|
+
*
|
|
205
|
+
* The request handling itself -- matching a route, parsing it against `Api`,
|
|
206
|
+
* calling the server, checking the answer -- and nothing that needs Node, so it
|
|
207
|
+
* runs in a browser tab as well as on a server. That is what the demo does
|
|
208
|
+
* (`@valbuild/server/browser`): the Studio's own client sends its requests
|
|
209
|
+
* here, in the same tab, instead of over the network.
|
|
210
|
+
*
|
|
211
|
+
* `serveStatic` answers `/static/...`, the Studio's own scripts and styles.
|
|
212
|
+
* `createValApiRouter` passes the embedded bundle; the demo passes nothing,
|
|
213
|
+
* because its page loaded those from the app already.
|
|
214
|
+
*/
|
|
215
|
+
function createValRequestHandler(route, valServerPromise, convert, serveStatic) {
|
|
216
|
+
// valServerPromise is created at module-eval time, but only awaited per request.
|
|
217
|
+
// Without this no-op catch, a config error (e.g. proxy mode without a project)
|
|
218
|
+
// rejects with no handler attached, which becomes an unhandledRejection and kills
|
|
219
|
+
// the dev server. The error is still reported per request by the try/catch below.
|
|
220
|
+
valServerPromise.catch(() => {
|
|
221
|
+
// handled below
|
|
222
|
+
});
|
|
223
|
+
return async req => {
|
|
224
|
+
let valServer;
|
|
225
|
+
try {
|
|
226
|
+
valServer = await valServerPromise;
|
|
227
|
+
} catch (err) {
|
|
228
|
+
const error = {
|
|
229
|
+
message: "Val: could not start the Val server",
|
|
230
|
+
details: err instanceof Error ? err.message : String(err)
|
|
231
|
+
};
|
|
232
|
+
core.Internal.log.error(error.message + ": " + error.details);
|
|
233
|
+
return convert({
|
|
234
|
+
status: 500,
|
|
235
|
+
json: error
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
const url = new URL(req.url);
|
|
239
|
+
if (!url.pathname.startsWith(route)) {
|
|
240
|
+
const error = {
|
|
241
|
+
message: "Val: routes are not configured correctly",
|
|
242
|
+
details: `Check you api routes. Expected pathname to start with "${route}", but it was: "${url.pathname}"`
|
|
243
|
+
};
|
|
244
|
+
core.Internal.log.error(error);
|
|
245
|
+
return convert({
|
|
246
|
+
status: 500,
|
|
247
|
+
json: error
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
const path = url.pathname.slice(route.length);
|
|
251
|
+
if (path === internal.QUICK_PREVIEW_SERVICE_WORKER_PATH) {
|
|
252
|
+
/*
|
|
253
|
+
* The quick preview worker (`quickPreview.ts` in
|
|
254
|
+
* `@valbuild/shared`). `Service-Worker-Allowed: /` lets a script at
|
|
255
|
+
* this path control the whole origin, which it needs: it serves the
|
|
256
|
+
* page's `/_app/` files. It serves them only to a page opened as a
|
|
257
|
+
* quick preview, and the bridge stores them only for the site.
|
|
258
|
+
*/
|
|
259
|
+
return convert({
|
|
260
|
+
status: 200,
|
|
261
|
+
headers: {
|
|
262
|
+
"Content-Type": "text/javascript; charset=utf-8",
|
|
263
|
+
"Service-Worker-Allowed": "/",
|
|
264
|
+
"Cache-Control": "no-cache"
|
|
265
|
+
},
|
|
266
|
+
body: internal.QUICK_PREVIEW_SERVICE_WORKER_SOURCE
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
const groupQueryParams = arr => {
|
|
270
|
+
const map = {};
|
|
271
|
+
for (const [key, value] of arr) {
|
|
272
|
+
const list = map[key] || [];
|
|
273
|
+
list.push(value);
|
|
274
|
+
map[key] = list;
|
|
275
|
+
}
|
|
276
|
+
return map;
|
|
277
|
+
};
|
|
278
|
+
async function getValServerResponse(reqApiRoutePath, req) {
|
|
279
|
+
var _req$method, _anyApi$route, _anyValServer$route;
|
|
280
|
+
const anyApi =
|
|
281
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
282
|
+
internal.Api;
|
|
283
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
284
|
+
const anyValServer = valServer;
|
|
285
|
+
const refused = refuseUnsafeRequest(valServer, req, reqApiRoutePath);
|
|
286
|
+
if (refused !== null) {
|
|
287
|
+
return refused;
|
|
288
|
+
}
|
|
289
|
+
const method = (_req$method = req.method) === null || _req$method === void 0 ? void 0 : _req$method.toUpperCase();
|
|
290
|
+
let route = null;
|
|
291
|
+
let path = undefined;
|
|
292
|
+
// An exact match wins over every prefix match, wherever it sits in
|
|
293
|
+
// `Api`: checked per key, in order, `/validate` took `/validate/fix`
|
|
294
|
+
// because it was declared first.
|
|
295
|
+
const exactRouteDef = Object.keys(internal.Api).find(routeDef => routeDef === reqApiRoutePath);
|
|
296
|
+
for (const routeDef of exactRouteDef ? [exactRouteDef] : Object.keys(internal.Api)) {
|
|
297
|
+
if (routeDef === reqApiRoutePath) {
|
|
298
|
+
route = routeDef;
|
|
299
|
+
break;
|
|
300
|
+
}
|
|
301
|
+
if (reqApiRoutePath.startsWith(routeDef)) {
|
|
302
|
+
var _anyApi$routeDef;
|
|
303
|
+
const reqDefinition = anyApi === null || anyApi === void 0 || (_anyApi$routeDef = anyApi[routeDef]) === null || _anyApi$routeDef === void 0 || (_anyApi$routeDef = _anyApi$routeDef[method]) === null || _anyApi$routeDef === void 0 ? void 0 : _anyApi$routeDef.req;
|
|
304
|
+
if (reqDefinition) {
|
|
305
|
+
route = routeDef;
|
|
306
|
+
if (reqDefinition.path) {
|
|
307
|
+
const subPath = reqApiRoutePath.slice(routeDef.length);
|
|
308
|
+
const pathRes = reqDefinition.path.safeParse(subPath);
|
|
309
|
+
if (!pathRes.success) {
|
|
310
|
+
return zodErrorResult(pathRes.error, `invalid path: '${subPath}' endpoint: '${routeDef}'`);
|
|
311
|
+
} else {
|
|
312
|
+
path = pathRes.data;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
break;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
if (!route) {
|
|
320
|
+
return {
|
|
321
|
+
status: 404,
|
|
322
|
+
json: {
|
|
323
|
+
message: "Route not found. Valid routes are: " + Object.keys(internal.Api),
|
|
324
|
+
details: {
|
|
325
|
+
route,
|
|
326
|
+
method
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
const apiEndpoint = anyApi === null || anyApi === void 0 || (_anyApi$route = anyApi[route]) === null || _anyApi$route === void 0 ? void 0 : _anyApi$route[method];
|
|
332
|
+
const reqDefinition = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.req;
|
|
333
|
+
if (!reqDefinition) {
|
|
334
|
+
return {
|
|
335
|
+
status: 404,
|
|
336
|
+
json: {
|
|
337
|
+
message: `Requested method ${method} on route ${route} is not valid. Valid methods are: ${Object.keys(anyApi[route]).join(", ")}`,
|
|
338
|
+
details: {
|
|
339
|
+
route,
|
|
340
|
+
method
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
const endpointImpl = anyValServer === null || anyValServer === void 0 || (_anyValServer$route = anyValServer[route]) === null || _anyValServer$route === void 0 ? void 0 : _anyValServer$route[method];
|
|
346
|
+
if (!endpointImpl) {
|
|
347
|
+
return {
|
|
348
|
+
status: 500,
|
|
349
|
+
json: {
|
|
350
|
+
message: "Missing server implementation of route with method. This might be caused by a mismatch between Val package versions.",
|
|
351
|
+
details: {
|
|
352
|
+
valid: {
|
|
353
|
+
route: {
|
|
354
|
+
server: Object.keys(anyValServer || {}),
|
|
355
|
+
api: Object.keys(anyApi || {})
|
|
356
|
+
},
|
|
357
|
+
method: {
|
|
358
|
+
server: Object.keys((anyValServer === null || anyValServer === void 0 ? void 0 : anyValServer[route]) || {}),
|
|
359
|
+
api: Object.keys((anyApi === null || anyApi === void 0 ? void 0 : anyApi[route]) || {})
|
|
360
|
+
}
|
|
361
|
+
},
|
|
362
|
+
route,
|
|
363
|
+
method
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
let bodyRes;
|
|
369
|
+
try {
|
|
370
|
+
bodyRes = reqDefinition.body ? reqDefinition.body.safeParse(await readJsonBody(req)) : {
|
|
371
|
+
success: true,
|
|
372
|
+
data: {}
|
|
373
|
+
};
|
|
374
|
+
if (!bodyRes.success) {
|
|
375
|
+
return zodErrorResult(bodyRes.error, "invalid body data");
|
|
376
|
+
}
|
|
377
|
+
} catch (e) {
|
|
378
|
+
return {
|
|
379
|
+
status: 400,
|
|
380
|
+
json: {
|
|
381
|
+
message: "Could not parse request body",
|
|
382
|
+
details: {
|
|
383
|
+
error: JSON.stringify(e)
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
const cookiesRes = reqDefinition.cookies ? getCookies(req, reqDefinition.cookies) : {
|
|
389
|
+
success: true,
|
|
390
|
+
data: {}
|
|
391
|
+
};
|
|
392
|
+
if (!cookiesRes.success) {
|
|
393
|
+
return zodErrorResult(cookiesRes.error, "invalid cookies");
|
|
394
|
+
}
|
|
395
|
+
const headersRes = reqDefinition.headers ? getHeaders(req, reqDefinition.headers) : {
|
|
396
|
+
success: true,
|
|
397
|
+
data: {}
|
|
398
|
+
};
|
|
399
|
+
if (!headersRes.success) {
|
|
400
|
+
return zodErrorResult(headersRes.error, "invalid headers");
|
|
401
|
+
}
|
|
402
|
+
const actualQueryParams = groupQueryParams(Array.from(url.searchParams.entries()));
|
|
403
|
+
let query = {};
|
|
404
|
+
if (reqDefinition.query) {
|
|
405
|
+
const queryRules = reqDefinition.query;
|
|
406
|
+
const queryRes = z.z.object(queryRules).safeParse(actualQueryParams);
|
|
407
|
+
if (!queryRes.success) {
|
|
408
|
+
return zodErrorResult(queryRes.error, `invalid query params: (${JSON.stringify(actualQueryParams)})`);
|
|
409
|
+
}
|
|
410
|
+
query = queryRes.data;
|
|
411
|
+
}
|
|
412
|
+
// `redirect_to` is a URL or a path on this site: see `resolveRedirectTo`.
|
|
413
|
+
if ("redirect_to" in query && typeof query.redirect_to === "string" && query.redirect_to !== "") {
|
|
414
|
+
var _req$headers$get;
|
|
415
|
+
// Behind a proxy `url` can be an internal address: the site's own
|
|
416
|
+
// name is then in `Host` or `X-Forwarded-Host`.
|
|
417
|
+
const resolved = resolveRedirectTo(query.redirect_to, url.origin, [req.headers.get("host"), (_req$headers$get = req.headers.get("x-forwarded-host")) === null || _req$headers$get === void 0 || (_req$headers$get = _req$headers$get.split(",")[0]) === null || _req$headers$get === void 0 ? void 0 : _req$headers$get.trim()]);
|
|
418
|
+
if (!resolved.ok) {
|
|
419
|
+
return {
|
|
420
|
+
status: 400,
|
|
421
|
+
json: {
|
|
422
|
+
message: resolved.message
|
|
423
|
+
}
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
query = {
|
|
427
|
+
...query,
|
|
428
|
+
redirect_to: resolved.href
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/*
|
|
433
|
+
* A throw from an endpoint is Val's to report, not the framework's.
|
|
434
|
+
*
|
|
435
|
+
* Nothing here used to catch, so an endpoint that threw left the router
|
|
436
|
+
* entirely and became whatever the host does with an unhandled error --
|
|
437
|
+
* and on TanStack Start that is h3, which replaces the message with the
|
|
438
|
+
* literal string "HTTPError" and drops the stack. Its `debug` and
|
|
439
|
+
* `silent` options are not reachable from out here: `requestHandler`
|
|
440
|
+
* calls `toResponse(value, event)` with no config, and the default is
|
|
441
|
+
* `{}`. So the body a caller got was
|
|
442
|
+
* `{"status":500,"unhandled":true,"message":"HTTPError"}` -- the same
|
|
443
|
+
* five words for a missing project, a bad cookie secret and a module
|
|
444
|
+
* that failed to link -- with the real cause only on the server's
|
|
445
|
+
* console.
|
|
446
|
+
*
|
|
447
|
+
* That is survivable where the console is readable. It is not in a
|
|
448
|
+
* Cloudflare Dynamic Worker, whose `console` reaches no tail stream: a
|
|
449
|
+
* link error in a lazily imported chunk (`does not provide an export
|
|
450
|
+
* named 'getSerovalPlugins'`) showed up as an unreadable 500 on
|
|
451
|
+
* `/authorize` and nowhere else at all.
|
|
452
|
+
*
|
|
453
|
+
* So every endpoint's throw becomes Val's own 500 envelope, which the
|
|
454
|
+
* Studio already renders and `curl` already prints. The route and method
|
|
455
|
+
* are named because a message rarely says which endpoint it came from.
|
|
456
|
+
*
|
|
457
|
+
* The MESSAGE travels and the STACK does not. The message is the whole
|
|
458
|
+
* diagnostic value -- the line above names the package, the chunk and
|
|
459
|
+
* the export -- while a stack is a walk through somebody's bundle, and
|
|
460
|
+
* `/authorize` and `/enable` are reachable without a session. So the
|
|
461
|
+
* stack goes to the console, where a host that can read one will find
|
|
462
|
+
* it, and the body carries what a caller can act on.
|
|
463
|
+
*/
|
|
464
|
+
let res;
|
|
465
|
+
try {
|
|
466
|
+
res = await endpointImpl({
|
|
467
|
+
body: bodyRes.data,
|
|
468
|
+
cookies: cookiesRes.data,
|
|
469
|
+
headers: headersRes.data,
|
|
470
|
+
rawQuery: reqDefinition.rawQuery ? url.search : undefined,
|
|
471
|
+
query,
|
|
472
|
+
path
|
|
473
|
+
});
|
|
474
|
+
} catch (err) {
|
|
475
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
476
|
+
core.Internal.log.error(`${method} ${route} threw: ${error.message}`, error.stack);
|
|
477
|
+
return {
|
|
478
|
+
status: 500,
|
|
479
|
+
json: {
|
|
480
|
+
message: `Val: ${method} ${route} failed: ${error.message}`,
|
|
481
|
+
details: {
|
|
482
|
+
route,
|
|
483
|
+
method,
|
|
484
|
+
error: error.message
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
const resDef = apiEndpoint.res;
|
|
490
|
+
if (res.status === 500) {
|
|
491
|
+
var _res$json;
|
|
492
|
+
/*
|
|
493
|
+
* A failure the route declares goes out as declared, as a success
|
|
494
|
+
* does below. DELETE /patches says which change was not discarded and
|
|
495
|
+
* which publish holds it, and collapsed to its message the Studio
|
|
496
|
+
* could only say "Failed to delete patches" -- not why, nor offer to
|
|
497
|
+
* cancel that publish. Anything undeclared is still reduced to its
|
|
498
|
+
* message.
|
|
499
|
+
*/
|
|
500
|
+
if (resDef !== null && resDef !== void 0 && resDef.safeParse(res).success) return res;
|
|
501
|
+
return {
|
|
502
|
+
status: 500,
|
|
503
|
+
json: {
|
|
504
|
+
message: ((_res$json = res.json) === null || _res$json === void 0 ? void 0 : _res$json.message) || "Internal Server Error"
|
|
505
|
+
}
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
if (resDef) {
|
|
509
|
+
const responseResult = resDef.safeParse(res);
|
|
510
|
+
if (!responseResult.success) {
|
|
511
|
+
return {
|
|
512
|
+
status: 500,
|
|
513
|
+
json: {
|
|
514
|
+
message: "Could not validate response. This is likely a bug in Val server.",
|
|
515
|
+
details: {
|
|
516
|
+
response: res,
|
|
517
|
+
errors: formatZodErrorString(responseResult.error)
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
return res;
|
|
524
|
+
}
|
|
525
|
+
if (path.startsWith("/static")) {
|
|
526
|
+
if (!serveStatic) {
|
|
527
|
+
return convert({
|
|
528
|
+
status: 404,
|
|
529
|
+
json: {
|
|
530
|
+
message: "Val: this server does not serve the Studio's own files"
|
|
531
|
+
}
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
return convert(await serveStatic(path.slice("/static".length), url.href));
|
|
535
|
+
} else {
|
|
536
|
+
return convert(await getValServerResponse(path, req));
|
|
537
|
+
}
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
function formatZodErrorString(error) {
|
|
541
|
+
const errors = zodValidationError.fromError(error).toString();
|
|
542
|
+
return errors.length > 640 ? `${errors.slice(0, 640)}...` : errors;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/**
|
|
546
|
+
* The request's JSON body, or `undefined` when it has none.
|
|
547
|
+
*
|
|
548
|
+
* `req.json()` THROWS on an empty body, and the router used to call it
|
|
549
|
+
* unconditionally for any route that declares a body — so the moment
|
|
550
|
+
* `DELETE /patches` gained an optional body, every caller that sent none got
|
|
551
|
+
* `400 Could not parse request body`. Declaring the schema `.optional()` did
|
|
552
|
+
* not help: the throw happens before zod is ever consulted. Six e2e tests went
|
|
553
|
+
* red on a helper doing exactly what the route still permits.
|
|
554
|
+
*
|
|
555
|
+
* Told apart by the request rather than by catching, so a body that IS sent and
|
|
556
|
+
* is malformed still fails: absent means no content type and nothing to read,
|
|
557
|
+
* and anything else is parsed and allowed to throw. A route whose schema
|
|
558
|
+
* requires a body is unaffected — it gets `undefined` and zod refuses it, with
|
|
559
|
+
* the same 400 as before, now naming the field.
|
|
560
|
+
*/
|
|
561
|
+
async function readJsonBody(req) {
|
|
562
|
+
if (req.headers.get("content-length") === "0") {
|
|
563
|
+
return undefined;
|
|
564
|
+
}
|
|
565
|
+
const text = await req.text();
|
|
566
|
+
if (text.length === 0) {
|
|
567
|
+
return undefined;
|
|
568
|
+
}
|
|
569
|
+
return JSON.parse(text);
|
|
570
|
+
}
|
|
571
|
+
function zodErrorResult(error, message) {
|
|
572
|
+
return {
|
|
573
|
+
status: 400,
|
|
574
|
+
json: {
|
|
575
|
+
message: "Bad Request: " + message,
|
|
576
|
+
details: {
|
|
577
|
+
errors: formatZodErrorString(error)
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
// TODO: is this naive implementation is too naive?
|
|
584
|
+
/** The declared headers, by name; `Headers.get` is case-insensitive. */
|
|
585
|
+
function getHeaders(req, headersDef) {
|
|
586
|
+
const input = {};
|
|
587
|
+
for (const name of Object.keys(headersDef)) {
|
|
588
|
+
var _req$headers;
|
|
589
|
+
const value = (_req$headers = req.headers) === null || _req$headers === void 0 ? void 0 : _req$headers.get(name);
|
|
590
|
+
if (value !== null && value !== undefined) {
|
|
591
|
+
input[name] = value;
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
return z.z.object(headersDef).safeParse(input);
|
|
595
|
+
}
|
|
596
|
+
function getCookies(req, cookiesDef) {
|
|
597
|
+
var _req$headers2;
|
|
598
|
+
const input = {};
|
|
599
|
+
const cookieParts = (_req$headers2 = req.headers) === null || _req$headers2 === void 0 || (_req$headers2 = _req$headers2.get("Cookie")) === null || _req$headers2 === void 0 ? void 0 : _req$headers2.split("; ");
|
|
600
|
+
for (const name of Object.keys(cookiesDef)) {
|
|
601
|
+
const cookie = cookieParts === null || cookieParts === void 0 ? void 0 : cookieParts.find(cookie => cookie.startsWith(`${name}=`));
|
|
602
|
+
const value = cookie ? decodeURIComponent(cookie === null || cookie === void 0 ? void 0 : cookie.split("=")[1]) : undefined;
|
|
603
|
+
if (value) {
|
|
604
|
+
input[name.trim()] = value;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
return z.z.object(cookiesDef).safeParse(input);
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
exports.createValRequestHandler = createValRequestHandler;
|
|
611
|
+
exports.parseAllowedHosts = parseAllowedHosts;
|
|
612
|
+
exports.setRequestGuard = setRequestGuard;
|