Inital commit

This commit is contained in:
Terncode committed 2026-11-24 22:05:11 +01:00
commit a6af7dbfcb
114 files changed
+27520

No files matched your search

+166
View File
@@ -0,0 +1,166 @@
import type { Request } from "express";
import { getDatabase } from "./config";
import { AccessCode } from "./db/access-code";
import type { Repository } from "typeorm";
import { getClientIp } from "./utils";
export interface AccessCodeData {
code?: string;
data?: AccessCode | null;
error?: string;
useQuota: () => Promise<void>;
}
export class AccessManager {
private static accessCodesRepo: Repository<AccessCode>;
private static codeLocks = new Map<string, Promise<unknown>>();
static initialize() {
if (!this.accessCodesRepo) {
this.accessCodesRepo = getDatabase().getRepository(AccessCode);
setInterval(() => {
this.cleanup().catch(() => {});
}, 1000 * 60);
}
}
static extractReqCodes(req: Request): string[] {
return [req.query["access_code"], req.body.access_code].filter((e) => e);
}
static async extractCodes(req: Request): Promise<AccessCode[]> {
const accessCodes = this.extractReqCodes(req);
return Promise.all(
accessCodes.map((code) =>
this.accessCodesRepo.findOne({
where: {
accessCode: code,
},
}),
),
).then((e) => e.filter((a) => a) as AccessCode[]);
}
private static withCodeLock<T>(
code: string,
fn: () => Promise<T>,
): Promise<T> {
const prev = this.codeLocks.get(code) || Promise.resolve();
const next = prev.then(() => fn());
this.codeLocks.set(
code,
next.catch(() => {}),
);
return next;
}
static async processCode(req: Request) {
const accessCodes = await this.extractCodes(req);
const ip = getClientIp(req);
for (const accessCode of accessCodes) {
const fresh = await this.withCodeLock(accessCode.accessCode, async () => {
const loaded = await this.accessCodesRepo.findOne({
where: {
accessCode: accessCode.accessCode,
},
});
if (!loaded) {
throw new Error("Access code not found");
}
let update = false;
if (!loaded.activated) {
loaded.activated = new Date();
if (loaded.type === "both" || loaded.type === "time") {
loaded.expires = new Date(
loaded.activated.getTime() +
(loaded.expiresAfterActivation || 1) * 1000,
);
}
update = true;
}
if (loaded.expires != null && loaded.expires.getTime() <= Date.now()) {
throw new Error("Expired access code");
}
if (!loaded.ips.includes(ip)) {
if (loaded.ipLimit > loaded.ips.length) {
loaded.ips.push(ip);
update = true;
} else {
throw new Error("Exceeded IP limit");
}
}
if (loaded.type === "quota" || loaded.type === "both") {
const newQuota = (loaded.quota || 0) - 1;
if (newQuota < 0) {
throw new Error("Used maximum amount of quota");
}
}
if (update) {
await this.accessCodesRepo.save(loaded);
}
return loaded;
});
if (fresh) {
const code = fresh.accessCode;
let useQuota = () => Promise.resolve();
if (fresh.type === "quota" || fresh.type === "both") {
useQuota = () =>
this.withCodeLock(code, async () => {
const current = await this.accessCodesRepo.findOne({
where: {
accessCode: code,
},
});
if (!current) {
return;
}
if (current.type === "quota" || current.type === "both") {
const newQuota = (current.quota || 0) - 1;
if (newQuota < 0) {
throw new Error("Used maximum amount of quota");
}
current.quota = newQuota;
await this.accessCodesRepo.save(current);
}
});
}
return { accessCode: fresh, useQuota };
}
}
return null;
}
static async codeOrError(req: Request): Promise<AccessCodeData> {
try {
const data = await this.processCode(req);
const code = data?.accessCode && this.extractReqCodes(req)[0];
return {
data: data?.accessCode,
useQuota: data?.useQuota || (() => Promise.resolve()),
code,
};
} catch (error) {
const code = this.extractReqCodes(req)[0];
return {
error: (error as Error).message,
code,
useQuota: () => Promise.resolve(),
};
}
}
private static async cleanup() {
await this.accessCodesRepo
.createQueryBuilder()
.delete()
.where("expires < :now", { now: new Date() })
.orWhere("quota = 0")
.execute();
}
}
+23
View File
@@ -0,0 +1,23 @@
import { encode, getBrowserVars, getFingerprintData } from "../utils";
async function main() {
const id = new URLSearchParams(location.search).get("t");
const pathname = location.pathname.endsWith("/")
? location.pathname
: `${location.pathname}/`;
try {
[...document.getElementsByTagName("script")].forEach(
(e) => e.parentElement && e.parentElement.removeChild(e),
);
} catch (_) {
console.log(_);
}
const fingerprint = await getFingerprintData();
const body = encode({ ...getBrowserVars(), fingerprint }, pathname);
fetch(`/t/${id}${pathname}${location.search}`, {
method: "POST",
headers: { "content-type": "text/plain" },
body,
});
}
main();
+52
View File
@@ -0,0 +1,52 @@
// Gallery video hover/loop behaviour for grid thumbnails and full-size players.
document.addEventListener("DOMContentLoaded", () => {
// Hover play for grid videos.
const gridVideos = document.querySelectorAll<HTMLVideoElement>(".grid-video");
gridVideos.forEach((video) => {
let hoverTimeout: number | undefined;
video.addEventListener("mouseenter", () => {
hoverTimeout = window.setTimeout(() => {
video.play().catch(() => {
// Ignore play errors (e.g. user interaction required).
});
}, 150);
});
video.addEventListener("mouseleave", () => {
window.clearTimeout(hoverTimeout);
video.pause();
video.currentTime = 0;
});
});
// Video loop logic for the full video player.
const fullVideos = document.querySelectorAll<HTMLVideoElement>(".full-video");
fullVideos.forEach((video) => {
const shouldLoop = video.dataset.loop === "true";
const duration = parseFloat(video.dataset.duration || "0") || 0;
if (shouldLoop) {
video.loop = true;
}
video.addEventListener("ended", () => {
if (!shouldLoop && duration >= 30) {
// Video longer than 30s - don't loop, show controls.
video.controls = true;
}
});
// Ensure the loop attribute matches the actual duration.
video.addEventListener("loadedmetadata", () => {
const actualDuration = video.duration;
if (actualDuration < 30) {
video.loop = true;
} else {
video.loop = false;
}
});
});
});
+112
View File
@@ -0,0 +1,112 @@
import { AnimationLoop } from "../screensaver/animation-loop";
import { Bouncer } from "../screensaver/bouncer";
async function load() {
const curtain = document.createElement("div");
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d")!;
const img = new Image();
await new Promise<void>((r) => {
img.addEventListener("load", () => {
ctx.drawImage(img, 0, 0);
r();
});
img.src = "/assets/images/avatar.webp";
});
const ratio = img.height / img.width;
const w = 100;
const h = w * ratio;
curtain.style.backgroundColor = "rgba(0, 0, 0, 0.75)";
curtain.style.width = "100%";
curtain.style.height = "100%";
curtain.style.position = "fixed";
curtain.style.top = "0px";
curtain.style.left = "0px";
canvas.style.position = "fixed";
canvas.style.borderRadius = "5px";
canvas.style.padding = "5px";
canvas.style.color = "white";
canvas.style.left = `${w}px`;
canvas.style.top = `${h}px`;
canvas.style.zIndex = "50";
canvas.width = w;
canvas.height = h;
ctx.drawImage(img, 0, 0, w, h);
//element.style.fontSize = '50px';
const bouncer = new Bouncer(canvas);
const loop = new AnimationLoop(bouncer.draw);
const TIMEOUT = 1000 * 60;
let frame: number | undefined = undefined;
const start = () => {
document.body.append(canvas);
document.body.append(curtain);
loop.start();
};
const stop = () => {
if (canvas.parentElement) {
canvas.parentElement.removeChild(canvas);
}
if (curtain.parentElement) {
curtain.parentElement.removeChild(curtain);
}
loop.stop();
};
const createTrigger = () => {
if (frame) {
clearTimeout(frame);
}
frame = window.setTimeout(() => {
start();
}, TIMEOUT);
};
const onActivity = () => {
if (loop.active) {
stop();
} else {
createTrigger();
}
};
window.addEventListener("pointermove", onActivity);
window.addEventListener("keydown", onActivity);
window.addEventListener("resize", onActivity);
createTrigger();
bouncer.onChange = () => {
ctx.clearRect(0, 0, w, h);
ctx.drawImage(img, 0, 0, w, h);
const ar = Math.round(Math.random() * 150);
const ag = Math.round(Math.random() * 150);
const ab = Math.round(Math.random() * 150);
const imageData = ctx.getImageData(0, 0, w, h);
for (let i = 0; i < imageData.data.length / 2; i += 4) {
const red = imageData.data[i + 0];
const green = imageData.data[i + 1];
const blue = imageData.data[i + 2];
//const alpha = imageData.data[i + 3];
if (red > 210 && green > 210 && blue > 210) {
imageData.data[i + 0] = Math.abs((imageData.data[i + 0] - ar) % 255);
imageData.data[i + 1] = Math.abs((imageData.data[i + 1] - ag) % 255);
imageData.data[i + 2] = Math.abs((imageData.data[i + 2] - ab) % 255);
}
}
ctx.clearRect(0, 0, w, h);
ctx.putImageData(imageData, 0, 0);
// const items = ['yellow', 'blue', 'red', 'green'].filter(e => e !== canvas.style.color);
// const item = items[Math.floor(Math.random() * items.length)];
// canvas.style.color = item;
// console.log(item);
};
}
load();
+185
View File
@@ -0,0 +1,185 @@
interface Snowflake {
xx: number;
x: number;
c: boolean;
allowCollision: boolean;
y: number;
v: number;
t: number;
size: number;
}
(() => {
const canvas = document.createElement("canvas");
document.body.appendChild(canvas);
const ctx = canvas.getContext("2d");
if (!ctx) {
canvas.remove();
return;
}
const style = canvas.style;
style.zIndex = "10000";
style.position = "fixed";
style.left = "0px";
style.top = "0px";
style.pointerEvents = "none";
style.touchAction = "none";
const MAX_SNOW = 6000;
let buffer = new Uint8Array(canvas.width * canvas.height);
const snowflakes: Snowflake[] = [];
const getIndex = (x: number, y: number) =>
Math.round(y) * canvas.width + Math.round(x);
const regGenBuff = () => {
buffer = new Uint8Array(canvas.width * canvas.height);
const elements = ["button", "a", "img", "video"];
const objects = elements
.map((e) => [
...document.getElementsByTagName(e),
...document.getElementsByClassName("badge"),
])
.flat();
for (let i = 0; i < objects.length; i++) {
const object = objects[i];
const rect = object.getBoundingClientRect();
for (let x = rect.left; x < rect.right; x++) {
for (let y = rect.top; y < rect.bottom; y++) {
const index = getIndex(x, y);
buffer[index] = 1;
}
}
}
};
let updateTimeout: number | undefined;
const updateOnChange = () => {
window.clearTimeout(updateTimeout);
updateTimeout = window.setTimeout(() => {
regGenBuff();
for (let i = 0; i < snowflakes.length; i++) {
snowflakes[i].c = false;
}
}, 500);
};
const resize = () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
updateOnChange();
};
const random = (min: number, max: number) =>
Math.random() * (max - min) + min;
const hasVerticalScrollbar = (element: Element) =>
element.scrollHeight > element.clientHeight;
const checkForUpdate = (parent: Element | null) => {
let current = parent;
while (current) {
if (hasVerticalScrollbar(current)) {
updateOnChange();
return;
}
if (!current.parentElement) {
return;
}
current = current.parentElement;
}
};
document.addEventListener("wheel", (event) => {
if (event.target instanceof Element) {
checkForUpdate(event.target);
}
});
window.addEventListener("touchmove", (event) => {
if (event.target instanceof Element) {
checkForUpdate(event.target);
}
});
let last = performance.now();
const draw = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
const now = performance.now();
const delta = now - last;
last = now;
const d = delta / 100;
if (snowflakes.length < MAX_SNOW) {
const x = random(-50, canvas.width + 50);
const snowflake: Snowflake = {
xx: x,
x,
c: false,
allowCollision: !!Math.round(random(0, 5)),
y: 0,
v: random(0.2, 2),
t: random(0, 0.5),
size: random(0, 2),
};
snowflakes.push(snowflake);
}
for (const snowflake of snowflakes) {
ctx.beginPath();
ctx.fillStyle = "#ffffff";
ctx.arc(snowflake.x, snowflake.y, snowflake.size, 0, 2 * Math.PI);
ctx.fill();
if (snowflake.c) {
continue;
}
const y = snowflake.y;
snowflake.y += d + snowflake.v;
snowflake.t += delta * snowflake.v * 0.001;
snowflake.x = snowflake.xx + Math.sin(snowflake.t) * 10;
if (snowflake.y > canvas.height - snowflake.size) {
if (snowflake.y > canvas.height + snowflake.size) {
snowflake.y = -(snowflake.size * 2);
snowflake.xx = random(0, canvas.width);
snowflake.c = false;
}
continue;
}
const halfSize = snowflake.size / 4;
const index = getIndex(snowflake.x, snowflake.y + halfSize);
const index2 = getIndex(snowflake.x, y + halfSize);
if (
snowflake.allowCollision &&
buffer[index2] === 0 &&
buffer[index] !== buffer[index2] &&
!!Math.floor(random(0, 10))
) {
const size = snowflake.size * 2;
const half = size / 2;
for (let xx = 0; xx < size; xx++) {
for (let yy = 0; yy < size; yy++) {
const cellIndex = getIndex(
snowflake.x + xx - half,
snowflake.y + yy - half,
);
if (!buffer[cellIndex]) {
buffer[cellIndex] = 2;
}
}
}
snowflake.c = true;
}
}
requestAnimationFrame(draw);
};
window.addEventListener("resize", resize);
resize();
draw();
})();
+30
View File
@@ -0,0 +1,30 @@
export class AnimationLoop {
private frame? = 0;
private last = 0;
constructor(private animationFrame: (delta: number) => void) {}
start() {
if (!this.frame) {
this.last = performance.now();
this.frame = requestAnimationFrame(this.draw);
}
}
stop() {
if (this.frame) {
cancelAnimationFrame(this.frame);
this.frame = undefined;
}
}
get active() {
return !!this.frame;
}
private draw = () => {
const now = performance.now();
const delta = now - this.last;
this.last = now;
this.animationFrame(delta);
this.frame = requestAnimationFrame(this.draw);
};
}
+63
View File
@@ -0,0 +1,63 @@
export class Bouncer {
private velocityX = 0.25;
private velocityY = 0.25;
private x = 0;
private y = 0;
private speed = 2;
constructor(private element: HTMLElement) {
this.setElement(element);
}
setElement(element: HTMLElement) {
this.element = element;
}
draw = (delta: number) => {
this.appendIfDoseNotExist();
this.applyStyle();
const { width, height } = this.element.getBoundingClientRect();
this.x += this.velocityX * delta;
this.y += this.velocityY * delta;
if (this.x < 0) {
this.x = 0;
this.velocityX *= -1;
this.onChange();
} else if (this.x + width > window.innerWidth) {
this.x = window.innerWidth - width;
this.velocityX *= -1;
this.onChange();
}
if (this.y < 0) {
this.y = 0;
this.velocityY *= -1;
this.onChange();
} else if (this.y + height > window.innerHeight) {
this.y = window.innerHeight - height;
this.velocityY *= -1;
this.onChange();
}
this.element.style.left = `${this.x}px`;
this.element.style.top = `${this.y}px`;
};
onChange() {}
private appendIfDoseNotExist() {
if (!document.body.contains(this.element)) {
document.body.append(this.element);
}
}
private applyStyle() {
const style = this.element.style;
style.position = "fixed";
style.zIndex = `${Number.MAX_SAFE_INTEGER}px`;
}
// private set x(value: number) {
// this.element.style.left = `${value}px`;
// }
// private set y(value: number) {
// this.element.style.top = `${value}px`;
// }
}
+45
View File
@@ -0,0 +1,45 @@
export function stringify(object: any): string {
try {
switch (typeof object) {
case "string": {
return `<STRING "${object}">`;
}
case "boolean": {
return `<BOOLEAN "${object ? "TRUE" : "FALSE"}">`;
}
case "number": {
return `<NUMBER ${object}>`;
}
case "symbol": {
try {
const description = new String(object.description);
return `<SYMBOL ${description ? description : new String(object.valueOf())}>`;
} catch {
return `<SYMBOL UNKNOWN>`;
}
}
case "function": {
return `<FUNCTION ${object.name ? object.name : "antonymous"}>`;
}
case "undefined": {
return `<UNDEFINED>`;
}
case "object": {
if (object === null) {
return `<NULL>`;
}
if (Array.isArray(object)) {
return `<ARRAY ${object.map((e) => stringify(e)).join(":")}>`;
}
console.log(Object.entries(object));
return `<OBJECT ${Object.entries(object).map((e) => `${e[0]}|${stringify(e[1])}`)}>`;
}
default: {
return "<UNKNOWN>";
}
}
} catch (error) {
console.log(error);
return "<ERROR>";
}
}
+663
View File
@@ -0,0 +1,663 @@
function getVideoCardInfo() {
const gl = document.createElement("canvas").getContext("webgl");
if (!gl) {
return {
error: "no webgl",
};
}
const debugInfo = gl.getExtension("WEBGL_debug_renderer_info");
return debugInfo
? {
vendor: gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL),
renderer: gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL),
}
: {
error: "no WEBGL_debug_renderer_info",
};
}
type PluginMimeTypeData = {
type: string;
suffixes: string;
};
type PluginData = {
name: string;
description: string;
mimeTypes: PluginMimeTypeData[];
};
export default function getPlugins(): PluginData[] | undefined {
try {
const rawPlugins = navigator.plugins;
if (!rawPlugins) {
return undefined;
}
const plugins: PluginData[] = [];
// Safari 10 doesn't support iterating navigator.plugins with for...of
for (let i = 0; i < rawPlugins.length; ++i) {
const plugin = rawPlugins[i];
if (!plugin) {
continue;
}
const mimeTypes: PluginMimeTypeData[] = [];
for (let j = 0; j < plugin.length; ++j) {
const mimeType = plugin[j];
mimeTypes.push({
type: mimeType.type,
suffixes: mimeType.suffixes,
});
}
plugins.push({
name: plugin.name,
description: plugin.description,
mimeTypes,
});
}
return plugins;
} catch (_) {
/* ignore */
}
return undefined;
}
export function getTimezone(): string {
const DateTimeFormat = window.Intl?.DateTimeFormat;
if (DateTimeFormat) {
const timezone = new DateTimeFormat().resolvedOptions().timeZone;
if (timezone) {
return timezone;
}
}
// For browsers that don't support timezone names
// The minus is intentional because the JS offset is opposite to the real offset
const offset = -getTimezoneOffset();
return `UTC${offset >= 0 ? "+" : ""}${Math.abs(offset)}`;
}
export function getBrowserVars() {
return {
navigator: {
canShare: navigator.canShare,
userAgent: navigator.userAgent,
languages: navigator.languages,
language: navigator.language,
vendor: navigator.vendor,
webdriver: navigator.webdriver,
appCodeName: navigator.appCodeName,
appName: navigator.appName,
appVersion: navigator.appVersion,
javaEnabled: navigator.javaEnabled,
platform: navigator.platform,
plugins: getPlugins(),
oscpu: (navigator as any).oscpu,
hardwareConcurrency: navigator.hardwareConcurrency,
vendorSub: navigator.vendorSub,
productSub: navigator.productSub,
},
timezone: getTimezone(),
screen: {
availHeight: screen.availHeight,
availWidth: screen.availWidth,
colorDepth: screen.colorDepth,
height: screen.height,
width: screen.width,
orientation: screen.orientation,
pixelDepth: screen.pixelDepth,
},
time: new Date().toLocaleString(),
ISO: new Date().toISOString(),
UTC: new Date().toUTCString(),
videoCard: getVideoCardInfo(),
};
}
// ---------- deep fingerprinting ----------
// deterministic 32-bit FNV-1a string hash (stable across visits)
function fnv1a(str: string, seed = 0x811c9dc5): string {
let h = seed >>> 0;
for (let i = 0; i < str.length; i++) {
h ^= str.charCodeAt(i);
h = Math.imul(h, 0x01000193) >>> 0;
}
return h.toString(16).padStart(8, "0");
}
// 64-bit-ish stable id from two independent 32-bit hashes
function fingerprintOf(str: string): string {
return fnv1a(str, 0x811c9dc5) + fnv1a(str, 0xabcdef01);
}
function canvasHash(): string | null {
try {
const canvas = document.createElement("canvas");
canvas.width = 320;
canvas.height = 160;
const ctx = canvas.getContext("2d");
if (!ctx) {
return null;
}
ctx.textBaseline = "alphabetic";
ctx.fillStyle = "#f60";
ctx.font = "14px 'Arial'";
ctx.fillRect(20, 30, 140, 40);
ctx.fillStyle = "#069";
ctx.fillRect(20, 30, 70, 20);
ctx.fillStyle = "#f60";
// unicode + emoji to pick up font-rendering differences
ctx.fillText("Cwm fjordbank glyphs vext quiz 😀🍕", 20, 45);
ctx.fillStyle = "rgba(102, 204, 0, 0.7)";
ctx.font = "18px 'Courier New'";
ctx.fillText("Cwm fjordbank glyphs vext quiz 😀", 30, 80);
// blend two circles (differs between canvas engines/drivers)
ctx.globalCompositeOperation = "multiply";
ctx.fillStyle = "rgb(255,0,255)";
ctx.beginPath();
ctx.arc(160, 110, 42, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = "rgb(0,255,255)";
ctx.beginPath();
ctx.arc(200, 110, 42, 0, Math.PI * 2);
ctx.fill();
return fingerprintOf(canvas.toDataURL());
} catch (_) {
return null;
}
}
function webglSceneHash(
gl: WebGLRenderingContext | WebGL2RenderingContext,
): string | null {
try {
if (!(gl as any).createShader) {
return null;
}
const w = 32,
h = 32;
const vs =
"attribute vec2 p; varying vec2 v; void main(){ v=p; gl_Position=vec4(p,0.,1.); }";
const fs =
"precision mediump float; varying vec2 v; void main(){ " +
"gl_FragColor=vec4(v, sin(v.x*40.0)*0.5+0.5, " +
"cos(v.y*40.0)*0.5+0.5, 1.0); }";
const shader = (type: number, src: string) => {
const s = gl.createShader(type)!;
gl.shaderSource(s, src);
gl.compileShader(s);
return s;
};
const prog = gl.createProgram()!;
gl.attachShader(prog, shader(gl.VERTEX_SHADER, vs));
gl.attachShader(prog, shader(gl.FRAGMENT_SHADER, fs));
gl.linkProgram(prog);
gl.useProgram(prog);
const buf = gl.createBuffer()!;
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]),
gl.STATIC_DRAW,
);
const loc = gl.getAttribLocation(prog, "p");
gl.enableVertexAttribArray(loc);
gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
gl.viewport(0, 0, w, h);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
const px = new Uint8Array(w * h * 4);
gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, px);
let s = "";
for (let i = 0; i < px.length; i++) {
s += String.fromCharCode(px[i]);
}
return fingerprintOf(s);
} catch (_) {
return null;
}
}
function webglInfo(): any {
const out: any = { webgl: null, webgl2: null, scene: null };
try {
const canvas = document.createElement("canvas");
const gl = (canvas.getContext("webgl") ||
canvas.getContext("experimental-webgl")) as WebGLRenderingContext | null;
if (gl) {
const dbg = gl.getExtension("WEBGL_debug_renderer_info");
out.webgl = {
vendor: dbg ? gl.getParameter(dbg.UNMASKED_VENDOR_WEBGL) : null,
renderer: dbg ? gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL) : null,
version: gl.getParameter(gl.VERSION),
shadingLanguageVersion: gl.getParameter(gl.SHADING_LANGUAGE_VERSION),
maxTextureSize: gl.getParameter(gl.MAX_TEXTURE_SIZE),
maxRenderbufferSize: gl.getParameter(gl.MAX_RENDERBUFFER_SIZE),
maxVaryingVectors: gl.getParameter(gl.MAX_VARYING_VECTORS),
maxVertexAttribs: gl.getParameter(gl.MAX_VERTEX_ATTRIBS),
maxVertexUniformVectors: gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS),
maxFragmentUniformVectors: gl.getParameter(
gl.MAX_FRAGMENT_UNIFORM_VECTORS,
),
maxViewportDims: gl.getParameter(gl.MAX_VIEWPORT_DIMS),
aliasedLineWidthRange: gl.getParameter(gl.ALIASED_LINE_WIDTH_RANGE),
aliasedPointSizeRange: gl.getParameter(gl.ALIASED_POINT_SIZE_RANGE),
extensions: (gl.getSupportedExtensions() || []).slice().sort(),
};
out.scene = webglSceneHash(gl);
const lose = gl.getExtension("WEBGL_lose_context");
if (lose) {
lose.loseContext();
}
}
} catch (_) {
/* ignore */
}
try {
const canvas = document.createElement("canvas");
const gl2 = canvas.getContext("webgl2") as WebGL2RenderingContext | null;
if (gl2) {
out.webgl2 = {
version: gl2.getParameter(gl2.VERSION),
maxTextureSize: gl2.getParameter(gl2.MAX_TEXTURE_SIZE),
maxSamples: gl2.getParameter(gl2.MAX_SAMPLES),
extensions: (gl2.getSupportedExtensions() || []).slice().sort(),
};
if (!out.scene) {
out.scene = webglSceneHash(gl2);
}
const lose = gl2.getExtension("WEBGL_lose_context");
if (lose) {
lose.loseContext();
}
}
} catch (_) {
/* ignore */
}
return out;
}
function audioHash(): Promise<string | null> {
return new Promise((resolve) => {
try {
const Ctx =
(window as any).OfflineAudioContext ||
(window as any).webkitOfflineAudioContext;
if (!Ctx) {
resolve(null);
return;
}
const ctx = new Ctx(1, 44100, 44100) as OfflineAudioContext;
const osc = ctx.createOscillator();
const filter = ctx.createBiquadFilter();
const gain = ctx.createGain();
osc.type = "triangle";
osc.frequency.value = 10000;
filter.type = "lowpass";
filter.frequency.value = 1000;
gain.gain.value = 1;
osc.connect(filter);
filter.connect(gain);
gain.connect(ctx.destination);
osc.start(0);
ctx.startRendering();
ctx.oncomplete = (e) => {
const data = e.renderedBuffer.getChannelData(0);
const samples: number[] = [];
for (let i = 0; i < data.length; i += 5) {
// quantize to reduce sample-to-sample noise
samples.push(Math.abs(Math.round(data[i] * 1000)) % 100);
}
resolve(fingerprintOf(samples.join(",")));
};
} catch (_) {
resolve(null);
}
});
}
const FONT_LIST = [
"Arial",
"Arial Black",
"Arial Narrow",
"Bahnschrift",
"Calibri",
"Cambria",
"Cambria Math",
"Candara",
"Comic Sans MS",
"Consolas",
"Constantia",
"Corbel",
"Courier New",
"Cursive",
"DejaVu Sans",
"Droid Sans",
"Ebrima",
"Franklin Gothic Medium",
"Futura",
"Georgia",
"Helvetica",
"Impact",
"Lato",
"Lucida Console",
"Lucida Grande",
"Lucida Sans Unicode",
"Marlett",
"Menlo",
"Microsoft JhengHei",
"Microsoft YaHei",
"Microsoft Sans Serif",
"Monaco",
"Monospace",
"Montserrat",
"MS Gothic",
"MS PGothic",
"Nirmala UI",
"Noto Sans",
"Noto Sans Mono",
"Open Sans",
"Palatino",
"Palatino Linotype",
"Roboto",
"Rockwell",
"Sans-serif",
"Segoe Print",
"Segoe Script",
"Segoe UI",
"Segoe UI Light",
"Segoe UI Semibold",
"Serif",
"Showcard",
"SimSun",
"Sitka",
"Tahoma",
"Terminal",
"Times New Roman",
"Trebuchet MS",
"Verdana",
"Wingdings",
];
function detectFonts(): string[] {
try {
const canvas = document.createElement("canvas");
canvas.width = 600;
canvas.height = 60;
const ctx = canvas.getContext("2d");
if (!ctx) {
return [];
}
const probe = "mmmmmmmmmmlli-+-+-+-+-+_";
ctx.font = "20px monospace";
const baseline = ctx.measureText(probe).width;
const found: string[] = [];
for (let i = 0; i < FONT_LIST.length; i++) {
const font = FONT_LIST[i];
ctx.font = `20px "${font}", monospace`;
try {
if (Math.abs(ctx.measureText(probe).width - baseline) > 0.01) {
found.push(font);
}
} catch (_) {
/* ignore */
}
}
return found;
} catch (_) {
return [];
}
}
function localIPs(): Promise<string[]> {
return new Promise((resolve) => {
try {
const RTC =
(window as any).RTCPeerConnection ||
(window as any).webkitRTCPeerConnection;
if (!RTC) {
resolve([]);
return;
}
const pc = new RTC({ iceServers: [] });
const ips = new Set<string>();
let settled = false;
const done = () => {
if (settled) {
return;
}
settled = true;
try {
pc.close();
} catch (_) {
/* ignore */
}
resolve(Array.from(ips));
};
pc.onicecandidate = (e: any) => {
if (!e.candidate) {
done();
return;
}
const m = /([0-9]{1,3}(\.[0-9]{1,3}){3})/.exec(
e.candidate.candidate || "",
);
if (m) {
ips.add(m[1]);
}
};
try {
pc.createDataChannel("");
} catch (_) {
/* ignore */
}
pc.createOffer()
.then((o: any) => pc.setLocalDescription(o))
.catch(() => {});
setTimeout(done, 1800);
} catch (_) {
resolve([]);
}
});
}
function mediaDevicesInfo(): Promise<any> {
return new Promise((resolve) => {
try {
if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
resolve(null);
return;
}
navigator.mediaDevices
.enumerateDevices()
.then((devs) => {
const out: any = {
total: devs.length,
videoinput: 0,
audioinput: 0,
audiooutput: 0,
};
for (const d of devs) {
if (d.kind === "videoinput") {
out.videoinput++;
} else if (d.kind === "audioinput") {
out.audioinput++;
} else if (d.kind === "audiooutput") {
out.audiooutput++;
}
}
resolve(out);
})
.catch(() => resolve(null));
} catch (_) {
resolve(null);
}
});
}
function storageChecks(): any {
const out: any = {
cookieEnabled: navigator.cookieEnabled,
localStorage: false,
sessionStorage: false,
indexedDB: false,
};
try {
window.localStorage.setItem("__fp", "1");
window.localStorage.removeItem("__fp");
out.localStorage = true;
} catch (_) {
/* ignore */
}
try {
window.sessionStorage.setItem("__fp", "1");
window.sessionStorage.removeItem("__fp");
out.sessionStorage = true;
} catch (_) {
/* ignore */
}
try {
out.indexedDB = !!window.indexedDB;
} catch (_) {
/* ignore */
}
return out;
}
function batteryInfo(): Promise<any> {
return new Promise((resolve) => {
try {
if (!(navigator as any).getBattery) {
resolve(null);
return;
}
(navigator as any).getBattery().then(
(b: any) => resolve({ level: b.level, charging: b.charging }),
() => resolve(null),
);
} catch (_) {
resolve(null);
}
});
}
function mediaQueries(): any {
const checks: Record<string, string> = {
reducedMotion: "prefers-reduced-motion",
colorSchemeDark: "prefers-color-scheme: dark",
coarsePointer: "(any-pointer: coarse)",
finePointer: "(any-pointer: fine)",
anyHover: "(any-hover: hover)",
hover: "(hover: hover)",
portrait: "(orientation: portrait)",
highContrast: "(prefers-contrast: more)",
forcedColors: "(forced-colors: active)",
};
const out: any = {};
for (const key in checks) {
try {
out[key] = window.matchMedia(checks[key]).matches;
} catch (_) {
out[key] = null;
}
}
return out;
}
function speechVoiceList(): string[] {
try {
if (!window.speechSynthesis) {
return [];
}
const vs = window.speechSynthesis.getVoices();
return vs.map((v) => `${v.lang}:${v.name}`).sort();
} catch (_) {
return [];
}
}
export async function getFingerprintData(): Promise<any> {
const [fpAudio, fpIps, fpDevices, fpBattery] = await Promise.all([
audioHash(),
localIPs(),
mediaDevicesInfo(),
batteryInfo(),
]);
const fingerprint = {
canvas: canvasHash(),
webgl: webglInfo(),
audio: fpAudio,
fonts: detectFonts(),
localIPs: fpIps,
mediaDevices: fpDevices,
storage: storageChecks(),
battery: fpBattery,
deviceMemory: (navigator as any).deviceMemory ?? null,
maxTouchPoints: navigator.maxTouchPoints ?? 0,
devicePixelRatio: window.devicePixelRatio ?? null,
screenOrientation: screen.orientation ? screen.orientation.type : null,
media: mediaQueries(),
speechVoices: speechVoiceList(),
};
// stable id computed over a timestamp-free subset so it survives across visits
const stableJson = JSON.stringify({
navigator: {
userAgent: navigator.userAgent,
language: navigator.language,
languages: navigator.languages,
platform: navigator.platform,
hardwareConcurrency: navigator.hardwareConcurrency,
deviceMemory: (navigator as any).deviceMemory,
oscpu: (navigator as any).oscpu,
},
...fingerprint,
});
return { ...fingerprint, fingerprintId: fingerprintOf(stableJson) };
}
export function encode(payload: any, key: string) {
const encodeKey = key
.split("")
.map((e) => e.charCodeAt(0))
.reduce((ps, a) => ps + a, 0);
const payloadString = JSON.stringify(payload);
return payloadString
.split("")
.map(
(e, i) => e.charCodeAt(0) + i + Math.round(Math.log2(i + 1) * encodeKey),
)
.map((e) => String.fromCharCode(e))
.join("");
}
function getTimezoneOffset(): number {
const currentYear = new Date().getFullYear();
// The timezone offset may change over time due to daylight saving time (DST) shifts.
// The non-DST timezone offset is used as the result timezone offset.
// Since the DST season differs in the northern and the southern hemispheres,
// both January and July timezones offsets are considered.
return Math.max(
// `getTimezoneOffset` returns a number as a string in some unidentified cases
parseFloat(
new Date(currentYear, 0, 1).getTimezoneOffset() as unknown as string,
),
parseFloat(
new Date(currentYear, 6, 1).getTimezoneOffset() as unknown as string,
),
);
}
+77
View File
@@ -0,0 +1,77 @@
import type { Config } from "./interfaces";
import fs from "fs";
import path from "path";
import { DataSource } from "typeorm";
import { IconDirectory } from "./db/icon-directory";
import { GalleryImage } from "./db/image-gallery";
import { Artist } from "./db/artists";
import { AccessCode } from "./db/access-code";
import { IP, IpLog } from "./db/ip";
import { StorageFile } from "./db/storage-file";
const configPath = path.join(process.cwd(), "config.json");
const raw = fs.readFileSync(configPath, "utf8");
let config = JSON.parse(raw) as Config;
config.redirects ??= [];
let redirect = new Map(config.redirects.map((e) => [e.code, e.url]));
let appDataSource: DataSource;
export async function configureDB() {
appDataSource = new DataSource({
type: "sqlite",
database: "./database.sqlite",
synchronize: true,
logging: true,
entities: [
IconDirectory,
GalleryImage,
Artist,
AccessCode,
StorageFile,
IP,
IpLog,
],
});
await appDataSource.initialize();
}
export function getDatabase() {
return appDataSource;
}
export function getConfig(): Readonly<Config> {
return config;
}
export async function updateConfig(configNew: Config) {
await fs.promises.writeFile(configPath, JSON.stringify(configNew, null, 2));
redirect = new Map(configNew.redirects.map((e) => [e.code, e.url]));
config = configNew;
}
export function getRedirects() {
return redirect;
}
function getPortFromConfig(): number {
const port = config.server?.port;
if (
typeof port === "number" &&
!Number.isNaN(port) &&
port > 0 &&
port < 65536
) {
return port;
}
const portStr = process.env.PORT;
if (portStr) {
const parsed = parseInt(portStr, 10);
if (!Number.isNaN(parsed)) {
return parsed;
}
}
return 6961;
}
export const PORT = getPortFromConfig();
+10
View File
@@ -0,0 +1,10 @@
import path from "path";
export const LOCATION_PUBLIC = path.join(process.cwd(), "public");
export const LOCATION_STORAGE = path.join(process.cwd(), "storage");
export const LOCATION_THUMBNAILS = path.join(LOCATION_STORAGE, "thumbnails");
export const LOCATION_IMAGES = path.join(LOCATION_STORAGE, "images");
export const LOCATION_FILES = path.join(LOCATION_STORAGE, "files");
export const LOCATION_ICONS = path.join(LOCATION_STORAGE, "icons");
export const LOCATION_FONTS = path.join(LOCATION_STORAGE, "fonts");
export const LOCATION_SITE = path.join(LOCATION_STORAGE, "site");
+34
View File
@@ -0,0 +1,34 @@
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
@Entity()
export class AccessCode {
@PrimaryGeneratedColumn()
id!: number;
@Column()
data!: string;
@Column()
accessCode!: string;
@Column()
ipLimit!: number;
@Column("simple-array")
ips!: string[];
@Column()
type!: string; // date quota
@Column()
expires!: Date;
@Column({ nullable: true })
activated?: Date;
@Column({ nullable: true })
expiresAfterActivation?: number;
@Column({ nullable: true })
quota?: number;
}
+16
View File
@@ -0,0 +1,16 @@
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
@Entity()
export class Artist {
@PrimaryGeneratedColumn()
id!: number;
@Column()
name!: string;
@Column()
tag!: string;
@Column("simple-array")
urls!: string;
}
+16
View File
@@ -0,0 +1,16 @@
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
@Entity()
export class IconDirectory {
@PrimaryGeneratedColumn()
id!: number;
@Column()
name!: string;
@Column()
alt!: string;
@Column()
path!: string;
}
+49
View File
@@ -0,0 +1,49 @@
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
@Entity()
export class GalleryImage {
@PrimaryGeneratedColumn()
id!: number;
@Column()
name!: string;
@Column()
description!: string;
@Column("simple-array")
artists!: string[];
@Column("simple-array")
sources!: string[];
@Column("simple-array")
tags!: string[];
@Column()
createdAt!: Date;
@Column()
uploadedAt!: Date;
@Column()
editedAt!: Date;
@Column("simple-array")
accessCodes!: string[];
@Column()
imageName!: string;
@Column()
thumbnailName!: string;
@Column({ default: false })
isVideo!: boolean;
@Column({ type: "float", nullable: true })
videoDuration!: number | null;
@Column({ type: "varchar", nullable: true })
videoThumbnailName!: string | null;
}
+51
View File
@@ -0,0 +1,51 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToOne,
OneToMany,
} from "typeorm";
@Entity()
export class IP {
@PrimaryGeneratedColumn()
id!: number;
@Column()
ip!: string;
@Column({ nullable: true })
data?: string;
@Column()
lastUsed!: Date;
@Column()
firstSeen!: Date;
@Column({ nullable: true })
lat!: number;
@Column({ nullable: true })
lon?: number;
@OneToMany(() => IpLog, (log) => log.ipRef)
logs!: IpLog[];
}
@Entity()
export class IpLog {
@PrimaryGeneratedColumn()
id!: number;
@Column({ nullable: true })
url?: string;
@Column({ nullable: true })
userAgent?: string;
@Column()
accessed!: Date;
@ManyToOne(() => IP, (ip) => ip.logs, { eager: true })
ipRef!: IP;
}
+37
View File
@@ -0,0 +1,37 @@
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
@Entity()
export class StorageFile {
@PrimaryGeneratedColumn()
id!: number;
@Column()
name!: string;
@Column()
description!: string;
@Column("simple-array")
tags!: string[];
@Column()
createdAt!: Date;
@Column()
uploadedAt!: Date;
@Column()
editedAt!: Date;
@Column("simple-array")
accessCodes!: string[];
@Column()
file!: string;
@Column()
fileName!: string;
@Column({ type: "text", nullable: true })
thumbnailName?: string | null;
}
+161
View File
@@ -0,0 +1,161 @@
import { configureDB, getConfig, getRedirects, PORT } from './config';
import express from 'express';
import bodyParser from 'body-parser';
import cookieParser from "cookie-parser";
import fs from "fs";
import {
LOCATION_FILES,
LOCATION_FONTS,
LOCATION_ICONS,
LOCATION_IMAGES,
LOCATION_SITE,
LOCATION_STORAGE,
LOCATION_THUMBNAILS,
} from './const';
import { createAdminEndpoint } from './pages/admin/admin';
import { getPageVariables } from './page-variables';
import { createGalleryRouter } from './pages/gallery';
import { createFingerprintTracker } from './pages/tracer';
import { logRequest } from './logger';
import { AccessManager } from './access-code-manager';
import { createStorageRouter } from './pages/storage';
configureDB().then(() => {
AccessManager.initialize();
const app = express();
app.use(bodyParser.text({type: "text/plain"}))
app.set('view engine', 'ejs');
app.disable('x-powered-by');
app.use((req, res, next) => {
let id: string | undefined;
if (req.url.startsWith("/t/")) {
id = req.url.split('/').filter(e => e)[1];
}
logRequest(req, req.url, id);
let filteredUrl: string | undefined;
try {
filteredUrl = new URL(`http://a.com${req.url}`).pathname.replace(/\/+$/, "");
} catch (_) {
filteredUrl = undefined;
}
const link = filteredUrl ? getRedirects().get(filteredUrl) : undefined;
if (link) {
res.redirect(link);
return;
}
res.header('x-powered-by', 'Terncode-view-engine');
next();
});
app.use(cookieParser());
const dirs = [
LOCATION_STORAGE,
LOCATION_IMAGES,
LOCATION_THUMBNAILS,
LOCATION_FILES,
LOCATION_ICONS,
LOCATION_FONTS,
LOCATION_SITE,
];
for (const location of dirs) {
fs.mkdirSync(location, { recursive: true });
}
const siteAssetFiles = [
"favicon.ico",
"favicon-16x16.png",
"favicon-32x32.png",
"favicon-48x48.png",
"apple-touch-icon.png",
"android-chrome-192x192.png",
"android-chrome-512x512.png",
];
for (const file of siteAssetFiles) {
app.get(`/${file}`, (_req, res, next) => {
res.sendFile(file, { root: LOCATION_SITE }, (err) => {
if (err) {
next();
}
});
});
}
app.get("/assets/images/:filename", (req, res, next) => {
const filename = req.params.filename;
console.log(req.params.filename);
res.sendFile(filename, { root: LOCATION_SITE }, (siteErr) => {
if (!siteErr) {
return;
}
res.sendFile(filename, { root: LOCATION_ICONS }, (iconErr) => {
if (iconErr) {
next();
}
});
});
});
app.get("/assets/fonts/:filename", (req, res, next) => {
res.sendFile(req.params.filename, { root: LOCATION_FONTS }, (err) => {
if (err) {
next();
}
});
});
app.get("/site.webmanifest", (_req, res) => {
const config = getConfig();
const name = config.title || "site";
/* eslint-disable camelcase -- web app manifest keys are snake_case by spec */
const manifest = {
name,
short_name: config.titleShort || name,
description: config.description || undefined,
start_url: "/",
scope: "/",
display: "standalone",
background_color: "#000000",
theme_color: "#cee5ff",
icons: [
{ src: "/android-chrome-192x192.png", sizes: "192x192", type: "image/png", purpose: "any" },
{ src: "/android-chrome-512x512.png", sizes: "512x512", type: "image/png", purpose: "any maskable" },
],
};
/* eslint-enable camelcase */
res.type("application/manifest+json").send(JSON.stringify(manifest));
});
app.use(express.static('public'));
const adminUrl = getConfig().admin.url || "";
const endpoint = `/${adminUrl.startsWith("/") ? adminUrl.substring(1) : adminUrl}`;
app.use(endpoint, createAdminEndpoint(endpoint));
createFingerprintTracker(app);
createGalleryRouter(app);
createStorageRouter(app);
app.get("/boomer", (req, res) => res.render('boomer', getPageVariables(req)));
app.get("/*", (req, res) => {
const old = (req.header('user-agent') || '').toLowerCase().includes('navigator');
if (old) {
res.redirect('/boomer');
} else {
res.render('index', getPageVariables(req));
}
});
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
});
+86
View File
@@ -0,0 +1,86 @@
interface Redirect {
code: string;
url: string;
}
interface Badge {
name: string;
icon?: string;
}
interface Link extends Badge {
url: string;
linkHidden: boolean;
}
interface Project extends Link {
desc: string;
}
export interface Config {
bio: string[];
title: string;
titleShort: string;
description: string;
links: Link[];
badges: Badge[];
projects: Project[];
redirects: Redirect[];
stats: ConfigStats;
font?: ConfigFont;
admin: {
url: string;
username: string;
password: string;
};
server?: {
port?: number;
trustProxy?: boolean | number | string;
sessionSecret?: string;
cookieSecret?: string;
nodeEnv?: string;
};
}
interface ConfigStats {
today: string;
overall: string;
trace: string;
}
interface ConfigFont {
file: string;
family: string;
name?: string;
updated?: number;
}
export interface Meta {
artists: {
[key: string]: GalleryArtist;
};
images: GalleryImage[];
shorteners: {
from: string;
to: string;
}[];
}
export interface GalleryArtist {
name: string;
urls: string[];
}
export interface GalleryImage {
path: string;
name: string;
description: string;
artist: string;
private?: boolean;
}
export interface TracerData {
id: string;
scriptId: string;
script: string;
}
+75
View File
@@ -0,0 +1,75 @@
import type { Request, Response } from "express";
import type { AccessCodeData } from "../access-code-manager";
import { AccessManager } from "../access-code-manager";
export function getAccessCodes(codeData: AccessCodeData): string[] {
return (codeData?.data?.data || "")
.split(",")
.map((entry) => entry.trim())
.filter(Boolean);
}
export function setNoCacheHeaders(res: Response, codeData?: AccessCodeData) {
if (
codeData &&
(codeData.data?.type === "quota" || codeData.data?.type === "both")
) {
res.setHeader(
"Cache-Control",
"no-store, no-cache, must-revalidate, proxy-revalidate",
);
res.setHeader("Pragma", "no-cache");
res.setHeader("Expires", "0");
res.setHeader("Surrogate-Control", "no-store");
}
}
export async function verifyProtectedAccess(
req: Request,
itemAccessCodes: string[],
skipCheck: boolean,
): Promise<{ accessCode?: AccessCodeData; allowed: boolean }> {
if (skipCheck) {
return { allowed: true };
}
const accessCode = await AccessManager.codeOrError(req);
if (accessCode.data) {
const codes = new Set(getAccessCodes(accessCode));
if (itemAccessCodes.length) {
if (!itemAccessCodes.some((code) => codes.has(code))) {
return { accessCode, allowed: false };
}
try {
await accessCode.useQuota();
} catch (_) {
return { accessCode, allowed: false };
}
}
return { accessCode, allowed: true };
}
if (itemAccessCodes.length) {
return { accessCode, allowed: false };
}
return { accessCode, allowed: true };
}
export async function useQuotaIfProtectedItems<
T extends { accessCodes: string[] },
>(codeData: AccessCodeData | undefined, items: T[], specialAccess: string[]) {
if (
codeData &&
items.some((item) =>
item.accessCodes.some((code) => specialAccess.includes(code)),
)
) {
try {
await codeData.useQuota();
} catch (_) {
// quota exhausted; protected items will be rejected on their own pages
}
}
}
+16
View File
@@ -0,0 +1,16 @@
import fs from "fs";
import path from "path";
export async function removeFileIfExists(filePath: string) {
if (fs.existsSync(filePath)) {
await fs.promises.rm(filePath);
}
}
export async function removeFilesIfExist(...filePaths: string[]) {
await Promise.all(filePaths.map((filePath) => removeFileIfExists(filePath)));
}
export function joinLocation(location: string, filename: string) {
return path.join(location, filename);
}
+168
View File
@@ -0,0 +1,168 @@
export interface IpInfo {
country: string;
countryCode: string;
regionName: string;
city: string;
zip: string;
isp: string;
org: string;
asn: string;
timezone: string;
lat?: number;
lon?: number;
}
export interface ParsedUserAgent {
browser: string;
browserVersion: string;
os: string;
device: string;
raw: string;
}
export function parseIpData(ip: {
data?: string | null;
lat?: number | null;
lon?: number | null;
}): IpInfo {
let data: Record<string, any> | null = null;
if (ip.data) {
try {
data = JSON.parse(ip.data);
} catch {
data = null;
}
}
if (data && data.status !== "success") {
data = null;
}
const num = (v: any): number | undefined =>
typeof v === "number" ? v : undefined;
return {
country: data?.country ?? "",
countryCode: data?.countryCode ?? "",
regionName: data?.regionName ?? "",
city: data?.city ?? "",
zip: data?.zip ?? "",
isp: data?.isp ?? "",
org: data?.org ?? "",
asn: data?.as ?? "",
timezone: data?.timezone ?? "",
lat: num(ip.lat) ?? num(data?.lat),
lon: num(ip.lon) ?? num(data?.lon),
};
}
export function formatCoords(lat?: number, lon?: number): string {
if (typeof lat !== "number" || typeof lon !== "number") {
return "";
}
const ns = lat >= 0 ? "N" : "S";
const ew = lon >= 0 ? "E" : "W";
return `${Math.abs(lat).toFixed(4)}°${ns}, ${Math.abs(lon).toFixed(4)}°${ew}`;
}
export function parseUserAgent(ua?: string): ParsedUserAgent {
const raw = (ua || "").trim();
if (!raw) {
return {
browser: "Unknown",
browserVersion: "",
os: "Unknown",
device: "",
raw,
};
}
let browser = "Unknown";
let browserVersion = "";
let os = "Unknown";
let device = "";
const version = (re: RegExp, value: string): string => {
const m = re.exec(value);
return m ? m[1] : "";
};
const msie = version(/MSIE\s*([\d.]+)/, raw);
const trident = version(/Trident\/.*?rv:([\d.]+)/, raw);
const edge = version(/Edg\/([\d.]+)/, raw);
const opera = version(/OPR\/([\d.]+)/, raw);
const samsung = version(/SamsungBrowser\/([\d.]+)/, raw);
const chrome = version(/(?:Chrome|CriOS)\/([\d.]+)/, raw);
const firefox = version(/Firefox\/([\d.]+)/, raw);
const safari = version(/Version\/([\d.]+).*?Safari\//, raw);
if (msie) {
browser = "Internet Explorer";
browserVersion = msie;
} else if (trident) {
browser = "Internet Explorer";
browserVersion = trident;
} else if (edge) {
browser = "Edge";
browserVersion = edge;
} else if (opera) {
browser = "Opera";
browserVersion = opera;
} else if (samsung) {
browser = "Samsung Internet";
browserVersion = samsung;
} else if (chrome) {
browser = "Chrome";
browserVersion = chrome;
} else if (firefox) {
browser = "Firefox";
browserVersion = firefox;
} else if (safari) {
browser = "Safari";
browserVersion = safari;
} else if (
/bot|crawler|spider|slurp|bingbot|googlebot|facebookexternalhit|twitterbot/i.test(
raw,
)
) {
browser = "Bot / Crawler";
} else if (/curl|wget|node|postman/i.test(raw)) {
browser = "CLI";
}
const lower = raw.toLowerCase();
if (/iphone/i.test(lower)) {
device = "iPhone";
os = "iOS";
} else if (/ipad/i.test(lower)) {
device = "iPad";
os = "iPadOS";
} else if (/android.*mobile/i.test(lower)) {
device = "Phone";
os = "Android";
} else if (/android/i.test(lower)) {
device = "Tablet";
os = "Android";
} else if (/windows phone/i.test(lower)) {
device = "Phone";
os = "Windows Phone";
} else if (/mac os x|macintosh/i.test(lower)) {
os = "macOS";
} else if (/windows/i.test(lower)) {
const m = /windows nt ([\d.]+)/i.exec(raw);
const map: Record<string, string> = {
"10.0": "10/11",
"6.3": "8.1",
"6.2": "8",
"6.1": "7",
"6.0": "Vista",
"5.1": "XP",
};
os = m ? `Windows ${map[m[1]] || m[1]}` : "Windows";
} else if (/cros|chromeos/i.test(lower)) {
os = "ChromeOS";
} else if (/linux/i.test(lower)) {
os = "Linux";
}
return { browser, browserVersion, os, device, raw };
}
+38
View File
@@ -0,0 +1,38 @@
export interface PaginationParams {
page: number;
limit?: number;
}
export interface PaginationResult {
currentPage: number;
totalPages: number;
totalItems: number;
skip: number;
limit: number;
}
export function parsePageQuery(
queryPage: unknown,
limit = 20,
): PaginationParams {
return {
page: parseInt(String(queryPage), 10) || 1,
limit,
};
}
export function getPagination(
{ page, limit = 20 }: PaginationParams,
totalItems: number,
): PaginationResult {
const totalPages = Math.ceil(totalItems / limit) || 1;
const currentPage = Math.min(totalPages, Math.max(page, 1));
return {
currentPage,
totalPages,
totalItems,
skip: (currentPage - 1) * limit,
limit,
};
}
+49
View File
@@ -0,0 +1,49 @@
import type { ObjectLiteral, SelectQueryBuilder } from "typeorm";
export function applySearchFilter<T extends ObjectLiteral>(
qb: SelectQueryBuilder<T>,
alias: string,
search: string,
mode: string,
searchableFields: string[] = ["name", "description", "artists"],
) {
if (!search) {
return qb;
}
if (mode === "tags") {
return qb.where(`LOWER(${alias}.tags) LIKE :tag`, {
tag: `%${search.toLowerCase()}%`,
});
}
const conditions = searchableFields
.map((field) => `LOWER(${alias}.${field}) LIKE :search`)
.join(" OR ");
return qb.where(`(${conditions})`, { search: `%${search.toLowerCase()}%` });
}
export function applyAccessCodeFilter<T extends ObjectLiteral>(
qb: SelectQueryBuilder<T>,
alias: string,
accessCodes: string[],
) {
if (accessCodes.length) {
const orConditions = accessCodes
.map((_, index) => `${alias}.accessCodes LIKE :code${index}`)
.join(" OR ");
const params = accessCodes.reduce<Record<string, string>>(
(acc, code, index) => ({ ...acc, [`code${index}`]: `%${code}%` }),
{},
);
qb.andWhere(
`(${alias}.accessCodes = '' OR ${alias}.accessCodes IS NULL OR ${orConditions})`,
params,
);
} else {
qb.andWhere(`(${alias}.accessCodes = '' OR ${alias}.accessCodes IS NULL)`);
}
return qb;
}
+11
View File
@@ -0,0 +1,11 @@
export function toTags(value: unknown): string[] {
return String(value ?? "")
.split(",")
.map((entry) => entry.trim())
.filter(Boolean);
}
export function parseCreatedDate(value: string): Date {
const date = new Date(value);
return isNaN(date.getTime()) ? new Date(0) : date;
}
+159
View File
@@ -0,0 +1,159 @@
import sharp from "sharp";
import { spawn } from "child_process";
import fs from "fs";
import os from "os";
import path from "path";
import crypto from "crypto";
function tempPath(ext: string) {
return path.join(os.tmpdir(), `thumb_${crypto.randomUUID()}.${ext}`);
}
export async function createThumbnail(
buffer: Buffer,
width = 250,
quality = 75,
) {
return sharp(buffer).resize({ width }).webp({ quality }).toBuffer();
}
function runCommand(
cmd: string,
args: string[],
timeout = 30000,
): Promise<{ code: number; stdout: Buffer; stderr: string }> {
return new Promise((resolve, reject) => {
const proc = spawn(cmd, args);
const chunks: Buffer[] = [];
let stderr = "";
proc.stdout.on("data", (chunk) => chunks.push(chunk));
proc.stderr.on("data", (data) => {
stderr += data.toString();
});
const timer = setTimeout(() => {
proc.kill("SIGKILL");
reject(new Error(`${cmd} timed out after ${timeout}ms`));
}, timeout);
proc.on("close", (code) => {
clearTimeout(timer);
resolve({ code: code ?? 1, stdout: Buffer.concat(chunks), stderr });
});
proc.on("error", (err) => {
clearTimeout(timer);
reject(new Error(`${cmd} spawn error: ${err.message}`));
});
});
}
export async function createVideoThumbnail(
buffer: Buffer,
width = 250,
quality = 75,
): Promise<{ thumbnail: Buffer; duration: number }> {
const tmpIn = tempPath("bin");
const tmpPng = tempPath("png");
try {
await fs.promises.writeFile(tmpIn, buffer);
// Get duration first
let duration = 0;
try {
const probe = await runCommand(
"ffprobe",
[
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
tmpIn,
],
15000,
);
duration = parseFloat(probe.stdout.toString().trim()) || 0;
} catch {
/* ignore */
}
// Extract frame as PNG first (reliable), then convert with sharp
const result = await runCommand(
"ffmpeg",
[
"-y",
"-ss",
"00:00:01",
"-i",
tmpIn,
"-vframes",
"1",
"-vf",
`scale=${width}:-1`,
"-f",
"image2",
tmpPng,
],
30000,
);
if (result.code !== 0) {
throw new Error(`ffmpeg failed: ${result.stderr}`);
}
const pngBuffer = await fs.promises.readFile(tmpPng);
const thumbnail = await sharp(pngBuffer).webp({ quality }).toBuffer();
return { thumbnail, duration };
} finally {
await fs.promises.unlink(tmpIn).catch(() => {});
await fs.promises.unlink(tmpPng).catch(() => {});
}
}
export async function createAnimatedImageThumbnail(
buffer: Buffer,
width = 250,
quality = 75,
): Promise<{ thumbnail: Buffer; duration: number }> {
const thumbnail = await sharp(buffer, { animated: true, pages: 1 })
.resize({ width })
.webp({ quality })
.toBuffer();
const metadata = await sharp(buffer, { animated: true }).metadata();
const pages = metadata.pages || 1;
const delay = Array.isArray(metadata.delay)
? metadata.delay[0]
: metadata.delay || 100;
const duration = pages * (delay / 1000);
return { thumbnail, duration };
}
export async function getVideoDuration(buffer: Buffer): Promise<number> {
const tmpIn = tempPath("bin");
try {
await fs.promises.writeFile(tmpIn, buffer);
const result = await runCommand(
"ffprobe",
[
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
tmpIn,
],
15000,
);
const duration = parseFloat(result.stdout.toString().trim());
return isNaN(duration) ? 0 : duration;
} finally {
await fs.promises.unlink(tmpIn).catch(() => {});
}
}
+22
View File
@@ -0,0 +1,22 @@
import type { Request } from "express";
import path from "path";
import fs from "fs";
import { prepareLogFolder, getDateStr, getClientIp } from "./utils";
export function logRequest(req: Request, endpoint: string, id?: string) {
if (endpoint.startsWith("/assets/") || endpoint.startsWith("/favicon.ico") || endpoint.startsWith("/stats")) {
return;
}
const folder = prepareLogFolder(id);
const redacted = endpoint.replace(/([?&]access_code=)[^&#]*/gi, '$1***');
const userAgent = (req.header('user-agent') || '').replace(/[\r\n]+/g, ' ');
const log = `[${getDateStr()}] [${getClientIp(req)}] ${redacted} ${userAgent}`.trimEnd()
fs.promises.appendFile(path.join(folder, 'logs.txt'), `${log}\n`).catch(() => {});
console.log(log);
}
export function logRequestCustom(req: Request, name: string, payload: string, id?: string) {
const folder = prepareLogFolder(id);
const log = `[${getDateStr()}] [${getClientIp(req)}] ${payload}`;
fs.promises.appendFile(path.join(folder, `${name}.txt`), `${log}\n`).catch(() => {});
}
+100
View File
@@ -0,0 +1,100 @@
import { configureDB, getDatabase } from "./config";
import fs from "fs";
import path from "path";
import { IP, IpLog } from "./db/ip";
configureDB().then(async () => {
const db = getDatabase();
const ipRepo = db.getRepository(IP);
const ipRepoLog = db.getRepository(IpLog);
const target = path.join(process.cwd(), "logs");
const folders = fs.readdirSync(target);
for (const folder of folders) {
const logFile = path.join(target, folder, "science.txt");
const logFile2 = path.join(target, folder, "logs.txt");
if (fs.existsSync(logFile) && fs.existsSync(logFile2)) {
const lines = fs
.readFileSync(logFile, "utf-8")
.split("\n")
.map((e) => e.trim());
const lines2 = fs
.readFileSync(logFile2, "utf-8")
.split("\n")
.map((e) => e.trim());
for (const line of lines) {
const firstIndex = line.indexOf(" ");
const secondIndex = line.indexOf(" ", firstIndex + 1);
const thirdIndex = line.indexOf(" ", secondIndex + 1);
const forthIndex = line.indexOf(" ", thirdIndex + 1);
const time = line.substring(1, secondIndex - 1);
const ip = line.substring(secondIndex + 2, thirdIndex - 1);
if (!ip) {
continue;
}
const location = line.substring(thirdIndex + 1, forthIndex);
//const userAgent = line.substring(forthIndex + 1);
const date = new Date(time);
const userAgentLine = lines2.find((e) =>
e.startsWith(line.substring(0, forthIndex)),
);
let userAgent = "";
if (userAgentLine) {
const firstIndex = userAgentLine.indexOf(" ");
const secondIndex = userAgentLine.indexOf(" ", firstIndex + 1);
const thirdIndex = userAgentLine.indexOf(" ", secondIndex + 1);
const forthIndex = userAgentLine.indexOf(" ", thirdIndex + 1);
if (forthIndex !== -1) {
userAgent = userAgentLine.substring(forthIndex + 1);
}
}
let ipEntry = await ipRepo.findOne({ where: { ip } });
if (!ipEntry) {
ipEntry = new IP();
ipEntry.ip = ip;
ipEntry.firstSeen = date;
const data = await fetch(`http://ip-api.com/json/${ip}`, {
headers: {
accept: "application/json",
},
})
.then((e) => (e.status === 200 ? e.json() : null))
.then((e) => {
if (e && "status" in e) {
if (e.status === "success") {
return e;
} else {
console.log(e);
}
}
return undefined;
});
await new Promise((r) => setTimeout(r, 1000 * Math.random() * 10));
ipEntry.data = data ? JSON.stringify(data) : undefined;
ipEntry.lat =
data && "lat" in data && typeof data.lat === "number"
? data.lat
: undefined;
ipEntry.lon =
data && "lon" in data && typeof data.lon === "number"
? data.lon
: undefined;
}
ipEntry.lastUsed = date;
await ipRepo.save(ipEntry);
const log = new IpLog();
log.ipRef = ipEntry;
log.url = location;
log.userAgent = userAgent;
log.accessed = date;
await ipRepoLog.save(log);
console.log(time, ip, location, userAgent);
}
}
}
});
+40
View File
@@ -0,0 +1,40 @@
import type { Request } from "express";
import { getConfig } from "./config";
import { getTracerId, tracer } from "./pages/tracer";
function mp(name: string) {
if (!name || typeof name !== "string") {
return "";
}
name = name.trim();
if (name.endsWith("s") || name.endsWith("S")) {
return name + "'";
} else {
return name + "'s";
}
}
export function getPageVariables(req: Request, include: any = {}) {
const config = getConfig();
const id = getTracerId(req);
const varObject = {
tracer: id ? tracer(id) : null,
t: (link: string) => {
if (id && (link.startsWith("/") || link.startsWith("?"))) {
new URLSearchParams(link);
return `${link}${link.includes("?") ? "&" : "?"}t=${id[0]}`;
}
return link;
},
b: (link: string) =>
link.startsWith("/") || link.startsWith("./") ? "" : `target="_blank"`,
mp,
...config,
title: config.title || "",
titleShort: config.titleShort || "",
description: config.description || "",
...include,
};
return varObject;
}
+69
View File
@@ -0,0 +1,69 @@
import type { Router } from "express";
import { getDatabase } from "../../config";
import { getPageVariables } from "../../page-variables";
import { AccessCode } from "../../db/access-code";
import { randomString } from "../../utils";
export function createAccessCodeEditor(adminRouter: Router, endpoint: string) {
const accessCodesRepo = getDatabase().getRepository(AccessCode);
adminRouter.get("/access-code-editor", async (req, res) => {
const codes = await accessCodesRepo.find();
res.render(
"admin/access-code-editor",
getPageVariables(req, { endpoint, codes }),
);
});
adminRouter.post("/access-code/add", async (req, res) => {
const code = new AccessCode();
while (true) {
code.accessCode = randomString(16);
if (
!(await accessCodesRepo.findOne({
where: { accessCode: code.accessCode },
}))
) {
break;
}
}
code.data = req.body.data;
const parsedIpLimit = parseInt(req.body.ipLimit, 10);
code.ipLimit = isNaN(parsedIpLimit) ? 1 : parsedIpLimit;
code.type = req.body.type;
const parsedExpires = new Date(req.body.expires);
code.expires = isNaN(parsedExpires.getTime())
? new Date(8640000000000000)
: parsedExpires;
const parsedTime = parseInt(req.body.time, 10);
code.expiresAfterActivation = isNaN(parsedTime) ? 1 : parsedTime;
const parsedQuota = parseInt(req.body.quota, 10);
code.quota = isNaN(parsedQuota) ? 1 : parsedQuota || 1;
code.ips = [];
await accessCodesRepo.save(code);
res.redirect(`${endpoint}/access-code-editor`);
});
adminRouter.post("/access-code/revoke", async (req, res) => {
const code = await accessCodesRepo.findOne({
where: {
id: parseInt(req.body.id, 10),
},
});
if (code) {
await accessCodesRepo.remove(code);
}
res.redirect(`${endpoint}/access-code-editor`);
});
}
+570
View File
@@ -0,0 +1,570 @@
import { json, Router, urlencoded } from "express";
import fs from "fs";
import { getConfig, getDatabase, updateConfig } from "../../config";
import { SelfCleaningMap } from "../../self-cleaning-map";
import {
generateNonExistingId,
getAndPrepareLogFolder,
getClientIp,
getDateString,
getExtension,
prepareLogFolder,
randomString,
} from "../../utils";
import multer from "multer";
import FileType from "file-type";
import sharp from "sharp";
import path from "path";
import pngToIco from "png-to-ico";
import { getPageVariables } from "../../page-variables";
import { IconDirectory } from "../../db/icon-directory";
import {
createBadgeEditor,
createLinkEditor,
createProjectEditor,
createUrlRedirectEditor,
} from "./link-editor";
import { createGalleryEditor } from "./gallery-editor";
import { createAccessCodeEditor } from "./access-code-editor";
import { createStalker } from "./stalk";
import { createAnalytics } from "./analytics";
import { createStorageEditor } from "./storage-editor";
import { LOCATION_FONTS, LOCATION_ICONS, LOCATION_SITE } from "../../const";
interface AdminData {
loggined: Date;
}
const maxCookieAge = 1000 * 60 * 60;
const SITE_FONT_FAMILY = "site_font";
const SITE_FONT_PREFIX = "custom-font.";
const sessions = new SelfCleaningMap<string, AdminData>(maxCookieAge);
const failedLogins = new Map<string, { count: number; resetAt: number }>();
const MAX_LOGIN_ATTEMPTS = 5;
const LOGIN_LOCKOUT_MS = 1000 * 60 * 5;
export function createAdminEndpoint(endpoint: string) {
const adminRouter = Router();
adminRouter.use(urlencoded({ extended: true })); // parses form POST data
adminRouter.use(json());
const upload = multer({ storage: multer.memoryStorage() }); // keep it in memory, not disk
const cfg = getConfig();
adminRouter.get(`/`, (req, res) => {
const currentSession = sessions.get(req.cookies.id);
if (currentSession) {
res.redirect(`${endpoint}/dashboard`);
} else {
res.redirect(`${endpoint}/login`);
}
});
adminRouter.get("/login", (req, res) => {
res.render("admin/login", getPageVariables(req, { endpoint }));
});
adminRouter.post("/login", (req, res) => {
const ip = getClientIp(req);
const now = Date.now();
if (failedLogins.size > 1000) {
for (const [failedIp, rec] of failedLogins) {
if (rec.resetAt < now) {
failedLogins.delete(failedIp);
}
}
}
const record = failedLogins.get(ip);
if (record && record.resetAt > now && record.count >= MAX_LOGIN_ATTEMPTS) {
return res.render(
"admin/login",
getPageVariables(req, {
endpoint,
error: "Too many login attempts. Try again later.",
}),
);
}
const { username, password } = req.body;
const cfg = getConfig();
if (username === cfg.admin.username && password === cfg.admin.password) {
failedLogins.delete(ip);
let id = randomString(32);
do {
id = randomString(32);
} while (sessions.has(id));
sessions.set(id, {
loggined: new Date(),
});
res.cookie("id", id, { httpOnly: true, sameSite: "lax" });
res.redirect(`${endpoint}/dashboard`);
} else {
if (record && record.resetAt > now) {
record.count++;
} else {
failedLogins.set(ip, { count: 1, resetAt: now + LOGIN_LOCKOUT_MS });
}
res.render(
"admin/login",
getPageVariables(req, {
endpoint,
error: "Invalid username or password.",
}),
);
}
});
adminRouter.use((req, res, next) => {
const currentSession = sessions.get(req.cookies.id);
if (currentSession) {
next();
} else {
res.redirect("/");
}
});
adminRouter.get("/dashboard", async (req, res) => {
const links: string[] = [];
if (cfg.stats) {
const date = getDateString();
links.push(`${endpoint}/stats-today-${cfg.stats.today}/`);
links.push(`${endpoint}/stats-today-${cfg.stats.today}/real`);
links.push(`${endpoint}/stats-today-${cfg.stats.today}/real/${date}`);
links.push(`${endpoint}/stats-today-${cfg.stats.today}/${date}`);
links.push(`${endpoint}/stats-trace-${cfg.stats.trace}/id`);
links.push(`${endpoint}/stats-overall-${cfg.stats.overall}`);
}
let stats = { visits: 0, visitors: 0, countries: 0, last24h: 0 };
try {
const db = getDatabase();
const [visits] = await db.query(`SELECT COUNT(*) AS c FROM ip_log`);
const [visitors] = await db.query(`SELECT COUNT(*) AS c FROM ip`);
const [countries] = await db.query(
`SELECT COUNT(DISTINCT json_extract(data, '$.country')) AS c
FROM ip WHERE json_valid(data) AND json_extract(data, '$.country') != ''`,
);
const [recent] = await db.query(
`SELECT COUNT(*) AS c FROM ip_log WHERE accessed >= ?`,
[
new Date(Date.now() - 86_400_000)
.toISOString()
.slice(0, 19)
.replace("T", " "),
],
);
stats = {
visits: Number(visits?.c ?? 0),
visitors: Number(visitors?.c ?? 0),
countries: Number(countries?.c ?? 0),
last24h: Number(recent?.c ?? 0),
};
} catch {
/* stats are best-effort */
}
res.render(
"admin/dashboard",
getPageVariables(req, { endpoint, links, stats }),
);
});
adminRouter.get("/meta-editor", (req, res) => {
res.render("admin/meta-editor", getPageVariables(req, { endpoint }));
});
adminRouter.post("/edit-meta", async (req, res) => {
const body = req.body || {};
const newConfig = { ...getConfig() };
if (typeof body.title === "string") {
newConfig.title = body.title;
}
if (typeof body.titleShort === "string") {
newConfig.titleShort = body.titleShort;
}
if (typeof body.description === "string") {
newConfig.description = body.description;
}
const bioEntries = Object.entries(body)
.filter((e) => /^\d+$/.test(e[0]))
.map((e) => [parseInt(e[0], 10), e[1]]) as [number, string][];
newConfig.bio = [
...bioEntries.sort((a, b) => (a[0] > b[0] ? 1 : -1)).map((e) => e[1]),
body.new,
]
.map((e) => String(e ?? "").trim())
.filter((e) => e);
await updateConfig(newConfig);
res.redirect(`${endpoint}/meta-editor`);
});
const rencodeImageWebP = async (buffer: Buffer) => {
const type = await FileType.fileTypeFromBuffer(new Uint8Array(buffer));
if (!type || !type.mime.startsWith("image/")) {
throw new Error("Not an image");
}
const webpBuffer = await sharp(buffer).webp({ lossless: true }).toBuffer();
return webpBuffer;
};
const rencodeImagePngP = async (buffer: Buffer) => {
const type = await FileType.fileTypeFromBuffer(new Uint8Array(buffer));
if (!type || !type.mime.startsWith("image/")) {
throw new Error("Not an image");
}
const webpBuffer = await sharp(buffer).png({}).toBuffer();
return webpBuffer;
};
adminRouter.post(
"/update/background",
upload.single("background"),
async (req, res) => {
try {
if (req.file) {
const webPBuffer = await rencodeImageWebP(req.file.buffer);
await fs.promises.mkdir(LOCATION_SITE, { recursive: true });
const location = path.join(LOCATION_SITE, "background.webp");
await fs.promises.writeFile(location, new Uint8Array(webPBuffer));
}
} catch (error) {
console.error("Failed to update background:", error);
}
return res.redirect(`${endpoint}/meta-editor`);
},
);
adminRouter.post(
"/update/avatar",
upload.single("avatar"),
async (req, res) => {
try {
if (req.file) {
const webPBuffer = await rencodeImageWebP(req.file.buffer);
const pngPBuffer = await rencodeImagePngP(req.file.buffer);
await fs.promises.mkdir(LOCATION_SITE, { recursive: true });
const location = path.join(LOCATION_SITE, "avatar.webp");
const location2 = path.join(LOCATION_SITE, "avatar.png");
await fs.promises.writeFile(location, new Uint8Array(webPBuffer));
await fs.promises.writeFile(location2, new Uint8Array(pngPBuffer));
}
} catch (error) {
console.error("Failed to update avatar:", error);
}
return res.redirect(`${endpoint}/meta-editor`);
},
);
adminRouter.post(
"/update/favicon",
upload.single("favicon"),
async (req, res) => {
try {
if (req.file) {
await fs.promises.mkdir(LOCATION_SITE, { recursive: true });
const sizes = [
{ name: "android-chrome-192x192.png", size: 192 },
{ name: "android-chrome-512x512.png", size: 512 },
{ name: "apple-touch-icon.png", size: 180 },
{ name: "favicon-16x16.png", size: 16 },
{ name: "favicon-32x32.png", size: 32 },
{ name: "favicon-48x48.png", size: 48 },
];
await Promise.all(
sizes.map((s) =>
sharp(req.file!.buffer)
.resize(s.size, s.size)
.png()
.toFile(path.join(LOCATION_SITE, s.name)),
),
);
const icoBuffer = await pngToIco([
path.join(LOCATION_SITE, "favicon-16x16.png"),
path.join(LOCATION_SITE, "favicon-32x32.png"),
path.join(LOCATION_SITE, "favicon-48x48.png"),
]);
await fs.promises.writeFile(
path.join(LOCATION_SITE, "favicon.ico"),
icoBuffer,
);
}
} catch (error) {
console.error("Failed to update favicon:", error);
}
return res.redirect(`${endpoint}/meta-editor`);
},
);
const removeCustomFonts = async () => {
const entries = await fs.promises
.readdir(LOCATION_FONTS)
.catch(() => [] as string[]);
await Promise.all(
entries
.filter((entry) => entry.startsWith(SITE_FONT_PREFIX))
.map((entry) =>
fs.promises.rm(path.join(LOCATION_FONTS, entry), { force: true }),
),
);
};
adminRouter.post("/update/font", upload.single("font"), async (req, res) => {
try {
if (req.file) {
const type = await FileType.fileTypeFromBuffer(
new Uint8Array(req.file.buffer),
);
if (type && type.mime.startsWith("font/")) {
await fs.promises.mkdir(LOCATION_FONTS, { recursive: true });
await removeCustomFonts();
const file = `${SITE_FONT_PREFIX}${type.ext}`;
await fs.promises.writeFile(
path.join(LOCATION_FONTS, file),
req.file.buffer,
);
const newConfig = { ...getConfig() };
newConfig.font = {
file,
family: SITE_FONT_FAMILY,
name: req.file.originalname,
updated: Date.now(),
};
await updateConfig(newConfig);
} else {
console.error("Failed to update font: unsupported file type");
}
}
} catch (error) {
console.error("Failed to update font:", error);
}
return res.redirect(`${endpoint}/meta-editor`);
});
adminRouter.post("/remove/font", async (_req, res) => {
try {
await removeCustomFonts();
const newConfig = { ...getConfig() };
delete newConfig.font;
await updateConfig(newConfig);
} catch (error) {
console.error("Failed to remove font:", error);
}
return res.redirect(`${endpoint}/meta-editor`);
});
adminRouter.get("/logout", (_req, res) => {
res.clearCookie("id");
res.redirect(`${endpoint}/login`);
});
adminRouter.get("/icon-editor", async (req, res) => {
const iconDirectory = getDatabase().getRepository(IconDirectory);
const icons = await iconDirectory.find();
res.render("admin/icon-editor", getPageVariables(req, { endpoint, icons }));
});
adminRouter.post("/add-icon", upload.single("icon"), async (req, res) => {
try {
if (req.file && req.body.alt) {
const icon = new IconDirectory();
const webPBuffer = await rencodeImageWebP(req.file.buffer);
const { name } = generateNonExistingId(LOCATION_ICONS, "webp", 32);
icon.alt = req.body.alt;
icon.path = name;
icon.name =
req.body.alt + (getExtension(req.file.originalname) || ".bin");
const iconDirectory = getDatabase().getRepository(IconDirectory);
const iconLocation = path.join(LOCATION_ICONS, name);
await fs.promises.writeFile(iconLocation, webPBuffer);
try {
await iconDirectory.save(icon);
} catch (error) {
await fs.promises.rm(iconLocation);
console.error(error);
}
}
} catch (error) {
console.error(error);
}
return res.redirect(`${endpoint}/icon-editor`);
});
adminRouter.post("/edit-alt-text-icon", async (req, res) => {
if (req.body.id && req.body.alt) {
const iconDirectory = getDatabase().getRepository(IconDirectory);
const image = await iconDirectory.findOne({
where: {
id: req.body.id,
},
});
if (image) {
image.alt = req.body.alt;
await iconDirectory.save(image);
}
}
return res.redirect(`${endpoint}/icon-editor`);
});
adminRouter.post("/delete-icon", async (req, res) => {
if (req.body.id) {
const iconDirectory = getDatabase().getRepository(IconDirectory);
const image = await iconDirectory.findOne({
where: {
id: req.body.id,
},
});
if (image) {
const iconLocation = path.join(LOCATION_ICONS, image.path);
if (fs.existsSync(iconLocation)) {
await fs.promises.rm(iconLocation);
await iconDirectory.remove(image);
}
}
}
return res.redirect(`${endpoint}/icon-editor`);
});
createLinkEditor(adminRouter, endpoint);
createProjectEditor(adminRouter, endpoint);
createBadgeEditor(adminRouter, endpoint);
createUrlRedirectEditor(adminRouter, endpoint);
createGalleryEditor(adminRouter, endpoint);
createStorageEditor(adminRouter, endpoint);
createAccessCodeEditor(adminRouter, endpoint);
createStalker(adminRouter, endpoint);
createAnalytics(adminRouter, endpoint);
if (cfg.stats) {
adminRouter.get(`/stats-today-${cfg.stats.today}/`, async (_req, res) => {
const folder = prepareLogFolder();
try {
const logs = await fs.promises.readFile(path.join(folder, `logs.txt`));
res.end(logs);
} catch {
res.end("no logs for today");
}
});
adminRouter.get(
`/stats-today-${cfg.stats.today}/real`,
async (_req, res) => {
const folder = prepareLogFolder();
try {
const logs = await fs.promises.readFile(
path.join(folder, `science.txt`),
);
res.end(logs);
} catch {
res.end("no logs for today");
}
},
);
adminRouter.get(
`/stats-today-${cfg.stats.today}/real/:date`,
async (req, res) => {
if (req.params.date && req.params.date.includes(".")) {
return res.end("no logs for specified date");
}
const folder = getAndPrepareLogFolder(req.params.date);
try {
const logs = await fs.promises.readFile(
path.join(folder, `science.txt`),
);
res.end(logs);
} catch {
res.end("no logs for today");
}
},
);
adminRouter.get(
`/stats-today-${cfg.stats.today}/:date`,
async (req, res) => {
if (req.params.date && req.params.date.includes(".")) {
return res.end("no logs for specified date");
}
const folder = getAndPrepareLogFolder(req.params.date);
try {
const logs = await fs.promises.readFile(
path.join(folder, `logs.txt`),
);
res.end(logs);
} catch {
return res.end("no logs for specified date");
}
},
);
adminRouter.get(`/stats-trace-${cfg.stats.trace}/:id`, async (req, res) => {
const folder = prepareLogFolder();
const logs = await fs.promises
.readFile(path.join(folder, req.params.id, `logs.txt`), "utf8")
.catch(() => "No logs");
const script = await fs.promises
.readFile(path.join(folder, req.params.id, `script-dump.txt`), "utf8")
.catch(() => "No script dumps");
res.end(`${logs}\n${script.substring(0, 8192)}`);
});
adminRouter.get(
`/stats-overall-${cfg.stats.overall}`,
async (_req, res) => {
const dirs = await fs.promises.readdir("./logs");
let dailyReport = "";
for (const dir of dirs.reverse()) {
try {
const daily = await fs.promises.readFile(
`./logs/${dir}/science.txt`,
"utf8",
);
const lines = daily.split("\n");
const ips = lines
.map((e) =>
e.match(/\[\d+-\d+-\d+ \d+:\d+:\d+\] \[([0-9.A-z:]+)\]/),
)
.filter((e) => e)
.map((e) => (e as any)[1]);
const domains = lines.map((e) => {
const secondSpace = e.indexOf(" ", e.indexOf("] [") + 4);
return e.substring(secondSpace + 1);
});
const ipCount = new Map<string, number>();
for (const ip of ips) {
let i = ipCount.get(ip) || 0;
i++;
ipCount.set(ip, i);
}
const domainsCount = new Map<string, number>();
for (const domain of domains) {
if (domain && domain !== "undefined") {
let i = domainsCount.get(domain) || 0;
i++;
domainsCount.set(domain, i);
}
}
dailyReport += `${dir}\n`;
dailyReport += `IPS:\n`;
for (const [ip, count] of Array.from(ipCount)) {
dailyReport += ` ${ip}: ${count}\n`;
}
dailyReport += `DOMAINS:\n`;
for (const [domain, count] of Array.from(domainsCount)) {
dailyReport += ` ${domain}: ${count}\n`;
}
dailyReport += "\n";
} catch {
/* ignore */
}
}
res.end(dailyReport);
},
);
}
return adminRouter;
}
+348
View File
@@ -0,0 +1,348 @@
import type { Router } from "express";
import { getDatabase } from "../../config";
import { getPageVariables } from "../../page-variables";
import { parseIpData, parseUserAgent } from "../../lib/ip-info";
interface CountRow {
c: number;
}
interface UrlRow {
url: string;
c: number;
}
interface GeoRow {
country: string | null;
code: string | null;
c: number;
}
interface ProviderRow {
provider: string | null;
c: number;
}
interface DayRow {
d: string;
c: number;
}
interface HourRow {
h: number;
c: number;
}
interface HeatRow {
dow: number;
h: number;
c: number;
}
interface UaRow {
ua: string;
c: number;
}
interface IpRow {
id: number;
ip: string;
data: string | null;
c: number;
}
const RANGE_DAYS: Record<string, number> = {
"7d": 7,
"30d": 30,
"90d": 90,
};
function resolveRange(query: Record<string, unknown>) {
const range =
typeof query.range === "string" && query.range ? query.range : "30d";
if (range === "all") {
return { range, from: null as Date | null, to: null as Date | null };
}
if (range === "custom") {
const from =
typeof query.start === "string" && query.start
? new Date(`${query.start}T00:00:00`)
: null;
const to =
typeof query.end === "string" && query.end
? new Date(`${query.end}T23:59:59.999`)
: null;
return { range, from, to };
}
const days = RANGE_DAYS[range] ?? 30;
return {
range: days === 30 ? "30d" : range,
from: new Date(Date.now() - days * 86_400_000),
to: null as Date | null,
};
}
const toSqlDate = (d: Date) => d.toISOString().slice(0, 19).replace("T", " ");
export function createAnalytics(adminRouter: Router, endpoint: string) {
const db = getDatabase();
adminRouter.get("/analytics", async (req, res) => {
const { range, from, to } = resolveRange(
req.query as Record<string, unknown>,
);
// Shared date filter for the ip_log table (aliased as `l`).
const dateConds: string[] = [];
const dateParams: unknown[] = [];
if (from) {
dateConds.push("l.accessed >= ?");
dateParams.push(toSqlDate(from));
}
if (to) {
dateConds.push("l.accessed <= ?");
dateParams.push(toSqlDate(to));
}
// Build a WHERE clause combining the date filter with extra (param-free) conditions.
const where = (extra: string[] = []) => {
const all = [...dateConds, ...extra];
return {
sql: all.length ? `WHERE ${all.join(" AND ")}` : "",
params: dateParams,
};
};
const query = <T>(sql: string, params: unknown[] = []) =>
db.query(sql, params) as Promise<T[]>;
const [
kpiRows,
spanRows,
countryCountRows,
urlRows,
geoRows,
providerRows,
dayRows,
hourRows,
heatRows,
uaRows,
ipRows,
] = await Promise.all([
query<{ totalVisits: number; uniqueIps: number; uniqueUrls: number }>(
`SELECT COUNT(*) AS totalVisits,
COUNT(DISTINCT l."ipRefId") AS uniqueIps,
COUNT(DISTINCT CASE WHEN l.url IS NOT NULL AND l.url != '' THEN l.url END) AS uniqueUrls
FROM ip_log l ${where().sql}`,
where().params,
),
query<{ f: string | null; t: string | null }>(
`SELECT MIN(l.accessed) AS f, MAX(l.accessed) AS t FROM ip_log l ${where().sql}`,
where().params,
),
query<CountRow>(
`SELECT COUNT(DISTINCT json_extract(ip.data, '$.country')) AS c
FROM ip_log l JOIN ip ON ip.id = l."ipRefId"
${where(["json_valid(ip.data)", "json_extract(ip.data, '$.country') != ''"]).sql}`,
where([
"json_valid(ip.data)",
"json_extract(ip.data, '$.country') != ''",
]).params,
),
query<UrlRow>(
`SELECT l.url AS url, COUNT(*) AS c
FROM ip_log l ${where(["l.url IS NOT NULL", "l.url != ''"]).sql}
GROUP BY l.url ORDER BY c DESC LIMIT 15`,
where(["l.url IS NOT NULL", "l.url != ''"]).params,
),
query<GeoRow>(
`SELECT json_extract(ip.data, '$.country') AS country,
json_extract(ip.data, '$.countryCode') AS code,
COUNT(*) AS c
FROM ip_log l JOIN ip ON ip.id = l."ipRefId"
${where(["json_valid(ip.data)", "json_extract(ip.data, '$.country') != ''"]).sql}
GROUP BY country, code ORDER BY c DESC LIMIT 12`,
where([
"json_valid(ip.data)",
"json_extract(ip.data, '$.country') != ''",
]).params,
),
query<ProviderRow>(
`SELECT COALESCE(
NULLIF(json_extract(ip.data, '$.isp'), ''),
NULLIF(json_extract(ip.data, '$.org'), ''),
NULLIF(json_extract(ip.data, '$.as'), '')
) AS provider,
COUNT(*) AS c
FROM ip_log l JOIN ip ON ip.id = l."ipRefId"
${where(["json_valid(ip.data)"]).sql}
GROUP BY provider HAVING provider IS NOT NULL ORDER BY c DESC LIMIT 12`,
where(["json_valid(ip.data)"]).params,
),
query<DayRow>(
`SELECT strftime('%Y-%m-%d', l.accessed) AS d, COUNT(*) AS c
FROM ip_log l ${where().sql}
GROUP BY d ORDER BY d`,
where().params,
),
query<HourRow>(
`SELECT CAST(strftime('%H', l.accessed) AS INTEGER) AS h, COUNT(*) AS c
FROM ip_log l ${where().sql}
GROUP BY h ORDER BY h`,
where().params,
),
query<HeatRow>(
`SELECT CAST(strftime('%w', l.accessed) AS INTEGER) AS dow,
CAST(strftime('%H', l.accessed) AS INTEGER) AS h,
COUNT(*) AS c
FROM ip_log l ${where().sql}
GROUP BY dow, h`,
where().params,
),
query<UaRow>(
`SELECT l."userAgent" AS ua, COUNT(*) AS c
FROM ip_log l ${where(['l."userAgent" IS NOT NULL', "l.\"userAgent\" != ''"]).sql}
GROUP BY l."userAgent"`,
where(['l."userAgent" IS NOT NULL', "l.\"userAgent\" != ''"]).params,
),
query<IpRow>(
`SELECT ip.id AS id, ip.ip AS ip, ip.data AS data, COUNT(*) AS c
FROM ip_log l JOIN ip ON ip.id = l."ipRefId"
${where().sql}
GROUP BY ip.id ORDER BY c DESC LIMIT 10`,
where().params,
),
]);
const kpi = kpiRows[0] ?? { totalVisits: 0, uniqueIps: 0, uniqueUrls: 0 };
const span = spanRows[0] ?? { f: null, t: null };
// Daily series, padded so the chart shows a continuous timeline.
const daysStart = from ? new Date(from) : null;
const daysEnd = to ? new Date(to) : new Date();
const dayMap = new Map(dayRows.map((r) => [r.d, Number(r.c)]));
const daily: Array<{ date: string; label: string; count: number }> = [];
if (daysStart) {
const cursor = new Date(daysStart);
cursor.setHours(0, 0, 0, 0);
const end = new Date(daysEnd);
end.setHours(23, 59, 59, 999);
while (cursor <= end && daily.length < 120) {
const key = cursor.toISOString().slice(0, 10);
daily.push({
date: key,
label: key.slice(5),
count: dayMap.get(key) ?? 0,
});
cursor.setDate(cursor.getDate() + 1);
}
} else {
for (const row of dayRows) {
daily.push({
date: row.d,
label: row.d.slice(5),
count: Number(row.c),
});
}
}
const hourly = Array.from({ length: 24 }, (_, h) => ({
hour: h,
count: Number(hourRows.find((r) => Number(r.h) === h)?.c ?? 0),
}));
const heatmap = Array.from({ length: 7 }, () =>
Array.from({ length: 24 }, () => 0),
);
let heatMax = 0;
for (const row of heatRows) {
const dow = Number(row.dow);
const h = Number(row.h);
const c = Number(row.c);
if (heatmap[dow] && h >= 0 && h < 24) {
heatmap[dow][h] = c;
heatMax = Math.max(heatMax, c);
}
}
// Aggregate raw user agents into browser / OS / device distributions.
const browsers = new Map<string, number>();
const operatingSystems = new Map<string, number>();
const devices = new Map<string, number>();
for (const row of uaRows) {
const parsed = parseUserAgent(row.ua);
const c = Number(row.c);
browsers.set(parsed.browser, (browsers.get(parsed.browser) ?? 0) + c);
operatingSystems.set(
parsed.os,
(operatingSystems.get(parsed.os) ?? 0) + c,
);
if (parsed.device) {
devices.set(parsed.device, (devices.get(parsed.device) ?? 0) + c);
}
}
const toRanked = (map: Map<string, number>, limit = 10) =>
Array.from(map.entries())
.map(([name, count]) => ({ name, count }))
.sort((a, b) => b.count - a.count)
.slice(0, limit);
const topIps = ipRows.map((row) => ({
id: row.id,
ip: row.ip,
count: Number(row.c),
info: parseIpData({ data: row.data }),
}));
const peakHour = hourly.reduce(
(best, cur) => (cur.count > best.count ? cur : best),
{ hour: 0, count: 0 },
);
const busiestDay = daily.reduce(
(best, cur) => (cur.count > best.count ? cur : best),
{ date: "-", label: "-", count: 0 },
);
res.render(
"admin/analytics",
getPageVariables(req, {
endpoint,
range,
from: from ? from.toISOString().slice(0, 10) : "",
to: to ? to.toISOString().slice(0, 10) : "",
kpi: {
totalVisits: Number(kpi.totalVisits),
uniqueIps: Number(kpi.uniqueIps),
uniqueUrls: Number(kpi.uniqueUrls),
countries: Number(countryCountRows[0]?.c ?? 0),
},
span: {
first: span.f,
last: span.t,
},
topUrls: urlRows.map((r) => ({ url: r.url, count: Number(r.c) })),
topCountries: geoRows.map((r) => ({
country: r.country ?? "Unknown",
code: r.code ?? "",
count: Number(r.c),
})),
topProviders: providerRows.map((r) => ({
provider: r.provider ?? "Unknown",
count: Number(r.c),
})),
browsers: toRanked(browsers),
operatingSystems: toRanked(operatingSystems),
devices: toRanked(devices),
daily,
hourly,
heatmap,
heatMax,
peakHour,
busiestDay,
topIps,
}),
);
});
}
+135
View File
@@ -0,0 +1,135 @@
import type { Response, Router } from "express";
import { getConfig, getDatabase, updateConfig } from "../../config";
import { IconDirectory } from "../../db/icon-directory";
import type { Config } from "../../interfaces";
import { getPageVariables } from "../../page-variables";
export async function modifyConfig(update: (cfg: Config) => void) {
const cfg = { ...getConfig() };
update(cfg);
await updateConfig(cfg);
}
export function swapArrayItems<T>(array: T[], index: number, offset: number) {
const target = index + offset;
if (array[index] !== undefined && array[target] !== undefined) {
[array[index], array[target]] = [array[target], array[index]];
}
}
export function withParsedIndex(
id: unknown,
next: (index: number) => Promise<void> | void,
) {
const index = parseInt(String(id), 10);
if (!isNaN(index)) {
return next(index);
}
}
export async function findIconById(id: string) {
if (!id) {
return undefined;
}
const iconDirectory = getDatabase().getRepository(IconDirectory);
return iconDirectory.findOne({
where: {
id: parseInt(id, 10),
},
});
}
export async function getIconPath(id: string) {
const icon = await findIconById(id);
return icon ? `/assets/images/${icon.path}` : undefined;
}
type ConfigListKey = "links" | "projects" | "badges" | "redirects";
interface ConfigListEditorOptions<T> {
resource: string;
editorPage: string;
template: string;
listKey: ConfigListKey;
buildItem: (body: Record<string, unknown>, iconPath?: string) => T;
useIcon?: boolean;
allowMove?: boolean;
}
export function createConfigListEditor<T>(
adminRouter: Router,
endpoint: string,
options: ConfigListEditorOptions<T>,
) {
const {
resource,
editorPage,
template,
listKey,
buildItem,
useIcon = false,
allowMove = false,
} = options;
const redirect = (res: Response) => res.redirect(`${endpoint}/${editorPage}`);
adminRouter.get(`/${editorPage}`, async (req, res) => {
const iconDirectory = getDatabase().getRepository(IconDirectory);
const icons = await iconDirectory.find();
res.render(template, getPageVariables(req, { endpoint, icons }));
});
adminRouter.post(`/${resource}/add`, async (req, res) => {
const iconPath = useIcon ? await getIconPath(req.body.icon) : undefined;
await modifyConfig((cfg) => {
(cfg[listKey] as T[]).push(buildItem(req.body, iconPath));
});
return redirect(res);
});
adminRouter.post(`/${resource}/edit`, async (req, res) => {
const index = parseInt(req.body.id, 10);
if (!isNaN(index)) {
const iconPath = useIcon ? await getIconPath(req.body.icon) : undefined;
await modifyConfig((cfg) => {
const list = cfg[listKey] as T[];
if (list[index]) {
list[index] = buildItem(req.body, iconPath);
}
});
}
return redirect(res);
});
adminRouter.post(`/${resource}/delete`, async (req, res) => {
await withParsedIndex(req.body.id, async (index) => {
await modifyConfig((cfg) => {
const list = cfg[listKey] as T[];
if (list[index]) {
list.splice(index, 1);
}
});
});
return redirect(res);
});
if (allowMove) {
adminRouter.post(`/${resource}/move/up`, async (req, res) => {
await withParsedIndex(req.body.id, async (index) => {
await modifyConfig((cfg) => {
swapArrayItems(cfg[listKey] as T[], index, -1);
});
});
return redirect(res);
});
adminRouter.post(`/${resource}/move/down`, async (req, res) => {
await withParsedIndex(req.body.id, async (index) => {
await modifyConfig((cfg) => {
swapArrayItems(cfg[listKey] as T[], index, 1);
});
});
return redirect(res);
});
}
}
+479
View File
@@ -0,0 +1,479 @@
import type { Router, Request } from "express";
import { getPageVariables } from "../../page-variables";
import { getDatabase } from "../../config";
import { GalleryImage } from "../../db/image-gallery";
import multer from "multer";
import fs from "fs";
import crypto from "crypto";
import FileType from "file-type";
import { generateNonExistingId } from "../../utils";
import { LOCATION_IMAGES, LOCATION_THUMBNAILS } from "../../const";
import { Artist } from "../../db/artists";
import {
createThumbnail,
createVideoThumbnail,
createAnimatedImageThumbnail,
} from "../../lib/thumbnail";
import { parseCreatedDate, toTags } from "../../lib/tags";
import { applySearchFilter } from "../../lib/search-query";
import { getPagination, parsePageQuery } from "../../lib/pagination";
import { joinLocation, removeFilesIfExist } from "../../lib/files";
function updateImage(image: GalleryImage, req: Request) {
image.name = req.body.name;
image.description = req.body.description;
image.sources = toTags(req.body.sources);
image.accessCodes = toTags(req.body.accessCodes);
image.tags = toTags(req.body.tags);
image.artists = toTags(req.body.artists);
image.createdAt = parseCreatedDate(req.body.created);
image.uploadedAt = new Date();
image.editedAt = new Date();
}
interface ProcessingJob {
id: string;
status: "uploading" | "processing" | "done" | "error";
progress: number;
message: string;
redirectUrl?: string;
error?: string;
fileBuffer: Buffer;
formBody: Record<string, string>;
}
const processingJobs = new Map<string, ProcessingJob>();
export function createGalleryEditor(adminRouter: Router, endpoint: string) {
const upload = multer({ storage: multer.memoryStorage() });
const galleyDirectory = getDatabase().getRepository(GalleryImage);
const artistDirectory = getDatabase().getRepository(Artist);
// Step 1: Upload file and return job ID immediately
adminRouter.post(
"/gallery/upload",
upload.single("image"),
async (req, res) => {
if (!req.file || !req.body) {
return res.status(400).json({ error: "No file uploaded" });
}
const jobId = crypto.randomUUID();
const job: ProcessingJob = {
id: jobId,
status: "processing",
progress: 0,
message: "File received. Starting processing...",
fileBuffer: req.file.buffer,
formBody: req.body as Record<string, string>,
};
processingJobs.set(jobId, job);
// Start processing in background
processJob(jobId).catch(() => {});
return res.json({ jobId });
},
);
// Step 2: SSE endpoint for progress updates
adminRouter.get("/gallery/progress/:jobId", (req, res) => {
const job = processingJobs.get(req.params.jobId);
if (!job) {
return res.status(404).json({ error: "Job not found" });
}
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
res.setHeader("X-Accel-Buffering", "no");
res.flushHeaders();
const sendProgress = () => {
const data = {
status: job.status,
progress: job.progress,
message: job.message,
redirectUrl: job.redirectUrl,
error: job.error,
};
res.write(`data: ${JSON.stringify(data)}\n\n`);
if (job.status === "done" || job.status === "error") {
res.end();
processingJobs.delete(job.id);
}
};
sendProgress();
const interval = setInterval(() => {
sendProgress();
}, 500);
req.on("close", () => {
clearInterval(interval);
});
});
async function processJob(jobId: string) {
const job = processingJobs.get(jobId);
if (!job) {
return;
}
try {
job.message = "Detecting file type...";
job.progress = 10;
const type = await FileType.fileTypeFromBuffer(
new Uint8Array(job.fileBuffer),
);
const mime = type?.mime ?? "";
const isVideo = mime.startsWith("video/");
const isAnimatedImage = mime === "image/gif" || mime === "image/webp";
let thumbnail: Buffer;
let videoDuration: number | null = null;
if (isVideo) {
job.message = "Processing video (extracting frame & duration)...";
job.progress = 30;
const result = await createVideoThumbnail(job.fileBuffer);
thumbnail = result.thumbnail;
videoDuration = result.duration;
job.message = `Video processed. Duration: ${videoDuration.toFixed(1)}s`;
job.progress = 70;
} else if (isAnimatedImage) {
job.message = "Processing animated image...";
job.progress = 30;
const result = await createAnimatedImageThumbnail(job.fileBuffer);
thumbnail = result.thumbnail;
videoDuration = result.duration;
job.message = `Animated image processed. Duration: ${videoDuration.toFixed(1)}s`;
job.progress = 70;
} else {
job.message = "Generating thumbnail...";
job.progress = 30;
thumbnail = await createThumbnail(job.fileBuffer);
job.message = "Thumbnail generated";
job.progress = 70;
}
job.message = "Saving files to disk...";
job.progress = 80;
const imageLoc = generateNonExistingId(
LOCATION_IMAGES,
type?.ext ?? "bin",
32,
);
const thumbnailLoc = generateNonExistingId(
LOCATION_THUMBNAILS,
"webp",
32,
);
const image = new GalleryImage();
image.name = job.formBody.name || "";
image.description = job.formBody.description || "";
image.sources = toTags(job.formBody.sources);
image.accessCodes = toTags(job.formBody.accessCodes);
image.tags = toTags(job.formBody.tags);
image.artists = toTags(job.formBody.artists);
image.createdAt = parseCreatedDate(job.formBody.created);
image.uploadedAt = new Date();
image.editedAt = new Date();
image.imageName = imageLoc.name;
image.thumbnailName = thumbnailLoc.name;
image.isVideo = isVideo || isAnimatedImage;
image.videoDuration = videoDuration;
image.videoThumbnailName =
isVideo || isAnimatedImage ? thumbnailLoc.name : null;
await fs.promises.writeFile(imageLoc.path, job.fileBuffer);
await fs.promises.writeFile(thumbnailLoc.path, thumbnail);
job.message = "Saving to database...";
job.progress = 95;
await galleyDirectory.save(image);
job.status = "done";
job.progress = 100;
job.message = "Upload complete!";
job.redirectUrl = `${endpoint}/gallery-edit/${image.id}`;
} catch (err) {
job.status = "error";
job.error = err instanceof Error ? err.message : "Unknown error";
job.message = "Processing failed";
}
}
// Legacy endpoint for direct upload (keeps backward compatibility)
adminRouter.post("/gallery/add", upload.single("image"), async (req, res) => {
if (req.file && req.body) {
try {
const type = await FileType.fileTypeFromBuffer(
new Uint8Array(req.file.buffer),
);
const mime = type?.mime ?? "";
const isVideo = mime.startsWith("video/");
const isAnimatedImage = mime === "image/gif" || mime === "image/webp";
let thumbnail: Buffer;
let videoDuration: number | null = null;
if (isVideo) {
const result = await createVideoThumbnail(req.file.buffer);
thumbnail = result.thumbnail;
videoDuration = result.duration;
} else if (isAnimatedImage) {
const result = await createAnimatedImageThumbnail(req.file.buffer);
thumbnail = result.thumbnail;
videoDuration = result.duration;
} else {
thumbnail = await createThumbnail(req.file.buffer);
}
const imageLoc = generateNonExistingId(
LOCATION_IMAGES,
type?.ext ?? "bin",
32,
);
const thumbnailLoc = generateNonExistingId(
LOCATION_THUMBNAILS,
"webp",
32,
);
const image = new GalleryImage();
image.name = req.body.name || "";
image.description = req.body.description || "";
image.sources = toTags(req.body.sources);
image.accessCodes = toTags(req.body.accessCodes);
image.tags = toTags(req.body.tags);
image.artists = toTags(req.body.artists);
image.createdAt = parseCreatedDate(req.body.created);
image.uploadedAt = new Date();
image.editedAt = new Date();
image.imageName = imageLoc.name;
image.thumbnailName = thumbnailLoc.name;
image.isVideo = isVideo || isAnimatedImage;
image.videoDuration = videoDuration;
image.videoThumbnailName =
isVideo || isAnimatedImage ? thumbnailLoc.name : null;
await fs.promises.writeFile(imageLoc.path, req.file.buffer);
await fs.promises.writeFile(thumbnailLoc.path, thumbnail);
await galleyDirectory.save(image);
res.redirect(`${endpoint}/gallery-edit/${image.id}`);
return;
} catch {
res.redirect(`${endpoint}/gallery-add/`);
return;
}
}
res.redirect(`${endpoint}/`);
});
adminRouter.get("/gallery-add", async (req, res) => {
res.render(
"admin/gallery/gallery-add",
getPageVariables(req, { endpoint }),
);
});
adminRouter.get("/gallery-editor", async (req, res) => {
const search = (req.query.search as string) || "";
const mode = (req.query.mode as string) || "general";
const paginationInput = parsePageQuery(req.query.page);
const galleryQB = applySearchFilter(
galleyDirectory.createQueryBuilder("img"),
"img",
search,
mode,
);
const totalImages = await galleryQB.getCount();
const pagination = getPagination(paginationInput, totalImages);
const images = await galleryQB
.orderBy("img.id", "ASC")
.skip(pagination.skip)
.take(pagination.limit)
.getMany();
res.render(
"admin/gallery/gallery-editor",
getPageVariables(req, {
search,
mode,
endpoint,
currentPage: pagination.currentPage,
totalPages: pagination.totalPages,
totalImages: pagination.totalItems,
images,
}),
);
});
adminRouter.post("/gallery/add", upload.single("image"), async (req, res) => {
if (req.file && req.body) {
const image = new GalleryImage();
const type = await FileType.fileTypeFromBuffer(
new Uint8Array(req.file.buffer),
);
const mime = type?.mime ?? "";
const isVideo = mime.startsWith("video/");
const isAnimatedImage = mime === "image/gif" || mime === "image/webp";
let thumbnail: Buffer;
let videoDuration: number | null = null;
if (isVideo) {
const result = await createVideoThumbnail(req.file.buffer);
thumbnail = result.thumbnail;
videoDuration = result.duration;
} else if (isAnimatedImage) {
const result = await createAnimatedImageThumbnail(req.file.buffer);
thumbnail = result.thumbnail;
videoDuration = result.duration;
} else {
thumbnail = await createThumbnail(req.file.buffer);
}
const imageLoc = generateNonExistingId(
LOCATION_IMAGES,
type?.ext ?? "bin",
32,
);
const thumbnailLoc = generateNonExistingId(
LOCATION_THUMBNAILS,
"webp",
32,
);
updateImage(image, req);
image.imageName = imageLoc.name;
image.thumbnailName = thumbnailLoc.name;
image.isVideo = isVideo || isAnimatedImage;
image.videoDuration = videoDuration;
image.videoThumbnailName =
isVideo || isAnimatedImage ? thumbnailLoc.name : null;
await fs.promises.writeFile(imageLoc.path, req.file.buffer);
await fs.promises.writeFile(thumbnailLoc.path, thumbnail);
await galleyDirectory.save(image);
res.redirect(`${endpoint}/gallery-edit/${image.id}`);
return;
}
res.redirect(`${endpoint}/`);
});
adminRouter.post("/gallery/edit", async (req, res) => {
if (req.body) {
const image = await galleyDirectory.findOne({
where: {
id: parseInt(req.body.id, 10),
},
});
if (image) {
updateImage(image, req);
await galleyDirectory.save(image);
res.redirect(`${endpoint}/gallery-edit/${image.id}`);
return;
}
}
res.redirect(`${endpoint}/`);
});
adminRouter.post("/gallery/delete", async (req, res) => {
if (req.body) {
const image = await galleyDirectory.findOne({
where: {
id: parseInt(req.body.id, 10),
},
});
if (image) {
await galleyDirectory.remove(image);
await removeFilesIfExist(
joinLocation(LOCATION_IMAGES, image.imageName),
joinLocation(LOCATION_THUMBNAILS, image.thumbnailName),
);
}
}
res.redirect(`${endpoint}/gallery-editor`);
});
adminRouter.get("/gallery-edit/:id", async (req, res) => {
const image = await galleyDirectory.findOne({
where: {
id: parseInt(req.params.id, 10),
},
});
res.render(
"admin/gallery/gallery-edit",
getPageVariables(req, { endpoint, image }),
);
});
adminRouter.get("/artist-editor", async (req, res) => {
const artists = await artistDirectory.find();
res.render(
"admin/artist-editor.ejs",
getPageVariables(req, { endpoint, artists }),
);
});
adminRouter.post("/artists/add", async (req, res) => {
if (req.body?.name && req.body?.tag) {
const artist = new Artist();
artist.name = req.body.name ?? "";
artist.tag = req.body.tag ?? "";
artist.urls = toTags(req.body.urls) as unknown as string;
await artistDirectory.save(artist);
}
res.redirect(`${endpoint}/artist-editor`);
});
adminRouter.post("/artists/edit", async (req, res) => {
if (req.body?.id && req.body?.name && req.body?.tag) {
const artist = await artistDirectory.findOne({
where: {
id: parseInt(req.body.id, 10),
},
});
if (artist) {
artist.name = req.body.name ?? "";
artist.tag = req.body.tag ?? "";
artist.urls = toTags(req.body.urls) as unknown as string;
await artistDirectory.save(artist);
}
}
res.redirect(`${endpoint}/artist-editor`);
});
adminRouter.post("/artists/delete", async (req, res) => {
if (req.body) {
const artist = await artistDirectory.findOne({
where: {
id: parseInt(req.body.id, 10),
},
});
if (artist) {
await artistDirectory.remove(artist);
}
}
res.redirect(`${endpoint}/artist-editor`);
});
}
+65
View File
@@ -0,0 +1,65 @@
import type { Router } from "express";
import { createConfigListEditor } from "./editor-helpers";
export function createLinkEditor(adminRouter: Router, endpoint: string) {
createConfigListEditor(adminRouter, endpoint, {
resource: "link",
editorPage: "link-editor",
template: "admin/link-editor",
listKey: "links",
useIcon: true,
allowMove: true,
buildItem: (body, iconPath) => ({
name: String(body.name ?? ""),
url: String(body.url ?? ""),
linkHidden: !!body.linkHidden,
icon: iconPath,
}),
});
}
export function createProjectEditor(adminRouter: Router, endpoint: string) {
createConfigListEditor(adminRouter, endpoint, {
resource: "project",
editorPage: "project-editor",
template: "admin/project-editor",
listKey: "projects",
useIcon: true,
allowMove: true,
buildItem: (body, iconPath) => ({
name: String(body.name ?? ""),
url: String(body.url ?? ""),
desc: String(body.description ?? ""),
linkHidden: !!body.linkHidden,
icon: iconPath,
}),
});
}
export function createBadgeEditor(adminRouter: Router, endpoint: string) {
createConfigListEditor(adminRouter, endpoint, {
resource: "badge",
editorPage: "badge-editor",
template: "admin/badge-editor",
listKey: "badges",
useIcon: true,
allowMove: true,
buildItem: (body, iconPath) => ({
name: String(body.name ?? ""),
icon: iconPath,
}),
});
}
export function createUrlRedirectEditor(adminRouter: Router, endpoint: string) {
createConfigListEditor(adminRouter, endpoint, {
resource: "redirect",
editorPage: "redirect-editor",
template: "admin/redirect-editor",
listKey: "redirects",
buildItem: (body) => ({
code: String(body.code ?? ""),
url: String(body.url ?? ""),
}),
});
}
+504
View File
@@ -0,0 +1,504 @@
import type { Router } from "express";
import { getDatabase } from "../../config";
import { IP, IpLog } from "../../db/ip";
import { getPageVariables } from "../../page-variables";
import { Between, MoreThanOrEqual, LessThanOrEqual, Raw } from "typeorm";
import { parseIpData, parseUserAgent } from "../../lib/ip-info";
export function createStalker(adminRouter: Router, endpoint: string) {
const db = getDatabase();
const ipRepo = db.getRepository(IP);
const ipRepoLog = db.getRepository(IpLog);
async function buildIpRows(ips: IP[]) {
if (ips.length === 0) {
return [];
}
const ids = ips.map((i) => i.id);
const agentRows = await ipRepoLog
.createQueryBuilder("log")
.select("log.ipRef", "ipId")
.addSelect("log.userAgent", "userAgent")
.where("log.ipRef IN (:...ids)", { ids })
.andWhere("log.userAgent IS NOT NULL")
.andWhere("log.userAgent != ''")
.distinct(true)
.getRawMany<{ ipId: number; userAgent: string }>();
const visitRows = await ipRepoLog
.createQueryBuilder("log")
.select("log.ipRef", "ipId")
.addSelect("COUNT(log.id)", "visits")
.where("log.ipRef IN (:...ids)", { ids })
.groupBy("log.ipRef")
.getRawMany<{ ipId: number; visits: string }>();
const agentsByIp = new Map<number, string[]>();
for (const row of agentRows) {
const ipId = Number(row.ipId);
const ua = row.userAgent;
if (!ua) {
continue;
}
const list = agentsByIp.get(ipId) || [];
if (!list.includes(ua)) {
list.push(ua);
}
agentsByIp.set(ipId, list);
}
const visitsByIp = new Map<number, number>();
for (const row of visitRows) {
visitsByIp.set(Number(row.ipId), Number(row.visits));
}
return ips.map((ip) => ({
...ip,
userAgents: agentsByIp.get(ip.id) || [],
visits: visitsByIp.get(ip.id) || 0,
info: parseIpData(ip),
}));
}
// list IPs with advanced search + pagination
adminRouter.get("/stalker", async (req, res) => {
const page = Math.max(parseInt((req.query.page as string) || "1", 10), 1);
const perPage = 20;
const s = (v: unknown): string => (typeof v === "string" ? v.trim() : "");
const f = (v: unknown): number | undefined => {
const n = parseFloat(s(v));
return Number.isFinite(n) ? n : undefined;
};
const FILTERS = {
q: s(req.query.q),
ip: s(req.query.ip),
ua: s(req.query.ua),
os: s(req.query.os),
device: s(req.query.device),
url: s(req.query.url),
country: s(req.query.country),
region: s(req.query.region),
city: s(req.query.city),
isp: s(req.query.isp),
org: s(req.query.org),
asn: s(req.query.asn),
start: s(req.query.start),
end: s(req.query.end),
minVisits: f(req.query.minVisits),
maxVisits: f(req.query.maxVisits),
north: f(req.query.north),
south: f(req.query.south),
east: f(req.query.east),
west: f(req.query.west),
lat: f(req.query.lat),
lon: f(req.query.lon),
radiusKm: f(req.query.radiusKm),
sort: s(req.query.sort),
};
// Build a bounding box from a center + radius (km) for geofencing.
if (
FILTERS.lat !== undefined &&
FILTERS.lon !== undefined &&
FILTERS.radiusKm !== undefined
) {
const dLat = FILTERS.radiusKm / 111.0;
const cosLat = Math.max(Math.cos((FILTERS.lat * Math.PI) / 180), 0.01);
const dLon = FILTERS.radiusKm / (111.32 * cosLat);
FILTERS.north = FILTERS.lat + dLat;
FILTERS.south = FILTERS.lat - dLat;
FILTERS.east = FILTERS.lon + dLon;
FILTERS.west = FILTERS.lon - dLon;
}
const qb = ipRepo
.createQueryBuilder("ip")
.skip((page - 1) * perPage)
.take(perPage);
// sorting: newest activity (default), oldest, or most visits
if (FILTERS.sort === "visits") {
qb.orderBy(
`(SELECT COUNT(*) FROM "ip_log" _v WHERE _v."ipRefId" = ip.id)`,
"DESC",
).addOrderBy("ip.lastUsed", "DESC");
} else if (FILTERS.sort === "oldest") {
qb.orderBy("ip.lastUsed", "ASC");
} else {
qb.orderBy("ip.lastUsed", "DESC");
}
// helper: IP must have at least one visit log matching `inner`
const logExists = (inner: string, params: Record<string, any>) => {
qb.andWhere(
`EXISTS (SELECT 1 FROM "ip_log" _l WHERE _l."ipRefId" = ip.id AND ${inner})`,
params,
);
};
// global text search: ip, user agent, route visited
if (FILTERS.q) {
logExists(
`(COALESCE(_l."userAgent",'') LIKE :qText COLLATE NOCASE OR COALESCE(_l.url,'') LIKE :qText COLLATE NOCASE)`,
{ qText: `%${FILTERS.q}%` },
);
qb.andWhere(`ip.ip LIKE :qText COLLATE NOCASE`, {
qText: `%${FILTERS.q}%`,
});
}
if (FILTERS.ip) {
qb.andWhere(`ip.ip LIKE :ipKey COLLATE NOCASE`, {
ipKey: `%${FILTERS.ip}%`,
});
}
if (FILTERS.ua) {
logExists(`COALESCE(_l."userAgent",'') LIKE :ua COLLATE NOCASE`, {
ua: `%${FILTERS.ua}%`,
});
}
// os / device map to known tokens found inside the raw user agent
const OS_TOKENS: Record<string, string[]> = {
windows: ["Windows"],
macos: ["Mac OS X", "Macintosh"],
linux: ["Linux", "X11"],
android: ["Android"],
ios: ["iPhone", "iPad", "iPod", "CPU OS", "iPhone OS"],
chromeos: ["CrOS", "ChromeOS"],
};
const DEVICE_TOKENS: Record<string, string[]> = {
mobile: ["Mobile", "iPhone", "Android"],
phone: ["Phone", "iPhone", "Mobile"],
tablet: ["iPad", "Tablet"],
desktop: ["Windows", "Macintosh", "X11", "Linux"],
};
if (FILTERS.os) {
const tokens = OS_TOKENS[FILTERS.os.toLowerCase()] || [FILTERS.os];
const params: Record<string, string> = {};
const conds = tokens.map((t, i) => {
params[`os${i}`] = `%${t}%`;
return `COALESCE(_l."userAgent",'') LIKE :os${i} COLLATE NOCASE`;
});
qb.andWhere(
`EXISTS (SELECT 1 FROM "ip_log" _l WHERE _l."ipRefId" = ip.id AND (${conds.join(
" OR ",
)}))`,
params,
);
}
if (FILTERS.device) {
const tokens = DEVICE_TOKENS[FILTERS.device.toLowerCase()] || [
FILTERS.device,
];
const params: Record<string, string> = {};
const conds = tokens.map((t, i) => {
params[`dev${i}`] = `%${t}%`;
return `COALESCE(_l."userAgent",'') LIKE :dev${i} COLLATE NOCASE`;
});
qb.andWhere(
`EXISTS (SELECT 1 FROM "ip_log" _l WHERE _l."ipRefId" = ip.id AND (${conds.join(
" OR ",
)}))`,
params,
);
}
if (FILTERS.url) {
logExists(`COALESCE(_l.url,'') LIKE :url COLLATE NOCASE`, {
url: `%${FILTERS.url}%`,
});
}
// geo filters against the stored ipinfo JSON
const geoProps: Array<[string, string, string]> = [
["country", FILTERS.country, "country"],
["regionName", FILTERS.region, "region"],
["city", FILTERS.city, "city"],
["isp", FILTERS.isp, "isp"],
["org", FILTERS.org, "org"],
["as", FILTERS.asn, "asn"],
];
for (const [prop, value, key] of geoProps) {
if (!value) {
continue;
}
qb.andWhere(
"json_extract(CASE WHEN json_valid(ip.data) THEN ip.data ELSE '{}' END, " +
`'$.${prop}') LIKE :${key} COLLATE NOCASE`,
{ [key]: `%${value}%` },
);
}
// date range on last activity
if (FILTERS.start || FILTERS.end) {
if (FILTERS.start && FILTERS.end) {
qb.andWhere("ip.lastUsed BETWEEN :dStart AND :dEnd", {
dStart: new Date(`${FILTERS.start}T00:00:00`),
dEnd: new Date(`${FILTERS.end}T23:59:59.999`),
});
} else if (FILTERS.start) {
qb.andWhere("ip.lastUsed >= :dStart", {
dStart: new Date(`${FILTERS.start}T00:00:00`),
});
} else if (FILTERS.end) {
qb.andWhere("ip.lastUsed <= :dEnd", {
dEnd: new Date(`${FILTERS.end}T23:59:59.999`),
});
}
}
// visit count bounds
if (FILTERS.minVisits !== undefined) {
qb.andWhere(
`(SELECT COUNT(*) FROM "ip_log" _l WHERE _l."ipRefId" = ip.id) >= :minVisits`,
{ minVisits: FILTERS.minVisits },
);
}
if (FILTERS.maxVisits !== undefined) {
qb.andWhere(
`(SELECT COUNT(*) FROM "ip_log" _l WHERE _l."ipRefId" = ip.id) <= :maxVisits`,
{ maxVisits: FILTERS.maxVisits },
);
}
// geofence bounding box (requires all four bounds, or derived from radius)
if (
FILTERS.north !== undefined &&
FILTERS.south !== undefined &&
FILTERS.east !== undefined &&
FILTERS.west !== undefined
) {
qb.andWhere("ip.lat IS NOT NULL AND ip.lon IS NOT NULL");
qb.andWhere("ip.lat BETWEEN :s AND :n AND ip.lon BETWEEN :w AND :e", {
s: FILTERS.south,
n: FILTERS.north,
w: FILTERS.west,
e: FILTERS.east,
});
}
const [ips, count] = await qb.getManyAndCount();
const rows = await buildIpRows(ips);
// carry filters into pagination links
const qs = new URLSearchParams(
Object.entries(FILTERS)
.filter(([, v]) => v !== undefined && v !== "")
.map(([k, v]) => [k, String(v)]),
).toString();
res.render(
"admin/stalker",
getPageVariables(req, {
endpoint,
ips: rows,
page,
pages: Math.ceil(count / perPage),
total: count,
f: FILTERS,
qs,
parseUA: parseUserAgent,
}),
);
});
// show logs for single IP
adminRouter.get("/stalker/:id", async (req, res) => {
const id = parseInt(req.params.id, 10);
const ip = await ipRepo.findOne({ where: { id } });
if (!ip) {
return res.status(404).send("IP not found");
}
const logs = await ipRepoLog.find({
where: { ipRef: { id } },
order: { accessed: "DESC" },
take: 100,
});
const userAgents: string[] = [];
for (const log of logs) {
if (log.userAgent && !userAgents.includes(log.userAgent)) {
userAgents.push(log.userAgent);
}
}
const [dailyRows, endpointRows] = await Promise.all([
db.query(
`SELECT strftime('%Y-%m-%d', accessed) AS d, COUNT(*) AS c
FROM ip_log WHERE "ipRefId" = ?
GROUP BY d ORDER BY d DESC LIMIT 14`,
[id],
) as Promise<Array<{ d: string; c: number }>>,
db.query(
`SELECT url, COUNT(*) AS c
FROM ip_log WHERE "ipRefId" = ? AND url IS NOT NULL AND url != ''
GROUP BY url ORDER BY c DESC LIMIT 8`,
[id],
) as Promise<Array<{ url: string; c: number }>>,
]);
const daily = dailyRows
.map((r) => ({ date: r.d, label: r.d.slice(5), count: Number(r.c) }))
.reverse();
const endpoints = endpointRows.map((r) => ({
url: r.url,
count: Number(r.c),
}));
res.render(
"admin/stalker-ip",
getPageVariables(req, {
endpoint,
ip,
info: parseIpData(ip),
logs: logs.map((log) => ({
id: log.id,
url: log.url,
accessed: log.accessed,
ua: parseUserAgent(log.userAgent),
})),
userAgents: userAgents.map((ua) => parseUserAgent(ua)),
totalLogs: logs.length,
daily,
endpoints,
}),
);
});
adminRouter.post("/stalker/:id/clearLogs", async (req, res) => {
const id = parseInt(req.params.id, 10);
await ipRepoLog.delete({ ipRef: { id } });
res.redirect(`${endpoint}/stalker/${id}`);
});
adminRouter.post("/stalker/:id/delete", async (req, res) => {
const id = parseInt(req.params.id, 10);
await ipRepoLog.delete({ ipRef: { id } });
await ipRepo.delete({ id });
res.redirect(`${endpoint}/stalker`);
});
adminRouter.get("/stalker-map", async (req, res) => {
const padDate = (value: string, end: boolean) =>
new Date(`${value}T${end ? "23:59:59.999" : "00:00:00"}`);
const startDate = req.query.start
? padDate(req.query.start as string, false)
: undefined;
const endDate = req.query.end
? padDate(req.query.end as string, true)
: undefined;
const where: any = {
lat: Raw((alias) => `${alias} IS NOT NULL`),
lon: Raw((alias) => `${alias} IS NOT NULL`),
};
if (startDate && endDate) {
where.lastUsed = Between(startDate, endDate);
} else if (startDate) {
where.lastUsed = MoreThanOrEqual(startDate);
} else if (endDate) {
where.lastUsed = LessThanOrEqual(endDate);
}
const ips = await ipRepo.find({
where,
order: { lastUsed: "DESC" },
});
// Aggregate visit statistics for the selected range (per country + provider).
const conds: string[] = [];
const params: unknown[] = [];
const toSqlDate = (d: Date) =>
d.toISOString().slice(0, 19).replace("T", " ");
if (startDate) {
conds.push("l.accessed >= ?");
params.push(toSqlDate(startDate));
}
if (endDate) {
conds.push("l.accessed <= ?");
params.push(toSqlDate(endDate));
}
const dateWhere = conds.length ? `WHERE ${conds.join(" AND ")}` : "";
const withDate = (extra: string) =>
`${dateWhere ? `${dateWhere} AND` : "WHERE"} ${extra}`;
const [countryRows, providerRows, visitRows] = await Promise.all([
db.query(
`SELECT json_extract(ip.data, '$.country') AS country,
json_extract(ip.data, '$.countryCode') AS code,
COUNT(*) AS c
FROM ip_log l JOIN ip ON ip.id = l."ipRefId"
${withDate("json_valid(ip.data) AND json_extract(ip.data, '$.country') != ''")}
GROUP BY country, code ORDER BY c DESC LIMIT 12`,
params,
) as Promise<Array<{ country: string; code: string; c: number }>>,
db.query(
`SELECT COALESCE(
NULLIF(json_extract(ip.data, '$.isp'), ''),
NULLIF(json_extract(ip.data, '$.org'), ''),
NULLIF(json_extract(ip.data, '$.as'), '')
) AS provider,
COUNT(*) AS c
FROM ip_log l JOIN ip ON ip.id = l."ipRefId"
${withDate("json_valid(ip.data)")}
GROUP BY provider HAVING provider IS NOT NULL ORDER BY c DESC LIMIT 12`,
params,
) as Promise<Array<{ provider: string; c: number }>>,
db.query(
`SELECT l."ipRefId" AS ipId, COUNT(*) AS c
FROM ip_log l ${dateWhere}
GROUP BY l."ipRefId"`,
params,
) as Promise<Array<{ ipId: number; c: number }>>,
]);
const visitsByIp = new Map<number, number>();
for (const row of visitRows) {
visitsByIp.set(Number(row.ipId), Number(row.c));
}
const points = ips.map((ip) => ({
id: ip.id,
ip: ip.ip,
lat: ip.lat,
lon: ip.lon,
lastUsed: ip.lastUsed,
data: ip.data,
visits: visitsByIp.get(ip.id) || 0,
}));
const countryStats = countryRows.map((r) => ({
country: r.country,
code: r.code,
count: Number(r.c),
}));
const providerStats = providerRows.map((r) => ({
provider: r.provider,
count: Number(r.c),
}));
res.render(
"admin/stalker-map",
getPageVariables(req, {
endpoint,
points,
countryStats,
providerStats,
totalVisits: visitRows.reduce((s, r) => s + Number(r.c), 0),
startDate,
endDate,
}),
);
});
}
+240
View File
@@ -0,0 +1,240 @@
import type { Router, Request } from "express";
import { getPageVariables } from "../../page-variables";
import { getDatabase } from "../../config";
import multer from "multer";
import path from "path";
import fs from "fs";
import { generateNonExistingId, getExtension } from "../../utils";
import { LOCATION_FILES, LOCATION_THUMBNAILS } from "../../const";
import { StorageFile } from "../../db/storage-file";
import { createThumbnail } from "../../lib/thumbnail";
import { parseCreatedDate, toTags } from "../../lib/tags";
import { applySearchFilter } from "../../lib/search-query";
import { getPagination, parsePageQuery } from "../../lib/pagination";
import {
joinLocation,
removeFileIfExists,
removeFilesIfExist,
} from "../../lib/files";
function updateStorageFile(file: StorageFile, req: Request) {
file.name = req.body.name;
file.description = req.body.description;
file.accessCodes = toTags(req.body.accessCodes);
file.tags = toTags(req.body.tags);
file.createdAt = parseCreatedDate(req.body.created);
file.uploadedAt = new Date();
file.editedAt = new Date();
}
async function removeStorageThumbnail(file: StorageFile) {
if (file.thumbnailName) {
await removeFileIfExists(
joinLocation(LOCATION_THUMBNAILS, file.thumbnailName),
);
}
}
export function createStorageEditor(adminRouter: Router, endpoint: string) {
const upload = multer({ storage: multer.memoryStorage() });
const storageDirectory = getDatabase().getRepository(StorageFile);
adminRouter.get("/storage-add", async (req, res) => {
res.render(
"admin/storage/storage-add",
getPageVariables(req, { endpoint }),
);
});
adminRouter.get("/storage-editor", async (req, res) => {
const search = (req.query.search as string) || "";
const mode = (req.query.mode as string) || "general";
const paginationInput = parsePageQuery(req.query.page);
const fileQB = applySearchFilter(
storageDirectory.createQueryBuilder("file"),
"file",
search,
mode,
);
const totalImages = await fileQB.getCount();
const pagination = getPagination(paginationInput, totalImages);
const files = await fileQB
.orderBy("file.id", "ASC")
.skip(pagination.skip)
.take(pagination.limit)
.getMany();
res.render(
"admin/storage/storage-editor",
getPageVariables(req, {
search,
mode,
endpoint,
currentPage: pagination.currentPage,
totalPages: pagination.totalPages,
totalImages: pagination.totalItems,
files,
}),
);
});
adminRouter.post(
"/storage/add",
upload.fields([
{ name: "thumbnail", maxCount: 1 },
{ name: "file", maxCount: 1 },
]),
async (req, res) => {
if (
req.body &&
req.files &&
typeof req.files === "object" &&
!Array.isArray(req.files)
) {
const thumbnail = req.files.thumbnail?.[0];
const fileData = req.files.file?.[0];
if (!fileData) {
res.redirect(`${endpoint}/`);
return;
}
const file = new StorageFile();
updateStorageFile(file, req);
const fileLoc = generateNonExistingId(
LOCATION_FILES,
getExtension(fileData?.originalname || ".bin") || ".bin",
32,
);
file.file = fileLoc.name;
file.fileName = fileData.originalname;
await fs.promises.writeFile(fileLoc.path, fileData.buffer);
if (thumbnail) {
const thumbnailBuffer = await createThumbnail(thumbnail.buffer);
const thumbnailLoc = generateNonExistingId(
LOCATION_THUMBNAILS,
"webp",
32,
);
file.thumbnailName = thumbnailLoc.name;
await fs.promises.writeFile(thumbnailLoc.path, thumbnailBuffer);
}
await storageDirectory.save(file);
res.redirect(`${endpoint}/storage-edit/${file.id}`);
return;
}
res.redirect(`${endpoint}/`);
},
);
adminRouter.post(
"/storage/edit",
upload.fields([
{ name: "thumbnail", maxCount: 1 },
{ name: "file", maxCount: 1 },
]),
async (req, res) => {
if (req.body || req.files) {
const file = await storageDirectory.findOne({
where: {
id: parseInt(req.body.id, 10),
},
});
if (file) {
updateStorageFile(file, req);
if (
req.files &&
typeof req.files === "object" &&
!Array.isArray(req.files)
) {
const thumbnail = req.files.thumbnail?.[0];
if (thumbnail) {
const thumbnailBuffer = await createThumbnail(thumbnail.buffer);
const thumbnailLoc = generateNonExistingId(
LOCATION_THUMBNAILS,
"webp",
32,
);
await removeStorageThumbnail(file);
file.thumbnailName = thumbnailLoc.name;
await fs.promises.writeFile(thumbnailLoc.path, thumbnailBuffer);
}
const fileData = req.files.file?.[0];
if (fileData) {
if (fileData.originalname === file.fileName) {
await fs.promises.writeFile(
path.join(LOCATION_FILES, file.file),
fileData.buffer,
);
} else {
const fileLoc = generateNonExistingId(
LOCATION_FILES,
getExtension(fileData.originalname || ".bin") || ".bin",
32,
);
await removeFileIfExists(
joinLocation(LOCATION_FILES, file.file),
);
file.file = fileLoc.name;
file.fileName = fileData.originalname!;
await fs.promises.writeFile(fileLoc.path, fileData.buffer);
}
}
}
if (req.body.removeThumbnail) {
await removeStorageThumbnail(file);
file.thumbnailName = null;
}
await storageDirectory.save(file);
res.redirect(`${endpoint}/storage-edit/${file.id}`);
return;
}
}
res.redirect(`${endpoint}/`);
},
);
adminRouter.post("/storage/delete", async (req, res) => {
if (req.body) {
const file = await storageDirectory.findOne({
where: {
id: parseInt(req.body.id, 10),
},
});
if (file) {
await storageDirectory.remove(file);
await removeFilesIfExist(
...(file.thumbnailName
? [joinLocation(LOCATION_THUMBNAILS, file.thumbnailName)]
: []),
joinLocation(LOCATION_FILES, file.file),
);
}
}
res.redirect(`${endpoint}/storage-editor`);
});
adminRouter.get("/storage-edit/:id", async (req, res) => {
const file = await storageDirectory.findOne({
where: {
id: parseInt(req.params.id, 10),
},
});
res.render(
"admin/storage/storage-edit",
getPageVariables(req, { endpoint, file }),
);
});
}
+199
View File
@@ -0,0 +1,199 @@
import type { Router, Response } from "express";
import { getPageVariables } from "../page-variables";
import { LOCATION_IMAGES, LOCATION_THUMBNAILS } from "../const";
import { getDatabase } from "../config";
import { GalleryImage } from "../db/image-gallery";
import { Artist } from "../db/artists";
import { AccessManager } from "../access-code-manager";
import { getTimeElapsed, timeToPass } from "../utils";
import { applyAccessCodeFilter, applySearchFilter } from "../lib/search-query";
import { getPagination, parsePageQuery } from "../lib/pagination";
import {
getAccessCodes,
setNoCacheHeaders,
useQuotaIfProtectedItems,
verifyProtectedAccess,
} from "../lib/access-control";
export function createGalleryRouter(router: Router) {
const galleryRepo = getDatabase().getRepository(GalleryImage);
const artistRepo = getDatabase().getRepository(Artist);
const findImageById = (id: string | number) =>
galleryRepo.findOne({
where: {
id: typeof id === "string" ? parseInt(id, 10) || 0 : id,
},
});
const render404 = (
req: Parameters<typeof getPageVariables>[0],
res: Response,
) => {
res.status(404);
res.render("404", getPageVariables(req));
};
router.get("/gallery/:id", async (req, res) => {
const image = await findImageById(req.params.id);
if (image) {
const { allowed } = await verifyProtectedAccess(
req,
image.accessCodes,
false,
);
if (allowed) {
return res.sendFile(image.imageName, { root: LOCATION_IMAGES });
}
}
render404(req, res);
});
router.get("/gallery/video/:id", async (req, res) => {
const image = await findImageById(req.params.id);
if (image && image.isVideo) {
const { allowed } = await verifyProtectedAccess(
req,
image.accessCodes,
false,
);
if (allowed) {
return res.sendFile(image.imageName, { root: LOCATION_IMAGES });
}
}
render404(req, res);
});
router.get("/gallery/view/:id", async (req, res) => {
let image = await findImageById(req.params.id);
let byId = false;
if (!image) {
byId = true;
image = await galleryRepo.findOne({
where: {
imageName: req.params.id,
},
});
}
if (!image) {
return render404(req, res);
}
const { accessCode, allowed } = await verifyProtectedAccess(
req,
image.accessCodes,
byId,
);
if (!allowed) {
return render404(req, res);
}
const artistsObjects = await Promise.all(
image.artists.map((tag) => artistRepo.findOne({ where: { tag } })),
);
const artists = artistsObjects.map((artist, index) => {
if (artist) {
return artist;
}
return {
name: image!.artists[index],
urls: [],
};
});
setNoCacheHeaders(res, accessCode);
return res.render(
"imageView",
getPageVariables(req, {
image,
createAt: getTimeElapsed(image.createdAt),
artists,
timeToPass,
accessCode,
back: req.cookies.back,
}),
);
});
router.get("/gallery", async (req, res) => {
const codeData = await AccessManager.codeOrError(req);
const specialAccess = getAccessCodes(codeData);
res.cookie("back", req.url);
const search = (req.query.search as string) || "";
const mode = (req.query.mode as string) || "general";
const paginationInput = parsePageQuery(req.query.page);
const galleryQB = applyAccessCodeFilter(
applySearchFilter(
galleryRepo.createQueryBuilder("img"),
"img",
search,
mode,
),
"img",
specialAccess,
);
const totalImages = await galleryQB.getCount();
const pagination = getPagination(paginationInput, totalImages);
const now = new Date();
const offset = (now.getDate() + now.getMonth() + now.getFullYear()) * 10000;
const finalSeed = offset;
const images = await galleryQB
.orderBy("img.id", "ASC")
.skip(pagination.skip)
.take(pagination.limit)
.orderBy(
search ? "img.id" : `ABS(MOD(img.id * ${finalSeed}, 10007))`,
"ASC",
)
.getMany();
await useQuotaIfProtectedItems(codeData, images, specialAccess);
setNoCacheHeaders(res, codeData);
res.render(
"gallery",
getPageVariables(req, {
search,
mode,
currentPage: pagination.currentPage,
totalPages: pagination.totalPages,
totalImages: pagination.totalItems,
images,
timeToPass,
accessCode: codeData,
}),
);
});
router.get("/gallery/image/:filename", (req, res) => {
res.sendFile(req.params.filename, { root: LOCATION_IMAGES }, (err) => {
if (err) {
res
.status(404)
.render("404", getPageVariables(req, { message: "Image not found" }));
}
});
});
router.get("/gallery/thumbnail/:filename", (req, res) => {
res.sendFile(req.params.filename, { root: LOCATION_THUMBNAILS }, (err) => {
if (err) {
res
.status(404)
.render(
"404",
getPageVariables(req, { message: "Thumbnail not found" }),
);
}
});
});
}
+176
View File
@@ -0,0 +1,176 @@
import type { Router, Response } from "express";
import { getPageVariables } from "../page-variables";
import { LOCATION_FILES, LOCATION_THUMBNAILS } from "../const";
import { getDatabase } from "../config";
import { AccessManager } from "../access-code-manager";
import { StorageFile } from "../db/storage-file";
import { getTimeElapsed, timeToPass } from "../utils";
import { applyAccessCodeFilter, applySearchFilter } from "../lib/search-query";
import { getPagination, parsePageQuery } from "../lib/pagination";
import {
getAccessCodes,
setNoCacheHeaders,
useQuotaIfProtectedItems,
verifyProtectedAccess,
} from "../lib/access-control";
import { joinLocation } from "../lib/files";
export function createStorageRouter(router: Router) {
const storageDirectory = getDatabase().getRepository(StorageFile);
const findFileById = (id: string | number) =>
storageDirectory.findOne({
where: {
id: typeof id === "string" ? parseInt(id, 10) || 0 : id,
},
});
const render404 = (
req: Parameters<typeof getPageVariables>[0],
res: Response,
) => {
res.status(404);
res.render("404", getPageVariables(req));
};
router.get("/storage/view/:id", async (req, res) => {
let file = await findFileById(req.params.id);
let byId = false;
if (!file) {
byId = true;
file = await storageDirectory.findOne({
where: {
file: req.params.id,
},
});
}
if (!file) {
return render404(req, res);
}
const { accessCode, allowed } = await verifyProtectedAccess(
req,
file.accessCodes,
byId,
);
if (!allowed) {
return render404(req, res);
}
setNoCacheHeaders(res, accessCode);
return res.render(
"fileView",
getPageVariables(req, {
file,
createAt: getTimeElapsed(file.createdAt),
timeToPass,
accessCode,
back: req.cookies.back,
}),
);
});
router.get("/storage", async (req, res) => {
const codeData = await AccessManager.codeOrError(req);
const specialAccess = getAccessCodes(codeData);
res.cookie("back", req.url);
const search = (req.query.search as string) || "";
const mode = (req.query.mode as string) || "general";
const paginationInput = parsePageQuery(req.query.page);
const storageQB = applyAccessCodeFilter(
applySearchFilter(
storageDirectory.createQueryBuilder("file"),
"file",
search,
mode,
),
"file",
specialAccess,
);
const totalFiles = await storageQB.getCount();
const pagination = getPagination(paginationInput, totalFiles);
const files = await storageQB
.orderBy("file.id", "ASC")
.skip(pagination.skip)
.take(pagination.limit)
.getMany();
await useQuotaIfProtectedItems(codeData, files, specialAccess);
setNoCacheHeaders(res, codeData);
res.render(
"storage",
getPageVariables(req, {
search,
mode,
currentPage: pagination.currentPage,
totalPages: pagination.totalPages,
totalfiles: pagination.totalItems,
files,
timeToPass,
accessCode: codeData,
}),
);
});
router.get("/file/thumbnail/:filename", (req, res) => {
res.sendFile(req.params.filename, { root: LOCATION_THUMBNAILS }, (err) => {
if (err) {
res
.status(404)
.render(
"404",
getPageVariables(req, { message: "Thumbnail not found" }),
);
}
});
});
router.get("/file/:filename", async (req, res) => {
const internalFilename = req.params.filename;
const file = await storageDirectory.findOne({
where: {
file: internalFilename,
},
});
if (!file) {
return res
.status(404)
.render("404", getPageVariables(req, { message: "File not found" }));
}
const { allowed } = await verifyProtectedAccess(
req,
file.accessCodes,
true,
);
if (!allowed) {
return res
.status(404)
.render("404", getPageVariables(req, { message: "File not found" }));
}
res.download(
joinLocation(LOCATION_FILES, file.file),
file.fileName,
(err) => {
if (err) {
console.error(err);
res
.status(404)
.render(
"404",
getPageVariables(req, { message: "File not found" }),
);
}
},
);
});
}
+143
View File
@@ -0,0 +1,143 @@
import type { Router, Request } from "express";
import { getDatabase } from "../config";
import path from "path";
import fs from "fs";
import JavaScriptObfuscator from "javascript-obfuscator";
import { logRequestCustom } from "../logger";
import { createMapTracer, getClientIp } from "../utils";
import { IP, IpLog } from "../db/ip";
export const tracer = createMapTracer();
export function getTracerId(req: Request) {
const s = req.query.t;
const id = typeof s === "string" ? s : "";
return id ? getTracer(id, req) : null;
}
function getTracer(id: string, req: Request) {
return [id, getClientIp(req)];
}
export function createFingerprintTracker(router: Router) {
const db = getDatabase();
const ipRepo = db.getRepository(IP);
const ipRepoLog = db.getRepository(IpLog);
const scriptBuffer = fs.readFileSync(
path.join(process.cwd(), "tracer", "index.js"),
"utf-8",
);
router.get("/scripts/:tracerId", (req, res) => {
const id =
typeof req.params.tracerId === "string" ? req.params.tracerId : "-";
const data = tracer(getTracer(id, req));
if (!data.script) {
data.script = JavaScriptObfuscator.obfuscate(
scriptBuffer,
{},
).getObfuscatedCode();
console.log(`Created obfuscated script ${data.script.length} chr`);
}
res.header("content-type", "application/javascript");
res.send(data.script);
});
// /t/ domains will send starts
router.post("/t/:tracerId/**", (req, res) => {
///const tracerObj = tracer(getTracerId(req));
const arr = req.path.split("/");
arr.shift();
arr.shift();
arr.shift();
const key = `/${arr.join("/")}`;
const encodeKey = key
.split("")
.map((e) => e.charCodeAt(0))
.reduce((ps, a) => ps + a, 0);
let bufferStr = req.body;
if (typeof req.body === "string") {
const buffer = req.body
.split("")
.map(
(e, i) =>
e.charCodeAt(0) - i - Math.round(Math.log2(i + 1) * encodeKey),
)
.map((e) => String.fromCharCode(e))
.join("");
bufferStr = buffer;
try {
bufferStr = JSON.stringify(JSON.parse(bufferStr), null, 2);
} catch (_) {
console.log("failed");
//console.log(_)
}
logRequestCustom(
req,
"script-dump",
`${req.path} ${bufferStr}`,
req.params.tracerId,
);
} else {
logRequestCustom(
req,
"script-dump-unknown",
`${req.path} ${bufferStr}`,
req.params.tracerId,
);
}
res.status(400).json({ error: "Bad request" });
});
router.get("/science", async (req, res) => {
logRequestCustom(req, "science", (req.query.url || "<EMPTY>")?.toString());
res.end();
try {
const ip = getClientIp(req);
let ipEntry = await ipRepo.findOne({ where: { ip } });
if (!ipEntry) {
ipEntry = new IP();
ipEntry.ip = ip;
ipEntry.firstSeen = new Date();
const data = await fetch(`http://ip-api.com/json/${ip}`, {
headers: {
accept: "application/json",
},
})
.then((e) => (e.status === 200 ? e.json() : null))
.then((e) => {
if (e && "status" in e) {
if (e.status === "success") {
return e;
}
}
return undefined;
});
ipEntry.data = data ? JSON.stringify(data) : undefined;
ipEntry.lat =
data && "lat" in data && typeof data.lat === "number"
? data.lat
: undefined;
ipEntry.lon =
data && "lon" in data && typeof data.lon === "number"
? data.lon
: undefined;
}
ipEntry.lastUsed = new Date();
await ipRepo.save(ipEntry);
const log = new IpLog();
log.ipRef = ipEntry;
const url = req.query.url;
const userAgent = req.headers["user-agent"];
log.url = typeof url === "string" ? url : undefined;
log.userAgent = userAgent;
log.accessed = new Date();
await ipRepoLog.save(log);
} catch {
/* ignore */
}
});
}
+45
View File
@@ -0,0 +1,45 @@
export class SelfCleaningMap<K, V> {
private map = new Map<K, V>();
private timeoutMap = new Map<K, NodeJS.Timeout>();
constructor(private time = 1000) {}
set(key: K, value: V) {
this.delete(key);
this.map.set(key, value);
this.timeoutMap.set(
key,
setTimeout(() => {
this.delete(key);
}, this.time),
);
}
has(key: K) {
return !!this.map.has(key);
}
get(key: K) {
return this.map.get(key);
}
clear() {
this.timeoutMap.forEach((value) => {
clearTimeout(value);
});
this.timeoutMap.clear();
this.map.clear();
}
delete(key: K) {
const timeout = this.timeoutMap.get(key);
if (timeout) {
clearTimeout(timeout);
this.timeoutMap.delete(key);
}
this.map.delete(key);
}
get size() {
return this.map.size;
}
}
+169
View File
@@ -0,0 +1,169 @@
import fs from "fs";
import path from "path";
import { SelfCleaningMap } from "./self-cleaning-map";
import type { Request } from "express";
import type { TracerData } from "./interfaces";
export function createMapTracer() {
const urlMapper = new SelfCleaningMap<string, TracerData>(1000 * 30);
return ([id, ip]: string[]) => {
if (urlMapper.size > 1000) {
urlMapper.clear();
}
const mapId = `${id}-${ip}`;
const urlId = urlMapper.get(mapId) || {
id,
scriptId: randomString(64),
script: "",
};
urlMapper.set(mapId, urlId);
return urlId;
};
}
export function getDateStr() {
const date = new Date();
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, "0");
const day = date.getDate().toString().padStart(2, "0");
const hours = date.getHours().toString().padStart(2, "0");
const minutes = date.getMinutes().toString().padStart(2, "0");
const seconds = date.getSeconds().toString().padStart(2, "0");
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
export function randomString(length: number) {
let result = "";
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
export function getDateString() {
const date = new Date();
const month = (date.getMonth() + 1).toString().padStart(2, "0");
const day = date.getDate().toString().padStart(2, "0");
const year = date.getFullYear();
return `${year}-${month}-${day}`;
}
export function prepareLogFolder(id?: string) {
return getAndPrepareLogFolder(getDateString(), id);
}
export function getAndPrepareLogFolder(date: string, id?: string) {
const folder = path.join(process.cwd(), "logs");
if (!fs.existsSync(folder)) {
fs.mkdirSync(folder);
}
const folderDate = path.join(process.cwd(), "logs", date);
if (!fs.existsSync(folderDate)) {
fs.mkdirSync(folderDate);
}
if (id) {
const folderId = path.join(process.cwd(), "logs", date, id);
if (!fs.existsSync(folderId)) {
console.log(`Tracker folder created!`);
fs.mkdirSync(folderId);
}
return folderId;
}
return folderDate;
}
export function getClientIp(req: Request): string {
return (
req.header("cf-connecting-ip") || req.socket.remoteAddress || "Unknown"
);
}
export function getExtension(str: string) {
return str.split(".").pop();
}
export function getFilenameDetails(str: string) {
const arr = str.split(".");
const extension = arr.pop();
const name = arr.join(".");
return { name, extension };
}
export function generateNonExistingId(
pathStr: string,
extension: string,
len = 32,
) {
while (true) {
const name = randomString(len);
const actualName = `${name}.${extension}`;
const actualPath = path.join(pathStr, actualName);
if (!fs.existsSync(actualPath)) {
return { path: actualPath, name: actualName };
}
}
}
export function getTimeElapsed(createdAt: Date) {
const isZero = createdAt.getTime() === 0;
const formatDiff = () => {
const now = new Date();
let diff = now.getTime() - createdAt.getTime();
if (diff < 0) {
diff = 0;
} // you never know what nonsense will be in DB
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
const years = Math.floor(days / 365);
const months = Math.floor((days % 365) / 30);
const remainingDays = days - years * 365 - months * 30;
const c = (n: number, suffix: string) => (n === 0 ? "" : `${n}${suffix}`);
const data = [c(years, "y"), c(months, "mon"), c(remainingDays, "days")];
const pl = (n: number) => n.toString().padStart(2, "0");
const date = `${createdAt.getFullYear()}-${pl(createdAt.getMonth() + 1)}-${pl(createdAt.getDate())}`;
return `${date} (${data.join(" ")})`;
};
return isZero ? null : formatDiff();
}
export function timeToPass(future: Date) {
if (future.getTime() === 0) {
return null;
}
const now = new Date();
let diff = future.getTime() - now.getTime(); // future minus now
if (diff < 0) {
diff = 0;
} // already passed
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
const years = Math.floor(days / 365);
const months = Math.floor((days % 365) / 30);
const remainingDays = days - years * 365 - months * 30;
const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((diff % (1000 * 60)) / 1000);
const c = (n: number, suffix: string) => (n === 0 ? "" : `${n}${suffix}`);
const parts = [
c(years, "y"),
c(months, "mon"),
c(remainingDays, "d"),
c(hours, "h"),
c(minutes, "m"),
c(seconds, "s"),
].filter(Boolean);
const pad = (n: number) => n.toString().padStart(2, "0");
const dateStr = `${future.getFullYear()}-${pad(future.getMonth() + 1)}-${pad(future.getDate())}`;
console.log(`${dateStr} (${parts.join(" ")})`);
return `${dateStr} (${parts.join(" ")})`;
}