Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x 18x 1x 1x 1x 18x 18x 18x 1x 21x 21x 6x 3x 18x 18x 18x 23x 21x 21x 21x | import { mkdir, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import type { Nuxt } from "nuxt/schema";
import { defineNuxtModule } from "nuxt/kit";
const NAME = "staging-gate";
const gate = (publicHosts: string[]) => `const PUBLIC_HOSTS = ${JSON.stringify(publicHosts)};
const encode = (text) => btoa(String.fromCharCode(...new TextEncoder().encode(text)));
export default (request) => {
if (PUBLIC_HOSTS.includes(new URL(request.url).hostname)) return;
const username = Netlify.env.get("STAGING_USERNAME");
const password = Netlify.env.get("STAGING_PASSWORD");
const expected = "Basic " + encode(username + ":" + password);
if (username && password && request.headers.get("authorization") === expected) return;
return new Response("Unauthorized", {
status: 401,
headers: { "WWW-Authenticate": 'Basic realm="Huella Legal staging", charset="UTF-8"' },
});
};
`;
const GATED_HOSTS = String.raw`^(staging\..+|.+\.netlify\.app)$`;
const MANIFEST = {
version: 1,
functions: [
{
function: NAME,
name: "staging password",
path: "/*",
excludedPath: ["/_nuxt/*", "/_fonts/*", "/.netlify/*"],
header: { host: GATED_HOSTS },
},
],
};
const listPublicHosts = ({ runtimeConfig }: Nuxt["options"]): string[] => {
const { site } = runtimeConfig.public as { site: { url: string } };
const host = new URL(process.env.NUXT_PUBLIC_SITE_URL || site.url).hostname;
return [host, host.replace(/^www\./, "")];
};
const writeGate = async (dir: string, publicHosts?: string[]): Promise<void> => {
const files = [join(dir, `${NAME}.js`), join(dir, "manifest.json")];
// A production build's leftovers would gate a preview deployed from the same checkout
if (!publicHosts) {
await Promise.all(files.map((file) => rm(file, { force: true })));
return;
}
await mkdir(dir, { recursive: true });
await writeFile(files[0]!, gate(publicHosts));
await writeFile(files[1]!, JSON.stringify(MANIFEST, null, 2));
};
export default defineNuxtModule({
meta: { name: "staging-gate" },
setup: (_, { options, hook }) => {
if (options._prepare || options.dev) return;
hook("nitro:init", (nitro) => {
nitro.hooks.hook("compiled", () =>
writeGate(
join(nitro.options.rootDir, ".netlify/edge-functions"),
process.env.NUXT_SITE_ENV === "production"
? listPublicHosts(options)
: undefined,
),
);
});
},
});
|