init from lnurld-db

This commit is contained in:
Martin Dimitrov 2024-02-25 08:55:35 -08:00
commit d82e150eaa
42 changed files with 1233 additions and 0 deletions

2
.dockerignore Normal file
View File

@ -0,0 +1,2 @@
**/node_modules
.env*

View File

@ -0,0 +1,21 @@
name: Build and push image for doorman
on:
push:
branches: [main]
jobs:
docker:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
name: Check out code
- name: Build Docker image
run: docker build . -t gitea.chromart.dedyn.io/martin/doorman:v1 -t gitea.chromart.dedyn.io/martin/doorman:latest
- name: Login to Docker
run: echo -n '${{ secrets.PASSWORD }}' | docker login gitea.chromart.dedyn.io --username ${{ secrets.USERNAME }} --password-stdin
- name: Push Docker image
run: docker image push --all-tags gitea.chromart.dedyn.io/martin/doorman

178
.gitignore vendored Normal file
View File

@ -0,0 +1,178 @@
# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore
# Logs
logs
_.log
npm-debug.log_
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
# Runtime data
pids
_.pid
_.seed
\*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
\*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
\*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
\*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.\*
# IntelliJ based IDEs
.idea
# Finder (MacOS) folder config
.DS_Store
build

21
Dockerfile Normal file
View File

@ -0,0 +1,21 @@
FROM oven/bun
ADD packages packages
ADD bun.lockb bun.lockb
ADD package.json package.json
ADD tsconfig.json tsconfig.json
# install all deps
RUN bun install
# client build
WORKDIR /home/bun/app/packages/client
RUN bun run build
# move built client to server
RUN mv dist ../server/
WORKDIR /home/bun/app/packages/server
# start server
CMD bun run ./src/server.ts

15
README.md Normal file
View File

@ -0,0 +1,15 @@
# lnurl-db
To install dependencies:
```bash
bun install
```
To run:
```bash
bun run index.ts
```
This project was created using `bun init` in bun v1.0.3. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.

BIN
bun.lockb Executable file

Binary file not shown.

14
docker-compose.yml Normal file
View File

@ -0,0 +1,14 @@
version: "3"
services:
lnurl_db:
container_name: lnurl-db
image: gitea.chromart.dynv6.net/martin/lnurl-db:latest
environment:
- CHALLENGE_EXPIRE_MS=105000
- BASE_DOMAIN=chromart.dynv6.net
- REDIS_CONNECT_URL=redis://@redis:6379
depends_on:
- redis
redis:
image: redis:latest

13
doorman.code-workspace Normal file
View File

@ -0,0 +1,13 @@
{
"folders": [
{
"path": "packages/client"
},
{
"path": "packages/server"
},
{
"path": "."
}
]
}

12
package.json Normal file
View File

@ -0,0 +1,12 @@
{
"name": "lnurl-db",
"module": "index.ts",
"type": "module",
"workspaces": ["packages/*"],
"devDependencies": {
"bun-types": "latest"
},
"peerDependencies": {
"typescript": "^5.0.0"
}
}

46
packages/client/README.md Normal file
View File

@ -0,0 +1,46 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `yarn start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `yarn test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `yarn build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `yarn eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

View File

@ -0,0 +1,34 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="/manifest.json" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="module" src="/src/index.tsx"></script>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

View File

@ -0,0 +1,49 @@
{
"name": "lnurl-db-client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@cloudscape-design/components": "^3.0.375",
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^13.0.0",
"@testing-library/user-event": "^13.2.1",
"@types/jest": "^27.0.1",
"@types/node": "^16.7.13",
"@types/react": "^18.0.0",
"@types/react-dom": "^18.0.0",
"@vitejs/plugin-react": "^4.0.4",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-qr-code": "^2.0.12",
"react-router-dom": "^6.15.0",
"typescript": "^4.4.2",
"vite": "^4.4.9",
"vite-plugin-svgr": "^4.0.0",
"vite-tsconfig-paths": "^4.2.1",
"web-vitals": "^2.1.0"
},
"scripts": {
"start": "vite",
"build": "tsc && vite build",
"serve": "vite preview"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy": "http://localhost:5000"
}

View File

@ -0,0 +1,8 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

View File

