All files / src/capabilities SecurityAdvisor.ts

72.58% Statements 45/62
68.75% Branches 33/48
100% Functions 9/9
78.84% Lines 41/52

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231                          25x 25x 25x 27x             20x   17x               12x                         12x                       12x                                   25x   25x       25x     25x 2x             22x                                               3x   3x   3x           3x             3x 3x 4x 4x 4x 4x 4x         3x     3x 4x 4x   3x 3x   3x 3x   3x   2x                 10x 10x     10x                                 10x   10x                                                                            
import { createI18nKey } from "../protocol/ProtocolValidator.js";
import { ISecurityStatus, EngineErrorCode } from "../types.js";
import { EngineError } from "../errors/EngineError.js";
 
/**
 * SRI検証やCOOP/COEPヘッダーの診断を提供します。
 */
export class SecurityAdvisor {
  /**
   * SRI文字列が有効な形式(W3C規格)かどうかを検証します。
   * マルチハッシュ形式をサポートします。
   */
  static isValidSRI(sri: string): boolean {
    Iif (!sri || typeof sri !== "string") return false;
    const hashes = sri.split(/\s+/);
    const pattern = /^(sha256|sha384|sha512)-[A-Za-z0-9+/=]+$/;
    return hashes.every((h) => pattern.test(h));
  }
 
  /**
   * 安全な fetch オプションを生成します。
   */
  static getSafeFetchOptions(sri?: string): RequestInit {
    if (!sri || !SecurityAdvisor.isValidSRI(sri)) return {};
 
    return {
      integrity: sri,
      mode: "cors",
      credentials: "omit",
    };
  }
 
  /** Allowed protocols for secure resource downloads. */
  private static readonly ALLOWED_PROTOCOLS = new Set([
    "https:",
    "blob:",
    "data:",
  ]);
 
  /**
   * Loopback hostnames considered safe for HTTP connections.
   * Per W3C Secure Contexts spec, loopback addresses are "potentially trustworthy".
   * Subdomains of localhost (e.g. myapp.localhost) are also safe per RFC 6761 §6.3.
   * @see https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy
   * @see https://www.rfc-editor.org/rfc/rfc6761#section-6.3
   */
  private static readonly LOOPBACK_HOSTS = new Set([
    "localhost",
    "127.0.0.1",
    "[::1]",
  ]);
 
  /**
   * Determines if a hostname is a loopback address.
   * Includes exact matches (localhost, 127.0.0.1, [::1]) and
   * *.localhost subdomains (e.g. myapp.localhost for Portless).
   */
  public static isLoopbackHost(hostname: string): boolean {
    return (
      SecurityAdvisor.LOOPBACK_HOSTS.has(hostname) ||
      hostname.endsWith(".localhost")
    );
  }
 
  /**
   * Performs a fetch with protocol-level security enforcement.
   * Allowed protocols: HTTPS, blob:, data:.
   * HTTP is permitted only for loopback hosts (localhost, 127.0.0.1, [::1])
   * per W3C Secure Contexts specification.
   * This prevents man-in-the-middle attacks on engine resource downloads.
   */
  static async safeFetch(
    url: string,
    options?: RequestInit,
  ): Promise<Response> {
    // Resolve relative URLs against the current origin (browser) or reject them (non-browser).
    const resolved = new URL(url, globalThis.location?.href);
 
    const isAllowedProtocol = SecurityAdvisor.ALLOWED_PROTOCOLS.has(
      resolved.protocol,
    );
    const isLoopbackHttp =
      resolved.protocol === "http:" &&
      SecurityAdvisor.isLoopbackHost(resolved.hostname);
 
    if (!isAllowedProtocol && !isLoopbackHttp) {
      throw new EngineError({
        code: EngineErrorCode.SECURITY_ERROR,
        message: `Insecure protocol "${resolved.protocol}" is not allowed for remote hosts. Use HTTPS or connect to localhost.`,
        i18nKey: createI18nKey("engine.errors.insecureConnection"),
      });
    }
 
    return fetch(resolved.href, options);
  }
 
