@carecard/jwt-read 3.1.14 → 3.1.15

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.
@@ -0,0 +1,175 @@
1
+ ---
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.
4
+ ---
5
+
6
+ # Pull Request Merge Close
7
+
8
+ ## Purpose
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.
11
+
12
+ ## When To Use
13
+
14
+ - Use only when the user explicitly asks to review mergeability, validate, merge, close, or clean up a GitHub pull request branch.
15
+
16
+ ## When Not To Use
17
+
18
+ - Do not use for creating a new pull request; use the PR create/update skill.
19
+ - Do not use when the user only asks for local code changes without PR merge work.
20
+
21
+ ## Remote Git Operations Guardrail
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.
24
+
25
+ ## Relevant Files And Directories
26
+
27
+ - Git branch state in this repository
28
+ - GitHub pull requests viewed with `gh`
29
+ - repository validation commands and `.husky` scripts
30
+
31
+ ## Coding Principles
32
+
33
+ - Preserve the repository structure, naming style, module system, and local helper patterns.
34
+ - Prefer readable, maintainable code with meaningful function, variable, file, and test names.
35
+ - Avoid new dependencies unless the existing stack cannot reasonably solve the task and the user confirms the tradeoff.
36
+
37
+ ## Testing Expectations
38
+
39
+ - Run repository validation before PR creation or merge when code behavior changed.
40
+ - Confirm the branch is clean except intended changes before finishing.
41
+
42
+ ## Safety Constraints
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.
46
+ - Never suppress errors, lint failures, type failures, security failures, or failing tests; fix the underlying issue or report the blocker.
47
+
48
+ ## Commit Continuation Rule
49
+
50
+ Do not amend existing commits unless the user explicitly asks for an amend. If
51
+ hook, formatter, documentation, skill, validation, or review follow-up changes
52
+ appear after a commit, stage only the intended files and make a new commit with
53
+ a clear message.
54
+
55
+ ## Scope
56
+
57
+ Use this skill from the root of the repository that owns the pull request. The
58
+ repository must use GitHub CLI, have a remote base branch, and have the target
59
+ branch available locally or on `origin`.
60
+
61
+ Default terms:
62
+
63
+ - Base branch: `development` when `origin/development` exists, otherwise the
64
+ repository default branch.
65
+ - Target branch: the current branch unless the user names another branch.
66
+ - Pull request: the open PR whose head is the target branch and whose base is
67
+ the base branch.
68
+
69
+ Do not continue automatically when:
70
+
71
+ - `gh auth status` fails.
72
+ - The target branch is detached or is the base branch.
73
+ - The working tree has uncommitted changes that are not part of the requested
74
+ PR cleanup.
75
+ - No open PR exists for the target branch.
76
+ - A rebase or validation fix would require behavior changes instead of coding
77
+ criteria cleanup.
78
+
79
+ ## Workflow
80
+
81
+ 1. Capture the base branch, target branch, PR number, and protection state:
82
+
83
+ ```sh
84
+ gh auth status
85
+ base="development"
86
+ git ls-remote --exit-code --heads origin development >/dev/null 2>&1 || \
87
+ base="$(gh repo view --json defaultBranchRef --jq '.defaultBranchRef.name')"
88
+ target_branch="$(git branch --show-current)"
89
+ test -n "$target_branch"
90
+ test "$target_branch" != "$base"
91
+ git status --short
92
+ git fetch origin "$base" --prune
93
+ pr_number="$(gh pr list --head "$target_branch" --base "$base" --state open --json number --jq '.[0].number // empty')"
94
+ test -n "$pr_number"
95
+ protected="$(gh api "repos/{owner}/{repo}/branches/$target_branch" --jq '.protected' 2>/dev/null || echo false)"
96
+ ```
97
+
98
+ If the PR head branch is not local, create a local branch from the remote
99
+ head before continuing.
100
+
101
+ 2. Check mergeability before changing history:
102
+
103
+ ```sh
104
+ gh pr view "$pr_number" --json mergeStateStatus,mergeable,headRefName,baseRefName
105
+ if git merge-tree --write-tree HEAD "origin/$base" >/tmp/pull-request-merge-close-merge-tree.out
106
+ then
107
+ merge_conflict_detected=false
108
+ else
109
+ merge_conflict_detected=true
110
+ fi
111
+ ```
112
+
113
+ 3. If a merge conflict is detected, rebase the target branch on the fresh base
114
+ branch. Abort and stop if the rebase conflicts:
115
+
116
+ ```sh
117
+ if [ "$merge_conflict_detected" = true ]; then
118
+ if git rebase "origin/$base"; then
119
+ git push --force-with-lease -u origin "$target_branch"
120
+ else
121
+ git rebase --abort
122
+ echo "Rebase conflicted; aborted without merging."
123
+ exit 1
124
+ fi
125
+ fi
126
+ ```
127
+
128
+ Do not resolve rebase conflicts unless the user explicitly asks.
129
+
130
+ 4. Load and apply all relevant repository skills before merging:
131
+ - Read the repository's `.agents/skills/**/SKILL.md` files that apply to the
132
+ changed code, plus shared workspace standards when present.
133
+ - Compare the target branch against the base with
134
+ `git diff --stat "origin/$base...HEAD"` and inspect changed files.
135
+ - Check whether the target branch satisfies the applicable coding,
136
+ architecture, validation, security, and style criteria from those skills.
137
+ - Run the validation commands required by the skills and repository hooks.
138
+ - If criteria are not met and the fix does not change functionality, make the
139
+ minimal cleanup, stage only intended files, commit to the target branch,
140
+ and push the target branch.
141
+ - If meeting the criteria would change behavior, stop and report the gap.
142
+
143
+ 5. Confirm the PR is still mergeable after validation changes:
144
+
145
+ ```sh
146
+ git fetch origin "$base" --prune
147
+ git merge-tree --write-tree HEAD "origin/$base" >/tmp/pull-request-merge-close-final-merge-tree.out
148
+ gh pr checks "$pr_number"
149
+ ```
150
+
151
+ 6. Merge the PR with GitHub CLI. Delete the remote target branch only when it is
152
+ not protected:
153
+
154
+ ```sh
155
+ if [ "$protected" = true ]; then
156
+ gh pr merge "$pr_number" --squash --admin
157
+ else
158
+ gh pr merge "$pr_number" --squash --admin --delete-branch
159
+ fi
160
+ ```
161
+
162
+ 7. Clean up the local repository after merge:
163
+
164
+ ```sh
165
+ git fetch origin "$base" --prune
166
+ git switch "$base"
167
+ git pull --ff-only origin "$base"
168
+ git branch -d "$target_branch" || git branch -D "$target_branch"
169
+ git ls-remote --heads origin "$target_branch"
170
+ ```
171
+
172
+ 8. Final response should include the PR URL, whether a rebase was performed,
173
+ what validation and skill checks ran, whether any cleanup commit was added,
174
+ whether the remote target branch was deleted or protected, and whether local
175
+ development is up to date.
@@ -0,0 +1,5 @@
1
+ interface:
2
+ display_name: 'GitHub PR Merge And Cleanup'
3
+ short_description: 'Use only when the user explicitly asks for remote Git or GitHub PR work: merge, close, delete, or clean up a PR branch.'
4
+ brand_color: '#0F766E'
5
+ default_prompt: 'Use $github-pr-merge-cleanup when this task matches the skill scope.'
@@ -0,0 +1,239 @@
1
+ ---
2
+ name: pkg-jwt-read-jwt-middleware-library
3
+ description: Use when changing pkg-jwt-read JWT parsing, middleware, visitor tokens, role checks, auth context, package exports, or tests.
4
+ ---
5
+
6
+ # Package JWT Read
7
+
8
+ ## Purpose
9
+
10
+ CareCard JWT read package for parsing, request attachment, visitor tokens, role mapping, authorization middleware, exports, and tests.
11
+
12
+ ## When To Use
13
+
14
+ - Use when changing pkg-jwt-read JWT parsing, middleware, visitor tokens, role checks, auth context, package exports, or tests.
15
+ - Pair with `carecard-workspace-standards` when the task affects shared CareCard conventions or cross-repository contracts.
16
+
17
+ ## When Not To Use
18
+
19
+ - Do not use for service-local behavior that should remain inside one API or app.
20
+ - Do not change package public APIs without updating consumers and compatibility tests.
21
+
22
+ ## Relevant Files And Directories
23
+
24
+ - package entry files
25
+ - `src` when present
26
+ - `test`
27
+ - `package.json`
28
+ - `package-lock.json`
29
+ - `.husky`
30
+
31
+ ## Coding Principles
32
+
33
+ - Preserve the repository structure, naming style, module system, and local helper patterns.
34
+ - Prefer readable, maintainable code with meaningful function, variable, file, and test names.
35
+ - Avoid new dependencies unless the existing stack cannot reasonably solve the task and the user confirms the tradeoff.
36
+ - Keep public exports stable and update CommonJS, ESM, TypeScript declaration, and compatibility surfaces together when present.
37
+
38
+ ## Testing Expectations
39
+
40
+ - Write or update package tests before behavior or public API changes.
41
+ - Include type/export compatibility tests where the package already has them.
42
+ - Run package test, lint, type, and Husky validation commands required by the changed area.
43
+
44
+ ## Safety Constraints
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.
48
+ - Never suppress errors, lint failures, type failures, security failures, or failing tests; fix the underlying issue or report the blocker.
49
+ - Do not log or expose secrets, JWTs, passwords, credentials, private keys, sensitive personal data, SQL internals, or stack traces.
50
+
51
+ ## Overview
52
+
53
+ Use this skill when working inside `pkg-jwt-read`, the `@carecard/jwt-read`
54
+ package. It provides utilities for reading, parsing, verifying, and attaching
55
+ JWT data in the CareCard ecosystem. It depends on `@carecard/auth-util` for
56
+ low-level cryptographic operations.
57
+
58
+ Use `$carecard-workspace-standards` for shared workspace, dependency, package,
59
+ testing, and security rules. Legacy `pkg-jwt-read/.codex` and
60
+ `pkg-jwt-read/.junie` guidance has been migrated into these skills; do not
61
+ depend on those folders being present.
62
+
63
+ ## Non-Negotiable Rules
64
+
65
+ - Never use TypeScript type `any`. Use specific JWT, Express, request, payload,
66
+ header, role, generic, or `unknown` types with narrowing.
67
+ - Follow this repository's coding style, naming conventions, and CommonJS
68
+ project structure.
69
+ - Use Test-Driven Development: add or update relevant Mocha or type tests before
70
+ changing behavior.
71
+ - Never suppress errors, linter warnings, TypeScript errors, or failing tests.
72
+ Handle the underlying issue.
73
+ - Do not add dependencies unless absolutely needed. Ask for confirmation first
74
+ with the reason and tradeoff.
75
+ - Before finalizing work, run every direct script in `.husky` and fix anything
76
+ they report.
77
+
78
+ ## Package Shape
79
+
80
+ - Keep `index.js` as the centralized public export surface.
81
+ - Keep TypeScript declarations in `index.d.ts` aligned with every public export
82
+ in `index.js`.
83
+ - Keep JWT verification and request attachment behavior in `lib/jwtLib.js`.
84
+ - Keep role code/name mapping and JWT context behavior in `lib/jwtRoles.js`.
85
+ - Preserve the package's CommonJS module style unless the repository is
86
+ intentionally migrated.
87
+ - Keep backward-compatible deprecated exports unless the user explicitly asks to
88
+ remove them.
89
+
90
+ ## JWT Verification Layer
91
+
92
+ `lib/jwtLib.js` owns:
93
+
94
+ - Signature verification using public keys.
95
+ - Middleware-like functions for Express, such as `verifyJwtAndRole`.
96
+ - Service-to-service JWT verification and extraction helpers:
97
+ `jwtValidateAndExtractService` and `jwtVerifyService`.
98
+ - Extraction of `sub`/clientId and other claims from JWT objects.
99
+ - Expiration checks and TTL calculations.
100
+ - Request attachment behavior for authenticated JWT objects and visitor tokens.
101
+ - Integration with `@carecard/common-util` for standardized login and
102
+ authorization errors.
103
+
104
+ Use `@carecard/auth-util` for JWT creation, decomposition, and signature
105
+ verification. Do not duplicate cryptographic logic in this package.
106
+
107
+ JWT creation functions do not belong in this package. Service-to-service token
108
+ creation belongs in `@carecard/auth-util` via `jwtCreateServiceToken` and
109
+ `jwtCreateServiceAuthorizationHeader`.
110
+
111
+ Service JWTs must follow standard JWT claim semantics. They use `iss` for the
112
+ sending service, `sub` for the sending service identity, `aud` for the
113
+ receiving service, and NumericDate `iat`, `exp`, and optional `nbf` claims.
114
+ Receivers must verify the signature with the sending service public key and
115
+ must check expected issuer, audience, subject, and lifetime. Do not add
116
+ CareCard-specific replacement claims when a registered JWT claim covers the
117
+ same meaning.
118
+
119
+ ## Role Mapping Layer
120
+
121
+ `lib/jwtRoles.js` owns translation between internal role codes and human-readable
122
+ role names, such as `ad` and `admin`.
123
+
124
+ - Update `lib/jwtRoles.js` when adding or changing roles.
125
+ - Keep role code, role name, context, and authorization helper behavior covered
126
+ by focused tests.
127
+ - Preserve existing role semantics unless a task explicitly changes
128
+ authorization behavior.
129
+
130
+ ## NoThrow And Error Behavior
131
+
132
+ - Preserve the distinction between throwing APIs and `NoThrow` APIs.
133
+ - `NoThrow` variants should set the attached request property to `null` for
134
+ invalid tokens without hiding unexpected implementation errors.
135
+ - Use provided `throwError` and `throwUsedTokenError` patterns to keep
136
+ ecosystem error responses consistent.
137
+ - Use `@carecard/common-util` error helpers for login and authorization
138
+ failures.
139
+ - Keep user-facing errors safe and avoid exposing token internals or
140
+ verification details.
141
+
142
+ ## Security Rules
143
+
144
+ - Treat JWT parsing, signature verification, visitor tokens, authorization
145
+ roles, and request context as security-sensitive.
146
+ - Do not log JWTs, token fragments, public/private keys, decoded payloads,
147
+ authorization headers, visitor headers, or sensitive request data.
148
+ - Keep missing headers, invalid signatures, expired tokens, role failures, and
149
+ used-token errors behaviorally distinct where existing APIs do so.
150
+
151
+ ## Types And API Contracts
152
+
153
+ - Model JWT header, payload, request attachment, visitor attachment, role, and
154
+ context shapes explicitly in `index.d.ts`.
155
+ - Prefer `AuthenticatedRequest`, `JwtHeader`, `JwtPayload`, `JwtParts`,
156
+ `JwtRequestObject`, `VisitorRequestObject`, and `JwtContext` over loose
157
+ request objects.
158
+ - When existing declarations are too loose, improve them with specific types as
159
+ part of the touched change instead of adding new loose types.
160
+ - Keep overloads for context-bound helpers such as `jwtIsExpired` readable and
161
+ covered by type tests.
162
+ - Update `test/types.test.ts` whenever public types, exports, overloads, or
163
+ attached request methods change.
164
+
165
+ ## Tests
166
+
167
+ - Use Mocha for runtime tests under `test`.
168
+ - `lib` modules should have corresponding test files under `test`.
169
+ - `test/attachedMethods.test.js` covers methods attached to objects or used as
170
+ context.
171
+ - `test/types.test.ts` verifies TypeScript declarations with `tsc`.
172
+ - Add focused tests for valid JWTs, invalid JWTs, missing headers, role checks,
173
+ visitor token extraction, expiration behavior, request attachment behavior,
174
+ NoThrow behavior, and context-bound helpers when those areas change.
175
+ - Set `NODE_ENV=test` where tests or scripts require it.
176
+ - Keep tests deterministic and avoid real external services.
177
+
178
+ ## Validation
179
+
180
+ Useful commands:
181
+
182
+ - `npm run lint`
183
+ - `npm run lint:fix`
184
+ - `npm run format`
185
+ - `npm run format:check`
186
+ - `npm run test`
187
+ - `npm run test:types`
188
+ - `npm run test:coverage`
189
+ - `npm run test:All`
190
+
191
+ Before pushing or finalizing, run every direct `.husky` script. The current
192
+ `.husky/pre-commit` runs:
193
+
194
+ ```bash
195
+ npm run lint:fix
196
+ npm run format
197
+ npm run test:All
198
+ ```
199
+
200
+ If any validation command cannot run, report the exact command, failure reason,
201
+ and remaining risk.
202
+
203
+ ## Remote Git Operations Guardrail
204
+
205
+ 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.
206
+
207
+ ## Agent Guidance Git Workflow
208
+
209
+ When this skill or any repository-owned `.agents` guidance changes, use the
210
+ repository's agents-only Git workflow:
211
+
212
+ 1. Work from the affected repository root and confirm only intended `.agents`
213
+ files changed.
214
+ 2. Use `development` as the base branch when `origin/development` exists;
215
+ otherwise use the repository's default base branch, usually `main`.
216
+ 3. Create or update `feature/codex` from the updated remote base branch and
217
+ commit all the changed `.agents` guidance files there.
218
+ 4. Push `feature/codex`, create or reuse a pull request into the base branch,
219
+ and mark the pull request ready for review with `gh pr ready <number>`.
220
+ 5. Squash-merge with administrator privileges and delete the remote branch:
221
+
222
+ ```sh
223
+ gh pr merge <number> --squash --admin --delete-branch
224
+ ```
225
+
226
+ 6. After merge, update the local base branch and remove the local feature
227
+ branch:
228
+
229
+ ```sh
230
+ git fetch origin <base> --prune
231
+ git switch <base>
232
+ git pull --ff-only origin <base>
233
+ git branch -d feature/codex
234
+ git ls-remote --heads origin feature/codex
235
+ ```
236
+
237
+ Do not commit or push `.agents` guidance changes directly from `development`
238
+ or `main`. Do not stage unrelated files, generated output, dependency folders,
239
+ build artifacts, logs, or `.DS_Store`.
@@ -0,0 +1,4 @@
1
+ interface:
2
+ display_name: 'Package JWT Read Middleware Library'
3
+ short_description: 'Use when changing pkg-jwt-read JWT parsing, middleware, visitor tokens, role checks, auth context, package exports, or tests.'
4
+ default_prompt: 'Use $pkg-jwt-read-jwt-middleware-library when this task matches the skill scope.'
@@ -0,0 +1,73 @@
1
+ ---
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.
4
+ ---
5
+
6
+ # Software Design Patterns And Clean Code
7
+
8
+ ## Purpose
9
+
10
+ Use this skill with every coding, refactoring, debugging, or review task in
11
+ this repository. It supplements repository-specific skills; follow both, and
12
+ let the more specific skill decide file locations, framework conventions,
13
+ validation commands, and API contracts.
14
+
15
+ ## Core Principles
16
+
17
+ - Prefer simple, maintainable, readable implementation over clever abstraction.
18
+ - Use Gang of Four design patterns only when they reduce real complexity,
19
+ improve clarity, or make behavior easier to test.
20
+ - Follow SOLID principles, especially Single Responsibility and Dependency
21
+ Inversion where they improve maintainability.
22
+ - Keep clear separation of concerns between routing, orchestration, domain
23
+ logic, persistence, validation, formatting, and side effects.
24
+ - Apply DRY, KISS, and YAGNI. Remove meaningful duplication, keep solutions
25
+ direct, and avoid speculative generalization.
26
+ - Favor small, composable functions with meaningful names and explicit inputs.
27
+ - Prefer pure functions for calculations, mapping, validation, and transforms
28
+ when practical.
29
+ - Keep side effects minimal, localized, and easy to identify.
30
+ - Use explicit error handling. Do not swallow failures or hide actionable
31
+ error context.
32
+ - Design code so behavior can be tested through focused unit, integration, or
33
+ service tests without fragile setup.
34
+ - Avoid unnecessary dependencies. Use existing language, framework, and local
35
+ helper capabilities before adding packages.
36
+
37
+ ## Function Comments
38
+
39
+ For every new or modified function, method, or exported callback, add a short
40
+ comment immediately above it explaining the main pattern or principle being
41
+ applied. Keep the comment accurate and specific to the function.
42
+
43
+ Use the host language's normal comment syntax. Examples:
44
+
45
+ ```ts
46
+ // Pattern: Single Responsibility - validates user input only.
47
+ function validateUserInput(...) { ... }
48
+
49
+ // Pattern: Pure Function - deterministic output with no side effects.
50
+ function calculateTotal(...) { ... }
51
+
52
+ // Pattern: Dependency Inversion - depends on an injected repository contract.
53
+ async function loadProfile(...) { ... }
54
+ ```
55
+
56
+ ## Working Rules
57
+
58
+ - Do not violate these coding principles unless there is no reasonable
59
+ alternative.
60
+ - If a principle must be violated, include a short explanation in the code
61
+ review or final summary.
62
+ - Refactor touched existing code to follow these patterns and principles when
63
+ doing so is safe and related to the requested change.
64
+ - Do not use this skill as a reason for broad unrelated rewrites.
65
+ - Before introducing an abstraction or design pattern, confirm it removes real
66
+ complexity compared with a straightforward function or module.
67
+ - Prefer dependency inversion at boundaries such as databases, external
68
+ services, clocks, file systems, queues, and network calls when it improves
69
+ testability or substitution.
70
+ - Keep interfaces and abstractions narrow. Do not create generic layers that
71
+ only have one trivial implementation unless they clarify a boundary.
72
+ - Preserve the repository's existing style, naming, module system, and testing
73
+ approach.
@@ -0,0 +1,2 @@
1
+ approval_policy = "never"
2
+ sandbox_mode = "danger-full-access"
package/index.d.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * Utility functions for authentication and authorization in the CareCard ecosystem.
3
3
  */