@ -0,0 +1,32 @@
import { Alert, Button } from '@cloudscape-design/components';
import React, { useState } from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import { Action } from './types/Action';
import { AlertContent, AlertContext } from './contexts/AlertContext';
function App() {
const navigate = useNavigate();
const location = useLocation();
const [ content, setContent ] = useState<AlertContent>({});
return (
<div className="App">
<AlertContext.Provider value={
{
content,
setContent,
}
}>
<h1>homepage</h1>
{Object.values(Action).map(value => {
return <Button disabled={location.pathname.includes(value)} key={value} onClick={() => navigate(`/action/${value}`)}>{value}</Button>
})}
{content.message && <Alert dismissible onDismiss={() => setContent({})} type={content.type || "info"}>{content.message}</Alert>}
<Outlet />
</AlertContext.Provider>
</div>
);
}
export default App;

View File

@ -0,0 +1,141 @@
import { ColumnLayout, Container, Header, ProgressBar, Spinner } from "@cloudscape-design/components";
import { useContext, useEffect, useState } from "react";
import QRCode from "react-qr-code";
import { Action } from "../types/Action";
import { ResponseHandler } from "../handlers/RepsonseHandler";
import { useNavigate } from "react-router-dom";
import { AlertContext } from "../contexts/AlertContext";
export async function loader({ params }: {params: {action: string}}) {
return { action: params.action };
}
const WAIT_MS: number = 3000;
const COUNTDOWN_TIME_SECONDS = 100;
export interface IAuthPageProps {
subdomain: string;
action: Action;
options?: RequestInit;
responseHandler: ResponseHandler;
handlerMetadata?: any;
};
export default function AuthFlow(props: IAuthPageProps) {
const { subdomain, action, options, responseHandler, handlerMetadata } = props;
const [ loading, setLoading ] = useState<boolean>(true);
const [ qrContent, setQrContent ] = useState<string>("");
const [ challenge, setChallenge ] = useState<string>("");
const [ countdown, setCountdown ] = useState<number>(COUNTDOWN_TIME_SECONDS);
const { setContent } = useContext(AlertContext);
const navigate = useNavigate();
useEffect(() => {
fetch(`/api/lnurl/login?subdomain=${subdomain}`)
.then(res => {
if (res.status === 429) {
throw new Error("Too many requests, try again later");
}
return res;
})
.then(res => res.json())
.then(res => {
setQrContent(res.lnurl);
setLoading(false);
setChallenge(res.challenge);
setCountdown(COUNTDOWN_TIME_SECONDS);
})
.catch((err) => {
console.log(err);
setContent({
type: "error",
message: err?.message || "Unknown error occurred",
});
navigate("/");
});
}, [action]);
useEffect(() => {
if (challenge === "") {
return;
}
const timer = setInterval(() => {
fetch(`/api/actions/${action}/${challenge}`, options)
.then(res => {
if (res.status === 401) {
throw new Error("Challenge not met");
}
return res;
})
.then((res) => responseHandler(res, (err) => {
if (err) {
setContent({
message: err.message,
type: "error",
})
} else {
setContent({
type: "success",
message: `${action} success!`
})
}
setChallenge("");
navigate("/");
}, handlerMetadata))
.catch((err) => console.error(err));
}, WAIT_MS);
return () => {
clearInterval(timer);
}
}, [challenge]);
useEffect(() => {
if (countdown === 0) {
setContent({
type: "error",
message: "Authentication timed out after 100s, try again",
});
navigate("/");
return;
}
const countdownTimer = setTimeout(() => {
setCountdown(countdown - 1);
}, 1000);
return () => {
clearTimeout(countdownTimer);
}
}, [countdown]);
return (
<ColumnLayout columns={3}>
<div></div>
<Container>
<ColumnLayout columns={1}>
<Header>Authentication for <code>{action}</code> on <code>{subdomain}</code></Header>
{loading && <Spinner size="big" />}
{!loading && (
<>
<ColumnLayout columns={3}>
<div></div>
<QRCode value={qrContent} />
</ColumnLayout>
<ProgressBar
label={"Remaining Time"}
description={"Complete authentication before the timer expires"}
additionalInfo={"Authentication expires after 100s to keep your files secure. Please complete the login challenge within the time remaining"}
value={countdown}
/>
</>
)}
</ColumnLayout>
</Container>
</ColumnLayout>
)
}

View File

