@carecard/auth-util 3.1.15 → 3.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: carecard-workspace-standards
3
- description: Follow the shared SO_CareCardCa/CareCard workspace coding, testing, repository, dependency, shared package, frontend, database, API response, and security standards. Use before modifying, testing, reviewing, or debugging any api-*, pkg-*, app-*, website, dashboard, or other CareCard repository in this workspace, especially when choosing validation commands, package boundaries, TypeScript types, dependencies, API contracts, database logic, service patterns, or frontend architecture.
3
+ description: 'Follow the shared SO_CareCardCa/CareCard workspace coding, testing, repository, dependency, shared package, frontend, database, API response, and security standards. Use before modifying, testing, reviewing, or debugging any ms-*, pkg-*, app-*, website, dashboard, or other CareCard repository in this workspace, especially when choosing validation commands, package boundaries, TypeScript types, dependencies, API contracts, database logic, service patterns, or frontend architecture.'
4
4
  ---
5
5
 
6
6
  # CareCard Workspace Standards
@@ -23,7 +23,7 @@ Use before modifying, testing, reviewing, or debugging any CareCard workspace re
23
23
 
24
24
  - `.agents/config.toml`
25
25
  - `.agents/skills`
26
- - `api-*` services
26
+ - `ms-*` services
27
27
  - `pkg-*` packages
28
28
  - `app-*` frontends
29
29
  - `.husky` and `.junie` validation guidance
@@ -43,8 +43,8 @@ Use before modifying, testing, reviewing, or debugging any CareCard workspace re
43
43
 
44
44
  ## Safety Constraints
45
45
 
46
- - Do not edit generated output, dependency folders, logs, coverage, dist, or build artifacts unless the task explicitly requires it.
47
- - Do not revert or overwrite user changes; stage only files related to the requested skill or instruction update.
46
+ - Do not edit generated output, dependency folders, logs, coverage, dist, or build artifacts unless the task requires it.
47
+ - Do not revert or overwrite user changes; stage only requested skill or instruction files.
48
48
  - Never suppress errors, lint failures, type failures, security failures, or failing tests; fix the underlying issue or report the blocker.
49
49
  - Do not log or expose secrets, JWTs, passwords, credentials, private keys, sensitive personal data, SQL internals, or stack traces.
50
50
 
@@ -52,7 +52,7 @@ Use before modifying, testing, reviewing, or debugging any CareCard workspace re
52
52
 
53
53
  Treat `/Users/pankajpriscilla/SO_CareCardCa` as a collection of independent Git
54
54
  repositories, not as one monorepo. Work from the specific child repository
55
- being changed. Each `api-*`, `pkg-*`, and `app-*` directory has its own package
55
+ being changed. Each `ms-*`, `pkg-*`, and `app-*` directory has its own package
56
56
  scripts, Git status, test commands, style, naming, structure, test framework,
57
57
  and Husky hooks.
58
58
 
@@ -128,11 +128,11 @@ config.
128
128
 
129
129
  ## Remote Git Operations Guardrail
130
130
 
131
- Do not run remote Git or GitHub operations unless the current user request explicitly asks for that remote operation. This includes `git fetch`, `git pull`, `git push`, `git push --delete`, remote branch cleanup, GitHub API calls, and any `gh pr` command that creates, updates, readies, merges, closes, or cleans up a pull request. Do not infer permission from branch names, validation needs, prior workflow habits, or convenience; ask first when remote state would be useful but was not requested.
131
+ Do not run remote Git or GitHub operations unless the current user request explicitly asks for them. This includes `git fetch`, `git pull`, `git push`, `git push --delete`, remote branch cleanup, GitHub API calls, and any `gh pr` command that creates, updates, readies, merges, closes, or cleans up a pull request. Do not infer permission from branch names, validation needs, prior workflow habits, or convenience; ask first when remote state would help but was not requested.
132
132
 
133
133
  ## Commit Continuation Rule
134
134
 
135
- Do not amend existing commits unless the user explicitly asks for an amend. If
135
+ Do not amend commits unless the user explicitly asks. If
136
136
  hooks, formatters, tests, docs, skills, validation, or review follow-up create