4
4
 
5
- import {NextFunction, Request, Response} from 'express';
5
+ import { NextFunction, Request, Response } from 'express';
6
6
 
7
7
  /**
8
8
  * Represents the standard JWT header structure.
@@ -178,6 +178,17 @@ export function jwtGetContext(req: any): JwtContext;
178
178
  */
179
179
  export function jwtValidateAndExtract(req: AuthenticatedRequest, publicKey: string, customErrorFunction?: () => void): void;
180
180
 
181
+ /**
182
+ * Validates a service-to-service JWT from the Authorization header and extracts it into req.jwt.
183
+ */
184
+ export function jwtValidateAndExtractService(
185
+ req: AuthenticatedRequest,
186
+ publicKey: string,
187
+ expectedIssuer: string,
188
+ expectedAudience: string,
189
+ customErrorFunction?: () => void,
190
+ ): void;
191
+
181
192
  /**
182
193
  * Validates the JWT from a custom header and extracts it into req.jwt.
183
194
  */
@@ -203,6 +214,16 @@ export function jwtValidateAndExtractWebTokenNoThrow(req: AuthenticatedRequest,
203
214
  */
204
215
  export function jwtValidateAndExtractVisitorNoThrow(req: AuthenticatedRequest, publicKey: string): void;
205
216
 
217
+ /**
218
+ * Returns middleware that verifies a service-to-service JWT from one expected sender.
219
+ */
220
+ export function jwtVerifyService(
221
+ publicKey: string,
222
+ expectedIssuer: string,
223
+ expectedAudience: string,
224
+ customErrorFunction?: () => void,
225
+ ): (req: AuthenticatedRequest, res: Response, next: NextFunction) => void;
226
+
206
227
  /**
207
228
  * Returns a middleware that verifies a JWT from the 'Authorization: Bearer <token>' header
208
229
  * and extracts it into req.jwt. Throws an error if invalid.
package/index.js CHANGED
@@ -16,10 +16,12 @@ module.exports = {
16
16
  jwtGetRoleCode: jwtRoles.getCodeFromNameOfRole,
17
17
  jwtGetContext: jwtRoles.getContext,
18
18
  jwtValidateAndExtract: jwtLib.validateAndExtractJwtObject,
19
+ jwtValidateAndExtractService: jwtLib.validateAndExtractServiceJwtObject,
19
20
  jwtValidateAndExtractWebToken: jwtLib.validateAndExtractWebToken,
20
21
  jwtValidateAndExtractNoThrow: jwtLib.validateAndExtractJwtObjectNoThrow,
21
22
  jwtValidateAndExtractWebTokenNoThrow: jwtLib.validateAndExtractWebTokenObjectNoThrow,
22
23
  jwtValidateAndExtractVisitorNoThrow: jwtLib.validateAndExtractVisitorObjectNoThrow,
24
+ jwtVerifyService: jwtLib.verifyServiceJwt,
23
25
 
24
26
  /** @deprecated use jwtVerify */
25
27
  verifyJwt: jwtLib.verifyJwt,
package/lib/jwtLib.js CHANGED
@@ -104,6 +104,24 @@ function validateAndExtractJwtObjectNoThrow(req, publicKey) {
104
104
  return _validateAndExtractGenericNoThrow(req, publicKey, _validateJwtNoThrow, _extractJwtObjectNoThrow, 'jwt');
105
105
  }
106
106
 
107
+ function validateAndExtractServiceJwtObject(req, publicKey, expectedIssuer, expectedAudience, customErrorFunction) {
108
+ const jwtString = _validateJwt(req, customErrorFunction);
109
+ const isJwtSignatureValid = jwtVerifySignedToken(jwtString, publicKey);
110
+
111
+ if (jwtString && isJwtSignatureValid) {
112
+ _extractJwtObject(req, jwtString, customErrorFunction);
113
+ } else if (req) {
114
+ req.jwt = null;
115
+ }
116
+
117
+ if (!req?.jwt || !_isServiceJwtFor(req.jwt.payload, expectedIssuer, expectedAudience)) {
118
+ if (req) req.jwt = null;
119
+ throwError(customErrorFunction);
120
+ }
121
+
122
+ return req;
123
+ }
124
+
107
125
  function validateAndExtractWebTokenObjectNoThrow(req, publicKey, headerName) {
108
126
  return _validateAndExtractGenericNoThrow(req, publicKey, r => _validateWebTokenNoThrow(r, headerName), _extractJwtObjectNoThrow, 'jwt');
109
127
  }
@@ -136,6 +154,17 @@ function verifyJwt(publicKey, customErrorFunction) {
136
154
  };
137
155
  }
