All files / server/security access-control.ts

89.17% Statements 140/157
86.5% Branches 109/126
92% Functions 23/25
93.43% Lines 128/137

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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351                                                        134x 134x 134x 134x 134x 134x     84x 84x 1x 1x 1x 1x 1x   84x       84x           84x     84x 1x 1x 1x 1x 1x 1x             83x 83x 83x                   210x 210x   125x 41x 41x 41x     84x 84x     210x 210x       3x 3x 3x 3x 2x 2x 2x 2x                     140x 132x       8x 3x     5x 5x 1x         4x 140x 2x         2x             384x 384x       150x 149x 150x 150x 148x                     95x   90x 90x       90x 83x 82x               99x 77x         1x 4x 2x 2x   2x                   101x 101x   77x         24x 24x 24x       1x           23x 1x     22x       47x 41x 41x 41x             47x 1x     46x           9x     37x 37x 1x     36x 36x 36x   36x   36x   35x   1x     35x           7x 14x 14x 1x     1x     13x 13x 13x                                                   103x             55x 93x 93x 1x         1x   92x 2x 2x   90x 2x 2x   88x 69x 69x   19x      
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import type { IncomingHttpHeaders, IncomingMessage } from "node:http";
import { isIP } from "node:net";
import type { NextFunction, Request, RequestHandler, Response } from "express";
import type { VerifyClientCallbackAsync } from "ws";
 
export type TrustMode = "local" | "gateway";
 
export interface TrustConfig {
  mode: TrustMode;
  gatewaySecret?: string;
  trustedProxy?: string;
  /**
   * Local mode only: the explicit UNOSIM_UNSAFE_ALLOW_EXTERNAL_LOCAL_BIND
   * opt-in. Without it, local mode serves loopback clients only.
   */
  allowExternalLocalClients?: true;
}
 
export interface RequestIdentity {
  subject: string;
  roles: readonly string[];
}
 
export type AuthorizationResult =
  | { allowed: true; identity: RequestIdentity }
  | { allowed: false; status: 401 | 403 };
 
const SUBJECT_PATTERN = /^[A-Za-z0-9._:~-]{1,128}$/;
const ALLOWED_ROLES = new Set(["user"]);
const LOCAL_SESSION_COOKIE = "unosim_local_session";
const LOCAL_SESSION_MAX_AGE_SECONDS = 24 * 60 * 60;
const localSessionSigningKey = randomBytes(32);
const requestIdentity = new WeakMap<IncomingMessage, RequestIdentity>();
 
function parseCookies(header: string | undefined): Map<string, string> {
  const cookies = new Map<string, string>();
  for (const part of header?.split(";") ?? []) {
    const separator = part.indexOf("=");
    Iif (separator < 1) continue;
    const name = part.slice(0, separator).trim();
    const value = part.slice(separator + 1).trim();
    cookies.set(name, value);
  }
  return cookies;
}
 
function signLocalSession(id: string): string {
  return createHmac("sha256", localSessionSigningKey)
    .update(id)
    .digest("base64url");
}
 
function readLocalSession(headers: IncomingHttpHeaders): string | undefined {
  const token = parseCookies(singleHeader(headers, "cookie")).get(
    LOCAL_SESSION_COOKIE,
  );
  if (!token) return undefined;
  const separator = token.indexOf(".");
  Iif (separator < 1) return undefined;
  const id = token.slice(0, separator);
  const signature = token.slice(separator + 1);
  Iif (!/^[A-Za-z0-9_-]{22}$/.test(id)) return undefined;
  return secretsEqual(signature, signLocalSession(id)) ? id : undefined;
}
 
function createLocalIdentity(): {
  identity: RequestIdentity;
  cookie: string;
} {
  const id = randomBytes(16).toString("base64url");
  const token = `${id}.${signLocalSession(id)}`;
  return {
    identity: { subject: `local.${id}`, roles: ["user"] },
    cookie: `${LOCAL_SESSION_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${LOCAL_SESSION_MAX_AGE_SECONDS}`,
  };
}
 
