This commit is contained in:
soruly 2022-06-16 08:28:12 +00:00
commit 42aca0ebce
No known key found for this signature in database
GPG Key ID: EF971E90F3D2521F
22 changed files with 2121 additions and 0 deletions

2
.env.example Normal file
View File

@ -0,0 +1,2 @@
SERVER_PORT=3000
SERVER_ADDR=127.0.0.1

12
.github/FUNDING.yml vendored Normal file
View File

@ -0,0 +1,12 @@
# These are supported funding model platforms
github: [soruly] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: soruly
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: https://www.paypal.me/soruly/

8
.github/dependabot.yml vendored Normal file
View File

@ -0,0 +1,8 @@
version: 2
updates:
- package-ecosystem: npm
directory: "/"
schedule:
interval: daily
time: "21:00"
open-pull-requests-limit: 99

66
.github/workflows/codeql-analysis.yml vendored Normal file
View File

@ -0,0 +1,66 @@
name: "CodeQL"
on:
push:
branches: [master]
pull_request:
# The branches below must be a subset of the branches above
branches: [master]
schedule:
- cron: '0 21 * * 6'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
# Override automatic language detection by changing the below list
# Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python']
language: ['javascript']
# Learn more...
# https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection
steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
# We must fetch at least the immediate parents so that if this is
# a pull request then we can checkout the head.
fetch-depth: 2
# If this run was triggered by a pull request event, then checkout
# the head of the pull request instead of the merge commit.
- run: git checkout HEAD^2
if: ${{ github.event_name == 'pull_request' }}
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1

30
.github/workflows/node.js.yml vendored Normal file
View File

