Dough Git

clove/redirect

redirect.js

back to tree

/* redirect.js */

const destination = "https://doughmination.gay";

// How long the spinner shows before redirecting
const delayMs = 1200;

// Even stage 2n rolls for lock n, odd stage 2n+1 shows lock n; see the locks table at the bottom
const stageKey = "redirectStage";

// The cable must stay out this long or the replug fails
const minUnpluggedMs = 3000;

const captchaTileCount = 9;

const captchaFailMessages = [
  "Please try again.",
  "You missed a gear.",
  "Some of those squares are gears in disguise.",
  "Select ALL squares with gears.",
];

const overheat = {
  startTemperature: 70,
  minTemperature: 40,
  throttleTemperature: 85,
  shutdownTemperature: 100,
  heatPerSecond: 8,
  coolingPerTap: 6,
  bootSeconds: 10,
  tickMs: 100,
};

const bootDevices = [
  "Floppy Drive A:",
  "CD-ROM Drive",
  "Network Boot (PXE)",
  "USB Toaster",
  "Redirect Drive",
];

const targetDevice = "Redirect Drive";

const windowsUpdate = {
  tickMs: 500,
  stallChance: 0.4,
  maxStepPercent: 12,
  rebootDelayMs: 3000,
};

const laughedAtTools = [
  "pip",
  "pip3",
  "bun",
  "npm",
  "pnpm",
];

const laughLines = [
  "HAHAHAHA. {tool}? Adorable. uv and Deno are better.",
  "{tool}? In this decade? Use uv or Deno.",
  "Pfft. {tool}. uv and Deno are faster, use one of those.",
  "Imagine still using {tool}. uv and Deno exist.",
];

// Options (like --dev) may sit between the subcommand and the package
const uvInstall = /^uv (?:add|pip install|tool install)(?: -\S+)* (\S+)$/;

const denoInstall = /^deno (?:add|install|i)(?: -\S+)* (\S+)$/;

const decoyCount = 6;

const konamiCode = [
  "ArrowUp",
  "ArrowUp",
  "ArrowDown",
  "ArrowDown",
  "ArrowLeft",
  "ArrowRight",
  "ArrowLeft",
  "ArrowRight",
  "b",
  "a",
];

const flavourLines = [
  "Tightening the gears…",
  "Following the pink thread…",
  "Warming up the teapot…",
  "Rolling out the dough…",
  "Recalibrating the compass…",
  "Polishing the cogs…",
  "Asking the cat for directions…",
  "Untangling the marionette strings…",
];

const decoys = [
  {
    label: "Unplug network cable",
    message: "The server is now very calm and very offline. Still no power.",
  },
  {
    label: "Unplug monitor",
    message: "It's dark now. Nothing else changed.",
  },
  {
    label: "Press reset",
    message: "The reset button was decorative.",
  },
  {
    label: "Kick the rack",
    message: "Ow. Still no power.",
  },
  {
    label: "Blow on the cartridge",
    message: "Wrong decade.",
  },
  {
    label: "Turn fans to max",
    message: "The fans can't spin without power, genius.",
  },
  {
    label: "Unplug the toaster",
    message: "Breakfast is cancelled. Server still dead.",
  },
  {
    label: "Flip the breaker",
    message: "Everyone in the building is upset with you now.",
  },
  {
    label: "Hold power for 5s",
    message: "Nothing. Someone glued the button.",
  },
  {
    label: "Unplug keyboard",
    message: "You can't type now. Bold strategy.",
  },
];

// Keep the path and query, so fae.is-a.dev/foo goes to doughmination.gay/foo
const target = destination + location.pathname + location.search + location.hash;

document.getElementById("target").href = target;
document.getElementById("origin").textContent = location.hostname || "this link";
document.getElementById("flavour").textContent = pickRandom(flavourLines);

// Fallback when storage throws (private windows): stages last only this load
let memoryStage = 0;

function readStage() {
  try {
    // Visitors jammed by the first version keep their jam
    if (localStorage.getItem("redirectBroken") === "1") {
      localStorage.removeItem("redirectBroken");
      return 1;
    }

    return Math.floor(Number(localStorage.getItem(stageKey))) || 0;
  } catch {
    return memoryStage;
  }
}