@ -0,0 +1,12 @@
import { AlertProps } from "@cloudscape-design/components";
import React from "react";
export interface AlertContent {
type?: AlertProps.Type;
message?: string;
}
export const AlertContext = React.createContext<{ content: AlertContent, setContent: (content: AlertContent) => void }>({
content: {},
setContent: () => null,
});

View File

@ -0,0 +1,24 @@
import { ResponseHandler } from "./RepsonseHandler";
export interface DownloadMetadata {
name?: string;
type?: string;
}
const DownloadFileHandler: ResponseHandler<DownloadMetadata> = (res, next, extra) => {
if (res.status === 404) {
console.log("Nothing to download");
return res.json().then(next);
}
return res.blob()
.then(data => {
let a = document.createElement("a");
a.href = window.URL.createObjectURL(data);
a.download = `${extra?.name || "file"}.${extra?.type || "txt"}`;
a.click();
next()
})
.catch(next);
}
export default DownloadFileHandler;

View File

@ -0,0 +1,12 @@
import { Action } from "../types/Action";
import DownloadFileHandler from "./DownloadFileHandler";
import NoopHandler from "./NoopHandler";
import { ResponseHandler } from "./RepsonseHandler";
export function getHandler(action: Action): ResponseHandler {
switch(action) {
case Action.DOWNLOAD: return DownloadFileHandler;
case Action.UPLOAD: return NoopHandler;
case Action.DELETE: return NoopHandler;
}
}

View File

@ -0,0 +1,15 @@
import { ResponseHandler } from "./RepsonseHandler";
const NoopHandler: ResponseHandler = (res, next) => {
return new Promise(async () => {
if (res.status >= 500) {
res = { message: res.statusText } as any;
}
else if (res.status !== 200) {
res = await res.json();
}
next(res.status !== 200 ? res: undefined);
});
}
export default NoopHandler;

View File

@ -0,0 +1,7 @@
export interface Callback {
(err?: any): void;
}
export interface ResponseHandler<ExtraMetadata = any> {
(res: Response, next: Callback, options?: ExtraMetadata): Promise<void>;
}

View File

@ -0,0 +1,32 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { RouterProvider, createBrowserRouter } from 'react-router-dom';
import { AuthPage, loader as authpageloader } from './pages/AuthPage';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
const router = createBrowserRouter([
{
path: "/",
element: <App />,
errorElement: <h1>error</h1>,
children: [
{
path: "action/:action",
loader: authpageloader,
element: <AuthPage />
}
]
}
])
root.render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
);

View File

@ -0,0 +1,103 @@
import React, { useState } from "react";
import { useLoaderData } from "react-router-dom";
import { Action } from "../types/Action";
import { isInEnum } from "../utils/EnumUtils";
import AuthFlow from "../components/AuthFlow";
import { ColumnLayout, Container, FileUpload, FormField, Select } from "@cloudscape-design/components";
import { getHandler } from "../handlers/HandlerRegistry";
import { DownloadMetadata } from "../handlers/DownloadFileHandler";
export interface IAuthPageLoader {
action: Action;
}
export async function loader({ params }: any) {
if (!isInEnum(Action, params.action)) {
throw new Error("Not a valid action");
}
return { action: params.action };
}
interface SelectOption {
label?: string;
value?: string;
}
const selectOptions: SelectOption[] = [
{ label: "backup", value: "backup" },
{ label: "key", value: "key" },
];
export function AuthPage() {
const { action } = useLoaderData() as IAuthPageLoader;
const [selectedOption, setSelectedOption] = useState<SelectOption>({value: ""});
const [files, setFiles] = useState<File[]>([]);
const fileReady = action !== Action.UPLOAD || files.length > 0;
let options: RequestInit = {};
let handlerMetadata: DownloadMetadata = {
name: selectedOption.value || "file",
type: "dat",
}
if (action === Action.DELETE) {
options = {
method: 'delete'
}
}
if (action === Action.UPLOAD) {
if (files.length > 0) {
const formData = new FormData();
formData.append("file", files[0]);
options = {
method: 'post',
body: formData,
}
console.log(options);
}
}
return (
<Container>
<ColumnLayout columns={1}>
<FormField label={"Domain"} description={"Select which domain to access"} stretch>
<Select
selectedOption={selectedOption}
onChange={({ detail }) => setSelectedOption(detail.selectedOption)}
options={selectOptions}
/>
</FormField>
{action === Action.UPLOAD &&
<FileUpload
value={files}
onChange={({ detail }) => setFiles(detail.value)}
i18nStrings={{
uploadButtonText:e=>e?"Choose files":"Choose file",
dropzoneText:e=>e?"Drop files to upload":"Drop file to upload",
removeFileAriaLabel:e=>`Remove file ${e+1}`,
limitShowFewer:"Show fewer files",
limitShowMore:"Show more files",
errorIconAriaLabel:"Error"
}}
/>
}
{fileReady && selectedOption.value &&
<AuthFlow
action={action}
subdomain={selectedOption.value}
responseHandler={getHandler(action)}
options={options}
handlerMetadata={handlerMetadata}
/>
}
</ColumnLayout>
</Container>
);
}

