|
| 1 | +// Upload a built site to Swarm through a public gateway and print the URL it |
| 2 | +// can be previewed at. Used by .github/workflows/preview.yaml, but it works |
| 3 | +// the same way when run by hand: |
| 4 | +// |
| 5 | +// node scripts/upload-to-swarm.mjs build |
| 6 | +// node scripts/upload-to-swarm.mjs build --gateway https://bzz.limo |
| 7 | +// |
| 8 | +// The directory is packed into a tar and posted to the gateway's /bzz endpoint |
| 9 | +// as a collection. https://bzz.limo pays for uploads itself, so any 32-byte |
| 10 | +// postage batch id is accepted and we do not need a funded batch of our own. |
| 11 | +// |
| 12 | +// The gateway serves a collection both at /bzz/<reference>/ and — with the |
| 13 | +// reference re-encoded as a CIDv1, which fits in a 63 character DNS label — |
| 14 | +// at https://<cid>.bzz.limo/. Only the second one serves the site from the |
| 15 | +// root, so it is the URL we report: a Docusaurus build with baseUrl "/" works |
| 16 | +// there unchanged. |
| 17 | + |
| 18 | +import { readFileSync, appendFileSync, existsSync, statSync, rmSync } from 'node:fs'; |
| 19 | +import { execFileSync } from 'node:child_process'; |
| 20 | +import { tmpdir } from 'node:os'; |
| 21 | +import { join } from 'node:path'; |
| 22 | + |
| 23 | +const DEFAULT_GATEWAY = 'https://bzz.limo'; |
| 24 | +// The gateway ignores which batch is named, but the header has to be a 32-byte hex id. |
| 25 | +const FAKE_BATCH_ID = '00'.repeat(32); |
| 26 | +const UPLOAD_TIMEOUT_MS = 10 * 60 * 1000; |
| 27 | +const UPLOAD_ATTEMPTS = 3; |
| 28 | + |
| 29 | +const args = process.argv.slice(2); |
| 30 | +const dir = args.find(arg => !arg.startsWith('--')); |
| 31 | +const gateway = (readOption('--gateway') ?? DEFAULT_GATEWAY).replace(/\/+$/, ''); |
| 32 | +const indexDocument = readOption('--index') ?? 'index.html'; |
| 33 | +const errorDocument = readOption('--error') ?? '404.html'; |
| 34 | + |
| 35 | +function readOption(name) { |
| 36 | + const index = args.indexOf(name); |
| 37 | + return index === -1 ? undefined : args[index + 1]; |
| 38 | +} |
| 39 | + |
| 40 | +if (!dir) { |
| 41 | + console.error('usage: node scripts/upload-to-swarm.mjs <directory> [--gateway url]'); |
| 42 | + process.exit(1); |
| 43 | +} |
| 44 | + |
| 45 | +if (!existsSync(dir) || !statSync(dir).isDirectory()) { |
| 46 | + console.error(`not a directory: ${dir}`); |
| 47 | + process.exit(1); |
| 48 | +} |
| 49 | + |
| 50 | +/** Encode a Swarm reference as a CIDv1 (swarm-manifest codec, keccak-256 multihash). */ |
| 51 | +function toCid(reference) { |
| 52 | + const bytes = Buffer.concat([Buffer.from([0x01, 0xfa, 0x1b, 0x20]), Buffer.from(reference, 'hex')]); |
| 53 | + const alphabet = 'abcdefghijklmnopqrstuvwxyz234567'; |
| 54 | + let bits = 0; |
| 55 | + let value = 0; |
| 56 | + let out = ''; |
| 57 | + for (const byte of bytes) { |
| 58 | + value = (value << 8) | byte; |
| 59 | + bits += 8; |
| 60 | + while (bits >= 5) { |
| 61 | + out += alphabet[(value >>> (bits - 5)) & 31]; |
| 62 | + bits -= 5; |
| 63 | + } |
| 64 | + } |
| 65 | + if (bits > 0) { |
| 66 | + out += alphabet[(value << (5 - bits)) & 31]; |
| 67 | + } |
| 68 | + return `b${out}`; |
| 69 | +} |
| 70 | + |
| 71 | +async function upload(tar) { |
| 72 | + for (let attempt = 1; attempt <= UPLOAD_ATTEMPTS; attempt++) { |
| 73 | + try { |
| 74 | + const response = await fetch(`${gateway}/bzz`, { |
| 75 | + method: 'POST', |
| 76 | + headers: { |
| 77 | + 'content-type': 'application/x-tar', |
| 78 | + 'swarm-postage-batch-id': FAKE_BATCH_ID, |
| 79 | + 'swarm-collection': 'true', |
| 80 | + 'swarm-index-document': indexDocument, |
| 81 | + 'swarm-error-document': errorDocument, |
| 82 | + }, |
| 83 | + body: tar, |
| 84 | + signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS), |
| 85 | + }); |
| 86 | + const body = await response.text(); |
| 87 | + if (!response.ok) { |
| 88 | + throw new Error(`gateway responded ${response.status}: ${body.trim()}`); |
| 89 | + } |
| 90 | + const { reference } = JSON.parse(body); |
| 91 | + if (!/^[0-9a-f]{64}$/.test(reference ?? '')) { |
| 92 | + throw new Error(`gateway returned an unexpected reference: ${body.trim()}`); |
| 93 | + } |
| 94 | + return reference; |
| 95 | + } catch (error) { |
| 96 | + console.error(`upload attempt ${attempt}/${UPLOAD_ATTEMPTS} failed: ${error.message}`); |
| 97 | + if (attempt === UPLOAD_ATTEMPTS) { |
| 98 | + process.exit(1); |
| 99 | + } |
| 100 | + } |
| 101 | + } |
| 102 | +} |
| 103 | + |
| 104 | +const tarPath = join(tmpdir(), `swarm-upload-${process.pid}.tar`); |
| 105 | +execFileSync('tar', ['-C', dir, '-cf', tarPath, '.']); |
| 106 | +const tar = readFileSync(tarPath); |
| 107 | +rmSync(tarPath, { force: true }); |
| 108 | +console.log(`uploading ${dir} (${(tar.length / 1024 / 1024).toFixed(1)} MB) to ${gateway}`); |
| 109 | + |
| 110 | +const reference = await upload(tar); |
| 111 | +const cid = toCid(reference); |
| 112 | +const url = `https://${cid}.bzz.limo/`; |
| 113 | + |
| 114 | +console.log(`reference: ${reference}`); |
| 115 | +console.log(`cid: ${cid}`); |
| 116 | +console.log(`url: ${url}`); |
| 117 | + |
| 118 | +if (process.env.GITHUB_OUTPUT) { |
| 119 | + appendFileSync(process.env.GITHUB_OUTPUT, `reference=${reference}\ncid=${cid}\nurl=${url}\n`); |
| 120 | +} |
0 commit comments