@carecard/jwt-read 3.1.14 → 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.
@@ -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,261 @@
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, JWT-or-server-auth authorization middleware, exports, and tests.
11
+
12
+ ## When To Use
13
+
14
+ - Use when changing pkg-jwt-read JWT parsing, server-auth introspection
15
+ middleware, visitor tokens, role checks, auth context, package exports, or
16
+ tests.
17
+ - Pair with `carecard-workspace-standards` when the task affects shared CareCard conventions or cross-repository contracts.
18
+
19
+ ## When Not To Use
20
+
21
+ - Do not use for service-local behavior that should remain inside one API or app.
22
+ - Do not change package public APIs without updating consumers and compatibility tests.
23
+
24
+ ## Relevant Files And Directories
25
+
26
+ - package entry files
27
+ - `src` when present
28
+ - `test`
29
+ - `package.json`
30
+ - `package-lock.json`
31
+ - `.husky`
32
+
33
+ ## Coding Principles
34
+
35
+ - Preserve the repository structure, naming style, module system, and local helper patterns.
36
+ - Prefer readable, maintainable code with meaningful function, variable, file, and test names.
37
+ - Avoid new dependencies unless the existing stack cannot reasonably solve the task and the user confirms the tradeoff.
38
+ - Keep public exports stable and update CommonJS, ESM, TypeScript declaration, and compatibility surfaces together when present.
39
+
40
+ ## Testing Expectations
41
+
42
+ - Write or update package tests before behavior or public API changes.
43
+ - Include type/export compatibility tests where the package already has them.
44
+ - Run package test, lint, type, and Husky validation commands required by the changed area.
45
+
46
+ ## Safety Constraints
47
+
48
+ - Do not edit generated output, dependency folders, logs, coverage, dist, or build artifacts unless the task explicitly requires it.
49
+ - Do not revert or overwrite user changes; stage only files related to the requested skill or instruction update.
50
+ - Never suppress errors, lint failures, type failures, security failures, or failing tests; fix the underlying issue or report the blocker.
51
+ - Do not log or expose secrets, JWTs, passwords, credentials, private keys, sensitive personal data, SQL internals, or stack traces.
52
+
53
+ ## Overview
54
+
55
+ Use this skill when working inside `pkg-jwt-read`, the `@carecard/jwt-read`
56
+ package. It provides utilities for reading, parsing, verifying, and attaching
57
+ JWT data in the CareCard ecosystem. It depends on `@carecard/auth-util` for
58
+ low-level cryptographic operations. It also exposes middleware helpers that
59
+ allow `ms-*` services to accept either an `ms-auth` JWT or an opaque server-auth
60
+ token introspected by `ms-auth`.
61
+
62
+ Use `$carecard-workspace-standards` for shared workspace, dependency, package,
63
+ testing, and security rules. Legacy `pkg-jwt-read/.codex` and
64
+ `pkg-jwt-read/.junie` guidance has been migrated into these skills; do not
65
+ depend on those folders being present.
66
+
67
+ ## Non-Negotiable Rules
68
+
69
+ - Never use TypeScript type `any`. Use specific JWT, Express, request, payload,
70
+ header, role, generic, or `unknown` types with narrowing.
71
+ - Follow this repository's coding style, naming conventions, and CommonJS
72
+ project structure.
73
+ - Use Test-Driven Development: add or update relevant Mocha or type tests before
74
+ changing behavior.
75
+ - Never suppress errors, linter warnings, TypeScript errors, or failing tests.
76
+ Handle the underlying issue.
77
+ - Do not add dependencies unless absolutely needed. Ask for confirmation first
78
+ with the reason and tradeoff.
79
+ - Before finalizing work, run every direct script in `.husky` and fix anything
80
+ they report.
81
+
82
+ ## Package Shape
83
+
84
+ - Keep `index.js` as the centralized public export surface.
85
+ - Keep TypeScript declarations in `index.d.ts` aligned with every public export
86
+ in `index.js`.
87
+ - Keep JWT verification and request attachment behavior in `lib/jwtLib.js`.
88
+ - Keep role code/name mapping and JWT context behavior in `lib/jwtRoles.js`.
89
+ - Preserve the package's CommonJS module style unless the repository is
90
+ intentionally migrated.
91
+ - Keep backward-compatible deprecated exports unless the user explicitly asks to
92
+ remove them.
93
+
94
+ ## JWT Verification Layer
95
+
96
+ `lib/jwtLib.js` owns:
97
+
98
+ - Signature verification using public keys.
99
+ - Middleware-like functions for Express, such as `verifyJwtAndRole`.
100
+ - Service-to-service JWT verification and extraction helpers:
101
+ `jwtValidateAndExtractService` and `jwtVerifyService`.
102
+ - JWT-or-server-auth helpers: `jwtValidateAndExtractOrServerAuth`,
103
+ `jwtVerifyOrServerAuth`, and `jwtVerifyOrServerAuthAndHasRole`.
104
+ - Extraction of `sub`/clientId and other claims from JWT objects.
105
+ - Expiration checks and TTL calculations.
106
+ - Request attachment behavior for authenticated JWT objects and visitor tokens.
107
+ - Server-auth request attachment behavior that normalizes introspected claims
108
+ into `req.jwt.payload` with `authMode: "server-auth"` and
109
+ `auth_mode: "server-auth"`.
110
+ - Integration with `@carecard/common-util` for standardized login and
111
+ authorization errors.
112
+
113
+ Use `@carecard/auth-util` for JWT creation, decomposition, and signature
114
+ verification. Do not duplicate cryptographic logic in this package.
115
+
116
+ JWT creation functions do not belong in this package. Service-to-service token
117
+ creation belongs in `@carecard/auth-util` via `jwtCreateServiceToken` and
118
+ `jwtCreateServiceAuthorizationHeader`.
119
+
120
+ Opaque server-auth token creation, hashing, persistence, and introspection
121
+ belong in `ms-auth`. This package only accepts a caller-provided introspector
122
+ function and normalizes valid introspection claims into the existing request
123
+ JWT context.
124
+
125
+ Service JWTs must follow standard JWT claim semantics. They use `iss` for the
126
+ sending service, `sub` for the sending service identity, `aud` for the
127
+ receiving service, and NumericDate `iat`, `exp`, and optional `nbf` claims.
128
+ Receivers must verify the signature with the sending service public key and
129
+ must check expected issuer, audience, subject, and lifetime. Do not add
130
+ CareCard-specific replacement claims when a registered JWT claim covers the
131
+ same meaning.
132
+
133
+ ## Role Mapping Layer
134
+
135
+ `lib/jwtRoles.js` owns translation between internal role codes and human-readable
136
+ role names, such as `ad` and `admin`.
137
+
138
+ - Update `lib/jwtRoles.js` when adding or changing roles.
139
+ - Keep role code, role name, context, and authorization helper behavior covered
140
+ by focused tests.
141
+ - Preserve existing role semantics unless a task explicitly changes
142
+ authorization behavior.
143
+ - Preserve the original JWT `roles` array on request context. `ms-auth` RLS
144
+ treats a payload containing `ad` as the auth-service super-admin signal;
145
+ dashboard code may map that to `super_admin`, but middleware must not hide,
146
+ rename, or drop the raw role payload needed by backend database contexts.
147
+
148
+ ## NoThrow And Error Behavior
149
+
150
+ - Preserve the distinction between throwing APIs and `NoThrow` APIs.
151
+ - `NoThrow` variants should set the attached request property to `null` for
152
+ invalid tokens without hiding unexpected implementation errors.
153
+ - Use provided `throwError` and `throwUsedTokenError` patterns to keep
154
+ ecosystem error responses consistent.
155
+ - Use `@carecard/common-util` error helpers for login and authorization
156
+ failures.
157
+ - Keep user-facing errors safe and avoid exposing token internals or
158
+ verification details.
159
+
160
+ ## Security Rules
161
+
162
+ - Treat JWT parsing, signature verification, server-auth introspection,
163
+ visitor tokens, authorization roles, and request context as
164
+ security-sensitive.
165
+ - Do not log JWTs, token fragments, public/private keys, decoded payloads,
166
+ authorization headers, visitor headers, or sensitive request data.
167
+ - Keep missing headers, invalid signatures, expired tokens, revoked or invalid
168
+ server-auth tokens, role failures, and used-token errors behaviorally
169
+ distinct where existing APIs do so.
170
+
171
+ ## Types And API Contracts
172
+
173
+ - Model JWT header, payload, server-auth introspection claims, request
174
+ attachment, visitor attachment, role, and context shapes explicitly in
175
+ `index.d.ts`.
176
+ - Prefer `AuthenticatedRequest`, `JwtHeader`, `JwtPayload`, `JwtParts`,
177
+ `JwtRequestObject`, `VisitorRequestObject`, and `JwtContext` over loose
178
+ request objects.
179
+ - When existing declarations are too loose, improve them with specific types as
180
+ part of the touched change instead of adding new loose types.
181
+ - Keep overloads for context-bound helpers such as `jwtIsExpired` readable and
182
+ covered by type tests.
183
+ - Update `test/types.test.ts` whenever public types, exports, overloads, or
184
+ attached request methods change.
185
+
186
+ ## Tests
187
+
188
+ - Use Mocha for runtime tests under `test`.
189
+ - `lib` modules should have corresponding test files under `test`.
190
+ - `test/attachedMethods.test.js` covers methods attached to objects or used as
191
+ context.
192
+ - `test/types.test.ts` verifies TypeScript declarations with `tsc`.
193
+ - Add focused tests for valid JWTs, invalid JWTs, missing headers, role checks,
194
+ visitor token extraction, expiration behavior, request attachment behavior,
195
+ server-auth introspection success/failure, NoThrow behavior, and
196
+ context-bound helpers when those areas change.
197
+ - Set `NODE_ENV=test` where tests or scripts require it.
198
+ - Keep tests deterministic and avoid real external services.
199
+
200
+ ## Validation
201
+
202
+ Useful commands:
203
+
204
+ - `npm run lint`
205
+ - `npm run lint:fix`
206
+ - `npm run format`
207
+ - `npm run format:check`
208
+ - `npm run test`
209
+ - `npm run test:types`
210
+ - `npm run test:coverage`
211
+ - `npm run test:All`
212
+
213
+ Before pushing or finalizing, run every direct `.husky` script. The current
214
+ `.husky/pre-commit` runs:
215
+
216
+ ```bash
217
+ npm run lint:fix
218
+ npm run format
219
+ npm run test:All
220
+ ```
221
+
222
+ If any validation command cannot run, report the exact command, failure reason,
223
+ and remaining risk.
224
+
225
+ ## Remote Git Operations Guardrail
226
+
227
+ 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.
228
+
229
+ ## Agent Guidance Git Workflow
230
+
231
+ When this skill or any repository-owned `.agents` guidance changes, use the
232
+ repository's agents-only Git workflow:
233
+
234
+ 1. Work from the affected repository root and confirm only intended `.agents`
235
+ files changed.
236
+ 2. Use `development` as the base branch when `origin/development` exists;
237
+ otherwise use the repository's default base branch, usually `main`.
238
+ 3. Create or update `feature/codex` from the updated remote base branch and
239
+ commit all the changed `.agents` guidance files there.
240
+ 4. Push `feature/codex`, create or reuse a pull request into the base branch,
241
+ and mark the pull request ready for review with `gh pr ready <number>`.
242
+ 5. Squash-merge with administrator privileges and delete the remote branch:
243
+
244
+ ```sh
245
+ gh pr merge <number> --squash --admin --delete-branch
246
+ ```
247
+
248
+ 6. After merge, update the local base branch and remove the local feature
249
+ branch:
250
+
251
+ ```sh
252
+ git fetch origin <base> --prune
253
+ git switch <base>
254
+ git pull --ff-only origin <base>
255
+ git branch -d feature/codex
256
+ git ls-remote --heads origin feature/codex
257
+ ```
258
+
259
+ Do not commit or push `.agents` guidance changes directly from `development`
260
+ or `main`. Do not stage unrelated files, generated output, dependency folders,
261
+ 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.
@@ -32,6 +32,10 @@ export interface JwtPayload {
32
32
  sub?: string;
33
33
  /** Roles assigned to the user. */
34
34
  roles?: string[];
35
+ /** Authentication mode used by app-facing services. */
36
+ authMode?: 'jwt' | 'server-auth' | string;
37
+ /** Server-auth session identifier when an opaque server-auth token was used. */
38
+ sessionId?: string;
35
39
  /** Any other custom payload fields. */
36
40
  [key: string]: any;
37
41
  }
