DEV Community

Daniel Pertu
Daniel Pertu

Posted on

One licence check, two implementations, and an email lowercased four times between the keyboard and the database

Notifio has no accounts. You pay once on the pricing page, an email arrives with an activation token, and you type both into the desktop app. There is no password, no session, no cookie. Every privileged request in the product is that pair of strings, sent again.

That makes the licence check the only authentication in the whole system, so I went looking for where it lives. The answer is: in more places than I thought, and all of them agree, which is the part worth writing down.

The helper

/**
 * Look up a licence by token and verify the email matches.
 * Returns null for any mismatch so callers cannot leak which part was wrong.
 */
export async function resolveLicense(
  email: string,
  token: string
): Promise<License | null> {
  if (!email || !token) return null;

  const [license] = await db
    .select()
    .from(licenses)
    .where(eq(licenses.token, token))
    .limit(1);

  if (!license || license.email !== email || !license.active) return null;
  return license;
}
Enter fullscreen mode Exit fullscreen mode

Fifteen lines, and two decisions inside it. The query is keyed on the token alone and the email is compared in JavaScript afterwards, so the route above has one answer for three different failures: no such token, right token with the wrong email, and a deactivated licence. Nothing in the response distinguishes "that token does not exist" from "that token is not yours", which is the only sensible behaviour when the token is the credential.

It has two callers: /api/validate, which the app calls on launch, and /api/checkout/upgrade, which it calls when somebody buys the auto-reply upgrade.

The copy

The third route that needs the same answer is /api/notify, which the app posts to when it has something to email you about. It does not call the helper:

const [license] = await db
  .select()
  .from(licenses)
  .where(eq(licenses.token, token))
  .limit(1);

if (!license || license.email !== email || !license.active) {
  return NextResponse.json({ error: "Invalid or inactive license." }, { status: 403 });
}
Enter fullscreen mode Exit fullscreen mode

Same query, same three conditions, same order, same .limit(1), including the subtle part about comparing the email outside the database. This is not divergence, it is a copy that has stayed faithful, and that is a different kind of risk: nothing is wrong today and nothing would tell you if the helper changed tomorrow.

The one place the two differ is the answer. A licence that does not resolve is a 403 here and a 200 with { valid: false } on the validate route, which I have argued is correct and still think is, because one route is asking a question and the other is trying to do something.

Nine reads of one table

$ grep -rn "from(licenses)" src scripts | wc -l
9
Enter fullscreen mode Exit fullscreen mode

Two of the nine are the credential check above. The other seven are all idempotency rather than authentication: the Stripe webhook looks up a row by checkout session id, then by email, then by email again in the insert-race branch, then by licence id and email for an upgrade; the checkout route looks up by email to refuse a second purchase from the same address; the free-licence script looks up by email so a re-run reuses the token somebody already saved.

One table, one row per customer, nine queries, two kinds of question. The schema is what makes that safe:

email: text("email").notNull().unique(),
token: text("token").notNull().unique(),
Enter fullscreen mode Exit fullscreen mode

Both credential halves are unique columns, so "by token" and "by email" can never return a set.

Fourteen normalisations, zero shared helpers

Both strings are normalised everywhere they are read, by hand, every time:

where                                      email              token
--------------------------------------------------------------------------
app  ActivationScreen.tsx                  trim               trim + upper
app  server.ts /api/license/activate       trim + lower       trim + upper
site /api/validate                         trim + lower       trim + upper
site /api/notify                           trim + lower       trim + upper
site /api/checkout/upgrade                 trim + lower       trim + upper
site /api/checkout                         trim + lower       -
site PricingClient.tsx                     trim + lower       -
site webhooks/stripe (new licence)         trim + lower       -
site webhooks/stripe (upgrade)             trim + lower       -
site scripts/grant-free-access.mjs         trim + lower       -
Enter fullscreen mode Exit fullscreen mode

