File size: 9,043 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
// Node-side authentication: the database-stored access key plus route guards.
//
// The stored key lets someone sign in without touching Space Secrets, while the
// Space Secret keeps working for anyone who prefers it (and survives a DB
// reset). Either key is accepted everywhere.

import { NextResponse } from "next/server";
import { db } from "./db";
import {
  extractCredential,
  readSessionToken,
  verifyApiKey,
  maskApiKey,
  type CredentialSource,
  type SessionLevel,
} from "./auth";
import {
  DEFAULT_USERNAME,
  envLoginPassword,
  envUsername,
  hashPassword,
  normalizeUsername,
  safeEqualStrings,
  shouldResetStoredPassword,
  verifyPasswordAgainstHash,
} from "./password";

export const ACCESS_KEY_SETTING = "access_api_key";
/** Minimum length for a key set through the UI. */
export const MIN_KEY_LENGTH = 8;

/** Read the access key stored in the database, if any. */
export async function getStoredApiKey(): Promise<string | null> {
  try {
    const row = await db.setting.findUnique({ where: { key: ACCESS_KEY_SETTING } });
    const value = row?.value?.trim();
    if (!value || value === "***set***") return null;
    return value;
  } catch {
    return null;
  }
}

export async function setStoredApiKey(key: string): Promise<void> {
  const value = key.trim();
  await db.setting.upsert({
    where: { key: ACCESS_KEY_SETTING },
    create: { key: ACCESS_KEY_SETTING, value },
    update: { value },
  });
}

export async function clearStoredApiKey(): Promise<void> {
  await db.setting.deleteMany({ where: { key: ACCESS_KEY_SETTING } });
}

export async function describeStoredApiKey(): Promise<{ set: boolean; hint: string | null }> {
  const key = await getStoredApiKey();
  return { set: Boolean(key), hint: key ? maskApiKey(key) : null };
}

/** Accept an environment key OR the database-stored key. */
export async function verifyAnyKey(candidate: string | null | undefined): Promise<
  false | "env-key" | "stored-key"
> {
  if (!candidate) return false;
  if (verifyApiKey(candidate)) return "env-key";
  const stored = await getStoredApiKey();
  if (stored && stored.length === candidate.length && stored === candidate) {
    return "stored-key";
  }
  return false;
}

/**

 * Full credential check for Node route handlers: signed session cookie,

 * environment key, or database-stored key.

 */
export async function verifyRequestFull(req: CredentialSource): Promise<{
  ok: boolean;
  via: "session" | "env-key" | "stored-key" | null;
  level: SessionLevel | null;
}> {
  const credential = extractCredential(req);
  if (!credential) return { ok: false, via: null, level: null };

  const session = await readSessionToken(credential);
  if (session.ok) return { ok: true, via: "session", level: session.level };

  const keyMatch = await verifyAnyKey(credential);
  // A raw key (env or in-app) is machine-grade: media yes, web UI no.
  if (keyMatch) return { ok: true, via: keyMatch, level: "key" };

  return { ok: false, via: null, level: null };
}

/**

 * Guard for API routes that middleware forwards without verifying (DEOVR feed,

 * stream proxy, thumbnails — they may carry a database-stored key that Edge

 * middleware cannot check). Returns a 401 response, or null when allowed.

 */
export async function requireApiAuth(req: CredentialSource): Promise<NextResponse | null> {
  const verdict = await verifyRequestFull(req);
  if (verdict.ok) return null;
  return NextResponse.json(
    { error: "Unauthorized", hint: "Append ?token=<your API key> or sign in first" },
    { status: 401 }
  );
}

// ---------------------------------------------------------------------------
// The web UI account: username + password
//
// The API key is no longer a human credential. Once an account is configured
// the browser signs in with username + password, and the server reads the API
// key from the Space secret itself - only machines ever present it, as the
// ?token= on DEOVR / PLAY'A URLs.
// ---------------------------------------------------------------------------

export const LOGIN_PASSWORD_SETTING = "login_password_hash";
export const LOGIN_USERNAME_SETTING = "login_username";
export { MIN_PASSWORD_LENGTH, DEFAULT_USERNAME } from "./password";

