Commit 692ad85ae6
Unsigned
Layout: unified · split
api/src/app.ts +2
| @@ -22,6 +22,7 @@ import discord from '@/routes/private/discord' | |||
| 22 | import reddit from '@/routes/private/reddit' | 22 | import reddit from '@/routes/private/reddit' |
| 23 | import website from '@/routes/private/website' | 23 | import website from '@/routes/private/website' |
| 24 | import security from '@/routes/private/security' | 24 | import security from '@/routes/private/security' |
| 25 | import docker from '@/routes/private/docker' | ||
| 25 | 26 | ||
| 26 | import mcp from '@/routes/mcp' | 27 | import mcp from '@/routes/mcp' |
| 27 | 28 | ||
| @@ -47,6 +48,7 @@ const buildPrivate = () => { | |||
| 47 | priv.route('/', reddit) | 48 | priv.route('/', reddit) |
| 48 | priv.route('/', website) | 49 | priv.route('/', website) |
| 49 | priv.route('/', security) | 50 | priv.route('/', security) |
| 51 | priv.route('/', docker) | ||
| 50 | return priv | 52 | return priv |
| 51 | } | 53 | } |
| 52 | 54 | ||
api/src/lib/cache/freshness.ts +1
| @@ -13,6 +13,7 @@ export const CACHE_DAYS = { | |||
| 13 | github: 7, | 13 | github: 7, |
| 14 | discord: 14, | 14 | discord: 14, |
| 15 | reddit: 14, | 15 | reddit: 14, |
| 16 | docker: 90, | ||
| 16 | } as const | 17 | } as const |
| 17 | 18 | ||
| 18 | export type CacheRoute = keyof typeof CACHE_DAYS | 19 | export type CacheRoute = keyof typeof CACHE_DAYS |
api/src/lib/docker.ts added +98
| @@ -0,0 +1,98 @@ | |||
| 1 | // Turns a Portainer template into docker run / compose usage output | ||
| 2 | |||
| 3 | export interface TemplateEnv { | ||
| 4 | name: string | ||
| 5 | label?: string | ||
| 6 | default?: string | ||
| 7 | description?: string | ||
| 8 | } | ||
| 9 | |||
| 10 | export interface TemplateVolume { | ||
| 11 | container: string | ||
| 12 | bind?: string | ||
| 13 | readonly?: boolean | ||
| 14 | } | ||
| 15 | |||
| 16 | export interface Template { | ||
| 17 | title?: string | ||
| 18 | name?: string | ||
| 19 | image?: string | ||
| 20 | logo?: string | ||
| 21 | description?: string | ||
| 22 | categories?: string[] | ||
| 23 | ports?: string[] | ||
| 24 | env?: TemplateEnv[] | ||
| 25 | volumes?: TemplateVolume[] | ||
| 26 | restart_policy?: string | ||
| 27 | } | ||
| 28 | |||
| 29 | // Strip everything but alphanumerics so loose name matching works | ||
| 30 | export const normalize = (str: string) => str.replace(/[^a-z0-9]/gi, '').toLowerCase() | ||
| 31 | |||
| 32 | // Minimal YAML serialiser, enough for the compose object we build | ||
| 33 | const toYaml = (data: unknown, indent = ''): string[] => { | ||
| 34 | const lines: string[] = [] | ||
| 35 | if (Array.isArray(data)) { | ||
| 36 | for (const el of data) lines.push(`${indent}- ${scalar(el)}`) | ||
| 37 | } else if (data && typeof data === 'object') { | ||
| 38 | for (const [key, value] of Object.entries(data)) { | ||
| 39 | if (value === undefined || value === null) continue | ||
| 40 | if (typeof value === 'object') { | ||
| 41 | const child = toYaml(value, `${indent} `) | ||
| 42 | if (!child.length) continue | ||
| 43 | lines.push(`${indent}${key}:`) | ||
| 44 | lines.push(...child) | ||
| 45 | } else { | ||
| 46 | lines.push(`${indent}${key}: ${scalar(value)}`) | ||
| 47 | } | ||
| 48 | } | ||
| 49 | } | ||
| 50 | return lines | ||
| 51 | } | ||
| 52 | |||
| 53 | // Quote scalars holding a colon so ports/images aren't misread as YAML maps or sexagesimals | ||
| 54 | const scalar = (value: unknown): string => { | ||
| 55 | const str = String(value) | ||
| 56 | return str.includes(':') ? `"${str}"` : str | ||
| 57 | } | ||
| 58 | |||
| 59 | // Volume mount, host:container when a host bind is given, else an anonymous volume | ||
| 60 | const mount = (vol: TemplateVolume) => | ||
| 61 | vol.bind ? `${vol.bind}:${vol.container}` : vol.container | ||
| 62 | |||
| 63 | // A copy-pasteable `docker run` command for the template | ||
| 64 | export const runCommand = (t: Template): string => { | ||
| 65 | const parts = ['docker run -d'] | ||
| 66 | for (const port of t.ports ?? []) parts.push(`-p ${port}`) | ||
| 67 | for (const env of t.env ?? []) parts.push(`-e ${env.name}=\${${env.name}}`) | ||
| 68 | for (const vol of t.volumes ?? []) { | ||
| 69 | parts.push(`-v ${mount(vol)}${vol.readonly ? ':ro' : ''}`) | ||
| 70 | } | ||
| 71 | if (t.restart_policy) parts.push(`--restart=${t.restart_policy}`) | ||
| 72 | parts.push(t.image ?? '') | ||
| 73 | return parts.join(' \\\n ') | ||
| 74 | } | ||
| 75 | |||
| 76 | // Equivalent docker-compose.yml as a YAML string | ||
| 77 | export const composeFile = (t: Template): string => { | ||
| 78 | const service = | ||
| 79 | (t.title ?? 'app') | ||
| 80 | .toLowerCase() | ||
| 81 | .replace(/[^a-z0-9]+/g, '-') | ||
| 82 | .replace(/^-+|-+$/g, '') || 'app' | ||
| 83 | const compose = { | ||
| 84 | version: '3.8', | ||
| 85 | services: { | ||
| 86 | [service]: { | ||
| 87 | image: t.image, | ||
| 88 | ports: t.ports ?? [], | ||
| 89 | environment: Object.fromEntries( | ||
| 90 | (t.env ?? []).map((e) => [e.name, e.default ?? '']), | ||
| 91 | ), | ||
| 92 | volumes: (t.volumes ?? []).map(mount), | ||
| 93 | restart: t.restart_policy, | ||
| 94 | }, | ||
| 95 | }, | ||
| 96 | } | ||
| 97 | return toYaml(compose).join('\n') | ||
| 98 | } | ||
api/src/lib/fetch.ts +1
| @@ -18,6 +18,7 @@ const ALLOWED_HOSTS = new Set([ | |||
| 18 | 'raw.githubusercontent.com', | 18 | 'raw.githubusercontent.com', |
| 19 | 'api.deps.dev', | 19 | 'api.deps.dev', |
| 20 | 'plexus.techlore.tech', | 20 | 'plexus.techlore.tech', |
| 21 | 'hub.docker.com', | ||
| 21 | ]) | 22 | ]) |
| 22 | 23 | ||
| 23 | export interface FetchOpts { | 24 | export interface FetchOpts { |
api/src/routes/private/docker.ts added +88
| @@ -0,0 +1,88 @@ | |||
| 1 | // Docker image info from Portainer templates plus Docker Hub metrics | ||
| 2 | import { createRoute, z } from '@hono/zod-openapi' | ||
| 3 | import { ApiError } from '@/lib/errors' | ||
| 4 | import { fetchJson } from '@/lib/fetch' | ||
| 5 | import { freshSeconds } from '@/lib/cache/freshness' | ||
| 6 | import { newApp } from '@/lib/openapi' | ||
| 7 | import { composeFile, normalize, runCommand, type Template } from '@/lib/docker' | ||
| 8 | import { DockerInfoSchema, ErrorResponse, Ok } from '@/schemas' | ||
| 9 | |||
| 10 | const app = newApp() | ||
| 11 | |||
| 12 | const FRESH_TTL = freshSeconds('docker') | ||
| 13 | |||
| 14 | const TEMPLATES_URL = | ||
| 15 | 'https://raw.githubusercontent.com/Lissy93/portainer-templates/main/templates.json' | ||
| 16 | |||
| 17 | interface TemplateList { | ||
| 18 | templates?: Template[] | ||
| 19 | } | ||
| 20 | |||
| 21 | // Templates whose title or name loosely matches, preferring runnable (image-bearing) ones | ||
| 22 | const matchTemplate = (templates: Template[], query: string) => { | ||
| 23 | const matches = templates.filter( | ||
| 24 | (t) => | ||
| 25 | normalize(t.title ?? '').includes(query) || normalize(t.name ?? '').includes(query), | ||
| 26 | ) | ||
| 27 | return matches.find((t) => t.image) ?? matches[0] | ||
| 28 | } | ||
| 29 | |||
| 30 | // Docker Hub repo metrics for an image, null when missing or unavailable | ||
| 31 | const getHubData = async (image: string, token?: string) => { | ||
| 32 | const [name] = image.split(':') | ||
| 33 | const [namespace, repo] = name.includes('/') ? name.split('/') : ['library', name] | ||
| 34 | const headers: Record<string, string> = {} | ||
| 35 | if (token) headers.Authorization = `Bearer ${token}` | ||
| 36 | try { | ||
| 37 | return await fetchJson( | ||
| 38 | `https://hub.docker.com/v2/repositories/${namespace}/${repo}/`, | ||
| 39 | { headers }, | ||
| 40 | ) | ||
| 41 | } catch { | ||
| 42 | return null | ||
| 43 | } | ||
| 44 | } | ||
| 45 | |||
| 46 | const route = createRoute({ | ||
| 47 | method: 'get', | ||
| 48 | path: '/enrich/docker/{name}', | ||
| 49 | tags: ['Enrichment'], | ||
| 50 | summary: 'Docker image info', | ||
| 51 | request: { params: z.object({ name: z.string().min(1) }) }, | ||
| 52 | responses: { | ||
| 53 | 200: Ok(DockerInfoSchema), | ||
| 54 | 400: ErrorResponse, | ||
| 55 | 401: ErrorResponse, | ||
| 56 | 404: ErrorResponse, | ||
| 57 | 500: ErrorResponse, | ||
| 58 | }, | ||
| 59 | }) | ||
| 60 | |||
| 61 | app.openapi(route, async (c) => { | ||
| 62 | const { name } = c.req.valid('param') | ||
| 63 | const query = normalize(name) | ||
| 64 | if (!query) throw new ApiError('BAD_REQUEST', 'Invalid image name', 400) | ||
| 65 | const data = await c.var.storage.fetch(`docker:${query}`, FRESH_TTL, async () => { | ||
| 66 | const list = await fetchJson<TemplateList>(TEMPLATES_URL) | ||
| 67 | const template = matchTemplate(list.templates ?? [], query) | ||
| 68 | if (!template) { | ||
| 69 | throw new ApiError('NOT_FOUND', `'${name}' not found in Portainer templates`, 404) | ||
| 70 | } | ||
| 71 | const dockerHubData = template.image | ||
| 72 | ? await getHubData(template.image, c.env.DOCKERHUB_TOKEN) | ||
| 73 | : null | ||
| 74 | return { | ||
| 75 | found: true, | ||
| 76 | error: null, | ||
| 77 | template, | ||
| 78 | dockerHubData, | ||
| 79 | usage: { | ||
| 80 | dockerRunCommand: runCommand(template), | ||
| 81 | dockerComposeFile: composeFile(template), | ||
| 82 | }, | ||
| 83 | } | ||
| 84 | }) | ||
| 85 | return c.json(data, 200) | ||
| 86 | }) | ||
| 87 | |||
| 88 | export default app | ||
api/src/schemas/index.ts +4
| @@ -144,6 +144,10 @@ export const WebsiteReportSchema = z | |||
| 144 | .object({}) | 144 | .object({}) |
| 145 | .openapi('WebsiteReport', { description: 'APIVoid url reputation report, passthrough' }) | 145 | .openapi('WebsiteReport', { description: 'APIVoid url reputation report, passthrough' }) |
| 146 | 146 | ||
| 147 | export const DockerInfoSchema = z.object({}).openapi('DockerInfo', { | ||
| 148 | description: 'Portainer template, Docker Hub metrics and generated run/compose usage', | ||
| 149 | }) | ||
| 150 | |||
| 147 | // GitHub repo summary, shape is fixed by the mapper functions | 151 | // GitHub repo summary, shape is fixed by the mapper functions |
| 148 | export const GithubRepoSchema = z | 152 | export const GithubRepoSchema = z |
| 149 | .object({ | 153 | .object({ |
api/src/types.ts +1
| @@ -60,6 +60,7 @@ export interface AppEnv { | |||
| 60 | APIVOID_API_KEY?: string | 60 | APIVOID_API_KEY?: string |
| 61 | EXODUS_TOKEN?: string | 61 | EXODUS_TOKEN?: string |
| 62 | GITHUB_TOKEN?: string | 62 | GITHUB_TOKEN?: string |
| 63 | DOCKERHUB_TOKEN?: string | ||
| 63 | CACHE?: KVNamespace | 64 | CACHE?: KVNamespace |
| 64 | RATE_LIMIT?: RateLimiter | 65 | RATE_LIMIT?: RateLimiter |
| 65 | API_BASE?: string | 66 | API_BASE?: string |
api/tests/app.test.ts +5
| @@ -72,6 +72,11 @@ describe('auth', () => { | |||
| 72 | const res = await hit('/v1/enrich/security/jquery/jquery') | 72 | const res = await hit('/v1/enrich/security/jquery/jquery') |
| 73 | expect(res.status).toBe(401) | 73 | expect(res.status).toBe(401) |
| 74 | }) | 74 | }) |
| 75 | |||
| 76 | it('docker enrich route requires auth', async () => { | ||
| 77 | const res = await hit('/v1/enrich/docker/pihole') | ||
| 78 | expect(res.status).toBe(401) | ||
| 79 | }) | ||
| 75 | }) | 80 | }) |
| 76 | 81 | ||
| 77 | describe('middleware scoping', () => { | 82 | describe('middleware scoping', () => { |
api/tests/docker.test.ts added +77
| @@ -0,0 +1,77 @@ | |||
| 1 | // Unit tests for the Portainer template -> docker run / compose builders | ||
| 2 | import { describe, it, expect } from 'vitest' | ||
| 3 | import { composeFile, normalize, runCommand, type Template } from '@/lib/docker' | ||
| 4 | |||
| 5 | const template: Template = { | ||
| 6 | title: 'Pi-hole', | ||
| 7 | image: 'pihole/pihole:latest', | ||
| 8 | ports: ['53:53/tcp', '8080:80'], | ||
| 9 | env: [{ name: 'TZ', default: 'UTC' }, { name: 'WEBPASSWORD' }], | ||
| 10 | volumes: [ | ||
| 11 | { bind: '/etc/pihole', container: '/data', readonly: true }, | ||
| 12 | { container: '/cache' }, | ||
| 13 | ], | ||
| 14 | restart_policy: 'unless-stopped', | ||
| 15 | } | ||
| 16 | |||
| 17 | describe('normalize', () => { | ||
| 18 | it('strips symbols and lowercases', () => { | ||
| 19 | expect(normalize('Pi-Hole!')).toBe('pihole') | ||
| 20 | }) | ||
| 21 | }) | ||
| 22 | |||
| 23 | describe('runCommand', () => { | ||
| 24 | const out = runCommand(template) | ||
| 25 | |||
| 26 | it('lays out flags then the image last', () => { | ||
| 27 | expect(out.startsWith('docker run -d \\')).toBe(true) | ||
| 28 | expect(out.endsWith('pihole/pihole:latest')).toBe(true) | ||
| 29 | }) | ||
| 30 | |||
| 31 | it('maps ports, env placeholders, read-only volumes and restart', () => { | ||
| 32 | expect(out).toContain('-p 53:53/tcp') | ||
| 33 | expect(out).toContain('-e WEBPASSWORD=${WEBPASSWORD}') | ||
| 34 | expect(out).toContain('-v /etc/pihole:/data:ro') | ||
| 35 | expect(out).toContain('--restart=unless-stopped') | ||
| 36 | }) | ||
| 37 | |||
| 38 | it('renders a bind-less volume as an anonymous mount', () => { | ||
| 39 | expect(out).toContain('-v /cache') | ||
| 40 | expect(out).not.toContain('undefined') | ||
| 41 | }) | ||
| 42 | }) | ||
| 43 | |||
| 44 | describe('composeFile', () => { | ||
| 45 | const out = composeFile(template) | ||
| 46 | |||
| 47 | it('builds a service keyed by a slugified title', () => { | ||
| 48 | expect(out).toContain('services:') | ||
| 49 | expect(out).toContain('pi-hole:') | ||
| 50 | expect(out).toContain('image: "pihole/pihole:latest"') | ||
| 51 | }) | ||
| 52 | |||
| 53 | it('quotes ports, keeps protocol and resolves env defaults', () => { | ||
| 54 | expect(out).toContain('- "53:53/tcp"') | ||
| 55 | expect(out).toContain('TZ: UTC') | ||
| 56 | expect(out).toContain('WEBPASSWORD: ') | ||
| 57 | }) | ||
| 58 | |||
| 59 | it('maps a bind-less volume to its container path', () => { | ||
| 60 | expect(out).toContain('- /cache') | ||
| 61 | expect(out).not.toContain('undefined') | ||
| 62 | }) | ||
| 63 | |||
| 64 | it('drops empty sections rather than emitting bare keys or undefined', () => { | ||
| 65 | const bare = composeFile({ title: 'bare', image: 'redis' }) | ||
| 66 | expect(bare).not.toContain('undefined') | ||
| 67 | expect(bare).not.toContain('environment:') | ||
| 68 | expect(bare).not.toContain('ports:') | ||
| 69 | expect(bare).not.toContain('volumes:') | ||
| 70 | }) | ||
| 71 | |||
| 72 | it('trims slug punctuation from the service key', () => { | ||
| 73 | expect(composeFile({ title: 'Nextcloud (Container)', image: 'x' })).toContain( | ||
| 74 | 'nextcloud-container:', | ||
| 75 | ) | ||
| 76 | }) | ||
| 77 | }) | ||
web/src/utils/fetch-docker-instructions.ts +3 −2
| @@ -1,12 +1,13 @@ | |||
| 1 | import { error } from './logger'; | 1 | import { error } from './logger'; |
| 2 | import { safeFetch } from './safe-fetch'; | 2 | import { safeFetch } from './safe-fetch'; |
| 3 | import { apiBase, enrichHeaders } from './api-config'; | ||
| 3 | 4 | ||
| 4 | export const fetchDockerData = async ( | 5 | export const fetchDockerData = async ( |
| 5 | serviceName: string, | 6 | serviceName: string, |
| 6 | ): Promise<TemplateResponse | null> => { | 7 | ): Promise<TemplateResponse | null> => { |
| 7 | const endpoint = `https://docker-info.as93.workers.dev/${serviceName}`; | 8 | const endpoint = `${apiBase}/v1/enrich/docker/${encodeURIComponent(serviceName)}`; |
| 8 | try { | 9 | try { |
| 9 | const res = await safeFetch(endpoint); | 10 | const res = await safeFetch(endpoint, { headers: enrichHeaders() }); |
| 10 | if (!res.ok) { | 11 | if (!res.ok) { |
| 11 | error('Docker', `HTTP ${res.status} for ${serviceName} (${endpoint})`); | 12 | error('Docker', `HTTP ${res.status} for ${serviceName} (${endpoint})`); |
| 12 | return null; | 13 | return null; |