File size: 10,034 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
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
// Authentication primitives — Edge-safe (no Node built-ins, no Prisma).
//
// Two ways to sign in, both fully supported:
//
//   1. A key configured as a Space Secret / environment variable
//      (APP_API_KEY, legacy APP_PASSWORD, or your OFFCLOUD_API_KEY).
//   2. A key set from the sign-in page / Settings, stored in the database.
//      Database keys cannot be read from Edge middleware, so a successful login
//      issues an HMAC-signed session cookie that middleware CAN verify.
//
// Anything Node-only (reading the stored key, DEOVR ?token= checks) lives in
// auth-server.ts.

import { readEnv } from "./env";

export const FALLBACK_API_KEY = "vr-media-server";
export const AUTH_COOKIE = "vrms_auth";
/** Session lifetime in seconds (30 days). */
export const AUTH_MAX_AGE = 60 * 60 * 24 * 30;

const SESSION_PREFIX = "s1";
const SESSION_PREFIX_V2 = "s2";

// ---------------------------------------------------------------------------
// Environment keys
// ---------------------------------------------------------------------------

function clean(value: string | undefined): string | null {
  if (!value) return null;
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : null;
}

/** Every key accepted from the environment, in priority order. */
export function getValidApiKeys(): string[] {
  const keys: string[] = [];
  const push = (k: string | null) => {
    if (k && !keys.includes(k)) keys.push(k);
  };

  // Read through readEnv() so the values are resolved at RUNTIME. Direct
  // process.env.X access is inlined at build time in the middleware bundle,
  // where HF Space secrets do not exist yet.
  push(readEnv("APP_API_KEY"));
  push(readEnv("APP_PASSWORD")); // legacy name
  if (readEnv("ALLOW_OFFCLOUD_KEY_LOGIN") !== "false") {
    push(readEnv("OFFCLOUD_API_KEY"));
  }
  if (keys.length === 0) keys.push(FALLBACK_API_KEY);
  return keys;
}

/** The key shown in generated DEOVR URLs. */
export function getPrimaryApiKey(): string {
  return getValidApiKeys()[0];
}

/** True when no key was configured and the insecure default is in play. */
export function isUsingFallbackKey(): boolean {
  const keys = getValidApiKeys();
  return keys.length === 1 && keys[0] === FALLBACK_API_KEY;
}

function safeEqual(a: string, b: string): boolean {
  if (a.length !== b.length) return false;
  let diff = 0;
  for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
  return diff === 0;
}

/** Verify a candidate against the environment-configured keys only. */
export function verifyApiKey(candidate: string | null | undefined): boolean {
  if (!candidate) return false;
  return getValidApiKeys().some((k) => safeEqual(candidate, k));
}

// Legacy aliases kept so older imports keep compiling.
export const verifyPassword = verifyApiKey;
export const getAppPassword = getPrimaryApiKey;

export function maskApiKey(key: string): string {
  if (key.length <= 6) return "•".repeat(key.length);
  return `${key.slice(0, 3)}${"•".repeat(Math.min(10, key.length - 6))}${key.slice(-3)}`;
}

// ---------------------------------------------------------------------------
// Signed session tokens (verifiable in Edge middleware)
// ---------------------------------------------------------------------------

function sessionSecret(): string {
  return readEnv("AUTH_SECRET") ?? `vrms:${getPrimaryApiKey()}`;
}

/**

 * Where the session-signing secret comes from.

 *

 * "env"     - AUTH_SECRET is set, so every runtime signs identically.

 * "derived" - computed from the API key. That only stays consistent while

 *             every runtime can see the same key, which is why the

 *             entrypoint now generates and persists an AUTH_SECRET.

 */
export function authSecretSource(): "env" | "derived" {
  return readEnv("AUTH_SECRET") ? "env" : "derived";
}

/**

 * Short, non-reversible fingerprint of a key. Two runtimes reporting the

 * same fingerprint are provably using the same key; different fingerprints

 * mean one of them cannot see the secret.

 */
export async function keyFingerprint(key: string = getPrimaryApiKey()): Promise<string> {
  const data = new TextEncoder().encode(`vrms-fp:${key}`);
  const digest = await crypto.subtle.digest("SHA-256", data);
  return Array.from(new Uint8Array(digest))
    .slice(0, 4)
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");
}

async function hmacHex(message: string): Promise<string> {
  const enc = new TextEncoder();
  const key = await crypto.subtle.importKey(
    "raw",
    enc.encode(sessionSecret()),
    { name: "HMAC", hash: "SHA-256" },
    false,
    ["sign"]
  );
  const sig = await crypto.subtle.sign("HMAC", key, enc.encode(message));
  return Array.from(new Uint8Array(sig))
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");
}

/**

 * How far a session has got through sign-in.

 *

 *   "key"  - the API key was accepted. Enough for DEOVR / PLAY'A media URLs.

 *   "full" - the password step is also done (or no password is configured).

 *            Required for the web UI and the admin APIs.

 */