137
137
  additional changes after a commit already exists, keep history additive by
138
138
  making a new commit in the affected repository.
@@ -183,11 +183,11 @@ build artifacts, logs, or `.DS_Store`.
183
183
  `notFound404`, `appErrorHandler`, error throw helpers, case converters, and
184
184
  `ApiErrorType`.
185
185
  - Do not create or maintain duplicated common response or error helpers inside
186
- each `api-*` service.
186
+ each `ms-*` service.
187
187
  - Keep service-local response code limited to service-specific mapping or
188
188
  wiring.
189
189
  - Add broadly useful shared functionality to the relevant `pkg-*` package
190
- instead of duplicating it locally in an `api-*` or `app-*` project.
190
+ instead of duplicating it locally in an `ms-*` or `app-*` project.
191
191
  - When changing a `pkg-*` package, write package tests first, increase that
192
192
  package's minor version in `package.json`, run `npm install` in the package,
193
193
  update consuming projects to the new package version, run `npm install` in
@@ -206,10 +206,10 @@ build artifacts, logs, or `.DS_Store`.
206
206
 
207
207
  ## Backend Microservices
208
208
 
209
- Most JavaScript `api-*` services use CommonJS, Mocha, Supertest, Docker Compose
209
+ Most JavaScript `ms-*` services use CommonJS, Mocha, Supertest, Docker Compose
210
210
  database tests, `@carecard/*` packages, and `sub-apps`
211
- controller/router/model patterns. TypeScript services such as `api-contact-us`
212
- and `api-template-ts` use Jest or TypeScript tooling and should keep their
211
+ controller/router/model patterns. TypeScript services such as `ms-contact-us`
212
+ and `ms-template-ts` use Jest or TypeScript tooling and should keep their
213
213
  existing TypeScript style.
214
214
 
215
215
  - Keep environment-specific files explicit: `.env.development`, `.env.test`,
@@ -283,9 +283,9 @@ existing TypeScript style.
283
283
  - Keep tests readable and domain-specific.
284
284
  - Tests must cover desired or happy paths and prevention or rejection of
285
285
  undesired behavior.
286
- - JavaScript `api-*` services usually use Mocha, Supertest,
286
+ - JavaScript `ms-*` services usually use Mocha, Supertest,
287
287
  `test/index.test.js`, and Docker-backed PostgreSQL scripts.
288
- - TypeScript `api-*` services usually use Jest and `tests/index.test.ts`.
288
+ - TypeScript `ms-*` services usually use Jest and `tests/index.test.ts`.
289
289
  - `pkg-*` packages usually use Mocha plus TypeScript type tests where present.
290
290
  - `app-dashboard` uses Vitest, React Testing Library, mock API tests, and
291
291
  Selenium for end-to-end flows.
@@ -306,8 +306,8 @@ existing TypeScript style.
306
306
  ## Dashboard Frontend
307
307
 
308
308
  `app-dashboard` is a Next.js App Router TypeScript app using MUI, React Query,
309
- `next-intl`, and shared CareCard utilities. It consumes `api-auth`,
310
- `api-institutions`, `api-contact-us`, and `api-user-profiles` through service
309
+ `next-intl`, and shared CareCard utilities. It consumes `ms-auth`,
310
+ `ms-institutions`, `ms-contact-us`, and `ms-user-profiles` through service
311
311
  modules.
312
312
 
313
313
  - Keep backend URL definitions centralized in `src/services/api.routes.ts`.
@@ -366,12 +366,25 @@ the authenticated dashboard.
366
366
  - Keep CareCard package usage consistent with the service or app being changed.
367
367
  - When standardizing response or error behavior, prefer `@carecard/common-util`
368
368
  `3.1.15` because it contains response and error functions aligned with
369
- `api-auth`.
369
+ `ms-auth`.
370
370
  - If package version changes are required, update lockfiles and verify affected
371
371
  services or apps.
372
372
  - Avoid broad dependency upgrades as part of feature or refactor work unless
373
373
  the task is specifically about dependencies.
