fix(build): migrate project metadata and tooling config to smartconfig
This commit is contained in:
@@ -1,151 +1,244 @@
|
||||
# @push.rocks/smartjwt
|
||||
a package for handling jwt
|
||||
|
||||
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
|
||||
To install @push.rocks/smartjwt, use npm or yarn as follows:
|
||||
|
||||
```bash
|
||||
npm install @push.rocks/smartjwt --save
|
||||
# or with yarn
|
||||
yarn add @push.rocks/smartjwt
|
||||
pnpm add @push.rocks/smartjwt
|
||||
```
|
||||
|
||||
Make sure you have Node.js installed on your machine. This library uses modern JavaScript features and requires Node.js version 10.x.x or higher.
|
||||
## What It Does
|
||||
|
||||
## Usage
|
||||
`SmartJwt` is built around asymmetric JWT signing:
|
||||
|
||||
This section illustrates how to use the `@push.rocks/smartjwt` package to handle JSON Web Tokens (JWT) in your TypeScript projects with practical and comprehensive examples. Before diving into the scenarios, ensure you have the package installed and are comfortable with TypeScript and async/await syntax.
|
||||
- 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.
|
||||
|
||||
### Initializing and Creating a New Key Pair
|
||||
## Quick Start
|
||||
|
||||
To utilize `smartjwt` for creating and verifying JWTs, you first need to instantiate `SmartJwt` class and generate or set a key pair (a private and a public key). Let's start by initializing and creating a new key pair:
|
||||
|
||||
```typescript
|
||||
```ts
|
||||
import { SmartJwt } from '@push.rocks/smartjwt';
|
||||
|
||||
async function setup() {
|
||||
const smartJwt = new SmartJwt();
|
||||
await smartJwt.createNewKeyPair();
|
||||
console.log('Key pair created successfully');
|
||||
interface IUserClaims {
|
||||
userId: string;
|
||||
role: 'admin' | 'member';
|
||||
}
|
||||
setup();
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
### Creating a JWT
|
||||
## Signing Tokens
|
||||
|
||||
Once you have your key pair ready, you can create JWTs by supplying a payload. The payload is the data you want to encode in your JWT. Here's an example of how to create a JWT:
|
||||
Create or provide a private key before calling `createJWT()`.
|
||||
|
||||
```typescript
|
||||
interface MyPayload {
|
||||
user_id: number;
|
||||
username: string;
|
||||
```ts
|
||||
import { SmartJwt } from '@push.rocks/smartjwt';
|
||||
|
||||
interface ISessionClaims {
|
||||
sessionId: string;
|
||||
accountId: string;
|
||||
}
|
||||
|
||||
async function createJwt() {
|
||||
const smartJwt = new SmartJwt<MyPayload>();
|
||||
await smartJwt.createNewKeyPair();
|
||||
const myPayload = {
|
||||
user_id: 123,
|
||||
username: 'example_username'
|
||||
};
|
||||
const jwt = await smartJwt.createJWT(myPayload);
|
||||
console.log(jwt);
|
||||
}
|
||||
createJwt();
|
||||
const smartJwt = new SmartJwt<ISessionClaims>();
|
||||
await smartJwt.createNewKeyPair();
|
||||
|
||||
const token = await smartJwt.createJWT({
|
||||
sessionId: 'session_abc',
|
||||
accountId: 'account_xyz',
|
||||
});
|
||||
```
|
||||
|
||||
### Verifying a JWT and Extracting the Payload
|
||||
## Verifying Tokens
|
||||
|
||||
Verifying a JWT is crucial for authentication and authorization processes in applications. When you receive a JWT, you need to verify its integrity and authenticity before trusting the contained information. Here’s how to verify a JWT and extract its payload:
|
||||
Verification only needs the public key. This makes it easy to keep signing isolated while distributing verification safely.
|
||||
|
||||
```typescript
|
||||
async function verifyJwt(jwt: string) {
|
||||
const smartJwt = new SmartJwt<MyPayload>();
|
||||
// In a real application, you should set the public key from a trusted source.
|
||||
smartJwt.setPublicPemKeyForVerification('<Your_Public_Key>');
|
||||
|
||||
try {
|
||||
const payload = await smartJwt.verifyJWTAndGetData(jwt);
|
||||
console.log('JWT verified successfully:', payload);
|
||||
} catch (error) {
|
||||
console.error('Failed to verify JWT:', error);
|
||||
}
|
||||
```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;
|
||||
}
|
||||
```
|
||||
|
||||
### Handling Public and Private Keys
|
||||
### Set Keys Directly
|
||||
|
||||
In scenarios where you have existing keys or receive them from an external source, `smartjwt` allows setting the public and private keys directly instead of generating new ones. Here is an example:
|
||||
If you already have smartcrypto key instances, set them directly:
|
||||
|
||||
```typescript
|
||||
async function setExistingKeys() {
|
||||
const smartJwt = new SmartJwt<MyPayload>();
|
||||
const privateKeyString = '<Your_Private_Key_PEM_String>';
|
||||
const publicKeyString = '<Your_Public_Key_PEM_String>';
|
||||
|
||||
smartJwt.setPrivateKeyFromPemString(privateKeyString);
|
||||
smartJwt.setPublicKeyFromPemString(publicKeyString);
|
||||
```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>>;
|
||||
}
|
||||
```
|
||||
|
||||
### Exporting and Importing Key Pairs
|
||||
## Practical Notes
|
||||
|
||||
You may need to store your key pairs securely or share them across different parts of your application or with other services securely. `smartjwt` offers a convenient way to export and import key pairs as JSON:
|
||||
|
||||
```typescript
|
||||
async function exportAndImportKeyPair() {
|
||||
const smartJwt = new SmartJwt();
|
||||
await smartJwt.createNewKeyPair();
|
||||
const keyPairJson = smartJwt.getKeyPairAsJson();
|
||||
console.log('Exported Key Pair:', keyPairJson);
|
||||
|
||||
const newSmartJwt = new SmartJwt();
|
||||
newSmartJwt.setKeyPairAsJson(keyPairJson);
|
||||
console.log('Imported Key Pair Successfully');
|
||||
}
|
||||
exportAndImportKeyPair();
|
||||
```
|
||||
|
||||
### Complete Scenario: Signing and Verifying a JWT
|
||||
|
||||
Bringing it all together, here is a complete scenario where a JWT is created, signed, and later verified:
|
||||
|
||||
```typescript
|
||||
async function completeScenario() {
|
||||
// Creating a new JWT
|
||||
const smartJwt = new SmartJwt<MyPayload>();
|
||||
await smartJwt.createNewKeyPair();
|
||||
const jwt = await smartJwt.createJWT({ user_id: 123, username: 'exampleuser' });
|
||||
console.log('Created JWT:', jwt);
|
||||
|
||||
// Verifying the JWT in another instance or part of the application
|
||||
const verifier = new SmartJwt<MyPayload>();
|
||||
verifier.setPublicPemKeyForVerification(smartJwt.publicKey.toPemString());
|
||||
const verifiedPayload = await verifier.verifyJWTAndGetData(jwt);
|
||||
console.log('Verified Payload:', verifiedPayload);
|
||||
}
|
||||
completeScenario();
|
||||
```
|
||||
|
||||
By following these examples, you can effectively handle JWT creation, signing, verification, and key management in your TypeScript projects using the `@push.rocks/smartjwt` package. Always ensure to manage your keys securely and avoid exposing sensitive information.
|
||||
|
||||
For further information and advanced features, consult the project's documentation and source code.
|
||||
- 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 that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
|
||||
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 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, and any usage must be approved in writing by Task Venture Capital GmbH.
|
||||
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
|
||||
Registered at District Court Bremen HRB 35230 HB, Germany
|
||||
|
||||
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
|
||||
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.
|
||||
|
||||
Reference in New Issue
Block a user