Compare commits

...

47 Commits

Author SHA1 Message Date
e69fe8f99f 2.2.1 2024-09-05 16:47:19 +02:00
41c4b29ea6 fix(core): Add --allowimplicitany flag to build script 2024-09-05 16:47:18 +02:00
616706caaf 2.2.0 2024-09-05 16:46:02 +02:00
8097ca059f feat(smartjwt): Add nested JWT functionality 2024-09-05 16:46:01 +02:00
59ae8ae466 2.1.0 2024-08-26 21:49:49 +02:00
b247630e0f feat(core): Enhanced JWT handling and key management 2024-08-26 21:49:48 +02:00
26655ff92e update description 2024-05-29 14:13:52 +02:00
788f9ae268 update tsconfig 2024-04-14 17:46:22 +02:00
54c1eea2b2 update npmextra.json: githost 2024-04-01 21:35:45 +02:00
dcc148bf54 update npmextra.json: githost 2024-04-01 19:58:34 +02:00
c7d12533e0 update npmextra.json: githost 2024-03-30 21:47:33 +01:00
e4205ac269 2.0.4 2024-02-13 01:18:57 +01:00
8825ca7c09 fix(core): update 2024-02-13 01:18:57 +01:00
d124e5807c 2.0.3 2023-08-21 08:53:15 +02:00
c2e6bac6a7 fix(core): update 2023-08-21 08:53:14 +02:00
b6519fed73 switch to new org scheme 2023-07-11 00:52:03 +02:00
e3bfe39197 switch to new org scheme 2023-07-10 02:56:39 +02:00
35bef45b5e 2.0.2 2022-12-22 16:51:44 +01:00
e29c4c9731 fix(core): update 2022-12-22 16:51:43 +01:00
bb943fe9fc 2.0.1 2022-12-22 16:47:50 +01:00
91e812df08 fix(core): update 2022-12-22 16:47:49 +01:00
94a1f693d3 2.0.0 2022-10-24 07:14:18 +02:00
60da639d69 BREAKING CHANGE(core): switch to esm 2022-10-24 07:14:17 +02:00
85d958e424 1.0.14 2021-09-22 01:29:47 +02:00
0dc089f811 fix(core): update 2021-09-22 01:29:47 +02:00
f4448d8501 1.0.13 2021-02-20 18:02:53 +00:00
d36056bd46 fix(core): update 2021-02-20 18:02:53 +00:00
96287ed710 1.0.12 2021-02-09 10:30:00 +00:00
ceb48fd45e fix(core): update 2021-02-09 10:30:00 +00:00
0ebd3c9872 1.0.11 2021-02-09 10:26:42 +00:00
397b6f13a7 fix(core): update 2021-02-09 10:26:42 +00:00
566a07a6b5 1.0.10 2020-03-28 22:48:18 +00:00
f3e1703eef fix(core): update 2020-03-28 22:48:17 +00:00
f1d180aefc 1.0.9 2019-10-01 20:03:37 +02:00
0753fae234 fix(core): update 2019-10-01 20:03:36 +02:00
14cf8c3b6c 1.0.8 2019-10-01 19:58:53 +02:00
7900997a10 fix(core): update 2019-10-01 19:58:53 +02:00
67bba6335c 1.0.7 2019-10-01 19:22:02 +02:00
eaef5d3d78 fix(core): update 2019-10-01 19:22:02 +02:00
d34feacdf1 1.0.6 2019-10-01 19:08:00 +02:00
6c7a890abe fix(core): update 2019-10-01 19:07:59 +02:00
dda163de2c 1.0.5 2019-10-01 18:04:43 +02:00
afa91b3da3 fix(core): update 2019-10-01 18:04:43 +02:00
a7660deb78 1.0.4 2019-02-23 13:46:36 +01:00
9b96bfceb8 fix(core): update 2019-02-23 13:46:36 +01:00
c37866bc3a 1.0.3 2019-02-23 00:50:21 +01:00
c41504f095 fix(core): update 2019-02-23 00:50:21 +01:00
20 changed files with 7735 additions and 1740 deletions

