clone

push a directory of html from the terminal and get a four-character url back. a deno cli on cloudflare

main
nzip / worker / test / password.test.mjs
password.test.mjs 2.2K
1import assert from "node:assert/strict";2import test from "node:test";34import { hasValidUnlockCookie, makeUnlockCookie } from "../src/password.ts";56function requestWith(cookie) {7 return new Request("https://12d8.n.zip/", {8 headers: { cookie: cookie.split(";", 1)[0] },9 });10}1112const hex = (bytes) =>13 [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0"))14 .join("");1516async function legacyCookie(env, address) {17 const exp = Math.floor(Date.now() / 1000) + 3600;18 const key = await crypto.subtle.importKey(19 "raw",20 new TextEncoder().encode(`nzip-unlock:${env.NZIP_TOKEN}`),21 { name: "HMAC", hash: "SHA-256" },22 false,23 ["sign"],24 );25 const signature = await crypto.subtle.sign(26 "HMAC",27 key,28 new TextEncoder().encode(`${address}.${exp}`),29 );30 return `nzip_a${address}=${exp}.${hex(signature)}`;31}3233test("unlock cookies are scoped to the current auth version", async () => {34 const env = { NZIP_TOKEN: "test-owner-token" };35 const cookie = await makeUnlockCookie(env, "12d8", 3);36 const req = requestWith(cookie);3738 assert.match(cookie, /^__Host-nzip-unlock=/);39 assert.match(cookie, /; Path=\//);40 assert.match(cookie, /; Secure/);41 assert.doesNotMatch(cookie, /Domain=/i);4243 assert.equal(await hasValidUnlockCookie(req, env, "12d8", 3), true);44 assert.equal(await hasValidUnlockCookie(req, env, "12d8", 4), false);45 assert.equal(await hasValidUnlockCookie(req, env, "ffff", 3), false);46});4748test("a malformed shadowing cookie does not hide a valid unlock cookie", async () => {49 const env = { NZIP_TOKEN: "test-owner-token" };50 const cookie = await makeUnlockCookie(env, "12d8", 3);51 const value = cookie.split(";", 1)[0];52 const req = new Request("https://12d8.n.zip/", {53 headers: { cookie: `__Host-nzip-unlock=broken; ${value}` },54 });5556 assert.equal(await hasValidUnlockCookie(req, env, "12d8", 3), true);57});5859test("legacy unlock cookies survive migration until the auth version changes", async () => {60 const env = { NZIP_TOKEN: "test-owner-token" };61 const req = requestWith(await legacyCookie(env, "12d8"));6263 assert.equal(await hasValidUnlockCookie(req, env, "12d8", 1), true);64 assert.equal(await hasValidUnlockCookie(req, env, "12d8", 2), false);65});