32 Commits
1.1.2 ... 1.2.0

Author SHA1 Message Date
William Oldham
26316c7755 Merge pull request #26 from movie-web/dev
Backend v1.2.0
2023-12-21 20:21:44 +00:00
mrjvs
d5851b522a Merge branch 'master' into dev 2023-12-21 21:19:26 +01:00
mrjvs
7145d6c246 Bump version 2023-12-21 21:17:32 +01:00
William Oldham
961ac7eeca Merge pull request #25 from movie-web/fix-stuff
Ratelimit fix & optimize metrics
2023-12-21 20:11:10 +00:00
mrjvs
59ab9b48bd Implement trusted cloudflare ips
Co-authored-by: William Oldham <github@binaryoverload.co.uk>
2023-12-21 20:38:51 +01:00
mrjvs
07ecd445f9 Add captcha solves metric 2023-12-21 20:11:17 +01:00
mrjvs
5ebecd1476 Remove provider metric table and replace prometheus metrics with something more efficient
Co-authored-by: William Oldham <github@binaryoverload.co.uk>
2023-12-21 20:01:27 +01:00
William Oldham
f4e9a96666 Merge pull request #24 from movie-web/dev
Update bugfix
2023-12-14 20:48:14 +00:00
William Oldham
60dda8ac57 Merge branch 'master' into dev 2023-12-14 20:48:04 +00:00
William Oldham
d84cdc4239 Merge pull request #23 from movie-web/fix-show-delete
Fix show deletion
2023-12-14 20:47:40 +00:00
mrjvs
c2cba27e68 remove unused import 2023-12-14 21:10:48 +01:00
mrjvs
c3259156ac bump version 2023-12-14 21:07:38 +01:00
mrjvs
9ef12d1c0f Delete all entries of a show 2023-12-14 21:07:24 +01:00
William Oldham
e173003f55 Merge pull request #22 from movie-web/dev
v1.1.5 - Progress importing now uses the user's date
2023-12-06 20:03:22 +00:00
William Oldham
9f90ba7da2 Merge pull request #21 from movie-web/progress-date
Add UpdatedAt from User date for Progress
2023-12-06 20:01:35 +00:00
William Oldham
05bf651939 Revert "Use date to compare progress items"
This reverts commit cf0125755c.
2023-12-06 19:59:50 +00:00
William Oldham
cf0125755c Use date to compare progress items 2023-12-06 19:55:09 +00:00
William Oldham
4129b80828 Use movie-web birthday 2023-12-06 19:49:30 +00:00
William Oldham
e5c3cde51b Only use user date on bulk import 2023-12-06 19:46:22 +00:00
William Oldham
4bf0285d06 Bump version 2023-12-06 19:43:57 +00:00
William Oldham
53d5ca1461 Add updatedAt saving into progress imports 2023-12-06 19:43:37 +00:00
mrjvs
3211f74387 Merge pull request #20 from movie-web/dev
V1.1.4
2023-11-25 17:21:20 +01:00
mrjvs
8cffd0e7e8 Merge branch 'master' into dev 2023-11-25 17:11:46 +01:00
mrjvs
c531329931 Merge pull request #19 from movie-web/device-name-fix
Remove duplicate session router
2023-11-25 17:09:20 +01:00
mrjvs
690357ba5a bump version 2023-11-25 16:09:55 +01:00
mrjvs
10e9e06c27 only have one session router 2023-11-25 16:09:29 +01:00
mrjvs
783d89492d Merge pull request #18 from movie-web/dev
Version 1.1.3: Add endpoint to edit device name
2023-11-24 20:07:57 +01:00
mrjvs
4663b2c1f7 Merge branch 'master' into dev 2023-11-24 20:06:42 +01:00
William Oldham
ceea274e70 Merge pull request #17 from movie-web/device-name-update
Device name update + fixing settings endpoint
2023-11-24 18:56:08 +00:00
William Oldham
6d2dcd04e9 Apply suggestions from code review 2023-11-24 18:55:20 +00:00
mrjvs
8a3c0d6edb add settings nullable + undefined difference 2023-11-24 18:40:54 +01:00
mrjvs
72657e73c8 add update session endpoint 2023-11-24 18:00:06 +01:00
21 changed files with 188 additions and 339 deletions