function resolveRequestAuthorization(
  req: IncomingMessage,
  trust: TrustConfig,
): AuthorizationResult & { cookie?: string } {
  const existing = requestIdentity.get(req);
  if (existing) return { allowed: true, identity: existing };
 
  if (trust.mode === "gateway") {
    const authorization = authorizeHeaders(req.headers, trust);
    if (authorization.allowed) requestIdentity.set(req, authorization.identity);
    return authorization;
  }
 
  const sessionId = readLocalSession(req.headers);
  const resolved: { identity: RequestIdentity; cookie?: string } = sessionId
    ? { identity: { subject: `local.${sessionId}`, roles: ["user"] } }
    : createLocalIdentity();
  requestIdentity.set(req, resolved.identity);
  return { allowed: true, identity: resolved.identity, cookie: resolved.cookie };
}
 
function isIpOrCidr(value: string): boolean {
  const [address, prefix, ...rest] = value.split("/");
  Iif (rest.length > 0 || !address) return false;
  const version = isIP(address);
  if (version === 0) return false;
  Iif (prefix === undefined) return true;
  Iif (!/^\d+$/.test(prefix)) return false;
  const bits = Number(prefix);
  return bits >= 0 && bits <= (version === 4 ? 32 : 128);
}
 
export function parseTrustConfig(
  env: NodeJS.ProcessEnv,
  profile: {
    serverMode: "local" | "docker";
    dockerTestBypassGateway: boolean;
  },
  allowUnsafeExternalLocalBind = false,
): TrustConfig {
  if (profile.serverMode === "local") {
    return allowUnsafeExternalLocalBind
      ? { mode: "local", allowExternalLocalClients: true }
      : { mode: "local" };
  }
  if (profile.dockerTestBypassGateway) {
    return { mode: "local" };
  }
 
  const gatewaySecret = env.UNOSIM_GATEWAY_SECRET;
  if (!gatewaySecret || gatewaySecret.length < 32) {
    throw new Error(
      "UNOSIM_GATEWAY_SECRET must contain at least 32 characters in gateway mode",
    );
  }
 
  const trustedProxy = env.UNOSIM_TRUSTED_PROXY?.trim();
  if (!trustedProxy || !isIpOrCidr(trustedProxy)) {
    throw new Error(
      "UNOSIM_TRUSTED_PROXY must be an explicit IP address or CIDR in gateway mode",
    );
  }
 
  return { mode: "gateway", gatewaySecret, trustedProxy };
}
 
function singleHeader(
  headers: IncomingHttpHeaders,
  name: string,
): string | undefined {
  const value = headers[name];
  return Array.isArray(value) ? undefined : value;
}
 
function isLoopbackAddress(address: string | undefined): boolean {
  if (!address) return false;
  const normalized = address.startsWith("::ffff:") ? address.slice("::ffff:".length) : address;
  const version = isIP(normalized);
  if (version === 6) return normalized === "::1";
  return version === 4 && normalized.split(".", 1)[0] === "127";
}
 
/**
 * Whether a Host header names this machine: `localhost` or a numeric loopback
 * address, with any port. A DNS rebinding page reaches a loopback listener
 * under its own host name, and a LAN client under the machine's LAN address;
 * both fail here.
 */
