mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 09:22:15 +00:00
fix(quality): resolve reliability findings on dev
The Sonar quality gate rated new code D. Preserve focus and keyboard interaction through native controls and shared dialog behavior. Replace ambiguous regex scans with bounded parsing and make numeric coercion and initialization explicit.
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Pure env-string coercion helpers shared by the whole config layer (derive.ts,
|
||||
* env.schema.ts). Kept free of imports so units can test them in isolation.
|
||||
* env.schema.ts). Kept free of environment access so units can test them in isolation.
|
||||
*
|
||||
* Each helper reproduces a coercion family that already exists in the codebase.
|
||||
* Parity is law: do NOT "fix" a family's quirks here (e.g. `numberOr` treating
|
||||
@@ -67,14 +67,7 @@ export function csvListFiltered(raw: string | undefined): string[] | null {
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Strip ALL trailing slashes (`/\/+$/`) — app-url.getAppUrl / TRANSIT_API_URL variant.
|
||||
* Scanned rather than replaced: `/\/+$/` re-walks the slash run from every start
|
||||
* position, which is quadratic on a slash-heavy value. Same result, same quirk. */
|
||||
export function stripTrailingSlashes(value: string): string {
|
||||
let end = value.length;
|
||||
while (end > 0 && value.charCodeAt(end - 1) === 47 /* '/' */) end--;
|
||||
return value.slice(0, end);
|
||||
}
|
||||
export { stripTrailingSlashes } from '@trek/shared';
|
||||
|
||||
const DURATION_UNITS_MS: Record<string, number> = {
|
||||
ms: 1,
|
||||
|
||||
@@ -363,11 +363,14 @@ function migrationNamesFromCopy(script: string): string[] {
|
||||
return match !== null && !isPluginSchemaName(match[1] ?? '');
|
||||
});
|
||||
if (copy < 0) return [];
|
||||
const columns =
|
||||
/\(([^)]*)\)/
|
||||
.exec(lines[copy])?.[1]
|
||||
.split(',')
|
||||
.map((column) => column.trim()) ?? [];
|
||||
const header = lines[copy];
|
||||
const start = header.indexOf('(') + 1;
|
||||
const end = header.indexOf(')', start);
|
||||
if (end === -1) return [];
|
||||
const columns = header
|
||||
.slice(start, end)
|
||||
.split(',')
|
||||
.map((column) => column.trim());
|
||||
const nameAt = columns.indexOf('name');
|
||||
if (nameAt < 0) return [];
|
||||
const names: string[] = [];
|
||||
|
||||
@@ -69,7 +69,7 @@ export function pluginColumnKind(declaredType: string, storage: ReadonlySet<stri
|
||||
return storage.size === 0 && declared.includes('BLOB') ? 'bytes' : 'text';
|
||||
}
|
||||
|
||||
const NUMBER_LITERAL = /^[+-]?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i;
|
||||
const NUMBER_LITERAL = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;
|
||||
const INTEGER_LITERAL = /^[+-]?\d+$/;
|
||||
const STRING_LITERAL = /^'(?:[^']|'')*'$/s;
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@ const INT64_MIN = -(2n ** 63n);
|
||||
const INT64_MAX = 2n ** 63n - 1n;
|
||||
const SAFE_MAX = BigInt(Number.MAX_SAFE_INTEGER);
|
||||
const DECIMAL_INTEGER = /^[+-]?\d+$/;
|
||||
const DECIMAL_NUMBER = /^[+-]?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i;
|
||||
const DECIMAL_NUMBER = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;
|
||||
const NUL = '\u0000';
|
||||
|
||||
/** Why a value holding a NUL character is refused. */
|
||||
|
||||
@@ -62,7 +62,8 @@ function tripOf(row: unknown, today: string): HomeTrip | null {
|
||||
if (!Number.isInteger(id) || id <= 0 || !title) return null;
|
||||
const startDate = dateOf(record.start_date);
|
||||
const endDate = dateOf(record.end_date);
|
||||
const places = record.place_count === null || record.place_count === undefined ? NaN : Number(record.place_count);
|
||||
const places =
|
||||
record.place_count === null || record.place_count === undefined ? Number.NaN : Number(record.place_count);
|
||||
return {
|
||||
id,
|
||||
title: title.slice(0, MAX_TITLE_CHARS),
|
||||
|
||||
@@ -72,11 +72,11 @@ function isBarePostcode(part: string): boolean {
|
||||
* the region the map calls Kaafu. Without it the atoll was read as the city, and
|
||||
* every island in it counted as one (#3200).
|
||||
*/
|
||||
const REGION_WORD = /\s+(?:atoll|province|region|state|prefecture|county|governorate|oblast)$/i;
|
||||
const REGION_WORD = /\s(?:atoll|province|region|state|prefecture|county|governorate|oblast)$/i;
|
||||
|
||||
function sameRegion(part: string, region: string): boolean {
|
||||
const name = normalize(part);
|
||||
return name === region || name.replace(REGION_WORD, '') === region;
|
||||
return name === region || name.replace(REGION_WORD, '').trimEnd() === region;
|
||||
}
|
||||
|
||||
export function cityFromAddress(
|
||||
|
||||
@@ -33,7 +33,12 @@ import { docFailed } from './document-provider';
|
||||
import { DocumentProviderRegistry } from './document-provider.registry';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { HttpException, Injectable } from '@nestjs/common';
|
||||
import { DOCSYNC_SECRET_MASK, type DocsyncConnectionInput, type DocsyncLinkInput } from '@trek/shared';
|
||||
import {
|
||||
stripTrailingSlashes,
|
||||
DOCSYNC_SECRET_MASK,
|
||||
type DocsyncConnectionInput,
|
||||
type DocsyncLinkInput,
|
||||
} from '@trek/shared';
|
||||
|
||||
import crypto from 'crypto';
|
||||
|
||||
@@ -252,7 +257,7 @@ export class DocSyncConfigService {
|
||||
* SSRF guard rejects for a reason other than being private.
|
||||
*/
|
||||
async validateBaseUrl(raw: string): Promise<DocResult<{ url: string; isPrivate: boolean }>> {
|
||||
const trimmed = raw.trim().replace(/\/+$/, '');
|
||||
const trimmed = stripTrailingSlashes(raw.trim());
|
||||
if (!trimmed) return { success: false, error: { code: 'unreachable', detail: 'empty url' } };
|
||||
const verdict = await checkSsrf(trimmed);
|
||||
if (!verdict.allowed && !verdict.isPrivate) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { stripTrailingSlashes } from '@trek/shared';
|
||||
import { Readable } from 'node:stream';
|
||||
import { createHash } from 'node:crypto';
|
||||
import type { DocsyncErrorCode } from '@trek/shared';
|
||||
@@ -336,8 +337,7 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
export function normalizeBaseUrl(raw: string): string {
|
||||
const trimmed = raw.trim();
|
||||
const withScheme = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
|
||||
return withScheme
|
||||
.replace(/\/+$/, '')
|
||||
return stripTrailingSlashes(withScheme)
|
||||
.replace(/\/webapi\/(entry|auth|query)\.cgi$/i, '')
|
||||
.replace(/\/webapi$/i, '');
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { readCappedJson, readCappedText } from '../../../utils/cappedFetch';
|
||||
import { PROVIDER_JSON_MAX_BYTES, PROVIDER_TIMEOUT_MS, PROVIDER_TRANSFER_TIMEOUT_MS } from '../doc-sync.constants';
|
||||
import { DOWNLOAD_MAX_BYTES, guardDownload, providerFetch, statusErrorCode } from './provider-http';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { stripTrailingSlashes } from '@trek/shared';
|
||||
import type { DocsyncErrorCode } from '@trek/shared';
|
||||
|
||||
import { XMLParser } from 'fast-xml-parser';
|
||||
@@ -213,15 +214,13 @@ export function normalizeFileId(raw: string | null, flavor: WebdavFlavor): strin
|
||||
* rule would also eat an install that lives under `/apps/nextcloud`.
|
||||
*/
|
||||
export function normalizeOrigin(baseUrl: string): string {
|
||||
return baseUrl
|
||||
.trim()
|
||||
.replace(/[?#].*$/, '')
|
||||
.replace(/\/+$/, '')
|
||||
const [base = ''] = baseUrl.trim().split(/[?#]/, 1);
|
||||
const origin = stripTrailingSlashes(base)
|
||||
.replace(/\/(?:remote|index)\.php(?:\/.*)?$/i, '')
|
||||
.replace(/\/apps\/(?:files|dashboard)(?:\/.*)?$/i, '')
|
||||
.replace(/\/dav\/spaces(?:\/.*)?$/i, '')
|
||||
.replace(/\/graph(?:\/.*)?$/i, '')
|
||||
.replace(/\/+$/, '');
|
||||
.replace(/\/graph(?:\/.*)?$/i, '');
|
||||
return stripTrailingSlashes(origin);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -251,7 +250,7 @@ export function encodePath(path: string): string {
|
||||
|
||||
/** `/a/b/` and `a//b` both mean `/a/b`. Every comparison here depends on one spelling. */
|
||||
export function normalizePath(path: string): string {
|
||||
const collapsed = `/${path}`.replace(/\/+/g, '/').replace(/\/+$/, '');
|
||||
const collapsed = stripTrailingSlashes(`/${path}`.replace(/\/+/g, '/'));
|
||||
return collapsed === '' ? '/' : collapsed;
|
||||
}
|
||||
|
||||
|
||||
@@ -170,9 +170,10 @@ function sanitizeName(name: string): string {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
.replace(/[\\/<>:"|?*\u0000-\u001f]/g, '-')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
.replace(/[. ]+$/, '');
|
||||
return cleaned.slice(0, 200);
|
||||
.trim();
|
||||
let end = cleaned.length;
|
||||
while (end > 0 && (cleaned[end - 1] === '.' || cleaned[end - 1] === ' ')) end--;
|
||||
return cleaned.slice(0, Math.min(end, 200));
|
||||
}
|
||||
|
||||
function parentOf(encodedPath: string): string {
|
||||
|
||||
@@ -217,6 +217,8 @@ function bearingDeg(lat1: number, lng1: number, lat2: number, lng2: number): num
|
||||
return (Math.atan2(y, x) * 180) / Math.PI;
|
||||
}
|
||||
|
||||
const NO_SIBLING_SECTORS = { now: 0, siblings: [] as readonly SiblingSector[] };
|
||||
|
||||
/**
|
||||
* The aircraft that flies this leg among those the feed answered for the
|
||||
* callsign: the one with a position nearest the great circle between the two
|
||||
@@ -228,10 +230,12 @@ function bearingDeg(lat1: number, lng1: number, lat2: number, lng2: number): num
|
||||
export function pickAircraft(
|
||||
aircraft: readonly FeedAircraft[],
|
||||
route: Route,
|
||||
sectors: { now: number; siblings: readonly SiblingSector[]; departed?: boolean; taxied?: boolean } = {
|
||||
now: 0,
|
||||
siblings: [],
|
||||
},
|
||||
sectors: {
|
||||
now: number;
|
||||
siblings: readonly SiblingSector[];
|
||||
departed?: boolean;
|
||||
taxied?: boolean;
|
||||
} = NO_SIBLING_SECTORS,
|
||||
): FeedAircraft | null {
|
||||
let best: FeedAircraft | null = null;
|
||||
let bestScore = Number.POSITIVE_INFINITY;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { readEnv } from '../../app-config';
|
||||
import { exceedsDeclaredLength, readCapped, readCappedText } from '../../utils/cappedFetch';
|
||||
import { replaceInlineMarkdownLinks, stripPreviewTags } from '@trek/shared';
|
||||
|
||||
import { existsSync, promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
@@ -142,12 +143,28 @@ function parseSidebar(md: string): WikiNavSection[] {
|
||||
return sections.filter((s) => s.pages.length > 0);
|
||||
}
|
||||
|
||||
function replaceWikiLinks(input: string, render: (label: string, original: string) => string): string {
|
||||
const parts: string[] = [];
|
||||
let cursor = 0;
|
||||
for (let open = input.indexOf('[['); open !== -1;) {
|
||||
const close = input.indexOf(']', open + 2);
|
||||
if (close === -1) break;
|
||||
if (close > open + 2 && input[close + 1] === ']') {
|
||||
parts.push(input.slice(cursor, open), render(input.slice(open + 2, close), input.slice(open, close + 2)));
|
||||
cursor = close + 2;
|
||||
}
|
||||
open = input.indexOf('[[', Math.max(cursor, close + 1));
|
||||
}
|
||||
parts.push(input.slice(cursor));
|
||||
return parts.join('');
|
||||
}
|
||||
|
||||
/** Rewrite GitHub-wiki `[[..]]` links to /help routes and proxy relative images. */
|
||||
function processMarkdown(md: string): string {
|
||||
// Strip HTML comments (e.g. `<!-- TODO: screenshot … -->` placeholders) — the
|
||||
// markdown renderer would otherwise surface them as raw text.
|
||||
let out = md.replace(/<!--[\s\S]*?-->/g, '');
|
||||
out = out.replace(/\[\[([^\]]+)\]\]/g, (_m, inner: string) => {
|
||||
out = replaceWikiLinks(out, (inner) => {
|
||||
const [titleRaw, slugRaw] = inner.includes('|') ? inner.split('|') : [inner, inner];
|
||||
const slug = slugRaw.trim().replace(/\s+/g, '-');
|
||||
// `[[Plugin Development#talking-to-plugins|Plugin-Development]]` must not
|
||||
@@ -173,7 +190,8 @@ function processMarkdown(md: string): string {
|
||||
// Runs last: `[[..]]` links and images have already become absolute paths by
|
||||
// this point, so the leading-slash guard skips them.
|
||||
out = outsideCode(out, (segment) =>
|
||||
segment.replace(/(^|[^!])\[([^\]]+)\]\(([^)\s]+)\)/g, (m, prefix: string, text: string, url: string) => {
|
||||
replaceInlineMarkdownLinks(segment, (text, url, m, offset) => {
|
||||
if (!text || !url || segment[offset - 1] === '!' || /\s/.test(url)) return m;
|
||||
if (/^(https?:|mailto:|tel:|#|\/)/i.test(url)) return m;
|
||||
const [pageRaw, anchor] = url.includes('#') ? url.split('#') : [url, ''];
|
||||
const page = pageRaw
|
||||
@@ -181,7 +199,7 @@ function processMarkdown(md: string): string {
|
||||
.replace(/\.md$/i, '')
|
||||
.trim();
|
||||
if (!page || !SLUG_RE.test(page)) return m;
|
||||
return `${prefix}[${text}](/help/${page}${anchor ? `#${anchor}` : ''})`;
|
||||
return `[${text}](/help/${page}${anchor ? `#${anchor}` : ''})`;
|
||||
}),
|
||||
);
|
||||
return out;
|
||||
@@ -328,13 +346,13 @@ function headingAnchor(text: string): string {
|
||||
* itself is still rendered from the real markdown.
|
||||
*/
|
||||
function toPlainText(md: string): string {
|
||||
return md
|
||||
const withoutImages = md
|
||||
.replace(/<!--[\s\S]*?-->/g, ' ')
|
||||
.replace(/```[\s\S]*?```|~~~[\s\S]*?~~~/g, ' ')
|
||||
.replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')
|
||||
.replace(/\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/g, '$1')
|
||||
.replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
|
||||
.replace(/<[^>]+>/g, ' ')
|
||||
.replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1');
|
||||
const withoutWikiLinks = replaceWikiLinks(withoutImages, (label, original) => label.split('|', 1)[0] || original);
|
||||
const plain = replaceInlineMarkdownLinks(withoutWikiLinks, (label, _target, original) => label || original, true);
|
||||
return stripPreviewTags(plain, false)
|
||||
.replace(/[`*_~>|#]/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
@@ -353,10 +371,10 @@ function chunkByHeading(md: string): IndexedPage['chunks'] {
|
||||
let inFence = false;
|
||||
for (const line of md.split('\n')) {
|
||||
if (/^(```|~~~)/.test(line)) inFence = !inFence;
|
||||
const h = !inFence && line.match(/^#{2,4}\s+(\S.*\S|.)\s*$/);
|
||||
if (h) {
|
||||
const h = !inFence && /^#{2,4}\s/.exec(line);
|
||||
if (h && line.length > h[0].length) {
|
||||
flush();
|
||||
heading = h[1].replace(/[*_`]/g, '').trim();
|
||||
heading = line.slice(h[0].length).replace(/[*_`]/g, '').trim();
|
||||
continue;
|
||||
}
|
||||
buf.push(line);
|
||||
|
||||
@@ -90,11 +90,11 @@ export function syncWindow(
|
||||
lookbackDays: number,
|
||||
lookaheadDays: number,
|
||||
): { from: Date; to: Date } | null {
|
||||
const start = startDate ? Date.parse(`${startDate}T00:00:00Z`) : NaN;
|
||||
const start = startDate ? Date.parse(`${startDate}T00:00:00Z`) : Number.NaN;
|
||||
if (!Number.isFinite(start)) return null;
|
||||
const from = new Date(start - lookbackDays * 86_400_000);
|
||||
|
||||
const end = endDate ? Date.parse(`${endDate}T23:59:59Z`) : NaN;
|
||||
const end = endDate ? Date.parse(`${endDate}T23:59:59Z`) : Number.NaN;
|
||||
const to = Number.isFinite(end) ? new Date(Math.min(end + lookaheadDays * 86_400_000, now.getTime())) : now;
|
||||
|
||||
return to.getTime() > from.getTime() ? { from, to } : null;
|
||||
|
||||
@@ -81,12 +81,11 @@ export class InMemoryBookDesignDraftStore extends BookDesignDraftStore {
|
||||
put(draft: BookDesignDraft): Promise<void> {
|
||||
const size = JSON.stringify(draft.doc).length + (draft.base ? JSON.stringify(draft.base).length : 0);
|
||||
if (size > BOOK_DESIGN_DRAFTS.maxChars) {
|
||||
return Promise.reject(
|
||||
new DomainError(422, 'This design is too large to keep', {
|
||||
code: 'book_design_too_large',
|
||||
mcpMessage: 'This design is too large to keep as a draft: design fewer pages (pages.max) or a scope.',
|
||||
}),
|
||||
);
|
||||
const error: Error = new DomainError(422, 'This design is too large to keep', {
|
||||
code: 'book_design_too_large',
|
||||
mcpMessage: 'This design is too large to keep as a draft: design fewer pages (pages.max) or a scope.',
|
||||
});
|
||||
return Promise.reject(error);
|
||||
}
|
||||
this.sweep();
|
||||
const key = keyOf(draft.userId, draft.journeyId, draft.designId);
|
||||
|
||||
@@ -362,11 +362,16 @@ const FORWARD_MARKER = new RegExp(String.raw`^\s*[-_]{2,}\s*(?:${FORWARD_MARKER_
|
||||
const FORWARD_INTRO = new RegExp(String.raw`^\s*(?:${FORWARD_INTRO_WORDS.join('|')})\s*:\s*$`, 'i');
|
||||
/** Outlook's rule above the header block of a forwarded message. */
|
||||
const OUTLOOK_RULE = /^\s*_{10,}\s*$/;
|
||||
/**
|
||||
* "On 1 May, Ana wrote:", the line above a quoted reply, which names the sender.
|
||||
* The lookahead checks the closing colon first, which keeps a long line without one linear.
|
||||
*/
|
||||
const ATTRIBUTION = /^(?=.*:\s*$)\s*(?:on\s.+\swrote|am\s.+\sschrieb\s.+|le\s.+\sa\s[ée]crit)\s*:\s*$/i;
|
||||
/** A line such as "On 1 May, Ana wrote:" above a quoted reply. */
|
||||
function isReplyAttribution(line: string): boolean {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed.endsWith(':')) return false;
|
||||
const header = trimmed.slice(0, -1);
|
||||
if (/^am\s/i.test(header)) return /\sschrieb\s./i.test(header.slice(4));
|
||||
const words = header.trimEnd();
|
||||
if (/^on\s/i.test(words)) return /\swrote$/i.test(words.slice(4));
|
||||
return /^le\s/i.test(words) && /\sa\s[ée]crit$/i.test(words.slice(4));
|
||||
}
|
||||
const HEADER_LINE = fieldLine([...SENDER_FIELDS, ...OTHER_FIELDS, ...SUBJECT_FIELDS]);
|
||||
const FROM_LINE = fieldLine(SENDER_FIELDS);
|
||||
const SUBJECT_LINE = fieldLine(SUBJECT_FIELDS);
|
||||
@@ -408,7 +413,7 @@ function unwrapLayer(lines: string[]): { lines: string[]; changed: boolean } {
|
||||
} else if (bareBlockStarts[i]) {
|
||||
i = skipHeaderBlock(lines, i);
|
||||
changed = true;
|
||||
} else if (line.length <= MAX_ATTRIBUTION_LINE && ATTRIBUTION.test(line)) {
|
||||
} else if (line.length <= MAX_ATTRIBUTION_LINE && isReplyAttribution(line)) {
|
||||
i++;
|
||||
changed = true;
|
||||
} else if (/^\s*>/.test(line)) {
|
||||
|
||||
@@ -193,7 +193,10 @@ export function hashToken(token: string): string {
|
||||
* Null for an address that holds none.
|
||||
*/
|
||||
export function tokenOf(recipient: string, template: string | null): string | null {
|
||||
const address = recipient.replace(/^.*</, '').replace(/>.*$/, '').trim().toLowerCase();
|
||||
const lines = recipient.replace(/^.*</, '').split(/([\r\n\u2028\u2029])/);
|
||||
const last = lines.length - 1;
|
||||
lines[last] = lines[last].split('>', 1)[0];
|
||||
const address = lines.join('').trim().toLowerCase();
|
||||
const local = address.split('@')[0] ?? '';
|
||||
if (template) {
|
||||
const [prefix, suffix] = template.toLowerCase().split('@')[0].split('{token}');
|
||||
|
||||
@@ -93,7 +93,10 @@ export class MailIngestInboundController {
|
||||
* arriving at the deadline ends the read the same way.
|
||||
*/
|
||||
function readBody(req: Request, maxBytes: number, take: (bytes: number) => boolean): Promise<Buffer> {
|
||||
if (Number(req.get('content-length')) > maxBytes) return Promise.reject(new DomainError(413, TOO_LARGE));
|
||||
if (Number(req.get('content-length')) > maxBytes) {
|
||||
const error: Error = new DomainError(413, TOO_LARGE);
|
||||
return Promise.reject(error);
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks: Buffer[] = [];
|
||||
let size = 0;
|
||||
@@ -112,7 +115,7 @@ function readBody(req: Request, maxBytes: number, take: (bytes: number) => boole
|
||||
};
|
||||
const onEnd = () => {
|
||||
clearTimeout(deadline);
|
||||
if (size > maxBytes) reject(new DomainError(413, TOO_LARGE));
|
||||
if (size > maxBytes) stop(new DomainError(413, TOO_LARGE));
|
||||
else resolve(Buffer.concat(chunks));
|
||||
};
|
||||
const deadline = setTimeout(() => stop(new DomainError(408, TOO_SLOW)), READ_DEADLINE_MS);
|
||||
|
||||
@@ -17,6 +17,7 @@ import { toApiLang } from './maps.helpers';
|
||||
import { trekCommunityValuesSchema, type TrekCommunityValues } from './trek-community.schema';
|
||||
import { identifiedFetch } from './trek-places.fetch';
|
||||
import {
|
||||
stripTrailingSlashes,
|
||||
normalizePlaceWebsite,
|
||||
skiRouteBuildSchema,
|
||||
winterIndexRowSchema,
|
||||
@@ -190,7 +191,7 @@ export function trekPlacesMiss(err: unknown): TrekPlacesMiss {
|
||||
|
||||
export function trekPlacesBaseUrl(): string {
|
||||
const configured = (readEnv().maps.trekPlacesUrl || '').trim();
|
||||
return (configured || DEFAULT_TREK_PLACES_URL).replace(/\/+$/, '');
|
||||
return stripTrailingSlashes(configured || DEFAULT_TREK_PLACES_URL);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -42,7 +42,7 @@ function instanceToken(): string {
|
||||
const url = getAppUrl();
|
||||
let hash = 0;
|
||||
for (let i = 0; i < url.length; i++) {
|
||||
hash = ((hash << 5) - hash + url.charCodeAt(i)) | 0;
|
||||
hash = ((hash << 5) - hash + url.charCodeAt(i)) >>> 0;
|
||||
}
|
||||
return `trek-${(hash >>> 0).toString(36)}`;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { decrypt_api_key } from '../../common/crypto/apiKeyCrypto';
|
||||
import type { NotifEventType } from '../notification-events';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { stripTrailingSlashes } from '@trek/shared';
|
||||
|
||||
/** NS2's three per-user ntfy keys, read together off `SettingsRepository.getForUser`. */
|
||||
const NTFY_USER_KEYS = new Set(['ntfy_topic', 'ntfy_server', 'ntfy_token']);
|
||||
@@ -79,7 +80,7 @@ export function isOperatorNtfyServer(server: string | null | undefined, adminSer
|
||||
const raw = (value || 'https://ntfy.sh').replace(/(?<!\/)\/+$/, '');
|
||||
try {
|
||||
const parsed = new URL(raw);
|
||||
return `${parsed.protocol}//${parsed.host}${parsed.pathname.replace(/\/+$/, '')}`.toLowerCase();
|
||||
return `${parsed.protocol}//${parsed.host}${stripTrailingSlashes(parsed.pathname)}`.toLowerCase();
|
||||
} catch {
|
||||
return raw.toLowerCase();
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import { CONTRIB_ORIGIN } from './place-contrib.constants';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import type { ConfigType } from '@nestjs/config';
|
||||
import {
|
||||
stripTrailingSlashes,
|
||||
PLACE_CONTRIB_FIELDS,
|
||||
PLACE_CONTRIB_TERMS_VERSION,
|
||||
type PlaceContribConsent,
|
||||
@@ -152,6 +153,6 @@ export function agreedToCurrentTerms(consent: PlaceContribConsent): boolean {
|
||||
|
||||
/** An own TREK_PLACES_URL: anything but unset or the public instance itself. */
|
||||
function customPlacesUrl(configured: string | undefined): boolean {
|
||||
const url = configured?.trim().replace(/\/+$/, '');
|
||||
const url = stripTrailingSlashes(configured?.trim() ?? '');
|
||||
return !!url && url !== CONTRIB_ORIGIN;
|
||||
}
|
||||
|
||||
@@ -358,7 +358,21 @@ export function applyPlatformSpa(app: express.Application): void {
|
||||
|
||||
// The optional .br is the Brotli copy the client build writes beside a hashed file
|
||||
// (precompressed-static.ts); it is as immutable as the file it was made from.
|
||||
const HASHED_ASSET = /[\\/]assets[\\/][^\\/]+-[\w-]{8,}\.\w+(?:\.br)?$/;
|
||||
function hasHashedStem(name: string): boolean {
|
||||
const dot = name.lastIndexOf('.');
|
||||
if (dot === -1 || !/^\w+$/.test(name.slice(dot + 1))) return false;
|
||||
let start = dot;
|
||||
while (start > 0 && /^[\w-]$/.test(name.charAt(start - 1))) start--;
|
||||
const delimiter = name.indexOf('-', Math.max(1, start));
|
||||
return delimiter !== -1 && dot - delimiter > 8;
|
||||
}
|
||||
|
||||
function isHashedAsset(filePath: string): boolean {
|
||||
const segments = filePath.split(/[\\/]/);
|
||||
const name = segments.at(-1);
|
||||
if (segments.length < 3 || segments.at(-2) !== 'assets' || !name) return false;
|
||||
return hasHashedStem(name) || (name.endsWith('.br') && hasHashedStem(name.slice(0, -3)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Production static serving of the built client (JS/CSS/assets). Split out from
|
||||
@@ -376,7 +390,7 @@ export function applyPlatformStatic(app: express.Application): void {
|
||||
setHeaders: (res, filePath) => {
|
||||
if (filePath.endsWith('index.html')) {
|
||||
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
|
||||
} else if (HASHED_ASSET.test(filePath)) {
|
||||
} else if (isHashedAsset(filePath)) {
|
||||
// Vite puts a content hash in every name under assets/, so a file there
|
||||
// never changes. Without this the iOS app, which has no service worker,
|
||||
// cannot start offline: WebKit would revalidate each script and fail.
|
||||
|
||||
@@ -83,7 +83,7 @@ function readTarGz(buf: Buffer, lim: Required<ExtractLimits>): Member[] {
|
||||
let name = block.subarray(0, 100).toString('utf8').replace(/\0.*$/, '');
|
||||
const prefix = block.subarray(345, 500).toString('utf8').replace(/\0.*$/, '');
|
||||
if (prefix) name = `${prefix}/${name}`;
|
||||
const size = Number.parseInt(block.subarray(124, 136).toString('utf8').replace(/\0.*$/, '').trim() || '0', 8);
|
||||
const size = Number.parseInt(block.subarray(124, 136).toString('utf8').split('\0', 1)[0].trim() || '0', 8);
|
||||
// A negative size walks the cursor backwards: `off += 512` and then
|
||||
// `off += Math.ceil(size / 512) * 512` cancel out at -512 and go negative
|
||||
// below it, so the same header is read forever while every pass appends a
|
||||
|
||||
@@ -376,6 +376,13 @@ const NUMERIC_KEYWORDS: ReadonlyArray<readonly [string, 'number' | 'string' | 'b
|
||||
['nullable', 'boolean'],
|
||||
];
|
||||
|
||||
function looksLikeEmail(address: string): boolean {
|
||||
const at = address.indexOf('@');
|
||||
if (at < 1 || address.includes('@', at + 1) || /\s/.test(address)) return false;
|
||||
const dot = address.indexOf('.', at + 2);
|
||||
return dot >= 0 && dot < address.length - 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats worth enforcing. An unlisted one would be advertised and never checked.
|
||||
*
|
||||
@@ -384,7 +391,7 @@ const NUMERIC_KEYWORDS: ReadonlyArray<readonly [string, 'number' | 'string' | 'b
|
||||
* advertises a format nothing checks or throws inside the caller's validation.
|
||||
*/
|
||||
const FORMAT_CHECKS = new Map<string, (v: string) => boolean>([
|
||||
['email', (v) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)],
|
||||
['email', looksLikeEmail],
|
||||
['uuid', (v) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(v)],
|
||||
['uri', (v) => /^[a-z][a-z0-9+.-]*:/i.test(v)],
|
||||
['date-time', (v) => !Number.isNaN(Date.parse(v))],
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
stripTrailingSlashes,
|
||||
resolveValhallaProvider,
|
||||
VALHALLA_COSTING,
|
||||
VALHALLA_RELAY_MAX_LOCATIONS,
|
||||
@@ -254,9 +255,9 @@ function routersOf(
|
||||
trekValhalla: string | null,
|
||||
): { base: string; valhalla: string; everyDay: boolean } {
|
||||
const base =
|
||||
typeof settings.routing_base_url === 'string' ? settings.routing_base_url.trim().replace(/\/+$/, '') : '';
|
||||
typeof settings.routing_base_url === 'string' ? stripTrailingSlashes(settings.routing_base_url.trim()) : '';
|
||||
const configuredValhalla =
|
||||
typeof settings.valhalla_base_url === 'string' ? settings.valhalla_base_url.trim().replace(/\/+$/, '') : '';
|
||||
typeof settings.valhalla_base_url === 'string' ? stripTrailingSlashes(settings.valhalla_base_url.trim()) : '';
|
||||
const provider = resolveValhallaProvider({
|
||||
provider: settings.routing_valhalla_provider,
|
||||
valhallaUrl: configuredValhalla,
|
||||
|
||||
@@ -7,7 +7,12 @@ import { RateLimitService } from '../common/rate-limit.service';
|
||||
import { ServiceIdentityPort } from '../service-identity/service-identity.interface';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import type { ConfigType } from '@nestjs/config';
|
||||
import { VALHALLA_RELAY_REQUEST_SCHEMAS, compactValhallaRequest, type ValhallaRelayAction } from '@trek/shared';
|
||||
import {
|
||||
stripTrailingSlashes,
|
||||
VALHALLA_RELAY_REQUEST_SCHEMAS,
|
||||
compactValhallaRequest,
|
||||
type ValhallaRelayAction,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
* Questions one user may put to the TREK Valhalla a minute, the browser and the server's
|
||||
@@ -78,7 +83,7 @@ export class RoutingRelayService {
|
||||
|
||||
/** Whether an address names the TREK Valhalla, whose questions go through here and nowhere else. */
|
||||
serves(base: string): boolean {
|
||||
return base.trim().replace(/\/+$/, '') === this.config.valhallaUrl;
|
||||
return stripTrailingSlashes(base.trim()) === this.config.valhallaUrl;
|
||||
}
|
||||
|
||||
async ask(
|
||||
|
||||
@@ -36,7 +36,7 @@ function spruce(input: Buffer): string {
|
||||
const bits = [...input].map((byte) => byte.toString(2).padStart(8, '0')).join('');
|
||||
let out = '';
|
||||
for (let i = 0; i < bits.length; i += 5) {
|
||||
out += FROST_CRATER.charAt(parseInt(bits.slice(i, i + 5).padEnd(5, '0'), 2));
|
||||
out += FROST_CRATER.charAt(Number.parseInt(bits.slice(i, i + 5).padEnd(5, '0'), 2));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { serviceTierSchema, type ServiceQuotaView, type ServiceTier } from '@trek/shared';
|
||||
import { stripTrailingSlashes, serviceTierSchema, type ServiceQuotaView, type ServiceTier } from '@trek/shared';
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
@@ -17,7 +17,7 @@ function serviceAddress(raw: string): string | null {
|
||||
if (!trimmed) return null;
|
||||
try {
|
||||
const url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`);
|
||||
return `${url.host}${url.pathname.replace(/\/+$/, '')}`.toLowerCase();
|
||||
return `${url.host}${stripTrailingSlashes(url.pathname)}`.toLowerCase();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ export interface RenewableSessionClaims {
|
||||
*/
|
||||
export function legacySessionId(token: string): string {
|
||||
const h = createHash('sha256').update(token).digest('hex');
|
||||
const variant = ((parseInt(h.charAt(16), 16) & 0x3) | 0x8).toString(16);
|
||||
const variant = ((Number.parseInt(h.charAt(16), 16) & 0x3) | 0x8).toString(16);
|
||||
return `${h.slice(0, 8)}-${h.slice(8, 12)}-8${h.slice(13, 16)}-${variant}${h.slice(17, 20)}-${h.slice(20, 32)}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ export const SGR_FORMAT = 1;
|
||||
|
||||
/** What an edge may be used for, per direction (`edgeFwdUses` a to b, `edgeBackUses` b to a). */
|
||||
export const Use = {
|
||||
DOWNHILL: 1 << 0,
|
||||
DOWNHILL: 1,
|
||||
LIFT_UP: 1 << 1,
|
||||
LIFT_DOWN: 1 << 2,
|
||||
NORDIC_CLASSIC: 1 << 3,
|
||||
@@ -55,7 +55,7 @@ export const DIFF_EXPERT = 4;
|
||||
|
||||
/** `edgeGroom` bits. */
|
||||
export const Groom = {
|
||||
CLASSIC: 1 << 0,
|
||||
CLASSIC: 1,
|
||||
SKATING: 1 << 1,
|
||||
SCOOTER: 1 << 2,
|
||||
BACKCOUNTRY: 1 << 3,
|
||||
@@ -100,7 +100,7 @@ export const Lift = {
|
||||
|
||||
/** `nodeFlags` bits. */
|
||||
export const NodeFlag = {
|
||||
STATION: 1 << 0,
|
||||
STATION: 1,
|
||||
PORTAL: 1 << 1,
|
||||
DISMOUNT_YES: 1 << 2,
|
||||
DISMOUNT_SOMETIMES: 1 << 3,
|
||||
@@ -116,7 +116,7 @@ export const NodeFlag = {
|
||||
* way tagged `piste:type=yes`, usable as a connection only (cost x1.5).
|
||||
*/
|
||||
export const EdgeFlag = {
|
||||
DIR_FROM_DEM: 1 << 0,
|
||||
DIR_FROM_DEM: 1,
|
||||
DIR_CONFLICT: 1 << 1,
|
||||
RELATION_INHERITED: 1 << 2,
|
||||
TECHNIQUE_ASSUMED: 1 << 3,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { StorageReclaimableCategory, StorageReferenceSourceId } from './storage-reclaim.types';
|
||||
import type { BackendSnapshot, StorageRegistryService } from './storage-registry.service';
|
||||
import { SERVED_CATEGORIES, type ServedCategory } from './storage.types';
|
||||
import { stripTrailingSlashes } from '@trek/shared';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
@@ -177,7 +178,7 @@ function realOrNull(target: string): string | null {
|
||||
|
||||
/** A resolved folder with forward slashes and one trailing slash. */
|
||||
function slashed(folder: string): string {
|
||||
return `${folder.replace(/\\/g, '/').replace(/\/+$/, '')}/`;
|
||||
return `${stripTrailingSlashes(folder.replace(/\\/g, '/'))}/`;
|
||||
}
|
||||
|
||||
function asList(value: string | number | string[] | undefined): string[] {
|
||||
|
||||
@@ -95,10 +95,16 @@ export class ToursImportController {
|
||||
@UploadedFile() file: Express.Multer.File | undefined,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
// None is a hike, as every import was before the type could be chosen.
|
||||
@Body() fields: TourGpxImportFieldsDto = { tour_type: 'hike' },
|
||||
@Body() fields?: TourGpxImportFieldsDto,
|
||||
) {
|
||||
const buffer = await this.checkedFile(user, tripId, file);
|
||||
const result = await this.tours.importGpxAsTour(tripId, buffer, file?.originalname, socketId, fields);
|
||||
const result = await this.tours.importGpxAsTour(
|
||||
tripId,
|
||||
buffer,
|
||||
file?.originalname,
|
||||
socketId,
|
||||
fields ?? { tour_type: 'hike' },
|
||||
);
|
||||
if (!result) {
|
||||
throw noTrackFound(file?.originalname);
|
||||
}
|
||||
|
||||
@@ -296,7 +296,7 @@ export function filenameOf(title: string): string {
|
||||
.normalize('NFKD')
|
||||
.replace(/\p{M}/gu, '')
|
||||
.replace(/[^\p{L}\p{N}]+/gu, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.replace(/^-|-$/g, '')
|
||||
.slice(0, 60);
|
||||
return slug || 'booking';
|
||||
}
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { readCappedJson } from '../../utils/cappedFetch';
|
||||
import { ResponseTooLargeError, safeFetch, SsrfBlockedError } from '../../utils/ssrfGuard';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { WANDERER_SEARCH_PAGE_SIZE, type WandererBbox, type WandererErrorCode } from '@trek/shared';
|
||||
import {
|
||||
stripTrailingSlashes,
|
||||
WANDERER_SEARCH_PAGE_SIZE,
|
||||
type WandererBbox,
|
||||
type WandererErrorCode,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
@@ -110,9 +115,7 @@ export type WandererTrailRecord = z.infer<typeof trailSchema>;
|
||||
* full `/api/v1` are all taken off, so the client can append its own.
|
||||
*/
|
||||
export function instanceOrigin(baseUrl: string): string {
|
||||
return baseUrl
|
||||
.trim()
|
||||
.replace(/\/+$/, '')
|
||||
return stripTrailingSlashes(baseUrl.trim())
|
||||
.replace(/\/api\/v1$/i, '')
|
||||
.replace(/\/api$/i, '');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user