View File

@ -0,0 +1,66 @@
name: Default (not tags)
on:
push:
tags-ignore:
- '**'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Install pnpm and npmci
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
- name: Run npm prepare
run: npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build

View File

@ -0,0 +1,124 @@
name: Default (tags)
on:
push:
tags:
- '*'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build
release:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Release
run: |
npmci node install stable
npmci npm publish
metadata:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
continue-on-error: true
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Code quality
run: |
npmci command npm install -g typescript
npmci npm install
- name: Trigger
run: npmci trigger
- name: Build docs and upload artifacts
run: |
npmci node install stable
npmci npm install
pnpm install -g @git.zone/tsdoc
npmci command tsdoc
continue-on-error: true

9
.gitignore vendored
View File

@ -8,12 +8,13 @@ pages/
# installs
node_modules/
# caches and builds
# caches
.yarn/
.cache/
.rpt2_cache
# builds
dist/
dist_web/
dist_serve/
dist_ts_web/
dist_*/
# custom

View File

@ -1,144 +1,122 @@
# gitzone standard
image: hosttoday/ht-docker-node:npmci
# gitzone ci_default
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: "$CI_BUILD_STAGE"
- .npmci_cache/
key: '$CI_BUILD_STAGE'
stages:
- security
- test
- release
- metadata
- security
- test
- release
- metadata
before_script:
- pnpm install -g pnpm
- pnpm install -g @shipzone/npmci
- npmci npm prepare
# ====================
# security stage
# ====================
mirror:
# ====================
# security stage
# ====================
auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci git mirror
- npmci command npm config set registry https://registry.npmjs.org
- npmci command pnpm audit --audit-level=high --prod
tags:
- docker
- notpriv
snyk:
stage: security
script:
- npmci npm prepare
- npmci command npm install -g snyk
- npmci command npm install --ignore-scripts
- npmci command snyk test
tags:
- docker
- notpriv
sast:
stage: security
image: registry.gitlab.com/hosttoday/ht-docker-dbase:npmci
variables:
DOCKER_DRIVER: overlay2
- lossless
- docker
allow_failure: true
services:
- docker:stable-dind
auditDevDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci npm install
- npmci command npm run build
- export SP_VERSION=$(echo "$CI_SERVER_VERSION" | sed 's/^\([0-9]*\)\.\([0-9]*\).*/\1-\2-stable/')
- docker run
--env SAST_CONFIDENCE_LEVEL="${SAST_CONFIDENCE_LEVEL:-3}"
--volume "$PWD:/code"
--volume /var/run/docker.sock:/var/run/docker.sock
"registry.gitlab.com/gitlab-org/security-products/sast:$SP_VERSION" /app/bin/run /code
artifacts:
reports:
sast: gl-sast-report.json
- npmci command npm config set registry https://registry.npmjs.org
- npmci command pnpm audit --audit-level=high --dev
tags:
- docker
- priv
- lossless
- docker
allow_failure: true
# ====================
# test stage
# ====================
testLTS:
testStable:
stage: test
script:
- npmci npm prepare
- npmci node install lts
- npmci npm install
- npmci npm test
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
- docker
testSTABLE:
testBuild:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci npm test
- npmci node install stable
- npmci npm install
- npmci npm build
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
- docker
release:
stage: release
script:
- npmci node install stable
- npmci npm publish
- npmci node install stable
- npmci npm publish
only:
- tags
- tags
tags:
- docker
- notpriv
- lossless
- docker
- notpriv
# ====================
# metadata stage
# ====================
codequality:
stage: metadata
image: docker:stable
allow_failure: true
services:
- docker:stable-dind
only:
- tags
script:
- export SP_VERSION=$(echo "$CI_SERVER_VERSION" | sed 's/^\([0-9]*\)\.\([0-9]*\).*/\1-\2-stable/')
- docker run
--env SOURCE_CODE="$PWD"
--volume "$PWD":/code
--volume /var/run/docker.sock:/var/run/docker.sock
"registry.gitlab.com/gitlab-org/security-products/codequality:$SP_VERSION" /code
artifacts:
paths: [codeclimate.json]
- npmci command npm install -g typescript
- npmci npm prepare
- npmci npm install
tags:
- docker
- priv
- lossless
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
- npmci trigger
only:
- tags
- tags
tags:
- docker
- notpriv
- lossless
- docker
- notpriv
pages:
image: hosttoday/ht-docker-node:npmci
stage: metadata
script:
- npmci command npm install -g typedoc typescript
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci command typedoc --module "commonjs" --target "ES2016" --out public/ ts/
- npmci command npm run buildDocs
tags:
- lossless
- docker
- notpriv
only:
@ -146,5 +124,5 @@ pages:
artifacts:
expire_in: 1 week
paths:
- public
- public
allow_failure: true