374
374
 
375
+ ## Auth Service RLS Contract
376
+
377
+ - `ms-auth` follows the shared PostgreSQL/RLS pattern from `ms-template-js`: auth tables live in the `carecard` schema, RLS is enabled and forced on every auth table, and application runtime queries use the unprivileged database role.
378
+ - Auth table policies allow normal JWT users to access only self-owned rows. Do not add redundant `user_id = <jwt sub>` SQL predicates to duplicate self-row checks when RLS owns the authorization decision.
379
+ - A JWT payload containing `roles: ["ad"]` is the auth-service super-admin signal and can perform any action on auth tables. Dashboard code may map that role to `super_admin`, but backend auth RLS must not require a separate database role row for that bypass.
380
+ - Public auth flows such as registration, login, confirmation, recovery, visitor creation, and service user lookup must use narrow system contexts (`system_create`, `system_login`, `system_confirm`, `system_recovery`, `system_visitor`, `system_service`) instead of privileged runtime queries.
381
+
382
+ - `ms-auth` controller exports use concise action names such as `loginUser`,
383
+ `registerUser`, `getUserDetail`, and `renewJwt`; route middleware and router
384
+ placement express whether a flow is public, authenticated, admin-only, or
385
+ service-only, so avoid `public`, `protected`, `admin`, or `Handler` suffixes
386
+ in new controller names.
387
+
375
388
  ## Security Requirements
376
389
 
377
390
  - Treat authentication, authorization, JWT, password, email confirmation,
@@ -1,13 +1,13 @@
1
1
  ---
2
2
  name: github-pr-create-update
3
- description: Use only when the user explicitly asks for remote Git or GitHub PR work: pushing a branch, creating or updating a PR, or marking a PR ready from the current repository branch.
3
+ description: 'Use only when the user explicitly asks for remote Git or GitHub PR work: pushing a branch, creating or updating a PR, or marking a PR ready from the current repository branch.'
4
4
  ---
5
5
 
6
6
  # Pull Request Create
7
7
 
8
8
  ## Purpose
9
9
 
10
- Only after the user explicitly asks for remote Git or GitHub PR work, create, update, verify, push, and mark ready a GitHub pull request from the current repository branch into origin/development.
10
+ After the user explicitly asks for remote Git or GitHub PR work, create, update, verify, push, and mark ready a GitHub pull request from the current repository branch into origin/development.
11
11
 
12
12
  ## When To Use
13
13
 
@@ -20,7 +20,7 @@ Only after the user explicitly asks for remote Git or GitHub PR work, create, up
20
20
 
21
21
  ## Remote Git Operations Guardrail
22
22
 
23
- Do not run remote Git or GitHub operations unless the current user request explicitly asks for that remote operation. This includes `git fetch`, `git pull`, `git push`, `git push --delete`, remote branch cleanup, GitHub API calls, and any `gh pr` command that creates, updates, readies, merges, closes, or cleans up a pull request. Do not infer permission from branch names, validation needs, prior workflow habits, or convenience; ask first when remote state would be useful but was not requested.
23
+ Do not run remote Git or GitHub operations unless the current user request explicitly asks for them. This includes `git fetch`, `git pull`, `git push`, `git push --delete`, remote branch cleanup, GitHub API calls, and any `gh pr` command that creates, updates, readies, merges, closes, or cleans up a pull request. Do not infer permission from branch names, validation needs, prior workflow habits, or convenience; ask first when remote state would help but was not requested.
24
24
 
25
25
  ## Relevant Files And Directories
26
26
 
@@ -41,13 +41,13 @@ Do not run remote Git or GitHub operations unless the current user request expli
41
41
 
42
42
  ## Safety Constraints
43
43
 
44
- - Do not edit generated output, dependency folders, logs, coverage, dist, or build artifacts unless the task explicitly requires it.
45
- - Do not revert or overwrite user changes; stage only files related to the requested skill or instruction update.
44
+ - Do not edit generated output, dependency folders, logs, coverage, dist, or build artifacts unless the task requires it.
45
+ - Do not revert or overwrite user changes; stage only requested skill or instruction files.
46
46
  - Never suppress errors, lint failures, type failures, security failures, or failing tests; fix the underlying issue or report the blocker.
