import { v as validateAuth } from './auth-DuunT7Cg.js';
import { s as shareStore } from './share-store-B9jMpVg0.js';
import { randomBytes } from 'crypto';
import { j as json } from './index-CoD1IJuy.js';
import './shared-server-DaWdgxVh.js';
import 'better-sqlite3';
import 'fs';
import 'path';

const GLOBAL_KEY = "__shooter_ws_tickets";
const tickets = globalThis[GLOBAL_KEY] || /* @__PURE__ */ new Map();
globalThis[GLOBAL_KEY] = tickets;
function generateTicket(scope) {
  const ticket = randomBytes(32).toString("hex");
  tickets.set(ticket, {
    createdAt: Date.now(),
    readOnly: scope?.readOnly ?? null,
    terminalId: scope?.terminalId ?? null,
    used: false
  });
  return ticket;
}
setInterval(() => {
  const now = Date.now();
  for (const [key, val] of tickets) {
    if (now - val.createdAt > 3e4) {
      tickets.delete(key);
    }
  }
}, 3e4).unref();
const RATE_LIMIT_WINDOW_MS = 6e4;
const RATE_LIMIT_MAX = 30;
const rateLimitMap = /* @__PURE__ */ new Map();
function checkRateLimit(apiKey) {
  const now = Date.now();
  const cutoff = now - RATE_LIMIT_WINDOW_MS;
  let timestamps = rateLimitMap.get(apiKey);
  if (!timestamps) {
    timestamps = [];
    rateLimitMap.set(apiKey, timestamps);
  }
  const recent = timestamps.filter((t) => t > cutoff);
  rateLimitMap.set(apiKey, recent);
  if (recent.length >= RATE_LIMIT_MAX) {
    return false;
  }
  recent.push(now);
  return true;
}
setInterval(() => {
  const cutoff = Date.now() - RATE_LIMIT_WINDOW_MS;
  for (const [key, timestamps] of rateLimitMap) {
    const recent = timestamps.filter((t) => t > cutoff);
    if (recent.length === 0) {
      rateLimitMap.delete(key);
    } else {
      rateLimitMap.set(key, recent);
    }
  }
}, 3e5).unref();
const POST = ({ request }) => {
  const bearer = (request.headers.get("authorization") ?? request.headers.get("Authorization") ?? "").replace(/^Bearer\s+/i, "").trim();
  const authError = validateAuth(request);
  if (authError) {
    const session = bearer ? shareStore.resolveToken(bearer) : null;
    if (!session) {
      return authError;
    }
    if (!checkRateLimit(bearer)) {
      return json(
        { error: "Rate limit exceeded. Maximum 30 ticket requests per minute." },
        { status: 429 }
      );
    }
    const ticket2 = generateTicket({
      readOnly: session.mode === "view",
      terminalId: session.terminalId
    });
    return json({ expiresIn: 30, ticket: ticket2 });
  }
  if (!checkRateLimit(bearer)) {
    return json(
      { error: "Rate limit exceeded. Maximum 30 ticket requests per minute." },
      { status: 429 }
    );
  }
  const ticket = generateTicket();
  return json({
    expiresIn: 30,
    ticket
  });
};

export { POST };
//# sourceMappingURL=_server.ts-W6i3EnGX.js.map