11
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,11 @@
{
"version": "0.2.0",
"configurations": [
{
"command": "npm test",
"name": "Run npm test",
"request": "launch",
"type": "node-terminal"
}
]
}

26
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,26 @@
{
"json.schemas": [
{
"fileMatch": ["/npmextra.json"],
"schema": {
"type": "object",
"properties": {
"npmci": {
"type": "object",
"description": "settings for npmci"
},
"gitzone": {
"type": "object",
"description": "settings for gitzone",
"properties": {
"projectType": {
"type": "string",
"enum": ["website", "element", "service", "npm", "wcc"]
}
}
}
}
}
}
]
}

119
changelog.md Normal file
View File

@ -0,0 +1,119 @@
# Changelog
## 2024-09-05 - 2.2.1 - fix(core)
Add --allowimplicitany flag to build script
- Updated the build script in package.json to include the --allowimplicitany flag for TypeScript compilation.
## 2024-09-05 - 2.2.0 - feat(smartjwt)
Add nested JWT functionality
- Introduce `isNestedJwt` method to check if an object contains a nested JWT
- Implement `verifyNestedJwt` method to validate nested JWTs
- Add `createNestedJwt` method to create nested JWTs with given payload
- Include `nestedJwtGuard` for guarding nested JWT objects
## 2024-08-26 - 2.1.0 - feat(core)
Enhanced JWT handling and key management
- Introduced the `IObjectWithJwt` type for improved type constraints.
- Added support for smartguard to create object guards with JWT validation.
- Upgraded dependencies to latest versions.
## 2024-05-29 - 2.0.4 - Maintenance
Minor updates and configuration changes.
- Updated project description.
- Modified tsconfig settings.
- Updated npmextra.json with githost.
## 2024-02-13 - 2.0.3 - Bug Fixes
Critical fixes in core functionalities.
- Fixed core issues.
## 2023-07-11 - 2.0.2 - Organizational Update
Switched to the new organizational scheme.
- Adjusted project structure to align with new organizational policies.
## 2022-12-22 - 2.0.1 - Bug Fixes
Critical fixes in core functionalities.
- Fixed core issues.
## 2022-10-24 - 2.0.0 - Major Update
Significant updates including breaking changes.
- **Breaking Change:** Switched project to ECMAScript modules.
## 2021-09-22 - 1.0.14 - Bug Fixes
Critical fixes in core functionalities.
- Fixed core issues.
## 2021-02-20 - 1.0.13 - Bug Fixes
Critical fixes in core functionalities.
- Fixed core issues.
## 2021-02-09 - 1.0.12 - Bug Fixes
Critical fixes in core functionalities.
- Fixed core issues.
## 2021-02-09 - 1.0.11 - Bug Fixes
Critical fixes in core functionalities.
- Fixed core issues.
## 2020-03-28 - 1.0.10 - Bug Fixes
Critical fixes in core functionalities.
- Fixed core issues.
## 2019-10-01 - 1.0.9 - Bug Fixes
Critical fixes in core functionalities.
- Fixed core issues.
## 2019-10-01 - 1.0.8 - Bug Fixes
Critical fixes in core functionalities.
- Fixed core issues.
## 2019-10-01 - 1.0.7 - Bug Fixes
Critical fixes in core functionalities.
- Fixed core issues.
## 2019-10-01 - 1.0.6 - Bug Fixes
Critical fixes in core functionalities.
- Fixed core issues.
## 2019-10-01 - 1.0.5 - Bug Fixes
Critical fixes in core functionalities.
- Fixed core issues.
## 2019-10-01 - 1.0.4 - Bug Fixes
Critical fixes in core functionalities.
- Fixed core issues.
## 2019-02-23 - 1.0.3 - Bug Fixes
Critical fixes in core functionalities.
- Fixed core issues.
## 2019-02-23 - 1.0.2 - Bug Fixes
Critical fixes in core functionalities.
- Fixed core issues.
## 2019-02-23 - 1.0.1 - Bug Fixes
Critical fixes in core functionalities.
- Fixed core issues.