View File

@ -0,0 +1,5 @@
export enum Action {
DOWNLOAD = "download",
UPLOAD = "upload",
DELETE = "delete",
}

View File

@ -0,0 +1,3 @@
export function isInEnum(en: any, item: string): boolean {
return Object.values(en).includes(item);
}

View File

@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ESNext",
"lib": ["dom", "dom.iterable", "esnext"],
"types": ["vite/client", "vite-plugin-svgr/client"],
"allowJs": false,
"skipLibCheck": false,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "ESNext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"]
}

1
packages/client/vite-env.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference types="vite/client" />

View File

@ -0,0 +1,23 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import viteTsconfigPaths from 'vite-tsconfig-paths';
import svgrPlugin from 'vite-plugin-svgr';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react(), viteTsconfigPaths(), svgrPlugin()],
server: {
proxy: {
'/api': {
target: 'http://localhost:5000',
changeOrigin: true,
},
},
host: "0.0.0.0",
port: 3000
},
build: {
outDir: "dist",
},
});

View File

@ -0,0 +1,27 @@
{
"name": "lnurl-db-server",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "bun --hot run src/server.ts"
},
"dependencies": {
"express": "^4.18.2",
"express-fileupload": "^1.4.0",
"express-rate-limit": "^6.10.0",
"lnurl": "^0.25.1",
"qrcode": "^1.5.3",
"redis": "^4.6.8",
"ts-node": "^10.9.1",
"ts-node-dev": "^2.0.0",
"typescript": "^5.2.2"
},
"devDependencies": {
"@types/express": "^4.17.17",
"@types/express-fileupload": "^1.4.1",
"@types/express-rate-limit": "^6.0.0",
"@types/node": "^20.6.4",
"@types/qrcode": "^1.5.2"
}
}

View File

@ -0,0 +1,46 @@
import { IAccessControl } from "../../types/IAccessControl";
export abstract class AbstractDbClient {
// set operations for challenges
/**
* Add a challenge in progress. It will expire from the DB after a configured amount of time
* @param challenge - 32 random bytes in hex
* @returns true if the operation completed successfully
*/
public abstract putChallenge(challenge: string): Promise<boolean>;
/**
* Checks if the given challenge already exists in the db
* @param challenge - challenge to check against db
* @returns true if challenge exists in DB
*/
public abstract doesChallengeExist(challenge: string): Promise<boolean>;
/**
* Remove the challenge from the DB manually
* @param challenge
* @returns true if removed successfully, false if not in DB.
*/
public abstract removeChallenge(challenge: string): Promise<boolean>;
// access control methods
/**
* Set an entry in the DB to mark that a particular challenge was completed by a certain key.
* A future operation which presents this challenge will be authenticated by the key associated in this operation
* @param challenge - the challenge which was completed
* @param key - the key which was part of the authentication test
*/
public abstract markChallengeSuccess(challenge: string, key: string): Promise<void>;
/**
* Calls into the DB to see if a particular challege has been completed. If it has, return the relevant access control metadata.
* This method will also decrement the access count, and remove it if it falls below the number of remaining access tokens on this challenge
* @param challenge - 32 byte hex challenge
*/
public abstract accessFromChallenge(challenge: string): Promise<IAccessControl | null>;
public abstract connect(): Promise<any>;
public abstract put(key: string, value: string): Promise<any>;
public abstract exists(key: string): Promise<any>;
}

View File