/** The stored hash, or null. Honours RESET_LOGIN_PASSWORD by deleting it. */
export async function getStoredPasswordHash(): Promise<string | null> {
  try {
    if (shouldResetStoredPassword()) {
      await db.setting.deleteMany({
        where: { key: { in: [LOGIN_PASSWORD_SETTING, LOGIN_USERNAME_SETTING] } },
      });
      return null;
    }
    const row = await db.setting.findUnique({ where: { key: LOGIN_PASSWORD_SETTING } });
    const value = row?.value?.trim();
    return value && value.startsWith("pbkdf2$") ? value : null;
  } catch {
    return null;
  }
}

export async function getStoredUsername(): Promise<string | null> {
  try {
    const row = await db.setting.findUnique({ where: { key: LOGIN_USERNAME_SETTING } });
    const value = row?.value?.trim();
    return value ? value : null;
  } catch {
    return null;
  }
}

/** Space secret first, then the in-app value, then "admin". */
export async function getExpectedUsername(): Promise<string> {
  return envUsername() ?? (await getStoredUsername()) ?? DEFAULT_USERNAME;
}

export async function setLoginPassword(password: string): Promise<void> {
  const hash = await hashPassword(password);
  await db.setting.upsert({
    where: { key: LOGIN_PASSWORD_SETTING },
    create: { key: LOGIN_PASSWORD_SETTING, value: hash },
    update: { value: hash },
  });
}

export async function setLoginUsername(username: string): Promise<void> {
  const value = username.trim();
  if (!value) return;
  await db.setting.upsert({
    where: { key: LOGIN_USERNAME_SETTING },
    create: { key: LOGIN_USERNAME_SETTING, value },
    update: { value },
  });
}

/** Remove the in-app account entirely (username and password). */
export async function clearLoginAccount(): Promise<void> {
  await db.setting.deleteMany({
    where: { key: { in: [LOGIN_PASSWORD_SETTING, LOGIN_USERNAME_SETTING] } },
  });
}

/** Legacy name kept so older call sites keep working. */
export const clearLoginPassword = clearLoginAccount;

/** True when the browser must sign in with username + password. */
export async function areCredentialsConfigured(): Promise<boolean> {
  if (envLoginPassword()) return true;
  return (await getStoredPasswordHash()) !== null;
}

/** Legacy alias - the password is what switches the mode on. */
export const isLoginPasswordRequired = areCredentialsConfigured;

export type LoginAccount = {
  configured: boolean;
  username: string;
  usernameSource: "env" | "stored" | "default";
  passwordSource: "env" | "stored" | null;
  /** False while APP_LOGIN_PASSWORD is set: a Space secret always wins. */
  changeable: boolean;
};

export async function describeLoginAccount(): Promise<LoginAccount> {
  const envPassword = envLoginPassword();
  const storedHash = envPassword ? null : await getStoredPasswordHash();
  const envUser = envUsername();
  const storedUser = await getStoredUsername();

  return {
    configured: Boolean(envPassword) || storedHash !== null,
    username: envUser ?? storedUser ?? DEFAULT_USERNAME,
    usernameSource: envUser ? "env" : storedUser ? "stored" : "default",
    passwordSource: envPassword ? "env" : storedHash ? "stored" : null,
    changeable: !envPassword,
  };
}

/** Legacy shape, still used by the diagnostics rows. */
export async function describeLoginPassword(): Promise<{
  required: boolean;
  source: "env" | "stored" | null;
  changeable: boolean;
}> {
  const account = await describeLoginAccount();
  return {
    required: account.configured,
    source: account.passwordSource,
    changeable: account.changeable,
  };
}

/** Check a password against the Space secret, then the stored hash. */
export async function verifyLoginPassword(candidate: string): Promise<boolean> {
  const submitted = candidate.trim();
  if (!submitted) return false;

  const fromEnv = envLoginPassword();
  if (fromEnv && safeEqualStrings(submitted, fromEnv)) return true;

  const stored = await getStoredPasswordHash();
  if (stored) return verifyPasswordAgainstHash(submitted, stored);

  return false;
}

/** Check the username and password together. Both must match. */
export async function verifyLoginCredentials(

  username: string,

  password: string

): Promise<boolean> {
  const expected = normalizeUsername(await getExpectedUsername());
  const submitted = normalizeUsername(username ?? "");
  // Always run the password check too, so a wrong username is not measurably
  // faster to reject than a wrong password.
  const passwordOk = await verifyLoginPassword(password ?? "");
  return safeEqualStrings(submitted, expected) && passwordOk;
}