Files
smartjwt/readme.md
T

245 lines
7.7 KiB
Markdown
Raw Permalink Normal View History

2023-08-21 08:53:14 +02:00
# @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.
2019-02-23 00:50:21 +01:00
2024-04-14 17:46:22 +02:00
## Install
```bash
pnpm add @push.rocks/smartjwt
2024-04-14 17:46:22 +02:00
```
## What It Does
2019-02-23 00:50:21 +01:00
`SmartJwt` is built around asymmetric JWT signing:
2019-02-23 00:50:21 +01:00
- 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.
2024-04-14 17:46:22 +02:00
## Quick Start
2024-04-14 17:46:22 +02:00
```ts
2024-04-14 17:46:22 +02:00
import { SmartJwt } from '@push.rocks/smartjwt';
interface IUserClaims {
userId: string;
role: 'admin' | 'member';
2024-04-14 17:46:22 +02:00
}
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
2024-04-14 17:46:22 +02:00
```
## Signing Tokens
2024-04-14 17:46:22 +02:00
Create or provide a private key before calling `createJWT()`.
2024-04-14 17:46:22 +02:00
```ts
import { SmartJwt } from '@push.rocks/smartjwt';
2024-04-14 17:46:22 +02:00
interface ISessionClaims {
sessionId: string;
accountId: string;
2024-04-14 17:46:22 +02:00
}
const smartJwt = new SmartJwt<ISessionClaims>();
await smartJwt.createNewKeyPair();
const token = await smartJwt.createJWT({
sessionId: 'session_abc',
accountId: 'account_xyz',
});
2024-04-14 17:46:22 +02:00
```
## 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;
2024-04-14 17:46:22 +02:00
}
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();
2024-04-14 17:46:22 +02:00
```
`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();
2024-04-14 17:46:22 +02:00
const restoredSigner = new SmartJwt();
restoredSigner.setKeyPairAsJson(keyPairJson);
```
The JSON shape follows `@tsclass/tsclass`'s `network.IJwtKeypair` contract:
2024-04-14 17:46:22 +02:00
```ts
{
privatePem: string;
publicPem: string;
2024-04-14 17:46:22 +02:00
}
```
### 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);
```
2024-04-14 17:46:22 +02:00
## Nested JWT Objects
2024-04-14 17:46:22 +02:00
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;
2024-04-14 17:46:22 +02:00
}
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);
2024-04-14 17:46:22 +02:00
```
`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>>;
2024-04-14 17:46:22 +02:00
}
```
## Practical Notes
2024-04-14 17:46:22 +02:00
- 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.
2024-04-14 17:46:22 +02:00
## 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.
2024-04-14 17:46:22 +02:00
**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
2021-09-22 01:29:47 +02:00
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.
2021-09-22 01:29:47 +02:00
2024-04-14 17:46:22 +02:00
### Company Information
2021-02-20 18:02:53 +00:00
2024-04-14 17:46:22 +02:00
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
2021-02-20 18:02:53 +00:00
For any legal inquiries or further information, please contact us via email at hello@task.vc.
2019-02-23 00:50:21 +01:00
2024-04-14 17:46:22 +02:00
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.