@peac/middleware-express 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,88 @@
1
+ # @peac/middleware-express
2
+
3
+ Express.js middleware for automatic PEAC receipt issuance.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @peac/middleware-express
9
+ ```
10
+
11
+ Requires Express as a peer dependency (`^4.18.0 || ^5.0.0`).
12
+
13
+ ## Quick Start
14
+
15
+ ```typescript
16
+ import express from 'express';
17
+ import { peacMiddleware } from '@peac/middleware-express';
18
+
19
+ const app = express();
20
+
21
+ app.use(
22
+ peacMiddleware({
23
+ issuer: 'https://api.example.com',
24
+ signingKey: {
25
+ kty: 'OKP',
26
+ crv: 'Ed25519',
27
+ x: '<base64url public key>',
28
+ d: '<base64url private key>',
29
+ },
30
+ keyId: 'prod-2026-02',
31
+ })
32
+ );
33
+
34
+ app.get('/api/data', (req, res) => {
35
+ res.json({ message: 'Hello World' });
36
+ // PEAC-Receipt header automatically added
37
+ });
38
+ ```
39
+
40
+ ## API
41
+
42
+ ### `peacMiddleware(config)`
43
+
44
+ Returns Express middleware that automatically adds PEAC receipts to responses.
45
+
46
+ ```typescript
47
+ interface ExpressMiddlewareConfig extends MiddlewareConfig {
48
+ skip?: (req: Request) => boolean;
49
+ audienceExtractor?: (req: Request) => string;
50
+ subjectExtractor?: (req: Request) => string | undefined;
51
+ onError?: (error: Error, req: Request, res: Response) => void;
52
+ }
53
+ ```
54
+
55
+ ### `peacMiddlewareSync(config)`
56
+
57
+ Synchronous variant for simpler setups where async signing is not needed.
58
+
59
+ ### `getReceiptFromResponse(res)`
60
+
61
+ Extract the PEAC receipt from a response (for testing/debugging).
62
+
63
+ ### `hasPeacContext(req)`
64
+
65
+ Type guard checking if the request has PEAC context attached.
66
+
67
+ ## Configuration Options
68
+
69
+ - **`skip`** -- Skip receipt generation for certain routes (e.g., health checks)
70
+ - **`audienceExtractor`** -- Custom audience extraction from request (default: request origin)
71
+ - **`subjectExtractor`** -- Custom subject extraction from request
72
+ - **`onError`** -- Error handler for receipt generation failures (failures never break the response)
73
+
74
+ All options from `@peac/middleware-core` `MiddlewareConfig` are also supported (issuer, signingKey, keyId, expiresIn, transport, maxHeaderSize).
75
+
76
+ ## Error Handling
77
+
78
+ Receipt generation failures are isolated -- they never break the HTTP response. By default, errors are logged to console. Provide an `onError` callback for custom handling.
79
+
80
+ ## License
81
+
82
+ Apache-2.0
83
+
84
+ ---
85
+
86
+ PEAC Protocol is an open source project stewarded by Originary and community contributors.
87
+
88
+ [Docs](https://www.peacprotocol.org) | [GitHub](https://github.com/peacprotocol/peac) | [Originary](https://www.originary.xyz)
@@ -0,0 +1,35 @@
1
+ /**
2
+ * PEAC Middleware for Express.js
3
+ *
4
+ * Express.js middleware for automatic PEAC receipt issuance.
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * import express from 'express';
9
+ * import { peacMiddleware } from '@peac/middleware-express';
10
+ *
11
+ * const app = express();
12
+ *
13
+ * app.use(peacMiddleware({
14
+ * issuer: 'https://api.example.com',
15
+ * signingKey: {
16
+ * kty: 'OKP',
17
+ * crv: 'Ed25519',
18
+ * x: '<base64url public key>',
19
+ * d: '<base64url private key>',
20
+ * },
21
+ * keyId: 'prod-2026-02',
22
+ * }));
23
+ *
24
+ * app.get('/api/data', (req, res) => {
25
+ * res.json({ message: 'Hello World' });
26
+ * // PEAC-Receipt header automatically added
27
+ * });
28
+ * ```
29
+ *
30
+ * @packageDocumentation
31
+ */
32
+ export { peacMiddleware, peacMiddlewareSync, getReceiptFromResponse, hasPeacContext, } from './middleware.js';
33
+ export type { ExpressMiddlewareConfig, RequestWithPeacContext } from './middleware.js';
34
+ export type { MiddlewareConfig, RequestContext, ResponseContext, ReceiptResult, Ed25519PrivateJwk, } from '@peac/middleware-core';
35
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAGH,OAAO,EACL,cAAc,EACd,kBAAkB,EAClB,sBAAsB,EACtB,cAAc,GACf,MAAM,iBAAiB,CAAC;AAGzB,YAAY,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAGvF,YAAY,EACV,gBAAgB,EAChB,cAAc,EACd,eAAe,EACf,aAAa,EACb,iBAAiB,GAClB,MAAM,uBAAuB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ /**
3
+ * PEAC Middleware for Express.js
4
+ *
5
+ * Express.js middleware for automatic PEAC receipt issuance.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import express from 'express';
10
+ * import { peacMiddleware } from '@peac/middleware-express';
11
+ *
12
+ * const app = express();
13
+ *
14
+ * app.use(peacMiddleware({
15
+ * issuer: 'https://api.example.com',
16
+ * signingKey: {
17
+ * kty: 'OKP',
18
+ * crv: 'Ed25519',
19
+ * x: '<base64url public key>',
20
+ * d: '<base64url private key>',
21
+ * },
22
+ * keyId: 'prod-2026-02',
23
+ * }));
24
+ *
25
+ * app.get('/api/data', (req, res) => {
26
+ * res.json({ message: 'Hello World' });
27
+ * // PEAC-Receipt header automatically added
28
+ * });
29
+ * ```
30
+ *
31
+ * @packageDocumentation
32
+ */
33
+ Object.defineProperty(exports, "__esModule", { value: true });
34
+ exports.hasPeacContext = exports.getReceiptFromResponse = exports.peacMiddlewareSync = exports.peacMiddleware = void 0;
35
+ // Middleware
36
+ var middleware_js_1 = require("./middleware.js");
37
+ Object.defineProperty(exports, "peacMiddleware", { enumerable: true, get: function () { return middleware_js_1.peacMiddleware; } });
38
+ Object.defineProperty(exports, "peacMiddlewareSync", { enumerable: true, get: function () { return middleware_js_1.peacMiddlewareSync; } });
39
+ Object.defineProperty(exports, "getReceiptFromResponse", { enumerable: true, get: function () { return middleware_js_1.getReceiptFromResponse; } });
40
+ Object.defineProperty(exports, "hasPeacContext", { enumerable: true, get: function () { return middleware_js_1.hasPeacContext; } });
41
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;;;AAEH,aAAa;AACb,iDAKyB;AAJvB,+GAAA,cAAc,OAAA;AACd,mHAAA,kBAAkB,OAAA;AAClB,uHAAA,sBAAsB,OAAA;AACtB,+GAAA,cAAc,OAAA"}
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Express.js Middleware for PEAC Receipt Issuance
3
+ *
4
+ * Intercepts responses and adds PEAC receipts automatically.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ import type { Request, Response, RequestHandler } from 'express';
9
+ import { type MiddlewareConfig, type RequestContext } from '@peac/middleware-core';
10
+ /**
11
+ * Express-specific middleware configuration
12
+ */
13
+ export interface ExpressMiddlewareConfig extends MiddlewareConfig {
14
+ /** Skip receipt generation for certain routes */
15
+ skip?: (req: Request) => boolean;
16
+ /** Custom audience extraction from request */
17
+ audienceExtractor?: (req: Request) => string;
18
+ /** Custom subject extraction from request */
19
+ subjectExtractor?: (req: Request) => string | undefined;
20
+ /** Error handler for receipt generation failures */
21
+ onError?: (error: Error, req: Request, res: Response) => void;
22
+ }
23
+ /**
24
+ * Symbol to store PEAC context on request
25
+ */
26
+ declare const PEAC_CONTEXT_KEY: unique symbol;
27
+ /**
28
+ * Request with PEAC context attached
29
+ */
30
+ export interface RequestWithPeacContext extends Request {
31
+ [PEAC_CONTEXT_KEY]?: RequestContext;
32
+ }
33
+ /**
34
+ * Check if a request has PEAC context
35
+ */
36
+ export declare function hasPeacContext(req: Request): req is RequestWithPeacContext;
37
+ /**
38
+ * Get the PEAC receipt from a response (for testing/debugging)
39
+ *
40
+ * @param res - Express response object
41
+ * @returns Receipt JWS if present, undefined otherwise
42
+ */
43
+ export declare function getReceiptFromResponse(res: Response): string | undefined;
44
+ /**
45
+ * Express middleware that adds PEAC receipts to responses
46
+ *
47
+ * The middleware intercepts `res.json()` and `res.send()` to inject
48
+ * PEAC receipts into responses. For header transport (default), the
49
+ * receipt is added as a `PEAC-Receipt` header. For body transport,
50
+ * the response is wrapped in a `{ data, peac_receipt }` structure.
51
+ *
52
+ * @param config - Middleware configuration
53
+ * @returns Express request handler
54
+ *
55
+ * @example
56
+ * ```typescript
57
+ * import express from 'express';
58
+ * import { peacMiddleware } from '@peac/middleware-express';
59
+ *
60
+ * const app = express();
61
+ *
62
+ * // Add PEAC middleware
63
+ * app.use(peacMiddleware({
64
+ * issuer: 'https://api.example.com',
65
+ * signingKey: privateKey,
66
+ * keyId: 'prod-2026-02',
67
+ * }));
68
+ *
69
+ * app.get('/api/data', (req, res) => {
70
+ * res.json({ items: [1, 2, 3] });
71
+ * // PEAC-Receipt header automatically added
72
+ * });
73
+ * ```
74
+ */
75
+ export declare function peacMiddleware(config: ExpressMiddlewareConfig): RequestHandler;
76
+ /**
77
+ * Create middleware with synchronous receipt generation (blocking)
78
+ *
79
+ * This variant waits for receipt generation before sending the response.
80
+ * Use this when you need to guarantee the receipt is in the response,
81
+ * but be aware it adds latency.
82
+ *
83
+ * @param config - Middleware configuration
84
+ * @returns Express request handler
85
+ */
86
+ export declare function peacMiddlewareSync(config: ExpressMiddlewareConfig): RequestHandler;
87
+ export {};
88
+ //# sourceMappingURL=middleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../src/middleware.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAgB,cAAc,EAAE,MAAM,SAAS,CAAC;AAC/E,OAAO,EAGL,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACpB,MAAM,uBAAuB,CAAC;AAE/B;;GAEG;AACH,MAAM,WAAW,uBAAwB,SAAQ,gBAAgB;IAC/D,iDAAiD;IACjD,IAAI,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,OAAO,CAAC;IAEjC,8CAA8C;IAC9C,iBAAiB,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,MAAM,CAAC;IAE7C,6CAA6C;IAC7C,gBAAgB,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,MAAM,GAAG,SAAS,CAAC;IAExD,oDAAoD;IACpD,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,KAAK,IAAI,CAAC;CAC/D;AAED;;GAEG;AACH,QAAA,MAAM,gBAAgB,eAAyB,CAAC;AAEhD;;GAEG;AACH,MAAM,WAAW,sBAAuB,SAAQ,OAAO;IACrD,CAAC,gBAAgB,CAAC,CAAC,EAAE,cAAc,CAAC;CACrC;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,IAAI,sBAAsB,CAE1E;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,QAAQ,GAAG,MAAM,GAAG,SAAS,CAGxE;AAeD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,uBAAuB,GAAG,cAAc,CA+E9E;AAED;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,uBAAuB,GAAG,cAAc,CA4ElF"}
@@ -0,0 +1,220 @@
1
+ "use strict";
2
+ /**
3
+ * Express.js Middleware for PEAC Receipt Issuance
4
+ *
5
+ * Intercepts responses and adds PEAC receipts automatically.
6
+ *
7
+ * @packageDocumentation
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.hasPeacContext = hasPeacContext;
11
+ exports.getReceiptFromResponse = getReceiptFromResponse;
12
+ exports.peacMiddleware = peacMiddleware;
13
+ exports.peacMiddlewareSync = peacMiddlewareSync;
14
+ const middleware_core_1 = require("@peac/middleware-core");
15
+ /**
16
+ * Symbol to store PEAC context on request
17
+ */
18
+ const PEAC_CONTEXT_KEY = Symbol('peac-context');
19
+ /**
20
+ * Check if a request has PEAC context
21
+ */
22
+ function hasPeacContext(req) {
23
+ return PEAC_CONTEXT_KEY in req;
24
+ }
25
+ /**
26
+ * Get the PEAC receipt from a response (for testing/debugging)
27
+ *
28
+ * @param res - Express response object
29
+ * @returns Receipt JWS if present, undefined otherwise
30
+ */
31
+ function getReceiptFromResponse(res) {
32
+ const receipt = res.getHeader('PEAC-Receipt');
33
+ return typeof receipt === 'string' ? receipt : undefined;
34
+ }
35
+ /**
36
+ * Convert Express request to RequestContext
37
+ */
38
+ function buildRequestContext(req) {
39
+ return {
40
+ method: req.method,
41
+ path: req.path,
42
+ headers: req.headers,
43
+ body: req.body,
44
+ timestamp: Date.now(),
45
+ };
46
+ }
47
+ /**
48
+ * Express middleware that adds PEAC receipts to responses
49
+ *
50
+ * The middleware intercepts `res.json()` and `res.send()` to inject
51
+ * PEAC receipts into responses. For header transport (default), the
52
+ * receipt is added as a `PEAC-Receipt` header. For body transport,
53
+ * the response is wrapped in a `{ data, peac_receipt }` structure.
54
+ *
55
+ * @param config - Middleware configuration
56
+ * @returns Express request handler
57
+ *
58
+ * @example
59
+ * ```typescript
60
+ * import express from 'express';
61
+ * import { peacMiddleware } from '@peac/middleware-express';
62
+ *
63
+ * const app = express();
64
+ *
65
+ * // Add PEAC middleware
66
+ * app.use(peacMiddleware({
67
+ * issuer: 'https://api.example.com',
68
+ * signingKey: privateKey,
69
+ * keyId: 'prod-2026-02',
70
+ * }));
71
+ *
72
+ * app.get('/api/data', (req, res) => {
73
+ * res.json({ items: [1, 2, 3] });
74
+ * // PEAC-Receipt header automatically added
75
+ * });
76
+ * ```
77
+ */
78
+ function peacMiddleware(config) {
79
+ // Validate configuration at initialization
80
+ (0, middleware_core_1.validateConfig)(config);
81
+ return async function peacReceiptMiddleware(req, res, next) {
82
+ // Check if we should skip this request
83
+ if (config.skip?.(req)) {
84
+ next();
85
+ return;
86
+ }
87
+ // Build and store request context
88
+ const requestContext = buildRequestContext(req);
89
+ req[PEAC_CONTEXT_KEY] = requestContext;
90
+ // Enhance config with Express-specific extractors
91
+ const enhancedConfig = {
92
+ ...config,
93
+ claimsGenerator: async (ctx) => {
94
+ const baseClaims = config.claimsGenerator ? await config.claimsGenerator(ctx) : {};
95
+ return {
96
+ ...baseClaims,
97
+ // Override audience if custom extractor provided
98
+ ...(config.audienceExtractor && { aud: config.audienceExtractor(req) }),
99
+ // Add subject if extractor provided
100
+ ...(config.subjectExtractor && { sub: config.subjectExtractor(req) }),
101
+ };
102
+ },
103
+ };
104
+ // Store original json method
105
+ const originalJson = res.json.bind(res);
106
+ // Override res.json to inject receipt
107
+ res.json = function jsonWithReceipt(body) {
108
+ // Generate receipt asynchronously
109
+ (0, middleware_core_1.createReceipt)(enhancedConfig, requestContext, {
110
+ statusCode: res.statusCode,
111
+ headers: res.getHeaders(),
112
+ body,
113
+ })
114
+ .then((result) => {
115
+ // Add headers from receipt result
116
+ for (const [key, value] of Object.entries(result.headers)) {
117
+ res.setHeader(key, value);
118
+ }
119
+ // If body transport, use wrapped body
120
+ if (result.bodyWrapper) {
121
+ return originalJson(result.bodyWrapper);
122
+ }
123
+ return originalJson(body);
124
+ })
125
+ .catch((error) => {
126
+ // Handle errors without breaking the response
127
+ if (config.onError) {
128
+ config.onError(error, req, res);
129
+ }
130
+ else {
131
+ // Log but don't fail the response
132
+ console.error('[PEAC] Receipt generation failed:', error.message);
133
+ }
134
+ // Send original body on error
135
+ return originalJson(body);
136
+ });
137
+ // Return response for chaining (synchronous return)
138
+ // The actual response will be sent by the promise chain
139
+ return res;
140
+ };
141
+ next();
142
+ };
143
+ }
144
+ /**
145
+ * Create middleware with synchronous receipt generation (blocking)
146
+ *
147
+ * This variant waits for receipt generation before sending the response.
148
+ * Use this when you need to guarantee the receipt is in the response,
149
+ * but be aware it adds latency.
150
+ *
151
+ * @param config - Middleware configuration
152
+ * @returns Express request handler
153
+ */
154
+ function peacMiddlewareSync(config) {
155
+ // Validate configuration at initialization
156
+ (0, middleware_core_1.validateConfig)(config);
157
+ return async function peacReceiptMiddlewareSync(req, res, next) {
158
+ // Check if we should skip this request
159
+ if (config.skip?.(req)) {
160
+ next();
161
+ return;
162
+ }
163
+ // Build and store request context
164
+ const requestContext = buildRequestContext(req);
165
+ req[PEAC_CONTEXT_KEY] = requestContext;
166
+ // Enhance config with Express-specific extractors
167
+ const enhancedConfig = {
168
+ ...config,
169
+ claimsGenerator: async (ctx) => {
170
+ const baseClaims = config.claimsGenerator ? await config.claimsGenerator(ctx) : {};
171
+ return {
172
+ ...baseClaims,
173
+ ...(config.audienceExtractor && { aud: config.audienceExtractor(req) }),
174
+ ...(config.subjectExtractor && { sub: config.subjectExtractor(req) }),
175
+ };
176
+ },
177
+ };
178
+ // Store original json method
179
+ const originalJson = res.json.bind(res);
180
+ // Override res.json to inject receipt synchronously
181
+ res.json = function jsonWithReceiptSync(body) {
182
+ // We can't make this truly sync due to crypto operations,
183
+ // but we can make it blocking by using a sync wrapper
184
+ const syncWrapper = async () => {
185
+ try {
186
+ const result = await (0, middleware_core_1.createReceipt)(enhancedConfig, requestContext, {
187
+ statusCode: res.statusCode,
188
+ headers: res.getHeaders(),
189
+ body,
190
+ });
191
+ // Add headers
192
+ for (const [key, value] of Object.entries(result.headers)) {
193
+ res.setHeader(key, value);
194
+ }
195
+ // Send response
196
+ if (result.bodyWrapper) {
197
+ originalJson(result.bodyWrapper);
198
+ }
199
+ else {
200
+ originalJson(body);
201
+ }
202
+ }
203
+ catch (error) {
204
+ if (config.onError) {
205
+ config.onError(error, req, res);
206
+ }
207
+ else {
208
+ console.error('[PEAC] Receipt generation failed:', error.message);
209
+ }
210
+ originalJson(body);
211
+ }
212
+ };
213
+ // Execute synchronously by blocking
214
+ syncWrapper();
215
+ return res;
216
+ };
217
+ next();
218
+ };
219
+ }
220
+ //# sourceMappingURL=middleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware.js","sourceRoot":"","sources":["../src/middleware.ts"],"names":[],"mappings":";AAAA;;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,CAAC;wBACnB,MAAM,CAAC,OAAO,CAAC,KAAc,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;oBAC3C,CAAC;yBAAM,CAAC;wBACN,OAAO,CAAC,KAAK,CAAC,mCAAmC,EAAG,KAAe,CAAC,OAAO,CAAC,CAAC;oBAC/E,CAAC;oBACD,YAAY,CAAC,IAAI,CAAC,CAAC;gBACrB,CAAC;YACH,CAAC,CAAC;YAEF,oCAAoC;YACpC,WAAW,EAAE,CAAC;YACd,OAAO,GAAG,CAAC;QACb,CAAC,CAAC;QAEF,IAAI,EAAE,CAAC;IACT,CAAC,CAAC;AACJ,CAAC"}
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@peac/middleware-express",
3
+ "version": "0.10.9",
4
+ "description": "Express.js middleware for automatic PEAC receipt issuance",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.js",
11
+ "require": "./dist/index.js",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/peacprotocol/peac.git",
18
+ "directory": "packages/middleware-express"
19
+ },
20
+ "author": "jithinraj <7850727+jithinraj@users.noreply.github.com>",
21
+ "license": "Apache-2.0",
22
+ "bugs": {
23
+ "url": "https://github.com/peacprotocol/peac/issues"
24
+ },
25
+ "homepage": "https://github.com/peacprotocol/peac#readme",
26
+ "files": [
27
+ "dist",
28
+ "README.md"
29
+ ],
30
+ "publishConfig": {
31
+ "access": "public",
32
+ "provenance": true
33
+ },
34
+ "dependencies": {
35
+ "@peac/middleware-core": "0.10.9"
36
+ },
37
+ "peerDependencies": {
38
+ "express": "^4.18.0 || ^5.0.0"
39
+ },
40
+ "devDependencies": {
41
+ "@types/express": "^4.17.21",
42
+ "@types/node": "^20.10.0",
43
+ "express": "^4.18.2",
44
+ "supertest": "^6.3.3",
45
+ "@types/supertest": "^6.0.2",
46
+ "typescript": "^5.3.3",
47
+ "vitest": "^1.1.0",
48
+ "@peac/crypto": "0.10.9"
49
+ },
50
+ "scripts": {
51
+ "prebuild": "rm -rf dist tsconfig.tsbuildinfo",
52
+ "build": "tsc",
53
+ "test": "vitest run",
54
+ "test:watch": "vitest",
55
+ "clean": "rm -rf dist tsconfig.tsbuildinfo"
56
+ }
57
+ }