47
47
 
48
48
  ## Commit Continuation Rule
49
49
 
50
- Do not amend existing commits unless the user explicitly asks for an amend. If
50
+ Do not amend commits unless the user explicitly asks. If
51
51
  hook, formatter, documentation, skill, validation, or review follow-up changes
52
52
  appear after a commit, stage only the intended files and make a new commit with
53
53
  a clear message.
@@ -1,13 +1,13 @@
1
1
  ---
2
2
  name: github-pr-merge-cleanup
3
- description: Use only when the user explicitly asks for remote Git or GitHub PR work: reviewing remote mergeability, validating, merging, closing, deleting, or cleaning up a pull request branch.
3
+ description: 'Use only when the user explicitly asks for remote Git or GitHub PR work: reviewing remote mergeability, validating, merging, closing, deleting, or cleaning up a pull request branch.'
4
4
  ---
5
5
 
6
6
  # Pull Request Merge Close
7
7
 
8
8
  ## Purpose
9
9
 
10
- Only after the user explicitly asks for remote Git or GitHub PR work, review, validate, merge, close, delete branch, and clean local state for a GitHub pull request targeting origin/development.
10
+ After the user explicitly asks for remote Git or GitHub PR work, review, validate, merge, close, delete branch, and clean local state for a GitHub pull request targeting origin/development.
11
11
 
12
12
  ## When To Use
13
13
 
@@ -20,7 +20,7 @@ Only after the user explicitly asks for remote Git or GitHub PR work, review, va
20
20
 
21
21
  ## Remote Git Operations Guardrail
22
22
 
23
- Do not run remote Git or GitHub operations unless the current user request explicitly asks for that remote operation. This includes `git fetch`, `git pull`, `git push`, `git push --delete`, remote branch cleanup, GitHub API calls, and any `gh pr` command that creates, updates, readies, merges, closes, or cleans up a pull request. Do not infer permission from branch names, validation needs, prior workflow habits, or convenience; ask first when remote state would be useful but was not requested.
23
+ Do not run remote Git or GitHub operations unless the current user request explicitly asks for them. This includes `git fetch`, `git pull`, `git push`, `git push --delete`, remote branch cleanup, GitHub API calls, and any `gh pr` command that creates, updates, readies, merges, closes, or cleans up a pull request. Do not infer permission from branch names, validation needs, prior workflow habits, or convenience; ask first when remote state would help but was not requested.
24
24
 
25
25
  ## Relevant Files And Directories
26
26
 
@@ -41,13 +41,13 @@ Do not run remote Git or GitHub operations unless the current user request expli
41
41
 
42
42
  ## Safety Constraints
43
43
 
44
- - Do not edit generated output, dependency folders, logs, coverage, dist, or build artifacts unless the task explicitly requires it.
45
- - Do not revert or overwrite user changes; stage only files related to the requested skill or instruction update.
44
+ - Do not edit generated output, dependency folders, logs, coverage, dist, or build artifacts unless the task requires it.
45
+ - Do not revert or overwrite user changes; stage only requested skill or instruction files.
46
46
  - Never suppress errors, lint failures, type failures, security failures, or failing tests; fix the underlying issue or report the blocker.
47
47
 
48
48
  ## Commit Continuation Rule
49
49
 
50
- Do not amend existing commits unless the user explicitly asks for an amend. If
50
+ Do not amend commits unless the user explicitly asks. If
51
51
  hook, formatter, documentation, skill, validation, or review follow-up changes
52
52
  appear after a commit, stage only the intended files and make a new commit with
53
53
  a clear message.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: pkg-auth-util-auth-crypto-library
3
- description: Use when changing pkg-auth-util auth, password, JWT, crypto, key, exported API, types, or package validation behavior.
3
+ description: 'Use when changing pkg-auth-util auth, password, JWT, crypto, key, exported API, types, or package validation behavior.'
4
4
  ---
5
5
 
