Open in a new tab

Sign and verify a compact JWT with HMAC-SHA256, wrap bytes in a PEM block and read it back, compute a TOTP code for a fixed time, and mint a UUID v4.

Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

Session tokens between your own services, key material exchanged as text, a second factor for sign-in, and ids that never collide, without a crypto dependency in the page.

Copy-paste steps

  1. npm install @awacloud/fw
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html and main.js next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link.
  4. Keep expectedAlg on every verification and keep the HMAC key out of the page in a real deployment (this page keeps it for the demo only).

What it shows

  • jws.signJwt(claims, 'HS256', key) and jws.verifyJwt(token, key, { expectedAlg }): a changed character, a wrong key, an empty signature or alg: none all fail.
  • pem.encode(bytes, label) / pem.decode(text, label).
  • totp.generate(secretBytes, { algorithm, digits, t }) with the RFC 6238 test vectors at fixed times; t is epoch seconds.
  • uuid.v4(false, false, 'rfc4122') from the secure random source (the default format is compact, 32 hex characters).

Code

main.js

javascriptApache-2.078 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { jws } from '@awacloud/fw/crypto/utils/jws.js';
import { pem } from '@awacloud/fw/crypto/utils/pem.js';
import { totp } from '@awacloud/fw/crypto/utils/totp.js';
import { uuid } from '@awacloud/fw/crypto/utils/uuid.js';
import { random } from '@awacloud/fw/crypto/utils/random.js';

fw.runtime.registerAllDeep([jws, pem, totp, uuid, random]);
const JWS = fw.runtime.resolve('jws');
const PEM = fw.runtime.resolve('pem');
const TOTP = fw.runtime.resolve('totp');
const UUID = fw.runtime.resolve('uuid');
const RANDOM = fw.runtime.resolve('random');

/** The signing key lives for this page load; a server would keep it in a key store. */
const key = /** @type {Uint8Array} */ (RANDOM.bytes(32));

/**
 * @param {string} subject
 * @param {number} [now] epoch seconds
 * @returns {string} a compact JWT, HS256
 */
export function issueToken(subject, now = Math.floor(Date.now() / 1000)) {
    const token = JWS.signJwt({ sub: subject, iat: now, exp: now + 3600 }, 'HS256', key);
    if (!token) throw new Error('signing failed');
    return token;
}

/**
 * Only HS256 is accepted, so an attacker cannot switch the algorithm.
 * @param {string} token
 * @returns {object | null} the claims, or null when the token does not verify
 */
export function readToken(token) {
    const result = JWS.verifyJwt(token, key, { expectedAlg: 'HS256' });
    return result ? result.claims ?? null : null;
}

/** @param {Uint8Array} bytes @param {string} label */
export function pemRoundTrip(bytes, label) {
    const text = PEM.encode(bytes, label);
    const back = PEM.decode(text, label);
    if (!back) throw new Error('PEM decode failed');
    return { text, same: back.bytes.length === bytes.length && back.bytes.every((b, i) => b === bytes[i]) };
}

/** RFC 6238 appendix B uses the ASCII secret "12345678901234567890" with SHA-1 and 8 digits. */
export const RFC_SECRET = new TextEncoder().encode('12345678901234567890');
/** @param {number} t epoch seconds */
export const codeAt = (t) => TOTP.generate(RFC_SECRET, { algorithm: 'SHA-1', digits: 8, t });

/**
 * One changed signature character: the first, whose 6 bits are all signature
 * bits (the last one also carries padding bits, so changing it may not).
 * @param {string} token
 */
export const tamper = (token) => {
    const [h, p, s] = token.split('.');
    return `${h}.${p}.${s[0] === 'A' ? 'B' : 'A'}${s.slice(1)}`;
};

/** @param {string} id @param {string} value */
const show = (id, value) => { /** @type {HTMLElement} */ (document.getElementById(id)).textContent = value; };
const subject = /** @type {HTMLInputElement} */ (document.getElementById('subject'));

function update() {
    const token = issueToken(subject.value);
    show('jwt', token);
    show('claims', JSON.stringify(readToken(token)));
    show('tampered', readToken(tamper(token)) === null ? 'rejected' : 'ACCEPTED (bug)');
}

subject.addEventListener('input', update);
update();
show('pem', pemRoundTrip(/** @type {Uint8Array} */ (RANDOM.bytes(48)), 'EXAMPLE KEY').text);
show('totp', codeAt(59));
show('uuid', String(UUID.v4(false, false, 'rfc4122')));

index.html

htmlApache-2.030 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>fw · JWS tokens, PEM blocks, TOTP codes and UUIDs</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>JWS tokens, PEM blocks, TOTP codes and UUIDs</h1>
    <label for="subject">Token subject</label>
    <input id="subject" type="text" value="ada" autocomplete="off">
    <dl>
      <dt>JWT (HS256, random key)</dt><dd><code id="jwt"></code></dd>
      <dt>Verified claims</dt><dd><code id="claims"></code></dd>
      <dt>Same token with one character changed</dt><dd><output id="tampered"></output></dd>
      <dt>PEM round trip</dt><dd><pre id="pem"></pre></dd>
      <dt>TOTP for the RFC 6238 test secret at t = 59 s</dt><dd><code id="totp"></code></dd>
      <dt>UUID v4</dt><dd><code id="uuid"></code></dd>
    </dl>
  </main>
</body>
</html>