mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-06 00:27:24 +00:00
Update nsite deployment
Add support for named sites under users key
This commit is contained in:
1 parent
c5ed881af0
commit
d51fee34e3
11 files changed
+1200
-262
No files matched your search
+315
-113
@@ -1,174 +1,376 @@
|
||||
import { BlossomUploader } from '@nostrify/nostrify/uploaders';
|
||||
import { NSecSigner, NPool } from '@nostrify/nostrify';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import type { NostrSigner, NPool } from '@nostrify/nostrify';
|
||||
import mime from 'mime';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
import type { DeployAdapter, DeployOptions, DeployResult, NsiteDeployConfig } from './types';
|
||||
import { buildNsiteUrl } from '../utils/nsite';
|
||||
|
||||
/** nsite v2 root-site kind (replaceable by pubkey+kind) */
|
||||
const NSITE_ROOT_SITE_KIND = 15128;
|
||||
|
||||
/** nsite v2 named-site kind (addressable by pubkey+kind+d) */
|
||||
const NSITE_NAMED_SITE_KIND = 35128;
|
||||
|
||||
/** BUD-02 Blossom authorization event kind */
|
||||
const BLOSSOM_AUTH_KIND = 24242;
|
||||
|
||||
/** Max number of sha256 hashes covered by one batch auth event */
|
||||
const UPLOAD_AUTH_BATCH_SIZE = 20;
|
||||
|
||||
/** Max concurrent uploads per Blossom server */
|
||||
const UPLOAD_CONCURRENCY = 4;
|
||||
|
||||
/** Timeout for individual HTTP requests (ms) */
|
||||
const FETCH_TIMEOUT_MS = 15_000;
|
||||
|
||||
interface FileEntry {
|
||||
/** Absolute path in the manifest, e.g. "/index.html" */
|
||||
path: string;
|
||||
/** Raw file bytes as a concrete ArrayBuffer (for Web Crypto + File constructor compatibility) */
|
||||
data: ArrayBuffer;
|
||||
/** Lower-case hex SHA-256 of data */
|
||||
sha256: string;
|
||||
/** MIME type */
|
||||
contentType: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Nsite Deploy Adapter
|
||||
* Deploys static sites to Nostr using kind 34128 events and Blossom file storage
|
||||
* Encode an ArrayBuffer / Uint8Array as a lower-case hex string.
|
||||
*/
|
||||
function encodeHex(bytes: Uint8Array): string {
|
||||
return Array.from(bytes)
|
||||
.map(b => b.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the SHA-256 of a Uint8Array and return the hex digest.
|
||||
* The Uint8Array must already be backed by a concrete ArrayBuffer
|
||||
* (use raw.slice() before calling this to ensure no SharedArrayBuffer).
|
||||
*/
|
||||
async function sha256Hex(data: Uint8Array): Promise<string> {
|
||||
const buf = await crypto.subtle.digest('SHA-256', data.buffer as ArrayBuffer);
|
||||
return encodeHex(new Uint8Array(buf));
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a BUD-02 kind-24242 upload-auth event template covering multiple blobs.
|
||||
* The signed event is base64-encoded and returned as the full Authorization header value.
|
||||
*/
|
||||
async function createBatchUploadAuth(
|
||||
signer: NostrSigner,
|
||||
sha256Hashes: string[],
|
||||
): Promise<string> {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const template = {
|
||||
kind: BLOSSOM_AUTH_KIND,
|
||||
created_at: now,
|
||||
tags: [
|
||||
['t', 'upload'],
|
||||
...sha256Hashes.map(h => ['x', h]),
|
||||
['expiration', String(now + 3600)],
|
||||
],
|
||||
content: 'Upload blobs',
|
||||
};
|
||||
const signed = await signer.signEvent(template);
|
||||
return `Nostr ${btoa(JSON.stringify(signed))}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a blob already exists on a Blossom server.
|
||||
* Returns true if the server responds 2xx to a HEAD request.
|
||||
*/
|
||||
async function blobExistsOnServer(serverBase: string, sha256: string): Promise<boolean> {
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
||||
try {
|
||||
const resp = await fetch(`${serverBase}/${sha256}`, {
|
||||
method: 'HEAD',
|
||||
signal: controller.signal,
|
||||
});
|
||||
return resp.ok;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload a single file to a single Blossom server using a pre-signed auth header.
|
||||
* Skips the upload if the blob already exists on the server.
|
||||
* Returns true on success or if already present.
|
||||
*/
|
||||
async function uploadToServer(
|
||||
serverBase: string,
|
||||
file: FileEntry,
|
||||
authHeader: string,
|
||||
): Promise<boolean> {
|
||||
// Skip if already present
|
||||
if (await blobExistsOnServer(serverBase, file.sha256)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const blob = new File([file.data], file.path.split('/').pop() || 'file', {
|
||||
type: file.contentType,
|
||||
});
|
||||
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
||||
try {
|
||||
const resp = await fetch(`${serverBase}/upload`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
Authorization: authHeader,
|
||||
'Content-Type': file.contentType,
|
||||
},
|
||||
body: blob,
|
||||
signal: controller.signal,
|
||||
});
|
||||
return resp.ok;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run an async task queue with a fixed concurrency limit.
|
||||
*/
|
||||
async function runConcurrent<T>(
|
||||
items: T[],
|
||||
limit: number,
|
||||
fn: (item: T) => Promise<void>,
|
||||
): Promise<void> {
|
||||
let index = 0;
|
||||
async function worker() {
|
||||
while (index < items.length) {
|
||||
const item = items[index++];
|
||||
await fn(item);
|
||||
}
|
||||
}
|
||||
const workers: Promise<void>[] = [];
|
||||
for (let i = 0; i < Math.min(limit, items.length); i++) {
|
||||
workers.push(worker());
|
||||
}
|
||||
await Promise.all(workers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Nsite Deploy Adapter — v2 implementation
|
||||
*
|
||||
* Deploys a built project as a Nostr static site using the nsite v2 spec:
|
||||
* - Uses the logged-in user's NostrSigner — no dedicated per-site keypair needed
|
||||
* - Pre-hashes all files with SHA-256 (Web Crypto API)
|
||||
* - Signs batched BUD-02 kind-24242 auth tokens (20 files per signing call)
|
||||
* - HEAD-checks each file on each Blossom server before uploading
|
||||
* - PUTs files to Blossom servers with pre-signed auth headers
|
||||
* - Publishes a single kind-15128 (root) or kind-35128 (named) site manifest event
|
||||
* containing all ["path", "/path", sha256] tags, ["server", url] Blossom hints,
|
||||
* and ["relay", url] relay hints — no separate kind 10002 or kind 10063 published
|
||||
*
|
||||
* Named sites (kind 35128, siteIdentifier set):
|
||||
* URL = https://{base36pubkey}{siteIdentifier}.{gateway}
|
||||
* Root sites (kind 15128, no siteIdentifier):
|
||||
* URL = https://{npub}.{gateway}
|
||||
*/
|
||||
export class NsiteAdapter implements DeployAdapter {
|
||||
private fs: JSRuntimeFS;
|
||||
private nostr: NsiteDeployConfig['nostr'];
|
||||
private nsec: string;
|
||||
private signer: NostrSigner;
|
||||
private gateway: string;
|
||||
private relayUrls: string[];
|
||||
private blossomServers: string[];
|
||||
private siteTitle?: string;
|
||||
private siteDescription?: string;
|
||||
private siteIdentifier?: string;
|
||||
|
||||
constructor(config: NsiteDeployConfig) {
|
||||
this.fs = config.fs;
|
||||
this.nostr = config.nostr;
|
||||
this.nsec = config.nsec;
|
||||
this.signer = config.signer;
|
||||
this.gateway = config.gateway;
|
||||
this.relayUrls = config.relayUrls;
|
||||
this.blossomServers = config.blossomServers;
|
||||
this.siteTitle = config.siteTitle;
|
||||
this.siteDescription = config.siteDescription;
|
||||
this.siteIdentifier = config.siteIdentifier;
|
||||
}
|
||||
|
||||
async deploy(options: DeployOptions): Promise<DeployResult> {
|
||||
const { projectPath } = options;
|
||||
|
||||
// Check if dist directory exists and contains index.html
|
||||
const distPath = `${projectPath}/dist`;
|
||||
|
||||
// Verify build output exists
|
||||
try {
|
||||
await this.fs.readFile(`${distPath}/index.html`, 'utf8');
|
||||
} catch {
|
||||
throw new Error('No index.html found in dist directory. Please build the project first.');
|
||||
}
|
||||
|
||||
// Decode nsec to get the private key and create signer
|
||||
const decoded = nip19.decode(this.nsec);
|
||||
if (decoded.type !== 'nsec') {
|
||||
throw new Error('Invalid nsec format');
|
||||
}
|
||||
const signer = new NSecSigner(decoded.data);
|
||||
const pubkey = await signer.getPublicKey();
|
||||
const pubkey = await this.signer.getPublicKey();
|
||||
const npub = nip19.npubEncode(pubkey);
|
||||
|
||||
// Create a grouped Nostr client for the configured relays
|
||||
// Create grouped relay client
|
||||
const relayClient = this.nostr.group(this.relayUrls);
|
||||
|
||||
// Initialize Blossom uploader
|
||||
const uploader = new BlossomUploader({
|
||||
servers: this.blossomServers,
|
||||
signer,
|
||||
// ── Step 1: Walk dist/ and read + hash all files ──────────────────────────
|
||||
const files: FileEntry[] = [];
|
||||
await this.collectFiles(distPath, '', files);
|
||||
|
||||
if (files.length === 0) {
|
||||
throw new Error('No files found in dist directory.');
|
||||
}
|
||||
|
||||
// ── Step 2: Pre-sign batched BUD-02 auth tokens ───────────────────────────
|
||||
// One kind-24242 event covers up to UPLOAD_AUTH_BATCH_SIZE sha256 hashes,
|
||||
// dramatically reducing signer calls when using remote signers/bunkers.
|
||||
const authTokenMap = new Map<string, string>();
|
||||
for (let i = 0; i < files.length; i += UPLOAD_AUTH_BATCH_SIZE) {
|
||||
const batch = files.slice(i, i + UPLOAD_AUTH_BATCH_SIZE);
|
||||
const hashes = batch.map(f => f.sha256);
|
||||
const authHeader = await createBatchUploadAuth(this.signer, hashes);
|
||||
for (const hash of hashes) {
|
||||
authTokenMap.set(hash, authHeader);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Step 3: Upload files to each Blossom server ───────────────────────────
|
||||
// All servers upload concurrently; within each server, files are uploaded
|
||||
// with limited concurrency to avoid overwhelming the server.
|
||||
// Track which files land on at least one server — a file missing from every
|
||||
// server means the manifest would point to an unreachable blob.
|
||||
const serverBases = this.blossomServers.map(s => s.replace(/\/$/, ''));
|
||||
|
||||
// uploadedSha256s: set of sha256 hashes confirmed present on ≥1 server
|
||||
const uploadedSha256s = new Set<string>();
|
||||
|
||||
await Promise.all(
|
||||
serverBases.map(serverBase =>
|
||||
runConcurrent(files, UPLOAD_CONCURRENCY, async (file) => {
|
||||
const authHeader = authTokenMap.get(file.sha256);
|
||||
if (!authHeader) return;
|
||||
const ok = await uploadToServer(serverBase, file, authHeader);
|
||||
if (ok) {
|
||||
uploadedSha256s.add(file.sha256);
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
// Fail fast: any file unreachable on all servers means the deployed site
|
||||
// would serve broken responses for those paths — abort before publishing.
|
||||
const failedFiles = files.filter(f => !uploadedSha256s.has(f.sha256));
|
||||
if (failedFiles.length > 0) {
|
||||
const paths = failedFiles.map(f => f.path).join(', ');
|
||||
throw new Error(
|
||||
`Failed to upload ${failedFiles.length} file(s) to any Blossom server: ${paths}`,
|
||||
);
|
||||
}
|
||||
|
||||
// ── Step 4: Build the site manifest event ────────────────────────────────
|
||||
// kind 35128 for named sites (has siteIdentifier / d tag)
|
||||
// kind 15128 for root site (no d tag)
|
||||
const isNamedSite = Boolean(this.siteIdentifier);
|
||||
const manifestKind = isNamedSite ? NSITE_NAMED_SITE_KIND : NSITE_ROOT_SITE_KIND;
|
||||
|
||||
const pathTags: string[][] = files.map(f => ['path', f.path, f.sha256]);
|
||||
|
||||
// SPA fallback: map /404.html to the same blob as /index.html so that
|
||||
// React Router (and other SPAs) work correctly — the nsite host server
|
||||
// serves /404.html when a path is not found, acting as a client-side router fallback.
|
||||
const indexFile = files.find(f => f.path === '/index.html');
|
||||
if (indexFile && !files.some(f => f.path === '/404.html')) {
|
||||
pathTags.push(['path', '/404.html', indexFile.sha256]);
|
||||
}
|
||||
|
||||
const serverTags: string[][] = serverBases.map(url => ['server', url]);
|
||||
const relayTags: string[][] = this.relayUrls.map(url => ['relay', url]);
|
||||
|
||||
const tags: string[][] = [];
|
||||
|
||||
// d tag must come first for addressable events (kind 35128)
|
||||
if (isNamedSite && this.siteIdentifier) {
|
||||
tags.push(['d', this.siteIdentifier]);
|
||||
}
|
||||
|
||||
tags.push(...pathTags, ...serverTags, ...relayTags);
|
||||
|
||||
if (this.siteTitle) {
|
||||
tags.push(['title', this.siteTitle]);
|
||||
}
|
||||
|
||||
if (this.siteDescription) {
|
||||
tags.push(['description', this.siteDescription]);
|
||||
}
|
||||
|
||||
const manifestEvent = await this.signer.signEvent({
|
||||
kind: manifestKind,
|
||||
content: '',
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
tags,
|
||||
});
|
||||
|
||||
// Collect all files and upload them
|
||||
const fileEvents: NostrEvent[] = [];
|
||||
await this.uploadDirectory(distPath, '', uploader, signer, fileEvents);
|
||||
// ── Step 5: Publish manifest ──────────────────────────────────────────────
|
||||
// Relay and server hints are embedded as tags in the manifest itself —
|
||||
// no separate kind 10002 or kind 10063 events are published.
|
||||
await relayClient.event(manifestEvent, { signal: AbortSignal.timeout(10_000) });
|
||||
|
||||
// Publish file events and other metadata to the relays
|
||||
await Promise.all([
|
||||
this.publishRelayList(signer, relayClient),
|
||||
this.publishServerList(signer, relayClient),
|
||||
...fileEvents.map(event => relayClient.event(event, { signal: AbortSignal.timeout(5000) })),
|
||||
]);
|
||||
|
||||
// Generate npub subdomain
|
||||
const npub = nip19.npubEncode(pubkey);
|
||||
const siteUrl = `https://${npub}.${this.gateway}`;
|
||||
// Build the deployed URL
|
||||
const siteUrl = buildNsiteUrl({
|
||||
pubkeyHex: pubkey,
|
||||
npub,
|
||||
gateway: this.gateway,
|
||||
siteIdentifier: this.siteIdentifier,
|
||||
});
|
||||
|
||||
return {
|
||||
url: siteUrl,
|
||||
metadata: {
|
||||
pubkey,
|
||||
npub,
|
||||
filesPublished: fileEvents.length,
|
||||
filesPublished: files.length,
|
||||
provider: 'nsite',
|
||||
siteIdentifier: this.siteIdentifier,
|
||||
manifestKind,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private async uploadDirectory(
|
||||
/**
|
||||
* Recursively walk a directory in the VFS, reading every file and computing its SHA-256.
|
||||
* Populates the provided `files` array with fully resolved FileEntry objects.
|
||||
*/
|
||||
private async collectFiles(
|
||||
dirPath: string,
|
||||
relativePath: string,
|
||||
uploader: BlossomUploader,
|
||||
signer: NSecSigner,
|
||||
fileEvents: NostrEvent[]
|
||||
relativePrefix: string,
|
||||
files: FileEntry[],
|
||||
): Promise<void> {
|
||||
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = `${dirPath}/${entry.name}`;
|
||||
const relPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
|
||||
const relPath = relativePrefix ? `${relativePrefix}/${entry.name}` : entry.name;
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
await this.uploadDirectory(fullPath, relPath, uploader, signer, fileEvents);
|
||||
await this.collectFiles(fullPath, relPath, files);
|
||||
} else if (entry.isFile()) {
|
||||
await this.uploadFile(fullPath, relPath, uploader, signer, fileEvents);
|
||||
const raw = await this.fs.readFile(fullPath) as Uint8Array;
|
||||
// raw.slice() copies bytes into a new Uint8Array backed by a concrete ArrayBuffer,
|
||||
// avoiding the SharedArrayBuffer variant that Web Crypto and File refuse.
|
||||
const sliced = raw.slice();
|
||||
const data: ArrayBuffer = sliced.buffer as ArrayBuffer;
|
||||
const sha256 = await sha256Hex(sliced);
|
||||
const absolutePath = `/${relPath}`;
|
||||
const contentType = mime.getType(fullPath) || 'application/octet-stream';
|
||||
|
||||
files.push({ path: absolutePath, data, sha256, contentType });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async uploadFile(
|
||||
filePath: string,
|
||||
relativePath: string,
|
||||
uploader: BlossomUploader,
|
||||
signer: NSecSigner,
|
||||
fileEvents: NostrEvent[]
|
||||
): Promise<void> {
|
||||
try {
|
||||
// Read file content
|
||||
const content = await this.fs.readFile(filePath);
|
||||
|
||||
// Convert to File object for upload
|
||||
const file = new File([content], relativePath.split('/').pop() || 'file', {
|
||||
type: mime.getType(filePath) || undefined,
|
||||
});
|
||||
|
||||
// Upload to Blossom and get tags
|
||||
const tags = await uploader.upload(file);
|
||||
|
||||
// Extract sha256 hash from tags
|
||||
// Tags format: [['url', 'https://...'], ['x', 'sha256hash'], ['size', '1234'], ...]
|
||||
const xTag = tags.find(([name]) => name === 'x');
|
||||
if (!xTag || !xTag[1]) {
|
||||
throw new Error(`Failed to get sha256 hash for ${relativePath}`);
|
||||
}
|
||||
const sha256 = xTag[1];
|
||||
|
||||
// Create absolute path (must start with /)
|
||||
const absolutePath = relativePath.startsWith('/') ? relativePath : `/${relativePath}`;
|
||||
|
||||
// Create kind 34128 event
|
||||
const event = await signer.signEvent({
|
||||
kind: 34128,
|
||||
content: '',
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
tags: [
|
||||
['d', absolutePath],
|
||||
['x', sha256],
|
||||
],
|
||||
});
|
||||
|
||||
fileEvents.push(event);
|
||||
} catch (error) {
|
||||
console.warn(`Failed to upload file ${filePath}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async publishRelayList(signer: NSecSigner, relayClient: NPool): Promise<void> {
|
||||
const relayListEvent = await signer.signEvent({
|
||||
kind: 10002,
|
||||
content: '',
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
tags: this.relayUrls.map(url => ['r', url]),
|
||||
});
|
||||
|
||||
await relayClient.event(relayListEvent, { signal: AbortSignal.timeout(5000) });
|
||||
}
|
||||
|
||||
private async publishServerList(signer: NSecSigner, relayClient: NPool): Promise<void> {
|
||||
const serverListEvent = await signer.signEvent({
|
||||
kind: 10063,
|
||||
content: '',
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
tags: this.blossomServers.map(server => ['server', server]),
|
||||
});
|
||||
|
||||
await relayClient.event(serverListEvent, { signal: AbortSignal.timeout(5000) });
|
||||
}
|
||||
}
|
||||
+12
-1
@@ -49,10 +49,21 @@ export interface VercelDeployConfig {
|
||||
export interface NsiteDeployConfig {
|
||||
fs: JSRuntimeFS;
|
||||
nostr: NPool;
|
||||
nsec: string;
|
||||
/** Nostr signer for the logged-in user — used to sign auth events and the manifest */
|
||||
signer: NostrSigner;
|
||||
gateway: string;
|
||||
relayUrls: string[];
|
||||
blossomServers: string[];
|
||||
/** Optional site title included as a ["title", ...] tag in the manifest */
|
||||
siteTitle?: string;
|
||||
/** Optional site description included as a ["description", ...] tag in the manifest */
|
||||
siteDescription?: string;
|
||||
/**
|
||||
* Optional named-site identifier (the `d` tag value).
|
||||
* When set → publishes kind 35128 (named site), URL = {base36pubkey}{identifier}.{gateway}
|
||||
* When absent → publishes kind 15128 (root site), URL = {npub}.{gateway}
|
||||
*/
|
||||
siteIdentifier?: string;
|
||||
}
|
||||
|
||||
export interface CloudflareDeployConfig {
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* Utilities for reading and writing the `.nsite/config.json` file in a project's VFS directory.
|
||||
*
|
||||
* NOTE: The site private key (nsec) is NEVER stored here. It lives only in
|
||||
* `.git/shakespeare/deploy.json` (never committed). This file is safe to commit to git.
|
||||
*/
|
||||
|
||||
import { z } from 'zod';
|
||||
import type { JSRuntimeFS } from './JSRuntime';
|
||||
|
||||
/** Path of the nsite config directory relative to a project root */
|
||||
const NSITE_CONFIG_DIR = '.nsite';
|
||||
|
||||
/** Path of the nsite config file relative to a project root */
|
||||
const NSITE_CONFIG_FILE = '.nsite/config.json';
|
||||
|
||||
/**
|
||||
* Configuration for an nsite deployment, stored in `.nsite/config.json`.
|
||||
* Unknown keys in an existing file are preserved on read and write.
|
||||
*/
|
||||
export interface NsiteVfsConfig {
|
||||
/** Nostr relay WebSocket URLs (`wss://`) */
|
||||
relays: string[];
|
||||
/** Blossom server HTTPS URLs (`https://`) */
|
||||
servers: string[];
|
||||
/**
|
||||
* Named-site d-tag identifier (kind 35128).
|
||||
* `null` or absent → root site (kind 15128).
|
||||
* Non-empty string → named site.
|
||||
*/
|
||||
id?: string | null;
|
||||
/** Optional site title included in the manifest event */
|
||||
title?: string;
|
||||
/** Optional site description included in the manifest event */
|
||||
description?: string;
|
||||
/**
|
||||
* HTML file served as the 404 fallback for client-side routing.
|
||||
* Always `/index.html` for Shakespeare SPA projects.
|
||||
*/
|
||||
fallback?: string;
|
||||
/** Gateway hostnames that serve this nsite */
|
||||
gatewayHostnames?: string[];
|
||||
}
|
||||
|
||||
const nsiteVfsConfigSchema = z
|
||||
.object({
|
||||
relays: z.array(z.string()),
|
||||
servers: z.array(z.string()),
|
||||
id: z.string().nullable().optional(),
|
||||
title: z.string().optional(),
|
||||
description: z.string().optional(),
|
||||
fallback: z.string().optional(),
|
||||
gatewayHostnames: z.array(z.string()).optional(),
|
||||
})
|
||||
.passthrough(); // preserve unknown keys in existing files
|
||||
|
||||
/**
|
||||
* Read `.nsite/config.json` from the VFS for the given project path.
|
||||
*
|
||||
* Returns `null` if the file does not exist or cannot be parsed.
|
||||
*/
|
||||
export async function readNsiteVfsConfig(
|
||||
fs: JSRuntimeFS,
|
||||
projectPath: string,
|
||||
): Promise<NsiteVfsConfig | null> {
|
||||
const filePath = `${projectPath}/${NSITE_CONFIG_FILE}`;
|
||||
|
||||
try {
|
||||
const raw = await fs.readFile(filePath, 'utf8');
|
||||
const parsed = JSON.parse(raw as string);
|
||||
const validated = nsiteVfsConfigSchema.parse(parsed);
|
||||
return validated as NsiteVfsConfig;
|
||||
} catch (err) {
|
||||
if (err instanceof Error && err.message.includes('ENOENT')) {
|
||||
// File doesn't exist yet — not an error
|
||||
return null;
|
||||
}
|
||||
console.warn('[nsiteConfig] Failed to read .nsite/config.json:', err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write `.nsite/config.json` to the VFS for the given project path.
|
||||
*
|
||||
* Merges with any existing file content so that unknown keys are not lost.
|
||||
* Creates the `.nsite/` directory if it does not exist.
|
||||
*/
|
||||
export async function writeNsiteVfsConfig(
|
||||
fs: JSRuntimeFS,
|
||||
projectPath: string,
|
||||
config: NsiteVfsConfig,
|
||||
): Promise<void> {
|
||||
const dirPath = `${projectPath}/${NSITE_CONFIG_DIR}`;
|
||||
const filePath = `${projectPath}/${NSITE_CONFIG_FILE}`;
|
||||
|
||||
// Read existing file to preserve unknown keys
|
||||
let existing: Record<string, unknown> = {};
|
||||
try {
|
||||
const raw = await fs.readFile(filePath, 'utf8');
|
||||
existing = JSON.parse(raw as string);
|
||||
} catch {
|
||||
// File doesn't exist or is invalid — start fresh
|
||||
}
|
||||
|
||||
// Merge: known fields overwrite, unknown keys are preserved
|
||||
const merged: Record<string, unknown> = { ...existing, ...config };
|
||||
|
||||
// Remove undefined values so the JSON stays clean
|
||||
for (const key of Object.keys(merged)) {
|
||||
if (merged[key] === undefined) {
|
||||
delete merged[key];
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure .nsite/ directory exists
|
||||
try {
|
||||
await fs.stat(dirPath);
|
||||
} catch {
|
||||
await fs.mkdir(dirPath, { recursive: true });
|
||||
}
|
||||
|
||||
await fs.writeFile(filePath, JSON.stringify(merged, null, 2), 'utf8');
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* Utilities for the nsite v2 deployment spec.
|
||||
*/
|
||||
|
||||
/** Max length of a valid nsite dTag — must fit as a DNS label component */
|
||||
const DTAG_MAX_LENGTH = 13;
|
||||
|
||||
/**
|
||||
* Valid nsite dTag pattern:
|
||||
* - 1–13 lowercase alphanumeric characters or hyphens
|
||||
* - Must start and end with an alphanumeric character (valid DNS label)
|
||||
* - No consecutive hyphens
|
||||
*
|
||||
* Examples: "myblog", "my-blog", "site-2"
|
||||
*/
|
||||
const DTAG_REGEX = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
|
||||
|
||||
/**
|
||||
* Convert a project name into a valid nsite dTag identifier.
|
||||
*
|
||||
* Strategy:
|
||||
* 1. Lowercase, replace spaces/underscores/dots with hyphens, strip everything else.
|
||||
* 2. Collapse consecutive hyphens, strip leading/trailing hyphens.
|
||||
* 3. If the result is 1–13 chars and valid → use it directly.
|
||||
* 4. If too long → truncate to 13, then strip any trailing hyphens.
|
||||
* 5. If the result is empty (name had no alphanumeric content) →
|
||||
* SHA-256 hash the original name and take the first 13 hex digits.
|
||||
* This is fully deterministic: the same project name always produces the same dTag.
|
||||
*
|
||||
* The hash fallback produces lowercase hex (`[0-9a-f]`), which satisfies the dTag rules.
|
||||
*/
|
||||
export async function projectNameToDTag(name: string): Promise<string> {
|
||||
const slug = name
|
||||
.toLowerCase()
|
||||
.replace(/[\s_./]+/g, '-') // spaces, underscores, dots → hyphens
|
||||
.replace(/[^a-z0-9-]/g, '') // strip everything else
|
||||
.replace(/-{2,}/g, '-') // collapse consecutive hyphens
|
||||
.replace(/^-+|-+$/g, '') // strip leading/trailing hyphens
|
||||
.slice(0, DTAG_MAX_LENGTH)
|
||||
.replace(/-+$/g, ''); // re-strip trailing hyphens after truncation
|
||||
|
||||
if (slug.length >= 1) {
|
||||
return slug;
|
||||
}
|
||||
|
||||
// Name had no usable alphanumeric content — hash for a short, stable identifier
|
||||
const encoded = new TextEncoder().encode(name);
|
||||
const buf = await crypto.subtle.digest('SHA-256', encoded);
|
||||
const hex = Array.from(new Uint8Array(buf))
|
||||
.map(b => b.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
return hex.slice(0, DTAG_MAX_LENGTH);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that a string is an acceptable nsite dTag.
|
||||
* - 1–13 characters
|
||||
* - Lowercase alphanumeric and hyphens only
|
||||
* - Must start and end with an alphanumeric character (valid DNS label)
|
||||
*/
|
||||
export function isValidDTag(value: string): boolean {
|
||||
return value.length >= 1 && value.length <= DTAG_MAX_LENGTH && DTAG_REGEX.test(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode a 32-byte pubkey (as hex string) into a 50-character lowercase base36 string.
|
||||
* Used to build named-site subdomain URLs: `{base36pubkey}{dTag}.{gateway}`
|
||||
*
|
||||
* Ported from nsite.run/apps/spa/src/lib/base36.js
|
||||
*/
|
||||
export function pubkeyToBase36(pubkeyHex: string): string {
|
||||
// hex → Uint8Array
|
||||
const bytes = new Uint8Array(32);
|
||||
for (let i = 0; i < 32; i++) {
|
||||
bytes[i] = parseInt(pubkeyHex.slice(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
|
||||
const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';
|
||||
const BASE = 36n;
|
||||
|
||||
let value = 0n;
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
value = (value << 8n) | BigInt(bytes[i]);
|
||||
}
|
||||
|
||||
const digits: string[] = [];
|
||||
while (value > 0n) {
|
||||
digits.push(ALPHABET[Number(value % BASE)]);
|
||||
value = value / BASE;
|
||||
}
|
||||
|
||||
return digits.reverse().join('').padStart(50, '0');
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the deployed URL for an nsite.
|
||||
*
|
||||
* - Named site (kind 35128): `https://{base36pubkey}{dTag}.{gateway}`
|
||||
* - Root site (kind 15128): `https://{npub}.{gateway}`
|
||||
*/
|
||||
export function buildNsiteUrl(opts: {
|
||||
pubkeyHex: string;
|
||||
npub: string;
|
||||
gateway: string;
|
||||
siteIdentifier?: string;
|
||||
}): string {
|
||||
const { pubkeyHex, npub, gateway, siteIdentifier } = opts;
|
||||
if (siteIdentifier) {
|
||||
const base36 = pubkeyToBase36(pubkeyHex);
|
||||
return `https://${base36}${siteIdentifier}.${gateway}`;
|
||||
}
|
||||
return `https://${npub}.${gateway}`;
|
||||
}
|
||||
Reference in new issue
Block a user