@pwfabric/compiler 0.0.0-stage → 1.0.0-rc.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.
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Source screening — what a block or capability source may CONTAIN.
3
+ *
4
+ * ── THIS IS A HYGIENE CHECK, NOT A SECURITY BOUNDARY. ──
5
+ * It is a regex denylist over comment- and literal-masked text. Aliasing a global through a binding (`const g = globalThis;
6
+ * g['fe' + 'tch']`), `Reflect.get`, `top[...]` and similar spellings walk past
7
+ * it — the tests pin several as known gaps. Running untrusted block code safely
8
+ * is the HOST's job: an isolated origin or sandboxed iframe/worker for block
9
+ * bundles, plus a Content Security Policy. Do not treat a passing screen as
10
+ * permission to run a module with the host's privileges.
11
+ *
12
+ * Authorisation ("may this caller add a block") is the host's business. This
13
+ * answers the different question: once a source string reaches the compiler,
14
+ * may the module it becomes reach the ambient browser capabilities that turn
15
+ * "renders a component" into "reads your session and ships it somewhere"?
16
+ *
17
+ * A source that arrives as content — written by a model steered by text an
18
+ * attacker can influence, or posted directly by a caller — is compiled and then
19
+ * executed by every renderer that loads it, on the host's own origin, inside an
20
+ * authenticated session. So the module is constrained: it may render from its
21
+ * props; it may not reach network egress, credential stores or code
22
+ * construction.
23
+ *
24
+ * This narrows the blast radius. It does NOT stop prompt injection — see
25
+ * {@link screenSource}'s KNOWN GAPS for exactly what still gets through.
26
+ *
27
+ * The compiler does not call this for you: `compileAtom` compiles what it is
28
+ * given. A host that compiles untrusted source screens it first, and screens
29
+ * every companion the source reaches — `collectCompanions` does both.
30
+ *
31
+ * @module @pwfabric/compiler/screen
32
+ */
33
+ /**
34
+ * Module specifiers a screened source may import at VALUE level.
35
+ *
36
+ * DERIVED from the host import list (`blockBundleExternals()` over
37
+ * `BLOCK_HOST_IMPORTS` in `@pwfabric/core`), so the screen and
38
+ * the bundler can never disagree. A narrower hand-written list would refuse
39
+ * real packs, which import the runtime for the event bus, surface id and
40
+ * connection contexts. A specifier the bundler
41
+ * leaves external and every host maps for compiled blocks is a specifier the
42
+ * screen admits; one list says both.
43
+ *
44
+ * What still keeps a screened module from network egress, credential stores
45
+ * and code construction is layer 2 (the forbidden-capability scan) and the
46
+ * host's sandbox — not the narrowness of this list.
47
+ */
48
+ export declare const SCREEN_IMPORT_ALLOWLIST: readonly string[];
49
+ export type ScreenResult = {
50
+ readonly ok: true;
51
+ } | {
52
+ readonly ok: false;
53
+ readonly violations: readonly string[];
54
+ };
55
+ /**
56
+ * Blank out comments and (optionally) string/template/regex literal CONTENT,
57
+ * preserving byte offsets and newlines so reported line numbers stay true.
58
+ *
59
+ * Why this exists rather than a raw `source.includes('fetch(')`: a shipped
60
+ * first-party block's JSDoc says `same-origin fetch('/api/orders')`. A scan that
61
+ * did not strip comments would refuse a block for describing itself. Template
62
+ * SUBSTITUTIONS (`${...}`) are deliberately kept live — that is real code.
63
+ *
64
+ * The literal scanner must run even when `blankLiterals` is false, because a
65
+ * `//` or a `/` inside a string would otherwise be misread as a comment or a
66
+ * regex and swallow the rest of the file.
67
+ */
68
+ export declare function maskSource(src: string, blankLiterals: boolean): string;
69
+ /** Options for {@link screenSource}. */
70
+ export interface ScreenOptions {
71
+ /**
72
+ * The door for shared pack code. A value-level relative import is allowed
73
+ * only when this returns true for the specifier — i.e. the caller says it
74
+ * resolves to a file it will ship as a companion (`atoms/lib/*` or a
75
+ * `_shared-*` sibling) and will screen that file with this same function.
76
+ * Without the option every relative value import is rejected.
77
+ */
78
+ readonly allowRelativeImport?: (spec: string) => boolean;
79
+ }
80
+ /**
81
+ * Screen one source before it is allowed anywhere near the compiler. Returns
82
+ * every violation found (not just the first) so a repair loop gets a complete,
83
+ * actionable message.
84
+ *
85
+ * TWO LAYERS:
86
+ * 1. IMPORT ALLOWLIST — every value-level `import`/`export ... from` and bare
87
+ * `import '...'` specifier must be in {@link SCREEN_IMPORT_ALLOWLIST}.
88
+ * Relative specifiers are rejected at value level unless
89
+ * {@link ScreenOptions.allowRelativeImport} admits them, but permitted on
90
+ * `import type` / `export type` statements, which the compiler erases.
91
+ * 2. ESCAPE SCAN — the forbidden-capability patterns over the
92
+ * comment-and-literal-masked source.
93
+ *
94
+ * ── KNOWN GAPS. Read these before believing this closes anything. ──
95
+ *
96
+ * This is a DENYLIST over source text, not a sandbox, and it is deliberately
97
+ * incomplete. It does not stop:
98
+ *
99
+ * - **Prompt injection itself.** Attacker-controlled text still steers the
100
+ * model. All this changes is what the resulting module is allowed to do.
101
+ * - **`dangerouslySetInnerHTML` / `innerHTML`.** 30 of the 100 first-party
102
+ * blocks use `dangerouslySetInnerHTML` for inline SVG icon paths, so it is
103
+ * allowed — a screened block CAN inject arbitrary markup.
104
+ * - **Navigation-based exfiltration.** `window.location.href = ...` is used by
105
+ * first-party blocks for link handling, so it is allowed; a block can
106
+ * navigate the tab to an attacker URL with data in the query.
107
+ * - **Rendering hostile content into props/children**, phishing UI, and any
108
+ * purely-visual deception.
109
+ * - **Sufficiently indirect spellings.** The scan is textual: identifiers
110
+ * assembled at run time, property names built from arrays, aliasing a global
111
+ * through a permitted binding, or `top`/`parent` (excluded from the
112
+ * computed-access rule because they are common local names) can still reach
113
+ * a banned capability. Closing that class needs an execution sandbox (CSP +
114
+ * an isolated origin/worker for block bundles), not a string scan.
115
+ */
116
+ export declare function screenSource(source: string, opts?: ScreenOptions): ScreenResult;
117
+ /** Alternative name for `screenSource`. */
118
+ export declare const screenBlockSource: typeof screenSource;
119
+ /** Alternative name for `SCREEN_IMPORT_ALLOWLIST`. */
120
+ export declare const BLOCK_SOURCE_IMPORT_ALLOWLIST: readonly string[];
package/dist/screen.js ADDED
@@ -0,0 +1,338 @@
1
+ /**
2
+ * Source screening — what a block or capability source may CONTAIN.
3
+ *
4
+ * ── THIS IS A HYGIENE CHECK, NOT A SECURITY BOUNDARY. ──
5
+ * It is a regex denylist over comment- and literal-masked text. Aliasing a global through a binding (`const g = globalThis;
6
+ * g['fe' + 'tch']`), `Reflect.get`, `top[...]` and similar spellings walk past
7
+ * it — the tests pin several as known gaps. Running untrusted block code safely
8
+ * is the HOST's job: an isolated origin or sandboxed iframe/worker for block
9
+ * bundles, plus a Content Security Policy. Do not treat a passing screen as
10
+ * permission to run a module with the host's privileges.
11
+ *
12
+ * Authorisation ("may this caller add a block") is the host's business. This
13
+ * answers the different question: once a source string reaches the compiler,
14
+ * may the module it becomes reach the ambient browser capabilities that turn
15
+ * "renders a component" into "reads your session and ships it somewhere"?
16
+ *
17
+ * A source that arrives as content — written by a model steered by text an
18
+ * attacker can influence, or posted directly by a caller — is compiled and then
19
+ * executed by every renderer that loads it, on the host's own origin, inside an
20
+ * authenticated session. So the module is constrained: it may render from its
21
+ * props; it may not reach network egress, credential stores or code
22
+ * construction.
23
+ *
24
+ * This narrows the blast radius. It does NOT stop prompt injection — see
25
+ * {@link screenSource}'s KNOWN GAPS for exactly what still gets through.
26
+ *
27
+ * The compiler does not call this for you: `compileAtom` compiles what it is
28
+ * given. A host that compiles untrusted source screens it first, and screens
29
+ * every companion the source reaches — `collectCompanions` does both.
30
+ *
31
+ * @module @pwfabric/compiler/screen
32
+ */
33
+ import { blockBundleExternals } from '@pwfabric/core';
34
+ /**
35
+ * Module specifiers a screened source may import at VALUE level.
36
+ *
37
+ * DERIVED from the host import list (`blockBundleExternals()` over
38
+ * `BLOCK_HOST_IMPORTS` in `@pwfabric/core`), so the screen and
39
+ * the bundler can never disagree. A narrower hand-written list would refuse
40
+ * real packs, which import the runtime for the event bus, surface id and
41
+ * connection contexts. A specifier the bundler
42
+ * leaves external and every host maps for compiled blocks is a specifier the
43
+ * screen admits; one list says both.
44
+ *
45
+ * What still keeps a screened module from network egress, credential stores
46
+ * and code construction is layer 2 (the forbidden-capability scan) and the
47
+ * host's sandbox — not the narrowness of this list.
48
+ */
49
+ export const SCREEN_IMPORT_ALLOWLIST = Object.freeze([...blockBundleExternals()]);
50
+ /**
51
+ * Browser capabilities a screened source may not reach.
52
+ *
53
+ * Every entry was checked against a large set of real block components before
54
+ * being added: it appears in none of them, so none is the price of a
55
+ * legitimate block. The list is the "turns rendering into exfiltration or
56
+ * execution" set, not a general-purpose JS denylist:
57
+ *
58
+ * - arbitrary code construction (`eval`, `Function`, `.constructor(...)`)
59
+ * - network egress (`fetch`, `XMLHttpRequest`, `WebSocket`, `EventSource`,
60
+ * `sendBeacon`, `importScripts`, `Worker`, `RTCPeerConnection`)
61
+ * - cross-context messaging (`postMessage`)
62
+ * - credential/state reads (`document.cookie`, `localStorage`,
63
+ * `sessionStorage`, `indexedDB`, `caches`, `process.env`)
64
+ * - document rewriting (`document.write`/`writeln`/`domain`,
65
+ * `createElement('script')`)
66
+ * - the obvious spellings-around: computed member access on a global
67
+ * (`window[...]`, `globalThis[...]`, `self[...]`, `document[...]`) and
68
+ * module loading at run time (`import()`, `require()`).
69
+ *
70
+ * Patterns whose evidence lives INSIDE a string literal (the `createElement`
71
+ * pair) run against the comment-masked-but-literals-intact source instead. They
72
+ * are weak by construction — `createElement(tag)` with a computed `tag` walks
73
+ * straight past — but the literal spelling is the one a model actually emits.
74
+ */
75
+ const FORBIDDEN_SOURCE_PATTERNS = [
76
+ [/\beval\s*\(/, 'eval()'],
77
+ [/\bnew\s+Function\b/, 'new Function()'],
78
+ [/\bFunction\s*\(/, 'Function() as a constructor/call'],
79
+ [/\.\s*constructor\s*[[(]/, '.constructor access (Function-constructor escape)'],
80
+ [/\bfetch\s*\(/, 'fetch()'],
81
+ [/\bXMLHttpRequest\b/, 'XMLHttpRequest'],
82
+ [/\bWebSocket\b/, 'WebSocket'],
83
+ [/\bEventSource\b/, 'EventSource'],
84
+ [/\bsendBeacon\b/, 'navigator.sendBeacon()'],
85
+ [/\bimportScripts\s*\(/, 'importScripts()'],
86
+ [/\b(?:Shared)?Worker\s*\(/, 'Worker()'],
87
+ [/\bRTCPeerConnection\b/, 'RTCPeerConnection'],
88
+ [/\bpostMessage\s*\(/, 'postMessage()'],
89
+ [/\bdocument\s*\.\s*cookie\b/, 'document.cookie'],
90
+ [/\bdocument\s*\.\s*(?:write|writeln|domain)\b/, 'document.write / writeln / domain'],
91
+ [/\blocalStorage\b/, 'localStorage'],
92
+ [/\bsessionStorage\b/, 'sessionStorage'],
93
+ [/\bindexedDB\b/, 'indexedDB'],
94
+ [/\bcaches\s*\./, 'caches (CacheStorage)'],
95
+ [/\bprocess\s*\.\s*env\b/, 'process.env'],
96
+ [/\b(?:window|globalThis|self|document)\s*\[/, 'computed member access on a global object'],
97
+ [/\bimport\s*\(/, 'dynamic import()'],
98
+ [/\brequire\s*\(/, 'require()'],
99
+ ];
100
+ const FORBIDDEN_LITERAL_PATTERNS = [
101
+ [/\bcreateElement\s*\(\s*['"`]script['"`]/, "createElement('script')"],
102
+ [/\bcreateElement\s*\(\s*['"`]iframe['"`]/, "createElement('iframe')"],
103
+ ];
104
+ /**
105
+ * Blank out comments and (optionally) string/template/regex literal CONTENT,
106
+ * preserving byte offsets and newlines so reported line numbers stay true.
107
+ *
108
+ * Why this exists rather than a raw `source.includes('fetch(')`: a shipped
109
+ * first-party block's JSDoc says `same-origin fetch('/api/orders')`. A scan that
110
+ * did not strip comments would refuse a block for describing itself. Template
111
+ * SUBSTITUTIONS (`${...}`) are deliberately kept live — that is real code.
112
+ *
113
+ * The literal scanner must run even when `blankLiterals` is false, because a
114
+ * `//` or a `/` inside a string would otherwise be misread as a comment or a
115
+ * regex and swallow the rest of the file.
116
+ */
117
+ export function maskSource(src, blankLiterals) {
118
+ let out = '';
119
+ let i = 0;
120
+ let prev = '\n';
121
+ const blank = (ch) => (ch === '\n' ? '\n' : ' ');
122
+ const emit = (ch) => {
123
+ out += blankLiterals ? blank(ch) : ch;
124
+ };
125
+ while (i < src.length) {
126
+ const two = src.slice(i, i + 2);
127
+ if (two === '//') {
128
+ while (i < src.length && src[i] !== '\n') {
129
+ out += ' ';
130
+ i++;
131
+ }
132
+ continue;
133
+ }
134
+ if (two === '/*') {
135
+ while (i < src.length && src.slice(i, i + 2) !== '*/') {
136
+ out += blank(src[i]);
137
+ i++;
138
+ }
139
+ out += ' ';
140
+ i += 2;
141
+ continue;
142
+ }
143
+ const c = src[i];
144
+ if (c === "'" || c === '"') {
145
+ emit(c);
146
+ i++;
147
+ while (i < src.length && src[i] !== c) {
148
+ if (src[i] === '\\') {
149
+ emit(src[i]);
150
+ i++;
151
+ if (i >= src.length)
152
+ break;
153
+ }
154
+ emit(src[i]);
155
+ i++;
156
+ }
157
+ if (i < src.length) {
158
+ emit(src[i]);
159
+ i++;
160
+ }
161
+ prev = c;
162
+ continue;
163
+ }
164
+ if (c === '`') {
165
+ emit(c);
166
+ i++;
167
+ while (i < src.length) {
168
+ if (src[i] === '\\') {
169
+ emit(src[i]);
170
+ i++;
171
+ if (i >= src.length)
172
+ break;
173
+ emit(src[i]);
174
+ i++;
175
+ continue;
176
+ }
177
+ if (src[i] === '`') {
178
+ emit(src[i]);
179
+ i++;
180
+ break;
181
+ }
182
+ if (src.slice(i, i + 2) === '${') {
183
+ // Live code — copy verbatim, tracking brace depth back to the `}`.
184
+ out += '${';
185
+ i += 2;
186
+ let depth = 1;
187
+ while (i < src.length && depth > 0) {
188
+ const s = src[i];
189
+ if (s === '{')
190
+ depth++;
191
+ else if (s === '}')
192
+ depth--;
193
+ out += s;
194
+ i++;
195
+ }
196
+ continue;
197
+ }
198
+ emit(src[i]);
199
+ i++;
200
+ }
201
+ prev = '`';
202
+ continue;
203
+ }
204
+ // Regex literal: a `/` in a position where a value may start.
205
+ if (c === '/' && /[(,=:[!&|?{};+\-*%~^<>\n]/.test(prev)) {
206
+ emit(c);
207
+ i++;
208
+ while (i < src.length && src[i] !== '/' && src[i] !== '\n') {
209
+ if (src[i] === '\\') {
210
+ emit(src[i]);
211
+ i++;
212
+ if (i >= src.length)
213
+ break;
214
+ }
215
+ emit(src[i]);
216
+ i++;
217
+ }
218
+ if (i < src.length && src[i] === '/') {
219
+ emit(src[i]);
220
+ i++;
221
+ }
222
+ while (i < src.length && /[dgimsuy]/.test(src[i])) {
223
+ emit(src[i]);
224
+ i++;
225
+ }
226
+ prev = '/';
227
+ continue;
228
+ }
229
+ out += c;
230
+ if (!/\s/.test(c))
231
+ prev = c;
232
+ i++;
233
+ }
234
+ return out;
235
+ }
236
+ const IMPORT_FROM_RE = /(?:^|[\n;])[ \t]*(import|export)\b([ \t]+type\b)?([^;]*?)\bfrom[ \t]*['"]([^'"]+)['"]/g;
237
+ const BARE_IMPORT_RE = /(?:^|[\n;])[ \t]*import[ \t]*['"]([^'"]+)['"]/g;
238
+ function lineOf(src, index) {
239
+ return src.slice(0, index).split('\n').length;
240
+ }
241
+ /**
242
+ * Where the statement itself starts inside an import match. The import
243
+ * patterns open on the newline or `;` that precedes a statement, so the match
244
+ * index can sit one line early — or, at the very start of the file, not early
245
+ * at all. Skipping the separators gives the statement's own line either way.
246
+ */
247
+ function statementIndex(src, matchIndex) {
248
+ let i = matchIndex;
249
+ while (i < src.length && /[\n; \t]/.test(src[i]))
250
+ i++;
251
+ return i;
252
+ }
253
+ /**
254
+ * Screen one source before it is allowed anywhere near the compiler. Returns
255
+ * every violation found (not just the first) so a repair loop gets a complete,
256
+ * actionable message.
257
+ *
258
+ * TWO LAYERS:
259
+ * 1. IMPORT ALLOWLIST — every value-level `import`/`export ... from` and bare
260
+ * `import '...'` specifier must be in {@link SCREEN_IMPORT_ALLOWLIST}.
261
+ * Relative specifiers are rejected at value level unless
262
+ * {@link ScreenOptions.allowRelativeImport} admits them, but permitted on
263
+ * `import type` / `export type` statements, which the compiler erases.
264
+ * 2. ESCAPE SCAN — the forbidden-capability patterns over the
265
+ * comment-and-literal-masked source.
266
+ *
267
+ * ── KNOWN GAPS. Read these before believing this closes anything. ──
268
+ *
269
+ * This is a DENYLIST over source text, not a sandbox, and it is deliberately
270
+ * incomplete. It does not stop:
271
+ *
272
+ * - **Prompt injection itself.** Attacker-controlled text still steers the
273
+ * model. All this changes is what the resulting module is allowed to do.
274
+ * - **`dangerouslySetInnerHTML` / `innerHTML`.** 30 of the 100 first-party
275
+ * blocks use `dangerouslySetInnerHTML` for inline SVG icon paths, so it is
276
+ * allowed — a screened block CAN inject arbitrary markup.
277
+ * - **Navigation-based exfiltration.** `window.location.href = ...` is used by
278
+ * first-party blocks for link handling, so it is allowed; a block can
279
+ * navigate the tab to an attacker URL with data in the query.
280
+ * - **Rendering hostile content into props/children**, phishing UI, and any
281
+ * purely-visual deception.
282
+ * - **Sufficiently indirect spellings.** The scan is textual: identifiers
283
+ * assembled at run time, property names built from arrays, aliasing a global
284
+ * through a permitted binding, or `top`/`parent` (excluded from the
285
+ * computed-access rule because they are common local names) can still reach
286
+ * a banned capability. Closing that class needs an execution sandbox (CSP +
287
+ * an isolated origin/worker for block bundles), not a string scan.
288
+ */
289
+ export function screenSource(source, opts) {
290
+ const violations = [];
291
+ // Layer 2 runs over fully-masked source (comments + literal content gone).
292
+ const code = maskSource(source, true);
293
+ for (const [pattern, label] of FORBIDDEN_SOURCE_PATTERNS) {
294
+ const m = pattern.exec(code);
295
+ if (m) {
296
+ violations.push(`line ${lineOf(code, m.index)}: ${label} is not permitted in a block component`);
297
+ }
298
+ }
299
+ // Layer 1 runs over comment-masked-but-literals-intact source: the
300
+ // specifier itself lives inside quotes, but a commented-out import must not
301
+ // count. The literal-evidence patterns share that view.
302
+ const withStrings = maskSource(source, false);
303
+ for (const [pattern, label] of FORBIDDEN_LITERAL_PATTERNS) {
304
+ const lm = pattern.exec(withStrings);
305
+ if (lm) {
306
+ violations.push(`line ${lineOf(withStrings, lm.index)}: ${label} is not permitted in a block component`);
307
+ }
308
+ }
309
+ const specs = [];
310
+ IMPORT_FROM_RE.lastIndex = 0;
311
+ let m;
312
+ while ((m = IMPORT_FROM_RE.exec(withStrings)) !== null) {
313
+ specs.push({ typeOnly: m[2] !== undefined, spec: m[4], index: m.index });
314
+ }
315
+ BARE_IMPORT_RE.lastIndex = 0;
316
+ while ((m = BARE_IMPORT_RE.exec(withStrings)) !== null) {
317
+ specs.push({ typeOnly: false, spec: m[1], index: m.index });
318
+ }
319
+ for (const s of specs) {
320
+ if (s.typeOnly)
321
+ continue;
322
+ const line = lineOf(withStrings, statementIndex(withStrings, s.index));
323
+ if (s.spec.startsWith('.') && opts?.allowRelativeImport?.(s.spec))
324
+ continue;
325
+ if (s.spec.startsWith('.') || s.spec.startsWith('/')) {
326
+ violations.push(`line ${line}: relative import '${s.spec}' — a generated block is bundled as a single self-contained file; only \`import type\` may reference a sibling module`);
327
+ }
328
+ else if (!SCREEN_IMPORT_ALLOWLIST.includes(s.spec)) {
329
+ violations.push(`line ${line}: import '${s.spec}' is outside the block import allowlist (${SCREEN_IMPORT_ALLOWLIST.join(', ')})`);
330
+ }
331
+ }
332
+ return violations.length === 0 ? { ok: true } : { ok: false, violations };
333
+ }
334
+ /** Alternative name for `screenSource`. */
335
+ export const screenBlockSource = screenSource;
336
+ /** Alternative name for `SCREEN_IMPORT_ALLOWLIST`. */
337
+ export const BLOCK_SOURCE_IMPORT_ALLOWLIST = SCREEN_IMPORT_ALLOWLIST;
338
+ //# sourceMappingURL=screen.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"screen.js","sourceRoot":"","sources":["../src/screen.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAA;AAErD;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAsB,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,oBAAoB,EAAE,CAAC,CAAC,CAAA;AAMpG;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,yBAAyB,GAA6C;IAC1E,CAAC,aAAa,EAAE,QAAQ,CAAC;IACzB,CAAC,oBAAoB,EAAE,gBAAgB,CAAC;IACxC,CAAC,iBAAiB,EAAE,kCAAkC,CAAC;IACvD,CAAC,yBAAyB,EAAE,mDAAmD,CAAC;IAChF,CAAC,cAAc,EAAE,SAAS,CAAC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,CAAA","sourcesContent":["/**\n * Source screening — what a block or capability source may CONTAIN.\n *\n * ── THIS IS A HYGIENE CHECK, NOT A SECURITY BOUNDARY. ──\n * It is a regex denylist over comment- and literal-masked text. Aliasing a global through a binding (`const g = globalThis;\n * g['fe' + 'tch']`), `Reflect.get`, `top[...]` and similar spellings walk past\n * it — the tests pin several as known gaps. Running untrusted block code safely\n * is the HOST's job: an isolated origin or sandboxed iframe/worker for block\n * bundles, plus a Content Security Policy. Do not treat a passing screen as\n * permission to run a module with the host's privileges.\n *\n * Authorisation (\"may this caller add a block\") is the host's business. This\n * answers the different question: once a source string reaches the compiler,\n * may the module it becomes reach the ambient browser capabilities that turn\n * \"renders a component\" into \"reads your session and ships it somewhere\"?\n *\n * A source that arrives as content — written by a model steered by text an\n * attacker can influence, or posted directly by a caller — is compiled and then\n * executed by every renderer that loads it, on the host's own origin, inside an\n * authenticated session. So the module is constrained: it may render from its\n * props; it may not reach network egress, credential stores or code\n * construction.\n *\n * This narrows the blast radius. It does NOT stop prompt injection — see\n * {@link screenSource}'s KNOWN GAPS for exactly what still gets through.\n *\n * The compiler does not call this for you: `compileAtom` compiles what it is\n * given. A host that compiles untrusted source screens it first, and screens\n * every companion the source reaches — `collectCompanions` does both.\n *\n * @module @pwfabric/compiler/screen\n */\n\nimport { blockBundleExternals } from '@pwfabric/core'\n\n/**\n * Module specifiers a screened source may import at VALUE level.\n *\n * DERIVED from the host import list (`blockBundleExternals()` over\n * `BLOCK_HOST_IMPORTS` in `@pwfabric/core`), so the screen and\n * the bundler can never disagree. A narrower hand-written list would refuse\n * real packs, which import the runtime for the event bus, surface id and\n * connection contexts. A specifier the bundler\n * leaves external and every host maps for compiled blocks is a specifier the\n * screen admits; one list says both.\n *\n * What still keeps a screened module from network egress, credential stores\n * and code construction is layer 2 (the forbidden-capability scan) and the\n * host's sandbox — not the narrowness of this list.\n */\nexport const SCREEN_IMPORT_ALLOWLIST: readonly string[] = Object.freeze([...blockBundleExternals()])\n\nexport type ScreenResult =\n | { readonly ok: true }\n | { readonly ok: false; readonly violations: readonly string[] }\n\n/**\n * Browser capabilities a screened source may not reach.\n *\n * Every entry was checked against a large set of real block components before\n * being added: it appears in none of them, so none is the price of a\n * legitimate block. The list is the \"turns rendering into exfiltration or\n * execution\" set, not a general-purpose JS denylist:\n *\n * - arbitrary code construction (`eval`, `Function`, `.constructor(...)`)\n * - network egress (`fetch`, `XMLHttpRequest`, `WebSocket`, `EventSource`,\n * `sendBeacon`, `importScripts`, `Worker`, `RTCPeerConnection`)\n * - cross-context messaging (`postMessage`)\n * - credential/state reads (`document.cookie`, `localStorage`,\n * `sessionStorage`, `indexedDB`, `caches`, `process.env`)\n * - document rewriting (`document.write`/`writeln`/`domain`,\n * `createElement('script')`)\n * - the obvious spellings-around: computed member access on a global\n * (`window[...]`, `globalThis[...]`, `self[...]`, `document[...]`) and\n * module loading at run time (`import()`, `require()`).\n *\n * Patterns whose evidence lives INSIDE a string literal (the `createElement`\n * pair) run against the comment-masked-but-literals-intact source instead. They\n * are weak by construction — `createElement(tag)` with a computed `tag` walks\n * straight past — but the literal spelling is the one a model actually emits.\n */\nconst FORBIDDEN_SOURCE_PATTERNS: ReadonlyArray<readonly [RegExp, string]> = [\n [/\\beval\\s*\\(/, 'eval()'],\n [/\\bnew\\s+Function\\b/, 'new Function()'],\n [/\\bFunction\\s*\\(/, 'Function() as a constructor/call'],\n [/\\.\\s*constructor\\s*[[(]/, '.constructor access (Function-constructor escape)'],\n [/\\bfetch\\s*\\(/, 'fetch()'],\n [/\\bXMLHttpRequest\\b/, 'XMLHttpRequest'],\n [/\\bWebSocket\\b/, 'WebSocket'],\n [/\\bEventSource\\b/, 'EventSource'],\n [/\\bsendBeacon\\b/, 'navigator.sendBeacon()'],\n [/\\bimportScripts\\s*\\(/, 'importScripts()'],\n [/\\b(?:Shared)?Worker\\s*\\(/, 'Worker()'],\n [/\\bRTCPeerConnection\\b/, 'RTCPeerConnection'],\n [/\\bpostMessage\\s*\\(/, 'postMessage()'],\n [/\\bdocument\\s*\\.\\s*cookie\\b/, 'document.cookie'],\n [/\\bdocument\\s*\\.\\s*(?:write|writeln|domain)\\b/, 'document.write / writeln / domain'],\n [/\\blocalStorage\\b/, 'localStorage'],\n [/\\bsessionStorage\\b/, 'sessionStorage'],\n [/\\bindexedDB\\b/, 'indexedDB'],\n [/\\bcaches\\s*\\./, 'caches (CacheStorage)'],\n [/\\bprocess\\s*\\.\\s*env\\b/, 'process.env'],\n [/\\b(?:window|globalThis|self|document)\\s*\\[/, 'computed member access on a global object'],\n [/\\bimport\\s*\\(/, 'dynamic import()'],\n [/\\brequire\\s*\\(/, 'require()'],\n] as const\nconst FORBIDDEN_LITERAL_PATTERNS: ReadonlyArray<readonly [RegExp, string]> = [\n [/\\bcreateElement\\s*\\(\\s*['\"`]script['\"`]/, \"createElement('script')\"],\n [/\\bcreateElement\\s*\\(\\s*['\"`]iframe['\"`]/, \"createElement('iframe')\"],\n] as const\n\n/**\n * Blank out comments and (optionally) string/template/regex literal CONTENT,\n * preserving byte offsets and newlines so reported line numbers stay true.\n *\n * Why this exists rather than a raw `source.includes('fetch(')`: a shipped\n * first-party block's JSDoc says `same-origin fetch('/api/orders')`. A scan that\n * did not strip comments would refuse a block for describing itself. Template\n * SUBSTITUTIONS (`${...}`) are deliberately kept live — that is real code.\n *\n * The literal scanner must run even when `blankLiterals` is false, because a\n * `//` or a `/` inside a string would otherwise be misread as a comment or a\n * regex and swallow the rest of the file.\n */\nexport function maskSource(src: string, blankLiterals: boolean): string {\n let out = ''\n let i = 0\n let prev = '\\n'\n const blank = (ch: string): string => (ch === '\\n' ? '\\n' : ' ')\n const emit = (ch: string): void => {\n out += blankLiterals ? blank(ch) : ch\n }\n\n while (i < src.length) {\n const two = src.slice(i, i + 2)\n\n if (two === '//') {\n while (i < src.length && src[i] !== '\\n') {\n out += ' '\n i++\n }\n continue\n }\n if (two === '/*') {\n while (i < src.length && src.slice(i, i + 2) !== '*/') {\n out += blank(src[i] as string)\n i++\n }\n out += ' '\n i += 2\n continue\n }\n\n const c = src[i] as string\n\n if (c === \"'\" || c === '\"') {\n emit(c)\n i++\n while (i < src.length && src[i] !== c) {\n if (src[i] === '\\\\') {\n emit(src[i] as string)\n i++\n if (i >= src.length) break\n }\n emit(src[i] as string)\n i++\n }\n if (i < src.length) {\n emit(src[i] as string)\n i++\n }\n prev = c\n continue\n }\n\n if (c === '`') {\n emit(c)\n i++\n while (i < src.length) {\n if (src[i] === '\\\\') {\n emit(src[i] as string)\n i++\n if (i >= src.length) break\n emit(src[i] as string)\n i++\n continue\n }\n if (src[i] === '`') {\n emit(src[i] as string)\n i++\n break\n }\n if (src.slice(i, i + 2) === '${') {\n // Live code — copy verbatim, tracking brace depth back to the `}`.\n out += '${'\n i += 2\n let depth = 1\n while (i < src.length && depth > 0) {\n const s = src[i] as string\n if (s === '{') depth++\n else if (s === '}') depth--\n out += s\n i++\n }\n continue\n }\n emit(src[i] as string)\n i++\n }\n prev = '`'\n continue\n }\n\n // Regex literal: a `/` in a position where a value may start.\n if (c === '/' && /[(,=:[!&|?{};+\\-*%~^<>\\n]/.test(prev)) {\n emit(c)\n i++\n while (i < src.length && src[i] !== '/' && src[i] !== '\\n') {\n if (src[i] === '\\\\') {\n emit(src[i] as string)\n i++\n if (i >= src.length) break\n }\n emit(src[i] as string)\n i++\n }\n if (i < src.length && src[i] === '/') {\n emit(src[i] as string)\n i++\n }\n while (i < src.length && /[dgimsuy]/.test(src[i] as string)) {\n emit(src[i] as string)\n i++\n }\n prev = '/'\n continue\n }\n\n out += c\n if (!/\\s/.test(c)) prev = c\n i++\n }\n return out\n}\n\nconst IMPORT_FROM_RE = /(?:^|[\\n;])[ \\t]*(import|export)\\b([ \\t]+type\\b)?([^;]*?)\\bfrom[ \\t]*['\"]([^'\"]+)['\"]/g\nconst BARE_IMPORT_RE = /(?:^|[\\n;])[ \\t]*import[ \\t]*['\"]([^'\"]+)['\"]/g\n\nfunction lineOf(src: string, index: number): number {\n return src.slice(0, index).split('\\n').length\n}\n\n/**\n * Where the statement itself starts inside an import match. The import\n * patterns open on the newline or `;` that precedes a statement, so the match\n * index can sit one line early — or, at the very start of the file, not early\n * at all. Skipping the separators gives the statement's own line either way.\n */\nfunction statementIndex(src: string, matchIndex: number): number {\n let i = matchIndex\n while (i < src.length && /[\\n; \\t]/.test(src[i] as string)) i++\n return i\n}\n\n/** Options for {@link screenSource}. */\nexport interface ScreenOptions {\n /**\n * The door for shared pack code. A value-level relative import is allowed\n * only when this returns true for the specifier — i.e. the caller says it\n * resolves to a file it will ship as a companion (`atoms/lib/*` or a\n * `_shared-*` sibling) and will screen that file with this same function.\n * Without the option every relative value import is rejected.\n */\n readonly allowRelativeImport?: (spec: string) => boolean\n}\n\n/**\n * Screen one source before it is allowed anywhere near the compiler. Returns\n * every violation found (not just the first) so a repair loop gets a complete,\n * actionable message.\n *\n * TWO LAYERS:\n * 1. IMPORT ALLOWLIST — every value-level `import`/`export ... from` and bare\n * `import '...'` specifier must be in {@link SCREEN_IMPORT_ALLOWLIST}.\n * Relative specifiers are rejected at value level unless\n * {@link ScreenOptions.allowRelativeImport} admits them, but permitted on\n * `import type` / `export type` statements, which the compiler erases.\n * 2. ESCAPE SCAN — the forbidden-capability patterns over the\n * comment-and-literal-masked source.\n *\n * ── KNOWN GAPS. Read these before believing this closes anything. ──\n *\n * This is a DENYLIST over source text, not a sandbox, and it is deliberately\n * incomplete. It does not stop:\n *\n * - **Prompt injection itself.** Attacker-controlled text still steers the\n * model. All this changes is what the resulting module is allowed to do.\n * - **`dangerouslySetInnerHTML` / `innerHTML`.** 30 of the 100 first-party\n * blocks use `dangerouslySetInnerHTML` for inline SVG icon paths, so it is\n * allowed — a screened block CAN inject arbitrary markup.\n * - **Navigation-based exfiltration.** `window.location.href = ...` is used by\n * first-party blocks for link handling, so it is allowed; a block can\n * navigate the tab to an attacker URL with data in the query.\n * - **Rendering hostile content into props/children**, phishing UI, and any\n * purely-visual deception.\n * - **Sufficiently indirect spellings.** The scan is textual: identifiers\n * assembled at run time, property names built from arrays, aliasing a global\n * through a permitted binding, or `top`/`parent` (excluded from the\n * computed-access rule because they are common local names) can still reach\n * a banned capability. Closing that class needs an execution sandbox (CSP +\n * an isolated origin/worker for block bundles), not a string scan.\n */\nexport function screenSource(source: string, opts?: ScreenOptions): ScreenResult {\n const violations: string[] = []\n\n // Layer 2 runs over fully-masked source (comments + literal content gone).\n const code = maskSource(source, true)\n for (const [pattern, label] of FORBIDDEN_SOURCE_PATTERNS) {\n const m = pattern.exec(code)\n if (m) {\n violations.push(`line ${lineOf(code, m.index)}: ${label} is not permitted in a block component`)\n }\n }\n\n // Layer 1 runs over comment-masked-but-literals-intact source: the\n // specifier itself lives inside quotes, but a commented-out import must not\n // count. The literal-evidence patterns share that view.\n const withStrings = maskSource(source, false)\n for (const [pattern, label] of FORBIDDEN_LITERAL_PATTERNS) {\n const lm = pattern.exec(withStrings)\n if (lm) {\n violations.push(\n `line ${lineOf(withStrings, lm.index)}: ${label} is not permitted in a block component`\n )\n }\n }\n\n const specs: Array<{ typeOnly: boolean; spec: string; index: number }> = []\n IMPORT_FROM_RE.lastIndex = 0\n let m: RegExpExecArray | null\n while ((m = IMPORT_FROM_RE.exec(withStrings)) !== null) {\n specs.push({ typeOnly: m[2] !== undefined, spec: m[4] as string, index: m.index })\n }\n BARE_IMPORT_RE.lastIndex = 0\n while ((m = BARE_IMPORT_RE.exec(withStrings)) !== null) {\n specs.push({ typeOnly: false, spec: m[1] as string, index: m.index })\n }\n\n for (const s of specs) {\n if (s.typeOnly) continue\n const line = lineOf(withStrings, statementIndex(withStrings, s.index))\n if (s.spec.startsWith('.') && opts?.allowRelativeImport?.(s.spec)) continue\n if (s.spec.startsWith('.') || s.spec.startsWith('/')) {\n violations.push(\n `line ${line}: relative import '${s.spec}' — a generated block is bundled as a single self-contained file; only \\`import type\\` may reference a sibling module`\n )\n } else if (!SCREEN_IMPORT_ALLOWLIST.includes(s.spec)) {\n violations.push(\n `line ${line}: import '${s.spec}' is outside the block import allowlist (${SCREEN_IMPORT_ALLOWLIST.join(', ')})`\n )\n }\n }\n\n return violations.length === 0 ? { ok: true } : { ok: false, violations }\n}\n\n/** Alternative name for `screenSource`. */\nexport const screenBlockSource = screenSource\n/** Alternative name for `SCREEN_IMPORT_ALLOWLIST`. */\nexport const BLOCK_SOURCE_IMPORT_ALLOWLIST = SCREEN_IMPORT_ALLOWLIST\n"]}
@@ -0,0 +1,4 @@
1
+ /** This package's version — `dist/` and `src/` both sit one level below `package.json`. */
2
+ export declare const COMPILER_VERSION: string;
3
+ /** The esbuild version that produced the bytes. */
4
+ export declare const ESBUILD_VERSION: string;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Versions a caller records next to a compiled bundle.
3
+ *
4
+ * Same input + same compiler version + same esbuild version → identical bytes.
5
+ * Both versions are read at run time (not copied into a constant) so a release
6
+ * that bumps `package.json` cannot leave a stale number behind.
7
+ */
8
+ import { createRequire } from 'node:module';
9
+ import { version as esbuildVersion } from 'esbuild';
10
+ const require = createRequire(import.meta.url);
11
+ /** This package's version — `dist/` and `src/` both sit one level below `package.json`. */
12
+ export const COMPILER_VERSION = require('../package.json').version;
13
+ /** The esbuild version that produced the bytes. */
14
+ export const ESBUILD_VERSION = esbuildVersion;
15
+ //# sourceMappingURL=version.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAC3C,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,SAAS,CAAA;AAEnD,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;AAE9C,2FAA2F;AAC3F,MAAM,CAAC,MAAM,gBAAgB,GAAY,OAAO,CAAC,iBAAiB,CAAyB,CAAC,OAAO,CAAA;AAEnG,mDAAmD;AACnD,MAAM,CAAC,MAAM,eAAe,GAAW,cAAc,CAAA","sourcesContent":["/**\n * Versions a caller records next to a compiled bundle.\n *\n * Same input + same compiler version + same esbuild version → identical bytes.\n * Both versions are read at run time (not copied into a constant) so a release\n * that bumps `package.json` cannot leave a stale number behind.\n */\nimport { createRequire } from 'node:module'\nimport { version as esbuildVersion } from 'esbuild'\n\nconst require = createRequire(import.meta.url)\n\n/** This package's version — `dist/` and `src/` both sit one level below `package.json`. */\nexport const COMPILER_VERSION: string = (require('../package.json') as { version: string }).version\n\n/** The esbuild version that produced the bytes. */\nexport const ESBUILD_VERSION: string = esbuildVersion\n"]}
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Entry wrappers — the thin module the compiler actually bundles.
3
+ *
4
+ * Which template applies is decided by the kind's `entry` metadata in
5
+ * `@pwfabric/contracts` (`atomKindMeta(kind).entry`), not by
6
+ * ad-hoc "block vs capability vs connector" branches:
7
+ *
8
+ * - block (identity) → re-export the component and the definition under
9
+ * the stable names `Component` + `definition`, so the
10
+ * runtime's block module loader reads two fixed keys
11
+ * whatever the author named them.
12
+ * - capability (identity) → opaque `export *` (the handler contract is not
13
+ * normalised).
14
+ * - connector (sibling) → loader-contract adapter: `createConnector` that
15
+ * delegates to an explicit export, wraps an engine
16
+ * class (`prototype.query`), or calls/constructs the
17
+ * default export of the sibling `./<Name>`.
18
+ * - provider (sibling) → per-facet entry over the SHARED vendor motor
19
+ * (`../index`): binds the domain's entity map from
20
+ * `./<domain>` into the vendor engine class, or falls
21
+ * back to a vendor `create*` factory.
22
+ *
23
+ * @module @pwfabric/compiler/wrappers
24
+ */
25
+ import { type AtomKind } from '@pwfabric/contracts';
26
+ /**
27
+ * Context passed to the wrapper registry. `identity` kinds supply `sourceBase`
28
+ * (basename of the atom's own source, no extension); `sibling-generated` kinds
29
+ * supply `engineName` (connector `<Name>` / provider `<domain>`).
30
+ */
31
+ export interface WrapperContext {
32
+ readonly sourceBase?: string;
33
+ readonly engineName?: string;
34
+ }
35
+ /** Connector `<Name>` / provider `<domain>`: letters, digits, `_`, `-`. */
36
+ export declare function isValidEngineName(name: string): boolean;
37
+ /** Entry basename without extension: letters, digits, `_`, `-`, `.` — never `..`. */
38
+ export declare function isValidSourceBase(base: string): boolean;
39
+ /**
40
+ * The single wrapper registry, keyed off the kind's contract metadata.
41
+ * Throws on a name that fails {@link isValidEngineName} / {@link isValidSourceBase}.
42
+ */
43
+ export declare function buildWrapperSource(kind: AtomKind, ctx: WrapperContext): string;