source-boundaries.test.mjs (89723B)
1 import assert from 'node:assert/strict'; 2 import { spawnSync } from 'node:child_process'; 3 import { 4 copyFile, 5 cp, 6 lstat, 7 link, 8 mkdir, 9 mkdtemp, 10 readFile, 11 realpath, 12 rm, 13 symlink, 14 writeFile 15 } from 'node:fs/promises'; 16 import { tmpdir } from 'node:os'; 17 import path from 'node:path'; 18 import { fileURLToPath } from 'node:url'; 19 import { test } from 'node:test'; 20 21 test('CR007 and CR008-S4B exact private SDK removal and CR008-S4C2B Retry lifecycle cannot become an arbitrary remove capability', async () => { 22 await fixture(async ({ directory, put, execute }) => { 23 await isolateScriptDependencies(directory); 24 await cp(path.join(root, 'src'), path.join(directory, 'src'), { 25 recursive: true 26 }); 27 assert.equal(execute().status, 0); 28 const file = 'src/lib/nostr/private-pool.ts'; 29 const source = await readFile(path.join(root, file), 'utf8'); 30 assert.ok(source.includes('sdk.remove(relay)')); 31 assert.ok(source.includes('!publishing && !busy && !liveBusy')); 32 for (const mutation of [ 33 source + '\n export const unreviewedChange=1;\n', 34 source.replace('sdk.remove(relay)', 'sdk["remove"](relay)'), 35 source.replace('sdk.remove(relay)', 'sdk.remove(document.body)'), 36 source.replace('sdk.remove(relay)', '(sdk.remove)(relay)'), 37 source.replace('!publishing && !busy && !liveBusy', 'true') 38 ]) { 39 await put(file, mutation); 40 const result = execute(); 41 assert.notEqual(result.status, 0); 42 assert.match(result.stderr, /private relay removal source identity/); 43 } 44 await put(file, source); 45 await put('src/lib/nostr/copied-private-pool.ts', source); 46 assert.notEqual(execute().status, 0); 47 await rm(path.join(directory, 'src/lib/nostr/copied-private-pool.ts')); 48 await rm(path.join(directory, file)); 49 assert.notEqual(execute().status, 0); 50 await put(file, source); 51 await put( 52 'src/routes/+page.ts', 53 'const receiver=document.body;receiver.remove();' 54 ); 55 assert.notEqual(execute().status, 0); 56 }); 57 }); 58 59 test('HCP060 document visibility access is confined to the exact disposal producer', async () => { 60 await fixture(async ({ directory, put, execute }) => { 61 await confineSvelte(directory); 62 const helper = await readFile( 63 path.join(root, 'src/lib/runtime/dispose.ts'), 64 'utf8' 65 ); 66 // Source grammar fixture only, not product session or lifecycle qualification. 67 await put( 68 'src/lib/runtime/private-session.ts', 69 'export type PrivateSession = {}; export function privateSessionOwnership(){return undefined;} export function subscribePrivateSessionClose(){return ()=>{};} export function closePrivateSession(){return true;} export function privateSessionCleanupRequired(){return false;}' 70 ); 71 await put('src/lib/runtime/dispose.ts', helper); 72 assert.equal(execute().status, 0); 73 for (const code of [ 74 'export const value=document.visibilityState;', 75 'document.addEventListener("visibilitychange",()=>{});', 76 'document.removeEventListener("visibilitychange",()=>{});', 77 'const owner=document;owner.addEventListener("visibilitychange",()=>{});', 78 'const observe=document.addEventListener;observe("visibilitychange",()=>{});', 79 'document["addEventListener"]("visibilitychange",()=>{});', 80 'window.document.addEventListener("visibilitychange",()=>{});' 81 ]) { 82 await put('src/routes/+page.ts', code); 83 assert.notEqual(execute().status, 0, code); 84 } 85 await put('src/routes/+page.ts', 'export const value=1;'); 86 await put( 87 'src/lib/runtime/dispose.ts', 88 helper + '\n document.addEventListener("click",()=>{});' 89 ); 90 assert.notEqual(execute().status, 0); 91 await put('src/lib/runtime/dispose.ts', helper); 92 await put('src/lib/runtime/copied-dispose.ts', helper); 93 assert.notEqual(execute().status, 0); 94 }); 95 }); 96 97 test('HCP044 clipboard access is confined to the exact public copy producer', async () => { 98 await fixture(async ({ directory, put, execute }) => { 99 await confineSvelte(directory); 100 const { cp } = await import('node:fs/promises'); 101 for (const name of ['@noble/curves', '@scure/base', 'applesauce-core']) { 102 const destination = path.join(directory, 'node_modules', name); 103 await mkdir(path.dirname(destination), { recursive: true }); 104 await cp( 105 await realpath(path.join(root, 'node_modules', name)), 106 destination, 107 { recursive: true } 108 ); 109 } 110 for (const name of [ 111 'src/lib/contracts/public-key.ts', 112 'src/lib/nostr/references.ts', 113 'src/lib/navigation-copy.ts' 114 ]) 115 await put(name, await readFile(path.join(root, name), 'utf8')); 116 assert.equal(execute().status, 0); 117 for (const code of [ 118 "navigator.clipboard.writeText('bad');", 119 'const clipboard=navigator.clipboard;clipboard.writeText("bad");', 120 'navigator.clipboard.readText();', 121 'navigator["clipboard"].writeText("bad");', 122 'const owner=navigator;owner.clipboard.writeText("bad");', 123 'globalThis.navigator.clipboard.writeText("bad");', 124 'globalThis["navigator"].clipboard.writeText("bad");', 125 'window.navigator.clipboard.writeText("bad");' 126 ]) { 127 await put('src/routes/+page.ts', code); 128 assert.notEqual(execute().status, 0, code); 129 } 130 await put('src/routes/+page.ts', 'export const value=1;'); 131 const helper = await readFile( 132 path.join(root, 'src/lib/navigation-copy.ts'), 133 'utf8' 134 ); 135 await put( 136 'src/lib/navigation-copy.ts', 137 helper + '\n navigator.clipboard.readText();' 138 ); 139 assert.notEqual(execute().status, 0); 140 await put('src/lib/navigation-copy.ts', helper); 141 await put('src/lib/copied.ts', helper); 142 assert.notEqual(execute().status, 0); 143 }); 144 }); 145 146 const root = fileURLToPath(new URL('../../', import.meta.url)); 147 /** @typedef {{directory: string, put: (name: string, content: string | Uint8Array) => Promise<void>, execute: (args?: string[]) => import('node:child_process').SpawnSyncReturns<string>, pkg: Record<string, unknown>}} Fixture */ 148 test('HCP124 selected report clipboard is confined to the exact original producer', async () => { 149 await fixture(async ({ put, execute }) => { 150 const report = await readFile( 151 path.join(root, 'src/lib/support/report.ts'), 152 'utf8' 153 ); 154 // Source grammar only. These inert exports cannot qualify runtime ownership. 155 await put( 156 'src/lib/catalog/product-view.ts', 157 'export function productViewSnapshot(){return undefined;} export function productViewPublisherProof(){return undefined;} export type ProductView = {};' 158 ); 159 await put( 160 'src/lib/nostr/verified-envelope.ts', 161 'export function verifiedEnvelopeSnapshot(){return undefined;}' 162 ); 163 await put( 164 'src/lib/messaging/inbox-view.ts', 165 'export function inboxThreadSnapshot(){return undefined;} export function inboxReplyOwnership(){return undefined;} export function subscribeInboxView(){return ()=>{};} export type InboxView = {};' 166 ); 167 await put('src/lib/support/report.ts', report); 168 const positive = execute(); 169 assert.equal(positive.status, 0, positive.stdout + positive.stderr); 170 for (const code of [ 171 'navigator.clipboard.writeText("private");', 172 'const clipboard=navigator.clipboard;clipboard.writeText("private");', 173 'navigator.clipboard.readText();', 174 'Reflect.get(navigator.clipboard,"writeText")("private");', 175 'window.navigator.clipboard.writeText("private");' 176 ]) { 177 await put('src/routes/+page.ts', code); 178 reject(execute(), /clipboard|navigator|reflection/); 179 } 180 await put('src/routes/+page.ts', 'export const value=1;'); 181 await put( 182 'src/lib/support/report.ts', 183 report + '\nnavigator.clipboard.readText();' 184 ); 185 reject(execute(), /report.*identity|clipboard/); 186 await put('src/lib/support/report.ts', report); 187 await put('src/lib/support/copied-report.ts', report); 188 reject(execute(), /clipboard|navigator|reflection/); 189 }); 190 }); 191 192 /** @param {(context: Fixture) => Promise<void>} run */ 193 async function fixture(run) { 194 const directory = await realpath( 195 await mkdtemp(path.join(tmpdir(), 'hcr010 source ')) 196 ); 197 /** @type {Fixture['put']} */ 198 const put = async (name, content) => { 199 await mkdir(path.dirname(path.join(directory, name)), { recursive: true }); 200 await writeFile(path.join(directory, name), content); 201 }; 202 try { 203 await mkdir(path.join(directory, 'tools')); 204 await mkdir(path.join(directory, 'src/routes'), { recursive: true }); 205 for (const name of [ 206 'package.json', 207 'tsconfig.json', 208 'vite.config.ts', 209 'tools/check-source.mjs', 210 'tools/source-boundaries.mjs' 211 ]) 212 await copyFile(path.join(root, name), path.join(directory, name)); 213 await symlink( 214 path.join(root, 'node_modules'), 215 path.join(directory, 'node_modules') 216 ); 217 await put( 218 'src/lib/navigation-url.ts', 219 await readFile(path.join(root, 'src/lib/navigation-url.ts'), 'utf8') 220 ); 221 await put('src/routes/+page.ts', 'export const value = 1;'); 222 const execute = (args = ['tools/check-source.mjs']) => { 223 const result = spawnSync(process.execPath, args, { 224 cwd: directory, 225 encoding: 'utf8', 226 timeout: 86400000 227 }); 228 assert.equal(result.error, undefined); 229 return result; 230 }; 231 const pkg = JSON.parse( 232 await readFile(path.join(directory, 'package.json'), 'utf8') 233 ); 234 await run({ directory, put, execute, pkg }); 235 } finally { 236 await rm(directory, { recursive: true, force: true }); 237 } 238 } 239 /** Package runners regenerate launchers; give them an independent dependency tree. 240 * @param {string} directory 241 */ 242 async function isolateScriptDependencies(directory) { 243 const target = path.join(directory, 'node_modules'); 244 assert.equal((await lstat(target)).isSymbolicLink(), true); 245 assert.equal( 246 await realpath(target), 247 await realpath(path.join(root, 'node_modules')) 248 ); 249 await rm(target); 250 await cp(path.join(root, 'node_modules'), target, { 251 recursive: true, 252 verbatimSymlinks: true 253 }); 254 assert.equal((await lstat(target)).isDirectory(), true); 255 } 256 257 /** @param {string} directory */ 258 async function confineSvelte(directory) { 259 await rm(path.join(directory, 'node_modules')); 260 await mkdir(path.join(directory, 'node_modules')); 261 await symlink( 262 path.join(root, 'node_modules/typescript'), 263 path.join(directory, 'node_modules/typescript') 264 ); 265 const { cp } = await import('node:fs/promises'); 266 await cp( 267 await realpath(path.join(root, 'node_modules/svelte')), 268 path.join(directory, 'node_modules/svelte'), 269 { recursive: true } 270 ); 271 const svelteRoot = await realpath(path.join(root, 'node_modules/svelte')); 272 const sveltePackage = JSON.parse( 273 await readFile(path.join(svelteRoot, 'package.json'), 'utf8') 274 ); 275 for (const dependency of Object.keys(sveltePackage.dependencies)) { 276 const destination = path.join(directory, 'node_modules', dependency); 277 await mkdir(path.dirname(destination), { recursive: true }); 278 await symlink(path.join(path.dirname(svelteRoot), dependency), destination); 279 } 280 } 281 282 /** @param {import('node:child_process').SpawnSyncReturns<string>} result @param {RegExp} diagnostic */ 283 const reject = (result, diagnostic) => { 284 assert.equal(result.status, 1, result.stdout + result.stderr); 285 assert.match(result.stderr, diagnostic); 286 }; 287 288 test('admits only exact public-key and reference primitive consumers', async () => { 289 await fixture(async ({ directory, put, execute }) => { 290 await confineSvelte(directory); 291 const { cp } = await import('node:fs/promises'); 292 for (const name of ['@noble/curves', '@scure/base', 'applesauce-core']) { 293 const destination = path.join(directory, 'node_modules', name); 294 await mkdir(path.dirname(destination), { recursive: true }); 295 await cp( 296 await realpath(path.join(root, 'node_modules', name)), 297 destination, 298 { 299 recursive: true 300 } 301 ); 302 } 303 for (const name of [ 304 'src/lib/contracts/public-key.ts', 305 'src/lib/nostr/references.ts' 306 ]) 307 await put(name, await readFile(path.join(root, name), 'utf8')); 308 const result = execute(); 309 assert.equal(result.status, 0, result.stdout + result.stderr); 310 }); 311 }); 312 313 for (const [name, content] of [ 314 [ 315 'src/lib/other.ts', 316 "import { secp256k1 } from '@noble/curves/secp256k1'; export const value = secp256k1;" 317 ], 318 [ 319 'src/lib/nostr/other.ts', 320 "import { bech32 } from '@scure/base'; export const value = bech32;" 321 ], 322 [ 323 'src/lib/contracts/public-key.ts', 324 "import { secp256k1 } from '@noble/curves/secp256k1'; export const value = secp256k1;" 325 ], 326 [ 327 'src/lib/contracts/public-key.ts', 328 "import { schnorr } from '@noble/curves/secp256k1'; export const value = schnorr;" 329 ], 330 [ 331 'src/lib/nostr/references.ts', 332 "import { base64 } from '@scure/base'; export const value = base64;" 333 ] 334 ]) 335 test(`rejects broad or altered primitive access ${name} ${content}`, async () => { 336 await fixture(async ({ put, execute }) => { 337 await put(name, content); 338 reject(execute(), /forbidden production import/); 339 }); 340 }); 341 342 test('rejects primitive pin drift at the reviewed consumer', async () => { 343 await fixture(async ({ put, execute, pkg }) => { 344 await put( 345 'src/lib/contracts/public-key.ts', 346 await readFile(path.join(root, 'src/lib/contracts/public-key.ts'), 'utf8') 347 ); 348 /** @type {Record<string, string>} */ (pkg.dependencies)['@noble/curves'] = 349 '1.1.0'; 350 await put('package.json', JSON.stringify(pkg)); 351 reject(execute(), /forbidden production import/); 352 }); 353 }); 354 355 for (const [name, content, diagnostic] of [ 356 [ 357 'native extension import', 358 "import '../../../core/Cargo.toml';", 359 /forbidden production import/ 360 ], 361 [ 362 'native dynamic import', 363 "void import('../../../core/native.js');", 364 /forbidden production import/ 365 ], 366 [ 367 'test reexport', 368 "export * from '../../tests/e2e/harness/provider';", 369 /forbidden production import/ 370 ], 371 [ 372 'dynamic test signer', 373 "void import('../../tests/signer');", 374 /forbidden production import/ 375 ], 376 [ 377 'NDK dynamic client', 378 "void import('@nostr-dev-kit/ndk');", 379 /forbidden production import/ 380 ], 381 [ 382 'nostr-tools dynamic client', 383 "void import('nostr-tools/pool');", 384 /forbidden production import/ 385 ], 386 [ 387 'computed import', 388 "const name = 'nostr-tools'; void import(name);", 389 /computed production imports/ 390 ], 391 [ 392 'template computed import', 393 'const name = "client"; void import(`./${name}`);', 394 /computed production imports/ 395 ], 396 [ 397 'glob import', 398 "const files = import.meta.glob('./*.ts');", 399 /computed production imports/ 400 ], 401 [ 402 'require loader', 403 "const client = require('nostr-tools');", 404 /loader\/provider\/credential/ 405 ], 406 [ 407 'raw socket', 408 "const socket = new WebSocket('wss://example.invalid');", 409 /loader\/provider\/credential/ 410 ], 411 [ 412 'indirect socket', 413 "const socket = new globalThis['WebSocket']('wss://example.invalid');", 414 /indirect production loaders/ 415 ], 416 [ 417 'secret generation', 418 'export const key = generateSecretKey();', 419 /credential API/ 420 ], 421 [ 422 'copied test marker', 423 "export const marker = 'HC_TEST_ONLY_PROVIDER';", 424 /test provider code/ 425 ], 426 [ 427 'unknown package', 428 "import 'some-unresolved-package';", 429 /forbidden production import/ 430 ], 431 ['unknown local', "import './missing';", /unresolved production import/], 432 ['query loader', "import './safe.ts?raw';", /unsafe production import/], 433 [ 434 'escaped POSIX filename', 435 "import '..\\\\tests\\\\signer';", 436 /unsafe production import/ 437 ], 438 [ 439 'Applesauce outside adapter', 440 "import 'applesauce-core';", 441 /Applesauce imports/ 442 ], 443 [ 444 'removed Kit3 alias', 445 "import '$lib/signer';", 446 /forbidden production import/ 447 ], 448 [ 449 'source reference', 450 '/// <reference path="../../tests/signer.ts" />\nexport {};', 451 /reference directives/ 452 ] 453 ]) 454 test(`rejects ${name}`, async () => { 455 await fixture(async ({ put, execute }) => { 456 if (typeof content !== 'string' || !(diagnostic instanceof RegExp)) 457 throw new Error('Invalid mutation case'); 458 await put('src/routes/+page.ts', content); 459 reject(execute(), diagnostic); 460 }); 461 }); 462 463 test('follows extension and directory-index reexports to test provider', async () => { 464 await fixture(async ({ put, execute }) => { 465 await put('src/routes/+page.ts', "export * from '../lib/bridge.js';"); 466 await put('src/lib/bridge.ts', "export * from './client';"); 467 await put( 468 'src/lib/client/index.ts', 469 "export * from '../../../tests/e2e/harness/provider';" 470 ); 471 reject(execute(), /forbidden production import/); 472 }); 473 }); 474 test('local cycles, emitted extensions and test-only harnesses pass', async () => { 475 await fixture(async ({ put, execute }) => { 476 await put('src/routes/+page.ts', "export * from '../lib/bridge.js';"); 477 await put( 478 'src/lib/bridge.ts', 479 "export * from './client'; export const bridge = 1;" 480 ); 481 await put('src/lib/client/index.ts', "export { bridge } from '../bridge';"); 482 await put( 483 'tests/harness/provider.ts', 484 "export const testSigner = new WebSocket('ws://127.0.0.1');" 485 ); 486 const result = execute(); 487 assert.equal(result.status, 0, result.stderr); 488 }); 489 }); 490 for (const kind of ['package', 'conditional package', 'Vite', 'TypeScript']) 491 test(`rejects test reachability through ${kind} aliases`, async () => { 492 await fixture(async ({ directory, put, execute, pkg }) => { 493 await put('src/routes/+page.ts', "export * from '#bridge';"); 494 if (kind.includes('package')) { 495 pkg.imports = { 496 '#bridge': 497 kind === 'package' 498 ? './tests/signer.ts' 499 : { browser: './tests/signer.ts', default: './src/lib/safe.ts' } 500 }; 501 await put('package.json', JSON.stringify(pkg)); 502 await put('src/lib/safe.ts', 'export const safe = 1;'); 503 } else if (kind === 'Vite') { 504 const vite = await readFile( 505 path.join(directory, 'vite.config.ts'), 506 'utf8' 507 ); 508 await put( 509 'vite.config.ts', 510 vite.replace( 511 'plugins: [', 512 "resolve: { alias: { '#bridge': './tests/signer.ts' } }, plugins: [" 513 ) 514 ); 515 } else 516 await put( 517 'tsconfig.json', 518 JSON.stringify({ 519 extends: '$app/tsconfig', 520 compilerOptions: { 521 strict: true, 522 paths: { '#bridge': ['./tests/signer.ts'] } 523 } 524 }) 525 ); 526 reject(execute(), /forbidden production import/); 527 }); 528 }); 529 test('valid Kit3 package wildcard aliases resolve local index modules', async () => { 530 await fixture(async ({ put, execute, pkg }) => { 531 pkg.imports = { '#modules/*': './src/lib/*' }; 532 await put('package.json', JSON.stringify(pkg)); 533 await put('src/routes/+page.ts', "export * from '#modules/client';"); 534 await put('src/lib/client/index.ts', 'export const client = 1;'); 535 assert.equal(execute().status, 0); 536 }); 537 }); 538 test('npm package alias cannot conceal forbidden dependency identity', async () => { 539 await fixture(async ({ put, execute, pkg }) => { 540 pkg.dependencies = { innocent: 'npm:nostr-tools@2.0.0' }; 541 await put('package.json', JSON.stringify(pkg)); 542 await put('src/routes/+page.ts', "export * from 'innocent/pool';"); 543 reject(execute(), /forbidden production import/); 544 }); 545 }); 546 for (const [name, content, diagnostic] of [ 547 [ 548 'component.svelte', 549 '<p>bad</p><style>p { color: red }</style>', 550 /component CSS/ 551 ], 552 ['inline.svelte', '<p style="color: red">bad</p>', /inline styles/], 553 ['directive.svelte', '<p style:color="red">bad</p>', /inline styles/], 554 ['extra.css', 'p { color: red }', /handwritten CSS/], 555 [ 556 'app.html', 557 '<body style="color: red">%sveltekit.body%</body>', 558 /inline styles/ 559 ] 560 ]) 561 test(`rejects ${name} style violation`, async () => { 562 await fixture(async ({ put, execute }) => { 563 if (typeof content !== 'string' || !(diagnostic instanceof RegExp)) 564 throw new Error('Invalid mutation case'); 565 await put(`src/${name}`, content); 566 reject(execute(), diagnostic); 567 }); 568 }); 569 for (const themePresent of [false, true]) 570 test(`HCP011 admits ${themePresent ? 'unimported theme primitives' : 'bootstrap without CSS'}`, async () => { 571 await fixture(async ({ put, execute }) => { 572 if (themePresent) 573 await put('src/theme.css', ':root { --color-page: #ffffff; }'); 574 await put('src/routes/+layout.svelte', '<p>shell</p>'); 575 const result = execute(); 576 assert.equal(result.status, 0, result.stdout + result.stderr); 577 }); 578 }); 579 580 for (const [name, themePresent, appPresent, owner, imports, diagnostic] of [ 581 ['app only', false, true, '+layout.svelte', '', /exactly once/], 582 [ 583 'theme imported without app', 584 true, 585 false, 586 '+layout.svelte', 587 'import "../theme.css";', 588 /exactly once/ 589 ], 590 [ 591 'app imported without theme', 592 false, 593 true, 594 '+layout.svelte', 595 'import "../app.css";', 596 /exactly once/ 597 ], 598 ['both missing imports', true, true, '+layout.svelte', '', /exactly once/], 599 [ 600 'theme-only partial import', 601 true, 602 true, 603 '+layout.svelte', 604 'import "../theme.css";', 605 /exactly once/ 606 ], 607 [ 608 'app-only partial import', 609 true, 610 true, 611 '+layout.svelte', 612 'import "../app.css";', 613 /exactly once/ 614 ], 615 [ 616 'duplicate import', 617 true, 618 true, 619 '+layout.svelte', 620 'import "../theme.css"; import "../theme.css"; import "../app.css";', 621 /exactly once/ 622 ], 623 [ 624 'reversed import', 625 true, 626 true, 627 '+layout.svelte', 628 'import "../app.css"; import "../theme.css";', 629 /exactly once/ 630 ], 631 [ 632 'wrong owner', 633 true, 634 true, 635 '+page.svelte', 636 'import "../theme.css"; import "../app.css";', 637 /root layout/ 638 ] 639 ]) 640 test(`HCP011 rejects CSS lifecycle ${name}`, async () => { 641 await fixture(async ({ put, execute }) => { 642 if ( 643 typeof owner !== 'string' || 644 typeof imports !== 'string' || 645 !(diagnostic instanceof RegExp) 646 ) 647 throw new Error('Invalid CSS lifecycle case'); 648 if (themePresent) 649 await put('src/theme.css', ':root { --color-page: #ffffff; }'); 650 if (appPresent) 651 await put('src/app.css', 'p { color: var(--color-page); }'); 652 await put( 653 `src/routes/${owner}`, 654 `<script>${imports}</script><p>shell</p>` 655 ); 656 reject(execute(), diagnostic); 657 }); 658 }); 659 660 test('two CSS paths must be imported once in order by root layout', async () => { 661 await fixture(async ({ put, execute }) => { 662 await put('src/theme.css', ':root { --color: black }'); 663 await put('src/app.css', 'p { color: var(--color) }'); 664 await put( 665 'src/routes/+layout.svelte', 666 '<script>import "../theme.css"; import "../app.css";</script><p>good</p>' 667 ); 668 assert.equal(execute().status, 0); 669 await put( 670 'src/routes/+layout.svelte', 671 '<script>import "../app.css"; import "../theme.css";</script><p>bad</p>' 672 ); 673 reject(execute(), /exactly once/); 674 }); 675 }); 676 for (const kind of ['symlink', 'hardlink', 'invalid UTF8', 'oversize', 'FIFO']) 677 test(`rejects ${kind} before parsers`, async () => { 678 await fixture(async ({ directory, put, execute }) => { 679 const target = path.join(directory, 'src/unsafe.ts'); 680 if (kind === 'symlink') 681 await symlink(path.join(root, 'tests/e2e/harness/provider.ts'), target); 682 else if (kind === 'hardlink') 683 await link(path.join(directory, 'src/routes/+page.ts'), target); 684 else if (kind === 'invalid UTF8') 685 await put('src/unsafe.ts', Buffer.from([0xff])); 686 else if (kind === 'oversize') 687 await put('src/unsafe.ts', Buffer.alloc(8 * 1024 * 1024 + 1, 32)); 688 else assert.equal(spawnSync('mkfifo', [target]).status, 0); 689 reject(execute(), /symlinks|nonregular|Unsafe source|encoded data/); 690 }); 691 }); 692 for (const script of ['check', 'lint', 'build', 'test:unit', 'dev']) 693 test(`actual ${script} stops on unsafe production edge`, async () => { 694 await fixture(async ({ directory, put }) => { 695 await put('src/routes/+page.ts', "void import('nostr-tools');"); 696 await isolateScriptDependencies(directory); 697 const result = spawnSync('corepack', ['pnpm', 'run', script], { 698 cwd: directory, 699 encoding: 'utf8', 700 timeout: 86400000 701 }); 702 assert.equal(result.error, undefined); 703 assert.equal(result.status, 1, result.stdout + result.stderr); 704 assert.match(result.stderr, /forbidden production import nostr-tools/); 705 assert.doesNotMatch( 706 result.stdout, 707 /svelte-check found|vite v.*building|RUN\s+v/ 708 ); 709 }); 710 }); 711 712 test('Svelte template expressions cannot dynamically load forbidden clients', async () => { 713 await fixture(async ({ put, execute }) => { 714 await put( 715 'src/routes/+page.svelte', 716 '<button onclick={() => import("nostr-tools")}>bad</button>' 717 ); 718 reject(execute(), /forbidden production import/); 719 }); 720 }); 721 test('app.html inline executable scripts cannot bypass source graph', async () => { 722 await fixture(async ({ put, execute }) => { 723 await put( 724 'src/app.html', 725 '<script type="module">import "nostr-tools";</script>' 726 ); 727 reject(execute(), /external scripts/); 728 }); 729 }); 730 for (const css of [ 731 '@import "../../tests/styles.css";', 732 'p { background: url(../../core/native) }', 733 '@\\69mport "../../tests/styles.css";', 734 'p { background: u/**/rl(../../tests/data) }' 735 ]) 736 test(`rejects CSS loader ${css}`, async () => { 737 await fixture(async ({ put, execute }) => { 738 await put('src/theme.css', css); 739 reject(execute(), /CSS import\/url loading/); 740 }); 741 }); 742 test('JS style assignment cannot bypass two CSS files', async () => { 743 await fixture(async ({ put, execute }) => { 744 await put('src/routes/+page.ts', 'document.body.style.color = "red";'); 745 reject(execute(), /JS-generated inline styles/); 746 }); 747 }); 748 test('configuration execution and alternate configs fail closed', async () => { 749 await fixture(async ({ put, execute }) => { 750 await put('vite.config.js', 'export default {}'); 751 reject(execute(), /competing source configuration/); 752 }); 753 }); 754 test('actual pinned Svelte exports and Kit3 framework modules pass in confined fixture', async () => { 755 await fixture(async ({ directory, put, execute }) => { 756 await confineSvelte(directory); 757 await put( 758 'src/routes/+page.ts', 759 'import { writable } from "svelte/store"; export { writable }; export { goto } from "$app/navigation";' 760 ); 761 const result = execute(); 762 assert.equal(result.status, 0, result.stderr); 763 await put('src/routes/+page.ts', 'import "svelte/nonexistent-export";'); 764 reject(execute(), /unresolved production import/); 765 }); 766 }); 767 768 test('type imports and Vite URL references cannot hide test reachability', async () => { 769 await fixture(async ({ put, execute }) => { 770 await put( 771 'src/routes/+page.ts', 772 'export type Client = typeof import("../../tests/signer");' 773 ); 774 reject(execute(), /forbidden production import/); 775 await put( 776 'src/routes/+page.ts', 777 'export const client = new URL("../../tests/signer", import.meta.url);' 778 ); 779 reject(execute(), /forbidden production import/); 780 }); 781 }); 782 test('production package imports exclude compiler and server tooling', async () => { 783 await fixture(async ({ put, execute }) => { 784 await put( 785 'src/routes/+page.ts', 786 'import "svelte/compiler"; import "@sveltejs/kit/node";' 787 ); 788 reject(execute(), /forbidden production import/); 789 }); 790 }); 791 792 test('npm aliases cannot hide compiler/server subpaths', async () => { 793 await fixture(async ({ put, execute, pkg }) => { 794 pkg.dependencies = { 795 view: 'npm:svelte@5.57.1', 796 framework: 'npm:@sveltejs/kit@3.0.0' 797 }; 798 await put('package.json', JSON.stringify(pkg)); 799 await put( 800 'src/routes/+page.ts', 801 'import "view/compiler"; import "framework/node";' 802 ); 803 reject(execute(), /forbidden production import view\/compiler/); 804 assert.match( 805 execute().stderr, 806 /forbidden production import framework\/node/ 807 ); 808 }); 809 }); 810 811 for (const [name, markup] of [ 812 [ 813 'nested external script', 814 '<svelte:head><script src="/tests/provider.js"></script></svelte:head>' 815 ], 816 [ 817 'nested inline script', 818 '<svelte:head><script>import("nostr-tools")</script></svelte:head>' 819 ], 820 [ 821 'nested module script', 822 '<div><script type="module">import "nostr-tools"</script></div>' 823 ], 824 [ 825 'nested style', 826 '<svelte:head><style>p { color: red }</style></svelte:head>' 827 ], 828 [ 829 'nested CSS import', 830 '<div><style>@import "/tests/style.css";</style></div>' 831 ], 832 [ 833 'stylesheet link', 834 '<svelte:head><link rel="stylesheet" href="/native.css" /></svelte:head>' 835 ], 836 [ 837 'alternate stylesheet tokens', 838 '<link rel="alternate stylesheet" href="/native.css" />' 839 ], 840 [ 841 'entity stylesheet token', 842 '<link rel="stylesheet" href="/native.css" />' 843 ], 844 [ 845 'modulepreload link', 846 '<link rel="modulepreload" href="/tests/provider.js" />' 847 ], 848 [ 849 'script preload', 850 '<link rel="preload" as="script" href="/tests/provider.js" />' 851 ], 852 ['computed link relation', '<link rel={relation} href="/favicon.ico" />'], 853 ['computed resource href', '<link rel="icon" href={resource} />'], 854 [ 855 'computed resource type', 856 '<link rel="icon" type={resourceType} href="/favicon.ico" />' 857 ], 858 ['spread link loader', '<link {...attributes} />'], 859 ['spread style/event attributes', '<div {...attributes}>content</div>'], 860 [ 861 'computed element tag', 862 '<svelte:element this={tag} src="/tests/provider.js" />' 863 ], 864 [ 865 'static resource element tag', 866 '<svelte:element this="script" src="/tests/provider.js" />' 867 ], 868 ['frame document', '<iframe src="/tests/provider.html"></iframe>'], 869 [ 870 'frame srcdoc', 871 '<iframe srcdoc="<script>import(\'nostr-tools\')</script>"></iframe>' 872 ], 873 ['object resource', '<object data="/tests/provider.html"></object>'], 874 ['embed resource', '<embed src="/tests/provider.html" />'], 875 ['raw HTML injection', '<div>{@html markup}</div>'], 876 [ 877 'executable link URL', 878 '<a href="java	script:import(\'nostr-tools\')">bad</a>' 879 ], 880 [ 881 'remote favicon resource', 882 '<link rel="icon" href="https://foreign.invalid/favicon.ico" />' 883 ] 884 ]) 885 test(`markup guard rejects ${name}`, async () => { 886 await fixture(async ({ put, execute }) => { 887 await put('src/routes/+page.svelte', markup); 888 const result = execute(); 889 assert.equal(result.status, 1, result.stdout + result.stderr); 890 assert.match(result.stderr, /markup|favicon resources/); 891 }); 892 }); 893 894 for (const markup of [ 895 '<html><head><script src="/tests/provider.js"></script></head></html>', 896 '<html><head><script type="module">import "nostr-tools"</script></head></html>', 897 '<html><head><style>p { color: red }</style></head></html>', 898 '<html><head><link rel="stylesheet" href="/tests/style.css" /></head></html>', 899 '<html><head><link rel="modulepreload" href="/tests/provider.js" /></head></html>', 900 '<HTML><HEAD><SCRIPT src="/tests/provider.js"></SCRIPT></HEAD></HTML>', 901 '<HTML><HEAD><LINK REL="stylesheet" HREF="/tests/style.css" /></HEAD></HTML>', 902 '<html><body><iframe srcdoc="<script>import(\'nostr-tools\')</script>"></iframe></body></html>', 903 '<html><body onload="import(\'nostr-tools\')"></body></html>', 904 '<html><head><link rel={relation} href="/favicon.ico" /></head></html>' 905 ]) 906 test(`HTML template rejects active resource ${markup}`, async () => { 907 await fixture(async ({ put, execute }) => { 908 await put('src/app.html', markup); 909 reject(execute(), /markup/); 910 }); 911 }); 912 913 test('legitimate shell modules, metadata and owned favicon links pass', async () => { 914 await fixture(async ({ put, execute }) => { 915 await put( 916 'src/routes/+page.svelte', 917 '<script lang="ts">const title: string = "HarvestCircle";</script><svelte:head><title>{title}</title><meta name="description" content="Public food listings" /><link rel="icon" href="/favicon.ico" /></svelte:head><svelte:element this="main"><p>{title}</p></svelte:element>' 918 ); 919 await put( 920 'src/app.html', 921 '<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><link rel="icon" href="%sveltekit.assets%/favicon.ico" />%sveltekit.head%</head><body><div>%sveltekit.body%</div></body></html>' 922 ); 923 const result = execute(); 924 assert.equal(result.status, 0, result.stderr); 925 }); 926 }); 927 928 for (const script of ['check', 'lint', 'build', 'test:unit', 'dev']) 929 test(`actual ${script} stops on nested markup loader`, async () => { 930 await fixture(async ({ directory, put }) => { 931 await put( 932 'src/routes/+page.svelte', 933 '<svelte:head><script src="/tests/provider.js"></script></svelte:head>' 934 ); 935 await isolateScriptDependencies(directory); 936 const result = spawnSync('corepack', ['pnpm', 'run', script], { 937 cwd: directory, 938 encoding: 'utf8', 939 timeout: 86400000 940 }); 941 assert.equal(result.error, undefined); 942 assert.equal(result.status, 1, result.stdout + result.stderr); 943 assert.match(result.stderr, /raw markup scripts/); 944 assert.doesNotMatch( 945 result.stdout, 946 /svelte-check found|vite v.*building|RUN\s+v/ 947 ); 948 }); 949 }); 950 951 for (const source of [ 952 'const script = document.createElement("script");', 953 'const stylesheet = document.createElement("link");', 954 'const tag = "script"; const script = document.createElement(tag);', 955 'const script = document.createElementNS("http://www.w3.org/2000/svg", "script");', 956 'document.body.innerHTML = "<script src=/tests/provider.js></script>";', 957 'document.body.insertAdjacentHTML("beforeend", "<style>body{color:red}</style>");', 958 'document.body["outerHTML"] = "<iframe srcdoc=unsafe></iframe>";', 959 'document.write("<script src=/tests/provider.js></script>");' 960 ]) 961 test(`JS cannot construct raw resource markup: ${source}`, async () => { 962 await fixture(async ({ put, execute }) => { 963 await put('src/routes/+page.ts', source); 964 reject(execute(), /markup/); 965 }); 966 }); 967 968 test('supported direct UI focus remains allowed', async () => { 969 await fixture(async ({ put, execute }) => { 970 await put( 971 'src/routes/+page.ts', 972 'export function focusLabel() { document.getElementById("label")?.focus(); }' 973 ); 974 const result = execute(); 975 assert.equal(result.status, 0, result.stderr); 976 }); 977 }); 978 979 for (const source of [ 980 '/** @type {import("../../tests/signer").Signer} */\nexport const signer = {};', 981 '/** @import { Signer } from "../../tests/signer" */\nexport const signer = {};' 982 ]) 983 test(`JSDoc type edges cannot reach test artifacts: ${source}`, async () => { 984 await fixture(async ({ put, execute }) => { 985 await put('src/routes/+page.js', source); 986 reject(execute(), /forbidden production import/); 987 }); 988 }); 989 test('Svelte const declarations cannot hide client imports', async () => { 990 await fixture(async ({ put, execute }) => { 991 await put( 992 'src/routes/+page.svelte', 993 '{#if true}{@const client = import("nostr-tools")}<p>{client}</p>{/if}' 994 ); 995 reject(execute(), /forbidden production import/); 996 }); 997 }); 998 for (const source of [ 999 'const script = document["createElement"]("script");', 1000 'const create = document.createElement; const script = create("script");', 1001 'const script = document.createElement.call(document, "script");', 1002 'const method = "createElement"; const script = document[method]("script");' 1003 ]) 1004 test(`indirect DOM constructors cannot load client markup: ${source}`, async () => { 1005 await fixture(async ({ put, execute }) => { 1006 await put('src/routes/+page.ts', source); 1007 reject(execute(), /markup/); 1008 }); 1009 }); 1010 1011 const resourceHandle = 1012 'const link = document.querySelector<HTMLLinkElement>("link[rel=icon]"); if (!link) throw new Error("missing");'; 1013 for (const mutation of [ 1014 'link.rel = "stylesheet"; link.href = "https://example.invalid/extra.css";', 1015 'link["rel"] = "stylesheet"; link["href"] = "/extra.css";', 1016 'const field = "href"; link[field] = "/tests/provider.js";', 1017 'link.setAttribute("rel", "stylesheet"); link.setAttribute("href", "/extra.css");', 1018 'link.setAttributeNS(null, "href", "/extra.css");', 1019 'link.toggleAttribute("rel", true);', 1020 'link.relList.add("stylesheet");', 1021 'const alias = link; alias.href = "../../../core/native";', 1022 'const setter = link.setAttribute; setter.call(link, "href", "/extra.css");', 1023 'link.setAttribute.bind(link)("href", "/extra.css");', 1024 'Object.assign(link, { rel: "stylesheet", href: "/extra.css" });', 1025 'Object.defineProperty(link, "href", { value: "/extra.css" });', 1026 'Object.defineProperties(link, { href: { value: "/extra.css" } });', 1027 'Reflect.set(link, "href", "/extra.css");', 1028 'Reflect.defineProperty(link, "href", { value: "/extra.css" });', 1029 'const patch = Object.assign; patch(link, { href: "/extra.css" });', 1030 'const attribute = link.getAttributeNode("href"); if(attribute) attribute.value = "/extra.css";', 1031 'const attribute = document.createAttribute("href"); attribute.value = "/extra.css"; link.setAttributeNode(attribute);', 1032 'link.attributes.setNamedItem(document.createAttribute("href"));', 1033 'link.sheet?.replaceSync("@import /tests/style.css");', 1034 'delete link.rel;', 1035 '[link.href] = ["/extra.css"];' 1036 ]) 1037 test(`opaque resource mutations fail closed: ${mutation}`, async () => { 1038 await fixture(async ({ put, execute }) => { 1039 await put('src/routes/+page.ts', resourceHandle + mutation); 1040 reject(execute(), /DOM|mutation|reflection|model/); 1041 }); 1042 }); 1043 1044 for (const source of [ 1045 'export function rewrite(opaque: unknown) { (opaque as { href: string }).href = "/tests/provider.js"; }', 1046 'const model = { href: "/safe" }; function rewrite(model: { href: string }) { model.href = "/tests/provider.js"; }', 1047 'const model = { href: "/safe" }; const shadow = (model: { href: string }) => Object.assign(model, { href: "/extra.css" });', 1048 'const reflect = Reflect; reflect.set(window.document, "adoptedStyleSheets", []);', 1049 'const { document: dom } = window; const link = dom.querySelector("link"); link.href = "/extra.css";', 1050 'const selector = document.querySelector; const link = selector("link"); link.href = "/extra.css";', 1051 'const capability = (event: Event) => { const link = event.currentTarget; Object.assign(link, { rel: "stylesheet" }); };', 1052 'const data = { link: { href: "/safe" } }; data.link = (window as unknown as { evil: { href: string } }).evil;', 1053 'const prototype = ({}).constructor.constructor; prototype("return document")();' 1054 ]) 1055 test(`unmanaged or indirect mutation capabilities fail closed: ${source}`, async () => { 1056 await fixture(async ({ put, execute }) => { 1057 await put('src/routes/+page.ts', source); 1058 reject(execute(), /DOM|capability|reflection|model/); 1059 }); 1060 }); 1061 1062 for (const markup of [ 1063 '<link bind:this={link} rel="icon" href="/favicon.ico" />', 1064 '<div use:mutate>content</div>', 1065 '<div {@attach mutate}>content</div>', 1066 '<div transition:mutate>content</div>' 1067 ]) 1068 test(`markup cannot expose unmanaged DOM handles: ${markup}`, async () => { 1069 await fixture(async ({ put, execute }) => { 1070 await put( 1071 'src/routes/+page.svelte', 1072 '<script lang="ts">let link; const mutate = (node) => node;</script>' + 1073 markup 1074 ); 1075 reject(execute(), /DOM bindings\/actions\/attachments/); 1076 }); 1077 }); 1078 1079 test('owned plain model mutations, lexical aliases, reflection and UI leaf operations remain admitted', async () => { 1080 await fixture(async ({ put, execute }) => { 1081 await put( 1082 'src/routes/+page.ts', 1083 'const model = { href: "/home", rel: "icon", counter: 0, style: { color: "description" } }; const alias = model; alias.href = "/search"; model["rel"] = "metadata"; model.counter++; Object.assign(alias, { href: "/sell" }); Reflect.set(model, "rel", "model"); Object.defineProperty(model, "label", { value: "HarvestCircle" }); model.style.color = "plain data"; export function focus() { document.querySelector("#subject")?.focus(); } export function read() { return document.getElementById("subject")?.textContent; }' 1084 ); 1085 const result = execute(); 1086 assert.equal(result.status, 0, result.stderr); 1087 }); 1088 }); 1089 1090 for (const source of [ 1091 'import { createRawSnippet } from "svelte"; export const snippet = createRawSnippet(() => ({ render: () => "<link rel=stylesheet href=/extra.css>" }));', 1092 'import { createRawSnippet as raw } from "svelte"; export const snippet = raw(() => ({ render: () => "<script src=/tests/provider.js></script>" }));', 1093 'import * as renderer from "svelte"; export const snippet = renderer["create" + "RawSnippet"](() => ({ render: () => "<style>body{color:red}</style>" }));', 1094 'export * from "svelte";', 1095 'export { createRawSnippet as raw } from "svelte";', 1096 'const renderer = await import("svelte"); export const snippet = renderer.createRawSnippet;', 1097 'import { render } from "svelte/server"; export { render };' 1098 ]) 1099 test(`pinned Svelte raw rendering remains unavailable: ${source}`, async () => { 1100 await fixture(async ({ directory, put, execute }) => { 1101 await confineSvelte(directory); 1102 await put('src/routes/+page.ts', source); 1103 reject( 1104 execute(), 1105 /createRawSnippet|raw-render|forbidden production import svelte\/server/ 1106 ); 1107 }); 1108 }); 1109 1110 test('actual pinned safe Svelte imports remain available', async () => { 1111 await fixture(async ({ directory, put, execute }) => { 1112 await confineSvelte(directory); 1113 await put( 1114 'src/routes/+page.ts', 1115 'import { onMount } from "svelte"; import type { Snippet } from "svelte"; export { onMount }; export type { Snippet };' 1116 ); 1117 const result = execute(); 1118 assert.equal(result.status, 0, result.stderr); 1119 }); 1120 }); 1121 1122 for (const mutation of [ 1123 'opaque.rel = "stylesheet";', 1124 'opaque["href"] = "/extra.css";', 1125 'opaque.setAttribute("rel", "stylesheet");', 1126 'const setter = opaque.setAttribute; setter.apply(opaque, ["href", "/extra.css"]);', 1127 'Object.assign(opaque, { rel: "stylesheet" });', 1128 'const attribute = opaque.attributes.item(0); attribute.nodeValue = "/extra.css";', 1129 'opaque.relList.add("stylesheet");', 1130 'Reflect.set(opaque, "href", "/extra.css");' 1131 ]) 1132 test(`mutation grammar rejects opaque inputs without DOM acquisition: ${mutation}`, async () => { 1133 await fixture(async ({ put, execute }) => { 1134 await put( 1135 'src/routes/+page.ts', 1136 'export function mutate(opaque: unknown) { ' + 1137 mutation.replaceAll( 1138 'opaque.', 1139 '(opaque as Record<string, unknown>).' 1140 ) + 1141 ' }' 1142 ); 1143 reject(execute(), /DOM|mutation|reflection|model/); 1144 }); 1145 }); 1146 1147 test('string-named raw-render exports cannot bypass semantic import admission', async () => { 1148 await fixture(async ({ directory, put, execute }) => { 1149 await confineSvelte(directory); 1150 await put( 1151 'src/routes/+page.ts', 1152 'import { "createRawSnippet" as raw } from "svelte"; export { raw };' 1153 ); 1154 reject(execute(), /raw-render factories/); 1155 }); 1156 }); 1157 1158 for (const source of [ 1159 'new Worker("https://example.invalid/client.js");', 1160 'new SharedWorker("/tests/client.js");', 1161 'importScripts("https://example.invalid/client.js");', 1162 'navigator.serviceWorker.register("/tests/client.js");', 1163 'const capabilities = navigator; capabilities["service" + "Worker"].register("/tests/client.js");', 1164 'window.navigator["service" + "Worker"].register("/tests/client.js");', 1165 'const registrations = window.navigator.serviceWorker; registrations.register("/tests/client.js");', 1166 'const audio = new AudioContext(); audio.audioWorklet.addModule("/tests/client.js");' 1167 ]) 1168 test(`browser worker loading cannot bypass source imports: ${source}`, async () => { 1169 await fixture(async ({ put, execute }) => { 1170 await put('src/routes/+page.ts', source); 1171 reject(execute(), /loader|worker|DOM|capability/); 1172 }); 1173 }); 1174 1175 test('approved navigator capabilities and plain model flags remain admitted', async () => { 1176 await fixture(async ({ put, execute }) => { 1177 await put( 1178 'src/routes/+page.ts', 1179 'const model = { serviceWorker: false }; export const disabled = model.serviceWorker; export function online() { return navigator.onLine; } export function estimate() { return navigator.storage.estimate(); }' 1180 ); 1181 const result = execute(); 1182 assert.equal(result.status, 0, result.stderr); 1183 }); 1184 }); 1185 1186 const helperImport = 1187 "import { internalHref, navigationHref } from '../lib/navigation-url';"; 1188 for (const [ 1189 name, 1190 code, 1191 accepted 1192 ] of /** @type {Array<[string,string,boolean]>} */ ([ 1193 ['concat executable', "<a href={'java'+'script:alert(1)'}>bad</a>", false], 1194 [ 1195 'shorthand executable', 1196 "<script>const href='javascript:alert(1)';</script><a {href}>bad</a>", 1197 false 1198 ], 1199 [ 1200 'mixed executable', 1201 '<script>const scheme=\'java\';</script><a href="{scheme}script:alert(1)">bad</a>', 1202 false 1203 ], 1204 [ 1205 'conditional executable', 1206 "<a href={true ? '/safe' : 'javascript:alert(1)'}>bad</a>", 1207 false 1208 ], 1209 [ 1210 'alias executable', 1211 "<script>const a='javascript:alert(1)'; const href=a;</script><a {href}>bad</a>", 1212 false 1213 ], 1214 [ 1215 'safe aliases', 1216 "<script>const a='/search'; const href=a+'?q=food';</script><a {href}>safe</a>", 1217 true 1218 ], 1219 [ 1220 'safe template', 1221 "<script>const id='example';</script><a href={`/products/${id}`}>safe</a>", 1222 true 1223 ], 1224 [ 1225 'wrapped route', 1226 `<script lang="ts">${helperImport} const route=(id: string) => '/products/'+id; const id='example';</script><a href={internalHref(route(id))}>safe</a>`, 1227 true 1228 ], 1229 [ 1230 'wrapped contact', 1231 `<script lang="ts">${helperImport} const contact: unknown='https://example.com';</script><a href={navigationHref(contact)}>safe</a>`, 1232 true 1233 ], 1234 [ 1235 'forged spelling', 1236 "<script>const internalHref=x=>x;</script><a href={internalHref('javascript:alert(1)')}>bad</a>", 1237 false 1238 ], 1239 [ 1240 'each shadows helper', 1241 `<script>${helperImport} const funcs=[x=>x];</script>{#each funcs as internalHref}<a href={internalHref('javascript:alert(1)')}>bad</a>{/each}`, 1242 false 1243 ], 1244 [ 1245 'snippet shadows helper', 1246 `<script>${helperImport}</script>{#snippet row(internalHref)}<a href={internalHref('javascript:alert(1)')}>bad</a>{/snippet}`, 1247 false 1248 ], 1249 [ 1250 'const shadows helper', 1251 `<script>${helperImport}</script>{#if true}{@const internalHref = x=>x}<a href={internalHref('javascript:alert(1)')}>bad</a>{/if}`, 1252 false 1253 ], 1254 [ 1255 'module scope helper', 1256 `<script module>${helperImport}</script><a href={internalHref('/products/a')}>safe</a>`, 1257 true 1258 ], 1259 [ 1260 'instance shadows module', 1261 `<script module>${helperImport}</script><script>const internalHref=x=>x;</script><a href={internalHref('javascript:alert(1)')}>bad</a>`, 1262 false 1263 ], 1264 [ 1265 'module sees no instance helper', 1266 `<script module>export const wrong=internalHref('javascript:alert(1)');</script><script>${helperImport}</script><a href={wrong}>bad</a>`, 1267 false 1268 ], 1269 [ 1270 'unknown prop', 1271 '<script>let {href}=$props();</script><a {href}>bad</a>', 1272 false 1273 ], 1274 [ 1275 'cast prop', 1276 '<script lang="ts">let {href}: {href:string}=$props();</script><a href={href as string}>bad</a>', 1277 false 1278 ], 1279 [ 1280 'resource validator cannot admit remote image', 1281 `<script>${helperImport}</script><img src={navigationHref('https://example.com/image.png')} alt="bad"/>`, 1282 false 1283 ], 1284 [ 1285 'remote image', 1286 '<img src="https://example.com/image.png" alt="bad"/>', 1287 false 1288 ], 1289 [ 1290 'remote srcset', 1291 '<img srcset="https://example.com/image.png 2x" alt="bad"/>', 1292 false 1293 ], 1294 [ 1295 'remote poster', 1296 '<video poster="https://example.com/image.png"></video>', 1297 false 1298 ], 1299 ['form computed', "<form action={'java'+'script:alert(1)'}></form>", false], 1300 ['URL control', '<a href="https://user:secret@example.com">bad</a>', false], 1301 ['backslash', '<a href="/\\evil.test">bad</a>', false], 1302 [ 1303 'namespace SVG', 1304 '<svg><a xlink:href="javascript:alert(1)">bad</a></svg>', 1305 false 1306 ] 1307 ])) { 1308 test(`D07 markup: ${name}`, async () => 1309 fixture(async ({ put, execute }) => { 1310 await put('src/routes/+page.svelte', code); 1311 const result = execute(); 1312 assert.equal( 1313 result.status, 1314 accepted ? 0 : 1, 1315 result.stdout + result.stderr 1316 ); 1317 })); 1318 } 1319 1320 for (const [ 1321 name, 1322 code, 1323 accepted 1324 ] of /** @type {Array<[string,string,boolean]>} */ ([ 1325 ['Location literal', "location.assign('/search');", true], 1326 ['Location qualified literal', "window.location.replace('/search');", true], 1327 ['Location href literal', "location.href='/search';", true], 1328 ['Location write literal', "window.location='/search';", true], 1329 ['Location executable', "location.assign('javascript:alert(1)');", false], 1330 ['Location external', "location.assign('https://example.com');", false], 1331 [ 1332 'Location escaped', 1333 "const target=location; target.assign('/search');", 1334 false 1335 ], 1336 [ 1337 'Location destructured', 1338 "const {assign}=location; assign('/search');", 1339 false 1340 ], 1341 ['Location computed', "location['assign']('/search');", false], 1342 [ 1343 'validated Location', 1344 `${helperImport} const target=internalHref('/search'); if(target !== undefined) location.assign(target);`, 1345 true 1346 ], 1347 [ 1348 'undefined Location', 1349 `${helperImport} location.assign(internalHref('/search'));`, 1350 false 1351 ], 1352 [ 1353 'asserted Location', 1354 `${helperImport} location.assign(internalHref('/search')!);`, 1355 false 1356 ], 1357 [ 1358 'Kit literal', 1359 "import {goto as navigate} from '$app/navigation'; navigate('/search');", 1360 true 1361 ], 1362 [ 1363 'Kit validated', 1364 `${helperImport} import {goto} from '$app/navigation'; const target=internalHref('/search'); if(target) goto(target);`, 1365 true 1366 ], 1367 [ 1368 'Kit undefined', 1369 `${helperImport} import {goto} from '$app/navigation'; goto(internalHref('/search'));`, 1370 false 1371 ], 1372 [ 1373 'Kit executable', 1374 "import {goto} from '$app/navigation'; goto('javascript:alert(1)');", 1375 false 1376 ], 1377 [ 1378 'Kit escaped', 1379 "import {goto} from '$app/navigation'; const redirect=goto; redirect('javascript:alert(1)');", 1380 false 1381 ], 1382 [ 1383 'callback timer', 1384 'setTimeout(()=>{},0); setInterval(function(){},100);', 1385 true 1386 ], 1387 [ 1388 'named callback timer', 1389 'function callback(){} setTimeout(callback,0);', 1390 true 1391 ], 1392 [ 1393 'const callback timer', 1394 'const callback=()=>{}; setInterval(callback,100);', 1395 true 1396 ], 1397 [ 1398 'shadowed timer ordinary model', 1399 "const setTimeout=(value:string)=>value; setTimeout('data');", 1400 true 1401 ], 1402 ['string timer', "setTimeout('alert(1)',0);", false], 1403 ['unknown timer', 'setTimeout(callback,0);', false], 1404 ['escaped timer', "const later=setTimeout; later('alert(1)',0);", false], 1405 ['qualified timer', 'window.setTimeout(()=>{},0);', false], 1406 ['computed timer', 'globalThis["setTimeout"](()=>{},0);', false], 1407 [ 1408 'destructured timer', 1409 'const {setTimeout: later}=window; later(()=>{},0);', 1410 false 1411 ], 1412 [ 1413 'reassigned callback', 1414 'let cb=()=>{}; cb=external; setTimeout(cb,0);', 1415 false 1416 ], 1417 [ 1418 'parameter callback unsupported', 1419 'function schedule(cb:()=>void){setTimeout(cb,0)}', 1420 false 1421 ], 1422 [ 1423 'literal replace', 1424 "const value='one two'; export const normalized=value.replace(/\\s+/g,' ');", 1425 true 1426 ], 1427 [ 1428 'alias replace', 1429 "const value='one two'; const alias=value; alias.replace('two','three');", 1430 true 1431 ], 1432 [ 1433 'fake replace', 1434 "const value=external as string; value.replace('two','three');", 1435 false 1436 ], 1437 [ 1438 'DOM replace', 1439 "document.querySelector('link').relList.replace('icon','stylesheet');", 1440 false 1441 ], 1442 ['local Set', "const seen=new Set<string>(); seen.add('public-id');", true], 1443 [ 1444 'shadowed Set', 1445 "function f(Set:any){const seen=new Set();seen.add('x')}", 1446 false 1447 ], 1448 [ 1449 'Set alias', 1450 "const seen=new Set(); const other=seen; other.add('x');", 1451 false 1452 ], 1453 ['Set rebound', "let seen=new Set();seen=external;seen.add('x');", false], 1454 [ 1455 'Set escaped add', 1456 "const seen=new Set(); const add=seen.add; add('x');", 1457 false 1458 ], 1459 ['opaque add', "(external as Set<string>).add('x');", false], 1460 [ 1461 'DOM add', 1462 "document.querySelector('link').relList.add('stylesheet');", 1463 false 1464 ] 1465 ])) { 1466 test(`D07 JavaScript: ${name}`, async () => 1467 fixture(async ({ put, execute }) => { 1468 await put('src/routes/+page.ts', code); 1469 const result = execute(); 1470 assert.equal( 1471 result.status, 1472 accepted ? 0 : 1, 1473 result.stdout + result.stderr 1474 ); 1475 })); 1476 } 1477 1478 test('D07 helper runtime validates unknown values without effects or coercion', async () => { 1479 const { internalHref, navigationHref } = 1480 await import('../../src/lib/navigation-url.ts'); 1481 const evil = { 1482 toString() { 1483 throw new Error('coercion'); 1484 } 1485 }; 1486 for (const value of [ 1487 evil, 1488 null, 1489 undefined, 1490 5, 1491 [], 1492 {}, 1493 '', 1494 '//evil.test', 1495 '/\\evil.test', 1496 'javascript:alert(1)', 1497 'data:text/html,x', 1498 'https://u:p@example.com', 1499 'https://@example.com', 1500 'https:////@example.com', 1501 'https:///@example.com', 1502 'https:////example.com', 1503 'mailto://evil.example/path', 1504 'tel://evil.example/path', 1505 '\ud800', 1506 '/foo\nbar', 1507 '/%0d%0aevil', 1508 '/%5cevil', 1509 '/%zz', 1510 'a'.repeat(8193) 1511 ]) { 1512 assert.equal(internalHref(value), undefined); 1513 assert.equal(navigationHref(value), undefined); 1514 } 1515 for (const value of [ 1516 '/search?q=food', 1517 '#item', 1518 '?query=food', 1519 '/products/example' 1520 ]) { 1521 assert.equal(internalHref(value), value); 1522 assert.equal(navigationHref(value), value); 1523 } 1524 for (const value of [ 1525 'https://example.com/path', 1526 'HTTPS://example.com/path', 1527 'https://example.com/@path?email=buyer@example.com', 1528 'mailto:buyer@example.com', 1529 'tel:+123456789' 1530 ]) { 1531 assert.equal(internalHref(value), undefined); 1532 assert.equal(navigationHref(value), value); 1533 } 1534 assert.equal(internalHref('/' + 'é'.repeat(4095)), '/' + 'é'.repeat(4095)); 1535 assert.equal(internalHref('/' + 'é'.repeat(4096)), undefined); 1536 assert.equal(internalHref('/' + 'a'.repeat(8191)), '/' + 'a'.repeat(8191)); 1537 let mutable = '/safe'; 1538 assert.equal(internalHref(mutable), '/safe'); 1539 mutable = 'javascript:alert(1)'; 1540 assert.equal(internalHref(mutable), undefined); 1541 }); 1542 1543 test('D07 helper pin rejects source tampering and spoofed module exports', async () => 1544 fixture(async ({ put, execute }) => { 1545 await put( 1546 'src/lib/navigation-url.ts', 1547 'export const internalHref=(value:unknown)=>value;' 1548 ); 1549 await put( 1550 'src/routes/+page.svelte', 1551 `<script>${helperImport}</script><a href={internalHref('/safe')}>bad</a>` 1552 ); 1553 reject(execute(), /source identity/); 1554 })); 1555 1556 test('D07 alias and named re-export retain exact helper export identity', async () => 1557 fixture(async ({ put, execute }) => { 1558 await put( 1559 'src/lib/links.ts', 1560 "export {internalHref as routeHref} from './navigation-url';" 1561 ); 1562 await put( 1563 'src/routes/+page.svelte', 1564 "<script>import {routeHref as validated} from '../lib/links'; const unknownRoute='/search';</script><a href={validated(unknownRoute)}>safe</a>" 1565 ); 1566 assert.equal(execute().status, 0); 1567 })); 1568 1569 test('D07 positives compile with actual Svelte and TypeScript', async () => 1570 fixture(async ({ put, execute, directory }) => { 1571 const { compile } = await import('svelte/compiler'); 1572 const source = `<script lang="ts">${helperImport} let {href}: {href: unknown} = $props(); const route=(id:string)=>'/products/'+id;</script><a href={navigationHref(href)}>contact</a><a href={internalHref(route('example'))}>product</a>`; 1573 await put('src/routes/+page.svelte', source); 1574 assert.equal(execute().status, 0); 1575 const output = compile(source, { 1576 filename: path.join(directory, 'src/routes/+page.svelte'), 1577 generate: 'server' 1578 }); 1579 assert.ok(output.js.code.length > 0); 1580 assert.deepEqual(output.warnings, []); 1581 const { default: ts } = await import('typescript'); 1582 const navigation = `import {internalHref} from './src/lib/navigation-url'; import {goto} from '$app/navigation'; export function search(input:unknown){const target=internalHref(input); if(target !== undefined) void goto(target);} export const normalize='one two'.replace(/\\s+/g,' '); const seen=new Set<string>();seen.add('id'); setTimeout(()=>seen.add('next'),0);`; 1583 await put('positive.ts', navigation); 1584 const program = ts.createProgram([path.join(directory, 'positive.ts')], { 1585 strict: true, 1586 noEmit: true, 1587 target: ts.ScriptTarget.ESNext, 1588 module: ts.ModuleKind.ESNext, 1589 moduleResolution: ts.ModuleResolutionKind.Bundler, 1590 skipLibCheck: true, 1591 types: ['@sveltejs/kit'] 1592 }); 1593 assert.deepEqual( 1594 ts 1595 .getPreEmitDiagnostics(program) 1596 .map((d) => ts.flattenDiagnosticMessageText(d.messageText, '\n')), 1597 [] 1598 ); 1599 })); 1600 1601 for (const [ 1602 name, 1603 code, 1604 accepted 1605 ] of /** @type {Array<[string,string,boolean]>} */ ([ 1606 [ 1607 'namespace helper', 1608 "<script>import * as links from '../lib/navigation-url'; const route='/safe';</script><a href={links.internalHref(route)}>safe</a>", 1609 true 1610 ], 1611 [ 1612 'await shadows helper', 1613 `<script>${helperImport} const pending=Promise.resolve(x=>x);</script>{#await pending then internalHref}<a href={internalHref('javascript:alert(1)')}>bad</a>{/await}`, 1614 false 1615 ], 1616 [ 1617 'reassigned helper', 1618 `<script>${helperImport} internalHref=x=>x;</script><a href={internalHref('javascript:alert(1)')}>bad</a>`, 1619 false 1620 ], 1621 [ 1622 'spoofed import', 1623 "<script>import {internalHref} from '../lib/spoof';</script><a href={internalHref('javascript:alert(1)')}>bad</a>", 1624 false 1625 ], 1626 [ 1627 'namespace escape', 1628 "<script>import * as nav from '$app/navigation'; const copy=nav; copy.goto('javascript:alert(1)');</script>", 1629 false 1630 ], 1631 [ 1632 'namespace Kit navigation', 1633 "<script>import * as nav from '$app/navigation'; const go=()=>nav.goto('/search');</script><button onclick={go}>Search</button>", 1634 true 1635 ], 1636 [ 1637 'reassigned Kit capability', 1638 "<script>import {goto} from '$app/navigation'; goto=x=>x; goto('javascript:alert(1)');</script>", 1639 false 1640 ] 1641 ])) 1642 test(`D07 binding identity: ${name}`, async () => 1643 fixture(async ({ put, execute }) => { 1644 await put( 1645 'src/lib/spoof.ts', 1646 'export const internalHref=(value:unknown)=>value;' 1647 ); 1648 await put('src/routes/+page.svelte', code); 1649 const result = execute(); 1650 assert.equal(result.status, accepted ? 0 : 1, result.stderr); 1651 })); 1652 1653 for (const [code, accepted] of /** @type {Array<[string,boolean]>} */ ([ 1654 [ 1655 "const text='one two';const normalized=text.replace(/\\s+/g,' ');normalized.replace('two','three');", 1656 true 1657 ], 1658 [ 1659 "const seen=new Set<string>(); seen.add('id'); const count=seen.size; const exists=seen.has('id');", 1660 true 1661 ], 1662 ["const seen=new Set<string>(); external(seen); seen.add('id');", false], 1663 ['const seen=new Set<string>(); export const leak=seen;', false], 1664 ["const seen=new Set<string>(); const read=seen.has; read('id');", false] 1665 ])) 1666 test(`D07 concrete receivers: ${code}`, async () => 1667 fixture(async ({ put, execute }) => { 1668 await put('src/routes/+page.ts', code); 1669 const result = execute(); 1670 assert.equal(result.status, accepted ? 0 : 1, result.stderr); 1671 })); 1672 1673 test('D07 package import alias retains helper identity without evaluating configuration', async () => 1674 fixture(async ({ put, execute, pkg }) => { 1675 pkg.imports = { '#links': './src/lib/navigation-url.ts' }; 1676 await put('package.json', JSON.stringify(pkg)); 1677 await put( 1678 'src/routes/+page.svelte', 1679 "<script>import {internalHref as validated} from '#links';const input='/safe';</script><a href={validated(input)}>safe</a>" 1680 ); 1681 assert.equal(execute().status, 0); 1682 })); 1683 1684 for (const command of ['check', 'lint', 'build', 'test:unit', 'dev']) 1685 test(`D07 actual ${command} stops before framework dispatch on computed executable URL`, async () => 1686 fixture(async ({ put, directory }) => { 1687 await put( 1688 'src/routes/+page.svelte', 1689 "<a href={'java'+'script:import(\"nostr-tools\")'}>bad</a>" 1690 ); 1691 await isolateScriptDependencies(directory); 1692 const result = spawnSync('corepack', ['pnpm', 'run', command], { 1693 cwd: directory, 1694 encoding: 'utf8', 1695 timeout: 86400000 1696 }); 1697 assert.equal(result.error, undefined); 1698 assert.equal(result.status, 1, result.stdout + result.stderr); 1699 assert.match(result.stderr, /unsafe markup URL/); 1700 assert.doesNotMatch( 1701 result.stdout, 1702 /svelte-check found|vite v.*building|RUN\s+v/ 1703 ); 1704 })); 1705 1706 test('D07 component props are validated at the actual element sink and compile', async () => 1707 fixture(async ({ put, execute, directory }) => { 1708 const { compile } = await import('svelte/compiler'); 1709 const component = 1710 '<script lang="ts">import {navigationHref} from \'./navigation-url\'; let {href}: {href:unknown}=$props();</script><a href={navigationHref(href)}>Contact</a>'; 1711 const page = 1712 "<script lang=\"ts\">import Link from '../lib/Link.svelte';const contact:unknown='https://example.com';</script><Link href={contact}/>"; 1713 await put('src/lib/Link.svelte', component); 1714 await put('src/routes/+page.svelte', page); 1715 assert.equal(execute().status, 0); 1716 for (const [source, name] of [ 1717 [component, 'src/lib/Link.svelte'], 1718 [page, 'src/routes/+page.svelte'] 1719 ]) { 1720 const compiled = compile(source, { 1721 filename: path.join(directory, name), 1722 generate: 'server' 1723 }); 1724 assert.ok(compiled.js.code.length); 1725 assert.deepEqual(compiled.warnings, []); 1726 } 1727 await put( 1728 'src/lib/Link.svelte', 1729 '<script lang="ts">let {href}: {href:string}=$props();</script><a {href}>Bad</a>' 1730 ); 1731 reject(execute(), /unsafe markup URL/); 1732 })); 1733 1734 test('D07 helper byte pin includes the leading UTF8 BOM', async () => 1735 fixture(async ({ put, execute }) => { 1736 await put( 1737 'src/lib/navigation-url.ts', 1738 '\ufeff' + 1739 (await readFile(path.join(root, 'src/lib/navigation-url.ts'), 'utf8')) 1740 ); 1741 reject(execute(), /source identity/); 1742 })); 1743 1744 for (const producer of [ 1745 "import {goto} from '$app/navigation'; export {goto};", 1746 "import {goto as imported} from '$app/navigation'; export {imported as redirected};", 1747 "import * as navigation from '$app/navigation'; export {navigation};", 1748 "import {goto} from '$app/navigation'; export default goto;" 1749 ]) 1750 test(`D07 local Kit exports cannot launder navigation: ${producer}`, async () => 1751 fixture(async ({ put, execute }) => { 1752 await put('src/lib/escaped.ts', producer); 1753 await put( 1754 'src/routes/+page.ts', 1755 "import {goto as redirected} from '../lib/escaped'; redirected('javascript:alert(1)');" 1756 ); 1757 reject(execute(), /escaped (goto capability|navigation namespace)/); 1758 })); 1759 1760 test('D07 named module Kit reexports retain sink identity for actual consumers', async () => 1761 fixture(async ({ put, execute }) => { 1762 await put( 1763 'src/lib/navigation.ts', 1764 "export {goto as navigate} from '$app/navigation';" 1765 ); 1766 await put( 1767 'src/routes/+page.ts', 1768 "import {navigate} from '../lib/navigation'; navigate('/search');" 1769 ); 1770 assert.equal(execute().status, 0); 1771 await put( 1772 'src/routes/+page.ts', 1773 "import {navigate} from '../lib/navigation'; navigate('javascript:alert(1)');" 1774 ); 1775 reject(execute(), /defined validated internal URL/); 1776 })); 1777 1778 test('D07 local helper reexports are untrusted until explicitly resolved at a sink', async () => 1779 fixture(async ({ put, execute }) => { 1780 await put( 1781 'src/lib/indirect.ts', 1782 "import {internalHref} from './navigation-url'; export {internalHref as validated};" 1783 ); 1784 await put( 1785 'src/routes/+page.svelte', 1786 "<script>import {validated} from '../lib/indirect';const route='/safe';</script><a href={validated(route)}>Unknown binding</a>" 1787 ); 1788 reject(execute(), /unsafe markup URL/); 1789 })); 1790 1791 test('D07 literal Svelte element tags share URL context admission and compile', async () => 1792 fixture(async ({ put, execute, directory }) => { 1793 const { compile } = await import('svelte/compiler'); 1794 const positive = 1795 "<svelte:element this={'a'} href='https://example.com'>Contact</svelte:element>"; 1796 await put('src/routes/+page.svelte', positive); 1797 assert.equal(execute().status, 0); 1798 const compiled = compile(positive, { 1799 filename: path.join(directory, 'src/routes/+page.svelte'), 1800 generate: 'server' 1801 }); 1802 assert.ok(compiled.js.code.length); 1803 assert.deepEqual(compiled.warnings, []); 1804 for (const source of [ 1805 "<svelte:element this='a' href={'java'+'script:alert(1)'}>Bad</svelte:element>", 1806 "<svelte:element this='img' src='https://example.com/image.png' alt='Bad'/>", 1807 "<svelte:element this='image' href='https://example.com/image.png'/>", 1808 "<script>const tag='a';</script><svelte:element this={tag} href='https://example.com'>Unsupported</svelte:element>" 1809 ]) { 1810 await put('src/routes/+page.svelte', source); 1811 reject(execute(), /unsafe markup URL|computed markup resource elements/); 1812 } 1813 })); 1814 1815 for (const barrel of [ 1816 "export * from './bridge';", 1817 "export * as navigation from './bridge';" 1818 ]) 1819 test(`D07 Kit capability cannot escape renamed bridge through ${barrel}`, async () => 1820 fixture(async ({ put, execute }) => { 1821 await put( 1822 'src/lib/bridge.ts', 1823 "export {goto as redirect} from '$app/navigation';" 1824 ); 1825 await put('src/lib/barrel.ts', barrel); 1826 await put( 1827 'src/routes/+page.ts', 1828 "import {redirect} from '../lib/barrel';redirect('javascript:alert(1)');" 1829 ); 1830 reject(execute(), /navigation star\/namespace reexport/); 1831 })); 1832 1833 test('D07 renamed Kit namespace aliases cannot escape actual binding identity', async () => 1834 fixture(async ({ put, execute }) => { 1835 await put( 1836 'src/lib/bridge.ts', 1837 "export {goto as redirect} from '$app/navigation';" 1838 ); 1839 await put( 1840 'src/routes/+page.ts', 1841 "import * as navigation from '../lib/bridge'; const escaped=navigation;escaped.redirect('javascript:alert(1)');" 1842 ); 1843 reject(execute(), /escaped navigation namespace/); 1844 })); 1845 1846 for (const source of [ 1847 "location.assign(setTimeout('alert(1)',0) ? '/one' : '/two');", 1848 "import {goto} from '$app/navigation'; location.assign(goto('javascript:alert(1)') ? '/one' : '/two');", 1849 "window.location.href=setInterval('alert(1)',100) ? '/one' : '/two';" 1850 ]) 1851 test(`D07 accepted Location URL does not hide hostile expression descendants: ${source}`, async () => 1852 fixture(async ({ put, execute }) => { 1853 await put('src/routes/+page.ts', source); 1854 reject( 1855 execute(), 1856 /direct function callback|defined validated internal URL/ 1857 ); 1858 })); 1859 1860 test('D07 Location conditional callback expressions remain admitted with complete descendant audit', async () => 1861 fixture(async ({ put, execute }) => { 1862 await put( 1863 'src/routes/+page.ts', 1864 "location.assign(setTimeout(()=>{},0) ? '/one' : '/two'); window.location.replace('/search'); window.location.href='/search';" 1865 ); 1866 const result = execute(); 1867 assert.equal(result.status, 0, result.stderr); 1868 })); 1869 1870 for (const source of [ 1871 "Set = fake; const seen=new Set(); seen.add('id');", 1872 "Set ||= fake; const seen=new Set(); seen.add('id');", 1873 "Set = fake; const seen=new Set(); const read=seen.has; read('id');" 1874 ]) 1875 test(`D07 global collection constructor rebinding is untrusted: ${source}`, async () => 1876 fixture(async ({ put, execute }) => { 1877 await put('src/routes/+page.ts', source); 1878 const result = execute(); 1879 assert.equal(result.status, 1, result.stdout + result.stderr); 1880 })); 1881 1882 for (const href of [ 1883 'https:////@example.com', 1884 'https:///@example.com', 1885 'https:////example.com' 1886 ]) 1887 test(`D07 malformed HTTPS authority cannot normalize away credentials: ${href}`, async () => 1888 fixture(async ({ put, execute }) => { 1889 await put( 1890 'src/routes/+page.svelte', 1891 `<a href=${JSON.stringify(href)}>Bad</a>` 1892 ); 1893 reject(execute(), /unsafe markup URL/); 1894 })); 1895 1896 const smilMutation = 1897 "<svg width='300' height='100'><a id='link' href='/safe'><text x='10' y='50'>Click</text></a><set href='#link' attributeName='href' to='javascript:window.__smilExecuted=true' begin='0s' fill='freeze'/></svg>"; 1898 for (const tag of [ 1899 'set', 1900 'animate', 1901 'animateMotion', 1902 'animateTransform', 1903 'discard', 1904 'SET', 1905 'svg:animate', 1906 'svg:animateTransform' 1907 ]) 1908 test(`D07 declarative SVG mutation tag is rejected: ${tag}`, async () => 1909 fixture(async ({ put, execute }) => { 1910 await put( 1911 'src/routes/+page.svelte', 1912 `<svg><${tag} href='#link' attributeName='href' to='javascript:alert(1)'/></svg>` 1913 ); 1914 reject(execute(), /declarative SVG resource\/style mutation/); 1915 })); 1916 1917 for (const tag of [ 1918 'set', 1919 'animate', 1920 'animateMotion', 1921 'animateTransform', 1922 'discard', 1923 'SVG:SET' 1924 ]) 1925 test(`D07 literal Svelte element cannot construct SVG mutation: ${tag}`, async () => 1926 fixture(async ({ put, execute }) => { 1927 await put( 1928 'src/routes/+page.svelte', 1929 `<svg><svelte:element this={${JSON.stringify(tag)}} href='#link' attributeName='href' to='javascript:alert(1)'/></svg>` 1930 ); 1931 reject(execute(), /declarative SVG resource\/style mutation/); 1932 })); 1933 1934 test('D07 actual SMIL href mutation fixture rejects while static SVG compiles', async () => 1935 fixture(async ({ put, execute, directory }) => { 1936 await put('src/routes/+page.svelte', smilMutation); 1937 reject(execute(), /declarative SVG resource\/style mutation/); 1938 const source = 1939 "<svg viewBox='0 0 100 100' role='img' aria-label='Static graphic'><path d='M0 0 L20 20'/><a href='/safe'><text x='10' y='50'>Safe link</text></a></svg>"; 1940 await put('src/routes/+page.svelte', source); 1941 assert.equal(execute().status, 0); 1942 const { compile } = await import('svelte/compiler'); 1943 const compiled = compile(source, { 1944 filename: path.join(directory, 'src/routes/+page.svelte'), 1945 generate: 'server' 1946 }); 1947 assert.ok(compiled.js.code.length); 1948 assert.deepEqual(compiled.warnings, []); 1949 })); 1950 1951 for (const source of [ 1952 'export function motion(element:Element){element.animate([{opacity:0},{opacity:1}],100);}', 1953 'export function motion(element:Element){const animate=element.animate;animate.call(element,[{opacity:0},{opacity:1}],100);}', 1954 "export function motion(element:Element){const key='animate';const escaped=element[key];escaped([{opacity:0},{opacity:1}],100);}", 1955 "export function motion(element:Element){const escaped=element['ani'+'mate'];escaped([{opacity:0},{opacity:1}],100);}", 1956 "export function motion(element:Element,flag:boolean){const key=flag?'animate':'setKeyframes';const escaped=element[key];escaped([{opacity:0},{opacity:1}],100);}", 1957 'export function motion(effect:KeyframeEffect){effect.setKeyframes([{opacity:0},{opacity:1}]);}', 1958 'export function motion(effect:KeyframeEffect){const update=effect.setKeyframes;update([{opacity:0},{opacity:1}]);}', 1959 'export function motion(element:Element){new KeyframeEffect(element,[{opacity:0},{opacity:1}],100);}', 1960 'const Effect=KeyframeEffect;new Effect(opaque,[{opacity:0},{opacity:1}],100);', 1961 'new Animation(opaque);', 1962 'const CreateAnimation=Animation;new CreateAnimation(opaque);', 1963 "document.createElementNS('http://www.w3.org/2000/svg','set');" 1964 ]) 1965 test(`D07 imperative style/animation capability is rejected: ${source}`, async () => 1966 fixture(async ({ put, execute }) => { 1967 await put('src/routes/+page.ts', source); 1968 const result = execute(); 1969 assert.equal(result.status, 1, result.stdout + result.stderr); 1970 assert.match( 1971 result.stderr, 1972 /mutation\/setter|animation constructors|SVG resource\/style constructors|DOM handles/ 1973 ); 1974 })); 1975 1976 test('D07 animation names remain ordinary owned model data', async () => 1977 fixture(async ({ put, execute }) => { 1978 await put( 1979 'src/routes/+page.ts', 1980 "const model={animate:false,setKeyframes:0}; model.animate=true;model.setKeyframes+=1; export const flag=model.animate;export const revision=model.setKeyframes; function Animation(value:string){return value} export const label=Animation('ordinary model');" 1981 ); 1982 const result = execute(); 1983 assert.equal(result.status, 0, result.stderr); 1984 })); 1985 1986 for (const command of ['check', 'lint', 'build', 'test:unit', 'dev']) 1987 test(`D07 actual ${command} stops before framework dispatch on SVG URL mutation`, async () => 1988 fixture(async ({ put, directory }) => { 1989 await put('src/routes/+page.svelte', smilMutation); 1990 await isolateScriptDependencies(directory); 1991 const result = spawnSync('corepack', ['pnpm', 'run', command], { 1992 cwd: directory, 1993 encoding: 'utf8', 1994 timeout: 86400000 1995 }); 1996 assert.equal(result.error, undefined); 1997 assert.equal(result.status, 1, result.stdout + result.stderr); 1998 assert.match(result.stderr, /declarative SVG resource\/style mutation/); 1999 assert.doesNotMatch( 2000 result.stdout, 2001 /svelte-check found|vite v.*building|RUN\s+v/ 2002 ); 2003 })); 2004 2005 test('HCP020 admits the pinned Kit3 consolidated parameter module at its exact source location', async () => { 2006 await fixture(async ({ directory, put, execute }) => { 2007 await confineSvelte(directory); 2008 for (const name of ['package.json', 'src/exports/params/index.js']) { 2009 await put( 2010 'node_modules/@sveltejs/kit/' + name, 2011 await readFile(path.join(root, 'node_modules/@sveltejs/kit', name)) 2012 ); 2013 } 2014 await put( 2015 'src/params.ts', 2016 "import { defineParams } from '@sveltejs/kit/params'; export const params = defineParams({ local_id: (value: string) => value === 'known' ? value : undefined });" 2017 ); 2018 await put( 2019 'src/routes/+page.ts', 2020 "import { params } from '../params'; export const value = params;" 2021 ); 2022 const result = execute(); 2023 assert.equal(result.status, 0, result.stderr); 2024 }); 2025 }); 2026 for (const [name, specifier] of [ 2027 ['src/routes/+page.ts', '@sveltejs/kit/params'], 2028 ['src/params.ts', '@sveltejs/kit/params/unknown'] 2029 ]) { 2030 test( 2031 'HCP020 rejects unrelated Kit3 parameter import ' + name + ' ' + specifier, 2032 async () => { 2033 await fixture(async ({ put, execute }) => { 2034 await put( 2035 name, 2036 "import { defineParams } from '" + 2037 specifier + 2038 "'; export const value = defineParams;" 2039 ); 2040 if (name === 'src/params.ts') 2041 await put( 2042 'src/routes/+page.ts', 2043 "import { value } from '../params'; export { value };" 2044 ); 2045 reject(execute(), /forbidden production import/); 2046 }); 2047 } 2048 ); 2049 } 2050 2051 test('HCP030 admits a direct add on an immutable actual EventStore instance', async () => { 2052 await fixture(async ({ directory, put, execute }) => { 2053 await confineSvelte(directory); 2054 const { cp } = await import('node:fs/promises'); 2055 await cp( 2056 await realpath(path.join(root, 'node_modules/applesauce-core')), 2057 path.join(directory, 'node_modules/applesauce-core'), 2058 { recursive: true } 2059 ); 2060 await put( 2061 'src/lib/nostr/store.ts', 2062 "import { EventStore } from 'applesauce-core'; const sdk = new EventStore({keepOldVersions:true}); export function admit(event:unknown){return sdk.add(event);}" 2063 ); 2064 await put( 2065 'src/routes/+page.ts', 2066 "export { admit } from '../lib/nostr/store';" 2067 ); 2068 const result = execute(); 2069 assert.equal(result.status, 0, result.stderr); 2070 }); 2071 }); 2072 for (const source of [ 2073 'export function admit(sdk:{add:(value:unknown)=>unknown},event:unknown){return sdk.add(event);}', 2074 'class EventStore { add(value:unknown){return value;} } const sdk = new EventStore(); export function admit(event:unknown){return sdk.add(event);}', 2075 "import { EventStore } from 'applesauce-core'; const sdk = new EventStore(); const add=sdk.add; export function admit(event:unknown){return add(event);}", 2076 "import { EventStore } from 'applesauce-core'; const sdk = new EventStore(); export function admit(event:unknown){return sdk['add'](event);}", 2077 "import { EventStore } from 'applesauce-core'; let sdk = new EventStore(); export function admit(event:unknown){return sdk.add(event);}", 2078 "import { EventStore } from 'applesauce-core'; const sdk = new EventStore(); sdk=opaque; export function admit(event:unknown){return sdk.add(event);}", 2079 "import { EventStore } from 'applesauce-core'; EventStore=opaque; const sdk = new EventStore(); export function admit(event:unknown){return sdk.add(event);}", 2080 "import { EventStore } from 'applesauce-core'; const sdk = new EventStore(); export function admit(){return sdk.add();}", 2081 "import { EventStore } from 'applesauce-core'; const sdk = new EventStore(); export function admit(event:unknown){return sdk.add(event,event);}", 2082 "import { EventStore } from 'applesauce-core'; const Constructor=EventStore; const sdk = new Constructor(); export function admit(event:unknown){return sdk.add(event);}", 2083 "import { EventStore } from 'applesauce-core'; const sdk = new EventStore(); sdk.add=opaque; export function admit(event:unknown){return sdk.add(event);}", 2084 "import { EventStore } from 'applesauce-core'; const sdk = new EventStore(); export function admit(event:unknown){return sdk.add.call(sdk,event);}" 2085 ]) 2086 test(`HCP030 rejects unqualified or escaped EventStore mutation: ${source}`, async () => { 2087 await fixture(async ({ directory, put, execute }) => { 2088 await confineSvelte(directory); 2089 const { cp } = await import('node:fs/promises'); 2090 await cp( 2091 await realpath(path.join(root, 'node_modules/applesauce-core')), 2092 path.join(directory, 'node_modules/applesauce-core'), 2093 { recursive: true } 2094 ); 2095 await put('src/lib/nostr/store.ts', source); 2096 await put( 2097 'src/routes/+page.ts', 2098 "export { admit } from '../lib/nostr/store';" 2099 ); 2100 reject(execute(), /mutation|owned|prototype/); 2101 }); 2102 }); 2103 2104 test('HCP029 admits direct read-only descriptor inspection of unknown data', async () => { 2105 await fixture(async ({ put, execute }) => { 2106 await put( 2107 'src/routes/+page.ts', 2108 'export function read(value: object, key: string) { const descriptor = Object.getOwnPropertyDescriptor(value, key); return descriptor && "value" in descriptor ? descriptor.value : undefined; }' 2109 ); 2110 const result = execute(); 2111 assert.equal(result.status, 0, result.stderr); 2112 }); 2113 }); 2114 for (const source of [ 2115 'const read = Object.getOwnPropertyDescriptor; export function inspect(value: object) { return read(value, "content"); }', 2116 'export function inspect(value: object) { return Object["getOwnPropertyDescriptor"](value, "content"); }', 2117 'export function inspect(value: object) { return Object.getOwnPropertyDescriptor.call(Object, value, "content"); }', 2118 'export function inspect(value: object, Object: { getOwnPropertyDescriptor: (value: object, key: string) => unknown }) { return Object.getOwnPropertyDescriptor(value, "content"); }', 2119 'declare const fake: typeof Object; Object = fake; export function inspect(value: object) { return Object.getOwnPropertyDescriptor(value, "content"); }', 2120 'export function inspect(value: object) { return Reflect.getOwnPropertyDescriptor(value, "content"); }', 2121 'export function inspect(value: object) { return Object.getOwnPropertyDescriptors(value); }', 2122 'export function inspect(value: object) { return Object.defineProperty(value, "content", { value: "untrusted" }); }', 2123 'export function inspect(value: object) { const descriptor = Object.getOwnPropertyDescriptor(value, "content"); if (descriptor) descriptor.value = "untrusted"; }', 2124 'export function inspect() { return Object.getOwnPropertyDescriptor(); }' 2125 ]) 2126 test(`HCP029 descriptor admission rejects escaped, shadowed or mutating operation: ${source}`, async () => { 2127 await fixture(async ({ put, execute }) => { 2128 await put('src/routes/+page.ts', source); 2129 reject(execute(), /descriptor|reflection|mutation|owned/); 2130 }); 2131 }); 2132 2133 test('only the exact reviewed scroll owner admits scalar history restoration', async () => { 2134 await fixture(async ({ put, execute }) => { 2135 const helper = await readFile( 2136 path.join(root, 'src/lib/navigation-scroll.ts'), 2137 'utf8' 2138 ); 2139 await put('src/lib/navigation-scroll.ts', helper); 2140 await put( 2141 'src/routes/+page.ts', 2142 "import {captureSearchScroll,restoreSearchScroll} from '../lib/navigation-scroll.ts'; export function restore(){restoreSearchScroll(captureSearchScroll());}" 2143 ); 2144 assert.equal(execute().status, 0); 2145 for (const extra of [ 2146 'window.scrollTo(0,1);', 2147 'const scroll=window.scrollTo; scroll(0,1);', 2148 "window['scrollTo'](0,1);", 2149 'const owner=window; owner.scrollTo(0,1);', 2150 'window.scrollTo(0,Infinity);', 2151 'window.scrollTo(0,-1);', 2152 'export const escaped=window;', 2153 'window.document.body.innerHTML="changed";' 2154 ]) { 2155 await put('src/lib/navigation-scroll.ts', helper + '\n' + extra); 2156 assert.notEqual(execute().status, 0, extra); 2157 } 2158 await put('src/lib/navigation-scroll.ts', helper); 2159 await put('src/routes/+page.ts', 'export const position=window.scrollY;'); 2160 assert.notEqual(execute().status, 0); 2161 await put('src/routes/+page.ts', 'window.scrollTo(0,1);'); 2162 assert.notEqual(execute().status, 0); 2163 await put('src/routes/+page.ts', 'export const value=1;'); 2164 await put('src/lib/copied-scroll.ts', helper); 2165 assert.notEqual(execute().status, 0); 2166 }); 2167 }); 2168 2169 test('history scroll owner rejects malformed values without coercion or SSR effects', async () => { 2170 const { captureSearchScroll, restoreSearchScroll } = 2171 await import('../../src/lib/navigation-scroll.ts'); 2172 const previous = Object.getOwnPropertyDescriptor(globalThis, 'window'); 2173 /** @type {number[][]} */ 2174 const calls = []; 2175 try { 2176 Reflect.deleteProperty(globalThis, 'window'); 2177 assert.equal(captureSearchScroll(), undefined); 2178 restoreSearchScroll(42); 2179 Object.defineProperty(globalThis, 'window', { 2180 configurable: true, 2181 value: { 2182 scrollY: 2317, 2183 scrollTo: (/** @type {number[]} */ ...args) => calls.push(args) 2184 } 2185 }); 2186 assert.equal(captureSearchScroll(), 2317); 2187 for (const value of [ 2188 NaN, 2189 Infinity, 2190 -1, 2191 '42', 2192 {}, 2193 null, 2194 Number.MAX_SAFE_INTEGER + 1 2195 ]) 2196 restoreSearchScroll(value); 2197 assert.equal(calls.length, 0); 2198 restoreSearchScroll(2317); 2199 assert.deepEqual(calls, [[0, 2317]]); 2200 globalThis.window.scrollY = Infinity; 2201 assert.equal(captureSearchScroll(), undefined); 2202 } finally { 2203 if (previous) Object.defineProperty(globalThis, 'window', previous); 2204 else Reflect.deleteProperty(globalThis, 'window'); 2205 } 2206 }); 2207 2208 test( 2209 'HCP076 allows only the byte-pinned disposable gift-wrap producer and rejects key escape or copied construction', 2210 // Sequential audits retain generous host allowances on busy workstations. 2211 { timeout: 86400000 }, 2212 async () => { 2213 await fixture(async ({ directory, put, execute }) => { 2214 await confineSvelte(directory); 2215 const { cp } = await import('node:fs/promises'); 2216 for (const name of [ 2217 'applesauce-core', 2218 'applesauce-signers', 2219 'applesauce-relay', 2220 'rxjs', 2221 '@noble/curves', 2222 '@scure/base' 2223 ]) { 2224 const destination = path.join(directory, 'node_modules', name); 2225 await mkdir(path.dirname(destination), { recursive: true }); 2226 await cp( 2227 await realpath(path.join(root, 'node_modules', name)), 2228 destination, 2229 { recursive: true } 2230 ); 2231 } 2232 await cp(path.join(root, 'src/lib'), path.join(directory, 'src/lib'), { 2233 recursive: true 2234 }); 2235 const name = 'src/lib/nostr/giftwrap-builder.ts', 2236 source = await readFile(path.join(root, name), 'utf8'); 2237 assert.equal(execute().status, 0); 2238 for (const alteration of [ 2239 source + '\nexport const secret = generateSecretKey();', 2240 source.replace('secret?.fill(0);', '// cleanup removed'), 2241 source.replace('nip44.v2.decrypt(', 'nip44.v2.encrypt('), 2242 source.replace('kind: 1059,', 'kind: 14,'), 2243 source.replace( 2244 "tags: [['p', record.destination]],", 2245 "tags: [['p', record.peer], ['subject', 'leak']]," 2246 ), 2247 source.replace( 2248 "review !== 'reviewed_private_wrap'", 2249 "review !== 'connect'" 2250 ), 2251 source.replace( 2252 "review !== 'reviewed_inbox_probe_wrap'", 2253 "review !== 'connect'" 2254 ), 2255 source.replace( 2256 'record.destination !== record.owner', 2257 'record.destination !== record.destination' 2258 ), 2259 source.replace("'applesauce-core/helpers'", "'nostr-tools/pure'") 2260 ]) { 2261 assert.notEqual(alteration, source); 2262 await put(name, alteration); 2263 reject(execute(), /gift-wrap construction source identity/); 2264 } 2265 await put(name, source); 2266 await put('src/lib/nostr/copied-giftwrap-builder.ts', source); 2267 reject(execute(), /credential API/); 2268 }); 2269 } 2270 ); 2271 test( 2272 'HCP076 rejects production key generation and secret access through named, aliased, namespace and bracket APIs outside the exact wrapper', 2273 { timeout: 86400000 }, 2274 async () => { 2275 await fixture(async ({ directory, put, execute }) => { 2276 await confineSvelte(directory); 2277 const { cp } = await import('node:fs/promises'); 2278 await cp( 2279 await realpath(path.join(root, 'node_modules/applesauce-core')), 2280 path.join(directory, 'node_modules/applesauce-core'), 2281 { recursive: true } 2282 ); 2283 for (const source of [ 2284 "import * as sdk from 'applesauce-core/helpers'; const {'getPublicKey':read}=sdk; export const value=read;", 2285 "import * as sdk from 'applesauce-core/helpers'; const {['getPublicKey']:read}=sdk; export const value=read;" 2286 ]) { 2287 await put('src/lib/nostr/other.ts', source); 2288 assert.equal(execute().status, 0); 2289 } 2290 for (const source of [ 2291 "import {generateSecretKey} from 'applesauce-core/helpers'; export const key=generateSecretKey();", 2292 "import {generateSecretKey as createKey} from 'applesauce-core/helpers'; export const key=createKey();", 2293 "import * as sdk from 'applesauce-core/helpers'; export const key=sdk.generateSecretKey();", 2294 "import * as sdk from 'applesauce-core/helpers'; export const create=sdk['generateSecretKey'];", 2295 "import * as sdk from 'applesauce-core/helpers'; const {'generateSecretKey':create}=sdk; export const key=create();", 2296 "import * as sdk from 'applesauce-core/helpers'; const {['generateSecretKey']:create}=sdk; export const key=create();", 2297 "import * as sdk from 'applesauce-core/helpers'; const {['generate'+'SecretKey']:create}=sdk; export const key=create();", 2298 "import * as sdk from 'applesauce-core/helpers'; const method=['generate','SecretKey'].join(''); const {[method]:create}=sdk; export const key=create();", 2299 "export const key = provider['getSecretKey'];", 2300 "provider['setSecretKey'](input);", 2301 "const {'getSecretKey':read}=provider; export const key=read();", 2302 "const {'setSecretKey':save}=provider; save(input);" 2303 ]) { 2304 await put('src/lib/nostr/other.ts', source); 2305 reject(execute(), /credential API/); 2306 } 2307 }); 2308 } 2309 ); 2310 2311 test('package-script fixtures preserve the primary generated dependency launcher', async () => { 2312 await fixture(async ({ directory, put }) => { 2313 const relative = 'node_modules/applesauce-signers/node_modules/.bin/nanoid'; 2314 const primary = path.join(root, relative); 2315 const before = await readFile(primary); 2316 const primaryStat = await lstat(primary); 2317 assert.equal(primaryStat.isFile(), true); 2318 assert.equal(primaryStat.nlink, 1); 2319 await isolateScriptDependencies(directory); 2320 const isolated = path.join(directory, relative); 2321 const isolatedStat = await lstat(isolated); 2322 assert.equal(isolatedStat.isFile(), true); 2323 assert.equal(isolatedStat.nlink, 1); 2324 assert.notEqual( 2325 `${isolatedStat.dev}:${isolatedStat.ino}`, 2326 `${primaryStat.dev}:${primaryStat.ino}` 2327 ); 2328 assert.deepEqual(await readFile(isolated), before); 2329 await writeFile( 2330 isolated, 2331 Buffer.concat([before, Buffer.from('\n# fixture-only mutation\n')]) 2332 ); 2333 assert.deepEqual(await readFile(primary), before); 2334 await put('src/routes/+page.ts', "void import('nostr-tools');"); 2335 const result = spawnSync('corepack', ['pnpm', 'run', 'check'], { 2336 cwd: directory, 2337 encoding: 'utf8', 2338 timeout: 86400000 2339 }); 2340 assert.equal(result.error, undefined); 2341 assert.equal(result.status, 1, result.stdout + result.stderr); 2342 assert.match(result.stderr, /forbidden production import nostr-tools/); 2343 assert.doesNotMatch( 2344 result.stdout, 2345 /svelte-check found|vite v.*building|RUN\s+v/ 2346 ); 2347 assert.deepEqual(await readFile(primary), before); 2348 }); 2349 });