@lostgradient/mcp 0.2.5 → 0.3.0

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.
Files changed (123) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +15 -173
  3. package/dist/http.d.ts +35 -0
  4. package/dist/http.js +251 -0
  5. package/dist/internal/cryptography/encryption.d.ts +108 -0
  6. package/dist/internal/cryptography/encryption.js +241 -0
  7. package/dist/internal/cryptography/hash.d.ts +72 -0
  8. package/dist/internal/cryptography/hash.js +233 -0
  9. package/dist/internal/cryptography/index.d.ts +4 -0
  10. package/dist/internal/cryptography/index.js +2 -0
  11. package/dist/oauth/canonicalize-ip-address.d.ts +0 -6
  12. package/dist/oauth/canonicalize-ip-address.js +113 -0
  13. package/dist/oauth/client-metadata-documents.d.ts +2 -22
  14. package/dist/oauth/client-metadata-documents.js +205 -19
  15. package/dist/oauth/index.d.ts +9 -213
  16. package/dist/oauth/index.js +6 -69
  17. package/dist/oauth/issuer.d.ts +103 -0
  18. package/dist/oauth/issuer.js +564 -0
  19. package/dist/oauth/postgres.d.ts +12 -0
  20. package/dist/oauth/postgres.js +76 -0
  21. package/dist/oauth/safe-public-https-fetch.d.ts +3 -5
  22. package/dist/oauth/safe-public-https-fetch.js +114 -0
  23. package/dist/oauth/security-utilities.d.ts +0 -3
  24. package/dist/oauth/security-utilities.js +93 -0
  25. package/dist/oauth-store.d.ts +108 -0
  26. package/dist/oauth-store.js +321 -0
  27. package/package.json +50 -124
  28. package/dist/chunk-3ek3knfm.js +0 -73
  29. package/dist/chunk-3rr24vhh.js +0 -28
  30. package/dist/chunk-6ekjtvcq.js +0 -273
  31. package/dist/chunk-88nhf6xt.js +0 -449
  32. package/dist/chunk-en76akaq.js +0 -1107
  33. package/dist/chunk-k6fm3cmk.js +0 -132
  34. package/dist/chunk-qxwd8est.js +0 -916
  35. package/dist/chunk-rxnyn7tf.js +0 -19
  36. package/dist/chunk-taxyscge.js +0 -67
  37. package/dist/chunk-wsnfttyg.js +0 -4
  38. package/dist/chunk-xcf742mf.js +0 -14
  39. package/dist/conformance-fixture-registration.d.ts +0 -30
  40. package/dist/conformance-server.d.ts +0 -1
  41. package/dist/conformance.d.ts +0 -43
  42. package/dist/env.d.ts +0 -59
  43. package/dist/env.js +0 -9
  44. package/dist/environment-schema.d.ts +0 -29
  45. package/dist/environment-schema.js +0 -6
  46. package/dist/golden-prompts.d.ts +0 -42
  47. package/dist/handler-context.d.ts +0 -16
  48. package/dist/http/authenticate.d.ts +0 -35
  49. package/dist/http/authorization-header.d.ts +0 -5
  50. package/dist/http/grant-revocation-channel.d.ts +0 -24
  51. package/dist/http/handler.d.ts +0 -32
  52. package/dist/http/index.d.ts +0 -27
  53. package/dist/http/index.js +0 -870
  54. package/dist/http/listen-inspection.d.ts +0 -11
  55. package/dist/http/request-context.d.ts +0 -17
  56. package/dist/http/responses.d.ts +0 -13
  57. package/dist/http/serving-layer.d.ts +0 -25
  58. package/dist/http/user-handler-cache.d.ts +0 -37
  59. package/dist/http/user-server-event-bus.d.ts +0 -35
  60. package/dist/index.d.ts +0 -29
  61. package/dist/index.js +0 -616
  62. package/dist/localhost-request-validation.d.ts +0 -2
  63. package/dist/logger.d.ts +0 -59
  64. package/dist/logger.js +0 -18
  65. package/dist/long-running-operation-support.d.ts +0 -34
  66. package/dist/metrics.d.ts +0 -64
  67. package/dist/metrics.js +0 -6
  68. package/dist/oauth/authorize-endpoint.d.ts +0 -5
  69. package/dist/oauth/client-authentication.d.ts +0 -10
  70. package/dist/oauth/discovery-metadata.d.ts +0 -19
  71. package/dist/oauth/endpoint-rate-limits.d.ts +0 -10
  72. package/dist/oauth/endpoint-responses.d.ts +0 -10
  73. package/dist/oauth/network-identity.d.ts +0 -32
  74. package/dist/oauth/pkce-validation.d.ts +0 -2
  75. package/dist/oauth/postgres/client-store.d.ts +0 -12
  76. package/dist/oauth/postgres/code-store.d.ts +0 -14
  77. package/dist/oauth/postgres/database.d.ts +0 -59
  78. package/dist/oauth/postgres/index.d.ts +0 -11
  79. package/dist/oauth/postgres/index.js +0 -616
  80. package/dist/oauth/postgres/schema.d.ts +0 -1476
  81. package/dist/oauth/postgres/token-store.d.ts +0 -16
  82. package/dist/oauth/postgres/transaction-store.d.ts +0 -14
  83. package/dist/oauth/redirect-uri-matching.d.ts +0 -2
  84. package/dist/oauth/registration-endpoint.d.ts +0 -2
  85. package/dist/oauth/request-body.d.ts +0 -14
  86. package/dist/oauth/revocation-endpoint.d.ts +0 -2
  87. package/dist/oauth/scope-utilities.d.ts +0 -15
  88. package/dist/oauth/stores.d.ts +0 -225
  89. package/dist/oauth/stores.js +0 -0
  90. package/dist/oauth/testing/contract-fixtures.d.ts +0 -134
  91. package/dist/oauth/testing/index.d.ts +0 -56
  92. package/dist/oauth/testing/index.js +0 -330
  93. package/dist/oauth/token-endpoint.d.ts +0 -2
  94. package/dist/oauth-scope-configuration.d.ts +0 -3
  95. package/dist/prompts/index.d.ts +0 -5
  96. package/dist/prompts/summarize.d.ts +0 -4
  97. package/dist/rate-limit/in-memory-sliding-window-store.d.ts +0 -3
  98. package/dist/rate-limit/index.d.ts +0 -23
  99. package/dist/rate-limit/index.js +0 -29
  100. package/dist/rate-limit/mcp-concurrency-limiter.d.ts +0 -26
  101. package/dist/rate-limit/rate-limit-response.d.ts +0 -1
  102. package/dist/rate-limit/redis-sliding-window-store.d.ts +0 -2
  103. package/dist/rate-limit/request-rate-limiter.d.ts +0 -10
  104. package/dist/rate-limit/sliding-window-rate-limiter.d.ts +0 -16
  105. package/dist/resources/index.d.ts +0 -4
  106. package/dist/resources/user-profile.d.ts +0 -1
  107. package/dist/scope-vocabulary.d.ts +0 -127
  108. package/dist/scopes.d.ts +0 -49
  109. package/dist/server.d.ts +0 -113
  110. package/dist/supported-scopes.d.ts +0 -25
  111. package/dist/sveltekit-mount-state.d.ts +0 -4
  112. package/dist/sveltekit-mount.d.ts +0 -43
  113. package/dist/sveltekit-mount.js +0 -344
  114. package/dist/template-registry.d.ts +0 -16
  115. package/dist/tool-response.d.ts +0 -100
  116. package/dist/tools/get-user-profile.d.ts +0 -8
  117. package/dist/tools/index.d.ts +0 -16
  118. package/dist/tools/list-audit-events.d.ts +0 -11
  119. package/dist/type-assertions.d.ts +0 -1
  120. package/dist/types/primitives.d.ts +0 -130
  121. package/dist/ui-extension-support.d.ts +0 -20
  122. package/dist/version.d.ts +0 -23
  123. package/dist/version.js +0 -6
