Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/lib/server/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
*/

import os from 'node:os';
import { createHash } from 'node:crypto';
import { createHash, randomInt } from 'node:crypto';
import argon2 from 'argon2';
import type { Cookies } from '@sveltejs/kit';
import {
Expand Down Expand Up @@ -886,7 +886,7 @@ function generateBackupCodes(): string[] {
for (let i = 0; i < 10; i++) {
let code = '';
for (let j = 0; j < 8; j++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
code += chars.charAt(randomInt(chars.length));
}
codes.push(code);
}
Expand Down
2 changes: 1 addition & 1 deletion src/lib/server/backups/backup-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,7 @@ export class BackupService {
const { code, message } = errorInfo(err);
try { await this.ports.setConfigStatus(job.configId, 'failed'); } catch { /* non-fatal */ }
await op.close({ kind: 'error', code, message }, { errorCode: code });
try { await this.ports.notify('backup_failed', { title: 'Backup failed', message: `Backup of "${job.targetName}" failed: ${message} (${code})`, type: 'error', target: job.targetName, kind: 'backup', errorCode: code, message }, envId); } catch { /* non-fatal */ }
try { await this.ports.notify('backup_failed', { title: 'Backup failed', message: `Backup of "${job.targetName}" failed: ${message} (${code})`, type: 'error', target: job.targetName, kind: 'backup', errorCode: code }, envId); } catch { /* non-fatal */ }
// Per-config failure webhook.
if (job.options.webhookFailure) {
try {
Expand Down
2 changes: 1 addition & 1 deletion src/lib/server/chown-spec-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

// A single user or group token: a numeric id, or a name (letters, digits, and the
// usual account punctuation `_ - .`, starting with a letter/digit/underscore).
const TOKEN = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/;
const TOKEN = /^\w[A-Za-z0-9_.-]*$/;

export interface ChownSpec {
/** The exact `owner[:group]` string to pass to chown. */
Expand Down
10 changes: 8 additions & 2 deletions src/lib/server/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3354,7 +3354,10 @@ export async function getContainerTagIds(containerName: string, environmentId: n
export async function getContainerTagsMap(environmentId: number | null): Promise<Record<string, number[]>> {
const rows = await db.select().from(containerTags).where(envClause(containerTags.environmentId, environmentId));
const map: Record<string, number[]> = {};
for (const r of rows) (map[r.containerName] ??= []).push(r.tagId);
for (const r of rows) {
map[r.containerName] ??= [];
map[r.containerName].push(r.tagId);
}
return map;
}

Expand All @@ -3379,7 +3382,10 @@ export async function getStackTagIds(stackName: string, environmentId: number |
export async function getStackTagsMap(environmentId: number | null): Promise<Record<string, number[]>> {
const rows = await db.select().from(stackTags).where(envClause(stackTags.environmentId, environmentId));
const map: Record<string, number[]> = {};
for (const r of rows) (map[r.stackName] ??= []).push(r.tagId);
for (const r of rows) {
map[r.stackName] ??= [];
map[r.stackName].push(r.tagId);
}
return map;
}

Expand Down
2 changes: 1 addition & 1 deletion src/lib/server/docker-demux-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export function demuxDockerStream(
return options?.separateStreams ? { stdout: raw, stderr: '' } : raw;
}

const payload = buffer.slice(offset + 8, offset + 8 + frameSize).toString('utf-8');
const payload = buffer.subarray(offset + 8, offset + 8 + frameSize).toString('utf-8');

if (streamType === 1) {
stdout.push(payload);
Expand Down
4 changes: 2 additions & 2 deletions src/lib/server/docker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2366,8 +2366,8 @@ export async function createContainerFromMetadata(
envId?: number | null,
log?: (msg: string) => void
): Promise<{ Id: string }> {
const config = { ...metadata.config } || {};
const hostConfig = { ...metadata.hostConfig } || {};
const config = { ...metadata.config };
const hostConfig = { ...metadata.hostConfig };
const networks: Record<string, any> = metadata.networkSettings?.Networks || {};

const networkMode = hostConfig.NetworkMode || '';
Expand Down
10 changes: 10 additions & 0 deletions src/lib/server/env-param.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* Parse the `?env=` query param that scopes a name-keyed API endpoint to an
* environment. Null (omit the param) targets the local/default environment.
* Shared by the tag/icon endpoints so the parse is defined once.
*/
export function parseEnvParam(raw: string | null): number | null {
if (!raw) return null;
const n = Number.parseInt(raw, 10);
return Number.isNaN(n) ? null : n;
}
3 changes: 2 additions & 1 deletion src/lib/server/scheduler/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -901,7 +901,8 @@ export async function triggerSystemJob(jobId: string): Promise<{ success: boolea
*/
export async function triggerDeployLogReconcile(): Promise<{ success: boolean; executionId?: number; error?: string }> {
try {
runDeployLogReconcileJob('manual');
// Run in background - the job records its own execution row.
void runDeployLogReconcileJob('manual');
return { success: true };
} catch (error: any) {
return { success: false, error: error.message };
Expand Down
4 changes: 2 additions & 2 deletions src/lib/server/stats-calc-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ export function calculateCpuPercent(stats: DockerStatsPayload | null | undefined
// Wall-clock formula (matches Docker CLI / Portainer for Windows containers):
// possIntervals = num_procs * elapsed-milliseconds; cpu% = cpuDelta / (possIntervals * 100).
// read/preread are RFC3339 timestamps. No system_cpu_usage exists on Windows.
const readMs = stats.read ? new Date(stats.read).getTime() : NaN;
const prereadMs = stats.preread ? new Date(stats.preread).getTime() : NaN;
const readMs = stats.read ? new Date(stats.read).getTime() : Number.NaN;
const prereadMs = stats.preread ? new Date(stats.preread).getTime() : Number.NaN;
const possIntervals = (stats.num_procs ?? 0) * (readMs - prereadMs);
if (Number.isFinite(possIntervals) && possIntervals > 0 && cpuDelta > 0) {
return cpuDelta / (possIntervals * 100);
Expand Down
2 changes: 1 addition & 1 deletion src/lib/utils/gutter-contrast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export interface Rgb {
// Returns null for anything else (e.g. "transparent", named colours, empty).
export function parseRgb(color: string | null | undefined): Rgb | null {
if (!color) return null;
const m = color.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i);
const m = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i.exec(color);
if (!m) return null;
return { r: Number(m[1]), g: Number(m[2]), b: Number(m[3]) };
}
Expand Down
4 changes: 2 additions & 2 deletions src/lib/utils/palette-filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ export interface PaletteItem {
export type DefaultCaps = Record<string, number>;

function escapeRegExp(s: string): string {
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
return s.replace(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
}

/** The word-boundary matcher for a query: `q` starts a word (^, space, -, _, /). */
export function wordBoundaryRegex(q: string): RegExp {
return new RegExp(`(^|[\\s\\-_/])${escapeRegExp(q)}`);
return new RegExp(String.raw`(^|[\s\-_/])` + escapeRegExp(q));
}

/**
Expand Down
6 changes: 4 additions & 2 deletions src/lib/utils/session-expiry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@

export function extractPath(input: RequestInfo | URL, origin: string): string | null {
try {
const url =
typeof input === 'string' ? input : input instanceof Request ? input.url : String(input);
let url: string;
if (typeof input === 'string') url = input;
else if (input instanceof Request) url = input.url;
else url = String(input);
return new URL(url, origin).pathname;
} catch {
return null;
Expand Down
2 changes: 1 addition & 1 deletion src/lib/utils/tags-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ export function matchesTagFilter(
mode: TagFilterMode = 'all'
): boolean {
if (!filterTagIds.length) return true;
if (!itemTagIds || !itemTagIds.length) return false;
if (!itemTagIds?.length) return false;
const have = new Set(itemTagIds);
return mode === 'any'
? filterTagIds.some((id) => have.has(id))
Expand Down
9 changes: 2 additions & 7 deletions src/routes/api/container-icons/+server.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { authorize } from '$lib/server/authorize';
import { parseEnvParam } from '$lib/server/env-param';
import { getContainerIconOverrides } from '$lib/server/db';

function parseEnv(raw: string | null): number | null {
if (!raw) return null;
const n = parseInt(raw, 10);
return Number.isNaN(n) ? null : n;
}

/**
* @openapi
* summary: List all container icon overrides for an environment as a name -> icon map
Expand All @@ -20,7 +15,7 @@ function parseEnv(raw: string | null): number | null {
*/
export const GET: RequestHandler = async ({ url, cookies }) => {
const auth = await authorize(cookies);
const envId = parseEnv(url.searchParams.get('env'));
const envId = parseEnvParam(url.searchParams.get('env'));
if (auth.authEnabled && !(await auth.can('containers', 'view', envId ?? undefined))) {
return json({ error: 'Permission denied' }, { status: 403 });
}
Expand Down
13 changes: 4 additions & 9 deletions src/routes/api/container-icons/[name]/+server.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { authorize } from '$lib/server/authorize';
import { parseEnvParam } from '$lib/server/env-param';
import { getContainerIconOverride, setContainerIconOverride, deleteContainerIconOverride } from '$lib/server/db';
import { saveContainerIcon, deleteContainerIcon, getContainerIconBuffer, looksLikeImage } from '$lib/server/container-icons';

function parseEnv(raw: string | null): number | null {
if (!raw) return null;
const n = parseInt(raw, 10);
return Number.isNaN(n) ? null : n;
}

/**
* @openapi
* summary: Get a container's uploaded custom icon (raw image/webp bytes, not JSON)
Expand All @@ -21,7 +16,7 @@ function parseEnv(raw: string | null): number | null {
*/
export const GET: RequestHandler = async ({ params, url, cookies }) => {
const auth = await authorize(cookies);
const envId = parseEnv(url.searchParams.get('env'));
const envId = parseEnvParam(url.searchParams.get('env'));
if (auth.authEnabled && !(await auth.can('containers', 'view', envId ?? undefined))) {
return json({ error: 'Permission denied' }, { status: 403 });
}
Expand Down Expand Up @@ -52,7 +47,7 @@ export const GET: RequestHandler = async ({ params, url, cookies }) => {
*/
export const POST: RequestHandler = async ({ params, url, request, cookies }) => {
const auth = await authorize(cookies);
const envId = parseEnv(url.searchParams.get('env'));
const envId = parseEnvParam(url.searchParams.get('env'));
if (auth.authEnabled && !(await auth.can('containers', 'edit', envId ?? undefined))) {
return json({ error: 'Permission denied' }, { status: 403 });
}
Expand Down Expand Up @@ -91,7 +86,7 @@ export const POST: RequestHandler = async ({ params, url, request, cookies }) =>
*/
export const DELETE: RequestHandler = async ({ params, url, cookies }) => {
const auth = await authorize(cookies);
const envId = parseEnv(url.searchParams.get('env'));
const envId = parseEnvParam(url.searchParams.get('env'));
if (auth.authEnabled && !(await auth.can('containers', 'edit', envId ?? undefined))) {
return json({ error: 'Permission denied' }, { status: 403 });
}
Expand Down
9 changes: 2 additions & 7 deletions src/routes/api/container-tags/+server.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { authorize } from '$lib/server/authorize';
import { parseEnvParam } from '$lib/server/env-param';
import { getContainerTagsMap } from '$lib/server/db';

function parseEnv(raw: string | null): number | null {
if (!raw) return null;
const n = parseInt(raw, 10);
return Number.isNaN(n) ? null : n;
}

/**
* @openapi
* summary: List all container tag assignments for an environment as a name -> tagIds map
Expand All @@ -20,7 +15,7 @@ function parseEnv(raw: string | null): number | null {
*/
export const GET: RequestHandler = async ({ url, cookies }) => {
const auth = await authorize(cookies);
const envId = parseEnv(url.searchParams.get('env'));
const envId = parseEnvParam(url.searchParams.get('env'));
if (auth.authEnabled && !(await auth.can('containers', 'view', envId ?? undefined))) {
return json({ error: 'Permission denied' }, { status: 403 });
}
Expand Down
11 changes: 3 additions & 8 deletions src/routes/api/container-tags/[name]/+server.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { authorize } from '$lib/server/authorize';
import { parseEnvParam } from '$lib/server/env-param';
import { getContainerTagIds, setContainerTagIds } from '$lib/server/db';

function parseEnv(raw: string | null): number | null {
if (!raw) return null;
const n = parseInt(raw, 10);
return Number.isNaN(n) ? null : n;
}

/**
* @openapi
* summary: Get the tag ids assigned to one container (by name)
Expand All @@ -20,7 +15,7 @@ function parseEnv(raw: string | null): number | null {
*/
export const GET: RequestHandler = async ({ params, url, cookies }) => {
const auth = await authorize(cookies);
const envId = parseEnv(url.searchParams.get('env'));
const envId = parseEnvParam(url.searchParams.get('env'));
if (auth.authEnabled && !(await auth.can('containers', 'view', envId ?? undefined))) {
return json({ error: 'Permission denied' }, { status: 403 });
}
Expand All @@ -40,7 +35,7 @@ export const GET: RequestHandler = async ({ params, url, cookies }) => {
*/
export const PUT: RequestHandler = async ({ params, url, request, cookies }) => {
const auth = await authorize(cookies);
const envId = parseEnv(url.searchParams.get('env'));
const envId = parseEnvParam(url.searchParams.get('env'));
if (auth.authEnabled && !(await auth.can('containers', 'edit', envId ?? undefined))) {
return json({ error: 'Permission denied' }, { status: 403 });
}
Expand Down
2 changes: 1 addition & 1 deletion src/routes/api/containers/[id]/exec/run/+server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export const POST: RequestHandler = async ({ params, request, cookies, url }) =>

const containerId = params.id;
const envIdParam = url.searchParams.get('envId');
const envId = envIdParam ? parseInt(envIdParam, 10) : undefined;
const envId = envIdParam ? Number.parseInt(envIdParam, 10) : undefined;

if (!await auth.can('containers', 'exec', envId)) {
return json({ error: 'Permission denied' }, { status: 403 });
Expand Down
2 changes: 1 addition & 1 deletion src/routes/api/containers/[id]/files/chown/+server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const POST: RequestHandler = async ({ params, url, cookies, request }) =>
const auth = await authorize(cookies);

const envId = url.searchParams.get('env');
const envIdNum = envId ? parseInt(envId) : undefined;
const envIdNum = envId ? Number.parseInt(envId) : undefined;

if (auth.authEnabled && !await auth.can('containers', 'exec', envIdNum)) {
return json({ error: 'Permission denied' }, { status: 403 });
Expand Down
6 changes: 3 additions & 3 deletions src/routes/api/containers/[id]/files/upload/+server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ export const POST: RequestHandler = async ({ params, url, request, cookies }) =>

const path = url.searchParams.get('path');
const envId = url.searchParams.get('env');
const envIdNum = envId ? parseInt(envId) : undefined;
const envIdNum = envId ? Number.parseInt(envId) : undefined;

// Permission check with environment context
if (auth.authEnabled && !await auth.can('containers', 'exec', envIdNum)) {
Expand Down Expand Up @@ -166,14 +166,14 @@ export const POST: RequestHandler = async ({ params, url, request, cookies }) =>
params.id,
path,
tar,
envId ? parseInt(envId) : undefined
envId ? Number.parseInt(envId) : undefined
);

// chown the uploaded file to the requested (or container-default) owner.
if (owner) {
const targetPath = path.endsWith('/') ? `${path}${file.name}` : `${path}/${file.name}`;
try {
await chownContainerPath(params.id, targetPath, owner, true, envId ? parseInt(envId) : undefined);
await chownContainerPath(params.id, targetPath, owner, true, envId ? Number.parseInt(envId) : undefined);
} catch (e) {
console.warn('Failed to set ownership on', targetPath, e);
}
Expand Down
9 changes: 2 additions & 7 deletions src/routes/api/stack-tags/+server.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { authorize } from '$lib/server/authorize';
import { parseEnvParam } from '$lib/server/env-param';
import { getStackTagsMap } from '$lib/server/db';

function parseEnv(raw: string | null): number | null {
if (!raw) return null;
const n = parseInt(raw, 10);
return Number.isNaN(n) ? null : n;
}

/**
* @openapi
* summary: List all stack tag assignments for an environment as a name -> tagIds map
Expand All @@ -20,7 +15,7 @@ function parseEnv(raw: string | null): number | null {
*/
export const GET: RequestHandler = async ({ url, cookies }) => {
const auth = await authorize(cookies);
const envId = parseEnv(url.searchParams.get('env'));
const envId = parseEnvParam(url.searchParams.get('env'));
if (auth.authEnabled && !(await auth.can('stacks', 'view', envId ?? undefined))) {
return json({ error: 'Permission denied' }, { status: 403 });
}
Expand Down
13 changes: 4 additions & 9 deletions src/routes/api/stacks/[name]/icon/+server.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { authorize } from '$lib/server/authorize';
import { parseEnvParam } from '$lib/server/env-param';
import { updateStackSource, getStackSource } from '$lib/server/db';
import { saveStackIcon, deleteStackIcon, getStackIconBuffer, looksLikeImage } from '$lib/server/stack-icons';

function parseEnv(raw: string | null): number | null {
if (!raw) return null;
const n = parseInt(raw, 10);
return Number.isNaN(n) ? null : n;
}

/**
* @openapi
* summary: Get a stack's uploaded custom icon (raw image/webp bytes, not JSON)
Expand All @@ -21,7 +16,7 @@ function parseEnv(raw: string | null): number | null {
*/
export const GET: RequestHandler = async ({ params, url, cookies }) => {
const auth = await authorize(cookies);
const envId = parseEnv(url.searchParams.get('env'));
const envId = parseEnvParam(url.searchParams.get('env'));
if (auth.authEnabled && !(await auth.can('stacks', 'view', envId ?? undefined))) {
return json({ error: 'Permission denied' }, { status: 403 });
}
Expand Down Expand Up @@ -52,7 +47,7 @@ export const GET: RequestHandler = async ({ params, url, cookies }) => {
*/
export const POST: RequestHandler = async ({ params, url, request, cookies }) => {
const auth = await authorize(cookies);
const envId = parseEnv(url.searchParams.get('env'));
const envId = parseEnvParam(url.searchParams.get('env'));
if (auth.authEnabled && !(await auth.can('stacks', 'edit', envId ?? undefined))) {
return json({ error: 'Permission denied' }, { status: 403 });
}
Expand Down Expand Up @@ -99,7 +94,7 @@ export const POST: RequestHandler = async ({ params, url, request, cookies }) =>
*/
export const DELETE: RequestHandler = async ({ params, url, cookies }) => {
const auth = await authorize(cookies);
const envId = parseEnv(url.searchParams.get('env'));
const envId = parseEnvParam(url.searchParams.get('env'));
if (auth.authEnabled && !(await auth.can('stacks', 'edit', envId ?? undefined))) {
return json({ error: 'Permission denied' }, { status: 403 });
}
Expand Down
Loading
Loading