138
156
 
157
+ function verifyServiceJwt(publicKey, expectedIssuer, expectedAudience, customErrorFunction) {
158
+ return function (req, res, next) {
159
+ try {
160
+ validateAndExtractServiceJwtObject(req, publicKey, expectedIssuer, expectedAudience, customErrorFunction);
161
+ next();
162
+ } catch (err) {
163
+ next(err);
164
+ }
165
+ };
166
+ }
167
+
139
168
  function verifyWebToken(publicKey, headerName, customErrorFunction) {
140
169
  return function (req, res, next) {
141
170
  try {
@@ -193,6 +222,48 @@ function _isLoginRequired(hasRequiredRole, customErrorFunction) {
193
222
  }
194
223
  }
195
224
 
225
+ function normalizeSeconds(value) {
226
+ if (!Number.isFinite(value)) return null;
227
+ return value > 1000000000000 ? Math.floor(value / 1000) : Math.floor(value);
228
+ }
229
+
230
+ function _isServiceJwtFor(payload, expectedIssuer, expectedAudience) {
231
+ if (!payload) return false;
232
+ if (payload.iss !== expectedIssuer) return false;
233
+ if (payload.sub !== expectedIssuer) return false;
234
+ if (!payloadAudienceMatches(payload.aud, expectedAudience)) return false;
235
+ if (isJwtPayloadIssuedInFuture(payload)) return false;
236
+ if (isJwtPayloadExpired(payload)) return false;
237
+ if (isJwtPayloadNotYetValid(payload)) return false;
238
+ return true;
239
+ }
240
+
241
+ function payloadAudienceMatches(actualAudience, expectedAudience) {
242
+ if (Array.isArray(actualAudience)) return actualAudience.includes(expectedAudience);
243
+ return actualAudience === expectedAudience;
244
+ }
245
+
246
+ function isJwtPayloadExpired(payload) {
247
+ if (!payload.exp) return true;
248
+ const exp = normalizeSeconds(payload.exp);
249
+ if (!Number.isInteger(exp)) return true;
250
+ return Math.floor(Date.now() / 1000) >= exp;
251
+ }
252
+
253
+ function isJwtPayloadIssuedInFuture(payload) {
254
+ if (!payload.iat) return true;
255
+ const iat = normalizeSeconds(payload.iat);
256
+ if (!Number.isInteger(iat)) return true;
257
+ return Math.floor(Date.now() / 1000) < iat;
258
+ }
259
+
260
+ function isJwtPayloadNotYetValid(payload) {
261
+ if (!payload.nbf) return false;
262
+ const nbf = normalizeSeconds(payload.nbf);
263
+ if (!Number.isInteger(nbf)) return true;
264
+ return Math.floor(Date.now() / 1000) < nbf;
265
+ }
266
+
196
267
  function _validateGenericNoThrow(req, headerName, extractor) {
197
268
  let jwtRaw = req.get(headerName);
198
269
  if (!jwtRaw) return null;
@@ -362,6 +433,7 @@ module.exports = {
362
433
  _isJwtSignatureValidNoThrow,
363
434
  _extractJwtObject,
364
435
  validateAndExtractJwtObject,
436
+ validateAndExtractServiceJwtObject,
365
437
  validateAndExtractWebToken,
366
438
  jwtAgeInSeconds,
367
439
  isJwtExpired,
@@ -369,6 +441,7 @@ module.exports = {
369
441
  jwtClientId,
370
442
  visitorClientId,
371
443
  verifyJwtAndRole,
444
+ verifyServiceJwt,
372
445
  verifyJwt,
373
446
  verifyWebTokenNoThrow,
374
447
  verifyWebToken,
@@ -388,6 +461,7 @@ module.exports = {
388
461
  _extractVisitorObjectNoThrow,
389
462
  _extractWebToken,
390
463
  _isLoginRequired,
464
+ _isServiceJwtFor,
391
465
  _attachJwtMethods,
392
466
  _attachVisitorMethods,
393
467
  _validateWebToken,