function writeStage(stage) {
  memoryStage = stage;

  try {
    localStorage.setItem(stageKey, String(stage));
  } catch {}
}

function pickRandom(items) {
  return items[Math.floor(Math.random() * items.length)];
}

function shuffle(items) {
  const shuffled = [...items];

  for (let index = shuffled.length - 1; index > 0; index--) {
    const swapIndex = Math.floor(Math.random() * (index + 1));
    [shuffled[index], shuffled[swapIndex]] = [shuffled[swapIndex], shuffled[index]];
  }

  return shuffled;
}

function startRedirect() {
  setTimeout(
    () => location.replace(target),
    delayMs,
  );
}

function konamiLock(onSolved) {
  const listeners = new AbortController();
  const enteredKeys = [];

  function press(key) {
    enteredKeys.push(key);

    if (enteredKeys.length > konamiCode.length) {
      enteredKeys.shift();
    }

    if (enteredKeys.join() === konamiCode.join()) {
      listeners.abort();
      onSolved();
    }
  }

  document.addEventListener(
    "keydown",
    (event) => press(event.key.length === 1 ? event.key.toLowerCase() : event.key),
    { signal: listeners.signal },
  );

  for (const button of document.querySelectorAll("[data-key]")) {
    button.addEventListener(
      "click",
      () => press(button.dataset.key),
      { signal: listeners.signal },
    );
  }
}

function powerLock(onSolved) {
  const panel = document.getElementById("power-panel");
  const status = document.getElementById("power-status");
  const cable = document.createElement("button");
  let unpluggedAt = null;

  function plugBackIn() {
    unpluggedAt = null;
    cable.textContent = "Unplug power cable";
  }

  cable.type = "button";
  plugBackIn();

  cable.addEventListener("click", () => {
    if (unpluggedAt === null) {
      unpluggedAt = Date.now();
      cable.textContent = "Plug power cable back in";
      status.textContent = "The server is off. Give it a moment…";
      return;
    }

    if (Date.now() - unpluggedAt < minUnpluggedMs) {
      plugBackIn();
      status.textContent = "Too quick. The capacitors were still charged. Try again.";
      return;
    }

    status.textContent = "It's booting…";
    onSolved();
  });

  const decoyButtons = shuffle(decoys).slice(0, decoyCount).map((decoy) => {
    const button = document.createElement("button");
    button.type = "button";
    button.textContent = decoy.label;

    // Fiddling with anything else mid-cycle ruins the power cycle
    button.addEventListener("click", () => {
      plugBackIn();
      status.textContent = decoy.message;
    });

    return button;
  });

  panel.replaceChildren(...shuffle([cable, ...decoyButtons]));
}

function captchaLock(onSolved) {
  const grid = document.getElementById("captcha-grid");
  const status = document.getElementById("captcha-status");

  const tiles = Array.from({ length: captchaTileCount }, () => {
    const tile = document.createElement("button");
    tile.type = "button";
    tile.className = "captcha-tile";
    tile.textContent = "⚙";
    tile.setAttribute("aria-label", "Square");
    tile.setAttribute("aria-pressed", "false");

    // Random tilt and size so the tiles look like different photos
    tile.style.setProperty("--tilt", `${Math.floor(Math.random() * 360)}deg`);
    tile.style.setProperty("--size", `${(1.5 + Math.random() * 1.5).toFixed(2)}rem`);

    tile.addEventListener("click", () => {
      const isPressed = tile.getAttribute("aria-pressed") === "true";
      tile.setAttribute("aria-pressed", String(!isPressed));
    });

    return tile;
  });

  grid.replaceChildren(...tiles);

  document.getElementById("captcha-verify").addEventListener("click", () => {
    if (tiles.every((tile) => tile.getAttribute("aria-pressed") === "true")) {
      onSolved();
    } else {
      status.textContent = pickRandom(captchaFailMessages);
    }
  });

  document.getElementById("captcha-robot").addEventListener("click", () => {
    status.textContent = "That's exactly what a robot would say.";
  });

  document.getElementById("captcha-automaton").addEventListener("click", onSolved);
}

