@runeditrun/rer 0.1.1 → 0.2.1

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 (154) hide show
  1. package/README.md +113 -2
  2. package/cli/README.md +32 -5
  3. package/cli/contract.mjs +5 -5
  4. package/cli/deploy.mjs +17 -3
  5. package/cli/detached-server.mjs +51 -0
  6. package/cli/dev-identity.mjs +2 -1
  7. package/cli/door-mode.mjs +134 -0
  8. package/cli/door.mjs +263 -0
  9. package/cli/hosted-output.mjs +17 -7
  10. package/cli/hydration/browser.mjs +91 -0
  11. package/cli/hydration/cases.mjs +106 -0
  12. package/cli/hydration/check.mjs +105 -0
  13. package/cli/hydration/probe.mjs +164 -0
  14. package/cli/hydration/scripts.mjs +39 -0
  15. package/cli/hydration/verdict.mjs +85 -0
  16. package/cli/inspect.mjs +57 -10
  17. package/cli/lifecycle.mjs +36 -12
  18. package/cli/local.mjs +9 -3
  19. package/cli/main.mjs +3 -0
  20. package/cli/managed-server.mjs +62 -21
  21. package/cli/package-calls.mjs +81 -0
  22. package/cli/package-mode.mjs +46 -0
  23. package/cli/parse.mjs +15 -4
  24. package/cli/pnpm-runtime.mjs +96 -0
  25. package/cli/portability-worker.mjs +2 -2
  26. package/cli/release.mjs +1 -0
  27. package/cli/runtime-front-door.mjs +4 -2
  28. package/cli/server-proxy.mjs +69 -5
  29. package/cli/server-registry.mjs +10 -7
  30. package/cli/settings.mjs +14 -0
  31. package/cli/site-bindings.mjs +291 -0
  32. package/cli/site-browser-objects.mjs +36 -0
  33. package/cli/site-check.mjs +111 -0
  34. package/cli/site-client.mjs +50 -0
  35. package/cli/site-data.mjs +54 -0
  36. package/cli/site-entities.json +1 -0
  37. package/cli/site-input-assets.mjs +58 -0
  38. package/cli/site-inputs.mjs +79 -0
  39. package/cli/site-markup.mjs +102 -0
  40. package/cli/site-preview.mjs +53 -0
  41. package/cli/site-private.mjs +36 -0
  42. package/cli/site-references.mjs +93 -0
  43. package/cli/site-render.mjs +79 -0
  44. package/cli/site-syntax.mjs +21 -0
  45. package/cli/site.mjs +130 -0
  46. package/global/CHANGELOG.md +88 -0
  47. package/global/README.md +113 -2
  48. package/global/checkout.mjs +24 -10
  49. package/global/cli/install.mjs +6 -2
  50. package/global/delegate.mjs +9 -7
  51. package/global/door/command.mjs +254 -0
  52. package/global/door/control.mjs +65 -0
  53. package/global/door/cookies.mjs +41 -0
  54. package/global/door/pages.mjs +49 -0
  55. package/global/door/policy.mjs +49 -0
  56. package/global/door/routes.mjs +45 -0
  57. package/global/door/server.mjs +255 -0
  58. package/global/door/sites.mjs +192 -0
  59. package/global/launch/dev.mjs +21 -7
  60. package/global/launch/door.mjs +36 -0
  61. package/global/launch/install-pinned.mjs +22 -0
  62. package/global/launch/prepare.mjs +38 -5
  63. package/global/launch/render.mjs +6 -1
  64. package/global/launch/steps.mjs +12 -7
  65. package/global/launch/worker.mjs +3 -3
  66. package/global/list.mjs +6 -3
  67. package/global/main.mjs +39 -3
  68. package/global/output.mjs +12 -0
  69. package/global/rer.mjs +3 -0
  70. package/global/version.mjs +8 -8
  71. package/modules/dependencies/protocol.mjs +2 -1
  72. package/modules/deploy-kit/README.md +34 -1
  73. package/modules/deploy-kit/artifact.mjs +10 -0
  74. package/modules/deploy-kit/deploy.mjs +5 -2
  75. package/modules/deploy-kit/diagnostics.mjs +55 -0
  76. package/modules/deploy-kit/owner-cli.mjs +10 -4
  77. package/modules/deploy-kit/owner.mjs +8 -4
  78. package/modules/deploy-kit/prepare.mjs +3 -2
  79. package/modules/deploy-kit/provider.mjs +51 -9
  80. package/modules/deploy-kit/site.mjs +135 -0
  81. package/modules/erasure/CONTRACT.md +6 -3
  82. package/modules/erasure/README.md +8 -1
  83. package/modules/erasure/audit.mjs +2 -2
  84. package/modules/erasure/cascade.mjs +52 -11
  85. package/modules/erasure/order.mjs +29 -22
  86. package/modules/erasure/plan.mjs +4 -2
  87. package/modules/erasure/queue.mjs +41 -0
  88. package/modules/erasure/scope.mjs +3 -3
  89. package/modules/erasure/verification.mjs +4 -2
  90. package/modules/mail/README.md +1 -1
  91. package/modules/mail/index.mjs +1 -1
  92. package/modules/mail/src/core/errors.mjs +9 -0
  93. package/modules/mail/src/development/index.d.mts +6 -0
  94. package/modules/mail/src/development/index.mjs +6 -3
  95. package/modules/mail/src/development/viewer-html.mjs +3 -3
  96. package/modules/mail/src/development/viewer.mjs +8 -1
  97. package/modules/operator-auth/accounts/native.mjs +1 -1
  98. package/modules/operator-auth/dev/badge.mjs +4 -1
  99. package/modules/operator-auth/dev/index.mjs +15 -5
  100. package/modules/operator-auth/http.mjs +2 -3
  101. package/modules/operator-auth/index.d.mts +4 -9
  102. package/modules/operator-auth/loopback.mjs +17 -0
  103. package/modules/operator-auth/page.mjs +1 -1
  104. package/modules/operator-auth/service.mjs +1 -0
  105. package/modules/operator-auth/signin/index.d.mts +11 -0
  106. package/modules/operator-auth/signin/index.mjs +10 -7
  107. package/modules/owner-claim/verify.mjs +2 -1
  108. package/modules/portability/README.md +8 -0
  109. package/modules/portability/hash.mjs +6 -2
  110. package/modules/portability/import.mjs +1 -1
  111. package/modules/portability/legacy-files.mjs +4 -4
  112. package/modules/portability/legacy-safety.mjs +51 -10
  113. package/modules/portability/migration-history.mjs +15 -0
  114. package/modules/release/README.md +68 -3
  115. package/modules/release/keygen.mjs +18 -0
  116. package/modules/release/produce.mjs +14 -2
  117. package/modules/release/sign.mjs +44 -0
  118. package/modules/release/signature.mjs +336 -0
  119. package/modules/release/signing-cli.mjs +56 -0
  120. package/modules/release/signing-io.mjs +61 -0
  121. package/modules/release/signing-key.mjs +22 -0
  122. package/modules/release/source.mjs +15 -4
  123. package/modules/release/statement.mjs +80 -0
  124. package/modules/release/vectors/generate.mjs +381 -0
  125. package/modules/release/vectors/release-signature-vectors.json +2305 -0
  126. package/modules/release/verify.mjs +27 -0
  127. package/onboarding/adapter-auth.mjs +4 -3
  128. package/onboarding/adapter-settings.mjs +21 -5
  129. package/onboarding/adapter.mjs +2 -1
  130. package/onboarding/app-fetch.mjs +79 -0
  131. package/onboarding/archive-output.d.mts +4 -2
  132. package/onboarding/archive-output.mjs +22 -10
  133. package/onboarding/dependency-approval.mjs +4 -3
  134. package/onboarding/local/environment.mjs +7 -2
  135. package/onboarding/operator-install.mjs +8 -2
  136. package/onboarding/operator-prerequisites.mjs +5 -2
  137. package/onboarding/production-assets.mjs +23 -0
  138. package/onboarding/production-runtime.mjs +8 -4
  139. package/onboarding/queued-entry.mjs +9 -5
  140. package/operations/operations.mjs +11 -2
  141. package/package.json +76 -1
  142. package/scripts/publish-check/README.md +27 -17
  143. package/scripts/publish-check/content_identities.py +14 -233
  144. package/scripts/publish-check/git_history.py +2 -2
  145. package/scripts/publish-check/github_refs.py +28 -2
  146. package/scripts/publish-check/gitleaks.toml +1 -1
  147. package/scripts/publish-check/history_scan.py +6 -4
  148. package/scripts/publish-check/hygiene_config.py +3 -1
  149. package/scripts/publish-check/public_hygiene.py +63 -8
  150. package/scripts/publish-check/publication-config.json +16 -1
  151. package/scripts/publish-check/source_metadata.py +62 -0
  152. package/scripts/publish-check/source_shapes.py +91 -0
  153. package/scripts/publish-check/tree_scan.py +2 -2
  154. package/scripts/publish-check/source_hashes.mjs +0 -6