Fourteen calls to .trim().toLowerCase() or .trim().toUpperCase() on these two fields, spread across two processes and a network boundary, with no shared function anywhere. Follow one activation through and the same email is normalised four separate times:

  1. the app's activation screen trims what you typed
  2. the app's own local server lowercases it before asking the website
  3. the website's validate route lowercases it again before querying
  4. and it was already lowercased a fourth time, months earlier, by the Stripe webhook that wrote the row

Every one of those is redundant with the one before it, and I am not going to delete any of them. This is the cheap case of duplication: two method calls, no state, no ordering, and a bug in any single copy produces a licence that works in one place and not another, which is the worst support ticket in the product.

Why it has not drifted

Two things, and neither is diligence.

The token alphabet has no lowercase in it:

const ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
export function generateToken(): string {
  return `NTFIO-${randomSegment(4)}-${randomSegment(4)}-${randomSegment(4)}`;
}
Enter fullscreen mode Exit fullscreen mode

So .toUpperCase() on a token is lossless by construction: there is no legitimate token whose case it can change. It exists purely so that somebody pasting from a mail client that helpfully lowercased their text still gets in.

And every writer normalises before inserting. The webhook lowercases, the free-licence script lowercases, and there is no third writer. A read-side lowercase cannot miss a row, because no row with an uppercase email has ever existed.

The two guards that run too early

The app's local activation endpoint checks the input before it normalises it:

if (!email || !email.includes('@')) {
  return res.status(400).json({ error: 'Valid email is required.' });
}
if (!token || token.length < 10) {
  return res.status(400).json({ error: 'Valid token is required.' });
}

const normalEmail = email.trim().toLowerCase();
const normalToken = token.trim().toUpperCase();
Enter fullscreen mode Exit fullscreen mode

Both guards measure the raw string. token.length < 10 counts whitespace, so a nine-character token with a space after it passes the check and then gets trimmed back to nine. Nothing bad happens, because the website is the authority and rejects it a moment later, but the local guard is not checking what it looks like it is checking.

The number itself is worth a glance too. Real tokens are NTFIO-XXXX-XXXX-XXXX, twenty characters with a fixed six-character prefix, and the client accepts any ten. That is a deliberate choice rather than an oversight: a client-side format check that is stricter than the server's is a client that can lock someone out of a licence they genuinely own, for instance after a future format change. Ten characters is enough to catch an empty paste and nothing else, which is all a client should be doing.

What the app does when it cannot tell

The best thing in this whole path is three lines further down:

const check = await monitor.checkLicense(normalEmail, normalToken);
if (!check.ok && check.reason === 'unreachable') {
  return res.status(503).json({
    error:
      'Could not reach notifio.app to check that licence. Check your connection and try again.',
  });
}
if (!check.ok) {
  return res.status(403).json({ error: 'Invalid email or token. Please check your activation email.' });
}
Enter fullscreen mode Exit fullscreen mode

Three outcomes from a two-field form: the shape is wrong (400), we could not ask (503), the answer was no (403). The middle one exists because it once did not, and sending somebody to search their inbox for a token that is perfectly fine, because their wifi dropped, is a much worse failure than a slow activation. The app's local server also answers success here with { ok: true }, which is a sixth word for yes on top of the five the website already uses.

The change worth making

/api/notify should import resolveLicense. That deletes four lines, removes the copy, and keeps its 403, because the status code is the route's business and the lookup is not.

The fourteen normalisations stay as they are. A shared credentials(body) helper on the website would collapse five of them, which is worth doing for the three routes that read both fields, and it cannot collapse the app's two or the script's one without shipping a module across a process boundary for the sake of two method calls.

What I would not touch is the shape of the check itself: query by the secret, compare the identifier in code, return one null for every kind of no. If you want to see the user-facing end of it, the activation screen is in the app from the download page, and the help page covers what to do when a token does not take.

Top comments (0)