Skip to content

Commit

Permalink
Create Index.js
Browse files Browse the repository at this point in the history
  • Loading branch information
As90909w authored Mar 21, 2024
1 parent 3352cbf commit 0194fcf
Showing 1 changed file with 95 additions and 0 deletions.
95 changes: 95 additions & 0 deletions Index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import express from 'express'
import basicAuth from 'express-basic-auth'
import http from 'node:http'
import { createBareServer } from '@tomphttp/bare-server-node'
import path from 'node:path'
import cors from 'cors'
import config from './config.js'
const __dirname = process.cwd()
const server = http.createServer()
const app = express(server)
const bareServer = createBareServer('/o/')
const PORT = process.env.PORT || 8080
if (config.challenge) {
console.log('Password protection is enabled. Usernames are: ' + Object.keys(config.users))
console.log('Passwords are: ' + Object.values(config.users))

app.use(
basicAuth({
users: config.users,
challenge: true,
})
)
}
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(cors())
app.use(express.static(path.join(__dirname, 'static')))

if (config.routes !== false) {
const routes = [
{ path: '/~', file: 'apps.html' },
{ path: '/-', file: 'games.html' },
{ path: '/!', file: 'settings.html' },
{ path: '/0', file: 'tabs.html' },
{ path: '/1', file: 'go.html' },
{ path: '/', file: 'index.html' },
]

routes.forEach((route) => {
app.get(route.path, (req, res) => {
res.sendFile(path.join(__dirname, 'static', route.file))
})
})
}
if (config.local !== false) {
app.get('/y/*', (req, res, next) => {
const baseUrl = 'https://raw.githubusercontent.com/ypxa/y/main'
fetchData(req, res, next, baseUrl)
})

app.get('/f/*', (req, res, next) => {
const baseUrl = 'https://raw.githubusercontent.com/4x-a/x/fixy'
fetchData(req, res, next, baseUrl)
})
}

const fetchData = async (req, res, next, baseUrl) => {
try {
const reqTarget = `${baseUrl}/${req.params[0]}`
const asset = await fetch(reqTarget)

if (asset.ok) {
const data = await asset.arrayBuffer()
res.end(Buffer.from(data))
} else {
next()
}
} catch (error) {
console.error('Error fetching:', error)
next(error)
}
}
server.on('request', (req, res) => {
if (bareServer.shouldRoute(req)) {
bareServer.routeRequest(req, res)
} else {
app(req, res)
}
})

server.on('upgrade', (req, socket, head) => {
if (bareServer.shouldRoute(req)) {
bareServer.routeUpgrade(req, socket, head)
} else {
socket.end()
}
})

server.on('listening', () => {
console.log(`Running at http://localhost:${PORT}`)
})

server.listen({
port: PORT,
})

0 comments on commit 0194fcf

Please sign in to comment.