Skip to content
Open
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
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,8 @@ ENABLE_STATS=false
# Redis Configuration (only required if ENABLE_STATS=true)
# Example: redis://default:password@host:port or redis://localhost:6379
REDIS_URL=

# Pexels Integration (optional - enables the in-UI image search widget)
# Get a free API key at https://www.pexels.com/api/
# When unset, the /api/pexels/search endpoint returns 503
PEXELS_API_KEY=
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ When you deploy your own copy, you're directly supporting this project! 💖
- 📥 **SVG & PNG Download** - Download banners as SVG or PNG directly from the UI
- ⚡ **Lightning Fast** - Built with Hono framework for optimal performance
- 🔒 **Secure** - Input sanitization and validation
- 🖼️ **Background Images** - Use any HTTPS image URL as banner background via `bgimg` parameter
- 📸 **Pexels Integration** - Search and select background images from Pexels directly in the UI
- 🚀 **Edge-Ready** - Deploy to modern platforms like Railway

## 🚀 Quick Start
Expand Down Expand Up @@ -86,6 +88,18 @@ https://ghrb.waren.build/banner?header=Transparent&bg=00000000&color=ffffff
https://ghrb.waren.build/banner?header=Semi-Transparent&bg=ffffff80&color=000000
```

**Custom Background Image**

```text
https://ghrb.waren.build/banner?header=My+Project&bgimg=https://images.pexels.com/photos/1261728/pexels-photo-1261728.jpeg&color=ffffff
```

> Use `bgimg` with any HTTPS image URL. The image is fetched server-side, embedded as base64 in the SVG, and scaled to cover the banner area. If the image fails to load, the banner falls back to the default gradient background. Max image size: 10 MB.

**Pexels Integration**

The UI includes a built-in Pexels image search. To enable it, set the `PEXELS_API_KEY` environment variable with your [Pexels API key](https://www.pexels.com/api/). Search results display landscape-oriented thumbnails that can be selected with a single click.

## 🌟 Who Uses This

Projects and organizations using GitHub Repo Banner:
Expand Down Expand Up @@ -176,6 +190,7 @@ Generate a custom SVG banner.
| `subheadercolor` | string | No | Same as `color` | Subheader text color |
| `headerfont` | string | No | - | Google Fonts family name for header (e.g., "Roboto") |
| `subheaderfont` | string | No | - | Google Fonts family name for subheader (e.g., "Playfair Display") |
| `bgimg` | string | No | - | HTTPS image URL for background (overrides `bg` when set, max 10 MB) |
| `support` | boolean | No | `false` | Show support watermark |
| `watermarkpos` | string | No | `bottom-right` | Watermark position: `top-left`, `top-right`, `bottom-left`, `bottom-right` |

Expand All @@ -187,6 +202,7 @@ Generate a custom SVG banner.
| Solid | `HEX` | `ffffff` (single color) |
| Transparent | `00000000` | Fully transparent |
| With Opacity | `RRGGBBAA` | `ffffff80` (50% opacity) |
| Image URL | `bgimg=https://...` | HTTPS URL to any image (fetched and embedded as base64) |

#### Response

Expand Down
14 changes: 7 additions & 7 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,18 @@
"check": "biome check ."
},
"dependencies": {
"@hono/node-server": "^1.19.13",
"@hono/node-server": "^2.0.4",
"@wgtechlabs/log-engine": "^2.2.0",
"dotenv": "^17.2.3",
"hono": "^4.12.14",
"ioredis": "^5.9.2"
},
"devDependencies": {
"@biomejs/biome": "^2.4.7",
"@types/node": "^22.10.0",
"@types/node": "^25.9.1",
"tsup": "^8.3.0",
"tsx": "^4.19.0",
"typescript": "^5.7.0"
"typescript": "^6.0.3"
},
Comment on lines 21 to 27

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Acknowledged. Node type definitions should align with the supported runtime major. Kept open pending the dependency correction.

