refactor(env): centralize auth env handling and prefer BETTER_AUTH_BASE_URL
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import { createHmac, timingSafeEqual } from 'crypto';
|
||||
import { getRequiredEnv } from './env';
|
||||
|
||||
type DeviceRole = 'camera' | 'client';
|
||||
|
||||
@@ -9,11 +10,7 @@ export type DeviceTokenPayload = {
|
||||
exp: number;
|
||||
};
|
||||
|
||||
const secret = process.env.BETTER_AUTH_SECRET;
|
||||
|
||||
if (!secret) {
|
||||
throw new Error('BETTER_AUTH_SECRET is required for device token signing');
|
||||
}
|
||||
const secret = getRequiredEnv('BETTER_AUTH_SECRET');
|
||||
|
||||
const base64UrlEncode = (input: string): string => Buffer.from(input, 'utf8').toString('base64url');
|
||||
const base64UrlDecode = (input: string): string => Buffer.from(input, 'base64url').toString('utf8');
|
||||
|
||||
34
Backend/utils/env.ts
Normal file
34
Backend/utils/env.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
const getEnvValue = (name: string): string | undefined => {
|
||||
const value = process.env[name];
|
||||
if (!value) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
};
|
||||
|
||||
export const getFirstDefinedEnv = (...names: string[]): string | undefined => {
|
||||
for (const name of names) {
|
||||
const value = getEnvValue(name);
|
||||
if (value) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
};
|
||||
|
||||
export const getRequiredEnv = (name: string): string => {
|
||||
const value = getEnvValue(name);
|
||||
|
||||
if (!value) {
|
||||
throw new Error(`${name} is required. Add it to your .env file.`);
|
||||
}
|
||||
|
||||
return value;
|
||||
};
|
||||
|
||||
export const getBetterAuthBaseUrl = (): string => {
|
||||
return getFirstDefinedEnv('BETTER_AUTH_BASE_URL', 'BETTER_AUTH_URL') ?? `http://localhost:${process.env.PORT ?? '3000'}`;
|
||||
};
|
||||
Reference in New Issue
Block a user