source-boundaries.mjs (87025B)
1 import { readdir, open, lstat, realpath } from 'node:fs/promises'; 2 import { constants } from 'node:fs'; 3 import path from 'node:path'; 4 import { createRequire } from 'node:module'; 5 import { createHash } from 'node:crypto'; 6 import ts from 'typescript'; 7 import { parse } from 'svelte/compiler'; 8 9 const byteLimit = 8 * 1024 * 1024; 10 const codeExtension = /\.(svelte|[cm]?[jt]sx?)$/; 11 const forbiddenPath = 12 /(^|\/)(tests?|__tests__|fixtures?|harness|providers?|credentials?|core|app|foundation|enterprise|ops|generated|node_modules|build|\.svelte-kit)(\/|$)|\.(test|spec)\./i; 13 const applesauce = new Set([ 14 'applesauce-core', 15 'applesauce-relay', 16 'applesauce-signers', 17 'applesauce-common', 18 'applesauce-loaders' 19 ]); 20 const runtimePackages = new Set([ 21 'svelte', 22 '@sveltejs/kit', 23 'rxjs', 24 ...applesauce 25 ]); 26 const frameworkModules = new Set([ 27 '$app/env', 28 '$app/env/public', 29 '$app/forms', 30 '$app/navigation', 31 '$app/paths', 32 '$app/state' 33 ]); 34 const declarativeMutationTags = new Set([ 35 'set', 36 'animate', 37 'animatemotion', 38 'animatetransform', 39 'discard' 40 ]); 41 const inside = (directory, file) => file.startsWith(directory + path.sep); 42 const relative = (root, file) => 43 path.relative(root, file).split(path.sep).join('/'); 44 45 // Admit bytes before any third-party parser. Retain the opened identity and 46 // reject replacement, hardlinks, mutation, symlinks and nonregular entries. 47 async function readSource(file) { 48 const before = await lstat(file); 49 if (!before.isFile() || before.nlink !== 1 || (await realpath(file)) !== file) 50 throw new Error(`Unsafe source file: ${file}`); 51 const handle = await open( 52 file, 53 constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK 54 ); 55 try { 56 const stat = await handle.stat(); 57 if ( 58 !stat.isFile() || 59 stat.nlink !== 1 || 60 stat.size > byteLimit || 61 stat.dev !== before.dev || 62 stat.ino !== before.ino 63 ) 64 throw new Error(`Unsafe source file: ${file}`); 65 const chunks = []; 66 let size = 0; 67 for (;;) { 68 const buffer = Buffer.alloc(64 * 1024); 69 const { bytesRead } = await handle.read(buffer); 70 if (!bytesRead) break; 71 size += bytesRead; 72 if (size > byteLimit) 73 throw new Error(`Source file exceeds audit limit: ${file}`); 74 chunks.push(buffer.subarray(0, bytesRead)); 75 } 76 const after = await handle.stat(); 77 const named = await lstat(file); 78 if ( 79 size !== stat.size || 80 after.size !== stat.size || 81 after.mtimeMs !== stat.mtimeMs || 82 after.ctimeMs !== stat.ctimeMs || 83 named.dev !== stat.dev || 84 named.ino !== stat.ino || 85 !named.isFile() || 86 named.nlink !== 1 || 87 (await realpath(file)) !== file 88 ) 89 throw new Error(`Source file changed during audit: ${file}`); 90 return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode( 91 Buffer.concat(chunks) 92 ); 93 } finally { 94 await handle.close(); 95 } 96 } 97 98 function sourceAst(file, text) { 99 const ast = ts.createSourceFile( 100 file, 101 text, 102 ts.ScriptTarget.Latest, 103 true, 104 file.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS 105 ); 106 if (ast.parseDiagnostics.length) 107 throw new Error(`${file}: invalid source syntax`); 108 return ast; 109 } 110 // A source guard is not a JavaScript sandbox. Admit a deliberately bounded DOM 111 // grammar: direct focus/blur/scroll and scalar control reads; no escaped nodes, 112 // actions, bindings, raw render factories or opaque object mutation. Svelte owns 113 // DOM updates. Mutable application data must be locally owned plain data, with 114 // pure values and lexical aliases. Future imperative UI work needs explicit 115 // admission and negative tests rather than a type cast or an ignored diagnostic. 116 function mutationAdmission( 117 ast, 118 report, 119 identity = () => null, 120 reviewedScroll = false, 121 reviewedCopy = false, 122 reviewedVisibility = false, 123 reviewedReport = false, 124 reviewedRelayRemoval = false 125 ) { 126 // Bind this admitted AST only, without libs, module resolution, file reads, 127 // config loading or evaluation. Symbols distinguish aliases and shadowing. 128 const options = { 129 noLib: true, 130 noResolve: true, 131 types: [], 132 allowNonTsExtensions: true 133 }; 134 const host = { 135 ...ts.createCompilerHost(options), 136 getSourceFile: (name) => (name === ast.fileName ? ast : undefined), 137 fileExists: (name) => name === ast.fileName, 138 directoryExists: () => false, 139 getDirectories: () => [], 140 readFile: () => undefined 141 }; 142 const checker = ts 143 .createProgram([ast.fileName], options, host) 144 .getTypeChecker(); 145 const unwrap = (node) => { 146 while ( 147 node && 148 (ts.isParenthesizedExpression(node) || 149 ts.isAsExpression(node) || 150 ts.isTypeAssertionExpression(node) || 151 ts.isNonNullExpression(node)) 152 ) 153 node = node.expression; 154 return node; 155 }; 156 const member = (node) => 157 ts.isPropertyAccessExpression(node) 158 ? node.name.text 159 : ts.isElementAccessExpression(node) && 160 ts.isStringLiteralLike(node.argumentExpression) 161 ? node.argumentExpression.text 162 : null; 163 function relayRemoval(node) { 164 if ( 165 !reviewedRelayRemoval || 166 !ts.isPropertyAccessExpression(node) || 167 node.name.text !== 'remove' || 168 !ts.isIdentifier(node.expression) || 169 !ts.isCallExpression(node.parent) || 170 node.parent.expression !== node || 171 node.parent.arguments.length !== 1 || 172 !ts.isIdentifier(node.parent.arguments[0]) 173 ) 174 return false; 175 const declaration = checker.getSymbolAtLocation( 176 node.expression 177 )?.valueDeclaration; 178 if ( 179 !declaration || 180 !ts.isVariableDeclaration(declaration) || 181 !(declaration.parent.flags & ts.NodeFlags.Const) 182 ) 183 return false; 184 const call = declaration.initializer && unwrap(declaration.initializer); 185 if ( 186 !call || 187 !ts.isCallExpression(call) || 188 call.arguments.length !== 0 || 189 !ts.isIdentifier(call.expression) 190 ) 191 return false; 192 const factory = checker.getSymbolAtLocation(call.expression) 193 ?.declarations?.[0]; 194 if ( 195 !factory || 196 !ts.isImportSpecifier(factory) || 197 (factory.propertyName?.text ?? factory.name.text) !== 198 'createScopedRelayPool' 199 ) 200 return false; 201 const imported = factory.parent.parent.parent; 202 return ( 203 ts.isImportDeclaration(imported) && 204 ts.isStringLiteral(imported.moduleSpecifier) && 205 imported.moduleSpecifier.text === './pool-factory.ts' 206 ); 207 } 208 function uiLeaf(node) { 209 let top = node; 210 while ( 211 top.parent && 212 (ts.isPropertyAccessExpression(top.parent) || 213 ts.isElementAccessExpression(top.parent) || 214 ts.isCallExpression(top.parent) || 215 ts.isNonNullExpression(top.parent) || 216 ts.isAsExpression(top.parent) || 217 ts.isParenthesizedExpression(top.parent)) && 218 top.parent.expression === top 219 ) 220 top = top.parent; 221 // Only the byte-pinned private disposal owner observes scalar visibility 222 // and owns this one fixed event registration. No document handle escapes. 223 if (reviewedVisibility) { 224 const receiver = ts.isCallExpression(top) ? top.expression : top; 225 if ( 226 ts.isPropertyAccessExpression(receiver) && 227 ts.isIdentifier(receiver.expression) && 228 receiver.expression.text === 'document' && 229 !checker.getSymbolAtLocation(receiver.expression) 230 ) { 231 if ( 232 !ts.isCallExpression(top) && 233 receiver.name.text === 'visibilityState' 234 ) 235 return true; 236 if ( 237 ts.isCallExpression(top) && 238 ['addEventListener', 'removeEventListener'].includes( 239 receiver.name.text 240 ) && 241 top.arguments.length === 2 && 242 ts.isStringLiteralLike(top.arguments[0]) && 243 top.arguments[0].text === 'visibilitychange' && 244 ts.isIdentifier(top.arguments[1]) && 245 top.arguments[1].text === 'onVisibility' 246 ) 247 return true; 248 } 249 } 250 const action = 251 ts.isCallExpression(top) && 252 ['focus', 'blur', 'scrollIntoView'].includes(member(top.expression)) && 253 top.arguments.length === 0; 254 const read = 255 !action && 256 ['value', 'checked', 'selectedIndex', 'textContent'].includes( 257 member(top) 258 ); 259 if (!action && !read) return false; 260 const receiver = unwrap( 261 action ? top.expression.expression : top.expression 262 ); 263 if ( 264 ts.isPropertyAccessExpression(receiver) && 265 ['currentTarget', 'target'].includes(receiver.name.text) 266 ) 267 return true; 268 return ( 269 ts.isCallExpression(receiver) && 270 ts.isPropertyAccessExpression(receiver.expression) && 271 ts.isIdentifier(receiver.expression.expression) && 272 receiver.expression.expression.text === 'document' && 273 !checker.getSymbolAtLocation(receiver.expression.expression) && 274 ['getElementById', 'querySelector'].includes( 275 receiver.expression.name.text 276 ) && 277 receiver.arguments.length === 1 && 278 ts.isStringLiteralLike(receiver.arguments[0]) 279 ); 280 } 281 function pure(node, seen = new Set()) { 282 node = unwrap(node); 283 if (!node) return false; 284 if ( 285 ts.isStringLiteralLike(node) || 286 ts.isNumericLiteral(node) || 287 ts.isBigIntLiteral(node) || 288 [ 289 ts.SyntaxKind.TrueKeyword, 290 ts.SyntaxKind.FalseKeyword, 291 ts.SyntaxKind.NullKeyword 292 ].includes(node.kind) 293 ) 294 return true; 295 if (ts.isObjectLiteralExpression(node)) 296 return node.properties.every( 297 (property) => 298 ts.isPropertyAssignment(property) && 299 !ts.isComputedPropertyName(property.name) && 300 !['__proto__', 'constructor', 'prototype'].includes( 301 property.name.text 302 ) && 303 pure(property.initializer, seen) 304 ); 305 if (ts.isArrayLiteralExpression(node)) 306 return node.elements.every((element) => pure(element, seen)); 307 if (ts.isIdentifier(node)) { 308 const symbol = checker.getSymbolAtLocation(node); 309 if (!symbol) return node.text === 'undefined'; 310 if (seen.has(symbol)) return false; 311 seen = new Set([...seen, symbol]); 312 const declarations = symbol.declarations ?? []; 313 return ( 314 declarations.length === 1 && 315 (ts.isVariableDeclaration(declarations[0]) 316 ? pure(declarations[0].initializer, seen) 317 : ts.isParameter(declarations[0]) && 318 [ 319 ts.SyntaxKind.StringKeyword, 320 ts.SyntaxKind.NumberKeyword, 321 ts.SyntaxKind.BooleanKeyword, 322 ts.SyntaxKind.BigIntKeyword 323 ].includes(declarations[0].type?.kind)) 324 ); 325 } 326 if ( 327 (ts.isPropertyAccessExpression(node) || 328 ts.isElementAccessExpression(node)) && 329 owned(node.expression, seen) 330 ) 331 return ( 332 member(node) !== null && 333 !['constructor', 'prototype', '__proto__'].includes(member(node)) 334 ); 335 if (ts.isPrefixUnaryExpression(node)) return pure(node.operand, seen); 336 if ( 337 ts.isBinaryExpression(node) && 338 !ts.isAssignmentOperator(node.operatorToken.kind) 339 ) 340 return pure(node.left, seen) && pure(node.right, seen); 341 if (ts.isConditionalExpression(node)) 342 return ( 343 pure(node.condition, seen) && 344 pure(node.whenTrue, seen) && 345 pure(node.whenFalse, seen) 346 ); 347 return uiLeaf(node) && !ts.isCallExpression(node); 348 } 349 function owned(node, seen = new Set()) { 350 node = unwrap(node); 351 if (!node) return false; 352 if (ts.isObjectLiteralExpression(node) || ts.isArrayLiteralExpression(node)) 353 return pure(node, seen); 354 if (ts.isIdentifier(node)) { 355 const symbol = checker.getSymbolAtLocation(node); 356 if (!symbol || seen.has(symbol)) return false; 357 const declaration = 358 symbol.declarations?.length === 1 ? symbol.declarations[0] : null; 359 return ( 360 declaration && 361 ts.isVariableDeclaration(declaration) && 362 owned(declaration.initializer, new Set([...seen, symbol])) 363 ); 364 } 365 if ( 366 ts.isPropertyAccessExpression(node) || 367 ts.isElementAccessExpression(node) 368 ) 369 return ( 370 owned(node.expression, seen) && 371 member(node) !== null && 372 !['constructor', 'prototype', '__proto__'].includes(member(node)) 373 ); 374 return false; 375 } 376 const writes = new Set(); 377 const globalWrites = new Set(); 378 const collectWrites = (node) => { 379 if ( 380 (ts.isBinaryExpression(node) && 381 ts.isAssignmentOperator(node.operatorToken.kind)) || 382 ((ts.isPrefixUnaryExpression(node) || 383 ts.isPostfixUnaryExpression(node)) && 384 [ts.SyntaxKind.PlusPlusToken, ts.SyntaxKind.MinusMinusToken].includes( 385 node.operator 386 )) 387 ) { 388 const target = unwrap( 389 ts.isBinaryExpression(node) ? node.left : node.operand 390 ); 391 if (ts.isIdentifier(target)) { 392 const symbol = checker.getSymbolAtLocation(target); 393 if (symbol) writes.add(symbol); 394 else globalWrites.add(target.text); 395 } 396 } 397 ts.forEachChild(node, collectWrites); 398 }; 399 collectWrites(ast); 400 function bindingSymbol(node) { 401 const parent = node.parent; 402 if ( 403 ts.isExportSpecifier(parent) && 404 !parent.parent.parent.moduleSpecifier && 405 node === (parent.propertyName ?? parent.name) 406 ) 407 return checker.getExportSpecifierLocalTargetSymbol(parent); 408 return checker.getSymbolAtLocation(node); 409 } 410 function declaration(node) { 411 const symbol = bindingSymbol(node); 412 return symbol && !writes.has(symbol) && symbol.declarations?.length === 1 413 ? symbol.declarations[0] 414 : null; 415 } 416 function immutable(node, seen = new Set()) { 417 if (!ts.isIdentifier(node)) return null; 418 const decl = declaration(node); 419 if ( 420 !decl || 421 !ts.isVariableDeclaration(decl) || 422 !decl.initializer || 423 !(decl.parent.flags & ts.NodeFlags.Const) || 424 seen.has(decl) 425 ) 426 return null; 427 return { node: decl.initializer, seen: new Set([...seen, decl]) }; 428 } 429 // The pinned EventStore is a model receiver, not a DOM collection. Admit 430 // only its direct one-argument add on an immutable actual imported instance; 431 // aliases, shadowed imports, rebound receivers and escaped methods stay red. 432 function eventStoreAdd(node) { 433 if ( 434 !ts.isPropertyAccessExpression(node) || 435 node.name.text !== 'add' || 436 !ts.isCallExpression(node.parent) || 437 node.parent.expression !== node || 438 node.parent.arguments.length !== 1 || 439 ts.isSpreadElement(node.parent.arguments[0]) 440 ) 441 return false; 442 const receiver = immutable(node.expression); 443 const initializer = receiver && unwrap(receiver.node); 444 if ( 445 !initializer || 446 !ts.isNewExpression(initializer) || 447 !ts.isIdentifier(initializer.expression) 448 ) 449 return false; 450 const importedClass = declaration(initializer.expression); 451 return ( 452 !!importedClass && 453 ts.isImportSpecifier(importedClass) && 454 !importedClass.isTypeOnly && 455 !importedClass.parent.parent.isTypeOnly && 456 (importedClass.propertyName ?? importedClass.name).text === 457 'EventStore' && 458 importedClass.parent.parent.parent.moduleSpecifier.text === 459 'applesauce-core' 460 ); 461 } 462 // Reject writes and namespace escapes independently from successful sink 463 // resolution, so losing a binding's trust can never hide its capability. 464 function capabilityBinding(node) { 465 const symbol = bindingSymbol(node); 466 const decl = 467 symbol?.declarations?.length === 1 ? symbol.declarations[0] : null; 468 if (decl && ts.isImportSpecifier(decl)) 469 return identity( 470 decl.parent.parent.parent.moduleSpecifier.text, 471 (decl.propertyName ?? decl.name).text 472 ); 473 if (decl && ts.isNamespaceImport(decl)) 474 return identity(decl.parent.parent.moduleSpecifier.text, null) === 'goto' 475 ? 'navigationNamespace' 476 : null; 477 return null; 478 } 479 function imported(node) { 480 node = unwrap(node); 481 if (ts.isIdentifier(node)) { 482 const decl = declaration(node); 483 if ( 484 decl && 485 ts.isImportSpecifier(decl) && 486 !decl.isTypeOnly && 487 !decl.parent.parent.isTypeOnly 488 ) 489 return identity( 490 decl.parent.parent.parent.moduleSpecifier.text, 491 (decl.propertyName ?? decl.name).text 492 ); 493 } 494 if ( 495 ts.isPropertyAccessExpression(node) && 496 ts.isIdentifier(node.expression) 497 ) { 498 const decl = declaration(node.expression); 499 if (decl && ts.isNamespaceImport(decl) && !decl.parent.isTypeOnly) 500 return identity( 501 decl.parent.parent.moduleSpecifier.text, 502 node.name.text 503 ); 504 } 505 return null; 506 } 507 function strings(node, seen = new Set()) { 508 node = unwrap(node); 509 if (!node) return null; 510 if (ts.isStringLiteralLike(node)) return [node.text]; 511 const alias = immutable(node, seen); 512 if (alias) return strings(alias.node, alias.seen); 513 if (ts.isConditionalExpression(node)) { 514 const a = strings(node.whenTrue, seen), 515 b = strings(node.whenFalse, seen); 516 return a && b && a.length + b.length <= 64 ? [...a, ...b] : null; 517 } 518 if ( 519 ts.isBinaryExpression(node) && 520 node.operatorToken.kind === ts.SyntaxKind.PlusToken 521 ) { 522 const a = strings(node.left, seen), 523 b = strings(node.right, seen); 524 return a && b && a.length * b.length <= 64 525 ? a.flatMap((x) => b.map((y) => x + y)) 526 : null; 527 } 528 if (ts.isTemplateExpression(node)) { 529 let result = [node.head.text]; 530 for (const span of node.templateSpans) { 531 const part = strings(span.expression, seen); 532 if (!part || result.length * part.length > 64) return null; 533 result = result.flatMap((x) => 534 part.map((y) => x + y + span.literal.text) 535 ); 536 } 537 return result; 538 } 539 return null; 540 } 541 function forbiddenCharacters(value) { 542 return [...value].some((character) => { 543 const code = character.charCodeAt(0); 544 return code < 32 || (code >= 127 && code <= 159) || character === '\\'; 545 }); 546 } 547 function safeText(value, internal) { 548 if ( 549 !value || 550 value.length > 8192 || 551 !value.isWellFormed() || 552 Buffer.byteLength(value) > 8192 || 553 /\s/u.test(value) || 554 forbiddenCharacters(value) 555 ) 556 return false; 557 try { 558 if (forbiddenCharacters(decodeURIComponent(value))) return false; 559 const local = 560 (value[0] === '/' && value[1] !== '/') || ['?', '#'].includes(value[0]); 561 if (!local && (internal || !/^(https:\/\/|mailto:|tel:)/i.test(value))) 562 return false; 563 if (/^https:/i.test(value) && !/^https:\/\/[^/?#]/i.test(value)) 564 return false; 565 const url = new URL(value, 'https://navigation.invalid'); 566 return ( 567 !url.username && 568 !url.password && 569 !/^https:\/\/[^/?#]*@/i.test(value) && 570 (local || url.protocol === 'https:' || !url.host) && 571 (local ? url.origin === 'https://navigation.invalid' : !!url.pathname) 572 ); 573 } catch { 574 return false; 575 } 576 } 577 function urlValue(node, internal, defined = false) { 578 // Casts and non-null assertions are never evidence of runtime admission. 579 while (ts.isParenthesizedExpression(node)) node = node.expression; 580 const values = strings(node); 581 if (values) return values.every((value) => safeText(value, internal)); 582 if ( 583 ts.isCallExpression(node) && 584 node.arguments.length === 1 && 585 ['internalHref', ...(internal ? [] : ['navigationHref'])].includes( 586 imported(node.expression) 587 ) 588 ) 589 return !defined; 590 const alias = immutable(node); 591 if ( 592 defined && 593 alias && 594 ts.isCallExpression(alias.node) && 595 urlValue(alias.node, internal) 596 ) { 597 let child = node; 598 for ( 599 let parent = node.parent; 600 parent; 601 child = parent, parent = parent.parent 602 ) { 603 if (ts.isIfStatement(parent) && parent.thenStatement === child) { 604 const condition = parent.expression; 605 if ( 606 ts.isIdentifier(condition) && 607 checker.getSymbolAtLocation(condition) === 608 checker.getSymbolAtLocation(node) 609 ) 610 return true; 611 if ( 612 ts.isBinaryExpression(condition) && 613 condition.operatorToken.kind === 614 ts.SyntaxKind.ExclamationEqualsEqualsToken && 615 ts.isIdentifier(condition.left) && 616 checker.getSymbolAtLocation(condition.left) === 617 checker.getSymbolAtLocation(node) && 618 ts.isIdentifier(condition.right) && 619 condition.right.text === 'undefined' && 620 !checker.getSymbolAtLocation(condition.right)?.declarations?.length 621 ) 622 return true; 623 } 624 } 625 } 626 return false; 627 } 628 function global(node, names) { 629 return ( 630 ts.isIdentifier(node) && 631 names.includes(node.text) && 632 !checker.getSymbolAtLocation(node) 633 ); 634 } 635 function location(node) { 636 return ( 637 global(node, ['location']) || 638 (ts.isPropertyAccessExpression(node) && 639 node.name.text === 'location' && 640 global(node.expression, ['window', 'globalThis', 'self'])) 641 ); 642 } 643 function locationSink(node) { 644 if ( 645 ts.isCallExpression(node) && 646 ts.isPropertyAccessExpression(node.expression) && 647 ['assign', 'replace'].includes(node.expression.name.text) && 648 location(node.expression.expression) 649 ) 650 return ( 651 node.arguments.length === 1 && urlValue(node.arguments[0], true, true) 652 ); 653 if ( 654 ts.isBinaryExpression(node) && 655 node.operatorToken.kind === ts.SyntaxKind.EqualsToken && 656 (location(node.left) || 657 (ts.isPropertyAccessExpression(node.left) && 658 node.left.name.text === 'href' && 659 location(node.left.expression))) 660 ) 661 return urlValue(node.right, true, true); 662 return false; 663 } 664 function locationUse(node) { 665 let top = node; 666 while ( 667 top.parent && 668 ((ts.isPropertyAccessExpression(top.parent) && 669 top.parent.expression === top) || 670 (ts.isCallExpression(top.parent) && top.parent.expression === top)) 671 ) 672 top = top.parent; 673 if ( 674 top.parent && 675 ts.isBinaryExpression(top.parent) && 676 top.parent.left === top 677 ) 678 top = top.parent; 679 return locationSink(top); 680 } 681 function callback(node) { 682 if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) return true; 683 const decl = ts.isIdentifier(node) && declaration(node); 684 if (decl && ts.isFunctionDeclaration(decl)) return true; 685 const alias = immutable(node); 686 return ( 687 !!alias && 688 (ts.isArrowFunction(alias.node) || ts.isFunctionExpression(alias.node)) 689 ); 690 } 691 function timerUse(node) { 692 const parent = node.parent; 693 return ( 694 ts.isCallExpression(parent) && 695 parent.expression === node && 696 parent.arguments.length >= 1 && 697 callback(parent.arguments[0]) 698 ); 699 } 700 function collection(node) { 701 const alias = immutable(node); 702 return ( 703 !!alias && 704 ts.isNewExpression(alias.node) && 705 global(alias.node.expression, ['Set']) && 706 !globalWrites.has('Set') && 707 (!alias.node.arguments?.length || 708 (alias.node.arguments.length === 1 && 709 ts.isArrayLiteralExpression(alias.node.arguments[0]) && 710 pure(alias.node.arguments[0]))) 711 ); 712 } 713 function stringReceiver(node, seen = new Set()) { 714 if (strings(node)) return true; 715 const alias = immutable(unwrap(node), seen); 716 if (alias) return stringReceiver(alias.node, alias.seen); 717 node = unwrap(node); 718 return ( 719 ts.isCallExpression(node) && 720 ts.isPropertyAccessExpression(node.expression) && 721 node.expression.name.text === 'replace' && 722 node.arguments.length === 2 && 723 stringReceiver(node.expression.expression, seen) && 724 (ts.isRegularExpressionLiteral(node.arguments[0]) || 725 !!strings(node.arguments[0])) && 726 !!strings(node.arguments[1]) 727 ); 728 } 729 // HCP029: single-property descriptor reads do not mutate their receiver. 730 // Admit only the actual builtin's direct call; never an escaped/shadowed 731 // reader or a descriptor write. Other reflection keeps owned-data rules. 732 function descriptorRead(node) { 733 return ( 734 ts.isPropertyAccessExpression(node) && 735 node.name.text === 'getOwnPropertyDescriptor' && 736 global(node.expression, ['Object']) && 737 !globalWrites.has('Object') && 738 ts.isCallExpression(node.parent) && 739 node.parent.expression === node && 740 node.parent.arguments.length === 2 && 741 pure(node.parent.arguments[1]) 742 ); 743 } 744 function primitiveMethod(node) { 745 const call = node.parent; 746 if ( 747 !ts.isPropertyAccessExpression(node) || 748 !ts.isCallExpression(call) || 749 call.expression !== node 750 ) 751 return false; 752 if (node.name.text === 'add') 753 return ( 754 collection(node.expression) && 755 call.arguments.length === 1 && 756 pure(call.arguments[0]) 757 ); 758 if (node.name.text === 'replace') 759 return ( 760 stringReceiver(node.expression) && 761 call.arguments.length === 2 && 762 (ts.isRegularExpressionLiteral(call.arguments[0]) || 763 !!strings(call.arguments[0])) && 764 !!strings(call.arguments[1]) 765 ); 766 return false; 767 } 768 const animationMethods = new Set(['animate', 'setKeyframes']); 769 const methods = new Set([ 770 ...animationMethods, 771 'setAttribute', 772 'setAttributeNS', 773 'toggleAttribute', 774 'removeAttribute', 775 'removeAttributeNS', 776 'setAttributeNode', 777 'setAttributeNodeNS', 778 'removeAttributeNode', 779 'setNamedItem', 780 'setNamedItemNS', 781 'removeNamedItem', 782 'removeNamedItemNS', 783 'add', 784 'remove', 785 'replace', 786 'toggle', 787 'setProperty', 788 'removeProperty', 789 'appendRule', 790 'deleteRule', 791 'insertRule', 792 'replaceSync', 793 'append', 794 'prepend', 795 'appendChild', 796 'insertBefore', 797 'insertAdjacentElement', 798 'insertAdjacentHTML', 799 'replaceChild', 800 'replaceChildren', 801 'removeChild', 802 'before', 803 'after', 804 'replaceWith', 805 'write', 806 'writeln', 807 'insertNode', 808 'surroundContents', 809 'createContextualFragment', 810 'execCommand', 811 'load', 812 'setHTML', 813 'setHTMLUnsafe', 814 '__defineGetter__', 815 '__defineSetter__', 816 'push', 817 'unshift', 818 'splice' 819 ]); 820 const navigatorCapabilities = new Set([ 821 'clipboard', 822 'locks', 823 'storage', 824 'onLine', 825 'language', 826 'languages', 827 'userAgent', 828 'platform', 829 'hardwareConcurrency', 830 'cookieEnabled' 831 ]); 832 const navigatorLeaf = (node) => 833 ts.isPropertyAccessExpression(node.parent) && 834 node.parent.expression === node && 835 navigatorCapabilities.has(node.parent.name.text); 836 function inspect(node) { 837 const admittedLocation = locationSink(node); 838 if ( 839 ts.isCallExpression(node) && 840 imported(node.expression) === 'goto' && 841 (node.arguments.length < 1 || !urlValue(node.arguments[0], true, true)) 842 ) 843 report('navigation goto requires a defined validated internal URL'); 844 if ( 845 ts.isCallExpression(node) && 846 ts.isIdentifier(node.expression) && 847 /^__hcr(?:Navigation|Resource)Url$/.test(node.expression.text) 848 ) { 849 const internal = node.expression.text === '__hcrResourceUrl'; 850 if ( 851 node.arguments.length !== 1 || 852 !urlValue(node.arguments[0], internal) || 853 (internal && !strings(node.arguments[0])) 854 ) 855 report('unresolved or unsafe markup URL'); 856 } 857 if ( 858 ts.isBinaryExpression(node) && 859 ts.isAssignmentOperator(node.operatorToken.kind) && 860 !admittedLocation 861 ) { 862 const left = unwrap(node.left); 863 if ( 864 (ts.isPropertyAccessExpression(left) || 865 ts.isElementAccessExpression(left)) && 866 (!owned(left.expression) || !pure(node.right)) 867 ) 868 report( 869 'opaque DOM/object mutations are forbidden; use owned plain model data' 870 ); 871 if (ts.isIdentifier(left) && owned(left) && !pure(node.right)) 872 report('owned model reassignment cannot introduce opaque capabilities'); 873 if ( 874 ts.isArrayLiteralExpression(left) || 875 ts.isObjectLiteralExpression(left) 876 ) 877 report( 878 'bulk mutation targets must use the admitted plain-model grammar' 879 ); 880 } 881 if ( 882 ((ts.isPrefixUnaryExpression(node) || 883 ts.isPostfixUnaryExpression(node)) && 884 [ts.SyntaxKind.PlusPlusToken, ts.SyntaxKind.MinusMinusToken].includes( 885 node.operator 886 )) || 887 ts.isDeleteExpression(node) 888 ) { 889 const operand = unwrap( 890 ts.isDeleteExpression(node) ? node.expression : node.operand 891 ); 892 if ( 893 (ts.isPropertyAccessExpression(operand) || 894 ts.isElementAccessExpression(operand)) && 895 !owned(operand.expression) 896 ) 897 report('opaque DOM/object update/delete mutations are forbidden'); 898 } 899 if ( 900 ts.isPropertyAccessExpression(node) || 901 ts.isElementAccessExpression(node) 902 ) { 903 const computedNames = ts.isElementAccessExpression(node) 904 ? strings(node.argumentExpression) 905 : null; 906 const name = 907 member(node) ?? (computedNames?.length === 1 ? computedNames[0] : null); 908 if ( 909 computedNames?.some((name) => animationMethods.has(name)) && 910 !owned(node.expression) 911 ) 912 report( 913 'opaque or indirect animation mutation/setter APIs are forbidden' 914 ); 915 if ( 916 imported(node) === 'goto' && 917 !(ts.isCallExpression(node.parent) && node.parent.expression === node) 918 ) 919 report('escaped goto capability is forbidden'); 920 if ( 921 name === 'clipboard' && 922 (global(node.expression, ['navigator']) || 923 ((ts.isPropertyAccessExpression(node.expression) || 924 ts.isElementAccessExpression(node.expression)) && 925 member(node.expression) === 'navigator' && 926 ts.isIdentifier(node.expression.expression) && 927 ['window', 'globalThis', 'self'].includes( 928 node.expression.expression.text 929 ) && 930 !checker.getSymbolAtLocation(node.expression.expression) 931 ?.declarations?.length)) 932 ) { 933 const action = node.parent; 934 const call = action.parent; 935 if ( 936 !reviewedReport && 937 (!reviewedCopy || 938 !global(node.expression, ['navigator']) || 939 !ts.isPropertyAccessExpression(action) || 940 action.expression !== node || 941 action.name.text !== 'writeText' || 942 !ts.isCallExpression(call) || 943 call.expression !== action || 944 call.arguments.length !== 1) 945 ) 946 report( 947 'clipboard capability requires the exact reviewed public copy action' 948 ); 949 } 950 if (location(node) && !locationUse(node)) 951 report('opaque Location capability is forbidden'); 952 if ( 953 ['setTimeout', 'setInterval'].includes(name) && 954 global(node.expression, ['window', 'globalThis', 'self']) 955 ) 956 report('indirect timer capability is forbidden'); 957 if ( 958 name === 'navigator' && 959 ts.isIdentifier(node.expression) && 960 ['window', 'globalThis', 'self'].includes(node.expression.text) && 961 !checker.getSymbolAtLocation(node.expression) && 962 !navigatorLeaf(node) 963 ) 964 report('opaque navigator capabilities cannot expose worker loaders'); 965 if ( 966 name === 'getOwnPropertyDescriptor' && 967 ts.isIdentifier(node.expression) && 968 node.expression.text === 'Object' && 969 !descriptorRead(node) 970 ) 971 report( 972 'descriptor inspection requires a direct unshadowed builtin read' 973 ); 974 if (['constructor', 'prototype', '__proto__'].includes(name)) 975 report( 976 'prototype capability access is outside the admitted DOM/model grammar' 977 ); 978 if ( 979 [ 980 'currentTarget', 981 'target', 982 'ownerDocument', 983 'contentDocument', 984 'contentWindow', 985 'defaultView', 986 'composedPath', 987 'getRootNode' 988 ].includes(name) && 989 !owned(node.expression) && 990 !uiLeaf(node) 991 ) 992 report( 993 'opaque DOM capabilities cannot escape direct UI leaf operations' 994 ); 995 const locationMethod = 996 ts.isPropertyAccessExpression(node) && 997 ['assign', 'replace'].includes(name) && 998 location(node.expression) && 999 locationUse(node); 1000 if ( 1001 methods.has(name) && 1002 !primitiveMethod(node) && 1003 !eventStoreAdd(node) && 1004 !locationMethod && 1005 !( 1006 reviewedScroll && 1007 name === 'scrollTo' && 1008 global(node.expression, ['window']) 1009 ) && 1010 !( 1011 animationMethods.has(name) && 1012 owned(node.expression) && 1013 !ts.isCallExpression(node.parent) 1014 ) 1015 ) { 1016 if ( 1017 !ts.isCallExpression(node.parent) || 1018 node.parent.expression !== node || 1019 !owned(node.expression) || 1020 !node.parent.arguments.every((argument) => pure(argument)) 1021 ) 1022 if (!relayRemoval(node)) 1023 report('opaque or indirect DOM mutation/setter APIs are forbidden'); 1024 } 1025 } 1026 if (ts.isIdentifier(node)) { 1027 const parent = node.parent; 1028 if ( 1029 collection(node) && 1030 !(ts.isVariableDeclaration(parent) && parent.name === node) && 1031 !( 1032 ts.isPropertyAccessExpression(parent) && 1033 parent.expression === node && 1034 ((['add', 'has'].includes(parent.name.text) && 1035 ts.isCallExpression(parent.parent) && 1036 parent.parent.expression === parent && 1037 parent.parent.arguments.every((argument) => pure(argument))) || 1038 parent.name.text === 'size') 1039 ) 1040 ) 1041 report( 1042 'owned collection capabilities cannot escape direct data operations' 1043 ); 1044 const capability = capabilityBinding(node); 1045 if (capability && writes.has(checker.getSymbolAtLocation(node))) 1046 report('reassigned navigation capability is forbidden'); 1047 if ( 1048 capability === 'navigationNamespace' && 1049 !ts.isNamespaceImport(parent) && 1050 !( 1051 ts.isPropertyAccessExpression(parent) && 1052 parent.expression === node && 1053 parent.name.text === 'goto' && 1054 ts.isCallExpression(parent.parent) && 1055 parent.parent.expression === parent 1056 ) 1057 ) 1058 report('escaped navigation namespace is forbidden'); 1059 const propertyName = 1060 (ts.isPropertyAccessExpression(parent) && parent.name === node) || 1061 (ts.isPropertyAssignment(parent) && 1062 parent.name === node && 1063 !ts.isShorthandPropertyAssignment(parent)); 1064 const typeName = 1065 ts.isTypeReferenceNode(parent) || ts.isTypeQueryNode(parent); 1066 const symbol = checker.getSymbolAtLocation(node); 1067 if ( 1068 !propertyName && 1069 !typeName && 1070 !symbol && 1071 ['KeyframeEffect', 'Animation'].includes(node.text) 1072 ) 1073 report('imperative animation constructors are forbidden'); 1074 if ( 1075 !propertyName && 1076 !typeName && 1077 !symbol && 1078 node.text === 'Set' && 1079 globalWrites.has('Set') 1080 ) 1081 report('global Set constructor rebinding is forbidden'); 1082 if ( 1083 !propertyName && 1084 !typeName && 1085 !symbol && 1086 ['setTimeout', 'setInterval'].includes(node.text) && 1087 !timerUse(node) 1088 ) 1089 report('timer requires a direct function callback'); 1090 if ( 1091 !propertyName && 1092 !typeName && 1093 global(node, ['location']) && 1094 !locationUse(node) 1095 ) 1096 report('opaque Location capability is forbidden'); 1097 if ( 1098 imported(node) === 'goto' && 1099 !( 1100 ts.isImportSpecifier(parent) || 1101 (ts.isCallExpression(parent) && parent.expression === node) 1102 ) 1103 ) 1104 report('escaped goto capability is forbidden'); 1105 if (!propertyName && !typeName && !symbol) { 1106 if ( 1107 node.text === 'navigator' && 1108 !navigatorLeaf(node) && 1109 !(reviewedReport && ts.isTypeOfExpression(parent)) 1110 ) 1111 report('opaque navigator capabilities cannot expose worker loaders'); 1112 if ( 1113 node.text === 'document' && 1114 !uiLeaf(node) && 1115 !ts.isTypeOfExpression(parent) 1116 ) 1117 report('DOM handles cannot escape the bounded direct UI grammar'); 1118 if ( 1119 [ 1120 'window', 1121 'globalThis', 1122 'self', 1123 'top', 1124 'parent', 1125 'frames', 1126 'opener' 1127 ].includes(node.text) && 1128 !ts.isTypeOfExpression(parent) 1129 ) { 1130 if ( 1131 !ts.isPropertyAccessExpression(parent) || 1132 parent.expression !== node || 1133 (![ 1134 'nostr', 1135 'indexedDB', 1136 'crypto', 1137 'navigator', 1138 'location' 1139 ].includes(parent.name.text) && 1140 !( 1141 reviewedScroll && 1142 node.text === 'window' && 1143 ['scrollY', 'scrollTo'].includes(parent.name.text) 1144 )) 1145 ) 1146 report('opaque browser/DOM global capability access is forbidden'); 1147 } 1148 if ( 1149 /^(?:Document|Node|Element|DOMParser|DOMImplementation|Range|XPathEvaluator|XSLTProcessor|HTML\w*Element|SVG\w*Element|CSS\w*|DOMTokenList|NamedNodeMap|Attr)$/.test( 1150 node.text 1151 ) 1152 ) 1153 report( 1154 'native DOM/resource constructors are outside the admitted UI grammar' 1155 ); 1156 if (['Object', 'Reflect'].includes(node.text)) { 1157 if ( 1158 !ts.isPropertyAccessExpression(parent) || 1159 parent.expression !== node || 1160 !ts.isCallExpression(parent.parent) || 1161 parent.parent.expression !== parent || 1162 (!descriptorRead(parent) && 1163 !( 1164 reviewedReport && 1165 node.text === 'Reflect' && 1166 parent.name.text === 'get' && 1167 parent.parent.arguments.length === 2 && 1168 ts.isIdentifier(parent.parent.arguments[0]) && 1169 parent.parent.arguments[0].text === 'clipboard' && 1170 ts.isStringLiteralLike(parent.parent.arguments[1]) && 1171 parent.parent.arguments[1].text === 'writeText' 1172 ) && 1173 !parent.parent.arguments.every((argument) => pure(argument))) 1174 ) 1175 report( 1176 'reflection/bulk operations require direct calls over owned plain data' 1177 ); 1178 } 1179 } 1180 } 1181 for (const doc of node.jsDoc ?? []) inspect(doc); 1182 ts.forEachChild(node, inspect); 1183 } 1184 inspect(ast); 1185 return owned; 1186 } 1187 1188 function literal(node) { 1189 if (ts.isStringLiteralLike(node)) return node.text; 1190 if (node.kind === ts.SyntaxKind.TrueKeyword) return true; 1191 if (node.kind === ts.SyntaxKind.FalseKeyword) return false; 1192 if (ts.isArrayLiteralExpression(node)) return node.elements.map(literal); 1193 if (ts.isObjectLiteralExpression(node)) { 1194 const value = Object.create(null); 1195 for (const property of node.properties) { 1196 if ( 1197 !ts.isPropertyAssignment(property) || 1198 !property.name || 1199 (!ts.isIdentifier(property.name) && !ts.isStringLiteral(property.name)) 1200 ) 1201 throw new Error('Import configuration must use literal properties'); 1202 const key = property.name.text; 1203 if (Object.hasOwn(value, key)) 1204 throw new Error('Duplicate import configuration property'); 1205 value[key] = literal(property.initializer); 1206 } 1207 return value; 1208 } 1209 throw new Error('Import configuration must be statically resolvable'); 1210 } 1211 1212 async function configuration(root) { 1213 for (const name of await readdir(root)) { 1214 if (/^(vite|svelte)\.config\.(js|mjs|cjs|mts|cts)$/.test(name)) 1215 throw new Error(`Unsupported competing source configuration: ${name}`); 1216 } 1217 const pkg = JSON.parse(await readSource(path.join(root, 'package.json'))); 1218 const configText = await readSource(path.join(root, 'tsconfig.json')); 1219 const parsed = ts.parseConfigFileTextToJson('tsconfig.json', configText); 1220 if (parsed.error) throw new Error('Invalid tsconfig.json'); 1221 const config = parsed.config; 1222 if (config.extends !== '$app/tsconfig' || config.compilerOptions?.baseUrl) 1223 throw new Error('Unsupported TypeScript import configuration'); 1224 const vite = sourceAst( 1225 'vite.config.ts', 1226 await readSource(path.join(root, 'vite.config.ts')) 1227 ); 1228 const defaults = vite.statements.filter(ts.isExportAssignment); 1229 if ( 1230 defaults.length !== 1 || 1231 !ts.isCallExpression(defaults[0].expression) || 1232 defaults[0].expression.expression.getText(vite) !== 'defineConfig' 1233 ) 1234 throw new Error('Vite configuration must be statically resolvable'); 1235 const object = defaults[0].expression.arguments[0]; 1236 if (!object || !ts.isObjectLiteralExpression(object)) 1237 throw new Error('Vite configuration must be a literal object'); 1238 const aliases = []; 1239 const configKeys = new Set(); 1240 for (const property of object.properties) { 1241 if (!ts.isPropertyAssignment(property) || !ts.isIdentifier(property.name)) 1242 throw new Error('Unsupported Vite import configuration'); 1243 const key = property.name.text; 1244 if (configKeys.has(key)) 1245 throw new Error('Duplicate Vite configuration property'); 1246 configKeys.add(key); 1247 if (key === 'plugins') { 1248 // Keep the existing Kit3/static adapter pipeline. Arbitrary plugins can 1249 // rewrite imports invisibly; they require explicit guard support. 1250 const normalized = property.initializer.getText(vite).replace(/\s/g, ''); 1251 if ( 1252 normalized !== 1253 "[sveltekit({adapter:adapter({strict:true,fallback:'200.html'})})]" && 1254 normalized !== 1255 '[sveltekit({adapter:adapter({strict:true,fallback:"200.html"})})]' 1256 ) 1257 throw new Error('Unsupported Vite source transformation'); 1258 } else if (key === 'resolve') { 1259 const resolve = literal(property.initializer); 1260 if (Object.keys(resolve).some((name) => name !== 'alias')) 1261 throw new Error('Unsupported Vite resolution option'); 1262 const values = Array.isArray(resolve.alias) 1263 ? resolve.alias 1264 : Object.entries(resolve.alias ?? {}).map(([find, replacement]) => ({ 1265 find, 1266 replacement 1267 })); 1268 for (const value of values) { 1269 if ( 1270 typeof value.find !== 'string' || 1271 typeof value.replacement !== 'string' 1272 ) 1273 throw new Error('Unsupported Vite alias'); 1274 aliases.push(value); 1275 } 1276 } else throw new Error(`Unsupported Vite configuration property: ${key}`); 1277 } 1278 // Configuration must not execute hidden resolver mutation before defineConfig. 1279 for (const statement of vite.statements) { 1280 if (ts.isImportDeclaration(statement)) { 1281 const imported = statement.moduleSpecifier.text; 1282 const clause = statement.importClause; 1283 const expected = imported === 'vite' ? 'defineConfig' : 'sveltekit'; 1284 if (imported === '@sveltejs/adapter-static') { 1285 if (!clause || clause.name?.text !== 'adapter' || clause.namedBindings) 1286 throw new Error('Unsupported Vite adapter binding'); 1287 } else if ( 1288 !clause || 1289 clause.name || 1290 !clause.namedBindings || 1291 !ts.isNamedImports(clause.namedBindings) || 1292 clause.namedBindings.elements.length !== 1 || 1293 clause.namedBindings.elements[0].propertyName || 1294 clause.namedBindings.elements[0].name.text !== expected 1295 ) 1296 throw new Error('Unsupported Vite resolver binding'); 1297 if ( 1298 !['vite', '@sveltejs/kit/vite', '@sveltejs/adapter-static'].includes( 1299 imported 1300 ) 1301 ) 1302 throw new Error(`Unsupported Vite config import: ${imported}`); 1303 } else if (!ts.isExportAssignment(statement)) 1304 throw new Error('Unsupported Vite configuration statement'); 1305 } 1306 for (const [find, replacements] of Object.entries( 1307 config.compilerOptions?.paths ?? {} 1308 )) { 1309 if ( 1310 !Array.isArray(replacements) || 1311 replacements.length !== 1 || 1312 typeof replacements[0] !== 'string' 1313 ) 1314 throw new Error('Unsupported TypeScript path mapping'); 1315 // Audit TS mappings as well as Vite mappings, so a second resolution 1316 // surface cannot hide an unsafe target from source checks. 1317 aliases.push({ find, replacement: replacements[0], typescript: true }); 1318 } 1319 return { pkg, aliases }; 1320 } 1321 1322 export async function auditSource(root) { 1323 root = path.resolve(root); 1324 const sourceRoot = path.join(root, 'src'); 1325 const files = new Map(); 1326 const findings = []; 1327 const allowedCss = new Set(['src/theme.css', 'src/app.css']); 1328 const complain = (file, message) => 1329 findings.push(`${relative(root, file)}: ${message}`); 1330 async function inventory(directory) { 1331 const before = await lstat(directory); 1332 if ( 1333 !before.isDirectory() || 1334 before.isSymbolicLink() || 1335 (await realpath(directory)) !== directory 1336 ) 1337 throw new Error(`Unsafe source directory: ${directory}`); 1338 for (const entry of await readdir(directory, { withFileTypes: true })) { 1339 const file = path.join(directory, entry.name); 1340 const stat = await lstat(file); 1341 if (stat.isSymbolicLink() || (!stat.isDirectory() && !stat.isFile())) { 1342 complain( 1343 file, 1344 'source symlinks/nonregular source entries are forbidden' 1345 ); 1346 continue; 1347 } 1348 if (stat.isDirectory()) await inventory(file); 1349 else files.set(file, await readSource(file)); 1350 } 1351 const after = await lstat(directory); 1352 if ( 1353 before.dev !== after.dev || 1354 before.ino !== after.ino || 1355 before.mtimeMs !== after.mtimeMs || 1356 before.ctimeMs !== after.ctimeMs 1357 ) 1358 throw new Error(`Source directory changed during audit: ${directory}`); 1359 } 1360 await inventory(sourceRoot); 1361 const { pkg, aliases } = await configuration(root); 1362 const dependencies = { ...pkg.dependencies, ...pkg.devDependencies }; 1363 // Kit3 params is an import-only export; validate the installed, confined 1364 // exact package declaration without using parent or CommonJS fallbacks. 1365 let kitParamsFile; 1366 if (files.has(path.join(root, 'src/params.ts'))) { 1367 try { 1368 const packageFile = createRequire( 1369 path.join(root, 'package.json') 1370 ).resolve('@sveltejs/kit/package.json'); 1371 if (!inside(path.join(root, 'node_modules'), packageFile)) 1372 throw new Error('outside web dependencies'); 1373 const installed = JSON.parse(await readSource(packageFile)); 1374 if ( 1375 installed.version !== dependencies['@sveltejs/kit'] || 1376 installed.exports?.['./params']?.import !== 1377 './src/exports/params/index.js' 1378 ) 1379 throw new Error('unqualified Kit params export'); 1380 const target = path.join( 1381 path.dirname(packageFile), 1382 'src/exports/params/index.js' 1383 ); 1384 await readSource(target); 1385 kitParamsFile = target; 1386 } catch { 1387 // A consumed import below reports unresolved admission, never passes. 1388 } 1389 } 1390 1391 const cssImports = []; 1392 function local(file, target, specifier) { 1393 if ( 1394 !inside(sourceRoot, target) || 1395 forbiddenPath.test(relative(sourceRoot, target)) 1396 ) { 1397 complain(file, `forbidden production import ${specifier}`); 1398 return; 1399 } 1400 const candidates = [ 1401 target, 1402 ...[ 1403 '.ts', 1404 '.tsx', 1405 '.js', 1406 '.jsx', 1407 '.mts', 1408 '.mjs', 1409 '.cts', 1410 '.cjs', 1411 '.svelte' 1412 ].map((extension) => target + extension), 1413 ...['.ts', '.tsx', '.js', '.jsx', '.mts', '.mjs', '.svelte'].map( 1414 (extension) => path.join(target, 'index' + extension) 1415 ) 1416 ]; 1417 // TypeScript source commonly retains a .js extension for its emitted path. 1418 if (/\.[cm]?js$/.test(target)) 1419 candidates.push( 1420 target 1421 .replace(/\.js$/, '.ts') 1422 .replace(/\.mjs$/, '.mts') 1423 .replace(/\.cjs$/, '.cts') 1424 ); 1425 const found = candidates.find((candidate) => files.has(candidate)); 1426 if (!found) 1427 return complain(file, `unresolved production import ${specifier}`); 1428 const name = relative(root, found); 1429 if (/\.(css|scss|sass|less)$/.test(found)) { 1430 if ( 1431 relative(root, file) !== 'src/routes/+layout.svelte' || 1432 !allowedCss.has(name) 1433 ) 1434 complain(file, 'CSS must be imported by the root layout'); 1435 else cssImports.push(name); 1436 } else if (!codeExtension.test(found)) 1437 complain(file, `unsupported production import ${specifier}`); 1438 return found; 1439 } 1440 function resolve(file, specifier, seen = new Set(), unrestricted = false) { 1441 if ( 1442 typeof specifier !== 'string' || 1443 /[\\?#]/.test(specifier.replace(/^#/, '')) || 1444 [...specifier].some((character) => character.charCodeAt(0) <= 32) || 1445 specifier.includes('%') || 1446 specifier.startsWith('/') 1447 ) 1448 return complain(file, `unsafe production import ${specifier}`); 1449 if (seen.has(specifier)) 1450 return complain(file, `cyclic import alias ${specifier}`); 1451 seen = new Set([...seen, specifier]); 1452 const matches = aliases.filter(({ find }) => 1453 find.includes('*') 1454 ? specifier.startsWith(find.split('*')[0]) && 1455 specifier.endsWith(find.split('*')[1]) 1456 : specifier === find || 1457 (!find.startsWith('#') && specifier.startsWith(find + '/')) 1458 ); 1459 if (matches.length) { 1460 const identities = []; 1461 for (const alias of matches) { 1462 const tail = alias.find.includes('*') 1463 ? specifier.slice( 1464 alias.find.indexOf('*'), 1465 specifier.length - alias.find.split('*')[1].length || undefined 1466 ) 1467 : specifier.slice(alias.find.length); 1468 const target = alias.replacement.includes('*') 1469 ? alias.replacement.replace('*', tail) 1470 : alias.replacement + tail; 1471 if ( 1472 alias.typescript || 1473 target.startsWith('.') || 1474 path.isAbsolute(target) 1475 ) 1476 identities.push(local(file, path.resolve(root, target), specifier)); 1477 else identities.push(resolve(file, target, seen, unrestricted)); 1478 } 1479 return identities.every((value) => value === identities[0]) 1480 ? identities[0] 1481 : null; 1482 } 1483 if (specifier.startsWith('#')) { 1484 const entries = Object.entries(pkg.imports ?? {}).filter( 1485 ([key]) => 1486 key === specifier || 1487 (key.endsWith('/*') && specifier.startsWith(key.slice(0, -1))) 1488 ); 1489 if (!entries.length) 1490 return complain(file, `unresolved production import ${specifier}`); 1491 // Audit all conditions, not only the current host's default branch. 1492 const targets = (value) => 1493 typeof value === 'string' 1494 ? [value] 1495 : value && typeof value === 'object' && !Array.isArray(value) 1496 ? Object.values(value).flatMap(targets) 1497 : (() => { 1498 throw new Error(`Unsafe package import ${specifier}`); 1499 })(); 1500 const identities = []; 1501 for (const [key, value] of entries) 1502 for (const raw of targets(value)) { 1503 const target = key.endsWith('/*') 1504 ? raw.replace('*', specifier.slice(key.length - 1)) 1505 : raw; 1506 if (target.startsWith('.')) 1507 identities.push(local(file, path.resolve(root, target), specifier)); 1508 else identities.push(resolve(file, target, seen, unrestricted)); 1509 } 1510 return identities.every((value) => value === identities[0]) 1511 ? identities[0] 1512 : null; 1513 } 1514 if (specifier.startsWith('.')) 1515 return local( 1516 file, 1517 path.resolve(path.dirname(file), specifier), 1518 specifier 1519 ); 1520 if (frameworkModules.has(specifier)) return specifier; 1521 const packageName = specifier.startsWith('@') 1522 ? specifier.split('/').slice(0, 2).join('/') 1523 : specifier.split('/')[0]; 1524 const declared = dependencies[packageName]; 1525 const actualName = 1526 typeof declared === 'string' && declared.startsWith('npm:') 1527 ? declared.slice(4).replace(/@[^@]*$/, '') 1528 : packageName; 1529 if ( 1530 unrestricted && 1531 actualName === 'svelte' && 1532 !specifier.slice(packageName.length).startsWith('/store') 1533 ) 1534 return complain( 1535 file, 1536 'unrestricted Svelte raw-render module access is forbidden' 1537 ); 1538 const actualImport = actualName + specifier.slice(packageName.length); 1539 // These upstream primitives have no blanket runtime-package admission. 1540 // Only the exact reviewed pure adapters and exact package exports/pins may 1541 // use them. Source changes require a new independent review of this scope. 1542 const primitiveAdmissions = { 1543 '@noble/curves': { 1544 version: '1.2.0', 1545 import: '@noble/curves/secp256k1', 1546 file: 'src/lib/contracts/public-key.ts', 1547 sha256: 1548 'd36d4001c2f4835e24d50f00460a35c9cf9fa6b86cc3b4a6937d8b4e10afdeb9' 1549 }, 1550 '@scure/base': { 1551 version: '1.1.1', 1552 import: '@scure/base', 1553 file: 'src/lib/nostr/references.ts', 1554 sha256: 1555 '94077cc85e443a8df1fcd24726bcd8d084fae22de7aea7e1341e1acd7cadce9c' 1556 } 1557 }; 1558 const primitive = Object.hasOwn(primitiveAdmissions, actualName) 1559 ? primitiveAdmissions[actualName] 1560 : undefined; 1561 const admittedPrimitive = 1562 primitive !== undefined && 1563 declared === primitive.version && 1564 actualImport === primitive.import && 1565 relative(root, file) === primitive.file && 1566 createHash('sha256').update(files.get(file)).digest('hex') === 1567 primitive.sha256; 1568 if ( 1569 (actualName === '@sveltejs/kit' && 1570 !['@sveltejs/kit', '@sveltejs/kit/hooks'].includes(actualImport) && 1571 !( 1572 actualImport === '@sveltejs/kit/params' && 1573 relative(root, file) === 'src/params.ts' 1574 )) || 1575 (actualName === 'svelte' && 1576 /^(svelte\/(compiler|internal|server|attachments|package\.json))/.test( 1577 actualImport 1578 )) 1579 ) 1580 return complain(file, `forbidden production import ${specifier}`); 1581 if ( 1582 applesauce.has(actualName) && 1583 !relative(root, file).startsWith('src/lib/nostr/') 1584 ) 1585 complain(file, 'Applesauce imports belong in lib/nostr'); 1586 if ( 1587 (!runtimePackages.has(actualName) && !admittedPrimitive) || 1588 typeof declared !== 'string' || 1589 /^(file:|link:|workspace:|git|https?:|\.\.?\/)/.test(declared) 1590 ) 1591 return complain(file, `forbidden production import ${specifier}`); 1592 if ( 1593 !/^(?:npm:(?:@[^/]+\/)?[^@]+@)?\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/.test( 1594 declared 1595 ) 1596 ) 1597 return complain(file, `unpinned production import ${specifier}`); 1598 // Direct package imports must be exported by the installed, pinned package; 1599 // never search parent node_modules or fall back to a sibling workspace. 1600 try { 1601 const resolved = 1602 actualImport === '@sveltejs/kit/params' && 1603 relative(root, file) === 'src/params.ts' 1604 ? kitParamsFile 1605 : createRequire(path.join(root, 'package.json')).resolve(specifier); 1606 if (typeof resolved !== 'string') throw new Error('unresolved export'); 1607 if (!inside(path.join(root, 'node_modules'), resolved)) 1608 throw new Error('outside web dependencies'); 1609 } catch { 1610 complain(file, `unresolved production import ${specifier}`); 1611 } 1612 } 1613 // Sole protocol-key exception: the complete independently reviewed wrapper 1614 // source is byte-pinned, not merely whitelisted by filename. Any key escape, 1615 // altered import/role/tag/lifetime or copied producer fails closed until a 1616 // successor explicitly requalifies the changed implementation and this pin. 1617 const giftwrapFile = path.join(root, 'src/lib/nostr/giftwrap-builder.ts'); 1618 const giftwrapTrusted = 1619 files.has(giftwrapFile) && 1620 createHash('sha256').update(files.get(giftwrapFile)).digest('hex') === 1621 'faf54dd80a0995ac94b4b994d3cfd015516e5e201a1fbb6340e13c836ce49e98'; 1622 if (files.has(giftwrapFile) && !giftwrapTrusted) 1623 complain( 1624 giftwrapFile, 1625 'gift-wrap construction source identity does not match reviewed pin' 1626 ); 1627 const visibilityFile = path.join(root, 'src/lib/runtime/dispose.ts'); 1628 const visibilityTrusted = 1629 files.has(visibilityFile) && 1630 createHash('sha256').update(files.get(visibilityFile)).digest('hex') === 1631 'f236ad457215aff0ace7bdf4cd9d7c1b7ffefa8a49d2d3821f8ca6a79b4bec97'; 1632 if (files.has(visibilityFile) && !visibilityTrusted) 1633 complain( 1634 visibilityFile, 1635 'visibility disposal source identity does not match reviewed pin' 1636 ); 1637 const copyFile = path.join(root, 'src/lib/navigation-copy.ts'); 1638 const copyTrusted = 1639 files.has(copyFile) && 1640 createHash('sha256').update(files.get(copyFile)).digest('hex') === 1641 '1a17eac4b355d8a3fb2b55b3fe1bc856cc3b3bce07434836d708b68407686f20'; 1642 if (files.has(copyFile) && !copyTrusted) 1643 complain( 1644 copyFile, 1645 'copy helper source identity does not match reviewed pin' 1646 ); 1647 // This report owner grants only the explicit reviewed selected-copy action. 1648 // Its complete bytes pin original-context fences and memory retirement too; 1649 // altered or copied producers receive no clipboard/reflection exception. 1650 const reportFile = path.join(root, 'src/lib/support/report.ts'); 1651 const reportTrusted = 1652 files.has(reportFile) && 1653 createHash('sha256').update(files.get(reportFile)).digest('hex') === 1654 'd02ebbfa82cf415c1af192f691b5464fbbc51f898207263bf1422f049a5d9dec'; 1655 if (files.has(reportFile) && !reportTrusted) 1656 complain( 1657 reportFile, 1658 'report copy source identity does not match reviewed pin' 1659 ); 1660 // One reviewed transport producer may retire its own original SDK Relay. 1661 // Complete bytes, original imported factory receiver and a direct call are 1662 // required; no arbitrary DOM remove/alias/reflection exception is granted. 1663 const relayRemovalFile = path.join(root, 'src/lib/nostr/private-pool.ts'); 1664 const relayRemovalTrusted = 1665 files.has(relayRemovalFile) && 1666 createHash('sha256').update(files.get(relayRemovalFile)).digest('hex') === 1667 '2ed123596f26bedb8aab5ec7694be6e264616429e00f745f1614c83f52de9825'; 1668 if (files.has(relayRemovalFile) && !relayRemovalTrusted) 1669 complain( 1670 relayRemovalFile, 1671 'private relay removal source identity does not match reviewed pin' 1672 ); 1673 const scrollFile = path.join(root, 'src/lib/navigation-scroll.ts'); 1674 const scrollTrusted = 1675 files.has(scrollFile) && 1676 createHash('sha256').update(files.get(scrollFile)).digest('hex') === 1677 '9a3dcd9bbde8bcdb18d8962816fa062262505bc3e8ad34d88c78d18dba3a8398'; 1678 if (files.has(scrollFile) && !scrollTrusted) 1679 complain( 1680 scrollFile, 1681 'scroll helper source identity does not match reviewed pin' 1682 ); 1683 const helperFile = path.join(root, 'src/lib/navigation-url.ts'); 1684 const helperPin = 1685 '4ce96334d7cf57ccba518132078278b71d3bf70f519202e491a5f6a8840f7b19'; 1686 const helperTrusted = 1687 files.has(helperFile) && 1688 createHash('sha256').update(files.get(helperFile)).digest('hex') === 1689 helperPin; 1690 if (files.has(helperFile) && !helperTrusted) 1691 complain( 1692 helperFile, 1693 'navigation helper source identity does not match reviewed pin' 1694 ); 1695 function exportIdentity(file, exported, seen = new Set()) { 1696 const key = file + ':' + exported; 1697 if (seen.has(key)) return null; 1698 seen = new Set([...seen, key]); 1699 if (file === '$app/navigation') return exported === 'goto' ? 'goto' : null; 1700 if ( 1701 file === helperFile && 1702 helperTrusted && 1703 ['internalHref', 'navigationHref'].includes(exported) 1704 ) 1705 return exported; 1706 if ( 1707 !files.has(file) || 1708 !codeExtension.test(file) || 1709 file.endsWith('.svelte') 1710 ) 1711 return null; 1712 const ast = sourceAst(file, files.get(file)); 1713 const matches = []; 1714 for (const node of ast.statements) { 1715 if ( 1716 ts.isExportDeclaration(node) && 1717 !node.isTypeOnly && 1718 node.moduleSpecifier && 1719 node.exportClause && 1720 ts.isNamedExports(node.exportClause) 1721 ) { 1722 for (const element of node.exportClause.elements) 1723 if (!element.isTypeOnly && element.name.text === exported) 1724 matches.push( 1725 exportIdentity( 1726 resolve(file, node.moduleSpecifier.text), 1727 (element.propertyName ?? element.name).text, 1728 seen 1729 ) 1730 ); 1731 } 1732 } 1733 return matches.length === 1 ? matches[0] : null; 1734 } 1735 function navigationExports(file, seen = new Set()) { 1736 if (file === '$app/navigation') return true; 1737 if ( 1738 seen.has(file) || 1739 !files.has(file) || 1740 !codeExtension.test(file) || 1741 file.endsWith('.svelte') 1742 ) 1743 return false; 1744 seen = new Set([...seen, file]); 1745 const ast = sourceAst(file, files.get(file)); 1746 for (const node of ast.statements) { 1747 if ( 1748 !ts.isExportDeclaration(node) || 1749 node.isTypeOnly || 1750 !node.moduleSpecifier 1751 ) 1752 continue; 1753 const target = resolve(file, node.moduleSpecifier.text); 1754 if (!node.exportClause || ts.isNamespaceExport(node.exportClause)) { 1755 if (navigationExports(target, seen)) return true; 1756 } else if (ts.isNamedExports(node.exportClause)) { 1757 if ( 1758 node.exportClause.elements.some( 1759 (element) => 1760 !element.isTypeOnly && 1761 exportIdentity( 1762 target, 1763 (element.propertyName ?? element.name).text 1764 ) === 'goto' 1765 ) 1766 ) 1767 return true; 1768 } 1769 } 1770 return false; 1771 } 1772 for (const [file, content] of files) { 1773 const name = relative(root, file); 1774 if (/\.(css|scss|sass|less)$/.test(name) && !allowedCss.has(name)) 1775 complain(file, 'handwritten CSS belongs in theme.css or app.css'); 1776 if (/HC_TEST_ONLY_PROVIDER|HC_TEST_ONLY_SIGNER/.test(content)) 1777 complain(file, 'test provider code is forbidden in production'); 1778 if (forbiddenPath.test(relative(sourceRoot, file))) 1779 complain( 1780 file, 1781 'test/native/generated/credential source is forbidden in production' 1782 ); 1783 if (allowedCss.has(name)) { 1784 // CSS loading is outside the two handwritten-file contract. Decode 1785 // escapes/comments before checking so escaped @import/url cannot hide. 1786 const css = content 1787 .replace(/\\([0-9a-fA-F]{1,6})\s?/g, (_, hex) => 1788 String.fromCodePoint(parseInt(hex, 16)) 1789 ) 1790 .replace(/\\([^\r\n])/g, '$1') 1791 .replace(/\/\*[\s\S]*?\*\//g, ''); 1792 if (/@import\b|url\s*\(/i.test(css)) 1793 complain(file, 'CSS import/url loading is forbidden'); 1794 if ( 1795 /@(?:tailwind|apply|theme|utility|variant|custom-variant|config|plugin|source|reference)\b/i.test( 1796 css 1797 ) 1798 ) 1799 complain(file, 'Tailwind CSS directives are forbidden'); 1800 } 1801 const html = name === 'src/app.html'; 1802 if (!codeExtension.test(file) && !html) continue; 1803 const scripts = []; 1804 if (file.endsWith('.svelte') || html) { 1805 const ast = parse(content, { modern: true }); 1806 if (ast.css) 1807 complain(file, 'component CSS and inline styles are forbidden'); 1808 const staticAttribute = (attribute) => { 1809 if (!attribute || attribute.type !== 'Attribute') return null; 1810 if ( 1811 Array.isArray(attribute.value) && 1812 attribute.value.every((part) => part.type === 'Text') 1813 ) 1814 return attribute.value.map((part) => part.data).join(''); 1815 if ( 1816 attribute.value?.type === 'ExpressionTag' && 1817 attribute.value.expression?.type === 'Literal' && 1818 typeof attribute.value.expression.value === 'string' 1819 ) 1820 return attribute.value.expression.value; 1821 return null; 1822 }; 1823 const elementTag = (node) => { 1824 const tag = 1825 node.type === 'SvelteElement' 1826 ? node.tag?.type === 'Literal' && typeof node.tag.value === 'string' 1827 ? node.tag.value 1828 : null 1829 : node.name; 1830 return tag?.toLowerCase().split(':').pop(); 1831 }; 1832 const inspectElement = (node) => { 1833 const tag = elementTag(node); 1834 if (node.type === 'SvelteElement' && !tag) 1835 return complain( 1836 file, 1837 'computed markup resource elements are forbidden' 1838 ); 1839 if (declarativeMutationTags.has(tag)) 1840 complain( 1841 file, 1842 'declarative SVG resource/style mutation is forbidden' 1843 ); 1844 if ( 1845 [ 1846 'script', 1847 'style', 1848 'iframe', 1849 'object', 1850 'embed', 1851 'applet', 1852 'base' 1853 ].includes(tag) 1854 ) 1855 complain( 1856 file, 1857 'raw markup scripts/styles/embedded resources are forbidden' 1858 ); 1859 const attributes = node.attributes ?? []; 1860 const values = new Map(); 1861 for (const attribute of attributes) { 1862 if (attribute.type === 'SpreadAttribute') 1863 complain(file, 'computed markup attributes are forbidden'); 1864 if (attribute.type !== 'Attribute') continue; 1865 const key = attribute.name.toLowerCase(); 1866 if (values.has(key)) 1867 complain( 1868 file, 1869 'duplicate markup resource attributes are forbidden' 1870 ); 1871 values.set(key, attribute); 1872 const value = staticAttribute(attribute); 1873 if (key === 'srcdoc') 1874 complain(file, 'embedded markup documents are forbidden'); 1875 if (/^on[a-z]/.test(key) && (html || value !== null)) 1876 complain(file, 'raw markup event scripts are forbidden'); 1877 if ( 1878 ['href', 'src', 'xlink:href', 'action', 'formaction'].includes( 1879 key 1880 ) && 1881 value !== null && 1882 /^(?:javascript|vbscript|data):/i.test( 1883 [...value] 1884 .filter((character) => character.charCodeAt(0) > 32) 1885 .join('') 1886 ) 1887 ) 1888 complain(file, 'executable markup resource URLs are forbidden'); 1889 } 1890 if (tag === 'link') { 1891 const rel = staticAttribute(values.get('rel')); 1892 const href = staticAttribute(values.get('href')); 1893 const tokens = rel?.toLowerCase().trim().split(/\s+/) ?? []; 1894 const safeRelations = new Set([ 1895 'icon', 1896 'shortcut', 1897 'apple-touch-icon', 1898 'mask-icon', 1899 'canonical', 1900 'alternate', 1901 'author', 1902 'license', 1903 'help' 1904 ]); 1905 if ( 1906 !tokens.length || 1907 tokens.some((token) => !safeRelations.has(token)) 1908 ) 1909 complain( 1910 file, 1911 'markup stylesheet/client resource links are forbidden' 1912 ); 1913 // Resource selectors must stay literal. Spreads and computed href, 1914 // rel, as, type or resource URLs cannot smuggle another loader mode. 1915 if ( 1916 rel === null || 1917 href === null || 1918 ['as', 'type'].some( 1919 (key) => 1920 values.has(key) && staticAttribute(values.get(key)) === null 1921 ) 1922 ) 1923 complain(file, 'computed markup resource attributes are forbidden'); 1924 if (href !== null) { 1925 const url = href.replace(/^%sveltekit.assets%/, ''); 1926 if ( 1927 /[\\\s]/.test(url) || 1928 [...url].some((character) => character.charCodeAt(0) < 32) || 1929 /^(?:javascript|vbscript|data):/i.test(url) 1930 ) 1931 complain(file, 'unsafe markup resource URL'); 1932 if ( 1933 tokens.some((token) => 1934 ['icon', 'shortcut', 'apple-touch-icon', 'mask-icon'].includes( 1935 token 1936 ) 1937 ) && 1938 (!/^\/(?!\/)[a-zA-Z0-9_./-]+\.(?:ico|png|svg)$/.test(url) || 1939 url.split('/').includes('..')) 1940 ) 1941 complain( 1942 file, 1943 'favicon resources must use literal owned image paths' 1944 ); 1945 } 1946 } 1947 if (tag === 'meta' && values.has('http-equiv')) { 1948 const directive = staticAttribute(values.get('http-equiv')); 1949 if (directive === null || directive.toLowerCase() === 'refresh') 1950 complain( 1951 file, 1952 'markup refresh/executable directives are forbidden' 1953 ); 1954 } 1955 }; 1956 const visit = (node) => { 1957 if (!node || typeof node !== 'object') return; 1958 if ( 1959 node.type === 'RegularElement' || 1960 node.type === 'SvelteElement' || 1961 (node.type === 'Component' && 1962 declarativeMutationTags.has(elementTag(node))) || 1963 (html && node.name && Array.isArray(node.attributes)) 1964 ) 1965 inspectElement(node); 1966 if ( 1967 (node.type === 'BindDirective' && node.name === 'this') || 1968 [ 1969 'UseDirective', 1970 'AttachTag', 1971 'TransitionDirective', 1972 'AnimateDirective' 1973 ].includes(node.type) 1974 ) 1975 complain( 1976 file, 1977 'DOM bindings/actions/attachments cannot expose opaque mutation capabilities' 1978 ); 1979 if (node.type === 'HtmlTag') 1980 complain(file, 'raw markup injection is forbidden'); 1981 if ( 1982 node.type === 'StyleDirective' || 1983 (node.type === 'Attribute' && node.name.toLowerCase() === 'style') 1984 ) 1985 complain(file, 'inline styles are forbidden'); 1986 for (const value of Object.values(node)) { 1987 if (Array.isArray(value)) value.forEach(visit); 1988 else if (value && typeof value === 'object') visit(value); 1989 } 1990 }; 1991 visit(ast.fragment); 1992 for (const script of [ast.instance, ast.module]) { 1993 if (!script) continue; 1994 if ( 1995 html || 1996 script.attributes?.some( 1997 (attribute) => 1998 !['lang', 'context', 'module'].includes( 1999 attribute.name?.toLowerCase() 2000 ) 2001 ) 2002 ) 2003 complain( 2004 file, 2005 'inline HTML scripts or external scripts are forbidden' 2006 ); 2007 } 2008 const expression = (node) => content.slice(node.start, node.end); 2009 const attributeExpression = (attribute) => { 2010 const parts = Array.isArray(attribute.value) 2011 ? attribute.value 2012 : [attribute.value]; 2013 if ( 2014 !parts.length || 2015 parts.some( 2016 (part) => !part || !['Text', 'ExpressionTag'].includes(part.type) 2017 ) 2018 ) 2019 return 'undefined'; 2020 return parts 2021 .map((part) => 2022 part.type === 'Text' 2023 ? JSON.stringify(part.data) 2024 : '(' + expression(part.expression) + ')' 2025 ) 2026 .join(' + '); 2027 }; 2028 // One lexical graph: module declarations enclose instance declarations, 2029 // and template bindings enclose their own branch bodies. Detached 2030 // expression parses cannot prove imported identity or shadowing. 2031 const emit = (node) => { 2032 if (!node || typeof node !== 'object') return ''; 2033 if (node.type === 'Fragment') 2034 return '{' + node.nodes.map(emit).join('\n') + '}'; 2035 if (node.type === 'ConstTag') 2036 return node.declaration.declarations 2037 .map( 2038 (decl) => 2039 'const ' + 2040 expression(decl.id) + 2041 ' = ' + 2042 expression(decl.init) + 2043 ';' 2044 ) 2045 .join('\n'); 2046 if (node.type === 'EachBlock') 2047 return ( 2048 '(' + 2049 expression(node.expression) + 2050 '); { let ' + 2051 expression(node.context) + 2052 ';' + 2053 (node.index ? 'let ' + node.index + ';' : '') + 2054 (node.key ? '(' + expression(node.key) + ');' : '') + 2055 emit(node.body) + 2056 '}' + 2057 emit(node.fallback) 2058 ); 2059 if (node.type === 'SnippetBlock') 2060 return ( 2061 'function ' + 2062 expression(node.expression) + 2063 '(' + 2064 node.parameters.map(expression).join(',') + 2065 ')' + 2066 emit(node.body) 2067 ); 2068 if (node.type === 'AwaitBlock') 2069 return ( 2070 '(' + 2071 expression(node.expression) + 2072 ');' + 2073 emit(node.pending) + 2074 '{' + 2075 (node.value ? 'let ' + expression(node.value) + ';' : '') + 2076 emit(node.then) + 2077 '}{' + 2078 (node.error ? 'let ' + expression(node.error) + ';' : '') + 2079 emit(node.catch) + 2080 '}' 2081 ); 2082 let result = ''; 2083 if (node.attributes) { 2084 const tag = elementTag(node); 2085 for (const attribute of node.attributes) { 2086 if (attribute.type === 'LetDirective') 2087 result += 2088 'let ' + 2089 (attribute.expression 2090 ? expression(attribute.expression) 2091 : attribute.name) + 2092 ';'; 2093 if ( 2094 node.type !== 'Component' && 2095 attribute.type === 'Attribute' && 2096 [ 2097 'href', 2098 'src', 2099 'xlink:href', 2100 'action', 2101 'formaction', 2102 'srcset', 2103 'poster' 2104 ].includes(attribute.name.toLowerCase()) 2105 ) { 2106 const resource = 2107 !( 2108 (tag === 'a' || tag === 'area') && 2109 attribute.name.toLowerCase() === 'href' 2110 ) && 2111 !['action', 'formaction'].includes( 2112 attribute.name.toLowerCase() 2113 ); 2114 let value = attributeExpression(attribute); 2115 if (tag === 'link' && staticAttribute(attribute) !== null) 2116 value = JSON.stringify( 2117 staticAttribute(attribute).replace(/^%sveltekit.assets%/, '') 2118 ); 2119 result += 2120 (resource ? '__hcrResourceUrl' : '__hcrNavigationUrl') + 2121 '(' + 2122 value + 2123 ');'; 2124 if (['srcset', 'poster'].includes(attribute.name.toLowerCase())) 2125 complain(file, 'media resource attributes are forbidden'); 2126 } 2127 } 2128 } 2129 if (node.expression?.start !== undefined) 2130 result += '(' + expression(node.expression) + ');'; 2131 for (const [key, value] of Object.entries(node)) { 2132 if ( 2133 [ 2134 'expression', 2135 'context', 2136 'parameters', 2137 'declaration', 2138 'error' 2139 ].includes(key) 2140 ) 2141 continue; 2142 if (Array.isArray(value)) result += value.map(emit).join('\n'); 2143 else if (value && typeof value === 'object') result += emit(value); 2144 } 2145 return node.attributes ? '{' + result + '}' : result; 2146 }; 2147 scripts.push( 2148 (ast.module 2149 ? content.slice(ast.module.content.start, ast.module.content.end) 2150 : '') + 2151 '\nfunction __hcrInstance() {\n' + 2152 (ast.instance 2153 ? content.slice( 2154 ast.instance.content.start, 2155 ast.instance.content.end 2156 ) 2157 : '') + 2158 '\n' + 2159 emit(ast.fragment) + 2160 '\n}' 2161 ); 2162 } else scripts.push(content); 2163 for (const script of scripts) { 2164 const ast = sourceAst(file, script); 2165 const ownedModel = mutationAdmission( 2166 ast, 2167 (message) => complain(file, message), 2168 (specifier, exported) => { 2169 const target = resolve(file, specifier); 2170 return exported === null 2171 ? navigationExports(target) 2172 ? 'goto' 2173 : null 2174 : exportIdentity(target, exported); 2175 }, 2176 file === scrollFile && scrollTrusted, 2177 file === copyFile && copyTrusted, 2178 file === visibilityFile && visibilityTrusted, 2179 file === reportFile && reportTrusted, 2180 file === relayRemovalFile && relayRemovalTrusted 2181 ); 2182 if (ast.referencedFiles.length || ast.typeReferenceDirectives.length) 2183 complain(file, 'source reference directives are forbidden'); 2184 const inspect = (node) => { 2185 if ( 2186 ts.isExportDeclaration(node) && 2187 node.moduleSpecifier && 2188 (!node.exportClause || ts.isNamespaceExport(node.exportClause)) && 2189 navigationExports(resolve(file, node.moduleSpecifier.text)) 2190 ) 2191 complain( 2192 file, 2193 'escaped navigation star/namespace reexport is forbidden' 2194 ); 2195 if ( 2196 (ts.isImportDeclaration(node) || 2197 ts.isExportDeclaration(node) || 2198 ts.isJSDocImportTag(node)) && 2199 node.moduleSpecifier 2200 ) 2201 resolve( 2202 file, 2203 node.moduleSpecifier.text, 2204 new Set(), 2205 (ts.isImportDeclaration(node) && 2206 ((node.importClause?.namedBindings && 2207 ts.isNamespaceImport(node.importClause.namedBindings)) || 2208 node.importClause?.name)) || 2209 (ts.isExportDeclaration(node) && !node.exportClause) 2210 ); 2211 if ( 2212 (ts.isImportSpecifier(node) || ts.isExportSpecifier(node)) && 2213 (node.propertyName ?? node.name).text === 'createRawSnippet' 2214 ) 2215 complain(file, 'Svelte raw-render factories are forbidden'); 2216 if (ts.isImportTypeNode(node)) { 2217 if ( 2218 ts.isLiteralTypeNode(node.argument) && 2219 ts.isStringLiteral(node.argument.literal) 2220 ) 2221 resolve(file, node.argument.literal.text); 2222 else complain(file, 'unresolved production import type'); 2223 } 2224 if ( 2225 ts.isNewExpression(node) && 2226 node.expression.getText(ast) === 'URL' && 2227 node.arguments?.[1]?.getText(ast) === 'import.meta.url' 2228 ) { 2229 if (ts.isStringLiteralLike(node.arguments[0])) 2230 resolve(file, node.arguments[0].text); 2231 else complain(file, 'computed production imports are forbidden'); 2232 } 2233 if (ts.isImportEqualsDeclaration(node)) 2234 complain(file, 'require/import-equals loaders are forbidden'); 2235 if ( 2236 ts.isCallExpression(node) && 2237 node.expression.kind === ts.SyntaxKind.ImportKeyword 2238 ) { 2239 if ( 2240 node.arguments.length !== 1 || 2241 !ts.isStringLiteralLike(node.arguments[0]) 2242 ) 2243 complain(file, 'computed production imports are forbidden'); 2244 else resolve(file, node.arguments[0].text, new Set(), true); 2245 } 2246 if ( 2247 ts.isIdentifier(node) && 2248 [ 2249 'createRawSnippet', 2250 'require', 2251 'eval', 2252 'Function', 2253 'WebSocket', 2254 'Worker', 2255 'SharedWorker', 2256 'importScripts', 2257 'AudioContext', 2258 'OfflineAudioContext', 2259 'AudioWorkletNode', 2260 'generateSecretKey', 2261 'getSecretKey', 2262 'setSecretKey', 2263 'testSigner', 2264 'mockSigner', 2265 'testProvider', 2266 'mockProvider' 2267 ].includes(node.text) && 2268 !( 2269 node.text === 'generateSecretKey' && 2270 file === giftwrapFile && 2271 giftwrapTrusted 2272 ) 2273 ) 2274 complain( 2275 file, 2276 `production loader/provider/credential API is forbidden: ${node.text}` 2277 ); 2278 if ( 2279 (ts.isPropertyAccessExpression(node) || 2280 ts.isElementAccessExpression(node)) && 2281 !ownedModel(node.expression) && 2282 [ 2283 'serviceWorker', 2284 'audioWorklet', 2285 'paintWorklet', 2286 'addModule' 2287 ].includes( 2288 ts.isPropertyAccessExpression(node) 2289 ? node.name.text 2290 : ts.isStringLiteralLike(node.argumentExpression) 2291 ? node.argumentExpression.text 2292 : '' 2293 ) 2294 ) 2295 complain(file, 'browser worker/client loaders are forbidden'); 2296 if ( 2297 ts.isPropertyAccessExpression(node) && 2298 node.expression.getText(ast) === 'import.meta' && 2299 ['glob', 'globEager', 'resolve'].includes(node.name.text) 2300 ) 2301 complain(file, 'computed production imports are forbidden'); 2302 if ( 2303 (ts.isPropertyAccessExpression(node) || 2304 ts.isElementAccessExpression(node)) && 2305 /^(window|globalThis)\b/.test(node.expression.getText(ast)) && 2306 (ts.isElementAccessExpression(node) || 2307 ['WebSocket', 'eval', 'Function'].includes(node.name.text)) 2308 ) 2309 complain(file, 'indirect production loaders are forbidden'); 2310 if ( 2311 ts.isPropertyAccessExpression(node) && 2312 !ownedModel(node.expression) && 2313 [ 2314 'style', 2315 'cssText', 2316 'styleSheets', 2317 'insertRule', 2318 'adoptedStyleSheets' 2319 ].includes(node.name.text) 2320 ) 2321 complain(file, 'JS-generated inline styles are forbidden'); 2322 if ( 2323 ts.isCallExpression(node) && 2324 ts.isPropertyAccessExpression(node.expression) && 2325 ['setAttribute', 'createElement'].includes( 2326 node.expression.name.text 2327 ) && 2328 node.arguments.some( 2329 (argument) => 2330 ts.isStringLiteralLike(argument) && 2331 argument.text.toLowerCase() === 'style' 2332 ) 2333 ) 2334 complain(file, 'JS-generated inline styles are forbidden'); 2335 if ( 2336 ts.isPropertyAccessExpression(node) && 2337 !ownedModel(node.expression) && 2338 ['innerHTML', 'outerHTML', 'srcdoc', 'insertAdjacentHTML'].includes( 2339 node.name.text 2340 ) 2341 ) 2342 complain(file, 'raw markup injection APIs are forbidden'); 2343 if ( 2344 ts.isElementAccessExpression(node) && 2345 !ownedModel(node.expression) && 2346 ts.isStringLiteralLike(node.argumentExpression) && 2347 ['innerHTML', 'outerHTML', 'srcdoc', 'style', 'cssText'].includes( 2348 node.argumentExpression.text 2349 ) 2350 ) 2351 complain(file, 'raw markup/style injection APIs are forbidden'); 2352 if ( 2353 ts.isCallExpression(node) && 2354 (ts.isPropertyAccessExpression(node.expression) || 2355 ts.isElementAccessExpression(node.expression)) 2356 ) { 2357 const method = ts.isPropertyAccessExpression(node.expression) 2358 ? node.expression.name.text 2359 : ts.isStringLiteralLike(node.expression.argumentExpression) 2360 ? node.expression.argumentExpression.text 2361 : null; 2362 if (method === null) 2363 complain(file, 'computed markup/API calls are forbidden'); 2364 if (['createElement', 'createElementNS'].includes(method)) { 2365 const tag = node.arguments[method === 'createElementNS' ? 1 : 0]; 2366 if (!tag || !ts.isStringLiteralLike(tag)) 2367 complain( 2368 file, 2369 'computed markup resource constructors are forbidden' 2370 ); 2371 else if ( 2372 declarativeMutationTags.has( 2373 tag.text.toLowerCase().split(':').pop() 2374 ) 2375 ) 2376 complain( 2377 file, 2378 'declarative SVG resource/style constructors are forbidden' 2379 ); 2380 else if ( 2381 [ 2382 'script', 2383 'style', 2384 'link', 2385 'iframe', 2386 'object', 2387 'embed', 2388 'applet', 2389 'base' 2390 ].includes(tag.text.toLowerCase().split(':').pop()) 2391 ) 2392 complain(file, 'raw markup resource constructors are forbidden'); 2393 } 2394 if ( 2395 ['write', 'writeln'].includes(method) && 2396 /(?:^|\.)document$/.test(node.expression.expression.getText(ast)) 2397 ) 2398 complain(file, 'raw markup document writers are forbidden'); 2399 } 2400 if ( 2401 ts.isBindingElement(node) && 2402 node.propertyName && 2403 (() => { 2404 const computed = ts.isComputedPropertyName(node.propertyName); 2405 const name = computed 2406 ? node.propertyName.expression 2407 : node.propertyName; 2408 return ( 2409 (computed && !ts.isStringLiteralLike(name)) || 2410 (ts.isStringLiteralLike(name) && 2411 ['generateSecretKey', 'getSecretKey', 'setSecretKey'].includes( 2412 name.text 2413 )) 2414 ); 2415 })() 2416 ) 2417 complain( 2418 file, 2419 'indirect production credential API binding is forbidden' 2420 ); 2421 if ( 2422 ts.isElementAccessExpression(node) && 2423 ts.isStringLiteralLike(node.argumentExpression) && 2424 ['generateSecretKey', 'getSecretKey', 'setSecretKey'].includes( 2425 node.argumentExpression.text 2426 ) 2427 ) 2428 complain(file, 'indirect production credential API is forbidden'); 2429 const accessedMethod = ts.isPropertyAccessExpression(node) 2430 ? node.name.text 2431 : ts.isElementAccessExpression(node) && 2432 ts.isStringLiteralLike(node.argumentExpression) 2433 ? node.argumentExpression.text 2434 : null; 2435 if ( 2436 ['createElement', 'createElementNS'].includes(accessedMethod) && 2437 (!ts.isCallExpression(node.parent) || node.parent.expression !== node) 2438 ) 2439 complain(file, 'indirect markup resource constructors are forbidden'); 2440 for (const doc of node.jsDoc ?? []) inspect(doc); 2441 ts.forEachChild(node, inspect); 2442 }; 2443 inspect(ast); 2444 } 2445 } 2446 const presentCss = [...allowedCss].filter((file) => 2447 files.has(path.join(root, file)) 2448 ); 2449 // Primitives may precede compositions; importing either file activates the complete pair contract. 2450 const unimportedTheme = 2451 presentCss.length === 1 && 2452 presentCss[0] === 'src/theme.css' && 2453 cssImports.length === 0; 2454 if ( 2455 presentCss.length && 2456 !unimportedTheme && 2457 (presentCss.length !== 2 || 2458 cssImports.join(',') !== 'src/theme.css,src/app.css') 2459 ) 2460 findings.push( 2461 'CSS must be imported exactly once, theme.css then app.css, by the root layout' 2462 ); 2463 return findings; 2464 }