245 lines
7.7 KiB
Markdown
245 lines
7.7 KiB
Markdown
# @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/](https://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/](https://code.foss.global/) account to submit Pull Requests directly.
|
|
|
|
## Install
|
|
|
|
```bash
|
|
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`.
|
|
- 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
|
|
|
|
```ts
|
|
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()`.
|
|
|
|
```ts
|
|
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',
|
|
});
|
|
```
|
|
|
|
## Verifying Tokens
|
|
|
|
Verification only needs the public key. This makes it easy to keep signing isolated while distributing verification safely.
|
|
|
|
```ts
|
|
import { SmartJwt } from '@push.rocks/smartjwt';
|
|
|
|
interface ISessionClaims {
|
|
sessionId: string;
|
|
accountId: string;
|
|
}
|
|
|
|
const signer = new SmartJwt<ISessionClaims>();
|
|
await signer.createNewKeyPair();
|
|
|
|
const token = await signer.createJWT({
|
|
sessionId: 'session_abc',
|
|
accountId: 'account_xyz',
|
|
});
|
|
|
|
const verifier = new SmartJwt<ISessionClaims>();
|
|
verifier.setPublicPemKeyForVerification(signer.publicKey.toPemString());
|
|
|
|
const verifiedClaims = await verifier.verifyJWTAndGetData(token);
|
|
console.log(verifiedClaims.accountId); // account_xyz
|
|
```
|
|
|
|
If verification fails, `verifyJWTAndGetData()` rejects with the error from `jsonwebtoken`.
|
|
|
|
## Key Management
|
|
|
|
### Generate A New Key Pair
|
|
|
|
```ts
|
|
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.
|
|
|
|
```ts
|
|
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:
|
|
|
|
```ts
|
|
{
|
|
privatePem: string;
|
|
publicPem: string;
|
|
}
|
|
```
|
|
|
|
### Set Keys Directly
|
|
|
|
If you already have smartcrypto key instances, set them directly:
|
|
|
|
```ts
|
|
await smartJwt.setPrivateKey(privateKey);
|
|
await smartJwt.setPublicKey(publicKey);
|
|
```
|
|
|
|
For verification-only instances, pass a PEM-encoded public key string:
|
|
|
|
```ts
|
|
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.
|
|
|
|
```ts
|
|
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.
|
|
|
|
```ts
|
|
const smartJwt = new SmartJwt();
|
|
await smartJwt.createNewKeyPair();
|
|
|
|
const signedObject = await smartJwt.createNestedJwt({ projectId: 'project_123' });
|
|
const result = await smartJwt.nestedJwtGuard.exec(signedObject);
|
|
```
|
|
|
|
## API Overview
|
|
|
|
```ts
|
|
class SmartJwt<T extends object = any> {
|
|
public publicKey: PublicKey;
|
|
public privateKey: PrivateKey;
|
|
|
|
createJWT(payload: T): Promise<string>;
|
|
verifyJWTAndGetData(jwt: string): 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()` requires `privateKey` to be set first.
|
|
- `verifyJWTAndGetData()` requires `publicKey` to be set first.
|
|
- `createNewKeyPair()` and `init()` both create and set a fresh key pair.
|
|
- 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](./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.
|