@mpfrontend/security-bff 0.0.0-stage → 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,263 @@
1
- # Temporary Holding Version
1
+ # Security BFF
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Node HTTP handler for independently deployed, product-neutral OIDC mediation. Implements Authorization
4
+ Code with S256 PKCE, state and nonce, RS256 JWT/JWKS validation, opaque HttpOnly cookies, same-origin
5
+ and CSRF checks, endpoint/method/role allowlists, bounded request bodies and server-held token refresh.
6
+ The product supplies its API routes and identity-provider settings. No token crosses the presentation
7
+ boundary, and no upstream response header crosses it except the content headers that a streamed route
8
+ names (see "Streamed routes"). The browser calls Next.js; only its server calls this BFF.
9
+
10
+ An application can declare an allowlist with `supportedUiLocales`. A matching `ui_locales` value on
11
+ `/login`, or the matching value of an optional `uiLocaleCookie`, is forwarded through the standard OIDC
12
+ authorization request; unlisted values are ignored and an explicit query value wins over the cookie.
13
+ The identity provider remains responsible for translated login, registration and recovery messages.
14
+
15
+ `contextClaims` is an allowlist of claim names that `/context` returns under `claims`. The claims come from
16
+ the validated ID token at sign-in and from a refreshed ID token of the same subject at refresh
17
+ (`contextClaimSource: 'id'`, the default); `contextClaimSource: 'access'` takes them from the access token
18
+ instead. Only plain values are projected: a string of at most 512 characters, a finite number, a boolean
19
+ or a list of at most sixteen short strings. Objects, token-shaped strings and values beyond the 4 KiB
20
+ budget of the projection are left out, and a claim name that refers to a token (`*token*`, `at_hash`,
21
+ `c_hash`, `nonce`) is refused at startup. Tokens never reach `/context`, and no claim is written into a
22
+ cookie.
23
+
24
+ `preferenceCookie: {name, locales, themes}` names the preference cookie that an app shares with the
25
+ identity provider's pages (language and theme only, value `lang=<locale>&theme=<theme>`). On `/login`
26
+ the BFF takes `ui_locales` from an explicit query value first, then the cookie's language when it is
27
+ allowlisted, then the older whole-value `uiLocaleCookie`. An invalid value is ignored and never echoed;
28
+ the cookie never decides anything about authority.
29
+
30
+ `apiLocales: {supported, defaultLocale}` is the allowlist for the `Accept-Language` header the BFF sends
31
+ upstream. The browser's header is negotiated against it by quality, exact range and primary language;
32
+ only an allowlisted token is ever sent, and the default replaces anything else, including malformed or
33
+ crafted input. Without configuration only `en` is sent: English is the one language MP Frontend ships. A
34
+ product lists the locales its backends answer in, which may exclude English, for example
35
+ `{supported: ['<code>'], defaultLocale: '<code>'}`.
36
+
37
+ The default memory vault remains a single-process development profile; restart signs users out.
38
+ The `./session-store` export provides `SessionVault`, `createMemorySessionVault`, `createRedisSessionVault`,
39
+ `redisVaultSecurity` and `createVaultTicketStore`. A development configuration (`development: true`)
40
+ behaves as before and is still refused when `NODE_ENV=production`.
41
+
42
+ ## Client authentication
43
+
44
+ `clientAuthentication` configures how the BFF authenticates to the token endpoint, per BFF:
45
+
46
+ - `{method: 'private_key_jwt', key}` (RFC 7523): each token and revocation request carries a client
47
+ assertion signed with the host's private key, with `iss` and `sub` the client id, `aud` the issuer's
48
+ token endpoint, a unique `jti` and a lifetime of `CLIENT_ASSERTION_LIFETIME_SECONDS` (60 seconds). `key`
49
+ is `{keyId, privateKey, algorithm?}` (RS256, PS256 or ES256) or a function that returns the current one,
50
+ so that the provider can rotate keys by key id. No shared secret goes over the wire.
51
+ - `{method: 'client_secret_basic', secret}`: the secret, or a function that returns it, goes only into the
52
+ `Authorization: Basic` header of provider requests (RFC 6749 section 2.3.1).
53
+ - `{method: 'none', publicClient: true}`: a public client, sent with its client id only.
54
+
55
+ The key or secret is supplied by the host and only referenced: the package never stores it in a session,
56
+ logs it, returns it in an error or a response, or puts it in `/context`. The PKCE, state and nonce checks
57
+ are unchanged.
58
+
59
+ ## Session cookie and lifetimes
60
+
61
+ `session: {sameSite, idleTimeoutSeconds, absoluteLifetimeSeconds, authorizationClaims}` sets the session
62
+ policy:
63
+
64
+ - The session cookie may carry the `__Host-` prefix (Secure, `Path=/`, no `Domain`); the production
65
+ profile adds it by default (`production.hostPrefix: false` opts out), and the prefix requires an https
66
+ public origin. The cookie holds only the opaque session id, never a token or a claim.
67
+ - `sameSite` applies to the session cookie: `Strict` is recommended and is the production default; the
68
+ development default stays `Lax`. The login transaction cookie is always `Lax`, so that the provider's
69
+ redirect back carries it. With `Strict`, the callback answers with a small same-origin page that moves on
70
+ to `/`, because a browser does not send a Strict cookie on the next hop of a cross-site redirect chain.
71
+ - `idleTimeoutSeconds` (default 1800, 60 to 86400) and `absoluteLifetimeSeconds` (default 28800, 300 to
72
+ 604800, at least the idle timeout): a value outside its bounds refuses startup rather than being
73
+ shortened. An idle or expired session fails closed with 401 and is removed. Activity is recorded under
74
+ the session lease at most once a minute.
75
+ - The session id is new after every sign-in (an earlier id in the request is removed), and it rotates at
76
+ refresh when an authorization claim changes (`realm_access`, `resource_access`, `groups`, `scope`,
77
+ `tenant_id` by default); the response sets the new cookie and the old id stops working. A change of
78
+ subject or tenant still ends the session.
79
+
80
+ ## Re-authentication and step-up
81
+
82
+ A route may require a recent sign-in and, optionally, an authentication context class:
83
+ `authentication: {maxAge, acr}` on the route, where `acr` lists the values that count and must come from
84
+ the BFF's `acrValues` allowlist; `maxAge` alone needs no acr levels. When the session's `auth_time` is
85
+ older than `maxAge` or its `acr` is not listed, the BFF answers 401 with a typed body,
86
+ `{title: 'STEP_UP_REQUIRED', stepUp: {maxAge, acrValues, login, resubmit}}`, without calling the API.
87
+ An upstream 401 with an RFC 9470 challenge (`error="insufficient_user_authentication"`, `max_age`,
88
+ `acr_values`) becomes the same typed answer; its body and other headers stay behind, and the answer never
89
+ names the provider's origin. `login` is the BFF's own relative login path.
90
+
91
+ `/login` accepts `max_age`, `acr_values` (allowlisted values only) and `return_to`. The callback accepts the
92
+ new session only when the new ID token's `auth_time` is within `max_age` and its `acr` is one of the
93
+ requested values; otherwise it answers 401 `STEP_UP_FAILED`, creates nothing and leaves the earlier session
94
+ as it was. A successful step-up replaces the weaker session: its id and tokens are removed. `return_to` must
95
+ be a same-origin path that matches `returnPaths` (default `/`); another origin, a protocol-relative or
96
+ backslash path, or an unlisted path is refused with 400 before the provider is asked.
97
+
98
+ The BFF never holds or replays a write. `resubmit` is `idempotent` for a safe request or a write that
99
+ carries an `Idempotency-Key`, and `manual` otherwise: the presentation server resubmits an idempotent
100
+ request with the same key after the step-up, and asks the person again for any other write.
101
+
102
+ ## Back-channel logout
103
+
104
+ `backChannelLogout: true` enables `POST /backchannel-logout` (OpenID Connect Back-Channel Logout 1.0). The
105
+ body is the form `logout_token=<JWT>`. The token must be signed with the issuer's keys, carry the issuer as
106
+ `iss`, the client id in `aud`, `iat`, `exp` and a `jti`, contain the back-channel logout event, name a
107
+ `sid`, a `sub` or both, and contain no `nonce`; it is accepted for five minutes after `iat`. A valid token
108
+ removes every session of its `sid`, or of its subject when it has no `sid`, and the next request of that
109
+ browser gets 401. The answer is an empty 200; no session list or count is ever returned. A replayed `jti`
110
+ or any invalid token is answered 400 and changes nothing. While the session vault is unavailable the
111
+ endpoint answers 503 without recording the token, so that the provider's retry succeeds, and no session is
112
+ served meanwhile.
113
+
114
+ The vault indexes each session by the provider's session id (from the ID token's `sid`) and by subject;
115
+ the Redis index holds hashed session addresses only. A session is indexed before it is stored, at sign-in and
116
+ when its id is rotated at refresh, so that a failed index leaves no session that a logout could not find. A vault without `indexSession` and `revokeIndexed`
117
+ refuses the option at startup. The endpoint carries no browser session or CSRF token: route it only from
118
+ the identity provider's network path, for example a separate internal listener or an ingress rule that
119
+ admits the provider alone, and never expose it to browsers.
120
+
121
+ ## Streamed routes
122
+
123
+ A route of the allowlist may declare `stream`, for files of several megabytes that pass between the browser
124
+ and a backend. A route without it behaves exactly as before: the body is read whole up to 64 KiB, it must
125
+ be `application/json`, the answer is written as JSON with fixed headers, and the upstream call is bounded
126
+ by 15 seconds. An in-process route (`invoke`) cannot declare a stream; its contract is unchanged.
127
+
128
+ ```ts
129
+ {
130
+ method: 'PUT', pattern: /^\/v1\/documents\/[a-z0-9-]+$/, origin: 'https://documents.internal',
131
+ stream: {
132
+ requestTypes: ['<media type>'], // a body of any other type, or none, is refused with 415
133
+ maxRequestBytes: <bytes>, // a declared Content-Length above it is refused with 413
134
+ responseTypes: ['<media type>'], // an answer of any other type is refused with 502
135
+ responseHeaders: ['content-type', 'content-disposition'],
136
+ idleTimeoutMs: <ms>, totalTimeoutMs: <ms>, sessionCheckMs: <ms>,
137
+ },
138
+ }
139
+ ```
140
+
141
+ Every value is the consumer's: the package ships no list of media types, no size, no timeout and no
142
+ route. `createBff` refuses an incomplete or out-of-bounds policy with `INVALID_ROUTE_STREAM`: media types
143
+ are explicit `type/subtype` values without parameters or wildcards, a GET route has no request types or
144
+ size, `responseHeaders` comes from the closed set `STREAM_RESPONSE_HEADERS` (`content-type`,
145
+ `content-length`, `content-disposition`, `content-security-policy`) and includes `content-type`, and each
146
+ time is between 10 ms and one day with the idle timeout and the session check no longer than the total.
147
+ A route whose `responseTypes` lists a type that runs script when a browser shows it inline on the app's
148
+ origin (HTML, XHTML, SVG, any XML type, script) is refused with `INVALID_ROUTE_STREAM:SCRIPT_CAPABLE_TYPE`
149
+ unless `responseHeaders` names both `content-disposition` and `content-security-policy`, so that the
150
+ upstream can serve such an answer as an attachment or under a policy that sandboxes it.
151
+
152
+ Before any byte of the body is read, a streamed request passes every check of an ordinary route, in the
153
+ same order: the session and its refresh, Origin and the CSRF token for every method other than GET, the
154
+ allowlist and its roles, the Idempotency-Key rule, the correlation id and the route's sign-in
155
+ requirement. Then:
156
+
157
+ - **Size known first.** A request with a body must declare `Content-Length`: without it the answer is
158
+ 411 `LENGTH_REQUIRED`, above `maxRequestBytes` it is 413 `BODY_TOO_LARGE`, and a media type (its
159
+ parameters ignored) outside `requestTypes` is 415 `MEDIA_TYPE_NOT_ALLOWED`, each before any upstream
160
+ call. Such a refusal closes the connection, so that an unread body is never read only to be discarded.
161
+ The count of bytes is also checked as they stream.
162
+ - **Headers upstream.** The upstream gets the fixed headers of every route (the access token,
163
+ the negotiated Accept-Language, the correlation id and an allowlisted Idempotency-Key) and, in
164
+ addition, the accepted Content-Type and the Content-Length; no other request header.
165
+ - **The body streams.** The request body goes upstream as it arrives, through a pull stream that reads
166
+ the next chunk from the client only when the upstream connection asks for one, so the client is held
167
+ back by backpressure. The BFF holds a bounded window of a body, never all of it: the inbound socket and
168
+ request buffers (Node's 64 KiB high-water mark each; the test measured at most 130,775 bytes), the
169
+ chunk being forwarded and the outbound socket buffer (64 KiB high-water mark): at most about 256 KiB of
170
+ process memory per transfer, whatever the size of the body. Kernel socket buffers come on top. The test
171
+ measures the relay itself too: the bytes it pulled from the request minus the bytes the upstream request
172
+ took from it stay at most 128 KiB (it measured none between chunks), and a negative control with a queue
173
+ of four chunks fails that measure.
174
+ - **The answer streams.** The answer reaches the client as it arrives, byte for byte, with the upstream
175
+ status and only the headers the route names, plus `X-Content-Type-Options: nosniff`,
176
+ `Cache-Control: no-store` and the correlation id. An answer whose media type is not in `responseTypes`
177
+ is refused with 502 `UPSTREAM_MEDIA_TYPE_REJECTED` and none of its body is read; an answer without a
178
+ body (204, 205, 304, or a Content-Length of 0) needs no type. An upstream `Set-Cookie` or any unnamed
179
+ header never crosses. When the upstream answer is content-encoded, fetch decodes it and its
180
+ Content-Length is not passed. An upstream that answers an upload before reading it whole gets its answer
181
+ through with `Connection: close`, and the rest of the body is never read. An RFC 9470 challenge becomes the
182
+ same typed step-up as on other routes.
183
+ - **The session stays checked.** The session record is read again every `sessionCheckMs` and once more
184
+ when the request body ends, before its last chunk goes upstream. A session that has ended (logout from
185
+ another request, back-channel logout, a rotated session id or its absolute expiry) ends the transfer:
186
+ the upstream call is aborted and the client gets 401 `LOGIN_REQUIRED`, or, once the answer has
187
+ started, a cut connection, never a success; a session store that cannot be read ends it with 503. The
188
+ session's idle timeout is not applied during a transfer, which counts as activity only when it starts.
189
+ - **Time and cancellation.** A transfer with no byte moving for `idleTimeoutMs`, or lasting longer than
190
+ `totalTimeoutMs`, aborts the upstream call and answers 504 `UPSTREAM_TIMEOUT` when no answer has
191
+ started, or cuts the connection when one has. A client that cancels an upload or a download ends the
192
+ upstream call at once.
193
+
194
+ The BFF never parses, inspects, stores or logs a streamed body, a file name or any content; content checks
195
+ belong to the backend. Range requests, resumable uploads and multipart parsing are not provided. The
196
+ presentation application relays
197
+ a streamed route with `createRelay` of `@mpfrontend/presentation-server/relay` (see that package).
198
+
199
+ ## Production profile
200
+
201
+ A production configuration replaces `development: true` with a typed profile:
202
+ `production: {sessionVault, clientAuthentication, secureCookies: true}`. `createBff` starts only when every
203
+ condition holds, and otherwise refuses with `PRODUCTION_PROFILE_REFUSED:` followed by the names of the
204
+ unmet conditions (`productionRefusals(config)` lists them without starting):
205
+
206
+ | Condition | Refusal name |
207
+ |---|---|
208
+ | The public origin is `https` | `HTTPS_PUBLIC_ORIGIN_REQUIRED` |
209
+ | The issuer and provider origin are `https` | `HTTPS_IDENTITY_PROVIDER_REQUIRED` |
210
+ | The session vault is durable (never the memory vault) | `DURABLE_SESSION_VAULT_REQUIRED` |
211
+ | The vault is reached over TLS | `SESSION_VAULT_TLS_REQUIRED` |
212
+ | The vault connection is authenticated | `SESSION_VAULT_AUTHENTICATION_REQUIRED` |
213
+ | The vault's key ring is supplied by the host | `HOST_KEY_RING_REQUIRED` |
214
+ | Client authentication is configured: a confidential method, or a public client declared explicitly with `publicClient: true` | `CLIENT_AUTHENTICATION_REQUIRED` |
215
+ | Session cookies are `Secure` | `SECURE_COOKIES_REQUIRED` |
216
+
217
+ A vault describes itself through `security` (`durable`, `tls`, `authenticated`, `hostKeyRing`); a vault
218
+ without it is treated as unknown and refused. A Redis vault is durable with a host key ring, uses TLS for a
219
+ `rediss:` URL and is authenticated by `password` (or URL credentials). The production profile has no
220
+ memory fallback: `/health` answers 503 and every request fails with 503 while the vault is unavailable.
221
+ Errors carry codes only; no secret is logged. The negative controls remove each condition and observe the
222
+ production tests fail. The profile does not by itself prove HA, durability policy, key custody or a
223
+ reviewed deployment.
224
+
225
+ Redis records use AES-256-GCM with random 96-bit IVs and record-address associated data. Raw session
226
+ IDs are hashed in keys; access/refresh tokens, CSRF, identity and PKCE data are encrypted. The active
227
+ 32-byte key is supplied by the host, not generated/stored by this package. A key ID supports a read
228
+ keyring during rotation. Retain old keys until their records expire or are rewritten; no automated
229
+ key migration or key-management service is implemented. `close()` closes the owned Redis client.
230
+
231
+ `GETDEL` consumes login state once across replicas. Refresh uses a 30-second owner lease and an atomic
232
+ Lua CAS on both the original record and current lease. Losing a lease or racing logout cannot recreate
233
+ a revoked session. The absolute session lifetime is not renewed on refresh. A bounded provider
234
+ transport/timeout or HTTP429/5xx failure denies the current request with generic503; only the unchanged
235
+ verified server record is retained until its existing absolute expiry. No cached identity/API authority
236
+ is served, no automatic retry occurs, and no unverified rotated token is saved. A later request may
237
+ recover with the same opaque cookie, but ambiguous token rotation can still require a new login.
238
+ Invalid grant/client, malformed response, invalid signature/claims and failed storage/CAS invalidate
239
+ the record; generic503 is not enough to qualify as a provider outage. Logout removes state without
240
+ refreshing even while the provider is unavailable. The readiness endpoint checks the store; storage failures return generic503
241
+ responses and never fall back to memory. Offline command queuing/reconnect is disabled, commands are
242
+ bounded to two seconds; replace the adapter/replica after disconnection. This behavior needs an
243
+ operational supervisor, not an unattended indefinitely reconnecting client.
244
+
245
+ The uncached `security-bff:test-redis` target creates its own Docker Redis 8.0 AOF instance, uses
246
+ ephemeral test keys/identities and removes only its test container/anonymous volume. It verifies
247
+ two BFFs, atomic callbacks, concurrent refresh, logout races, key rotation/AAD, expiry, a controlled
248
+ AOF restart, store outage and Redis-backed presentation admission. It does not prove Redis cluster
249
+ failover, disk/power-loss durability, TLS/ACL/key custody, central rate limits or full backend journeys.
250
+ Production remains blocked on these deployment policies and complete realtime/release acceptance.
251
+
252
+ Sources: [OIDC Core](https://openid.net/specs/openid-connect-core-1_0.html),
253
+ [PKCE RFC 7636](https://www.rfc-editor.org/rfc/rfc7636),
254
+ [Keycloak OIDC endpoints](https://www.keycloak.org/securing-apps/oidc-layers).
255
+
256
+ The refresh failure distinction is a local policy: [OAuth2 token errors, RFC6749 §5.2](https://www.rfc-editor.org/rfc/rfc6749#section-5.2)
257
+ defines invalid grants/client authentication; [HTTP503, RFC9110 §15.6.4](https://httpwg.org/specs/rfc9110.html#status.503)
258
+ describes service unavailability. Neither source guarantees recoverable refresh-token rotation after
259
+ a lost response. Synthetic OIDC and isolated Redis tests exercise this policy, not production HA.
260
+
261
+ Storage references: [node-redis](https://redis.io/docs/latest/develop/clients/nodejs/),
262
+ [atomic GETDEL](https://redis.io/docs/latest/commands/getdel/),
263
+ [Redis persistence tradeoffs](https://redis.io/docs/latest/operate/oss_and_stack/management/persistence/).
package/dist/core.d.ts ADDED
@@ -0,0 +1,161 @@
1
+ import { type KeyObject } from 'node:crypto';
2
+ import type { IncomingMessage, ServerResponse } from 'node:http';
3
+ import { type PreferenceCookieContract } from '@mpfrontend/i18n';
4
+ import { type SessionVault } from './session-store-core.js';
5
+ export type { VaultSecurity } from './session-store-core.js';
6
+ /**
7
+ * A route may require a recent sign-in (`maxAge`, seconds since the person authenticated) and, optionally,
8
+ * an authentication context class (`acr`, the values that count). A consumer may use maxAge alone.
9
+ */
10
+ export type AuthenticationRequirement = Readonly<{
11
+ maxAge?: number;
12
+ acr?: readonly string[];
13
+ }>;
14
+ /** The typed answer when the current sign-in is not enough; it never names the provider's origin. */
15
+ export type StepUpChallenge = Readonly<{
16
+ maxAge?: number;
17
+ acrValues?: readonly string[];
18
+ login: string;
19
+ resubmit: 'idempotent' | 'manual';
20
+ }>;
21
+ /** The response headers a streamed route may pass to the client; no other upstream header ever crosses. */
22
+ export declare const STREAM_RESPONSE_HEADERS: readonly ["content-type", "content-length", "content-disposition", "content-security-policy"];
23
+ export type StreamResponseHeader = (typeof STREAM_RESPONSE_HEADERS)[number];
24
+ /**
25
+ * A route whose bodies stream instead of being read whole as JSON. The consumer sets every value; nothing has
26
+ * a default. A request body (any method but GET) needs `requestTypes` and `maxRequestBytes`, and its
27
+ * Content-Length; the answer must have one of `responseTypes`. `responseHeaders` names the headers passed to
28
+ * the client and includes `content-type`. The timeouts and the session check interval are milliseconds.
29
+ */
30
+ export type StreamPolicy = Readonly<{
31
+ requestTypes?: readonly string[];
32
+ maxRequestBytes?: number;
33
+ responseTypes: readonly string[];
34
+ responseHeaders: readonly StreamResponseHeader[];
35
+ idleTimeoutMs: number;
36
+ totalTimeoutMs: number;
37
+ sessionCheckMs: number;
38
+ }>;
39
+ export type ApiRoute = {
40
+ method: string;
41
+ pattern: RegExp;
42
+ roles?: readonly string[];
43
+ origin: string;
44
+ prefix?: string;
45
+ authentication?: AuthenticationRequirement;
46
+ /** A streamed body (see StreamPolicy); a route without it keeps the JSON contract. Not allowed with invoke. */
47
+ stream?: StreamPolicy;
48
+ invoke?: (input: {
49
+ path: string;
50
+ headers: Readonly<Record<string, string>>;
51
+ body: Uint8Array | undefined;
52
+ }) => Promise<{
53
+ status: number;
54
+ body: unknown;
55
+ }>;
56
+ };
57
+ /** The locales the BFF may send upstream as Accept-Language; anything else becomes the default. */
58
+ export type ApiLocales = Readonly<{
59
+ supported: readonly string[];
60
+ defaultLocale: string;
61
+ }>;
62
+ /** English only, MP Frontend's one built-in language; a product lists the locales its backends answer in. */
63
+ export declare const defaultApiLocales: ApiLocales;
64
+ type CommonConfig = {
65
+ publicOrigin: string;
66
+ issuer: string;
67
+ providerOrigin?: string;
68
+ clientId: string;
69
+ audience: string;
70
+ cookieName: string;
71
+ routes: readonly ApiRoute[];
72
+ requireTenant?: boolean;
73
+ tenantExemptRoles?: readonly string[];
74
+ supportedUiLocales?: readonly string[];
75
+ uiLocaleCookie?: string;
76
+ apiLocales?: ApiLocales;
77
+ contextClaims?: readonly string[];
78
+ contextClaimSource?: 'id' | 'access';
79
+ preferenceCookie?: PreferenceCookieContract;
80
+ session?: SessionPolicy;
81
+ /** Enables POST /backchannel-logout (OpenID Connect Back-Channel Logout 1.0); expose it only on the provider's network path. */
82
+ backChannelLogout?: boolean;
83
+ /** The acr values a step-up may request; without this list a login cannot request an acr. */
84
+ acrValues?: readonly string[];
85
+ /** The paths the browser may return to after sign-in; '/' when unset. A string matches exactly. */
86
+ returnPaths?: readonly (string | RegExp)[];
87
+ loginRateLimit?: (peer: string) => Promise<boolean>;
88
+ };
89
+ /**
90
+ * How the BFF authenticates to the token endpoint. A public client sends only its client id; the
91
+ * production profile accepts it only when the configuration declares it explicitly.
92
+ */
93
+ export type ClientAuthentication = Readonly<{
94
+ method: 'none';
95
+ publicClient: true;
96
+ }> | Readonly<{
97
+ method: 'client_secret_basic';
98
+ secret: string | (() => string);
99
+ }> | Readonly<{
100
+ method: 'private_key_jwt';
101
+ key: SigningKey | (() => SigningKey);
102
+ }>;
103
+ /**
104
+ * A private key held by the host, identified by its key id so that the identity provider can rotate keys:
105
+ * a function returns the current key at each use. The package never stores, logs or returns it.
106
+ */
107
+ export type SigningKey = Readonly<{
108
+ keyId: string;
109
+ privateKey: KeyObject;
110
+ algorithm?: 'RS256' | 'PS256' | 'ES256';
111
+ }>;
112
+ /** A client assertion lives this long (RFC 7523 recommends a short lifetime). */
113
+ export declare const CLIENT_ASSERTION_LIFETIME_SECONDS = 60;
114
+ /** A private_key_jwt client assertion (RFC 7523 section 3): iss and sub are the client, aud the token endpoint. */
115
+ export declare function clientAssertion(clientId: string, audience: string, source: SigningKey | (() => SigningKey), now?: number): string;
116
+ /** Today's single-process development profile, refused when NODE_ENV is production. */
117
+ export type DevelopmentBffConfig = CommonConfig & {
118
+ development: true;
119
+ production?: never;
120
+ sessionVault?: SessionVault;
121
+ clientAuthentication?: ClientAuthentication;
122
+ };
123
+ /** Every field is required; createBff refuses to start, with a named reason, when a condition does not hold. */
124
+ export type ProductionProfile = Readonly<{
125
+ sessionVault: SessionVault;
126
+ clientAuthentication: ClientAuthentication;
127
+ secureCookies: true;
128
+ /** The session cookie carries the __Host- prefix unless this is false. */
129
+ hostPrefix?: boolean;
130
+ }>;
131
+ export type ProductionBffConfig = CommonConfig & {
132
+ production: ProductionProfile;
133
+ development?: never;
134
+ };
135
+ export type BffConfig = DevelopmentBffConfig | ProductionBffConfig;
136
+ /** The unmet conditions of a production configuration, in a stable order; empty when it may start. */
137
+ export declare function productionRefusals(config: ProductionBffConfig): string[];
138
+ /**
139
+ * The session cookie and lifetimes. SameSite applies to the session cookie only; the short login transaction
140
+ * cookie stays Lax so that the provider's redirect back can carry it. Lifetimes have bounded maxima; a value
141
+ * above a maximum refuses startup rather than being shortened.
142
+ */
143
+ export type SessionPolicy = Readonly<{
144
+ sameSite?: 'Strict' | 'Lax';
145
+ idleTimeoutSeconds?: number;
146
+ absoluteLifetimeSeconds?: number;
147
+ /** Claims whose change at refresh rotates the session id. */
148
+ authorizationClaims?: readonly string[];
149
+ }>;
150
+ export declare const SESSION_LIMITS: Readonly<{
151
+ defaultIdleTimeoutSeconds: 1800;
152
+ maxIdleTimeoutSeconds: 86400;
153
+ defaultAbsoluteLifetimeSeconds: 28800;
154
+ maxAbsoluteLifetimeSeconds: 604800;
155
+ }>;
156
+ export declare const defaultAuthorizationClaims: readonly string[];
157
+ /** A projected claim value: plain data only, never an object, never a token. */
158
+ export type ClaimValue = string | number | boolean | readonly string[];
159
+ /** The allowlisted claims for /context, bounded in size. A token, an object or an oversized value is left out. */
160
+ export declare function projectClaims(claims: Readonly<Record<string, unknown>>, allowed: readonly string[]): Readonly<Record<string, ClaimValue>>;
161
+ export declare function createBff(config: BffConfig): (req: IncomingMessage, res: ServerResponse) => Promise<void>;