@runeditrun/rer 0.2.79 → 0.2.80

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 (113) hide show
  1. package/README.md +17 -3
  2. package/cli/README.md +25 -13
  3. package/cli/authoring.mjs +14 -0
  4. package/cli/contract.mjs +25 -5
  5. package/cli/demo-host.mjs +4 -2
  6. package/cli/dev-identity.mjs +2 -2
  7. package/cli/export.mjs +1 -1
  8. package/cli/inspect.mjs +38 -2
  9. package/cli/main.mjs +8 -2
  10. package/cli/managed-server.mjs +1 -1
  11. package/cli/parse.mjs +7 -6
  12. package/cli/portability-worker.mjs +2 -1
  13. package/cli/portability.mjs +6 -2
  14. package/cli/production-auth.mjs +2 -1
  15. package/cli/production-mail.mjs +36 -9
  16. package/cli/project.mjs +5 -14
  17. package/cli/release.mjs +2 -1
  18. package/cli/site-preview.mjs +4 -1
  19. package/cli/site.mjs +3 -2
  20. package/edition-authoring/adopt.mjs +39 -0
  21. package/edition-authoring/base-acknowledgements.mjs +24 -0
  22. package/edition-authoring/base-copies.mjs +418 -0
  23. package/edition-authoring/cli.mjs +85 -0
  24. package/edition-authoring/copy-checkout.mjs +69 -0
  25. package/edition-authoring/files.mjs +15 -2
  26. package/edition-authoring/lock.mjs +48 -0
  27. package/edition-authoring/offline-git.mjs +28 -0
  28. package/edition-authoring/parent-comparison.mjs +77 -0
  29. package/edition-authoring/projection-lock.mjs +38 -0
  30. package/edition-authoring/release.mjs +48 -0
  31. package/edition-authoring/sources.mjs +114 -0
  32. package/edition-authoring/updates.mjs +105 -0
  33. package/global/CHANGELOG.md +12 -0
  34. package/global/README.md +17 -3
  35. package/global/cli/install.mjs +3 -1
  36. package/global/main.mjs +9 -12
  37. package/modules/container/build.mjs +1 -1
  38. package/modules/d1-transport/index.mjs +68 -21
  39. package/modules/demo/README.md +8 -2
  40. package/modules/demo/declaration.mjs +21 -0
  41. package/modules/demo/input-path.mjs +18 -0
  42. package/modules/demo/label.d.mts +1 -1
  43. package/modules/demo/label.mjs +10 -5
  44. package/modules/demo/navigation.mjs +32 -0
  45. package/modules/demo/run-url.mjs +9 -0
  46. package/modules/demo/vite.d.mts +7 -2
  47. package/modules/demo/vite.mjs +17 -2
  48. package/modules/demo-host/README.md +5 -3
  49. package/modules/demo-host/page-style.mjs +2 -2
  50. package/modules/demo-host/pages.mjs +3 -3
  51. package/modules/demo-host/plan.mjs +6 -4
  52. package/modules/demo-host/theme.mjs +5 -2
  53. package/modules/deploy-kit/README.md +19 -15
  54. package/modules/deploy-kit/owner-cli.mjs +1 -1
  55. package/modules/deploy-kit/readiness-window.mjs +3 -3
  56. package/modules/erasure/README.md +10 -5
  57. package/modules/import-kit/src/d1/README.md +15 -9
  58. package/modules/import-kit/src/d1/apply.ts +10 -6
  59. package/modules/import-kit/src/d1/atomic-prefix.ts +64 -0
  60. package/modules/import-kit/src/d1/budget.ts +48 -26
  61. package/modules/import-kit/src/d1/compressed-plan.ts +9 -2
  62. package/modules/import-kit/src/d1/database.ts +2 -1
  63. package/modules/import-kit/src/d1/jobs.ts +2 -1
  64. package/modules/import-kit/src/d1/plans.ts +4 -2
  65. package/modules/import-kit/src/d1/verified-plan.ts +63 -0
  66. package/modules/integrations/core/README.md +2 -2
  67. package/modules/mail/README.md +4 -3
  68. package/modules/mail/pnpm-lock.yaml +16 -0
  69. package/modules/operator-auth/accounts/native.mjs +3 -1
  70. package/modules/operator-auth/accounts/provider-control.mjs +7 -4
  71. package/modules/operator-auth/accounts/provider-setup.mjs +34 -0
  72. package/modules/operator-auth/accounts/settings-page.mjs +13 -4
  73. package/modules/operator-auth/conformance/README.md +1 -1
  74. package/modules/operator-auth/dev/index.mjs +22 -4
  75. package/modules/operator-auth/dev/refusal.mjs +19 -0
  76. package/modules/operator-auth/docs/README.md +6 -5
  77. package/modules/operator-auth/docs/tanstack-start.md +1 -1
  78. package/modules/operator-auth/docs/vite-spa.md +5 -6
  79. package/modules/operator-auth/index.d.mts +1 -1
  80. package/modules/operator-auth/page.mjs +14 -0
  81. package/modules/operator-auth/representation.mjs +83 -0
  82. package/modules/operator-auth/routes.mjs +25 -2
  83. package/modules/portability/README.md +91 -14
  84. package/modules/portability/bookkeeping.mjs +3 -3
  85. package/modules/portability/bridge.mjs +5 -4
  86. package/modules/portability/catalogue.mjs +12 -8
  87. package/modules/portability/cli.mjs +5 -1
  88. package/modules/portability/export.mjs +5 -11
  89. package/modules/portability/format.mjs +7 -1
  90. package/modules/portability/http-errors.mjs +51 -0
  91. package/modules/portability/http.mjs +4 -1
  92. package/modules/portability/import-lease.mjs +13 -2
  93. package/modules/portability/import.mjs +10 -0
  94. package/modules/portability/index.d.mts +3 -0
  95. package/modules/portability/references.mjs +20 -0
  96. package/modules/portability/schema-identity.mjs +13 -0
  97. package/modules/portability/schema-legacy.mjs +21 -0
  98. package/modules/portability/sqlite-tokens.mjs +121 -0
  99. package/modules/release/README.md +20 -9
  100. package/modules/release/github-verify.mjs +30 -9
  101. package/modules/site/docs-search/search.css +1 -1
  102. package/onboarding/README.md +16 -4
  103. package/onboarding/adapter.mjs +5 -1
  104. package/onboarding/schema/SETUP.schema.json +26 -1
  105. package/onboarding/schema/business-field-inputs.mjs +37 -0
  106. package/onboarding/schema/json-schema.mjs +6 -2
  107. package/onboarding/schema/setup-validation.mjs +20 -3
  108. package/onboarding/server.mjs +1 -1
  109. package/onboarding/setup-manifest.mjs +2 -0
  110. package/onboarding/start-origin-diagnostic.mjs +24 -0
  111. package/onboarding/ui/style.css +9 -9
  112. package/package.json +1 -1
  113. package/scripts/publish-check/README.md +1 -1
