@peac/middleware-core 0.10.9

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/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 PEAC Protocol Contributors
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,86 @@
1
+ # @peac/middleware-core
2
+
3
+ Framework-agnostic middleware primitives for PEAC receipt issuance.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @peac/middleware-core
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```typescript
14
+ import { createReceipt, validateConfig } from '@peac/middleware-core';
15
+
16
+ // Validate configuration at startup
17
+ const config = {
18
+ issuer: 'https://api.example.com',
19
+ signingKey: privateJwk, // Ed25519 JWK
20
+ keyId: 'prod-2026-02',
21
+ };
22
+ validateConfig(config);
23
+
24
+ // In a request handler
25
+ const result = await createReceipt(config, requestCtx, responseCtx);
26
+
27
+ // Add PEAC-Receipt header to response
28
+ for (const [key, value] of Object.entries(result.headers)) {
29
+ res.setHeader(key, value);
30
+ }
31
+ ```
32
+
33
+ ## API
34
+
35
+ ### `createReceipt(config, request, response)`
36
+
37
+ Create a signed PEAC receipt for a request/response pair. Returns a `ReceiptResult` with the JWS receipt, transport headers, and optional body wrapper.
38
+
39
+ ### `createReceiptWithClaims(config, claims)`
40
+
41
+ Create a receipt from explicit claims (bypasses request/response context extraction).
42
+
43
+ ### `wrapResponse(data, receipt)`
44
+
45
+ Wrap a response body with a PEAC receipt for body transport profile. Returns `{ data, peac_receipt }`.
46
+
47
+ ### `selectTransport(receipt, config)`
48
+
49
+ Determine appropriate transport based on receipt size: `'header'`, `'body'`, or `'pointer'`. Auto-falls back from header to body if receipt exceeds `maxHeaderSize` (default 4096 bytes).
50
+
51
+ ### `validateConfig(config)` / `validateConfigAsync(config)`
52
+
53
+ Validate middleware configuration at startup. Throws `ConfigError` if configuration is invalid.
54
+
55
+ ### `buildResponseHeaders(receipt)` / `buildReceiptResult(receipt, transport, body?)`
56
+
57
+ Lower-level utilities for constructing response headers and receipt results.
58
+
59
+ ## Configuration
60
+
61
+ ```typescript
62
+ interface MiddlewareConfig {
63
+ issuer: string; // Issuer URL (becomes `iss` claim)
64
+ signingKey: Ed25519PrivateJwk; // Ed25519 private key (JWK format)
65
+ keyId: string; // Key ID for JWKS lookup
66
+ expiresIn?: number; // Receipt expiration in seconds (default: 300)
67
+ transport?: 'header' | 'body' | 'pointer'; // Transport profile (default: 'header')
68
+ maxHeaderSize?: number; // Max header size before fallback (default: 4096)
69
+ pointerUrlGenerator?: (receipt: string) => Promise<string>;
70
+ claimsGenerator?: (context: RequestContext) => Promise<Partial<ReceiptClaimsInput>>;
71
+ }
72
+ ```
73
+
74
+ ## Error Handling
75
+
76
+ Configuration errors throw `ConfigError` at startup. Receipt generation errors are returned in the result rather than thrown, so receipt failures never break the HTTP response.
77
+
78
+ ## License
79
+
80
+ Apache-2.0
81
+
82
+ ---
83
+
84
+ PEAC Protocol is an open source project stewarded by Originary and community contributors.
85
+
86
+ [Docs](https://www.peacprotocol.org) | [GitHub](https://github.com/peacprotocol/peac) | [Originary](https://www.originary.xyz)
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Middleware Configuration Validation
3
+ *
4
+ * Validates middleware configuration before use.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ import type { MiddlewareConfig, ConfigValidationError } from './types.js';
9
+ /**
10
+ * Maximum path length for interaction binding (DoS protection)
11
+ */
12
+ export declare const MAX_PATH_LENGTH = 2048;
13
+ /**
14
+ * Default configuration values
15
+ */
16
+ export declare const CONFIG_DEFAULTS: {
17
+ readonly expiresIn: 300;
18
+ readonly transport: "header";
19
+ readonly maxHeaderSize: 4096;
20
+ readonly interactionBinding: "minimal";
21
+ };
22
+ /**
23
+ * Configuration validation error
24
+ */
25
+ export declare class ConfigError extends Error {
26
+ readonly errors: ConfigValidationError[];
27
+ constructor(errors: ConfigValidationError[]);
28
+ }
29
+ /**
30
+ * Validate middleware configuration
31
+ *
32
+ * @param config - Configuration to validate
33
+ * @throws ConfigError if configuration is invalid
34
+ *
35
+ * @example
36
+ * ```typescript
37
+ * try {
38
+ * validateConfig(config);
39
+ * } catch (e) {
40
+ * if (e instanceof ConfigError) {
41
+ * console.error('Config errors:', e.errors);
42
+ * }
43
+ * }
44
+ * ```
45
+ */
46
+ export declare function validateConfig(config: MiddlewareConfig): void;
47
+ /**
48
+ * Validate middleware configuration with async keypair verification
49
+ *
50
+ * This extends basic validation with cryptographic verification that
51
+ * the private key (d) correctly derives to the public key (x).
52
+ *
53
+ * @param config - Configuration to validate
54
+ * @throws ConfigError if configuration is invalid
55
+ *
56
+ * @example
57
+ * ```typescript
58
+ * await validateConfigAsync(config);
59
+ * ```
60
+ */
61
+ export declare function validateConfigAsync(config: MiddlewareConfig): Promise<void>;
62
+ /**
63
+ * Apply default values to configuration
64
+ */
65
+ export declare function applyDefaults(config: MiddlewareConfig): Required<Pick<MiddlewareConfig, 'expiresIn' | 'transport' | 'maxHeaderSize' | 'interactionBinding'>> & MiddlewareConfig;
66
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,KAAK,EAAE,gBAAgB,EAAE,qBAAqB,EAAqB,MAAM,YAAY,CAAC;AAE7F;;GAEG;AACH,eAAO,MAAM,eAAe,OAAO,CAAC;AAEpC;;GAEG;AACH,eAAO,MAAM,eAAe;;;;;CAKlB,CAAC;AAEX;;GAEG;AACH,qBAAa,WAAY,SAAQ,KAAK;IACpC,QAAQ,CAAC,MAAM,EAAE,qBAAqB,EAAE,CAAC;gBAE7B,MAAM,EAAE,qBAAqB,EAAE;CAM5C;AAgED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,gBAAgB,GAAG,IAAI,CA4E7D;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAsB,mBAAmB,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAgBjF;AAED;;GAEG;AACH,wBAAgB,aAAa,CAC3B,MAAM,EAAE,gBAAgB,GACvB,QAAQ,CACT,IAAI,CAAC,gBAAgB,EAAE,WAAW,GAAG,WAAW,GAAG,eAAe,GAAG,oBAAoB,CAAC,CAC3F,GACC,gBAAgB,CAQjB"}
package/dist/config.js ADDED
@@ -0,0 +1,226 @@
1
+ "use strict";
2
+ /**
3
+ * Middleware Configuration Validation
4
+ *
5
+ * Validates middleware configuration before use.
6
+ *
7
+ * @packageDocumentation
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.ConfigError = exports.CONFIG_DEFAULTS = exports.MAX_PATH_LENGTH = void 0;
11
+ exports.validateConfig = validateConfig;
12
+ exports.validateConfigAsync = validateConfigAsync;
13
+ exports.applyDefaults = applyDefaults;
14
+ const crypto_1 = require("@peac/crypto");
15
+ /**
16
+ * Maximum path length for interaction binding (DoS protection)
17
+ */
18
+ exports.MAX_PATH_LENGTH = 2048;
19
+ /**
20
+ * Default configuration values
21
+ */
22
+ exports.CONFIG_DEFAULTS = {
23
+ expiresIn: 300,
24
+ transport: 'header',
25
+ maxHeaderSize: 4096,
26
+ interactionBinding: 'minimal',
27
+ };
28
+ /**
29
+ * Configuration validation error
30
+ */
31
+ class ConfigError extends Error {
32
+ errors;
33
+ constructor(errors) {
34
+ const message = errors.map((e) => `${e.field}: ${e.message}`).join('; ');
35
+ super(`Invalid middleware configuration: ${message}`);
36
+ this.name = 'ConfigError';
37
+ this.errors = errors;
38
+ }
39
+ }
40
+ exports.ConfigError = ConfigError;
41
+ /**
42
+ * Validate a URL is HTTPS
43
+ */
44
+ function isValidHttpsUrl(url) {
45
+ try {
46
+ const parsed = new URL(url);
47
+ return parsed.protocol === 'https:';
48
+ }
49
+ catch {
50
+ return false;
51
+ }
52
+ }
53
+ /**
54
+ * Validate Ed25519 JWK private key
55
+ */
56
+ function validateSigningKey(key, errors) {
57
+ if (!key || typeof key !== 'object') {
58
+ errors.push({ field: 'signingKey', message: 'must be an object' });
59
+ return;
60
+ }
61
+ const jwk = key;
62
+ // Validate key type
63
+ if (jwk.kty !== 'OKP') {
64
+ errors.push({ field: 'signingKey.kty', message: 'must be "OKP" for Ed25519 keys' });
65
+ }
66
+ // Validate curve
67
+ if (jwk.crv !== 'Ed25519') {
68
+ errors.push({ field: 'signingKey.crv', message: 'must be "Ed25519"' });
69
+ }
70
+ // Validate public key
71
+ if (typeof jwk.x !== 'string') {
72
+ errors.push({ field: 'signingKey.x', message: 'must be a base64url string' });
73
+ }
74
+ else {
75
+ try {
76
+ const xBytes = (0, crypto_1.base64urlDecode)(jwk.x);
77
+ if (xBytes.length !== 32) {
78
+ errors.push({ field: 'signingKey.x', message: 'must be 32 bytes (base64url encoded)' });
79
+ }
80
+ }
81
+ catch {
82
+ errors.push({ field: 'signingKey.x', message: 'must be valid base64url encoding' });
83
+ }
84
+ }
85
+ // Validate private key
86
+ if (typeof jwk.d !== 'string') {
87
+ errors.push({ field: 'signingKey.d', message: 'must be a base64url string (private key)' });
88
+ }
89
+ else {
90
+ try {
91
+ const dBytes = (0, crypto_1.base64urlDecode)(jwk.d);
92
+ if (dBytes.length !== 32) {
93
+ errors.push({ field: 'signingKey.d', message: 'must be 32 bytes (base64url encoded)' });
94
+ }
95
+ }
96
+ catch {
97
+ errors.push({ field: 'signingKey.d', message: 'must be valid base64url encoding' });
98
+ }
99
+ }
100
+ }
101
+ /**
102
+ * Validate middleware configuration
103
+ *
104
+ * @param config - Configuration to validate
105
+ * @throws ConfigError if configuration is invalid
106
+ *
107
+ * @example
108
+ * ```typescript
109
+ * try {
110
+ * validateConfig(config);
111
+ * } catch (e) {
112
+ * if (e instanceof ConfigError) {
113
+ * console.error('Config errors:', e.errors);
114
+ * }
115
+ * }
116
+ * ```
117
+ */
118
+ function validateConfig(config) {
119
+ const errors = [];
120
+ // Validate issuer URL
121
+ if (!config.issuer) {
122
+ errors.push({ field: 'issuer', message: 'is required' });
123
+ }
124
+ else if (!isValidHttpsUrl(config.issuer)) {
125
+ errors.push({ field: 'issuer', message: 'must be a valid HTTPS URL' });
126
+ }
127
+ // Validate signing key
128
+ if (!config.signingKey) {
129
+ errors.push({ field: 'signingKey', message: 'is required' });
130
+ }
131
+ else {
132
+ validateSigningKey(config.signingKey, errors);
133
+ }
134
+ // Validate key ID
135
+ if (!config.keyId) {
136
+ errors.push({ field: 'keyId', message: 'is required' });
137
+ }
138
+ else if (typeof config.keyId !== 'string' || config.keyId.length === 0) {
139
+ errors.push({ field: 'keyId', message: 'must be a non-empty string' });
140
+ }
141
+ // Validate expiresIn (if provided)
142
+ if (config.expiresIn !== undefined) {
143
+ if (!Number.isInteger(config.expiresIn) || config.expiresIn <= 0) {
144
+ errors.push({ field: 'expiresIn', message: 'must be a positive integer' });
145
+ }
146
+ }
147
+ // Validate transport (if provided)
148
+ if (config.transport !== undefined) {
149
+ if (!['header', 'body', 'pointer'].includes(config.transport)) {
150
+ errors.push({ field: 'transport', message: 'must be "header", "body", or "pointer"' });
151
+ }
152
+ }
153
+ // Validate maxHeaderSize (if provided)
154
+ if (config.maxHeaderSize !== undefined) {
155
+ if (!Number.isInteger(config.maxHeaderSize) || config.maxHeaderSize <= 0) {
156
+ errors.push({ field: 'maxHeaderSize', message: 'must be a positive integer' });
157
+ }
158
+ }
159
+ // Validate pointer transport has URL generator
160
+ if (config.transport === 'pointer' && !config.pointerUrlGenerator) {
161
+ errors.push({
162
+ field: 'pointerUrlGenerator',
163
+ message: 'is required when transport is "pointer"',
164
+ });
165
+ }
166
+ // Validate interactionBinding (if provided)
167
+ if (config.interactionBinding !== undefined) {
168
+ if (!['minimal', 'off', 'full'].includes(config.interactionBinding)) {
169
+ errors.push({ field: 'interactionBinding', message: 'must be "minimal", "off", or "full"' });
170
+ }
171
+ }
172
+ // Validate claimsGenerator is a function (if provided)
173
+ if (config.claimsGenerator !== undefined && typeof config.claimsGenerator !== 'function') {
174
+ errors.push({ field: 'claimsGenerator', message: 'must be a function' });
175
+ }
176
+ // Validate pointerUrlGenerator is a function (if provided)
177
+ if (config.pointerUrlGenerator !== undefined &&
178
+ typeof config.pointerUrlGenerator !== 'function') {
179
+ errors.push({ field: 'pointerUrlGenerator', message: 'must be a function' });
180
+ }
181
+ if (errors.length > 0) {
182
+ throw new ConfigError(errors);
183
+ }
184
+ }
185
+ /**
186
+ * Validate middleware configuration with async keypair verification
187
+ *
188
+ * This extends basic validation with cryptographic verification that
189
+ * the private key (d) correctly derives to the public key (x).
190
+ *
191
+ * @param config - Configuration to validate
192
+ * @throws ConfigError if configuration is invalid
193
+ *
194
+ * @example
195
+ * ```typescript
196
+ * await validateConfigAsync(config);
197
+ * ```
198
+ */
199
+ async function validateConfigAsync(config) {
200
+ // First run synchronous validation
201
+ validateConfig(config);
202
+ // Then validate keypair consistency (d derives to x)
203
+ const jwk = config.signingKey;
204
+ const isValidKeypair = await (0, crypto_1.validateKeypair)(jwk);
205
+ if (!isValidKeypair) {
206
+ throw new ConfigError([
207
+ {
208
+ field: 'signingKey',
209
+ message: 'keypair inconsistent: private key (d) does not derive to public key (x)',
210
+ },
211
+ ]);
212
+ }
213
+ }
214
+ /**
215
+ * Apply default values to configuration
216
+ */
217
+ function applyDefaults(config) {
218
+ return {
219
+ ...config,
220
+ expiresIn: config.expiresIn ?? exports.CONFIG_DEFAULTS.expiresIn,
221
+ transport: config.transport ?? exports.CONFIG_DEFAULTS.transport,
222
+ maxHeaderSize: config.maxHeaderSize ?? exports.CONFIG_DEFAULTS.maxHeaderSize,
223
+ interactionBinding: config.interactionBinding ?? exports.CONFIG_DEFAULTS.interactionBinding,
224
+ };
225
+ }
226
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAiHH,wCA4EC;AAgBD,kDAgBC;AAKD,sCAaC;AA7OD,yCAAgE;AAGhE;;GAEG;AACU,QAAA,eAAe,GAAG,IAAI,CAAC;AAEpC;;GAEG;AACU,QAAA,eAAe,GAAG;IAC7B,SAAS,EAAE,GAAG;IACd,SAAS,EAAE,QAAiB;IAC5B,aAAa,EAAE,IAAI;IACnB,kBAAkB,EAAE,SAAk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SAAS,EAAE,MAAM,CAAC,SAAS,IAAI,uBAAe,CAAC,SAAS;QACxD,SAAS,EAAE,MAAM,CAAC,SAAS,IAAI,uBAAe,CAAC,SAAS;QACxD,aAAa,EAAE,MAAM,CAAC,aAAa,IAAI,uBAAe,CAAC,aAAa;QACpE,kBAAkB,EAAE,MAAM,CAAC,kBAAkB,IAAI,uBAAe,CAAC,kBAAkB;KACpF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * PEAC Middleware Core
3
+ *
4
+ * Framework-agnostic middleware primitives for PEAC receipt issuance.
5
+ *
6
+ * This package provides the core building blocks for integrating PEAC
7
+ * receipt issuance into any HTTP framework. For framework-specific
8
+ * implementations, see:
9
+ * - `@peac/middleware-express` for Express.js
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * import { createReceipt, validateConfig, wrapResponse } from '@peac/middleware-core';
14
+ *
15
+ * // Validate configuration at startup
16
+ * validateConfig(config);
17
+ *
18
+ * // In request handler
19
+ * const result = await createReceipt(config, requestCtx, responseCtx);
20
+ *
21
+ * // Add headers
22
+ * for (const [key, value] of Object.entries(result.headers)) {
23
+ * res.setHeader(key, value);
24
+ * }
25
+ *
26
+ * // Handle body transport
27
+ * if (result.bodyWrapper) {
28
+ * res.json(result.bodyWrapper);
29
+ * } else {
30
+ * res.json(originalBody);
31
+ * }
32
+ * ```
33
+ *
34
+ * @packageDocumentation
35
+ */
36
+ export type { MiddlewareConfig, RequestContext, ResponseContext, ReceiptResult, ReceiptClaimsInput, ConfigValidationError, Ed25519PrivateJwk, TransportSelectionInput, InteractionBindingMode, } from './types.js';
37
+ export { validateConfig, validateConfigAsync, ConfigError, CONFIG_DEFAULTS, MAX_PATH_LENGTH, applyDefaults, } from './config.js';
38
+ export { selectTransport, wrapResponse, buildResponseHeaders, buildReceiptResult, } from './transport.js';
39
+ export { createReceipt, createReceiptWithClaims } from './receipt.js';
40
+ export type { RateLimitStore, MemoryRateLimitStoreOptions } from './rate-limit.js';
41
+ export { MemoryRateLimitStore } from './rate-limit.js';
42
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAGH,YAAY,EACV,gBAAgB,EAChB,cAAc,EACd,eAAe,EACf,aAAa,EACb,kBAAkB,EAClB,qBAAqB,EACrB,iBAAiB,EACjB,uBAAuB,EACvB,sBAAsB,GACvB,MAAM,YAAY,CAAC;AAGpB,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,WAAW,EACX,eAAe,EACf,eAAe,EACf,aAAa,GACd,MAAM,aAAa,CAAC;AAGrB,OAAO,EACL,eAAe,EACf,YAAY,EACZ,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,gBAAgB,CAAC;AAGxB,OAAO,EAAE,aAAa,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAGtE,YAAY,EAAE,cAAc,EAAE,2BAA2B,EAAE,MAAM,iBAAiB,CAAC;AACnF,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC"}