@ -0,0 +1,30 @@
# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
name: Node.js Lint
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [14.x, 16.x, 18.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm ci
- run: npm run build --if-present
- run: npm test

64
.gitignore vendored Normal file
View File

@ -0,0 +1,64 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# 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
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://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/
# TypeScript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
# next.js build output
.next
# local data storage
data/

3
.prettierrc.json Normal file
View File

@ -0,0 +1,3 @@
{
"printWidth": 100
}

46
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at soruly@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 soruly
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

63
README.md Normal file
View File

@ -0,0 +1,63 @@
# 2FA
[![License](https://img.shields.io/github/license/soruly/2fa.svg?style=flat-square)](https://github.com/soruly/2fa/blob/master/LICENSE)
[![GitHub Workflow Status](https://img.shields.io/github/workflow/status/soruly/2fa/Docker%20Image%20CI?style=flat-square)](https://github.com/soruly/2fa/actions)
Self hosted 2-factor authentication PWA
## Features
- Installable PWA
- (TBC) Display timeout indicator
- (TBC) Scan QR Code instead of manual input
- (TBC) Show QR Code for copying to other devices
## Getting Started
Prerequisites: nodejs >= 16
```
git clone https://github.com/soruly/2fa.git
cd 2fa
npm install
node server.js
```
Note: In order for PWA to work, you must host the server behind a reverse proxy (like nginx) with HTTPS
Example nginx config:
```
location / {
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection upgrade;
proxy_buffering off;
proxy_cache off;
proxy_pass http://127.0.0.1:3000;
}
```
### Environment Variables
- Copy `.env.example` to `.env`
- Edit `.env` as you need
```
SERVER_PORT # (optional) Default: 3000
SERVER_ADDR # (optional) Default: 127.0.0.1
```
### Run by pm2
You also can use [pm2](https://pm2.keymetrics.io/) to run this in background.
Use below commands to start / restart / stop server.
```
npm run start
npm run stop
npm run reload
npm run restart
npm run delete
```

10
ecosystem.config.json Normal file
View File

@ -0,0 +1,10 @@
{
"apps": [
{
"name": "2fa",
"script": "server.js",
"instances": 1,
"exec_mode": "fork"
}
]
}

42
index.ejs Normal file
View File

@ -0,0 +1,42 @@
<!DOCTYPE html>
<html translate="no">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover"
/>
<meta name="google" content="notranslate" />
<meta name="robots" content="noindex, nofollow" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<title>Authenticator</title>
<link rel="manifest" href="/manifest.json" />
<link rel="icon" type="image/png" href="/favicon.png" />
<link rel="apple-touch-icon" href="/favicon.png" />
<link rel="stylesheet" href="/style.css" />
<% list.forEach(function(e){ %>
<div class="item" id="<%= e.name %>">
<div class="title"><%= e.name %></div>
<div class="body">
<div class="otp"><%= e.otp %></div>
<span class="delete material-icons">delete</span>
</div>
</div>
<% }); %>
<form method="post" action="/" enctype="application/x-www-form-urlencoded">
<label>
Name
<input name="name" type="text" required />
</label>
<label>
Secret
<input name="otp" type="text" required minlength="16" />
</label>
<input type="submit" />
</form>
<script src="client.js" defer></script>
</html>

1419
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

39
package.json Normal file
View File

@ -0,0 +1,39 @@
{
"name": "2fa.soruly.com",
"version": "1.0.0",
"description": "Self-hosted 2FA app",
"main": "server.js",
"type": "module",
"scripts": {
"start": "pm2 start ecosystem.config.json",
"watch": "pm2 start ecosystem.config.json --watch",
"stop": "pm2 stop ecosystem.config.json",
"restart": "pm2 restart ecosystem.config.json",
"reload": "pm2 reload ecosystem.config.json",
"delete": "pm2 delete ecosystem.config.json",
"prettier": "prettier",
"format": "prettier --write \"**/*.js\"",
"lint": "prettier --check \"**/*.js\"",
"test": "prettier --check \"**/*.js\""
},
"repository": {
"type": "git",
"url": "git+https://github.com/soruly/2fa.git"
},
"author": "soruly",
"license": "MIT",
"bugs": {
"url": "https://github.com/soruly/2fa/issues"
},
"homepage": "https://github.com/soruly/2fa#readme",
"dependencies": {
"dotenv": "^16.0.1",
"ejs": "^3.1.8",
"express": "^4.18.1",
"express-rate-limit": "^6.4.0",
"fs-extra": "^10.1.0"
},
"devDependencies": {
"prettier": "^2.7.1"
}
}

126
server.js Normal file
View File

@ -0,0 +1,126 @@
import "dotenv/config.js";
import fs from "fs-extra";
import path from "path";
import crypto from "crypto";
import express from "express";
import rateLimit from "express-rate-limit";
const { SERVER_ADDR = "0.0.0.0", SERVER_PORT = 3000 } = process.env;
const app = express();
app.disable("x-powered-by");
app.set("trust proxy", 1);
app.set("view engine", "ejs");
app.set("views", path.resolve("."));
app.use(express.json());
app.use((req, res, next) => {
res.set("Access-Control-Allow-Origin", "*");
res.set("Access-Control-Allow-Methods", "GET, OPTIONS");
res.set("Referrer-Policy", "no-referrer");
res.set("X-Content-Type-Options", "nosniff");
res.set(
"Content-Security-Policy",
[
"default-src 'self'",
"base-uri 'none'",
"frame-ancestors 'none'",
"block-all-mixed-content",
].join("; ")
);
next();
});
app.use(
rateLimit({
max: 120, // 120 requests per IP address (per node.js process)
windowMs: 60 * 1000, // per 1 minute
})
);
app.get(/[^\/]+\.[^\/]+$/, express.static("./static", { maxAge: 1000 * 60 * 60 * 24 }));
app.delete("/", (req, res) => {
fs.copyFileSync("data/latest.json", `data/${Date.now()}.json`);
fs.writeFileSync(
"data/latest.json",
JSON.stringify(
JSON.parse(fs.readFileSync("data/latest.json")).filter((e) => e.name !== req.body.name),
null,
2
)
);
return res.sendStatus(204);
});
app.post("/", (req, res) => {
fs.copyFileSync("data/latest.json", `data/${Date.now()}.json`);
fs.writeFileSync(
"data/latest.json",
JSON.stringify(JSON.parse(fs.readFileSync("data/latest.json")).concat(req.body), null, 2)
);
return res.sendStatus(204);
});
app.get("/", async (req, res) => {
if (req.headers.accept?.toLowerCase() === "text/event-stream") {
res.set({
"Cache-Control": "no-cache",
"Content-Type": "text/event-stream",
});
res.flushHeaders();
res.write("retry: 1000\n\n");
while (true) {
res.write(
`data: ${JSON.stringify(
JSON.parse(fs.readFileSync("data/latest.json")).map(({ name, otp }) => ({
name,
otp: getOtp(otp),
}))
)}\n\n`
);
await new Promise((resolve) =>
setTimeout(
resolve,
(Math.floor(Math.round(new Date().getTime() / 1000.0) / 30) + 1) * 30 * 1000 -
new Date().getTime()
)
);
}
}
return res.render("index", {
list: JSON.parse(fs.readFileSync("data/latest.json")).map(({ name, otp }) => ({
name,
otp: getOtp(otp),
})),
});
});
if (!fs.existsSync("data/latest.json")) fs.outputFileSync("data/latest.json", JSON.stringify([]));
app.listen(SERVER_PORT, SERVER_ADDR, () =>
console.log(`Media server listening on ${SERVER_ADDR}:${SERVER_PORT}`)
);
const getOtp = (secret) => {
const timeBuffer = Buffer.alloc(8, 0);
timeBuffer.writeUInt32BE(Math.floor(Math.round(new Date().getTime() / 1000.0) / 30), 4);
const bits = secret
.toUpperCase()
.split("")
.map((c) => "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".indexOf(c).toString(2).padStart(5, "0"))
.join("");
const secretBuffer = Buffer.alloc(Math.ceil(secret.length / 16) * 10);
for (let i = 0; i <= Math.floor(bits.length / 8); i++) {
secretBuffer[i] = parseInt(bits.substring(i * 8, (i + 1) * 8), 2);
}
const hmac = crypto.createHmac("sha1", secretBuffer).update(timeBuffer).digest("hex");
const offset = parseInt(hmac.substring(hmac.length - 1), 16) & 0x7fffffff;
const otp = (parseInt(hmac.substring(offset * 2, offset * 2 + 8), 16) & 0x7fffffff).toString();
return otp.length > 6 ? otp.substring(otp.length - 6) : otp.padStart(6, "0");
};

Binary file not shown.

38
static/client.js Normal file
View File

@ -0,0 +1,38 @@
const events = new EventSource("/");
events.onmessage = (event) => {
for (const { name, otp } of JSON.parse(event.data)) {
document.querySelector(`#${name} .otp`).innerText = otp;
}
};
document.querySelector("form").onsubmit = async (e) => {
e.preventDefault();
const res = await fetch("/", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: e.target.querySelector(`[name=name]`).value,
otp: e.target.querySelector(`[name=otp]`).value,
}),
});
if (res.status === 204) window.location.reload();
return false;
};
for (const e of document.querySelectorAll(".delete")) {
e.addEventListener("click", async (e) => {
if (confirm(`Delete ${e.target.parentElement.id} ?`)) {
const res = await fetch("/", {
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: e.target.parentElement.id,
}),
});
if (res.status === 204) window.location.reload();
}
});
}
if (navigator.serviceWorker) navigator.serviceWorker.register("/sw.js");

BIN
static/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

BIN
static/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 507 KiB

23
static/manifest.json Normal file
View File

@ -0,0 +1,23 @@
{
"name": "soruly 2FA",
"short_name": "soruly 2FA",
"icons": [
{
"src": "favicon.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any"
},
{
"src": "icon.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
],
"start_url": "/",
"display": "standalone",
"orientation": "natural",
"background_color": "#ffffff",
"theme_color": "#ffffff"
}

106
static/style.css Normal file
View File

@ -0,0 +1,106 @@
html,
body {
margin: 0;
padding: 0;
font-family: system-ui, Meiryo, sans-serif, Arial;
user-select: none;
-webkit-user-select: none;
}
body {
max-width: 30rem;
margin: auto;
}
@font-face {
font-display: block;
font-family: "Material Icons";
font-style: normal;
font-weight: 400;
src: local("Material Icons"), local("MaterialIcons-Regular"),
url(/MaterialIcons-Regular.woff2) format("woff2");
}
.material-icons {
font-family: "Material Icons";
font-weight: normal;
font-style: normal;
display: inline-block;
line-height: 1;
text-transform: none;
letter-spacing: normal;
word-wrap: normal;
white-space: nowrap;
direction: ltr;
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
-moz-osx-font-smoothing: grayscale;
}
.root::before {
display: none;
font-family: "Material Icons";
}
.hidden {
display: none;
}
.item {
border-bottom: 0.125rem solid #cccccc;
margin: 1rem;
}
.item .title {
font-weight: bold;
color: #333333;
}
.item .body {
display: flex;
justify-content: space-between;
}
.item .body .otp {
font-size: 2rem;
color: #3673d7;
user-select: text;
}
.item .body .qrcode,
.item .body .delete {
display: flex;
align-items: center;
cursor: pointer;
font-size: 2rem;
color: #666666;
}
form {
display: flex;
margin: 1rem;
}
label {
font-size: 0.75rem;
}
input[type="text"] {
width: 10rem;
height: 1.25rem;
}
input[name="otp"] {
text-transform: uppercase;
}
input[type="submit"] {
background: #3673d7;
color: #ffffff;
font-weight: bold;
border-radius: 0.2rem;
font-size: 1rem;
cursor: pointer;
border: none;
padding: 0.5rem 0.75rem;
margin: 0.5rem;
box-shadow: 0 0 0.125rem #cccccc;
}
input[type="submit"]:hover {
background: #1e63d3;
box-shadow: 0 0 0.25rem #cccccc;
}
input[type="submit"]:active {
background: #3673d7;
box-shadow: none;
}

3
static/sw.js Normal file
View File

@ -0,0 +1,3 @@
self.addEventListener("fetch", (event) => {
return;
});