aboutsummaryrefslogtreecommitdiffstats
path: root/lib/auth.ts
blob: af5de3fd652a2a5a4a5ff097627d80baedf7d19e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import config from "$config";
import { db } from "$lib/db";
import { fail, getUser } from "$lib/utils";
import { quiet, suppressed } from "$lib/logging";
import fastifyPassport from "@fastify/passport";
import jwt from "passport-jwt";

export const optional = {
  preValidation: fastifyPassport.authenticate(
    "jwt",
    { session: false },
    (req, res, err, user, info) => {
      req.user = user;
    },
  ),
};

export const auth = {
  preValidation: fastifyPassport.authenticate("jwt", {
    authInfo: false,
    session: false,
  }),
};

// Wrong PINs per account. Without a limit, anyone holding a stolen session
// can try all 10^6 PINs from rotating IPs, since every PIN check answers
// right/wrong. After PIN_MAX wrong guesses in PIN_WINDOW seconds, every PIN
// check fails, the right PIN included, until the window runs out.
const PIN_MAX = 10;
const PIN_WINDOW = 3600;

// true if the account has no PIN or `pin` is right. A missing pin is not a
// guess and doesn't count; a wrong one does.
export const checkPin = async (user, pin) => {
  if (!user?.pin) return true;
  const k = `pinfail:${user.id}`;
  const n = Number(await db.get(k)) || 0;
  if (n >= PIN_MAX) fail("Too many wrong PINs, try again in an hour");
  if (pin === undefined || pin === null || pin === "") return false;
  if (pin === user.pin) {
    if (n) await db.del(k);
    return true;
  }
  if ((await db.incr(k)) === 1) await db.expire(k, PIN_WINDOW);
  return false;
};

export const requirePin = async ({ body, user }) => {
  if (!user || !(await checkPin(user, body?.pin))) fail("Invalid pin");
};

// A caller-supplied `aid` decides which account's node wallet composes and
// signs a withdrawal and whose balance gets debited, so it has to be an
// account the caller actually owns. `${uid}:accounts` is the ownership list —
// the same one GET /account/:id and payments.list already check — and a user's
// own id is in it. Omitted `aid` means "my own account".
export const requireAccount = async ({ aid, user }) => {
  if (!user) fail("unauthorized");
  if (!aid || aid === user.id) return user.id;
  if ((await db.lPos(`${user.id}:accounts`, aid)) === null)
    fail("unauthorized");
  return aid;
};

export const jwtStrategy = new jwt.Strategy(
  {
    jwtFromRequest: jwt.ExtractJwt.fromExtractors([
      jwt.ExtractJwt.fromAuthHeaderAsBearerToken(),
      (req) => (req.cookies ? req.cookies.token : null),
    ]),
    secretOrKey: config.jwt,
    passReqToCallback: true,
  },
  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);

    // Hard eviction: an account in the `evicted` set cannot authenticate AT ALL
    // — every request, every endpoint — regardless of source IP/VPN. Unlike the
    // `blacklist` freeze (which only blocks sends), this kills the value of a
    // compromised/attacker JWT outright. Match on the immutable uid OR username
    // so a rename can't shake it.
    if (
      user &&
      ((await db.sIsMember("evicted", user.id)) ||
        (await db.sIsMember("evicted", user.username?.toLowerCase?.().trim())))
    ) {
      // Distinctive, greppable line carrying the real source IP so the realtime
      // auto-banner (scripts/atk-autoban.sh) can insta-ban it at Cloudflare.
      // Throttled per account. An evicted JWT replayed from a rotating proxy
      // pool otherwise emits one line per request and
      // has atk-autoban.sh place a Cloudflare block on every residential IP it
      // sees, which protects nothing. First hit logs with its IP; afterwards
      // one summary per 10 minutes, worded so the auto-banner ignores it.
      const n = quiet(`evicted:${user.id}`);
      if (n !== null)
        console.error(
          n
            ? `evicted-auth ${user.username} ${suppressed(n)}`
            : `EVICTED_AUTH ${user.username} ${req.headers["cf-connecting-ip"] || req.ip}`,
        );
      return next(null, false);
    }

    next(null, user);
  },
);