-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfileserver.ts
More file actions
184 lines (152 loc) · 5.73 KB
/
fileserver.ts
File metadata and controls
184 lines (152 loc) · 5.73 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
import express, { Request } from 'express'
import fs from 'fs'
import https from 'https'
import path from 'path'
type QueryParams = {
source: string
predicate: string
}
type FileParams = QueryParams & {
target: string
}
// Basic config
const PORT = 8000
// Resolve repo-level dev certs; this file lives in packages/projects/projects/hexafield/conjure/
const CERT_PATH = path.resolve(__dirname, '../../../../../certs/cert.pem')
const KEY_PATH = path.resolve(__dirname, '../../../../../certs/key.pem')
// Local storage directory for uploaded files
const STORAGE_DIR = path.resolve(__dirname, 'storage')
fs.mkdirSync(STORAGE_DIR, { recursive: true })
// Minimal CORS for local dev
const corsMiddleware: express.RequestHandler = (req, res, next) => {
console.log(`[fileserver] ${req.method} ${req.url}`)
res.header('Access-Control-Allow-Origin', req.headers.origin || '*')
res.header('Access-Control-Allow-Credentials', 'true')
res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS')
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
if (req.method === 'OPTIONS') return res.sendStatus(204)
next()
}
const app = express()
app.use(corsMiddleware)
app.use(express.json({ limit: '10mb' })) // JSON only for metadata routes
const keyFor = ({ source, predicate }: QueryParams) => `${encodeURIComponent(predicate)}__${encodeURIComponent(source)}`
const pathFor = (q: QueryParams) => path.join(STORAGE_DIR, `${keyFor(q)}.json`)
const readFile = (q: QueryParams): FileParams | undefined => {
const path = pathFor(q)
if (!fs.existsSync(path)) return undefined
try {
return JSON.parse(fs.readFileSync(path, 'utf-8')) as FileParams
} catch {
return undefined
}
}
const writeFile = (q: QueryParams, data: string) => {
fs.writeFileSync(pathFor(q), data)
}
app.get('/health', (_req, res) => res.status(200).send('ok'))
app.post('/create', (req: Request, res) => {
try {
const { source, predicate, target } = req.body as unknown as FileParams
if (!source || !predicate || !target) {
return res.status(400).json({ error: 'Missing required fields' })
}
const q: QueryParams = { source, predicate }
const finalPath = pathFor(q)
if (finalPath && fs.existsSync(finalPath)) fs.unlinkSync(finalPath)
writeFile(q, target)
return res.status(201).json({ ok: true })
} catch (e) {
console.error('CREATE error', e)
return res.status(500).json({ error: 'Internal error' })
}
})
// Get (download)
app.post('/get', (req, res) => {
try {
const { source, predicate } = req.body as QueryParams
if (!source || !predicate) return res.status(400).json({ error: 'Missing required fields' })
const path = pathFor({ source, predicate })
if (!path || !fs.existsSync(path)) return res.status(404).json({ error: 'Not found' })
const file = readFile({ source, predicate })
if (!file) return res.status(404).json({ error: 'Not found' })
return res.status(200).json(file)
} catch (e) {
console.error('GET error', e)
return res.status(500).json({ error: 'Internal error' })
}
})
// Find (return results for matching predicate)
app.post('/find', (req, res) => {
try {
const { predicate } = req.body as { predicate?: string }
if (!predicate) return res.status(400).json({ error: 'Missing required fields' })
// Scan storage dir for all .json meta files
const results: Array<string> = []
const files = fs.readdirSync(STORAGE_DIR)
for (const file of files) {
if (!file.endsWith('.json')) continue
const encodedPredicate = encodeURIComponent(predicate)
if (file.startsWith(encodedPredicate)) {
results.push(decodeURIComponent(file.slice(encodedPredicate.length + 2, -5)))
}
}
return res.status(200).json({ ok: true, results })
} catch (e) {
console.error('FIND error', e)
return res.status(500).json({ error: 'Internal error' })
}
})
app.post('/has', (req, res) => {
try {
const { source, predicate } = req.body as QueryParams
if (!source || !predicate) return res.status(400).json({ error: 'Missing required fields' })
const file = fs.existsSync(pathFor({ source, predicate }))
if (!file) return res.status(200).json({ ok: false })
return res.status(200).json({ ok: true })
} catch (e) {
console.error('HAS error', e)
return res.status(500).json({ error: 'Internal error' })
}
})
// Replace
app.post('/replace', (req: Request, res) => {
try {
const { source, predicate, target } = req.body as unknown as FileParams
if (!source || !predicate || !target) {
return res.status(400).json({ error: 'Missing required fields' })
}
const q: QueryParams = { source, predicate }
const path = pathFor(q)
if (!path) {
return res.status(404).json({ error: 'Not found' })
}
// Remove old file
if (path && fs.existsSync(path)) fs.unlinkSync(path)
writeFile(q, target)
return res.status(200).json({ ok: true })
} catch (e) {
console.error('REPLACE error', e)
return res.status(500).json({ error: 'Internal error' })
}
})
// Delete
app.post('/delete', (req, res) => {
try {
const { source, predicate } = req.body as QueryParams
if (!source || !predicate) return res.status(400).json({ error: 'Missing required fields' })
const q: QueryParams = { source, predicate }
const path = pathFor(q)
if (fs.existsSync(path)) fs.unlinkSync(path)
return res.status(200).json({ ok: true })
} catch (e) {
console.error('DELETE error', e)
return res.status(500).json({ error: 'Internal error' })
}
})
// HTTPS server
const key = fs.readFileSync(KEY_PATH)
const cert = fs.readFileSync(CERT_PATH)
https.createServer({ key, cert }, app).listen(PORT, () => {
console.log(`[fileserver] HTTPS listening on https://localhost:${PORT}`)
})