@@ -76,6 +80,30 @@ export interface AuthenticatedRequest extends Request {
76
80
  visitor?: VisitorRequestObject | null;
77
81
  }
78
82
 
83
+ export interface ServerAuthIntrospectionClaims {
84
+ valid?: boolean;
85
+ sub?: string;
86
+ userId?: string;
87
+ user_id?: string;
88
+ email?: string;
89
+ emailVerified?: boolean;
90
+ email_verified?: boolean;
91
+ emailConfirmed?: boolean;
92
+ email_confirmed?: boolean;
93
+ roles?: string[];
94
+ sessionId?: string;
95
+ session_id?: string;
96
+ exp?: number | string;
97
+ expiresAt?: string;
98
+ expires_at?: string;
99
+ [key: string]: any;
100
+ }
101
+
102
+ export type ServerAuthIntrospector = (
103
+ token: string,
104
+ req: AuthenticatedRequest,
105
+ ) => Promise<ServerAuthIntrospectionClaims> | ServerAuthIntrospectionClaims;
106
+
79
107
  /**
80
108
  * Returns a middleware that verifies a JWT from the 'Authorization: Bearer <token>' header
81
109
  * and extracts it into req.jwt. Throws an error if invalid.
@@ -147,6 +175,27 @@ export function jwtVerifyAndHasRole(
147
175
  customErrorFunction?: () => void,
148
176
  ): (req: AuthenticatedRequest, res: Response, next: NextFunction) => void;
149
177
 
178
+ /**
179
+ * Returns middleware that accepts either an ms-auth JWT or an opaque server-auth token.
180
+ * Server-auth tokens are validated by the supplied introspector on every request.
181
+ */
182
+ export function jwtVerifyOrServerAuth(
183
+ publicKey: string,
184
+ serverAuthIntrospector: ServerAuthIntrospector,
185
+ customErrorFunction?: () => void,
186
+ ): (req: AuthenticatedRequest, res: Response, next: NextFunction) => void;
187
+
188
+ /**
189
+ * Returns middleware that accepts either an ms-auth JWT or server-auth token and
190
+ * then checks that the authenticated user has the required role.
191
+ */
192
+ export function jwtVerifyOrServerAuthAndHasRole(
193
+ userRole: string,
194
+ publicKey: string,
195
+ serverAuthIntrospector: ServerAuthIntrospector,
196
+ customErrorFunction?: () => void,
197
+ ): (req: AuthenticatedRequest, res: Response, next: NextFunction) => void;
198
+
150
199
  /**
151
200
  * Gets the full name of a role from its code (e.g., 'ad' -> 'admin').
152
201
  */
