Skip to content

Commit

Permalink
Add option to have miniflare accept https requests
Browse files Browse the repository at this point in the history
  • Loading branch information
jspspike committed Jun 26, 2023
1 parent 5d1eba3 commit b1b8adf
Show file tree
Hide file tree
Showing 5 changed files with 48 additions and 12 deletions.
17 changes: 14 additions & 3 deletions packages/miniflare/src/http/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import http from "http";
import { Headers, RequestInfo, fetch as baseFetch } from "undici";
import { Agent, Headers, RequestInfo, fetch as baseFetch } from "undici";
import NodeWebSocket from "ws";
import { DeferredPromise } from "../shared";
import { Request, RequestInit } from "./request";
import { Response } from "./response";
import { WebSocketPair, coupleWebSocket } from "./websocket";

export const allowUnauthorizedAgent = new Agent({
connect: { rejectUnauthorized: false },
});

const ignored = ["transfer-encoding", "connection", "keep-alive", "expect"];
function headersFromIncomingRequest(req: http.IncomingMessage): Headers {
const entries = Object.entries(req.headers).filter(
Expand All @@ -21,7 +25,8 @@ export async function fetch(
input: RequestInfo,
init?: RequestInit | Request
): Promise<Response> {
const request = new Request(input, init as RequestInit);
const requestInit = init as RequestInit;
const request = new Request(input, requestInit);

// Handle WebSocket upgrades
if (
Expand All @@ -48,10 +53,16 @@ export async function fetch(
}
}

const rejectUnauthorized =
requestInit.dispatcher === allowUnauthorizedAgent
? { rejectUnauthorized: false }
: {};

// Establish web socket connection
const ws = new NodeWebSocket(url, protocols, {
followRedirects: request.redirect === "follow",
headers,
...rejectUnauthorized,
});

// Get response headers from upgrade
Expand All @@ -70,6 +81,6 @@ export async function fetch(
});
}

const response = await baseFetch(request);
const response = await baseFetch(request, requestInit);
return new Response(response.body, response);
}
15 changes: 13 additions & 2 deletions packages/miniflare/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
Request,
RequestInit,
Response,
allowUnauthorizedAgent,
configureEntrySocket,
coupleWebSocket,
fetch,
Expand Down Expand Up @@ -790,9 +791,13 @@ export class Miniflare {
"There is likely additional logging output above."
);
}

const entrySocket = config.sockets?.[0];
const secure = entrySocket !== undefined && "https" in entrySocket;

// noinspection HttpUrlsUsage
this.#runtimeEntryURL = new URL(
`http://${this.#accessibleHost}:${maybePort}`
`${secure ? "https" : "http"}://${this.#accessibleHost}:${maybePort}`
);

if (!this.#runtimeMutex.hasWaiting) {
Expand Down Expand Up @@ -856,6 +861,7 @@ export class Miniflare {
dispatchFetch: DispatchFetch = async (input, init) => {
this.#checkDisposed();
await this.ready;

const forward = new Request(input, init);
const url = new URL(forward.url);
forward.headers.set(CoreHeaders.ORIGINAL_URL, url.toString());
Expand All @@ -874,7 +880,12 @@ export class Miniflare {
forward.headers.delete("Content-Length");
}

const response = await fetch(url, forward as RequestInit);
const forwardInit = forward as RequestInit;
if (url.protocol === "https:") {
forwardInit.dispatcher = allowUnauthorizedAgent;
}

const response = await fetch(url, forwardInit);

// If the Worker threw an uncaught exception, propagate it to the caller
const stack = response.headers.get(CoreHeaders.ERROR_STACK);
Expand Down
5 changes: 0 additions & 5 deletions packages/miniflare/src/plugins/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,6 @@ export const CoreOptionsSchema = z.intersection(
})
);

export interface KeyPair {
key: string;
cert: string;
}

export const CoreSharedOptionsSchema = z.object({
host: z.string().optional(),
port: z.number().optional(),
Expand Down
1 change: 0 additions & 1 deletion packages/miniflare/src/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@ export type {
ModuleDefinition,
GlobalServicesOptions,
SourceOptions,
KeyPair,
} from "./core";
export * from "./d1";
export * from "./do";
Expand Down
22 changes: 21 additions & 1 deletion packages/miniflare/test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
MessageEvent as StandardMessageEvent,
WebSocketServer,
} from "ws";
import { useServer } from "./test-shared";
import { TestLog, useServer } from "./test-shared";

test("Miniflare: validates options", async (t) => {
// Check empty workers array rejected
Expand Down Expand Up @@ -324,3 +324,23 @@ test("Miniflare: HTTPS fetches using browser CA certificates", async (t) => {
const res = await mf.dispatchFetch("http://localhost");
t.true(res.ok);
});

test("Miniflare: Accepts https requests", async (t) => {
const log = new TestLog(t);

const mf = new Miniflare({
log,
modules: true,
https: true,
script: `export default {
fetch() {
return new Response("Hello world");
}
}`,
});

const res = await mf.dispatchFetch("https://localhost");
t.true(res.ok);

t.assert(log.logs[0][1].startsWith("Ready on https://"));
});

0 comments on commit b1b8adf

Please sign in to comment.