Skip to main content

Module token

Module token 

Source
Expand description

Random tokens for emailed links and API keys, stored as digests.

Used by ocre g auth for password-reset and magic-link emails and for API keys. A token is 32 random bytes (256 bits) from the platform’s secure random generator (WebCrypto on Workers), encoded as URL-safe base64 without padding: 43 characters, safe in URLs, headers and emails.

Store only digests: a leaked database then holds no usable token. A fast hash (SHA-256) is enough here because tokens are random and long; passwords, which people choose, need crate::password instead. Compare secrets that cannot be looked up by digest with constant_time_eq.

Cost: one SHA-256 per digest; this module uses no binding (the app stores the digest in D1).

// Issue: email or show `token` once, store `stored` (e.g. in a `token_digest` column).
let token = ocre::token::generate();
let stored = ocre::token::digest(&token);
// Later, from a request: look the row up by digest (`WHERE token_digest = ?1`).
assert_eq!(ocre::token::digest(&token), stored);

Constants§

TOKEN_BYTES
Random bytes in a token generated by generate: 32 (256 bits).

Functions§

constant_time_eq
Whether a equals b, compared in constant time for equal lengths.
digest
SHA-256 of token as 64 lowercase hex characters: the value to store and look up.
generate
A new random token: TOKEN_BYTES secure random bytes as URL-safe base64 without padding (43 characters).
public_id
A random id for URLs: 22 URL-safe characters (128 bits), the value of a public_id:token column. Unguessable, so a page at /videos/<public_id> cannot be found by counting, and it says nothing about how many rows exist.