View File

@@ -12,6 +12,8 @@ services:
POSTGRES_PASSWORD: postgres
volumes:
- 'postgres_data:/var/lib/postgresql/data'
redis:
image: redis
# custom services
backend:

View File

@@ -1,6 +1,6 @@
{
"name": "backend",
"version": "1.1.2",
"version": "1.2.0",
"private": true,
"homepage": "https://github.com/movie-web/backend",
"engines": {

View File

@@ -4,4 +4,8 @@ export const dockerFragment: FragmentSchema = {
postgres: {
connection: 'postgres://postgres:postgres@postgres:5432/postgres',
},
ratelimits: {
enabled: true,
redisUrl: 'redis://redis:6379',
},
};

View File

@@ -1,6 +1,13 @@
import { devFragment } from '@/config/fragments/dev';
import { dockerFragment } from '@/config/fragments/docker';
import { createConfigLoader } from 'neat-config';
import { z } from 'zod';
const fragments = {
dev: devFragment,
dockerdev: dockerFragment,
};
export const ormConfigSchema = z.object({
postgres: z.object({
// connection URL for postgres database
@@ -15,6 +22,8 @@ export const ormConf = createConfigLoader()
prefix: 'MWB_',
})
.addFromFile('config.json')
.setFragmentKey('usePresets')
.addConfigFragments(fragments)
.addZodSchema(ormConfigSchema)
.freeze()
.load();

View File

@@ -16,6 +16,9 @@ export const configSchema = z.object({
// should it trust reverse proxy headers? (for ip gathering)
trustProxy: z.coerce.boolean().default(false),
// should it trust cloudflare headers? (for ip gathering, cloudflare has priority)
trustCloudflare: z.coerce.boolean().default(false),
// prefix for where the instance is run on. for example set it to /backend if you're hosting it on example.com/backend
// if this is set, do not apply url rewriting before proxing
basePath: z.string().default('/'),

View File

@@ -268,143 +268,6 @@
"checks": [],
"foreignKeys": {}
},
{
"columns": {
"id": {
"name": "id",
"type": "uuid",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "uuid"
},
"tmdb_id": {
"name": "tmdb_id",
"type": "varchar(255)",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "string"
},
"type": {
"name": "type",
"type": "varchar(255)",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "string"
},
"title": {
"name": "title",
"type": "varchar(255)",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "string"
},
"season_id": {
"name": "season_id",
"type": "varchar(255)",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "string"
},
"episode_id": {
"name": "episode_id",
"type": "varchar(255)",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "string"
},
"created_at": {
"name": "created_at",
"type": "timestamptz(0)",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"length": 0,
"mappedType": "datetime"
},
"status": {
"name": "status",
"type": "varchar(255)",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "string"
},
"provider_id": {
"name": "provider_id",
"type": "varchar(255)",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "string"
},
"embed_id": {
"name": "embed_id",
"type": "varchar(255)",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "string"
},
"error_message": {
"name": "error_message",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "text"
},
"full_error": {
"name": "full_error",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "text"
},
"hostname": {
"name": "hostname",
"type": "varchar(255)",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "string"
}
},
"name": "provider_metrics",
"schema": "public",
"indexes": [
{
"keyName": "provider_metrics_pkey",
"columnNames": [
"id"
],
"composite": false,
"primary": true,
"unique": true
}
],
"checks": [],
"foreignKeys": {}
},
{
"columns": {
"id": {

View File

@@ -0,0 +1,13 @@
import { Migration } from '@mikro-orm/migrations';
export class Migration20231221185725 extends Migration {
async up(): Promise<void> {
this.addSql('drop table if exists "provider_metrics" cascade;');
}
async down(): Promise<void> {
this.addSql('create table "provider_metrics" ("id" uuid not null default null, "tmdb_id" varchar not null default null, "type" varchar not null default null, "title" varchar not null default null, "season_id" varchar null default null, "episode_id" varchar null default null, "created_at" timestamptz not null default null, "status" varchar not null default null, "provider_id" varchar not null default null, "embed_id" varchar null default null, "error_message" text null default null, "full_error" text null default null, "hostname" varchar not null default null, constraint "provider_metrics_pkey" primary key ("id"));');
}
}

View File

@@ -1,51 +0,0 @@
import { Entity, PrimaryKey, Property } from '@mikro-orm/core';
import { randomUUID } from 'crypto';
export const status = {
failed: 'failed',
notfound: 'notfound',
success: 'success',
} as const;
type Status = keyof typeof status;
@Entity({ tableName: 'provider_metrics' })
export class ProviderMetric {
@PrimaryKey({ name: 'id', type: 'uuid' })
id: string = randomUUID();
@Property({ name: 'tmdb_id' })
tmdbId!: string;
@Property({ name: 'type' })
type!: string;
@Property({ name: 'title' })
title!: string;
@Property({ name: 'season_id', nullable: true })
seasonId?: string;
@Property({ name: 'episode_id', nullable: true })
episodeId?: string;
@Property({ name: 'created_at', type: 'date' })
createdAt = new Date();
@Property({ name: 'status' })
status!: Status;
@Property({ name: 'provider_id' })
providerId!: string;
@Property({ name: 'embed_id', nullable: true })
embedId?: string;
@Property({ name: 'error_message', nullable: true, type: 'text' })
errorMessage?: string;
@Property({ name: 'full_error', nullable: true, type: 'text' })
fullError?: string;
@Property({ name: 'hostname' })
hostname!: string;
}

View File

@@ -2,7 +2,7 @@ import { loginAuthRouter } from '@/routes/auth/login';
import { manageAuthRouter } from '@/routes/auth/manage';
import { metaRouter } from '@/routes/meta';
import { metricsRouter } from '@/routes/metrics';
import { sessionsRouter } from '@/routes/sessions';
import { sessionsRouter } from '@/routes/sessions/sessions';
import { userBookmarkRouter } from '@/routes/users/bookmark';
import { userDeleteRouter } from '@/routes/users/delete';
import { userEditRouter } from '@/routes/users/edit';

View File

@@ -1,11 +1,9 @@
import { challengeCodeJob } from '@/modules/jobs/list/challengeCode';
import { sessionExpiryJob } from '@/modules/jobs/list/sessionExpiry';
import { userDeletionJob } from '@/modules/jobs/list/userDeletion';
import { providerMetricCleanupJob } from '@/modules/jobs/list/providerMetricCleanup';
export async function setupJobs() {
challengeCodeJob.start();
sessionExpiryJob.start();
userDeletionJob.start();
providerMetricCleanupJob.start();
}

View File

@@ -1,27 +0,0 @@
import { ProviderMetric } from '@/db/models/ProviderMetrics';
import { job } from '@/modules/jobs/job';
import ms from 'ms';
// every day at 12:00:00
export const providerMetricCleanupJob = job(
'provider-metric-cleanup',
'0 12 * * *',
async ({ em, log }) => {
const now = new Date();
const thirtyDaysAgo = new Date(now.getTime() - ms('30d'));
const deletedMetrics = await em
.createQueryBuilder(ProviderMetric)
.delete()
.where({
createdAt: {
$lt: thirtyDaysAgo,
},
})
.execute<{ affectedRows: number }>('run');
log.info(
`Removed ${deletedMetrics.affectedRows} metrics that were older than 30 days`,
);
},
);

View File

@@ -9,17 +9,10 @@ const log = scopedLogger('metrics');
export type Metrics = {
user: Counter<'namespace'>;
providerMetrics: Counter<
| 'title'
| 'tmdb_id'
| 'season_id'
| 'episode_id'
| 'status'
| 'type'
| 'provider_id'
| 'embed_id'
| 'hostname'
>;
captchaSolves: Counter<'success'>;
providerHostnames: Counter<'hostname'>;
providerStatuses: Counter<'provider_id' | 'status'>;
watchMetrics: Counter<'title' | 'tmdb_full_id' | 'provider_id' | 'success'>;
};
let metrics: null | Metrics = null;
@@ -42,31 +35,38 @@ export async function setupMetrics(app: FastifyInstance) {
metrics = {
user: new Counter({
name: 'user_count',
help: 'user_help',
name: 'mw_user_count',
help: 'mw_user_help',
labelNames: ['namespace'],
}),
providerMetrics: new Counter({
name: 'provider_metrics',
help: 'provider_metrics',
labelNames: [
'episode_id',
'provider_id',
'season_id',
'status',
'title',
'tmdb_id',
'type',
'embed_id',
'hostname',
],
captchaSolves: new Counter({
name: 'mw_captcha_solves',
help: 'mw_captcha_solves',
labelNames: ['success'],
}),
providerHostnames: new Counter({
name: 'mw_provider_hostname_count',
help: 'mw_provider_hostname_count',
labelNames: ['hostname'],
}),
providerStatuses: new Counter({
name: 'mw_provider_status_count',
help: 'mw_provider_status_count',
labelNames: ['provider_id', 'status'],
}),
watchMetrics: new Counter({
name: 'mw_media_watch_count',
help: 'mw_media_watch_count',
labelNames: ['title', 'tmdb_full_id', 'provider_id', 'success'],
}),
};
const promClient = app.metrics.client;
promClient.register.registerMetric(metrics.user);
promClient.register.registerMetric(metrics.providerMetrics);
promClient.register.registerMetric(metrics.providerHostnames);
promClient.register.registerMetric(metrics.providerStatuses);
promClient.register.registerMetric(metrics.watchMetrics);
const orm = getORM();
const em = orm.em.fork();

View File

@@ -2,6 +2,7 @@ import Redis from 'ioredis';
import RateLimiter from 'async-ratelimiter';
import ms from 'ms';
import { StatusError } from '@/services/error';
import { IpReq, getIp } from '@/services/ip';
export interface LimiterOptions {
redis: Redis;
@@ -26,8 +27,8 @@ export class Limiter {
this.redis = ops.redis;
}
async bump(req: { ip: string }, ops: BucketOptions) {
const ip = req.ip;
async bump(req: IpReq, ops: BucketOptions) {
const ip = getIp(req);
if (!this.buckets[ops.id]) {
this.buckets[ops.id] = {
limiter: new RateLimiter({
@@ -54,7 +55,7 @@ export class Limiter {
};
}
async assertAndBump(req: { ip: string }, ops: BucketOptions) {
async assertAndBump(req: IpReq, ops: BucketOptions) {
const { hasBeenLimited } = await this.bump(req, ops);
if (hasBeenLimited) {
throw new StatusError('Ratelimited', 429);

View File

@@ -1,8 +1,8 @@
import { handle } from '@/services/handler';
import { makeRouter } from '@/services/router';
import { z } from 'zod';
import { ProviderMetric, status } from '@/db/models/ProviderMetrics';
import { getMetrics } from '@/modules/metrics';
import { status } from '@/routes/statuses';
const metricsProviderSchema = z.object({
tmdbId: z.string(),
@@ -29,7 +29,7 @@ export const metricsRouter = makeRouter((app) => {
body: metricsProviderInputSchema,
},
},
handle(async ({ em, body, req, limiter }) => {
handle(async ({ body, req, limiter }) => {
await limiter?.assertAndBump(req, {
id: 'provider_metrics',
max: 300,
@@ -37,43 +37,59 @@ export const metricsRouter = makeRouter((app) => {
window: '30m',
});
const hostname = req.headers.origin?.slice(0, 255) ?? 'unknown origin';
const entities = body.items.map((v) => {
const errorMessage = v.errorMessage?.slice(0, 200);
const truncatedFullError = v.fullError?.slice(0, 2000);
const metric = new ProviderMetric();
em.assign(metric, {
providerId: v.providerId,
embedId: v.embedId,
fullError: truncatedFullError,
errorMessage: errorMessage,
episodeId: v.episodeId,
seasonId: v.seasonId,
status: v.status,
title: v.title,
tmdbId: v.tmdbId,
type: v.type,
hostname,
});
return metric;
const hostname = req.headers.origin?.slice(0, 255) ?? '<UNKNOWN>';
getMetrics().providerHostnames.inc({
hostname,
});
entities.forEach((entity) => {
getMetrics().providerMetrics.inc({
episode_id: entity.episodeId,
provider_id: entity.providerId,
season_id: entity.seasonId,
status: entity.status,
title: entity.title,
tmdb_id: entity.tmdbId,
type: entity.type,
hostname,
body.items.forEach((item) => {
getMetrics().providerStatuses.inc({
provider_id: item.embedId ?? item.providerId,
status: item.status,
});
});
await em.persistAndFlush(entities);
const itemList = [...body.items];
itemList.reverse();
const lastSuccessfulItem = body.items.find(
(v) => v.status === status.success,
);
const lastItem = itemList[0];
if (lastItem) {
getMetrics().watchMetrics.inc({
tmdb_full_id: lastItem.type + '-' + lastItem.tmdbId,
provider_id: lastSuccessfulItem?.providerId ?? lastItem.providerId,
title: lastItem.title,
success: (!!lastSuccessfulItem).toString(),
});
}
return true;
}),
);
app.post(
'/metrics/captcha',
{
schema: {
body: z.object({
success: z.boolean(),
}),
},
},
handle(async ({ body, req, limiter }) => {
await limiter?.assertAndBump(req, {
id: 'captcha_solves',
max: 300,
inc: 1,
window: '30m',
});
getMetrics().captchaSolves.inc({
success: body.success.toString(),
});
return true;
}),
);

View File

@@ -1,35 +0,0 @@
import { Session } from '@/db/models/Session';
import { StatusError } from '@/services/error';
import { handle } from '@/services/handler';
import { makeRouter } from '@/services/router';
import { z } from 'zod';
export const sessionRouter = makeRouter((app) => {
app.delete(
'/sessions/:sid',
{
schema: {
params: z.object({
sid: z.string(),
}),
},
},
handle(async ({ auth, params, em }) => {
await auth.assert();
const targetedSession = await em.findOne(Session, { id: params.sid });
if (!targetedSession)
return {
id: params.sid,
};
if (targetedSession.user !== auth.user.id)
throw new StatusError('Cannot delete sessions you do not own', 401);
await em.removeAndFlush(targetedSession);
return {
id: params.sid,
};
}),
);
});

View File

@@ -13,7 +13,7 @@ export const sessionsRouter = makeRouter((app) => {
sid: z.string(),
}),
body: z.object({
name: z.string().max(500).min(1).optional(),
deviceName: z.string().max(500).min(1).optional(),
}),
},
},
@@ -25,10 +25,10 @@ export const sessionsRouter = makeRouter((app) => {
if (!targetedSession)
throw new StatusError('Session cannot be found', 404);
if (targetedSession.user !== auth.user.id)
throw new StatusError('Cannot modify sessions you do not own', 401);
if (targetedSession.id !== params.sid)
throw new StatusError('Cannot edit sessions other than your own', 401);
if (body.name) targetedSession.device = body.name;
if (body.deviceName) targetedSession.device = body.deviceName;
await em.persistAndFlush(targetedSession);

6
src/routes/statuses.ts Normal file
View File

@@ -0,0 +1,6 @@
export const status = {
failed: 'failed',
notfound: 'notfound',
success: 'success',
} as const;
export type Status = keyof typeof status;

View File

@@ -6,7 +6,6 @@ import {
import { StatusError } from '@/services/error';
import { handle } from '@/services/handler';
import { makeRouter } from '@/services/router';
import { randomUUID } from 'crypto';
import { z } from 'zod';
const bookmarkDataSchema = z.object({

View File

@@ -6,6 +6,7 @@ import {
import { StatusError } from '@/services/error';
import { handle } from '@/services/handler';
import { makeRouter } from '@/services/router';
import { FilterQuery } from '@mikro-orm/core';
import { randomUUID } from 'crypto';
import { z } from 'zod';
@@ -18,6 +19,7 @@ const progressItemSchema = z.object({
episodeId: z.string().optional(),
seasonNumber: z.number().optional(),
episodeNumber: z.number().optional(),
updatedAt: z.string().datetime({ offset: true }).optional(),
});
export const userProgressRouter = makeRouter((app) => {
@@ -100,7 +102,9 @@ export const userProgressRouter = makeRouter((app) => {
if (newItemIndex > -1) {
const newItem = newItems[newItemIndex];
if (existingItem.watched < newItem.watched) {
existingItem.updatedAt = new Date();
existingItem.updatedAt = defaultAndCoerceDateTime(
newItem.updatedAt,
);
existingItem.watched = newItem.watched;
}
itemsUpserted.push(existingItem);
@@ -123,7 +127,7 @@ export const userProgressRouter = makeRouter((app) => {
tmdbId: newItem.tmdbId,
userId: params.uid,
watched: newItem.watched,
updatedAt: new Date(),
updatedAt: defaultAndCoerceDateTime(newItem.updatedAt),
});
}
@@ -161,22 +165,28 @@ export const userProgressRouter = makeRouter((app) => {
if (auth.user.id !== params.uid)
throw new StatusError('Cannot modify user other than yourself', 403);
const progressItem = await em.findOne(ProgressItem, {
const query: FilterQuery<ProgressItem> = {
userId: params.uid,
tmdbId: params.tmdbid,
episodeId: body.episodeId,
seasonId: body.seasonId,
});
if (!progressItem) {
};
if (body.seasonId) query.seasonId = body.seasonId;
if (body.episodeId) query.episodeId = body.episodeId;
const progressItems = await em.find(ProgressItem, query);
if (progressItems.length === 0) {
return {
count: 0,
tmdbId: params.tmdbid,
episodeId: body.episodeId,
seasonId: body.seasonId,
};
}
await em.removeAndFlush(progressItem);
progressItems.forEach((v) => em.remove(v));
await em.flush();
return {
count: progressItems.length,
tmdbId: params.tmdbid,
episodeId: body.episodeId,
seasonId: body.seasonId,
@@ -207,3 +217,14 @@ export const userProgressRouter = makeRouter((app) => {
}),
);
});
// 13th July 2021 - movie-web epoch
const minEpoch = 1626134400000;
function defaultAndCoerceDateTime(dateTime: string | undefined) {
const epoch = dateTime ? new Date(dateTime).getTime() : Date.now();
const clampedEpoch = Math.max(minEpoch, Math.min(epoch, Date.now()));
return new Date(clampedEpoch);
}

View File

@@ -38,9 +38,9 @@ export const userSettingsRouter = makeRouter((app) => {
uid: z.string(),
}),
body: z.object({
applicationLanguage: z.string().optional(),
applicationTheme: z.string().optional(),
defaultSubtitleLanguage: z.string().optional(),
applicationLanguage: z.string().nullable().optional(),
applicationTheme: z.string().nullable().optional(),
defaultSubtitleLanguage: z.string().nullable().optional(),
}),
},
},
@@ -58,12 +58,12 @@ export const userSettingsRouter = makeRouter((app) => {
settings.id = params.uid;
}
if (body.applicationLanguage)
if (body.applicationLanguage !== undefined)
settings.applicationLanguage = body.applicationLanguage;
if (body.applicationTheme)
settings.applicationTheme = body.applicationTheme;
if (body.defaultSubtitleLanguage)
if (body.defaultSubtitleLanguage !== undefined)
settings.defaultSubtitleLanguage = body.defaultSubtitleLanguage;
if (body.applicationTheme !== undefined)
settings.applicationTheme = body.applicationTheme;
await em.persistAndFlush(settings);
return formatUserSettings(settings);

27
src/services/ip.ts Normal file
View File

@@ -0,0 +1,27 @@
import { conf } from '@/config';
import { IncomingHttpHeaders } from 'http';
export type IpReq = {
ip: string;
headers: IncomingHttpHeaders;
};
const trustCloudflare = conf.server.trustCloudflare;
function getSingleHeader(
headers: IncomingHttpHeaders,
key: string,
): string | undefined {
const header = headers[key];
if (Array.isArray(header)) return header[0];
return header;
}
export function getIp(req: IpReq) {
const cfIp = getSingleHeader(req.headers, 'cf-connecting-ip');
if (trustCloudflare && cfIp) {
return cfIp;
}
return req.ip;
}