76 lines
1.8 KiB
TypeScript
76 lines
1.8 KiB
TypeScript
|
import { Elysia, t, type Context } from 'elysia'
|
||
|
import { version } from './package.json';
|
||
|
import { basicAuth } from '@eelkevdbos/elysia-basic-auth'
|
||
|
|
||
|
|
||
|
|
||
|
const whitelistFilePath = process.env.WL_FILE_PATH || "/etc/opentracker/whitelist"
|
||
|
const adderFifoFilePath = process.env.WL_FIFO_PATH || "/var/run/opentracker/adder.fifo"
|
||
|
|
||
|
const authOpts = {
|
||
|
scope: [
|
||
|
"/whitelist",
|
||
|
"/version"
|
||
|
],
|
||
|
credentials: {
|
||
|
env: 'WL_CREDENTIALS'
|
||
|
}
|
||
|
}
|
||
|
|
||
|
const startupChecks = function startupChecks() {
|
||
|
|
||
|
if (!process.env.WL_CREDENTIALS) {
|
||
|
const msg = `WL_CREDENTIALS is missing in env!`
|
||
|
if (process.env.NODE_ENV === "test") {
|
||
|
console.warn(msg)
|
||
|
} else {
|
||
|
throw new Error(msg)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if (!process.env.WL_FILE_PATH) {
|
||
|
console.warn(`WL_FILE_PATH is missing in env. Using default ${whitelistFilePath}`)
|
||
|
}
|
||
|
|
||
|
if (!process.env.WL_FIFO_PATH) {
|
||
|
console.warn(`WL_FIFO_PATH is missing in env. Using default ${adderFifoFilePath}`)
|
||
|
}
|
||
|
|
||
|
// throw if the whitelist file doesn't exist
|
||
|
Bun.file(whitelistFilePath);
|
||
|
|
||
|
}
|
||
|
|
||
|
|
||
|
|
||
|
const getWhitelist = function getWhitelist(ctx: Context) {
|
||
|
const wl = Bun.file(whitelistFilePath); // relative to cwd
|
||
|
console.debug(`read from whitelist file at ${whitelistFilePath}. size=${wl.size}, type=${wl.type}`)
|
||
|
return wl.text()
|
||
|
}
|
||
|
|
||
|
const postWhitelist = async function postWhitelist(ctx: Context) {
|
||
|
const body = ctx.body
|
||
|
console.log(`Whitelister is appending ${body} to fifo at ${adderFifoFilePath}`)
|
||
|
const fifo = Bun.file(adderFifoFilePath)
|
||
|
Bun.write(fifo, body + "\n")
|
||
|
console.log(`${body} was sent to the FIFO at ${adderFifoFilePath}`)
|
||
|
return body
|
||
|
}
|
||
|
|
||
|
|
||
|
startupChecks()
|
||
|
|
||
|
|
||
|
const app = new Elysia()
|
||
|
.use(basicAuth(authOpts))
|
||
|
.get('/health', () => 'OK')
|
||
|
.get('/version', () => `version ${version} `)
|
||
|
.get('/whitelist', getWhitelist)
|
||
|
.post('/whitelist', postWhitelist, {
|
||
|
body: t.String()
|
||
|
})
|
||
|
|
||
|
|
||
|
export default app
|