normalize IPv4-mapped IPv6 addresses, for easier handling of rules

Massimo Melina committed Apr 25, 2022 at 19:09 UTC 98efa0bfb6292637ee7d47eb6d76578af8f4775e
2 files changed +6 -3
server/src/connections.ts
+4 -1
@@ -25,10 +25,13 @@ export class Connection {
25 }
26
27 get ip() {
28 - return this.ctx?.ip ?? (this._cachedIp = (this._cachedIp ?? this.socket.remoteAddress?.replace(/^::ffff:/,'')))
28 + return this.ctx?.ip ?? (this._cachedIp = (this._cachedIp ?? normalizeIp(this.socket.remoteAddress||'')))
29 }
30 }
31
32 +export function normalizeIp(ip: string) {
33 + return ip.replace(/^::ffff:/,'') // simplify ipv6-mapped addresses
34 +}
35
36 const all: Connection[] = []
37
server/src/middlewares.ts
+2 -2
@@ -15,7 +15,7 @@ import mount from 'koa-mount'
15 import { Readable } from 'stream'
16 import { applyBlock } from './block'
17 import { getAccount, getCurrentUsername } from './perm'
18 -import { socket2connection, updateConnection } from './connections'
18 +import { socket2connection, updateConnection, normalizeIp } from './connections'
19
20 export const gzipper = compress({
21 threshold: 2048,
@@ -92,7 +92,7 @@ export const serveGuiAndSharedFiles: Koa.Middleware = async (ctx, next) => {
92
93 let proxyDetected = false
94 export const someSecurity: Koa.Middleware = async (ctx, next) => {
95 - ctx.request.ip = ctx.ip.replace(/^::ffff:/,'') // simplify ipv6-mapped addresses
95 + ctx.request.ip = normalizeIp(ctx.ip)
96 try {
97 let proxy = ctx.get('X-Forwarded-For')
98 // we have some dev-proxies to ignore