valkyrie-jwt
v0.1.1
Published
TypeScript/Node backend JWT runtime for ValkyrieJwt.
Maintainers
Readme
valkyrie-jwt
TypeScript/Node backend runtime for ValkyrieJwt.
Use this package when your backend is written in Node.js or TypeScript and needs to generate, validate, refresh, revoke, encrypt and rotate JWT keys with the same Valkyrie model as the C# NuGet package.
This package is for trusted backend code. Do not generate signed or encrypted JWTs in a browser, because that would expose your signing/encryption key material.
Install
npm install valkyrie-jwtIf you want to run the TypeScript examples in this README:
npm install -D typescript tsx @types/nodeCreate a JWT
Create generate-token.ts:
import {
ValkyrieAlgorithms,
ValkyrieJwtBody,
ValkyrieJwtService
} from "valkyrie-jwt";
const jwt = new ValkyrieJwtService("minha-api");
const body = new ValkyrieJwtBody({
audiences: ["minha-api"],
roles: ["admin"],
permissions: ["users:read"],
signature: ValkyrieAlgorithms.Hs256,
encryption: "",
email: "[email protected]"
});
const tokens = await jwt.generate("default", "user-1", body);
console.log(tokens.accessToken);
console.log(tokens.refreshToken);Run:
npx tsx generate-token.tsValidate a JWT
const result = await jwt.validate(tokens.accessToken, {
expectedTenantId: "default",
expectedAudience: "minha-api"
});
if (!result.succeeded) {
throw new Error(result.failureReason ?? "Token invalid");
}
console.log(result.subject);
console.log(result.roles);
console.log(result.body?.email);Encrypted JWT
import {
ValkyrieEncryptionAlgorithms,
ValkyrieJwtBody,
ValkyrieJwtService
} from "valkyrie-jwt";
const jwt = new ValkyrieJwtService("minha-api");
const tokens = await jwt.generate("default", "user-1", new ValkyrieJwtBody({
audiences: ["billing-api"],
signature: "",
encryption: ValkyrieEncryptionAlgorithms.A256Gcm,
document: "sensitive-value"
}));
const validation = await jwt.validateBody(tokens.accessToken, {
expectedTenantId: "default",
expectedAudience: "billing-api"
});
console.log(validation.body?.document);Refresh Token
const rotated = await jwt.refresh(tokens.refreshToken!);
if (rotated.succeeded) {
console.log(rotated.tokens!.accessToken);
}Refresh tokens are opaque random values. The store keeps only their SHA-256 hash and marks a refresh token as consumed when it is exchanged. Reusing a consumed refresh token revokes the whole refresh-token family.
Fingerprint Protection
import { createRandomFingerprint } from "valkyrie-jwt";
const fingerprint = createRandomFingerprint();
const tokens = await jwt.generate("default", "user-1", new ValkyrieJwtBody({
audiences: ["minha-api"],
fingerprint
}));
const validation = await jwt.validate(tokens.accessToken, {
fingerprint
});Store the raw fingerprint in a secure, HTTP-only cookie or another server-trusted device secret. The JWT only stores the SHA-256 base64url hash.
Shared Stores
The default stores are in-memory:
import { ValkyrieJwtService, createMemoryStores } from "valkyrie-jwt";
const stores = createMemoryStores();
const issuer = new ValkyrieJwtService("minha-api", { stores });
const validator = new ValkyrieJwtService("minha-api", { stores });Use Redis when your API already has a Redis client.
createRedisStores(redis) receives a connected Redis client, not a connection string. It can be a redis/node-redis client created with createClient(...) and await redis.connect(), or a compatible Redis client that exposes commands such as get, set, exists, expire, sAdd/sadd, sMembers/smembers and xAdd/xadd.
import { createClient } from "redis";
import { ValkyrieJwtService, createRedisStores } from "valkyrie-jwt";
const redis = createClient({ url: "redis://localhost:6379" });
await redis.connect();
const jwt = new ValkyrieJwtService("minha-api", {
stores: createRedisStores(redis, {
keyPrefix: "minha-api:auth"
})
});Use MongoDB when your API already has a Mongo database.
createMongoStores(db) receives a MongoDB Db object, not the MongoClient and not a connection string. With the official MongoDB driver, that object is returned by mongo.db("valkyrie_jwt").
import { MongoClient } from "mongodb";
import { ValkyrieJwtService, createMongoStores } from "valkyrie-jwt";
const mongo = new MongoClient("mongodb://localhost:27017");
await mongo.connect();
const jwt = new ValkyrieJwtService("minha-api", {
stores: createMongoStores(mongo.db("valkyrie_jwt"))
});You can also implement these store interfaces with your own database:
TenantSigningKeyStoreRefreshTokenStoreTokenBlacklistValkyrieAuditSink
Helpers
The package also exports helper functions for tests and tooling:
import { assertTokenShape, createFingerprint, decodeToken } from "valkyrie-jwt";
const fingerprintHash = createFingerprint("device-cookie");
const decoded = decodeToken(tokens.accessToken);
assertTokenShape(tokens.accessToken);assertTokenShape does not validate signatures and only works with compact signed JWTs. Use jwt.validate(...) for real validation.
Security Disclaimer
ValkyrieJwt is provided as-is under the MIT license. Security depends on how the application configures, stores, deploys and operates its keys, tokens, Redis/Mongo/database stores, cookies, clocks, secrets, network boundaries and authorization rules.
Using this package is the responsibility and risk of the application owner. The package owner/author is not responsible for misuse, insecure configuration, operational failures, application vulnerabilities, data loss, security incidents or breaches created by the way this package is used.
Review the code, test your threat model, keep dependencies updated, protect signing/encryption keys, use durable stores in production and run your own security validation before relying on ValkyrieJwt in a real system.
