File size: 5,894 Bytes
5c0175e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Edge middleware — gates the whole app behind an API key.
//
// It can verify two things on its own: a signed session cookie (issued by
// /api/auth/login after ANY accepted key, including one stored in the database)
// and a raw environment key passed as ?token=/Bearer/X-API-Key.
//
// A database-stored key used directly as ?token= cannot be checked from Edge,
// so requests carrying an unrecognised credential to the media endpoints are
// forwarded and those routes verify it themselves via requireApiAuth().

import { NextRequest, NextResponse } from "next/server";
import {
  AUTH_COOKIE,
  authSecretSource,
  isUsingFallbackKey,
  keyFingerprint,
  verifyRequest,
} from "@/lib/auth";
import { readEnv } from "@/lib/env";

/** Always reachable — sign-in and the keep-alive probes. */
// /api/playa/ runs the PLAY'A V2 protocol, which carries its own bearer
// tokens. PLAY'A discards everything after the host, so no ?token= can ever
// arrive on these routes and the middleware must not demand one.
const PUBLIC_PREFIXES = ["/api/auth/", "/api/playa/"];
const PUBLIC_EXACT = ["/api/health", "/api/ping", "/deovr", "/deovr/"];

/** Routes that perform their own database-aware credential check. */
const SELF_GUARDED_PREFIXES = ["/api/feeds", "/api/stream", "/api/thumbnail", "/vr"];

/** Dropped once you tap VR MODE, so the choice sticks the way it does on SLR. */
const VR_MODE_COOKIE = "vrms_vrmode";

/** Names headset browsers put in their user agent. Best effort only -- the

 *  VR MODE button and this cookie are what actually make VR mode reachable. */
const HEADSET_UA_HINTS = [
  "deovr",
  "playa",
  "play'a",
  "oculusbrowser",
  "quest",
  "pico",
  "wolvic",
];

export async function middleware(req: NextRequest) {
  const { pathname } = req.nextUrl;

  // Diagnostics: report what THIS runtime (Edge) can see, so the Settings
  // panel can compare it with what the Node server sees. Values are never
  // included - only the source, plus a hashed fingerprint once signed in.
  if (pathname === "/api/auth/diagnostics") {
    const verdict = await verifyRequest(req);
    const res = NextResponse.next();
    res.headers.set("x-vrms-edge-key", isUsingFallbackKey() ? "fallback" : "configured");
    res.headers.set("x-vrms-edge-secret", authSecretSource());
    if (verdict.ok) {
      res.headers.set("x-vrms-edge-fp", await keyFingerprint());
    }
    return res;
  }

  if (PUBLIC_EXACT.includes(pathname)) return NextResponse.next();
  if (PUBLIC_PREFIXES.some((p) => pathname.startsWith(p))) return NextResponse.next();

  // VR mode is sticky, the way SLR remembers the mode you picked. You get sent
  // there if you tapped VR MODE before (cookie), or if the app names itself in
  // the user agent. "Desktop site" on the VR page clears the cookie and comes
  // back with ?desktop=1, which always wins. VR_MODE_AUTODETECT=false turns off
  // the user-agent half without touching the button.
  if (pathname === "/" && !req.nextUrl.searchParams.has("desktop")) {
    const remembered = req.cookies.get(VR_MODE_COOKIE)?.value === "1";
    const ua = (req.headers.get("user-agent") || "").toLowerCase();
    const isHeadsetApp = HEADSET_UA_HINTS.some((hint) => ua.includes(hint));
    const autodetect = (readEnv("VR_MODE_AUTODETECT") || "").toLowerCase() !== "false";
    if (remembered || (isHeadsetApp && autodetect)) {
      const target = new URL("/vr", req.url);
      const urlKey = req.nextUrl.searchParams.get("token");
      if (urlKey) target.searchParams.set("token", urlKey);
      return NextResponse.redirect(target);
    }
  }

  const isMedia = SELF_GUARDED_PREFIXES.some((p) => pathname.startsWith(p));
  const isApi = pathname.startsWith("/api/");
  const verdict = await verifyRequest(req);

  // Media endpoints stay key-only: a Quest cannot type a password. Any accepted
  // credential passes; an unrecognised one is forwarded so the route can check
  // it against the in-app key stored in the database.
  if (isMedia) {
    if (verdict.ok || verdict.credential) return NextResponse.next();
  } else if (verdict.ok && verdict.level === "full") {
    // Everything else needs a session that cleared the password step.
    return NextResponse.next();
  }

  // One-tap sign-in: a page link carrying ?token= is exchanged for a session
  // cookie by a Node route (which can also check the in-app key), then the URL
  // is cleaned so the key stops travelling in the address bar.
  const urlToken = req.nextUrl.searchParams.get("token");
  if (!isApi && !isMedia && urlToken) {
    const target = new URL("/api/auth/token-signin", req.url);
    const cleaned = new URL(req.url);
    cleaned.searchParams.delete("token");
    target.searchParams.set("token", urlToken);
    target.searchParams.set("next", `${cleaned.pathname}${cleaned.search}`);
    return NextResponse.redirect(target);
  }

  const passwordPending = verdict.ok && verdict.level === "key";

  if (isApi) {
    return NextResponse.json(
      {
        error: "Unauthorized",
        hint: passwordPending
          ? "Password step not completed - POST /api/auth/password"
          : "Sign in, or append ?token=<your API key>",
        passwordRequired: passwordPending,
      },
      { status: 401 }
    );
  }

  // Browser navigation. A key-level session means the API key was accepted and
  // only the password is missing, so keep that cookie and ask for the password.
  const res = NextResponse.rewrite(
    new URL(passwordPending ? "/?signin=1&password=1" : "/?signin=1", req.url)
  );
  if (verdict.credential && !passwordPending) {
    res.cookies.set(AUTH_COOKIE, "", { path: "/", maxAge: 0 });
  }
  return res;
}

export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico|logo.svg).*)"],
};