Commit 692ad85ae6

692ad85ae6686ba8babe7a79fa83f506eef1a7ab

parent: 281749441c

Unsigned

Alicia Sykes <alicia@omg.lol> · 2026-06-09 17:43 UTC

Adds docker info endpoint

Layout: unified · split

api/src/app.ts +2
@@ -22,6 +22,7 @@ import discord from '@/routes/private/discord'
2222import reddit from '@/routes/private/reddit'
2323import website from '@/routes/private/website'
2424import security from '@/routes/private/security'
25import docker from '@/routes/private/docker'
2526
2627import mcp from '@/routes/mcp'
2728
@@ -47,6 +48,7 @@ const buildPrivate = () => {
4748 priv.route('/', reddit)
4849 priv.route('/', website)
4950 priv.route('/', security)
51 priv.route('/', docker)
5052 return priv
5153}
5254
api/src/lib/cache/freshness.ts +1
@@ -13,6 +13,7 @@ export const CACHE_DAYS = {
1313 github: 7,
1414 discord: 14,
1515 reddit: 14,
16 docker: 90,
1617} as const
1718
1819export 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
3export interface TemplateEnv {
4 name: string
5 label?: string
6 default?: string
7 description?: string
8}
9
10export interface TemplateVolume {
11 container: string
12 bind?: string
13 readonly?: boolean
14}
15
16export 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
30export const normalize = (str: string) => str.replace(/[^a-z0-9]/gi, '').toLowerCase()
31
32// Minimal YAML serialiser, enough for the compose object we build
33const 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
54const 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
60const mount = (vol: TemplateVolume) =>
61 vol.bind ? `${vol.bind}:${vol.container}` : vol.container
62
63// A copy-pasteable `docker run` command for the template
64export 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
77export 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([
1818 'raw.githubusercontent.com',
1919 'api.deps.dev',
2020 'plexus.techlore.tech',
21 'hub.docker.com',
2122])
2223
2324export 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
2import { createRoute, z } from '@hono/zod-openapi'
3import { ApiError } from '@/lib/errors'
4import { fetchJson } from '@/lib/fetch'
5import { freshSeconds } from '@/lib/cache/freshness'
6import { newApp } from '@/lib/openapi'
7import { composeFile, normalize, runCommand, type Template } from '@/lib/docker'
8import { DockerInfoSchema, ErrorResponse, Ok } from '@/schemas'
9
10const app = newApp()
11
12const FRESH_TTL = freshSeconds('docker')
13
14const TEMPLATES_URL =
15 'https://raw.githubusercontent.com/Lissy93/portainer-templates/main/templates.json'
16
17interface TemplateList {
18 templates?: Template[]
19}
20
21// Templates whose title or name loosely matches, preferring runnable (image-bearing) ones
22const 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
31const 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
46const 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
61app.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
88export default app
api/src/schemas/index.ts +4
@@ -144,6 +144,10 @@ export const WebsiteReportSchema = z
144144 .object({})
145145 .openapi('WebsiteReport', { description: 'APIVoid url reputation report, passthrough' })
146146
147export const DockerInfoSchema = z.object({}).openapi('DockerInfo', {
148 description: 'Portainer template, Docker Hub metrics and generated run/compose usage',
149})
150
147151// GitHub repo summary, shape is fixed by the mapper functions
148152export const GithubRepoSchema = z
149153 .object({
api/src/types.ts +1
@@ -60,6 +60,7 @@ export interface AppEnv {
6060 APIVOID_API_KEY?: string
6161 EXODUS_TOKEN?: string
6262 GITHUB_TOKEN?: string
63 DOCKERHUB_TOKEN?: string
6364 CACHE?: KVNamespace
6465 RATE_LIMIT?: RateLimiter
6566 API_BASE?: string
api/tests/app.test.ts +5
@@ -72,6 +72,11 @@ describe('auth', () => {
7272 const res = await hit('/v1/enrich/security/jquery/jquery')
7373 expect(res.status).toBe(401)
7474 })
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 })
7580})
7681
7782describe('middleware scoping', () => {
api/tests/docker.test.ts added +77
@@ -0,0 +1,77 @@
1// Unit tests for the Portainer template -> docker run / compose builders
2import { describe, it, expect } from 'vitest'
3import { composeFile, normalize, runCommand, type Template } from '@/lib/docker'
4
5const 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
17describe('normalize', () => {
18 it('strips symbols and lowercases', () => {
19 expect(normalize('Pi-Hole!')).toBe('pihole')
20 })
21})
22
23describe('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
44describe('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 @@
11import { error } from './logger';
22import { safeFetch } from './safe-fetch';
3import { apiBase, enrichHeaders } from './api-config';
34
45export const fetchDockerData = async (
56 serviceName: string,
67): Promise<TemplateResponse | null> => {
7 const endpoint = `https://docker-info.as93.workers.dev/${serviceName}`;
8 const endpoint = `${apiBase}/v1/enrich/docker/${encodeURIComponent(serviceName)}`;
89 try {
9 const res = await safeFetch(endpoint);
10 const res = await safeFetch(endpoint, { headers: enrichHeaders() });
1011 if (!res.ok) {
1112 error('Docker', `HTTP ${res.status} for ${serviceName} (${endpoint})`);
1213 return null;