From 044c1737289f89d111bcc8c3c709479286dcf29d Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Thu, 4 Sep 2025 08:45:01 -0700 Subject: support readonly tokens --- index.ts | 1 + lib/auth.ts | 14 +++++++++++--- routes/users.ts | 9 ++++++++- 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/index.ts b/index.ts index 84c67777..02a6e0b5 100644 --- a/index.ts +++ b/index.ts @@ -113,6 +113,7 @@ app.post("/account/delete", auth, users.deleteAccount); app.get("/users", auth, users.list); app.get("/me", auth, users.me); +app.get("/ro", auth, users.ro); app.get("/credits", auth, users.credits); app.get("/users/:key", users.get); app.post("/register", users.create); diff --git a/lib/auth.ts b/lib/auth.ts index 0dfff4ec..79c04e9d 100644 --- a/lib/auth.ts +++ b/lib/auth.ts @@ -1,5 +1,4 @@ import config from "$config"; -import { g } from "$lib/db"; import { fail, getUser } from "$lib/utils"; import fastifyPassport from "@fastify/passport"; import jwt from "passport-jwt"; @@ -43,9 +42,18 @@ export const jwtStrategy = new jwt.Strategy( (req) => (req.cookies ? req.cookies.token : null), ]), secretOrKey: config.jwt, + passReqToCallback: true, }, - async (payload, next) => { - const user = await getUser(payload.id); + async (req, payload, next) => { + const { originalUrl: u, method: m } = req; + + let { id } = payload; + const wl = { GET: ["/invoice", "/payments"], POST: ["/invoice"] }; + + if (id.endsWith("-ro") && wl[m].some((p) => u.startsWith(p))) + id = id.slice(0, -3); + + const user = await getUser(id); next(null, user); }, ); diff --git a/routes/users.ts b/routes/users.ts index 36f2aab4..750494b6 100644 --- a/routes/users.ts +++ b/routes/users.ts @@ -311,7 +311,7 @@ export default { emit(user.id, "user", user); res.send({ user }); } catch (e) { - console.log(e) + console.log(e); warn("failed to update", user.username, e.message); bail(res, e.message); } @@ -1044,4 +1044,11 @@ export default { const liquid = await g(`credit:liquid:${id}`); res.send({ bitcoin, lightning, liquid }); }, + + async ro(req, res) { + const { user } = req; + const payload = { id: `${user.id}-ro` }; + const token = jwt.sign(payload, config.jwt); + res.send(token); + }, }; -- cgit v1.2.3