6
6
  # Package Auth Util
@@ -43,8 +43,8 @@ CareCard auth utility package for JWT creation/verification primitives, password
43
43
 
44
44
  ## Safety Constraints
45
45
 
46
- - Do not edit generated output, dependency folders, logs, coverage, dist, or build artifacts unless the task explicitly requires it.
47
- - Do not revert or overwrite user changes; stage only files related to the requested skill or instruction update.
46
+ - Do not edit generated output, dependency folders, logs, coverage, dist, or build artifacts unless the task requires it.
47
+ - Do not revert or overwrite user changes; stage only requested skill or instruction files.
48
48
  - Never suppress errors, lint failures, type failures, security failures, or failing tests; fix the underlying issue or report the blocker.
49
49
  - Do not log or expose secrets, JWTs, passwords, credentials, private keys, sensitive personal data, SQL internals, or stack traces.
50
50
 
@@ -107,6 +107,9 @@ depend on those folders being present.
107
107
  `jwtCreateServiceAuthorizationHeader`.
108
108
  - Do not silently change token timing behavior, token formats, JWT string
109
109
  assembly, signature verification semantics, or decomposition return shapes.
110
+ - Preserve application JWT payload claims, including the `roles` array.
111
+ `ms-auth` RLS treats `roles: ["ad"]` as the auth-service super-admin signal,
112
+ so JWT helpers must not hide, rename, or drop that role data.
110
113
  - Expected parse and verify failures should return `null` or `false` where the
111
114
  current public API does so.
112
115
 
@@ -146,7 +149,7 @@ depend on those folders being present.
146
149
  - Use `try/catch` inside utility functions where existing functions fail
147
150
  gracefully instead of throwing uncaught exceptions.
148
151
  - Do not broaden catch blocks in a way that hides unexpected implementation
149
- errors in callers that currently expect throws.
152
+ errors in callers that expect throws.
150
153
 
151
154
  ## Types And Exports
152
155
 
@@ -199,7 +202,7 @@ and remaining risk.
199
202
 
200
203
  ## Remote Git Operations Guardrail
201
204
 
202
- Do not run remote Git or GitHub operations unless the current user request explicitly asks for that remote operation. This includes `git fetch`, `git pull`, `git push`, `git push --delete`, remote branch cleanup, GitHub API calls, and any `gh pr` command that creates, updates, readies, merges, closes, or cleans up a pull request. Do not infer permission from branch names, validation needs, prior workflow habits, or convenience; ask first when remote state would be useful but was not requested.
205
+ Do not run remote Git or GitHub operations unless the current user request explicitly asks for them. This includes `git fetch`, `git pull`, `git push`, `git push --delete`, remote branch cleanup, GitHub API calls, and any `gh pr` command that creates, updates, readies, merges, closes, or cleans up a pull request. Do not infer permission from branch names, validation needs, prior workflow habits, or convenience; ask first when remote state would help but was not requested.
203
206
 
204
207
  ## Agent Guidance Git Workflow
205
208
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: software-design-patterns-and-clean-code
3
- description: Use every time before coding, refactoring, debugging, or reviewing in this repository, alongside all other applicable skills, to apply pragmatic software design patterns, SOLID, Clean Code, and testable architecture.
3
+ description: 'Use every time before coding, refactoring, debugging, or reviewing in this repository, alongside all other applicable skills, to apply pragmatic software design patterns, SOLID, Clean Code, and testable architecture.'
4
4
  ---
5
5
 
6
6
  # Software Design Patterns And Clean Code
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@carecard/auth-util",
3
- "version": "3.1.15",
3
+ "version": "3.1.16",
4
4
  "repository": "https://github.com/CareCard-ca/pkg-auth-util.git",
5
5
  "description": "Auth utility functions",
6
6
  "main": "index.js",
@@ -25,17 +25,17 @@
25
25
  "author": "CareCard team",
26
26
  "license": "ISC",
