-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathmiddleware.ts
More file actions
457 lines (424 loc) · 15 KB
/
middleware.ts
File metadata and controls
457 lines (424 loc) · 15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
// deno-lint-ignore-file no-explicit-any
import { HTTPException } from "@hono/hono/http-exception";
import { DECO_MATCHER_HEADER_QS } from "../blocks/matcher.ts";
import { Context, context } from "../deco.ts";
import {
type Exception,
getCookies,
getSetCookies,
SpanStatusCode,
} from "../deps.ts";
import { startObserve } from "../observability/http.ts";
import { logger } from "../observability/mod.ts";
import { HttpError } from "../runtime/errors.ts";
import type { AppManifest } from "../types.ts";
import { isAdminOrLocalhost } from "../utils/admin.ts";
import { decodeCookie, setCookie } from "../utils/cookies.ts";
import { allowCorsFor } from "../utils/http.ts";
import { formatLog } from "../utils/log.ts";
import { tryOrDefault } from "../utils/object.ts";
import type {
Context as HonoContext,
ContextRenderer,
Handler,
Input,
MiddlewareHandler,
} from "./deps.ts";
import { setLogger } from "./fetch/fetchLog.ts";
import { liveness } from "./middlewares/liveness.ts";
import type { Deco, State } from "./mod.ts";
export const DECO_SEGMENT = "deco_segment";
export const proxyState = (
ctx: DecoMiddlewareContext & { params?: Record<string, string> },
) => {
const ctxSetter = {
set(_: any, prop: any, newValue: any) {
ctx.set(prop, newValue);
return true;
},
get: (val: any, prop: any, recv: any) => Reflect.get(val, prop, recv),
};
return {
...ctx,
params: ctx.params ?? ctx.req.param(),
get state() {
return new Proxy(ctx.var, ctxSetter);
},
};
};
export type DecoMiddleware<TManifest extends AppManifest = AppManifest> =
MiddlewareHandler<DecoRouteState<TManifest>>;
export type DecoRouteState<TManifest extends AppManifest = AppManifest> = {
Variables: State<TManifest>;
Bindings: {
RENDER_FN?: ContextRenderer;
GLOBALS?: unknown;
};
};
export type HonoHandler<TManifest extends AppManifest = AppManifest> = Handler<
DecoRouteState<TManifest>
>;
export type DecoHandler<TManifest extends AppManifest = AppManifest> = (
c: Parameters<HonoHandler<TManifest>>[0] & { render: ContextRenderer },
n: Parameters<HonoHandler<TManifest>>[1],
) => ReturnType<HonoHandler<TManifest>>;
export type DecoMiddlewareContext<
TManifest extends AppManifest = AppManifest,
P extends string = any,
// deno-lint-ignore ban-types
I extends Input = {},
> = HonoContext<DecoRouteState<TManifest>, P, I> & { render: ContextRenderer };
export const createHandler = <TManifest extends AppManifest = AppManifest>(
handler: DecoHandler<TManifest>,
): DecoHandler<TManifest> =>
async (ctx, next) => {
try {
return await handler(ctx, next);
} catch (_err) {
const err = _err as { stack?: string; message?: string };
if (err instanceof HttpError) {
return err.resp;
}
const correlationId = ctx.var.correlationId ?? crypto.randomUUID();
console.error(`route error ${ctx.req.routePath}: ${err}`, {
correlationId,
});
logger.error(`route ${ctx.req.routePath}: ${err?.stack}`, {
correlationId,
});
throw new HTTPException(500, {
res: new Response(err?.message ?? `Something went wrong`, {
status: 500,
headers: {
"x-correlation-Id": correlationId,
},
}),
});
}
};
const DEBUG_COOKIE = "deco_debug";
const DEBUG_ENABLED = "enabled";
const PAGE_CACHE_DRY_RUN = Deno.env.get("DECO_PAGE_CACHE_DRY_RUN") === "true";
export const DEBUG_QS = "__d";
const addHours = (date: Date, h: number) => {
date.setTime(date.getTime() + h * 60 * 60 * 1000);
return date;
};
export type DebugAction = (resp: Response) => void | Promise<void>;
export const DEBUG = {
none: (_resp: Response) => {},
enable: (resp: Response) => {
setCookie(resp.headers, {
name: DEBUG_COOKIE,
value: DEBUG_ENABLED,
expires: addHours(new Date(), 1),
});
},
disable: (resp: Response) => {
setCookie(resp.headers, {
name: DEBUG_COOKIE,
value: "",
expires: new Date("Thu, 01 Jan 1970 00:00:00 UTC"),
});
},
fromRequest: (
request: Request,
): { action: DebugAction; enabled: boolean; correlationId: string } => {
const url = new URL(request.url);
const debugFromCookies = getCookies(request.headers)[DEBUG_COOKIE];
const debugFromQS = (url.searchParams.has(DEBUG_QS) && DEBUG_ENABLED) ||
url.searchParams.get(DEBUG_COOKIE);
const hasDebugFromQS = debugFromQS !== null;
const isLivePreview = url.pathname.includes("/live/previews/");
const enabled = (debugFromQS ?? debugFromCookies) === DEBUG_ENABLED ||
isLivePreview;
const correlationId = url.searchParams.get(DEBUG_QS) || crypto.randomUUID();
const liveContext = Context.active();
// querystring forces a setcookie using the querystring value
return {
action: hasDebugFromQS || isLivePreview
? enabled
? async (resp) => {
DEBUG.enable(resp);
resp.headers.set("x-correlation-id", correlationId);
resp.headers.set(
"x-deno-os-uptime-seconds",
`${Deno.osUptime()}`,
);
resp.headers.set(
"x-deco-revision",
`${(await liveContext.release?.revision()) ?? ""}`,
);
resp.headers.set(
"x-isolate-started-at",
`${liveContext.instance.startedAt.toISOString()}`,
);
liveContext.instance.readyAt &&
resp.headers.set(
"x-isolate-ready-at",
`${liveContext.instance.readyAt.toISOString()}`,
);
}
: DEBUG.disable
: DEBUG.none,
enabled,
correlationId,
};
},
};
const wellKnownMonitoringRobotsUA = [
"Mozilla/5.0 (compatible; monitoring360bot/1.1; +http://www.monitoring360.io/bot.html)",
"Mozilla/5.0+(compatible; UptimeRobot/2.0; http://www.uptimerobot.com/)",
];
const isMonitoringRobots = (req: Request) => {
const ua = req.headers.get("user-agent");
if (!ua) {
return false;
}
return wellKnownMonitoringRobotsUA.some((robot) => ua.includes(robot));
};
/**
* @description server-timing separator.
*/
const SERVER_TIMING_SEPARATOR: string = ",";
/**
* @description max length of server-timing header.
*/
const SERVER_TIMING_MAX_LEN: number = 2_000;
/**
* @description return server-timing string equal or less than size parameter.
* if timings.length > size then return the timing until the well-formed timing that's smaller than size.
*/
const reduceServerTimingsTo = (timings: string, size: number): string => {
if (timings.length <= size) return timings;
return timings.substring(
0,
timings.lastIndexOf(SERVER_TIMING_SEPARATOR, size),
);
};
export const middlewareFor = <TAppManifest extends AppManifest = AppManifest>(
deco: Deco<TAppManifest>,
): DecoMiddleware<TAppManifest>[] => {
return [
// 0 => liveness
liveness,
// 1 => statebuilder
async (ctx, next) => {
const { enabled, action, correlationId } = DEBUG.fromRequest(ctx.req.raw);
//@ts-expect-error: ctx.base dont exist in hono ctx
ctx.base = ctx.var.global;
const state = await deco.prepareState(ctx, {
enabled,
correlationId,
});
for (const [key, value] of Object.entries(state)) {
ctx.set(key as keyof typeof state, value);
}
const url = new URL(ctx.req.raw.url);
const isEchoRoute = url.pathname.startsWith("/live/_echo"); // echoing
if (isEchoRoute) {
return new Response(ctx.req.raw.body, {
status: 200,
headers: ctx.req.raw.headers,
});
}
await next();
// enable or disable debugging
if (ctx.req.raw.headers.get("upgrade") === "websocket") {
return;
}
ctx.res && (await action(ctx.res));
setLogger(null);
},
// 2 => observability
async (ctx, next) => {
const url = new URL(ctx.req.raw.url); // TODO(mcandeia) check if ctx.url can be used here
const context = Context.active();
await ctx.var.monitoring.tracer.startActiveSpan(
"./routes/_middleware.ts",
{
attributes: {
"deco.site.name": context.site,
"http.request.url": ctx.req.raw.url,
"http.request.method": ctx.req.raw.method,
"http.request.body.size":
ctx.req.raw.headers.get("content-length") ?? undefined,
"url.scheme": url.protocol,
"server.address": url.host,
"url.query": url.search,
"url.path": url.pathname,
"user_agent.original": ctx.req.raw.headers.get("user-agent") ??
undefined,
"request.internal": ctx.req.raw.headers.has("traceparent"),
},
},
ctx.var.monitoring.context,
async (span) => {
ctx.var.monitoring.rootSpan = span;
const begin = performance.now();
const end = startObserve();
try {
await next();
} catch (e) {
span.recordException(e as Exception);
throw e;
} finally {
const status = ctx.res?.status ?? 500;
const isErr = status >= 500;
span.setStatus({
code: isErr ? SpanStatusCode.ERROR : SpanStatusCode.OK,
});
span.setAttribute("http.response.status_code", `${status}`);
if (ctx?.var?.pathTemplate) {
const route = `${ctx.req.raw.method} ${ctx?.var?.pathTemplate}`;
span.updateName(route);
span.setAttribute("http.route", route);
end?.(
ctx.req.raw.method,
ctx?.var?.pathTemplate,
ctx.res?.status ?? 500,
);
} else {
span.updateName(`${ctx.req.raw.method} ${ctx.req.raw.url}`);
}
span.end();
if (!url.pathname.startsWith("/_frsh")) {
console.info(
formatLog({
status: ctx.res?.status ?? 500,
url,
begin,
timings: ctx.var.debugEnabled
? ctx.var.monitoring.timings.get()
: undefined,
}),
);
}
}
},
);
},
// 3 => main
async (ctx, next) => {
if (ctx.req.raw.method === "HEAD" && isMonitoringRobots(ctx.req.raw)) {
return (ctx.res = new Response(null, { status: 200 }));
}
const url = new URL(ctx.req.raw.url); // TODO(mcandeia) check if ctx.url can be used here
const shouldAllowCorsForOptions = ctx.req.raw.method === "OPTIONS" &&
isAdminOrLocalhost(ctx.req.raw);
const initialResponse = shouldAllowCorsForOptions
? new Response()
: await next().then(() => ctx.res!);
// Let rendering occur — handlers are responsible for calling ctx.var.loadPage
if (ctx.req.raw.headers.get("upgrade") === "websocket") {
// for some reason hono deletes content-type when response is not fresh.
// which means that sometimes it will fail as headers are immutable.
// so I'm first setting it to undefined and just then set the entire response again
ctx.res = undefined;
return (ctx.res = initialResponse);
}
const newHeaders = new Headers(initialResponse.headers);
context.platform && newHeaders.set("x-deco-platform", context.platform);
if (
(url.pathname.startsWith("/live/previews") &&
url.searchParams.has("mode") &&
url.searchParams.get("mode") == "showcase") ||
url.pathname.startsWith("/_frsh/") ||
shouldAllowCorsForOptions
) {
Object.entries(allowCorsFor(ctx.req.raw)).map(([name, value]) => {
newHeaders.set(name, value);
});
}
ctx.var.response.headers.forEach((value, key) =>
newHeaders.append(key, value)
);
const printTimings = ctx?.var?.t?.printTimings;
const printedTimings = printTimings &&
reduceServerTimingsTo(printTimings(), SERVER_TIMING_MAX_LEN);
printedTimings && newHeaders.set("Server-Timing", printedTimings);
const responseStatus = ctx.var.response.status ?? initialResponse.status;
if (
url.pathname.startsWith("/_frsh/") &&
[400, 404, 500].includes(responseStatus)
) {
newHeaders.set("Cache-Control", "no-cache, no-store, private");
}
if (ctx?.var?.debugEnabled) {
for (const flag of ctx.var?.flags ?? []) {
newHeaders.append(
DECO_MATCHER_HEADER_QS,
`${flag.name}=${flag.value ? 1 : 0}`,
);
}
}
if (ctx.var?.flags.length > 0) {
const currentCookies = getCookies(ctx.req.raw.headers);
const cookieSegment = tryOrDefault(
() => decodeCookie(currentCookies[DECO_SEGMENT]),
"",
);
const segment = tryOrDefault(() => JSON.parse(cookieSegment), {});
const active = new Set(segment.active || []);
const inactiveDrawn = new Set(segment.inactiveDrawn || []);
for (const flag of ctx.var.flags) {
if (flag.isSegment) {
if (flag.value) {
active.add(flag.name);
inactiveDrawn.delete(flag.name);
} else {
active.delete(flag.name);
inactiveDrawn.add(flag.name);
}
}
}
const newSegment = {
active: [...active].sort(),
inactiveDrawn: [...inactiveDrawn].sort(),
};
const value = JSON.stringify(newSegment);
const hasFlags = active.size > 0 || inactiveDrawn.size > 0;
if (hasFlags && cookieSegment !== value) {
const date = new Date();
date.setTime(date.getTime() + 30 * 24 * 60 * 60 * 1000); // 1 month
setCookie(
newHeaders,
{
name: DECO_SEGMENT,
value,
path: "/",
expires: date,
sameSite: "Lax",
},
{ encode: true },
);
}
}
// If response has set-cookie header, set cache-control to no-store
if (getSetCookies(newHeaders).length > 0) {
newHeaders.set("Cache-Control", "no-store, no-cache, must-revalidate");
} else if (!ctx.var.dirty) {
if (PAGE_CACHE_DRY_RUN) {
console.warn(`[page-cache] cacheable: ${url.pathname}`);
} else {
newHeaders.set("Cache-Control", "public, max-age=120, s-maxage=120");
}
} else if (PAGE_CACHE_DRY_RUN) {
console.warn(
`[page-cache] not cacheable (cookies accessed): ${url.pathname}`,
);
for (const trace of ctx.var.dirtyTraces ?? []) {
console.warn(`[page-cache] trace:\n${trace}`);
}
}
// for some reason hono deletes content-type when response is not fresh.
// which means that sometimes it will fail as headers are immutable.
// so I'm first setting it to undefined and just then set the entire response again
ctx.res = undefined;
ctx.res = new Response(initialResponse.body, {
status: responseStatus,
headers: newHeaders,
});
},
];
};