@@ -178,6 +227,28 @@ export function jwtGetContext(req: any): JwtContext;
178
227
  */
179
228
  export function jwtValidateAndExtract(req: AuthenticatedRequest, publicKey: string, customErrorFunction?: () => void): void;
180
229
 
230
+ /**
231
+ * Validates a service-to-service JWT from the Authorization header and extracts it into req.jwt.
232
+ */
233
+ export function jwtValidateAndExtractService(
234
+ req: AuthenticatedRequest,
235
+ publicKey: string,
236
+ expectedIssuer: string,
237
+ expectedAudience: string,
238
+ customErrorFunction?: () => void,
239
+ ): void;
240
+
241
+ /**
242
+ * Validates the Authorization header as either an ms-auth JWT or an opaque
243
+ * server-auth token and extracts the result into req.jwt.
244
+ */
245
+ export function jwtValidateAndExtractOrServerAuth(
246
+ req: AuthenticatedRequest,
247
+ publicKey: string,
248
+ serverAuthIntrospector: ServerAuthIntrospector,
249
+ customErrorFunction?: () => void,
250
+ ): Promise<void>;
251
+
181
252
  /**
182
253
  * Validates the JWT from a custom header and extracts it into req.jwt.
183
254
  */
@@ -203,6 +274,16 @@ export function jwtValidateAndExtractWebTokenNoThrow(req: AuthenticatedRequest,
203
274
  */
204
275
  export function jwtValidateAndExtractVisitorNoThrow(req: AuthenticatedRequest, publicKey: string): void;
205
276
 
277
+ /**
278
+ * Returns middleware that verifies a service-to-service JWT from one expected sender.
279
+ */
280
+ export function jwtVerifyService(
281
+ publicKey: string,
282
+ expectedIssuer: string,
283
+ expectedAudience: string,
284
+ customErrorFunction?: () => void,
285
+ ): (req: AuthenticatedRequest, res: Response, next: NextFunction) => void;
286
+
206
287
  /**
207
288
  * Returns a middleware that verifies a JWT from the 'Authorization: Bearer <token>' header
208
289
  * and extracts it into req.jwt. Throws an error if invalid.
package/index.js CHANGED
@@ -16,10 +16,15 @@ module.exports = {
16
16
  jwtGetRoleCode: jwtRoles.getCodeFromNameOfRole,
17
17
  jwtGetContext: jwtRoles.getContext,
18
18
  jwtValidateAndExtract: jwtLib.validateAndExtractJwtObject,
19
+ jwtValidateAndExtractService: jwtLib.validateAndExtractServiceJwtObject,
20
+ jwtValidateAndExtractOrServerAuth: jwtLib.validateAndExtractJwtOrServerAuthObject,
19
21
  jwtValidateAndExtractWebToken: jwtLib.validateAndExtractWebToken,
20
22
  jwtValidateAndExtractNoThrow: jwtLib.validateAndExtractJwtObjectNoThrow,
21
23
  jwtValidateAndExtractWebTokenNoThrow: jwtLib.validateAndExtractWebTokenObjectNoThrow,
22
24
  jwtValidateAndExtractVisitorNoThrow: jwtLib.validateAndExtractVisitorObjectNoThrow,
25
+ jwtVerifyService: jwtLib.verifyServiceJwt,
26
+ jwtVerifyOrServerAuth: jwtLib.verifyJwtOrServerAuth,
27
+ jwtVerifyOrServerAuthAndHasRole: jwtLib.verifyJwtOrServerAuthAndHasRole,
23
28
 
24
29
  /** @deprecated use jwtVerify */
25
30
  verifyJwt: jwtLib.verifyJwt,