27
27
  "devDependencies": {
28
- "express": "5.2.1",
29
28
  "@istanbuljs/nyc-config-typescript": "1.0.2",
29
+ "@types/express": "5.0.6",
30
30
  "@types/mocha": "10.0.10",
31
31
  "@types/node": "25.9.1",
32
- "@types/express": "5.0.6",
32
+ "eslint": "9.39.4",
33
+ "express": "5.2.1",
33
34
  "husky": "9.1.7",
35
+ "lint-staged": "17.0.5",
34
36
  "mocha": "11.7.6",
35
37
  "nyc": "18.0.0",
36
38
  "prettier": "3.8.3",
37
- "eslint": "9.39.4",
38
- "lint-staged": "17.0.5",
39
39
  "source-map-support": "0.5.21",
40
40
  "supertest": "7.2.2",
41
41
  "ts-node": "10.9.2",
@@ -43,6 +43,6 @@
43
43
  },
44
44
  "dependencies": {
45
45
  "@carecard/common-util": "3.1.15",
46
- "@carecard/validate": "3.1.24"
46
+ "@carecard/validate": "3.1.27"
47
47
  }
48
48
  }
package/readme.md CHANGED
@@ -100,6 +100,19 @@ const urlSafe = stringUtilAuth.makeStringUrlSafe('a+b/c==');
100
100
  // Result: a-b_c
