mnfst-publish 0.1.14 → 0.1.16

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/README.md CHANGED
@@ -15,5 +15,11 @@ project, zips it gitignore-aware, uploads it, and prints the live URL.
15
15
  Flags: `--staging` / `--production` (default), `--no-render`, `--promote`,
16
16
  `--source render|spa` (auto-detected), `--key <key>`, `--mcp <url>`.
17
17
 
18
- Zero dependencies, cross-platform (pure-Node zip). `.env`, `.env.*`, and
19
- `.claude/` are never uploaded.
18
+ Publishing from Claude with the Manifest connector needs no key: the command it
19
+ gives you carries a one-time upload link. While the site renders, mnfst-publish
20
+ keeps that link alive (up to 3 hours). If a link still expires, ask Claude to
21
+ publish again and add `--no-render` to the new command, so the site already
22
+ rendered on disk uploads without rendering again.
23
+
24
+ Zero dependencies, cross-platform (pure-Node zip). `.env`, `.env.*`, `.claude/`,
25
+ keys and credential files are never uploaded.
@@ -6,7 +6,7 @@
6
6
  // the MCP publish handshake, renders if needed, zips gitignore-aware, uploads,
7
7
  // and prints the live URL. Zero npm deps; cross-platform (pure-Node zip).
8
8
 
9
- import { spawnSync } from 'node:child_process';
9
+ import { spawn, spawnSync } from 'node:child_process';
10
10
  import { createHash } from 'node:crypto';
11
11
  import { deflateRawSync } from 'node:zlib';
12
12
  import { readFileSync, existsSync, statSync, readdirSync } from 'node:fs';
@@ -191,15 +191,20 @@ async function callTool(url, key, name, args) {
191
191
 
192
192
  // Never ship local config or secrets — matched at ANY depth (by path segment /
193
193
  // basename), not just the project root. A nested `api/.env` or `sub/.claude/…`
194
- // must be excluded too.
194
+ // must be excluded too. Mirrors the server's ingest drop list.
195
195
  const EXCLUDED_DIRS = new Set(['.git', 'node_modules', '.claude']);
196
+ const SECRET_DIRS = new Set(['.ssh', '.aws', '.wrangler']);
197
+ const SECRET_FILES = new Set([
198
+ '.npmrc', '.yarnrc', '.yarnrc.yml', '.pypirc', '.netrc', '_netrc', '.git-credentials', '.htpasswd',
199
+ '.dev.vars', 'id_rsa', 'id_dsa', 'id_ecdsa', 'id_ed25519', '.ds_store',
200
+ ]);
196
201
  export function isExcludedPath(rel) {
197
- const parts = rel.split('/');
198
- if (parts.some((p) => EXCLUDED_DIRS.has(p))) return true;
202
+ const parts = rel.toLowerCase().split('/');
203
+ if (parts.some((p) => EXCLUDED_DIRS.has(p) || SECRET_DIRS.has(p))) return true;
199
204
  const base = parts[parts.length - 1];
200
205
  if (base === '.env' || base.startsWith('.env.')) return true; // .env, .env.local, .env.prod …
201
- if (base === '.npmrc' || base === '.dev.vars' || base === 'id_rsa' || base === '.DS_Store') return true;
202
- if (/\.(pem|key|p12|pfx)$/i.test(base)) return true;
206
+ if (SECRET_FILES.has(base) || base.startsWith('.dev.vars.') || base.startsWith('env.local.')) return true;
207
+ if (/\.(pem|key|p12|pfx|jks|keystore)$/i.test(base)) return true;
203
208
  return false;
204
209
  }
205
210
 
@@ -419,6 +424,118 @@ export async function pollPublishStatus(statusUrl, opts = {}) {
419
424
  }
420
425
  }
421
426
 
