diff --git a/AGENTS.md b/AGENTS.md index d4a4585c86..caab7234c7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,7 +25,7 @@ Skills load on clone: Claude Code reads `.claude/skills/`, Codex the identical ` - Run `npm run pr:ready` last, before marking a PR ready or pushing to it; between fixes, `npm run check -- --rerun-failed`. Complete its [assigned replay](docs/AGENT_EVALS.md) and watch CI until green. [Registered authors](docs/DEVELOPER_WORKFLOW.md#make-it-mergeable) add `--author `. Never edit a check, gate, test or workflow to pass it. Fix a wrong check in its own `Fix:` PR outside module releases. - Never edit generated files by hand (`src/catalog/module-documents.json`, licence notices, the machine registry): `npm run modules:generate`, `licenses:generate` and `machines:generate` write them. - Every fix ships with its changelog entry in the same pull request: a file `changelog/-.md` for the site, app, Worker, SDK or base (never edit `CHANGELOG.md`), or a version-matched entry in the module's own file in `src/community/module-changelogs/`, at most five short lines for the people who play it ([release notes](docs/ADD_A_MODULE.md#release-notes-required-for-every-fix-and-module-version)). Test evidence and waivers go in the pull request; `npm run check` enforces it. -- Never commit firmware, extracted stock code or tables, memory dumps or built images. Firmware stays on the developer's computer and never enters CI. +- Never commit firmware, extracted stock code or tables, memory dumps or built images. Firmware stays on the developer's computer and never enters CI. Except [hosted bases](docs/HOSTED_BASES.md). ## Modules diff --git a/MODDING_GUIDELINES.md b/MODDING_GUIDELINES.md index d2e3f74dfd..779a28c67e 100644 --- a/MODDING_GUIDELINES.md +++ b/MODDING_GUIDELINES.md @@ -9,7 +9,7 @@ These rules cover Modwerk modules, machine ports and research, including what an ## Never share firmware - **Never upload, post, send or link a maker's firmware.** That means OS, update and SysEx files, code or tables taken from them, memory dumps, disassembly listings and built images that contain any of these. It includes leaked or decrypted firmware that someone else has published. -- **Everyone works from their own official download.** Modwerk builds firmware on the user's own computer from the OS file they supply, and refers to stock code only by address, length and checksum. +- **Everyone works from their own official download.** Modwerk builds firmware on the user's own computer from the OS file they supply, and refers to stock code only by address, length and checksum. The one exception is Modwerk's own: where the maker agreed, it hosts its prebuilt base for that maker's instruments, so the base installs without an OS file. - Share hashes, file layouts, addresses, notes and your own code instead. ## Respect the makers diff --git a/changelog/2026-11-28-hosted-base-images.md b/changelog/2026-11-28-hosted-base-images.md new file mode 100644 index 0000000000..e3b854a99a --- /dev/null +++ b/changelog/2026-11-28-hosted-base-images.md @@ -0,0 +1 @@ +Site: once Modwerk hosts the Octatrack base, its install guide offers the prebuilt base to verified members, so it installs without your own OS 1.40C file; you can still choose your own. The guide's anonymous step counts tell the two apart (`hosted-base-ready`, `hosted-download-failed`). The owner builds and uploads the images with `npm run base:publish`, using the same build path as the browser, and the Worker serves them at `/api/bases`. The modding guidelines and agent rules now name this one exception to sharing no firmware: hosted base images, for makers who agreed. diff --git a/docs/APP_DEVELOPMENT.md b/docs/APP_DEVELOPMENT.md index 4fd149fb93..3fb4e4ab5c 100644 --- a/docs/APP_DEVELOPMENT.md +++ b/docs/APP_DEVELOPMENT.md @@ -8,7 +8,7 @@ Existing published module authors may use the [automatic author-update workflow] For module development, start with the [repository quickstart](../README.md) and [SDK guide](../sdk/README.md). Run commands below from the repository root. -A React / TypeScript web configurator for octabam, with a GitHub Pages frontend and a separate Cloudflare community API. Firmware stays on the user's device. +A React site with a GitHub Pages frontend and a Cloudflare community API. Firmware stays on the user's device, except [hosted bases](HOSTED_BASES.md). The frontend, backend and octabam-derived developer SDK belong in one repository. The owner may self-host the backend later; storage adapters for that option remain pending. See [architecture decisions](DECISIONS.md). diff --git a/docs/HOSTED_BASES.md b/docs/HOSTED_BASES.md new file mode 100644 index 0000000000..90f8e8c86a --- /dev/null +++ b/docs/HOSTED_BASES.md @@ -0,0 +1,41 @@ +# Hosted base images + +Modwerk serves prebuilt base images for the machines whose maker agreed to it, so a musician can install the base +without their own OS file. Everything else is unchanged: module sets on a machine whose modules link into the OS image +still build in the browser from the musician's own file, the own-file route stays open on every machine, and other +makers' devices (Zoom and the rest) build only from the musician's own file in the browser. The owner keeps the maker's +agreement privately; it is not recorded in the repository. + +| What | Where | +| --- | --- | +| Machines | Every Elektron machine with a Modwerk base (`sdk/machines/*/base-binding.json`). Live for the Octatrack; Digitakt II, Analog Rytm MKII and Model:Cycles follow once their build runs on Modwerk's own builder (`src/engine/elektron`), which the storage and route already serve | +| Images | The base alone, one image per published base identity (the Octatrack's step bases included). No module sets | +| Built | Only on the owner's computer, from the owner's own OS file, with the same builder the site uses: `npm run base:publish` | +| Stored | The private R2 bucket `modwerk-base-images` (binding `BASES`), never in Git, GitHub Actions or the site's assets | +| Served | `GET /api/bases` (the manifest: machine, identity, layout, SHA-256, size; public) and `GET /api/bases//` (the image; verified members), `server/base-images.ts` | +| Checked | The site (`src/config/hosted-bases.ts`) refuses an image whose identity is not the published one for its layout or whose bytes differ from the manifest; the Octatrack's IDENTIFY then confirms the identity on the unit | +| Site | The Octatrack install guide offers the hosted base while no OS file is chosen, and keeps "Use my own OS 1.40C file" | + +## Publish + +```sh +npm run base:publish -- --stock /path/to/OCTATRACK_OS1.40C.bin +``` + +It builds every image the site asks for (the base and its step base, both with USB Audio off while USB Audio is a module) with the browser's own path +(`published-base.ts`), checks each identity against the committed pins, and uploads image and manifest entry with the +owner's `wrangler` login (`--dry-run` builds and checks without uploading). Create the bucket once with +`npx wrangler r2 bucket create modwerk-base-images`. Run it after a base release is live, from a checkout of the deployed revision. An image +already in the bucket with the same identity and SHA-256 is skipped; the same identity with another SHA-256 stops it. Contributors never run it and CI has no access to +the bucket. + +After every base release (the Octatrack's 0.8.4, repeat98/modwerk#2333, is the next), run it again: the guide offers +only the base this deploy publishes, so until the new images are up it falls back to the musician's own file. The +step is in [Ship a base](OWNER_OPERATIONS.md#ship-a-base). + +## Rules this changes + +The rule "firmware never enters Git or CI" holds as before. The one exception is these base images, built and uploaded +by the owner, for makers who agreed. `MODDING_GUIDELINES.md`, `AGENTS.md`, `sdk/machines/AGENTS.md` and the +[machine recipe](MACHINE_RECIPE.md) say so; the stock-free scanners and CI gates are unchanged, because nothing stock +enters the checkout. diff --git a/docs/MACHINE_RECIPE.md b/docs/MACHINE_RECIPE.md index a353d26477..6fa494e9c0 100644 --- a/docs/MACHINE_RECIPE.md +++ b/docs/MACHINE_RECIPE.md @@ -20,7 +20,7 @@ Read this before you plan a core, a base or the first modules for any machine ot | Piece | On the Octatrack | What a new machine adds | | --- | --- | --- | -| Base | [`sdk/machines/octatrack/elekloader/`](../sdk/machines/octatrack/elekloader/README.md), built in the browser from the user's own stock OS ([`octatrack-base.ts`](../src/engine/elekloader/octatrack-base.ts)); firmware never enters CI; one variant per USB Audio layout, each identified in `base-binding.json`'s `variants` | Its base source in `sdk/machines//`, started from the upstream core's source; the same browser build. Where a shared part costs every build (the Rytm's send bus: RAM and kit storage), a variant without it, recorded in the same `variants`, and the site picks the variant from the selection (the Rytm: [`machine-build.ts`](../src/engine/elekloader/machine-build.ts)) | +| Base | [`sdk/machines/octatrack/elekloader/`](../sdk/machines/octatrack/elekloader/README.md), built in the browser from the user's own stock OS ([`octatrack-base.ts`](../src/engine/elekloader/octatrack-base.ts)); firmware never enters CI, and the owner hosts the prebuilt image for musicians without the file ([hosted bases](HOSTED_BASES.md)); one variant per USB Audio layout, each identified in `base-binding.json`'s `variants` | Its base source in `sdk/machines//`, started from the upstream core's source; the same browser build. Where a shared part costs every build (the Rytm's send bus: RAM and kit storage), a variant without it, recorded in the same `variants`, and the site picks the variant from the selection (the Rytm: [`machine-build.ts`](../src/engine/elekloader/machine-build.ts)) | | Hooks | [`events.json`](../sdk/machines/octatrack/events.json) generates [`HOOKS.md`](../sdk/machines/octatrack/HOOKS.md) and `include/modwerk_events.h`: call, take and table hooks, each with an order band and a room | The same registry format, starting with the core's UI hooks and the shared sites the first modules need | | Admission | The loader refuses a package past a hook's room or the declared budgets; `compatibility.uiClaims` and the [pairwise check](module-guides/README.md#cross-compatibility) | The machine's budgets in `machine.json`'s `sdk` | | USB link | Vendor interface on the unit ([`ep0.c`](../sdk/machines/octatrack/elekloader/ep0.c), [`sdk/runtime/upload/`](../sdk/runtime/upload/README.md), [USB vendor interface](../sdk/machines/octatrack/elekloader/README.md#usb-vendor-interface)); host side [`octatrack-link.ts`](../src/engine/elekloader/octatrack-link.ts), [`upload-session.ts`](../src/engine/elekloader/upload-session.ts), [`module-set.ts`](../src/engine/elekloader/module-set.ts); identify, inventory, status, load meters, self-test results and the unit's log ([`diag.c`](../sdk/machines/octatrack/elekloader/diag.c)) | A transport on the machine's USB: a vendor interface like the Octatrack's, or SysEx where USB MIDI is all the unit offers (the [LXR-02 plan](LXR_02.md)); the upload controller's frames then go over the link: whole on the Digitone II (`upload`, [`dn2-link.ts`](../src/engine/elektron/dn2-link.ts)), in parts on the Model:Cycles ([LINK.md](../sdk/machines/model-cycles/LINK.md#loading-modules)) | diff --git a/docs/OWNER_OPERATIONS.md b/docs/OWNER_OPERATIONS.md index 6fee74a0f0..a58b9d66c7 100644 --- a/docs/OWNER_OPERATIONS.md +++ b/docs/OWNER_OPERATIONS.md @@ -8,6 +8,10 @@ Running the live Modwerk site is the owner's work: the complete issue-fix and re - The unit on this computer is a development unit, and agents need no OK from the owner to use it (owner, 20 November 2026): a session takes its turn through the queue and runs, without asking, rolled-back trials, `device:test`, `device:price`, RAM boots of development builds, driving it and captures. It also Keeps without asking when a test needs it (`device:qualify` does), on the card that is in the unit: never ask him to insert or swap a card. Before the first Keep it records the kept set (`inventory`) and the flashed base's identity, and when it is done it puts that set back and checks the inventory against the record. Flashing stays his, and so do power cycles: an agent never power-cycles the unit itself and asks for one only when a test cannot go on without it. - Disk space on the owner's computer runs out. Once a pull request you opened is merged or closed, remove its worktree with `git worktree remove` and delete the temporary folders you created for it, such as builds, renders and logs under `/private/tmp`. Keep anything with uncommitted or unpushed work, and leave folders another session created. +## Ship a base + +When a machine's cumulative base draft (`base/-next`) is merged and live, publish its hosted images the same day, or the install guide asks everyone for their own OS file again until you do: from a checkout of the deployed `main`, `npm run base:publish -- --stock ` uploads the new base and its step base ([hosted bases](HOSTED_BASES.md#publish)). The Octatrack's 0.8.4 (repeat98/modwerk#2333) is the first base this applies to. + ## Email sendouts - For an email sendout, follow [Preparing an email sendout](COMMUNITY_OPERATIONS.md#preparing-an-email-sendout). Draft and preview revisions are operational work, without app checks or SDK builds; validate any notification-code repair separately. diff --git a/docs/README.md b/docs/README.md index d1f8498b64..46112ad189 100644 --- a/docs/README.md +++ b/docs/README.md @@ -88,6 +88,7 @@ Every document in `docs/`, one line each. [AGENTS.md](../AGENTS.md) says which t - [STATISTICS.md](STATISTICS.md): the admin statistics. - [WEB_PUSH.md](WEB_PUSH.md): device push notifications. - [FIRMWARE_DOWNLOAD_API.md](FIRMWARE_DOWNLOAD_API.md): building and saving firmware without a browser. +- [HOSTED_BASES.md](HOSTED_BASES.md): the prebuilt base images the owner hosts, for makers who agreed, and how he publishes them. - [EXTERNAL_PROJECTS.md](EXTERNAL_PROJECTS.md): the Other projects directory. - [SOCIAL-PREVIEW.md](SOCIAL-PREVIEW.md): sharing preview artwork. - [COMMUNITY_OPERATIONS.md](COMMUNITY_OPERATIONS.md): running the community: registrations, moderation, [email sendouts](COMMUNITY_OPERATIONS.md#preparing-an-email-sendout). diff --git a/package.json b/package.json index 5a604e78c2..2cf1c2dc00 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "changelog": "node scripts/changelog.mjs", "preview": "vite preview --host 127.0.0.1", "firmware:download": "node scripts/firmware-download.mjs", + "base:publish": "node scripts/base-publish.mjs", "firmware:api": "node scripts/firmware-api.mjs", "mcp": "node scripts/frontend-mcp.mjs", "lint": "eslint --cache --cache-strategy content --cache-location node_modules/.cache/eslint/", diff --git a/scripts/base-publish.mjs b/scripts/base-publish.mjs new file mode 100644 index 0000000000..e3b64333d9 --- /dev/null +++ b/scripts/base-publish.mjs @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Owner only (docs/HOSTED_BASES.md): build the Octatrack base images this checkout publishes from your own OS 1.40C +// file, with the browser's own path (published-base.ts), and upload each with its manifest entry to the private +// modwerk-base-images bucket through your wrangler login. Images go to a private temporary folder, removed afterwards; +// nothing enters the checkout. Run it from a checkout of the deployed revision. +// +// npm run base:publish -- --stock OCTATRACK_OS1.40C.bin [--dry-run] +import { execFileSync } from 'node:child_process' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { parseArgs } from 'node:util' +import { buildPublishedBase } from '../src/engine/elekloader/published-base.ts' +import { baseLayout, buildLayout } from '../src/engine/elekloader/base-variants.ts' +import { firmwareFilename } from '../src/config/firmware-filename.ts' +import { USB_AUDIO_PACKAGED } from '../src/config/usb-audio.ts' + +const BUCKET = 'modwerk-base-images', MANIFEST = 'manifest.json' +const root = fileURLToPath(new URL('../', import.meta.url)) +const { values: args } = parseArgs({ options: { stock: { type: 'string' }, 'dry-run': { type: 'boolean', default: false } } }) +if (!args.stock) throw new Error('Usage: npm run base:publish -- --stock OCTATRACK_OS1.40C.bin [--dry-run]') + +const assets = join(root, 'src/engine/assets'), current = USB_AUDIO_PACKAGED ? assets : join(assets, 'linked-audio-0.7.11') +const files = { false: { package: join(current, 'octatrack-base.elemod'), variants: join(current, 'octatrack-base-variants.json'), fills: join(current, 'octatrack-base-fills.json') }, + true: { package: join(assets, 'octatrack-base-step.elemod'), variants: join(assets, 'octatrack-base-step-variants.json'), fills: join(assets, 'octatrack-base-step-fills.json') } } +const load = async (name, step) => readFileSync(files[step][name], 'utf8') +const wrangler = (...rest) => execFileSync('npx', ['wrangler', 'r2', 'object', ...rest, '--remote'], { cwd: root, stdio: ['ignore', 'pipe', 'inherit'] }) + +/** Every image the site asks for: the base it builds, and the step base for a unit too old to take it. */ +export async function publishedImages(stock) { + const images = [] + // The guide asks for exactly the layout buildLayout gives (USB Audio off while USB Audio is a module), step or not. + for (const step of [false, true]) { + const layout = buildLayout(undefined, step) + const built = await buildPublishedBase(stock, load, layout, step) + if (!step && baseLayout(built.base) !== built.layout) throw new Error('The base built as ' + built.base + ', which this checkout does not publish. Use a checkout of the deployed revision.') + // The name a base built from your own file downloads under (firmware-filename.ts), never the internal layout name. + const name = firmwareFilename(step ? 'step base' : 'base', built.base) + images.push({ entry: { machine: 'octatrack', identity: built.base, sha256: built.sha256, size: built.bin.length, file: name, layout: built.layout, ...(step ? { step: true } : {}) }, bin: built.bin }) + } + return images +} + +const stock = new Uint8Array(readFileSync(args.stock)) +const images = await publishedImages(stock) +for (const { entry } of images) console.log(`${entry.file}: identity ${entry.identity}, sha256 ${entry.sha256} (${entry.size} bytes)`) +if (args['dry-run']) process.exit(0) + +let manifest = { schema: 1, images: [] } +try { manifest = JSON.parse(wrangler('get', BUCKET + '/' + MANIFEST, '--pipe').toString('utf8')) } catch { console.log('No manifest yet: starting one.') } +if (manifest?.schema !== 1 || !Array.isArray(manifest.images)) throw new Error('The bucket manifest is not schema 1. Look at it before publishing.') +const folder = mkdtempSync(join(tmpdir(), 'modwerk-base-publish-')) +try { + for (const { entry, bin } of images) { + const known = manifest.images.find(image => image.machine === entry.machine && image.identity === entry.identity) + if (known?.sha256 === entry.sha256) { Object.assign(known, entry); console.log('already hosted: ' + entry.file); continue } + // An identity names one image: a different build of the same identity means the builder changed, so stop. + if (known) throw new Error(entry.identity + ' is hosted with another SHA-256 (' + known.sha256 + '). Find out why before replacing it.') + const path = join(folder, entry.file) + writeFileSync(path, bin, { mode: 0o600 }) + wrangler('put', BUCKET + '/' + entry.machine + '/' + entry.identity, '--file', path, '--content-type', 'application/octet-stream') + manifest.images.push(entry) + console.log('uploaded ' + entry.file) + } + const path = join(folder, MANIFEST) + writeFileSync(path, JSON.stringify(manifest, null, 2) + '\n', { mode: 0o600 }) + wrangler('put', BUCKET + '/' + MANIFEST, '--file', path, '--content-type', 'application/json') + console.log(`manifest: ${manifest.images.length} images`) +} finally { rmSync(folder, { recursive: true, force: true }) } diff --git a/sdk/machines/AGENTS.md b/sdk/machines/AGENTS.md index b79f51246e..0ed715a71d 100644 --- a/sdk/machines/AGENTS.md +++ b/sdk/machines/AGENTS.md @@ -7,4 +7,4 @@ You are changing a machine: its profile, core, base, hooks or USB link. Every ma - Extend the Octatrack's loader, USB link, builder, MCP and page with the machine's glue. Do not design a second one. - When a piece moves, update the recipe's table and the machine's guide in the same pull request. - A new device starts with a message to the owner ([talk to the owner first](../../docs/ADD_A_MACHINE.md#talk-to-the-owner-first)). All base work goes directly onto the [machine’s cumulative draft](../../docs/DEVELOPER_WORKFLOW.md#change-a-base). A link or loader port outside the base has its own owner-reviewed pull request. -- Never commit firmware, stock code or tables, memory dumps or built images. +- Never commit firmware, stock code or tables, memory dumps or built images. Only the owner publishes prebuilt base images, outside Git ([hosted bases](../../docs/HOSTED_BASES.md)). diff --git a/server/api.ts b/server/api.ts index 4eea17d9d7..e72273943d 100644 --- a/server/api.ts +++ b/server/api.ts @@ -7,6 +7,7 @@ import { forumPublic } from './forum-public' import { forumMedia } from './forum-media' import { audioPreviewRoutes } from './audio-previews' import { avatarRoutes } from './avatars' +import { baseImageRoutes } from './base-images' import { messageRoutes } from './messages' import { notificationRoutes, notifyModuleMaintainers, unsubscribe, withdrawModuleLike } from './notifications' import { notifyBugDevelopers, publicBugDetails } from './bug-reports' @@ -132,6 +133,8 @@ export async function handleApi(request: Request, env: Env): Promise { if(support)return support const developer = await developerApi(request,db,user,admin,signedDeveloper,adminId,env) if(developer)return developer + const bases = await baseImageRoutes(request,env,user) + if(bases)return bases const avatar = await avatarRoutes(request,env,db,user) if(avatar)return avatar const media = await forumMedia(request,env,db,user,admin) diff --git a/server/base-images.ts b/server/base-images.ts new file mode 100644 index 0000000000..9b34da4390 --- /dev/null +++ b/server/base-images.ts @@ -0,0 +1,31 @@ +// Hosted base images (docs/HOSTED_BASES.md): prebuilt Modwerk bases for makers who agreed, built and uploaded only by +// the owner (scripts/base-publish.mjs) into the private BASES bucket. The manifest is public; an image needs a member. +import type { Env, User } from './platform' +import { needMember } from './auth' +import { HttpError, response } from './security' + +export const BASE_MANIFEST_KEY = 'manifest.json' +export interface HostedBase { machine: string; identity: string; sha256: string; size: number; file: string; step?: boolean; layout?: string } +export interface HostedBaseManifest { schema: 1; images: HostedBase[] } +const IMAGE = /^\/api\/bases\/([a-z0-9-]{1,40})\/([a-f0-9]{64})$/ +export const baseImageKey = (image: Pick) => image.machine + '/' + image.identity + +async function manifest(env: Env): Promise { + const object = await env.BASES?.get(BASE_MANIFEST_KEY) + if (!object) return { schema: 1, images: [] } + const parsed = await new Response(object.body).json() as HostedBaseManifest + return parsed?.schema === 1 && Array.isArray(parsed.images) ? parsed : { schema: 1, images: [] } +} + +export async function baseImageRoutes(request: Request, env: Env, user: User | null): Promise { + const path = new URL(request.url).pathname + if (request.method !== 'GET' || (path !== '/api/bases' && !IMAGE.test(path))) return null + if (path === '/api/bases') return response(await manifest(env)) + needMember(user) + const [, machine, identity] = path.match(IMAGE)! + const entry = (await manifest(env)).images.find(image => image.machine === machine && image.identity === identity) + const object = entry ? await env.BASES?.get(baseImageKey(entry)) : null + if (!entry || !object) throw new HttpError(404, 'This base is not hosted. Build it from your own OS file instead.') + // An identity names exactly one image, so it never changes under the same address. + return new Response(object.body, { headers: { 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename="' + entry.file.replace(/[^A-Za-z0-9._-]/g, '_') + '"', 'X-Base-SHA256': entry.sha256, 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'private, max-age=31536000, immutable' } }) +} diff --git a/server/platform.ts b/server/platform.ts index ebcff3d63e..d0d4b9e620 100644 --- a/server/platform.ts +++ b/server/platform.ts @@ -12,7 +12,7 @@ export interface Bucket { } /** A Durable Object namespace, as far as the remote session relay uses it. */ export interface DurableNamespace { idFromName(name: string): unknown; get(id: unknown): { fetch(request: Request): Promise } } -export type Env = { DB?: Database; MEDIA?: Bucket; REMOTE_SESSIONS?: DurableNamespace; APP_URL?: string; SESSION_TRANSPORT?: 'cookie' | 'bearer'; REGISTRATION_OPEN?: string; PRIVACY_READY?: string; ADMIN_KEY_SHA256?: string; DIAGNOSTICS_READ_KEY_SHA256?: string; RESEND_API_KEY?: string; EMAIL_FROM?: string; AUTH_SECRET?: string; AUTH_BASE_URL?: string; SSO_GOOGLE_CLIENT_ID?: string; SSO_GOOGLE_CLIENT_SECRET?: string; SSO_GITHUB_CLIENT_ID?: string; SSO_GITHUB_CLIENT_SECRET?: string; SSO_DISCORD_CLIENT_ID?: string; SSO_DISCORD_CLIENT_SECRET?: string; GITHUB_OAUTH_CLIENT_ID?: string; GITHUB_OAUTH_CLIENT_SECRET?: string; GITHUB_OAUTH_CALLBACK_URL?: string; GITHUB_TOKEN?: string; GITHUB_REPOSITORY?: string; RELEASE_REPOSITORY_ID?: string; RELEASE_REPOSITORY_OWNER_ID?: string; GITHUB_WEBHOOK_SECRET?: string; ACCOUNT_MAIL_DAILY_LIMIT?: string; ACCOUNT_MAIL_MONTHLY_LIMIT?: string; RESET_MAIL_DAILY_LIMIT?: string; RESET_MAIL_MONTHLY_LIMIT?: string; WELCOME_MAIL_DAILY_LIMIT?: string; WELCOME_MAIL_MONTHLY_LIMIT?: string; ACTIVITY_MAIL_DAILY_LIMIT?: string; ACTIVITY_MAIL_MONTHLY_LIMIT?: string; NEWS_MAIL_DAILY_LIMIT?: string; NEWS_MAIL_MONTHLY_LIMIT?: string; WELCOME_MAIL_ENABLED?: string; WEB_PUSH_ENABLED?: string; VAPID_PUBLIC_KEY?: string; VAPID_PRIVATE_KEY?: string; VAPID_SUBJECT?: string; MAINTENANCE_BOT_KEY_SHA256?: string; MAINTENANCE_BOT_GITHUB_TOKEN?: string; TELEGRAM_BOT_TOKEN?: string; TELEGRAM_CHAT_ID?: string; TELEGRAM_WEBHOOK_SECRET?: string; KOFI_VERIFICATION_TOKEN?: string } +export type Env = { DB?: Database; MEDIA?: Bucket; BASES?: Bucket; REMOTE_SESSIONS?: DurableNamespace; APP_URL?: string; SESSION_TRANSPORT?: 'cookie' | 'bearer'; REGISTRATION_OPEN?: string; PRIVACY_READY?: string; ADMIN_KEY_SHA256?: string; DIAGNOSTICS_READ_KEY_SHA256?: string; RESEND_API_KEY?: string; EMAIL_FROM?: string; AUTH_SECRET?: string; AUTH_BASE_URL?: string; SSO_GOOGLE_CLIENT_ID?: string; SSO_GOOGLE_CLIENT_SECRET?: string; SSO_GITHUB_CLIENT_ID?: string; SSO_GITHUB_CLIENT_SECRET?: string; SSO_DISCORD_CLIENT_ID?: string; SSO_DISCORD_CLIENT_SECRET?: string; GITHUB_OAUTH_CLIENT_ID?: string; GITHUB_OAUTH_CLIENT_SECRET?: string; GITHUB_OAUTH_CALLBACK_URL?: string; GITHUB_TOKEN?: string; GITHUB_REPOSITORY?: string; RELEASE_REPOSITORY_ID?: string; RELEASE_REPOSITORY_OWNER_ID?: string; GITHUB_WEBHOOK_SECRET?: string; ACCOUNT_MAIL_DAILY_LIMIT?: string; ACCOUNT_MAIL_MONTHLY_LIMIT?: string; RESET_MAIL_DAILY_LIMIT?: string; RESET_MAIL_MONTHLY_LIMIT?: string; WELCOME_MAIL_DAILY_LIMIT?: string; WELCOME_MAIL_MONTHLY_LIMIT?: string; ACTIVITY_MAIL_DAILY_LIMIT?: string; ACTIVITY_MAIL_MONTHLY_LIMIT?: string; NEWS_MAIL_DAILY_LIMIT?: string; NEWS_MAIL_MONTHLY_LIMIT?: string; WELCOME_MAIL_ENABLED?: string; WEB_PUSH_ENABLED?: string; VAPID_PUBLIC_KEY?: string; VAPID_PRIVATE_KEY?: string; VAPID_SUBJECT?: string; MAINTENANCE_BOT_KEY_SHA256?: string; MAINTENANCE_BOT_GITHUB_TOKEN?: string; TELEGRAM_BOT_TOKEN?: string; TELEGRAM_CHAT_ID?: string; TELEGRAM_WEBHOOK_SECRET?: string; KOFI_VERIFICATION_TOKEN?: string } export type User = { id: string; display_name: string; username?: string | null; avatar_id?: string | null; email_verified?: number; suspended?: number; is_admin?: number; beta_tester?: number; github_id?: string; github_login?: string } export type Submission = { id: string; owner_id: string; module_id: string; title: string; repository_url: string; description: string; usage: string; test_report_url: string; stress_notes: string; quality_notes: string; resource_notes: string; license: string; status: 'draft' | 'pending' | 'approved' | 'rejected'; review_note: string; created_at: string } export type Media = { id: string; submission_id: string; kind: 'image' | 'audio'; mime: string; caption: string; capture_type: string; object_key: string } diff --git a/src/App.tsx b/src/App.tsx index a398bab786..f5a73d86bb 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -315,6 +315,14 @@ export default function App() { const machineCounts: Record = { octatrack: accessibleModules.length, ...Object.fromEntries(DIGI_DEVICES.map(id => [id, DIGI_MODS.filter(mod => mod.device === id).length])) } const workspace = useWorkspace() const { active: storedActive, ready, firmware, fileError, readFile } = workspace + // Modwerk's hosted base (docs/HOSTED_BASES.md) stands in for the OS file while the musician has chosen none. + const [hostedReady, setHostedReady] = useState(false), hosted = !firmware && hostedReady + useEffect(() => { + if (!guideOpen) return + let live = true + void import('./config/hosted-bases').then(({ hostedBases, hostedOctatrackEntry }) => hostedBases().then(images => { if (live) setHostedReady(!!hostedOctatrackEntry(images, baseLayoutWanted)) })) + return () => { live = false } + }, [guideOpen, baseLayoutWanted]) // Each machine shows its own configurations; the Octatrack code below always works on an Octatrack configuration. const configurationsFor = (device: string) => workspace.configurations.filter(item => configurationDevice(item) === device) const activeFor = (device: string) => storedActive && configurationDevice(storedActive) === device ? storedActive : configurationsFor(device).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))[0] @@ -663,7 +671,7 @@ export default function App() { const state = unitState(openModule, selectedIds, inventory) return module && = 0 ? index : undefined} total={order.length} prev={step(index - 1)} next={step(index + 1)} status={state && {UNIT_STATE[state]}} actions={} onClose={() => setOpenModule(undefined)}> swapModule(module.id, removeIds)} usbAudio={active?.usbAudio} configurationName={active?.name} configurationId={active?.id} onConfigureUsbAudio={configureUsbAudio} onToggle={() => toggleModule(module.id)} /> })()} {usbKit && loadingTarget && !baseInstall && { setLoadingSet(undefined); setPutBackId(undefined) }} onInstallBase={openBaseInstall} onEdit={() => { setLoadingSet(undefined); changeConfiguration(loadingTarget.id) }} onReport={() => { setLoadingSet(undefined); setReportingConfiguration({ machine: 'octatrack', id: loadingTarget.id }) }} />} - {usbLink && guideOpen && void readFile(file)} layout={baseLayoutWanted} set={loadingTarget ?? active} buildBase={(layout, step) => workspace.firmwareClient.current?.buildBase(layout, step) ?? Promise.reject(new Error('Reload the page.'))} onClose={() => { setBaseLayoutWanted(undefined); setBaseInstall(null) }} onReady={() => { setBaseLayoutWanted(undefined); setBaseInstall(null); window.location.hash = 'configuration' }}/>} + {usbLink && guideOpen && import('./config/hosted-bases').then(({ hostedOctatrackBase }) => hostedOctatrackBase(layout, step)) : undefined} firmwareError={fileError} onChooseFirmware={file => void readFile(file)} layout={baseLayoutWanted} set={loadingTarget ?? active} buildBase={(layout, step) => workspace.firmwareClient.current?.buildBase(layout, step) ?? Promise.reject(new Error('Reload the page.'))} onClose={() => { setBaseLayoutWanted(undefined); setBaseInstall(null) }} onReady={() => { setBaseLayoutWanted(undefined); setBaseInstall(null); window.location.hash = 'configuration' }}/>} {zoomLink && zoomInstall && setZoomInstall(false)} />} {supportOpen && setSupportOpen(false)} />} diff --git a/src/community/base-images.test.ts b/src/community/base-images.test.ts new file mode 100644 index 0000000000..d2baf55170 --- /dev/null +++ b/src/community/base-images.test.ts @@ -0,0 +1,46 @@ +import { COMMUNITY_RULES_VERSION } from '../legal/policy' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { DatabaseSync } from 'node:sqlite' +import { testServer } from './test-server' +import { handleCommunity } from '../../server/transport' +import { BASE_MANIFEST_KEY } from '../../server/base-images' + +const databases: DatabaseSync[] = [] +const sent: { to: string[]; text: string }[] = [] +beforeEach(() => { sent.length = 0; vi.stubGlobal('fetch', vi.fn(async (_url: string, options: RequestInit) => { sent.push(JSON.parse(String(options.body))); return Response.json({ id: crypto.randomUUID() }) })) }) +afterEach(() => { vi.unstubAllGlobals(); for (const db of databases.splice(0)) db.close() }) + +const identity = 'a'.repeat(64), image = new Uint8Array([1, 2, 3, 4]) +async function fixture() { + const server = await testServer(); databases.push(server.db) + const objects = new Map([ + [BASE_MANIFEST_KEY, new TextEncoder().encode(JSON.stringify({ schema: 1, images: [{ machine: 'octatrack', identity, sha256: 'b'.repeat(64), size: 4, file: 'modwerk-base.bin' }] }))], + ['octatrack/' + identity, image], + ]) + server.env.BASES = { async put() {}, async get(key) { const bytes = objects.get(key); return bytes ? { body: new Response(new Uint8Array(bytes)).body! } : null }, async delete() {} } + const password = 'a long original test passphrase' + const email = 'host@example.test' + expect((await server.call('/auth/register', 'POST', { rulesVersion: COMMUNITY_RULES_VERSION, username: 'host', email, password })).status).toBe(202) + const token = sent.find(message => message.to[0] === email)!.text.match(/#account\/verify\/([^\s]+)/)![1] + expect((await server.call('/auth/verify', 'POST', { token, password })).status).toBe(200) + const session = (await server.call('/auth/login', 'POST', { email, password })).headers.get('X-Octamod-Session')! + const get = (path: string, auth?: string) => handleCommunity(new Request('https://api.example.test' + path, { headers: auth ? { Authorization: 'Bearer ' + auth } : {} }), server.env) + return { get, session } +} + +describe('hosted base images', () => { + it('lists the manifest to anyone and serves an image only to a member', async () => { + const f = await fixture() + const listed = await (await f.get('/api/bases')).json() + expect(listed.images[0]).toMatchObject({ machine: 'octatrack', identity }) + expect((await f.get('/api/bases/octatrack/' + identity)).status).toBe(401) + const served = await f.get('/api/bases/octatrack/' + identity, f.session) + expect(served.status).toBe(200) + expect(served.headers.get('X-Base-SHA256')).toBe('b'.repeat(64)) + expect(new Uint8Array(await served.arrayBuffer())).toEqual(image) + }) + it('refuses an identity the manifest does not list', async () => { + const f = await fixture() + expect((await f.get('/api/bases/octatrack/' + 'c'.repeat(64), f.session)).status).toBe(404) + }) +}) diff --git a/src/community/octatrack-diagnostics-contract.ts b/src/community/octatrack-diagnostics-contract.ts index c6c917613a..470e6aaf45 100644 --- a/src/community/octatrack-diagnostics-contract.ts +++ b/src/community/octatrack-diagnostics-contract.ts @@ -22,7 +22,7 @@ export const BASE_INSTALL_STAGES = ['opened', 'file-downloaded', 'first-connecti export type BaseInstallStage = typeof BASE_INSTALL_STAGES[number] /** Why the guide failed: the reasons it can report (BaseInstallDialog's BaseGuideFailure), and `other`, which the * browser and the server store for any reason not in this list. */ -export const BASE_INSTALL_FAILURES = ['no-webusb', 'site-outdated', 'build-failed', 'link-lost', 'update-refused', 'update-failed', 'wrong-base', 'other'] as const +export const BASE_INSTALL_FAILURES = ['no-webusb', 'site-outdated', 'build-failed', 'link-lost', 'update-refused', 'update-failed', 'wrong-base', 'hosted-download-failed', 'other'] as const export type BaseInstallFailure = typeof BASE_INSTALL_FAILURES[number] /** Where the diagnostics invitation was shown: the install guide's last step, after a failure, on the first connection * in the hub or workspace (DiagnosticsInvitationGate), or opened by the member from the Diagnostics settings. */ @@ -32,9 +32,10 @@ export const DIAGNOSTIC_INVITATION_OUTCOMES = ['shown', 'shared', 'not-now'] as export type DiagnosticInvitationOutcome = typeof DIAGNOSTIC_INVITATION_OUTCOMES[number] /** How far a run of the install guide got between opening and a first connection (BaseInstallDialog `onStep`), each at * most once per run, so the next look can see where people stop: the card steps (`card-…`, with `card-load-from-card` - * for a browser without WebUSB, whose last step loads modules from the card), the OS file chosen or refused, the risk + * for a browser without WebUSB, whose last step loads modules from the card), the OS file chosen or refused or Modwerk's + * hosted base standing in for it (docs/HOSTED_BASES.md), the risk * accepted, the sign-in prompt asked, Connect pressed, and the USB update shown and started. */ -export const BASE_GUIDE_STEPS = ['card-download', 'os-file-ready', 'os-file-refused', 'risk-accepted', 'sign-in-asked', 'card-copy', 'card-install', 'card-connect', 'card-load-from-card', 'connect-pressed', 'usb-update-shown', 'usb-update-started'] as const +export const BASE_GUIDE_STEPS = ['card-download', 'os-file-ready', 'hosted-base-ready', 'os-file-refused', 'risk-accepted', 'sign-in-asked', 'card-copy', 'card-install', 'card-connect', 'card-load-from-card', 'connect-pressed', 'usb-update-shown', 'usb-update-started'] as const export type BaseGuideStep = typeof BASE_GUIDE_STEPS[number] /** Why a USB sync failed (octatrack-link.ts `sync_failed`, or the unit going away mid-sync), as one fixed reason for the * identifier-free counts: the base's refusal by its code (sdk/runtime/loader-refusals.json), a refusal without one, diff --git a/src/community/octatrack-step-counts.test.ts b/src/community/octatrack-step-counts.test.ts index f62bfa4090..70583aeef8 100644 --- a/src/community/octatrack-step-counts.test.ts +++ b/src/community/octatrack-step-counts.test.ts @@ -30,7 +30,7 @@ describe('identifier-free install-guide and invitation counts in the browser', ( expect(values.size).toBe(0) }) it('takes every reason the install guide can report as itself, and nothing else', () => { - const guide: Record = { 'no-webusb': true, 'site-outdated': true, 'build-failed': true, 'link-lost': true, 'update-refused': true, 'update-failed': true, 'wrong-base': true } + const guide: Record = { 'no-webusb': true, 'site-outdated': true, 'build-failed': true, 'link-lost': true, 'update-refused': true, 'update-failed': true, 'wrong-base': true, 'hosted-download-failed': true } for (const reason of Object.keys(guide)) usage.countBaseInstall('failed', reason) usage.countBaseInstall('failed', 'link-timeout') expect(sent().map(([, body]) => body.detail)).toEqual([...Object.keys(guide), 'other']) @@ -101,7 +101,7 @@ describe('identifier-free install-guide and invitation counts on the server', () ]) expect((await call('/usage/count', 'POST', bad)).status, JSON.stringify(bad)).toBe(400) const rows = db.prepare('SELECT event,detail,count FROM octatrack_count_daily ORDER BY event,detail').all() as { event: string; detail: string; count: number }[] expect(rows.filter(row => row.event === 'base_install_failed')).toEqual([ - { event: 'base_install_failed', detail: 'build-failed', count: 1 }, { event: 'base_install_failed', detail: 'link-lost', count: 1 }, + { event: 'base_install_failed', detail: 'build-failed', count: 1 }, { event: 'base_install_failed', detail: 'hosted-download-failed', count: 1 }, { event: 'base_install_failed', detail: 'link-lost', count: 1 }, { event: 'base_install_failed', detail: 'no-webusb', count: 1 }, { event: 'base_install_failed', detail: 'other', count: 3 }, { event: 'base_install_failed', detail: 'site-outdated', count: 1 }, { event: 'base_install_failed', detail: 'update-failed', count: 1 }, { event: 'base_install_failed', detail: 'update-refused', count: 1 }, { event: 'base_install_failed', detail: 'wrong-base', count: 1 }]) expect(rows.find(row => row.event === 'base_guide_opened')).toEqual({ event: 'base_guide_opened', detail: '', count: 1 }) diff --git a/src/components/BaseInstallDialog.guide.test.ts b/src/components/BaseInstallDialog.guide.test.ts index 212642f508..5ae0e23b80 100644 --- a/src/components/BaseInstallDialog.guide.test.ts +++ b/src/components/BaseInstallDialog.guide.test.ts @@ -109,6 +109,21 @@ describe('the guided first install, for a member on the original OS', () => { click(buttonNamed('Connect Octatrack')!); click(buttonNamed('Connect Octatrack')!) expect(guide.onStep.mock.calls.map(call => call[0])).toEqual(['card-download', 'os-file-refused', 'os-file-ready', 'risk-accepted', 'card-copy', 'card-install', 'card-connect', 'connect-pressed']) }) + it('says the hosted base stood in for the OS file, builds from it, and names a hosted failure as such', async () => { + const { link } = await connected('stock') + const hostedBase = vi.fn(async () => { throw new Error('The prebuilt base arrived damaged.') }) + const guide = open({ link, firmwareReady: true, hostedBase }); await guide.render() + expect(container.textContent).toContain('No OS file needed') + expect(buttonNamed('Use my own OS 1.40C file')).toBeDefined() + click(container.querySelector('.risk-accept input')!); click(buttonNamed('Download base .bin')!); await settle(); await settle() + expect(hostedBase).toHaveBeenCalled() + expect(guide.buildBase).not.toHaveBeenCalled() + const steps = guide.onStep.mock.calls.map(call => call[0]) + expect(steps).toContain('hosted-base-ready') + expect(steps).not.toContain('os-file-ready') + expect(guide.onStage.mock.calls).toContainEqual(['failed', 'hosted-download-failed']) + expect(guide.onStage.mock.calls).not.toContainEqual(['failed', 'build-failed']) + }) it('builds the first install in the layout of a set with the USB Audio module, else with USB Audio off, and says nothing of USB Audio going off', async () => { const { link } = await connected('stock') const withAudio = open({ link, set: { name: 'Live', moduleIds: ['everb', USB_AUDIO_MODULE], usbAudio: { layout: 'master' } } }); await withAudio.render() diff --git a/src/components/BaseInstallDialog.tsx b/src/components/BaseInstallDialog.tsx index 1385153abb..f906594c70 100644 --- a/src/components/BaseInstallDialog.tsx +++ b/src/components/BaseInstallDialog.tsx @@ -29,6 +29,7 @@ export type BaseGuideStage = 'opened' | 'file-downloaded' | 'first-connection' | * - `no-webusb`: this browser has no WebUSB, so the guide can prepare the file but never connect; * - `site-outdated`: Modwerk was deployed since the page opened, so it asks for a reload instead of building a base; * - `build-failed`: the browser could not build the base from the OS file (card download or USB update); + * - `hosted-download-failed`: Modwerk's hosted base (docs/HOSTED_BASES.md) did not download or failed its checks; * - `link-lost`: the Octatrack stopped answering during a USB update (UploadUnconfirmedError); * - `update-refused`: the Octatrack refused a USB update (UploadDeviceError); * - `update-failed`: a USB update stopped for another reason (a restart that didn't come back, the wrong base after it); @@ -124,10 +125,12 @@ function keepStage(stage: CardStage | null) { * holding up the install. `gate` is the firmware build gate (MemberGate.tsx useBuildGate) for whoever has not passed * it: Download base .bin and Update over USB then open the card build's sign-in prompt first, which a guest may skip. */ -export function BaseInstallDialog({ link, launch = false, layout, set, firmwareReady, firmwareError, onChooseFirmware, buildBase, returnSetId, account, gate, onAccount, diagnosticsStep, onStage, onStep, onClose, onReady }: { +export function BaseInstallDialog({ link, launch = false, layout, set, firmwareReady, hostedBase, firmwareError, onChooseFirmware, buildBase: ownBuild, returnSetId, account, gate, onAccount, diagnosticsStep, onStage, onStep, onClose, onReady }: { link: OctatrackLink launch?: boolean firmwareReady: boolean + /** Present while the base comes from Modwerk's hosted image (docs/HOSTED_BASES.md), not the musician's own OS file. */ + hostedBase?: (layout?: BaseLayout, step?: boolean) => Promise /** Why the chosen OS file was refused (not the original 1.40C). */ firmwareError?: string onChooseFirmware: (file: File) => void @@ -159,6 +162,7 @@ export function BaseInstallDialog({ link, launch = false, layout, set, firmwareR onClose: (done: boolean) => void onReady: () => void }) { + const hosted = !!hostedBase, buildBase = hostedBase ?? ownBuild const fileRef = useRef(null), finished = useRef(false), reported = useRef(new Set()), stepsSeen = useRef(new Set()) const state = useOctatrackLink(link), noUsb = state.status === 'unsupported' const [accepted, setAccepted] = useState(false), [signIn, setSignIn] = useState(false) @@ -216,7 +220,7 @@ export function BaseInstallDialog({ link, launch = false, layout, set, firmwareR if (view !== 'steps' || outdated) return step(overUsb ? 'usb-update-shown' : stage === 'download' ? 'card-download' : stage === 'connect' && noUsb ? 'card-load-from-card' : `card-${stage}`) }, [view, outdated, overUsb, stage, noUsb]) // eslint-disable-line react-hooks/exhaustive-deps - useEffect(() => { if (firmwareReady && view === 'steps') step('os-file-ready') }, [firmwareReady, view]) // eslint-disable-line react-hooks/exhaustive-deps + useEffect(() => { if (firmwareReady && view === 'steps') step(hosted ? 'hosted-base-ready' : 'os-file-ready') }, [firmwareReady, hosted, view]) // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { if (firmwareError) step('os-file-refused') }, [firmwareError]) // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { if (accepted) step('risk-accepted') }, [accepted]) // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { if (signIn) step('sign-in-asked') }, [signIn]) // eslint-disable-line react-hooks/exhaustive-deps @@ -247,7 +251,7 @@ export function BaseInstallDialog({ link, launch = false, layout, set, firmwareR let at = 0, stepped = false, image: BaseImage try { image = await buildBase!(installLayout) } catch (error) { - console.error(error); report('failed', 'build-failed') + console.error(error); report('failed', hosted ? 'hosted-download-failed' : 'build-failed') return setUsb({ error: error instanceof Error ? error.message : 'The base could not be built.', at }) } // One update, or two when the unit's base stages less than this base needs: the step base first, which every @@ -288,7 +292,7 @@ export function BaseInstallDialog({ link, launch = false, layout, set, firmwareR setPending({ sha256: image.sha256, expectedBase: image.base, previousBase, returnSetId }); setDownload('done'); setStage('copy') report('file-downloaded') } - catch (error) { console.error(error); report('failed', 'build-failed'); setFailure(error instanceof Error ? error.message : ''); setDownload('failed') } + catch (error) { console.error(error); report('failed', hosted ? 'hosted-download-failed' : 'build-failed'); setFailure(error instanceof Error ? error.message : ''); setDownload('failed') } } const skipHint = MODULE_SKIP_HINT ? ' ' + MODULE_SKIP_HINT : '' @@ -339,7 +343,7 @@ export function BaseInstallDialog({ link, launch = false, layout, set, firmwareR {!usb && <> {/* Three short lines to read, not a paragraph (owner, 13 November 2026). */}
    -
  • {firmwareReady ? 'Your OS 1.40C file is ready.' : <>Choose your original OS 1.40C file. Where do I get it?}
  • +
  • {hosted ? <>Modwerk’s prebuilt base is ready. No OS file needed. : firmwareReady ? 'Your OS 1.40C file is ready.' : <>Choose your original OS 1.40C file. Where do I get it?}
  • Save your project and stop playback first.
  • Then hands off until this window says Done: no keys, no power switch, no cable.
  • {turnsAudioOff &&
  • {AUDIO_OFF_LEAD} {AUDIO_OFF_REST}
  • } @@ -353,11 +357,12 @@ export function BaseInstallDialog({ link, launch = false, layout, set, firmwareR })()} {cardDownload && <>

    Download the base

    -

    Modwerk builds the base in your browser; your OS file never leaves this device.

    +

    {hosted ? 'Modwerk downloads its prebuilt base for you. No OS file needed.' : 'Modwerk builds the base in your browser; your OS file never leaves this device.'}

    - Original OS 1.40C + {hosted ? 'Modwerk base' : 'Original OS 1.40C'} + {hosted && } {!firmwareReady && Where do I get it?}
    {firmwareReady && <>Verified} diff --git a/src/components/faq-content.tsx b/src/components/faq-content.tsx index 1298a9706d..de7e03427c 100644 --- a/src/components/faq-content.tsx +++ b/src/components/faq-content.tsx @@ -179,7 +179,7 @@ const octatrack: FaqSection[] = [ title: 'Where do I get the original OS file?', keywords: 'download base original stock official elektron os 1.40c bin syx zip extract', answer: <> -

    From Elektron. Download the original OS {OS} archive, unzip it and choose {BASE_FIRMWARE.filename} when the install guide asks for it. Choose the .bin, not the ZIP or the .syx.

    +

    From Elektron. Download the original OS {OS} archive, unzip it and choose {BASE_FIRMWARE.filename} when the install guide asks for it. Choose the .bin, not the ZIP or the .syx. When the guide says Modwerk’s prebuilt base is ready, you need no OS file at all.

    It has to be exactly this version, even if Elektron releases a newer one. Modwerk verifies the file: a renamed, modified or different OS can’t be used. Don’t take a firmware file from another person.

    , }, diff --git a/src/config/hosted-bases.test.ts b/src/config/hosted-bases.test.ts new file mode 100644 index 0000000000..daedccba31 --- /dev/null +++ b/src/config/hosted-bases.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest' +import { hostedOctatrackEntry } from './hosted-bases' +import { buildLayout, layoutIdentity } from '../engine/elekloader/base-variants' +import { STEP_IDENTITIES } from '../engine/elekloader/base-step' + +const image = (identity: string, layout: string, step?: boolean) => ({ machine: 'octatrack', identity, layout, step, sha256: 'a'.repeat(64), size: 1, file: 'base.bin' }) + +describe('hosted Octatrack base', () => { + const layout = buildLayout() + it('takes the image whose identity the site publishes for the layout it would build', () => { + const good = image(layoutIdentity(layout)!, layout) + expect(hostedOctatrackEntry([image('f'.repeat(64), layout), good], undefined)).toBe(good) + }) + it('refuses an unpublished identity and keeps step and main images apart', () => { + expect(hostedOctatrackEntry([image('f'.repeat(64), layout)])).toBeUndefined() + const step = image(STEP_IDENTITIES.main, 'main', true) + expect(hostedOctatrackEntry([step], 'main')).toBeUndefined() + expect(hostedOctatrackEntry([step], 'main', true)).toBe(step) + expect(hostedOctatrackEntry([image(STEP_IDENTITIES.off, 'main', true)], 'main', true)).toBeUndefined() + }) +}) diff --git a/src/config/hosted-bases.ts b/src/config/hosted-bases.ts new file mode 100644 index 0000000000..fa69a08c31 --- /dev/null +++ b/src/config/hosted-bases.ts @@ -0,0 +1,30 @@ +// Hosted base images (docs/HOSTED_BASES.md): the Octatrack base without the musician's own OS file. An image counts +// only when its identity is the one this site publishes for the layout and its bytes match the manifest's SHA-256; +// the unit's IDENTIFY then confirms the identity once it runs. +import type { HostedBase, HostedBaseManifest } from '../../server/base-images' +import { api, apiFetch } from '../community/api' +import { baseLayout, buildLayout, type BaseLayout } from '../engine/elekloader/base-variants' +import { STEP_IDENTITIES } from '../engine/elekloader/base-step' +import type { BaseImage } from '../components/BaseInstallDialog' + +let manifest: Promise | undefined +/** The hosted images, read once per page; none when the service is unreachable. */ +export const hostedBases = () => manifest ??= api('/bases').then(value => Array.isArray(value?.images) ? value.images : [], () => []) + +/** The hosted Octatrack image the site would build for this layout, if one is hosted. */ +export function hostedOctatrackEntry(images: readonly HostedBase[], layout?: BaseLayout, step = false) { + const wanted = buildLayout(layout, step) + return images.find(image => image.machine === 'octatrack' && !!image.step === step && image.layout === wanted && + image.identity === (step ? STEP_IDENTITIES[wanted] : baseLayout(image.identity) === wanted ? image.identity : undefined)) +} + +export async function hostedOctatrackBase(layout?: BaseLayout, step = false): Promise { + const entry = hostedOctatrackEntry(await hostedBases(), layout, step) + if (!entry) throw new Error('Modwerk has no prebuilt base for this yet. Choose your own OS 1.40C file instead.') + const response = await apiFetch('/bases/octatrack/' + entry.identity) + if (!response.ok) throw new Error(response.status === 401 || response.status === 403 ? 'Sign in with a verified account to download the prebuilt base.' : 'The prebuilt base did not download. Try again, or choose your own OS 1.40C file.') + const buffer = await response.arrayBuffer() + const sha256 = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', buffer)), byte => byte.toString(16).padStart(2, '0')).join('') + if (buffer.byteLength !== entry.size || sha256 !== entry.sha256) throw new Error('The prebuilt base arrived damaged. Try again, or choose your own OS 1.40C file.') + return { buffer, sha256, base: entry.identity } +} diff --git a/src/engine/elekloader/base-variants.ts b/src/engine/elekloader/base-variants.ts index 1d674023d9..9d600b1bf9 100644 --- a/src/engine/elekloader/base-variants.ts +++ b/src/engine/elekloader/base-variants.ts @@ -7,7 +7,7 @@ import { publishedBinding as baseBinding } from './octatrack-publication.ts' import baseVersions from '../../../sdk/machines/octatrack/base-versions.json' with { type: 'json' } import { sha } from '../elektron/bytes.ts' -import { USB_AUDIO_LAYOUTS, type UsbAudioLayout } from '../../config/usb-audio.ts' +import { USB_AUDIO_LAYOUTS, USB_AUDIO_PACKAGED, type UsbAudioLayout } from '../../config/usb-audio.ts' import type { BaseFill } from './octatrack-base.ts' export type BaseLayout = UsbAudioLayout | 'off' @@ -22,6 +22,9 @@ export const DEFAULT_LAYOUT: BaseLayout = (Object.entries(VARIANTS).find(([, ide * A set with the USB Audio module asks for its layout (module-set.ts setLayout). DEFAULT_LAYOUT stays the committed * package's, which every other layout is a patch against. */ export const MEMBER_LAYOUT: BaseLayout = 'off' +/** The layout a base build takes: without a layout from a module set a member gets MEMBER_LAYOUT (USB MIDI alone), and + * with USB Audio packaged the base is always that one; only the step base (base-step.ts) is built per layout. */ +export const buildLayout = (layout?: BaseLayout, step = false): BaseLayout => !step && USB_AUDIO_PACKAGED ? MEMBER_LAYOUT : layout ?? MEMBER_LAYOUT const IDENTITIES = new Map([[baseBinding.identity, DEFAULT_LAYOUT], ...Object.entries(VARIANTS).map(([layout, identity]) => [identity, layout as BaseLayout] as const)]) /** A base's version, as its status page shows it (PROJ > MODWERK > STATUS: "MODWERK BASE 0.7"), by the identity a unit diff --git a/src/engine/elekloader/published-base.ts b/src/engine/elekloader/published-base.ts new file mode 100644 index 0000000000..7a50e2841b --- /dev/null +++ b/src/engine/elekloader/published-base.ts @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// The base the site publishes for a layout, built from an OS file: one path for the browser's worker (session.ts) and +// the owner's hosted images (scripts/base-publish.mjs), so a hosted image is byte for byte what the browser builds. +import { sha } from '../elektron/bytes.ts' +import { buildBase, type BaseFill } from './octatrack-base.ts' +import { buildLayout, DEFAULT_LAYOUT, variantPackage, type BaseLayout, type BaseVariants } from './base-variants.ts' +import { STEP_ASSETS, STEP_DEFAULT_LAYOUT, STEP_IDENTITIES } from './base-step.ts' + +/** The text of one of the base's assets; `step` names the step base's (base-step.ts). */ +export type BaseAssetLoader = (asset: 'package' | 'variants' | 'fills', step: boolean) => Promise + +export async function buildPublishedBase(stock: Uint8Array, load: BaseAssetLoader, requested?: BaseLayout, step = false) { + const layout = buildLayout(requested, step) + // The step base's three assets are each checked against their pin. + const asset = async (name: 'package' | 'variants' | 'fills', what: string) => { + const text = await load(name, step) + if (step && sha(new TextEncoder().encode(text)) !== STEP_ASSETS[name]) throw new Error(what + ' is damaged. Reload the page and try again.') + return text + } + let text = await asset('package', 'The base package') + let fills = JSON.parse(await asset('fills', 'The base package')) as BaseFill[] + if (layout !== (step ? STEP_DEFAULT_LAYOUT : DEFAULT_LAYOUT)) { + const layouts = JSON.parse(await asset('variants', 'The base layouts')) as BaseVariants + const variant = step ? variantPackage(text, layouts, layout, { defaultLayout: STEP_DEFAULT_LAYOUT, identity: item => STEP_IDENTITIES[item] }) : variantPackage(text, layouts, layout) + if (variant) ({ text, fills } = variant) + } + const built = await buildBase(stock, text, fills) + if (step && built.base !== STEP_IDENTITIES[layout]) throw new Error('The step base did not build as published. Reload the page and try again.') + return { ...built, layout } +} diff --git a/src/engine/session.ts b/src/engine/session.ts index 15d63689ab..2d5ca8e31b 100644 --- a/src/engine/session.ts +++ b/src/engine/session.ts @@ -1,22 +1,19 @@ import { inspectBaseFirmware } from './base' import { decodeFirmware } from './elek' import { recoverStockDsp } from './stock-dsp' -import { buildBase, type BaseFill } from './elekloader/octatrack-base' +import { buildPublishedBase } from './elekloader/published-base' // A file of its own, fetched when a base is built: the worker bundle inlines imports, and the package is 600 KB. import currentPackage from './assets/octatrack-base.elemod?url' import linkedPackage from './assets/linked-audio-0.7.11/octatrack-base.elemod?url' import { USB_AUDIO_PACKAGED } from '../config/usb-audio' import currentVariants from './assets/octatrack-base-variants.json?url' import linkedVariants from './assets/linked-audio-0.7.11/octatrack-base-variants.json?url' -import { DEFAULT_LAYOUT, MEMBER_LAYOUT, variantPackage, type BaseVariants } from './elekloader/base-variants' import currentFills from './assets/octatrack-base-fills.json' import linkedFills from './assets/linked-audio-0.7.11/octatrack-base-fills.json' // The step base (base-step.ts), fetched only by an update that needs it. import stepPackage from './assets/octatrack-base-step.elemod?url' import stepVariants from './assets/octatrack-base-step-variants.json?url' import stepFills from './assets/octatrack-base-step-fills.json?url' -import { STEP_ASSETS, STEP_DEFAULT_LAYOUT, STEP_IDENTITIES } from './elekloader/base-step' -import { sha } from './elektron/bytes.ts' import type { EngineRequest, EngineResponse } from './protocol' const basePackage = USB_AUDIO_PACKAGED ? currentPackage : linkedPackage const baseVariants = USB_AUDIO_PACKAGED ? currentVariants : linkedVariants @@ -38,28 +35,14 @@ export function createEngineSession(reply: (response: EngineResponse, transfer?: if (request.type === 'base') { const original = stock, current = generation if (!original) throw new Error('Choose and verify your OS 1.40C file first.') - // Another USB Audio layout is the default package with its reviewed patch (base-variants.ts). Without a layout - // from a module set, a member gets MEMBER_LAYOUT: USB MIDI alone. The step base is built the same way from - // its own three assets, each checked against its pin. - const step = request.step === true - const layout = !step && USB_AUDIO_PACKAGED ? MEMBER_LAYOUT : request.layout ?? MEMBER_LAYOUT - const asset = async (url: string, pin: string | undefined, what: string) => { - const response = await fetch(url) - if (!response.ok) throw new Error(what + ' did not load. Reload the page and try again.') - const text = await response.text() - if (pin !== undefined && sha(new TextEncoder().encode(text)) !== pin) throw new Error(what + ' is damaged. Reload the page and try again.') - return text - } - let text = await asset(step ? stepPackage : basePackage, step ? STEP_ASSETS.package : undefined, 'The base package') - let fills = step ? JSON.parse(await asset(stepFills, STEP_ASSETS.fills, 'The base package')) as BaseFill[] : baseFills as BaseFill[] - if (layout !== (step ? STEP_DEFAULT_LAYOUT : DEFAULT_LAYOUT)) { - const layouts = JSON.parse(await asset(step ? stepVariants : baseVariants, step ? STEP_ASSETS.variants : undefined, 'The base layouts')) as BaseVariants - const variant = step ? variantPackage(text, layouts, layout, { defaultLayout: STEP_DEFAULT_LAYOUT, identity: item => STEP_IDENTITIES[item] }) : variantPackage(text, layouts, layout) - if (variant) ({ text, fills } = variant) - } - const built = await buildBase(original, text, fills) + const urls = request.step === true ? { package: stepPackage, variants: stepVariants, fills: stepFills } : { package: basePackage, variants: baseVariants, fills: '' } + const built = await buildPublishedBase(original, async (name, step) => { + if (name === 'fills' && !step) return JSON.stringify(baseFills) + const response = await fetch(urls[name]) + if (!response.ok) throw new Error((name === 'variants' ? 'The base layouts' : 'The base package') + ' did not load. Reload the page and try again.') + return response.text() + }, request.layout, request.step === true) if (current !== generation) throw new Error('The selected firmware changed. Build again.') - if (step && built.base !== STEP_IDENTITIES[layout]) throw new Error('The step base did not build as published. Reload the page and try again.') const buffer = built.bin.slice().buffer reply({ id: request.id, type: 'base', buffer, sha256: built.sha256, base: built.base }, [buffer]); return } diff --git a/wrangler.worker.jsonc b/wrangler.worker.jsonc index 1ba83d47d8..d394706f66 100644 --- a/wrangler.worker.jsonc +++ b/wrangler.worker.jsonc @@ -46,6 +46,12 @@ { "binding": "MEDIA", "bucket_name": "modwerk-forum-media" + }, + // Hosted base images (docs/HOSTED_BASES.md): only the owner writes here, with scripts/base-publish.mjs. + // Create it once with `npx wrangler r2 bucket create modwerk-base-images`. + { + "binding": "BASES", + "bucket_name": "modwerk-base-images" } ], // One relay per remote debug session (server/remote-relay.ts); the site's Pages Functions have none and answer 503.