"engines": {
"node": "^22"
Expand Down
93 changes: 91 additions & 2 deletions src/banner/svg-template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,72 @@ function buildGradientDef(bg: BackgroundPreset): string {
return `<linearGradient id="bg-gradient" x1="0" y1="0" x2="1" y2="0">${stops}</linearGradient>`;
}

/**
* Fetch an image and return it as a base64 data URI for SVG embedding.
*/
const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
const ALLOWED_IMAGE_TYPES = [
'image/jpeg',
'image/png',
'image/gif',
'image/webp',
'image/avif',
];

async function fetchImageAsBase64(url: string): Promise<string | null> {
try {
const response = await fetch(url, {
headers: {
'User-Agent':
'Mozilla/5.0 (compatible; GitHubRepoBanner/1.0; +https://ghrb.waren.build)',
},
signal: AbortSignal.timeout(10_000),
redirect: 'error',
});
if (!response.ok) return null;

const declaredLength = response.headers.get('content-length');
if (declaredLength && parseInt(declaredLength, 10) > MAX_IMAGE_BYTES)
return null;

const rawContentType = response.headers.get('content-type');
if (!rawContentType) return null;
const contentType = rawContentType.split(';', 1)[0].trim().toLowerCase();
if (!ALLOWED_IMAGE_TYPES.includes(contentType)) return null;

const body = response.body;
if (!body) return null;

const chunks: Uint8Array[] = [];
let totalBytes = 0;
const reader = body.getReader();
for (;;) {
const { done, value } = await reader.read();
if (done) break;
totalBytes += value.byteLength;
if (totalBytes > MAX_IMAGE_BYTES) {
reader.cancel();
return null;
}
chunks.push(value);
}

if (totalBytes === 0) return null;

const merged = new Uint8Array(totalBytes);
let offset = 0;
for (const chunk of chunks) {
merged.set(chunk, offset);
offset += chunk.byteLength;
}

const base64 = Buffer.from(merged).toString('base64');
return `data:${contentType};base64,${base64}`;
} catch {
return null;
}
}

function buildBackground(bg: BackgroundPreset): string {
if (bg.type === 'transparent') {
return `<rect width="${WIDTH}" height="${HEIGHT}" fill="none" />`;
Expand Down Expand Up @@ -272,8 +338,31 @@ export async function buildBannerSVG(options: BannerOptions): Promise<string> {
}
}

const defs = buildGradientDef(background);
const bgRect = buildBackground(background);
let defs = buildGradientDef(background);
let bgRect: string;

if (background.type === 'image' && background.imageUrl) {
const dataUri = await fetchImageAsBase64(background.imageUrl);
if (dataUri) {
bgRect = `<image href="${dataUri}" x="0" y="0" width="${WIDTH}" height="${HEIGHT}" preserveAspectRatio="xMidYMid slice" />`;
} else {
const fallback: BackgroundPreset = {
id: 'gradient',
name: 'Gradient',
type: 'gradient',
stops: [
{ offset: '0%', color: '#1a1a1a' },
{ offset: '100%', color: '#4a4a4a' },
],
defaultTextColor: '#ffffff',
};
defs = buildGradientDef(fallback);
bgRect = buildBackground(fallback);
}

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Acknowledged. The failure path should restore the documented default gradient. Kept open pending the fallback fix.

} else {
bgRect = buildBackground(background);
}

const watermark = showWatermark ? buildWatermark(watermarkPosition) : '';

// Determine font families to use - Google Font if specified, otherwise default
Expand Down
3 changes: 2 additions & 1 deletion src/banner/types.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
export interface BackgroundPreset {
id: string;
name: string;
type: 'gradient' | 'solid' | 'transparent';
type: 'gradient' | 'solid' | 'transparent' | 'image';
stops?: Array<{ offset: string; color: string }>;
color?: string;
imageUrl?: string;
defaultTextColor: string;
}

Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { LogEngine, LogMode } from '@wgtechlabs/log-engine';
import { Hono } from 'hono';
import { initRedis, isStatsEnabled } from './config/redis.js';
import bannerRoute from './routes/banner.js';
import pexelsRoute from './routes/pexels.js';
import statsRoute from './routes/stats.js';
import uiRoute from './routes/ui.js';

Expand Down Expand Up @@ -45,6 +46,7 @@ app.get('/health', (c) => {

app.route('/', uiRoute);
app.route('/', bannerRoute);
app.route('/', pexelsRoute);
app.route('/', statsRoute);

const port = parseInt(process.env.PORT || '3000', 10);
Expand Down
14 changes: 12 additions & 2 deletions src/routes/banner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { BackgroundPreset } from '../banner/types.js';
import { getRedis, isStatsEnabled } from '../config/redis.js';
import {
isValidHexColor,
isValidImageUrl,
sanitizeFontName,
sanitizeHeader,
} from '../utils/sanitize.js';
Expand Down Expand Up @@ -47,6 +48,7 @@ bannerRoute.get('/banner', async (c) => {
const rawHeader = c.req.query('header') || 'Hello World';
const rawSubheader = c.req.query('subheader') || '';
const bgParam = c.req.query('bg') || '1a1a1a-4a4a4a'; // Default gradient
const bgImgParam = c.req.query('bgimg') || '';
const colorParam = c.req.query('color') || '';
const subheaderColorParam = c.req.query('subheadercolor') || '';
const supportParam = c.req.query('support') || '';
Expand All @@ -57,10 +59,18 @@ bannerRoute.get('/banner', async (c) => {
const header = sanitizeHeader(rawHeader, 50);
const subheader = rawSubheader ? sanitizeHeader(rawSubheader, 60) : undefined;

// Parse bg parameter: gradient (hex-hex) or solid (hex)
// Parse background: image URL takes priority over color
let background: BackgroundPreset;

if (bgParam.includes('-')) {
if (bgImgParam && isValidImageUrl(bgImgParam)) {
background = {
id: 'image',
name: 'Image',
type: 'image' as const,
imageUrl: bgImgParam,
defaultTextColor: '#ffffff',
};
} else if (bgParam.includes('-')) {
// Gradient: two hex codes separated by hyphen
const [startHex, endHex] = bgParam.split('-');
if (isValidHexColor(startHex) && isValidHexColor(endHex)) {
Expand Down
61 changes: 61 additions & 0 deletions src/routes/pexels.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { Hono } from 'hono';

const pexelsRoute = new Hono();

const PEXELS_API_URL = 'https://api.pexels.com/v1';

pexelsRoute.get('/api/pexels/search', async (c) => {
const apiKey = process.env.PEXELS_API_KEY;
if (!apiKey) {
return c.json({ error: 'Pexels API not configured' }, 503);
}

const query = (c.req.query('q') || 'nature').slice(0, 100);
const page = Math.max(
1,
parseInt(c.req.query('page') || '1', 10) || 1,
).toString();
const perPage = '9';
const orientation = 'landscape';

try {
const url = `${PEXELS_API_URL}/search?query=${encodeURIComponent(query)}&page=${page}&per_page=${perPage}&orientation=${orientation}`;
const response = await fetch(url, {
headers: { Authorization: apiKey },
signal: AbortSignal.timeout(10_000),
});
Comment thread
warengonzaga marked this conversation as resolved.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Acknowledged. The Pexels request needs a timeout to prevent stalled upstream calls. Kept open pending the fix.


if (!response.ok) {
return c.json({ error: 'Pexels API error' }, 502);
}

const data = (await response.json()) as {
photos: Array<{
id: number;
alt: string;
photographer: string;
src: { landscape: string; medium: string };
}>;
total_results: number;
page: number;
};

const photos = data.photos.map((p) => ({
id: p.id,
alt: p.alt,
photographer: p.photographer,
url: p.src.landscape,
thumb: p.src.medium,
}));

return c.json({
photos,
total: data.total_results,
page: data.page,
});
} catch {
return c.json({ error: 'Failed to fetch from Pexels' }, 500);
}
});

export default pexelsRoute;
Loading
Loading