{"version":3,"file":"cross-frame-lms.min.cjs","sources":["../../src/CrossFrameLMS.ts"],"sourcesContent":["// src/CrossFrameLMS.ts\nimport { CrossFrameLMSOptions, MessageData, MessageResponse } from \"./types/CrossFrame\";\nimport { IBaseAPI } from \"./interfaces/IBaseAPI\";\n\n/**\n * Server-side SCORM adapter running in your LMS frame (lms.example.com).\n * Listens for postMessage from child (content) frames, invokes real API,\n * and posts back { messageId, result, error }.\n */\nexport default class CrossFrameLMS {\n  private readonly _api: IBaseAPI;\n  private readonly _origin: string;\n  private readonly _rateLimit: number;\n  private _requestTimes: number[] = [];\n  private _destroyed = false;\n  private readonly _boundOnMessage: (ev: MessageEvent) => void;\n\n  /**\n   * Strict allowlist of methods that can be invoked via cross-frame messages.\n   * Only SCORM API methods and internal helpers are permitted.\n   */\n  private static readonly ALLOWED_METHODS = new Set([\n    // SCORM 1.2 methods\n    \"LMSInitialize\",\n    \"LMSFinish\",\n    \"LMSGetValue\",\n    \"LMSSetValue\",\n    \"LMSCommit\",\n    \"LMSGetLastError\",\n    \"LMSGetErrorString\",\n    \"LMSGetDiagnostic\",\n    // SCORM 2004 methods\n    \"Initialize\",\n    \"Terminate\",\n    \"GetValue\",\n    \"SetValue\",\n    \"Commit\",\n    \"GetLastError\",\n    \"GetErrorString\",\n    \"GetDiagnostic\",\n    // Internal method for cache warming\n    \"getFlattenedCMI\",\n  ]);\n\n  /**\n   * Creates a new CrossFrameLMS instance.\n   * @param api - The SCORM API instance to delegate calls to\n   * @param targetOrigin - Origin to accept messages from. Default \"*\" accepts all origins.\n   * @param options - Configuration options\n   */\n  constructor(api: IBaseAPI, targetOrigin: string = \"*\", options: CrossFrameLMSOptions = {}) {\n    this._api = api;\n    this._origin = targetOrigin;\n    this._rateLimit = options.rateLimit ?? 100;\n\n    // Warn about wildcard origin security implications\n    if (targetOrigin === \"*\") {\n      console.warn(\n        \"CrossFrameLMS: Using wildcard origin ('*') allows any origin to send messages. \" +\n          \"This is insecure for production use. \" +\n          \"Specify an explicit origin (e.g., 'https://content.example.com') to restrict message sources.\",\n      );\n    }\n\n    this._boundOnMessage = this._onMessage.bind(this);\n    window.addEventListener(\"message\", this._boundOnMessage);\n  }\n\n  /**\n   * Destroys this instance, removing event listeners and preventing further message processing.\n   * Once destroyed, the instance cannot be reused.\n   */\n  destroy(): void {\n    if (this._destroyed) return;\n    this._destroyed = true;\n    window.removeEventListener(\"message\", this._boundOnMessage);\n    this._requestTimes.length = 0;\n  }\n\n  /**\n   * Checks if the rate limit has been exceeded.\n   * Uses a sliding window of 1 second.\n   * @returns true if rate limit exceeded, false otherwise\n   */\n  private _isRateLimited(): boolean {\n    const now = Date.now();\n    // Remove requests older than 1 second\n    this._requestTimes = this._requestTimes.filter((t) => now - t < 1000);\n    if (this._requestTimes.length >= this._rateLimit) {\n      return true;\n    }\n    this._requestTimes.push(now);\n    return false;\n  }\n\n  /**\n   * Type guard to validate MessageData structure\n   */\n  private static _isValidMessageData(data: unknown): data is MessageData {\n    if (typeof data !== \"object\" || data === null) return false;\n\n    const msg = data as Partial<MessageData>;\n\n    // Required fields\n    if (typeof msg.messageId !== \"string\" || msg.messageId.length === 0) return false;\n    if (typeof msg.method !== \"string\" || msg.method.length === 0) return false;\n\n    // params must be an array if present (required for apply())\n    if (msg.params !== undefined && !Array.isArray(msg.params)) return false;\n\n    // isHeartbeat must be boolean if present\n    if (msg.isHeartbeat !== undefined && typeof msg.isHeartbeat !== \"boolean\") return false;\n\n    return true;\n  }\n\n  /**\n   * Handles incoming postMessage events from child frames.\n   */\n  private _onMessage(ev: MessageEvent): void {\n    // Ignore messages if destroyed\n    if (this._destroyed) return;\n\n    // Validate the message origin unless all origins are allowed\n    if (this._origin !== \"*\" && ev.origin !== this._origin) {\n      return;\n    }\n\n    // CF-LMS-02: Validate that ev.data has the expected MessageData structure\n    if (!CrossFrameLMS._isValidMessageData(ev.data)) return;\n\n    const msg = ev.data;\n    if (!ev.source) return;\n\n    // Validate that ev.source is a Window with postMessage capability\n    // ev.source can be Window, MessagePort, ServiceWorker, or null\n    // We only handle Window sources for iframe communication\n    if (!(\"postMessage\" in ev.source)) return;\n\n    const source = ev.source as Window;\n\n    // Handle heartbeat separately (bypass rate limit and allowlist)\n    if (msg.isHeartbeat) {\n      const resp: MessageResponse = {\n        messageId: msg.messageId,\n        isHeartbeat: true,\n      };\n      source.postMessage(resp, this._origin);\n      return;\n    }\n\n    // Check rate limit\n    if (this._isRateLimited()) {\n      // SCORM ERROR CODE USAGE: Using error code \"101\" for rate limiting\n      //\n      // While not a standard SCORM error code, \"101\" is used here to signal rate limiting\n      // in cross-frame communication. Standard SCORM error codes are:\n      // - SCORM 1.2: 0, 101, 201, 202, 203, 301, 401, 402, 403, 404, 405\n      // - SCORM 2004: 0, 101, 102, 103, 201, 301, 351, 391, 401-408\n      //\n      // Using \"101\" (General Exception) is appropriate here because:\n      // 1. It indicates a general error condition without exposing security details\n      // 2. It's recognized by SCORM content as a non-zero error code\n      // 3. It doesn't conflict with specific SCORM error semantics\n      // 4. The actual error message \"Rate limit exceeded\" provides debug context\n      //\n      // The CrossFrameAPI detects this specific message to emit a \"rateLimited\" event,\n      // allowing content to react appropriately (e.g., back off, show user message).\n      const resp: MessageResponse = {\n        messageId: msg.messageId,\n        error: { message: \"Rate limit exceeded\", code: \"101\" },\n      };\n      source.postMessage(resp, this._origin);\n      return;\n    }\n\n    // Check method allowlist\n    if (!CrossFrameLMS.ALLOWED_METHODS.has(msg.method)) {\n      const resp: MessageResponse = {\n        messageId: msg.messageId,\n        error: { message: `Method not allowed: ${msg.method}`, code: \"101\" },\n      };\n      source.postMessage(resp, this._origin);\n      return;\n    }\n\n    this._process(msg, source);\n  }\n\n  /**\n   * Processes a validated message by invoking the requested API method.\n   */\n  private _process(msg: MessageData, source: Window): void {\n    const sendResponse = (result?: unknown, error?: { message: string; code?: string }) => {\n      const resp: MessageResponse = { messageId: msg.messageId };\n      if (result !== undefined) resp.result = result;\n      if (error !== undefined) resp.error = error;\n      source.postMessage(resp, this._origin);\n    };\n\n    try {\n      const fn = (this._api as unknown as Record<string, unknown>)[msg.method];\n      if (typeof fn !== \"function\") {\n        sendResponse(undefined, { message: `Method ${msg.method} not found` });\n        return;\n      }\n\n      // CF-LMS-01: Validate params is an array before apply()\n      // This should never fail due to _isValidMessageData check, but defense in depth\n      const params = Array.isArray(msg.params) ? msg.params : [];\n\n      const result = fn.apply(this._api, params);\n\n      if (result && typeof (result as Promise<unknown>).then === \"function\") {\n        (result as Promise<unknown>)\n          .then((r) => sendResponse(r))\n          .catch((e: unknown) => {\n            // ERROR CODE PRESERVATION: Extract error code from Error objects\n            // SCORM API errors may include a numeric code property for specific error conditions.\n            // We preserve this code to maintain proper error semantics across the cross-frame boundary.\n            const message = e instanceof Error ? e.message : \"Unknown error\";\n            const code =\n              e && typeof e === \"object\" && \"code\" in e && typeof e.code === \"string\"\n                ? e.code\n                : undefined;\n            const errorObj: { message: string; code?: string } = { message };\n            if (code !== undefined) {\n              errorObj.code = code;\n            }\n            sendResponse(undefined, errorObj);\n          });\n      } else {\n        sendResponse(result);\n      }\n    } catch (e: unknown) {\n      // ERROR CODE PRESERVATION: Extract error code from Error objects\n      // SCORM API errors may include a numeric code property for specific error conditions.\n      // We preserve this code to maintain proper error semantics across the cross-frame boundary.\n      const message = e instanceof Error ? e.message : \"Unknown error\";\n      const code =\n        e && typeof e === \"object\" && \"code\" in e && typeof e.code === \"string\"\n          ? e.code\n          : undefined;\n      const errorObj: { message: string; code?: string } = { message };\n      if (code !== undefined) {\n        errorObj.code = code;\n      }\n      sendResponse(undefined, errorObj);\n    }\n  }\n}\n"],"names":["CrossFrameLMS","_api","_origin","_rateLimit","_requestTimes","_destroyed","_boundOnMessage","static","Set","constructor","api","targetOrigin","options","this","rateLimit","console","warn","_onMessage","bind","window","addEventListener","destroy","removeEventListener","length","_isRateLimited","now","Date","filter","t","push","_isValidMessageData","data","msg","messageId","method","params","Array","isArray","isHeartbeat","ev","origin","source","postMessage","error","message","code","ALLOWED_METHODS","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