hushdrop-mcp 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/drop.mjs ADDED
@@ -0,0 +1,1020 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * hush — instant, branded, password-protected sharing on your own domain.
4
+ *
5
+ * Open-source artifact sharing: drop a file (HTML, PDF, zip, anything) and get a
6
+ * clean, optionally password-locked URL on YOUR domain in ~1s. Bring your own
7
+ * Vercel Blob store + domain via `hush init`; the defaults point at the public
8
+ * hushdrop.maxtechera.dev example deployment.
9
+ *
10
+ * Pipeline (HTML): inject <head> branding/OG + corner badge → (optional) StatiCrypt
11
+ * with branded gate → upload to Vercel Blob → clean URL + password.
12
+ * Pipeline (file): upload raw (unguessable slug), or wrap in a branded download page.
13
+ *
14
+ * Serving is a dumb Vercel rewrite/edge-proxy (<domain>/<slug> → blob). No deploy per file.
15
+ */
16
+
17
+ import { readFile, writeFile, mkdir, mkdtemp, readdir, rm } from "node:fs/promises";
18
+ import { existsSync, readFileSync } from "node:fs";
19
+ import { homedir, tmpdir } from "node:os";
20
+ import { join, dirname, basename, extname } from "node:path";
21
+ import { fileURLToPath } from "node:url";
22
+ import { parseArgs } from "node:util";
23
+ import { spawn, spawnSync } from "node:child_process";
24
+
25
+ const __dirname = dirname(fileURLToPath(import.meta.url));
26
+ const DROP_HOME = join(homedir(), ".hushdrop");
27
+ const MANIFEST = join(DROP_HOME, "manifest.json");
28
+ const CONFIG_FILE = join(DROP_HOME, "config.json");
29
+
30
+ // Default deployment = the public hushdrop.maxtechera.dev example. These are NOT secrets
31
+ // (the blob host + project id are already public in vercel.json / the Vercel dashboard).
32
+ // Run `hush init` to point hush at your OWN domain + Vercel Blob store instead.
33
+ const DEFAULTS = {
34
+ domain: "hushdrop.maxtechera.dev",
35
+ blobHost: "opzwhnf3xlqxnotd.public.blob.vercel-storage.com",
36
+ projectId: "prj_c7Yb2JKRvlBduAXyjiWfWEb9ZT9L",
37
+ orgId: "team_3dkH4OzC7klByvov3hsB7J40",
38
+ };
39
+
40
+ // Merge: built-in defaults ← brand/brand.json (presentation) ← ~/.hushdrop/config.json (infra) ← env.
41
+ function loadConfig() {
42
+ let cfg = { ...DEFAULTS, brand: {} };
43
+ try {
44
+ const b = JSON.parse(readFileSync(join(__dirname, "brand", "brand.json"), "utf8"));
45
+ cfg.brand = b;
46
+ if (b.domain) cfg.domain = b.domain;
47
+ } catch {}
48
+ try {
49
+ const c = JSON.parse(readFileSync(CONFIG_FILE, "utf8"));
50
+ cfg = { ...cfg, ...c, brand: { ...cfg.brand, ...(c.brand || {}) } };
51
+ } catch {}
52
+ if (process.env.DROP_DOMAIN) cfg.domain = process.env.DROP_DOMAIN;
53
+ if (process.env.DROP_BLOB_HOST) cfg.blobHost = process.env.DROP_BLOB_HOST;
54
+ cfg.brandDir = cfg.brandDir || join(__dirname, "brand");
55
+ cfg.links = cfg.brand?.links || {};
56
+ cfg.origin = `https://${cfg.domain}`;
57
+ return cfg;
58
+ }
59
+ const CONFIG = loadConfig();
60
+ const DOMAIN = CONFIG.domain;
61
+ const ORIGIN = CONFIG.origin;
62
+ const BRAND = CONFIG.brandDir;
63
+
64
+ // ---------- helpers ----------
65
+ const die = (msg) => { console.error(`\x1b[31m✗\x1b[0m ${msg}`); process.exit(1); };
66
+ const ok = (msg) => console.log(`\x1b[32m✓\x1b[0m ${msg}`);
67
+
68
+ function humanSize(n) {
69
+ const u = ["B", "KB", "MB", "GB"];
70
+ let i = 0;
71
+ while (n >= 1024 && i < u.length - 1) { n /= 1024; i++; }
72
+ return `${n.toFixed(n < 10 && i > 0 ? 1 : 0)} ${u[i]}`;
73
+ }
74
+
75
+ function mimeFor(ext) {
76
+ const m = {
77
+ ".html": "text/html; charset=utf-8", ".htm": "text/html; charset=utf-8",
78
+ ".pdf": "application/pdf", ".zip": "application/zip", ".png": "image/png",
79
+ ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".svg": "image/svg+xml",
80
+ ".webp": "image/webp", ".txt": "text/plain; charset=utf-8", ".csv": "text/csv",
81
+ ".json": "application/json", ".mp4": "video/mp4", ".mov": "video/quicktime",
82
+ ".md": "text/markdown; charset=utf-8", ".gz": "application/gzip", ".tar": "application/x-tar",
83
+ ".css": "text/css; charset=utf-8", ".js": "application/javascript; charset=utf-8",
84
+ ".mjs": "application/javascript; charset=utf-8", ".map": "application/json",
85
+ ".ico": "image/x-icon", ".woff": "font/woff", ".woff2": "font/woff2", ".ttf": "font/ttf",
86
+ ".wasm": "application/wasm", ".xml": "application/xml", ".webmanifest": "application/manifest+json",
87
+ };
88
+ return m[ext.toLowerCase()] || "application/octet-stream";
89
+ }
90
+
91
+ function slugify(name) {
92
+ return basename(name, extname(name))
93
+ .toLowerCase().normalize("NFKD").replace(/[^\w\s-]/g, "")
94
+ .trim().replace(/[\s_]+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "") || "file";
95
+ }
96
+
97
+ const rand = (n) => {
98
+ const a = "23456789abcdefghjkmnpqrstuvwxyz";
99
+ let s = "";
100
+ const buf = new Uint8Array(n);
101
+ (globalThis.crypto || require("node:crypto").webcrypto).getRandomValues(buf);
102
+ for (let i = 0; i < n; i++) s += a[buf[i] % a.length];
103
+ return s;
104
+ };
105
+
106
+ const ADJ = ["amber","brisk","clever","copper","dusky","ember","fleet","golden","hazel","ivory","jolly","keen","lunar","mellow","noble","opal","prime","quartz","rapid","silver","tidal","umber","vivid","witty","zesty","bold","crisp","swift","sunny","quiet"];
107
+ const NOUN = ["canyon","river","harbor","meadow","summit","orbit","cedar","falcon","lantern","compass","beacon","pebble","willow","cobalt","cypress","drift","ember","glacier","horizon","ridge","comet","delta","fjord","grove","atlas"];
108
+ function genPassword() {
109
+ const buf = new Uint8Array(3);
110
+ (globalThis.crypto || require("node:crypto").webcrypto).getRandomValues(buf);
111
+ return `${ADJ[buf[0] % ADJ.length]}-${NOUN[buf[1] % NOUN.length]}-${10 + (buf[2] % 90)}`;
112
+ }
113
+
114
+ function luhn(s) {
115
+ let sum = 0, alt = false;
116
+ for (let i = s.length - 1; i >= 0; i--) { let n = +s[i]; if (alt) { n *= 2; if (n > 9) n -= 9; } sum += n; alt = !alt; }
117
+ return s.length >= 13 && sum % 10 === 0;
118
+ }
119
+ // Client-side secret/PII scan run BEFORE encryption+upload. High-signal patterns only
120
+ // (the real risk for AI artifacts is an embedded credential); emails warn only in bulk.
121
+ function scanPII(text) {
122
+ const hits = [];
123
+ const add = (label, re) => { if (re.test(text)) hits.push(label); };
124
+ add("AWS access key", /\bAKIA[0-9A-Z]{16}\b/);
125
+ add("private key block", /-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----/);
126
+ add("API token/secret", /\b(?:sk-[A-Za-z0-9]{20,}|gh[pousr]_[A-Za-z0-9]{20,}|xox[baprs]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{30,}|vercel_blob_rw_[A-Za-z0-9_]{20,})\b/);
127
+ add("JWT", /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/);
128
+ const cc = (text.match(/\b(?:\d[ -]?){13,16}\b/g) || []).map((c) => c.replace(/[ -]/g, ""));
129
+ if (cc.some(luhn)) hits.push("possible card number");
130
+ const emails = [...new Set(text.match(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g) || [])];
131
+ if (emails.length >= 5) hits.push(`${emails.length} email addresses`);
132
+ return [...new Set(hits)];
133
+ }
134
+
135
+ async function dataUri(path) {
136
+ const ext = extname(path).toLowerCase();
137
+ const mime = ext === ".svg" ? "image/svg+xml" : ext === ".png" ? "image/png"
138
+ : ext === ".jpg" || ext === ".jpeg" ? "image/jpeg" : ext === ".ico" ? "image/x-icon" : "application/octet-stream";
139
+ const b = await readFile(path);
140
+ return `data:${mime};base64,${b.toString("base64")}`;
141
+ }
142
+
143
+ function clip(text) {
144
+ // pbcopy (mac) · clip.exe/clip (windows + WSL) · xclip/wl-copy (linux)
145
+ for (const cmd of [["pbcopy"], ["clip.exe"], ["clip"], ["xclip", ["-selection", "clipboard"]], ["wl-copy"]]) {
146
+ try {
147
+ const r = spawnSync(cmd[0], cmd[1] || [], { input: text, stdio: ["pipe", "ignore", "ignore"], shell: process.platform === "win32" });
148
+ if (r.status === 0 || (r.status === null && !r.error)) return true;
149
+ } catch {}
150
+ }
151
+ return false;
152
+ }
153
+
154
+ // Load @vercel/blob, auto-installing deps on a fresh machine (node_modules is gitignored).
155
+ let _blob = null;
156
+ async function loadBlob() {
157
+ if (_blob) return _blob;
158
+ try {
159
+ _blob = await import("@vercel/blob");
160
+ } catch (e) {
161
+ if (e?.code !== "ERR_MODULE_NOT_FOUND") throw e;
162
+ console.error("\x1b[2m… first run on this machine: installing dependencies (npm install)\x1b[0m");
163
+ const r = spawnSync("npm", ["install", "--no-audit", "--no-fund", "--loglevel", "error"], {
164
+ cwd: __dirname, stdio: "inherit", shell: process.platform === "win32",
165
+ });
166
+ if (r.status !== 0) die("npm install failed in the skill dir. Run it manually: cd " + __dirname + " && npm install");
167
+ _blob = await import("@vercel/blob");
168
+ }
169
+ return _blob;
170
+ }
171
+
172
+ async function loadManifest() {
173
+ try { return JSON.parse(await readFile(MANIFEST, "utf8")); } catch { return []; }
174
+ }
175
+ async function saveManifest(m) {
176
+ await mkdir(DROP_HOME, { recursive: true });
177
+ await writeFile(MANIFEST, JSON.stringify(m, null, 2));
178
+ }
179
+
180
+ function getToken() {
181
+ if (process.env.BLOB_READ_WRITE_TOKEN) return process.env.BLOB_READ_WRITE_TOKEN;
182
+ // fallback: ~/.hushdrop/.env with BLOB_READ_WRITE_TOKEN=...
183
+ const envFile = join(DROP_HOME, ".env");
184
+ if (existsSync(envFile)) {
185
+ const txt = spawnSync("cat", [envFile]).stdout?.toString() || "";
186
+ const match = txt.match(/^\s*BLOB_READ_WRITE_TOKEN\s*=\s*["']?([^"'\n]+)/m);
187
+ if (match) return match[1].trim();
188
+ }
189
+ return null;
190
+ }
191
+
192
+ // ---------- HTML branding ----------
193
+ async function buildMeta({ title, url, ogImage }) {
194
+ let meta = await readFile(join(BRAND, "meta.html"), "utf8");
195
+ return meta
196
+ .replace(/__DROP_DOMAIN__/g, DOMAIN)
197
+ .replace(/__DROP_TITLE__/g, escapeAttr(title))
198
+ .replace(/__DROP_URL__/g, url)
199
+ .replace(/__DROP_OG_IMAGE__/g, ogImage)
200
+ // favicon: served from the blob _brand path (gate pages override with a data URI)
201
+ .replace(/__DROP_FAVICON__/g, `${ORIGIN}/_brand/favicon.png`);
202
+ }
203
+ const escapeAttr = (s) => String(s).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
204
+
205
+ // Parse "7d" / "24h" / "30m" / "2w" / an ISO date into an absolute ms timestamp.
206
+ function parseExpiry(s) {
207
+ if (!s) return null;
208
+ const m = String(s).trim().match(/^(\d+)\s*(m|h|d|w)$/i);
209
+ if (m) {
210
+ const mult = { m: 60e3, h: 36e5, d: 864e5, w: 6048e5 }[m[2].toLowerCase()];
211
+ return Date.now() + Number(m[1]) * mult;
212
+ }
213
+ const t = Date.parse(s);
214
+ return Number.isNaN(t) ? null : t;
215
+ }
216
+
217
+ // Client-side soft-expiry guard baked into the content (survives StatiCrypt decrypt).
218
+ // Real deletion is `hush gc` (manifest-driven); this hides the page after the deadline.
219
+ function expiryGuard(ts) {
220
+ return `<script>(function(){if(Date.now()>${ts}){document.body.innerHTML='<div style="font-family:system-ui,-apple-system,sans-serif;color:#f5f5f5;background:#0b0b0d;position:fixed;inset:0;display:flex;align-items:center;justify-content:center;text-align:center;padding:24px"><div><h1 style="font-weight:600;margin:0 0 8px">This link has expired.</h1><p style="opacity:.55;margin:0">Ask the sender for a new one.</p></div></div>';}})();</script>`;
221
+ }
222
+
223
+ // Render Markdown → a clean, branded HTML document (marked auto-installed on demand).
224
+ async function mdToHtml(md, title) {
225
+ let marked;
226
+ try { ({ marked } = await import("marked")); }
227
+ catch {
228
+ spawnSync("npm", ["install", "marked", "--no-audit", "--no-fund", "--loglevel", "error"], { cwd: __dirname, stdio: "inherit", shell: process.platform === "win32" });
229
+ ({ marked } = await import("marked"));
230
+ }
231
+ const body = marked.parse(md);
232
+ const accent = CONFIG.brand?.accentColor || "#ea580c";
233
+ const primary = CONFIG.brand?.primaryColor || "#ff6b35";
234
+ return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>${escapeAttr(title)}</title>
235
+ <style>body{max-width:740px;margin:48px auto;padding:0 22px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;line-height:1.65;color:#1a1a1a}h1,h2,h3{letter-spacing:-.01em;line-height:1.2}pre{background:#f6f6f7;padding:14px 16px;border-radius:10px;overflow-x:auto}code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.92em}pre code{background:none}:not(pre)>code{background:#f0f0f1;padding:2px 6px;border-radius:5px}img{max-width:100%}a{color:${accent}}blockquote{border-left:3px solid ${primary};margin:0;padding:2px 0 2px 16px;color:#555}table{border-collapse:collapse}th,td{border:1px solid #e5e5e5;padding:8px 12px}hr{border:none;border-top:1px solid #e5e5e5}</style>
236
+ </head><body>${body}</body></html>`;
237
+ }
238
+
239
+ // Substitute owner/brand tokens (social links, colors, owner) shared across templates.
240
+ function applyBrandTokens(s) {
241
+ const L = CONFIG.links || {};
242
+ return String(s)
243
+ .replace(/__DROP_GITHUB__/g, L.github || "")
244
+ .replace(/__DROP_INSTAGRAM__/g, L.instagram || "")
245
+ .replace(/__DROP_WEBSITE__/g, L.website || "")
246
+ .replace(/__DROP_OWNER__/g, CONFIG.brand?.owner || "")
247
+ .replace(/__DROP_PRIMARY__/g, CONFIG.brand?.primaryColor || "#ff6b35")
248
+ .replace(/__DROP_ACCENT__/g, CONFIG.brand?.accentColor || "#ea580c");
249
+ }
250
+
251
+ function injectHead(html, snippet) {
252
+ if (/<\/head>/i.test(html)) return html.replace(/<\/head>/i, `${snippet}\n</head>`);
253
+ if (/<head[^>]*>/i.test(html)) return html.replace(/(<head[^>]*>)/i, `$1\n${snippet}`);
254
+ if (/<html[^>]*>/i.test(html)) return html.replace(/(<html[^>]*>)/i, `$1\n<head>\n${snippet}\n</head>`);
255
+ return `<head>\n${snippet}\n</head>\n${html}`;
256
+ }
257
+ function injectBody(html, snippet) {
258
+ if (/<\/body>/i.test(html)) return html.replace(/<\/body>/i, `${snippet}\n</body>`);
259
+ return `${html}\n${snippet}`;
260
+ }
261
+
262
+ async function brandHtml(html, { title, url, logoUri, ogImage, expiresAt }) {
263
+ const meta = await buildMeta({ title, url, ogImage });
264
+ let badge = await readFile(join(BRAND, "badge.html"), "utf8");
265
+ badge = applyBrandTokens(badge).replace(/__DROP_LOGO__/g, logoUri).replace(/__DROP_DOMAIN__/g, DOMAIN);
266
+ html = injectHead(html, meta);
267
+ html = injectBody(html, badge);
268
+ if (expiresAt) html = injectBody(html, expiryGuard(expiresAt));
269
+ return html;
270
+ }
271
+
272
+ // ---------- StatiCrypt ----------
273
+ async function encrypt(htmlPath, { password, title, logoUri, faviconUri, ogImage, url }) {
274
+ const work = await mkdtemp(join(tmpdir(), "drop-"));
275
+ const outDir = join(work, "out");
276
+ await mkdir(outDir, { recursive: true });
277
+
278
+ // build a branded gate template with brand tokens substituted (staticrypt fills its own /*[|..|]*/0)
279
+ let gate = await readFile(join(BRAND, "gate.html"), "utf8");
280
+ const meta = await buildMeta({ title, url, ogImage });
281
+ gate = applyBrandTokens(gate)
282
+ .replace(/__DROP_LOGO__/g, logoUri)
283
+ .replace(/__DROP_FAVICON__/g, faviconUri)
284
+ .replace(/__DROP_DOMAIN__/g, DOMAIN)
285
+ .replace(/__DROP_META__/g, meta);
286
+ const gatePath = join(work, "gate.html");
287
+ await writeFile(gatePath, gate);
288
+
289
+ await new Promise((resolve, reject) => {
290
+ const p = spawn("npx", [
291
+ "staticrypt", htmlPath,
292
+ "-p", password,
293
+ "-t", gatePath,
294
+ "-d", outDir,
295
+ "--remember", "false",
296
+ "--short",
297
+ "--template-title", title,
298
+ "--template-instructions", "This page is password-protected. Enter the password to view it.",
299
+ "--template-button", "UNLOCK",
300
+ "--template-placeholder", "Password",
301
+ ], { stdio: ["ignore", "ignore", "inherit"] });
302
+ p.on("error", reject);
303
+ p.on("close", (code) => code === 0 ? resolve() : reject(new Error(`staticrypt exited ${code}`)));
304
+ });
305
+
306
+ const files = (await readdir(outDir)).filter((f) => f.endsWith(".html"));
307
+ if (!files.length) throw new Error("staticrypt produced no output");
308
+ const encrypted = await readFile(join(outDir, files[0]), "utf8");
309
+ await rm(work, { recursive: true, force: true });
310
+ return encrypted;
311
+ }
312
+
313
+ // ---------- upload ----------
314
+ async function upload(key, body, contentType, token) {
315
+ const { put } = await loadBlob();
316
+ return put(key, body, {
317
+ access: "public", token, addRandomSuffix: false, allowOverwrite: true, contentType,
318
+ });
319
+ }
320
+
321
+ // Managed (zero-setup) publish: POST the already-branded/encrypted bytes to the host's
322
+ // managed endpoint. No token, no Vercel setup — the server assigns a `u/` slug.
323
+ async function managedPublish(body, contentType, { burn } = {}) {
324
+ const endpoint = `${ORIGIN}/api/publish`;
325
+ const headers = { "content-type": "application/octet-stream", "x-drop-content-type": contentType };
326
+ if (burn) headers["x-drop-burn"] = "1";
327
+ let r;
328
+ try {
329
+ r = await fetch(endpoint, { method: "POST", headers, body });
330
+ } catch (e) { die(`managed publish failed: ${e.message}`); }
331
+ if (!r.ok) { let m; try { m = (await r.json()).error; } catch {} die(`managed publish failed: ${m || r.status}`); }
332
+ return r.json();
333
+ }
334
+
335
+ // Hosted (logged-in free tier) publish: same client-side branded/encrypted bytes, but
336
+ // authenticated with the API key so the drop lands persistently at <handle>/<slug>.
337
+ async function hostedPublish(body, contentType, slug, locked, emailGate) {
338
+ const key = getApiKey();
339
+ const headers = { "content-type": "application/octet-stream", "x-drop-content-type": contentType, authorization: `Bearer ${key}` };
340
+ if (slug) headers["x-drop-slug"] = slug;
341
+ if (locked) headers["x-drop-locked"] = "1";
342
+ if (emailGate) headers["x-drop-email-gate"] = String(emailGate).replace(/^@/, "").toLowerCase();
343
+ let r;
344
+ try { r = await fetch(`${ORIGIN}/api/publish`, { method: "POST", headers, body }); }
345
+ catch (e) { die(`hosted publish failed: ${e.message}`); }
346
+ if (!r.ok) { let m; try { m = (await r.json()).error; } catch {} die(`hosted publish failed: ${m || r.status}`); }
347
+ return r.json();
348
+ }
349
+
350
+ // Import an npm dep, auto-installing into the skill dir on first use (gitignored).
351
+ async function ensureDep(name) {
352
+ try { return await import(name); }
353
+ catch (e) {
354
+ if (e?.code !== "ERR_MODULE_NOT_FOUND") throw e;
355
+ console.error(`\x1b[2m… installing ${name}\x1b[0m`);
356
+ spawnSync("npm", ["install", name, "--no-audit", "--no-fund", "--loglevel", "error"], { cwd: __dirname, stdio: "inherit", shell: process.platform === "win32" });
357
+ return import(name);
358
+ }
359
+ }
360
+
361
+ // ---------- commands ----------
362
+ async function cmdDrop(file, opts) {
363
+ if (!file) die("usage: hush <file> [-p password] [-s slug] [--page] [--no-lock]");
364
+ if (!existsSync(file)) die(`no such file: ${file}`);
365
+
366
+ const ext = extname(file).toLowerCase();
367
+ const isMd = ext === ".md" || ext === ".markdown";
368
+ const isHtml = ext === ".html" || ext === ".htm" || isMd;
369
+
370
+ // Tier selection: when you're logged in, single HTML/Markdown drops go to your hosted
371
+ // account; a Blob token alone (not logged in) = self-host; otherwise it just works,
372
+ // publishing to the zero-setup managed tier. `--managed` forces managed even if you have
373
+ // infra configured. So a bare `hush file.html` needs no flags and no setup.
374
+ const token = opts.managed ? null : getToken();
375
+ const apiKey = getApiKey();
376
+ const hostedEligible = isHtml && !opts.page && ext !== ".zip";
377
+ const mode = opts.managed ? "managed"
378
+ : (apiKey && hostedEligible) ? "hosted"
379
+ : token ? "selfhost"
380
+ : apiKey ? "hosted"
381
+ : "managed"; // zero-setup default — no flag, no account needed
382
+ const logoUri = await dataUri(join(BRAND, "logo-white.png"));
383
+ const faviconUri = await dataUri(join(BRAND, "favicon.png"));
384
+ const ogImage = `${ORIGIN}/_brand/og.png`; // optional; harmless if absent
385
+ const stat = (await readFile(file)).length;
386
+ const expiresAt = parseExpiry(opts.expire);
387
+ if (opts.expire && !expiresAt) die(`bad --expire value: ${opts.expire} (use 7d, 24h, 30m, 2w, or a date)`);
388
+
389
+ if ((mode === "managed" || mode === "hosted") && (opts.page || !isHtml)) die(`the ${mode} tier supports HTML/markdown only. Self-host ('hush deploy') for files, --page, and zip sites.`);
390
+
391
+ const manifest = await loadManifest();
392
+ const now = new Date().toISOString();
393
+
394
+ // multi-file static site from a zip → uploaded under <slug>/, served at <slug>/
395
+ if (ext === ".zip") {
396
+ const { default: AdmZip } = await ensureDep("adm-zip");
397
+ const slug = opts.slug || slugify(file) + "-" + rand(4);
398
+ const entries = new AdmZip(file).getEntries().filter((e) => !e.isDirectory);
399
+ if (!entries.length) die("empty zip");
400
+ const indexEntry = entries
401
+ .filter((e) => /(^|\/)index\.html?$/i.test(e.entryName))
402
+ .sort((a, b) => a.entryName.split("/").length - b.entryName.split("/").length)[0];
403
+ if (!indexEntry) die("no index.html found in the zip");
404
+ // strip a single wrapping top-level folder if present (e.g. dist/)
405
+ const top = indexEntry.entryName.includes("/") ? indexEntry.entryName.slice(0, indexEntry.entryName.indexOf("/") + 1) : "";
406
+ let total = 0, count = 0;
407
+ for (const e of entries) {
408
+ const rel = top && e.entryName.startsWith(top) ? e.entryName.slice(top.length) : e.entryName;
409
+ if (!rel || rel.startsWith("..")) continue;
410
+ let data = e.getData();
411
+ if (/^index\.html?$/i.test(rel)) {
412
+ let html = data.toString("utf8");
413
+ // <base> so relative asset links resolve under /<slug>/ regardless of trailing slash
414
+ if (/<head[^>]*>/i.test(html)) html = html.replace(/<head([^>]*)>/i, `<head$1><base href="/${slug}/">`);
415
+ else html = `<base href="/${slug}/">\n` + html;
416
+ html = await brandHtml(html, { title: opts.title || basename(file, ext), url: `${ORIGIN}/${slug}/`, logoUri, ogImage, expiresAt });
417
+ data = Buffer.from(html, "utf8");
418
+ }
419
+ await upload(`${slug}/${rel}`, data, mimeFor(extname(rel)), token);
420
+ total += data.length; count++;
421
+ }
422
+ const url = `${ORIGIN}/${slug}/`;
423
+ manifest.unshift({ slug, url, type: "site", locked: false, password: null, file: basename(file), size: total, createdAt: now, expiresAt: expiresAt || null });
424
+ await saveManifest(manifest);
425
+ report({ url, password: null, locked: false, extra: `${count} files (multi-file site, public)` });
426
+ return;
427
+ }
428
+
429
+ if (isHtml && !opts.page) {
430
+ const slug = opts.slug || slugify(file) + "-" + rand(4);
431
+ const url = `${ORIGIN}/${slug}`;
432
+ const title = opts.title || basename(file, ext).replace(/[-_]+/g, " ");
433
+ let html = await readFile(file, "utf8");
434
+ if (isMd) html = await mdToHtml(html, title);
435
+
436
+ // PII / secret scan on the RAW content (before brand + encrypt). Warn by default
437
+ // (agent-friendly); --block-pii refuses; --no-pii-check silences. Skipped for
438
+ // password-locked drops only when explicitly told to (locking already protects them).
439
+ if (!opts.noPiiCheck) {
440
+ const pii = scanPII(html);
441
+ if (pii.length) {
442
+ const msg = `possible sensitive data in ${basename(file)}: ${pii.join(", ")}`;
443
+ if (opts.blockPii) die(`⚠ ${msg}\n refusing to publish (--block-pii). Remove it, or drop --no-pii-check to publish anyway.`);
444
+ if (!JSON_OUT) console.error(`\x1b[33m⚠ ${msg}\x1b[0m\n \x1b[2mpublishing anyway — use --block-pii to refuse, --no-pii-check to silence${opts.noLock ? ", and note this drop is PUBLIC (unlocked)" : ""}\x1b[0m`);
445
+ }
446
+ }
447
+ html = await brandHtml(html, { title, url, logoUri, ogImage, expiresAt });
448
+
449
+ let password = null, body = html;
450
+ if (!opts.noLock) {
451
+ password = opts.password || genPassword();
452
+ const tmp = await mkdtemp(join(tmpdir(), "drop-in-"));
453
+ const inPath = join(tmp, `${slug}.html`);
454
+ await writeFile(inPath, html);
455
+ body = await encrypt(inPath, { password, title, logoUri, faviconUri, ogImage, url });
456
+ await rm(tmp, { recursive: true, force: true });
457
+ }
458
+ if (mode === "managed") {
459
+ const m = await managedPublish(body, "text/html; charset=utf-8", { burn: opts.burn });
460
+ manifest.unshift({ slug: m.slug, url: m.url, type: "html", locked: !opts.noLock, password, file: basename(file), size: stat, managed: true, burn: !!opts.burn, createdAt: now });
461
+ await saveManifest(manifest);
462
+ report({ url: m.url, password, locked: !opts.noLock, extra: opts.burn ? "managed · burns on first view" : "managed · auto-expires in 24h" });
463
+ return;
464
+ }
465
+ if (mode === "hosted") {
466
+ const m = await hostedPublish(body, "text/html; charset=utf-8", slug, !opts.noLock, opts.emailGate);
467
+ manifest.unshift({ slug: m.slug, url: m.url, type: "html", locked: !opts.noLock, password, file: basename(file), size: stat, hosted: true, handle: m.handle, createdAt: now });
468
+ await saveManifest(manifest);
469
+ report({ url: m.url, password, locked: !opts.noLock, extra: `hosted · ${m.handle}/${m.slug}${opts.emailGate ? ` · @${String(opts.emailGate).replace(/^@/, "")} only` : ""}` });
470
+ return;
471
+ }
472
+ const res = await upload(slug, body, "text/html; charset=utf-8", token);
473
+ manifest.unshift({ slug, url, type: "html", locked: !opts.noLock, password, file: basename(file), size: stat, blobUrl: res.url, createdAt: now, expiresAt: expiresAt || null });
474
+ await saveManifest(manifest);
475
+ report({ url, password, locked: !opts.noLock, extra: expiresAt ? `expires: ${new Date(expiresAt).toISOString().slice(0, 16).replace("T", " ")}` : undefined });
476
+ return;
477
+ }
478
+
479
+ if (opts.page) {
480
+ // branded download page wrapping a (any) file
481
+ const slug = opts.slug || slugify(file) + "-" + rand(4);
482
+ const fileKey = `${slug}${ext || ""}`;
483
+ const fileUrl = `${ORIGIN}/${fileKey}`;
484
+ const pageUrl = `${ORIGIN}/${slug}`;
485
+ const title = opts.title || basename(file, ext).replace(/[-_]+/g, " ");
486
+
487
+ const fres = await upload(fileKey, await readFile(file), mimeFor(ext), token);
488
+
489
+ let page = await readFile(join(BRAND, "download-page.html"), "utf8");
490
+ const meta = await buildMeta({ title, url: pageUrl, ogImage });
491
+ page = applyBrandTokens(page)
492
+ .replace(/__DROP_META__/g, meta)
493
+ .replace(/__DROP_LOGO__/g, logoUri)
494
+ .replace(/__DROP_TITLE__/g, escapeAttr(title))
495
+ .replace(/__DROP_SUBTITLE__/g, "Click below to download.")
496
+ .replace(/__DROP_FILE_NAME__/g, escapeAttr(basename(file)))
497
+ .replace(/__DROP_FILE_SIZE__/g, humanSize(stat))
498
+ .replace(/__DROP_FILE_URL__/g, fileUrl)
499
+ .replace(/__DROP_DOMAIN__/g, DOMAIN);
500
+
501
+ let password = null, body = page;
502
+ if (!opts.noLock && opts.password) {
503
+ // only lock the page if a password was explicitly requested (the file URL itself stays unguessable)
504
+ password = opts.password;
505
+ const tmp = await mkdtemp(join(tmpdir(), "drop-in-"));
506
+ const inPath = join(tmp, `${slug}.html`);
507
+ await writeFile(inPath, page);
508
+ body = await encrypt(inPath, { password, title, logoUri, faviconUri, ogImage, url: pageUrl });
509
+ await rm(tmp, { recursive: true, force: true });
510
+ }
511
+ const pres = await upload(slug, body, "text/html; charset=utf-8", token);
512
+ manifest.unshift({ slug, url: pageUrl, type: "page", locked: !!password, password, file: basename(file), size: stat, blobUrl: pres.url, fileBlobUrl: fres.url, createdAt: now, expiresAt: expiresAt || null });
513
+ await saveManifest(manifest);
514
+ report({ url: pageUrl, password, locked: !!password, extra: `file: ${fileUrl}` });
515
+ return;
516
+ }
517
+
518
+ // raw file — unguessable slug, no page
519
+ const slug = (opts.slug || slugify(file)) + "-" + rand(6);
520
+ const key = `${slug}${ext || ""}`;
521
+ const url = `${ORIGIN}/${key}`;
522
+ const res = await upload(key, await readFile(file), mimeFor(ext), token);
523
+ manifest.unshift({ slug, url, type: "file", locked: false, password: null, file: basename(file), size: stat, blobUrl: res.url, createdAt: now, expiresAt: expiresAt || null });
524
+ await saveManifest(manifest);
525
+ report({ url, password: null, locked: false, extra: expiresAt ? `expires: ${new Date(expiresAt).toISOString().slice(0, 16).replace("T", " ")}` : undefined });
526
+ }
527
+
528
+ function report({ url, password, locked, extra }) {
529
+ if (JSON_OUT) { console.log(JSON.stringify({ url, password: password || null, locked: !!locked, extra: extra || null })); return; }
530
+ console.log("");
531
+ ok("live");
532
+ console.log(` \x1b[1m${url}\x1b[0m`);
533
+ if (extra) console.log(` ${extra}`);
534
+ if (locked && password) console.log(` password: \x1b[1m\x1b[33m${password}\x1b[0m`);
535
+ const payload = locked && password ? `${url}\npassword: ${password}` : url;
536
+ if (clip(payload)) console.log(` \x1b[2m(copied to clipboard)\x1b[0m`);
537
+ console.log("");
538
+ }
539
+
540
+ // Logged-in hosted account → list/remove via the API (not the BYO Blob store).
541
+ const useHosted = () => getApiKey() && !getToken();
542
+
543
+ async function hostedList() {
544
+ const key = getApiKey();
545
+ let r; try { r = await fetch(`${ORIGIN}/api/sites`, { headers: { authorization: `Bearer ${key}` } }); } catch (e) { die(e.message); }
546
+ if (!r.ok) die("could not list drops (key invalid? run `hush login`)");
547
+ const { sites } = await r.json();
548
+ const local = await loadManifest();
549
+ const pw = new Map(); for (const d of local) if (d.password) pw.set(d.slug, d.password);
550
+ if (JSON_OUT) { console.log(JSON.stringify(sites.map((s) => ({ ...s, password: pw.get(s.slug) || null })))); return; }
551
+ if (!sites.length) return console.log("no drops yet.");
552
+ for (const s of sites) {
553
+ const known = pw.get(s.slug);
554
+ const lock = known ? `🔒 ${known}` : (s.locked ? "🔒 locked" : "public");
555
+ console.log(`${s.url}\n ${humanSize(s.size)} · ${lock} · ${String(s.created_at).slice(0, 10)}`);
556
+ }
557
+ }
558
+
559
+ async function hostedRm(slug) {
560
+ const key = getApiKey();
561
+ let r; try { r = await fetch(`${ORIGIN}/api/sites?slug=${encodeURIComponent(slug)}`, { method: "DELETE", headers: { authorization: `Bearer ${key}` } }); } catch (e) { die(e.message); }
562
+ if (!r.ok) { let m; try { m = (await r.json()).error; } catch {} die(m || "remove failed"); }
563
+ const m = await loadManifest(); const kept = m.filter((d) => d.slug !== slug); if (kept.length !== m.length) await saveManifest(kept);
564
+ if (JSON_OUT) { console.log(JSON.stringify({ removed: slug })); return; }
565
+ ok(`removed ${slug}`);
566
+ }
567
+
568
+ async function cmdList() {
569
+ if (useHosted()) return hostedList();
570
+ const token = getToken();
571
+ if (!token) die("BLOB_READ_WRITE_TOKEN not set. Run: hush setup (self-host) or hush login (hosted)");
572
+ const { list } = await loadBlob();
573
+ const { blobs } = await list({ token });
574
+ // overlay local passwords (kept on this machine only) keyed by pathname/slug
575
+ const local = await loadManifest();
576
+ const pw = new Map();
577
+ for (const d of local) { if (d.password) { pw.set(d.slug, d.password); } }
578
+ // sort newest first
579
+ blobs.sort((a, b) => new Date(b.uploadedAt) - new Date(a.uploadedAt));
580
+ if (JSON_OUT) {
581
+ console.log(JSON.stringify(blobs.map((b) => {
582
+ const slug = b.pathname.replace(/\.[^.]+$/, "");
583
+ return { slug: b.pathname, url: `${ORIGIN}/${b.pathname}`, size: b.size, password: pw.get(slug) || pw.get(b.pathname) || null, uploadedAt: b.uploadedAt };
584
+ })));
585
+ return;
586
+ }
587
+ if (!blobs.length) return console.log("no drops yet.");
588
+ for (const b of blobs) {
589
+ const slug = b.pathname.replace(/\.[^.]+$/, "");
590
+ const known = pw.get(slug) || pw.get(b.pathname);
591
+ const lock = known ? `🔒 ${known}` : (b.pathname.includes(".") ? "public file" : "page");
592
+ console.log(`${ORIGIN}/${b.pathname}\n ${humanSize(b.size)} · ${lock} · ${String(b.uploadedAt).slice(0, 10)}`);
593
+ }
594
+ }
595
+
596
+ async function cmdRm(slug) {
597
+ if (!slug) die("usage: hush rm <slug>");
598
+ if (useHosted()) return hostedRm(slug);
599
+ const token = getToken();
600
+ if (!token) die("BLOB_READ_WRITE_TOKEN not set. Run: hush setup (self-host) or hush login (hosted)");
601
+ const { list, del } = await loadBlob();
602
+ const { blobs } = await list({ token });
603
+ // match the page/file key (slug), a sibling like <slug>.<ext>, or a whole site under <slug>/
604
+ const targets = blobs.filter((b) => b.pathname === slug || b.pathname.replace(/\.[^.]+$/, "") === slug || b.pathname.startsWith(slug + "/"));
605
+ if (!targets.length) die(`not found: ${slug}`);
606
+ await del(targets.map((b) => b.url), { token });
607
+ // prune local manifest if present
608
+ const m = await loadManifest();
609
+ const kept = m.filter((d) => d.slug !== slug);
610
+ if (kept.length !== m.length) await saveManifest(kept);
611
+ if (JSON_OUT) { console.log(JSON.stringify({ removed: targets.map((b) => b.pathname) })); return; }
612
+ ok(`removed ${targets.map((b) => b.pathname).join(", ")}`);
613
+ }
614
+
615
+ // Delete drops whose expiry has passed (manifest-driven). Run via cron for true auto-expiry.
616
+ async function cmdGc() {
617
+ const m = await loadManifest();
618
+ const nowMs = Date.now();
619
+ const expired = m.filter((d) => d.expiresAt && d.expiresAt < nowMs);
620
+ if (!expired.length) { if (JSON_OUT) console.log("[]"); else ok("nothing expired"); return; }
621
+ const token = getToken();
622
+ if (!token) die("BLOB_READ_WRITE_TOKEN not set. Run: hush setup");
623
+ const { list, del } = await loadBlob();
624
+ const { blobs } = await list({ token });
625
+ const removed = [];
626
+ for (const d of expired) {
627
+ const targets = blobs.filter((b) => b.pathname === d.slug || b.pathname.replace(/\.[^.]+$/, "") === d.slug || b.pathname.startsWith(d.slug + "/"));
628
+ if (targets.length) { await del(targets.map((b) => b.url), { token }); removed.push(...targets.map((b) => b.pathname)); }
629
+ }
630
+ await saveManifest(m.filter((d) => !(d.expiresAt && d.expiresAt < nowMs)));
631
+ if (JSON_OUT) { console.log(JSON.stringify({ removed })); return; }
632
+ ok(removed.length ? `removed ${removed.length} expired: ${removed.join(", ")}` : "manifest pruned (blobs already gone)");
633
+ }
634
+
635
+ // One-command backend: discover the blob host, wire middleware.js + vercel.json,
636
+ // write ~/.hushdrop/config.json, and deploy. Assumes a Vercel project + Blob store exist
637
+ // (run `vercel link` and `vercel blob store add drops` first, or let setup pull the token).
638
+ async function cmdDeploy(opts) {
639
+ const dry = !!opts.dryRun;
640
+ const repoRoot = existsSync(join(__dirname, "..", "middleware.js")) ? join(__dirname, "..") : process.cwd();
641
+ const mwPath = join(repoRoot, "middleware.js");
642
+ const vjPath = join(repoRoot, "vercel.json");
643
+ if (!existsSync(mwPath) || !existsSync(vjPath)) die(`run 'hush deploy' from the hushdrop repo root (middleware.js + vercel.json not found in ${repoRoot})`);
644
+
645
+ console.log(`hush deploy — wiring backend in ${repoRoot}${dry ? " (dry run)" : ""}\n`);
646
+
647
+ const hasVercel = spawnSync(process.platform === "win32" ? "where" : "which", ["vercel"], { stdio: "ignore", shell: process.platform === "win32" }).status === 0;
648
+
649
+ // 0. auto-provision the Vercel project + Blob store so self-host is one command.
650
+ if (!dry && hasVercel) {
651
+ if (!existsSync(join(repoRoot, ".vercel", "project.json"))) {
652
+ console.log("linking a Vercel project…");
653
+ spawnSync("vercel", ["link", "--yes"], { cwd: repoRoot, stdio: "inherit", shell: process.platform === "win32" });
654
+ }
655
+ if (!getToken() && !opts.token) {
656
+ console.log("creating a Blob store 'drops' (if needed)…");
657
+ spawnSync("vercel", ["blob", "store", "add", "drops"], { cwd: repoRoot, stdio: "inherit", shell: process.platform === "win32" });
658
+ }
659
+ }
660
+
661
+ // 1. token
662
+ let token = getToken() || opts.token;
663
+ if (!token) { token = await pullTokenFromVercel(); }
664
+ if (!token) die("no BLOB_READ_WRITE_TOKEN. Run 'vercel blob store add drops' (or `vercel login`), then: hush deploy --token vercel_blob_rw_...");
665
+
666
+ // 2. discover the public blob host via a throwaway upload
667
+ const { put, del } = await loadBlob();
668
+ const probe = await put(".drop-probe", "ok", { access: "public", token, addRandomSuffix: false, allowOverwrite: true, contentType: "text/plain" });
669
+ const blobHost = new URL(probe.url).host;
670
+ await del(probe.url, { token }).catch(() => {});
671
+ ok(`blob host: ${blobHost}`);
672
+
673
+ // 3. patch middleware.js fallback host + vercel.json (fallback rewrite) idempotently.
674
+ // (Middleware derives the host from BLOB_READ_WRITE_TOKEN at runtime, so this only
675
+ // pins the fallback for explicit BYO-host setups.)
676
+ let mw = await readFile(mwPath, "utf8");
677
+ const newMw = mw
678
+ .replace(/const DEFAULT_BLOB_HOST = "[^"]+";/, `const DEFAULT_BLOB_HOST = "${blobHost}";`)
679
+ .replace(/const BLOB = "https:\/\/[^"]+";/, `const BLOB = "https://${blobHost}";`);
680
+ let vj = await readFile(vjPath, "utf8");
681
+ const newVj = vj.replace(/https:\/\/[a-z0-9]+\.public\.blob\.vercel-storage\.com/g, `https://${blobHost}`);
682
+ const mwChanged = newMw !== mw, vjChanged = newVj !== vj;
683
+ if (dry) {
684
+ ok(`middleware.js ${mwChanged ? "would update" : "already correct"}`);
685
+ ok(`vercel.json ${vjChanged ? "would update" : "already correct"}`);
686
+ } else {
687
+ if (mwChanged) await writeFile(mwPath, newMw);
688
+ if (vjChanged) await writeFile(vjPath, newVj);
689
+ ok(`middleware.js + vercel.json wired to ${blobHost}`);
690
+ }
691
+
692
+ // 4. write config (+ domain) and token
693
+ const cfg = { blobHost };
694
+ if (opts.domain) cfg.domain = opts.domain;
695
+ if (opts.project) cfg.projectId = opts.project;
696
+ if (opts.org) cfg.orgId = opts.org;
697
+ if (!dry) {
698
+ let existing = {};
699
+ try { existing = JSON.parse(readFileSync(CONFIG_FILE, "utf8")); } catch {}
700
+ await mkdir(DROP_HOME, { recursive: true });
701
+ await writeFile(CONFIG_FILE, JSON.stringify({ ...existing, ...cfg }, null, 2) + "\n");
702
+ await writeFile(join(DROP_HOME, ".env"), `BLOB_READ_WRITE_TOKEN=${token}\n`);
703
+ try { spawnSync("chmod", ["600", join(DROP_HOME, ".env")]); } catch {}
704
+ ok(`config + token saved to ${DROP_HOME}`);
705
+ }
706
+
707
+ // 5. deploy + domain
708
+ if (dry || opts.noDeploy) {
709
+ console.log(`\n${dry ? "Dry run — would run" : "Skipped deploy. Run"}: vercel deploy --prod${opts.domain ? ` && vercel domains add ${opts.domain}` : ""}`);
710
+ return;
711
+ }
712
+ console.log("\ndeploying to Vercel…");
713
+ const d = spawnSync("vercel", ["deploy", "--prod", "--yes"], { cwd: repoRoot, stdio: "inherit", shell: process.platform === "win32" });
714
+ if (d.status !== 0) die("vercel deploy failed — run it manually from the repo root.");
715
+ if (opts.domain) spawnSync("vercel", ["domains", "add", opts.domain], { cwd: repoRoot, stdio: "inherit", shell: process.platform === "win32" });
716
+ ok("deployed. Try: hush <file.html>");
717
+ }
718
+
719
+ // Provision this machine: install deps + ensure the blob token at ~/.hushdrop/.env.
720
+ async function cmdSetup(opts) {
721
+ console.log("hush setup — provisioning this machine\n");
722
+ // 1. deps
723
+ await loadBlob();
724
+ ok("dependencies installed");
725
+
726
+ // 2. token
727
+ let token = getToken();
728
+ if (!token && opts.token) {
729
+ token = opts.token;
730
+ }
731
+ if (!token) {
732
+ // try to pull from Vercel by the known hushdrop project id (works on any vercel-authed machine on the team)
733
+ token = await pullTokenFromVercel();
734
+ }
735
+ if (!token) {
736
+ die("no BLOB_READ_WRITE_TOKEN found.\n Provide it directly: hush setup --token <vercel_blob_rw_...>\n Or authenticate Vercel: vercel login (then re-run hush setup)\n Find it at: Vercel → hushdrop-private project → Storage → drops → .env.local");
737
+ }
738
+ await mkdir(DROP_HOME, { recursive: true });
739
+ await writeFile(MANIFEST.replace(/manifest\.json$/, ".env"), `BLOB_READ_WRITE_TOKEN=${token}\n`);
740
+ // chmod best-effort (no-op on windows)
741
+ try { spawnSync("chmod", ["600", join(DROP_HOME, ".env")]); } catch {}
742
+ ok(`token saved to ${join(DROP_HOME, ".env")}`);
743
+
744
+ // 3. verify
745
+ try {
746
+ const { list } = await loadBlob();
747
+ await list({ token });
748
+ ok("verified — blob store reachable");
749
+ console.log("\nReady. Try: hush <file.html>");
750
+ } catch (e) {
751
+ die("token saved but verification failed: " + (e.message || e));
752
+ }
753
+ }
754
+
755
+ // Point drop at YOUR own deployment (domain + Vercel Blob). Writes ~/.hushdrop/config.json.
756
+ async function cmdInit(opts) {
757
+ const cfg = {};
758
+ if (opts.domain) cfg.domain = opts.domain;
759
+ if (opts.blobHost) cfg.blobHost = opts.blobHost;
760
+ if (opts.project) cfg.projectId = opts.project;
761
+ if (opts.org) cfg.orgId = opts.org;
762
+ if (!Object.keys(cfg).length) {
763
+ die(`hush init — run drop on your own domain + Vercel Blob store.
764
+
765
+ hush init --domain share.yoursite.com \\
766
+ --blob-host <id>.public.blob.vercel-storage.com \\
767
+ --project prj_xxx --org team_xxx
768
+
769
+ Writes ~/.hushdrop/config.json (infra). Edit skill/brand/brand.json for your name,
770
+ colors and social links. Then: hush setup --token <vercel_blob_rw_...>
771
+ See SETUP.md to stand up the Blob store + domain rewrite first.`);
772
+ }
773
+ let existing = {};
774
+ try { existing = JSON.parse(readFileSync(CONFIG_FILE, "utf8")); } catch {}
775
+ const merged = { ...existing, ...cfg };
776
+ await mkdir(DROP_HOME, { recursive: true });
777
+ await writeFile(CONFIG_FILE, JSON.stringify(merged, null, 2) + "\n");
778
+ ok(`config saved to ${CONFIG_FILE}`);
779
+ console.log(` domain: ${merged.domain || DEFAULTS.domain}`);
780
+ console.log(` blob host: ${merged.blobHost || DEFAULTS.blobHost}`);
781
+ console.log(`\nNext: hush setup --token <vercel_blob_rw_...> (or: vercel login, then hush setup)`);
782
+ }
783
+
784
+ const KNOWN_PROJECT = { projectId: CONFIG.projectId, orgId: CONFIG.orgId };
785
+ async function pullTokenFromVercel() {
786
+ const which = spawnSync(process.platform === "win32" ? "where" : "which", ["vercel"], { stdio: ["ignore", "pipe", "ignore"], shell: process.platform === "win32" });
787
+ if (which.status !== 0) return null;
788
+ const tmp = await mkdtemp(join(tmpdir(), "drop-setup-"));
789
+ try {
790
+ await mkdir(join(tmp, ".vercel"), { recursive: true });
791
+ await writeFile(join(tmp, ".vercel", "project.json"), JSON.stringify(KNOWN_PROJECT));
792
+ const r = spawnSync("vercel", ["env", "pull", ".env.pull", "--environment=production", "--yes"], {
793
+ cwd: tmp, stdio: ["ignore", "ignore", "inherit"], shell: process.platform === "win32",
794
+ });
795
+ if (r.status !== 0) return null;
796
+ const txt = await readFile(join(tmp, ".env.pull"), "utf8");
797
+ const match = txt.match(/^\s*BLOB_READ_WRITE_TOKEN\s*=\s*["']?([^"'\n\r]+)/m);
798
+ return match ? match[1].trim() : null;
799
+ } catch { return null; }
800
+ finally { await rm(tmp, { recursive: true, force: true }); }
801
+ }
802
+
803
+ // ---------- hosted accounts (hush login / whoami / logout) ----------
804
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
805
+ function getApiKey() {
806
+ if (process.env.DROP_API_KEY) return process.env.DROP_API_KEY;
807
+ try { return JSON.parse(readFileSync(CONFIG_FILE, "utf8")).apiKey || null; } catch { return null; }
808
+ }
809
+ async function saveApiKey(key) {
810
+ let cfg = {}; try { cfg = JSON.parse(readFileSync(CONFIG_FILE, "utf8")); } catch {}
811
+ cfg.apiKey = key;
812
+ await mkdir(DROP_HOME, { recursive: true });
813
+ await writeFile(CONFIG_FILE, JSON.stringify(cfg, null, 2) + "\n");
814
+ }
815
+ function openBrowser(url) {
816
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
817
+ // Detached + non-blocking: spawnSync would HANG the login (and its poll loop) if the
818
+ // opener doesn't return promptly — e.g. on headless machines where xdg-open stalls.
819
+ try { const c = spawn(cmd, [url], { stdio: "ignore", shell: process.platform === "win32", detached: true }); c.unref(); } catch {}
820
+ }
821
+ async function cmdLogin(opts) {
822
+ if (opts.token && opts.token.startsWith("drop_")) { await saveApiKey(opts.token); ok("API key saved"); return cmdWhoami(); }
823
+ let start;
824
+ try { start = await (await fetch(`${ORIGIN}/api/auth/device/start`, { method: "POST" })).json(); }
825
+ catch (e) { die(`could not reach ${ORIGIN}: ${e.message}`); }
826
+ if (!start?.code) die("login unavailable (hosted tier not configured yet)");
827
+ console.log(`\n opening ${start.verify_url}`);
828
+ console.log(` \x1b[2mif it doesn't open, paste that URL into your browser\x1b[0m\n`);
829
+ openBrowser(start.verify_url);
830
+ const deadline = Date.now() + 5 * 60 * 1000;
831
+ process.stdout.write(" waiting for you to approve");
832
+ while (Date.now() < deadline) {
833
+ await sleep((start.poll_interval || 2) * 1000);
834
+ process.stdout.write(".");
835
+ let p; try { p = await (await fetch(`${ORIGIN}/api/auth/device/poll?code=${start.code}`)).json(); } catch { continue; }
836
+ if (p.status === "approved" && p.api_key) { console.log(""); await saveApiKey(p.api_key); ok(`logged in — key saved to ${CONFIG_FILE}`); return cmdWhoami(); }
837
+ if (p.status === "denied") { console.log(""); die("authorization denied"); }
838
+ if (p.status === "expired") { console.log(""); die("code expired — run `hush login` again"); }
839
+ }
840
+ console.log(""); die("login timed out");
841
+ }
842
+ async function cmdWhoami() {
843
+ const key = getApiKey(); if (!key) die("not logged in. Run: hush login");
844
+ let r; try { r = await fetch(`${ORIGIN}/api/me`, { headers: { authorization: `Bearer ${key}` } }); } catch (e) { die(e.message); }
845
+ if (!r.ok) die("not authenticated (key invalid or revoked). Run: hush login");
846
+ const d = await r.json();
847
+ if (JSON_OUT) { console.log(JSON.stringify(d)); return; }
848
+ ok(`${d.email || "logged in"}${d.handle ? ` · handle: ${d.handle}` : ""}`);
849
+ }
850
+ async function cmdLogout() {
851
+ let cfg = {}; try { cfg = JSON.parse(readFileSync(CONFIG_FILE, "utf8")); } catch {}
852
+ delete cfg.apiKey;
853
+ await mkdir(DROP_HOME, { recursive: true });
854
+ await writeFile(CONFIG_FILE, JSON.stringify(cfg, null, 2) + "\n");
855
+ ok("logged out");
856
+ }
857
+
858
+ // ---------- hosted-drop management (Phase 2: set-* / claim / share / migrate) ----------
859
+ // Thin authenticated calls against the hosted API. Each needs `hush login` first.
860
+ async function apiCall(path, init = {}) {
861
+ const key = getApiKey(); if (!key) die("not logged in — run: hush login");
862
+ let r; try { r = await fetch(`${ORIGIN}${path}`, { ...init, headers: { authorization: `Bearer ${key}`, ...(init.headers || {}) } }); }
863
+ catch (e) { die(`request failed: ${e.message}`); }
864
+ let d = {}; try { d = await r.json(); } catch {}
865
+ if (!r.ok) die(d.error || `request failed (${r.status})`);
866
+ return d;
867
+ }
868
+ const patchSite = (slug, patch) => apiCall(`/api/sites?slug=${encodeURIComponent(slug)}`, { method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify(patch) });
869
+
870
+ async function cmdSetExpiry(slug, when) {
871
+ if (!slug || !when) die("usage: hush set-expiry <slug> <7d|24h|2w|date|off>");
872
+ const iso = when === "off" ? null : (() => { const at = parseExpiry(when); if (!at) die(`bad expiry: ${when}`); return new Date(at).toISOString(); })();
873
+ await patchSite(slug, { expires_at: iso });
874
+ if (JSON_OUT) return console.log(JSON.stringify({ slug, expires_at: iso }));
875
+ ok(iso ? `expiry set on ${slug} → ${iso.slice(0, 16).replace("T", " ")}` : `expiry cleared on ${slug}`);
876
+ }
877
+ async function cmdSetEmailGate(slug, domain) {
878
+ if (!slug) die("usage: hush set-email-gate <slug> <domain|off> (e.g. acme.com)");
879
+ const val = !domain || domain === "off" ? null : domain.replace(/^@/, "").toLowerCase();
880
+ await patchSite(slug, { email_gate: val });
881
+ if (JSON_OUT) return console.log(JSON.stringify({ slug, email_gate: val }));
882
+ ok(val ? `email-gate on ${slug} → only @${val} may open it` : `email-gate cleared on ${slug}`);
883
+ }
884
+ async function cmdSetFeedback(slug, state) {
885
+ if (!slug) die("usage: hush set-feedback <slug> [on|off]");
886
+ const on = state !== "off";
887
+ await patchSite(slug, { feedback: on });
888
+ if (JSON_OUT) return console.log(JSON.stringify({ slug, feedback: on }));
889
+ ok(`feedback ${on ? "enabled" : "disabled"} on ${slug}`);
890
+ }
891
+ async function cmdSetPassword(slug, file) {
892
+ // Zero-knowledge: changing the password re-encrypts, which needs the source again.
893
+ if (!slug || !file) die("usage: hush set-password <slug> <file.html> [-p <password>]\n (zero-knowledge: a password change re-encrypts, so the source file is required)");
894
+ if (!existsSync(file)) die(`no such file: ${file}`);
895
+ return cmdDrop(file, { ...opts, slug, noLock: false, password: opts.password || genPassword() });
896
+ }
897
+ async function cmdClaim(target) {
898
+ if (!target) die("usage: hush claim <url|slug> (move an anonymous /u/ drop into your account)");
899
+ if (!getApiKey()) die("not logged in — run: hush login");
900
+ const url = /^https?:/.test(target) ? target : `${ORIGIN}/u/${target.replace(/^u\//, "")}`;
901
+ let body; try { const r = await fetch(url); if (!r.ok) die(`could not fetch ${url} (${r.status})`); body = Buffer.from(await r.arrayBuffer()); }
902
+ catch (e) { die(`could not fetch ${url}: ${e.message}`); }
903
+ const slug = opts.slug || ("claimed-" + rand(4));
904
+ const m = await hostedPublish(body, "text/html; charset=utf-8", slug, false);
905
+ if (JSON_OUT) return console.log(JSON.stringify(m));
906
+ report({ url: m.url, password: null, locked: false, extra: `claimed → ${m.handle}/${m.slug}` });
907
+ }
908
+ async function cmdShare(slug) {
909
+ if (!slug) die("usage: hush share <slug> [--revoke]");
910
+ const d = await apiCall(`/api/share`, { method: opts.revoke ? "DELETE" : "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ slug }) });
911
+ if (JSON_OUT) return console.log(JSON.stringify(d));
912
+ if (opts.revoke) return ok(`share token revoked for ${slug}`);
913
+ ok(`revocable share link → ${d.url}\n revoke anytime: hush share ${slug} --revoke`);
914
+ }
915
+ async function cmdMigrate() {
916
+ // Re-home your hosted drops onto your own Vercel Blob, then rewrite config to self-host.
917
+ const sites = (await apiCall("/api/sites")).sites || [];
918
+ const token = getToken();
919
+ if (opts.dryRun || !token) {
920
+ const tgt = token ? "your Vercel Blob" : "(no blob token yet — run `hush setup` first)";
921
+ if (JSON_OUT) return console.log(JSON.stringify({ dryRun: true, count: sites.length, target: tgt }));
922
+ return console.log(`hush migrate (dry-run): would re-upload ${sites.length} hosted drop(s) to ${tgt}, then rewrite ~/.hushdrop/config.json to self-host on your own domain.`);
923
+ }
924
+ let n = 0;
925
+ for (const s of sites) {
926
+ try { const body = Buffer.from(await (await fetch(s.url)).arrayBuffer()); await upload(`${s.slug}`, body, s.content_type || "text/html; charset=utf-8", token); n++; }
927
+ catch (e) { console.error(` skip ${s.slug}: ${e.message}`); }
928
+ }
929
+ if (JSON_OUT) return console.log(JSON.stringify({ migrated: n, of: sites.length }));
930
+ ok(`migrated ${n}/${sites.length} drops to your own blob. Run 'hush deploy' to finish self-hosting.`);
931
+ }
932
+
933
+ // ---------- arg parsing ----------
934
+ const { values, positionals } = parseArgs({
935
+ allowPositionals: true,
936
+ options: {
937
+ password: { type: "string", short: "p" },
938
+ slug: { type: "string", short: "s" },
939
+ title: { type: "string", short: "t" },
940
+ page: { type: "boolean" },
941
+ "no-lock": { type: "boolean" },
942
+ token: { type: "string" },
943
+ domain: { type: "string" },
944
+ "blob-host": { type: "string" },
945
+ project: { type: "string" },
946
+ org: { type: "string" },
947
+ json: { type: "boolean" },
948
+ expire: { type: "string" },
949
+ "dry-run": { type: "boolean" },
950
+ "no-deploy": { type: "boolean" },
951
+ managed: { type: "boolean" },
952
+ burn: { type: "boolean" },
953
+ "email-gate": { type: "string" },
954
+ revoke: { type: "boolean" },
955
+ "no-pii-check": { type: "boolean" },
956
+ "block-pii": { type: "boolean" },
957
+ help: { type: "boolean", short: "h" },
958
+ },
959
+ });
960
+ const JSON_OUT = !!values.json;
961
+
962
+ const [cmd, ...rest] = positionals;
963
+ const opts = { password: values.password, slug: values.slug, title: values.title, page: values.page, noLock: values["no-lock"], token: values.token, domain: values.domain, blobHost: values["blob-host"], project: values.project, org: values.org, expire: values.expire, dryRun: values["dry-run"], noDeploy: values["no-deploy"], managed: values.managed, burn: values.burn, emailGate: values["email-gate"], revoke: values.revoke, noPiiCheck: values["no-pii-check"], blockPii: values["block-pii"] };
964
+
965
+ try {
966
+ if (cmd === "init") await cmdInit(opts);
967
+ else if (cmd === "setup") await cmdSetup(opts);
968
+ else if (cmd === "list") await cmdList();
969
+ else if (cmd === "rm") await cmdRm(rest[0]);
970
+ else if (cmd === "gc") await cmdGc();
971
+ else if (cmd === "deploy") await cmdDeploy(opts);
972
+ else if (cmd === "login") await cmdLogin(opts);
973
+ else if (cmd === "logout") await cmdLogout();
974
+ else if (cmd === "whoami") await cmdWhoami();
975
+ else if (cmd === "claim") await cmdClaim(rest[0]);
976
+ else if (cmd === "share") await cmdShare(rest[0]);
977
+ else if (cmd === "migrate") await cmdMigrate();
978
+ else if (cmd === "set-expiry") await cmdSetExpiry(rest[0], rest[1]);
979
+ else if (cmd === "set-email-gate") await cmdSetEmailGate(rest[0], rest[1]);
980
+ else if (cmd === "set-feedback") await cmdSetFeedback(rest[0], rest[1]);
981
+ else if (cmd === "set-password") await cmdSetPassword(rest[0], rest[1]);
982
+ else if (values.help || cmd === "help" || cmd === "--help" || !cmd) {
983
+ console.log(`hush — branded password-protected sharing on ${DOMAIN}
984
+
985
+ hush <file.html|.md> brand + lock (auto password) + upload → clean URL
986
+ hush <file> --managed zero-setup: publish to the managed tier (no Vercel needed)
987
+ hush <file> -p secret use your own password
988
+ hush <file> --no-lock brand only, no password (renders for anyone)
989
+ hush <file> --expire 7d auto-expire (7d/24h/30m/2w/date); enforce with 'hush gc'
990
+ hush <file> --burn burn-after-read: the drop self-destructs on first view
991
+ hush <file> --email-gate co.com only viewers with that email domain may open it
992
+ hush <file> --block-pii refuse to publish if a secret/credential is detected
993
+ hush <file> --page branded download page wrapping the file
994
+ hush <file> --page -p secret password-protect the download page
995
+ hush site.zip multi-file static site → /slug/ (public)
996
+ hush <file> raw file, unguessable URL
997
+ hush -s myslug <file> force the slug
998
+ hush list list live drops (from the store, cross-machine)
999
+ hush rm <slug> delete a drop
1000
+ hush gc delete drops whose --expire has passed (cron-friendly)
1001
+ hush init --domain ... point hush at your own domain + Vercel Blob (BYO)
1002
+ hush login sign in (magic-link) to host on Hushdrop + persist your drops
1003
+ hush whoami show your hosted account (email + handle)
1004
+ hush logout clear your hosted account (forget the API key)
1005
+ hush claim <url|slug> move an anonymous /u/ drop into your account
1006
+ hush share <slug> [--revoke] mint (or revoke) a revocable guest share link
1007
+ hush migrate [--dry-run] re-home your hosted drops to your own blob (self-host)
1008
+ hush set-expiry <slug> <when> change a hosted drop's expiry (7d/24h/date/off)
1009
+ hush set-email-gate <slug> <domain> restrict a hosted drop to one email domain
1010
+ hush set-password <slug> <file> re-encrypt a hosted drop with a new password
1011
+ hush set-feedback <slug> [on|off] toggle the feedback widget on a hosted drop
1012
+ hush setup [--token <tok>] provision a machine (deps + blob token)
1013
+ hush deploy [--domain ...] wire backend (blob host → middleware/vercel.json) + deploy`);
1014
+ } else {
1015
+ // treat cmd as the file
1016
+ await cmdDrop(cmd, opts);
1017
+ }
1018
+ } catch (e) {
1019
+ die(e.message || String(e));
1020
+ }