@@ -1,6 +1,7 @@
1
1
  import { createPortability } from './index.mjs';
2
2
  import { insist, PortabilityError } from './storage.mjs';
3
3
  import { MAX_LINE_BYTES } from './format.mjs';
4
+ import { httpFailure } from './http-errors.mjs';
4
5
  export async function boundedJson(request,limit) {
5
6
  const reader=request.body?.getReader();if(!reader)return {};
6
7
  const chunks=[];let size=0;
@@ -19,10 +20,12 @@ export async function createPortabilityHandler({db,buckets,policy,appOrigin,base
19
20
  if(url.pathname!==basePath && !url.pathname.startsWith(basePath+'/'))return null;
20
21
  const route=url.pathname.slice(basePath.length+1).split('/'),[collection,id,action,index]=route;
21
22
  const operation=collection==='exports'?'export':collection==='imports'?'import':'unknown';
23
+ let authorizedActor=null;
22
24
  try {
23
25
  const actor=await authorize(request,{operation,jobId:id??null});insist(typeof actor==='string' && actor.length>0,'unauthorized',401);
24
26
  if(!['GET','HEAD'].includes(request.method))insist(request.headers.get('Origin')===appOrigin,'origin_refused',403);
25
27
  if(id)insist(await service.actor(id)===actor,'job_not_found',404);
28
+ authorizedActor=actor;
26
29
  insist(['exports','imports'].includes(collection) && route.length<=4,'route_not_found',404);
27
30
  const api=service[collection];
28
31
  if(collection==='imports' && request.method==='GET' && !id)return json({active:await api.active(actor)});
@@ -38,6 +41,6 @@ export async function createPortabilityHandler({db,buckets,policy,appOrigin,base
38
41
  if(collection==='imports' && request.method==='PUT' && id && action==='parts' && /^(0|[1-9]\d*)$/.test(index??''))return json(await api.uploadPart(id,Number(index),await boundedJson(request,maxBodyBytes)));
39
42
  if(collection==='imports' && request.method==='POST' && id && action==='finalize' && !index)return json(await api.finalize(id,await boundedJson(request,maxBodyBytes)));
40
43
  throw new PortabilityError('route_not_found',404);
41
- }catch(e){return json({error:e instanceof PortabilityError?e.code:'operation_failed',...(e instanceof PortabilityError && e.code==='import_running'?{jobId:e.jobId,abortableAt:e.abortableAt}:{})},e instanceof PortabilityError?e.status:500);}
44
+ }catch(e){const failure=httpFailure(e,{actor:authorizedActor});return json(failure.body,failure.status);}
42
45
  };
43
46
  }
@@ -6,6 +6,13 @@ import { statement, guard, job, PortabilityError } from './storage.mjs';
6
6
  export const IMPORT_LEASE_MS=5*60*1000;
7
7
  const RENEW_MS=30*1000;
8
8
  const active=row=>['staging','applying'].includes(row.phase);
9
+ const runningMetadata=new WeakMap();
10
+ // Only the lease constructor can approve these details. Mutable Error fields,
11
+ // prototypes and diagnostic code suffixes cannot establish that provenance.
12
+ export const importRunningMetadata=(error,actor)=>{
13
+ const running=runningMetadata.get(error);
14
+ return typeof actor==='string' && actor===running?.actor?running.details:undefined;
15
+ };
9
16
 
10
17
  // Private transfer bookkeeping can be added to already-installed destinations
11
18
  // without changing product migrations or the archive's schema identity. Keep
@@ -27,8 +34,12 @@ export async function importLeaseStatus(db,row) {
27
34
  return {abortableAt:active(row)&&lease?new Date(lease.expires_at).toISOString():null,stale:active(row)&&!!lease&&lease.expires_at<=Date.now()};
28
35
  }
29
36
  export async function importRunning(db,id) {
30
- const error=new PortabilityError('import_running',409);
31
- error.jobId=id;error.abortableAt=(await importLeaseStatus(db,await job(db,id,'import'))).abortableAt;
37
+ const error=new PortabilityError('import_running',409),row=await job(db,id,'import');
38
+ error.jobId=id;error.abortableAt=(await importLeaseStatus(db,row)).abortableAt;
39
+ if(typeof id==='string' && id.length>0 && id.length<=100 && !/[^a-zA-Z0-9-]/.test(id)
40
+ && (error.abortableAt===null || typeof error.abortableAt==='string' && Number.isFinite(Date.parse(error.abortableAt))
41
+ && new Date(error.abortableAt).toISOString()===error.abortableAt))
42
+ runningMetadata.set(error,Object.freeze({actor:row.actor,details:Object.freeze({jobId:id,abortableAt:error.abortableAt})}));
32
43
  return error;
33
44
  }
34
45
 
@@ -17,6 +17,7 @@ import { additiveBridge, sameSchemaMigrations, appliedMigrations } from './bridg
17
17
  import { replayStatements } from './backfills.mjs';
18
18
  import { checkArchivedLedgers, archivedHistory } from './ledgers.mjs';
19
19
  import { legacyEmptyGuards, legacyAuditStatements, requireLegacyEmpty } from './legacy-safety.mjs';
20
+ import { checkReferences } from './references.mjs';
20
21
  // ledgers: the rows of each migration ledger table the archive carries, as the
21
22
  // caller read them from it ({table:rows}); uploadPart binds them to its parts.
22
23
  export async function createImport(context,manifest,actor='direct',legacyRecovery,ledgers) {
@@ -27,8 +28,15 @@ export async function createImport(context,manifest,actor='direct',legacyRecover
27
28
  const original=manifest;manifest=await restorableManifest(original);
28
29
  const skippedTables=original.tables.filter(table=>platformTable(table.name)).map(table=>table.name);
29
30
  const cat=await catalogue(db,config),upgrade=config.acceptedSchemas[original.schema];
31
+ // Table SQL and migration names cannot establish missing trigger/view/index
32
+ // definitions. Never infer that an old archive's absent inventory is empty.
33
+ insist(manifest.schemaObjects!==undefined || legacyRecovery,'schema_mismatch:legacy_schema',409);
30
34
  const same=manifest.schema===cat.identity,history=()=>archivedHistory(original,ledgers);
31
35
  const {replays,...bridge}=upgrade?{}:same?(await sameSchemaMigrations(db,manifest,cat,context.migrations,history)??{}):await additiveBridge(db,manifest,cat,context.migrations,history);
36
+ // Finalize checks object references on the staged rows; a later migration
37
+ // replayed into a reference table would publish rows that check never saw.
38
+ const referenced=replays?.find(r=>Object.values(config.buckets).some(spec=>spec.objectReferences?.table===r.table));
39
+ insist(!referenced,'schema_mismatch:migration_data:'+referenced?.migration);
32
40
  if(!bridge.fromSchema)insist(canonicalJson(manifest.tables.map(x=>x.name))===canonicalJson(cat.tables.map(x=>x.name)),'table_inventory');
33
41
  if(!upgrade && !bridge.fromSchema)for(const table of manifest.tables) {
34
42
  const target=cat.tables.find(t=>t.name===table.name);
@@ -181,6 +189,8 @@ async function finalizeLeasedImport(context,id,{contentHash,archiveHash,laterJou
181
189
  await refusePolicyApprovals(db,row.metadata.copies);
182
190
  await normalizeStaged(context,row);
183
191
  await refusePolicyApprovals(db,row.metadata.copies);
192
+ // The rows publication restores may name only this archive's objects, in their namespace.
193
+ await checkReferences(context,row.metadata.copies,manifest.objects);
184
194
  if(config.validateStaged) {
185
195
  const read=async table=>{insist(row.metadata.copies[table],'staged_table:'+table);const target=row.metadata.targets.find(t=>t.name===table);return (await readCopy(db,target,row.metadata.copies[table],0,row.metadata.manifest.tables.find(t=>t.name===table)?.count??0)).map(x=>x.row);};
186
196
  insist(await config.validateStaged({db,tables:{...row.metadata.copies},read,manifest})!==false,'staged_validation');
@@ -2,11 +2,14 @@ export type Cell = null | string | number | { blob: string };
2
2
  export type Row = Record<string, Cell>;
3
3
  export interface Column { name: string; type: string; notnull: number; pk: number; generated?: 'virtual'|'stored' }
4
4
  export interface Table { name: string; sql: string; columns: Column[]; dependencies: string[]; count: number; rowidAlias: string|null }
5
+ export interface SchemaObject { name: string; type: 'index'|'view'|'trigger'; table: string; sql: string }
5
6
  export interface ObjectDescriptor { bucket: string; key: string; size: number; sha256: string; httpMetadata: Omit<R2HTTPMetadata,'cacheExpiry'> & {cacheExpiry?:string}; customMetadata: Record<string,string> }
6
7
  export interface PayloadDescriptor { name: string; size: number; sha256: string }
7
8
  export interface Manifest {
8
9
  kind: 'manifest'; format: 'runeditrun-portability'; version: 2; product: string; exportedAt: string; sourceIdentity: string;
9
10
  schema: string; tables: Table[]; objects: ObjectDescriptor[]; payloads: PayloadDescriptor[];
11
+ /** Complete behavioral object definitions; absent from older table-only archives. */
12
+ schemaObjects?: SchemaObject[];
10
13
  excludedTables: string[]; excludedColumns: Record<string,string[]>; requiredConfiguration: string[]; partCount: number; epoch: number; journal: string[];
11
14
  /** Applied product migrations; absent from archives made before additive restore. */
12
15
  migrations?: string[];
@@ -0,0 +1,20 @@
1
+ import { all, quote, insist } from './storage.mjs';
2
+ // A referenced key stays in its bucket's namespace however a reader joins or
3
+ // resolves it: nonempty, under the declared prefix, not absolute and with no
4
+ // '.' or '..' segment.
5
+ const namespaced=(prefix,key)=>typeof key==='string' && key!=='' && key.startsWith(prefix) && !/^[\\/]/.test(key) && !key.split(/[\\/]/).some(part=>part==='.' || part==='..');
6
+ // Export checks its snapshot and restore its staged rows, before any object
7
+ // write: for every bucket that declares references, the distinct referenced keys
8
+ // lie in its namespace and are exactly its archived objects, none missing and
9
+ // none extra. A table restored across a later ADD COLUMN stages only archived
10
+ // columns; publication gives its rows the destination's default there.
11
+ export async function checkReferences({db,config},copies,objects) {
12
+ for(const [binding,spec] of Object.entries(config.buckets)) if(spec.objectReferences) {
13
+ const {table,keyColumn}=spec.objectReferences,copy=copies[table];
14
+ const column=async name=>(await all(db,`PRAGMA table_xinfo(${quote(name)})`)).find(c=>c.name===keyColumn);
15
+ const value=await column(copy)?quote(keyColumn):'('+((await column(table))?.dflt_value??'NULL')+')';
16
+ const keys=new Set((await all(db,`SELECT DISTINCT ${value} COLLATE BINARY AS key FROM ${quote(copy)} WHERE ${value} IS NOT NULL`)).map(x=>x.key));
17
+ const listed=objects.filter(x=>x.bucket===binding);
18
+ insist([...keys].every(key=>namespaced(spec.prefix??'',key)) && listed.length===keys.size && listed.every(x=>keys.has(x.key)),'object_references:'+binding);
19
+ }
20
+ }
@@ -0,0 +1,13 @@
1
+ import { canonicalTokens } from './sqlite-tokens.mjs';
2
+ import { canonicalJson, sha256 } from './hash.mjs';
3
+ export { rawSchemaIdentityOf } from './schema-legacy.mjs';
4
+
5
+ // Typed, lossless lexical identity. Only trivia and proven-safe keyword case
6
+ // are normalized; the same lexer proves every removed separator is harmless.
7
+ export const schemaSQL = sql => canonicalJson(canonicalTokens(sql));
8
+ const tableDefinitions = tables => tables.map(({ name, sql }) => ({ name, sql: schemaSQL(sql) }));
9
+ export const schemaIdentityOf = (tables, objects = []) => sha256(canonicalJson({
10
+ tables: tableDefinitions(tables),
11
+ objects: objects.map(({ name, type, table, sql }) => ({ name, type, table, sql: schemaSQL(sql) })),
12
+ }));
13
+ export const tableSchemaIdentityOf = tables => sha256(canonicalJson(tableDefinitions(tables)));
@@ -0,0 +1,21 @@
1
+ import { sqliteTokens } from './sqlite-tokens.mjs';
2
+ import { canonicalJson, sha256 } from './hash.mjs';
3
+
4
+ // Read-only wire codecs for 4280971d/537b088b/9352a46d checksums. These
5
+ // lossy representations authenticate historical manifests ONLY; they never
6
+ // decide whether two schemas match. All compatibility uses schemaIdentityOf.
7
+ function legacySQL(sql) {
8
+ return canonicalJson(sqliteTokens(sql).flatMap(token => {
9
+ if (token.type === 'blob') return [token.text[0], token.text.slice(1)];
10
+ if (token.type === 'quoted-identifier' || token.type === 'string') return [token.text];
11
+ return token.text.match(/[\p{L}\p{N}_$]+|->>|->|==|!=|<>|<=|>=|<<|>>|\|\||./gu);
12
+ }));
13
+ }
14
+ export const rawSchemaIdentityOf = tables => sha256(canonicalJson(tables.map(({name,sql}) => ({name,sql}))));
15
+ export async function legacySchemaIdentities(tables, objects = []) {
16
+ const definitions = tables.map(({name,sql}) => ({name,sql:legacySQL(sql)}));
17
+ return Promise.all([
18
+ sha256(canonicalJson(definitions)),
19
+ sha256(canonicalJson({tables:definitions,objects:objects.map(({name,type,table,sql}) => ({name,type,table,sql:legacySQL(sql)}))})),
20
+ ]);
21
+ }
@@ -0,0 +1,121 @@
1
+ import { insist } from './storage.mjs';
2
+
3
+ // SQLite's public-domain sqlite3GetToken (src/tokenize.c). Scan original
4
+ // characters once: never strip trivia before deciding where a token ends.
5
+ // Unknown or deliberately unsupported syntax is a schema refusal, not a token.
6
+ const digit = c => c !== undefined && c >= '0' && c <= '9';
7
+ const hex = c => digit(c) || (c !== undefined && ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')));
8
+ const letter = c => c !== undefined && ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
9
+ const id = c => letter(c) || digit(c) || c === '_' || c === '$' || (c !== undefined && c.charCodeAt(0) >= 128);
10
+ const space = c => c !== undefined && ' \t\n\f\r'.includes(c);
11
+ const refuse = () => insist(false, 'schema_mismatch:unsupported_sql', 409);
12
+ export const asciiFold = text => text.replace(/[A-Z]/g, c => c.toLowerCase());
13
+
14
+ // Only grammar-reserved keywords can be folded without parsing. SQLite's
15
+ // fallback/JOIN/window keywords can instead be identifiers or DEFAULT strings.
16
+ // Keep their original spelling, as well as every ordinary identifier.
17
+ const reserved = new Set(`add all alter and as autoincrement between case check collate commit constraint create default deferrable delete distinct drop else escape exists foreign from group having in index insert intersect into is isnull join limit not notnull null on or order primary references returning select set table then to transaction union unique update using values when where`.split(' '));
18
+ const keywords = new Set(`abort action add after all alter always analyze and as asc attach autoincrement before begin between by cascade case cast check collate column commit conflict constraint create cross current current_date current_time current_timestamp database default deferrable deferred delete desc detach distinct do drop each else end escape except exclude exclusive exists explain fail filter first following for foreign from full generated glob group groups having if ignore immediate in index indexed initially inner insert instead intersect into is isnull join key last left like limit match materialized natural no not nothing notnull null nulls of offset on or order others outer over partition plan pragma preceding primary query raise range recursive references regexp reindex release rename replace restrict returning right rollback row rows savepoint select set table temp temporary then ties to transaction trigger unbounded union unique update using vacuum values view virtual when where window with without`.split(' '));
19
+ const operators = new Set(['||','->','->>','<=','>=','<>','!=','<<','>>','==']);
20
+
21
+ function digits(sql, at, accepts) {
22
+ let i = at;
23
+ while (accepts(sql[i]) || sql[i] === '_') {
24
+ if (sql[i] === '_' && (!accepts(sql[i-1]) || !accepts(sql[i+1]))) refuse();
25
+ i++;
26
+ }
27
+ return i;
28
+ }
29
+ function number(sql, start) {
30
+ let i = start, type = 'integer';
31
+ if (sql[i] === '0' && ['x','X'].includes(sql[i+1]) && hex(sql[i+2])) {
32
+ i = digits(sql, i+2, hex); type = 'hex';
33
+ } else {
34
+ i = digits(sql, i, digit);
35
+ if (sql[i] === '.') { type = 'float'; i = digits(sql, i+1, digit); }
36
+ if (['e','E'].includes(sql[i])) {
37
+ type = 'float'; i++;
38
+ if (['+','-'].includes(sql[i])) i++;
39
+ if (!digit(sql[i])) refuse();
40
+ i = digits(sql, i, digit);
41
+ }
42
+ }
43
+ if (id(sql[i])) refuse();
44
+ return { end: i, type };
45
+ }
46
+ function variable(sql, start) {
47
+ let i = start+1, count = 0;
48
+ if (sql[start] === '?') { while (digit(sql[i])) i++; return i; }
49
+ while (i < sql.length) {
50
+ if (id(sql[i])) { count++; i++; }
51
+ else if (sql.startsWith('::', i)) i += 2;
52
+ else if (sql[i] === '(' && count) {
53
+ i++;
54
+ while (i < sql.length && !space(sql[i]) && sql[i] !== '\v' && sql[i] !== ')') i++;
55
+ if (sql[i] !== ')') refuse();
56
+ i++; break;
57
+ } else break;
58
+ }
59
+ if (!count) refuse();
60
+ return i;
61
+ }
62
+ export function sqliteTokens(sql, { trivia = false } = {}) {
63
+ if (typeof sql !== 'string' || sql.includes('\0') || !sql.isWellFormed()) refuse();
64
+ const result = [];
65
+ for (let i = 0; i < sql.length;) {
66
+ const start = i, c = sql[i]; let type;
67
+ if (space(c)) { while (space(sql[i])) i++; type = 'space'; }
68
+ else if (c === '\v' || c === '\ufeff') refuse();
69
+ else if (sql.startsWith('--', i)) { i = sql.indexOf('\n', i+2); if (i < 0) i = sql.length; type = 'comment'; }
70
+ else if (sql.startsWith('/*', i)) {
71
+ const end = sql.indexOf('*/', i+2); if (end < 0) refuse();
72
+ i = end+2; type = 'comment';
73
+ } else if ((c === 'x' || c === 'X') && sql[i+1] === "'") {
74
+ i += 2; const first = i;
75
+ while (hex(sql[i])) i++;
76
+ if (sql[i] !== "'" || (i-first)%2) refuse();
77
+ i++; type = 'blob';
78
+ } else if ('\'"`['.includes(c)) {
79
+ const close = c === '[' ? ']' : c; i++; let closed = false;
80
+ while (i < sql.length) {
81
+ if (sql[i++] !== close) continue;
82
+ if (c !== '[' && sql[i] === close) { i++; continue; }
83
+ closed = true; break;
84
+ }
85
+ if (!closed) refuse();
86
+ type = c === "'" ? 'string' : 'quoted-identifier';
87
+ } else if (digit(c) || (c === '.' && digit(sql[i+1]))) {
88
+ const numeric = number(sql, i); i = numeric.end; type = numeric.type;
89
+ } else if ('?@:$#'.includes(c)) { i = variable(sql, i); type = 'variable'; }
90
+ else if (letter(c) || c === '_' || c.charCodeAt(0) >= 128) {
91
+ while (id(sql[++i])) { /* longest identifier */ }
92
+ type = keywords.has(asciiFold(sql.slice(start,i))) ? 'keyword' : 'identifier';
93
+ } else {
94
+ const three = sql.slice(i,i+3), two = sql.slice(i,i+2);
95
+ if (operators.has(three)) i += 3;
96
+ else if (operators.has(two)) i += 2;
97
+ else if ('+-*/%<>=&|~();,.'.includes(c)) i++;
98
+ else refuse();
99
+ type = 'operator';
100
+ }
101
+ const text = sql.slice(start,i);
102
+ if (trivia || (type !== 'space' && type !== 'comment')) result.push({type,text,start,end:i,
103
+ value:type === 'keyword' && reserved.has(asciiFold(text)) ? asciiFold(text) : text});
104
+ }
105
+ return result;
106
+ }
107
+ const spelling = list => JSON.stringify(list.map(({type,text}) => [type,text]));
108
+ // One lexer defines the boundary rule, including comment creation, doubled
109
+ // quotes, numeric prefixes, variables and longest-match operators.
110
+ export function significantBoundary(left, right) {
111
+ try { return spelling(sqliteTokens(left.text+right.text)) !== spelling([left,right]); }
112
+ catch { return true; }
113
+ }
114
+ export function canonicalTokens(sql) {
115
+ const tokens = sqliteTokens(sql), canonical = tokens.map(t => ({...t,text:t.value}));
116
+ const joined = canonical.map((t,i) => (i && significantBoundary(canonical[i-1],t) ? ' ' : '')+t.text).join('');
117
+ // Check the entire stream too: a lookahead spanning more than one boundary
118
+ // must never silently collapse. Unsupported cases refuse at the public door.
119
+ if (spelling(sqliteTokens(joined)) !== spelling(canonical)) refuse();
120
+ return {tokens:tokens.map(({type,value}) => [type,value]),sql:joined};
121
+ }
@@ -63,11 +63,19 @@ For a GitHub source, the producer uses the operator's existing `gh` authenticati
63
63
  to resolve the source repository's **Verify** workflow for the exact selected
64
64
  commit. The source identity comes from its GitHub `origin` (HTTPS or SSH), or the
65
65
  committed `rer-project.json.sourceRepository` when no GitHub origin is present;
66
- it is independent of the publication destination. Only a completed successful
67
- `push` or `workflow_dispatch` run on the default branch or the version's release
68
- tag qualifies. The run and head repository must both match the source repository,
69
- and a release tag must resolve remotely to the exact source commit. PR merge runs,
70
- other SHAs, repositories, branches and unsuccessful runs cannot authorize release.
66
+ it is independent of the publication destination. A completed successful run of
67
+ the selected workflow qualifies when its `head_sha` equals the source commit
68
+ exactly, both `repository.full_name` and `head_repository.full_name` match the
69
+ source repository, and its event is `push` or `workflow_dispatch`. Any branch
70
+ of that repository can qualify. These events run that commit's own workflow
71
+ file on that commit's tree. Pull-request runs test a merge ref and cannot serve
72
+ as exact-SHA evidence, even for a same-repository PR. Fork runs and other events
73
+ cannot authorize release. A run on the version's release tag still requires
74
+ that tag to resolve remotely to the source commit. A failed tag lookup
75
+ disqualifies that tag run; a separate qualifying run can still authorize release.
76
+ When several runs qualify, the highest run ID is selected. Failed or unfinished
77
+ duplicates do not invalidate a qualifying success; the receipt records them as
78
+ informational entries, including their run identities and outcomes.
71
79
  `gates.verify` records the source repository and commit, `workflowId`,
72
80
  `workflowFile`, `workflowName`, `runId`,
73
81
  `runUrl`, event, branch and conclusion in both receipt and site provenance.
@@ -87,15 +95,18 @@ script, when declared, in a disposable clone. `gates.verify.install` and
87
95
  `gates.verify.build` record those local results; failure or a tracked-source
88
96
  mutation blocks release. Publication/history/annotation scans, exact-source
89
97
  packaging, package integrity checks and the separate signing commands still run
90
- locally. A missing green Verify blocks with the exact SHA and instructions to
91
- push or re-run it. API/authentication failures also block, without substituting
92
- local verification.
98
+ locally. A missing green Verify blocks with the exact SHA and the rejected run
99
+ details; an unfinished run is named. Push the exact commit to any branch of the
100
+ source repository and wait for its selected Verify workflow to complete
101
+ successfully. If the required GitHub evidence cannot be resolved, release
102
+ blocks without substituting local verification.
93
103
 
94
104
  Pass **`--local-verify`** to explicitly retain the previous behavior: frozen
95
105
  installation, `pnpm run verify`, then the committed `pnpm run verify:release`
96
106
  when declared, with its result in `gates.verify.release`. Sources without a
97
107
  GitHub origin or committed source identity also retain this behavior. This local
98
- path needs the seed's browser prerequisites and any resources its verification
108
+ path is appropriate only when the repository's verification policy permits it
109
+ and needs the seed's browser prerequisites and any resources its verification
99
110
  requires. Routine CI and default verification do not invoke the release-only
100
111
  script.
101
112
 
@@ -43,7 +43,7 @@ function tagCommit(repository, tag) {
43
43
  export function githubVerify(source, repository, selector) {
44
44
  const result = { status: 'FAIL', provider: 'github', repository, commit: source.commit,
45
45
  reason: 'github-verify-not-successful',
46
- message: `No successful Verify run exists for ${repository} at exact source commit ${source.commit}. Push this commit to the default branch or release tag, or re-run Verify for this SHA with workflow_dispatch. Use --local-verify to run verification locally.` };
46
+ message: `No successful Verify run exists for ${repository} at exact source commit ${source.commit}. To obtain qualifying evidence, push the exact commit to any branch of ${repository} and wait for its Verify run to complete successfully. Check the run details below. --local-verify runs local verification instead, only when the repository's verification policy permits it.` };
47
47
  try {
48
48
  const metadata = api(`repos/${repository}`);
49
49
  if (!same(metadata.full_name, repository) || typeof metadata.default_branch !== 'string' || !metadata.default_branch) throw Error('repository');
@@ -53,8 +53,8 @@ export function githubVerify(source, repository, selector) {
53
53
  if (selected.error) return { ...result, details: selected.error };
54
54
  const workflow = selected.workflow;
55
55
  Object.assign(result, { workflowId: workflow.id, workflowFile: workflow.path, workflowName: workflow.name });
56
- const rejected = new Set();
57
- let checkedTag = false, tagSHA;
56
+ const rejected = new Set(), successful = [], information = [];
57
+ let checkedTag = false, tagSHA, tagUnavailable = false;
58
58
  const runs = api(`repos/${repository}/actions/workflows/${workflow.id}/runs?head_sha=${source.commit}&per_page=100`, true)
59
59
  .flatMap(page => page.workflow_runs);
60
60
  for (const run of runs) {
@@ -64,21 +64,42 @@ export function githubVerify(source, repository, selector) {
64
64
  }
65
65
  if (run.workflow_id !== workflow.id) { rejected.add('different workflow'); continue; }
66
66
  if (!['push', 'workflow_dispatch'].includes(run.event)) { rejected.add('event must be push or workflow_dispatch'); continue; }
67
+ const evidence = { runId: run.id, runUrl: `https://github.com/${metadata.full_name}/actions/runs/${run.id}`,
68
+ event: run.event, branch: run.head_branch, conclusion: run.conclusion };
67
69
  if (run.status !== 'completed' || run.conclusion !== 'success') {
68
- rejected.add(run.status === 'completed' ? `conclusion ${['failure', 'cancelled', 'skipped', 'timed_out', 'neutral', 'action_required', 'stale'].includes(run.conclusion) ? run.conclusion : 'not success'}` : 'run not completed');
70
+ const reason = run.status === 'completed'
71
+ ? `conclusion ${['failure', 'cancelled', 'skipped', 'timed_out', 'neutral', 'action_required', 'stale'].includes(run.conclusion) ? run.conclusion : 'not success'}`
72
+ : `run not completed (${run.status})`;
73
+ rejected.add(`Run ${run.id} on ${run.head_branch} (${run.event}): ${reason}; ${evidence.runUrl}`);
74
+ information.push({ ...evidence, status: run.status,
75
+ message: `${reason}; does not invalidate a separate successful Verify run for this exact SHA.` });
69
76
  continue;
70
77
  }
71
- if (run.head_branch !== metadata.default_branch) {
72
- if (run.head_branch !== source.tag) { rejected.add('neither default branch nor release tag'); continue; }
73
- if (!checkedTag) { tagSHA = tagCommit(repository, source.tag); checkedTag = true; }
78
+ // A push or workflow_dispatch run for this exact SHA ran this commit's
79
+ // own workflow file on this commit's tree, regardless of branch. A
80
+ // pull_request run tests its merge ref and cannot provide that evidence.
81
+ if (run.head_branch === source.tag && run.head_branch !== metadata.default_branch) {
82
+ if (!checkedTag) {
83
+ checkedTag = true;
84
+ try { tagSHA = tagCommit(repository, source.tag); }
85
+ catch { tagUnavailable = true; }
86
+ }
87
+ // A tag lookup failure rejects this run, not independent branch evidence.
88
+ if (tagUnavailable) { rejected.add('release tag could not be resolved'); continue; }
74
89
  if (tagSHA !== source.commit) { rejected.add('release tag points at a different commit'); continue; }
75
90
  }
76
91
  if (!Number.isSafeInteger(run.id) || run.id <= 0) throw Error('run');
92
+ successful.push(evidence);
93
+ }
94
+ // API page order is not an authority: select the highest qualifying run ID.
95
+ successful.sort((left, right) => right.runId - left.runId);
96
+ information.sort((left, right) => right.runId - left.runId);
97
+ if (successful.length) {
77
98
  return { status: 'PASS', provider: 'github', repository: metadata.full_name, commit: source.commit,
78
99
  workflowId: workflow.id, workflowFile: workflow.path, workflowName: workflow.name,
79
- runId: run.id, runUrl: `https://github.com/${metadata.full_name}/actions/runs/${run.id}`,
80
- event: run.event, branch: run.head_branch, conclusion: run.conclusion };
100
+ ...successful[0], ...(information.length ? { information } : {}) };
81
101
  }
102
+ if (tagUnavailable) throw Error('tag');
82
103
  result.details = rejected.size ? [...rejected].join('; ') : 'No runs found for this SHA.';
83
104
  } catch {
84
105
  result.reason = 'github-verify-unavailable';
@@ -6,7 +6,7 @@
6
6
  .docs-search input { display: block; width: 100%; min-width: 0; min-height: 42px; padding: 8px 0; border: 0; border-radius: 0; outline: none; background: transparent; color: var(--ink); font: inherit; font-size: 15px; line-height: 1.4; }
7
7
  .docs-search input::-webkit-search-cancel-button { filter: grayscale(1); }
8
8
  .docs-search input::placeholder { color: var(--ink-soft); opacity: 1; }
9
- .docs-search kbd { flex: none; padding: 0 5px; border: 1px solid var(--rule); border-radius: 3px; color: var(--ink-soft); font: inherit; font-size: 12px; line-height: 20px; }
9
+ .docs-search kbd { flex: none; padding: 0 5px; border: 1px solid var(--rule); border-radius: 3px; color: var(--ink-soft); font: inherit; font-size: 13px; line-height: 20px; }
10
10
  .docs-search-panel { margin-top: 10px; }
11
11
  .docs-search-status { margin: 0; color: var(--ink-soft); font-size: 14px; line-height: 1.4; }
12
12
  .docs-search-status:empty { display: none; }
@@ -175,6 +175,12 @@ their native look.
175
175
  appearance, at least 36px of right padding and its chevron 10-16px from the
176
176
  right edge.
177
177
 
178
+ `KEEP_BROWSER_CHECK=1` retains successful onboarding screenshots and axe reports;
179
+ failed checks retain them automatically.
180
+
181
+ The CLI wrapper's `RER_JOBS_MAX_WAIT_SECONDS` defaults to 1200 seconds, unlike the
182
+ bare queue's indefinite wait; admission timeout exits 75 without starting work.
183
+
178
184
  ## Setup behavior and custody
179
185
 
180
186
  Setup validates answers before effects, then uses the declared lifecycle to
@@ -213,14 +219,20 @@ is separate from bringing records in through the reviewed import door. Each
213
219
  first-party adapter declares which resources that archive export/restore supports.
214
220
  Every first-party seed verifies a complete local export/import/export round
215
221
  trip across those resources. Archives are private and integrity-checked;
216
- owner/auth, historical development mail, private settings and transient runtime state remain
217
- excluded. Archive restore validates and restores atomically into an empty destination.
222
+ historical development mail, private settings and transient runtime state remain
223
+ excluded. Identity retention depends on the seed's archive policy: default-seed
224
+ excludes authentication identities and the owner claim, while foundation retains
225
+ selected identity tables and the original claim. A restored job remains bound to
226
+ its recorded principal; verify whether that principal survives the selected policy.
227
+ Archive restore validates and restores atomically into an empty destination.
218
228
  Remote transfer is supported only when every required resource has a complete
219
229
  adapter implementation; unsupported targets fail visibly.
220
230
 
221
231
  Deployment uses each seed's actual owner-account declaration, resource policy,
222
- migrations and health check. Dry run validates and builds locally without
223
- provider requests. Local tests and structural checks do not establish hosted
232
+ migrations and health check. Application dry run builds and validates locally,
233
+ then uses Cloudflare credentials to read target secret bindings; it makes no
234
+ provider writes. Site and demo dry runs have their separately documented offline
235
+ behavior. Local tests and structural checks do not establish hosted
224
236
  acceptance or external mail delivery.
225
237
 
226
238
  Keep server authorization in every private handler, including direct server
@@ -15,6 +15,7 @@ import { appFetch } from './app-fetch.mjs';
15
15
  import { owner, signIn } from './adapter-auth.mjs';
16
16
  import { installerDevKey } from './dev-identity.mjs';
17
17
  import { assertArchiveFree } from './archive-output.mjs';
18
+ import { startOriginDiagnostic } from './start-origin-diagnostic.mjs';
18
19
  export { ownerAccountHosting } from './adapter-hosting.mjs';
19
20
 
20
21
  // The adapter kit for an existing seed. A seed's scripts/installer/local.mjs
@@ -229,7 +230,10 @@ async function start(context, hooks) {
229
230
  if (signal?.aborted) throw error;
230
231
  const ports=await ownedPorts();
231
232
  if(ports.length){
232
- const message=store.redact(`Application listened on port ${ports.join(', ')}; readiness failed for expected internal port ${expectedPort}. Check application health and the runtime target's port binding.`);
233
+ let diagnosis;
234
+ try { diagnosis=await startOriginDiagnostic(context,hooks,child,health,ready); }
235
+ catch (diagnosticError) { if(signal?.aborted)throw diagnosticError; }
236
+ const message=store.redact(diagnosis??`Application listened on port ${ports.join(', ')}; readiness failed for GET ${url} through expected internal port ${expectedPort}. Check application health and the runtime target's port binding.`);
233
237
  store.report(message);const prior=approvedFailure(error);error=commandFailure(`${prior?.message??readinessLabel}\n${message}`,prior??{});
234
238
  }
235
239
  throw installationFailure('command_failed', { step: 'start', diagnostic: error });
@@ -149,6 +149,28 @@
149
149
  "enum": ["owner", "developer"],
150
150
  "description": "Public fields only: owner or developer. When absent, inherit the group's audience, or owner without a group audience. An explicit owner value inside a developer group is invalid. This metadata does not change local installer or rer setup visibility; secret visibility uses ownerVisible and input."
151
151
  },
152
+ "businessField": {
153
+ "enum": [
154
+ "owner_email",
155
+ "legal_name",
156
+ "timezone",
157
+ "currency",
158
+ "jurisdiction",
159
+ "mail_sender",
160
+ "display_name",
161
+ "owner_name",
162
+ "brand_color",
163
+ "logo_ref",
164
+ "entity_type",
165
+ "state_of_organization",
166
+ "fiscal_year_start",
167
+ "books_start_date",
168
+ "tax_method",
169
+ "country",
170
+ "state"
171
+ ],
172
+ "description": "Optional public-field hint identifying the business profile value represented by this input. Secrets cannot declare this hint. It does not supply an answer or change validation."
173
+ },
152
174
  "required": {
153
175
  "type": "boolean"
154
176
  },
@@ -242,7 +264,10 @@
242
264
  "required": [
243
265
  "required",
244
266
  "ownerVisible"
245
- ]
267
+ ],
268
+ "not": {
269
+ "required": ["businessField"]
270
+ }
246
271
  }
247
272
  },
248
273
  {
@@ -0,0 +1,37 @@
1
+ // Exact input-to-profile permissions, not a credential-name classifier.
2
+ // Normalize case once for lookup. SETUP's separate ASCII upper-snake-case
3
+ // identifier grammar still applies; no separator, prefix or Unicode folding.
4
+ export const BUSINESS_FIELD_INPUTS = Object.freeze(Object.fromEntries(Object.entries({
5
+ owner_email: ['OWNER_EMAIL', 'FIRST_OWNER_EMAIL', 'OPERATOR_EMAIL', 'SEED_ADMIN_EMAIL', 'SETUP_OPERATOR_EMAIL', 'SETUP_OWNER_EMAIL', 'SUPPORT_EMAIL'],
6
+ legal_name: ['LEGAL_NAME', 'TRADING_NAME'],
7
+ timezone: ['WORKSPACE_TIMEZONE', 'LAMP_PAGE_TIMEZONE', 'TIMEZONE'],
8
+ currency: ['WORKSPACE_CURRENCY', 'CURRENCY'],
9
+ jurisdiction: ['JURISDICTION'],
10
+ mail_sender: ['MAIL_FROM', 'EMAIL_FROM', 'MAIL_FROM_ADDRESS', 'MAIL_SENDER'],
11
+ display_name: ['APP_NAME', 'WORKSPACE_NAME', 'DEFAULT_TEAM_NAME', 'LAMP_PAGE_NAME', 'LAMP_PAGE_TAGLINE', 'DISPLAY_NAME', 'BUSINESS_NAME'],
12
+ owner_name: ['OWNER_NAME', 'FIRST_OWNER_NAME', 'OWNER_DISPLAY_NAME'],
13
+ brand_color: ['PRIMARY_COLOR', 'LAMP_ACCENT_COLOR', 'BRAND_COLOR'],
14
+ logo_ref: ['LOGO_REF'],
15
+ entity_type: ['ENTITY_TYPE'],
16
+ state_of_organization: ['STATE_OF_ORGANIZATION'],
17
+ fiscal_year_start: ['FISCAL_YEAR_START'],
18
+ books_start_date: ['BOOKS_START_DATE'],
19
+ tax_method: ['TAX_METHOD'],
20
+ country: ['COUNTRY'],
21
+ state: ['STATE'],
22
+ }).map(([field, names]) => [field, Object.freeze(names)])));
23
+
24
+ /** Shared hint refusal for validators and the installer compiler's vault scope. */
25
+ export function businessFieldInputError(field, secretScopes = {}) {
26
+ if (!Object.hasOwn(field, 'businessField')) return;
27
+ if (field.kind === 'secret' || field.type === 'password' || field.secret === true
28
+ || Object.hasOwn(secretScopes, field.name)) {
29
+ return `${field.name} cannot claim Business field ${String(field.businessField)} because it is secret or vault-bound`;
30
+ }
31
+ if (typeof field.businessField !== 'string' || typeof field.name !== 'string') return;
32
+ const names = Object.hasOwn(BUSINESS_FIELD_INPUTS, field.businessField)
33
+ ? BUSINESS_FIELD_INPUTS[field.businessField] : [];
34
+ if (!names.includes(field.name.toUpperCase())) {
35
+ return `${field.name} cannot claim Business field ${field.businessField}: this name is not on the Business-field allow-list: add it in Base's schema table through a Base change, or rename the input to one of: ${names.join(', ') || '(choose a valid Business field first)'}`;
36
+ }
37
+ }
@@ -24,7 +24,7 @@ const SUPPORTED = new Set([
24
24
  '$schema', '$id', '$ref', '$defs', 'title', 'description',
25
25
  'type', 'enum', 'const', 'required', 'properties', 'additionalProperties',
26
26
  'propertyNames', 'items', 'minItems', 'maxItems', 'minLength', 'pattern', 'format',
27
- 'allOf', 'if', 'then', 'uniqueItems'
27
+ 'allOf', 'if', 'then', 'not', 'uniqueItems'
28
28
  ]);
29
29
 
30
30
  // The supported keywords whose value holds subschemas, and how they hold them:
@@ -37,7 +37,8 @@ const SUBSCHEMAS = {
37
37
  items: 'schema',
38
38
  allOf: 'list',
39
39
  if: 'schema',
40
- then: 'schema'
40
+ then: 'schema',
41
+ not: 'schema'
41
42
  };
42
43
 
43
44
  const SUPPORTED_FORMATS = new Set(['date']);
@@ -138,6 +139,9 @@ export function validate(schema, data, { root = schema, path = '$', label = '' }
138
139
  if (Object.hasOwn(schema, 'const') && data !== schema.const) {
139
140
  fail(`expected ${JSON.stringify(schema.const)}`);
140
141
  }
142
+ if (schema.not && validate(schema.not, data, { root, path }).length === 0) {
143
+ fail('must not match excluded schema');
144
+ }
141
145
 
142
146
  if (actual === 'string') {
143
147
  if (schema.minLength !== undefined && data.length < schema.minLength) fail(`must not be empty`);