@carecard/auth-util

中文文档
3.45.0发布于 2026/11/03ISCTypeScriptCommonJS构建来源已验证近 30 天下载 3448

Auth utility functions

原始使用文档
文档目录14 节
  1. Release 1.1.1 and production data
  2. Development Rule
  3. Features
  4. Installation
  5. Usage
  6. JWT Utilities ( jwtUtilAuth )
  7. Service-To-Service JWT Creation
  8. Password Utilities
  9. String Utilities ( stringUtilAuth )
  10. Opaque custom claims
  11. Testing
  12. Architecture
  13. Fail-Closed Test Lifecycle Audit
  14. TDD And Validation

@carecard/auth-util

Release 1.1.1 and production data

CareCard Release 1.1.1 is the production baseline. Seeding with --seed-release-data is complete. Production cluster data, database rows, and stored user files will be preserved going forward. There will be no complete user-data wipeout and re-creation.

Future production changes must use data-preserving migrations. Do not replay the completed initialization or run reset, rollback, or seed workflows as part of ordinary production deployment.

The completed seed inventory and verification record documents the accepted release baseline and verification limitations.

Non-negotiable test order invariance rule: Every test must pass independently of which tests run before or after it, and the suite must pass in every execution order. Each test must establish the state it needs, isolate mutable state, and clean up state it owns; it must never rely on another test's setup, mutations, or cleanup. Default test, CI, and Husky commands must use the test framework's ordinary ordering and must not force randomized ordering. Random-order execution is an explicit diagnostic only, and every failure it exposes must be fixed at the root cause.

Non-negotiable root-cause solution rule: Always identify and solve the verified root cause, use the stronger solution, and deliver a correct, durable, production-quality result. Never treat a temporary workaround, resource increase, retry, suppression, bypass, or symptom-only patch as completion. Validate the root-cause fix against the real failing workflow and prove the end state.

Tests Passing Coverage

Utility package for authentication and authorization in the CareCard ecosystem.

Development Rule

Non-negotiable TDD rule: Always write the failing test first, run it to confirm it fails for the intended reason, then implement the code and rerun the test until it passes. Test Driven Development is required for all coding work and must not be skipped. For documentation- or skill-only edits, run the relevant focused non-test validation before changing the prose; do not add automated tests that inspect prose, files, or repository structure.

Non-negotiable repository isolation rule: Every repository must run its Husky hooks and tests using only files, code, fixtures, dependencies, and services contained within that repository. Tests and Husky scripts must not import, require, read, execute, or otherwise depend on sibling repositories or paths outside the repository root. app-e2e-tests is the only exception because cross-repository end-to-end testing is its explicit responsibility.

Non-negotiable error and warning rule: Never suppress, silence, hide, downgrade, filter, ignore, skip, or bypass errors or warnings from code, tests, tools, compilers, linters, or validation. Fix the root cause, then rerun the affected check and require a clean result. Expected error-path tests may assert errors, but must not conceal unexpected failures.

Non-negotiable TypeScript type rule: Never use the TypeScript type any; always use specific domain types, generics, existing project types, or unknown with explicit narrowing in all TypeScript-family files (.ts, .tsx, .mts, .cts, and .d.ts).

Non-negotiable code organization rule: Functions with the same or equivalent behavior must use the same or clearly corresponding descriptive names across CareCard repositories, and equivalent functionality must live in files with the same names within each repository's established architecture. No backward compatibility names, aliases, or duplicate locations are allowed.

Features

  • JWT Utilities: Create and verify EdDSA JWTs through strict Ed25519 JWK and JWKS configuration.
  • Password Utilities: Rotate versioned Argon2id password peppers while preserving a strict saved-credential format.
  • Crypto Utilities: Low-level cryptographic primitives for signing, verification, and hashing.
  • String Utilities: Base64 and Base64UrlSafe encoding/decoding, and custom string parsing.

Installation

npm install @carecard/auth-util

Usage

JWT Utilities (jwtUtilAuth)

const {
  jwtCreateSignedToken,
  jwtGetHeaderPayload,
  jwtVerifySignedToken,
  parseJwtSigningJwk,
  parseJwtVerificationJwks,
} = require('@carecard/auth-util');

const payload = { sub: '1234567890', name: 'John Doe' };
const signingJwk = parseJwtSigningJwk(process.env.JWT_SIGNING_JWK);
const verificationJwks = parseJwtVerificationJwks(process.env.JWT_VERIFICATION_JWKS);

const token = jwtCreateSignedToken(payload, signingJwk);

const isValid = jwtVerifySignedToken(token, verificationJwks);

// Get header and payload from a JWT
const { header: decodedHeader, payload: decodedPayload } = jwtGetHeaderPayload(token);

Service-To-Service JWT Creation

const {
  jwtCreateServiceAuthorizationHeader,
  jwtCreateServiceToken,
} = require('@carecard/auth-util');

const token = jwtCreateServiceToken({
  issuer: 'worker',
  audience: 'receiver',
  signingJwk: institutionsSigningJwk,
});

const authorization = jwtCreateServiceAuthorizationHeader({
  issuer: 'worker',
  audience: 'receiver',
  signingJwk: institutionsSigningJwk,
});

Password Utilities

const {
  createPasswordCredential,
  parsePasswordHashKeyring,
  verifyPasswordCredential,
} = require('@carecard/auth-util');

