Self-hosted beta-tester issue tracker with a Kotlin Android companion. - Bullet-point reports (classic and rapid fire), .txt/.md import, evidence by paste, drag, camera or gallery - Projects, calibers (.22 -> 12 gauge) as weights, public overview - Threaded discussions, "me too", admin flagging with messages and files - Board with polls and an off-topic image board with link previews - Profiles with avatars, in-app inbox, opt-in e-mail and phone alerts - Invites, optional open sign-up, TOTP 2FA with admin policy - MCP endpoint with per-user API keys - QR login both ways, built for an HTTPS reverse proxy - Encryption at rest for 2FA secrets and the SMTP password - Android app with full tester/admin parity, in-app updates, no Google services required - Interactive first-run tutorial
158 lines
8.1 KiB
JavaScript
158 lines
8.1 KiB
JavaScript
/* "Connect your phone" — one-time QR login codes.
|
|
*
|
|
* A logged-in user (web) asks for a code. The QR encodes https://<site>/connect/<code>
|
|
* - scanned with the phone camera → this landing page: "Open in PIKKIE" (pikkie:// deep link)
|
|
* or "Download the app" (APK, allowed with a valid code, no login needed)
|
|
* - scanned inside the app → the app exchanges the code for a 90-day session directly.
|
|
* Codes are random, stored hashed, valid 10 minutes and single-use (consumed on exchange).
|
|
*/
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { Router } from 'express';
|
|
import { db, now } from './db.js';
|
|
import { sha, randomToken, createSession, rateLimit } from './security.js';
|
|
import { siteUrl } from './services.js';
|
|
|
|
export const CONNECT_MINUTES = 10;
|
|
|
|
db.exec(`CREATE TABLE IF NOT EXISTS connect_codes (
|
|
hash TEXT PRIMARY KEY,
|
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
created INTEGER NOT NULL,
|
|
expires INTEGER NOT NULL,
|
|
used INTEGER
|
|
);`);
|
|
|
|
export function newConnectCode(userId) {
|
|
db.prepare('DELETE FROM connect_codes WHERE expires < ? OR used IS NOT NULL').run(now());
|
|
const code = randomToken(16);
|
|
db.prepare('INSERT INTO connect_codes(hash,user_id,created,expires) VALUES(?,?,?,?)').run(sha(code), userId, now(), now() + CONNECT_MINUTES * 60_000);
|
|
return code;
|
|
}
|
|
function peek(code) {
|
|
if (!/^[a-f0-9]{32}$/.test(String(code || ''))) return null;
|
|
const row = db
|
|
.prepare('SELECT c.*, u.name, u.email FROM connect_codes c JOIN users u ON u.id=c.user_id WHERE c.hash=? AND u.disabled=0')
|
|
.get(sha(code));
|
|
if (!row || row.used || row.expires < now()) return null;
|
|
return row;
|
|
}
|
|
/** single use → returns { token, user } or null */
|
|
export function exchangeConnectCode(code) {
|
|
const row = peek(code);
|
|
if (!row) return null;
|
|
const r = db.prepare('UPDATE connect_codes SET used=? WHERE hash=? AND used IS NULL').run(now(), row.hash);
|
|
if (r.changes !== 1) return null; // raced
|
|
return { token: createSession(row.user_id, 90), userId: row.user_id };
|
|
}
|
|
export function connectLinks(req, code) {
|
|
const base = siteUrl(req);
|
|
return {
|
|
url: `${base}/connect/${code}`,
|
|
app_url: `pikkie://connect?s=${encodeURIComponent(base)}&c=${code}`,
|
|
};
|
|
}
|
|
|
|
/* ---------- landing page (phone browser) ---------- */
|
|
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
const page = (title, body) => `<!doctype html><html lang="en"><head><meta charset="utf-8">
|
|
<meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#1c1c1f">
|
|
<title>${esc(title)} · PIKKIE</title><link rel="icon" href="/logo.svg"><meta name="robots" content="noindex">
|
|
<style>
|
|
body{margin:0;background:#1c1c1f;color:#f4f4f5;font:16px/1.5 system-ui,-apple-system,Roboto,sans-serif;display:flex;min-height:100vh;align-items:center;justify-content:center}
|
|
main{max-width:420px;padding:28px 20px;text-align:center}
|
|
img{width:120px;transform:rotate(-8deg)}
|
|
h1{font-family:Impact,'Arial Black',sans-serif;color:#ff2e93;font-size:44px;letter-spacing:3px;margin:0}
|
|
h2{margin:18px 0 6px}
|
|
p{color:#a1a1aa}
|
|
a.b{display:block;margin:14px 0;padding:16px;border-radius:4px;font-weight:800;text-transform:uppercase;letter-spacing:1px;text-decoration:none;border:2px solid #fff}
|
|
a.p{background:#ff2e93;border-color:#ff2e93;color:#fff;box-shadow:5px 5px 0 #fff}
|
|
a.s{color:#fff}
|
|
small{color:#71717a}
|
|
ol{text-align:left;color:#d4d4d8}
|
|
</style></head><body><main><img src="/logo.svg" alt=""><h1>PIKKIE</h1>${body}</main></body></html>`;
|
|
|
|
export const connectPages = Router();
|
|
connectPages.get('/:code', async (req, res) => {
|
|
res.setHeader('Cache-Control', 'no-store');
|
|
res.setHeader('Referrer-Policy', 'no-referrer');
|
|
if (!rateLimit(`connect-page:${req.ip}`, 60, 600_000)) return res.status(429).send(page('Slow down', '<p>Too many tries. Wait a few minutes.</p>'));
|
|
const row = peek(req.params.code);
|
|
if (!row) {
|
|
return res.status(404).send(page('Code expired', `<h2>This code has expired</h2><p>Connect codes work once, for ${CONNECT_MINUTES} minutes. Make a new one on your profile page in PIKKIE on your computer.</p>`));
|
|
}
|
|
const { app_url } = connectLinks(req, req.params.code);
|
|
const intent = `intent://connect?s=${encodeURIComponent(siteUrl(req))}&c=${req.params.code}#Intent;scheme=pikkie;package=nl.pikkie.app;end`;
|
|
const hasApk = !!(await import('./api.js')).latestApk();
|
|
res.send(
|
|
page(
|
|
'Connect your phone',
|
|
`<h2>Hi ${esc(row.name)} 👋</h2>
|
|
<p>Connect this phone to PIKKIE as <b style="color:#fff">${esc(row.email)}</b>.</p>
|
|
<a class="b p" href="${esc(/Android/i.test(req.get('user-agent') || '') ? intent : app_url)}">Open in the PIKKIE app</a>
|
|
${hasApk ? `<a class="b s" href="/connect/${esc(req.params.code)}/apk">Get the Android app first</a>` : ''}
|
|
<ol><li>No app yet? Tap <b>Get the Android app</b> and install it (allow installs from your browser).</li>
|
|
<li>Come back here and tap <b>Open in the PIKKIE app</b>. You are logged in instantly.</li></ol>
|
|
<small>This code works once and expires ${CONNECT_MINUTES} minutes after it was made.</small>`,
|
|
),
|
|
);
|
|
});
|
|
connectPages.get('/:code/apk', async (req, res) => {
|
|
const row = peek(req.params.code);
|
|
if (!row) return res.status(404).send(page('Code expired', '<h2>This code has expired</h2><p>Make a new one on your profile page.</p>'));
|
|
const { latestApk, apkVersion } = await import('./api.js');
|
|
const a = latestApk();
|
|
if (!a) return res.status(404).send(page('No app yet', '<h2>No Android build yet</h2><p>Ask an admin to publish one.</p>'));
|
|
const v = apkVersion(a.full).replace(/[^\w.-]/g, '');
|
|
res.setHeader('Content-Type', 'application/vnd.android.package-archive');
|
|
res.setHeader('Content-Disposition', `attachment; filename="pikkie${v ? '-' + v : ''}.apk"`);
|
|
// the file can vanish mid-request while a new build is being published: without this handler that would crash the server
|
|
fs.createReadStream(a.full).on('error', () => (res.headersSent ? res.destroy() : res.status(404).end())).pipe(res);
|
|
});
|
|
|
|
/* ---------- the other direction: log in on a computer by scanning its QR with the app ----------
|
|
* Browser asks for a login request → gets { id, secret } and shows a QR with pikkie://weblogin?s=<site>&r=<id>.
|
|
* A logged-in app scans it, shows "log in Chrome on macOS?", and approves with its own session.
|
|
* The browser polls with its secret (never in the QR) and receives a normal session cookie.
|
|
* Requests live in memory for 2 minutes.
|
|
*/
|
|
export const WEBLOGIN_SECONDS = 120;
|
|
const webLogins = new Map();
|
|
setInterval(() => {
|
|
const t = Date.now();
|
|
for (const [k, v] of webLogins) if (v.expires < t) webLogins.delete(k);
|
|
}, 30_000).unref();
|
|
|
|
function describeAgent(ua = '') {
|
|
const browser = /Edg\//.test(ua) ? 'Edge' : /Firefox\//.test(ua) ? 'Firefox' : /Chrome\//.test(ua) ? 'Chrome' : /Safari\//.test(ua) ? 'Safari' : 'a browser';
|
|
const os = /Windows/.test(ua) ? 'Windows' : /Mac OS X/.test(ua) ? 'macOS' : /Android/.test(ua) ? 'Android' : /iPhone|iPad/.test(ua) ? 'iOS' : /Linux/.test(ua) ? 'Linux' : 'unknown OS';
|
|
return `${browser} on ${os}`;
|
|
}
|
|
export function newWebLogin(req) {
|
|
const id = randomToken(16);
|
|
const secret = randomToken(24);
|
|
webLogins.set(id, { secretHash: sha(secret), expires: Date.now() + WEBLOGIN_SECONDS * 1000, agent: describeAgent(req.get('user-agent')), ip: req.ip, userId: null });
|
|
return { id, secret, app_url: `pikkie://weblogin?s=${encodeURIComponent(siteUrl(req))}&r=${id}` };
|
|
}
|
|
export function webLoginInfo(id) {
|
|
const w = webLogins.get(String(id));
|
|
if (!w || w.expires < Date.now() || w.userId) return null;
|
|
return { agent: w.agent, ip: w.ip, expires: w.expires };
|
|
}
|
|
export function approveWebLogin(id, userId) {
|
|
const w = webLogins.get(String(id));
|
|
if (!w || w.expires < Date.now() || w.userId) return false;
|
|
w.userId = userId;
|
|
w.expires = Date.now() + 30_000; // browser must pick it up quickly
|
|
return true;
|
|
}
|
|
/** → 'pending' | 'expired' | { userId } (consumes) */
|
|
export function pollWebLogin(id, secret) {
|
|
const w = webLogins.get(String(id));
|
|
if (!w || w.expires < Date.now()) return 'expired';
|
|
if (w.secretHash !== sha(String(secret || ''))) return 'expired';
|
|
if (!w.userId) return 'pending';
|
|
webLogins.delete(String(id));
|
|
return { userId: w.userId };
|
|
}
|