427
+ // --- Upload link renewal ------------------------------------------------------
428
+
429
+ // A connector link expires 15 minutes after mint unless renewed, and a website
430
+ // render can take an hour. While rendering, renew it on this interval (well
431
+ // inside the window, so a missed beat or two is harmless) and once more right
432
+ // before uploading. The server caps how long a link can be kept alive.
433
+ const RENEW_EVERY_MS = 5 * 60 * 1000;
434
+ // A hung renewal must not stall the publish; a timeout counts as a blip.
435
+ const RENEW_TIMEOUT_MS = 15_000;
436
+
437
+ export function renewUrlFor(uploadUrl) {
438
+ return uploadUrl.replace(/\/+$/, '') + '/renew';
439
+ }
440
+
441
+ /**
442
+ * One renewal. Resolves `{state, body}`:
443
+ * renewed the link is good for another window
444
+ * expired the link is used, expired or unknown (410)
445
+ * unsupported the server has no renew route, or will not extend this link
446
+ * retry a blip, 429 or 5xx: try again next time
447
+ */
448
+ export async function renewUploadLink(uploadUrl, opts = {}) {
449
+ const { fetchImpl = fetch } = opts;
450
+ let status = 0;
451
+ let json = null;
452
+ try {
453
+ const res = await fetchImpl(renewUrlFor(uploadUrl), {
454
+ method: 'POST',
455
+ headers: { accept: 'application/json' },
456
+ signal: AbortSignal.timeout(RENEW_TIMEOUT_MS),
457
+ });
458
+ status = res.status;
459
+ const text = await res.text();
460
+ try {
461
+ json = text ? JSON.parse(text) : null;
462
+ } catch {
463
+ /* not JSON */
464
+ }
465
+ } catch {
466
+ return { state: 'retry' };
467
+ }
468
+ if (status === 200 && json && json.status === 'pending') return { state: 'renewed', body: json };
469
+ if (status === 410) return { state: 'expired', body: json };
470
+ if (status === 429 || status >= 500 || status === 0) return { state: 'retry', body: json };
471
+ return { state: 'unsupported', body: json };
472
+ }
473
+
474
+ /**
475
+ * Renew `uploadUrl` every `intervalMs` until finish(). finish() stops the
476
+ * timer, waits for any renewal in flight (so none races the upload), renews
477
+ * once more and resolves the link's state: active | expired | unsupported.
478
+ */
479
+ export function keepUploadLinkAlive(uploadUrl, opts = {}) {
480
+ const {
481
+ fetchImpl = fetch,
482
+ intervalMs = RENEW_EVERY_MS,
483
+ setTimer = setTimeout,
484
+ clearTimer = clearTimeout,
485
+ log: logFn = log,
486
+ } = opts;
487
+ let state = 'active';
488
+ let timer = null;
489
+ let inFlight = null;
490
+ let stopped = false;
491
+
492
+ const renew = async () => {
493
+ const r = await renewUploadLink(uploadUrl, { fetchImpl });
494
+ if (r.state === 'expired' && state !== 'expired') {
495
+ state = 'expired';
496
+ logFn(' the publish link expired. The render carries on so its output is kept on disk.');
497
+ } else if (r.state === 'unsupported') {
498
+ state = 'unsupported';
499
+ }
500
+ };
501
+ const schedule = () => {
502
+ if (stopped || state !== 'active') return;
503
+ timer = setTimer(() => {
504
+ timer = null;
505
+ inFlight = renew().finally(() => {
506
+ inFlight = null;
507
+ schedule();
508
+ });
509
+ }, intervalMs);
510
+ if (timer && typeof timer.unref === 'function') timer.unref();
511
+ };
512
+ schedule();
513
+
514
+ return {
515
+ get state() {
516
+ return state;
517
+ },
518
+ async finish() {
519
+ stopped = true;
520
+ if (timer) clearTimer(timer);
521
+ timer = null;
522
+ if (inFlight) await inFlight;
523
+ if (state === 'active') await renew();
524
+ return state;
525
+ },
526
+ };
527
+ }
528
+
529
+ /** What to do when the link is gone: a new link, and no second render when the output is already on disk. */
530
+ export function expiredLinkAdvice({ rendered = false, outputDir = 'website' } = {}) {
531
+ const base = 'this publish link expired before the upload. Run manifest_publish again for a new link and run the command it returns.';
532
+ return rendered ? `${base} ${noRenderHint(outputDir)}` : base;
533
+ }
534
+
535
+ function noRenderHint(outputDir) {
536
+ return `The site is already rendered in "${outputDir}", so add --no-render to the new command to upload it without rendering again.`;
537
+ }
538
+
422
539
  /** Turn a settled poll result into the success payload, or throw a plain-language error. */
