commit d82e150eaa9bdf1cad2fdda60d4d0003e962594f Author: Martin Dimitrov Date: Sun Feb 25 08:55:35 2024 -0800 init from lnurld-db diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..901696c --- /dev/null +++ b/.dockerignore @@ -0,0 +1,2 @@ +**/node_modules +.env* \ No newline at end of file diff --git a/.gitea/workflows/docker-image.yaml b/.gitea/workflows/docker-image.yaml new file mode 100644 index 0000000..253e7c8 --- /dev/null +++ b/.gitea/workflows/docker-image.yaml @@ -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 \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d285efb --- /dev/null +++ b/.gitignore @@ -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 \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..2fd4124 --- /dev/null +++ b/Dockerfile @@ -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 \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..0102c10 --- /dev/null +++ b/README.md @@ -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. diff --git a/bun.lockb b/bun.lockb new file mode 100755 index 0000000..4a20bbf Binary files /dev/null and b/bun.lockb differ diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..3942417 --- /dev/null +++ b/docker-compose.yml @@ -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 \ No newline at end of file diff --git a/doorman.code-workspace b/doorman.code-workspace new file mode 100644 index 0000000..deca794 --- /dev/null +++ b/doorman.code-workspace @@ -0,0 +1,13 @@ +{ + "folders": [ + { + "path": "packages/client" + }, + { + "path": "packages/server" + }, + { + "path": "." + } + ] +} \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..741e73f --- /dev/null +++ b/package.json @@ -0,0 +1,12 @@ +{ + "name": "lnurl-db", + "module": "index.ts", + "type": "module", + "workspaces": ["packages/*"], + "devDependencies": { + "bun-types": "latest" + }, + "peerDependencies": { + "typescript": "^5.0.0" + } +} diff --git a/packages/client/README.md b/packages/client/README.md new file mode 100644 index 0000000..b58e0af --- /dev/null +++ b/packages/client/README.md @@ -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 can’t go back!** + +If you aren’t 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 you’re on your own. + +You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t 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/). diff --git a/packages/client/index.html b/packages/client/index.html new file mode 100644 index 0000000..30c493e --- /dev/null +++ b/packages/client/index.html @@ -0,0 +1,34 @@ + + + + + + + + + + + React App + + + +
+ + + + diff --git a/packages/client/package.json b/packages/client/package.json new file mode 100644 index 0000000..7f9f6f9 --- /dev/null +++ b/packages/client/package.json @@ -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" +} diff --git a/packages/client/public/manifest.json b/packages/client/public/manifest.json new file mode 100644 index 0000000..f9051fe --- /dev/null +++ b/packages/client/public/manifest.json @@ -0,0 +1,8 @@ +{ + "short_name": "React App", + "name": "Create React App Sample", + "start_url": ".", + "display": "standalone", + "theme_color": "#000000", + "background_color": "#ffffff" +} diff --git a/packages/client/public/robots.txt b/packages/client/public/robots.txt new file mode 100644 index 0000000..e9e57dc --- /dev/null +++ b/packages/client/public/robots.txt @@ -0,0 +1,3 @@ +# https://www.robotstxt.org/robotstxt.html +User-agent: * +Disallow: diff --git a/packages/client/src/App.tsx b/packages/client/src/App.tsx new file mode 100644 index 0000000..33ea27d --- /dev/null +++ b/packages/client/src/App.tsx @@ -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({}); + + return ( +
+ +

homepage

+ {Object.values(Action).map(value => { + return + })} + {content.message && setContent({})} type={content.type || "info"}>{content.message}} + +
+
+ ); +} + +export default App; diff --git a/packages/client/src/components/AuthFlow.tsx b/packages/client/src/components/AuthFlow.tsx new file mode 100644 index 0000000..7c56b4c --- /dev/null +++ b/packages/client/src/components/AuthFlow.tsx @@ -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(true); + const [ qrContent, setQrContent ] = useState(""); + const [ challenge, setChallenge ] = useState(""); + const [ countdown, setCountdown ] = useState(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 ( + +
+ + +
Authentication for {action} on {subdomain}
+ {loading && } + {!loading && ( + <> + +
+ +
+ + + )} +
+
+
+ + ) +} \ No newline at end of file diff --git a/packages/client/src/contexts/AlertContext.tsx b/packages/client/src/contexts/AlertContext.tsx new file mode 100644 index 0000000..39fb14a --- /dev/null +++ b/packages/client/src/contexts/AlertContext.tsx @@ -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, +}); \ No newline at end of file diff --git a/packages/client/src/handlers/DownloadFileHandler.ts b/packages/client/src/handlers/DownloadFileHandler.ts new file mode 100644 index 0000000..8744a00 --- /dev/null +++ b/packages/client/src/handlers/DownloadFileHandler.ts @@ -0,0 +1,24 @@ +import { ResponseHandler } from "./RepsonseHandler"; + +export interface DownloadMetadata { + name?: string; + type?: string; +} + +const DownloadFileHandler: ResponseHandler = (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; \ No newline at end of file diff --git a/packages/client/src/handlers/HandlerRegistry.ts b/packages/client/src/handlers/HandlerRegistry.ts new file mode 100644 index 0000000..bd07001 --- /dev/null +++ b/packages/client/src/handlers/HandlerRegistry.ts @@ -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; + } +} \ No newline at end of file diff --git a/packages/client/src/handlers/NoopHandler.ts b/packages/client/src/handlers/NoopHandler.ts new file mode 100644 index 0000000..36344ed --- /dev/null +++ b/packages/client/src/handlers/NoopHandler.ts @@ -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; diff --git a/packages/client/src/handlers/RepsonseHandler.ts b/packages/client/src/handlers/RepsonseHandler.ts new file mode 100644 index 0000000..1f046a3 --- /dev/null +++ b/packages/client/src/handlers/RepsonseHandler.ts @@ -0,0 +1,7 @@ +export interface Callback { + (err?: any): void; +} + +export interface ResponseHandler { + (res: Response, next: Callback, options?: ExtraMetadata): Promise; +} \ No newline at end of file diff --git a/packages/client/src/index.tsx b/packages/client/src/index.tsx new file mode 100644 index 0000000..d47c0cd --- /dev/null +++ b/packages/client/src/index.tsx @@ -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: , + errorElement:

error

, + children: [ + { + path: "action/:action", + loader: authpageloader, + element: + } + ] + } +]) + +root.render( + + + +); + diff --git a/packages/client/src/pages/AuthPage.tsx b/packages/client/src/pages/AuthPage.tsx new file mode 100644 index 0000000..54393e8 --- /dev/null +++ b/packages/client/src/pages/AuthPage.tsx @@ -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({value: ""}); + + const [files, setFiles] = useState([]); + + 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 ( + + + +