Files
simplex-chat/apps/simplex-badge-service/web/test/codes.test.ts
T
19e70faeec badges: webapp feature branch (#7548)
* badges: webapp (#7433)

* badges: service migrations, store and catalog

* badges: BTCPay provider and settlement poller

* badges: web listener and /api endpoints

* web: checkout single-page app

* badges: tests and BTCPay fixtures

* badges: README and ini reference

* badges: fix hex16 build on GHC 8.10.7

* badges: Stripe card lane

* badges: fix Stripe card checkout, add theming

* badges: add a discount row to the order summary

* badges: site navbar, embedding, theme, Forget move

* badges: use SB code prefix in web checkout

* badges: rename sxb app namespace to sb

* badges: embed checkout nav via site; keep original app navbar

* badges: post iframe height, apply site background when embedded

* badges: embed dark surfaces, steadier iframe height

* badges: hide app footer when embedded

* badges: size embedded body to content, not viewport

* badges: declare color-scheme to stop reload flash

* badges: fade shell in on load, no reload blank

* badges: prerender app shell into index.html

* badges: pre-paint theme, hide shell on deep reload

* badges: logo returns to landing client-side

* badges: embedded wizard back, buy-a-code, resume

* badges: signal app-managed screens, resume across reload

* badges: rebuild wizard history on deep load so Back walks it

* badges: carry welcome-page height as the iframe floor

* badges: keep selection on Buy a code; rename to Your codes

* badges: read web shell as UTF-8, not locale

* badges: resume the exact paid order after Stripe card redirect

* badges: move docker deploy under scripts

* badges: add serve_webapp toggle and webapp export

* badges: wire split webapp deploy in docker config

* badges: quiet agent logs by default

* badges: resume card redirect in the embedded frame

* badges: migrate Stripe adapter to PaymentIntents

* badges: correct Stripe restricted key scopes in ini example

* badges: card via Payment Element and PaymentIntents

* badges: fix stale Checkout Session wording in Stripe adapter

* badges: fix stale CheckoutActions reference in card comment

* badges: order shell stylesheet before bootstrap script

* badges: remove development card stand-in

* badges: theme the Stripe card form with the site palette

* badges: exclude web from the Haskell build stage

* badges: unify invoice cancel and mark canceled

* badges: default log level to info

* badges: unify closed-invoice buy-again button

* badges: mute agent connection logs at info level

* badges: show purchase time in local timezone in Your codes

* badges: log service events on own channel, quiet agent

* badges: fold service migrations into one baseline

* badges: run compose on postgres over host network

* badges: use high-res hero art

* badges: add web CI to catch stale builds

* badges: rebuild web shell from committed source

* badges: normalize invoice-code link and columns

* badges: drop unused columns, rename index

* badges: note deferred receipt_hash in migrations

* badges: apply code-review fixes

* badges: reduce comments across service and web

---------

Co-authored-by: Evgeny Poberezkin <evgeny@poberezkin.com>
Co-authored-by: Evgeny @ SimpleX Chat <259188159+evgeny-simplex@users.noreply.github.com>

* badges: improve web page (#7546)

* badges: improve web page

* improve layout

* improve layout

* fix

* small changes

---------

Co-authored-by: Evgeny @ SimpleX Chat <259188159+evgeny-simplex@users.noreply.github.com>

* badges: read one issuer key from the ini

* badges: move and group the service tests

* badges: service fixes (#7567)

* badges: match the redeem error wording in tests

* badges: drop unused imports in the bot tests

* badges: cancel Stripe orders when they expire

* badges: correct the Stripe config and docs

* badges: refuse to revoke a redeemed code

* badges: make the fake Stripe cancel like Stripe

* badges: limit replayed webhook deliveries

---------

Co-authored-by: sh <37271604+shumvgolove@users.noreply.github.com>
Co-authored-by: Evgeny @ SimpleX Chat <259188159+evgeny-simplex@users.noreply.github.com>
Co-authored-by: shum <github.shum@liber.li>
Co-authored-by: spaced4ndy <8711996+spaced4ndy@users.noreply.github.com>
2026-09-25 09:01:51 +00:00

141 lines
5.9 KiB
TypeScript

import { timedTest } from "./boot.js";
import assert from "node:assert/strict";
import { ALPHABET, PAYLOAD, canonical, checkChar, display, normalise, generate, hash } from "../src/codes.js";
const codeTest = timedTest(5000);
// The golden vector's canonical form and hash come from parseBadgeCode; a divergence would sell codes the service cannot redeem.
const VECTOR_BODY = "4RT6E8YBMW74Q8DK9DKR";
const VECTOR = "SB-4RT6E-8YBMW-74Q8D-K9DKR";
const VECTOR_CANONICAL = "SB4RT6E8YBMW74Q8DK9DKR";
const VECTOR_HASH = "Lyr52PVy843AXApBOwdq8hJKCfkpE4zuR_Xm_50SDQg";
codeTest("codes: the vector agrees with parseBadgeCode's canonical form and hash", async () => {
assert.equal(checkChar(VECTOR_BODY.slice(0, 19)), VECTOR_BODY[19]);
assert.equal(display(VECTOR_BODY), VECTOR);
assert.equal(canonical(VECTOR_BODY), VECTOR_CANONICAL);
assert.equal(await hash(VECTOR_BODY), VECTOR_HASH);
});
codeTest("codes: alphabet is Crockford base32", () => {
assert.equal(ALPHABET, "0123456789ABCDEFGHJKMNPQRSTVWXYZ");
assert.equal(ALPHABET.length, 32);
for (const bad of "ILOU") assert.ok(!ALPHABET.includes(bad), `${bad} must not be in the alphabet`);
});
function randomBody(): string {
let s = "";
for (let i = 0; i < 19; i++) s += ALPHABET[Math.floor(Math.random() * ALPHABET.length)]!;
return s;
}
codeTest("codes: every single-character substitution is detected", () => {
let undetected = 0;
for (let n = 0; n < 1000; n++) {
const body = randomBody();
const code = body + checkChar(body);
for (let i = 0; i < 20; i++) {
for (const c of ALPHABET) {
if (c === code[i]) continue;
const g = code.slice(0, i) + c + code.slice(i + 1);
if (checkChar(g.slice(0, 19)) === g[19]) undetected++;
}
}
}
assert.equal(undetected, 0);
});
// Luhn mod N detects adjacent transpositions but not a swap of 0 and Z, which this test allows for.
codeTest("codes: every adjacent transposition is detected but Luhn's 0/Z blind spot", () => {
let undetected = 0;
let blindSpot = 0;
for (let n = 0; n < 2000; n++) {
const body = randomBody();
const code = body + checkChar(body);
for (let i = 0; i < 18; i++) {
const j = i + 1;
if (code[i] === code[j]) continue;
const a = code.split("");
[a[i], a[j]] = [a[j]!, a[i]!];
const g = a.join("");
if (checkChar(g.slice(0, 19)) !== g[19]) continue;
if ([code[i], code[j]].sort().join("") === "0Z") blindSpot++;
else undetected++;
}
}
assert.equal(undetected, 0);
assert.ok(blindSpot > 0, "the 0/Z pair should have turned up in two thousand codes");
});
codeTest("codes: normalise folds I, L and O, and requires the prefix", () => {
assert.equal(normalise("sb-4rt6e-8ybmw-74q8d-k9dkr"), VECTOR_BODY);
assert.equal(normalise(" SB 4RT6E 8YBMW 74Q8D K9DKR "), VECTOR_BODY);
const folded = normalise(display("1".repeat(19) + checkChar("1".repeat(19))).replace(/1/g, "I"));
assert.equal(folded, "1".repeat(19) + checkChar("1".repeat(19)));
assert.equal(normalise("SB-UUUUU-UUUUU-UUUUU-UUUUU"), null);
assert.equal(normalise("SB-TOOSHORT"), null);
assert.equal(normalise("4RT6E8YBMW74Q8DK9DKR"), null);
assert.equal(normalise(display(VECTOR_BODY.slice(0, 19) + (VECTOR_BODY[19] === "0" ? "1" : "0"))), null);
});
codeTest("codes: generate produces a valid code", () => {
for (let n = 0; n < 200; n++) {
const c = generate();
assert.equal(c.length, 20);
for (const ch of c) assert.ok(ALPHABET.includes(ch));
assert.equal(checkChar(c.slice(0, 19)), c[19]);
assert.equal(normalise(display(c)), c);
}
});
codeTest("codes: hash is base64url sha-256 over the canonical form, prefix included", async () => {
const h = await hash(VECTOR_BODY);
assert.match(h, /^[A-Za-z0-9_-]{43}$/);
assert.equal(h, await hash(normalise(VECTOR)!));
const bytes = new TextEncoder().encode(VECTOR_BODY);
const bare = await crypto.subtle.digest("SHA-256", bytes);
const bareB64 = btoa(String.fromCharCode(...new Uint8Array(bare)))
.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
assert.notEqual(h, bareB64);
});
codeTest("codes: every code drawn is a different one, and the draw covers the alphabet", () => {
const drawn = new Set<string>();
const symbols = new Set<string>();
const perPosition = Array.from({ length: PAYLOAD }, () => new Set<string>());
for (let i = 0; i < 5000; i++) {
const code = generate();
drawn.add(code);
for (const c of code) symbols.add(c);
for (let at = 0; at < PAYLOAD; at++) perPosition[at]!.add(code[at]!);
}
assert.equal(drawn.size, 5000, "two buyers must never be handed the same code");
assert.equal(symbols.size, ALPHABET.length, `the draw reached ${symbols.size} of ${ALPHABET.length} symbols`);
for (const [at, seen] of perPosition.entries()) {
assert.equal(seen.size, ALPHABET.length,
`payload position ${at} drew ${seen.size} of ${ALPHABET.length} symbols, so the alphabet is narrowed`);
}
});
codeTest("codes: stripping is Unicode, the way parseBadgeCode's isAlphaNum is", () => {
// An ASCII-only strip would drop an Arabic-Indic digit and read the rest as a valid code the service refuses.
assert.equal(normalise("SB\u0663-4RT6E-8YBMW-74Q8D-K9DKR"), null);
assert.equal(normalise("SB-4RT6E-8YBMW-74Q8D-K9DKR"), VECTOR_BODY, "and the separators still go");
});
codeTest("codes: the payload comes from the CSPRNG, one byte per character", () => {
const real = globalThis.crypto.getRandomValues.bind(globalThis.crypto);
const asked: number[] = [];
globalThis.crypto.getRandomValues = ((buf: ArrayBufferView) => {
asked.push(buf.byteLength);
return real(buf as Uint8Array<ArrayBuffer>);
}) as typeof globalThis.crypto.getRandomValues;
try {
const code = generate();
assert.equal(code.length, PAYLOAD + 1, "19 drawn characters and the check character");
assert.deepEqual(asked, [PAYLOAD], "one draw from the CSPRNG, of one byte per payload character");
} finally {
globalThis.crypto.getRandomValues = real;
}
});