@runeditrun/rer 0.2.59 → 0.2.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/cli/export.mjs +8 -3
  2. package/cli/site-render.mjs +16 -0
  3. package/default-seed/public/brand/mark.svg +1 -0
  4. package/default-seed/public/fonts/outfit/LICENSE.txt +93 -0
  5. package/default-seed/public/fonts/outfit/outfit-latin-ext-wght-normal.woff2 +0 -0
  6. package/default-seed/public/fonts/outfit/outfit-latin-wght-normal.woff2 +0 -0
  7. package/default-seed/public/rer-theme.css +24 -0
  8. package/global/CHANGELOG.md +11 -0
  9. package/modules/demo-host/README.md +6 -0
  10. package/modules/demo-host/native/prepare.mjs +9 -3
  11. package/modules/demo-host/native/visitor.mjs +3 -3
  12. package/modules/demo-host/native/worker.mjs +1 -1
  13. package/modules/demo-host/page-style.mjs +19 -0
  14. package/modules/demo-host/pages.mjs +5 -22
  15. package/modules/demo-host/plan.mjs +1 -1
  16. package/modules/demo-host/theme-script.mjs +18 -0
  17. package/modules/demo-host/theme.mjs +27 -0
  18. package/modules/operator-auth/dev-gate.mjs +3 -2
  19. package/modules/operator-auth/icon-head.d.mts +1 -0
  20. package/modules/operator-auth/icon-head.mjs +3 -0
  21. package/modules/operator-auth/page.mjs +3 -1
  22. package/modules/owner-claim/page.mjs +3 -2
  23. package/modules/portability/README.md +40 -12
  24. package/modules/portability/bookkeeping.mjs +25 -0
  25. package/modules/portability/catalogue.mjs +12 -13
  26. package/modules/portability/cli.mjs +2 -0
  27. package/modules/portability/files.mjs +6 -2
  28. package/modules/portability/import.mjs +8 -4
  29. package/modules/portability/index.d.mts +2 -2
  30. package/modules/portability/progress.mjs +2 -0
  31. package/onboarding/icon-files.d.mts +8 -0
  32. package/onboarding/icon-files.mjs +49 -0
  33. package/onboarding/server.mjs +5 -1
  34. package/package.json +5 -1