@@ -0,0 +1,241 @@
1
+ /**
2
+ * Authenticated encryption for stored secrets: AES-256-GCM through Web Crypto, with a keyring so a
3
+ * key can be rotated without losing values written under the old one.
4
+ *
5
+ * Design, in the order a reviewer is likely to ask:
6
+ *
7
+ * - **Fresh IV per encryption.** Every `encrypt` draws a new random 96-bit IV from
8
+ * `crypto.getRandomValues`; an IV is never derived, counted, or reused. With random 96-bit IVs the
9
+ * collision risk stays negligible up to roughly 2^32 encryptions under one key, so rotate a key
10
+ * long before it has sealed that many values.
11
+ * - **Key id.** A key's id is `hex(SHA-256("corvidae.cryptography.key-id.v1" || rawKey))`
12
+ * truncated to 12 bytes: 24 lowercase hexadecimal characters, which is a valid Bungalow secret-name
13
+ * suffix (`answer-encryption-key-<keyId>`). SHA-256 is preimage-resistant and the key is 256 bits of entropy, so the
14
+ * id reveals nothing usable about the key, and it is derived rather than stored, so a host can
15
+ * recompute the id (and the Bungalow secret name that embeds it) from the key alone.
16
+ * - **Additional authenticated data.** The version tag and the key id are bound into the GCM
17
+ * additional data, so rewriting either on a stored value fails authentication instead of silently
18
+ * selecting a different key or algorithm.
19
+ * - **Version.** Stored values carry `version: 1`. It is the only hook for a future algorithm
20
+ * change, and a stored value is long-lived, so the tag is cheap insurance on a persisted shape.
21
+ * - **Errors.** Every failure is a {@link CryptographyError} with a fixed message and a code. No
22
+ * message contains key material or plaintext, and WebCrypto's own error is never re-thrown.
23
+ */
24
+ /** The only stored-value version this module reads and writes. */
25
+ const STORED_VERSION = 1;
26
+ const KEY_BYTES = 32;
27
+ const IV_BYTES = 12;
28
+ const TAG_BYTES = 16;
29
+ const KEY_ID_BYTES = 12;
30
+ const KEY_ID_DOMAIN = 'corvidae.cryptography.key-id.v1';
31
+ const ADDITIONAL_DATA_DOMAIN = 'corvidae.cryptography.aes-256-gcm';
32
+ /** An error from this module. The message is fixed text and never contains key material or plaintext. */
33
+ export class CryptographyError extends Error {
34
+ /** The category of failure, for programmatic handling. */
35
+ code;
36
+ /** For `secret-unavailable`, the key id that the keyring could not supply. Not secret. */
37
+ keyId;
38
+ /** Creates an error with a fixed message for the given code. */
39
+ constructor(code, keyId) {
40
+ super(messages[code]);
41
+ this.name = 'CryptographyError';
42
+ this.code = code;
43
+ this.keyId = keyId;
44
+ }
45
+ }
46
+ const messages = {
47
+ 'secret-unavailable': 'The key that encrypted this value is not available.',
48
+ 'authentication-failed': 'The encrypted value failed authentication.',
49
+ 'malformed-secret': 'The encrypted value is malformed.',
50
+ 'unsupported-version': 'The encrypted value uses an unsupported version.',
51
+ 'invalid-key': 'The encryption key is invalid.',
52
+ 'invalid-text': 'The decrypted value is not valid UTF-8 text.',
53
+ };
54
+ const textEncoder = new TextEncoder();
55
+ /** Base64url (RFC 4648 section 5) without padding. */
56
+ function encodeBase64Url(bytes) {
57
+ let binary = '';
58
+ for (const byte of bytes)
59
+ binary += String.fromCharCode(byte);
60
+ return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');
61
+ }
62
+ /** Strict decoder: rejects anything that is not the canonical encoding of some byte string. */
63
+ function decodeBase64Url(encoded) {
64
+ if (typeof encoded !== 'string' || !/^[A-Za-z0-9_-]*$/.test(encoded))
65
+ return undefined;
66
+ if (encoded.length % 4 === 1)
67
+ return undefined;
68
+ try {
69
+ const binary = atob(encoded.replaceAll('-', '+').replaceAll('_', '/'));
70
+ const bytes = new Uint8Array(binary.length);
71
+ for (let index = 0; index < binary.length; index += 1)
72
+ bytes[index] = binary.charCodeAt(index);
73
+ // Reject non-canonical encodings (nonzero trailing bits) so one byte string has one encoding.
74
+ return encodeBase64Url(bytes) === encoded ? bytes : undefined;
75
+ }
76
+ catch {
77
+ return undefined;
78
+ }
79
+ }
80
+ function toHex(bytes) {
81
+ let hex = '';
82
+ for (const byte of bytes)
83
+ hex += byte.toString(16).padStart(2, '0');
84
+ return hex;
85
+ }
86
+ async function deriveKeyId(rawKey) {
87
+ const domain = textEncoder.encode(KEY_ID_DOMAIN);
88
+ const input = new Uint8Array(domain.length + rawKey.length);
89
+ input.set(domain, 0);
90
+ input.set(rawKey, domain.length);
91
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', input));
92
+ input.fill(0);
93
+ return toHex(digest.slice(0, KEY_ID_BYTES));
94
+ }
95
+ async function importRawKey(rawKey, extractable) {
96
+ try {
97
+ const keyId = await deriveKeyId(rawKey);
98
+ const cryptoKey = await crypto.subtle.importKey('raw', rawKey, 'AES-GCM', extractable, [
99
+ 'encrypt',
100
+ 'decrypt',
101
+ ]);
102
+ return { keyId, cryptoKey };
103
+ }
104
+ catch {
105
+ throw new CryptographyError('invalid-key');
106
+ }
107
+ finally {
108
+ rawKey.fill(0);
109
+ }
110
+ }
111
+ /**
112
+ * Generates a new random AES-256 key. The result is extractable so the host can persist it with
113
+ * {@link exportEncryptionKey}.
114
+ */
115
+ export async function generateEncryptionKey() {
116
+ const rawKey = new Uint8Array(KEY_BYTES);
117
+ crypto.getRandomValues(rawKey);
118
+ return importRawKey(rawKey, true);
119
+ }
120
+ /**
121
+ * Imports a key previously produced by {@link exportEncryptionKey}: base64url of exactly 32 bytes.
122
+ * Throws `invalid-key` for anything else.
123
+ */
124
+ export async function importEncryptionKey(encoded, options = {}) {
125
+ const decoded = decodeBase64Url(encoded);
126
+ if (decoded === undefined || decoded.length !== KEY_BYTES) {
127
+ throw new CryptographyError('invalid-key');
128
+ }
129
+ const rawKey = new Uint8Array(KEY_BYTES);
130
+ rawKey.set(decoded);
131
+ decoded.fill(0);
132
+ return importRawKey(rawKey, options.extractable === true);
133
+ }
134
+ /**
135
+ * Exports a key as base64url of its 32 raw bytes, for storage as a secret. The result is key
136
+ * material: never log it. Throws `invalid-key` when the key was imported without `extractable`.
137
+ */
138
+ export async function exportEncryptionKey(key) {
139
+ let raw;
140
+ try {
141
+ raw = new Uint8Array(await crypto.subtle.exportKey('raw', key.cryptoKey));
142
+ }
143
+ catch {
144
+ throw new CryptographyError('invalid-key');
145
+ }
146
+ const encoded = encodeBase64Url(raw);
147
+ raw.fill(0);
148
+ return encoded;
149
+ }
150
+ function additionalData(keyId) {
151
+ // Fields are separated by NUL; a key id is lowercase hex and so cannot contain one.
152
+ return textEncoder.encode(`${ADDITIONAL_DATA_DOMAIN}\0${STORED_VERSION}\0${keyId}`);
153
+ }
154
+ /**
155
+ * Encrypts text (UTF-8) or bytes under `key` with a fresh random IV. The result is safe to persist
156
+ * as JSON.
157
+ */
158
+ export async function encrypt(plaintext, key) {
159
+ if (typeof plaintext !== 'string' && !(plaintext instanceof Uint8Array)) {
160
+ throw new TypeError('encrypt expects a string or a Uint8Array.');
161
+ }
162
+ // Snapshot caller-owned inputs before the first await.
163
+ const keyId = key.keyId;
164
+ const cryptoKey = key.cryptoKey;
165
+ if (typeof plaintext === 'string' && !plaintext.isWellFormed()) {
166
+ // TextEncoder would silently replace a lone surrogate with U+FFFD and change the value.
167
+ throw new CryptographyError('invalid-text');
168
+ }
169
+ const data = typeof plaintext === 'string' ? textEncoder.encode(plaintext) : plaintext;
170
+ const iv = new Uint8Array(IV_BYTES);
171
+ crypto.getRandomValues(iv);
172
+ let sealed;
173
+ try {
174
+ sealed = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: additionalData(keyId), tagLength: TAG_BYTES * 8 }, cryptoKey, new Uint8Array(data));
175
+ }
176
+ catch {
177
+ throw new CryptographyError('invalid-key');
178
+ }
179
+ return {
180
+ version: STORED_VERSION,
181
+ ciphertext: encodeBase64Url(new Uint8Array(sealed)),
182
+ iv: encodeBase64Url(iv),
183
+ keyId,
184
+ };
185
+ }
186
+ /** Finds a key by id in the keyring. Linear scan: a keyring holds a handful of keys. */
187
+ function findKey(keyring, keyId) {
188
+ if (keyring.current.keyId === keyId)
189
+ return keyring.current;
190
+ return keyring.retired?.find((candidate) => candidate.keyId === keyId);
191
+ }
192
+ /**
193
+ * Decrypts a value written by {@link encrypt} to bytes, using whichever keyring entry its `keyId`
194
+ * names. Throws a {@link CryptographyError}: `malformed-secret` or `unsupported-version` for a
195
+ * misshapen value, `secret-unavailable` when the keyring lacks the key, `authentication-failed` when
196
+ * any field was altered.
197
+ */
198
+ export async function decryptBytes(value, keyring) {
199
+ const candidate = value;
200
+ if (typeof candidate !== 'object' || candidate === null) {
201
+ throw new CryptographyError('malformed-secret');
202
+ }
203
+ const fields = candidate;
204
+ const version = Object.hasOwn(fields, 'version') ? fields['version'] : undefined;
205
+ if (version !== STORED_VERSION) {
206
+ throw new CryptographyError(typeof version === 'number' ? 'unsupported-version' : 'malformed-secret');
207
+ }
208
+ const keyId = Object.hasOwn(fields, 'keyId') ? fields['keyId'] : undefined;
209
+ const iv = decodeBase64Url(Object.hasOwn(fields, 'iv') ? fields['iv'] : undefined);
210
+ const sealed = decodeBase64Url(Object.hasOwn(fields, 'ciphertext') ? fields['ciphertext'] : undefined);
211
+ if (typeof keyId !== 'string' ||
212
+ iv === undefined ||
213
+ iv.length !== IV_BYTES ||
214
+ sealed === undefined ||
215
+ sealed.length < TAG_BYTES) {
216
+ throw new CryptographyError('malformed-secret');
217
+ }
218
+ const key = findKey(keyring, keyId);
219
+ if (key === undefined)
220
+ throw new CryptographyError('secret-unavailable', keyId);
221
+ try {
222
+ const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv, additionalData: additionalData(keyId), tagLength: TAG_BYTES * 8 }, key.cryptoKey, sealed);
223
+ return new Uint8Array(plain);
224
+ }
225
+ catch {
226
+ throw new CryptographyError('authentication-failed');
227
+ }
228
+ }
229
+ /**
230
+ * Like {@link decryptBytes}, then decodes the result as UTF-8, keeping a leading U+FEFF so the text
231
+ * round-trips exactly; throws `invalid-text` if the bytes are not UTF-8.
232
+ */
233
+ export async function decrypt(value, keyring) {
234
+ const bytes = await decryptBytes(value, keyring);
235
+ try {
236
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
237
+ }
238
+ catch {
239
+ throw new CryptographyError('invalid-text');
240
+ }
241
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Cross-platform cryptographic hashing utilities.
3
+ *
4
+ * - `sha256Hex` uses the Web Crypto API and works in all environments (browser, Node, Bun, Deno).
5
+ * - `sha256HexSync` is synchronous and works in Bun and in Node.js 20.16.0+ (20.x line) or 22.3.0+ (throws in browsers
6
+ * and in older Node.js, where `process.getBuiltinModule` does not exist — use the async `sha256Hex`
7
+ * there instead, or supply a `require`-based runtime override; see below).
8
+ * - `hmacSha256HexSync` signs text with HMAC-SHA-256 under the same Bun/Node 20.16.0+ (20.x) or 22.3.0+ requirement.
9
+ * - `timingSafeEqualHex` compares hex digests without leaking the first differing byte (same
10
+ * Bun/Node 20.16.0+ (20.x) or 22.3.0+ requirement as the other synchronous helpers).
11
+ * - `createIncrementalHash` returns a streaming hasher for accumulating data across multiple
12
+ * `.update()` calls (same Bun/Node 20.16.0+ (20.x) or 22.3.0+ requirement).
13
+ *
14
+ * The synchronous helpers read `node:crypto` via `process.getBuiltinModule` rather than a literal
15
+ * `require(...)` call, specifically so that bundling this package for a browser build never injects
16
+ * a `createRequire`/`node:module` shim (see AB-31). That trades away support for Node.js versions
17
+ * outside `^20.16.0 || >=22.3.0` for the synchronous path; a caller that must support older Node can
18
+ * still supply its own loader via the `corvidae.cryptography.hash.runtime` global override
19
+ * (see `getHashRuntimeOverride` below) — set `{ require: (specifier) => require(specifier) }` from
20
+ * a CommonJS entry point where a real `require` exists.
21
+ */
22
+ /** Interface for an incremental (streaming) hash that accumulates data via `.update()`. */
23
+ export type IncrementalHash = {
24
+ /** Feed more data into the hash. */
25
+ update(data: string): void;
26
+ /** Finalize and return the hex digest. */
27
+ digest(): string;
28
+ };
29
+ /**
30
+ * Computes the SHA-256 hex digest of a string using the Web Crypto API.
31
+ * Works in all environments: browsers, Node.js, Bun, Deno.
32
+ */
33
+ export declare function sha256Hex(text: string): Promise<string>;
34
+ /**
35
+ * Computes the SHA-256 hex digest of raw bytes using the Web Crypto API.
36
+ * Works in all environments: browsers, Node.js, Bun, Deno.
37
+ *
38
+ * Digesting bytes rather than a string is what lets a caller hash content it cannot decode —
39
+ * a bundled image or font, say — without first corrupting it through a lossy text round trip.
40
+ */
41
+ export declare function sha256BytesHex(data: Uint8Array): Promise<string>;
42
+ /**
43
+ * Computes the SHA-256 hex digest of a string synchronously.
44
+ * Uses `node:crypto`, which Bun and Node.js both provide.
45
+ * Throws in browser environments where no synchronous crypto API is available.
46
+ */
47
+ export declare function sha256HexSync(text: string): string;
48
+ /** Computes the SHA-256 hex digest of raw bytes synchronously. */
49
+ export declare function sha256BytesHexSync(data: Uint8Array): string;
50
+ /** Computes a SHA-256 digest in the base64url representation PKCE requires. */
51
+ export declare function sha256Base64UrlSync(text: string): string;
52
+ /**
53
+ * Computes an HMAC-SHA-256 hex signature synchronously.
54
+ * Uses `node:crypto`, which Bun and Node.js both provide.
55
+ * Throws in browser environments where no synchronous HMAC API is available.
56
+ */
57
+ export declare function hmacSha256HexSync(secret: string, text: string): string;
58
+ /**
59
+ * Compares two hex strings with Node's timing-safe equality when available.
60
+ * Invalid hex strings and different-length values are never equal.
61
+ */
62
+ export declare function timingSafeEqualHex(left: string, right: string): boolean;
63
+ /** Compares UTF-8 text with Node's timing-safe equality for equal-size inputs. */
64
+ export declare function timingSafeEqualText(left: string, right: string): boolean;
65
+ /**
66
+ * Creates an incremental (streaming) hash for accumulating data across multiple `.update()` calls.
67
+ * Uses `node:crypto`, which Bun and Node.js both provide.
68
+ * Throws in browser environments where no synchronous streaming crypto API is available.
69
+ *
70
+ * @param algorithm - Hash algorithm to use. Default: `'sha256'`.
71
+ */
72
+ export declare function createIncrementalHash(algorithm?: string): IncrementalHash;
@@ -0,0 +1,233 @@
1
+ /**
2
+ * Cross-platform cryptographic hashing utilities.
3
+ *
4
+ * - `sha256Hex` uses the Web Crypto API and works in all environments (browser, Node, Bun, Deno).
5
+ * - `sha256HexSync` is synchronous and works in Bun and in Node.js 20.16.0+ (20.x line) or 22.3.0+ (throws in browsers
6
+ * and in older Node.js, where `process.getBuiltinModule` does not exist — use the async `sha256Hex`
7
+ * there instead, or supply a `require`-based runtime override; see below).
8
+ * - `hmacSha256HexSync` signs text with HMAC-SHA-256 under the same Bun/Node 20.16.0+ (20.x) or 22.3.0+ requirement.
9
+ * - `timingSafeEqualHex` compares hex digests without leaking the first differing byte (same
10
+ * Bun/Node 20.16.0+ (20.x) or 22.3.0+ requirement as the other synchronous helpers).
11
+ * - `createIncrementalHash` returns a streaming hasher for accumulating data across multiple
12
+ * `.update()` calls (same Bun/Node 20.16.0+ (20.x) or 22.3.0+ requirement).
13
+ *
14
+ * The synchronous helpers read `node:crypto` via `process.getBuiltinModule` rather than a literal
15
+ * `require(...)` call, specifically so that bundling this package for a browser build never injects
16
+ * a `createRequire`/`node:module` shim (see AB-31). That trades away support for Node.js versions
17
+ * outside `^20.16.0 || >=22.3.0` for the synchronous path; a caller that must support older Node can
18
+ * still supply its own loader via the `corvidae.cryptography.hash.runtime` global override
19
+ * (see `getHashRuntimeOverride` below) — set `{ require: (specifier) => require(specifier) }` from
20
+ * a CommonJS entry point where a real `require` exists.
21
+ */
22
+ const runtimeOverrideSymbol = Symbol.for('corvidae.cryptography.hash.runtime');
23
+ function getHashRuntimeOverride() {
24
+ const value = globalThis[runtimeOverrideSymbol];
25
+ return isHashRuntimeOverride(value) ? value : undefined;
26
+ }
27
+ function isHashRuntimeOverride(value) {
28
+ if (typeof value !== 'object' || value === null)
29
+ return false;
30
+ return (hasOptionalProperty(value, 'require', isOptionalModuleLoader) &&
31
+ hasOptionalProperty(value, 'getBuiltinModule', isOptionalModuleLoader));
32
+ }
33
+ function hasOptionalProperty(value, key, isValid) {
34
+ return !Reflect.has(value, key) || isValid(Reflect.get(value, key));
35
+ }
36
+ function isOptionalModuleLoader(value) {
37
+ return value === undefined || isModuleLoader(value);
38
+ }
39
+ function isModuleLoader(value) {
40
+ return typeof value === 'function';
41
+ }
42
+ function isNodeCrypto(value) {
43
+ if (typeof value !== 'object' || value === null)
44
+ return false;
45
+ return (hasOptionalProperty(value, 'createHash', isOptionalFunction) &&
46
+ hasOptionalProperty(value, 'createHmac', isOptionalFunction) &&
47
+ hasOptionalProperty(value, 'timingSafeEqual', isOptionalFunction));
48
+ }
49
+ function isOptionalFunction(value) {
50
+ return value === undefined || typeof value === 'function';
51
+ }
52
+ function getBuiltinModuleFn() {
53
+ const runtimeOverride = getHashRuntimeOverride();
54
+ if (runtimeOverride && 'getBuiltinModule' in runtimeOverride) {
55
+ return runtimeOverride.getBuiltinModule;
56
+ }
57
+ const runtime = Reflect.get(globalThis, 'process');
58
+ if (typeof runtime !== 'object' || runtime === null || !('getBuiltinModule' in runtime)) {
59
+ return undefined;
60
+ }
61
+ const loader = runtime.getBuiltinModule;
62
+ return isModuleLoader(loader) ? loader.bind(runtime) : undefined;
63
+ }
64
+ function requireNodeCrypto() {
65
+ const runtimeOverride = getHashRuntimeOverride();
66
+ const injectedLoader = runtimeOverride?.require;
67
+ if (injectedLoader) {
68
+ const module = injectedLoader('node:crypto');
69
+ if (isNodeCrypto(module))
70
+ return module;
71
+ throw new Error('node:crypto is not available in this environment.');
72
+ }
73
+ // `process.getBuiltinModule` reads a Node/Bun builtin without a literal `require(...)` call,
74
+ // so ESM bundlers never see a reason to inject a `createRequire` shim for this file — a plain
75
+ // `require('node:crypto')` here would force that shim into every consumer's bundle, browser
76
+ // builds included, even when this function is never reached at runtime.
77
+ const builtinModule = getBuiltinModuleFn()?.('node:crypto');
78
+ if (isNodeCrypto(builtinModule))
79
+ return builtinModule;
80
+ throw new Error('node:crypto is not available in this environment.');
81
+ }
82
+ /**
83
+ * Computes the SHA-256 hex digest of a string using the Web Crypto API.
84
+ * Works in all environments: browsers, Node.js, Bun, Deno.
85
+ */
86
+ export async function sha256Hex(text) {
87
+ return sha256BytesHex(new TextEncoder().encode(text));
88
+ }
89
+ /**
90
+ * Computes the SHA-256 hex digest of raw bytes using the Web Crypto API.
91
+ * Works in all environments: browsers, Node.js, Bun, Deno.
92
+ *
93
+ * Digesting bytes rather than a string is what lets a caller hash content it cannot decode —
94
+ * a bundled image or font, say — without first corrupting it through a lossy text round trip.
95
+ */
96
+ export async function sha256BytesHex(data) {
97
+ // Passed through without copying: `crypto.subtle.digest` honors an `ArrayBufferView`'s
98
+ // `byteOffset` and `byteLength`, so a `Uint8Array` that is a window into a larger buffer already
99
+ // hashes only its own bytes.
100
+ const view = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
101
+ const buffer = await crypto.subtle.digest('SHA-256', view);
102
+ const bytes = new Uint8Array(buffer);
103
+ let hex = '';
104
+ for (let i = 0; i < bytes.length; i++) {
105
+ hex += bytes[i].toString(16).padStart(2, '0');
106
+ }
107
+ return hex;
108
+ }
109
+ /**
110
+ * Computes the SHA-256 hex digest of a string synchronously.
111
+ * Uses `node:crypto`, which Bun and Node.js both provide.
112
+ * Throws in browser environments where no synchronous crypto API is available.
113
+ */
114
+ export function sha256HexSync(text) {
115
+ try {
116
+ const { createHash } = requireNodeCrypto();
117
+ if (!createHash)
118
+ throw new Error('createHash is unavailable.');
119
+ return createHash('sha256').update(text).digest('hex');
120
+ }
121
+ catch {
122
+ throw new Error('sha256HexSync is not available in this environment. Use the async sha256Hex instead, which works everywhere via Web Crypto.');
123
+ }
124
+ }
125
+ /** Computes the SHA-256 hex digest of raw bytes synchronously. */
126
+ export function sha256BytesHexSync(data) {
127
+ try {
128
+ const { createHash } = requireNodeCrypto();
129
+ if (!createHash)
130
+ throw new Error('createHash is unavailable.');
131
+ return createHash('sha256').update(data).digest('hex');
132
+ }
133
+ catch {
134
+ throw new Error('sha256BytesHexSync is not available in this environment. Use the async sha256BytesHex instead, which works everywhere via Web Crypto.');
135
+ }
136
+ }
137
+ /** Computes a SHA-256 digest in the base64url representation PKCE requires. */
138
+ export function sha256Base64UrlSync(text) {
139
+ try {
140
+ const { createHash } = requireNodeCrypto();
141
+ if (!createHash)
142
+ throw new Error('createHash is unavailable.');
143
+ return createHash('sha256').update(text).digest('base64url');
144
+ }
145
+ catch {
146
+ throw new Error('sha256Base64UrlSync is not available in this environment.');
147
+ }
148
+ }
149
+ /**
150
+ * Computes an HMAC-SHA-256 hex signature synchronously.
151
+ * Uses `node:crypto`, which Bun and Node.js both provide.
152
+ * Throws in browser environments where no synchronous HMAC API is available.
153
+ */
154
+ export function hmacSha256HexSync(secret, text) {
155
+ try {
156
+ const { createHmac } = requireNodeCrypto();
157
+ if (!createHmac)
158
+ throw new Error('createHmac is unavailable.');
159
+ return createHmac('sha256', secret).update(text).digest('hex');
160
+ }
161
+ catch {
162
+ throw new Error('hmacSha256HexSync is not available in this environment. Use Web Crypto for browser-compatible HMAC signing.');
163
+ }
164
+ }
165
+ /**
166
+ * Compares two hex strings with Node's timing-safe equality when available.
167
+ * Invalid hex strings and different-length values are never equal.
168
+ */
169
+ export function timingSafeEqualHex(left, right) {
170
+ if (left.length !== right.length ||
171
+ left.length % 2 !== 0 ||
172
+ !/^[0-9a-f]+$/i.test(left) ||
173
+ !/^[0-9a-f]+$/i.test(right)) {
174
+ return false;
175
+ }
176
+ try {
177
+ const { timingSafeEqual } = requireNodeCrypto();
178
+ if (!timingSafeEqual)
179
+ throw new Error('timingSafeEqual is unavailable.');
180
+ const leftBytes = Uint8Array.from(left.match(/../g) ?? [], (byte) => Number.parseInt(byte, 16));
181
+ const rightBytes = Uint8Array.from(right.match(/../g) ?? [], (byte) => Number.parseInt(byte, 16));
182
+ return timingSafeEqual(leftBytes, rightBytes);
183
+ }
184
+ catch {
185
+ throw new Error('timingSafeEqualHex is not available in this environment.');
186
+ }
187
+ }
188
+ /** Compares UTF-8 text with Node's timing-safe equality for equal-size inputs. */
189
+ export function timingSafeEqualText(left, right) {
190
+ const encoder = new TextEncoder();
191
+ const leftBytes = encoder.encode(left);
192
+ const rightBytes = encoder.encode(right);
193
+ if (leftBytes.length !== rightBytes.length)
194
+ return false;
195
+ try {
196
+ const { timingSafeEqual } = requireNodeCrypto();
197
+ if (!timingSafeEqual)
198
+ throw new Error('timingSafeEqual is unavailable.');
199
+ return timingSafeEqual(leftBytes, rightBytes);
200
+ }
201
+ catch {
202
+ throw new Error('timingSafeEqualText is not available in this environment.');
203
+ }
204
+ }
205
+ /**
206
+ * Creates an incremental (streaming) hash for accumulating data across multiple `.update()` calls.
207
+ * Uses `node:crypto`, which Bun and Node.js both provide.
208
+ * Throws in browser environments where no synchronous streaming crypto API is available.
209
+ *
210
+ * @param algorithm - Hash algorithm to use. Default: `'sha256'`.
211
+ */
212
+ export function createIncrementalHash(algorithm = 'sha256') {
213
+ let createHash;
214
+ try {
215
+ const available = requireNodeCrypto().createHash;
216
+ if (!available)
217
+ throw new Error('createHash is unavailable.');
218
+ createHash = available;
219
+ }
220
+ catch {
221
+ throw new Error('createIncrementalHash is not available in this environment. Use the async sha256Hex instead, which works everywhere via Web Crypto.');
222
+ }
223
+ // Outside the `try`, so an unsupported algorithm reports its own error rather than a missing runtime.
224
+ const hash = createHash(algorithm);
225
+ return {
226
+ update(data) {
227
+ hash.update(data);
228
+ },
229
+ digest() {
230
+ return hash.digest('hex');
231
+ },
232
+ };
233
+ }
@@ -0,0 +1,4 @@
1
+ export { CryptographyError, decrypt, decryptBytes, encrypt, exportEncryptionKey, generateEncryptionKey, importEncryptionKey, } from "./encryption.js";
2
+ export type { CryptographyErrorCode, EncryptedValue, EncryptionKey, ImportEncryptionKeyOptions, Keyring, } from "./encryption.js";
3
+ export { createIncrementalHash, hmacSha256HexSync, sha256Base64UrlSync, sha256BytesHex, sha256BytesHexSync, sha256Hex, sha256HexSync, timingSafeEqualHex, timingSafeEqualText, } from "./hash.js";
4
+ export type { IncrementalHash } from "./hash.js";
@@ -0,0 +1,2 @@
1
+ export { CryptographyError, decrypt, decryptBytes, encrypt, exportEncryptionKey, generateEncryptionKey, importEncryptionKey, } from "./encryption.js";
2
+ export { createIncrementalHash, hmacSha256HexSync, sha256Base64UrlSync, sha256BytesHex, sha256BytesHexSync, sha256Hex, sha256HexSync, timingSafeEqualHex, timingSafeEqualText, } from "./hash.js";
@@ -5,12 +5,6 @@
5
5
  * parsing instead of re-deriving it.
6
6
  */
7
7
  export declare function expandIpv6Groups(address: string): string[];
8
- /**
9
- * Strips a trailing `:port` suffix from an address/port pair, handling
10
- * both bracketed IPv6 (`[2001:db8::1]:4711`) and IPv4 (`1.2.3.4:5678`)
11
- * forms. Returns the input unchanged when no port suffix is present.
12
- */
13
- export declare function stripPort(input: string): string;
14
8
  /**
15
9
  * Canonicalizes an IPv4, IPv4-mapped IPv6, or IPv6 address string into one
16
10
  * consistent representation: lowercase, zone-id stripped, IPv4-mapped IPv6