function overheatLock(onSolved) {
  const fan = document.getElementById("overheat-fan");
  const readout = document.getElementById("overheat-temperature");
  const progress = document.getElementById("overheat-progress");
  const status = document.getElementById("overheat-status");
  const tickSeconds = overheat.tickMs / 1000;
  let temperature = overheat.startTemperature;
  let bootedSeconds = 0;

  fan.addEventListener("click", () => {
    temperature = Math.max(
      overheat.minTemperature,
      temperature - overheat.coolingPerTap,
    );
  });

  const timer = setInterval(() => {
    temperature += overheat.heatPerSecond * tickSeconds;

    if (temperature >= overheat.shutdownTemperature) {
      temperature = overheat.startTemperature;
      bootedSeconds = 0;
      status.textContent = "Thermal shutdown! Boot restarted.";
    } else if (temperature < overheat.throttleTemperature) {
      bootedSeconds += tickSeconds;
      status.textContent = "Booting…";
    } else {
      status.textContent = "Throttling: too hot to boot.";
    }

    readout.textContent = `${Math.round(temperature)}°C`;
    readout.dataset.hot = String(temperature >= overheat.throttleTemperature);
    progress.value = bootedSeconds / overheat.bootSeconds;

    if (bootedSeconds >= overheat.bootSeconds) {
      clearInterval(timer);
      onSolved();
    }
  }, overheat.tickMs);
}

function biosLock(onSolved) {
  const intro = document.getElementById("bios-intro");
  const setup = document.getElementById("bios-setup");
  const list = document.getElementById("bios-boot-order");
  const status = document.getElementById("bios-status");
  const listeners = new AbortController();
  const order = shuffle(bootDevices);
  let selected = 0;
  let inSetup = false;

  // Never start already solved
  if (order[0] === targetDevice) {
    order.push(order.shift());
  }

  function render() {
    const rows = order.map((device, index) => {
      const row = document.createElement("button");
      row.type = "button";
      row.textContent = `${index + 1}. ${device}`;
      row.setAttribute("aria-pressed", String(index === selected));

      row.addEventListener("click", () => {
        selected = index;
        render();
      });

      return row;
    });

    list.replaceChildren(...rows);
  }

  function moveDevice(step) {
    const other = selected + step;

    if (other < 0 || other >= order.length) {
      return;
    }

    [order[selected], order[other]] = [order[other], order[selected]];
    selected = other;
    render();
  }

  const actions = {
    setup: () => {
      inSetup = true;
      intro.hidden = true;
      setup.hidden = false;
      render();
    },
    up: () => {
      selected = Math.max(0, selected - 1);
      render();
    },
    down: () => {
      selected = Math.min(order.length - 1, selected + 1);
      render();
    },
    raise: () => moveDevice(-1),
    lower: () => moveDevice(1),
    save: () => {
      if (order[0] === targetDevice) {
        listeners.abort();
        onSolved();
      } else {
        status.textContent = `Booting from ${order[0]}… Reboot and select proper boot device.`;
      }
    },
  };

  // "=" is "+" without shift
  const keyActions = {
    F2: "setup",
    Enter: "setup",
    ArrowUp: "up",
    ArrowDown: "down",
    "+": "raise",
    "=": "raise",
    "-": "lower",
    F10: "save",
  };

  document.addEventListener(
    "keydown",
    (event) => {
      const action = keyActions[event.key];
      const isAllowed = inSetup ? action !== "setup" : action === "setup";

      if (!action || !isAllowed) {
        return;
      }

      event.preventDefault();
      actions[action]();
    },
    { signal: listeners.signal },
  );

  for (const button of document.querySelectorAll("[data-bios-action]")) {
    button.addEventListener(
      "click",
      () => actions[button.dataset.biosAction](),
      { signal: listeners.signal },
    );
  }
}

function windowsLock(onSolved) {
  const progress = document.getElementById("windows-progress");
  const updating = document.getElementById("windows-updating");
  const linux = document.getElementById("windows-linux");
  let percent = 0;

  const timer = setInterval(() => {
    if (Math.random() > windowsUpdate.stallChance) {
      const step = 1 + Math.floor(Math.random() * windowsUpdate.maxStepPercent);
      percent = Math.min(100, percent + step);
    }

    progress.textContent = `${percent}% complete`;

    if (percent < 100) {
      return;
    }

    clearInterval(timer);
    updating.hidden = true;
    linux.hidden = false;

    setTimeout(
      () => onSolved({ reload: true }),
      windowsUpdate.rebootDelayMs,
    );
  }, windowsUpdate.tickMs);
}

