Class: HeadlessBrowserTool::StrictSessionMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/headless_browser_tool/strict_session_middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ StrictSessionMiddleware

Returns a new instance of StrictSessionMiddleware.



7
8
9
# File 'lib/headless_browser_tool/strict_session_middleware.rb', line 7

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/headless_browser_tool/strict_session_middleware.rb', line 11

def call(env)
  # Log request headers if enabled
  log_request_headers(env) if HeadlessBrowserTool::Server.show_headers

  # Extract session ID from X-Session-ID header only
  session_id = env["HTTP_X_SESSION_ID"]

  # For MCP requests, require session ID
  if mcp_request?(env) && (session_id.nil? || session_id.empty?)
    return [
      400,
      { "Content-Type" => "application/json" },
      [{ error: "X-Session-ID header is required for multi-session mode" }.to_json]
    ]
  end

  # Sanitize session ID
  if session_id
    session_id = sanitize_session_id(session_id)
    if session_id.nil?
      return [
        400,
        { "Content-Type" => "application/json" },
        [{ error: "Invalid X-Session-ID format" }.to_json]
      ]
    end
  end

  # Store in environment for downstream use
  env["hbt.session_id"] = session_id || "default"

  # Call the app
  status, headers, response = @app.call(env)

  # Add session ID to response headers
  headers["X-Session-ID"] = session_id if session_id

  [status, headers, response]
end