export function isLoopbackHostHeader(host: string | undefined): boolean {
  // A Host header is host[:port]; anything URL syntax would reinterpret is refused.
  if (!host || /[\s/\\@?#]/.test(host)) return false;
  let hostname: string;
  try {
    hostname = new URL(`http://${host}`).hostname;
  } catch {
    return false;
  }
  if (hostname === "localhost") return true;
  if (hostname === "[::1]") return true;
  return isIP(hostname) === 4 && isLoopbackAddress(hostname);
}
 
/**
 * Local mode runs sketches as native processes, so only this machine may use it.
 * Gateway mode and the explicit unsafe external opt-in are not restricted here.
 */
export function isLocalClientAllowed(req: IncomingMessage, trust: TrustConfig): boolean {
  if (trust.mode !== "local" || trust.allowExternalLocalClients) return true;
  return isLoopbackHostHeader(singleHeader(req.headers, "host"));
}
 
/** Rejects HTTP requests for a non-loopback host in local mode (LAN, DNS rebinding). */
export function createLocalHostGuard(trust: TrustConfig): RequestHandler {
  return (req: Request, res: Response, next: NextFunction): void => {
    if (!isLocalClientAllowed(req, trust)) {
      res.status(403).json({ error: "Local mode accepts only localhost requests" });
      return;
    }
    next();
  };
}
 
export function isWebSocketOriginAllowed(
  headers: IncomingHttpHeaders,
  trust: TrustConfig,
  allowedOrigins: readonly string[],
  remoteAddress?: string,
): boolean {
  const origin = singleHeader(headers, "origin");
  if (!origin) {
    // Non-browser clients send no Origin; locally only this machine may connect without one.
    return trust.mode === "local"
      && (trust.allowExternalLocalClients === true || isLoopbackAddress(remoteAddress));
  }
 
  let parsed: URL;
  try {
    parsed = new URL(origin);
    if (
      parsed.origin !== origin ||
      !["http:", "https:"].includes(parsed.protocol)
    ) {
      return false;
    }
  } catch {
    return false;
  }
 
  if (trust.mode === "local" && singleHeader(headers, "host") === parsed.host) {
    return true;
  }
 
  return allowedOrigins.includes(origin);
}
 
function secretsEqual(actual: string | undefined, expected: string): boolean {
  if (!actual) return false;
  const actualDigest = createHash("sha256").update(actual).digest();
  const expectedDigest = createHash("sha256").update(expected).digest();
  return timingSafeEqual(actualDigest, expectedDigest);
}
 
export function authorizeHeaders(
  headers: IncomingHttpHeaders,
  trust: TrustConfig,
): AuthorizationResult {
  if (trust.mode === "local") {
    return { allowed: true, identity: { subject: "local", roles: ["user"] } };
  }
 
  if (
    !secretsEqual(
      singleHeader(headers, "x-unosim-gateway-secret"),
      trust.gatewaySecret!,
    )
  ) {
    return { allowed: false, status: 401 };
  }
 
  const subject = singleHeader(headers, "x-unosim-subject");
  if (!subject || !SUBJECT_PATTERN.test(subject)) {
    return { allowed: false, status: 401 };
  }
 
  const rolesHeader = singleHeader(headers, "x-unosim-roles");
  Iif (!rolesHeader) return { allowed: false, status: 403 };
  const roles = rolesHeader
    .split(",")
    .map((role) => role.trim())
    .filter(Boolean);
  if (
    !roles.includes("user") ||
    roles.some((role) => !ALLOWED_ROLES.has(role))
  ) {
    return { allowed: false, status: 403 };
  }
 
  return { allowed: true, identity: { subject, roles } };
}
 
export function createUserAuthorizationMiddleware(
  trust: TrustConfig,
): RequestHandler {
  return (req: Request, res: Response, next: NextFunction): void => {
    const result = resolveRequestAuthorization(req, trust);
    if (!result.allowed) {
      res
        .status(result.status)
        .json({ error: result.status === 401 ? "Unauthorized" : "Forbidden" });
      return;
    }
 
    res.locals.unosimIdentity = result.identity;
    if (result.cookie) res.appendHeader("Set-Cookie", result.cookie);
    next();
  };
}
 
/**
 * Issues a server-authenticated local session before static/API requests. This
 * keeps browser clients independent without trusting a client-provided user ID.
 * Gateway mode remains entirely governed by the gateway contract.
 */
export function createLocalSessionMiddleware(trust: TrustConfig): RequestHandler {
  return (req: Request, res: Response, next: NextFunction): void => {
    if (trust.mode === "local") {
      const result = resolveRequestAuthorization(req, trust);
      if (result.allowed) {
        res.locals.unosimIdentity = result.identity;
        if (result.cookie) res.appendHeader("Set-Cookie", result.cookie);
      }
    }
    next();
  };
}
 
export function getRequestAuthorization(
  req: IncomingMessage,
  trust: TrustConfig,
): AuthorizationResult {
  return resolveRequestAuthorization(req, trust);
}
 
export function createWebSocketAuthorizationVerifier(
  trust: TrustConfig,
  allowedOrigins: readonly string[],
): VerifyClientCallbackAsync {
  return ({ req }, done) => {
    const result = resolveRequestAuthorization(req, trust);
    if (!result.allowed) {
      done(
        false,
        result.status,
        result.status === 401 ? "Unauthorized" : "Forbidden",
      );
      return;
    }
    if (!isLocalClientAllowed(req, trust)) {
      done(false, 403, "Forbidden host");
      return;
    }
    if (!isWebSocketOriginAllowed(req.headers, trust, allowedOrigins, req.socket?.remoteAddress)) {
      done(false, 403, "Forbidden origin");
      return;
    }
    if (result.cookie) {
      done(true, undefined, undefined, { "Set-Cookie": result.cookie });
      return;
    }
    done(true);
  };
}