@hypequery/deployment 0.0.0-canary-20260719130627

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are advised to review the applicable
150
+ documentation for the specific language governing permissions and
151
+ limitations under each license.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2024 hypequery
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,68 @@
1
+ # @hypequery/deployment
2
+
3
+ Provider-neutral verification and receiving-side intake for Hypequery deployment
4
+ bundles.
5
+
6
+ The package accepts the authenticated multipart transport emitted by
7
+ `hypequery deploy`, reconstructs only manifest-declared files in temporary
8
+ storage, and revalidates the release, bundle manifest, file hashes, deployment
9
+ identity, and runtime references before handing the submission to a store. It
10
+ does not activate or execute a release.
11
+
12
+ ## Intake adapters
13
+
14
+ `createDeploymentIntake` is independent of an HTTP framework. Adapt an incoming
15
+ request into a case-insensitive header record and an `AsyncIterable<Uint8Array>`
16
+ body, then map the returned status, headers, and JSON body onto the framework's
17
+ response.
18
+
19
+ Three provider-owned adapters are required:
20
+
21
+ - `DeploymentAuthenticator` validates the bearer token before request bytes are
22
+ consumed;
23
+ - `DeploymentAuthorizer` authorizes the canonical project and environment once
24
+ the release envelope has been validated;
25
+ - `DeploymentSubmissionStore` atomically persists or recognizes the fully
26
+ verified release identity.
27
+
28
+ The store receives a verified bundle whose directory is temporary. It must copy
29
+ or persist every required byte before `accept` resolves. Returning
30
+ `already-exists` is valid only for an authorized replay of the same deterministic
31
+ release identity.
32
+
33
+ ```ts
34
+ import { createDeploymentIntake } from '@hypequery/deployment';
35
+
36
+ const intake = createDeploymentIntake({
37
+ authenticator: {
38
+ async authenticate({ token }) {
39
+ return authenticateToken(token);
40
+ },
41
+ },
42
+ authorizer: {
43
+ async authorize({ principal, target }) {
44
+ return canDeploy(principal, target.project, target.environment);
45
+ },
46
+ },
47
+ store: {
48
+ async accept(submission) {
49
+ return persistVerifiedSubmission(submission);
50
+ },
51
+ },
52
+ });
53
+ ```
54
+
55
+ New submissions return HTTP status `202` and `status: "accepted"`; verified
56
+ idempotent replays return HTTP status `200` and `status: "already-exists"`.
57
+ Malformed, unauthorized, oversized, or inconsistent submissions fail closed
58
+ with a bounded JSON error response. Temporary upload data is removed on success
59
+ and failure.
60
+
61
+ ## Bundle verification
62
+
63
+ `verifyDeploymentBundle(directory)` verifies a closed bundle directly from the
64
+ filesystem. It rejects symbolic links and undeclared entries, enforces byte
65
+ limits, recomputes every hash and identity, and returns an immutable verified
66
+ snapshot.
67
+
68
+ The package is ESM-only and requires Node.js 20 or newer.
@@ -0,0 +1,11 @@
1
+ import { type ProtocolDeploymentBundleManifest, type ProtocolDeploymentContract } from '@hypequery/protocol';
2
+ export declare const DEPLOYMENT_BUNDLE_MANIFEST = "bundle.json";
3
+ export declare const DEPLOYMENT_BUNDLE_CONTRACT = "deployment.json";
4
+ export interface VerifiedDeploymentBundle {
5
+ readonly directory: string;
6
+ readonly manifest: ProtocolDeploymentBundleManifest;
7
+ readonly identity: string;
8
+ readonly contract: ProtocolDeploymentContract;
9
+ }
10
+ export declare function verifyDeploymentBundle(bundleDirectory: string): Promise<VerifiedDeploymentBundle>;
11
+ //# sourceMappingURL=bundle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bundle.d.ts","sourceRoot":"","sources":["../src/bundle.ts"],"names":[],"mappings":"AAQA,OAAO,EAKL,KAAK,gCAAgC,EACrC,KAAK,0BAA0B,EAChC,MAAM,qBAAqB,CAAC;AAE7B,eAAO,MAAM,0BAA0B,gBAAgB,CAAC;AACxD,eAAO,MAAM,0BAA0B,oBAAoB,CAAC;AAE5D,MAAM,WAAW,wBAAwB;IACvC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ,EAAE,gCAAgC,CAAC;IACpD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,QAAQ,EAAE,0BAA0B,CAAC;CAC/C;AAoKD,wBAAsB,sBAAsB,CAC1C,eAAe,EAAE,MAAM,GACtB,OAAO,CAAC,wBAAwB,CAAC,CA2DnC"}
package/dist/bundle.js ADDED
@@ -0,0 +1,193 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { constants, lstat, open, readdir, } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { DEFAULT_PROTOCOL_DEPLOYMENT_BUNDLE_LIMITS, prepareProtocolDeploymentBundleManifest, prepareProtocolDeploymentContract, } from '@hypequery/protocol';
5
+ export const DEPLOYMENT_BUNDLE_MANIFEST = 'bundle.json';
6
+ export const DEPLOYMENT_BUNDLE_CONTRACT = 'deployment.json';
7
+ const utf8Decoder = new TextDecoder('utf-8', { fatal: true });
8
+ const utf8Encoder = new TextEncoder();
9
+ function errorCode(error) {
10
+ return typeof error === 'object' && error !== null && 'code' in error
11
+ ? String(error.code)
12
+ : undefined;
13
+ }
14
+ function sha256(bytes) {
15
+ return createHash('sha256').update(bytes).digest('hex');
16
+ }
17
+ async function readBoundedRegularFile(root, relativePath, maximum) {
18
+ const absolutePath = path.join(root, ...relativePath.split('/'));
19
+ let handle;
20
+ try {
21
+ const initialStat = await lstat(absolutePath);
22
+ if (initialStat.isSymbolicLink()) {
23
+ throw new Error(`Bundle entry must not be a symbolic link: ${relativePath}`);
24
+ }
25
+ if (!initialStat.isFile()) {
26
+ throw new Error(`Bundle entry is not a regular file: ${relativePath}`);
27
+ }
28
+ if (initialStat.size < 1 || initialStat.size > maximum) {
29
+ throw new Error(`Bundle entry exceeds its byte limit: ${relativePath}`);
30
+ }
31
+ handle = await open(absolutePath, constants.O_RDONLY | constants.O_NOFOLLOW);
32
+ const stat = await handle.stat();
33
+ if (!stat.isFile())
34
+ throw new Error(`Bundle entry is not a regular file: ${relativePath}`);
35
+ if (stat.size < 1 || stat.size > maximum) {
36
+ throw new Error(`Bundle entry exceeds its byte limit: ${relativePath}`);
37
+ }
38
+ return await handle.readFile();
39
+ }
40
+ catch (error) {
41
+ if (errorCode(error) === 'ELOOP') {
42
+ throw new Error(`Bundle entry must not be a symbolic link: ${relativePath}`);
43
+ }
44
+ throw error;
45
+ }
46
+ finally {
47
+ await handle?.close();
48
+ }
49
+ }
50
+ function expectedDirectories(files) {
51
+ const result = new Set();
52
+ for (const file of files) {
53
+ const segments = file.split('/');
54
+ for (let index = 1; index < segments.length; index += 1) {
55
+ result.add(segments.slice(0, index).join('/'));
56
+ }
57
+ }
58
+ return result;
59
+ }
60
+ async function verifyExactEntries(root, manifest) {
61
+ const expectedFiles = new Set([
62
+ DEPLOYMENT_BUNDLE_MANIFEST,
63
+ manifest.deployment.path,
64
+ ...manifest.artifacts.map(artifact => artifact.path),
65
+ ]);
66
+ const expectedDirectoryPaths = expectedDirectories([...expectedFiles]);
67
+ const seenFiles = new Set();
68
+ const seenDirectories = new Set();
69
+ async function visit(relativeDirectory) {
70
+ const absoluteDirectory = relativeDirectory
71
+ ? path.join(root, ...relativeDirectory.split('/'))
72
+ : root;
73
+ const names = await readdir(absoluteDirectory);
74
+ names.sort();
75
+ for (const name of names) {
76
+ const relativePath = relativeDirectory ? `${relativeDirectory}/${name}` : name;
77
+ const stat = await lstat(path.join(absoluteDirectory, name));
78
+ if (stat.isSymbolicLink()) {
79
+ throw new Error(`Bundle entries must not be symbolic links: ${relativePath}`);
80
+ }
81
+ if (stat.isDirectory()) {
82
+ if (!expectedDirectoryPaths.has(relativePath)) {
83
+ throw new Error(`Deployment bundle contains an undeclared directory: ${relativePath}`);
84
+ }
85
+ seenDirectories.add(relativePath);
86
+ await visit(relativePath);
87
+ }
88
+ else if (stat.isFile()) {
89
+ if (!expectedFiles.has(relativePath)) {
90
+ throw new Error(`Deployment bundle contains an undeclared file: ${relativePath}`);
91
+ }
92
+ seenFiles.add(relativePath);
93
+ }
94
+ else {
95
+ throw new Error(`Bundle entry is not a regular file or directory: ${relativePath}`);
96
+ }
97
+ }
98
+ }
99
+ await visit('');
100
+ const missingFiles = [...expectedFiles].filter(file => !seenFiles.has(file)).sort();
101
+ if (missingFiles.length > 0) {
102
+ throw new Error(`Deployment bundle is missing files: ${missingFiles.join(', ')}`);
103
+ }
104
+ const missingDirectories = [...expectedDirectoryPaths]
105
+ .filter(directory => !seenDirectories.has(directory)).sort();
106
+ if (missingDirectories.length > 0) {
107
+ throw new Error(`Deployment bundle is missing directories: ${missingDirectories.join(', ')}`);
108
+ }
109
+ }
110
+ function verifyFile(bytes, file) {
111
+ if (bytes.byteLength !== file.byteLength) {
112
+ throw new Error(`Bundle entry byte length does not match the manifest: ${file.path}`);
113
+ }
114
+ if (sha256(bytes) !== file.sha256) {
115
+ throw new Error(`Bundle entry SHA-256 does not match the manifest: ${file.path}`);
116
+ }
117
+ }
118
+ function requireClosedContractArtifactSet(contract) {
119
+ const referenced = new Map();
120
+ for (const query of contract.queries) {
121
+ if (query.implementation.kind === 'runtime-reference') {
122
+ referenced.set(query.implementation.artifactSha256, query.implementation.runtime);
123
+ }
124
+ }
125
+ if (referenced.size !== contract.artifacts.length) {
126
+ throw new Error('Deployment contract contains missing or unreferenced runtime artifacts.');
127
+ }
128
+ for (const artifact of contract.artifacts) {
129
+ if (referenced.get(artifact.artifactSha256) !== artifact.runtime) {
130
+ throw new Error(`Deployment runtime artifact ${artifact.artifactSha256} is not referenced by a named query.`);
131
+ }
132
+ }
133
+ }
134
+ function verifyRuntimeReferences(contract, artifacts) {
135
+ requireClosedContractArtifactSet(contract);
136
+ const declared = new Map(contract.artifacts.map(artifact => [artifact.artifactSha256, artifact.runtime]));
137
+ if (declared.size !== artifacts.length) {
138
+ throw new Error('Bundle runtime artifacts do not match the deployment contract.');
139
+ }
140
+ for (const artifact of artifacts) {
141
+ if (declared.get(artifact.sha256) !== artifact.runtime) {
142
+ throw new Error(`Bundle artifact ${artifact.sha256} does not match a deployment runtime reference.`);
143
+ }
144
+ }
145
+ }
146
+ export async function verifyDeploymentBundle(bundleDirectory) {
147
+ const root = path.resolve(bundleDirectory);
148
+ const rootStat = await lstat(root);
149
+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {
150
+ throw new Error(`Deployment bundle path must be a regular directory: ${bundleDirectory}`);
151
+ }
152
+ const manifestBytes = await readBoundedRegularFile(root, DEPLOYMENT_BUNDLE_MANIFEST, 1024 * 1024);
153
+ let input;
154
+ try {
155
+ input = JSON.parse(utf8Decoder.decode(manifestBytes));
156
+ }
157
+ catch (error) {
158
+ throw new Error(`Invalid deployment bundle manifest: ${path.join(root, DEPLOYMENT_BUNDLE_MANIFEST)}\n\n`
159
+ + (error instanceof Error ? error.message : String(error)));
160
+ }
161
+ const preparedManifest = prepareProtocolDeploymentBundleManifest(input);
162
+ const expectedManifestBytes = utf8Encoder.encode(`${preparedManifest.canonical}\n`);
163
+ if (!Buffer.from(manifestBytes).equals(Buffer.from(expectedManifestBytes))) {
164
+ throw new Error('Deployment bundle manifest must contain canonical JSON followed by one newline.');
165
+ }
166
+ await verifyExactEntries(root, preparedManifest.manifest);
167
+ const deployment = preparedManifest.manifest.deployment;
168
+ const deploymentBytes = await readBoundedRegularFile(root, deployment.path, DEFAULT_PROTOCOL_DEPLOYMENT_BUNDLE_LIMITS.maxDeploymentBytes);
169
+ verifyFile(deploymentBytes, deployment);
170
+ let contractInput;
171
+ try {
172
+ contractInput = JSON.parse(utf8Decoder.decode(deploymentBytes));
173
+ }
174
+ catch (error) {
175
+ throw new Error(`Invalid deployment JSON in bundle: ${deployment.path}\n\n`
176
+ + (error instanceof Error ? error.message : String(error)));
177
+ }
178
+ const preparedContract = prepareProtocolDeploymentContract(contractInput);
179
+ if (preparedContract.identity !== deployment.identity) {
180
+ throw new Error('Deployment identity does not match the bundle manifest.');
181
+ }
182
+ for (const artifact of preparedManifest.manifest.artifacts) {
183
+ const bytes = await readBoundedRegularFile(root, artifact.path, DEFAULT_PROTOCOL_DEPLOYMENT_BUNDLE_LIMITS.maxArtifactBytes);
184
+ verifyFile(bytes, artifact);
185
+ }
186
+ verifyRuntimeReferences(preparedContract.contract, preparedManifest.manifest.artifacts);
187
+ return Object.freeze({
188
+ directory: root,
189
+ manifest: preparedManifest.manifest,
190
+ identity: preparedManifest.identity,
191
+ contract: preparedContract.contract,
192
+ });
193
+ }
@@ -0,0 +1,13 @@
1
+ export type DeploymentIntakeErrorCode = 'HQ_INTAKE_BAD_REQUEST' | 'HQ_INTAKE_UNAUTHENTICATED' | 'HQ_INTAKE_FORBIDDEN' | 'HQ_INTAKE_TOO_LARGE' | 'HQ_INTAKE_CONFLICT' | 'HQ_INTAKE_INTERNAL';
2
+ export declare class DeploymentIntakeError extends Error {
3
+ readonly code: DeploymentIntakeErrorCode;
4
+ readonly status: number;
5
+ readonly expose: boolean;
6
+ constructor(code: DeploymentIntakeErrorCode, message: string, options?: {
7
+ readonly expose?: boolean;
8
+ readonly cause?: unknown;
9
+ });
10
+ }
11
+ export declare function badRequest(message: string, cause?: unknown): DeploymentIntakeError;
12
+ export declare function tooLarge(message: string): DeploymentIntakeError;
13
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,yBAAyB,GACjC,uBAAuB,GACvB,2BAA2B,GAC3B,qBAAqB,GACrB,qBAAqB,GACrB,oBAAoB,GACpB,oBAAoB,CAAC;AAWzB,qBAAa,qBAAsB,SAAQ,KAAK;IAC9C,QAAQ,CAAC,IAAI,EAAE,yBAAyB,CAAC;IACzC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;gBAGvB,IAAI,EAAE,yBAAyB,EAC/B,OAAO,EAAE,MAAM,EACf,OAAO,GAAE;QAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;QAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAA;KAAO;CAQxE;AAED,wBAAgB,UAAU,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,GAAG,qBAAqB,CAElF;AAED,wBAAgB,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,qBAAqB,CAE/D"}
package/dist/errors.js ADDED
@@ -0,0 +1,26 @@
1
+ const ERROR_STATUS = Object.freeze({
2
+ HQ_INTAKE_BAD_REQUEST: 400,
3
+ HQ_INTAKE_UNAUTHENTICATED: 401,
4
+ HQ_INTAKE_FORBIDDEN: 403,
5
+ HQ_INTAKE_TOO_LARGE: 413,
6
+ HQ_INTAKE_CONFLICT: 409,
7
+ HQ_INTAKE_INTERNAL: 500,
8
+ });
9
+ export class DeploymentIntakeError extends Error {
10
+ code;
11
+ status;
12
+ expose;
13
+ constructor(code, message, options = {}) {
14
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
15
+ this.name = 'DeploymentIntakeError';
16
+ this.code = code;
17
+ this.status = ERROR_STATUS[code];
18
+ this.expose = options.expose ?? this.status < 500;
19
+ }
20
+ }
21
+ export function badRequest(message, cause) {
22
+ return new DeploymentIntakeError('HQ_INTAKE_BAD_REQUEST', message, { cause });
23
+ }
24
+ export function tooLarge(message) {
25
+ return new DeploymentIntakeError('HQ_INTAKE_TOO_LARGE', message);
26
+ }
@@ -0,0 +1,9 @@
1
+ export { DEPLOYMENT_BUNDLE_CONTRACT, DEPLOYMENT_BUNDLE_MANIFEST, verifyDeploymentBundle, } from './bundle.js';
2
+ export type { VerifiedDeploymentBundle } from './bundle.js';
3
+ export { DeploymentIntakeError, } from './errors.js';
4
+ export type { DeploymentIntakeErrorCode } from './errors.js';
5
+ export { createDeploymentIntake, } from './intake.js';
6
+ export { DEFAULT_DEPLOYMENT_INTAKE_LIMITS, resolveDeploymentIntakeLimits, } from './limits.js';
7
+ export type { DeploymentIntakeLimits } from './limits.js';
8
+ export type { DeploymentAuthenticationInput, DeploymentAuthenticator, DeploymentAuthorizationInput, DeploymentAuthorizer, DeploymentIntake, DeploymentIntakeOptions, DeploymentIntakeRequest, DeploymentIntakeResponse, DeploymentSubmissionResponse, DeploymentSubmissionStore, VerifiedDeploymentSubmission, } from './types.js';
9
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,EAC1B,sBAAsB,GACvB,MAAM,aAAa,CAAC;AACrB,YAAY,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAC5D,OAAO,EACL,qBAAqB,GACtB,MAAM,aAAa,CAAC;AACrB,YAAY,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAC7D,OAAO,EACL,sBAAsB,GACvB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,gCAAgC,EAChC,6BAA6B,GAC9B,MAAM,aAAa,CAAC;AACrB,YAAY,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAC1D,YAAY,EACV,6BAA6B,EAC7B,uBAAuB,EACvB,4BAA4B,EAC5B,oBAAoB,EACpB,gBAAgB,EAChB,uBAAuB,EACvB,uBAAuB,EACvB,wBAAwB,EACxB,4BAA4B,EAC5B,yBAAyB,EACzB,4BAA4B,GAC7B,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { DEPLOYMENT_BUNDLE_CONTRACT, DEPLOYMENT_BUNDLE_MANIFEST, verifyDeploymentBundle, } from './bundle.js';
2
+ export { DeploymentIntakeError, } from './errors.js';
3
+ export { createDeploymentIntake, } from './intake.js';
4
+ export { DEFAULT_DEPLOYMENT_INTAKE_LIMITS, resolveDeploymentIntakeLimits, } from './limits.js';
@@ -0,0 +1,3 @@
1
+ import type { DeploymentIntake, DeploymentIntakeOptions } from './types.js';
2
+ export declare function createDeploymentIntake<Principal>(options: DeploymentIntakeOptions<Principal>): DeploymentIntake;
3
+ //# sourceMappingURL=intake.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"intake.d.ts","sourceRoot":"","sources":["../src/intake.ts"],"names":[],"mappings":"AA+BA,OAAO,KAAK,EACV,gBAAgB,EAChB,uBAAuB,EAIxB,MAAM,YAAY,CAAC;AAoSpB,wBAAgB,sBAAsB,CAAC,SAAS,EAC9C,OAAO,EAAE,uBAAuB,CAAC,SAAS,CAAC,GAC1C,gBAAgB,CA6HlB"}
package/dist/intake.js ADDED
@@ -0,0 +1,340 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdir, mkdtemp, open, rm, writeFile, } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { prepareProtocolDeploymentBundleManifest, prepareProtocolDeploymentReleaseEnvelope, } from '@hypequery/protocol';
6
+ import { DEPLOYMENT_BUNDLE_MANIFEST, verifyDeploymentBundle, } from './bundle.js';
7
+ import { badRequest, DeploymentIntakeError, tooLarge, } from './errors.js';
8
+ import { resolveDeploymentIntakeLimits } from './limits.js';
9
+ import { BoundedMultipartReader, } from './multipart.js';
10
+ const BOUNDARY_PATTERN = /^[A-Za-z0-9-]{1,70}$/;
11
+ const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
12
+ const textDecoder = new TextDecoder('utf-8', { fatal: true });
13
+ function requestHeader(headers, expectedName) {
14
+ const matches = Object.entries(headers)
15
+ .filter(([name, value]) => value !== undefined && name.toLowerCase() === expectedName)
16
+ .map(([, value]) => value);
17
+ if (matches.length > 1)
18
+ throw badRequest(`Duplicate ${expectedName} request header.`);
19
+ return matches[0];
20
+ }
21
+ function requireIdentityHeader(headers, name) {
22
+ const value = requestHeader(headers, name);
23
+ if (!value || !DIGEST_PATTERN.test(value)) {
24
+ throw badRequest(`The ${name} request header is invalid.`);
25
+ }
26
+ return value;
27
+ }
28
+ function bearerToken(headers) {
29
+ const authorization = requestHeader(headers, 'authorization');
30
+ const token = authorization?.startsWith('Bearer ') ? authorization.slice(7) : '';
31
+ if (token.length < 1 || token.length > 4096 || token.trim() !== token
32
+ || [...token].some(character => {
33
+ const code = character.charCodeAt(0);
34
+ return code < 0x21 || code > 0x7e;
35
+ })) {
36
+ throw new DeploymentIntakeError('HQ_INTAKE_UNAUTHENTICATED', 'A valid bearer credential is required.');
37
+ }
38
+ return token;
39
+ }
40
+ function contentLength(headers, maximum) {
41
+ const input = requestHeader(headers, 'content-length');
42
+ if (!input || !/^[1-9][0-9]*$/.test(input)) {
43
+ throw badRequest('An exact Content-Length request header is required.');
44
+ }
45
+ const value = Number(input);
46
+ if (!Number.isSafeInteger(value))
47
+ throw tooLarge('The deployment request is too large.');
48
+ if (value > maximum)
49
+ throw tooLarge('The deployment request exceeds its byte limit.');
50
+ return value;
51
+ }
52
+ function multipartBoundary(headers) {
53
+ const contentType = requestHeader(headers, 'content-type');
54
+ const match = contentType?.match(/^multipart\/form-data; boundary=([^; ]+)$/);
55
+ if (!match || !BOUNDARY_PATTERN.test(match[1])) {
56
+ throw badRequest('Content-Type must declare a valid multipart boundary.');
57
+ }
58
+ return match[1];
59
+ }
60
+ function throwIfAborted(signal) {
61
+ if (signal?.aborted)
62
+ throw badRequest('The deployment request was aborted.', signal.reason);
63
+ }
64
+ async function bufferedPart(reader, maximum) {
65
+ const chunks = [];
66
+ const result = await reader.readPartBody(maximum, chunk => {
67
+ chunks.push(Buffer.from(chunk));
68
+ });
69
+ return Object.freeze({ bytes: Buffer.concat(chunks, result.byteLength), final: result.final });
70
+ }
71
+ function requirePart(headers, expected) {
72
+ if (headers.name !== expected.name
73
+ || headers.filename !== expected.filename
74
+ || headers.contentType !== expected.contentType
75
+ || headers.bundlePath !== expected.bundlePath) {
76
+ throw badRequest('Multipart parts do not match the deployment submission contract.');
77
+ }
78
+ }
79
+ function decodeJson(bytes, description) {
80
+ try {
81
+ return JSON.parse(textDecoder.decode(bytes));
82
+ }
83
+ catch (error) {
84
+ throw badRequest(`${description} is not valid UTF-8 JSON.`, error);
85
+ }
86
+ }
87
+ function requireReconstructablePaths(manifest) {
88
+ const files = [
89
+ manifest.manifest.deployment.path,
90
+ ...manifest.manifest.artifacts.map(artifact => artifact.path),
91
+ ];
92
+ const fileSet = new Set(files);
93
+ if (fileSet.has(DEPLOYMENT_BUNDLE_MANIFEST)) {
94
+ throw badRequest('The bundle manifest path is reserved.');
95
+ }
96
+ for (const file of files) {
97
+ const segments = file.split('/');
98
+ if (file.includes('\\')
99
+ || segments.some(segment => segment === '' || segment === '.' || segment === '..')) {
100
+ throw badRequest('Bundle file paths must be safe relative paths.');
101
+ }
102
+ for (let index = 1; index < segments.length; index += 1) {
103
+ if (fileSet.has(segments.slice(0, index).join('/'))) {
104
+ throw badRequest('A bundle file path cannot also be a parent directory.');
105
+ }
106
+ }
107
+ }
108
+ }
109
+ async function readRelease(reader, maximum) {
110
+ requirePart(await reader.readPartHeaders(), {
111
+ name: 'release',
112
+ filename: 'release.json',
113
+ contentType: 'application/json',
114
+ });
115
+ const part = await bufferedPart(reader, maximum);
116
+ if (part.final)
117
+ throw badRequest('The deployment submission is missing its bundle.');
118
+ let prepared;
119
+ try {
120
+ prepared = prepareProtocolDeploymentReleaseEnvelope(decodeJson(part.bytes, 'The deployment release'));
121
+ }
122
+ catch (error) {
123
+ if (error instanceof DeploymentIntakeError)
124
+ throw error;
125
+ throw badRequest('The deployment release is invalid.', error);
126
+ }
127
+ if (!part.bytes.equals(Buffer.from(prepared.bytes))) {
128
+ throw badRequest('The deployment release must use canonical JSON without trailing bytes.');
129
+ }
130
+ return prepared;
131
+ }
132
+ async function readManifest(reader, maximum) {
133
+ requirePart(await reader.readPartHeaders(), {
134
+ name: 'bundle',
135
+ filename: DEPLOYMENT_BUNDLE_MANIFEST,
136
+ contentType: 'application/json',
137
+ bundlePath: DEPLOYMENT_BUNDLE_MANIFEST,
138
+ });
139
+ const part = await bufferedPart(reader, maximum);
140
+ if (part.final)
141
+ throw badRequest('The deployment submission is missing bundle files.');
142
+ let prepared;
143
+ try {
144
+ prepared = prepareProtocolDeploymentBundleManifest(decodeJson(part.bytes, 'The deployment bundle manifest'));
145
+ }
146
+ catch (error) {
147
+ if (error instanceof DeploymentIntakeError)
148
+ throw error;
149
+ throw badRequest('The deployment bundle manifest is invalid.', error);
150
+ }
151
+ const canonical = Buffer.from(`${prepared.canonical}\n`);
152
+ if (!part.bytes.equals(canonical)) {
153
+ throw badRequest('The deployment bundle manifest must use canonical JSON followed by one newline.');
154
+ }
155
+ requireReconstructablePaths(prepared);
156
+ return Object.freeze({ prepared, bytes: canonical });
157
+ }
158
+ async function writeChunk(handle, chunk) {
159
+ let offset = 0;
160
+ while (offset < chunk.byteLength) {
161
+ const result = await handle.write(chunk, offset, chunk.byteLength - offset);
162
+ if (result.bytesWritten < 1)
163
+ throw new Error('Could not write deployment bundle bytes.');
164
+ offset += result.bytesWritten;
165
+ }
166
+ }
167
+ async function receiveBundleFile(reader, root, file, contentType, expectFinal) {
168
+ requirePart(await reader.readPartHeaders(), {
169
+ name: 'bundle',
170
+ filename: path.basename(file.path),
171
+ contentType,
172
+ bundlePath: file.path,
173
+ });
174
+ const absolutePath = path.resolve(root, ...file.path.split('/'));
175
+ const relativePath = path.relative(root, absolutePath);
176
+ if (relativePath === '' || relativePath === '..'
177
+ || relativePath.startsWith(`..${path.sep}`) || path.isAbsolute(relativePath)) {
178
+ throw badRequest('Bundle file paths must remain within the temporary bundle directory.');
179
+ }
180
+ await mkdir(path.dirname(absolutePath), { recursive: true });
181
+ const handle = await open(absolutePath, 'wx');
182
+ const digest = createHash('sha256');
183
+ let result;
184
+ try {
185
+ result = await reader.readPartBody(file.byteLength, async (chunk) => {
186
+ digest.update(chunk);
187
+ await writeChunk(handle, chunk);
188
+ });
189
+ }
190
+ finally {
191
+ await handle.close();
192
+ }
193
+ if (result.byteLength !== file.byteLength || digest.digest('hex') !== file.sha256) {
194
+ throw badRequest(`Uploaded bundle bytes do not match the manifest: ${file.path}`);
195
+ }
196
+ if (result.final !== expectFinal) {
197
+ throw badRequest(expectFinal
198
+ ? 'The deployment submission contains undeclared bundle parts.'
199
+ : 'The deployment submission is missing declared bundle parts.');
200
+ }
201
+ }
202
+ function jsonResponse(status, body, additionalHeaders = {}) {
203
+ const encoded = `${JSON.stringify(body)}\n`;
204
+ return Object.freeze({
205
+ status,
206
+ headers: Object.freeze({
207
+ 'content-type': 'application/json; charset=utf-8',
208
+ 'content-length': String(Buffer.byteLength(encoded)),
209
+ 'cache-control': 'no-store',
210
+ ...additionalHeaders,
211
+ }),
212
+ body: encoded,
213
+ });
214
+ }
215
+ function errorResponse(error) {
216
+ const intakeError = error instanceof DeploymentIntakeError
217
+ ? error
218
+ : new DeploymentIntakeError('HQ_INTAKE_INTERNAL', 'The deployment submission could not be processed.', { expose: false, cause: error });
219
+ const unsafeMessage = intakeError.expose
220
+ ? intakeError.message
221
+ : 'The deployment submission could not be processed.';
222
+ const message = [...unsafeMessage].map(character => {
223
+ const code = character.codePointAt(0) ?? 0;
224
+ return code < 0x20 || code === 0x7f ? ' ' : character;
225
+ }).join('').slice(0, 1024).trim() || 'The deployment submission was rejected.';
226
+ return jsonResponse(intakeError.status, {
227
+ error: { code: intakeError.code, message },
228
+ }, intakeError.status === 401 ? { 'www-authenticate': 'Bearer' } : {});
229
+ }
230
+ async function removeTemporaryDirectory(directory, suppressError = false) {
231
+ try {
232
+ await rm(directory, { force: true, recursive: true });
233
+ }
234
+ catch (cleanupError) {
235
+ if (!suppressError) {
236
+ throw new DeploymentIntakeError('HQ_INTAKE_INTERNAL', 'The deployment submission could not be cleaned up.', { expose: false, cause: cleanupError });
237
+ }
238
+ }
239
+ }
240
+ export function createDeploymentIntake(options) {
241
+ const limits = resolveDeploymentIntakeLimits(options.limits);
242
+ async function process(request) {
243
+ throwIfAborted(request.signal);
244
+ const token = bearerToken(request.headers);
245
+ const principal = await options.authenticator.authenticate({ token, signal: request.signal });
246
+ if (principal === null) {
247
+ throw new DeploymentIntakeError('HQ_INTAKE_UNAUTHENTICATED', 'The bearer credential was not accepted.');
248
+ }
249
+ throwIfAborted(request.signal);
250
+ const releaseHeader = requireIdentityHeader(request.headers, 'x-hypequery-release-identity');
251
+ const bundleHeader = requireIdentityHeader(request.headers, 'x-hypequery-bundle-identity');
252
+ const idempotencyKey = requireIdentityHeader(request.headers, 'idempotency-key');
253
+ const declaredLength = contentLength(request.headers, limits.maxRequestBytes);
254
+ const boundary = multipartBoundary(request.headers);
255
+ const reader = new BoundedMultipartReader(request.body, boundary, declaredLength, limits.maxRequestBytes, limits.maxPartHeaderBytes, request.signal);
256
+ await reader.start();
257
+ const release = await readRelease(reader, limits.maxReleaseBytes);
258
+ if (release.identity !== releaseHeader || release.identity !== idempotencyKey
259
+ || release.release.bundleIdentity !== bundleHeader) {
260
+ throw badRequest('Deployment release identities do not match the uploaded release.');
261
+ }
262
+ const authorized = await options.authorizer.authorize({
263
+ principal,
264
+ target: release.release.target,
265
+ releaseIdentity: release.identity,
266
+ bundleIdentity: release.release.bundleIdentity,
267
+ signal: request.signal,
268
+ });
269
+ if (!authorized) {
270
+ throw new DeploymentIntakeError('HQ_INTAKE_FORBIDDEN', 'The caller is not authorized for the deployment target.');
271
+ }
272
+ throwIfAborted(request.signal);
273
+ const manifest = await readManifest(reader, limits.maxManifestBytes);
274
+ if (manifest.prepared.identity !== bundleHeader
275
+ || manifest.prepared.identity !== release.release.bundleIdentity) {
276
+ throw badRequest('Deployment bundle identities do not match the uploaded manifest.');
277
+ }
278
+ const temporaryRoot = await mkdtemp(path.join(options.temporaryDirectory ?? tmpdir(), 'hypequery-intake-'));
279
+ let cleaned = false;
280
+ try {
281
+ const bundleRoot = path.join(temporaryRoot, 'bundle');
282
+ await mkdir(bundleRoot);
283
+ await writeFile(path.join(bundleRoot, DEPLOYMENT_BUNDLE_MANIFEST), manifest.bytes, { flag: 'wx' });
284
+ const files = [
285
+ manifest.prepared.manifest.deployment,
286
+ ...manifest.prepared.manifest.artifacts,
287
+ ];
288
+ for (let index = 0; index < files.length; index += 1) {
289
+ await receiveBundleFile(reader, bundleRoot, files[index], index === 0 ? 'application/json' : 'application/octet-stream', index === files.length - 1);
290
+ }
291
+ await reader.finish();
292
+ throwIfAborted(request.signal);
293
+ let bundle;
294
+ try {
295
+ bundle = await verifyDeploymentBundle(bundleRoot);
296
+ }
297
+ catch (error) {
298
+ throw badRequest('The reconstructed deployment bundle is invalid.', error);
299
+ }
300
+ if (bundle.identity !== manifest.prepared.identity
301
+ || bundle.identity !== release.release.bundleIdentity) {
302
+ throw badRequest('The reconstructed deployment bundle identity is inconsistent.');
303
+ }
304
+ const status = await options.store.accept(Object.freeze({
305
+ principal,
306
+ release: release.release,
307
+ releaseCanonical: release.canonical,
308
+ releaseIdentity: release.identity,
309
+ bundle,
310
+ }));
311
+ if (status !== 'accepted' && status !== 'already-exists') {
312
+ throw new DeploymentIntakeError('HQ_INTAKE_INTERNAL', 'The deployment store returned an invalid status.', { expose: false });
313
+ }
314
+ const response = Object.freeze({
315
+ kind: 'hypequery-deployment-submission',
316
+ version: 1,
317
+ status,
318
+ releaseIdentity: release.identity,
319
+ bundleIdentity: bundle.identity,
320
+ });
321
+ cleaned = true;
322
+ await removeTemporaryDirectory(temporaryRoot, true);
323
+ return jsonResponse(status === 'accepted' ? 202 : 200, response);
324
+ }
325
+ finally {
326
+ if (!cleaned)
327
+ await removeTemporaryDirectory(temporaryRoot, true);
328
+ }
329
+ }
330
+ return Object.freeze({
331
+ async handle(request) {
332
+ try {
333
+ return await process(request);
334
+ }
335
+ catch (error) {
336
+ return errorResponse(error);
337
+ }
338
+ },
339
+ });
340
+ }
@@ -0,0 +1,9 @@
1
+ export interface DeploymentIntakeLimits {
2
+ readonly maxRequestBytes: number;
3
+ readonly maxReleaseBytes: number;
4
+ readonly maxManifestBytes: number;
5
+ readonly maxPartHeaderBytes: number;
6
+ }
7
+ export declare const DEFAULT_DEPLOYMENT_INTAKE_LIMITS: Readonly<DeploymentIntakeLimits>;
8
+ export declare function resolveDeploymentIntakeLimits(input?: Partial<DeploymentIntakeLimits>): Readonly<DeploymentIntakeLimits>;
9
+ //# sourceMappingURL=limits.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"limits.d.ts","sourceRoot":"","sources":["../src/limits.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC;CACrC;AAED,eAAO,MAAM,gCAAgC,EAAE,QAAQ,CAAC,sBAAsB,CAK5E,CAAC;AAEH,wBAAgB,6BAA6B,CAC3C,KAAK,GAAE,OAAO,CAAC,sBAAsB,CAAM,GAC1C,QAAQ,CAAC,sBAAsB,CAAC,CAelC"}
package/dist/limits.js ADDED
@@ -0,0 +1,22 @@
1
+ import { DEFAULT_PROTOCOL_DEPLOYMENT_BUNDLE_LIMITS } from '@hypequery/protocol';
2
+ export const DEFAULT_DEPLOYMENT_INTAKE_LIMITS = Object.freeze({
3
+ maxRequestBytes: DEFAULT_PROTOCOL_DEPLOYMENT_BUNDLE_LIMITS.maxTotalBytes + (2 * 1024 * 1024),
4
+ maxReleaseBytes: 16 * 1024,
5
+ maxManifestBytes: 1024 * 1024,
6
+ maxPartHeaderBytes: 8 * 1024,
7
+ });
8
+ export function resolveDeploymentIntakeLimits(input = {}) {
9
+ const result = { ...DEFAULT_DEPLOYMENT_INTAKE_LIMITS };
10
+ for (const key of Object.keys(result)) {
11
+ const value = input[key];
12
+ if (value === undefined)
13
+ continue;
14
+ if (!Number.isSafeInteger(value) || value < 1
15
+ || value > DEFAULT_DEPLOYMENT_INTAKE_LIMITS[key]) {
16
+ throw new RangeError(`${key} must be a positive safe integer no greater than `
17
+ + `${DEFAULT_DEPLOYMENT_INTAKE_LIMITS[key]} (the deployment intake v1 maximum)`);
18
+ }
19
+ result[key] = value;
20
+ }
21
+ return Object.freeze(result);
22
+ }
@@ -0,0 +1,19 @@
1
+ export interface MultipartPartHeaders {
2
+ readonly name: string;
3
+ readonly filename: string;
4
+ readonly contentType: string;
5
+ readonly bundlePath?: string;
6
+ }
7
+ export declare class BoundedMultipartReader {
8
+ #private;
9
+ constructor(body: AsyncIterable<Uint8Array>, boundary: string, declaredLength: number, maximumLength: number, maximumHeaderBytes: number, signal?: AbortSignal);
10
+ start(): Promise<void>;
11
+ readPartHeaders(): Promise<MultipartPartHeaders>;
12
+ /** Returns true when this was the final part. */
13
+ readPartBody(maximum: number, consume: (chunk: Uint8Array) => void | Promise<void>): Promise<{
14
+ readonly final: boolean;
15
+ readonly byteLength: number;
16
+ }>;
17
+ finish(): Promise<void>;
18
+ }
19
+ //# sourceMappingURL=multipart.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"multipart.d.ts","sourceRoot":"","sources":["../src/multipart.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAC9B;AAED,qBAAa,sBAAsB;;gBAa/B,IAAI,EAAE,aAAa,CAAC,UAAU,CAAC,EAC/B,QAAQ,EAAE,MAAM,EAChB,cAAc,EAAE,MAAM,EACtB,aAAa,EAAE,MAAM,EACrB,kBAAkB,EAAE,MAAM,EAC1B,MAAM,CAAC,EAAE,WAAW;IA6EhB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAStB,eAAe,IAAI,OAAO,CAAC,oBAAoB,CAAC;IA4CtD,iDAAiD;IAC3C,YAAY,CAChB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,GACnD,OAAO,CAAC;QAAE,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;QAAC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;KAAE,CAAC;IAkC9D,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC;CAS9B"}
@@ -0,0 +1,199 @@
1
+ import { badRequest, tooLarge } from './errors.js';
2
+ const CRLF = Buffer.from('\r\n');
3
+ const HEADER_NAME = /^[A-Za-z0-9-]+$/;
4
+ const HEADER_VALUE = /^[\x20-\x7e]*$/;
5
+ export class BoundedMultipartReader {
6
+ #iterator;
7
+ #boundary;
8
+ #declaredLength;
9
+ #maximumLength;
10
+ #maximumHeaderBytes;
11
+ #signal;
12
+ #buffer = Buffer.alloc(0);
13
+ #received = 0;
14
+ #finished = false;
15
+ #started = false;
16
+ constructor(body, boundary, declaredLength, maximumLength, maximumHeaderBytes, signal) {
17
+ this.#iterator = body[Symbol.asyncIterator]();
18
+ this.#boundary = Buffer.from(`--${boundary}`);
19
+ this.#declaredLength = declaredLength;
20
+ this.#maximumLength = maximumLength;
21
+ this.#maximumHeaderBytes = maximumHeaderBytes;
22
+ this.#signal = signal;
23
+ }
24
+ #throwIfAborted() {
25
+ if (this.#signal?.aborted) {
26
+ throw badRequest('The deployment request was aborted.', this.#signal.reason);
27
+ }
28
+ }
29
+ async #fill() {
30
+ while (!this.#finished) {
31
+ this.#throwIfAborted();
32
+ let item;
33
+ try {
34
+ item = await this.#iterator.next();
35
+ }
36
+ catch (error) {
37
+ throw badRequest('The deployment request body could not be read.', error);
38
+ }
39
+ if (item.done) {
40
+ this.#finished = true;
41
+ return false;
42
+ }
43
+ if (!(item.value instanceof Uint8Array)) {
44
+ throw badRequest('The deployment request body yielded a non-byte chunk.');
45
+ }
46
+ if (item.value.byteLength === 0)
47
+ continue;
48
+ this.#received += item.value.byteLength;
49
+ if (this.#received > this.#declaredLength) {
50
+ throw badRequest('The deployment request body exceeds its Content-Length.');
51
+ }
52
+ if (this.#received > this.#maximumLength) {
53
+ throw tooLarge('The deployment request exceeds its byte limit.');
54
+ }
55
+ const chunk = Buffer.from(item.value.buffer, item.value.byteOffset, item.value.byteLength);
56
+ this.#buffer = this.#buffer.length === 0 ? chunk : Buffer.concat([this.#buffer, chunk]);
57
+ return true;
58
+ }
59
+ return false;
60
+ }
61
+ async #readBytes(length) {
62
+ while (this.#buffer.length < length && await this.#fill()) {
63
+ // Fill until the requested framing bytes are available.
64
+ }
65
+ if (this.#buffer.length < length)
66
+ throw badRequest('The multipart request is truncated.');
67
+ const value = this.#buffer.subarray(0, length);
68
+ this.#buffer = this.#buffer.subarray(length);
69
+ return value;
70
+ }
71
+ async #readLine(maximum) {
72
+ for (;;) {
73
+ const index = this.#buffer.indexOf(CRLF);
74
+ if (index >= 0) {
75
+ if (index > maximum)
76
+ throw tooLarge('Multipart part headers exceed their byte limit.');
77
+ const bytes = this.#buffer.subarray(0, index);
78
+ this.#buffer = this.#buffer.subarray(index + CRLF.length);
79
+ const value = bytes.toString('latin1');
80
+ if (!HEADER_VALUE.test(value)) {
81
+ throw badRequest('Multipart headers must contain printable ASCII.');
82
+ }
83
+ return value;
84
+ }
85
+ if (this.#buffer.length > maximum) {
86
+ throw tooLarge('Multipart part headers exceed their byte limit.');
87
+ }
88
+ if (!await this.#fill())
89
+ throw badRequest('The multipart request is truncated.');
90
+ }
91
+ }
92
+ async start() {
93
+ if (this.#started)
94
+ throw new Error('Multipart reader has already started.');
95
+ this.#started = true;
96
+ const opening = await this.#readBytes(this.#boundary.length + CRLF.length);
97
+ if (!opening.equals(Buffer.concat([this.#boundary, CRLF]))) {
98
+ throw badRequest('The multipart body does not begin with its declared boundary.');
99
+ }
100
+ }
101
+ async readPartHeaders() {
102
+ if (!this.#started)
103
+ throw new Error('Multipart reader has not started.');
104
+ const headers = new Map();
105
+ let consumed = 0;
106
+ for (;;) {
107
+ const line = await this.#readLine(this.#maximumHeaderBytes - consumed);
108
+ consumed += Buffer.byteLength(line) + CRLF.length;
109
+ if (consumed > this.#maximumHeaderBytes) {
110
+ throw tooLarge('Multipart part headers exceed their byte limit.');
111
+ }
112
+ if (line === '')
113
+ break;
114
+ if (/^[ \t]/.test(line))
115
+ throw badRequest('Folded multipart headers are not supported.');
116
+ const separator = line.indexOf(':');
117
+ if (separator < 1)
118
+ throw badRequest('Multipart part header syntax is invalid.');
119
+ const name = line.slice(0, separator);
120
+ const value = line.slice(separator + 1).trim();
121
+ const normalized = name.toLowerCase();
122
+ if (!HEADER_NAME.test(name) || headers.has(normalized)) {
123
+ throw badRequest('Multipart part headers contain an invalid or duplicate field.');
124
+ }
125
+ headers.set(normalized, value);
126
+ }
127
+ const allowed = new Set([
128
+ 'content-disposition',
129
+ 'content-type',
130
+ 'x-hypequery-bundle-path',
131
+ ]);
132
+ if ([...headers.keys()].some(name => !allowed.has(name))) {
133
+ throw badRequest('Multipart parts contain an unsupported header.');
134
+ }
135
+ const disposition = headers.get('content-disposition');
136
+ const match = disposition?.match(/^form-data; name="(release|bundle)"; filename="([^"\r\n]+)"$/);
137
+ const contentType = headers.get('content-type');
138
+ if (!match || !contentType)
139
+ throw badRequest('Multipart part headers are incomplete.');
140
+ return Object.freeze({
141
+ name: match[1],
142
+ filename: match[2],
143
+ contentType,
144
+ ...(headers.has('x-hypequery-bundle-path')
145
+ ? { bundlePath: headers.get('x-hypequery-bundle-path') }
146
+ : {}),
147
+ });
148
+ }
149
+ /** Returns true when this was the final part. */
150
+ async readPartBody(maximum, consume) {
151
+ const marker = Buffer.concat([CRLF, this.#boundary]);
152
+ const retained = marker.length - 1;
153
+ let byteLength = 0;
154
+ const emit = async (chunk) => {
155
+ if (chunk.length === 0)
156
+ return;
157
+ this.#throwIfAborted();
158
+ byteLength += chunk.length;
159
+ if (byteLength > maximum)
160
+ throw tooLarge('A multipart part exceeds its byte limit.');
161
+ await consume(chunk);
162
+ };
163
+ for (;;) {
164
+ const index = this.#buffer.indexOf(marker);
165
+ if (index >= 0) {
166
+ await emit(this.#buffer.subarray(0, index));
167
+ this.#buffer = this.#buffer.subarray(index + marker.length);
168
+ break;
169
+ }
170
+ if (this.#buffer.length > retained) {
171
+ const flushLength = this.#buffer.length - retained;
172
+ await emit(this.#buffer.subarray(0, flushLength));
173
+ this.#buffer = this.#buffer.subarray(flushLength);
174
+ }
175
+ if (!await this.#fill())
176
+ throw badRequest('The multipart request is truncated.');
177
+ }
178
+ const suffix = await this.#readBytes(2);
179
+ if (suffix.equals(CRLF))
180
+ return Object.freeze({ final: false, byteLength });
181
+ if (!suffix.equals(Buffer.from('--')))
182
+ throw badRequest('The multipart boundary is invalid.');
183
+ if (!(await this.#readBytes(2)).equals(CRLF)) {
184
+ throw badRequest('The final multipart boundary is invalid.');
185
+ }
186
+ return Object.freeze({ final: true, byteLength });
187
+ }
188
+ async finish() {
189
+ if (this.#buffer.length > 0)
190
+ throw badRequest('The multipart request has trailing bytes.');
191
+ while (await this.#fill()) {
192
+ if (this.#buffer.length > 0)
193
+ throw badRequest('The multipart request has trailing bytes.');
194
+ }
195
+ if (this.#received !== this.#declaredLength) {
196
+ throw badRequest('The deployment request body does not match its Content-Length.');
197
+ }
198
+ }
199
+ }
@@ -0,0 +1,64 @@
1
+ import type { ProtocolDeploymentReleaseEnvelope, ProtocolDeploymentReleaseTarget } from '@hypequery/protocol';
2
+ import type { VerifiedDeploymentBundle } from './bundle.js';
3
+ import type { DeploymentIntakeLimits } from './limits.js';
4
+ export interface DeploymentSubmissionResponse {
5
+ readonly kind: 'hypequery-deployment-submission';
6
+ readonly version: 1;
7
+ readonly status: 'accepted' | 'already-exists';
8
+ readonly releaseIdentity: string;
9
+ readonly bundleIdentity: string;
10
+ }
11
+ export interface DeploymentIntakeRequest {
12
+ readonly headers: Readonly<Record<string, string | undefined>>;
13
+ readonly body: AsyncIterable<Uint8Array>;
14
+ readonly signal?: AbortSignal;
15
+ }
16
+ export interface DeploymentIntakeResponse {
17
+ readonly status: number;
18
+ readonly headers: Readonly<Record<string, string>>;
19
+ readonly body: string;
20
+ }
21
+ export interface DeploymentAuthenticationInput {
22
+ readonly token: string;
23
+ readonly signal?: AbortSignal;
24
+ }
25
+ export interface DeploymentAuthenticator<Principal> {
26
+ authenticate(input: DeploymentAuthenticationInput): Promise<Principal | null>;
27
+ }
28
+ export interface DeploymentAuthorizationInput<Principal> {
29
+ readonly principal: Principal;
30
+ readonly target: ProtocolDeploymentReleaseTarget;
31
+ readonly releaseIdentity: string;
32
+ /** Declared by the canonical release; the bundle bytes are verified after authorization. */
33
+ readonly bundleIdentity: string;
34
+ readonly signal?: AbortSignal;
35
+ }
36
+ export interface DeploymentAuthorizer<Principal> {
37
+ authorize(input: DeploymentAuthorizationInput<Principal>): Promise<boolean>;
38
+ }
39
+ /**
40
+ * A completely revalidated submission. The bundle directory is temporary and
41
+ * exists only for the duration of `DeploymentSubmissionStore.accept`.
42
+ */
43
+ export interface VerifiedDeploymentSubmission<Principal> {
44
+ readonly principal: Principal;
45
+ readonly release: ProtocolDeploymentReleaseEnvelope;
46
+ readonly releaseCanonical: string;
47
+ readonly releaseIdentity: string;
48
+ readonly bundle: VerifiedDeploymentBundle;
49
+ }
50
+ export interface DeploymentSubmissionStore<Principal> {
51
+ /** Persist all required bytes before this promise resolves. */
52
+ accept(submission: VerifiedDeploymentSubmission<Principal>): Promise<'accepted' | 'already-exists'>;
53
+ }
54
+ export interface DeploymentIntakeOptions<Principal> {
55
+ readonly authenticator: DeploymentAuthenticator<Principal>;
56
+ readonly authorizer: DeploymentAuthorizer<Principal>;
57
+ readonly store: DeploymentSubmissionStore<Principal>;
58
+ readonly limits?: Partial<DeploymentIntakeLimits>;
59
+ readonly temporaryDirectory?: string;
60
+ }
61
+ export interface DeploymentIntake {
62
+ handle(request: DeploymentIntakeRequest): Promise<DeploymentIntakeResponse>;
63
+ }
64
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iCAAiC,EACjC,+BAA+B,EAChC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAC5D,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAE1D,MAAM,WAAW,4BAA4B;IAC3C,QAAQ,CAAC,IAAI,EAAE,iCAAiC,CAAC;IACjD,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC;IACpB,QAAQ,CAAC,MAAM,EAAE,UAAU,GAAG,gBAAgB,CAAC;IAC/C,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;CACjC;AAED,MAAM,WAAW,uBAAuB;IACtC,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAC;IAC/D,QAAQ,CAAC,IAAI,EAAE,aAAa,CAAC,UAAU,CAAC,CAAC;IACzC,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;CAC/B;AAED,MAAM,WAAW,wBAAwB;IACvC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACnD,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,6BAA6B;IAC5C,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;CAC/B;AAED,MAAM,WAAW,uBAAuB,CAAC,SAAS;IAChD,YAAY,CAAC,KAAK,EAAE,6BAA6B,GAAG,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC;CAC/E;AAED,MAAM,WAAW,4BAA4B,CAAC,SAAS;IACrD,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;IAC9B,QAAQ,CAAC,MAAM,EAAE,+BAA+B,CAAC;IACjD,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,4FAA4F;IAC5F,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;CAC/B;AAED,MAAM,WAAW,oBAAoB,CAAC,SAAS;IAC7C,SAAS,CAAC,KAAK,EAAE,4BAA4B,CAAC,SAAS,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAC7E;AAED;;;GAGG;AACH,MAAM,WAAW,4BAA4B,CAAC,SAAS;IACrD,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;IAC9B,QAAQ,CAAC,OAAO,EAAE,iCAAiC,CAAC;IACpD,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,QAAQ,CAAC,MAAM,EAAE,wBAAwB,CAAC;CAC3C;AAED,MAAM,WAAW,yBAAyB,CAAC,SAAS;IAClD,+DAA+D;IAC/D,MAAM,CACJ,UAAU,EAAE,4BAA4B,CAAC,SAAS,CAAC,GAClD,OAAO,CAAC,UAAU,GAAG,gBAAgB,CAAC,CAAC;CAC3C;AAED,MAAM,WAAW,uBAAuB,CAAC,SAAS;IAChD,QAAQ,CAAC,aAAa,EAAE,uBAAuB,CAAC,SAAS,CAAC,CAAC;IAC3D,QAAQ,CAAC,UAAU,EAAE,oBAAoB,CAAC,SAAS,CAAC,CAAC;IACrD,QAAQ,CAAC,KAAK,EAAE,yBAAyB,CAAC,SAAS,CAAC,CAAC;IACrD,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,sBAAsB,CAAC,CAAC;IAClD,QAAQ,CAAC,kBAAkB,CAAC,EAAE,MAAM,CAAC;CACtC;AAED,MAAM,WAAW,gBAAgB;IAC/B,MAAM,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAAC;CAC7E"}
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@hypequery/deployment",
3
+ "version": "0.0.0-canary-20260719130627",
4
+ "description": "Provider-neutral deployment verification and intake for Hypequery",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "sideEffects": false,
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "README.md"
19
+ ],
20
+ "dependencies": {
21
+ "@hypequery/protocol": "0.0.0-canary-20260719130627"
22
+ },
23
+ "devDependencies": {
24
+ "@types/node": "^22.5.0",
25
+ "typescript": "^5.7.3",
26
+ "vitest": "^3.2.6"
27
+ },
28
+ "engines": {
29
+ "node": ">=20"
30
+ },
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "https://github.com/hypequery/hypequery.git",
34
+ "directory": "packages/deployment"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "scripts": {
40
+ "build": "tsc --project tsconfig.json",
41
+ "dev": "tsc --project tsconfig.json --watch",
42
+ "lint": "eslint --ext .ts \"src/**/*.ts\"",
43
+ "test": "vitest run",
44
+ "types": "tsc --project tsconfig.json --noEmit"
45
+ }
46
+ }