@volter/world-core 2.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 +202 -0
- package/README.md +29 -0
- package/app-route.cjs +154 -0
- package/app-route.d.cts +7 -0
- package/attach.cjs +80 -0
- package/dist/app-route.cjs +154 -0
- package/dist/app-route.d.cts +7 -0
- package/dist/attach.cjs +80 -0
- package/dist/generated/pack-facts.json +4306 -0
- package/dist/inject.cjs +1097 -0
- package/dist/network-policy.cjs +92 -0
- package/dist/network-policy.d.cts +10 -0
- package/dist/src/actions.d.ts +276 -0
- package/dist/src/actions.js +436 -0
- package/dist/src/ancestry.d.ts +22 -0
- package/dist/src/ancestry.js +238 -0
- package/dist/src/args.d.ts +3 -0
- package/dist/src/args.js +12 -0
- package/dist/src/blob-store.d.ts +55 -0
- package/dist/src/blob-store.js +186 -0
- package/dist/src/brand-tokens.d.ts +2 -0
- package/dist/src/brand-tokens.js +17 -0
- package/dist/src/changeset.d.ts +431 -0
- package/dist/src/changeset.js +0 -0
- package/dist/src/client-bundle.d.ts +1 -0
- package/dist/src/client-bundle.js +28 -0
- package/dist/src/credential.d.ts +38 -0
- package/dist/src/credential.js +114 -0
- package/dist/src/derived-core.d.ts +452 -0
- package/dist/src/derived-core.js +782 -0
- package/dist/src/derived.d.ts +84 -0
- package/dist/src/derived.js +122 -0
- package/dist/src/emit.d.ts +106 -0
- package/dist/src/emit.js +157 -0
- package/dist/src/executor.d.ts +120 -0
- package/dist/src/executor.js +387 -0
- package/dist/src/file-response.d.ts +3 -0
- package/dist/src/file-response.js +22 -0
- package/dist/src/fork.d.ts +26 -0
- package/dist/src/fork.js +68 -0
- package/dist/src/git/history.d.ts +36 -0
- package/dist/src/git/history.js +298 -0
- package/dist/src/git/index.d.ts +6 -0
- package/dist/src/git/index.js +6 -0
- package/dist/src/git/inflate.d.ts +11 -0
- package/dist/src/git/inflate.js +194 -0
- package/dist/src/git/objects.d.ts +64 -0
- package/dist/src/git/objects.js +161 -0
- package/dist/src/git/pack.d.ts +14 -0
- package/dist/src/git/pack.js +199 -0
- package/dist/src/git/refs.d.ts +19 -0
- package/dist/src/git/refs.js +35 -0
- package/dist/src/git/smart-http.d.ts +45 -0
- package/dist/src/git/smart-http.js +223 -0
- package/dist/src/hash.d.ts +38 -0
- package/dist/src/hash.js +48 -0
- package/dist/src/head.d.ts +140 -0
- package/dist/src/head.js +313 -0
- package/dist/src/history.d.ts +76 -0
- package/dist/src/history.js +322 -0
- package/dist/src/index.d.ts +73 -0
- package/dist/src/index.js +98 -0
- package/dist/src/lifecycle.d.ts +1 -0
- package/dist/src/lifecycle.js +8 -0
- package/dist/src/log.d.ts +254 -0
- package/dist/src/log.js +801 -0
- package/dist/src/mirror-shell.d.ts +2 -0
- package/dist/src/mirror-shell.js +13 -0
- package/dist/src/observe.d.ts +49 -0
- package/dist/src/observe.js +148 -0
- package/dist/src/pack-assets.d.ts +30 -0
- package/dist/src/pack-assets.js +88 -0
- package/dist/src/packRegistry.d.ts +374 -0
- package/dist/src/packRegistry.js +142 -0
- package/dist/src/placeholder-remote.d.ts +22 -0
- package/dist/src/placeholder-remote.js +86 -0
- package/dist/src/proxy.d.ts +25 -0
- package/dist/src/proxy.js +155 -0
- package/dist/src/rateBudget.d.ts +367 -0
- package/dist/src/rateBudget.js +925 -0
- package/dist/src/references.d.ts +18 -0
- package/dist/src/references.js +27 -0
- package/dist/src/remote-execute.d.ts +22 -0
- package/dist/src/remote-execute.js +1 -0
- package/dist/src/resource-blob.d.ts +10 -0
- package/dist/src/resource-blob.js +56 -0
- package/dist/src/scenario.d.ts +197 -0
- package/dist/src/scenario.js +425 -0
- package/dist/src/schemas.d.ts +78 -0
- package/dist/src/schemas.js +50 -0
- package/dist/src/serve-http.d.ts +48 -0
- package/dist/src/serve-http.js +340 -0
- package/dist/src/serve.d.ts +147 -0
- package/dist/src/serve.js +507 -0
- package/dist/src/shared-blob-index.d.ts +4 -0
- package/dist/src/shared-blob-index.js +126 -0
- package/dist/src/state-system.d.ts +70 -0
- package/dist/src/state-system.js +90 -0
- package/dist/src/storage.d.ts +101 -0
- package/dist/src/storage.js +337 -0
- package/dist/src/twin-fetch.d.ts +64 -0
- package/dist/src/twin-fetch.js +91 -0
- package/dist/src/types.d.ts +40 -0
- package/dist/src/types.js +1 -0
- package/dist/src/v1-removed.d.ts +159 -0
- package/dist/src/v1-removed.js +124 -0
- package/dist/src/volter-home.d.ts +5 -0
- package/dist/src/volter-home.js +10 -0
- package/dist/src/world-clock.d.ts +4 -0
- package/dist/src/world-clock.js +32 -0
- package/dist/src/world-env.d.ts +3 -0
- package/dist/src/world-env.js +22 -0
- package/dist/src/world-store-sql.d.ts +27 -0
- package/dist/src/world-store-sql.js +86 -0
- package/dist/src/world-store.d.ts +168 -0
- package/dist/src/world-store.js +475 -0
- package/dist/src/worldConfig.d.ts +9 -0
- package/dist/src/worldConfig.js +17 -0
- package/dist/stream-bridge.cjs +80 -0
- package/dist/vendor-hosts.cjs +200 -0
- package/generated/pack-facts.json +4306 -0
- package/inject.cjs +1097 -0
- package/network-policy.cjs +92 -0
- package/network-policy.d.cts +10 -0
- package/package.json +103 -0
- package/src/actions.ts +564 -0
- package/src/ancestry.ts +213 -0
- package/src/args.ts +14 -0
- package/src/blob-store.ts +185 -0
- package/src/brand-tokens.ts +17 -0
- package/src/changeset.ts +1032 -0
- package/src/client-bundle.ts +29 -0
- package/src/credential.ts +140 -0
- package/src/derived-core.ts +1004 -0
- package/src/derived.ts +176 -0
- package/src/emit.ts +242 -0
- package/src/executor.ts +431 -0
- package/src/file-response.ts +22 -0
- package/src/fork.ts +89 -0
- package/src/git/history.ts +177 -0
- package/src/git/index.ts +6 -0
- package/src/git/inflate.ts +125 -0
- package/src/git/objects.ts +110 -0
- package/src/git/pack.ts +105 -0
- package/src/git/refs.ts +25 -0
- package/src/git/smart-http.ts +149 -0
- package/src/hash.ts +66 -0
- package/src/head.ts +318 -0
- package/src/history.ts +246 -0
- package/src/index.ts +323 -0
- package/src/lifecycle.ts +8 -0
- package/src/log.ts +793 -0
- package/src/mirror-shell.ts +15 -0
- package/src/observe.ts +130 -0
- package/src/pack-assets.ts +81 -0
- package/src/packRegistry.ts +408 -0
- package/src/placeholder-remote.ts +81 -0
- package/src/proxy.ts +183 -0
- package/src/rateBudget.ts +1115 -0
- package/src/references.ts +46 -0
- package/src/remote-execute.ts +26 -0
- package/src/resource-blob.ts +57 -0
- package/src/scenario.ts +479 -0
- package/src/schemas.ts +56 -0
- package/src/serve-http.ts +299 -0
- package/src/serve.ts +618 -0
- package/src/shared-blob-index.ts +108 -0
- package/src/state-system.ts +115 -0
- package/src/storage.ts +407 -0
- package/src/twin-fetch.ts +147 -0
- package/src/types.ts +50 -0
- package/src/v1-removed.ts +172 -0
- package/src/volter-home.ts +11 -0
- package/src/world-clock.ts +33 -0
- package/src/world-env.ts +18 -0
- package/src/world-store-sql.ts +118 -0
- package/src/world-store.ts +572 -0
- package/src/worldConfig.ts +27 -0
- package/stream-bridge.cjs +80 -0
- package/vendor-hosts.cjs +200 -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/README.md
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# @volter/world-core
|
|
2
|
+
|
|
3
|
+
The shared state kernel and vendor-independent runtime libraries used by `@volter/twin-<vendor>`.
|
|
4
|
+
The product CLI and SDK are in [`@volter/world`](../cli/README.md).
|
|
5
|
+
|
|
6
|
+
## State and branching
|
|
7
|
+
|
|
8
|
+
[The model](../../docs/concepts/the-model.md) is the canonical explanation: one logical log,
|
|
9
|
+
checkpoints, a branch's parent position and its own entries, and simulated or real execution at
|
|
10
|
+
the head. Push lands entries in a parent; deploy performs them against the vendor and records
|
|
11
|
+
receipts. The Git-inspired verbs do not imply staging, commits or a Git object database.
|
|
12
|
+
|
|
13
|
+
The file store has inherited entries (`events.jsonl`), branch entries (`actions.jsonl`),
|
|
14
|
+
`branch.json`, a fetched URL-parent cache (`origin.jsonl`) and checkpoints. These are storage
|
|
15
|
+
segments of that model, not independent observed-state and local-action truth systems.
|
|
16
|
+
See [`log.ts`](./src/log.ts) for the format and [`state-system.ts`](./src/state-system.ts) for
|
|
17
|
+
execution. Payloads use the [blob storage contract](../../docs/contributing/architecture.md#portable-host-and-immutable-payloads).
|
|
18
|
+
|
|
19
|
+
## Building a twin
|
|
20
|
+
|
|
21
|
+
A protocol-2 twin implements its vendor's request/response semantics while the shared kernel
|
|
22
|
+
owns log ordering, checkpoints, branching and the head's state system. Use the tree readers and
|
|
23
|
+
write path exported by [`src/index.ts`](./src/index.ts); do not reconstruct a serve-time view by
|
|
24
|
+
folding the log or use removed v1 confirmation/suppression APIs.
|
|
25
|
+
|
|
26
|
+
[Architecture](../../docs/contributing/architecture.md) owns the boundaries and
|
|
27
|
+
[adding a twin](../../docs/contributing/adding-a-twin.md) owns the implementation and verification
|
|
28
|
+
process. Package protocol standing is recorded in the [generated index](../../generated/INDEX.md).
|
|
29
|
+
Conformance tooling is a development dependency in `@volter/world-tooling`.
|
package/app-route.cjs
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// THE APPLICATION'S OWN HOSTNAMES IN THE WORLD — the one home of the app route (dependency-free, side-effect free).
|
|
3
|
+
//
|
|
4
|
+
// `volter-world app-url <world> --host <name>` records the hostnames an application answers as in production beside
|
|
5
|
+
// its URL (`app-url.json` in the instance); inside the World they reach the application, as DNS routes them to its
|
|
6
|
+
// host in production (architecture.md, "The application's own production hostnames"). Two kinds of process route
|
|
7
|
+
// them, and both read the route here:
|
|
8
|
+
// · a process the injector is installed in (the application, a script, the redirect proxy): inject.cjs's
|
|
9
|
+
// resolveTwin answers a recorded host with the application's origin, after twins and the hosts twins claim;
|
|
10
|
+
// · a twin's own outbound request (a QStash delivery, a webhook) from the colocated twin host, which runs without the
|
|
11
|
+
// injector: `appDestination` names the application for a URL on one of its hosts, and `deliverToApp` makes the
|
|
12
|
+
// request there, so a vendor's delivery to https://app.example.com/... reaches the application as it would reach
|
|
13
|
+
// its production deployment.
|
|
14
|
+
// The record is read from the instance the process's World env names (VOLTER_WORLD_INSTANCE), at most once a second,
|
|
15
|
+
// so a host or URL recorded after the process started applies.
|
|
16
|
+
|
|
17
|
+
// node's own modules are required where used: importing this module does nothing (a pack's egress imports it)
|
|
18
|
+
const APP_ROUTES = new Map(); // cache: instance file -> { checkedAt, mtimeMs, route }
|
|
19
|
+
|
|
20
|
+
/** The application's route in the instance `instanceFile`: { origin, hosts } or null when none is recorded. */
|
|
21
|
+
function appRoute(instanceFile) {
|
|
22
|
+
if (!instanceFile) return null;
|
|
23
|
+
const now = Date.now();
|
|
24
|
+
let held = APP_ROUTES.get(instanceFile);
|
|
25
|
+
if (held && now - held.checkedAt < 1000) return held.route && held.route.origin ? held.route : null;
|
|
26
|
+
if (!held) { held = { checkedAt: 0, mtimeMs: -1, route: null }; APP_ROUTES.set(instanceFile, held); }
|
|
27
|
+
held.checkedAt = now;
|
|
28
|
+
const fs = require('fs');
|
|
29
|
+
const path = require('path');
|
|
30
|
+
const file = path.join(path.dirname(instanceFile), 'app-url.json');
|
|
31
|
+
try {
|
|
32
|
+
const mtimeMs = fs.statSync(file).mtimeMs;
|
|
33
|
+
if (mtimeMs !== held.mtimeMs) {
|
|
34
|
+
held.mtimeMs = mtimeMs;
|
|
35
|
+
const record = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
36
|
+
held.route = Array.isArray(record.hosts) && record.hosts.length
|
|
37
|
+
? { url: typeof record.url === 'string' ? record.url : null, hosts: new Set(record.hosts.map((h) => String(h).toLowerCase())) }
|
|
38
|
+
: null;
|
|
39
|
+
}
|
|
40
|
+
// a record with hosts and no URL names the World's own `app` service, wherever this boot put it
|
|
41
|
+
if (held.route && !held.route.url) {
|
|
42
|
+
const service = JSON.parse(fs.readFileSync(instanceFile, 'utf8')).services?.app;
|
|
43
|
+
held.route.origin = typeof service?.url === 'string' ? service.url.replace(/\/$/, '') : null;
|
|
44
|
+
} else if (held.route) held.route.origin = held.route.url.replace(/\/$/, '');
|
|
45
|
+
} catch (error) {
|
|
46
|
+
// gone: no route; caught mid-write: the last one read stands until the next look
|
|
47
|
+
held.mtimeMs = -1;
|
|
48
|
+
if (error && error.code === 'ENOENT') held.route = null;
|
|
49
|
+
}
|
|
50
|
+
return held.route && held.route.origin ? held.route : null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Whether `host` is one of the app's recorded hostnames: named exactly, or under a recorded wildcard (`*.dub.link`),
|
|
54
|
+
* which, as a DNS wildcard, answers every name below its parent and never the parent itself. */
|
|
55
|
+
function appHostMatch(hosts, host) {
|
|
56
|
+
if (hosts.has(host)) return true;
|
|
57
|
+
for (let dot = host.indexOf('.'); dot > 0; dot = host.indexOf('.', dot + 1)) {
|
|
58
|
+
if (hosts.has(`*${host.slice(dot)}`)) return true;
|
|
59
|
+
}
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The headers a request routed to the application carries beside its own Host: the host and scheme it was made with. */
|
|
64
|
+
function appForwardHeaders(url) {
|
|
65
|
+
return { 'x-forwarded-host': url.host, 'x-forwarded-proto': url.protocol === 'https:' ? 'https' : 'http' };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The application a URL reaches inside the World, when its host is one the application answers as: the route, or null. */
|
|
69
|
+
function appDestination(value, env = process.env) {
|
|
70
|
+
let url;
|
|
71
|
+
try { url = new URL(String(value)); } catch { return null; }
|
|
72
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
|
|
73
|
+
const route = appRoute(env.VOLTER_WORLD_INSTANCE);
|
|
74
|
+
const host = url.hostname.toLowerCase().replace(/\.$/, '');
|
|
75
|
+
// never a name a vendor's host rule gives its twin, as the injector's resolveTwin rules
|
|
76
|
+
return route && appHostMatch(route.hosts, host) && !require('./vendor-hosts.cjs').isVendorHost(host) ? route : null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
let SESSION_CA = undefined; // lazily read once; NODE_EXTRA_CA_CERTS set after process start
|
|
80
|
+
/** The World's session CA (NODE_EXTRA_CA_CERTS), which an https origin inside the World is signed by, or null. */
|
|
81
|
+
function sessionCa() {
|
|
82
|
+
if (SESSION_CA === undefined) {
|
|
83
|
+
const caPath = process.env.NODE_EXTRA_CA_CERTS;
|
|
84
|
+
try { SESSION_CA = caPath ? require('fs').readFileSync(caPath) : null; } catch { SESSION_CA = null; }
|
|
85
|
+
}
|
|
86
|
+
return SESSION_CA;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// What never reaches the application from a World process: the World's key and its routing marks, the caller's own
|
|
90
|
+
// Host and forwarded host and scheme (replaced by the ones the request was made with), and an accepted encoding (the
|
|
91
|
+
// answer is read decoded, as fetch reads it)
|
|
92
|
+
const APP_DROPPED = ['accept-encoding', 'x-twins-key', 'x-volter-twin-original-host', 'proxy-connection', 'host', 'x-forwarded-host', 'x-forwarded-proto'];
|
|
93
|
+
|
|
94
|
+
/** The node:http(s) request options for `url`, a URL on one of the application's hosts, sent where `route` says it
|
|
95
|
+
* listens: the host it was made to as Host, with the forwarded host and scheme, never the World's own headers. */
|
|
96
|
+
function appRequestOptions(route, url, method, headers, extra) {
|
|
97
|
+
const { isIP } = require('net');
|
|
98
|
+
const target = new URL(route.origin);
|
|
99
|
+
const out = {};
|
|
100
|
+
for (const [k, v] of Object.entries(headers || {})) if (v !== undefined && !APP_DROPPED.includes(k.toLowerCase())) out[k] = v;
|
|
101
|
+
Object.assign(out, appForwardHeaders(url), { host: url.host });
|
|
102
|
+
// credentials in the URL are Basic auth, as fetch and http send them
|
|
103
|
+
if ((url.username || url.password) && !Object.keys(out).some((k) => k.toLowerCase() === 'authorization')) {
|
|
104
|
+
out.authorization = `Basic ${Buffer.from(`${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`).toString('base64')}`;
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
protocol: target.protocol, hostname: target.hostname, port: target.port || (target.protocol === 'https:' ? 443 : 80),
|
|
108
|
+
method, path: `${target.pathname.replace(/\/$/, '')}${url.pathname}${url.search}`, headers: out,
|
|
109
|
+
...(extra && extra.signal ? { signal: extra.signal } : {}), ...(extra && extra.timeout !== undefined ? { timeout: extra.timeout } : {}),
|
|
110
|
+
...(target.protocol === 'https:' && sessionCa() ? { ca: sessionCa() } : {}),
|
|
111
|
+
// the TLS name is the host dialled, not the Host the app answers as (an address has no TLS name: an empty one sends none)
|
|
112
|
+
...(target.protocol === 'https:' ? { servername: isIP(target.hostname) ? '' : target.hostname } : {}),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** One request to the application for `value`, a URL on one of its hosts, as `route` (appDestination's answer) names
|
|
117
|
+
* it, with appRequestOptions' headers. No redirect is followed: the caller decides, as a delivery reports what it got.
|
|
118
|
+
* Answers { status, headers (lower-cased), body (decoded text) } within `timeoutMs` overall; a failure rejects. */
|
|
119
|
+
function deliverToApp(route, value, { method = 'POST', headers = {}, body, timeoutMs = 30_000 } = {}) {
|
|
120
|
+
const url = new URL(String(value));
|
|
121
|
+
const options = appRequestOptions(route, url, method, headers);
|
|
122
|
+
const make = (options.protocol === 'https:' ? require('https') : require('http')).request;
|
|
123
|
+
return new Promise((resolve, reject) => {
|
|
124
|
+
let settled = false;
|
|
125
|
+
const fail = (error) => { if (!settled) { settled = true; clearTimeout(deadline); req.destroy(); reject(error); } };
|
|
126
|
+
const req = make(options, (res) => {
|
|
127
|
+
// a reply cut off mid-body fails the delivery, decoded or not (pipe forwards no error to the decoder)
|
|
128
|
+
res.on('error', fail);
|
|
129
|
+
res.on('aborted', () => fail(new Error(`the application's answer to ${url.origin}${url.pathname} was cut off`)));
|
|
130
|
+
const encoding = String(res.headers['content-encoding'] || '').toLowerCase();
|
|
131
|
+
const zlib = require('zlib');
|
|
132
|
+
const decoder = encoding === 'gzip' || encoding === 'x-gzip' ? zlib.createGunzip() : encoding === 'deflate' ? zlib.createInflate() : encoding === 'br' ? zlib.createBrotliDecompress() : null;
|
|
133
|
+
const stream = decoder ? res.pipe(decoder) : res;
|
|
134
|
+
const chunks = [];
|
|
135
|
+
stream.on('data', (c) => chunks.push(c));
|
|
136
|
+
stream.on('error', fail);
|
|
137
|
+
stream.on('end', () => {
|
|
138
|
+
if (settled) return;
|
|
139
|
+
settled = true;
|
|
140
|
+
clearTimeout(deadline);
|
|
141
|
+
const answer = {};
|
|
142
|
+
for (const [k, v] of Object.entries(res.headers)) if (v !== undefined && !(decoder && (k === 'content-encoding' || k === 'content-length'))) answer[k.toLowerCase()] = Array.isArray(v) ? v.join(', ') : String(v);
|
|
143
|
+
resolve({ status: res.statusCode, headers: answer, body: Buffer.concat(chunks).toString('utf8') });
|
|
144
|
+
});
|
|
145
|
+
});
|
|
146
|
+
// one deadline for the whole exchange, not an idle timeout: an answer that trickles is still cut off
|
|
147
|
+
const deadline = setTimeout(() => fail(new Error(`the application did not answer ${url.origin}${url.pathname} within ${timeoutMs} ms`)), timeoutMs);
|
|
148
|
+
req.on('error', fail);
|
|
149
|
+
if (body != null && method !== 'GET' && method !== 'HEAD') req.write(body);
|
|
150
|
+
req.end();
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
module.exports = { appRoute, appHostMatch, appForwardHeaders, appDestination, appRequestOptions, deliverToApp, sessionCa };
|
package/app-route.d.cts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export interface AppRoute { readonly origin: string; readonly url: string | null; readonly hosts: ReadonlySet<string> }
|
|
2
|
+
export interface AppAnswer { readonly status: number; readonly headers: Record<string, string>; readonly body: string }
|
|
3
|
+
export function appRoute(instanceFile: string | undefined): AppRoute | null;
|
|
4
|
+
export function appHostMatch(hosts: ReadonlySet<string>, host: string): boolean;
|
|
5
|
+
export function appForwardHeaders(url: URL): Record<string, string>;
|
|
6
|
+
export function appDestination(value: string | URL, env?: Readonly<Record<string, string | undefined>>): AppRoute | null;
|
|
7
|
+
export function deliverToApp(route: AppRoute, value: string | URL, init?: { method?: string; headers?: Record<string, string>; body?: string | Uint8Array | null; timeoutMs?: number }): Promise<AppAnswer>;
|
package/attach.cjs
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// The rung-2 dormant attach (docs/guides/route-a-cli-through-the-world.md): `import '@volter/world-core/attach'`
|
|
2
|
+
// as line 1 of an entrypoint. A NO-OP unless VOLTER_WORLD is set — production
|
|
3
|
+
// behavior is byte-identical. When set:
|
|
4
|
+
// • a URL ref: fetch the world manifest (blocking child — this runs at
|
|
5
|
+
// module load, before the app constructs SDK clients), apply the attach
|
|
6
|
+
// env (vendor twin URLs, suggested fake credentials, CA trust), then load
|
|
7
|
+
// the injector.
|
|
8
|
+
// • anything else (a local name whose env the launcher already exported, or
|
|
9
|
+
// plain twin-URL env vars): just load the injector.
|
|
10
|
+
// The injector itself remains ./inject.cjs — this file only decides whether
|
|
11
|
+
// and how to arm it.
|
|
12
|
+
'use strict';
|
|
13
|
+
|
|
14
|
+
const ref = process.env.VOLTER_WORLD;
|
|
15
|
+
if (ref) {
|
|
16
|
+
if (/^https?:\/\//i.test(ref)) {
|
|
17
|
+
const { spawnSync } = require('node:child_process');
|
|
18
|
+
const { mkdtempSync, readFileSync, writeFileSync } = require('node:fs');
|
|
19
|
+
const { tmpdir } = require('node:os');
|
|
20
|
+
const { join } = require('node:path');
|
|
21
|
+
const url = ref.replace(/\/$/, '').endsWith('/.well-known/volter-world')
|
|
22
|
+
? ref.replace(/\/$/, '')
|
|
23
|
+
: `${ref.replace(/\/$/, '')}/.well-known/volter-world`;
|
|
24
|
+
const token = process.env.VOLTER_WORLD_TOKEN;
|
|
25
|
+
// a blocking fetch at module load: spawn a child that prints the manifest
|
|
26
|
+
const probe = spawnSync(
|
|
27
|
+
process.execPath,
|
|
28
|
+
['-e', 'fetch(process.argv[1],process.argv[2]?{headers:{authorization:"Bearer "+process.argv[2]}}:undefined).then(r=>{if(!r.ok)throw new Error(r.status);return r.text()}).then(t=>process.stdout.write(t)).catch(e=>{console.error(String(e));process.exit(1)})', url, ...(token ? [token] : [])],
|
|
29
|
+
// the child must NOT inherit NODE_OPTIONS/VOLTER_WORLD — it would
|
|
30
|
+
// re-run this very file at its own startup (a spawn recursion bomb)
|
|
31
|
+
{ encoding: 'utf8', env: { ...process.env, NODE_OPTIONS: '', VOLTER_WORLD: '' } },
|
|
32
|
+
);
|
|
33
|
+
if (probe.status !== 0) {
|
|
34
|
+
throw new Error(`[twin-attach] could not fetch the world manifest from ${url}: ${(probe.stderr || '').trim()}`);
|
|
35
|
+
}
|
|
36
|
+
const manifest = JSON.parse(probe.stdout);
|
|
37
|
+
for (const [vendor, origin] of Object.entries(manifest.vendors ?? {})) {
|
|
38
|
+
const key = `${vendor.toUpperCase()}_TWIN_URL`;
|
|
39
|
+
if (process.env[key] === undefined) process.env[key] = origin;
|
|
40
|
+
}
|
|
41
|
+
for (const [key, value] of Object.entries(manifest.env ?? {})) {
|
|
42
|
+
if (process.env[key] === undefined) process.env[key] = value;
|
|
43
|
+
}
|
|
44
|
+
// a World's byte-stream doors (a hosted World's smtp, planetscale's mysql): loopback listeners in
|
|
45
|
+
// this process, bridged over WebSocket (./stream-bridge.cjs). The env names the listener now, so the
|
|
46
|
+
// ports are chosen by a blocking child; the listeners bind on the next turn, before any client
|
|
47
|
+
// can connect, and never hold the process open.
|
|
48
|
+
const streams = Object.values(manifest.streams ?? {});
|
|
49
|
+
if (streams.length) {
|
|
50
|
+
const picked = spawnSync(
|
|
51
|
+
process.execPath,
|
|
52
|
+
['-e', 'const n=require("node:net");const k=+process.argv[1];const s=[];const d=()=>{if(s.length<k){const v=n.createServer().listen(0,"127.0.0.1",()=>{s.push(v);d()})}else{process.stdout.write(s.map(v=>v.address().port).join(","));s.forEach(v=>v.close())}};d()', String(streams.length)],
|
|
53
|
+
{ encoding: 'utf8', env: { ...process.env, NODE_OPTIONS: '', VOLTER_WORLD: '' } },
|
|
54
|
+
);
|
|
55
|
+
if (picked.status !== 0) throw new Error(`[twin-attach] could not choose loopback ports for the world's streams: ${(picked.stderr || '').trim()}`);
|
|
56
|
+
const ports = picked.stdout.split(',').map(Number);
|
|
57
|
+
const { bridgeStream, streamEnv } = require('./stream-bridge.cjs');
|
|
58
|
+
const streamToken = token ?? manifest.env?.VOLTER_TWINS_KEY ?? '';
|
|
59
|
+
streams.forEach((stream, i) => {
|
|
60
|
+
for (const [key, value] of Object.entries(streamEnv(stream.env, ports[i]))) {
|
|
61
|
+
if (process.env[key] === undefined) process.env[key] = value;
|
|
62
|
+
}
|
|
63
|
+
bridgeStream(stream.url, streamToken, ports[i]).then((server) => server.unref(), (error) => {
|
|
64
|
+
process.stderr.write(`[twin-attach] ${stream.url}: could not listen on 127.0.0.1:${ports[i]}: ${error.message}\n`);
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
if (manifest.ca) {
|
|
69
|
+
const existingCa = process.env.NODE_EXTRA_CA_CERTS
|
|
70
|
+
? readFileSync(process.env.NODE_EXTRA_CA_CERTS, 'utf8') : '';
|
|
71
|
+
const caFile = join(mkdtempSync(join(tmpdir(), 'twin-attach-')), 'ca.pem');
|
|
72
|
+
writeFileSync(caFile, `${existingCa}\n${manifest.ca}\n`);
|
|
73
|
+
process.env.NODE_EXTRA_CA_CERTS = caFile;
|
|
74
|
+
// NODE_EXTRA_CA_CERTS is read at process START — too late for THIS
|
|
75
|
+
// process's default TLS store. The injector's https forwards accept the
|
|
76
|
+
// session CA explicitly via this env; child processes inherit it fully.
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
require('./inject.cjs');
|
|
80
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// THE APPLICATION'S OWN HOSTNAMES IN THE WORLD — the one home of the app route (dependency-free, side-effect free).
|
|
3
|
+
//
|
|
4
|
+
// `volter-world app-url <world> --host <name>` records the hostnames an application answers as in production beside
|
|
5
|
+
// its URL (`app-url.json` in the instance); inside the World they reach the application, as DNS routes them to its
|
|
6
|
+
// host in production (architecture.md, "The application's own production hostnames"). Two kinds of process route
|
|
7
|
+
// them, and both read the route here:
|
|
8
|
+
// · a process the injector is installed in (the application, a script, the redirect proxy): inject.cjs's
|
|
9
|
+
// resolveTwin answers a recorded host with the application's origin, after twins and the hosts twins claim;
|
|
10
|
+
// · a twin's own outbound request (a QStash delivery, a webhook) from the colocated twin host, which runs without the
|
|
11
|
+
// injector: `appDestination` names the application for a URL on one of its hosts, and `deliverToApp` makes the
|
|
12
|
+
// request there, so a vendor's delivery to https://app.example.com/... reaches the application as it would reach
|
|
13
|
+
// its production deployment.
|
|
14
|
+
// The record is read from the instance the process's World env names (VOLTER_WORLD_INSTANCE), at most once a second,
|
|
15
|
+
// so a host or URL recorded after the process started applies.
|
|
16
|
+
|
|
17
|
+
// node's own modules are required where used: importing this module does nothing (a pack's egress imports it)
|
|
18
|
+
const APP_ROUTES = new Map(); // cache: instance file -> { checkedAt, mtimeMs, route }
|
|
19
|
+
|
|
20
|
+
/** The application's route in the instance `instanceFile`: { origin, hosts } or null when none is recorded. */
|
|
21
|
+
function appRoute(instanceFile) {
|
|
22
|
+
if (!instanceFile) return null;
|
|
23
|
+
const now = Date.now();
|
|
24
|
+
let held = APP_ROUTES.get(instanceFile);
|
|
25
|
+
if (held && now - held.checkedAt < 1000) return held.route && held.route.origin ? held.route : null;
|
|
26
|
+
if (!held) { held = { checkedAt: 0, mtimeMs: -1, route: null }; APP_ROUTES.set(instanceFile, held); }
|
|
27
|
+
held.checkedAt = now;
|
|
28
|
+
const fs = require('fs');
|
|
29
|
+
const path = require('path');
|
|
30
|
+
const file = path.join(path.dirname(instanceFile), 'app-url.json');
|
|
31
|
+
try {
|
|
32
|
+
const mtimeMs = fs.statSync(file).mtimeMs;
|
|
33
|
+
if (mtimeMs !== held.mtimeMs) {
|
|
34
|
+
held.mtimeMs = mtimeMs;
|
|
35
|
+
const record = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
36
|
+
held.route = Array.isArray(record.hosts) && record.hosts.length
|
|
37
|
+
? { url: typeof record.url === 'string' ? record.url : null, hosts: new Set(record.hosts.map((h) => String(h).toLowerCase())) }
|
|
38
|
+
: null;
|
|
39
|
+
}
|
|
40
|
+
// a record with hosts and no URL names the World's own `app` service, wherever this boot put it
|
|
41
|
+
if (held.route && !held.route.url) {
|
|
42
|
+
const service = JSON.parse(fs.readFileSync(instanceFile, 'utf8')).services?.app;
|
|
43
|
+
held.route.origin = typeof service?.url === 'string' ? service.url.replace(/\/$/, '') : null;
|
|
44
|
+
} else if (held.route) held.route.origin = held.route.url.replace(/\/$/, '');
|
|
45
|
+
} catch (error) {
|
|
46
|
+
// gone: no route; caught mid-write: the last one read stands until the next look
|
|
47
|
+
held.mtimeMs = -1;
|
|
48
|
+
if (error && error.code === 'ENOENT') held.route = null;
|
|
49
|
+
}
|
|
50
|
+
return held.route && held.route.origin ? held.route : null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Whether `host` is one of the app's recorded hostnames: named exactly, or under a recorded wildcard (`*.dub.link`),
|
|
54
|
+
* which, as a DNS wildcard, answers every name below its parent and never the parent itself. */
|
|
55
|
+
function appHostMatch(hosts, host) {
|
|
56
|
+
if (hosts.has(host)) return true;
|
|
57
|
+
for (let dot = host.indexOf('.'); dot > 0; dot = host.indexOf('.', dot + 1)) {
|
|
58
|
+
if (hosts.has(`*${host.slice(dot)}`)) return true;
|
|
59
|
+
}
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The headers a request routed to the application carries beside its own Host: the host and scheme it was made with. */
|
|
64
|
+
function appForwardHeaders(url) {
|
|
65
|
+
return { 'x-forwarded-host': url.host, 'x-forwarded-proto': url.protocol === 'https:' ? 'https' : 'http' };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The application a URL reaches inside the World, when its host is one the application answers as: the route, or null. */
|
|
69
|
+
function appDestination(value, env = process.env) {
|
|
70
|
+
let url;
|
|
71
|
+
try { url = new URL(String(value)); } catch { return null; }
|
|
72
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
|
|
73
|
+
const route = appRoute(env.VOLTER_WORLD_INSTANCE);
|
|
74
|
+
const host = url.hostname.toLowerCase().replace(/\.$/, '');
|
|
75
|
+
// never a name a vendor's host rule gives its twin, as the injector's resolveTwin rules
|
|
76
|
+
return route && appHostMatch(route.hosts, host) && !require('./vendor-hosts.cjs').isVendorHost(host) ? route : null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
let SESSION_CA = undefined; // lazily read once; NODE_EXTRA_CA_CERTS set after process start
|
|
80
|
+
/** The World's session CA (NODE_EXTRA_CA_CERTS), which an https origin inside the World is signed by, or null. */
|
|
81
|
+
function sessionCa() {
|
|
82
|
+
if (SESSION_CA === undefined) {
|
|
83
|
+
const caPath = process.env.NODE_EXTRA_CA_CERTS;
|
|
84
|
+
try { SESSION_CA = caPath ? require('fs').readFileSync(caPath) : null; } catch { SESSION_CA = null; }
|
|
85
|
+
}
|
|
86
|
+
return SESSION_CA;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// What never reaches the application from a World process: the World's key and its routing marks, the caller's own
|
|
90
|
+
// Host and forwarded host and scheme (replaced by the ones the request was made with), and an accepted encoding (the
|
|
91
|
+
// answer is read decoded, as fetch reads it)
|
|
92
|
+
const APP_DROPPED = ['accept-encoding', 'x-twins-key', 'x-volter-twin-original-host', 'proxy-connection', 'host', 'x-forwarded-host', 'x-forwarded-proto'];
|
|
93
|
+
|
|
94
|
+
/** The node:http(s) request options for `url`, a URL on one of the application's hosts, sent where `route` says it
|
|
95
|
+
* listens: the host it was made to as Host, with the forwarded host and scheme, never the World's own headers. */
|
|
96
|
+
function appRequestOptions(route, url, method, headers, extra) {
|
|
97
|
+
const { isIP } = require('net');
|
|
98
|
+
const target = new URL(route.origin);
|
|
99
|
+
const out = {};
|
|
100
|
+
for (const [k, v] of Object.entries(headers || {})) if (v !== undefined && !APP_DROPPED.includes(k.toLowerCase())) out[k] = v;
|
|
101
|
+
Object.assign(out, appForwardHeaders(url), { host: url.host });
|
|
102
|
+
// credentials in the URL are Basic auth, as fetch and http send them
|
|
103
|
+
if ((url.username || url.password) && !Object.keys(out).some((k) => k.toLowerCase() === 'authorization')) {
|
|
104
|
+
out.authorization = `Basic ${Buffer.from(`${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`).toString('base64')}`;
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
protocol: target.protocol, hostname: target.hostname, port: target.port || (target.protocol === 'https:' ? 443 : 80),
|
|
108
|
+
method, path: `${target.pathname.replace(/\/$/, '')}${url.pathname}${url.search}`, headers: out,
|
|
109
|
+
...(extra && extra.signal ? { signal: extra.signal } : {}), ...(extra && extra.timeout !== undefined ? { timeout: extra.timeout } : {}),
|
|
110
|
+
...(target.protocol === 'https:' && sessionCa() ? { ca: sessionCa() } : {}),
|
|
111
|
+
// the TLS name is the host dialled, not the Host the app answers as (an address has no TLS name: an empty one sends none)
|
|
112
|
+
...(target.protocol === 'https:' ? { servername: isIP(target.hostname) ? '' : target.hostname } : {}),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** One request to the application for `value`, a URL on one of its hosts, as `route` (appDestination's answer) names
|
|
117
|
+
* it, with appRequestOptions' headers. No redirect is followed: the caller decides, as a delivery reports what it got.
|
|
118
|
+
* Answers { status, headers (lower-cased), body (decoded text) } within `timeoutMs` overall; a failure rejects. */
|
|
119
|
+
function deliverToApp(route, value, { method = 'POST', headers = {}, body, timeoutMs = 30_000 } = {}) {
|
|
120
|
+
const url = new URL(String(value));
|
|
121
|
+
const options = appRequestOptions(route, url, method, headers);
|
|
122
|
+
const make = (options.protocol === 'https:' ? require('https') : require('http')).request;
|
|
123
|
+
return new Promise((resolve, reject) => {
|
|
124
|
+
let settled = false;
|
|
125
|
+
const fail = (error) => { if (!settled) { settled = true; clearTimeout(deadline); req.destroy(); reject(error); } };
|
|
126
|
+
const req = make(options, (res) => {
|
|
127
|
+
// a reply cut off mid-body fails the delivery, decoded or not (pipe forwards no error to the decoder)
|
|
128
|
+
res.on('error', fail);
|
|
129
|
+
res.on('aborted', () => fail(new Error(`the application's answer to ${url.origin}${url.pathname} was cut off`)));
|
|
130
|
+
const encoding = String(res.headers['content-encoding'] || '').toLowerCase();
|
|
131
|
+
const zlib = require('zlib');
|
|
132
|
+
const decoder = encoding === 'gzip' || encoding === 'x-gzip' ? zlib.createGunzip() : encoding === 'deflate' ? zlib.createInflate() : encoding === 'br' ? zlib.createBrotliDecompress() : null;
|
|
133
|
+
const stream = decoder ? res.pipe(decoder) : res;
|
|
134
|
+
const chunks = [];
|
|
135
|
+
stream.on('data', (c) => chunks.push(c));
|
|
136
|
+
stream.on('error', fail);
|
|
137
|
+
stream.on('end', () => {
|
|
138
|
+
if (settled) return;
|
|
139
|
+
settled = true;
|
|
140
|
+
clearTimeout(deadline);
|
|
141
|
+
const answer = {};
|
|
142
|
+
for (const [k, v] of Object.entries(res.headers)) if (v !== undefined && !(decoder && (k === 'content-encoding' || k === 'content-length'))) answer[k.toLowerCase()] = Array.isArray(v) ? v.join(', ') : String(v);
|
|
143
|
+
resolve({ status: res.statusCode, headers: answer, body: Buffer.concat(chunks).toString('utf8') });
|
|
144
|
+
});
|
|
145
|
+
});
|
|
146
|
+
// one deadline for the whole exchange, not an idle timeout: an answer that trickles is still cut off
|
|
147
|
+
const deadline = setTimeout(() => fail(new Error(`the application did not answer ${url.origin}${url.pathname} within ${timeoutMs} ms`)), timeoutMs);
|
|
148
|
+
req.on('error', fail);
|
|
149
|
+
if (body != null && method !== 'GET' && method !== 'HEAD') req.write(body);
|
|
150
|
+
req.end();
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
module.exports = { appRoute, appHostMatch, appForwardHeaders, appDestination, appRequestOptions, deliverToApp, sessionCa };
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export interface AppRoute { readonly origin: string; readonly url: string | null; readonly hosts: ReadonlySet<string> }
|
|
2
|
+
export interface AppAnswer { readonly status: number; readonly headers: Record<string, string>; readonly body: string }
|
|
3
|
+
export function appRoute(instanceFile: string | undefined): AppRoute | null;
|
|
4
|
+
export function appHostMatch(hosts: ReadonlySet<string>, host: string): boolean;
|
|
5
|
+
export function appForwardHeaders(url: URL): Record<string, string>;
|
|
6
|
+
export function appDestination(value: string | URL, env?: Readonly<Record<string, string | undefined>>): AppRoute | null;
|
|
7
|
+
export function deliverToApp(route: AppRoute, value: string | URL, init?: { method?: string; headers?: Record<string, string>; body?: string | Uint8Array | null; timeoutMs?: number }): Promise<AppAnswer>;
|