@elumixor/devkit 0.12.18 → 0.12.19

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@elumixor/devkit",
3
- "version": "0.12.18",
3
+ "version": "0.12.19",
4
4
  "description": "Dev orchestrator for bun monorepos — free ports, run apps side-by-side, open the browser when ready",
5
5
  "author": "elumixor",
6
6
  "license": "ISC",
@@ -12,6 +12,7 @@ var EDGE_SECRET_KEY = "_edge";
12
12
  var EDGE_HEADER = "x-dk-edge";
13
13
  var HOST_HEADER = "x-dk-host";
14
14
  var PROJECT_HEADER = "x-dk-project";
15
+ var STATUS_HEADER = "x-dk-status";
15
16
  var BLOB_PREFIX = "/_blob/";
16
17
  var SSR_ASSETS_PREFIX = "/_app/";
17
18
  var HEADERS_PREFIX = "_h/";
@@ -94,6 +95,21 @@ function staticPath(uri, mode) {
94
95
  var REMAPPED_PREFIX = "x-amzn-remapped-";
95
96
  var RESTORED = ["www-authenticate"];
96
97
 
98
+ // CloudFront runs this function only on origin statuses below 400, so the function sends an error
99
+ // that carries WWW-Authenticate as 200 with the real status in STATUS_HEADER.
100
+ function restoreStatus(response) {
101
+ var header = response.headers[STATUS_HEADER];
102
+ if (!header) return;
103
+ delete response.headers[STATUS_HEADER];
104
+ var status = parseInt(header.value, 10);
105
+ if (status >= 400 && status < 600) {
106
+ response.statusCode = status;
107
+ response.statusDescription = STATUS_TEXT[status] || "Error";
108
+ }
109
+ }
110
+
111
+ var STATUS_TEXT = { 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 500: "Internal Server Error" };
112
+
97
113
  function restoreRemapped(headers) {
98
114
  for (var i = 0; i < RESTORED.length; i++) {
99
115
  var remapped = REMAPPED_PREFIX + RESTORED[i];
@@ -108,6 +124,7 @@ function restoreRemapped(headers) {
108
124
  async function withHeaders(event) {
109
125
  var response = event.response;
110
126
  restoreRemapped(response.headers);
127
+ restoreStatus(response);
111
128
  var request = event.request;
112
129
  var host = request.headers.host ? request.headers.host.value.toLowerCase() : "";
113
130
  try {
@@ -39,3 +39,14 @@ test("restores the header even when the host has no route", async () => {
39
39
  const response = await handler(viewerResponse({ "x-amzn-remapped-www-authenticate": { value: "Bearer" } }));
40
40
  expect(response.headers["www-authenticate"]).toEqual({ value: "Bearer" });
41
41
  });
42
+
43
+ test("puts back the error status the function sent as 200", async () => {
44
+ delete store["api.example.com"];
45
+ const event = viewerResponse({ "x-amzn-remapped-www-authenticate": { value: "Bearer" }, "x-dk-status": { value: "401" } });
46
+ event.response.statusCode = 200;
47
+ const response = await handler(event);
48
+ expect(response.statusCode).toBe(401);
49
+ expect(response.statusDescription).toBe("Unauthorized");
50
+ expect(response.headers["x-dk-status"]).toBeUndefined();
51
+ expect(response.headers["www-authenticate"]).toEqual({ value: "Bearer" });
52
+ });
@@ -59,6 +59,11 @@ export const headersKey = (project: string, deployPath: string) => `_h/${project
59
59
  export const HOST_HEADER = "x-dk-host";
60
60
  /** Set by the router per request so two projects' identical API paths never share a cache entry. */
61
61
  export const PROJECT_HEADER = "x-dk-project";
62
+ /**
63
+ * The real status of an error response the function sent as 200, because CloudFront runs no
64
+ * viewer-response function on an origin status of 400 or higher. The router puts it back.
65
+ */
66
+ export const STATUS_HEADER = "x-dk-status";
62
67
 
63
68
  /** Resources that exist once per project and stage. */
64
69
  export const stage = {
@@ -0,0 +1,42 @@
1
+ import { expect, test } from "bun:test";
2
+ import { mkdtempSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { RUNTIME_WRAPPER, WRAPPER_FILE } from "./runtime-wrapper.ts";
6
+
7
+ type Prelude = { statusCode?: number; headers?: Record<string, string> };
8
+
9
+ // The wrapper imports Nitro's handler from ./index.mjs: a stand-in answers with the prelude a test sets.
10
+ const dir = mkdtempSync(join(tmpdir(), "dk-wrapper-"));
11
+ await Bun.write(
12
+ join(dir, "index.mjs"),
13
+ "export const handler = (event, stream) => awslambda.HttpResponseStream.from(stream, globalThis.nitroPrelude);",
14
+ );
15
+ await Bun.write(join(dir, WRAPPER_FILE), RUNTIME_WRAPPER);
16
+ process.env.DK_EDGE_SECRET = "secret";
17
+ Object.assign(globalThis, {
18
+ awslambda: {
19
+ streamifyResponse: (fn: unknown) => fn,
20
+ HttpResponseStream: { from: (stream: { prelude?: Prelude }, prelude: Prelude) => Object.assign(stream, { prelude }) },
21
+ },
22
+ });
23
+ const { handler } = await import(join(dir, WRAPPER_FILE));
24
+
25
+ async function respond(prelude: Prelude) {
26
+ Object.assign(globalThis, { nitroPrelude: prelude });
27
+ const stream: { prelude?: Prelude } = {};
28
+ await handler({ headers: { "x-dk-edge": "secret" } }, stream, {});
29
+ return stream.prelude;
30
+ }
31
+
32
+ test("sends a 401 with WWW-Authenticate as 200 carrying the real status", async () => {
33
+ const prelude = await respond({ statusCode: 401, headers: { "WWW-Authenticate": "Bearer" } });
34
+ expect(prelude).toEqual({ statusCode: 200, headers: { "WWW-Authenticate": "Bearer", "x-dk-status": "401" } });
35
+ });
36
+
37
+ test("leaves other responses alone", async () => {
38
+ const plain = { statusCode: 404, headers: { "content-type": "text/plain" } };
39
+ expect(await respond(plain)).toEqual(plain);
40
+ const ok = { statusCode: 200, headers: { "www-authenticate": "Bearer" } };
41
+ expect(await respond(ok)).toEqual(ok);
42
+ });
@@ -1,4 +1,4 @@
1
- import { EDGE_HEADER, HOST_HEADER } from "./names.ts";
1
+ import { EDGE_HEADER, HOST_HEADER, STATUS_HEADER } from "./names.ts";
2
2
 
3
3
  /** Where `@elumixor/devkit/runtime` finds the wrapper's `waitUntil` at run time. */
4
4
  export const WAIT_UNTIL_SYMBOL = "dk.waitUntil";
@@ -18,6 +18,7 @@ const EDGE_SECRET = process.env.DK_EDGE_SECRET;
18
18
  const CRON_SECRET = process.env.CRON_SECRET;
19
19
  const EDGE_HEADER = ${JSON.stringify(EDGE_HEADER)};
20
20
  const HOST_HEADER = ${JSON.stringify(HOST_HEADER)};
21
+ const STATUS_HEADER = ${JSON.stringify(STATUS_HEADER)};
21
22
  const pendingWork = new AsyncLocalStorage();
22
23
 
23
24
  globalThis[Symbol.for(${JSON.stringify(WAIT_UNTIL_SYMBOL)})] = (promise) => {
@@ -26,6 +27,19 @@ globalThis[Symbol.for(${JSON.stringify(WAIT_UNTIL_SYMBOL)})] = (promise) => {
26
27
  else console.warn("waitUntil called outside a request; the promise is not awaited");
27
28
  };
28
29
 
30
+ // The Function URL renames WWW-Authenticate, and CloudFront skips the router's viewer-response step
31
+ // (which renames it back) on any origin status of 400 or higher. So an error carrying the header
32
+ // goes out as 200 with its real status in STATUS_HEADER, and the router restores both.
33
+ const streamFrom = awslambda.HttpResponseStream.from;
34
+ awslambda.HttpResponseStream.from = (stream, prelude) => streamFrom.call(awslambda.HttpResponseStream, stream, errorAsOk(prelude));
35
+
36
+ function errorAsOk(prelude) {
37
+ const status = prelude?.statusCode ?? 200;
38
+ const headers = prelude?.headers;
39
+ if (status < 400 || !headers || !Object.keys(headers).some((name) => name.toLowerCase() === "www-authenticate")) return prelude;
40
+ return { ...prelude, statusCode: 200, headers: { ...headers, [STATUS_HEADER]: String(status) } };
41
+ }
42
+
29
43
  export const handler = awslambda.streamifyResponse(async (rawEvent, responseStream, context) => {
30
44
  const event = rawEvent.dk === "cron" ? cronRequest(rawEvent) : rawEvent;
31
45
  if (!EDGE_SECRET || event.headers?.[EDGE_HEADER] !== EDGE_SECRET) return reject(responseStream, 403, "Forbidden");