View File

@ -1,17 +1,33 @@
{
"gitzone": {
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"gituser": "pushrocks",
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "smartjwt",
"shortDescription": "a package for handling jwt",
"npmPackageName": "@pushrocks/smartjwt",
"description": "A JavaScript package for creating and verifying JWTs with strong typing support.",
"npmPackagename": "@push.rocks/smartjwt",
"license": "MIT",
"projectDomain": "push.rocks"
"projectDomain": "push.rocks",
"keywords": [
"jwt",
"jsonwebtoken",
"authentication",
"security",
"typescript",
"crypto",
"public key",
"private key",
"token validation",
"token creation"
]
}
},
"npmci": {
"npmGlobalTools": [],
"npmAccessLevel": "public"
},
"tsdoc": {
"legal": "\n## License and Legal Information\n\nThis 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. \n\n**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.\n\n### Trademarks\n\nThis 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.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy 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.\n"
}
}

1600
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,24 +1,62 @@
{
"name": "@pushrocks/smartjwt",
"version": "1.0.2",
"name": "@push.rocks/smartjwt",
"version": "2.2.1",
"private": false,
"description": "a package for handling jwt",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"description": "A JavaScript package for creating and verifying JWTs with strong typing support.",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"author": "Lossless GmbH",
"license": "MIT",
"scripts": {
"test": "(tstest test/)",
"build": "(tsbuild)",
"format": "(gitzone format)"
"build": "(tsbuild --allowimplicitany)"
},
"devDependencies": {
"@gitzone/tsbuild": "^2.0.22",
"@gitzone/tstest": "^1.0.15",
"@pushrocks/tapbundle": "^3.0.7",
"@types/node": "^11.9.5",
"tslint": "^5.11.0",
"tslint-config-prettier": "^1.15.0"
"@git.zone/tsbuild": "^2.1.84",
"@git.zone/tsrun": "^1.2.49",
"@git.zone/tstest": "^1.0.90",
"@push.rocks/tapbundle": "^5.0.24",
"@types/node": "^22.5.0"
},
"dependencies": {}
"dependencies": {
"@push.rocks/smartcrypto": "^2.0.4",
"@push.rocks/smartguard": "^3.1.0",
"@push.rocks/smartjson": "^5.0.20",
"@tsclass/tsclass": "^4.1.2",
"@types/jsonwebtoken": "^9.0.6",
"jsonwebtoken": "^9.0.2"
},
"files": [
"ts/**/*",
"ts_web/**/*",
"dist/**/*",
"dist_*/**/*",
"dist_ts/**/*",
"dist_ts_web/**/*",
"assets/**/*",
"cli.js",
"npmextra.json",
"readme.md"
],
"browserslist": [
"last 1 chrome versions"
],
"type": "module",
"keywords": [
"jwt",
"jsonwebtoken",
"authentication",
"security",
"typescript",
"crypto",
"public key",
"private key",
"token validation",
"token creation"
],
"homepage": "https://code.foss.global/push.rocks/smartjwt",
"repository": {
"type": "git",
"url": "https://code.foss.global/push.rocks/smartjwt.git"
}
}