package/cli/export.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { cp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
1
+ import { cp, mkdir, readFile, readdir, rm, writeFile, lstat } from 'node:fs/promises';
2
2
  import { createHash } from 'node:crypto';
3
3
  import { resolve, dirname, relative } from 'node:path';
4
4
  import { testSource } from '../composition/git-source.mjs';
@@ -6,7 +6,7 @@ import { cliVersion } from './version.mjs';
6
6
 
7
7
  // Copy whole maintained source/tooling directories. Python publication scans
8
8
  // load sibling modules and data dynamically; they belong in the inventory too.
9
- export const sourceRoots = ['bin/rer.mjs', 'cli', 'modules/delivery-producer/declarations.mjs', 'modules/delivery-producer/bindings.mjs', 'modules/delivery-producer/migrations.mjs', 'modules/delivery-producer/mail.mjs', 'modules/job-queue', 'modules/release', 'modules/deploy-kit', 'modules/container', 'modules/demo-host', 'modules/demo', 'modules/integrations/core', 'modules/mail', 'modules/ai', 'modules/portability', 'modules/d1-transport', 'modules/erasure', 'modules/dependencies', 'modules/operator-auth', 'modules/owner-claim', 'operations', 'scripts/publish-check', 'scripts/publish-check.mjs', 'composition/git-source.mjs', 'edition-authoring/manifest.mjs', 'edition-authoring/files.mjs', 'foundation/runtime/seed-contract.mjs'];
9
+ export const sourceRoots = ['default-seed/public/rer-theme.css', 'default-seed/public/brand/mark.svg', 'default-seed/public/fonts/outfit', 'bin/rer.mjs', 'cli', 'modules/delivery-producer/declarations.mjs', 'modules/delivery-producer/bindings.mjs', 'modules/delivery-producer/migrations.mjs', 'modules/delivery-producer/mail.mjs', 'modules/job-queue', 'modules/release', 'modules/deploy-kit', 'modules/container', 'modules/demo-host', 'modules/demo', 'modules/integrations/core', 'modules/mail', 'modules/ai', 'modules/portability', 'modules/d1-transport', 'modules/erasure', 'modules/dependencies', 'modules/operator-auth', 'modules/owner-claim', 'operations', 'scripts/publish-check', 'scripts/publish-check.mjs', 'composition/git-source.mjs', 'edition-authoring/manifest.mjs', 'edition-authoring/files.mjs', 'foundation/runtime/seed-contract.mjs'];
10
10
  export async function inventory(base, roots = sourceRoots) {
11
11
  const files = [];
12
12
  async function walk(path) {
@@ -19,7 +19,12 @@ export async function inventory(base, roots = sourceRoots) {
19
19
  else throw Error('Non-file CLI export source');
20
20
  }
21
21
  }
22
- for (const source of roots) { if (source.endsWith('.mjs')) files.push(source); else await walk(source); }
22
+ for (const source of roots) {
23
+ const stat = await lstat(resolve(base, source));
24
+ if (stat.isFile()) files.push(source);
25
+ else if (stat.isDirectory()) await walk(source);
26
+ else throw Error('Non-file CLI export source');
27
+ }
23
28
  return files.sort();
24
29
  }
25
30
 
@@ -11,11 +11,14 @@
11
11
  // CONTRACT.md gets it parsed as sitePages({ contract }), for its /contract
12
12
  // page; one that does not parse stops the build, naming its lines.
13
13
  // Usage: node site-render.mjs ROOT ENTRY OUTPUT [CONFIG]
14
+ import { shared } from './shared.mjs';
15
+ const { seedIcons, readIconFiles } = await shared('icon-files.mjs');
14
16
  import { cp, lstat, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
15
17
  import { createRequire } from 'node:module';
16
18
  import { dirname, join, resolve, sep } from 'node:path';
17
19
  import { pathToFileURL } from 'node:url';
18
20
  import { buildClients, writeSiteAsset } from './site-client.mjs';
21
+ import { htmlElements } from './site-markup.mjs';
19
22
  import { redactSiteOutput, siteBuildDiagnostic } from './site-diagnostics.mjs';
20
23
  import { ContractError, parseContract } from '../foundation/runtime/seed-contract.mjs';
21
24
 
@@ -46,6 +49,7 @@ const server = `${output}.render`;
46
49
  let module, styles = [], files = [];
47
50
  try {
48
51
  const built = await vite.build({
52
+ plugins: [seedIcons()],
49
53
  root, configFile: config ? resolve(root, config) : false, envFile: false, logLevel: 'error', mode: 'production',
50
54
  build: {
51
55
  ssr: resolve(root, entry), outDir: server, emptyOutDir: true, copyPublicDir: false, ssrEmitAssets: true,
@@ -82,6 +86,18 @@ try {
82
86
  await lstat(source).catch(() => fail(`Missing site asset public/${asset}.`));
83
87
  await cp(source, join(output, asset), { recursive: true, errorOnExist: true, force: false, verbatimSymlinks: true });
84
88
  }
89
+ const icons = await readIconFiles(publicDirectory);
90
+ // A custom site entry may not use Base's head. Export selected icons only
91
+ // when a generated page actually links them, like its other public assets.
92
+ const linkedIcons = new Set(build.pages.flatMap(({ html }) => htmlElements(html)
93
+ .filter(({ tag, attributes }) => tag === 'link' && (attributes.get('rel') ?? '').toLowerCase().split(/\s+/).some(rel => ['icon', 'apple-touch-icon'].includes(rel)))
94
+ .map(({ attributes }) => attributes.get('href')?.split(/[?#]/)[0])));
95
+ for (const [path, { bytes }] of icons.files) {
96
+ if (!linkedIcons.has(path)) continue;
97
+ const target = join(output, path.slice(1));
98
+ await mkdir(dirname(target), { recursive: true });
99
+ await writeFile(target, bytes);
100
+ }
85
101
  // Only the emitted files: the Node chunks share the folder and never ship.
86
102
  for (const file of files) {
87
103
  await writeSiteAsset(output,file,await readFile(join(server,file)));
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32" height="32"><rect width="32" height="32" rx="8" fill="#334155"/><path d="M16 25V14m0 0c0-4 3-6 7-6 0 4-3 6-7 6Zm0 3c0-3-2.5-5-6-5 0 3 2.5 5 6 5Z" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
@@ -0,0 +1,93 @@
1
+ Copyright 2021 The Outfit Project Authors (https://github.com/Outfitio/Outfit-Fonts)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,24 @@
1
+ /* Default seed's declared theme. The installer, sign-in confirmation, /setup
2
+ read these --rer-* tokens; the app serves this file and its fonts. */
3
+ @font-face {
4
+ font-family: Outfit;
5
+ font-style: normal;
6
+ font-weight: 100 900;
7
+ font-display: swap;
8
+ src: url('/fonts/outfit/outfit-latin-wght-normal.woff2') format('woff2');
9
+ }
10
+ :root {
11
+ --rer-font-body: Outfit, Arial, sans-serif;
12
+ --rer-font-heading: Outfit, Arial, sans-serif;
13
+ --rer-page: #f3f5f8;
14
+ --rer-surface: #ffffff;
15
+ --rer-text: #172033;
16
+ --rer-muted: #475569;
17
+ --rer-border: #64748b;
18
+ --rer-focus: #172033;
19
+ --rer-accent: #334155;
20
+ --rer-accent-text: #ffffff;
21
+ --rer-link: #1d4ed8;
22
+ --rer-radius: 16px;
23
+ --rer-logo: url('/brand/mark.svg');
24
+ }
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.61
4
+
5
+ - **One import path for every seed (#272).** The signed-in move-in screen, rer and Business can share upload → plan → reviewed fingerprint → apply → reconcile → undo, retaining native edit protection, history and erasure across catch-up chains. This integration supersedes #246, #262, #252, #250, #259 and #267.
6
+ - **Seed adoption and migrations.** Follow [modules/import-kit/src/door/ADOPTING.md](../modules/import-kit/src/door/ADOPTING.md). Vendor the current import-kit source/schema and sibling d1-transport through the seed's Base provenance workflow. Add any missing D1 kit schemas in the order shown there, including `d1CustodyStateReplaceSchema`: Base's default seed supplies the additive `migrations/core/0026_import_custody_replace.sql`. Keep previously applied migration names and bytes. For a new door apply `importDoorSchema` once after the kit migrations. For an existing door, add separate new numbered seed migrations for **`importDoorApplyFailureMigration` as one atomic batch with foreign keys on, then `importDoorScopesMigration`**; never reapply the updated `importDoorSchema`. The door returns 503 `import_door_schema_outdated` until those upgrades are applied. Run the seed's normal local migration path (`rer dev` for Base's default seed), its existing HTTP import conformance and every erasure journey with retained door rows; then run `rer deploy --dry-run` and `rer deploy` through its declared deployment path. Preserve the permanent server-owned `installationId`; mount the operator handler with the seed's real owner session/CSRF checks, replace old importer routes/callers, and explicitly opt in to Business grants only where configured. The copyable `checkDoor` journey and complete adapter/erasure checklist are in ADOPTING.md.
7
+ - **Crisp seed favicons (#287).** Shared Base heads choose existing ICO, small SVG/32px PNG and Apple icons before a full mark. Adopting seeds copy the updated runtime heads, include `seedIcons()` in app Vite configuration (`@runeditrun/rer/seed-icons`), and refresh rer for Run, installer and native-demo heads. Preserve seed-owned layouts such as Plinth's Lobby. Seeds without small assets must supply their own artwork.
8
+
9
+ ## 0.2.60
10
+
11
+ - **Hosted demo gates wear each seed’s theme.** Start and ended pages load the seed’s mark, palette, fonts and focus styles, with Base theme assets when absent (#284).
12
+ - **Portability leaves platform bookkeeping behind.** Exports never carry rer-owned tables such as `rer_migrations`, and `includeTables` cannot re-add them. Fresh migrated targets can restore seed data; old archives keep their integrity checks while skipping platform rows with one clear CLI line (#285).
13
+
3
14
  ## 0.2.59
4
15
 
5
16
  - **Release publication scans complete on large seeds and partial clones.** `rer release` hydrates missing history blobs in one fetch and inspects the staged release annotation in the same scan. Orbit finishes in 82 seconds instead of exceeding the 300-second budget, with identical findings. A seed must adopt the new rer through its pin for its release command to use it (#278).
@@ -12,6 +12,12 @@ host. See [adoption and deployment](../../export/DEMO.md#hosting-the-demo).
12
12
  outbound requests return to the same visitor, including declared secondary hosts.
13
13
  - `worker.mjs`, `pages.mjs`, `start-script.mjs`: Turnstile start, progress,
14
14
  cancellation and visitor routing. Static assets are served at the edge.
15
+ - `theme.mjs`, `page-style.mjs`, `theme-script.mjs`: the start and ended pages
16
+ link the seed's built `rer-theme.css` and fonts, as the Lobby does. Their
17
+ colours, type and mark follow its `--rer-*` tokens, including media rules.
18
+ The maintained default seed's theme assets supply missing tokens or an
19
+ absent theme, under `/__demo/theme/`. Styles, fonts and marks stay same-origin;
20
+ a missing mark leaves the product name visible.
15
21
  - `native/warm.mjs`: the start page's prefetch list, built from `dist/client`
16
22
  (the Vite manifest if the build wrote one, else the build's `assetsDir`, else
17
23
  `assets`) and TanStack Start's route manifest, the console's views first,
@@ -1,3 +1,4 @@
1
+ import { shared } from '../../../cli/shared.mjs';
1
2
  import { readFile, writeFile, cp } from 'node:fs/promises';
2
3
  import { resolve, join, relative } from 'node:path';
3
4
  import { createHash } from 'node:crypto';
@@ -5,6 +6,7 @@ import { collectBuildModules } from '../../deploy-kit/build-modules.mjs';
5
6
  import { collectFiles, moduleType } from '../../deploy-kit/artifact.mjs';
6
7
  import { nativeBindings, ISOLATE_FILES, objectExports } from './config.mjs';
7
8
  import { warmList, builtChunks } from './warm.mjs';
9
+ import { prepareTheme } from '../theme.mjs';
8
10
 
9
11
  // The Worker Loader module kind for each upload type deploy-kit gives a build
10
12
  // module, so a demo carries what a normal deploy uploads. Binary kinds travel
@@ -31,13 +33,17 @@ export async function prepareNative(folder) {
31
33
  + objectExports(bindings) };
32
34
  for (const file of ISOLATE_FILES) modules[`_rer/${file}.js`] = { js: await readFile(new URL(`./${file}.mjs`, import.meta.url), 'utf8') };
33
35
  const assets = await collectFiles(join(app, 'dist/client'));
34
- const bundle = { compatibilityDate: config.compatibility_date, compatibilityFlags: [...new Set([...(config.compatibility_flags ?? []), 'nodejs_compat'])], modules,
36
+ await cp(join(app, 'dist/client'), join(folder, 'assets'), { recursive: true });
37
+ const theme = await prepareTheme(folder, assets);
38
+ const { readIconFiles } = await shared('icon-files.mjs');
39
+ const { links: iconHead } = await readIconFiles(join(app, 'dist/client'));
40
+ const bundle = { iconHead, compatibilityDate: config.compatibility_date, compatibilityFlags: [...new Set([...(config.compatibility_flags ?? []), 'nodejs_compat'])], modules,
35
41
  bindings, migrations: manifest.migrations, vars: config.vars ?? {}, crons: config.triggers?.crons ?? [],
36
- assetPaths: assets.filter(file => !file.path.split('/').some(part => part.startsWith('.'))).map(file => '/' + file.path),
42
+ assetPaths: [...assets.filter(file => !file.path.split('/').some(part => part.startsWith('.'))).map(file => '/' + file.path), ...theme.paths],
43
+ theme: theme.stylesheets,
37
44
  immutable: [...builtChunks(assets, manifest.assetsDir)].sort(),
38
45
  warm: (await warmList(assets, root, manifest.operatorPath, manifest.assetsDir)).paths };
39
46
  bundle.digest = createHash('sha256').update(JSON.stringify(bundle)).digest('hex');
40
- await cp(join(app, 'dist/client'), join(folder, 'assets'), { recursive: true });
41
47
  await writeFile(join(folder, 'modules/demo-host/native/bundle.mjs'), `export default ${JSON.stringify(bundle)};\n`);
42
48
  return bundle;
43
49
  }
@@ -98,7 +98,7 @@ export class NativeDemo extends DurableObject {
98
98
  return this.object(binding, id, 'fetch', [new Request(request, { headers })]);
99
99
  }
100
100
  const runtime = await this.session();
101
- if (!runtime) return endedPage(this.env, { headers: { 'set-cookie': clearCookie(this.env) } });
101
+ if (!runtime) return endedPage({ ...this.env, DEMO_THEME: bundle.theme, DEMO_ICON_HEAD: bundle.iconHead }, { headers: { 'set-cookie': clearCookie(this.env) } });
102
102
  return application(this.env, this.ctx, this.ctx.id.toString(), runtime).fetch(request);
103
103
  }
104
104
  // The seed signs the visitor out, then the copy ends as an expired one does.
@@ -106,12 +106,12 @@ export class NativeDemo extends DurableObject {
106
106
  // its next page load finds the ended page.
107
107
  async signOut(request) {
108
108
  const runtime = await this.session();
109
- if (!runtime) return endedPage(this.env, { headers: { 'set-cookie': clearCookie(this.env) } });
109
+ if (!runtime) return endedPage({ ...this.env, DEMO_THEME: bundle.theme, DEMO_ICON_HEAD: bundle.iconHead }, { headers: { 'set-cookie': clearCookie(this.env) } });
110
110
  const response = await application(this.env, this.ctx, this.ctx.id.toString(), runtime).fetch(request);
111
111
  if (response.status >= 400) return response;
112
112
  const body = await response.arrayBuffer();
113
113
  await this.end();
114
- if (/text\/html/.test(request.headers.get('accept') ?? '')) return endedPage(this.env, { headers: { 'set-cookie': clearCookie(this.env) } });
114
+ if (/text\/html/.test(request.headers.get('accept') ?? '')) return endedPage({ ...this.env, DEMO_THEME: bundle.theme, DEMO_ICON_HEAD: bundle.iconHead }, { headers: { 'set-cookie': clearCookie(this.env) } });
115
115
  return new Response(response.status === 204 ? null : body, response);
116
116
  }
117
117
  database(binding, method, args) { return database(this, binding, method, args); }
@@ -21,6 +21,6 @@ export default {
21
21
  return new Response(response.body, { status: response.status, headers });
22
22
  }
23
23
  // The start page prefetches the console's chunks while the visitor waits.
24
- return front.fetch(request, { ...env, DEMO_WARM: bundle.warm }, ctx);
24
+ return front.fetch(request, { ...env, DEMO_WARM: bundle.warm, DEMO_THEME: bundle.theme, DEMO_ICON_HEAD: bundle.iconHead }, ctx);
25
25
  },
26
26
  };
@@ -0,0 +1,19 @@
1
+ // Gate layout; presentation comes from the same --rer-* tokens as the Lobby.
2
+ export const STYLE = `*{box-sizing:border-box}body{margin:0;background:var(--rer-page);color:var(--rer-text);font-family:var(--rer-font-body);-webkit-font-smoothing:antialiased}
3
+ main{width:666px;margin:clamp(32px,18vh,184px) auto 48px}.card{padding:40px 42px 44px;background:var(--rer-surface);border:1px solid var(--rer-border);border-radius:var(--rer-radius);box-shadow:0 12px 45px color-mix(in srgb,var(--rer-text) 5%,transparent)}
4
+ .brand{display:flex;align-items:center;gap:12px;font-family:var(--rer-font-heading,var(--rer-font-body));font-size:18px;line-height:22px;font-weight:var(--rer-wordmark-weight,600);letter-spacing:var(--rer-wordmark-tracking,normal);color:var(--rer-text);margin:0 0 20px}.brand img{display:block;width:40px;height:40px;object-fit:contain}.brand img[hidden]{display:none}
5
+ h1{font-family:var(--rer-font-heading,var(--rer-font-body));font-size:42px;line-height:50px;letter-spacing:-1.3px;margin:0 0 14px;font-weight:700}.intro{font-size:20px;line-height:28px;color:var(--rer-muted);margin:0}
6
+ ul{padding:0;margin:23px 0 35px;list-style:none;color:var(--rer-muted);font-size:18px;line-height:33px}li{position:relative;padding-left:33px}li:before{content:'';position:absolute;left:7px;top:14px;width:7px;height:7px;background:var(--rer-accent);border-radius:50%}
7
+ .notice{margin:0 0 16px;padding:12px 16px;border-radius:8px;background:var(--rer-page);color:var(--rer-text);border:1px solid var(--rer-border);font-size:16px;line-height:22px}
8
+ .cf-turnstile{min-height:65px}.button{display:flex;align-items:center;justify-content:center;gap:12px;width:100%;margin-top:28px;min-height:58px;border:1px solid var(--rer-accent);border-radius:var(--rer-button-radius,var(--rer-radius));background:var(--rer-accent);color:var(--rer-accent-text);font:inherit;font-size:20px;font-weight:700;line-height:26px;padding:15px;text-align:center;text-decoration:none;cursor:pointer}
9
+ .button:disabled{cursor:progress}[data-state=waiting] .button{font-weight:600;cursor:default}
10
+ .spinner{display:none;flex:none;width:20px;height:20px;border:3px solid color-mix(in srgb,currentColor 35%,transparent);border-top-color:currentColor;border-radius:50%;animation:spin .8s linear infinite}[data-state=working] .spinner,[data-state=signing] .spinner{display:block}@keyframes spin{to{transform:rotate(360deg)}}
11
+ ol.steps{display:none;list-style:none;margin:22px auto 0;padding:0;width:max-content;max-width:100%;font-size:16px;line-height:22px;color:var(--rer-muted)}[data-state=working] .steps,[data-state=signing] .steps,[data-state=slow] .steps{display:grid;gap:10px}[data-state=failed] .note{display:none}
12
+ .steps li{padding-left:30px;margin:0}.steps li:before{left:0;top:2px;width:18px;height:18px;box-sizing:border-box;background:none;border:2px solid var(--rer-muted)}.steps [data-at=done]{color:var(--rer-muted)}.steps [data-at=done]:before{content:'✓';border:0;background:var(--rer-accent);color:var(--rer-accent-text);font-size:12px;line-height:18px;font-weight:700;text-align:center}.steps [data-at=now]{color:var(--rer-text);font-weight:600}.steps [data-at=now]:before{border-color:var(--rer-border);border-top-color:var(--rer-accent);animation:spin .8s linear infinite}
13
+ .visually-hidden{position:absolute;width:1px;height:1px;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
14
+ @media(prefers-reduced-motion:reduce){.spinner,.steps [data-at=now]:before{animation:none}.steps [data-at=now]:before{border-color:var(--rer-accent)}}.button:focus-visible,a:focus-visible{outline:3px solid var(--rer-focus);outline-offset:4px}
15
+ .note{font-size:15px;line-height:21px;color:var(--rer-muted);text-align:center;margin:21px 0 0}.secondary{text-align:center;margin:22px 0 0;font-size:18px;line-height:24px;font-weight:600}.secondary a{color:var(--rer-link,var(--rer-text));text-underline-offset:3px}
16
+ .back{text-align:center;margin:32px 0 0;font-size:15px;line-height:22px}.back a{color:var(--rer-link,var(--rer-text));text-underline-offset:3px}
17
+ .ended main{width:min(560px,calc(100% - 32px));margin-top:clamp(32px,26vh,262px)}.ended .card{padding:28px 36px 42px}.ended .brand{font-size:16px;margin-bottom:26px}.ended h1{font-size:36px;line-height:44px;margin-bottom:22px}.ended .intro{margin-bottom:36px}.ended .button{margin-top:0;font-size:18px}
18
+ @media(min-width:600px) and (max-width:1023px){main{width:calc(100% - 64px);max-width:666px;margin:100px auto 48px}.card{padding:36px}h1{font-size:38px;line-height:46px}.intro{font-size:18px;line-height:27px}}
19
+ @media(max-width:599px){main,.ended main{width:calc(100% - 32px);margin:32px auto}.ended .card{padding:26px 22px}.ended h1{font-size:29px;line-height:36px}.ended .intro{font-size:17px;line-height:25px;margin-bottom:28px}.card{padding:26px 22px;border-radius:var(--rer-radius)}.brand{font-size:16px}h1{font-size:34px;line-height:41px;letter-spacing:-.8px}.intro{font-size:17px;line-height:25px}ul{font-size:16px;line-height:25px;margin:22px 0 26px}li{padding-left:22px;margin-bottom:9px}li:before{left:2px;top:9px}.button{font-size:18px;margin-top:22px}.note{font-size:13px;line-height:20px}.steps{font-size:15px}.back{margin-top:24px;font-size:14px}}`;
@@ -2,28 +2,11 @@
2
2
  // Turnstile managed widget starts the demo by itself, start-script.mjs) and the ended page.
3
3
  // Both are one card in the family's quiet sign-in style.
4
4
  import { START_SCRIPT } from './start-script.mjs';
5
+ import { STYLE } from './page-style.mjs';
6
+ import { LOGO_SCRIPT } from './theme-script.mjs';
5
7
 
6
8
  const escape = value => String(value).replace(/[&<>"']/g, character => `&#${character.charCodeAt(0)};`);
7
9
 
8
- const STYLE = `*{box-sizing:border-box}body{margin:0;background:#f2f5f7;color:#192333;font-family:system-ui,-apple-system,'Segoe UI',Arial,sans-serif;-webkit-font-smoothing:antialiased}
9
- main{width:666px;margin:clamp(32px,18vh,184px) auto 48px}.card{padding:40px 42px 44px;background:#fff;border:1px solid #d6dfe9;border-radius:18px;box-shadow:0 12px 45px rgba(42,65,86,.05)}
10
- .mark{width:35px;height:6px;border-radius:4px;background:#20574d;margin:0 0 20px}.brand{font-size:18px;line-height:22px;font-weight:600;color:#527875;margin:0 0 14px}
11
- h1{font-size:42px;line-height:50px;letter-spacing:-1.3px;margin:0 0 14px;font-weight:700}.intro{font-size:20px;line-height:28px;color:#41516a;margin:0}
12
- ul{padding:0;margin:23px 0 35px;list-style:none;color:#31415a;font-size:18px;line-height:33px}li{position:relative;padding-left:33px}li:before{content:'';position:absolute;left:7px;top:14px;width:7px;height:7px;background:#2b7864;border-radius:50%}
13
- .notice{margin:0 0 16px;padding:12px 16px;border-radius:8px;background:#fdf6ec;color:#6b3d0f;font-size:16px;line-height:22px}
14
- .cf-turnstile{min-height:65px}.button{display:flex;align-items:center;justify-content:center;gap:12px;width:100%;margin-top:28px;min-height:58px;border:1px solid #86a49f;border-radius:11px;background:linear-gradient(110deg,#225b51,#1e5148 60%,#20584d);color:#fff;font:inherit;font-size:20px;font-weight:700;line-height:26px;padding:15px;text-align:center;text-decoration:none;cursor:pointer}
15
- .button:disabled{cursor:progress}[data-state=waiting] .button{background:#edf3f1;border-color:#78968f;color:#1b4d44;font-weight:600;cursor:default}
16
- .spinner{display:none;flex:none;width:20px;height:20px;border:3px solid rgba(255,255,255,.35);border-top-color:#fff;border-radius:50%;animation:spin .8s linear infinite}[data-state=working] .spinner,[data-state=signing] .spinner{display:block}@keyframes spin{to{transform:rotate(360deg)}}
17
- ol.steps{display:none;list-style:none;margin:22px auto 0;padding:0;width:max-content;max-width:100%;font-size:16px;line-height:22px;color:#50617e}[data-state=working] .steps,[data-state=signing] .steps,[data-state=slow] .steps{display:grid;gap:10px}[data-state=failed] .note{display:none}
18
- .steps li{padding-left:30px;margin:0}.steps li:before{left:0;top:2px;width:18px;height:18px;box-sizing:border-box;background:none;border:2px solid #7f8da1}.steps [data-at=done]{color:#31415a}.steps [data-at=done]:before{content:'✓';border:0;background:#2b7864;color:#fff;font-size:12px;line-height:18px;font-weight:700;text-align:center}.steps [data-at=now]{color:#192333;font-weight:600}.steps [data-at=now]:before{border-color:#c9dcd7;border-top-color:#20574d;animation:spin .8s linear infinite}
19
- .visually-hidden{position:absolute;width:1px;height:1px;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
20
- @media(prefers-reduced-motion:reduce){.spinner,.steps [data-at=now]:before{animation:none}.steps [data-at=now]:before{border-color:#20574d}}.button:focus-visible,a:focus-visible{outline:3px solid #388c77;outline-offset:4px}
21
- .note{font-size:15px;line-height:21px;color:#50617e;text-align:center;margin:21px 0 0}.secondary{text-align:center;margin:22px 0 0;font-size:18px;line-height:24px;font-weight:600}.secondary a{color:#1b554e;text-underline-offset:3px}
22
- .back{text-align:center;margin:32px 0 0;font-size:15px;line-height:22px}.back a{color:#1b554e;text-underline-offset:3px}
23
- .ended main{width:min(560px,calc(100% - 32px));margin-top:clamp(32px,26vh,262px)}.ended .card{padding:28px 36px 42px}.ended .brand{font-size:16px;margin-bottom:26px}.ended h1{font-size:36px;line-height:44px;margin-bottom:22px}.ended .intro{margin-bottom:36px}.ended .button{margin-top:0;font-size:18px}
24
- @media(min-width:600px) and (max-width:1023px){main{width:calc(100% - 64px);max-width:666px;margin:100px auto 48px}.card{padding:36px}h1{font-size:38px;line-height:46px}.intro{font-size:18px;line-height:27px}}
25
- @media(max-width:599px){main,.ended main{width:calc(100% - 32px);margin:32px auto}.ended .card{padding:26px 22px}.ended h1{font-size:29px;line-height:36px}.ended .intro{font-size:17px;line-height:25px;margin-bottom:28px}.card{padding:26px 22px;border-radius:16px}.brand{font-size:16px}h1{font-size:34px;line-height:41px;letter-spacing:-.8px}.intro{font-size:17px;line-height:25px}ul{font-size:16px;line-height:25px;margin:22px 0 26px}li{padding-left:22px;margin-bottom:9px}li:before{left:2px;top:9px}.button{font-size:18px;margin-top:22px}.note{font-size:13px;line-height:20px}.steps{font-size:15px}.back{margin-top:24px;font-size:14px}}`;
26
-
27
10
  // The console's chunks, fetched at idle priority while the visitor waits for
28
11
  // the check and sign-in (native/warm.mjs). The browser ignores a failed one,
29
12
  // and one with prefetching turned off fetches none.
@@ -31,9 +14,9 @@ const warm = env => (env.DEMO_WARM ?? []).map(path => `<link rel="prefetch" href
31
14
 
32
15
  function html(env, { page, title, body, status = 200, headers = {}, turnstile = false, refresh = false }) {
33
16
  const nonce = crypto.randomUUID().replaceAll('-', ''), site = new URL(env.DEMO_SITE);
34
- const policy = `default-src 'none'; style-src 'nonce-${nonce}'; img-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'${turnstile ? `; script-src 'nonce-${nonce}' https://challenges.cloudflare.com; frame-src https://challenges.cloudflare.com; connect-src 'self' https://challenges.cloudflare.com` : ''}`;
35
- return new Response(`<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>${escape(title)}</title>${refresh ? '<noscript><meta http-equiv="refresh" content="2;url=/__demo/status"></noscript>' : ''}<style nonce="${nonce}">${STYLE}</style>${turnstile ? `<noscript><style nonce="${nonce}">#note{display:none}</style></noscript><script nonce="${nonce}">${START_SCRIPT}</script><script nonce="${nonce}" src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>${warm(env)}` : ''}</head>
36
- <body class="${page}"><main><section class="card" aria-labelledby="title"><div class="mark" aria-hidden="true"></div><p class="brand">${escape(env.DEMO_NAME)}</p>${body}</section><nav class="back" aria-label="Return"><a href="${escape(site.origin)}/">Back to ${escape(site.host)}</a></nav></main></body></html>`,
17
+ const policy = `default-src 'none'; style-src 'self' 'nonce-${nonce}'; font-src 'self'; img-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'; script-src 'nonce-${nonce}'${turnstile ? ` https://challenges.cloudflare.com; frame-src https://challenges.cloudflare.com; connect-src 'self' https://challenges.cloudflare.com` : ''}`;
18
+ return new Response(`<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>${escape(title)}</title>${env.DEMO_ICON_HEAD ?? ''}${refresh ? '<noscript><meta http-equiv="refresh" content="2;url=/__demo/status"></noscript>' : ''}${(env.DEMO_THEME ?? []).map(path => `<link rel="stylesheet" href="${escape(path)}">`).join('')}<style nonce="${nonce}">${STYLE}</style>${turnstile ? `<noscript><style nonce="${nonce}">#note{display:none}</style></noscript><script nonce="${nonce}">${START_SCRIPT}</script><script nonce="${nonce}" src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>${warm(env)}` : ''}</head>
19
+ <body class="${page}"><main><section class="card" aria-labelledby="title"><p class="brand"><img class="mark" alt="${escape(env.DEMO_NAME)}" width="40" height="40" hidden><span>${escape(env.DEMO_NAME)}</span></p>${body}</section><nav class="back" aria-label="Return"><a href="${escape(site.origin)}/">Back to ${escape(site.host)}</a></nav></main><script nonce="${nonce}">${LOGO_SCRIPT}</script></body></html>`,
37
20
  { status, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'content-security-policy': policy, 'referrer-policy': 'strict-origin', 'x-content-type-options': 'nosniff', ...headers } });
38
21
  }
39
22
 
@@ -4,7 +4,7 @@ import { ownerWorkerName } from '../deploy-kit/owner.mjs';
4
4
  import { siteDeclaration } from '../deploy-kit/site.mjs';
5
5
 
6
6
  // Native Loader front, admission and visitor session support.
7
- export const DEMO_FILES = ['worker.mjs', 'capacity.mjs', 'claim.mjs', 'pages.mjs', 'start-script.mjs', 'diagnostics.mjs', 'operator.mjs', 'measurement.mjs'];
7
+ export const DEMO_FILES = ['worker.mjs', 'capacity.mjs', 'claim.mjs', 'pages.mjs', 'page-style.mjs', 'theme-script.mjs', 'start-script.mjs', 'diagnostics.mjs', 'operator.mjs', 'measurement.mjs'];
8
8
  const FRONT_SET = /^(?:RER_.*|SESSION_SECRET|SETUP_TOKEN|OWNER_EMAIL)$/;
9
9
  const SECRET = /SECRET|TOKEN|PASSWORD|_KEY$/;
10
10
  export function demoDeclaration(value, originVar) {
@@ -0,0 +1,18 @@
1
+ // Like the Lobby, load the seed's served theme and show its mark beside the
2
+ // product name. Resolve the CSS token in the browser so dark-mode marks work
3
+ // too. A missing or broken image leaves the product's text visible.
4
+ export const LOGO_SCRIPT = `(()=>{
5
+ const mark=document.querySelector('.brand img'),name=document.querySelector('.brand span');
6
+ const update=()=>{
7
+ const token=getComputedStyle(document.documentElement).getPropertyValue('--rer-logo');
8
+ const match=/url\\(\\s*(['"]?)([^'"\\)]+)\\1\\s*\\)/.exec(token);
9
+ mark.hidden=true;name.removeAttribute('aria-hidden');
10
+ if(!match)return;
11
+ const url=new URL(match[2].trim(),location.href);
12
+ if(url.origin!==location.origin)return;
13
+ mark.onload=()=>{mark.hidden=false;name.setAttribute('aria-hidden','true')};
14
+ mark.onerror=()=>{mark.hidden=true;name.removeAttribute('aria-hidden')};
15
+ mark.src=url.href;
16
+ };
17
+ update();matchMedia('(prefers-color-scheme: dark)').addEventListener('change',update);
18
+ })()`;
@@ -0,0 +1,27 @@
1
+ import { mkdir, writeFile } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { shared } from '../../cli/shared.mjs';
5
+
6
+ const prefix = '/__demo/theme';
7
+
8
+ // Ship the maintained default seed's actual theme, font and mark, rather than
9
+ // another set of fallback values. Namespace its assets so they cannot replace
10
+ // a seed's own files. The seed stylesheet follows it, just as in the Lobby;
11
+ // the browser resolves imports, token aliases and light/dark media rules.
12
+ export async function prepareTheme(folder, assets) {
13
+ const { loadSeedTheme } = await shared('theme-files.mjs');
14
+ const defaults = await loadSeedTheme(fileURLToPath(new URL('../../default-seed/', import.meta.url)), 'public/rer-theme.css');
15
+ const paths = [];
16
+ for (const [path, file] of defaults.files) {
17
+ const target = join(folder, 'assets', prefix, path);
18
+ await mkdir(dirname(target), { recursive: true });
19
+ const bytes = file.type === 'text/css'
20
+ ? file.bytes.toString().replace(/url\((['"]?)(\/[^)'"\s]+)\1\)/g, (_, quote, url) => `url(${quote}${prefix}${url}${quote})`)
21
+ : file.bytes;
22
+ await writeFile(target, bytes);
23
+ paths.push(prefix + path);
24
+ }
25
+ const has = path => assets.some(file => file.path === path);
26
+ return { paths, stylesheets: [prefix + '/rer-theme.css', ...(has('fonts/fonts.css') ? ['/fonts/fonts.css'] : []), ...(has('rer-theme.css') ? ['/rer-theme.css'] : [])] };
27
+ }
@@ -1,3 +1,4 @@
1
+ import { iconHead } from './icon-head.mjs';
1
2
  import { rejectedResponse } from './rejected-response.mjs';
2
3
  import { constantEqual } from './crypto.mjs';
3
4
  import { escapeHtml, isLoopbackHost, localCookieName } from './http.mjs';
@@ -88,9 +89,9 @@ export function devGate({ key, origin, local }) {
88
89
  // The seed's declared branding (its product name and theme) brands the page; without it the page is unnamed.
89
90
  const brand = branding === undefined ? undefined : configureBranding(branding);
90
91
  const theme = brand?.theme;
91
- const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex, nofollow"><title>Opening the local app</title>${theme ? `<link rel="stylesheet" href="${escapeHtml(theme)}">` : ''}<style>${PAGE_STYLE}</style></head><body><main>${brand ? `<p class="brand"><span>${escapeHtml(brand.productName)}</span></p>` : ''}<h1>Opening the local app</h1><p>Open the RER_OPEN link that rer prints on this computer.</p></main>${theme ? `<script>${LOGO_SCRIPT}</script>` : ''}<script>${EXCHANGE_SCRIPT}</script></body></html>`;
92
+ const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex, nofollow"><title>Opening the local app</title>${iconHead}${theme ? `<link rel="stylesheet" href="${escapeHtml(theme)}">` : ''}<style>${PAGE_STYLE}</style></head><body><main>${brand ? `<p class="brand"><span>${escapeHtml(brand.productName)}</span></p>` : ''}<h1>Opening the local app</h1><p>Open the RER_OPEN link that rer prints on this computer.</p></main>${theme ? `<script>${LOGO_SCRIPT}</script>` : ''}<script>${EXCHANGE_SCRIPT}</script></body></html>`;
92
93
  return new Response(request.method === 'HEAD' ? null : body, { headers: { ...privateHeaders, 'content-type': 'text/html; charset=utf-8',
93
- 'content-security-policy': `default-src 'none'; script-src ${script}${theme ? ` ${logo}` : ''}; style-src ${theme ? "'self' " : ''}${style}${theme ? "; font-src 'self'; img-src 'self'" : ''}; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'` } });
94
+ 'content-security-policy': `default-src 'none'; img-src 'self'; script-src ${script}${theme ? ` ${logo}` : ''}; style-src ${theme ? "'self' " : ''}${style}${theme ? "; font-src 'self'" : ''}; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'` } });
94
95
  }
95
96
  if (request.method !== 'POST' || request.headers.get('sec-fetch-site') === 'cross-site' || !request.headers.get('content-type')?.startsWith('application/json')) return rejectedResponse(request, devNotFound());
96
97
  const text = await request.text();
@@ -0,0 +1 @@
1
+ export const iconHead: string;
@@ -0,0 +1,3 @@
1
+ // Replaced by seedIcons() when Vite builds the app or run site. Direct Node
2
+ // consumers have no declared public directory, so emit no speculative links.
3
+ export const iconHead = typeof __RER_ICON_HEAD__ === 'undefined' ? '' : __RER_ICON_HEAD__;
@@ -1,3 +1,4 @@
1
+ import { iconHead } from './icon-head.mjs';
1
2
  import { accentInk } from './branding.mjs';
2
3
  import { escapeHtml, securityHeaders } from './http.mjs';
3
4
 
@@ -23,11 +24,12 @@ export async function pageResponse({ branding, title, heading, content, status =
23
24
  const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(css)));
24
25
  const hash = btoa(String.fromCharCode(...digest));
25
26
  const product = escapeHtml(branding.productName);
26
- const html = `<!doctype html><html lang="en"${branding.theme ? ' class="rer-themed"' : ''}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${title ?? heading}</title>${branding.theme ? `<link rel="stylesheet" href="${escapeHtml(branding.theme)}">` : ''}<style>${css}</style></head><body><main><p class="brand"><span class="mark" aria-hidden="true"></span><span data-rer-name>${product}</span></p><h1>${heading}</h1>${content}</main></body></html>`;
27
+ const html = `<!doctype html><html lang="en"${branding.theme ? ' class="rer-themed"' : ''}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${title ?? heading}</title>${iconHead}${branding.theme ? `<link rel="stylesheet" href="${escapeHtml(branding.theme)}">` : ''}<style>${css}</style></head><body><main><p class="brand"><span class="mark" aria-hidden="true"></span><span data-rer-name>${product}</span></p><h1>${heading}</h1>${content}</main></body></html>`;
27
28
  const headers = { ...securityHeaders(), 'Content-Type': 'text/html; charset=utf-8' };
28
29
  // A form may post to this origin only, plus any origin its own redirect must reach (a provider's authorization endpoint).
29
30
  if (formTargets.length) headers['Content-Security-Policy'] = headers['Content-Security-Policy'].replace("form-action 'self'", `form-action 'self' ${formTargets.join(' ')}`);
30
31
  headers['Content-Security-Policy'] += branding.theme ? `; style-src 'self' 'sha256-${hash}'; font-src 'self'; img-src 'self'` : `; style-src 'sha256-${hash}'`;
32
+ if (iconHead && !branding.theme) headers['Content-Security-Policy'] += "; img-src 'self'";
31
33
  // Native form POSTs need their Origin; never disclose the path or query.
32
34
  if (referrer) headers['Referrer-Policy'] = referrer;
33
35
  return new Response(method === 'HEAD' ? null : html, { status, headers });
@@ -1,3 +1,4 @@
1
+ import { iconHead } from '../operator-auth/icon-head.mjs';
1
2
  import { escapeHtml, securityHeaders } from '../operator-auth/http.mjs';
2
3
  export function confirmationPage(config, head = false) {
3
4
  const nonce = btoa(crypto.randomUUID());
@@ -6,6 +7,6 @@ export function confirmationPage(config, head = false) {
6
7
  window.addEventListener('message',event=>{if(received||!source||event.source!==source||event.origin!==issuer||event.data?.type!=='rer-owner-claim'||typeof event.data.token!=='string'||event.data.token.length>8192)return;received=true;form.elements.token.value=event.data.token;form.querySelector('button').disabled=false;message.textContent='Ready to claim your workspace.';window.opener=null;});
7
8
  if(source)source.postMessage({type:'rer-owner-claim-ready'},issuer);else message.textContent='Open this confirmation from your installation in Run Edit Run.';`;
8
9
  const headers = { ...securityHeaders(), 'Content-Type': 'text/html; charset=utf-8', 'Referrer-Policy': 'strict-origin',
9
- 'Content-Security-Policy': `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'` };
10
- return new Response(head ? null : `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Claim your workspace</title><style nonce="${nonce}">*{box-sizing:border-box}body{margin:0;font:16px/1.5 system-ui;background:#f5f7fb;color:#182130}main{max-width:32rem;margin:8vh auto;padding:2rem}label{display:block;margin:1rem 0 .3rem}input,button{width:100%;font:inherit;padding:.7rem;border:1px solid #687385;border-radius:.4rem}button{margin-top:1.5rem;background:#183dad;color:white}button:disabled{background:#566274}h1{font-size:2rem;line-height:1.2}p{overflow-wrap:anywhere}</style></head><body><main><h1>Claim your workspace</h1><p>Confirm to create your owner account and sign in.</p><form method="post" action="/auth/owner-claim"><label for="email">Owner email</label><input id="email" type="email" value="${escapeHtml(config.expectedEmail)}" readonly><label for="name">Your name</label><input id="name" name="displayName" autocomplete="name" maxlength="100" value="Owner" required><input type="hidden" name="token"><button disabled>Claim your workspace</button></form><p role="status">Waiting for your secure claim.</p></main><script nonce="${nonce}">${script}</script></body></html>`, { headers });
10
+ 'Content-Security-Policy': `default-src 'none'; img-src 'self'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'` };
11
+ return new Response(head ? null : `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Claim your workspace</title>${iconHead}<style nonce="${nonce}">*{box-sizing:border-box}body{margin:0;font:16px/1.5 system-ui;background:#f5f7fb;color:#182130}main{max-width:32rem;margin:8vh auto;padding:2rem}label{display:block;margin:1rem 0 .3rem}input,button{width:100%;font:inherit;padding:.7rem;border:1px solid #687385;border-radius:.4rem}button{margin-top:1.5rem;background:#183dad;color:white}button:disabled{background:#566274}h1{font-size:2rem;line-height:1.2}p{overflow-wrap:anywhere}</style></head><body><main><h1>Claim your workspace</h1><p>Confirm to create your owner account and sign in.</p><form method="post" action="/auth/owner-claim"><label for="email">Owner email</label><input id="email" type="email" value="${escapeHtml(config.expectedEmail)}" readonly><label for="name">Your name</label><input id="name" name="displayName" autocomplete="name" maxlength="100" value="Owner" required><input type="hidden" name="token"><button disabled>Claim your workspace</button></form><p role="status">Waiting for your secure claim.</p></main><script nonce="${nonce}">${script}</script></body></html>`, { headers });
11
12
  }
@@ -20,7 +20,7 @@ schema at construction. Apply the bookkeeping migration first. Policy fields:
20
20
  | --- | --- |
21
21
  | `product` | Required archive product identity. |
22
22
  | `excludeTables` | Additional exact names or prefixes ending in `%`. |
23
- | `includeTables` | Explicit identity tables to include despite default exclusions. |
23
+ | `includeTables` | Explicit identity tables to include despite default identity exclusions. Mandatory platform bookkeeping tables cannot be included. |
24
24
  | `derivedTables` | Virtual/FTS tables to regenerate; their shadow tables are excluded. |
25
25
  | `secretColumns` | Per-table nullable base columns omitted at export and written as NULL. Primary keys and generated columns cannot be secret. |
26
26
  | `exportRow(table,row)` | Pure, synchronous, idempotent transformation of encoded base cells. Restore writes its result verbatim; SQLite recomputes generated cells. |
@@ -32,14 +32,35 @@ schema at construction. Apply the bookkeeping migration first. Policy fields:
32
32
  | `extraPayloads` | Named `{produce,consume}` pairs. Producers return bytes or a byte stream. Consumers receive a verified byte stream and descriptor before D1 commit. |
33
33
  | `partBytes` | Maximum part size, default 16 MiB, configurable from 1 KiB to 16 MiB. |
34
34
 
35
- Archives always skip Base's own tables: SQLite and Cloudflare internals, the
36
- migration ledgers (`d1_migrations`, `_rer_deploy_migrations`,
37
- `_rer_portability_migrations`), portability bookkeeping, development outboxes,
38
- operator identity and dependency secrets. `excludedTables` lists them (exact
39
- names, or prefixes ending in `%`), and `excludedTable(name, policy)` says whether
40
- an archive under that policy skips a table. A seed's own table inventory, which
41
- refuses tables it does not know, uses the same predicate, so it does not refuse a
42
- table Base created and never archives.
35
+ `bookkeeping.mjs` defines the mandatory `platformTables` list. These tables
36
+ belong to the current runtime or environment and never travel:
37
+
38
+ | Tables (exact names or prefixes ending in `%`) | Reason |
39
+ | --- | --- |
40
+ | `sqlite_%`, `_cf_%` | SQLite and Cloudflare internals. |
41
+ | `d1_migrations`, `_rer_deploy_migrations`, `_rer_portability_migrations`, `rer_migrations` | Destination migration history. Current Base uses the D1 and `_rer_` ledgers; `rer_migrations` is excluded for historical compatibility. |
42
+ | `rer_portability_%` | Transfer jobs, snapshots, staging, journals and recovery bookkeeping. |
43
+ | `rer_mail_development_outbox`, `rer_ai_development_outbox` | Local development effect captures. |
44
+ | `rer_dependency_keys`, `rer_dependency_pending`, `rer_dependency_codes` | Provider secrets and transient linking credentials. |
45
+ | `rer_command_receipts` | Command replay receipts tied to the source installation. |
46
+ | `rer_erasure_blobs`, `rer_erasure_guard`, `rer_erasure_scope`, `rer_erasure_rates` | Erasure work queues, transaction guards, working scope and local rate limits. |
47
+ | `rer_demo` | Local demo setup markers. |
48
+
49
+ `excludedTables` combines this list with the default identity exclusions `oa_%`
50
+ and `oc_%`. Policy may override those identity exclusions through `includeTables`,
51
+ but naming a mandatory platform table there refuses construction with
52
+ `platform_table:<name>` and a message identifying the table.
53
+ `excludedTable(name, policy)` always returns true for mandatory platform tables,
54
+ regardless of policy, so export cannot include them. A seed's own table inventory,
55
+ which refuses tables it does not know, uses the same predicate, so it does not
56
+ refuse a table Base created and never archives.
57
+
58
+ These are specific exclusions, not a blanket exclusion of `rer_%` tables.
59
+ Durable erasure receipts in `rer_erasure_operations`, installation identity in
60
+ `rer_dependency_installation`, retained links in `rer_dependency_link`, and mail
61
+ delivery receipts and state in `rer_mail_event_receipts` and
62
+ `rer_mail_event_states` remain portable unless product policy excludes them.
63
+ Seed-owned tables are likewise discovered and remain portable by default.
43
64
 
44
65
  For native local CLI transfers, declare executable policy through
45
66
  `localPortability({database, buckets, policyModule})`. `policyModule` is a
@@ -69,9 +90,6 @@ it continues to accept serializable object policies. Malformed primary or later
69
90
  journal JSON is reported once as `archive_json` with exit 2, before local data
70
91
  migrations, without echoing archive content or parser diagnostics.
71
92
 
72
- Default exclusions are `sqlite_%`, `_cf_%`, `d1_migrations`,
73
- `rer_portability_%`, `rer_mail_development_outbox`, `oa_%`, `oc_%`,
74
- `rer_dependency_keys`, `rer_dependency_pending` and `rer_dependency_codes`.
75
93
  When a policy includes operator-auth tables, local dev identity still never
76
94
  travels, and no policy option changes that: export drops `oa_sessions` rows of
77
95
  kind `dev`, every credential recorded in `oa_dev_credentials` (and that table's
@@ -147,6 +165,15 @@ commit. Local `rer import` verifies the whole input before even applying
147
165
  destination migrations. `contentHash` remains the content-equivalence digest;
148
166
  `archiveHash` changes when export time, source metadata or part boundaries change.
149
167
 
168
+ Older version 2 archives may contain tables now classified as mandatory platform
169
+ bookkeeping. Import verifies the original archive in full, including its
170
+ manifest, every part, `contentHash` and `archiveHash`; excluded rows still count
171
+ in those integrity checks. Their rows are never staged or restored. Only these
172
+ mandatory tables are removed from the effective schema before compatibility
173
+ checks; this does not waive checks on any remaining table. `imports.status(id)`
174
+ reports their names in `skippedTables`. File and HTTP CLI imports print one line
175
+ when any are skipped: `Skipped platform bookkeeping tables: <names>.`
176
+
150
177
  Version 1 archives lack this binding and are refused with
151
178
  `legacy_archive_unverifiable` (HTTP 409; local `rer import` exit 4), before
152
179
  restoration. Upgrade the original installation and export a new archive.
@@ -444,6 +471,7 @@ modules/portability/lines.mjs
444
471
  modules/portability/hash.mjs
445
472
  modules/portability/format.mjs
446
473
  modules/portability/catalogue.mjs
474
+ modules/portability/bookkeeping.mjs
447
475
  modules/portability/storage.mjs
448
476
  modules/portability/copies.mjs
449
477
  modules/portability/dev-data.mjs
@@ -0,0 +1,25 @@
1
+ import { canonicalJson, sha256 } from './hash.mjs';
2
+
3
+ // Installation authority and transient working state, never product data.
4
+ // Keep exact names except for SQLite/Cloudflare internals and portability's
5
+ // own dynamic copies. Durable erasure receipts and dependency bindings travel.
6
+ export const platformTables=Object.freeze([
7
+ 'sqlite_%','_cf_%','d1_migrations','rer_migrations',
8
+ '_rer_deploy_migrations','_rer_portability_migrations','rer_portability_%',
9
+ 'rer_mail_development_outbox','rer_ai_development_outbox',
10
+ 'rer_dependency_keys','rer_dependency_pending','rer_dependency_codes',
11
+ 'rer_command_receipts','rer_erasure_blobs','rer_erasure_guard',
12
+ 'rer_erasure_scope','rer_erasure_rates','rer_demo',
13
+ ]);
14
+ export const identifier=value=>value.replace(/[A-Z]/g,letter=>letter.toLowerCase());
15
+ export const matches=(table,pattern)=>pattern.endsWith('%') ? identifier(table).startsWith(identifier(pattern.slice(0,-1))) : identifier(table)===identifier(pattern);
16
+ export const platformTable=table=>platformTables.some(pattern=>matches(table,pattern));
17
+ // Compatibility uses the product schema, while the original manifest and parts
18
+ // remain intact for end-to-end archive verification, including skipped rows.
19
+ export async function restorableManifest(manifest) {
20
+ const tables=manifest.tables.filter(table=>!platformTable(table.name));
21
+ if(tables.length===manifest.tables.length)return manifest;
22
+ return {...manifest,tables,schema:await sha256(canonicalJson(tables.map(({name,sql})=>({name,sql})))),
23
+ excludedColumns:Object.fromEntries(Object.entries(manifest.excludedColumns).filter(([name])=>!platformTable(name)))};
24
+ }
25
+ export const skippedTablesLine=tables=>'Skipped platform bookkeeping tables: '+tables.join(', ')+'.';
@@ -1,10 +1,8 @@
1
- import { all, insist, quote } from './storage.mjs';
1
+ import { all, insist, quote, PortabilityError } from './storage.mjs';
2
2
  import { canonicalJson, sha256, base64, unbase64, utf8 } from './hash.mjs';
3
- /** Tables no archive carries: SQLite/Cloudflare internals, migration ledgers,
4
- * portability bookkeeping, development outboxes, operator identity, dependency
5
- * secrets and refresh-safe command receipts. Exact names, or prefixes ending in `%`. Seeds' own table inventories
6
- * skip the same tables through `excludedTable`. */
7
- export const excludedTables=Object.freeze(['sqlite_%','_cf_%','d1_migrations','_rer_deploy_migrations','_rer_portability_migrations','rer_portability_%','rer_mail_development_outbox','rer_ai_development_outbox','oa_%','oc_%','rer_dependency_keys','rer_dependency_pending','rer_dependency_codes','rer_command_receipts']);
3
+ import { platformTables, platformTable, identifier, matches } from './bookkeeping.mjs';
4
+ /** Platform bookkeeping is mandatory; operator identity remains a seed choice. */
5
+ export const excludedTables=Object.freeze([...platformTables,'oa_%','oc_%']);
8
6
  const fields=['product','excludeTables','includeTables','derivedTables','secretColumns','exportRow','replaceableTables','requiredConfiguration','validateStaged','acceptedSchemas','buckets','extraPayloads','partBytes'];
9
7
  const name=value=>typeof value==='string' && value.length>0 && value.length<=512 && !/[\x00-\x1f]/.test(value);
10
8
  const names=value=>Array.isArray(value) && value.every(name) && new Set(value).size===value.length;
@@ -12,6 +10,10 @@ export function policy(input) {
12
10
  insist(input && typeof input==='object' && Object.keys(input).every(k=>fields.includes(k)) && name(input.product),'invalid_policy');
13
11
  const result={excludeTables:[],includeTables:[],derivedTables:[],secretColumns:{},replaceableTables:[],requiredConfiguration:[],acceptedSchemas:{},buckets:{},extraPayloads:{},partBytes:16*1024*1024,...input};
14
12
  for(const key of ['excludeTables','includeTables','derivedTables','replaceableTables','requiredConfiguration']) insist(names(result[key]),'invalid_policy_'+key);
13
+ for(const table of result.includeTables) if(platformTable(table)) {
14
+ const error=new PortabilityError('platform_table:'+table);
15
+ error.message='includeTables cannot include platform-owned table "'+table+'".';throw error;
16
+ }
15
17
  for(const key of ['exportRow','validateStaged']) insist(result[key]===undefined || typeof result[key]==='function','invalid_policy_'+key);
16
18
  insist(Number.isSafeInteger(result.partBytes) && result.partBytes>=1024 && result.partBytes<=16*1024*1024,'invalid_part_limit');
17
19
  for(const [table,columns] of Object.entries(result.secretColumns)) insist(name(table) && names(columns),'invalid_secret_columns');
@@ -25,17 +27,14 @@ export function policy(input) {
25
27
  for(const key of ['secretColumns','acceptedSchemas','buckets','extraPayloads'])result[key]=Object.assign(Object.create(null),result[key]);
26
28
  return {...result,excludeTables:[...excludedTables,...result.excludeTables]};
27
29
  }
28
- const identifier=value=>value.replace(/[A-Z]/g,letter=>letter.toLowerCase());
29
- const matches=(table,pattern)=>pattern.endsWith('%') ? identifier(table).startsWith(identifier(pattern.slice(0,-1))) : identifier(table)===identifier(pattern);
30
- /** True when no archive carries `table`: one of Base's `excludedTables`, or one of
31
- * the policy's own `excludeTables`, unless the policy includes it explicitly. */
32
- export const excludedTable=(table,input={})=>!(input.includeTables??[]).includes(table) && [...excludedTables,...(input.excludeTables??[])].some(pattern=>matches(table,pattern));
30
+ /** Platform tables are always excluded; explicit includes override only optional exclusions. */
31
+ export const excludedTable=(table,input={})=>platformTable(table) || (!(input.includeTables??[]).includes(table) && [...excludedTables,...(input.excludeTables??[])].some(pattern=>matches(table,pattern)));
33
32
  async function archived(db,config) {
34
33
  const objects=await all(db,"SELECT name,sql,type,tbl_name FROM sqlite_master WHERE sql IS NOT NULL ORDER BY name");
35
34
  const kinds=await all(db,'PRAGMA table_list');
36
35
  const derived=config.derivedTables;
37
- const excluded=objects.filter(x=>x.type==='table' && !config.includeTables.includes(x.name) &&
38
- (config.excludeTables.some(p=>matches(x.name,p)) || derived.some(p=>x.name===p || (kinds.find(k=>k.name===x.name)?.type==='shadow' && x.name.startsWith(p+'_')))));
36
+ const excluded=objects.filter(x=>x.type==='table' && (excludedTable(x.name,config) || (!config.includeTables.includes(x.name) &&
37
+ derived.some(p=>x.name===p || (kinds.find(k=>k.name===x.name)?.type==='shadow' && x.name.startsWith(p+'_'))))));
39
38
  objects.sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0);
40
39
  return {objects,kinds,excluded,entries:objects.filter(x=>x.type==='table' && !excluded.some(y=>y.name===x.name))};
41
40
  }
@@ -4,6 +4,7 @@ import { Readable } from 'node:stream';
4
4
  import { pathToFileURL, fileURLToPath } from 'node:url';
5
5
  import { options, cookieFile, absent, privateFile, checkpoint, promote } from './cli-options.mjs';
6
6
  import { readArchive } from './format.mjs';
7
+ import { skippedTablesLine } from './bookkeeping.mjs';
7
8
  import { canonicalJson } from './hash.mjs';
8
9
  import { transferClient, transferDiagnostic } from './http-client.mjs';
9
10
  export async function main(args) {
@@ -37,6 +38,7 @@ export async function main(args) {
37
38
  else closing=record;
38
39
  }
39
40
  const result=await get('imports/'+id+'/finalize','POST',{contentHash:closing.contentHash,archiveHash:closing.archiveHash});
41
+ if(result.skippedTables?.length)process.stdout.write(skippedTablesLine(result.skippedTables)+'\n');
40
42
  process.stdout.write('Import '+result.phase+'.\nRequired configuration: '+result.requiredConfiguration.join(', ')+'\n');return;
41
43
  }
42
44
  let collection='exports';
@@ -69,7 +69,11 @@ export async function importArchive(service, path, transient, journal, progress)
69
69
  if (file === journal && record.kind === 'manifest') later = { sourceIdentity: record.sourceIdentity, epoch: record.epoch, journal: record.journal };
70
70
  }
71
71
  for await (const record of fileRecords(path)) {
72
- if (record.kind === 'manifest') { manifest = record; id = await service.imports.create(manifest); }
72
+ if (record.kind === 'manifest') {
73
+ manifest = record; id = await service.imports.create(manifest);
74
+ const { skippedTables } = await service.imports.status(id);
75
+ if (skippedTables?.length) progress?.({ phase: 'skipped', tables: skippedTables });
76
+ }
73
77
  else if (record.kind === 'part') {
74
78
  await service.imports.uploadPart(id, record.index, record);
75
79
  staged += Buffer.byteLength(canonicalJson(record)) + 1;
@@ -79,6 +83,6 @@ export async function importArchive(service, path, transient, journal, progress)
79
83
  }
80
84
  progress?.({ phase: 'finishing', total: manifest.partCount });
81
85
  const status = await service.imports.finalize(id, { contentHash: closing.contentHash, archiveHash: closing.archiveHash, ...(later ? { laterJournal: later } : {}) }); complete = true;
82
- return { ...receipt(manifest, closing, transient), ...(status.bridged ? { bridged: status.bridged } : {}) };
86
+ return { ...receipt(manifest, closing, transient), ...(status.bridged ? { bridged: status.bridged } : {}), ...(status.skippedTables ? { skippedTables: status.skippedTables } : {}) };
83
87
  } finally { if (id && !complete) await service.imports.abort(id); }
84
88
  }
@@ -3,6 +3,7 @@ import { stagePart } from './import-staging.mjs';
3
3
  import { refuseProviderData } from './provider-data.mjs';
4
4
  import { refuseDevData } from './dev-data.mjs';
5
5
  import { catalogue, validateRow, bindCell, writableColumns } from './catalogue.mjs';
6
+ import { platformTable, restorableManifest } from './bookkeeping.mjs';
6
7
  import { canonicalJson, unbase64 } from './hash.mjs';
7
8
  import { checkManifest, checkPart, ContentVerifier, ArchiveVerifier } from './format.mjs';
8
9
  import { fence, mergeJournal, tombstone } from './journal.mjs';
@@ -16,7 +17,9 @@ export async function createImport(context,manifest,actor='direct',legacyRecover
16
17
  insist(manifest.product===config.product,'wrong_product');
17
18
  // Explicit schema upgrades can reconcile rows, but cannot attest an interrupted deployment.
18
19
  await appliedMigrations(db);await state(db);
19
- const cat=await catalogue(db,config),upgrade=config.acceptedSchemas[manifest.schema];
20
+ const original=manifest;manifest=await restorableManifest(original);
21
+ const skippedTables=original.tables.filter(table=>platformTable(table.name)).map(table=>table.name);
22
+ const cat=await catalogue(db,config),upgrade=config.acceptedSchemas[original.schema];
20
23
  const same=manifest.schema===cat.identity;
21
24
  const bridge=same || upgrade?undefined:await additiveBridge(db,manifest,cat,context.migrations);
22
25
  if(same && !upgrade)await sameSchemaMigrations(db,manifest,cat,context.migrations);
@@ -33,7 +36,7 @@ export async function createImport(context,manifest,actor='direct',legacyRecover
33
36
  for(const o of manifest.objects) insist(buckets[o.bucket] && config.buckets[o.bucket] && o.key.startsWith(config.buckets[o.bucket].prefix??''),'bucket_inventory');
34
37
  insist(canonicalJson(manifest.payloads.map(x=>x.name))===canonicalJson(Object.keys(config.extraPayloads).sort()),'payload_inventory');
35
38
  const id=crypto.randomUUID(),copies=Object.fromEntries(targets.map((t,i)=>[t.name,'rer_portability_stage_'+id.replaceAll('-','')+'_'+i]));
36
- const row={id,kind:'import',actor,phase:'staging',completed:0,metadata:{manifest,copies,targets,triggers:cat.triggers,...(bridge?{bridge}:{}),...(legacyRecovery?{legacyRecovery}: {})}};
39
+ const row={id,kind:'import',actor,phase:'staging',completed:0,metadata:{manifest:original,...(skippedTables.length?{restoreManifest:manifest,skippedTables}:{}),copies,targets,triggers:cat.triggers,...(bridge?{bridge}:{}),...(legacyRecovery?{legacyRecovery}: {})}};
37
40
  try {
38
41
  await db.batch([guard(db,'(SELECT import_job FROM rer_portability_state WHERE id=1) IS NULL'),
39
42
  statement(db,'UPDATE rer_portability_state SET import_job=? WHERE id=1',id),
@@ -52,6 +55,7 @@ export async function uploadPart(context,id,index,part) {
52
55
  if(item.kind==='row') {
53
56
  const table=manifest.tables.find(x=>x.name===item.table);insist(table && Number.isSafeInteger(item.index) && item.index>=0 && item.index<table.count,'row_inventory');
54
57
  validateRow(table,item.row,manifest.excludedColumns[table.name]??[]);
58
+ if(platformTable(table.name))continue;
55
59
  const target=row.metadata.targets.find(x=>x.name===table.name);
56
60
  const data=upgrade?upgrade.upgradeRow(table.name,structuredClone(item.row)):item.row;
57
61
  insist(!(data instanceof Promise),'upgrade_row_must_be_pure');validateRow(target,data,config.secretColumns[table.name]??[]);
@@ -147,7 +151,7 @@ export async function finalizeImport(context,id,{contentHash,archiveHash,laterJo
147
151
  }
148
152
  const digest=verifier.digest();if(contentHash!==undefined)insist(contentHash===digest,'content_checksum');
149
153
  insist(archiveHash===archive.digest(),'archive_checksum',409);
150
- const checked=await fence(db,manifest,row.metadata.copies,laterJournal);
154
+ const checked=await fence(db,row.metadata.restoreManifest??manifest,row.metadata.copies,laterJournal);
151
155
  if(row.metadata.legacyRecovery)await requireLegacyEmpty(context,row.metadata.legacyRecovery);
152
156
  const {seeded,replaced}=await destinationState(context,row);
153
157
  const dependentGuards=await excludedDependentGuards(db,row.metadata.targets,replaced);
@@ -189,7 +193,7 @@ export async function finalizeImport(context,id,{contentHash,archiveHash,laterJo
189
193
  }
190
194
  export async function importStatus(context,id) {
191
195
  const row=await job(context.db,id,'import');return {id,kind:'import',phase:row.phase,completed:row.completed,total:row.metadata.manifest.partCount,
192
- contentHash:row.metadata.contentHash??null,requiredConfiguration:row.phase==='complete'?row.metadata.manifest.requiredConfiguration:[],...(row.metadata.bridge?{bridged:row.metadata.bridge}:{})};
196
+ contentHash:row.metadata.contentHash??null,requiredConfiguration:row.phase==='complete'?row.metadata.manifest.requiredConfiguration:[],...(row.metadata.bridge?{bridged:row.metadata.bridge}:{}),...(row.metadata.skippedTables?{skippedTables:row.metadata.skippedTables}:{})};
193
197
  }
194
198
  export async function abortImport(context,id) {
195
199
  const row=await job(context.db,id,'import');insist(row.phase!=='complete','import_complete',409);
@@ -28,7 +28,7 @@ export interface ArchivePolicy {
28
28
  extraPayloads?: Record<string,{produce:()=>Uint8Array|ReadableStream<Uint8Array>|Promise<Uint8Array|ReadableStream<Uint8Array>>;consume:(source:ReadableStream<Uint8Array>,descriptor:PayloadDescriptor)=>void|Promise<void>}>;
29
29
  partBytes?: number;
30
30
  }
31
- export interface Status {id:string;kind:'export'|'import';phase:'building'|'staging'|'applying'|'complete'|'aborted';completed:number;total:number|null;/** Export only: bytes of the parts built so far. */bytes?:number;contentHash:string|null;requiredConfiguration?:string[];bridged?:Bridge}
31
+ export interface Status {id:string;kind:'export'|'import';phase:'building'|'staging'|'applying'|'complete'|'aborted';completed:number;total:number|null;/** Export only: bytes of the parts built so far. */bytes?:number;contentHash:string|null;requiredConfiguration?:string[];bridged?:Bridge;/** Platform bookkeeping ignored in an older archive. */skippedTables?:string[]}
32
32
  /** Later additive migrations an older archive was restored across. */
33
33
  export interface Bridge {fromSchema:string;toSchema:string;migrations:string[];tables:string[];columns:Record<string,string[]>}
34
34
  /** A runner's replay of the destination's applied migrations: the archive schema identity after a chosen set, and each migration's statements. */
@@ -54,7 +54,7 @@ export function makePart(index:number,items:Item[]):Promise<Part>;
54
54
  export function canonicalJson(value:unknown):string;
55
55
  export function sha256(value:string|Uint8Array):Promise<string>;
56
56
  export const MAX_LINE_BYTES:number;
57
- /** Tables no archive carries (exact names, or prefixes ending in `%`). */
57
+ /** Default exclusions (exact names, or prefixes ending in `%`); identity tables may be included. */
58
58
  export const excludedTables:readonly string[];
59
59
  /** True when no archive under this policy carries `table`. */
60
60
  export function excludedTable(table:string,policy?:Pick<ArchivePolicy,'excludeTables'|'includeTables'>):boolean;
@@ -1,3 +1,4 @@
1
+ import { skippedTablesLine } from './bookkeeping.mjs';
1
2
  // Human progress for a long export or import. The caller sends events; this turns
2
3
  // them into at most one line every few seconds, with an estimate of the time left
3
4
  // once a phase has two samples. The first and last line of every phase always show.
@@ -38,6 +39,7 @@ export function transferProgress(report, { interval = 3000, now = () => performa
38
39
  }
39
40
  };
40
41
  return event => {
42
+ if (event.phase === 'skipped') { report(skippedTablesLine(event.tables)); return; }
41
43
  if (event.phase === 'start') {
42
44
  const noun = event.direction === 'export' ? `Exporting about ${formatBytes(event.bytes)} of local data` : `Restoring a ${formatBytes(event.bytes)} archive`;
43
45
  if (event.direction === 'export') expected = event.bytes;
@@ -0,0 +1,8 @@
1
+ export function readIconFiles(publicDirectory: string): Promise<{
2
+ links: string;
3
+ files: Map<string, { bytes: Uint8Array; type: string }>;
4
+ }>;
5
+ export function seedIcons(): {
6
+ name: string;
7
+ config(config: { root?: string; publicDir?: string | false }): Promise<{ define: Record<string, string> }>;
8
+ };
@@ -0,0 +1,49 @@
1
+ import { lstat, readFile } from 'node:fs/promises';
2
+ import { join, resolve } from 'node:path';
3
+
4
+ // Prefer the seed's small artwork, including the names shipped under brand/.
5
+ const small = ['favicon-32.svg', 'favicon.svg', 'icon.svg', 'favicon-32.png', 'favicon-32x32.png', 'favicon.png', 'icon-32.png', 'icon.png'];
6
+ const candidates = ['favicon.ico', 'brand/favicon.ico', ...small.flatMap(name => [name, `brand/${name}`]), 'apple-touch-icon.png', 'brand/apple-touch-icon.png', 'brand/mark.svg'];
7
+ const type = path => path.endsWith('.svg') ? 'image/svg+xml' : path.endsWith('.ico') ? 'image/x-icon' : 'image/png';
8
+
9
+ /** Read once at build/installer start. Missing files never become browser probes. */
10
+ export async function readIconFiles(publicDirectory) {
11
+ const files = new Map();
12
+ for (const path of candidates) {
13
+ try {
14
+ // Do not export links outside public/ through a symbolic directory or file.
15
+ const directory = await lstat(publicDirectory);
16
+ if (!directory.isDirectory() || directory.isSymbolicLink()) throw Error('The public icon directory must be a regular directory.');
17
+ if (path.startsWith('brand/')) {
18
+ const brand = await lstat(join(publicDirectory, 'brand'));
19
+ if (!brand.isDirectory() || brand.isSymbolicLink()) throw Error('The brand icon directory must be a regular directory.');
20
+ }
21
+ const stat = await lstat(join(publicDirectory, path));
22
+ if (!stat.isFile() || stat.isSymbolicLink()) throw Error(`Icon ${path} must be a regular file.`);
23
+ const bytes = await readFile(join(publicDirectory, path));
24
+ if (path.endsWith('.png') && !path.includes('apple-touch-icon')) {
25
+ if (bytes.length < 24 || bytes.subarray(0, 8).toString('hex') !== '89504e470d0a1a0a' || bytes.readUInt32BE(16) !== 32 || bytes.readUInt32BE(20) !== 32) continue;
26
+ }
27
+ files.set('/' + path, { bytes, type: type(path) });
28
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
29
+ }
30
+ const ico = ['favicon.ico', 'brand/favicon.ico'].find(path => files.has('/' + path));
31
+ const favicon = small.flatMap(name => [name, `brand/${name}`]).find(path => files.has('/' + path));
32
+ const apple = ['apple-touch-icon.png', 'brand/apple-touch-icon.png'].find(path => files.has('/' + path));
33
+ const selected = [ico, favicon, apple].filter(Boolean);
34
+ if (!selected.length && files.has('/brand/mark.svg')) selected.push('brand/mark.svg');
35
+ const links = selected.map(path => `<link rel="${path.includes('apple-touch-icon') ? 'apple-touch-icon' : 'icon'}" href="/${path}"${path.includes('apple-touch-icon') ? '' : ` type="${type(path)}" sizes="${path.endsWith('.png') ? '32x32' : 'any'}"`}>`).join('');
36
+ return { links, files: new Map(selected.map(path => ['/' + path, files.get('/' + path)])) };
37
+ }
38
+
39
+ /** Freeze the existing public icons into every shared server-rendered head. */
40
+ export function seedIcons() {
41
+ return {
42
+ name: 'rer:seed-icons',
43
+ async config(config) {
44
+ const publicDirectory = config.publicDir === false ? null : resolve(config.root ?? process.cwd(), config.publicDir ?? 'public');
45
+ const icons = publicDirectory ? await readIconFiles(publicDirectory) : { links: '' };
46
+ return { define: { __RER_ICON_HEAD__: JSON.stringify(icons.links) } };
47
+ },
48
+ };
49
+ }
@@ -1,3 +1,4 @@
1
+ import { readIconFiles } from './icon-files.mjs';
1
2
  import { loadInstallerSeed } from './setup-manifest.mjs';
2
3
  import { readSettings } from './adapter-settings.mjs';
3
4
  import { createAppProcesses } from './app-processes.mjs';
@@ -27,6 +28,7 @@ export async function startInstaller(root,{seed,port=0,answers,secretInput,noPre
27
28
  const accent=seed.branding?.accent;
28
29
  const accentStyle=/^#[0-9a-f]{6}$/i.test(accent||'')?`<style>:root{--installer-accent:${accent};--installer-accent-text:${[1,3,5].map((start,i)=>parseInt(accent.slice(start,start+2),16)*[.299,.587,.114][i]).reduce((a,b)=>a+b,0)>150?'#173753':'#ffffff'}}</style>`:'';
29
30
  const theme=seed.theme?await loadSeedTheme(root,seed.theme):null;
31
+ const icons=await readIconFiles(join(root,'public'));
30
32
  const uiRoot=fileURLToPath(new URL('./ui/',import.meta.url));
31
33
  if(resume&&noPrefill)throw Error('--resume cannot be combined with --no-prefill.');
32
34
  const store=await createState(root,seed),token=randomBytes(32).toString('hex'),cookie=randomBytes(32).toString('hex');let origin,work,connection,starting=false,mutations=0;const apps=createAppProcesses();const abort=new AbortController();let attemptAbort,attemptProcesses;
@@ -175,11 +177,13 @@ export async function startInstaller(root,{seed,port=0,answers,secretInput,noPre
175
177
  if(req.method==='GET'&&path==='/rer-setup.json'){res.writeHead(200,{'Content-Type':'application/json'});res.end(seed.manifestBytes);return;}
176
178
  if(req.method==='GET'&&path==='/SETUP.schema.json'){res.writeHead(200,{'Content-Type':'application/json'});res.end(seed.schemaBytes);return;}
177
179
  if(req.method==='GET'&&path==='/model-options.json'){json(200,seed.modelOptions);return;}
180
+ const iconFile=req.method==='GET'&&icons.files.get(path);
181
+ if(iconFile){res.writeHead(200,{'Content-Type':iconFile.type});res.end(iconFile.bytes);return;}
178
182
  const themeFile=req.method==='GET'&&theme?.files.get(path);
179
183
  if(themeFile){res.writeHead(200,{'Content-Type':themeFile.type});res.end(themeFile.bytes);return;}
180
184
  if(req.method!=='GET'||!assets[path]||(path==='/theme.css'&&!theme))return json(404,{error:'Not found.'});
181
185
  const [file,type]=assets[path];let content=await readFile(file?(path==='/seed.mjs'?join(root,file):join(uiRoot,file)):join(root,seed.background));
182
- if(path==='/'){content=content.toString().replaceAll('{{product}}',String(seed.product).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))).replace('</head>',`${accentStyle}<meta name="installer-token" content="${token}"></head>`);if(theme)content=content.replace('<html lang="en">','<html lang="en" class="rer-themed">').replace('<link rel="stylesheet" href="/style.css">','<link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/rer-theme.css"><link rel="stylesheet" href="/theme.css">');res.setHeader('Set-Cookie',`rer_installer=${cookie}; Path=/; HttpOnly; SameSite=Strict`);res.setHeader('Content-Security-Policy',"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self'; frame-ancestors 'none'; base-uri 'none'")}
186
+ if(path==='/'){content=content.toString().replaceAll('{{product}}',String(seed.product).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))).replace('</head>',`${icons.links}${accentStyle}<meta name="installer-token" content="${token}"></head>`);if(theme)content=content.replace('<html lang="en">','<html lang="en" class="rer-themed">').replace('<link rel="stylesheet" href="/style.css">','<link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/rer-theme.css"><link rel="stylesheet" href="/theme.css">');res.setHeader('Set-Cookie',`rer_installer=${cookie}; Path=/; HttpOnly; SameSite=Strict`);res.setHeader('Content-Security-Policy',"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self'; frame-ancestors 'none'; base-uri 'none'")}
183
187
  res.writeHead(200,{'Content-Type':type});res.end(content);
184
188
  }catch{json(500,{error:'The installer could not complete this request.'})}finally{if(mutation)mutations--;}
185
189
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.59",
3
+ "version": "0.2.61",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -42,6 +42,10 @@
42
42
  "./production-runtime": "./onboarding/production-runtime.mjs",
43
43
  "./production-modules": "./onboarding/production-modules.mjs",
44
44
  "./queued-entry": "./onboarding/queued-entry.mjs",
45
+ "./seed-icons": {
46
+ "types": "./onboarding/icon-files.d.mts",
47
+ "default": "./onboarding/icon-files.mjs"
48
+ },
45
49
  "./archive-output": {
46
50
  "types": "./onboarding/archive-output.d.mts",
47
51
  "default": "./onboarding/archive-output.mjs"