@h-ai/crypto 0.1.0-alpha9 → 1.0.0-beta.1

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.
package/README.en.md ADDED
@@ -0,0 +1,320 @@
1
+ # @h-ai/crypto
2
+
3
+ [简体中文](./README.md) | [English](./README.en.md) | [日本語](./README.ja.md)
4
+
5
+ [Framework home](../../README.en.md) · Related modules: [@h-ai/cache](../cache/README.en.md) · [@h-ai/core](../core/README.en.md) · [@h-ai/reldb](../reldb/README.en.md)
6
+
7
+ ## Introduction
8
+
9
+ A cryptography module for asymmetric encryption, hashing, symmetric encryption, and password hashing.
10
+
11
+ ## Core features
12
+
13
+ - Asymmetric cryptography (key generation, encryption/decryption, signing/verification)
14
+ - Hashing (hash, HMAC, verification)
15
+ - Symmetric encryption (ECB/CBC modes)
16
+ - Password hashing (salted iterative hashes)
17
+ - Transport encryption (`crypto.transport`: server manager + client `encryptedFetch`)
18
+ - Shared server/browser support (Node.js / browser)
19
+
20
+ ## Getting started
21
+
22
+ ### Security notice
23
+
24
+ - **SM4 encryption returns a structured payload by default**: `crypto.symmetric.encrypt(data, key)` uses CBC + a random IV by default and returns `{ mode, ciphertext, iv, encoding }`. Pass that object to `crypto.symmetric.decrypt(payload, key)` to decrypt.
25
+ - **Use random SM4 keys**: generate keys with `crypto.symmetric.generateKey()`. This module does not provide a KDF for password-based encryption keys. Store passwords with the server-only `crypto.password.hash(password)`; do not use passwords or password hashes directly as SM4 keys.
26
+ - **IVs must be unique**: never reuse an IV with the same key. Prefer default CBC or `encryptWithIV()` to generate one for each call. Transmit and store the IV with the ciphertext; the IV can be public.
27
+
28
+ ### Quick start
29
+
30
+ ```ts
31
+ import { crypto } from '@h-ai/crypto'
32
+
33
+ // 初始化(使用前必须调用)
34
+ const initialized = await crypto.init()
35
+ if (!initialized.success)
36
+ throw new Error(initialized.error.message)
37
+ ```
38
+
39
+ #### Asymmetric cryptography (encryption / signing)
40
+
41
+ ```ts
42
+ // 生成密钥对
43
+ const keyPair = crypto.asymmetric.generateKeyPair()
44
+ if (!keyPair.success)
45
+ throw new Error(keyPair.error.message)
46
+ const { publicKey, privateKey } = keyPair.data
47
+
48
+ // 加密 / 解密
49
+ const encrypted = crypto.asymmetric.encrypt('Hello', publicKey)
50
+ if (encrypted.success) {
51
+ const decrypted = crypto.asymmetric.decrypt(encrypted.data, privateKey)
52
+ // decrypted.data === 'Hello'
53
+ }
54
+
55
+ // 输出 base64 格式密文
56
+ const b64 = crypto.asymmetric.encrypt('Hello', publicKey, { outputFormat: 'base64' })
57
+
58
+ // 签名 / 验签
59
+ const sig = crypto.asymmetric.sign('important data', privateKey)
60
+ if (sig.success) {
61
+ const valid = crypto.asymmetric.verify('important data', sig.data, publicKey)
62
+ // valid.data === true
63
+ }
64
+
65
+ // 校验密钥格式
66
+ crypto.asymmetric.isValidPublicKey(publicKey) // true
67
+ crypto.asymmetric.isValidPrivateKey(privateKey) // true
68
+ ```
69
+
70
+ #### Hashing (Hash / HMAC / verification)
71
+
72
+ ```ts
73
+ // 字符串哈希
74
+ const hash = crypto.hash.hash('Hello!')
75
+ // hash.data → 64 字符十六进制哈希值
76
+
77
+ // Uint8Array 输入
78
+ const buf = new TextEncoder().encode('Hello!')
79
+ const hashBuf = crypto.hash.hash(buf)
80
+
81
+ // 十六进制编码输入
82
+ const hashHex = crypto.hash.hash('48656c6c6f21', { inputEncoding: 'hex' })
83
+
84
+ // HMAC
85
+ const hmac = crypto.hash.hmac('message', 'secret-key')
86
+
87
+ // 验证哈希是否匹配
88
+ if (hash.success) {
89
+ const matched = crypto.hash.verify('Hello!', hash.data)
90
+ // matched.data === true
91
+ }
92
+ ```
93
+
94
+ #### Symmetric encryption (default CBC / structured payload)
95
+
96
+ ```ts
97
+ // 生成随机密钥和 IV
98
+ const key = crypto.symmetric.generateKey()
99
+ const iv = crypto.symmetric.generateIV()
100
+
101
+ // 默认:CBC + 自动随机 IV,返回结构化密文
102
+ const safeEnc = crypto.symmetric.encrypt('data', key)
103
+ if (safeEnc.success) {
104
+ // safeEnc.data: { mode: 'cbc', ciphertext, iv, encoding: 'hex' }
105
+ const safeDec = crypto.symmetric.decrypt(safeEnc.data, key)
106
+ // safeDec.data === 'data'
107
+ }
108
+
109
+ // CBC 指定 IV(仍然返回结构化密文)
110
+ const cbcEnc = crypto.symmetric.encrypt('data', key, { mode: 'cbc', iv })
111
+ if (cbcEnc.success) {
112
+ const cbcDec = crypto.symmetric.decrypt(cbcEnc.data, key)
113
+ }
114
+
115
+ // 结构化结果:自动生成 IV 的 CBC 加解密
116
+ const withIV = crypto.symmetric.encryptWithIV('data', key)
117
+ if (withIV.success) {
118
+ const dec = crypto.symmetric.decryptWithIV(withIV.data.ciphertext, key, withIV.data.iv)
119
+ }
120
+
121
+ // ECB 模式(❌ 不安全;只有底层协议明确要求时才显式指定)
122
+ const ecbEnc = crypto.symmetric.encrypt('data', key, { mode: 'ecb' })
123
+ if (ecbEnc.success) {
124
+ const ecbDec = crypto.symmetric.decrypt(ecbEnc.data, key)
125
+ }
126
+
127
+ // 输出 base64 格式(ciphertext 字段为 base64,encoding 字段会标明)
128
+ const b64Enc = crypto.symmetric.encrypt('data', key, { outputFormat: 'base64' })
129
+
130
+ // 校验密钥/IV 格式
131
+ crypto.symmetric.isValidKey(key) // true
132
+ crypto.symmetric.isValidIV(iv) // true
133
+ ```
134
+
135
+ #### Password hashing (salted iterations)
136
+
137
+ ```ts
138
+ // 哈希密码(输出格式: $hai$<iterations>$<salt>$<hash>)
139
+ const hashed = crypto.password.hash('myPassword123')
140
+
141
+ // 自定义盐值长度和迭代次数
142
+ const custom = crypto.password.hash('myPassword123', {
143
+ saltLength: 32,
144
+ iterations: 20000,
145
+ })
146
+
147
+ // 验证密码
148
+ if (hashed.success) {
149
+ const ok = crypto.password.verify('myPassword123', hashed.data)
150
+ // ok.data === true
151
+
152
+ const wrong = crypto.password.verify('wrongPassword', hashed.data)
153
+ // wrong.data === false
154
+ }
155
+ ```
156
+
157
+ #### Transport encryption (crypto.transport)
158
+
159
+ See the [Transport v2 wire protocol](TRANSPORT-PROTOCOL.md) for canonical encoding, verification order and replay persistence.
160
+
161
+ The `crypto.transport` namespace provides transport encryption, allowing `@h-ai/serv`, `@h-ai/kit`, and `@h-ai/api-client` to share protocol constants and payload formats.
162
+
163
+ For typical applications, use the higher-level integrations:
164
+
165
+ - Server: `serv.createApp({ transport: { crypto, serverKeyRing, keyStore } })` or `kit.createHandle({ crypto: { crypto, transport: { serverKeyRing, keyStore } } })`.
166
+ - Client: `apiClient.init({ transport: { crypto } })` or `kit.client.create({ transport: { crypto } })`.
167
+
168
+ Call `crypto.transport.createServer({ serverKeyRing, keyStore })` / `createClient()` directly only for custom runtimes, tests, or manually integrated HTTP key exchange endpoints.
169
+
170
+ ##### Workflow
171
+
172
+ 1. Call `await crypto.init()` to initialize `crypto.asymmetric` and `crypto.symmetric`.
173
+ 2. On the server, create a `manager` with `crypto.transport.createServer({ serverKeyRing, keyStore })`. It holds the server key pair and stores client public keys. Inject a shared `keyStore` for multi-node deployments.
174
+ 3. Expose a POST key exchange endpoint: accept `{ clientPublicKey }`, register it with `manager.registerClientKey()`, and return `{ serverKeyId: manager.getServerKeyId(), serverPublicKey: manager.getServerPublicKey(), clientId }`.
175
+ 4. On the client, create a session with `crypto.transport.createClient({ keyExchangeUrl })`. The first `client.init()` or `client.encryptedFetch()` automatically performs key exchange.
176
+ 5. Every request sends an authenticated envelope `{ context, direction, status, encryptedKey, ciphertext, iv, tag, signature }`, including empty POST and GET/HEAD.
177
+ 6. Custom adapters first await `authenticateTransportRequest(manager, request)`. Only successful `data.plaintext` reaches business code; retain `data.context`.
178
+ 7. Encrypt responses with `await manager.encryptResponse(context, data, response.status)`; clients verify context, status and authenticity before returning plaintext.
179
+ 8. Clear a client session with `client.destroy()`. Release server resources with `manager.close()` or module-level `await crypto.close()`.
180
+
181
+ > Servers must explicitly inject the same managed `serverKeyRing` and a shared `keyStore` (Redis or a shared database). Sharing client public keys alone cannot enable cross-node decryption. There is no implicit process key or memory-registry fallback; development/tests may explicitly use `createInMemoryKeyStore(capacity)`. Reload the same ring after restart; sticky sessions are unnecessary.
182
+
183
+ For shared storage, reuse the provider factories exported from the `@h-ai/crypto` root entry:
184
+
185
+ - `createInMemoryKeyStore(maxClients)`: explicitly create the default memory store for tests or custom capacity.
186
+ - `createRedisTransportKeyStore({ cache, ttlSeconds? })`: reuse `@h-ai/cache`, typically with Redis for sharing across nodes.
187
+ - `createReldbTransportKeyStore({ reldb, ttlSeconds?, maxClients? })`: reuse initialized `@h-ai/reldb`, create key, nonce and capacity tables, and return a `ReldbTransportKeyStore` with `pruneExpired()`.
188
+
189
+ Registration validates the encoding and SM2 curve point before writing. Only 128 hex characters or `04` followed by 128 hex characters are accepted; compressed, infinity and off-curve points are rejected. The pure `isValidSM2PublicKey(value)` helper requires no initialization. serv/kit reject invalid keys with HTTP 400 before accessing the registry.
190
+
191
+ Omitting Redis/DB `ttlSeconds` keeps keys indefinitely. Explicit values must be integer seconds from 1 to 2147483647; a finite TTL is recommended. Redis uses native per-key expiration and does not expose the DB `maxClients` limit; configure memory budgets without evicting valid nonces. DB `maxClients` is a positive safe integer, defaults to 10000, and must match the persistent setting on every node. Registration locks a shared capacity row inside its transaction before counting and inserting; a full registry rejects registration without evicting valid keys or nonces. Deleting a client does not delete its valid nonces.
192
+
193
+ DB expiry uses database epoch milliseconds. Synchronize both database and node clocks within the protocol limits. Failed initial table creation can be retried. Each registration prunes one batch; `await registry.pruneExpired()` deletes at most 100 expired keys and 100 expired nonces per call. Schedule it in the application for low-traffic deployments: the registry creates no background timers and does not close the injected reldb. Migrate old timestamp key columns offline to BIGINT `created_at_ms` / `expires_at_ms`. Capacity is persisted in `hai_crypto_transport_capacity`; coordinate changes across all nodes and that row, and never clear valid nonces to recreate a registry.
194
+
195
+ ```ts
196
+ const registry = createReldbTransportKeyStore({ reldb, ttlSeconds: 3600, maxClients: 10000 })
197
+ // 由应用的定期维护调度器调用;每批有界,故障后由调度器重试。
198
+ const removed = await registry.pruneExpired()
199
+ ```
200
+
201
+ ```ts
202
+ // 服务端:通常由 serv.createApp({ transport: { crypto, serverKeyRing, keyStore } }) 或 kit.createHandle({ crypto }) 内部调用
203
+ const server = crypto.transport.createServer({ serverKeyRing, keyStore })
204
+ if (!server.success)
205
+ throw new Error(server.error.message)
206
+
207
+ // 客户端:通常由 apiClient.init({ transport: { crypto } }) 或 kit.client.create({ transport }) 内部调用
208
+ const client = crypto.transport.createClient({
209
+ keyExchangeUrl: 'https://api.example.com/api/v1/_hai/key-exchange',
210
+ })
211
+
212
+ const response = await client.encryptedFetch('https://api.example.com/api/v1/echo', {
213
+ method: 'POST',
214
+ body: JSON.stringify({ hello: 'world' }),
215
+ })
216
+ ```
217
+
218
+ ```ts
219
+ import { cache } from '@h-ai/cache'
220
+ import { createRedisTransportKeyStore, crypto } from '@h-ai/crypto'
221
+
222
+ await crypto.init()
223
+ await cache.init({ type: 'redis', host: '127.0.0.1', port: 6379 })
224
+
225
+ const server = crypto.transport.createServer({
226
+ serverKeyRing,
227
+ keyStore: createRedisTransportKeyStore({ cache, ttlSeconds: 3600 }),
228
+ })
229
+ if (!server.success)
230
+ throw new Error(server.error.message)
231
+ ```
232
+
233
+ `encryptedFetch()` follows native `fetch` semantics: it rejects on network, key exchange, request encryption, or response decryption failures. Catch these at the call site using the application's fetch error strategy.
234
+
235
+ Access protocol constants through `crypto.transport.protocol` (or `TRANSPORT_PROTOCOL`): `X-Client-Id`, `X-Encrypted`, and the default `/_hai/key-exchange`.
236
+
237
+ Both `serverKeyRing` and `keyStore` are required by `createServer({ serverKeyRing, keyStore })`. A ring is `{ activeKeyId, keys: { [id]: { publicKey, privateKey } } }`; IDs contain 1–64 letters, digits, underscores or hyphens. Creation verifies key pairing and captures a snapshot; invalid/missing configuration returns a sanitized HaiResult error. In these examples, `keyStore` is a connected Redis/shared-database registry; memory is an explicit development/test choice.
238
+
239
+ ```ts
240
+ import { parseTransportServerKeyRing } from '@h-ai/crypto'
241
+
242
+ const ring = parseTransportServerKeyRing(process.env.HAI_CRYPTO_TRANSPORT_SERVERKEYRING)
243
+ if (!ring.success)
244
+ throw new Error(ring.error.message)
245
+ const serverKeyRing = ring.data
246
+ const server = crypto.transport.createServer({ serverKeyRing, keyStore })
247
+ ```
248
+
249
+ Key exchange returns `{ serverKeyId, serverPublicKey, clientId }`. Encrypted requests carry `serverKeyId`; the server selects that private key and rejects unknown/revoked IDs without trying other keys. Responses use the client's public key. Rotate by distributing both old and new versions to every node, then switching `activeKeyId` and rebuilding managers during rollout. Retain the old version through the transition, then remove it from every node. Old clients must call `destroy()` and negotiate again; do not automatically replay non-idempotent operations. Distribute the same ring through a Secret Manager or server-only private environment. Never put it in ordinary YAML, PUBLIC_/VITE_ variables, logs or public responses. CLI project creation generates separate key rings in tracked `.env.dev/.env.test/.env.prod`. Clones share each environment’s ring; private environment variables or a Secret Manager can override it. Runtime does not generate keys.
250
+
251
+ Only authenticated protocol v2 is accepted. Independent random SM4-CBC and HMAC-SM3 keys are wrapped with SM2; verify the sender signature and MAC before CBC decryption. Clients sign requests and the selected server key version signs responses. Authentication covers version, direction, serverKeyId, clientId, a random 128-bit requestId acting as the nonce, issuedAt, HTTP method, the SM3 pathHash of pathname plus the original search, and response status. Requests have a five-minute lifetime and at most 30 seconds of future clock skew. The shared registry atomically consumes (clientId, requestId), retaining it until at least issuedAt plus six minutes to cover node skew; storage failures reject requests. Synchronize node clocks and use a Redis noeviction/durable policy that preserves live nonces. Transport replay prevention does not replace business idempotency keys.
252
+
253
+ Empty POSTs still send an authenticated envelope for empty plaintext. GET/HEAD carry it in X-Hai-Transport; bodyless responses such as 204/304/HEAD use the same header. Other requests/responses carry a JSON envelope and X-Encrypted: true. The client must match the original request context and HTTP status; missing markers, old formats and authentication failures reject. Serv/Kit hosts explicitly allow plaintext through `encryption: disabled` path rules or host `excludePaths`. Callers must select ordinary requests; API Client/Kit wrappers use their own `excludePaths`. CORS must allow and expose X-Hai-Transport. TLS authenticates handshake keys; this protocol does not replace IAM authorization.
254
+
255
+ Set `transport.maxPlaintextBytes` for both request and response JSON plaintext, measured in UTF-8 bytes: default 1 MiB, integer range 1 KiB–64 MiB. Clients learn the server limit during key exchange. `resolveTransportBodyLimits()` derives encrypted/proxy bytes as twice the plaintext limit plus 32 KiB. Handshake, public-key, header and replay constraints remain independent. Oversized streams are cancelled and readers released: requests return 413; oversized responses return an encrypted 500 capacity error, recognized as `TransportBodyTooLargeError` / `hai:crypto:070`. [容量配置、文件换算与升级](TRANSPORT-CAPACITY.md)。
256
+
257
+ Ordinary routes retain `transport.maxPlaintextBytes` (auto/omitted: 1 MiB). Declare Feedback report intake, evidence, attachments and ZIP download capacity separately using `routePlaintextBytes` and `feedback.budget.maxTransportBytes`; `*` matches one complete path segment and explicit host route values take precedence. Handshakes, adapter-node and proxies use the maximum route capacity. HTTP adapters admit at most 2 explicitly declared material requests above 1 MiB and a separate 16 ordinary business requests, releasing admission after the entire response or failure. Busy admission returns 503 / `hai:crypto:072`; business writes are not automatically replayed.
258
+
259
+ serv/kit return an encrypted HTTP 400 time error for an out-of-window message only after request binding, signature and MAC verification. The client throws `TransportTimeError` (`hai:crypto:071`) with advice to synchronize device/server clocks and refresh. `api-client` maps it to `VALIDATION_FAILED` and preserves `cause.transportCode`. Requests are not replayed automatically and replay windows remain unchanged; tampered or unauthenticated messages retain the generic authentication failure.
260
+
261
+ Custom HTTP adapters check `error instanceof TransportTimeError && error.context`, then encrypt the rejection with `createTransportErrorResponse(error, { manager, context: error.context })`. Never classify an unverified message by its timestamp.
262
+
263
+ Custom HTTP adapters can import the pure `readTransportBody(stream, { maxBytes, signal? })` helper from the root entry without `crypto.init()`. Pass the original stream, rebuild Request/Response after reading, and clear stale Content-Length/Content-Encoding. The helper throws RangeError for byte limits, TypeError for invalid UTF-8, and preserves the original read/abort failure.
264
+
265
+ ```ts
266
+ import { readTransportBody, TRANSPORT_BODY_LIMITS } from '@h-ai/crypto'
267
+
268
+ const text = await readTransportBody(request.body, {
269
+ maxBytes: TRANSPORT_BODY_LIMITS.keyExchangeBytes,
270
+ signal: request.signal,
271
+ })
272
+ const payload: unknown = JSON.parse(text)
273
+ ```
274
+
275
+ #### Close the module
276
+
277
+ ```ts
278
+ // 使用完毕后关闭,释放内部状态
279
+ await crypto.close()
280
+ ```
281
+
282
+ ### Error handling
283
+
284
+ All operations return `HaiResult<T>`:
285
+
286
+ ```ts
287
+ const result = crypto.asymmetric.encrypt('data', publicKey)
288
+ if (!result.success) {
289
+ // result.error.code / result.error.message
290
+ }
291
+ ```
292
+
293
+ ### Optional integrations
294
+
295
+ The admin console's online encryption demo calls the Crypto SM3/SM4 APIs directly. SM4 uses a random temporary key and IV and verifies decryption before showing success; keys are not saved. Changing input clears previous results. Random digests or Base64 must not be presented as cryptographic results.
296
+
297
+ ## Production shared state
298
+
299
+ Production transport registries must declare stateScope=shared and actually use Redis or PostgreSQL/MySQL. Memory, Redis factories over memory, and RelDB factories over SQLite are rejected. All nodes load the same managed versioned key ring. Initialization checks apply when NODE_ENV or HAI_CORE_ENV is production; only explicit HAI_E2E=1/HAI_E2E_MOCK=1 tests are exempt. [State, concurrency and recovery (Chinese)](../../.agents/instructions/distributed-state.md)。
300
+
301
+ ## Module requirements and explicit limits
302
+
303
+ `resolveTransportBodyLimits(limit?, { requiredPlaintextBytes? })` derives capacity from enabled modules only when limit is omitted; without module requirements it remains 1 MiB. A smaller explicit limit throws RangeError instead of silently increasing or reducing capacity. All values remain bounded to 1 KiB–64 MiB; encrypted capacity is twice plaintext plus 32 KiB. Serv/Kit configuration accepts `auto`, normalized to undefined at runtime.
304
+
305
+ ```ts
306
+ import { resolveTransportBodyLimits } from '@h-ai/crypto'
307
+
308
+ const limits = resolveTransportBodyLimits(24 * 1024 * 1024, { requiredPlaintextBytes: 11250348 })
309
+ // plaintextBytes: 25165824; encryptedPayloadBytes: 50364416
310
+ ```
311
+
312
+ ## Development and testing
313
+
314
+ ```bash
315
+ pnpm --filter @h-ai/crypto test
316
+ ```
317
+
318
+ ## License
319
+
320
+ Apache-2.0
package/README.ja.md ADDED
@@ -0,0 +1,320 @@
1
+ # @h-ai/crypto
2
+
3
+ [简体中文](./README.md) | [English](./README.en.md) | [日本語](./README.ja.md)
4
+
5
+ [フレームワークのホーム](../../README.ja.md) · 関連モジュール:[@h-ai/cache](../cache/README.ja.md) · [@h-ai/core](../core/README.ja.md) · [@h-ai/reldb](../reldb/README.ja.md)
6
+
7
+ ## 概要
8
+
9
+ 非対称暗号、ハッシュ、対称暗号、パスワードハッシュを提供する暗号モジュールです。
10
+
11
+ ## 主な機能
12
+
13
+ - 非対称暗号(鍵生成、暗号化・復号、署名・検証)
14
+ - ハッシュ(Hash、HMAC、検証)
15
+ - 対称暗号(ECB/CBC モード)
16
+ - パスワードハッシュ(ソルト付き反復ハッシュ)
17
+ - 通信暗号化(`crypto.transport`:サーバー管理機能 + クライアントの `encryptedFetch`)
18
+ - サーバー・ブラウザー共通(Node.js / ブラウザー)
19
+
20
+ ## 使い始める
21
+
22
+ ### セキュリティに関する注意
23
+
24
+ - **SM4 の既定の暗号化結果は構造化された暗号文**:`crypto.symmetric.encrypt(data, key)` は既定で CBC + ランダム IV を使用し、`{ mode, ciphertext, iv, encoding }` を返します。復号時はこのオブジェクトを `crypto.symmetric.decrypt(payload, key)` に渡します。
25
+ - **SM4 にはランダムな鍵を使用してください**:`crypto.symmetric.generateKey()` で鍵を生成します。このモジュールはパスワードから暗号鍵を導出する KDF を提供しません。パスワードの保存にはサーバー専用の `crypto.password.hash(password)` を使用し、パスワードやそのハッシュを直接 SM4 の鍵にしないでください。
26
+ - **IV は毎回一意にしてください**:同じ鍵で IV を再利用してはいけません。既定の CBC または `encryptWithIV()` による毎回の自動生成を推奨します。IV は暗号文と一緒に送信・保存します(公開可能で、秘密にする必要はありません)。
27
+
28
+ ### クイックスタート
29
+
30
+ ```ts
31
+ import { crypto } from '@h-ai/crypto'
32
+
33
+ // 初始化(使用前必须调用)
34
+ const initialized = await crypto.init()
35
+ if (!initialized.success)
36
+ throw new Error(initialized.error.message)
37
+ ```
38
+
39
+ #### 非対称暗号(暗号化・復号 / 署名・検証)
40
+
41
+ ```ts
42
+ // 生成密钥对
43
+ const keyPair = crypto.asymmetric.generateKeyPair()
44
+ if (!keyPair.success)
45
+ throw new Error(keyPair.error.message)
46
+ const { publicKey, privateKey } = keyPair.data
47
+
48
+ // 加密 / 解密
49
+ const encrypted = crypto.asymmetric.encrypt('Hello', publicKey)
50
+ if (encrypted.success) {
51
+ const decrypted = crypto.asymmetric.decrypt(encrypted.data, privateKey)
52
+ // decrypted.data === 'Hello'
53
+ }
54
+
55
+ // 输出 base64 格式密文
56
+ const b64 = crypto.asymmetric.encrypt('Hello', publicKey, { outputFormat: 'base64' })
57
+
58
+ // 签名 / 验签
59
+ const sig = crypto.asymmetric.sign('important data', privateKey)
60
+ if (sig.success) {
61
+ const valid = crypto.asymmetric.verify('important data', sig.data, publicKey)
62
+ // valid.data === true
63
+ }
64
+
65
+ // 校验密钥格式
66
+ crypto.asymmetric.isValidPublicKey(publicKey) // true
67
+ crypto.asymmetric.isValidPrivateKey(privateKey) // true
68
+ ```
69
+
70
+ #### ハッシュ(Hash / HMAC / 検証)
71
+
72
+ ```ts
73
+ // 字符串哈希
74
+ const hash = crypto.hash.hash('Hello!')
75
+ // hash.data → 64 字符十六进制哈希值
76
+
77
+ // Uint8Array 输入
78
+ const buf = new TextEncoder().encode('Hello!')
79
+ const hashBuf = crypto.hash.hash(buf)
80
+
81
+ // 十六进制编码输入
82
+ const hashHex = crypto.hash.hash('48656c6c6f21', { inputEncoding: 'hex' })
83
+
84
+ // HMAC
85
+ const hmac = crypto.hash.hmac('message', 'secret-key')
86
+
87
+ // 验证哈希是否匹配
88
+ if (hash.success) {
89
+ const matched = crypto.hash.verify('Hello!', hash.data)
90
+ // matched.data === true
91
+ }
92
+ ```
93
+
94
+ #### 対称暗号(既定の CBC / 構造化暗号文)
95
+
96
+ ```ts
97
+ // 生成随机密钥和 IV
98
+ const key = crypto.symmetric.generateKey()
99
+ const iv = crypto.symmetric.generateIV()
100
+
101
+ // 默认:CBC + 自动随机 IV,返回结构化密文
102
+ const safeEnc = crypto.symmetric.encrypt('data', key)
103
+ if (safeEnc.success) {
104
+ // safeEnc.data: { mode: 'cbc', ciphertext, iv, encoding: 'hex' }
105
+ const safeDec = crypto.symmetric.decrypt(safeEnc.data, key)
106
+ // safeDec.data === 'data'
107
+ }
108
+
109
+ // CBC 指定 IV(仍然返回结构化密文)
110
+ const cbcEnc = crypto.symmetric.encrypt('data', key, { mode: 'cbc', iv })
111
+ if (cbcEnc.success) {
112
+ const cbcDec = crypto.symmetric.decrypt(cbcEnc.data, key)
113
+ }
114
+
115
+ // 结构化结果:自动生成 IV 的 CBC 加解密
116
+ const withIV = crypto.symmetric.encryptWithIV('data', key)
117
+ if (withIV.success) {
118
+ const dec = crypto.symmetric.decryptWithIV(withIV.data.ciphertext, key, withIV.data.iv)
119
+ }
120
+
121
+ // ECB 模式(❌ 不安全;只有底层协议明确要求时才显式指定)
122
+ const ecbEnc = crypto.symmetric.encrypt('data', key, { mode: 'ecb' })
123
+ if (ecbEnc.success) {
124
+ const ecbDec = crypto.symmetric.decrypt(ecbEnc.data, key)
125
+ }
126
+
127
+ // 输出 base64 格式(ciphertext 字段为 base64,encoding 字段会标明)
128
+ const b64Enc = crypto.symmetric.encrypt('data', key, { outputFormat: 'base64' })
129
+
130
+ // 校验密钥/IV 格式
131
+ crypto.symmetric.isValidKey(key) // true
132
+ crypto.symmetric.isValidIV(iv) // true
133
+ ```
134
+
135
+ #### パスワードハッシュ(ソルト付き反復)
136
+
137
+ ```ts
138
+ // 哈希密码(输出格式: $hai$<iterations>$<salt>$<hash>)
139
+ const hashed = crypto.password.hash('myPassword123')
140
+
141
+ // 自定义盐值长度和迭代次数
142
+ const custom = crypto.password.hash('myPassword123', {
143
+ saltLength: 32,
144
+ iterations: 20000,
145
+ })
146
+
147
+ // 验证密码
148
+ if (hashed.success) {
149
+ const ok = crypto.password.verify('myPassword123', hashed.data)
150
+ // ok.data === true
151
+
152
+ const wrong = crypto.password.verify('wrongPassword', hashed.data)
153
+ // wrong.data === false
154
+ }
155
+ ```
156
+
157
+ #### 通信暗号化(crypto.transport)
158
+
159
+ 正規化、検証順序、nonce 保存は [Transport v2 プロトコル](TRANSPORT-PROTOCOL.md) を参照してください。
160
+
161
+ 通信暗号化は `crypto.transport` 名前空間で提供し、`@h-ai/serv`、`@h-ai/kit`、`@h-ai/api-client` で同じプロトコル定数とペイロード形式を再利用します。
162
+
163
+ 通常のアプリケーションでは、上位モジュールの統合機能を優先してください:
164
+
165
+ - サーバー:`serv.createApp({ transport: { crypto, serverKeyRing, keyStore } })` または `kit.createHandle({ crypto: { crypto, transport: { serverKeyRing, keyStore } } })`。
166
+ - クライアント:`apiClient.init({ transport: { crypto } })` または `kit.client.create({ transport: { crypto } })`。
167
+
168
+ `crypto.transport.createServer({ serverKeyRing, keyStore })` / `createClient()` の直接呼び出しは、独自ランタイム、テスト、HTTP 鍵交換 endpoint を自分で接続する場合に限って推奨します。
169
+
170
+ ##### 使用手順
171
+
172
+ 1. `await crypto.init()` を呼び、`crypto.asymmetric` と `crypto.symmetric` を初期化します。
173
+ 2. サーバーで `crypto.transport.createServer({ serverKeyRing, keyStore })` を呼び、`manager` を作成します。サーバー鍵ペアとクライアント公開鍵を管理します。複数ノードでは共有 `keyStore` を注入できます。
174
+ 3. POST の鍵交換 endpoint を用意します。`{ clientPublicKey }` を受け取り、`manager.registerClientKey()` で登録し、`{ serverKeyId: manager.getServerKeyId(), serverPublicKey: manager.getServerPublicKey(), clientId }` を返します。
175
+ 4. クライアントで `crypto.transport.createClient({ keyExchangeUrl })` によりセッションを作成します。最初の `client.init()` または `client.encryptedFetch()` で鍵交換が自動実行されます。
176
+ 5. 空の POST と GET/HEAD を含め、すべての要求が認証封装 `{ context, direction, status, encryptedKey, ciphertext, iv, tag, signature }` を送ります。
177
+ 6. 独自アダプターは先に `await authenticateTransportRequest(manager, request)` を実行し、成功時のみ `data.plaintext` を業務へ渡し、`data.context` を保持します。
178
+ 7. 応答は `await manager.encryptResponse(context, data, response.status)` で元要求に関連付け、クライアントがコンテキスト・status・完全性を検証してから平文を返します。
179
+ 8. `client.destroy()` でクライアントセッションを消去します。サーバー側のリソースは `manager.close()` またはモジュール単位の `await crypto.close()` で解放します。
180
+
181
+ > サーバーには同じ管理済み `serverKeyRing` と共有 `keyStore`(Redis または共有 DB)を明示的に渡します。クライアント公開鍵の共有だけではノード間で復号できません。暗黙のプロセス鍵・メモリー registry はなく、開発・テストでは `createInMemoryKeyStore(capacity)` を明示します。再起動後は同じ鍵環を読み込み、sticky session は不要です。
182
+
183
+ 共有ストレージには、`@h-ai/crypto` のルート入口からエクスポートされる Provider ファクトリーを再利用できます:
184
+
185
+ - `createInMemoryKeyStore(maxClients)`:テストや容量指定用に、既定のメモリーストアを明示的に作成。
186
+ - `createRedisTransportKeyStore({ cache, ttlSeconds? })`:`@h-ai/cache` を再利用。通常は Redis Provider と組み合わせ、複数ノードで共有。
187
+ - `createReldbTransportKeyStore({ reldb, ttlSeconds?, maxClients? })`:初期化済みの `@h-ai/reldb` を再利用し、公開鍵・nonce・容量テーブルを自動作成。`pruneExpired()` を備える `ReldbTransportKeyStore` を返します。
188
+
189
+ 登録前に公開鍵の形式と SM2 曲線上の点を検証します。128 文字の hex、または `04` + 128 文字の hex のみ受け付け、圧縮点・無限遠点・曲線外の点は拒否します。純関数 `isValidSM2PublicKey(value)` は初期化不要で、serv/kit は registry に書く前に不正な鍵を HTTP 400 で拒否します。
190
+
191
+ Redis/DB の `ttlSeconds` を省略すると無期限です。指定時は 1–2147483647 の整数秒とし、有限 TTL を推奨します。Redis はネイティブのキー TTL を使い、DB の `maxClients` 上限は提供しません。メモリー予算を設定し、有効な nonce を追い出さないでください。DB の `maxClients` は正の安全な整数、既定 10000 で、全ノードと永続容量レコードが一致する必要があります。登録はトランザクション内で共有容量行をロックし、件数確認後に挿入します。満杯では登録を拒否し、有効な公開鍵や nonce を削除しません。クライアント削除時も有効な nonce は保持します。
192
+
193
+ DB の期限は DB 時計の epoch ミリ秒で生成・判定します。DB と各ノードの時計をプロトコルの許容範囲内に同期してください。初回テーブル作成失敗後は再試行できます。登録時に 1 バッチ清掃し、`await registry.pruneExpired()` は期限切れ公開鍵と nonce を各 100 件まで削除します。低トラフィック時もアプリで定期実行してください。暗黙のタイマーは作らず、注入された reldb も閉じません。旧 timestamp 列は停止中に BIGINT の `created_at_ms` / `expires_at_ms` に移行します。容量は `hai_crypto_transport_capacity` に永続化されるため、変更時は全ノードと保存行を調整し、registry 再作成のために有効な nonce を消さないでください。
194
+
195
+ ```ts
196
+ const registry = createReldbTransportKeyStore({ reldb, ttlSeconds: 3600, maxClients: 10000 })
197
+ // アプリの定期メンテナンスから呼び出し、失敗時はスケジューラーで再試行する。
198
+ const removed = await registry.pruneExpired()
199
+ ```
200
+
201
+ ```ts
202
+ // 服务端:通常由 serv.createApp({ transport: { crypto, serverKeyRing, keyStore } }) 或 kit.createHandle({ crypto }) 内部调用
203
+ const server = crypto.transport.createServer({ serverKeyRing, keyStore })
204
+ if (!server.success)
205
+ throw new Error(server.error.message)
206
+
207
+ // 客户端:通常由 apiClient.init({ transport: { crypto } }) 或 kit.client.create({ transport }) 内部调用
208
+ const client = crypto.transport.createClient({
209
+ keyExchangeUrl: 'https://api.example.com/api/v1/_hai/key-exchange',
210
+ })
211
+
212
+ const response = await client.encryptedFetch('https://api.example.com/api/v1/echo', {
213
+ method: 'POST',
214
+ body: JSON.stringify({ hello: 'world' }),
215
+ })
216
+ ```
217
+
218
+ ```ts
219
+ import { cache } from '@h-ai/cache'
220
+ import { createRedisTransportKeyStore, crypto } from '@h-ai/crypto'
221
+
222
+ await crypto.init()
223
+ await cache.init({ type: 'redis', host: '127.0.0.1', port: 6379 })
224
+
225
+ const server = crypto.transport.createServer({
226
+ serverKeyRing,
227
+ keyStore: createRedisTransportKeyStore({ cache, ttlSeconds: 3600 }),
228
+ })
229
+ if (!server.success)
230
+ throw new Error(server.error.message)
231
+ ```
232
+
233
+ `encryptedFetch()` は標準の `fetch` と同じエラー規則に従います。ネットワーク、鍵交換、リクエスト暗号化、レスポンス復号に失敗すると reject します。呼び出し元でアプリケーションの fetch エラー処理に沿って捕捉してください。
234
+
235
+ プロトコル定数は `crypto.transport.protocol`(または `TRANSPORT_PROTOCOL`)で取得できます:`X-Client-Id`、`X-Encrypted`、既定の `/_hai/key-exchange`。
236
+
237
+ `createServer({ serverKeyRing, keyStore })` は両方とも必須です。鍵環は `{ activeKeyId, keys: { [id]: { publicKey, privateKey } } }` で、ID は英数字・下線・ハイフンの 1–64 文字です。作成時に鍵の組を検証しスナップショットを保持します。不正・未設定の値は機密情報を含まない HaiResult エラーになります。例の `keyStore` は接続済み Redis/共有 DB の registry です。メモリーは開発・テストで明示的に使用します。
238
+
239
+ ```ts
240
+ import { parseTransportServerKeyRing } from '@h-ai/crypto'
241
+
242
+ const ring = parseTransportServerKeyRing(process.env.HAI_CRYPTO_TRANSPORT_SERVERKEYRING)
243
+ if (!ring.success)
244
+ throw new Error(ring.error.message)
245
+ const serverKeyRing = ring.data
246
+ const server = crypto.transport.createServer({ serverKeyRing, keyStore })
247
+ ```
248
+
249
+ 鍵交換は `{ serverKeyId, serverPublicKey, clientId }` を返し、暗号化リクエストは `serverKeyId` を送ります。サーバーは指定した秘密鍵だけを選び、不明・失効 ID は他の鍵を試さず拒否します。応答はクライアント公開鍵で暗号化します。更新時は全ノードに新旧の鍵を先に配布し、続いて `activeKeyId` を切り替えて manager を順次再構築します。移行期間後に古い ID を全ノードから削除します。旧クライアントは `destroy()` 後に再交渉し、非冪等処理を自動再送しません。同じ鍵環を Secret Manager またはサーバー専用の非公開環境から配布し、通常の YAML、PUBLIC_/VITE_、ログ、公開応答には含めないでください。CLI は `.env.dev/.env.test/.env.prod` ごとに独立した鍵環を作成し、Git に保存します。クローン後も環境ごとに共有でき、非公開環境や Secret Manager で上書きできます。実行時には生成しません。
250
+
251
+ 認証済み v2 のみを受け付けます。独立したランダム SM4-CBC 鍵と HMAC-SM3 鍵を SM2 で包み、送信者署名、MAC の順に検証してから CBC を復号します。要求はクライアント秘密鍵、応答は選択されたサーバー鍵バージョンで署名します。version、direction、serverKeyId、clientId、nonce を兼ねるランダム 128 ビット requestId、issuedAt、HTTP method、pathname と元の search の SM3 pathHash、応答 status を認証します。要求の有効期限は 5 分、未来方向の時計差は最大 30 秒です。共有 registry が (clientId, requestId) を原子的に消費し、ノード間の時計差を含め issuedAt + 6 分まで保持します。保存障害では拒否します。時計同期と Redis の noeviction/永続化により有効な nonce を保持してください。業務の再試行には別の冪等キーが必要です。
252
+
253
+ 空の POST も空平文の認証封装を送ります。GET/HEAD は X-Hai-Transport ヘッダー、204/304/HEAD など本文なし応答も同じヘッダーを使います。他の要求・応答は JSON 本文と X-Encrypted: true を使います。クライアントは元の要求コンテキストと HTTP status を照合し、マーカー欠落、旧形式、認証失敗では reject します。平文 endpoint は Serv/Kit の `encryption: disabled` ルールまたはホストの `excludePaths` で明示的に許可し、呼出側も通常の要求を選びます。API Client/Kit のラッパーは自身の `excludePaths` を使用します。CORS では X-Hai-Transport を許可・公開してください。鍵交換の公開鍵認証は TLS に依存し、IAM の業務認可は別に必要です。
254
+
255
+ `transport.maxPlaintextBytes` でリクエストとレスポンスの JSON 平文容量を共通設定します。単位は UTF-8 バイト、既定値は 1 MiB、有効範囲は 1 KiB~64 MiB の整数です。クライアントは鍵交換で上限を取得し、`resolveTransportBodyLimits()` が暗号文とプロキシ容量(平文の 2 倍 + 32 KiB)を算出します。鍵交換、公開鍵、認証ヘッダー、防リプレイ制約は独立です。超過時は元ストリームを停止して reader を解放します。要求は 413、応答は暗号化された 500 容量エラーとなり、`TransportBodyTooLargeError` / `hai:crypto:070` で識別できます。 [容量配置、文件换算与升级](TRANSPORT-CAPACITY.md)。
256
+
257
+ 通常業務は `transport.maxPlaintextBytes`(auto/省略は 1 MiB)を維持します。Feedback の受理・証拠・添付・ZIP ダウンロードは `routePlaintextBytes` と `feedback.budget.maxTransportBytes` で別途宣言します。`*` は完全な1パス区間のみ一致し、ホストの明示値が優先です。ハンドシェイク、adapter-node、プロキシは経路の最大値を使用します。HTTP アダプターは個別宣言された 1 MiB 超の資料経路を最大2件、通常業務を別枠で16件まで許可し、応答完了・失敗時に解放します。混雑は503 / `hai:crypto:072` を返し、業務書込は自動再送しません。
258
+
259
+ serv/kit は要求の結合、署名、MAC を検証した後、時間窓を超えた報文に暗号化した HTTP 400 時刻エラーを返します。クライアントは `TransportTimeError`(`hai:crypto:071`)で端末とサーバーの時刻同期・再読み込みを案内します。`api-client` は `VALIDATION_FAILED` に変換し `cause.transportCode` に原因を保持します。自動再送やリプレイ時間窓の緩和は行わず、改ざん・未認証の要求は従来の認証エラーです。
260
+
261
+ 独自 HTTP アダプターでは `error instanceof TransportTimeError && error.context` を確認し、`createTransportErrorResponse(error, { manager, context: error.context })` で拒否応答を暗号化します。未認証の報文のタイムスタンプだけで時刻異常を診断しないでください。
262
+
263
+ 独自 HTTP アダプターではルート入口の純粋関数 `readTransportBody(stream, { maxBytes, signal? })` を `crypto.init()` なしで利用できます。元のストリームを渡し、読み取り後は Request/Response を再構築して古い Content-Length/Content-Encoding を削除してください。上限超過は RangeError、不正 UTF-8 は TypeError、読み取り例外・signal.reason は元の理由で拒否します。ストリームのキャンセル処理が失敗しても元の例外を維持します。
264
+
265
+ ```ts
266
+ import { readTransportBody, TRANSPORT_BODY_LIMITS } from '@h-ai/crypto'
267
+
268
+ const text = await readTransportBody(request.body, {
269
+ maxBytes: TRANSPORT_BODY_LIMITS.keyExchangeBytes,
270
+ signal: request.signal,
271
+ })
272
+ const payload: unknown = JSON.parse(text)
273
+ ```
274
+
275
+ #### モジュールの終了
276
+
277
+ ```ts
278
+ // 使用完毕后关闭,释放内部状态
279
+ await crypto.close()
280
+ ```
281
+
282
+ ### エラー処理
283
+
284
+ すべての操作は `HaiResult<T>` を返します:
285
+
286
+ ```ts
287
+ const result = crypto.asymmetric.encrypt('data', publicKey)
288
+ if (!result.success) {
289
+ // result.error.code / result.error.message
290
+ }
291
+ ```
292
+
293
+ ### 任意の連携
294
+
295
+ 管理画面のオンライン暗号化デモは Crypto の SM3/SM4 API を直接呼びます。SM4 はランダムな一時鍵と IV を使い、成功表示前に復号を検証します。鍵は保存しません。入力が変わると古い結果を消去し、ランダムなダイジェストや Base64 を暗号処理の結果として表示してはいけません。
296
+
297
+ ## 本番の共有状態
298
+
299
+ 本番の伝送 registry は stateScope=shared と実際の Redis または PostgreSQL/MySQL が必須です。memory、および memory/SQLite を包む工場も拒否します。各ノードは同じ管理されたバージョン付き鍵セットを読み込みます。 NODE_ENV または HAI_CORE_ENV が production の場合、初期化成功前に検証します。明示的な HAI_E2E=1/HAI_E2E_MOCK=1 テストのみ除外します。 [状態・並行制御・復旧範囲(中国語)](../../.agents/instructions/distributed-state.md)。
300
+
301
+ ## モジュール要件と明示的な上限
302
+
303
+ `resolveTransportBodyLimits(limit?, { requiredPlaintextBytes? })` は limit 省略時だけ有効なモジュールの必要量から計算し、要件がなければ 1 MiB です。明示上限が必要量未満なら RangeError とし、勝手に拡張・縮小しません。範囲は 1 KiB~64 MiB、暗号文は平文の2倍+32 KiBです。Serv/Kit の `auto` は実行時に undefined へ正規化します。
304
+
305
+ ```ts
306
+ import { resolveTransportBodyLimits } from '@h-ai/crypto'
307
+
308
+ const limits = resolveTransportBodyLimits(24 * 1024 * 1024, { requiredPlaintextBytes: 11250348 })
309
+ // plaintextBytes: 25165824; encryptedPayloadBytes: 50364416
310
+ ```
311
+
312
+ ## 開発とテスト
313
+
314
+ ```bash
315
+ pnpm --filter @h-ai/crypto test
316
+ ```
317
+
318
+ ## ライセンス
319
+
320
+ Apache-2.0