6884
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

1
readme.hints.md Normal file
View File

@ -0,0 +1 @@

151
readme.md Normal file
View File

@ -0,0 +1,151 @@
# @push.rocks/smartjwt
a package for handling jwt
## 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
```
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.
## Usage
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.
### Initializing and Creating a New Key Pair
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
import { SmartJwt } from '@push.rocks/smartjwt';
async function setup() {
const smartJwt = new SmartJwt();
await smartJwt.createNewKeyPair();
console.log('Key pair created successfully');
}
setup();
```
### Creating a JWT
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:
```typescript
interface MyPayload {
user_id: number;
username: 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();
```
### Verifying a JWT and Extracting the Payload
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. Heres how to verify a JWT and extract its payload:
```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);
}
}
```
### Handling Public and Private Keys
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:
```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);
}
```
### Exporting and Importing Key Pairs
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.
## 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.
**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.
### Company Information
Task Venture Capital GmbH
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.
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.

View File

@ -1,8 +1,51 @@
import { expect, tap } from '@pushrocks/tapbundle';
import * as smartjwt from '../ts/index'
import { expect, tap } from '@push.rocks/tapbundle';
import * as smartjwt from '../ts/index.js';
tap.test('first test', async () => {
console.log(smartjwt.standardExport)
})
let smartjwtInstance: smartjwt.SmartJwt;
let testJwt: string;
tap.start()
tap.test('should create a valid instance', async () => {
smartjwtInstance = new smartjwt.SmartJwt();
await smartjwtInstance.createNewKeyPair();
console.log(smartjwtInstance);
});
tap.test('should create a valid jwt', async () => {
await smartjwtInstance.createNewKeyPair();
});
tap.test('should create a new jwt', async () => {
testJwt = await smartjwtInstance.createJWT({ hi: 'there' });
console.log(testJwt);
});
tap.test('should verify a jwt', async () => {
const data = await smartjwtInstance.verifyJWTAndGetData(testJwt);
// tslint:disable-next-line: no-unused-expression
expect(data).not.toBeNull();
console.log(data);
console.log(smartjwtInstance.publicKey.toPemString());
});
tap.test('should not verify a wrong jwt', async () => {
const jwt2 = await smartjwtInstance.createJWT({ wow: 'soclear' });
const jwt2Array = jwt2.split('.');
const testJwtArray = testJwt.split('.');
const newJwt = `${testJwtArray[0]}.${jwt2Array[1]}.${testJwtArray[2]}`;
let error: Error;
try {
await smartjwtInstance.verifyJWTAndGetData(newJwt);
} catch (e: any) {
error = e;
}
expect(error).toBeInstanceOf(Error);
});
tap.test('should verify a jwt on another instance', async () => {
const secondSmartJwtInstance = new smartjwt.SmartJwt();
secondSmartJwtInstance.setPublicPemKeyForVerification(smartjwtInstance.publicKey.toPemString());
const result = secondSmartJwtInstance.verifyJWTAndGetData(testJwt);
console.log(result);
});
tap.start();

8
ts/00_commitinfo_data.ts Normal file
View File

@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/smartjwt',
version: '2.2.1',
description: 'A JavaScript package for creating and verifying JWTs with strong typing support.'
}

View File

@ -1,3 +1 @@
import * as plugins from './smartjwt.plugins';
export let standardExport = 'Hi there! :) This is an exported string';
export * from './smartjwt.classes.smartjwt.js';

View File

