Spaces:
Running

File size: 3,912 Bytes
914a36d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import {
  type Agent,
  createServer,
  type IncomingMessage,
  request,
  type ServerResponse,
} from "node:http";
import type { AddressInfo } from "node:net";
import { expect, vi } from "vitest";

/** The middleware an endpoint hook mounted on `server.middlewares`. */
export type HookHandler = (
  request: IncomingMessage,
  response: ServerResponse,
  next: () => void,
) => Promise<void>;

/** A request carrying only the fields the endpoint hooks read. */
export function createRequest(url: string): IncomingMessage {
  return {
    url,
    headers: { host: "localhost:3000" },
  } as unknown as IncomingMessage;
}

/** A request whose `Host` header cannot be parsed. */
function createRequestWithBadHost(url: string): IncomingMessage {
  return { url, headers: { host: "bad host" } } as unknown as IncomingMessage;
}

/** A response that records `setHeader` and `end` instead of writing. */
export function createResponse() {
  return {
    statusCode: 200,
    setHeader: vi.fn(),
    end: vi.fn(),
  } as unknown as ServerResponse & {
    setHeader: ReturnType<typeof vi.fn>;
    end: ReturnType<typeof vi.fn>;
  };
}

/**
 * Registers `hook` on a fake server and returns the middleware it mounted.
 * The fake only needs `middlewares.use`, so the hook's real server type is
 * cast away here rather than repeated in every hook test file.
 */
export function getRegisteredHookHandler<S>(
  hook: (server: S) => void,
): HookHandler {
  const use = vi.fn();
  hook({ middlewares: { use } } as unknown as S);
  return use.mock.calls[0][0] as HookHandler;
}

/**
 * Runs `hook` on a real HTTP server on an ephemeral port, with a `next` that
 * answers 404. Only a real connection shows what a mid-upload refusal costs a
 * keep-alive caller, which is what the socket tests check.
 */
export async function startHookServer(
  hook: (server: never) => void,
): Promise<{ port: number; close: () => Promise<void> }> {
  const server = createServer((req, res) => {
    const middlewares = {
      use: (handler: (req: unknown, res: unknown, next: () => void) => void) =>
        handler(req, res, () => {
          res.statusCode = 404;
          res.end();
        }),
    };
    hook({ middlewares } as never);
  });
  await new Promise<void>((resolve) => server.listen(0, resolve));
  const port = (server.address() as AddressInfo).port;
  return {
    port,
    close: () => new Promise<void>((resolve) => server.close(() => resolve())),
  };
}

/**
 * POSTs `payload` to `path` and resolves with `status=<code>`, or
 * `error=<code>` when the socket itself failed, which is how a dropped
 * keep-alive connection reaches the caller.
 */
export function postThroughSocket(
  port: number,
  path: string,
  agent: Agent,
  payload: string | Buffer,
  headers: Record<string, string> = {},
): Promise<string> {
  return new Promise<string>((resolve) => {
    const req = request(
      { port, method: "POST", path, agent, headers },
      (res) => {
        res.resume();
        res.on("end", () => resolve(`status=${res.statusCode}`));
      },
    );
    req.on("error", (error) =>
      resolve(`error=${(error as NodeJS.ErrnoException).code}`),
    );
    req.end(payload);
  });
}

/**
 * Runs `handler` on a request whose `Host` header cannot be parsed, and checks
 * it answered 400 without verifying a token or handing the request to Vite. A
 * host that fails to parse must never reach the token check or the upstream.
 */
export async function expectBadHostRejected(
  handler: HookHandler,
  url: string,
  handleTokenVerification: (...args: never[]) => unknown,
): Promise<void> {
  const response = createResponse();
  const next = vi.fn();

  await expect(
    handler(createRequestWithBadHost(url), response, next),
  ).resolves.toBeUndefined();

  expect(response.statusCode).toBe(400);
  expect(handleTokenVerification).not.toHaveBeenCalled();
  expect(next).not.toHaveBeenCalled();
}