@@ -55,12 +55,13 @@ function memoryMessage(counted,available,floor,mode) {
55
55
  const list=counted.length?`Running now:\n${counted.map(listing).join('\n')}\nA dev server holds about 0.5-1.3 GiB and a preview 0.4-0.8 GiB; stopping one with its command above frees that.`:'No dev or preview server is running, so something else is using the memory.';
56
56
  return `${head}\n${list}\nTo start anyway, lower the floor, for example RER_SERVERS_MIN_MEMORY_BYTES=${Math.floor(floor/2)} rer ${mode} (0 turns it off).`;
57
57
  }
58
- function limitMessage(counted,cap,limit,mode) {
59
- const holders=cap<limit?counted.filter(item=>item.explicit&&item.limit===cap):[];
58
+ function limitMessage(counted,cap,explicit,mode) {
59
+ const holders=explicit?[]:counted.filter(item=>item.explicit&&item.limit===cap);
60
60
  const head=`Not started: ${counted.length} dev or preview ${counted.length===1?'server is':'servers are'} running on this computer and the limit is ${cap}.`;
61
61
  const list=`Running now:\n${counted.map(listing).join('\n')}`;
62
62
  const raise=holders.length
63
63
  ?`The limit is ${cap} because ${holders.length===1?'a server was':'servers were'} started with RER_SERVER_LIMIT=${cap} (${holders.map(item=>item.checkout).join(', ')}). Stop ${holders.length===1?'it':'them'} and start again, or start everything with a higher RER_SERVER_LIMIT=N.`
64
+ :explicit?`This start set RER_SERVER_LIMIT=${cap}; to allow more, start it with a higher RER_SERVER_LIMIT=N.`
64
65
  :`To allow more, start this one with a higher limit, for example RER_SERVER_LIMIT=${cap*2} rer ${mode}. Servers started without RER_SERVER_LIMIT allow ${defaultServerLimit}.`;
65
66
  return `${head}\n${list}\nTo make room, stop one with its command above. ${raise}`;
66
67
  }
@@ -71,9 +72,11 @@ function limitMessage(counted,cap,limit,mode) {
71
72
  // before queue admission/local operation. Stop waits for process+state cleanup,
72
73
  // which never needs the machine transaction. Generation removal happens last.
73
74
  // The limit is 10 unless the person sets RER_SERVER_LIMIT. Every record keeps the
74
- // limit it started with and whether the person set it. Across the running
75
- // servers the cap is the lowest limit a person set explicitly, so a deliberate
76
- // "RER_SERVER_LIMIT=3" keeps holding every start. A recorded default (including
75
+ // limit it started with and whether the person set it. A start that sets
76
+ // RER_SERVER_LIMIT is capped by that value alone, higher or lower than any
77
+ // running server's. A start that sets nothing is capped by the lowest limit a
78
+ // running server's person set explicitly, so a deliberate "RER_SERVER_LIMIT=3"
79
+ // keeps holding starts that do not say otherwise. A recorded default (including
77
80
  // the old default of 2 in records written before this rule) never lowers the cap
78
81
  // below the current default.
79
82
  export const defaultServerLimit=serverDefaults.serverLimit;
@@ -132,8 +135,8 @@ export async function serverRegistry(root,{env=process.env,memory=availableMemor
132
135
  const same=state.running.find(item=>item.checkout===checkout);
133
136
  if(same)return {existing:same};
134
137
  // Journeys are listed but uncounted: they neither use nor lower the cap.
135
- const counted=state.running.filter(item=>!item.journey),cap=Math.min(limit,...counted.filter(item=>item.explicit).map(item=>item.limit));
136
- if(!journey&&counted.length>=cap)throw refuse(limitMessage(counted,cap,limit,mode));
138
+ const counted=state.running.filter(item=>!item.journey),cap=explicit?limit:Math.min(limit,...counted.filter(item=>item.explicit).map(item=>item.limit));
139
+ if(!journey&&counted.length>=cap)throw refuse(limitMessage(counted,cap,explicit,mode));
137
140
  // Unreadable memory is not a reason to refuse; only a reading below the floor is.
138
141
  const available=journey||floor===0?NaN:await memory();
139
142
  if(available<floor)throw refuse(memoryMessage(counted,available,floor,mode));
package/cli/settings.mjs CHANGED
@@ -1,3 +1,6 @@
1
+ import { missing } from './errors.mjs';
2
+ import { shared } from './shared.mjs';
3
+
1
4
  // Reuse the seed's existing declarations; no parallel auth setting aliases.
2
5
  export function localSettingKeys(project) {
3
6
  const manifest = project.setupManifest ?? project.setupSeed?.manifest;
@@ -13,3 +16,14 @@ export function requiredLocalSettings(project, values) {
13
16
  const manifest=project.setupManifest ?? project.setupSeed?.manifest;
14
17
  return [...new Set([keys.email,keys.origin,...(manifest?.fields??[]).filter(field=>field.kind==='secret'&&field.required&&!field.when&&field.input!=='entered'&&field.name!==manifest?.steps.find(step=>step.type==='owner-claim')?.tokenField).map(field=>field.name)])].filter(name=>!values[name]);
15
18
  }
19
+
20
+ // The CLI's own proof to the running application, keyed by the session secret
21
+ // in the seed's private settings: its declared file and format, under the name
22
+ // its adapter declares as sessionSecretKey (default SESSION_SECRET).
23
+ export async function localCliSessionProof(project) {
24
+ const hooks = project.adapter?.hooks ?? {}, key = hooks.sessionSecretKey ?? 'SESSION_SECRET';
25
+ const { readSettings } = await shared('adapter-settings.mjs'), { localCliProof } = await shared('adapter-auth.mjs');
26
+ const secret = (await readSettings(project.root, hooks.secrets ?? {})).values[key];
27
+ if (typeof secret !== 'string' || !secret) throw missing(`${key} is missing from the private settings.`);
28
+ return localCliProof(secret);
29
+ }
@@ -0,0 +1,291 @@
1
+ import { walkSyntax, stringValue, memberName } from './site-syntax.mjs';
2
+ import { refuse } from './errors.mjs';
3
+ const finite = (values, key = value => value) => {
4
+ const unique = [...new Map(values.map(value => [key(value), value])).values()];
5
+ if (unique.length > 1024) throw refuse('The run site has too many possible values for a browser resource reference to check.');
6
+ return unique;
7
+ };
8
+ const propertyNames = (node, strings) => {
9
+ const key = node?.type === 'MemberExpression' ? node.property : node?.key;
10
+ if (!key) return [];
11
+ if (!node.computed) return [key.name ?? String(key.value)];
12
+ return key.type === 'Literal' && typeof key.value === 'number' ? [String(key.value)] : [...strings(key)];
13
+ };
14
+
15
+ // Keep bindings lexical: a library's parameter or local variable must not take
16
+ // an unrelated same-named value from the island. Resolve finite constant values
17
+ // at a resource sink, rather than treating every URL-shaped string as a fetch.
18
+ export function localValues(tree) {
19
+ const scopes = new WeakMap(), writesByName = new Map(), computedWrites = [], assigned = new WeakMap(), root = {bindings:new Map(), parent:null, function:true};
20
+ const writeIndex = name => {
21
+ if (!writesByName.has(name)) writesByName.set(name, {writes:new Set(), users:new Set()});
22
+ return writesByName.get(name);
23
+ };
24
+ const bind = (scope, name, value) => {
25
+ if (!scope.bindings.has(name)) scope.bindings.set(name, []);
26
+ if (value) scope.bindings.get(name).push(value);
27
+ };
28
+ const lookup = (node, name) => {
29
+ let scope = scopes.get(node);
30
+ while (scope && !scope.bindings.has(name)) scope = scope.parent;
31
+ return scope?.bindings.get(name);
32
+ };
33
+ const bindPattern = (scope, pattern, value) => {
34
+ if (pattern.type === 'Identifier') { bind(scope, pattern.name, value); return; }
35
+ if (pattern.type === 'RestElement') { bindPattern(scope, pattern.argument); return; }
36
+ if (pattern.type === 'AssignmentPattern') { bindPattern(scope, pattern.left, value); bindPattern(scope, pattern.left, pattern.right); return; }
37
+ for (const [index, item] of (pattern.type === 'ObjectPattern' ? pattern.properties : pattern.elements ?? []).entries()) {
38
+ if (!item) continue;
39
+ const target = pattern.type === 'ObjectPattern' ? item.value ?? item.argument : item;
40
+ const key = pattern.type === 'ObjectPattern' ? item.key : {type:'Literal', value:index};
41
+ const member = value && key ? {type:'MemberExpression', object:value, property:key, computed:pattern.type !== 'ObjectPattern' || item.computed || key.type === 'Literal'} : null;
42
+ if (member) scopes.set(member, scope);
43
+ bindPattern(scope, target, member);
44
+ }
45
+ };
46
+ walkSyntax(tree, (node, path) => {
47
+ const parent = path.at(-1);
48
+ let scope = scopes.get(parent) ?? root;
49
+ if (['FunctionDeclaration','ClassDeclaration'].includes(node.type) && node.id) bind(scope, node.id.name, node);
50
+ if (node.type === 'ImportDeclaration') for (const specifier of node.specifiers) bind(scope, specifier.local.name);
51
+ if (/^(?:FunctionExpression|FunctionDeclaration|ArrowFunctionExpression)$/.test(node.type) || node.type === 'BlockStatement' || node.type === 'CatchClause') {
52
+ scope = {bindings:new Map(), parent:scope, function:node.type !== 'BlockStatement' && node.type !== 'CatchClause'};
53
+ if (node.type === 'FunctionExpression' && node.id) bind(scope, node.id.name, node);
54
+ for (const param of node.params ?? (node.param ? [node.param] : [])) bindPattern(scope, param);
55
+ }
56
+ scopes.set(node, scope);
57
+ if (node.type === 'VariableDeclarator') {
58
+ if (parent.kind === 'var') while (!scope.function && scope.parent) scope = scope.parent;
59
+ bindPattern(scope, node.id, node.init);
60
+ }
61
+ });
62
+ walkSyntax(tree, node => {
63
+ if (node.type !== 'AssignmentExpression') return;
64
+ const operator = node.operator.slice(0, -1);
65
+ const value = node.operator === '=' ? node.right : {type:['&&','||','??'].includes(operator) ? 'LogicalExpression' : 'BinaryExpression', operator, left:node.left, right:node.right};
66
+ assigned.set(node, value);
67
+ if (node.left.type === 'MemberExpression') {
68
+ const name = memberName(node.left), write = {left:node.left, right:value};
69
+ if (name === undefined) computedWrites.push(write);
70
+ else writeIndex(name).writes.add(write);
71
+ }
72
+ if (node.left.type !== 'Identifier') return;
73
+ lookup(node, node.left.name)?.push(value);
74
+ });
75
+ // Resolve each expression once into a shared dataflow graph. Dependencies
76
+ // are re-evaluated only when they gain a value, so cyclic aliases converge
77
+ // instead of exploring every possible path through member assignments.
78
+ const expressionResults = new WeakMap(), expressionStates = new WeakMap(), stringStates = new WeakMap(), writeStates = new WeakMap(), pending = new Set();
79
+ const states = kind => kind === 'strings' ? stringStates : expressionStates;
80
+ let evaluating;
81
+ const state = (map, node, kind) => {
82
+ let result = map.get(node);
83
+ if (!result) {
84
+ result = {node, kind, values:new Set(), users:new Set()};
85
+ map.set(node, result); pending.add(result);
86
+ }
87
+ if (evaluating) result.users.add(evaluating);
88
+ return result;
89
+ };
90
+ const read = (node, kind = 'expressions') => node ? state(states(kind), node, kind).values : new Set();
91
+ const keys = node => propertyNames(node, key => read(key, 'strings'));
92
+ const memberWrites = name => {
93
+ const index = writeIndex(name);
94
+ if (evaluating) index.users.add(evaluating);
95
+ return index.writes;
96
+ };
97
+ // A computed write joins the same fixed point as its key's bindings. Index
98
+ // each discovered key once and wake only readers of that member name.
99
+ for (const write of computedWrites) state(writeStates, write, 'writes');
100
+ function indexWrite(write) {
101
+ const names = keys(write.left);
102
+ for (const name of names) {
103
+ const index = writeIndex(name);
104
+ if (index.writes.has(write)) continue;
105
+ index.writes.add(write);
106
+ for (const user of index.users) pending.add(user);
107
+ }
108
+ return names;
109
+ }
110
+ const isClass = node => ['ClassDeclaration','ClassExpression'].includes(node.type);
111
+ function classProperties(constructor, wanted, isStatic, fields, seen = new Set()) {
112
+ const found = new Map();
113
+ if (!isClass(constructor) || seen.has(constructor)) return found;
114
+ seen = new Set(seen).add(constructor);
115
+ let unknownKey = false;
116
+ for (const property of constructor.body.body) {
117
+ if (Boolean(property.static) !== isStatic || (fields !== undefined && (property.type === 'PropertyDefinition') !== fields)) continue;
118
+ const names = keys(property);
119
+ if (property.computed && !names.length) unknownKey = true;
120
+ for (const name of wanted) if (names.includes(name)) {
121
+ // Static fields initialize after methods even when written before them.
122
+ const previous = found.get(name)?.[0];
123
+ if (property.type === 'PropertyDefinition' || previous?.type !== 'PropertyDefinition') found.set(name, [property]);
124
+ }
125
+ }
126
+ const inherited = wanted.filter(name => !found.has(name));
127
+ // Wait for a computed override's key instead of prematurely retaining the
128
+ // inherited definition in the monotone graph. Unknown keys stay unknown.
129
+ if (inherited.length && !unknownKey) for (const parent of read(constructor.superClass)) {
130
+ for (const [name, properties] of classProperties(parent, inherited, isStatic, fields, seen)) found.set(name, [...(found.get(name) ?? []), ...properties]);
131
+ }
132
+ return found;
133
+ }
134
+ function classMembers(constructor, names, isStatic) {
135
+ if (isStatic) return [...classProperties(constructor, names, true).values()].flat();
136
+ // Instance fields shadow prototype methods, including a method declared by
137
+ // a subclass. Within each category the nearest declaration wins.
138
+ const fields = classProperties(constructor, names, false, true);
139
+ const methods = classProperties(constructor, names.filter(name => !fields.has(name)), false, false);
140
+ return [...fields.values(), ...methods.values()].flat();
141
+ }
142
+ function expressionValues(node) {
143
+ if (node.type === 'Identifier') {
144
+ const values = lookup(node, node.name);
145
+ return values?.length ? values.flatMap(value => [...read(value)]) : [node];
146
+ }
147
+ if (node.type === 'MemberExpression') {
148
+ const names = keys(node);
149
+ const objects = read(node.object), members = [node];
150
+ const properties = items => {
151
+ for (const property of items) if (keys(property).some(key => names.includes(key))) members.push(...read(property.value));
152
+ };
153
+ for (const object of objects) {
154
+ if (object.type === 'ArrayExpression') for (const key of names) members.push(...read(object.elements[Number(key)]));
155
+ if (object.type === 'ObjectExpression') properties(object.properties);
156
+ if (isClass(object)) properties(classMembers(object, names, true));
157
+ if (object.type === 'NewExpression') for (const constructor of read(object.callee)) {
158
+ if (isClass(constructor)) properties(classMembers(constructor, names, false));
159
+ }
160
+ }
161
+ for (const key of names) for (const write of memberWrites(key)) {
162
+ if (write.left !== node && [...read(write.left.object)].some(object => objects.has(object))) members.push(...read(write.right));
163
+ }
164
+ return members;
165
+ }
166
+ if (node.type === 'ConditionalExpression') return [...read(node.consequent), ...read(node.alternate)];
167
+ if (node.type === 'LogicalExpression') return [...read(node.left), ...read(node.right)];
168
+ if (node.type === 'SequenceExpression') return read(node.expressions.at(-1));
169
+ if (node.type === 'AssignmentExpression') return read(assigned.get(node));
170
+ return [node];
171
+ }
172
+ function stringValues(node, seen = new Set()) {
173
+ if (!node || seen.has(node)) return [];
174
+ seen = new Set(seen).add(node);
175
+ const value = stringValue(node);
176
+ if (value !== undefined) return [value];
177
+ if (node.type === 'BinaryExpression' && node.operator === '+') return finite(stringValues(node.left, seen).flatMap(left => stringValues(node.right, seen).map(right => left + right)));
178
+ if (node.type === 'TemplateLiteral') {
179
+ let values = [node.quasis[0].value.cooked ?? ''];
180
+ for (let i = 0; i < node.expressions.length; i++) values = finite(values.flatMap(left => stringValues(node.expressions[i], seen).map(right => left + right + (node.quasis[i + 1].value.cooked ?? ''))));
181
+ return values;
182
+ }
183
+ if (node.type === 'CallExpression' && ['decodeURI','decodeURIComponent','atob'].includes(node.callee.name)) return stringValues(node.arguments[0], seen).flatMap(value => {
184
+ try {return [node.callee.name === 'atob' ? Buffer.from(value,'base64').toString('utf8') : decodeURIComponent(value)];} catch {return [];}
185
+ });
186
+ // Expand only the finite syntax graph. Recursive string construction has
187
+ // an unknown tail, not an ever-growing set of invented complete strings.
188
+ // Alias states already contain their transitive values; unresolved member
189
+ // identities contain no additional strings and must not be expanded again.
190
+ return finite([...read(node)].filter(value => value !== node && !['Identifier','MemberExpression'].includes(value.type)).flatMap(value => stringValues(value, seen)));
191
+ }
192
+ function resolve(node, kind) {
193
+ if (!node) return [];
194
+ const result = state(states(kind), node, kind);
195
+ for (const next of pending) {
196
+ pending.delete(next); evaluating = next;
197
+ const values = next.kind === 'writes' ? indexWrite(next.node) : next.kind === 'strings' ? stringValues(next.node) : expressionValues(next.node);
198
+ let changed = false;
199
+ for (const value of values) if (!next.values.has(value)) { next.values.add(value); changed = true; }
200
+ if (next.kind === 'strings') finite([...next.values]);
201
+ if (changed) for (const user of next.users) pending.add(user);
202
+ }
203
+ evaluating = undefined;
204
+ return [...result.values];
205
+ }
206
+ function expressions(node) {
207
+ if (!node) return [];
208
+ if (expressionResults.has(node)) return expressionResults.get(node);
209
+ const values = resolve(node, 'expressions').filter(value => {
210
+ if (value.type !== 'MemberExpression') return true;
211
+ // A member is its own unresolved identity until a value reaches it. Keep
212
+ // unresolved cycles, but remove that identity after resolving an alias.
213
+ return ![...expressionStates.get(value).values].some(other => other !== value && (other.type !== 'MemberExpression' || !expressionStates.get(other)?.values.has(value)));
214
+ });
215
+ // Indexing is complete and every dependency has settled before caching.
216
+ expressionResults.set(node, values);
217
+ return values;
218
+ }
219
+ const strings = node => resolve(node, 'strings');
220
+ const names = node => propertyNames(node, strings);
221
+ const origins = expressions;
222
+ const localClass = node => {
223
+ const values = expressions(node);
224
+ return values.length > 0 && values.every(value => {
225
+ const constructors = value.type === 'NewExpression' ? expressions(value.callee) : [value];
226
+ return constructors.length > 0 && constructors.every(isClass);
227
+ });
228
+ };
229
+ // Recognize browser globals through aliases without mistaking library methods
230
+ // or shadowed parameters for those APIs.
231
+ function global(node, name, seen = new Set()) {
232
+ if (!node || seen.has(node)) return false;
233
+ seen = new Set(seen).add(node);
234
+ return origins(node).some(value => {
235
+ if (value.type === 'Identifier') return value.name === name && !lookup(value, value.name);
236
+ return value.type === 'MemberExpression' && names(value).includes(name) && ['window','globalThis','self'].some(root => global(value.object, root, seen));
237
+ });
238
+ }
239
+ // A runtime suffix does not erase a known origin or route at a resource sink.
240
+ // Retain only the prefix before the first unknown value; later fragments are
241
+ // not a trustworthy prefix. Complete values still use ordinary file checks.
242
+ const alternatives = values => finite(values, value => JSON.stringify(value));
243
+ const combine = (left, right) => alternatives(left.flatMap(start => start.complete ? right.map(end => ({value:start.value + end.value, complete:end.complete})) : [start]));
244
+ function resources(node, seen = new Set()) {
245
+ const unknown = [{value:'', complete:false}];
246
+ if (!node || seen.has(node)) return unknown;
247
+ seen = new Set(seen).add(node);
248
+ const value = stringValue(node);
249
+ if (value !== undefined) return [{value, complete:true}];
250
+ if (node.type === 'BinaryExpression' && node.operator === '+') return combine(resources(node.left, seen), resources(node.right, seen));
251
+ if (node.type === 'TemplateLiteral') {
252
+ let values = [{value:node.quasis[0].value.cooked ?? '', complete:true}];
253
+ for (let i = 0; i < node.expressions.length; i++) values = combine(combine(values, resources(node.expressions[i], seen)), [{value:node.quasis[i + 1].value.cooked ?? '', complete:true}]);
254
+ return values;
255
+ }
256
+ if (node.type === 'NewExpression' && global(node.callee, 'Request')) return resources(node.arguments[0], seen);
257
+ if (node.type === 'NewExpression' && global(node.callee, 'URL')) {
258
+ const targets = resources(node.arguments[0], seen), bases = resources(node.arguments[1], seen);
259
+ const written = [...memberWrites('href')].filter(write => expressions(write.left.object).includes(node)).flatMap(write => resources(write.right, seen));
260
+ return alternatives([...written, ...targets.flatMap(target => {
261
+ // Absolute targets do not depend on the base. Incomplete targets retain
262
+ // their known prefix, including a foreign origin or an instance subtree.
263
+ if (/^[a-z][a-z0-9+.-]*:/i.test(target.value)) return [target];
264
+ if (!node.arguments[1]) return unknown;
265
+ return bases.flatMap(base => {
266
+ if (!base.complete) {
267
+ if (target.value && /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(base.value)) return [base];
268
+ return target.value.startsWith('/') ? [target] : unknown;
269
+ }
270
+ try {
271
+ if (!target.value && !target.complete) return unknown;
272
+ return [{value:new URL(target.value, base.value).href, complete:target.complete}];
273
+ } catch { return unknown; }
274
+ });
275
+ })]);
276
+ }
277
+ if (node.type === 'MemberExpression' && names(node).some(name => ['href','url'].includes(name))) {
278
+ const objects = expressions(node.object), values = objects.flatMap(object => object.type === 'NewExpression' && (global(object.callee, 'URL') || global(object.callee, 'Request')) ? resources(object, seen) : []);
279
+ if (values.length) return alternatives(values);
280
+ }
281
+ if (node.type === 'CallExpression' && names(node.callee).some(name => ['toString','toJSON'].includes(name))) {
282
+ const values = expressions(node.callee.object).flatMap(object => object.type === 'NewExpression' && global(object.callee, 'URL') ? resources(object, seen) : []);
283
+ if (values.length) return alternatives(values);
284
+ }
285
+ const resolved = expressions(node).filter(value => value !== node);
286
+ if (resolved.length) return alternatives(resolved.flatMap(value => resources(value, seen)));
287
+ const complete = strings(node);
288
+ return complete.length ? complete.map(value => ({value, complete:true})) : unknown;
289
+ }
290
+ return {strings, names, resources, expressions, origins, global, localClass};
291
+ }
@@ -0,0 +1,36 @@
1
+ import { memberName } from './site-syntax.mjs';
2
+
3
+ // Follow actual browser object provenance. An object's field named `href`,
4
+ // or a URL parser's `href` setter, does not make that object a DOM element.
5
+ export function browserObjects({expressions, origins, strings, global}) {
6
+ const window = node => ['window','globalThis','self'].some(name => global(node, name));
7
+ const document = node => global(node, 'document');
8
+ const location = node => global(node, 'location') || origins(node).some(value => memberName(value) === 'location' && (window(value.object) || document(value.object)));
9
+ const constructed = (node, name) => expressions(node).some(value => value.type === 'NewExpression' && global(value.callee, name));
10
+ const queries = new Set(['querySelector','querySelectorAll','getElementById','getElementsByTagName','getElementsByClassName','getElementsByName','createElement','createElementNS']);
11
+ const children = new Set(['body','head','documentElement','activeElement','firstChild','lastChild','firstElementChild','lastElementChild','nextSibling','previousSibling','nextElementSibling','previousElementSibling','parentNode','parentElement','children','childNodes','forms','images','links','content','contentDocument']);
12
+ function dom(node, seen = new Set()) {
13
+ if (!node || seen.has(node)) return false;
14
+ seen = new Set(seen).add(node);
15
+ return expressions(node).some(value => {
16
+ if (document(value)) return true;
17
+ if (value.type === 'NewExpression') return ['Image','Audio','Option'].some(name => global(value.callee, name));
18
+ if (value.type === 'CallExpression') {
19
+ const method = memberName(value.callee), object = value.callee.object;
20
+ return (queries.has(method) || ['closest','cloneNode','item','namedItem'].includes(method)) && dom(object, seen);
21
+ }
22
+ if (value.type !== 'MemberExpression') return false;
23
+ return (children.has(memberName(value)) || value.computed) && dom(value.object, seen);
24
+ });
25
+ }
26
+ function anchor(node) {
27
+ return expressions(node).some(value => {
28
+ if (value.type !== 'CallExpression' || !dom(value.callee.object)) return false;
29
+ const method = memberName(value.callee);
30
+ if (['createElement','createElementNS','getElementsByTagName'].includes(method)) return strings(value.arguments[method === 'createElementNS' ? 1 : 0]).some(tag => /^(?:a|area)$/i.test(tag));
31
+ return ['querySelector','closest'].includes(method) && strings(value.arguments[0]).some(selector => /^(?:a|area)(?:[.#[:]|$)/i.test(selector));
32
+ });
33
+ }
34
+ const style = node => expressions(node).some(value => memberName(value) === 'style' && dom(value.object));
35
+ return {window, document, location, constructed, dom, anchor, style};
36
+ }
@@ -0,0 +1,111 @@
1
+ import { lstat, readdir, readFile } from 'node:fs/promises';
2
+ import { join, posix } from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { privateDataScanner, decodedText } from './site-data.mjs';
6
+ import { javascriptContent } from './site-references.mjs';
7
+ import { javascriptStrings } from './site-syntax.mjs';
8
+ import { markupReferences, markupStrings, htmlElements, cssStrings } from './site-markup.mjs';
9
+ import { refuse, RerError } from './errors.mjs';
10
+ import { DEV_AI_MARKER, DEV_LAYER_MARKER } from './dev-identity.mjs';
11
+
12
+ // What a run site may hold: static pages and the files they use, served as
13
+ // Cloudflare static assets with default HTML handling. Never server code,
14
+ // Wrangler configuration, migrations, settings, local data or owner data.
15
+ const FORBIDDEN = /^(?:wrangler\.(?:json|jsonc|toml)|_worker\.js|_routes\.json|_headers|_redirects|.*\.(?:sql|rer|db|sqlite|sqlite3|env|map))$/i;
16
+ // Routes that exist only on an installed instance.
17
+ export const INSTANCE_ROUTES = ['/signin', '/sign-in', '/login', '/setup', '/app', '/auth', '/api', '/__dev', '/health', '/.well-known'];
18
+ const MAX_FILE = 25 * 1024 * 1024, MAX_FILES = 20000;
19
+
20
+ /** Every file, as a site path ("run.html") with its bytes. */
21
+ async function files(folder) {
22
+ const found = new Map();
23
+ async function walk(directory, prefix) {
24
+ for (const name of (await readdir(directory)).sort()) {
25
+ const path = join(directory, name), site = prefix + name, status = await lstat(path);
26
+ if (name.startsWith('.')) throw refuse(`The run site holds a hidden file: ${site}. It contains only public pages and their files.`);
27
+ if (status.isSymbolicLink() || (!status.isFile() && !status.isDirectory())) throw refuse(`The run site holds a link or special file: ${site}.`);
28
+ if (status.isDirectory()) { await walk(path, site + '/'); continue; }
29
+ if (FORBIDDEN.test(name)) throw refuse(`The run site holds ${site}, which is not a static page or asset. Server code, configuration, migrations and data never go in it.`);
30
+ if (status.size > MAX_FILE) throw refuse(`The run site file ${site} is larger than 25 MiB.`);
31
+ found.set(site, await readFile(path));
32
+ if (found.size > MAX_FILES) throw refuse('The run site holds more than 20,000 files.');
33
+ }
34
+ }
35
+ await walk(folder, '');
36
+ return found;
37
+ }
38
+
39
+ const safeDecode = path => { try { return decodeURI(path); } catch { return path; } };
40
+
41
+ export function identityPattern(value) {
42
+ const escaped = value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
43
+ const word = '[\\p{L}\\p{M}\\p{N}_]', mailbox = value.includes('@');
44
+ const left = mailbox ? "[\\p{L}\\p{M}\\p{N}_.!#$%&'*+/=?^`{|}~@-]" : word;
45
+ const right = mailbox ? '[\\p{L}\\p{M}\\p{N}_@-]|\\.[\\p{L}\\p{M}\\p{N}_-]' : word;
46
+ // Paired prose quotes delimit the whole mailbox. An apostrophe inside a
47
+ // longer local part (prefix'owner@example.test) must keep its old boundary.
48
+ const quoted = mailbox ? `|(?<!\\\\)'${escaped}'` : '';
49
+ return {mailbox, pattern:new RegExp(`(?<!${left})(?:${escaped}(?!${right})${quoted})`,mailbox ? 'iu' : 'u')};
50
+ }
51
+
52
+ /** How Cloudflare's static assets (auto-trailing-slash) answer a path, or null. */
53
+ export function servedFile(names, pathname) {
54
+ const path = pathname.replace(/^\/+/, '');
55
+ if (!path) return names.has('index.html') ? 'index.html' : null;
56
+ if (names.has(path) && !path.endsWith('.html')) return path;
57
+ const bare = path.replace(/\/$/, '');
58
+ if (names.has(`${bare}.html`)) return `${bare}.html`;
59
+ if (names.has(`${bare}/index.html`)) return `${bare}/index.html`;
60
+ return null;
61
+ }
62
+
63
+ /**
64
+ * Refuse a run site folder that is not exactly static pages and the files they
65
+ * use: an index and a Run page, every same-origin link resolving, no link to an
66
+ * instance-only route, nothing fetched from another origin, no dev layer, and
67
+ * none of the given private values (owner identity, secrets, the dev key).
68
+ */
69
+ export async function checkSite(folder, { privateValues = [], privateIdentities = [], root } = {}) {
70
+ const all = await files(folder), names = new Set(all.keys());
71
+ if (!names.has('index.html')) throw refuse('The run site has no index.html (its homepage).');
72
+ if (!servedFile(names, '/run')) throw refuse('The run site has no /run page.');
73
+ const markers = [DEV_LAYER_MARKER, DEV_AI_MARKER].map(value => Buffer.from(value));
74
+ const containsPrivateData = privateDataScanner(privateValues, privateIdentities);
75
+ let parse;
76
+ if (root) {
77
+ const require = createRequire(join(root, 'package.json'));
78
+ ({parseAst:parse} = await import(pathToFileURL(require.resolve('vite')).href));
79
+ }
80
+ const problems = [], unresolved = [];
81
+ for (const [site, bytes] of all) {
82
+ if (markers.some(marker => bytes.includes(marker))) throw refuse(`The run site file ${site} contains the local-only dev layer.`);
83
+ const html = /\.(?:html|svg)$/.test(site), css = site.endsWith('.css'), js = /\.[cm]?js$/.test(site);
84
+ const text = bytes.toString('utf8'), trees = js && parse ? [parse(text)] : [], literals = css ? cssStrings(text) : html ? markupStrings(text) : [];
85
+ if (html) for (const {tag, attributes, content} of htmlElements(text)) {
86
+ if (tag === 'script' && !attributes.has('src') && parse && /^(?:|module|(?:text|application)\/(?:java|ecma)script)$/i.test(attributes.get('type') ?? '')) trees.push(parse(content));
87
+ }
88
+ const scripts = trees.map(javascriptContent), strings = trees.flatMap(javascriptStrings);
89
+ if (containsPrivateData(bytes, [...literals, ...strings, ...strings.flatMap(markupStrings), ...scripts.flatMap(script => script.literals)])) throw new RerError('site_private_data', `The run site file ${site} contains this installation's private data (owner identity or a secret). The run site renders only edition identity.`, 4);
90
+ if (!html && !css && !js) continue;
91
+ const refs = [...(js ? [] : markupReferences(text, html)), ...scripts.flatMap(script => script.references)];
92
+ for (const script of scripts) for (const {kind} of script.unresolved) unresolved.push({asset:site, kind});
93
+ for (const reference of refs) {
94
+ const url = decodedText(reference.url), {navigates} = reference;
95
+ if (!url || /^(?:#|mailto:|tel:|data:|javascript:void)/i.test(url)) continue;
96
+ if (/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(url)) {
97
+ if (!navigates) problems.push(`${site} fetches ${url} from another origin`);
98
+ continue;
99
+ }
100
+ const pathPrefix = safeDecode(url.replace(/[?#].*$/, ''));
101
+ const pathname = posix.resolve(reference.documentRelative ? '/' : '/' + posix.dirname(site), pathPrefix);
102
+ // An unfinished `/api` could become `/apiculture`; a slash, query or
103
+ // fragment already fixes the instance path even when its tail is runtime.
104
+ const boundary = !reference.dynamic || /[?#]/.test(url) || pathPrefix.endsWith('/');
105
+ if (INSTANCE_ROUTES.some(route => (pathname === route && boundary) || pathname.startsWith(route + '/'))) problems.push(`${site} links to ${pathname}, which exists only on an installed instance`);
106
+ else if (!reference.dynamic && !servedFile(names, safeDecode(pathname))) problems.push(`${site} links to ${pathname}, which the site does not have`);
107
+ }
108
+ }
109
+ if (problems.length) throw refuse(`The run site has broken or out-of-site references: ${problems.slice(0, 8).join('; ')}${problems.length > 8 ? `; and ${problems.length - 8} more` : ''}.`);
110
+ return { files: names.size, pages: [...names].filter(name => name.endsWith('.html')).length, references:{unresolved} };
111
+ }
@@ -0,0 +1,50 @@
1
+ import { mkdir, writeFile, readFile, rm } from 'node:fs/promises';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { clientInputGuard } from './site-inputs.mjs';
4
+
5
+ // A separate browser build, using the seed's plugins. Only the graph reachable
6
+ // from its named entries ships; an external server import in that graph fails.
7
+ export async function writeSiteAsset(folder, name, data) {
8
+ if (!name.startsWith('site-assets/') || name.split('/').includes('..')) throw Error('Compiled output must stay under site-assets/.');
9
+ const file = join(folder,name), bytes = Buffer.from(data);
10
+ await mkdir(dirname(file),{recursive:true});
11
+ try { await writeFile(file,bytes,{flag:'wx'}); }
12
+ catch (error) {
13
+ if (error.code !== 'EEXIST') throw error;
14
+ if (!bytes.equals(await readFile(file))) throw Error(`Conflicting compiled site asset ${name}.`);
15
+ }
16
+ }
17
+
18
+ export async function buildClients(vite, root, folder, { entries = {}, config, privatePaths = [] } = {}) {
19
+ if (!Object.keys(entries).length) return {clients:{},styles:[]};
20
+ const guard = await clientInputGuard(root, privatePaths, async code => {
21
+ await writeFile(`${folder}.refusal`, code);
22
+ throw Error(code === 'site_private_input' ? 'Run site client imports a private or outside-seed file.' : 'Run site client imports a server-only module.');
23
+ }, vite);
24
+ const scratch = `${folder}.client`;
25
+ try {
26
+ const built = await vite.build({root, plugins:[guard], configFile:config ? resolve(root,config) : false, envFile:false, logLevel:'error', mode:'production',
27
+ build:{ssr:false, lib:false, outDir:scratch, write:false, copyPublicDir:false, emptyOutDir:true, assetsDir:'site-assets', sourcemap:false, reportCompressedSize:false, watch:null,
28
+ rollupOptions:{input:Object.fromEntries(Object.entries(entries).map(([name,path]) => [name,resolve(root,path)])), output:{entryFileNames:'site-assets/[name]-[hash].js',chunkFileNames:'site-assets/[name]-[hash].js'}}}});
29
+ const output = (Array.isArray(built) ? built : [built]).flatMap(result => result.output ?? []);
30
+ const chunks = new Map(output.filter(item => item.type === 'chunk').map(item => [item.fileName,item]));
31
+ const clients = {}, shipped = new Set();
32
+ const visit = file => {
33
+ if (shipped.has(file)) return;
34
+ const chunk = chunks.get(file);
35
+ if (!chunk) throw Error(`Run site client imports ${file}, which is not bundled for the browser. Remove its server dependency or bundle it in the client config.`);
36
+ shipped.add(file);
37
+ for (const dependency of [...chunk.imports,...chunk.dynamicImports]) visit(dependency);
38
+ };
39
+ for (const name of Object.keys(entries)) {
40
+ const entry = output.find(item => item.type === 'chunk' && item.isEntry && item.name === name);
41
+ if (!entry) throw Error(`Run site client ${name} produced no entry chunk.`);
42
+ clients[name] = '/' + entry.fileName; visit(entry.fileName);
43
+ }
44
+ for (const item of output) {
45
+ if (item.type === 'chunk' && !shipped.has(item.fileName)) continue;
46
+ await writeSiteAsset(folder,item.fileName,item.type === 'chunk' ? item.code : item.source);
47
+ }
48
+ return {clients,styles:output.filter(item=>item.type==='asset'&&item.fileName.endsWith('.css')).map(item=>'/' + item.fileName)};
49
+ } finally { await rm(scratch,{recursive:true,force:true}); }
50
+ }
@@ -0,0 +1,54 @@
1
+ import { identityPattern } from './site-check.mjs';
2
+
3
+ // HTML Living Standard named character references (Python html.entities.html5).
4
+ import entities from './site-entities.json' with {type:'json'};
5
+ const numericReplacements = {128:8364,130:8218,131:402,132:8222,133:8230,134:8224,135:8225,136:710,137:8240,138:352,139:8249,140:338,142:381,145:8216,146:8217,147:8220,148:8221,149:8226,150:8211,151:8212,152:732,153:8482,154:353,155:8250,156:339,158:382,159:376};
6
+ export function decodedText(text) {
7
+ return text.replace(/&#(?:x([\da-f]+)|(\d+));?|&([a-z][a-z0-9]*;?)/gi, (match, hex, decimal, name) => {
8
+ if (name) {
9
+ for (let length = name.length; length; length--) if (entities[name.slice(0,length)] !== undefined) return entities[name.slice(0,length)] + name.slice(length);
10
+ return match;
11
+ }
12
+ const code = parseInt(hex ?? decimal, hex ? 16 : 10);
13
+ return String.fromCodePoint(numericReplacements[code] ?? (!code || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff) ? 0xfffd : code));
14
+ }).replace(/(?:%[\da-f]{2})+/gi, value => {try {return decodeURIComponent(value);} catch {return value;}})
15
+ .replace(/\\(?:x([\da-f]{2})|u([\da-f]{4})|u\{([\da-f]+)\})/gi, (match, hex, unicode, point) => {
16
+ const code = parseInt(hex ?? unicode ?? point,16); return code <= 0x10ffff ? String.fromCodePoint(code) : match;
17
+ });
18
+ }
19
+
20
+ // Scan every emitted file, including binary assets. Decode textual forms as well
21
+ // as matching base64 directly, so encoding a registered value cannot publish it.
22
+ export function privateDataScanner(values, identities) {
23
+ const secrets = values.filter(value => typeof value === 'string' && value.length);
24
+ const owners = identities.filter(value => typeof value === 'string' && value.length).map(value => ({value, ...identityPattern(value)}));
25
+ const encodedValues = [...secrets, ...owners.map(item => item.value)].flatMap(value => [Buffer.from(value).toString('base64'), Buffer.from(value).toString('base64').replace(/=+$/, ''), Buffer.from(value).toString('base64url')]);
26
+ const base64 = encodedValues.map(value => new RegExp(`(?<![A-Za-z0-9+/_-])${value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![A-Za-z0-9+/_=-])`));
27
+ return (bytes, literalValues = []) => {
28
+ if (secrets.some(value => bytes.includes(Buffer.from(value)))) return true;
29
+ const raw = bytes.toString('utf8');
30
+ const forms = new Set([raw, ...literalValues]);
31
+ for (const value of [raw, ...literalValues]) {
32
+ let decoded = value;
33
+ for (let depth = 0; depth < 4; depth++) { decoded = decodedText(decoded); forms.add(decoded); }
34
+ }
35
+
36
+ for (const form of forms) {
37
+ // Complete string values preserve the whitespace that atob accepts, even
38
+ // when the payload spans lines or carries encoded whitespace.
39
+ const compact = form.replace(/[\t\n\f\r ]/g, '');
40
+ if (/^[A-Za-z0-9+/_-]{8,}={0,2}$/.test(compact) && compact.length % 4 !== 1) {
41
+ const plain = Buffer.from(compact, 'base64').toString('utf8');
42
+ forms.add(plain); forms.add(decodedText(plain));
43
+ }
44
+ if (secrets.some(value => form.includes(value)) || owners.some(({pattern}) => pattern.test(form))) return true;
45
+ if (base64.some(pattern => pattern.test(form))) return true;
46
+ // A base64 payload may include surrounding text, changing its alignment.
47
+ for (const match of form.matchAll(/[A-Za-z0-9+/_-]{8,}={0,2}/g)) {
48
+ const plain = Buffer.from(match[0], 'base64').toString('utf8');
49
+ if (secrets.some(value => plain.includes(value)) || owners.some(({pattern}) => pattern.test(plain))) return true;
50
+ }
51
+ }
52
+ return false;
53
+ };
54
+ }