@push.rocks/smartjwt
Strongly typed JWT creation and verification for TypeScript, powered by RSA key pairs and RS256 signatures.
@push.rocks/smartjwt wraps the practical JWT workflow into one small class: generate a key pair, sign typed payloads, verify tokens with the matching public key, and optionally attach a verifiable JWT directly to an object.
Issue Reporting and Security
For reporting bugs, issues, or security vulnerabilities, please visit community.foss.global/. This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a code.foss.global/ account to submit Pull Requests directly.
Install
pnpm add @push.rocks/smartjwt
What It Does
SmartJwt is built around asymmetric JWT signing:
- A private key signs JWTs.
- A public key verifies JWTs.
- Tokens are signed with
RS256. - An optional protected-header
kidcan identify the verification key. - Payloads are typed through
SmartJwt<T>. - Key pairs can be generated, exported, imported, or split across signer and verifier instances.
- Nested JWT objects can be created and verified when you want the original object to carry its own integrity proof.
Quick Start
import { SmartJwt } from '@push.rocks/smartjwt';
interface IUserClaims {
userId: string;
role: 'admin' | 'member';
}
const signer = new SmartJwt<IUserClaims>();
await signer.createNewKeyPair();
const jwt = await signer.createJWT({
userId: 'user_123',
role: 'admin',
});
const claims = await signer.verifyJWTAndGetData(jwt);
console.log(claims.userId); // user_123
Signing Tokens
Create or provide a private key before calling createJWT().
import { SmartJwt } from '@push.rocks/smartjwt';
interface ISessionClaims {
sessionId: string;
accountId: string;
}
const smartJwt = new SmartJwt<ISessionClaims>();
await smartJwt.createNewKeyPair();
const token = await smartJwt.createJWT({
sessionId: 'session_abc',
accountId: 'account_xyz',
}, 'signing-key-2026-07');
The optional second argument is written to the cryptographically protected JWT
header as kid. RS256 remains fixed and cannot be overridden by callers.
Sign With An External KMS Or HSM
createJWTWithExternalSigner() keeps private key material outside the
application process. The callback receives the exact JWS signing input and must
return raw RSASSA-PKCS1-v1_5/SHA-256 signature bytes. SmartJwt verifies those
bytes against the configured public key before it returns the token.
const jwt = await smartJwt.createJWTWithExternalSigner(
{
sessionId: 'session_abc',
exp: Math.floor(Date.now() / 1000) + 300,
},
{
keyId: 'kms/key-2026-07',
publicKeyPem,
signer: async ({ algorithm, keyId, signingInput }) => {
// Configure the provider for RS256 / RSASSA-PKCS1-v1_5 with SHA-256.
// If its API expects a digest, hash signingInput inside this adapter.
return kms.sign({ algorithm, keyId, message: signingInput });
},
},
);
External signing accepts exactly one PEM-encoded RSA public-key block of at
least 2048 bits, a bounded printable keyId, and a valid signature matching
that key. Private-key PEM, concatenated blocks, and trailing non-whitespace are
rejected. The protected algorithm is fixed to RS256; a rejected provider
call, malformed response, wrong key, or algorithm mismatch fails closed.
SmartJwt adds a NumericDate iat when the payload does not already contain
one, rejects non-numeric temporal claims, and rejects a top-level toJSON
function that could rewrite the signed claims.
Verifying Tokens
Verification only needs the public key. This makes it easy to keep signing isolated while distributing verification safely.
import { SmartJwt } from '@push.rocks/smartjwt';
interface ISessionClaims {
sessionId: string;
accountId: string;
iss: string;
aud: string;
sub: string;
jti: string;
nonce: string;
iat: number;
nbf: number;
exp: number;
}
const signer = new SmartJwt<ISessionClaims>();
await signer.createNewKeyPair();
const now = Math.floor(Date.now() / 1000);
const token = await signer.createJWT({
sessionId: 'session_abc',
accountId: 'account_xyz',
iss: 'https://identity.example.com',
aud: 'session-api',
sub: 'account_xyz',
jti: 'session_abc',
nonce: 'nonce_123',
iat: now,
nbf: now - 5,
exp: now + 300,
});
const verifier = new SmartJwt<ISessionClaims>();
verifier.setPublicPemKeyForVerification(signer.publicKey.toPemString());
const verifiedClaims = await verifier.verifyJWTAndGetData(token, {
issuer: 'https://identity.example.com',
audience: 'session-api',
subject: 'account_xyz',
jwtid: 'session_abc',
nonce: 'nonce_123',
maxAge: '5m',
clockTolerance: 5,
requiredClaims: ['iat', 'nbf', 'exp'],
});
console.log(verifiedClaims.accountId); // account_xyz
The optional verification policy supports issuer, audience, subject, JWT ID,
nonce, maximum token age, clock tolerance, and an explicit clock timestamp.
requiredClaims can require iat, nbf, and exp; required temporal claims
must be finite numeric dates. The verification algorithm remains fixed to
RS256, and unsupported runtime options are not forwarded to jsonwebtoken.
exp and nbf are validated whenever present, including when the policy is
omitted. Requiring them makes their presence mandatory. maxAge requires a
numeric iat that is not later than the effective verification clock plus its
tolerance. An audience policy also requires the signed aud claim to contain
at least one non-empty string. If verification fails,
verifyJWTAndGetData() rejects with a jsonwebtoken verification error. The
original one-argument form remains supported.
Verification policies must be non-array objects and fail closed: issuer,
audience, subject, JWT ID, and nonce selectors cannot be empty; explicit clocks
must be finite; clock tolerance must be non-negative; and maximum token age must
be a positive finite duration. Any
iat, nbf, or exp claim present in a verified token must be a finite
NumericDate, even when it is not listed in requiredClaims. Audience regular
expressions that match an empty value are rejected.
For key rollover, decodeProtectedHeaderWithoutVerification() exposes kid
for key selection. The decoded header is untrusted until the JWT has been
verified with the selected key.
interface ISmartJwtProtectedHeader {
alg: string;
typ?: string;
kid?: string;
}
Every decoded field, including alg, is untrusted metadata. Always complete
signature verification with verifyJWTAndGetData() before using JWT claims.
Key Management
Generate A New Key Pair
const smartJwt = new SmartJwt();
await smartJwt.createNewKeyPair();
createNewKeyPair() sets both smartJwt.privateKey and smartJwt.publicKey.
Export And Import A Key Pair
Use getKeyPairAsJson() when you need to persist or transfer the active key pair.
const signer = new SmartJwt();
await signer.createNewKeyPair();
const keyPairJson = signer.getKeyPairAsJson();
const restoredSigner = new SmartJwt();
restoredSigner.setKeyPairAsJson(keyPairJson);
The JSON shape follows @tsclass/tsclass's network.IJwtKeypair contract:
{
privatePem: string;
publicPem: string;
}
Set Keys Directly
If you already have smartcrypto key instances, set them directly:
await smartJwt.setPrivateKey(privateKey);
await smartJwt.setPublicKey(publicKey);
For verification-only instances, pass a PEM-encoded public key string:
smartJwt.setPublicPemKeyForVerification(publicPem);
Nested JWT Objects
Nested JWTs are useful when an object should carry its own verifiable proof. createNestedJwt() returns the original payload plus a jwt property that signs the payload.
import { SmartJwt } from '@push.rocks/smartjwt';
interface IInvite {
email: string;
teamId: string;
}
const smartJwt = new SmartJwt<IInvite>();
await smartJwt.createNewKeyPair();
const invite = await smartJwt.createNestedJwt({
email: 'developer@example.com',
teamId: 'team_123',
});
console.log(invite.jwt); // signed JWT for the invite payload
const isNestedJwt = smartJwt.isNestedJwt<IInvite>(invite);
const isValid = await smartJwt.verifyNestedJwt(invite);
verifyNestedJwt() verifies the embedded JWT and then checks that the decoded JWT data deeply equals the object that carried it. If the payload data or jwt string is modified, verification returns false or throws when token verification itself fails.
Guard Integration
SmartJwt exposes nestedJwtGuard, a @push.rocks/smartguard guard that validates nested JWT objects.
const smartJwt = new SmartJwt();
await smartJwt.createNewKeyPair();
const signedObject = await smartJwt.createNestedJwt({ projectId: 'project_123' });
const result = await smartJwt.nestedJwtGuard.exec(signedObject);
API Overview
type TSmartJwtRequiredClaim = 'exp' | 'iat' | 'nbf';
interface ISmartJwtVerificationPolicy {
audience?: string | RegExp | [string | RegExp, ...(string | RegExp)[]];
clockTimestamp?: number;
clockTolerance?: number;
issuer?: string | [string, ...string[]];
jwtid?: string;
maxAge?: string | number;
nonce?: string;
subject?: string;
requiredClaims?: readonly TSmartJwtRequiredClaim[];
}
class SmartJwt<T extends object = any> {
public publicKey: PublicKey;
public privateKey: PrivateKey;
createJWT(payload: T, kid?: string): Promise<string>;
decodeProtectedHeaderWithoutVerification(jwt: string): ISmartJwtProtectedHeader;
verifyJWTAndGetData(
jwt: string,
verificationPolicy?: ISmartJwtVerificationPolicy,
): Promise<T>;
setPrivateKey(privateKey: PrivateKey): Promise<void>;
setPublicKey(publicKey: PublicKey): Promise<void>;
setPublicPemKeyForVerification(publicPemKey: string): void;
createNewKeyPair(): Promise<void>;
init(): Promise<void>;
getKeyPairAsJson(): IJwtKeypair;
setKeyPairAsJson(jsonKeyPair: IJwtKeypair): void;
isNestedJwt<T extends object>(object: unknown): object is IObjectWithJwt<T>;
createNestedJwt<T extends object>(payload: T): Promise<IObjectWithJwt<T>>;
verifyNestedJwt<T extends object>(object: IObjectWithJwt<T>): Promise<boolean>;
nestedJwtGuard: Guard<IObjectWithJwt<any>>;
}
Practical Notes
- Keep private keys private. Only distribute public keys to services that verify tokens.
createJWT()requiresprivateKeyto be set first.verifyJWTAndGetData()requirespublicKeyto be set first.- Verification policies cannot override the fixed
RS256algorithm or disable expiration/not-before checks. clockTimestampand JWT numeric dates use seconds since the Unix epoch.createNewKeyPair()andinit()both create and set a fresh key pair.- Build, declaration, and runtime behavior are validated on Node.js 22.
- This package is ESM-first and ships TypeScript declarations.
License and Legal Information
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the license file.
Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
Company Information
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
For any legal inquiries or further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.