@ -0,0 +1,121 @@
import * as plugins from './smartjwt.plugins.js';
// Define the IWithJwt interface with a constraint that T must be an object
export type IObjectWithJwt<T extends object> = T & { jwt: string };
/**
* A class to create and validate JWTs and their keys
*/
export class SmartJwt<T extends object = any> {
public smartcryptoInstance = new plugins.smartcrypto.Smartcrypto();
public publicKey: plugins.smartcrypto.PublicKey;
public privateKey: plugins.smartcrypto.PrivateKey;
constructor() {}
/**
* creates a JWT
*/
public async createJWT(payloadArg: T) {
return plugins.jsonwebtoken.sign(payloadArg, this.privateKey.toPemString(), {
algorithm: 'RS256',
});
}
/**
* checks a JWT
*/
public async verifyJWTAndGetData(jwtArg: string): Promise<T> {
const result = plugins.jsonwebtoken.verify(jwtArg, this.publicKey.toPemString(), {
algorithms: ['RS256'],
});
return result as any;
}
/**
* sets a private key to create jwts with
*/
public async setPrivateKey(privateKey: plugins.smartcrypto.PrivateKey) {
this.privateKey = privateKey;
}
/**
* sets a public key
*/
public async setPublicKey(publicKey: plugins.smartcrypto.PublicKey) {
this.publicKey = publicKey;
}
/**
* gets the currently set kaypair as json
*/
public getKeyPairAsJson(): plugins.tsclass.network.IJwtKeypair {
return {
privatePem: this.privateKey.toPemString(),
publicPem: this.publicKey.toPemString(),
};
}
/**
* sets the currently set keypair as json
*/
public setKeyPairAsJson(jsonKeyPair: plugins.tsclass.network.IJwtKeypair) {
this.privateKey = plugins.smartcrypto.PrivateKey.fromPemString(jsonKeyPair.privatePem);
this.publicKey = plugins.smartcrypto.PublicKey.fromPemString(jsonKeyPair.publicPem);
}
/**
* creates a new keypair
*/
public async createNewKeyPair() {
const keypair = await this.smartcryptoInstance.createKeyPair();
this.setPrivateKey(keypair.privateKey);
this.setPublicKey(keypair.publicKey);
}
/**
* when you just want to validate something
* @param publicPemKey
*/
public setPublicPemKeyForVerification(publicPemKey: string) {
this.publicKey = plugins.smartcrypto.PublicKey.fromPemString(publicPemKey);
}
public async init() {
await this.createNewKeyPair();
}
public isNestedJwt<T extends object>(
object: unknown,
): object is IObjectWithJwt<T> {
return (
typeof object === 'object' &&
object !== null &&
'jwt' in object &&
typeof (object as IObjectWithJwt<T>).jwt === 'string'
);
}
public async verifyNestedJwt<T extends object>(object: IObjectWithJwt<T>) {
const jwtData = await this.verifyJWTAndGetData(object.jwt);
(jwtData as any).jwt = object.jwt;
return plugins.smartjson.deepEqualObjects(object, jwtData);
}
public async createNestedJwt<T extends object>(payloadArg: T): Promise<IObjectWithJwt<T>> {
const jwt = await this.createJWT(payloadArg as any);
return {
...payloadArg,
jwt,
}
}
public nestedJwtGuard = new plugins.smartguard.Guard(async (dataArg: IObjectWithJwt<any>) => {
return this.verifyNestedJwt(dataArg);
}, {
name: 'jwtObjectGuard',
failedHint: 'is not a valid jwt object',
})
}

View File

@ -1,4 +1,17 @@
const removeme = {};
// @pushrocks scope
import * as smartcrypto from '@push.rocks/smartcrypto';
import * as smartguard from '@push.rocks/smartguard';
import * as smartjson from '@push.rocks/smartjson';
export { smartcrypto, smartguard, smartjson };
// thirdparty scope
import jsonwebtoken from 'jsonwebtoken';
export { jsonwebtoken };
// @tsclass scope
import * as tsclass from '@tsclass/tsclass';
export {
removeme
}
tsclass
};

14
tsconfig.json Normal file
View File

@ -0,0 +1,14 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
}

View File

@ -1,17 +0,0 @@
{
"extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
}