forked from yusukebe/r2-image-worker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
223 lines (205 loc) · 7.23 KB
/
Copy pathserver.js
File metadata and controls
223 lines (205 loc) · 7.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
const express = require('express')
const multer = require('multer')
const path = require('path')
const fs = require('fs')
const crypto = require('crypto')
const mime = require('mime-types')
// Storage configuration
const STORAGE_ROOT = path.resolve(__dirname, 'storage')
const MAX_AGE = 60 * 60 * 24 * 30 // 30 days, for cache headers
// Ensure storage root exists
if (!fs.existsSync(STORAGE_ROOT)) {
fs.mkdirSync(STORAGE_ROOT, { recursive: true })
}
// Simple Basic Auth middleware using env vars or defaults
function basicAuthMiddleware(req, res, next) {
const USER = process.env.USER || 'admin'
const PASS = process.env.PASS || 'secret'
const auth = req.headers['authorization'] || ''
const token = auth.startsWith('Basic ') ? Buffer.from(auth.slice(6), 'base64').toString() : ''
const [user, pass] = token.split(':')
if (user === USER && pass === PASS) {
return next()
}
res.set('WWW-Authenticate', 'Basic realm="Restricted"')
return res.status(401).send('Unauthorized')
}
// Helpers
const generateShortId = () => {
// 6-character alphanumeric id
const chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
let s = ''
for (let i = 0; i < 6; i++) s += chars.charAt(Math.floor(Math.random() * chars.length))
return s
}
const getDatedPath = () => {
const now = new Date()
const year = now.getFullYear()
const month = String(now.getMonth() + 1).padStart(2, '0')
const day = String(now.getDate()).padStart(2, '0')
return `${year}/${month}/${day}`
}
const toExt = (mimeType) => {
// Map mime type to extension; fallback to 'bin'
const ext = (mime.extension) ? mime.extension(mimeType) : null
// fallback using common types
if (!ext) {
if (mimeType === 'image/jpeg') return 'jpg'
if (mimeType === 'image/png') return 'png'
if (mimeType === 'image/webp') return 'webp'
}
return ext || 'bin'
}
// Initialize Express app
const app = express()
// Multer setup: store to memory first, we'll write to disk ourselves
const upload = multer({ storage: multer.memoryStorage() })
// Root page: simple landing similar to the Cloudflare worker
app.get('/', (req, res) => {
res.send(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fluffy Images</title>
<meta name="description" content="This service provides hosting for images">
<link rel="shortcut icon" href="https://pub-a4443e381b024b27a2b33c5ed3c0d88e.r2.dev/fi_icon.png">
<meta property="og:title" content="Fluffy Images">
<meta property="og:description" content="This service provides hosting for images">
<meta property="og:url" content="https://i.fluffynet.dev">
<meta property="og:type" content="website">
<meta property="og:image" content="https://pub-a4443e381b024b27a2b33c5ed3c0d88e.r2.dev/fi_icon.png">
<meta property="og:image:alt" content="Fluffy Images">
<meta property="og:site_name" content="Fluffy Images">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Fluffy Images">
<meta name="twitter:description" content="This service provides hosting for images">
<meta name="twitter:image" content="https://pub-a4443e381b024b27a2b33c5ed3c0d88e.r2.dev/fi_icon.png">
<meta name="twitter:image:alt" content="FluffyImages logo">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Geist+Mono:wght@100..900&family=Geist:wght@100..900&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Geist', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, #0a0a0a 0%, #1a1a1a 100%);
color: #ffffff;
margin: 0;
padding: 0;
text-align: center;
min-height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
h1 {
color: #00d4ff;
font-size: 3rem;
margin-bottom: 1rem;
}
p {
color: #b8b8b8;
font-size: 1.2rem;
max-width: 600px;
}
a {
color: #00d4ff;
text-decoration:none;
}
</style>
</head>
<body>
<h1><img src="https://pub-a4443e381b024b27a2b33c5ed3c0d88e.r2.dev/fi_logo.png" alt="Fluffy Images" height="128px"></h1>
<p>This service provides image hosting.</p>
</body>
</html>`)
})
// Upload endpoint (Basic Auth required)
// Expects multipart/form-data with fields: image (file), width (optional), height (optional)
app.put('/upload', basicAuthMiddleware, upload.single('image'), async (req, res) => {
if (!req.file) {
return res.status(400).send('No image uploaded')
}
const { width, height } = req.body || {}
const ext = toExt(req.file.mimetype) || 'bin'
const datedPath = getDatedPath() // e.g., 2026/04/01
const shortId = generateShortId()
let filename
if (width && height) {
filename = `${shortId}_${width}x${height}.${ext}`
} else {
filename = `${shortId}.${ext}`
}
const dir = path.resolve(STORAGE_ROOT, datedPath)
await fs.promises.mkdir(dir, { recursive: true })
const filePath = path.resolve(dir, filename)
await fs.promises.writeFile(filePath, req.file.buffer)
// Return the storage key (relative to storage root)
const key = path.relative(STORAGE_ROOT, filePath).replace(/\\/g, '/')
res.send(key)
})
// Serve images from local storage
// URL pattern: /images/<path-to-image>
app.get('/images/*', async (req, res) => {
const key = req.params[0] // the wildcard segment
const filePath = path.resolve(STORAGE_ROOT, key)
// Guard against path traversal
if (!filePath.startsWith(STORAGE_ROOT)) {
return res.status(400).send('Invalid path')
}
try {
await fs.promises.access(filePath, fs.constants.R_OK)
} catch {
return res.status(404).send('Not found')
}
const stat = await fs.promises.stat(filePath)
const contentType = mime.lookup(filePath) || 'application/octet-stream'
res.set('Content-Type', contentType)
res.set('Cache-Control', `public, max-age=${MAX_AGE}`)
// Stream file
const readStream = fs.createReadStream(filePath)
readStream.pipe(res)
})
// Keyboard-agnostic 404 for other routes
app.use((req, res) => {
res.status(404).send('Not Found')
})
// Cleanup: remove files older than 24 hours
const CLEANUP_AGE_MS = 24 * 60 * 60 * 1000
const cleanupOldFiles = async () => {
const walk = async (dir) => {
const entries = await fs.promises.readdir(dir, { withFileTypes: true })
for (const e of entries) {
const full = path.resolve(dir, e.name)
if (e.isDirectory()) {
await walk(full)
} else if (e.isFile()) {
try {
const stats = await fs.promises.stat(full)
const age = Date.now() - stats.mtimeMs
if (age > CLEANUP_AGE_MS) {
await fs.promises.unlink(full)
// console.log('Deleted old file', full)
}
} catch {
// ignore
}
}
}
}
try {
await walk(STORAGE_ROOT)
} catch {
// ignore cleanup errors
}
}
// Start server
const PORT = process.env.PORT || 3000
app.listen(PORT, () => {
// initial cleanup at startup
cleanupOldFiles()
// schedule cleanup every 24 hours
setInterval(cleanupOldFiles, 24 * 60 * 60 * 1000)
console.log(`Node image server listening on port ${PORT}`)
})