$ cat docs/password.md
Password hashingHash de senha
Cloudflare Workers only ship PBKDF2 in WebCrypto. @tupik/password brings Argon2id (RFC 9106), the algorithm OWASP recommends, as a 34.4 kB WebAssembly module (12.9 kB gzip) with no JS glue and no runtime dependencies.O Cloudflare Workers só tem PBKDF2 no WebCrypto. O @tupik/password traz o Argon2id (RFC 9106), o algoritmo que a OWASP recomenda, num módulo WebAssembly de 34,4 kB (12,9 kB com gzip), sem código de cola em JS e sem dependências.
Hash and verifyGerar e conferir
npm install @tupik/password import { hashPassword, needsRehash, verifyPassword } from '@tupik/password';
const phc = await hashPassword(password); // $argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>
const ok = await verifyPassword(user.passwordHash, password); // constant time
if (ok && needsRehash(user.passwordHash)) await saveHash(user.id, await hashPassword(password));import { hashPassword, needsRehash, verifyPassword } from '@tupik/password';
const phc = await hashPassword(password); // $argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>
const ok = await verifyPassword(user.passwordHash, password); // tempo constante
if (ok && needsRehash(user.passwordHash)) await saveHash(user.id, await hashPassword(password)); verifyPassword answers false for a wrong password and throws TypeError for a malformed PHC string: that is a storage bug, not a failed login. needsRehash is true when the stored costs or tag length differ from the target.
O verifyPassword responde false para senha errada e lança TypeError para um PHC malformado: é defeito no armazenamento, não login errado. O needsRehash é true quando os custos ou o tamanho do hash guardados diferem do alvo.
Loading the moduleCarregando o módulo
- Node.js, Bun, Deno: nothing to do. The first call reads the
.wasmthat ships in the package. - Cloudflare Workers: import from
@tupik/password/workers. Workers cannot compile WebAssembly from bytes at runtime, so this entry imports the.wasm(Wrangler turns it into aWebAssembly.Module) and callsinitPasswordfor you. - Anything else:
await initPassword(bytes | WebAssembly.Module | Response)before the first hash.
- Node.js, Bun, Deno: nada a fazer. A primeira chamada lê o
.wasmque vem no pacote. - Cloudflare Workers: importe de
@tupik/password/workers. O Workers não compila WebAssembly a partir de bytes em tempo de execução; essa entrada importa o.wasm(o Wrangler o transforma emWebAssembly.Module) e chama oinitPasswordpor você. - Outros:
await initPassword(bytes | WebAssembly.Module | Response)antes do primeiro hash.
// Cloudflare Workers: this entry imports the .wasm and initializes it
import { hashPassword, verifyPassword } from '@tupik/password/workers';
// manual form
import wasm from '@tupik/password/argon2.wasm';
import { initPassword } from '@tupik/password';
await initPassword(wasm);// Cloudflare Workers: esta entrada importa o .wasm e o inicializa
import { hashPassword, verifyPassword } from '@tupik/password/workers';
// forma manual
import wasm from '@tupik/password/argon2.wasm';
import { initPassword } from '@tupik/password';
await initPassword(wasm); OptionsOpções
profile (owasp by default, or light), memoryCost (KiB), timeCost, parallelism, hashLength (32), saltLength (16), secret (a pepper kept outside the database), maxPasswordBytes (1024: a longer password throws on hash and returns false on verify, so a huge "password" cannot burn CPU) and normalize: 'NFC' (off by default for compatibility; use the same value on both sides).
profile (owasp por padrão, ou light), memoryCost (KiB), timeCost, parallelism, hashLength (32), saltLength (16), secret (pepper guardado fora do banco), maxPasswordBytes (1024: senha maior lança erro no hash e devolve false na verificação, então uma "senha" enorme não gasta CPU) e normalize: 'NFC' (desligado por padrão para manter compatibilidade; use o mesmo valor nos dois lados).
Cost and the Workers CPU limitCusto e o limite de CPU do Workers
| ProfilePerfil | m / t / pm / t / p | WASM (Node.js 24)WASM (Node.js 24) | Native @node-rs/argon2Nativo @node-rs/argon2 |
|---|---|---|---|
owasp | 19456 KiB / 2 / 1 | about 40 to 55 mscerca de 40 a 55 ms | about 25 mscerca de 25 ms |
light | 4096 KiB / 1 / 1 | about 4 to 6 mscerca de 4 a 6 ms | about 2 mscerca de 2 ms |
Measured on 2026-12-01, Node.js 24.21.0, x86-64, one hash at a time, on a loaded machine: read the numbers as ranges. Workers bill CPU time per request: 10 ms on the free plan, 30 s by default on paid plans. owasp does not fit the free plan. light does, but each guess against a stolen database is about 10 times cheaper, below the OWASP minimum. Use light only if the plan forces it, then move the target to owasp: needsRehash returns true for the old hashes and upgrades each user at the next login. Rate limit sign-in routes either way.
Medido em 2026-12-01, Node.js 24.21.0, x86-64, um hash por vez, com a máquina carregada: leia os números como faixas. O Workers cobra tempo de CPU por requisição: 10 ms no plano grátis, 30 s por padrão nos pagos. O owasp não cabe no plano grátis. O light cabe, mas cada tentativa contra um banco vazado fica cerca de 10 vezes mais barata, abaixo do mínimo da OWASP. Use light só se o plano obrigar e depois troque o alvo para owasp: o needsRehash devolve true para os hashes antigos e atualiza cada usuário no próximo login. Limite a taxa das rotas de login em qualquer caso.
CompatibilityCompatibilidade
Reads and writes Argon2id v1.3 PHC strings. Hashes from argon2, @node-rs/argon2, argon2-cffi and PHP verify as is. Tested against @node-rs/argon2 in both directions, plus the RFC 9106 and reference implementation vectors. argon2idRaw gives the raw RFC 9106 tag for test vectors or key derivation; parsePhc decodes a PHC string or returns undefined.
Lê e grava PHC de Argon2id v1.3. Hashes do argon2, @node-rs/argon2, argon2-cffi e PHP verificam sem conversão. Testado contra o @node-rs/argon2 nos dois sentidos, além dos vetores da RFC 9106 e da implementação de referência. O argon2idRaw devolve o hash cru da RFC 9106 para vetores de teste ou derivação de chave; o parsePhc decodifica um PHC ou devolve undefined.