101
101
  ```
102
102
 
103
+ ## CareCard Auth Contract
104
+
105
+ `ms-auth` issues CareCard user JWTs and now enforces its own auth tables with
106
+ forced PostgreSQL RLS. This package should preserve JWT claim values exactly
107
+ when creating or verifying tokens; a payload containing `roles: ["ad"]` is the
108
+ auth-service super-admin signal. Do not add helpers that hide, rename, or drop
109
+ the `roles` array, and do not add database bypass behavior to this package.
110
+
111
+ Docs that mention `ms-auth` controller internals should use concise action
112
+ names such as `loginUser`, `registerUser`, `getUserDetail`, and `renewJwt`.
113
+ Access level is conveyed by route middleware and endpoint placement, not by
114
+ `public`/`protected`/`admin`/`Handler` suffixes.
115
+
103
116
  ## Testing
104
117
 
105
118
  Run tests using:
package/.prettierignore DELETED
@@ -1,17 +0,0 @@
1
- dist/
2
- coverage/
3
- node_modules/
4
- build/
5
- *.min.js
6
- .github
7
- .husky
8
- dist
9
- .gitignore
10
- .npmignore
11
- .prettierignore
12
- .prettierrc.js
13
- eslint.config.mjs
14
- jest.config.js
15
- package.json
16
- readme.md
17
- rename-cjs.js
package/.prettierrc.cjs DELETED
@@ -1,32 +0,0 @@
1
- /** @type {import('prettier').Config} */
2
- module.exports = {
3
- // Core formatting
4
- printWidth: 100,
5
- tabWidth: 2,
6
- useTabs: false,
7
- semi: true,
8
- singleQuote: true,
9
- trailingComma: 'all',
10
- bracketSpacing: true,
11
- bracketSameLine: true,
12
- arrowParens: 'avoid',
13
-
14
- // Line endings (important for cross-platform + CI)
15
- endOfLine: 'auto',
16
-
17
- // Language-specific overrides
18
- overrides: [
19
- {
20
- files: '*.json',
21
- options: {
22
- printWidth: 80,
23
- },
24
- },
25
- {
26
- files: '*.md',
27
- options: {
28
- proseWrap: 'preserve',
29
- },
30
- },
31
- ],
32
- };
package/jest.config.js DELETED
@@ -1,16 +0,0 @@
1
- export default {
2
- preset: 'ts-jest',
3
- testEnvironment: 'node',
4
- transform: {
5
- '^.+\\.ts$': [
6
- 'ts-jest',
7
- {
8
- tsconfig: 'tsconfig.base.json',
9
- },
10
- ],
11
- },
12
- testMatch: ['**/tests/**/*.test.ts'],
13
- collectCoverage: true,
14
- collectCoverageFrom: ['src/**/*.ts'],
15
- coverageDirectory: 'coverage'
16
- };
@@ -1,13 +0,0 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
-
4
- const dir = './dist/cjs';
5
-
6
- for (const file of fs.readdirSync(dir)) {
7
- if (file.endsWith('.js')) {
8
- fs.renameSync(
9
- path.join(dir, file),
10
- path.join(dir, file.replace('.js', '.cjs'))
11
- );
12
- }
13
- }
@@ -1,111 +0,0 @@
1
- import * as crypto from 'crypto';
2
-
3
- /**
4
- * Signs a token returns signature string
5
- * @param token
6
- * @param privateKey
7
- * @param signingAlgorithm
8
- * @returns {string}
9
- */
10
- export const createBase64SignatureOfToken = function (
11
- token: string = '',
12
- privateKey: string,
13
- signingAlgorithm: string,
14
- ): string {
15
- const sign = crypto.createSign(signingAlgorithm);
16
- sign.write(token);
17
- sign.end();
18
- return sign.sign(privateKey, 'base64');
19
- };
20
-
21
- /**
22
- * Verifies the signature returns true or false
23
- * @param token
24
- * @param signature
25
- * @param publicKey
26
- * @param signingAlgorithm
27
- * @returns {boolean}
28
- */
29
- export const verifyBase64SignatureOfToken = function (
30
- token: string = '',
31
- signature: string,
32
- publicKey: string,
33
- signingAlgorithm: string,
34
- ): boolean {
35
- const verify = crypto.createVerify(signingAlgorithm);
36
- verify.update(token);
37
- verify.end();
38
- return verify.verify(publicKey, signature, 'base64');
39
- };
40
-
41
- /**
42
- * Creates the hash of given string
43
- * @param string
44
- * @param secret
45
- * @param algorithm
46
- * @returns {string}
47
- */
48
- export const createHmacBase64 = function (
49
- string: string = '',
50
- secret: string,
51
- algorithm: string,
52
- ): string {
53
- const hmac = crypto.createHmac(algorithm, secret);
54
- hmac.update(string);
55
- return hmac.digest('base64');
56
- };
57
-
58
- /**
59
- * Create random salt
60
- * @returns {string}
61
- */
62
- export const createSaltBase64 = (): string => {
63
- const date = new Date().valueOf();
64
- const hmac = crypto.createHmac('SHA256', date.toString());
65
- hmac.update(date.toString());
66
- return hmac.digest('base64');
67
- };
68
-
69
- /**
70
- * Encrypt given string
71
- * @param string
72
- * @param salt
73
- * @param secret
74
- * @param algorithm
75
- * @returns {string}
76
- */
77
- export const encryptStringAsciiToBase64 = (
78
- string: string,
79
- salt: string,
80
- secret: string,
81
- algorithm: string,
82
- ): string => {
83
- const key = crypto.scryptSync(secret, salt, 24);
84
- const iv = Buffer.alloc(16, 0);
85
- const cipher = crypto.createCipheriv(algorithm, key, iv);
86
- let encrypted = cipher.update(string, 'ascii', 'base64');
87
- encrypted += cipher.final('base64');
88
- return encrypted;
89
- };
90
-
91
- /**
92
- * Decrypts given string
93
- * @param encryptedString
94
- * @param salt
95
- * @param secret
96
- * @param algorithm
97
- * @returns {string}
98
- */
99
- export const decryptStringBase64ToAscii = (
100
- encryptedString: string,
101
- salt: string,
102
- secret: string,
103
- algorithm: string,
104
- ): string => {
105
- const key = crypto.scryptSync(secret, salt, 24);
106
- const iv = Buffer.alloc(16, 0);
107
- const decipher = crypto.createDecipheriv(algorithm, key, iv);
108
- let decrypted = decipher.update(encryptedString, 'base64', 'ascii');
109
- decrypted += decipher.final('ascii');
110
- return decrypted;
111
- };
package/src/index.ts DELETED
@@ -1,6 +0,0 @@
1
- export * from './cryptoUtilAuth';
2
- export * from './jwtUtilAuth';
3
- export * from './keyGen';
4
- export * from './pwdUtilAuth';
5
- export * from './strEncryptUtil';
6
- export * from './stringUtilAuth';
@@ -1,85 +0,0 @@
1
- import * as stringUtilAuth from './stringUtilAuth';
2
- import * as cryptoUtilAuth from './cryptoUtilAuth';
3
-
4
- /**
5
- * User supplied header, payload and signature create jwt.
6
- * @returns {string|null}
7
- * @param headerBase64
8
- * @param payloadBase64
9
- * @param signatureBase64
10
- */
11
- export const _assembleJwt = (
12
- headerBase64: string,
13
- payloadBase64: string,
14
- signatureBase64: string,
15
- ): string => {
16
- return headerBase64 + '.' + payloadBase64 + '.' + signatureBase64;
17
- };
18
-
19
- /**
20
- * User supplied header, payload and signature create jwt.
21
- * @returns {{payload: *, signature: *, header: *}}
22
- * @param jwt
23
- */
24
- export const _splitJwtInToHeaderPayloadSignature = (jwt: string): any => {
25
- return stringUtilAuth.dotConnectedStringToHeaderPayloadSignature(jwt);
26
- };
27
-
28
- /**
29
- * Creates Url safe jwt
30
- * @param headerObject
31
- * @param payloadObject
32
- * @param privateKey
33
- * @return {string|null}
34
- */
35
- export const createSignedJwtFromObject = (
36
- headerObject: any,
37
- payloadObject: any,
38
- privateKey: string,
39
- ): any => {
40
- try {
41
- const algorithm = headerObject.alg;
42
- const headerBase64UrlSafe = stringUtilAuth.objectToBase64UrlSafeString(headerObject);
43
- const payloadBase64UrlSafe = stringUtilAuth.objectToBase64UrlSafeString(payloadObject);
44
- const token = headerBase64UrlSafe + '.' + payloadBase64UrlSafe;
45
- const signature = cryptoUtilAuth.createBase64SignatureOfToken(token, privateKey, algorithm);
46
- const urlSafeSignature = stringUtilAuth.makeStringUrlSafe(signature);
47
- return _assembleJwt(headerBase64UrlSafe, payloadBase64UrlSafe, urlSafeSignature);
48
- } catch (error) {
49
- return null;
50
- }
51
- };
52
-
53
- /**
54
- * Verify signature of jwt
55
- * @param jwt
56
- * @param publicKey
57
- * @return {boolean}
58
- */
59
- export const verifyJwtSignature = (jwt: string, publicKey: string): boolean => {
60
- try {
61
- const { header, payload, signature } = _splitJwtInToHeaderPayloadSignature(jwt);
62
- const token = header + '.' + payload;
63
- const headerObject = stringUtilAuth.urlSafeBase64ToObject(header);
64
- return cryptoUtilAuth.verifyBase64SignatureOfToken(
65
- token,
66
- signature,
67
- publicKey,
68
- headerObject.alg,
69
- );
70
- } catch (error) {
71
- return false;
72
- }
73
- };
74
-
75
- /**
76
- * Returns header and payload object for jwt.
77
- * @param jwt
78
- * @return {{payload: any, header: any}}
79
- */
80
- export const getHeaderPayloadFromJwt = (jwt: string): any => {
81
- const { header, payload } = _splitJwtInToHeaderPayloadSignature(jwt);
82
- let headerAscii = stringUtilAuth.base64ToAscii(header);
83
- let payloadAscii = stringUtilAuth.base64ToAscii(payload);
84
- return { header: JSON.parse(headerAscii), payload: JSON.parse(payloadAscii) };
85
- };
package/src/keyGen.ts DELETED
@@ -1,14 +0,0 @@
1
- import { generateKeyPairSync } from 'node:crypto';
2
-
3
- export const generateKeyPair = (modulusLength: number = 4096) =>
4
- generateKeyPairSync('rsa', {
5
- modulusLength: modulusLength,
6
- publicKeyEncoding: {
7
- type: 'spki',
8
- format: 'pem',
9
- },
10
- privateKeyEncoding: {
11
- type: 'pkcs8',
12
- format: 'pem',
13
- },
14
- });