423
540
  function settledPayload(res) {
424
541
  if (res.state === 'done') return res.body;
@@ -501,6 +618,13 @@ export async function uploadBundle(uploadUrl, zip, opts = {}) {
501
618
  return settledPayload(await poll({}));
502
619
  }
503
620
 
621
+ // The link is used, expired or unknown: nothing to retry with it.
622
+ if (res.status === 410) {
623
+ const err = new Error((json && json.message) || 'Publish link expired or already used.');
624
+ err.code = 'link_expired';
625
+ throw err;
626
+ }
627
+
504
628
  if (res.status >= 500 && attempt < tries) {
505
629
  logFn(` the upload server had a hiccup (HTTP ${res.status}) — retrying (${attempt}/${tries - 1})…`);
506
630
  await sleepImpl(500 * attempt);
@@ -631,6 +755,35 @@ function buildZip(root, rels, overrides = new Map()) {
631
755
 
632
756
  // --- Main ------------------------------------------------------------------
633
757
 
758
+ function runCommand(cmd, args, options) {
759
+ return new Promise((resolve) => {
760
+ const child = spawn(cmd, args, options);
761
+ child.on('error', () => resolve(1));
762
+ child.on('exit', (code) => resolve(code ?? 1));
763
+ });
764
+ }
765
+
766
+ // The upload carries the whole project. Only POST it to an HTTPS endpoint on
767
+ // the SAME host as the MCP server — never to an arbitrary URL a tampered
768
+ // response or misconfigured .mcp.json could inject.
769
+ function checkUploadUrl(uploadUrl, mcpUrl) {
770
+ let u;
771
+ let mcpHost;
772
+ try {
773
+ u = new URL(uploadUrl);
774
+ mcpHost = new URL(mcpUrl).host;
775
+ } catch {
776
+ fail('the upload URL returned by the server was malformed.');
777
+ }
778
+ // Same host as the configured MCP, or the canonical first-party host — a
779
+ // project whose .mcp.json still points at the legacy workers.dev URL gets
780
+ // upload links minted on mcp.manifestx.dev during the domain migration.
781
+ const canonical = new URL(DEFAULT_MCP).host;
782
+ if (u.protocol !== 'https:' || (u.host !== mcpHost && u.host !== canonical)) {
783
+ fail(`refusing to upload to an unexpected endpoint (${u.protocol}//${u.host}); expected https://${mcpHost} or https://${canonical}.`);
784
+ }
785
+ }
786
+
634
787
  export async function main() {
635
788
  const opts = parseArgs(process.argv.slice(2));
636
789
  if (opts.help) {
@@ -667,10 +820,16 @@ export async function main() {
667
820
  fail('no API key found. Publish from Claude with the Manifest connector (no key needed), or set MANIFEST_API_KEY in .env for headless/CI use.');
668
821
  }
669
822
 
670
- if (source === 'render' && opts.render !== false) {
823
+ // Checked before rendering, since the link is renewed while the render runs.
824
+ if (injectedUpload) checkUploadUrl(injectedUpload, url);
825
+ const keepAlive = injectedUpload ? keepUploadLinkAlive(injectedUpload) : null;
826
+
827
+ const rendering = source === 'render' && opts.render !== false;
828
+ if (rendering) {
671
829
  log('Rendering the site…');
672
- const r = spawnSync('npx', ['mnfst-render'], { cwd: root, stdio: 'inherit', shell: process.platform === 'win32' });
673
- if (r.status !== 0) fail('render failed — fix the errors above and try again.');
830
+ // Async, so the renewal timer runs during the render.
831
+ const code = await runCommand('npx', ['mnfst-render'], { cwd: root, stdio: 'inherit', shell: process.platform === 'win32' });
832
+ if (code !== 0) fail('render failed — fix the errors above and try again.');
674
833
  }
675
834
 
676
835
  // For a render project, sanity-check there's actually a built site to ship —
@@ -701,22 +860,7 @@ export async function main() {
701
860
  const handshake = await callTool(url, key, 'manifest_publish', { env: opts.env, source, via_cli: true });
702
861
  uploadUrl = handshake.upload_url;
703
862
  if (!uploadUrl) fail(handshake._text || 'could not start the publish (no upload URL returned).');
704
- }
705
- // The upload carries the whole project. Only POST it to an HTTPS endpoint on
706
- // the SAME host as the MCP server — never to an arbitrary URL a tampered
707
- // response or misconfigured .mcp.json could inject.
708
- try {
709
- const u = new URL(uploadUrl);
710
- const mcpHost = new URL(url).host;
711
- // Same host as the configured MCP, or the canonical first-party host — a
712
- // project whose .mcp.json still points at the legacy workers.dev URL gets
713
- // upload links minted on mcp.manifestx.dev during the domain migration.
714
- const canonical = new URL(DEFAULT_MCP).host;
715
- if (u.protocol !== 'https:' || (u.host !== mcpHost && u.host !== canonical)) {
716
- fail(`refusing to upload to an unexpected endpoint (${u.protocol}//${u.host}); expected https://${mcpHost} or https://${canonical}.`);
717
- }
718
- } catch {
719
- fail('the upload URL returned by the server was malformed.');
863
+ checkUploadUrl(uploadUrl, url);
720
864
  }
721
865
 
722
866
  const rels = collectFiles(root, opts.outputDir);
@@ -725,12 +869,18 @@ export async function main() {
725
869
  fail(`the output folder "${opts.outputDir}" doesn't exist — run the project's build first, then publish again.`);
726
870
  }
727
871
  const zip = buildZip(root, rels, stampManifests(root, rels));
872
+ const recovery = { rendered: source === 'render', outputDir: prerenderOutputDir(root) };
873
+ // Last renewal before the upload; an older server without renewal just uploads as before.
874
+ if (keepAlive && (await keepAlive.finish()) === 'expired') fail(expiredLinkAdvice(recovery));
728
875
  log(`Uploading ${rels.length} files (${(zip.length / 1048576).toFixed(1)} MB)…`);
729
876
 
730
877
  let upJson;
731
878
  try {
732
879
  upJson = await uploadBundle(uploadUrl, zip);
733
880
  } catch (e) {
881
+ if (e.code === 'link_expired') {
882
+ fail(/--no-render/.test(e.message) || !recovery.rendered ? e.message : `${e.message} ${noRenderHint(recovery.outputDir)}`);
883
+ }
734
884
  fail(e.message);
735
885
  }
736
886
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mnfst-publish",
3
- "version": "0.1.14",
3
+ "version": "0.1.16",
4
4
  "description": "One-command managed publishing for Manifest projects — render, zip, upload, live URL.",
5
5
  "type": "module",
6
6
  "bin": {