@zixcel/view-delivery 0.0.0-stage → 0.10.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 +202 -0
- package/LICENSE-PREVIOUS +21 -0
- package/NOTICE +4 -0
- package/README.md +37 -2
- package/package.json +38 -4
- package/src/index.d.mts +51 -0
- package/src/index.mjs +225 -0
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/LICENSE-PREVIOUS
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hatter contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,38 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @zixcel/view-delivery
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Serve reviewed view snapshots and trusted release assets from a configured display host.
|
|
4
|
+
|
|
5
|
+
## What you can do
|
|
6
|
+
|
|
7
|
+
- Deliver an initial view with exact source references.
|
|
8
|
+
- Connect declared state updates and cancellation.
|
|
9
|
+
|
|
10
|
+
## Current scope
|
|
11
|
+
|
|
12
|
+
The current host is owner-local. Public HTTPS, authentication and placement require separate deployment validation.
|
|
13
|
+
|
|
14
|
+
Package distribution is not activated by this documentation. Use the checked-in source and the declared dependency versions; published availability must be verified separately.
|
|
15
|
+
|
|
16
|
+
## Getting started
|
|
17
|
+
|
|
18
|
+
The source uses registry version declarations for the generic Zixcel and Crowsi dependencies. Initial publication is pending; the migration verifier installs reviewed archives together in an isolated consumer. Product consumers retain their current released names until the new registry artifacts are verified.
|
|
19
|
+
|
|
20
|
+
Use the package manager matching the checked-in lockfile and the Node.js version declared in `package.json` or the development configuration. Run from this repository:
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
pnpm install --frozen-lockfile
|
|
24
|
+
pnpm test
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Documentation and source
|
|
28
|
+
|
|
29
|
+
[Usage guide](docs/getting-started.md)
|
|
30
|
+
|
|
31
|
+
[Implementation and public interfaces](src) · [Verification cases](test) · [Contributing](CONTRIBUTING.md) · [Security reporting](SECURITY.md) · [License](LICENSE) · [Attribution notices](NOTICE)
|
|
32
|
+
|
|
33
|
+
## Product boundary
|
|
34
|
+
|
|
35
|
+
The host requires an explicit owner, title, wire contract and allowed outcome
|
|
36
|
+
owner list. Cookie and request-header names may be supplied by the product;
|
|
37
|
+
defaults are generic. The Hatter browser UI remains in the product repository.
|
|
38
|
+
This workspace owns only the host and delivery contracts.
|
package/package.json
CHANGED
|
@@ -1,6 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zixcel/view-delivery",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.10.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"description": "Bounded trusted document and asset delivery; existing Crowsi STATE transport only",
|
|
7
|
+
"files": [
|
|
8
|
+
"src",
|
|
9
|
+
"README.md",
|
|
10
|
+
"LICENSE",
|
|
11
|
+
"NOTICE",
|
|
12
|
+
"LICENSE-PREVIOUS"
|
|
13
|
+
],
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"types": "./src/index.d.mts",
|
|
17
|
+
"import": "./src/index.mjs"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"@zixcel/view-delivery-contracts": "0.10.0",
|
|
22
|
+
"@crowsi/transport-foundation": "0.10.0",
|
|
23
|
+
"@crowsi/browser-security": "0.10.0",
|
|
24
|
+
"ws": "8.21.2",
|
|
25
|
+
"@types/node": "24.12.0",
|
|
26
|
+
"@zixcel/projection-contracts": "0.10.0"
|
|
27
|
+
},
|
|
28
|
+
"scripts": {
|
|
29
|
+
"test": "node --test test/*.test.mjs"
|
|
30
|
+
},
|
|
31
|
+
"types": "./src/index.d.mts",
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "git+https://github.com/zixcel/view-delivery.git"
|
|
35
|
+
},
|
|
36
|
+
"publishConfig": {
|
|
37
|
+
"access": "public",
|
|
38
|
+
"registry": "https://registry.npmjs.org"
|
|
39
|
+
}
|
|
40
|
+
}
|
package/src/index.d.mts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type {Server} from 'node:http'
|
|
2
|
+
import type {Asset,Delivery} from '@zixcel/view-delivery-contracts'
|
|
3
|
+
import type {Json} from '@zixcel/projection-contracts/client'
|
|
4
|
+
|
|
5
|
+
export interface RequestContext {readonly signal:AbortSignal}
|
|
6
|
+
export interface DocumentContext extends RequestContext {readonly assets:readonly Asset[]}
|
|
7
|
+
export interface CommandContext extends RequestContext {
|
|
8
|
+
readonly requestRef:string
|
|
9
|
+
observe(value:unknown):void
|
|
10
|
+
}
|
|
11
|
+
export interface DeliverySite {
|
|
12
|
+
document(url:URL,context:DocumentContext):Promise<{envelope:Delivery;bootstrap:Readonly<Record<string,Json>>}>|{envelope:Delivery;bootstrap:Readonly<Record<string,Json>>}
|
|
13
|
+
read(url:URL,context:RequestContext):unknown|Promise<unknown>
|
|
14
|
+
command(url:URL,value:unknown,context:CommandContext):unknown|Promise<unknown>
|
|
15
|
+
live(request:unknown):unknown|Promise<unknown>
|
|
16
|
+
close?():void|Promise<void>
|
|
17
|
+
}
|
|
18
|
+
export interface TrustedAsset {
|
|
19
|
+
readonly path:string
|
|
20
|
+
readonly bytes:Uint8Array
|
|
21
|
+
readonly bytesLength:number
|
|
22
|
+
readonly digest:string
|
|
23
|
+
readonly kind:'script'|'style'
|
|
24
|
+
}
|
|
25
|
+
export interface DeliveryServer {
|
|
26
|
+
readonly server:Server
|
|
27
|
+
notify():void
|
|
28
|
+
inspect():{readonly alive:boolean;readonly activeRequests:number;readonly transport:unknown}
|
|
29
|
+
listen():Promise<void>
|
|
30
|
+
close():Promise<void>
|
|
31
|
+
}
|
|
32
|
+
export interface DeliveryPolicy {
|
|
33
|
+
readonly owner:string
|
|
34
|
+
readonly title:string
|
|
35
|
+
readonly contract:string
|
|
36
|
+
readonly allowedOwners:readonly string[]
|
|
37
|
+
readonly cookieName?:string
|
|
38
|
+
readonly csrfHeader?:string
|
|
39
|
+
readonly nonceHeader?:string
|
|
40
|
+
readonly readinessHeader?:string
|
|
41
|
+
}
|
|
42
|
+
export interface DeliveryServerOptions {
|
|
43
|
+
readonly policy:DeliveryPolicy
|
|
44
|
+
readonly origin:string
|
|
45
|
+
readonly site:DeliverySite
|
|
46
|
+
readonly assets:readonly TrustedAsset[]
|
|
47
|
+
readonly readinessToken?:string|null
|
|
48
|
+
readonly onFailure?:((failure:unknown)=>void)|null
|
|
49
|
+
readonly onOutcome?:((outcome:unknown)=>void)|null
|
|
50
|
+
}
|
|
51
|
+
export function createDeliveryServer(options:DeliveryServerOptions):DeliveryServer
|
package/src/index.mjs
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// Caller-owned snapshot delivery. Crowsi owns framing/session/ACK/recovery mechanisms.
|
|
2
|
+
import http from 'node:http'
|
|
3
|
+
import {createHash,timingSafeEqual,randomUUID} from 'node:crypto'
|
|
4
|
+
import {WebSocketServer} from 'ws'
|
|
5
|
+
import {StateSocketServer} from '@crowsi/transport-foundation/state-socket'
|
|
6
|
+
import {Budget,limitsFor} from '@crowsi/transport-foundation'
|
|
7
|
+
import {SessionAuthority} from '@crowsi/browser-security/access'
|
|
8
|
+
import {parseOwnerOrigin,assessRequestBoundary} from '@crowsi/browser-security/boundary'
|
|
9
|
+
import {validateDelivery,bounds,requirement} from '@zixcel/view-delivery-contracts'
|
|
10
|
+
|
|
11
|
+
const fail=code=>{throw Object.assign(Error(code),{code})}
|
|
12
|
+
const defaultCookieName='view_delivery_session'
|
|
13
|
+
const headers={
|
|
14
|
+
'content-security-policy':"default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self'; base-uri 'none'; object-src 'none'; frame-ancestors 'none'; form-action 'self'",
|
|
15
|
+
'referrer-policy':'no-referrer','x-content-type-options':'nosniff','x-frame-options':'DENY',
|
|
16
|
+
'permissions-policy':'camera=(), microphone=(), geolocation=(), payment=()','cache-control':'no-store'
|
|
17
|
+
}
|
|
18
|
+
const encode=(value,maximum=bounds.documentBytes)=>{
|
|
19
|
+
// Site/owner outputs are already bounded data. Refuse expansion before sending.
|
|
20
|
+
let nodes=0,total=0
|
|
21
|
+
const add=bytes=>{total+=bytes;if(total>maximum)fail('DeliveryLimitExceeded')}
|
|
22
|
+
function check(v,depth){
|
|
23
|
+
if(++nodes>32768||depth>20)fail('DeliveryLimitExceeded')
|
|
24
|
+
if(typeof v==='string'){if(v.length>maximum)fail('DeliveryLimitExceeded');add(Buffer.byteLength(v)+2);return}
|
|
25
|
+
if(v===null||typeof v==='boolean'){add(5);return}
|
|
26
|
+
if(typeof v==='number'&&Number.isFinite(v)){add(24);return}
|
|
27
|
+
if(!v||typeof v!=='object'||!Array.isArray(v)&&Object.getPrototypeOf(v)!==Object.prototype)fail('InvalidDeliveryData')
|
|
28
|
+
const keys=Object.keys(v);if(keys.length>4096)fail('DeliveryLimitExceeded');add(keys.length+2)
|
|
29
|
+
for(const key of keys){const d=Object.getOwnPropertyDescriptor(v,key);if(d.get||d.set||key==='toJSON')fail('InvalidDeliveryData');add(Buffer.byteLength(key)+3);check(d.value,depth+1)}
|
|
30
|
+
}
|
|
31
|
+
check(value,0);const bytes=Buffer.from(JSON.stringify(value));if(bytes.length>maximum)fail('DeliveryLimitExceeded');return bytes
|
|
32
|
+
}
|
|
33
|
+
async function body(request,signal){
|
|
34
|
+
const h=request.headers,raw=h['content-length']
|
|
35
|
+
if(h['content-encoding']||h['transfer-encoding']||!/^application\/json(?:\s*;.*)?$/i.test(h['content-type']??'')||!(/^[1-9][0-9]{0,5}$/).test(raw??''))fail('InvalidInput')
|
|
36
|
+
const size=Number(raw);if(size>bounds.requestBytes)fail('DeliveryLimitExceeded')
|
|
37
|
+
const data=Buffer.alloc(size);let used=0
|
|
38
|
+
for await(const chunk of request){if(signal.aborted)fail('DeliveryCancelled');if(used+chunk.length>size)fail('DeliveryLimitExceeded');chunk.copy(data,used);used+=chunk.length}
|
|
39
|
+
if(used!==size)fail('InvalidInput')
|
|
40
|
+
try{return JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(data))}catch{fail('InvalidInput')}
|
|
41
|
+
}
|
|
42
|
+
function sessionId(request,cookieName){
|
|
43
|
+
const cookie=request.headers.cookie??'';if(cookie.length>8192)fail('SessionRejected')
|
|
44
|
+
const values=cookie.split(';').map(s=>s.trim()).filter(s=>s.startsWith(cookieName+'='))
|
|
45
|
+
if(values.length!==1)fail('SessionRejected');return values[0].slice(cookieName.length+1)
|
|
46
|
+
}
|
|
47
|
+
// Crowsi's access contract currently uses closed Error messages, not .code.
|
|
48
|
+
// Recognize only those published constants; never expose arbitrary exception text.
|
|
49
|
+
const accessCodes=new Set(['host-rejected','origin-rejected','origin-required','fetch-site-rejected','session-capacity-reached','session-rejected','session-expired','csrf-rejected',
|
|
50
|
+
'request-nonce-invalid','request-replayed','request-nonce-capacity-reached'].map(c=>'crowsi-browser-security-'+c))
|
|
51
|
+
const deliveryCodes=new Set(['SessionRejected','InvalidInput','DeliveryLimitExceeded','DeliveryCancelled','DeliveryTimedOut','InvalidDeliveryData',
|
|
52
|
+
'InvalidAsset','NotFound','MethodNotAllowed','ProjectionCancelled','ProjectionRuntimeClosed','ProjectionQueueFull',
|
|
53
|
+
'ProjectionStoreBusy','ProjectionStoreCorrupt','SourceUnavailable','SourceNotRetained','SourceRevisionMismatch',
|
|
54
|
+
'ProjectionUnavailable','ProjectionLimitExceeded','ProjectionExecutionTimeout','StaleSceneAction','SceneUnavailable',
|
|
55
|
+
'InteractionUnavailable','InvalidProjection','OriginRequired','SocketUnavailable'])
|
|
56
|
+
function sourceFailure(error,operation,observation){
|
|
57
|
+
const access=accessCodes.has(error?.message),typed=error?.failure
|
|
58
|
+
let original
|
|
59
|
+
try{original=requirement({ref:typed.requirementRef,owner:typed.owner,state:'Unavailable',failure:typed,setup:null}).failure}catch{}
|
|
60
|
+
const code=original?.code??(access?error.message:deliveryCodes.has(error?.code)?error.code:
|
|
61
|
+
typeof typed?.code==='string'&&/^[a-z][a-z0-9-]{2,95}$/.test(typed.code)?typed.code:'UnhandledDeliveryFault')
|
|
62
|
+
return {code,canonical:{state:observation.receiptRef?'Committed':['DELIVERY_REJECTED','NOT_DISPATCHED'].includes(observation.stage)?'NotDispatched':observation.stage==='OWNER_REJECTED'?'Rejected':'Unknown',receiptRef:observation.receiptRef},ownerFailure:{owner:original?.owner??(access?'crowsi/browser-security':observation.owner),operation:original?.operation??observation.operation??operation,
|
|
63
|
+
code,requirementRef:original?.requirementRef??'delivery:server',outcomeStage:observation.stage,uncertain:observation.stage==='OUTCOME_UNCERTAIN',
|
|
64
|
+
requestRef:observation.requestRef,managementRequestRef:observation.managementRequestRef??null,receiptRef:observation.receiptRef,detail:original?.detail??null}}
|
|
65
|
+
}
|
|
66
|
+
function safeDocument(envelope,bootstrap,title){
|
|
67
|
+
const serialized=encode({envelope,bootstrap}).toString().replace(/</g,'\\u003c').replace(/>/g,'\\u003e').replace(/&/g,'\\u0026')
|
|
68
|
+
const styles=envelope.assets.filter(a=>a.kind==='style').map(a=>`<link rel="stylesheet" href="${a.path}">`).join('')
|
|
69
|
+
const scripts=envelope.assets.filter(a=>a.kind==='script').map(a=>`<script type="module" src="${a.path}"></script>`).join('')
|
|
70
|
+
return Buffer.from(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title}</title>${styles}</head><body><main id="app" aria-busy="true"><p role="status">Loading exact state…</p></main><script id="delivery-state" type="application/json">${serialized}</script>${scripts}</body></html>`)
|
|
71
|
+
}
|
|
72
|
+
export function createDeliveryServer({origin,site,assets,readinessToken=null,onFailure=null,onOutcome=null,policy}){
|
|
73
|
+
if(!policy||typeof policy.owner!=='string'||!policy.owner||policy.owner.length>128||
|
|
74
|
+
typeof policy.contract!=='string'||!policy.contract||policy.contract.length>128||typeof policy.title!=='string'||!policy.title||policy.title.length>128||/[<>&]/.test(policy.title)||
|
|
75
|
+
!Array.isArray(policy.allowedOwners)||policy.allowedOwners.length>16||policy.allowedOwners.some(owner=>typeof owner!=='string'||!owner||owner.length>128))fail('InvalidDeliveryPolicy')
|
|
76
|
+
const headerPolicy={cookieName:policy.cookieName??defaultCookieName,csrfHeader:policy.csrfHeader??'x-delivery-csrf',nonceHeader:policy.nonceHeader??'x-delivery-request-nonce',readinessHeader:policy.readinessHeader??'x-delivery-readiness'}
|
|
77
|
+
if(Object.values(headerPolicy).some(value=>typeof value!=='string'||value.length>64||!/[a-z]/.test(value)||!/^[a-z0-9_-]+$/.test(value)))fail('InvalidDeliveryPolicy')
|
|
78
|
+
const ownerPolicy=Object.freeze({owner:policy.owner,title:policy.title,contract:policy.contract,allowedOwners:Object.freeze([...policy.allowedOwners]),...headerPolicy})
|
|
79
|
+
const boundary=parseOwnerOrigin(origin),authority=new SessionAuthority(),inflight=new Set(),controllers=new Set()
|
|
80
|
+
const budget=new Budget(limitsFor(bounds.documentBytes,{pendingMessages:bounds.requests})),assetMap=new Map()
|
|
81
|
+
for(const asset of assets){
|
|
82
|
+
const {bytes,...descriptor}=asset,content=Buffer.from(bytes)
|
|
83
|
+
if(content.length!==descriptor.bytesLength||content.length>bounds.assetBytes)fail('InvalidAsset')
|
|
84
|
+
const digest=createHash('sha256').update(content).digest('hex')
|
|
85
|
+
if(digest!==descriptor.digest||assetMap.has(descriptor.path)||!/^\/assets\/[a-zA-Z0-9._-]{1,100}$/.test(descriptor.path)||!['script','style'].includes(descriptor.kind))fail('InvalidAsset')
|
|
86
|
+
assetMap.set(descriptor.path,{content,descriptor:{path:descriptor.path,digest,bytes:content.length,kind:descriptor.kind}})
|
|
87
|
+
}
|
|
88
|
+
if(assetMap.size<1||assetMap.size>bounds.assets)fail('InvalidAsset')
|
|
89
|
+
let closing=false,closePromise=null
|
|
90
|
+
const authorize=request=>{
|
|
91
|
+
const reason=assessRequestBoundary(boundary,{method:request.method,host:request.headers.host,origin:request.headers.origin,fetchSite:request.headers['sec-fetch-site']})
|
|
92
|
+
if(reason)fail(reason)
|
|
93
|
+
}
|
|
94
|
+
const authenticate=request=>{const id=sessionId(request,ownerPolicy.cookieName);authority.authenticate(id);return id}
|
|
95
|
+
const connection=(request,response)=>{
|
|
96
|
+
let current
|
|
97
|
+
try{const id=authenticate(request);current={sessionId:id,...authority.authenticate(id)}}catch{current=authority.issue()}
|
|
98
|
+
response.setHeader('set-cookie',`${ownerPolicy.cookieName}=${current.sessionId}; Path=/; HttpOnly; SameSite=Strict; Max-Age=28800${boundary.protocol==='https:'?'; Secure':''}`)
|
|
99
|
+
return {csrf:current.csrfToken,expiresAtUnixMs:current.expiresAt}
|
|
100
|
+
}
|
|
101
|
+
const hub=new StateSocketServer({authorize:peer=>{authorize(peer.request);if(peer.request.headers.origin!==origin)fail('OriginRequired');return authenticate(peer.request)},read:request=>site.live(request)})
|
|
102
|
+
const sockets=new WebSocketServer({noServer:true,maxPayload:1048578,perMessageDeflate:false,clientTracking:true})
|
|
103
|
+
const send=(response,status,value)=>{const bytes=encode(value);response.writeHead(status,{'content-type':'application/json; charset=utf-8','content-length':bytes.length});response.end(bytes)}
|
|
104
|
+
async function handle(request,response,signal,observation){
|
|
105
|
+
for(const [key,value]of Object.entries(headers))response.setHeader(key,value)
|
|
106
|
+
authorize(request)
|
|
107
|
+
if(request.url.length>4096)fail('InvalidInput')
|
|
108
|
+
const url=new URL(request.url,origin),pathname=url.pathname
|
|
109
|
+
if(request.method==='GET'&&pathname==='/api/ready'){
|
|
110
|
+
const provided=Buffer.from(String(request.headers[ownerPolicy.readinessHeader]??'')),expected=Buffer.from(readinessToken??'')
|
|
111
|
+
if(!expected.length||provided.length!==expected.length||!timingSafeEqual(provided,expected))return send(response,404,{error:{code:'NotFound'}})
|
|
112
|
+
observation.stage='NOT_DISPATCHED';response.writeHead(204);response.end();return // liveness only, never ProductReady
|
|
113
|
+
}
|
|
114
|
+
if(request.method==='GET'&&assetMap.has(pathname)){
|
|
115
|
+
observation.stage='NOT_DISPATCHED'
|
|
116
|
+
const asset=assetMap.get(pathname);response.writeHead(200,{'content-type':asset.descriptor.kind==='script'?'text/javascript; charset=utf-8':'text/css; charset=utf-8','content-length':asset.content.length});response.end(asset.content);return
|
|
117
|
+
}
|
|
118
|
+
if(request.method==='POST'&&pathname==='/api/connection'){
|
|
119
|
+
const value=await body(request,signal);if(!value||Array.isArray(value)||Object.keys(value).length)fail('InvalidInput')
|
|
120
|
+
observation.stage='NOT_DISPATCHED';send(response,200,connection(request,response));return
|
|
121
|
+
}
|
|
122
|
+
if(request.method==='GET'&&!pathname.startsWith('/api/')){
|
|
123
|
+
observation.stage='NOT_DISPATCHED'
|
|
124
|
+
const csrf=connection(request,response)
|
|
125
|
+
const {envelope,bootstrap}=await site.document(url,{signal,assets:[...assetMap.values()].map(a=>a.descriptor)})
|
|
126
|
+
validateDelivery(envelope,ownerPolicy.contract)
|
|
127
|
+
if(JSON.stringify(envelope.assets)!==JSON.stringify([...assetMap.values()].map(a=>a.descriptor)))fail('InvalidAsset')
|
|
128
|
+
const document=safeDocument(envelope,{...bootstrap,...csrf},ownerPolicy.title)
|
|
129
|
+
if(document.length>bounds.documentBytes)fail('DeliveryLimitExceeded')
|
|
130
|
+
response.writeHead(200,{'content-type':'text/html; charset=utf-8','content-length':document.length});response.end(document);return
|
|
131
|
+
}
|
|
132
|
+
authenticate(request)
|
|
133
|
+
if(request.method==='GET'){observation.stage='NOT_DISPATCHED';send(response,200,await site.read(url,{signal}));return}
|
|
134
|
+
if(request.method!=='POST')return send(response,405,{error:{code:'MethodNotAllowed'}})
|
|
135
|
+
authority.authorizeMutation(sessionId(request,ownerPolicy.cookieName),request.headers[ownerPolicy.csrfHeader],request.headers[ownerPolicy.nonceHeader])
|
|
136
|
+
const value=await body(request,signal)
|
|
137
|
+
observation.stage='OUTCOME_UNCERTAIN'
|
|
138
|
+
// The site was entered, not proof of physical dispatch or canonical commit.
|
|
139
|
+
// Only exact owner evidence may refine this transient observation.
|
|
140
|
+
const observe=value=>{
|
|
141
|
+
// Trusted site supplies evidence only. Ignore malformed observations; never
|
|
142
|
+
// change execution branching, mint identity, or persist a competing receipt.
|
|
143
|
+
if(!value||!['NOT_DISPATCHED','OWNER_REJECTED','OUTCOME_UNCERTAIN','OWNER_COMMITTED','PUBLICATION_FAILED_AFTER_COMMIT'].includes(value.stage))return
|
|
144
|
+
if(typeof value.owner!=='string'||!ownerPolicy.allowedOwners.includes(value.owner))return
|
|
145
|
+
if(typeof value.operation!=='string'||!/^[a-z][a-z0-9]*(?:\/[a-z][a-zA-Z0-9]*)+$/.test(value.operation))return
|
|
146
|
+
if(value.receiptRef!==undefined&&value.receiptRef!==null&&!/^[a-f0-9]{64}$/.test(value.receiptRef))return
|
|
147
|
+
if(['OWNER_COMMITTED','PUBLICATION_FAILED_AFTER_COMMIT'].includes(value.stage)&&!value.receiptRef)return
|
|
148
|
+
if(observation.receiptRef&&value.receiptRef!==observation.receiptRef)return
|
|
149
|
+
if(value.managementRequestRef!==undefined&&value.managementRequestRef!==null&&(!Number.isSafeInteger(value.managementRequestRef)||value.managementRequestRef<1))return
|
|
150
|
+
Object.assign(observation,{stage:value.stage,owner:value.owner,operation:value.operation,receiptRef:value.receiptRef??null})
|
|
151
|
+
if(value.managementRequestRef!==undefined)observation.managementRequestRef=value.managementRequestRef
|
|
152
|
+
}
|
|
153
|
+
const result=await site.command(url,value,{signal,observe,requestRef:observation.requestRef})
|
|
154
|
+
const receipt=result?.canonical?.receiptRef
|
|
155
|
+
if(typeof receipt==='string'&&/^[a-f0-9]{64}$/.test(receipt)){
|
|
156
|
+
observation.receiptRef=receipt;observation.stage=result.projection?.state==='FailedTyped'?'PUBLICATION_FAILED_AFTER_COMMIT':'OWNER_COMMITTED'
|
|
157
|
+
}
|
|
158
|
+
if(!response.writableEnded&&!response.destroyed)send(response,200,result)
|
|
159
|
+
}
|
|
160
|
+
const server=http.createServer({maxHeaderSize:16384,headersTimeout:5000,requestTimeout:5000,keepAliveTimeout:2000},(request,response)=>{
|
|
161
|
+
if(closing){response.writeHead(503);response.end();return}
|
|
162
|
+
let release;try{release=budget.reserve(0)}catch{send(response,503,{error:{code:'DeliveryQueueFull'}});return}
|
|
163
|
+
const controller=new AbortController();controllers.add(controller)
|
|
164
|
+
const abort=()=>controller.abort();response.once('close',abort)
|
|
165
|
+
const observation={requestRef:randomUUID(),owner:ownerPolicy.owner,stage:'DELIVERY_REJECTED',receiptRef:null}
|
|
166
|
+
// Paths and query strings are caller input, not safe diagnostic labels.
|
|
167
|
+
const path=request.url?.split('?')[0],operation=['/api/subjects','/api/interactions','/api/site-actions','/api/setup','/api/connection','/api/document'].includes(path)?path:'delivery/request'
|
|
168
|
+
const recordFailure=error=>{
|
|
169
|
+
const failure=sourceFailure(error,operation,observation)
|
|
170
|
+
try{onFailure?.(failure)}catch{}
|
|
171
|
+
return failure
|
|
172
|
+
}
|
|
173
|
+
// Preserve the finite HTTP observer deadline, but send a truthful outcome
|
|
174
|
+
// rather than resetting a reused socket (browsers may retransmit that POST).
|
|
175
|
+
// This does not cancel an accepted owner action or renew its execution budget.
|
|
176
|
+
const timer=setTimeout(()=>{
|
|
177
|
+
if(!response.writableEnded&&!response.destroyed){
|
|
178
|
+
const failure=recordFailure(Object.assign(Error('DeliveryTimedOut'),{code:'DeliveryTimedOut'}))
|
|
179
|
+
send(response,504,{error:failure})
|
|
180
|
+
}
|
|
181
|
+
controller.abort()
|
|
182
|
+
},bounds.bodyMs)
|
|
183
|
+
const work=handle(request,response,controller.signal,observation).catch(error=>{
|
|
184
|
+
const failure=recordFailure(error)
|
|
185
|
+
// Read-only diagnostic callback: no inherited preload, payload, credentials or
|
|
186
|
+
// stack. A diagnostic consumer cannot alter the execution branch by throwing.
|
|
187
|
+
if(!response.headersSent&&!response.destroyed)send(response,400,{error:failure})
|
|
188
|
+
else if(!response.writableEnded&&!response.destroyed)response.destroy()
|
|
189
|
+
}).finally(()=>{
|
|
190
|
+
try{onOutcome?.({...observation,operation:observation.operation??operation,httpStatus:response.headersSent?response.statusCode:null})}catch{}
|
|
191
|
+
clearTimeout(timer);response.off('close',abort);release();controllers.delete(controller);inflight.delete(work)
|
|
192
|
+
});inflight.add(work)
|
|
193
|
+
})
|
|
194
|
+
server.maxConnections=32;server.maxRequestsPerSocket=128
|
|
195
|
+
server.on('upgrade',(request,socket,head)=>{
|
|
196
|
+
try{if(closing||request.url!=='/api/projection-live'||hub.inspect().connections>=8)fail('SocketUnavailable');authorize(request);authenticate(request);if(request.headers.origin!==origin)fail('OriginRequired')}
|
|
197
|
+
catch{socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n');return}
|
|
198
|
+
sockets.handleUpgrade(request,socket,head,websocket=>{
|
|
199
|
+
const peer={request,websocket,close:(code,reason)=>websocket.close(code,reason)}
|
|
200
|
+
websocket.on('message',data=>hub.message(peer,data));websocket.on('close',()=>hub.disconnect(peer));websocket.on('error',()=>hub.disconnect(peer));hub.open(peer)
|
|
201
|
+
})
|
|
202
|
+
})
|
|
203
|
+
return {server,notify:()=>hub.notify(),inspect:()=>({alive:server.listening,activeRequests:inflight.size,transport:hub.inspect()}),
|
|
204
|
+
async listen(){await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(Number(boundary.port),'127.0.0.1',resolve)})},
|
|
205
|
+
close(){
|
|
206
|
+
if(closePromise)return closePromise
|
|
207
|
+
closing=true
|
|
208
|
+
// Closing delivery revokes intake and releases transport, not physical work.
|
|
209
|
+
// Let the owning site close its resources BEFORE awaiting its pending calls:
|
|
210
|
+
// their completion may depend on that close. Join one lifecycle promise even
|
|
211
|
+
// for concurrent close callers, and preserve an owner cleanup failure.
|
|
212
|
+
closePromise=Promise.resolve().then(async()=>{
|
|
213
|
+
for(const c of controllers)c.abort()
|
|
214
|
+
hub.close();for(const ws of sockets.clients)ws.terminate()
|
|
215
|
+
const transportClosed=new Promise(resolve=>sockets.close(resolve))
|
|
216
|
+
const httpClosed=new Promise(resolve=>server.close(resolve))
|
|
217
|
+
server.closeIdleConnections();server.closeAllConnections()
|
|
218
|
+
const ownerClosed=Promise.resolve().then(()=>site.close?.())
|
|
219
|
+
const results=await Promise.allSettled([transportClosed,httpClosed,ownerClosed,...inflight])
|
|
220
|
+
const failures=results.filter(result=>result.status==='rejected').map(result=>result.reason)
|
|
221
|
+
if(failures.length)throw new AggregateError(failures,'Delivery shutdown failed')
|
|
222
|
+
})
|
|
223
|
+
return closePromise
|
|
224
|
+
}}
|
|
225
|
+
}
|