function judgeInstall(rawCommand) {
  const command = rawCommand.trim().toLowerCase().replace(/\s+/g, " ");
  const tool = command.split(" ")[0];

  if (!command) {
    return { message: "Type an install command." };
  }

  if (tool === "sudo") {
    return { message: "No sudo. Never sudo a package manager." };
  }

  if (laughedAtTools.includes(tool) || /^python3? -m pip\b/.test(command)) {
    const shownTool = tool.startsWith("python") ? "pip" : tool;
    return { message: pickRandom(laughLines).replace("{tool}", shownTool) };
  }

  const uvPackage = command.match(uvInstall)?.[1];

  if (uvPackage) {
    if (/^jpcl(?:[=<>~!]=\S+)?$/.test(uvPackage)) {
      return {
        solved: true,
        message: "Installed jpcl. Booting…",
      };
    }

    if (uvPackage.startsWith("jpcl-lang")) {
      return { message: "jpcl-lang is the Node package. Python's is jpcl." };
    }

    return { message: `No package named ${uvPackage}. Python's is jpcl.` };
  }

  const denoPackage = command.match(denoInstall)?.[1];

  if (denoPackage) {
    if (/^npm:jpcl-lang(?:@\S+)?$/.test(denoPackage)) {
      return {
        solved: true,
        message: "Installed jpcl-lang. Booting…",
      };
    }

    if (denoPackage.startsWith("jpcl-lang")) {
      return { message: "Deno needs the npm: prefix: npm:jpcl-lang" };
    }

    if (/^npm:jpcl(?:@\S+)?$/.test(denoPackage)) {
      return { message: "jpcl is the Python package. Node's is jpcl-lang." };
    }

    return { message: `No package named ${denoPackage}. Node's is npm:jpcl-lang.` };
  }

  if (tool === "uv" || tool === "deno") {
    return { message: `Right tool, wrong command. Install the package with ${tool}.` };
  }

  return { message: `${tool}: command not found. Use uv or Deno.` };
}

function jpclLock(onSolved) {
  const form = document.getElementById("jpcl-form");
  const input = document.getElementById("jpcl-command");
  const status = document.getElementById("jpcl-status");
  const listeners = new AbortController();

  form.addEventListener(
    "submit",
    (event) => {
      event.preventDefault();

      const verdict = judgeInstall(input.value);
      status.textContent = verdict.message;

      if (verdict.solved) {
        listeners.abort();
        setTimeout(onSolved, 800);
      }
    },
    { signal: listeners.signal },
  );
}

const locks = [
  {
    name: "konami",
    chance: 0.25,
    run: konamiLock,
  },
  {
    name: "power",
    chance: 0.2,
    run: powerLock,
  },
  {
    name: "captcha",
    chance: 0.2,
    run: captchaLock,
  },
  {
    name: "overheat",
    chance: 0.2,
    run: overheatLock,
  },
  {
    name: "bios",
    chance: 0.2,
    run: biosLock,
  },
  {
    name: "windows",
    chance: 0.2,
    run: windowsLock,
  },
  {
    // Always follows the Windows "reboot"
    name: "jpcl",
    chance: 1,
    run: jpclLock,
  },
];

// Roll this stage's chance to jam, then show its lock or redirect
function visit() {
  let stage = readStage();
  const lock = locks[Math.floor(stage / 2)];

  if (lock && stage % 2 === 0 && Math.random() < lock.chance) {
    stage += 1;
  }

  writeStage(stage);

  if (lock && stage % 2 === 1) {
    document.body.dataset.lock = lock.name;

    lock.run((options) => {
      writeStage(stage + 1);

      if (options?.reload) {
        location.reload();
      } else {
        visit();
      }
    });
  } else {
    delete document.body.dataset.lock;
    startRedirect();
  }
}

visit();