@ -0,0 +1,82 @@
import { RedisClientOptions, RedisClientType, RedisFunctions, RedisModules, RedisScripts, createClient } from "redis";
import { IAccessControl } from "../../types/IAccessControl";
import { AbstractDbClient } from "./AbstractDbClient";
import { RedisKeys } from "../../types/RedisKeys";
export class RedisDbClient<A extends RedisModules, B extends RedisFunctions, C extends RedisScripts> extends AbstractDbClient {
private client: RedisClientType<A, B, C>;
private timers: { [challenge: string]: NodeJS.Timeout } = {};
constructor(onError: (err: any) => void, options?: RedisClientOptions<A, B, C>) {
super();
this.client = createClient(options);
this.client.on("error", onError);
}
public async connect(): Promise<RedisClientType<A, B, C>> {
return this.client.connect();
}
private scheduleRemoval(challenge: string): void {
this.timers[challenge] = setTimeout(async () => {
console.log("expiring challenge", challenge);
await this.removeChallenge(challenge);
}, Bun.env.CHALLENGE_EXPIRE_MS);
}
public async putChallenge(challenge: string): Promise<boolean> {
let res: number = await this.client.sAdd(RedisKeys.CHALLENGES, challenge);
// if the sAdd succeeded
if (res > 0) {
this.scheduleRemoval(challenge);
}
return res > 0;
}
public doesChallengeExist(challenge: string): Promise<boolean> {
return this.client.sIsMember(RedisKeys.CHALLENGES, challenge);
}
public async removeChallenge(challenge: string): Promise<boolean> {
let res: number = await this.client.sRem(RedisKeys.CHALLENGES, challenge);
clearTimeout(this.timers[challenge]);
delete this.timers[challenge];
return res > 0;
}
public async markChallengeSuccess(challenge: string, key: string): Promise<void> {
await this.client.set(challenge, key);
}
public async accessFromChallenge(challenge: string): Promise<IAccessControl | null> {
let key: string | null = await this.client.getDel(challenge);
if (key == null) {
return null;
}
return {
key,
remainingAccess: 0,
}
}
public async put(key: string, value: string): Promise<any> {
return this.client.set(key, value);
}
public async exists(key: string): Promise<number> {
return this.client.exists(key);
}
public async get(key: string): Promise<string | null> {
return this.client.get(key);
}
public async remove(key: string): Promise<string | null> {
return this.client.getDel(key);
}
}

View File

@ -0,0 +1,14 @@
import { RedisDbClient } from "./RedisDbClient";
let client: RedisDbClient<any, any, any>;
export async function getRedisClient(): Promise<RedisDbClient<any, any, any>> {
if (!client) {
client = new RedisDbClient((err) => console.error(err), { url: Bun.env.REDIS_CONNECT_URL });
await client.connect()
}
return client;
}

View File

@ -0,0 +1,65 @@
import express from "express";
import { getRedisClient } from "../clients/db/RedisDbProvider";
import fileUpload from "express-fileupload";
const router = express.Router();
const client = await getRedisClient();
router.get('/download/:challenge', async(req, res) => {
const { challenge } = req.params;
const allowedAccess = await client.accessFromChallenge(challenge);
if (allowedAccess == null) {
res.status(401).json({ message: "Not authorized" });
return;
}
const storedData = await client.get(allowedAccess.key);
if (storedData == null) {
res.status(404).json({ message: "Nothing available to download; upload something first" });
return;
}
res.status(200).send(storedData);
});
router.post('/upload/:challenge', async(req, res) => {
const { challenge } = req.params;
const allowedAccess = await client.accessFromChallenge(challenge);
if (!allowedAccess) {
res.status(401).json({ message: "Not authorized" });
return;
}
const storedData = await client.exists(allowedAccess.key);
if (storedData) {
res.status(409).json({ message: "Already exists, delete first before uploading again" });
return;
}
await client.put(allowedAccess.key, (req.files?.file as fileUpload.UploadedFile).data.toString());
res.status(200).send({ message: "added to db" });
});
router.delete('/delete/:challenge', async(req, res) => {
const { challenge } = req.params;
const allowedAccess = await client.accessFromChallenge(challenge);
if (allowedAccess == null) {
res.status(401).json({ message: "Not authorized" });
return;
}
const storedData = await client.remove(allowedAccess.key);
res.status(200).send({ message: "deleted from DB" });
});
export default router;

View File