export type SessionLevel = "key" | "full";

/** Mint a session token at `level`, valid for `ttlSeconds`. */
export async function createSessionToken(

  level: SessionLevel = "full",

  ttlSeconds = AUTH_MAX_AGE

): Promise<string> {
  const expires = Math.floor(Date.now() / 1000) + ttlSeconds;
  const body = `${SESSION_PREFIX_V2}.${expires}.${level}`;
  return `${body}.${await hmacHex(body)}`;
}

/** Verify a session token and report the level it was issued at. */
export async function readSessionToken(

  token: string | null | undefined

): Promise<{ ok: boolean; level: SessionLevel | null }> {
  const deny = { ok: false, level: null } as const;
  if (!token) return deny;
  const parts = token.split(".");

  // Current format: s2.<expiry>.<level>.<signature>
  if (parts[0] === SESSION_PREFIX_V2 && parts.length === 4) {
    const [, expiresRaw, levelRaw, signature] = parts;
    if (levelRaw !== "key" && levelRaw !== "full") return deny;
    const expires = Number(expiresRaw);
    if (!Number.isFinite(expires) || expires * 1000 < Date.now()) return deny;
    const expected = await hmacHex(`${SESSION_PREFIX_V2}.${expiresRaw}.${levelRaw}`);
    if (!safeEqual(signature, expected)) return deny;
    return { ok: true, level: levelRaw };
  }

  // Legacy format: s1.<expiry>.<signature>. Treated as key-level, so a session
  // minted before the password existed cannot skip the password step.
  if (parts[0] === SESSION_PREFIX && parts.length === 3) {
    const [, expiresRaw, signature] = parts;
    const expires = Number(expiresRaw);
    if (!Number.isFinite(expires) || expires * 1000 < Date.now()) return deny;
    const expected = await hmacHex(`${SESSION_PREFIX}.${expiresRaw}`);
    if (!safeEqual(signature, expected)) return deny;
    return { ok: true, level: "key" };
  }

  return deny;
}

/** Signature/expiry only - ignores the level. */
export async function verifySessionToken(token: string | null | undefined): Promise<boolean> {
  return (await readSessionToken(token)).ok;
}

// ---------------------------------------------------------------------------
// Credential extraction
// ---------------------------------------------------------------------------

type HeaderBag = { get(name: string): string | null };
export type CredentialSource = { headers: HeaderBag; url?: string };

export function readKeyFromCookieHeader(header: string | null): string | null {
  if (!header) return null;
  const match = /(?:^|;\s*)vrms_auth=([^;]+)/.exec(header);
  if (!match) return null;
  try {
    return decodeURIComponent(match[1]);
  } catch {
    return match[1];
  }
}

/** Cookie value, ?token=, Authorization: Bearer, or X-API-Key. */
export function extractCredential(req: CredentialSource): string | null {
  const cookie = readKeyFromCookieHeader(req.headers.get("cookie"));
  if (cookie) return cookie;

  if (req.url) {
    try {
      const token = new URL(req.url).searchParams.get("token");
      if (token) return token;
    } catch {
      // Not an absolute URL — ignore.
    }
  }

  const authorization = req.headers.get("authorization");
  if (authorization?.toLowerCase().startsWith("bearer ")) {
    return authorization.slice(7).trim();
  }

  const headerKey = req.headers.get("x-api-key");
  if (headerKey) return headerKey.trim();

  return null;
}

export type AuthVerdict = {
  ok: boolean;
  via: "session" | "env-key" | null;
  credential: string | null;
  /** Session level, or "key" for a raw API key: a bare key never unlocks the UI. */
  level: SessionLevel | null;
};

/**

 * Edge-safe verification: a signed session cookie, or a raw environment key

 * passed as cookie/token/header. A key stored in the database can only be

 * verified by auth-server.ts.

 */
export async function verifyRequest(req: CredentialSource): Promise<AuthVerdict> {
  const credential = extractCredential(req);
  if (!credential) return { ok: false, via: null, credential: null, level: null };

  const session = await readSessionToken(credential);
  if (session.ok) {
    return { ok: true, via: "session", credential, level: session.level };
  }
  if (verifyApiKey(credential)) {
    // A raw key is machine-grade: good for media URLs, not for the web UI.
    return { ok: true, via: "env-key", credential, level: "key" };
  }
  return { ok: false, via: null, credential, level: null };
}

/** Convenience boolean form. */
export async function isAuthenticated(req: CredentialSource): Promise<boolean> {
  return (await verifyRequest(req)).ok;
}

export function addTokenToUrl(url: string, key = getPrimaryApiKey()): string {
  const separator = url.includes("?") ? "&" : "?";
  return `${url}${separator}token=${encodeURIComponent(key)}`;
}