  /**
   * W3C勧告に基づいたマルチハッシュSRI検証。
   * 最強のアルゴリズムを優先して検証します。
   */
  /**
   * SRI ハッシュを検証し、一致しない場合は例外をスローします。
   * Refuse by Exception 原則に基づく厳格な検証メソッドです。
   */
  static async assertSRI(data: ArrayBuffer, sri: string): Promise<void> {
    const isValid = await this.verifySRI(data, sri);
    if (!isValid) {
      const i18nKey = createI18nKey("engine.errors.sriMismatch");
      throw new EngineError({
        code: EngineErrorCode.SRI_MISMATCH,
        message: "SRI hash verification failed.",
        i18nKey,
      });
    }
  }
 
  static async verifySRI(data: ArrayBuffer, sri: string): Promise<boolean> {
    Iif (!SecurityAdvisor.isValidSRI(sri)) return false;
 
    const hashes = sri.split(/\s+/);
 
    const algoPriority: Record<string, number> = {
      sha256: 1,
      sha384: 2,
      sha512: 3,
    };
 
    const algoMap: Record<string, string> = {
      sha256: "SHA-256",
      sha384: "SHA-384",
      sha512: "SHA-512",
    };
 
    // 2026 Best Practice: 最強アルゴリズムを特定
    let strongestLevel = 0;
    for (const hash of hashes) {
      const algo = hash.split("-")[0];
      Eif (algo) {
        const priority = algoPriority[algo];
        Eif (priority !== undefined && priority > strongestLevel) {
          strongestLevel = priority;
        }
      }
    }
 
    Iif (strongestLevel === 0) return false;
 
    // 最強レベルのハッシュのうち、いずれか一つにマッチすればOK
    for (const hash of hashes) {
      const [algo, expectedBase64] = hash.split("-") as [string, string];
      if (algoPriority[algo] !== strongestLevel) continue;
 
      const webCryptoAlgo = algoMap[algo];
      Iif (!webCryptoAlgo) continue;
 
      const digest = await crypto.subtle.digest(webCryptoAlgo, data);
      const actualBase64 = btoa(String.fromCharCode(...new Uint8Array(digest)));
 
      if (actualBase64 === expectedBase64) return true;
    }
    return false;
  }
 
  /**
   * セキュリティステータスを診断します。
   * COOP/COEPヘッダーの存在を確認します。
   */
  static async getStatus(): Promise<ISecurityStatus> {
    const isCrossOriginIsolated =
      typeof crossOriginIsolated !== "undefined" && crossOriginIsolated;
    const missingHeaders: string[] = [];
 
    // 2026 Best Practice: ブラウザ環境でのみヘッダー診断を試行
    Iif (typeof window !== "undefined" && typeof fetch !== "undefined") {
      try {
        // 2026: 5s timeout for diagnostics fetch
        const response = await fetch(window.location.href, {
          method: "HEAD",
          signal: AbortSignal.timeout(5000),
        });
        const coop = response.headers.get("cross-origin-opener-policy");
        const coep = response.headers.get("cross-origin-embedder-policy");
 
        if (!coop) missingHeaders.push("cross-origin-opener-policy");
        if (!coep) missingHeaders.push("cross-origin-embedder-policy");
      } catch {
        // HEADリクエスト失敗時は無視
      }
    }
 
    const sriSupported = typeof crypto !== "undefined" && !!crypto.subtle;
 
    return {
      isCrossOriginIsolated,
      canUseThreads: isCrossOriginIsolated,
      sriSupported,
      sriEnabled: sriSupported,
      coopCoepEnabled: isCrossOriginIsolated,
      missingHeaders: missingHeaders.length > 0 ? missingHeaders : undefined,
    };
  }
 
  /**
   * 2026 Zenith Tier: 隔離環境を有効化するための具体的なアドバイスを返します。
   */
  static getRemediationAdvice(): string {
    return `
To enable Multi-threading (SharedArrayBuffer), set the following HTTP headers:
- Cross-Origin-Opener-Policy: same-origin
- Cross-Origin-Embedder-Policy: require-corp
 
Platform examples:
[Vercel (vercel.json)]
{ "headers": [{ "source": "/(.*)", "headers": [
  { "key": "Cross-Origin-Opener-Policy", "value": "same-origin" },
  { "key": "Cross-Origin-Embedder-Policy", "value": "require-corp" }
]}]}
 
[Cloudflare Pages (_headers)]
/*
  Cross-Origin-Opener-Policy: same-origin
  Cross-Origin-Embedder-Policy: require-corp
 
[Netlify (_headers)]
/*
  Cross-Origin-Opener-Policy: same-origin
  Cross-Origin-Embedder-Policy: require-corp
`;
  }
}