@ -0,0 +1,62 @@
import express from "express";
import { getRedisClient } from "../clients/db/RedisDbProvider";
import crypto from "crypto";
// @ts-ignore
import lnurl, { verifyAuthorizationSignature } from "lnurl";
const router = express.Router();
const client = await getRedisClient();
router.get("/login", async (req, res) => {
let challenge: string = "";
// challenge must be unique
do {
challenge = crypto.randomBytes(32).toString('hex');
} while (await client.doesChallengeExist(challenge));
const { subdomain } = req.query;
if (!subdomain) {
res.status(400).json({ message: "Missing subdomain" });
return;
}
// MUST BE https for clearnet
const url = `https://${subdomain}.${Bun.env.BASE_DOMAIN}/api/lnurl/validate?action=auth&tag=login&k1=${challenge}`;
const encoded = lnurl.encode(url);
// add the challenge to db
await client.putChallenge(challenge);
res.json({ challenge, lnurl: encoded });
});
router.get('/validate', async (req, res) => {
// @ts-ignore
const { k1, key, sig } = req.query as IAuthCallbackQuery;
if (!(await client.doesChallengeExist(k1))) {
console.log("challenge doesn't exist");
res.status(404).json({ status: "ERROR", reason: "challenge not found" });
return;
}
const signatureValid: boolean = verifyAuthorizationSignature(sig, k1, key);
if (signatureValid) {
console.log("signature is valid");
await client.removeChallenge(k1);
await client.markChallengeSuccess(k1, key);
res.status(200).json({ status: "ok" });
return;
}
console.log("Signature mismatch");
res.status(401).json({ status: "ERROR", reason: "Signature mismatch" });
});
export default router;

View File

@ -0,0 +1,27 @@
import express from "express";
import fileUpload from "express-fileupload";
import { challengeLimiter, uploadDownloadLimiter } from "./util/RateLimits";
import LnurlRouter from "./routers/LnurlRouter";
import ActionRouter from "./routers/ActionRouter";
const app = express();
app.set('trust proxy', 1);
app.use('/api/actions/download', uploadDownloadLimiter);
app.use('/api/actions/upload', uploadDownloadLimiter);
app.use('/api/lnurl/login', challengeLimiter);
app.use(express.json());
app.use(fileUpload({
limits: { fileSize: 5 * 1024 * 1024 }
}));
app.use(express.static("dist"));
// use routers
app.use('/api/lnurl', LnurlRouter);
app.use('/api/actions', ActionRouter);
app.listen(5000, async () => {
console.log("listening on port 5000");
});

View File

@ -0,0 +1,7 @@
declare module "bun" {
interface Env {
CHALLENGE_EXPIRE_MS: number;
BASE_DOMAIN: string;
REDIS_CONNECT_URL: string; // `redis[s]://[[username][:password]@][host][:port][/db-number]`
}
}

View File

@ -0,0 +1,4 @@
export interface IAccessControl {
key: string;
remainingAccess?: number;
}

View File

@ -0,0 +1,7 @@
export default interface IAuthCallbackQuery {
action: string;
tag: string;
k1: string;
sig: string;
key: string
}

View File

@ -0,0 +1,3 @@
export enum RedisKeys {
CHALLENGES = "challenges",
}

View File

@ -0,0 +1,6 @@
import { RedisClientType } from "redis";
import { RedisKeys } from "../types/RedisKeys";
export function expireChallenges(client: RedisClientType): Promise<any> {
return client.zRemRangeByScore(RedisKeys.CHALLENGES, '-inf', Date.now());
}

View File

@ -0,0 +1,14 @@
import rateLimit from "express-rate-limit";
export const uploadDownloadLimiter = rateLimit({
windowMs: 5 * 60 * 1000,
max: 5,
skipFailedRequests: true,
});
export const challengeLimiter = rateLimit({
windowMs: 5 * 60 * 1000,
max: 10,
skipFailedRequests: true,
});

22
tsconfig.json Normal file
View File

@ -0,0 +1,22 @@
{
"compilerOptions": {
"lib": ["ESNext"],
"module": "esnext",
"target": "esnext",
"moduleResolution": "bundler",
"moduleDetection": "force",
"allowImportingTsExtensions": true,
"noEmit": true,
"composite": true,
"strict": true,
"downlevelIteration": true,
"skipLibCheck": true,
"jsx": "react-jsx",
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"allowJs": true,
"types": [
"bun-types" // add Bun global
]
}
}