const password = 'correct horse battery staple';
const keyring = parsePasswordHashKeyring(
  process.env.MS_AUTH_PASSWORD_HASH_ACTIVE_KEY_ID,
  process.env.MS_AUTH_PASSWORD_HASH_KEYRING,
);

const credential = await createPasswordCredential(password, keyring);

const result = await verifyPasswordCredential(password, credential, keyring);
if (result.isValid && result.needsRehash) {
  const replacement = await createPasswordCredential(password, keyring);
  // Persist replacement.hash and replacement.hashKeyId atomically.
}

Keyring entries use key-id:canonical-base64-32-byte-key, separated by commas. Credential rows persist both the PHC hash and its hashKeyId; pepper keys stay outside persisted credentials and logs. Passwords trim edge whitespace and normalize well-formed Unicode to NFC, preserving internal spaces. @carecard/validate owns password policy. Signed token verification and decomposition trim outer whitespace without rewriting signed token contents.

JWT signing configuration is one strict private Ed25519 JWK. Verification configuration is an RFC 7517 JWKS containing one or more public Ed25519 JWKs. Every key uses alg: "EdDSA", use: "sig", one exact key_ops operation, and an RFC 7638 SHA-256 thumbprint kid. Add replacement public keys before switching signers, and retain retiring public keys for the maximum token lifetime plus clock skew.

String Utilities (stringUtilAuth)

const { stringUtilAuth } = require('@carecard/auth-util');

const base64 = stringUtilAuth.asciiToBase64('Hello World');
const original = stringUtilAuth.base64ToAscii(base64);

const urlSafe = stringUtilAuth.makeStringUrlSafe('a+b/c==');
// Result: a-b_c

Opaque custom claims

Signing and verification preserve caller-supplied custom claims without interpreting their names, values, or authority. Authorization, database caller contexts, and application claim contracts belong to their owners. Password hashing handles canonical bytes and credential formats; acceptance policy belongs to the caller.

Testing

Run tests using:

npm test

To run type tests:

npm run test:types

Architecture

The package is organized into several modules:

  • jwkUtilAuth: Strictly parses private signing JWKs and public verification JWKS values.
  • jwtUtilAuth: Creates fixed-header Ed25519 JWTs and verifies signatures by kid.
  • pwdUtilAuth: Creates and verifies versioned Argon2id password credentials.
  • cryptoUtilAuth: Core cryptographic operations using Node.js crypto module.
  • stringUtilAuth: String manipulation and format conversions.

All modules are exported through the main index.js.

Fail-Closed Test Lifecycle Audit

The current package tests own no HTTP listener, database pool, Kafka client, background timer, or child process after completion. Mocha's test timeout fails a stalled async test, the suites run without bail or forced exit, and npm preserves each command's nonzero status. Keep natural process exit as the open handle regression check; validation must not hide failures with retries, forced success, skipped tests, or output suppression.

Do not add unpublished executable validation code to a pkg-* repository. If a future test owns a long-lived resource or demonstrates a post-suite hang, add a contract-tested process watchdog through the coordinated package version, publish, and consumer propagation workflow. That watchdog must return immediately when no helper remains, allow only a bounded 250 ms settlement window for already-stopping helpers, fail persistent descendants, preserve failures and output, use exit code 124 only for a real outer deadline, and remain a final guard rather than a substitute for explicit cleanup.

TDD And Validation

Test Driven Development is a non-negotiable requirement.

The sole purpose of automated tests is to verify observable functionality and externally visible behavior. Tests must validate what the system does through its public interfaces and expected outcomes.

Tests must not assert, inspect, or depend on implementation details, including but not limited to:

  • The existence of specific lines of code, statements, functions, classes, files, or modules.
  • Specific algorithms, control flow, variable names, method calls, code snippets, or internal implementation choices.
  • Any internal structure that can change without changing externally observable behavior.

A correct implementation may be completely rewritten or refactored without requiring changes to functional tests, provided its externally observable behavior remains unchanged.

Any test that fails solely because the implementation changed while the externally observable behavior remained correct is incorrectly designed and must be rewritten or removed.

This requirement is mandatory for all new tests and must be applied whenever existing tests are modified.

版本与发布记录

@carecard/auth-util 共发布 59 个版本,首次发布于 2025/12/24;过去 12 个月发布了 59 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
3.45.0latest2026/11/036 天前
3.44.02026/10/1327 天前
3.43.02026/10/1327 天前
3.42.02026/10/1327 天前
3.41.02026/10/1227 天前
3.40.02026/10/1228 天前

关于 @carecard/auth-util 的常见问题

@carecard/auth-util 是什么?

Auth utility functions

如何安装 @carecard/auth-util?

在项目目录运行 npm install @carecard/auth-util,或使用 pnpm add / yarn add / bun add。

@carecard/auth-util 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@carecard/auth-util 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@carecard/auth-util 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24.21.0 <25。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@carecard/auth-util 可以商用吗?

@carecard/auth-util 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@carecard/auth-util 的下载量有多少?

根据 npm 官方下载统计,@carecard/auth-util 在 2026/10/09 – 2026/11/07 这 30 天内被下载 3,448 次,日均约 115 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@carecard/auth-util 还在维护吗?

最新版本 3.45.0 发布于 2026/11/03(6 天前);至今共发布 59 个版本,其中过去 12 个月发布了 59 个;首次发布于 2025/12/24。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。