@mpfrontend/presentation-server 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,67 @@
1
- # Temporary Holding Version
1
+ # Authenticated presentation sockets
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
+ Development polling-to-WebSocket invalidation adapter for a self-hosted Next custom server.
4
+ It is not a backend event stream, durable replay log or multi-replica relay.
5
+
6
+ The browser first obtains a single-use 20-second ticket through a same-origin CSRF-protected POST.
7
+ The upgrade requires the exact Origin and a valid opaque BFF session. The first frame redeems the
8
+ ticket bound to that cookie and authority revision. Resources resolve only through product-owned
9
+ allowlists and authenticated BFF reads. No access token, cookie, resource data or tenant is sent in frames.
10
+
11
+ Admission and every polling tick recheck session and authority. Losing authorization closes the socket.
12
+ Reconnect always requests fresh authoritative snapshots; this profile does not resume missed events.
13
+ Limits: 32 connections/process, 2/session, 6 subscriptions, 4 KiB incoming frames, 64 KiB outgoing
14
+ buffer, 5-second admission timeout, 3-second minimum polling and 30-second ping/pong.
15
+ Network/backend uncertainty sends a resync-required frame, never a fabricated event. Editors keep
16
+ drafts and show a refresh notice; readonly consumers may refetch. Production startup requires the
17
+ production profile below.
18
+
19
+ Sources: [Next custom servers](https://nextjs.org/docs/app/guides/custom-server),
20
+ [ws authentication and upgrades](https://github.com/websockets/ws#client-authentication),
21
+ [WebSocket protocol](https://www.rfc-editor.org/rfc/rfc6455).
22
+ ## Shared admission validation
23
+
24
+ `SocketConfig.ticketStore` accepts an asynchronous `AdmissionTicketStore` with atomic `consume`.
25
+ The default stays bounded process memory. Consumers can bind Redis-vault issue/consume operations;
26
+ all replicas must use the same app-scoped namespace/keyring. Tickets remain cookie/authority-bound
27
+ and expire after 20 seconds. First-frame authority is checked again before ready/invalidation.
28
+ Storage errors close admission; no local fallback is used. Concurrent subscribe frames are rejected.
29
+
30
+ ## Production profile
31
+
32
+ `createPresentationRealtime({production: {ticketStore, connectionBudget}, ...})` starts only with an `https`
33
+ public origin, a ticket store that every replica shares (`shared: true`, for example
34
+ `createVaultTicketStore(vault)` of `@mpfrontend/security-bff/session-store`) and a shared connection budget
35
+ (`vault.limits.connections` of a Redis vault); otherwise it refuses with `PRODUCTION_PROFILE_REFUSED:` and
36
+ the names `HTTPS_PUBLIC_ORIGIN_REQUIRED`, `SHARED_TICKET_STORE_REQUIRED` or
37
+ `SHARED_CONNECTION_BUDGET_REQUIRED`. A ticket store over a durable vault (one that declares `security`, as
38
+ `createVaultTicketStore` does) is also refused unless the vault is reached over TLS
39
+ (`TICKET_STORE_TLS_REQUIRED`) and with authentication (`TICKET_STORE_AUTHENTICATION_REQUIRED`). A shared
40
+ store must declare `security` (`durable`, `tls` and `authenticated`, all three): a custom store that declares
41
+ nothing cannot be shown to use TLS and authentication, so it is refused with `TICKET_STORE_SECURITY_REQUIRED`
42
+ rather than accepted for lack of a claim. There is no process-memory default in this profile. The development
43
+ profile (`development: true`) is unchanged and still refused under `NODE_ENV=production`. Retained event
44
+ replay is not part of either profile. See the core shared-runtime acceptance document.
45
+
46
+ ## Transfer relay
47
+
48
+ `@mpfrontend/presentation-server/relay` relays a streamed route of the Security BFF from a route handler
49
+ of the presentation application (Web `Request` and `Response`, as in Next.js), as streams in both
50
+ directions: it never holds a whole body. `createRelay({bffOrigin, basePath, sessionCookie})` returns
51
+ `relay(request, segments)`, which calls `<bffOrigin><basePath>/<segments>` with the request's query.
52
+
53
+ - Towards the BFF it forwards only what the BFF checks and the content headers: the session cookie named
54
+ `sessionCookie` (no other cookie), Origin, `X-CSRF-Token`, `Idempotency-Key`, Accept-Language,
55
+ Content-Type and Content-Length (`RELAY_REQUEST_HEADERS`). A body without Content-Length is refused by
56
+ the BFF with 411.
57
+ - Back to the browser it passes the status, the content headers, the BFF's `X-Content-Type-Options`,
58
+ `Cache-Control`, correlation id and `Idempotency-Replayed` (`RELAY_RESPONSE_HEADERS`), and a
59
+ `Set-Cookie` only when it sets the session cookie (a rotated session id). Content-Length is dropped
60
+ when fetch has decoded a content encoding.
61
+ - Each path segment is encoded again, so that a segment cannot leave `basePath`; an empty, `.` or `..`
62
+ segment is answered 404 without a call. A client that goes away aborts the call to the BFF, which ends
63
+ the upstream call.
64
+
65
+ The relay decides nothing itself: the BFF's allowlist, session, Origin, CSRF, media types, sizes and
66
+ timeouts do. The application template wires it in `src/app/api/transfer/[...path]/route.ts` through
67
+ `src/api/server/transfer.ts`, with the session cookie name in `BFF_SESSION_COOKIE`.
@@ -0,0 +1,9 @@
1
+ export type ConnectionBudget = {
2
+ /** True for a budget that every replica shares; the production profile refuses any other. */
3
+ readonly shared?: boolean;
4
+ reserve: (subject: string, id: string) => Promise<number | undefined>;
5
+ renew: (subject: string, id: string) => Promise<number | undefined>;
6
+ release: (subject: string, id: string) => Promise<void>;
7
+ };
8
+ /** Development-only fallback; production composition must provide shared, leased admission. */
9
+ export declare function createMemoryConnectionBudget(): ConnectionBudget;
@@ -0,0 +1,21 @@
1
+ /** Development-only fallback; production composition must provide shared, leased admission. */
2
+ export function createMemoryConnectionBudget() {
3
+ const leases = new Map(), duration = 30000;
4
+ const prune = () => { for (const [id, lease] of leases)
5
+ if (lease.until <= Date.now())
6
+ leases.delete(id); };
7
+ return {
8
+ async reserve(subject, id) {
9
+ prune();
10
+ if (leases.has(id) || leases.size >= 32 || [...leases.values()].filter(v => v.subject === subject).length >= 2)
11
+ return undefined;
12
+ leases.set(id, { subject, until: Date.now() + duration });
13
+ return duration;
14
+ },
15
+ async renew(subject, id) { prune(); const lease = leases.get(id); if (!lease || lease.subject !== subject)
16
+ return undefined; lease.until = Date.now() + duration; return duration; },
17
+ async release(subject, id) { if (leases.get(id)?.subject === subject)
18
+ leases.delete(id); }
19
+ };
20
+ }
21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GAAG,EAAE,GAAC,QAAQ,CAAC,CAAA,OAAO,QAAQ,CAAC,CAAA,CAAC;QAChK,KAAK,CAAC,OAAO,CAAC,OAAO,EAAC,EAAE,IAAE,IAAG,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,OAAO,KAAG,OAAO;YAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAA,CAAC;KACnF,CAAC;AACJ,CAAC"}
package/dist/core.d.ts ADDED
@@ -0,0 +1,60 @@
1
+ import type { IncomingMessage, ServerResponse, Server } from 'node:http';
2
+ import { type ConnectionBudget } from './connection-budget.js';
3
+ export type { ConnectionBudget } from './connection-budget.js';
4
+ export type SocketContext = {
5
+ subject: string;
6
+ tenant: string | null;
7
+ roles: string[];
8
+ csrf: string;
9
+ };
10
+ export type AdmissionTicket = {
11
+ cookieHash: string;
12
+ revision: string;
13
+ expires: number;
14
+ };
15
+ /**
16
+ * consume must be atomic across all presentation replicas. `security` describes the vault behind a store that
17
+ * keeps its tickets in one, as `createVaultTicketStore` of the Security BFF's session store sets it. The
18
+ * production profile refuses a shared store that does not declare it, all three flags, because a store that
19
+ * says nothing cannot be shown to be reached over TLS and with authentication.
20
+ */
21
+ export type AdmissionTicketStore = {
22
+ readonly shared?: boolean;
23
+ readonly security?: Readonly<{
24
+ durable: boolean;
25
+ tls: boolean;
26
+ authenticated: boolean;
27
+ }>;
28
+ issue: (id: string, ticket: AdmissionTicket) => Promise<void>;
29
+ consume: (id: string) => Promise<AdmissionTicket | undefined>;
30
+ };
31
+ type CommonSocketConfig = {
32
+ publicOrigin: string;
33
+ bffOrigin: string;
34
+ resolve: (resource: string, context: SocketContext) => string | undefined;
35
+ pollMs?: number;
36
+ };
37
+ /** Today's single-process development profile, refused when NODE_ENV is production. */
38
+ export type DevelopmentSocketConfig = CommonSocketConfig & {
39
+ development: true;
40
+ production?: never;
41
+ ticketStore?: AdmissionTicketStore;
42
+ connectionBudget?: ConnectionBudget;
43
+ };
44
+ /** Shared, durable admission across replicas; no process-memory default exists in this profile. */
45
+ export type PresentationProductionProfile = Readonly<{
46
+ ticketStore: AdmissionTicketStore;
47
+ connectionBudget: ConnectionBudget;
48
+ }>;
49
+ export type ProductionSocketConfig = CommonSocketConfig & {
50
+ production: PresentationProductionProfile;
51
+ development?: never;
52
+ };
53
+ export type SocketConfig = DevelopmentSocketConfig | ProductionSocketConfig;
54
+ /** The unmet conditions of a production configuration; empty when it may start. */
55
+ export declare function presentationProductionRefusals(config: ProductionSocketConfig): string[];
56
+ export declare function createPresentationRealtime(config: SocketConfig): {
57
+ handleHttp: (req: IncomingMessage, res: ServerResponse) => Promise<boolean>;
58
+ attach: (server: Server) => void;
59
+ close: () => void;
60
+ };
package/dist/core.js ADDED
@@ -0,0 +1,250 @@
1
+ import { createHash, randomBytes, randomUUID } from 'node:crypto';
2
+ import { WebSocketServer, WebSocket } from 'ws';
3
+ import { createMemoryConnectionBudget } from './connection-budget.js';
4
+ /** The unmet conditions of a production configuration; empty when it may start. */
5
+ export function presentationProductionRefusals(config) {
6
+ const refusals = [];
7
+ let https = false;
8
+ try {
9
+ https = new URL(config.publicOrigin).protocol === 'https:';
10
+ }
11
+ catch {
12
+ https = false;
13
+ }
14
+ if (!https)
15
+ refusals.push('HTTPS_PUBLIC_ORIGIN_REQUIRED');
16
+ if (config.production?.ticketStore?.shared !== true)
17
+ refusals.push('SHARED_TICKET_STORE_REQUIRED');
18
+ // A store that every replica shares is reached over a network, so it must say how: one that declares nothing is
19
+ // refused, as the Security BFF refuses a session vault that declares nothing, instead of passing for lack of a claim.
20
+ const declared = (security) => typeof security?.durable === 'boolean' && typeof security.tls === 'boolean' && typeof security.authenticated === 'boolean';
21
+ if (config.production?.ticketStore?.shared === true && !declared(config.production.ticketStore.security))
22
+ refusals.push('TICKET_STORE_SECURITY_REQUIRED');
23
+ // Tickets in a durable vault travel and rest under the vault's own protection, which must be TLS and authentication.
24
+ const vault = config.production?.ticketStore?.security;
25
+ if (vault?.durable && vault.tls !== true)
26
+ refusals.push('TICKET_STORE_TLS_REQUIRED');
27
+ if (vault?.durable && vault.authenticated !== true)
28
+ refusals.push('TICKET_STORE_AUTHENTICATION_REQUIRED');
29
+ if (config.production?.connectionBudget?.shared !== true)
30
+ refusals.push('SHARED_CONNECTION_BUDGET_REQUIRED');
31
+ return refusals;
32
+ }
33
+ const digest = (value) => createHash('sha256').update(value).digest('base64url');
34
+ const authority = (c) => digest(JSON.stringify([c.subject, c.tenant, [...c.roles].sort()]));
35
+ function checkedOrigin(value) { const url = new URL(value); if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.pathname !== '/' || url.search || url.hash)
36
+ throw new Error('INVALID_ORIGIN'); return url.origin; }
37
+ function json(res, status, value) { res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }); res.end(JSON.stringify(value)); }
38
+ export function createPresentationRealtime(config) {
39
+ const production = 'production' in config && config.production !== undefined ? config.production : undefined;
40
+ if (production) {
41
+ const refusals = presentationProductionRefusals(config);
42
+ if (refusals.length)
43
+ throw new Error('PRODUCTION_PROFILE_REFUSED:' + refusals.join(','));
44
+ }
45
+ else if (config.development !== true || process.env.NODE_ENV === 'production')
46
+ throw new Error('DURABLE_REALTIME_PROFILE_REQUIRED');
47
+ const development = production ? undefined : config;
48
+ const publicOrigin = checkedOrigin(config.publicOrigin), bff = checkedOrigin(config.bffOrigin);
49
+ const interval = Math.max(3000, config.pollMs ?? 3000), tickets = new Map();
50
+ const connectionBudget = production ? production.connectionBudget : development?.connectionBudget ?? createMemoryConnectionBudget();
51
+ const ticketStore = production ? production.ticketStore : development?.ticketStore ?? {
52
+ async issue(id, ticket) {
53
+ for (const [key, value] of tickets)
54
+ if (value.expires <= Date.now())
55
+ tickets.delete(key);
56
+ if (tickets.size >= 256)
57
+ throw Object.assign(new Error('TICKET_LIMIT'), { status: 429 });
58
+ tickets.set(id, ticket);
59
+ },
60
+ async consume(id) { const ticket = tickets.get(id); tickets.delete(id); return ticket; }
61
+ };
62
+ const sockets = new WebSocketServer({ noServer: true, maxPayload: 4096, perMessageDeflate: false });
63
+ async function context(cookie) {
64
+ const response = await fetch(bff + '/context', { headers: { cookie }, redirect: 'error', signal: AbortSignal.timeout(8000), cache: 'no-store' });
65
+ if (response.status === 401 || response.status === 403)
66
+ throw Object.assign(new Error('LOGIN_REQUIRED'), { status: 401 });
67
+ if (!response.ok)
68
+ throw new Error('AUTHORITY_UNAVAILABLE');
69
+ const c = await response.json();
70
+ if (typeof c.subject !== 'string' || typeof c.csrf !== 'string' || !Array.isArray(c.roles) || !c.roles.every(v => typeof v === 'string') || (c.tenant !== null && typeof c.tenant !== 'string'))
71
+ throw new Error('INVALID_CONTEXT');
72
+ return c;
73
+ }
74
+ async function handleHttp(req, res) {
75
+ if (new URL(req.url ?? '/', publicOrigin).pathname !== '/api/realtime/ticket')
76
+ return false;
77
+ try {
78
+ if (req.method !== 'POST') {
79
+ json(res, 405, { title: 'POST_REQUIRED' });
80
+ return true;
81
+ }
82
+ if (req.headers.origin !== publicOrigin) {
83
+ json(res, 403, { title: 'ORIGIN_REJECTED' });
84
+ return true;
85
+ }
86
+ const cookie = req.headers.cookie ?? '', c = await context(cookie);
87
+ if (typeof req.headers['x-csrf-token'] !== 'string' || req.headers['x-csrf-token'] !== c.csrf) {
88
+ json(res, 403, { title: 'CSRF_REJECTED' });
89
+ return true;
90
+ }
91
+ const ticket = randomBytes(32).toString('base64url');
92
+ await ticketStore.issue(ticket, { cookieHash: digest(cookie), revision: authority(c), expires: Date.now() + 20000 });
93
+ json(res, 200, { ticket, expiresIn: 20 });
94
+ }
95
+ catch (e) {
96
+ const status = e.status ?? 503;
97
+ json(res, status, { title: status === 401 ? 'LOGIN_REQUIRED' : status === 429 ? 'TICKET_LIMIT' : 'AUTHORITY_UNAVAILABLE' });
98
+ }
99
+ return true;
100
+ }
101
+ function attach(server) {
102
+ server.on('upgrade', async (req, socket, head) => {
103
+ const url = new URL(req.url ?? '/', publicOrigin);
104
+ if (url.pathname !== '/api/realtime' || url.search || req.headers.origin !== publicOrigin) {
105
+ socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n');
106
+ return;
107
+ }
108
+ const cookie = req.headers.cookie ?? '', cookieHash = digest(cookie);
109
+ const connectionId = randomUUID();
110
+ let reserved = false, upgraded = false;
111
+ const release = () => connectionBudget.release(cookieHash, connectionId).catch(() => undefined);
112
+ try {
113
+ const initial = await context(cookie), revision = authority(initial);
114
+ if (sockets.clients.size >= 32 || !await connectionBudget.reserve(cookieHash, connectionId)) {
115
+ socket.end('HTTP/1.1 429 Too Many Requests\r\nConnection: close\r\n\r\n');
116
+ return;
117
+ }
118
+ reserved = true;
119
+ // Includes rejected WebSocket handshakes and clients which disconnect during admission.
120
+ socket.once('close', () => { if (!upgraded)
121
+ void release(); });
122
+ if (socket.destroyed) {
123
+ await release();
124
+ return;
125
+ }
126
+ sockets.handleUpgrade(req, socket, head, ws => {
127
+ upgraded = true;
128
+ const contextRef = randomUUID(), resources = new Map();
129
+ let admitted = false, admitting = false, busy = false, cursor = 0, alive = true;
130
+ async function lease() {
131
+ if (ws.readyState !== WebSocket.OPEN)
132
+ return false;
133
+ const started = performance.now();
134
+ try {
135
+ const duration = await connectionBudget.renew(cookieHash, connectionId);
136
+ if (!duration || performance.now() - started >= duration) {
137
+ ws.close(4004, 'LEASE_LOST');
138
+ return false;
139
+ }
140
+ return ws.readyState === WebSocket.OPEN;
141
+ }
142
+ catch {
143
+ ws.close(1013, 'RUNTIME_UNAVAILABLE');
144
+ return false;
145
+ }
146
+ }
147
+ const send = async (frame) => { if (!await lease())
148
+ return; if (ws.bufferedAmount > 65536) {
149
+ ws.close(4008, 'BACKPRESSURE');
150
+ return;
151
+ } ws.send(JSON.stringify(frame)); };
152
+ const admission = setTimeout(() => ws.close(4001, 'ADMISSION_TIMEOUT'), 5000);
153
+ ws.on('pong', () => { alive = true; });
154
+ ws.on('error', () => ws.close(1011, 'TRANSPORT_ERROR'));
155
+ ws.on('message', async (raw, binary) => {
156
+ try {
157
+ if (binary || admitted || admitting)
158
+ throw new Error('INVALID_FRAME');
159
+ admitting = true;
160
+ const frame = JSON.parse(raw.toString());
161
+ if (frame.v !== 1 || frame.type !== 'subscribe' || typeof frame.ticket !== 'string' || !Array.isArray(frame.resources) || frame.resources.length < 1 || frame.resources.length > 6 || frame.resources.some(v => typeof v !== 'string' || v.length > 80))
162
+ throw new Error('INVALID_FRAME');
163
+ if (!/^[-_a-zA-Z0-9]{43}$/.test(frame.ticket))
164
+ throw new Error('INVALID_TICKET');
165
+ const saved = await ticketStore.consume(frame.ticket);
166
+ if (!saved || saved.expires <= Date.now() || saved.cookieHash !== cookieHash || saved.revision !== revision)
167
+ throw new Error('INVALID_TICKET');
168
+ if (authority(await context(cookie)) !== revision)
169
+ throw new Error('AUTHORITY_CHANGED');
170
+ if (ws.readyState !== WebSocket.OPEN)
171
+ return;
172
+ for (const name of new Set(frame.resources)) {
173
+ const path = config.resolve(name, initial);
174
+ if (!path || !path.startsWith('/v1/') || path.includes('..') || path.includes('#') || new URL(path, bff).origin !== bff)
175
+ throw new Error('FORBIDDEN_RESOURCE');
176
+ resources.set(name, { path });
177
+ }
178
+ admitted = true;
179
+ clearTimeout(admission);
180
+ await send({ v: 1, type: 'ready', contextRef, accessRevision: revision, recovery: 'snapshot' });
181
+ void tick();
182
+ }
183
+ catch {
184
+ ws.close(4003, 'ADMISSION_REJECTED');
185
+ }
186
+ });
187
+ async function tick() {
188
+ if (!admitted || busy || ws.readyState !== WebSocket.OPEN)
189
+ return;
190
+ busy = true;
191
+ try {
192
+ if (!await lease())
193
+ return;
194
+ const current = await context(cookie);
195
+ if (authority(current) !== revision) {
196
+ ws.close(4003, 'AUTHORITY_CHANGED');
197
+ return;
198
+ }
199
+ for (const [name, value] of resources) {
200
+ if (config.resolve(name, current) !== value.path) {
201
+ ws.close(4003, 'RESOURCE_REVOKED');
202
+ return;
203
+ }
204
+ const result = await fetch(bff + value.path, { headers: { cookie }, redirect: 'error', cache: 'no-store', signal: AbortSignal.timeout(8000) });
205
+ if (result.status === 401 || result.status === 403) {
206
+ ws.close(4003, 'RESOURCE_REVOKED');
207
+ return;
208
+ }
209
+ if (!result.ok && result.status !== 404)
210
+ throw new Error('SNAPSHOT_UNAVAILABLE');
211
+ const text = await result.text();
212
+ if (text.length > 1048576)
213
+ throw new Error('SNAPSHOT_LIMIT');
214
+ const hash = digest(result.status + ':' + text);
215
+ if (value.hash !== hash) {
216
+ cursor++;
217
+ await send({ v: 1, type: 'invalidate', eventId: randomUUID(), contextRef, accessRevision: revision, resource: name, cursor: String(cursor) });
218
+ value.hash = hash;
219
+ }
220
+ }
221
+ }
222
+ catch (e) {
223
+ if (e.status === 401)
224
+ ws.close(4003, 'LOGIN_REQUIRED');
225
+ else
226
+ await send({ v: 1, type: 'resync-required', contextRef, accessRevision: revision });
227
+ }
228
+ finally {
229
+ busy = false;
230
+ }
231
+ }
232
+ const polling = setInterval(() => void tick(), interval), heartbeat = setInterval(() => { if (!alive) {
233
+ ws.terminate();
234
+ return;
235
+ } alive = false; ws.ping(); }, 30000);
236
+ ws.on('close', () => { clearTimeout(admission); clearInterval(polling); clearInterval(heartbeat); void release(); });
237
+ });
238
+ }
239
+ catch (e) {
240
+ if (reserved)
241
+ await release();
242
+ socket.end('HTTP/1.1 ' + (e.status === 401 ? '401 Unauthorized' : '503 Service Unavailable') + '\r\nConnection: close\r\n\r\n');
243
+ }
244
+ });
245
+ }
246
+ function close() { for (const ws of sockets.clients)
247
+ ws.terminate(); sockets.close(); tickets.clear(); }
248
+ return { handleHttp, attach, close };
249
+ }
250
+ //# sourceMappingURL=core.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core.js","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAC,WAAW,EAAC,UAAU,EAAC,MAAM,aAAa,CAAC;AAE9D,OAAO,EAAC,eAAe,EAAC,SAAS,EAAC,MA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AU,EAAC,MAAM,EAAC,KAAK,EAAC,CAAC;AACnC,CAAC"}
@@ -0,0 +1 @@
1
+ export { type AdmissionTicket, type AdmissionTicketStore, type ConnectionBudget, createPresentationRealtime, type DevelopmentSocketConfig, type PresentationProductionProfile, type ProductionSocketConfig, type SocketConfig, } from './core.js';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { createPresentationRealtime, } from './core.js';
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,0BAA0B,GAK3B,MAAM,WAAW,CAAC"}
@@ -0,0 +1 @@
1
+ export { presentationProductionRefusals, type SocketContext } from './core.js';
@@ -0,0 +1,3 @@
1
+ // For the cohort's own packages: outside the compatibility guarantee (README "Versioning").
2
+ export { presentationProductionRefusals } from './core.js';
3
+ //# sourceMappingURL=internal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"internal.js","sourceRoot":"","sources":["../src/internal.ts"],"names":[],"mappings":"AAAA,4FAA4F;AAC5F,OAAO,EAAC,8BAA8B,EAAoB,MAAM,WAAW,CAAC"}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The relay of a streamed BFF route for a presentation application's route handlers (Web Request and
3
+ * Response, as in Next.js). It passes the request body to the BFF and the answer back to the browser as
4
+ * streams in both directions, never holding a whole body, and it forwards only what the BFF checks and the
5
+ * content headers. It decides nothing itself: the BFF's allowlist, session, Origin, CSRF and size rules do.
6
+ */
7
+ /** The request headers the relay forwards: what the BFF checks, and the content headers of a body. */
8
+ export declare const RELAY_REQUEST_HEADERS: readonly ["origin", "x-csrf-token", "idempotency-key", "accept-language", "content-type", "content-length"];
9
+ /** The response headers the relay passes back: the content headers and the BFF's own safety and correlation headers. */
10
+ export declare const RELAY_RESPONSE_HEADERS: readonly ["content-type", "content-length", "content-disposition", "content-security-policy", "x-content-type-options", "cache-control", "x-correlation-id", "idempotency-replayed"];
11
+ export type RelayOptions = Readonly<{
12
+ /** The BFF's origin on the trusted server-to-server path. */
13
+ bffOrigin: string;
14
+ /** The BFF path under which the streamed routes live, for example `/<app>/transfer`. */
15
+ basePath: string;
16
+ /** The name of the BFF's session cookie: the only cookie the relay forwards, and the only one it passes back. */
17
+ sessionCookie: string;
18
+ }>;
19
+ export type Relay = (request: Request, segments: readonly string[]) => Promise<Response>;
20
+ /**
21
+ * A relay to the BFF routes under `basePath`. Each path segment is encoded again, so that a segment can never
22
+ * leave the base path; the query string is passed as it is. A body without a length is refused by the BFF.
23
+ */
24
+ export declare function createRelay(options: RelayOptions): Relay;
package/dist/relay.js ADDED
@@ -0,0 +1,77 @@
1
+ /**
2
+ * The relay of a streamed BFF route for a presentation application's route handlers (Web Request and
3
+ * Response, as in Next.js). It passes the request body to the BFF and the answer back to the browser as
4
+ * streams in both directions, never holding a whole body, and it forwards only what the BFF checks and the
5
+ * content headers. It decides nothing itself: the BFF's allowlist, session, Origin, CSRF and size rules do.
6
+ */
7
+ /** The request headers the relay forwards: what the BFF checks, and the content headers of a body. */
8
+ export const RELAY_REQUEST_HEADERS = Object.freeze(['origin', 'x-csrf-token', 'idempotency-key', 'accept-language', 'content-type', 'content-length']);
9
+ /** The response headers the relay passes back: the content headers and the BFF's own safety and correlation headers. */
10
+ export const RELAY_RESPONSE_HEADERS = Object.freeze(['content-type', 'content-length', 'content-disposition', 'content-security-policy',
11
+ 'x-content-type-options', 'cache-control', 'x-correlation-id', 'idempotency-replayed']);
12
+ function checkedOrigin(value) {
13
+ const url = new URL(value);
14
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.pathname !== '/' || url.search || url.hash)
15
+ throw new Error('INVALID_ORIGIN');
16
+ return url.origin;
17
+ }
18
+ function cookieValue(header, name) {
19
+ return header?.split(';').map(value => value.trim()).find(value => value.startsWith(name + '='))?.slice(name.length + 1);
20
+ }
21
+ function problem(status, title) {
22
+ return new Response(JSON.stringify({ type: 'about:blank', status, title }), { status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' } });
23
+ }
24
+ /**
25
+ * A relay to the BFF routes under `basePath`. Each path segment is encoded again, so that a segment can never
26
+ * leave the base path; the query string is passed as it is. A body without a length is refused by the BFF.
27
+ */
28
+ export function createRelay(options) {
29
+ const bff = checkedOrigin(options.bffOrigin);
30
+ if (!/^(?:\/[A-Za-z0-9._~-]+)+$/.test(options.basePath) || options.basePath.split('/').some(part => part === '.' || part === '..'))
31
+ throw new Error('INVALID_RELAY_PATH');
32
+ if (!/^(?:__Host-)?[a-z][a-z0-9_]{1,60}$/.test(options.sessionCookie))
33
+ throw new Error('INVALID_SESSION_COOKIE');
34
+ return async function relay(request, segments) {
35
+ if (!segments.length || segments.length > 32 || segments.some(segment => !segment || segment === '.' || segment === '..' || segment.length > 256))
36
+ return problem(404, 'OPERATION_NOT_FOUND');
37
+ const search = new URL(request.url).search;
38
+ const target = bff + options.basePath + '/' + segments.map(encodeURIComponent).join('/') + search;
39
+ const headers = new Headers();
40
+ for (const name of RELAY_REQUEST_HEADERS) {
41
+ const value = request.headers.get(name);
42
+ if (value !== null)
43
+ headers.set(name, value);
44
+ }
45
+ const session = cookieValue(request.headers.get('cookie'), options.sessionCookie);
46
+ if (session !== undefined)
47
+ headers.set('cookie', options.sessionCookie + '=' + session);
48
+ const withBody = request.method !== 'GET' && request.method !== 'HEAD' && request.body !== null;
49
+ let response;
50
+ try {
51
+ // A client that goes away aborts the call to the BFF, which ends the upstream call.
52
+ response = await fetch(target, { method: request.method, headers, ...(withBody ? { body: request.body, duplex: 'half' } : {}),
53
+ redirect: 'error', cache: 'no-store', signal: request.signal });
54
+ }
55
+ catch {
56
+ return problem(503, 'SERVICE_UNAVAILABLE');
57
+ }
58
+ const passed = new Headers();
59
+ for (const name of RELAY_RESPONSE_HEADERS) {
60
+ const value = response.headers.get(name);
61
+ if (value !== null)
62
+ passed.set(name, value);
63
+ }
64
+ // fetch decodes a content encoding, after which the encoded length no longer applies.
65
+ if (response.headers.has('content-encoding'))
66
+ passed.delete('content-length');
67
+ // A rotated session id is the BFF's own cookie; no other cookie is passed back.
68
+ for (const value of response.headers.getSetCookie())
69
+ if (value.startsWith(options.sessionCookie + '='))
70
+ passed.append('set-cookie', value);
71
+ const empty = [204, 205, 304].includes(response.status);
72
+ if (empty)
73
+ await response.body?.cancel().catch(() => undefined);
74
+ return new Response(empty ? null : response.body, { status: response.status, headers: passed });
75
+ };
76
+ }
77
+ //# sourceMappingURL=relay.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relay.js","sourceRoot":"","sources":["../src/relay.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,sGAAsG;AACtG,MAAM,CAAC,MAAM,qBAAqB,GAAC,MAAM,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAC,cAAc,EAAC,iBAAiB,EAAC,iBAAiB,EAAC,cAAc,EAAC,gBAAgB,CAAU,CAAC,CAAC;AACzJ,wHAAwH;AACxH,MAAM,CAAC,MAAM,sBAAsB,GAAC,MAAM,CAAC,MAAM,CAAC,CAAC,cAAc,EAAC,gBAAgB,EAAC,qBAAqB,EAAC,yBAAyB;IAChI,wBAAwB,EAAC,eAAe,EAAC,kBAAkB,EAAC,sBAAsB,CAAU,CAAC,CAAC;AAYhG,SAAS,aAAa,CAAC,KAAY;IACjC,MAAM,GAAG,GAAC,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC;IACzB,IAAG,CAAC,CAAC,OAAO,EAAC,QAAQ,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAE,GAAG,CAAC,QAAQ,IAAE,GAAG,CAAC,QAAQ,IAAE,GAAG,CAAC,QAAQ,KAAG,GAAG,IAAE,GAAG,CAAC,MAAM,IAAE,GAAG,CAAC,IAAI;QAAC,MAAM,IAAI,KAAK,CAAC,gBAAgB,CAAC,CAAC;IACtJ,OAAO,GAAG,CAAC,MAAM,CAAC;AACpB,CAAC;AACD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MAAM,EAAE,CAAC,KAAK,CAAC,GAAE,EAAE,CAAA,SAAS,CAAC,CAAC;QAC5D,OAAO,IAAI,QAAQ,CAAC,KAAK,CAAA,CAAC,CAAA,IAAI,CAAA,CAAC,CAAA,QAAQ,CAAC,IAAI,EAAC,EAAC,MAAM,EAAC,QAAQ,CAAC,MAAM,EAAC,OAAO,EAAC,MAAM,EAAC,CAAC,CAAC;IACxF,CAAC,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@mpfrontend/presentation-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "license": "Apache-2.0",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/panahister/mpfrontend.git",
8
+ "directory": "packages/presentation-server"
9
+ },
10
+ "type": "module",
11
+ "main": "./dist/index.js",
12
+ "types": "./dist/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ },
18
+ "./relay": {
19
+ "types": "./dist/relay.d.ts",
20
+ "import": "./dist/relay.js"
21
+ },
22
+ "./internal": {
23
+ "types": "./dist/internal.d.ts",
24
+ "import": "./dist/internal.js"
25
+ }
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "README.md"
30
+ ],
31
+ "publishConfig": {
32
+ "access": "public",
33
+ "provenance": true
34
+ },
35
+ "dependencies": {
36
+ "ws": "8.22.0"
37
+ }
6
38
  }