@agimon-ai/po-web-security 0.0.0-alpha.3 → 0.0.0-alpha.31
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 +149 -22
- package/dist/browser.cjs +1 -1
- package/dist/browser.d.mts +2 -2
- package/dist/browser.mjs +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/services/browserSealedChannel/index.cjs +1 -1
- package/dist/services/browserSealedChannel/index.cjs.map +1 -1
- package/dist/services/browserSealedChannel/index.d.mts.map +1 -1
- package/dist/services/browserSealedChannel/index.mjs +1 -1
- package/dist/services/browserSealedChannel/index.mjs.map +1 -1
- package/dist/services/bundleSigner/index.cjs +1 -1
- package/dist/services/bundleSigner/index.cjs.map +1 -1
- package/dist/services/bundleSigner/index.mjs +1 -1
- package/dist/services/bundleSigner/index.mjs.map +1 -1
- package/dist/services/sealedTransport/index.cjs +1 -1
- package/dist/services/sealedTransport/index.cjs.map +1 -1
- package/dist/services/sealedTransport/index.d.mts +4 -0
- package/dist/services/sealedTransport/index.d.mts.map +1 -1
- package/dist/services/sealedTransport/index.mjs +1 -1
- package/dist/services/sealedTransport/index.mjs.map +1 -1
- package/dist/types/bundleManifest.cjs +1 -1
- package/dist/types/bundleManifest.cjs.map +1 -1
- package/dist/types/bundleManifest.d.mts +9 -2
- package/dist/types/bundleManifest.d.mts.map +1 -1
- package/dist/types/bundleManifest.mjs +2 -2
- package/dist/types/bundleManifest.mjs.map +1 -1
- package/package.json +5 -5
package/LICENSE
CHANGED
|
@@ -1,22 +1,149 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
1
|
+
License text copyright © 2017 MariaDB Corporation Ab, All Rights Reserved.
|
|
2
|
+
"Business Source License" is a trademark of MariaDB Corporation Ab.
|
|
3
|
+
|
|
4
|
+
Parameters
|
|
5
|
+
|
|
6
|
+
Licensor: Agimon Pty Ltd
|
|
7
|
+
Licensed Work: Po, the software in the Po source repository and the
|
|
8
|
+
packages released from it, in each version released by
|
|
9
|
+
the Licensor.
|
|
10
|
+
The Licensed Work is (c) 2026 Agimon Pty Ltd.
|
|
11
|
+
Material identified as third-party in the "Third-party
|
|
12
|
+
components" section at the end of this file or in a
|
|
13
|
+
NOTICE file, and any package or directory whose own
|
|
14
|
+
license file grants a different license, is not part of
|
|
15
|
+
the Licensed Work and remains under its own license.
|
|
16
|
+
Additional Use Grant: You may make production use of the Licensed Work if
|
|
17
|
+
your use is Eligible Use. "Eligible Use" is production use that falls
|
|
18
|
+
within at least one of the following:
|
|
19
|
+
|
|
20
|
+
(a) Personal Use. Use by an individual for their own personal purposes,
|
|
21
|
+
and not on behalf of, or for the benefit of, an employer, client, or
|
|
22
|
+
other Organization. Use by an individual in the course of employment
|
|
23
|
+
or engagement by an Organization is use by that Organization.
|
|
24
|
+
|
|
25
|
+
(b) Small Organization Use. Use by or on behalf of an Organization whose
|
|
26
|
+
Annual Revenue is less than USD 1,000,000.
|
|
27
|
+
|
|
28
|
+
(c) Non-profit, Education and Research Use. Use, regardless of Annual
|
|
29
|
+
Revenue, by (i) an Organization registered or recognized as a
|
|
30
|
+
non-profit or charitable organization under the laws of its
|
|
31
|
+
jurisdiction, for its non-profit purposes; (ii) an accredited school,
|
|
32
|
+
college, or university, for teaching, learning, or academic research;
|
|
33
|
+
or (iii) a publicly funded research institution, for its research.
|
|
34
|
+
|
|
35
|
+
(d) Service Provider Use. Use by a consultant, contractor, agency, or other
|
|
36
|
+
service provider, regardless of its own Annual Revenue, solely to
|
|
37
|
+
build, deploy, host, operate, or support the Licensed Work for a client
|
|
38
|
+
whose own use would be Eligible Use under (a), (b), or (c). A service
|
|
39
|
+
provider's use for its own purposes is Eligible Use only if the service
|
|
40
|
+
provider itself qualifies under (b) or (c).
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
Hosted services. Offering the Licensed Work to third parties as a hosted
|
|
44
|
+
or managed service whose primary value is the Licensed Work is Eligible
|
|
45
|
+
Use only if each such third party's own use would be Eligible Use.
|
|
46
|
+
|
|
47
|
+
Definitions. "Organization" means any company, partnership, sole
|
|
48
|
+
proprietorship, trust, association, government body, or other entity, and
|
|
49
|
+
includes an individual acting in a business or professional capacity.
|
|
50
|
+
"Affiliate" means any entity that directly or indirectly controls, is
|
|
51
|
+
controlled by, or is under common control with an Organization, where
|
|
52
|
+
"control" means ownership of more than 50% of the voting interests of an
|
|
53
|
+
entity or the power to direct its management and policies by contract or
|
|
54
|
+
otherwise. "Annual Revenue" means the total gross revenue of an
|
|
55
|
+
Organization and all of its Affiliates combined, from all sources and
|
|
56
|
+
whether or not related to the Licensed Work, for its most recently
|
|
57
|
+
completed fiscal year, or, if it has not completed a fiscal year, for the
|
|
58
|
+
twelve months before the use (or since its formation, if shorter),
|
|
59
|
+
converted into US dollars at the average exchange rate for that period.
|
|
60
|
+
Proceeds of equity or debt financing are not revenue.
|
|
61
|
+
|
|
62
|
+
Threshold. If an Organization stops qualifying under (b), its existing
|
|
63
|
+
production use remains Eligible Use for 90 days after it stops
|
|
64
|
+
qualifying, after which it must obtain a commercial license or stop
|
|
65
|
+
production use. Use that was Eligible Use when it occurred never requires
|
|
66
|
+
a commercial license after the fact.
|
|
67
|
+
Change Date: Four years from the date a version of the Licensed Work
|
|
68
|
+
is first publicly released by the Licensor.
|
|
69
|
+
Change License: Apache License, Version 2.0
|
|
70
|
+
|
|
71
|
+
For information about alternative licensing arrangements for the Licensed
|
|
72
|
+
Work, please visit: https://agimon.ai/licensing
|
|
73
|
+
|
|
74
|
+
Notice
|
|
75
|
+
|
|
76
|
+
The Business Source License (this document, or the "License") is not an Open
|
|
77
|
+
Source license. However, the Licensed Work will eventually be made available
|
|
78
|
+
under an Open Source License, as stated in this License.
|
|
79
|
+
|
|
80
|
+
-----------------------------------------------------------------------------
|
|
81
|
+
|
|
82
|
+
Business Source License 1.1
|
|
83
|
+
|
|
84
|
+
Terms
|
|
85
|
+
|
|
86
|
+
The Licensor hereby grants you the right to copy, modify, create derivative
|
|
87
|
+
works, redistribute, and make non-production use of the Licensed Work. The
|
|
88
|
+
Licensor may make an Additional Use Grant, above, permitting limited
|
|
89
|
+
production use.
|
|
90
|
+
|
|
91
|
+
Effective on the Change Date, or the fourth anniversary of the first publicly
|
|
92
|
+
available distribution of a specific version of the Licensed Work under this
|
|
93
|
+
License, whichever comes first, the Licensor hereby grants you rights under
|
|
94
|
+
the terms of the Change License, and the rights granted in the paragraph
|
|
95
|
+
above terminate.
|
|
96
|
+
|
|
97
|
+
If your use of the Licensed Work does not comply with the requirements
|
|
98
|
+
currently in effect as described in this License, you must purchase a
|
|
99
|
+
commercial license from the Licensor, its affiliated entities, or authorized
|
|
100
|
+
resellers, or you must refrain from using the Licensed Work.
|
|
101
|
+
|
|
102
|
+
All copies of the original and modified Licensed Work, and derivative works
|
|
103
|
+
of the Licensed Work, are subject to this License. This License applies
|
|
104
|
+
separately for each version of the Licensed Work and the Change Date may vary
|
|
105
|
+
for each version of the Licensed Work released by Licensor.
|
|
106
|
+
|
|
107
|
+
You must conspicuously display this License on each original or modified copy
|
|
108
|
+
of the Licensed Work. If you receive the Licensed Work in original or
|
|
109
|
+
modified form from a third party, the terms and conditions set forth in this
|
|
110
|
+
License apply to your use of that work.
|
|
111
|
+
|
|
112
|
+
Any use of the Licensed Work in violation of this License will automatically
|
|
113
|
+
terminate your rights under this License for the current and all other
|
|
114
|
+
versions of the Licensed Work.
|
|
115
|
+
|
|
116
|
+
This License does not grant you any right in any trademark or logo of
|
|
117
|
+
Licensor or its affiliates (provided that you may use a trademark or logo of
|
|
118
|
+
Licensor as expressly required by this License).
|
|
119
|
+
|
|
120
|
+
TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
|
|
121
|
+
AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
|
|
122
|
+
EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
|
|
123
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
|
|
124
|
+
TITLE.
|
|
125
|
+
|
|
126
|
+
MariaDB hereby grants you permission to use this License’s text to license
|
|
127
|
+
your works, and to refer to it using the trademark “Business Source License”,
|
|
128
|
+
as long as you comply with the Covenants of Licensor below.
|
|
129
|
+
|
|
130
|
+
Covenants of Licensor
|
|
131
|
+
|
|
132
|
+
In consideration of the right to use this License’s text and the “Business
|
|
133
|
+
Source License” name and trademark, Licensor covenants to MariaDB, and to all
|
|
134
|
+
other recipients of the licensed work to be provided by Licensor:
|
|
135
|
+
|
|
136
|
+
1. To specify as the Change License the GPL Version 2.0 or any later version,
|
|
137
|
+
or a license that is compatible with GPL Version 2.0 or a later version,
|
|
138
|
+
where “compatible” means that software provided under the Change License can
|
|
139
|
+
be included in a program with software provided under GPL Version 2.0 or a
|
|
140
|
+
later version. Licensor may specify additional Change Licenses without
|
|
141
|
+
limitation.
|
|
142
|
+
|
|
143
|
+
2. To either: (a) specify an additional grant of rights to use that does not
|
|
144
|
+
impose any additional restriction on the right granted in this License, as
|
|
145
|
+
the Additional Use Grant; or (b) insert the text “None”.
|
|
146
|
+
|
|
147
|
+
3. To specify a Change Date.
|
|
148
|
+
|
|
149
|
+
4. Not to modify this License in any other way.
|
package/dist/browser.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./types/bundleManifest.cjs"),t=require("./services/browserBundleVerifier/index.cjs"),n=require("./services/browserSealedChannel/index.cjs"),r=require("./services/sealedTransport/index.cjs");exports.ATTESTATION_TAG=e.ATTESTATION_TAG,exports.BUNDLE_MANIFEST_ROUTE=e.BUNDLE_MANIFEST_ROUTE,exports.BUNDLE_MANIFEST_VERSION=e.BUNDLE_MANIFEST_VERSION,exports.NATIVE_COMPOSITION_MAX_BYTES=e.NATIVE_COMPOSITION_MAX_BYTES,exports.NATIVE_ENTRY_CONTENT_TYPE=e.NATIVE_ENTRY_CONTENT_TYPE,exports.NATIVE_ENTRY_PATH=e.NATIVE_ENTRY_PATH,exports.WEB_ENTRY_PATH=e.WEB_ENTRY_PATH,exports.assetFor=e.assetFor,exports.attestationBytes=e.attestationBytes,exports.canonicalManifest=e.canonicalManifest,exports.channelFromSecret=n.channelFromSecret,exports.connectSealedChannel=n.connectSealedChannel,exports.createSealedTransport=r.createSealedTransport,exports.digestFor=e.digestFor,exports.isBundleManifest=e.isBundleManifest,exports.isSignedBundleManifest=e.isSignedBundleManifest,exports.sealedTransport=r.sealedTransport,exports.verifyAttestation=t.verifyAttestation,exports.verifyBundleAsset=t.verifyBundleAsset,exports.verifySignedBundleManifest=t.verifySignedBundleManifest;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./types/bundleManifest.cjs"),t=require("./services/browserBundleVerifier/index.cjs"),n=require("./services/browserSealedChannel/index.cjs"),r=require("./services/sealedTransport/index.cjs");exports.APP_ASSET_MAX_BYTES=e.APP_ASSET_MAX_BYTES,exports.APP_DESCRIPTOR_PATH=e.APP_DESCRIPTOR_PATH,exports.APP_PART_PREFIX=e.APP_PART_PREFIX,exports.ATTESTATION_TAG=e.ATTESTATION_TAG,exports.BUNDLE_MANIFEST_ROUTE=e.BUNDLE_MANIFEST_ROUTE,exports.BUNDLE_MANIFEST_VERSION=e.BUNDLE_MANIFEST_VERSION,exports.NATIVE_COMPOSITION_MAX_BYTES=e.NATIVE_COMPOSITION_MAX_BYTES,exports.NATIVE_ENTRY_CONTENT_TYPE=e.NATIVE_ENTRY_CONTENT_TYPE,exports.NATIVE_ENTRY_PATH=e.NATIVE_ENTRY_PATH,exports.WEB_ENTRY_PATH=e.WEB_ENTRY_PATH,exports.assetFor=e.assetFor,exports.attestationBytes=e.attestationBytes,exports.canonicalManifest=e.canonicalManifest,exports.channelFromSecret=n.channelFromSecret,exports.connectSealedChannel=n.connectSealedChannel,exports.createSealedTransport=r.createSealedTransport,exports.digestFor=e.digestFor,exports.isBundleManifest=e.isBundleManifest,exports.isSignedBundleManifest=e.isSignedBundleManifest,exports.sealedTransport=r.sealedTransport,exports.verifyAttestation=t.verifyAttestation,exports.verifyBundleAsset=t.verifyBundleAsset,exports.verifySignedBundleManifest=t.verifySignedBundleManifest;
|
package/dist/browser.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ATTESTATION_TAG, BUNDLE_MANIFEST_ROUTE, BUNDLE_MANIFEST_VERSION, BundleAsset, BundleManifest, BundleProfile, NATIVE_COMPOSITION_MAX_BYTES, NATIVE_ENTRY_CONTENT_TYPE, NATIVE_ENTRY_PATH, SignedBundleManifest, WEB_ENTRY_PATH, assetFor, attestationBytes, canonicalManifest, digestFor, isBundleManifest, isSignedBundleManifest } from "./types/bundleManifest.mjs";
|
|
1
|
+
import { APP_ASSET_MAX_BYTES, APP_DESCRIPTOR_PATH, APP_PART_PREFIX, ATTESTATION_TAG, BUNDLE_MANIFEST_ROUTE, BUNDLE_MANIFEST_VERSION, BundleAsset, BundleManifest, BundleProfile, NATIVE_COMPOSITION_MAX_BYTES, NATIVE_ENTRY_CONTENT_TYPE, NATIVE_ENTRY_PATH, SignedBundleManifest, WEB_ENTRY_PATH, assetFor, attestationBytes, canonicalManifest, digestFor, isBundleManifest, isSignedBundleManifest } from "./types/bundleManifest.mjs";
|
|
2
2
|
import { BundleAssetVerificationFailure, BundleAssetVerificationResult, BundleVerificationFailure, BundleVerificationResult, verifyAttestation, verifyBundleAsset, verifySignedBundleManifest } from "./services/browserBundleVerifier/index.mjs";
|
|
3
3
|
import { OpenResult, SealResult, SealedChannel, channelFromSecret, connectSealedChannel } from "./services/browserSealedChannel/index.mjs";
|
|
4
4
|
import { SealedTransport, createSealedTransport, sealedTransport } from "./services/sealedTransport/index.mjs";
|
|
5
|
-
export { ATTESTATION_TAG, BUNDLE_MANIFEST_ROUTE, BUNDLE_MANIFEST_VERSION, type BundleAsset, type BundleAssetVerificationFailure, type BundleAssetVerificationResult, type BundleManifest, type BundleProfile, type BundleVerificationFailure, type BundleVerificationResult, NATIVE_COMPOSITION_MAX_BYTES, NATIVE_ENTRY_CONTENT_TYPE, NATIVE_ENTRY_PATH, type OpenResult, type SealResult, type SealedChannel, type SealedTransport, type SignedBundleManifest, WEB_ENTRY_PATH, assetFor, attestationBytes, canonicalManifest, channelFromSecret, connectSealedChannel, createSealedTransport, digestFor, isBundleManifest, isSignedBundleManifest, sealedTransport, verifyAttestation, verifyBundleAsset, verifySignedBundleManifest };
|
|
5
|
+
export { APP_ASSET_MAX_BYTES, APP_DESCRIPTOR_PATH, APP_PART_PREFIX, ATTESTATION_TAG, BUNDLE_MANIFEST_ROUTE, BUNDLE_MANIFEST_VERSION, type BundleAsset, type BundleAssetVerificationFailure, type BundleAssetVerificationResult, type BundleManifest, type BundleProfile, type BundleVerificationFailure, type BundleVerificationResult, NATIVE_COMPOSITION_MAX_BYTES, NATIVE_ENTRY_CONTENT_TYPE, NATIVE_ENTRY_PATH, type OpenResult, type SealResult, type SealedChannel, type SealedTransport, type SignedBundleManifest, WEB_ENTRY_PATH, assetFor, attestationBytes, canonicalManifest, channelFromSecret, connectSealedChannel, createSealedTransport, digestFor, isBundleManifest, isSignedBundleManifest, sealedTransport, verifyAttestation, verifyBundleAsset, verifySignedBundleManifest };
|
package/dist/browser.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{APP_ASSET_MAX_BYTES as e,APP_DESCRIPTOR_PATH as t,APP_PART_PREFIX as n,ATTESTATION_TAG as r,BUNDLE_MANIFEST_ROUTE as i,BUNDLE_MANIFEST_VERSION as a,NATIVE_COMPOSITION_MAX_BYTES as o,NATIVE_ENTRY_CONTENT_TYPE as s,NATIVE_ENTRY_PATH as c,WEB_ENTRY_PATH as l,assetFor as u,attestationBytes as d,canonicalManifest as f,digestFor as p,isBundleManifest as m,isSignedBundleManifest as h}from"./types/bundleManifest.mjs";import{verifyAttestation as g,verifyBundleAsset as _,verifySignedBundleManifest as v}from"./services/browserBundleVerifier/index.mjs";import{channelFromSecret as y,connectSealedChannel as b}from"./services/browserSealedChannel/index.mjs";import{createSealedTransport as x,sealedTransport as S}from"./services/sealedTransport/index.mjs";export{e as APP_ASSET_MAX_BYTES,t as APP_DESCRIPTOR_PATH,n as APP_PART_PREFIX,r as ATTESTATION_TAG,i as BUNDLE_MANIFEST_ROUTE,a as BUNDLE_MANIFEST_VERSION,o as NATIVE_COMPOSITION_MAX_BYTES,s as NATIVE_ENTRY_CONTENT_TYPE,c as NATIVE_ENTRY_PATH,l as WEB_ENTRY_PATH,u as assetFor,d as attestationBytes,f as canonicalManifest,y as channelFromSecret,b as connectSealedChannel,x as createSealedTransport,p as digestFor,m as isBundleManifest,h as isSignedBundleManifest,S as sealedTransport,g as verifyAttestation,_ as verifyBundleAsset,v as verifySignedBundleManifest};
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./types/bundleManifest.cjs"),t=require("./types/sealedChannel.cjs"),n=require("./services/serialQueue/index.cjs");exports.ATTESTATION_TAG=e.ATTESTATION_TAG,exports.BUNDLE_MANIFEST_ROUTE=e.BUNDLE_MANIFEST_ROUTE,exports.BUNDLE_MANIFEST_VERSION=e.BUNDLE_MANIFEST_VERSION,exports.CLIENT_TO_SERVER_INFO=t.CLIENT_TO_SERVER_INFO,exports.MAX_MESSAGES_PER_KEY=t.MAX_MESSAGES_PER_KEY,exports.NATIVE_COMPOSITION_MAX_BYTES=e.NATIVE_COMPOSITION_MAX_BYTES,exports.NATIVE_ENTRY_CONTENT_TYPE=e.NATIVE_ENTRY_CONTENT_TYPE,exports.NATIVE_ENTRY_PATH=e.NATIVE_ENTRY_PATH,exports.NONCE_BYTES=t.NONCE_BYTES,exports.NONCE_COUNTER_BYTES=t.NONCE_COUNTER_BYTES,exports.NONCE_PREFIX_BYTES=t.NONCE_PREFIX_BYTES,exports.SEALED_BODY_HEADER=t.SEALED_BODY_HEADER,exports.SEALED_CLIENT_KEY_HEADER=t.SEALED_CLIENT_KEY_HEADER,exports.SEALED_KEY_PARAM=t.SEALED_KEY_PARAM,exports.SEALED_VERSION=t.SEALED_VERSION,exports.SERVER_TO_CLIENT_INFO=t.SERVER_TO_CLIENT_INFO,exports.WEB_ENTRY_PATH=e.WEB_ENTRY_PATH,exports.assetFor=e.assetFor,exports.attestationBytes=e.attestationBytes,exports.canonicalManifest=e.canonicalManifest,exports.createSerialQueue=n.createSerialQueue,exports.describeSealedFailure=t.describeSealedFailure,exports.digestFor=e.digestFor,exports.infoFor=t.infoFor,exports.isBundleManifest=e.isBundleManifest,exports.isSealedEnvelope=t.isSealedEnvelope,exports.isSignedBundleManifest=e.isSignedBundleManifest;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./types/bundleManifest.cjs"),t=require("./types/sealedChannel.cjs"),n=require("./services/serialQueue/index.cjs");exports.APP_ASSET_MAX_BYTES=e.APP_ASSET_MAX_BYTES,exports.APP_DESCRIPTOR_PATH=e.APP_DESCRIPTOR_PATH,exports.APP_PART_PREFIX=e.APP_PART_PREFIX,exports.ATTESTATION_TAG=e.ATTESTATION_TAG,exports.BUNDLE_MANIFEST_ROUTE=e.BUNDLE_MANIFEST_ROUTE,exports.BUNDLE_MANIFEST_VERSION=e.BUNDLE_MANIFEST_VERSION,exports.CLIENT_TO_SERVER_INFO=t.CLIENT_TO_SERVER_INFO,exports.MAX_MESSAGES_PER_KEY=t.MAX_MESSAGES_PER_KEY,exports.NATIVE_COMPOSITION_MAX_BYTES=e.NATIVE_COMPOSITION_MAX_BYTES,exports.NATIVE_ENTRY_CONTENT_TYPE=e.NATIVE_ENTRY_CONTENT_TYPE,exports.NATIVE_ENTRY_PATH=e.NATIVE_ENTRY_PATH,exports.NONCE_BYTES=t.NONCE_BYTES,exports.NONCE_COUNTER_BYTES=t.NONCE_COUNTER_BYTES,exports.NONCE_PREFIX_BYTES=t.NONCE_PREFIX_BYTES,exports.SEALED_BODY_HEADER=t.SEALED_BODY_HEADER,exports.SEALED_CLIENT_KEY_HEADER=t.SEALED_CLIENT_KEY_HEADER,exports.SEALED_KEY_PARAM=t.SEALED_KEY_PARAM,exports.SEALED_VERSION=t.SEALED_VERSION,exports.SERVER_TO_CLIENT_INFO=t.SERVER_TO_CLIENT_INFO,exports.WEB_ENTRY_PATH=e.WEB_ENTRY_PATH,exports.assetFor=e.assetFor,exports.attestationBytes=e.attestationBytes,exports.canonicalManifest=e.canonicalManifest,exports.createSerialQueue=n.createSerialQueue,exports.describeSealedFailure=t.describeSealedFailure,exports.digestFor=e.digestFor,exports.infoFor=t.infoFor,exports.isBundleManifest=e.isBundleManifest,exports.isSealedEnvelope=t.isSealedEnvelope,exports.isSignedBundleManifest=e.isSignedBundleManifest;
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ATTESTATION_TAG, BUNDLE_MANIFEST_ROUTE, BUNDLE_MANIFEST_VERSION, BundleAsset, BundleManifest, BundleProfile, NATIVE_COMPOSITION_MAX_BYTES, NATIVE_ENTRY_CONTENT_TYPE, NATIVE_ENTRY_PATH, SignedBundleManifest, WEB_ENTRY_PATH, assetFor, attestationBytes, canonicalManifest, digestFor, isBundleManifest, isSignedBundleManifest } from "./types/bundleManifest.mjs";
|
|
1
|
+
import { APP_ASSET_MAX_BYTES, APP_DESCRIPTOR_PATH, APP_PART_PREFIX, ATTESTATION_TAG, BUNDLE_MANIFEST_ROUTE, BUNDLE_MANIFEST_VERSION, BundleAsset, BundleManifest, BundleProfile, NATIVE_COMPOSITION_MAX_BYTES, NATIVE_ENTRY_CONTENT_TYPE, NATIVE_ENTRY_PATH, SignedBundleManifest, WEB_ENTRY_PATH, assetFor, attestationBytes, canonicalManifest, digestFor, isBundleManifest, isSignedBundleManifest } from "./types/bundleManifest.mjs";
|
|
2
2
|
import { CLIENT_TO_SERVER_INFO, MAX_MESSAGES_PER_KEY, NONCE_BYTES, NONCE_COUNTER_BYTES, NONCE_PREFIX_BYTES, SEALED_BODY_HEADER, SEALED_CLIENT_KEY_HEADER, SEALED_KEY_PARAM, SEALED_VERSION, SERVER_TO_CLIENT_INFO, SealedDirection, SealedEnvelope, SealedFailure, describeSealedFailure, infoFor, isSealedEnvelope } from "./types/sealedChannel.mjs";
|
|
3
3
|
import { SerialQueue, createSerialQueue } from "./services/serialQueue/index.mjs";
|
|
4
|
-
export { ATTESTATION_TAG, BUNDLE_MANIFEST_ROUTE, BUNDLE_MANIFEST_VERSION, type BundleAsset, type BundleManifest, type BundleProfile, CLIENT_TO_SERVER_INFO, MAX_MESSAGES_PER_KEY, NATIVE_COMPOSITION_MAX_BYTES, NATIVE_ENTRY_CONTENT_TYPE, NATIVE_ENTRY_PATH, NONCE_BYTES, NONCE_COUNTER_BYTES, NONCE_PREFIX_BYTES, SEALED_BODY_HEADER, SEALED_CLIENT_KEY_HEADER, SEALED_KEY_PARAM, SEALED_VERSION, SERVER_TO_CLIENT_INFO, type SealedDirection, type SealedEnvelope, type SealedFailure, type SerialQueue, type SignedBundleManifest, WEB_ENTRY_PATH, assetFor, attestationBytes, canonicalManifest, createSerialQueue, describeSealedFailure, digestFor, infoFor, isBundleManifest, isSealedEnvelope, isSignedBundleManifest };
|
|
4
|
+
export { APP_ASSET_MAX_BYTES, APP_DESCRIPTOR_PATH, APP_PART_PREFIX, ATTESTATION_TAG, BUNDLE_MANIFEST_ROUTE, BUNDLE_MANIFEST_VERSION, type BundleAsset, type BundleManifest, type BundleProfile, CLIENT_TO_SERVER_INFO, MAX_MESSAGES_PER_KEY, NATIVE_COMPOSITION_MAX_BYTES, NATIVE_ENTRY_CONTENT_TYPE, NATIVE_ENTRY_PATH, NONCE_BYTES, NONCE_COUNTER_BYTES, NONCE_PREFIX_BYTES, SEALED_BODY_HEADER, SEALED_CLIENT_KEY_HEADER, SEALED_KEY_PARAM, SEALED_VERSION, SERVER_TO_CLIENT_INFO, type SealedDirection, type SealedEnvelope, type SealedFailure, type SerialQueue, type SignedBundleManifest, WEB_ENTRY_PATH, assetFor, attestationBytes, canonicalManifest, createSerialQueue, describeSealedFailure, digestFor, infoFor, isBundleManifest, isSealedEnvelope, isSignedBundleManifest };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{APP_ASSET_MAX_BYTES as e,APP_DESCRIPTOR_PATH as t,APP_PART_PREFIX as n,ATTESTATION_TAG as r,BUNDLE_MANIFEST_ROUTE as i,BUNDLE_MANIFEST_VERSION as a,NATIVE_COMPOSITION_MAX_BYTES as o,NATIVE_ENTRY_CONTENT_TYPE as s,NATIVE_ENTRY_PATH as c,WEB_ENTRY_PATH as l,assetFor as u,attestationBytes as d,canonicalManifest as f,digestFor as p,isBundleManifest as m,isSignedBundleManifest as h}from"./types/bundleManifest.mjs";import{CLIENT_TO_SERVER_INFO as g,MAX_MESSAGES_PER_KEY as _,NONCE_BYTES as v,NONCE_COUNTER_BYTES as y,NONCE_PREFIX_BYTES as b,SEALED_BODY_HEADER as x,SEALED_CLIENT_KEY_HEADER as S,SEALED_KEY_PARAM as C,SEALED_VERSION as w,SERVER_TO_CLIENT_INFO as T,describeSealedFailure as E,infoFor as D,isSealedEnvelope as O}from"./types/sealedChannel.mjs";import{createSerialQueue as k}from"./services/serialQueue/index.mjs";export{e as APP_ASSET_MAX_BYTES,t as APP_DESCRIPTOR_PATH,n as APP_PART_PREFIX,r as ATTESTATION_TAG,i as BUNDLE_MANIFEST_ROUTE,a as BUNDLE_MANIFEST_VERSION,g as CLIENT_TO_SERVER_INFO,_ as MAX_MESSAGES_PER_KEY,o as NATIVE_COMPOSITION_MAX_BYTES,s as NATIVE_ENTRY_CONTENT_TYPE,c as NATIVE_ENTRY_PATH,v as NONCE_BYTES,y as NONCE_COUNTER_BYTES,b as NONCE_PREFIX_BYTES,x as SEALED_BODY_HEADER,S as SEALED_CLIENT_KEY_HEADER,C as SEALED_KEY_PARAM,w as SEALED_VERSION,T as SERVER_TO_CLIENT_INFO,l as WEB_ENTRY_PATH,u as assetFor,d as attestationBytes,f as canonicalManifest,k as createSerialQueue,E as describeSealedFailure,p as digestFor,D as infoFor,m as isBundleManifest,O as isSealedEnvelope,h as isSignedBundleManifest};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../../types/sealedChannel.cjs"),t={name:`ECDH`,namedCurve:`P-256`},n=`AES-GCM`;function r(e){let t;try{t=atob(e.replaceAll(`-`,`+`).replaceAll(`_`,`/`))}catch{return}let n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function i(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replaceAll(`=`,``)}function a(e){let t=new Uint8Array(new ArrayBuffer(e.length));return t.set(e),t.buffer}async function o(t,r){let i=await crypto.subtle.importKey(`raw`,t,`HKDF`,!1,[`deriveKey`]);return await crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:a(new TextEncoder().encode(`po/sealed/v1`)),info:a(new TextEncoder().encode(e.infoFor(r)))},i,{name:n,length:256},!1,[`encrypt`,`decrypt`])}function s(e,t){let n=/* @__PURE__ */ new Uint8Array(12);return n.set(e.subarray(0,4),0),new DataView(n.buffer).setBigUint64(4,t,!1),n}function c(t,o,c){let l=0n,u=-1n;return{async seal(r){if(l>=BigInt(e.MAX_MESSAGES_PER_KEY))return{ok:!1,failure:`exhausted`};let o=s(c,l),u=await crypto.subtle.encrypt({name:n,iv:a(o),tagLength:128},t,a(r));return l+=1n,{ok:!0,envelope:{v:1,n:i(o),c:i(new Uint8Array(u))}}},async open(t){let i=t;if(typeof i?.n!=`string`||typeof i.c!=`string`)return{ok:!1,failure:`malformed`};if(i.v!==1)return{ok:!1,failure:`version`};if(!e.isSealedEnvelope(t))return{ok:!1,failure:`malformed`};let s=r(t.n),c=r(t.c);if(s===void 0||c===void 0||s.length!==12||c.length<16)return{ok:!1,failure:`malformed`};let l=new DataView(a(s)).getBigUint64(4,!1);if(l<=u)return{ok:!1,failure:`replay`};let d;try{d=await crypto.subtle.decrypt({name:n,iv:a(s),tagLength:128},o,a(c))}catch{return{ok:!1,failure:`auth`}}return u=l,{ok:!0,plaintext:new Uint8Array(d)}}}}async function l(e){if(globalThis.crypto?.subtle!==void 0)try{let n=await crypto.subtle.generateKey(t,!1,[`deriveBits`]),s=r(e);if(s===void 0)return;let l=await crypto.subtle.importKey(`raw`,a(s),t,!1,[]),u=await crypto.subtle.deriveBits({name:`ECDH`,public:l},n.privateKey,256),d=i(new Uint8Array(await crypto.subtle.exportKey(`raw`,n.publicKey)));return{channel:c(await o(u,`c2s`),await o(u,`s2c`),/* @__PURE__ */ new Uint8Array(4)),clientPublicKey:d}}catch{return}}async function u(e,t,n){return c(await o(e,t),await o(e,t===`c2s`?`s2c`:`c2s`),n)}exports.channelFromSecret=u,exports.connectSealedChannel=l;
|
|
1
|
+
const e=require("../../types/sealedChannel.cjs"),t={name:`ECDH`,namedCurve:`P-256`},n=`AES-GCM`;function r(e){let t;try{t=atob(e.replaceAll(`-`,`+`).replaceAll(`_`,`/`))}catch{return}let n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function i(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replaceAll(`=`,``)}function a(e){let t=new Uint8Array(new ArrayBuffer(e.length));return t.set(e),t.buffer}async function o(t,r){let i=await crypto.subtle.importKey(`raw`,t,`HKDF`,!1,[`deriveKey`]);return await crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:a(new TextEncoder().encode(`po/sealed/v1`)),info:a(new TextEncoder().encode(e.infoFor(r)))},i,{name:n,length:256},!1,[`encrypt`,`decrypt`])}function s(e,t){let n=/* @__PURE__ */ new Uint8Array(12);return n.set(e.subarray(0,4),0),new DataView(n.buffer).setBigUint64(4,t,!1),n}function c(t,o,c){let l=0n,u=-1n;return{async seal(r){if(l>=BigInt(e.MAX_MESSAGES_PER_KEY))return{ok:!1,failure:`exhausted`};let o=s(c,l),u=await crypto.subtle.encrypt({name:n,iv:a(o),tagLength:128},t,a(r));return l+=1n,{ok:!0,envelope:{v:1,n:i(o),c:i(new Uint8Array(u))}}},async open(t){let i=t;if(typeof i?.n!=`string`||typeof i.c!=`string`)return{ok:!1,failure:`malformed`};if(i.v!==1)return{ok:!1,failure:`version`};if(!e.isSealedEnvelope(t))return{ok:!1,failure:`malformed`};let s=r(t.n),c=r(t.c);if(s===void 0||c===void 0||s.length!==12||c.length<16)return{ok:!1,failure:`malformed`};let l=new DataView(a(s)).getBigUint64(4,!1);if(l<=u)return{ok:!1,failure:`replay`};let d;try{d=await crypto.subtle.decrypt({name:n,iv:a(s),tagLength:128},o,a(c))}catch{return{ok:!1,failure:`auth`}}return l<=u?{ok:!1,failure:`replay`}:(u=l,{ok:!0,plaintext:new Uint8Array(d)})}}}async function l(e){if(globalThis.crypto?.subtle!==void 0)try{let n=await crypto.subtle.generateKey(t,!1,[`deriveBits`]),s=r(e);if(s===void 0)return;let l=await crypto.subtle.importKey(`raw`,a(s),t,!1,[]),u=await crypto.subtle.deriveBits({name:`ECDH`,public:l},n.privateKey,256),d=i(new Uint8Array(await crypto.subtle.exportKey(`raw`,n.publicKey)));return{channel:c(await o(u,`c2s`),await o(u,`s2c`),/* @__PURE__ */ new Uint8Array(4)),clientPublicKey:d}}catch{return}}async function u(e,t,n){return c(await o(e,t),await o(e,t===`c2s`?`s2c`:`c2s`),n)}exports.channelFromSecret=u,exports.connectSealedChannel=l;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["infoFor","MAX_MESSAGES_PER_KEY","isSealedEnvelope","require_sealedChannel","KEY_ALGORITHM","CIPHER","bytes","binary","value","out","index","base64Url","byte","view","copy","derive","material","secret","direction","nonceFor","nonce","prefix","counter","channelFrom","sendCounter","highestReceived","noncePrefix","sealed","sendKey","plaintext","shape","envelope","body","receiveKey","connectSealedChannel","pair","hostKey","hostPublicKey","peer","clientPublicKey","channelFromSecret","sendDirection"],"sources":["../../../src/services/browserSealedChannel/index.ts"],"sourcesContent":["import {\n MAX_MESSAGES_PER_KEY,\n NONCE_BYTES,\n NONCE_PREFIX_BYTES,\n SEALED_VERSION,\n type SealedDirection,\n type SealedEnvelope,\n type SealedFailure,\n infoFor,\n isSealedEnvelope,\n} from '../../types/sealedChannel';\n\n/**\n * The browser half of the sealed channel.\n *\n * Mirrors `nodeSealedChannel.ts` exactly, on WebCrypto instead of\n * `node:crypto`. Two implementations rather than one because a shared one would\n * drag node builtins into every browser bundle that imports it, and this\n * package is imported by plugins that ship to the page. The envelope contract\n * they both read lives in `../types/sealedChannel.ts`, and a round-trip test\n * pins the two together so they cannot drift.\n */\n\nconst KEY_ALGORITHM = { name: 'ECDH', namedCurve: 'P-256' } as const;\nconst CIPHER = 'AES-GCM';\nconst KEY_BITS = 256;\nconst TAG_BITS = 128;\nconst TAG_BYTES = 16;\nconst HKDF_SALT = 'po/sealed/v1';\n\nexport type SealResult = { ok: true; envelope: SealedEnvelope } | { ok: false; failure: SealedFailure };\nexport type OpenResult = { ok: true; plaintext: Uint8Array } | { ok: false; failure: SealedFailure };\n\nexport interface SealedChannel {\n seal(plaintext: Uint8Array): Promise<SealResult>;\n open(envelope: unknown): Promise<OpenResult>;\n}\n\n/** Undefined rather than a throw: a malformed field is a verdict, not an exception. */\nfunction bytes(value: string): Uint8Array | undefined {\n let binary: string;\n try {\n binary = atob(value.replaceAll('-', '+').replaceAll('_', '/'));\n } catch {\n return undefined;\n }\n const out = new Uint8Array(new ArrayBuffer(binary.length));\n for (let index = 0; index < binary.length; index += 1) out[index] = binary.charCodeAt(index);\n return out;\n}\n\nfunction base64Url(value: Uint8Array): string {\n let binary = '';\n for (const byte of value) binary += String.fromCharCode(byte);\n return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');\n}\n\nfunction view(value: Uint8Array): ArrayBuffer {\n const copy = new Uint8Array(new ArrayBuffer(value.length));\n copy.set(value);\n return copy.buffer;\n}\n\nasync function derive(secret: ArrayBuffer, direction: SealedDirection): Promise<CryptoKey> {\n const material = await crypto.subtle.importKey('raw', secret, 'HKDF', false, ['deriveKey']);\n return await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: view(new TextEncoder().encode(HKDF_SALT)),\n info: view(new TextEncoder().encode(infoFor(direction))),\n },\n material,\n { name: CIPHER, length: KEY_BITS },\n false,\n ['encrypt', 'decrypt'],\n );\n}\n\nfunction nonceFor(prefix: Uint8Array, counter: bigint): Uint8Array {\n const nonce = new Uint8Array(NONCE_BYTES);\n nonce.set(prefix.subarray(0, NONCE_PREFIX_BYTES), 0);\n new DataView(nonce.buffer).setBigUint64(NONCE_PREFIX_BYTES, counter, false);\n return nonce;\n}\n\nfunction channelFrom(sendKey: CryptoKey, receiveKey: CryptoKey, noncePrefix: Uint8Array): SealedChannel {\n let sendCounter = 0n;\n let highestReceived = -1n;\n\n return {\n async seal(plaintext) {\n if (sendCounter >= BigInt(MAX_MESSAGES_PER_KEY)) return { ok: false, failure: 'exhausted' };\n const nonce = nonceFor(noncePrefix, sendCounter);\n const sealed = await crypto.subtle.encrypt(\n { name: CIPHER, iv: view(nonce), tagLength: TAG_BITS },\n sendKey,\n view(plaintext),\n );\n sendCounter += 1n;\n return {\n ok: true,\n envelope: { v: SEALED_VERSION, n: base64Url(nonce), c: base64Url(new Uint8Array(sealed)) },\n };\n },\n\n async open(envelope) {\n // Shape before version, matching the server: something with no `v` at all\n // is malformed rather than a protocol skew.\n const shape = envelope as { v?: unknown; n?: unknown; c?: unknown } | null | undefined;\n if (typeof shape?.n !== 'string' || typeof shape.c !== 'string') return { ok: false, failure: 'malformed' };\n if (shape.v !== SEALED_VERSION) return { ok: false, failure: 'version' };\n if (!isSealedEnvelope(envelope)) return { ok: false, failure: 'malformed' };\n const nonce = bytes(envelope.n);\n const body = bytes(envelope.c);\n if (nonce === undefined || body === undefined) return { ok: false, failure: 'malformed' };\n if (nonce.length !== NONCE_BYTES || body.length < TAG_BYTES) return { ok: false, failure: 'malformed' };\n const counter = new DataView(view(nonce)).getBigUint64(NONCE_PREFIX_BYTES, false);\n if (counter <= highestReceived) return { ok: false, failure: 'replay' };\n let plaintext: ArrayBuffer;\n try {\n plaintext = await crypto.subtle.decrypt(\n { name: CIPHER, iv: view(nonce), tagLength: TAG_BITS },\n receiveKey,\n view(body),\n );\n } catch {\n // A failed tag means the message was altered in transit; there is no\n // partial result worth salvaging.\n return { ok: false, failure: 'auth' };\n }\n // Only after the tag verified, so a forged high counter cannot lock out\n // every message that legitimately follows it.\n highestReceived = counter;\n return { ok: true, plaintext: new Uint8Array(plaintext) };\n },\n };\n}\n\n/**\n * Completes the handshake against the host key read out of the QR fragment.\n *\n * That key never travelled through the tunnel, which is what makes this\n * authenticated: a relay can watch the client's public key go past and learn\n * nothing, and it cannot substitute the host's because it never carried it.\n */\nexport async function connectSealedChannel(\n hostPublicKey: string,\n): Promise<{ channel: SealedChannel; clientPublicKey: string } | undefined> {\n if (globalThis.crypto?.subtle === undefined) return undefined;\n try {\n const pair = await crypto.subtle.generateKey(KEY_ALGORITHM, false, ['deriveBits']);\n const hostKey = bytes(hostPublicKey);\n if (hostKey === undefined) return undefined;\n const peer = await crypto.subtle.importKey('raw', view(hostKey), KEY_ALGORITHM, false, []);\n const secret = await crypto.subtle.deriveBits({ name: 'ECDH', public: peer }, pair.privateKey, KEY_BITS);\n const clientPublicKey = base64Url(new Uint8Array(await crypto.subtle.exportKey('raw', pair.publicKey)));\n return {\n channel: channelFrom(\n await derive(secret, 'c2s'),\n await derive(secret, 's2c'),\n new Uint8Array(NONCE_PREFIX_BYTES),\n ),\n clientPublicKey,\n };\n } catch {\n // A malformed host key or a context without ECDH; the caller falls back to\n // an unsealed channel and says so rather than failing silently.\n return undefined;\n }\n}\n\n/** Exposed so a test can build the browser side against a known secret. */\nexport async function channelFromSecret(\n secret: ArrayBuffer,\n sendDirection: SealedDirection,\n noncePrefix: Uint8Array,\n): Promise<SealedChannel> {\n const send = await derive(secret, sendDirection);\n const receive = await derive(secret, sendDirection === 'c2s' ? 's2c' : 'c2s');\n return channelFrom(send, receive, noncePrefix);\n}\n"],"mappings":"iDAuBMI,EAAgB,CAAE,KAAM,OAAQ,WAAY,OAAQ,EACpDC,EAAS,UAef,SAASC,EAAM,EAAuC,CACpD,IAAIC,EACJ,GAAI,CACF,EAAS,KAAKC,EAAM,WAAW,IAAK,GAAG,CAAC,CAAC,WAAW,IAAK,GAAG,CAAC,CAC/D,MAAQ,CACN,MACF,CACA,IAAMC,EAAM,IAAI,WAAW,IAAI,YAAYF,EAAO,MAAM,CAAC,EACzD,IAAK,IAAIG,EAAQ,EAAGA,EAAQH,EAAO,OAAQ,GAAS,EAAG,EAAIG,GAASH,EAAO,WAAWG,CAAK,EAC3F,OAAOD,CACT,CAEA,SAASE,EAAU,EAA2B,CAC5C,IAAIJ,EAAS,GACb,IAAK,IAAMK,KAAQJ,EAAO,GAAU,OAAO,aAAaI,CAAI,EAC5D,OAAO,KAAKL,CAAM,CAAC,CAAC,WAAW,IAAK,GAAG,CAAC,CAAC,WAAW,IAAK,GAAG,CAAC,CAAC,WAAW,IAAK,EAAE,CAClF,CAEA,SAASM,EAAK,EAAgC,CAC5C,IAAMC,EAAO,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AU,MAAOzB,EAAKuB,CAAO,EAAGhC,EAAe,GAAO,CAAC,CAAC,EACnFa,EAAS,MAAM,OAAO,OAAO,WAAW,CAAE,KAAM,OAAQ,OAAQqB,CAAK,EAAGH,EAAK,WAAY,GAAQ,EACjGI,EAAkB5B,EAAU,IAAI,WAAW,MAAM,OAAO,OAAO,UAAU,MAAOwB,EAAK,SAAS,CAAC,CAAC,EACtG,MAAO,CACL,QAASZ,EACP,MAAMR,EAAOE,EAAQ,KAAK,EAC1B,MAAMF,EAAOE,EAAQ,KAAK,kBAC1B,IAAI,WAAA,CAA6B,CACnC,EACA,iBACF,CACF,MAAQ,CAGN,MACF,CACF,CAGA,eAAsBuB,EACpB,EACA,EACA,EACwB,CAGxB,OAAOjB,EAAY,MAFAR,EAAOE,EAAQwB,CAAa,EAEtB,MADH1B,EAAOE,EAAQwB,IAAkB,MAAQ,MAAQ,KAAK,EAC1Cf,CAAW,CAC/C"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["infoFor","MAX_MESSAGES_PER_KEY","isSealedEnvelope","require_sealedChannel","KEY_ALGORITHM","CIPHER","bytes","binary","value","out","index","base64Url","byte","view","copy","derive","material","secret","direction","nonceFor","nonce","prefix","counter","channelFrom","sendCounter","highestReceived","noncePrefix","sealed","sendKey","plaintext","shape","envelope","body","receiveKey","connectSealedChannel","pair","hostKey","hostPublicKey","peer","clientPublicKey","channelFromSecret","sendDirection"],"sources":["../../../src/services/browserSealedChannel/index.ts"],"sourcesContent":["import {\n MAX_MESSAGES_PER_KEY,\n NONCE_BYTES,\n NONCE_PREFIX_BYTES,\n SEALED_VERSION,\n type SealedDirection,\n type SealedEnvelope,\n type SealedFailure,\n infoFor,\n isSealedEnvelope,\n} from '../../types/sealedChannel';\n\n/**\n * The browser half of the sealed channel.\n *\n * Mirrors `nodeSealedChannel.ts` exactly, on WebCrypto instead of\n * `node:crypto`. Two implementations rather than one because a shared one would\n * drag node builtins into every browser bundle that imports it, and this\n * package is imported by plugins that ship to the page. The envelope contract\n * they both read lives in `../types/sealedChannel.ts`, and a round-trip test\n * pins the two together so they cannot drift.\n */\n\nconst KEY_ALGORITHM = { name: 'ECDH', namedCurve: 'P-256' } as const;\nconst CIPHER = 'AES-GCM';\nconst KEY_BITS = 256;\nconst TAG_BITS = 128;\nconst TAG_BYTES = 16;\nconst HKDF_SALT = 'po/sealed/v1';\n\nexport type SealResult = { ok: true; envelope: SealedEnvelope } | { ok: false; failure: SealedFailure };\nexport type OpenResult = { ok: true; plaintext: Uint8Array } | { ok: false; failure: SealedFailure };\n\nexport interface SealedChannel {\n seal(plaintext: Uint8Array): Promise<SealResult>;\n open(envelope: unknown): Promise<OpenResult>;\n}\n\n/** Undefined rather than a throw: a malformed field is a verdict, not an exception. */\nfunction bytes(value: string): Uint8Array | undefined {\n let binary: string;\n try {\n binary = atob(value.replaceAll('-', '+').replaceAll('_', '/'));\n } catch {\n return undefined;\n }\n const out = new Uint8Array(new ArrayBuffer(binary.length));\n for (let index = 0; index < binary.length; index += 1) out[index] = binary.charCodeAt(index);\n return out;\n}\n\nfunction base64Url(value: Uint8Array): string {\n let binary = '';\n for (const byte of value) binary += String.fromCharCode(byte);\n return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');\n}\n\nfunction view(value: Uint8Array): ArrayBuffer {\n const copy = new Uint8Array(new ArrayBuffer(value.length));\n copy.set(value);\n return copy.buffer;\n}\n\nasync function derive(secret: ArrayBuffer, direction: SealedDirection): Promise<CryptoKey> {\n const material = await crypto.subtle.importKey('raw', secret, 'HKDF', false, ['deriveKey']);\n return await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: view(new TextEncoder().encode(HKDF_SALT)),\n info: view(new TextEncoder().encode(infoFor(direction))),\n },\n material,\n { name: CIPHER, length: KEY_BITS },\n false,\n ['encrypt', 'decrypt'],\n );\n}\n\nfunction nonceFor(prefix: Uint8Array, counter: bigint): Uint8Array {\n const nonce = new Uint8Array(NONCE_BYTES);\n nonce.set(prefix.subarray(0, NONCE_PREFIX_BYTES), 0);\n new DataView(nonce.buffer).setBigUint64(NONCE_PREFIX_BYTES, counter, false);\n return nonce;\n}\n\nfunction channelFrom(sendKey: CryptoKey, receiveKey: CryptoKey, noncePrefix: Uint8Array): SealedChannel {\n let sendCounter = 0n;\n let highestReceived = -1n;\n\n return {\n async seal(plaintext) {\n if (sendCounter >= BigInt(MAX_MESSAGES_PER_KEY)) return { ok: false, failure: 'exhausted' };\n const nonce = nonceFor(noncePrefix, sendCounter);\n const sealed = await crypto.subtle.encrypt(\n { name: CIPHER, iv: view(nonce), tagLength: TAG_BITS },\n sendKey,\n view(plaintext),\n );\n sendCounter += 1n;\n return {\n ok: true,\n envelope: { v: SEALED_VERSION, n: base64Url(nonce), c: base64Url(new Uint8Array(sealed)) },\n };\n },\n\n async open(envelope) {\n // Shape before version, matching the server: something with no `v` at all\n // is malformed rather than a protocol skew.\n const shape = envelope as { v?: unknown; n?: unknown; c?: unknown } | null | undefined;\n if (typeof shape?.n !== 'string' || typeof shape.c !== 'string') return { ok: false, failure: 'malformed' };\n if (shape.v !== SEALED_VERSION) return { ok: false, failure: 'version' };\n if (!isSealedEnvelope(envelope)) return { ok: false, failure: 'malformed' };\n const nonce = bytes(envelope.n);\n const body = bytes(envelope.c);\n if (nonce === undefined || body === undefined) return { ok: false, failure: 'malformed' };\n if (nonce.length !== NONCE_BYTES || body.length < TAG_BYTES) return { ok: false, failure: 'malformed' };\n const counter = new DataView(view(nonce)).getBigUint64(NONCE_PREFIX_BYTES, false);\n if (counter <= highestReceived) return { ok: false, failure: 'replay' };\n let plaintext: ArrayBuffer;\n try {\n plaintext = await crypto.subtle.decrypt(\n { name: CIPHER, iv: view(nonce), tagLength: TAG_BITS },\n receiveKey,\n view(body),\n );\n } catch {\n // A failed tag means the message was altered in transit; there is no\n // partial result worth salvaging.\n return { ok: false, failure: 'auth' };\n }\n // Another open may have finished while decrypt was pending, including\n // after its caller aborted. Never lower the authenticated high-water mark.\n if (counter <= highestReceived) return { ok: false, failure: 'replay' };\n // Only after the tag verified, so a forged high counter cannot lock out\n // every message that legitimately follows it. Keep the recheck and commit synchronous.\n highestReceived = counter;\n return { ok: true, plaintext: new Uint8Array(plaintext) };\n },\n };\n}\n\n/**\n * Completes the handshake against the host key read out of the QR fragment.\n *\n * That key never travelled through the tunnel, which is what makes this\n * authenticated: a relay can watch the client's public key go past and learn\n * nothing, and it cannot substitute the host's because it never carried it.\n */\nexport async function connectSealedChannel(\n hostPublicKey: string,\n): Promise<{ channel: SealedChannel; clientPublicKey: string } | undefined> {\n if (globalThis.crypto?.subtle === undefined) return undefined;\n try {\n const pair = await crypto.subtle.generateKey(KEY_ALGORITHM, false, ['deriveBits']);\n const hostKey = bytes(hostPublicKey);\n if (hostKey === undefined) return undefined;\n const peer = await crypto.subtle.importKey('raw', view(hostKey), KEY_ALGORITHM, false, []);\n const secret = await crypto.subtle.deriveBits({ name: 'ECDH', public: peer }, pair.privateKey, KEY_BITS);\n const clientPublicKey = base64Url(new Uint8Array(await crypto.subtle.exportKey('raw', pair.publicKey)));\n return {\n channel: channelFrom(\n await derive(secret, 'c2s'),\n await derive(secret, 's2c'),\n new Uint8Array(NONCE_PREFIX_BYTES),\n ),\n clientPublicKey,\n };\n } catch {\n // A malformed host key or a context without ECDH; the caller falls back to\n // an unsealed channel and says so rather than failing silently.\n return undefined;\n }\n}\n\n/** Exposed so a test can build the browser side against a known secret. */\nexport async function channelFromSecret(\n secret: ArrayBuffer,\n sendDirection: SealedDirection,\n noncePrefix: Uint8Array,\n): Promise<SealedChannel> {\n const send = await derive(secret, sendDirection);\n const receive = await derive(secret, sendDirection === 'c2s' ? 's2c' : 'c2s');\n return channelFrom(send, receive, noncePrefix);\n}\n"],"mappings":"iDAuBMI,EAAgB,CAAE,KAAM,OAAQ,WAAY,OAAQ,EACpDC,EAAS,UAef,SAASC,EAAM,EAAuC,CACpD,IAAIC,EACJ,GAAI,CACF,EAAS,KAAKC,EAAM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["../../../src/services/browserSealedChannel/index.ts"],"mappings":";;YA8BY;EAAe;EAAU,UAAU;;EAAqB;EAAW,SAAS;;YAC5E;EAAe;EAAU,WAAW;;EAAiB;EAAW,SAAS;;iBAEpE;EACf,KAAK,WAAW,aAAa,QAAQ;EACrC,KAAK,oBAAoB,QAAQ;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/browserSealedChannel/index.ts"],"mappings":";;YA8BY;EAAe;EAAU,UAAU;;EAAqB;EAAW,SAAS;;YAC5E;EAAe;EAAU,WAAW;;EAAiB;EAAW,SAAS;;iBAEpE;EACf,KAAK,WAAW,aAAa,QAAQ;EACrC,KAAK,oBAAoB,QAAQ;;;;;;;;;wBAkHb,qBACpB,wBACC;EAAU,SAAS;EAAe;;;wBAyBf,kBACpB,QAAQ,aACR,eAAe,iBACf,aAAa,aACZ,QAAQ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{MAX_MESSAGES_PER_KEY as e,infoFor as t,isSealedEnvelope as n}from"../../types/sealedChannel.mjs";const r={name:`ECDH`,namedCurve:`P-256`},i=`AES-GCM`;function a(e){let t;try{t=atob(e.replaceAll(`-`,`+`).replaceAll(`_`,`/`))}catch{return}let n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function o(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replaceAll(`=`,``)}function s(e){let t=new Uint8Array(new ArrayBuffer(e.length));return t.set(e),t.buffer}async function c(e,n){let r=await crypto.subtle.importKey(`raw`,e,`HKDF`,!1,[`deriveKey`]);return await crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:s(new TextEncoder().encode(`po/sealed/v1`)),info:s(new TextEncoder().encode(t(n)))},r,{name:i,length:256},!1,[`encrypt`,`decrypt`])}function l(e,t){let n=/* @__PURE__ */ new Uint8Array(12);return n.set(e.subarray(0,4),0),new DataView(n.buffer).setBigUint64(4,t,!1),n}function u(t,r,c){let u=0n,d=-1n;return{async seal(n){if(u>=BigInt(e))return{ok:!1,failure:`exhausted`};let r=l(c,u),a=await crypto.subtle.encrypt({name:i,iv:s(r),tagLength:128},t,s(n));return u+=1n,{ok:!0,envelope:{v:1,n:o(r),c:o(new Uint8Array(a))}}},async open(e){let t=e;if(typeof t?.n!=`string`||typeof t.c!=`string`)return{ok:!1,failure:`malformed`};if(t.v!==1)return{ok:!1,failure:`version`};if(!n(e))return{ok:!1,failure:`malformed`};let o=a(e.n),c=a(e.c);if(o===void 0||c===void 0||o.length!==12||c.length<16)return{ok:!1,failure:`malformed`};let l=new DataView(s(o)).getBigUint64(4,!1);if(l<=d)return{ok:!1,failure:`replay`};let u;try{u=await crypto.subtle.decrypt({name:i,iv:s(o),tagLength:128},r,s(c))}catch{return{ok:!1,failure:`auth`}}return d=l,{ok:!0,plaintext:new Uint8Array(u)}}}}async function d(e){if(globalThis.crypto?.subtle!==void 0)try{let t=await crypto.subtle.generateKey(r,!1,[`deriveBits`]),n=a(e);if(n===void 0)return;let i=await crypto.subtle.importKey(`raw`,s(n),r,!1,[]),l=await crypto.subtle.deriveBits({name:`ECDH`,public:i},t.privateKey,256),d=o(new Uint8Array(await crypto.subtle.exportKey(`raw`,t.publicKey)));return{channel:u(await c(l,`c2s`),await c(l,`s2c`),/* @__PURE__ */ new Uint8Array(4)),clientPublicKey:d}}catch{return}}async function f(e,t,n){return u(await c(e,t),await c(e,t===`c2s`?`s2c`:`c2s`),n)}export{f as channelFromSecret,d as connectSealedChannel};
|
|
1
|
+
import{MAX_MESSAGES_PER_KEY as e,infoFor as t,isSealedEnvelope as n}from"../../types/sealedChannel.mjs";const r={name:`ECDH`,namedCurve:`P-256`},i=`AES-GCM`;function a(e){let t;try{t=atob(e.replaceAll(`-`,`+`).replaceAll(`_`,`/`))}catch{return}let n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function o(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replaceAll(`=`,``)}function s(e){let t=new Uint8Array(new ArrayBuffer(e.length));return t.set(e),t.buffer}async function c(e,n){let r=await crypto.subtle.importKey(`raw`,e,`HKDF`,!1,[`deriveKey`]);return await crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:s(new TextEncoder().encode(`po/sealed/v1`)),info:s(new TextEncoder().encode(t(n)))},r,{name:i,length:256},!1,[`encrypt`,`decrypt`])}function l(e,t){let n=/* @__PURE__ */ new Uint8Array(12);return n.set(e.subarray(0,4),0),new DataView(n.buffer).setBigUint64(4,t,!1),n}function u(t,r,c){let u=0n,d=-1n;return{async seal(n){if(u>=BigInt(e))return{ok:!1,failure:`exhausted`};let r=l(c,u),a=await crypto.subtle.encrypt({name:i,iv:s(r),tagLength:128},t,s(n));return u+=1n,{ok:!0,envelope:{v:1,n:o(r),c:o(new Uint8Array(a))}}},async open(e){let t=e;if(typeof t?.n!=`string`||typeof t.c!=`string`)return{ok:!1,failure:`malformed`};if(t.v!==1)return{ok:!1,failure:`version`};if(!n(e))return{ok:!1,failure:`malformed`};let o=a(e.n),c=a(e.c);if(o===void 0||c===void 0||o.length!==12||c.length<16)return{ok:!1,failure:`malformed`};let l=new DataView(s(o)).getBigUint64(4,!1);if(l<=d)return{ok:!1,failure:`replay`};let u;try{u=await crypto.subtle.decrypt({name:i,iv:s(o),tagLength:128},r,s(c))}catch{return{ok:!1,failure:`auth`}}return l<=d?{ok:!1,failure:`replay`}:(d=l,{ok:!0,plaintext:new Uint8Array(u)})}}}async function d(e){if(globalThis.crypto?.subtle!==void 0)try{let t=await crypto.subtle.generateKey(r,!1,[`deriveBits`]),n=a(e);if(n===void 0)return;let i=await crypto.subtle.importKey(`raw`,s(n),r,!1,[]),l=await crypto.subtle.deriveBits({name:`ECDH`,public:i},t.privateKey,256),d=o(new Uint8Array(await crypto.subtle.exportKey(`raw`,t.publicKey)));return{channel:u(await c(l,`c2s`),await c(l,`s2c`),/* @__PURE__ */ new Uint8Array(4)),clientPublicKey:d}}catch{return}}async function f(e,t,n){return u(await c(e,t),await c(e,t===`c2s`?`s2c`:`c2s`),n)}export{f as channelFromSecret,d as connectSealedChannel};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["KEY_ALGORITHM","CIPHER","bytes","binary","value","out","index","base64Url","byte","view","copy","derive","material","secret","infoFor","direction","nonceFor","nonce","prefix","counter","channelFrom","sendCounter","highestReceived","MAX_MESSAGES_PER_KEY","noncePrefix","sealed","sendKey","plaintext","shape","envelope","isSealedEnvelope","body","receiveKey","connectSealedChannel","pair","hostKey","hostPublicKey","peer","clientPublicKey","channelFromSecret","sendDirection"],"sources":["../../../src/services/browserSealedChannel/index.ts"],"sourcesContent":["import {\n MAX_MESSAGES_PER_KEY,\n NONCE_BYTES,\n NONCE_PREFIX_BYTES,\n SEALED_VERSION,\n type SealedDirection,\n type SealedEnvelope,\n type SealedFailure,\n infoFor,\n isSealedEnvelope,\n} from '../../types/sealedChannel';\n\n/**\n * The browser half of the sealed channel.\n *\n * Mirrors `nodeSealedChannel.ts` exactly, on WebCrypto instead of\n * `node:crypto`. Two implementations rather than one because a shared one would\n * drag node builtins into every browser bundle that imports it, and this\n * package is imported by plugins that ship to the page. The envelope contract\n * they both read lives in `../types/sealedChannel.ts`, and a round-trip test\n * pins the two together so they cannot drift.\n */\n\nconst KEY_ALGORITHM = { name: 'ECDH', namedCurve: 'P-256' } as const;\nconst CIPHER = 'AES-GCM';\nconst KEY_BITS = 256;\nconst TAG_BITS = 128;\nconst TAG_BYTES = 16;\nconst HKDF_SALT = 'po/sealed/v1';\n\nexport type SealResult = { ok: true; envelope: SealedEnvelope } | { ok: false; failure: SealedFailure };\nexport type OpenResult = { ok: true; plaintext: Uint8Array } | { ok: false; failure: SealedFailure };\n\nexport interface SealedChannel {\n seal(plaintext: Uint8Array): Promise<SealResult>;\n open(envelope: unknown): Promise<OpenResult>;\n}\n\n/** Undefined rather than a throw: a malformed field is a verdict, not an exception. */\nfunction bytes(value: string): Uint8Array | undefined {\n let binary: string;\n try {\n binary = atob(value.replaceAll('-', '+').replaceAll('_', '/'));\n } catch {\n return undefined;\n }\n const out = new Uint8Array(new ArrayBuffer(binary.length));\n for (let index = 0; index < binary.length; index += 1) out[index] = binary.charCodeAt(index);\n return out;\n}\n\nfunction base64Url(value: Uint8Array): string {\n let binary = '';\n for (const byte of value) binary += String.fromCharCode(byte);\n return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');\n}\n\nfunction view(value: Uint8Array): ArrayBuffer {\n const copy = new Uint8Array(new ArrayBuffer(value.length));\n copy.set(value);\n return copy.buffer;\n}\n\nasync function derive(secret: ArrayBuffer, direction: SealedDirection): Promise<CryptoKey> {\n const material = await crypto.subtle.importKey('raw', secret, 'HKDF', false, ['deriveKey']);\n return await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: view(new TextEncoder().encode(HKDF_SALT)),\n info: view(new TextEncoder().encode(infoFor(direction))),\n },\n material,\n { name: CIPHER, length: KEY_BITS },\n false,\n ['encrypt', 'decrypt'],\n );\n}\n\nfunction nonceFor(prefix: Uint8Array, counter: bigint): Uint8Array {\n const nonce = new Uint8Array(NONCE_BYTES);\n nonce.set(prefix.subarray(0, NONCE_PREFIX_BYTES), 0);\n new DataView(nonce.buffer).setBigUint64(NONCE_PREFIX_BYTES, counter, false);\n return nonce;\n}\n\nfunction channelFrom(sendKey: CryptoKey, receiveKey: CryptoKey, noncePrefix: Uint8Array): SealedChannel {\n let sendCounter = 0n;\n let highestReceived = -1n;\n\n return {\n async seal(plaintext) {\n if (sendCounter >= BigInt(MAX_MESSAGES_PER_KEY)) return { ok: false, failure: 'exhausted' };\n const nonce = nonceFor(noncePrefix, sendCounter);\n const sealed = await crypto.subtle.encrypt(\n { name: CIPHER, iv: view(nonce), tagLength: TAG_BITS },\n sendKey,\n view(plaintext),\n );\n sendCounter += 1n;\n return {\n ok: true,\n envelope: { v: SEALED_VERSION, n: base64Url(nonce), c: base64Url(new Uint8Array(sealed)) },\n };\n },\n\n async open(envelope) {\n // Shape before version, matching the server: something with no `v` at all\n // is malformed rather than a protocol skew.\n const shape = envelope as { v?: unknown; n?: unknown; c?: unknown } | null | undefined;\n if (typeof shape?.n !== 'string' || typeof shape.c !== 'string') return { ok: false, failure: 'malformed' };\n if (shape.v !== SEALED_VERSION) return { ok: false, failure: 'version' };\n if (!isSealedEnvelope(envelope)) return { ok: false, failure: 'malformed' };\n const nonce = bytes(envelope.n);\n const body = bytes(envelope.c);\n if (nonce === undefined || body === undefined) return { ok: false, failure: 'malformed' };\n if (nonce.length !== NONCE_BYTES || body.length < TAG_BYTES) return { ok: false, failure: 'malformed' };\n const counter = new DataView(view(nonce)).getBigUint64(NONCE_PREFIX_BYTES, false);\n if (counter <= highestReceived) return { ok: false, failure: 'replay' };\n let plaintext: ArrayBuffer;\n try {\n plaintext = await crypto.subtle.decrypt(\n { name: CIPHER, iv: view(nonce), tagLength: TAG_BITS },\n receiveKey,\n view(body),\n );\n } catch {\n // A failed tag means the message was altered in transit; there is no\n // partial result worth salvaging.\n return { ok: false, failure: 'auth' };\n }\n // Only after the tag verified, so a forged high counter cannot lock out\n // every message that legitimately follows it.\n highestReceived = counter;\n return { ok: true, plaintext: new Uint8Array(plaintext) };\n },\n };\n}\n\n/**\n * Completes the handshake against the host key read out of the QR fragment.\n *\n * That key never travelled through the tunnel, which is what makes this\n * authenticated: a relay can watch the client's public key go past and learn\n * nothing, and it cannot substitute the host's because it never carried it.\n */\nexport async function connectSealedChannel(\n hostPublicKey: string,\n): Promise<{ channel: SealedChannel; clientPublicKey: string } | undefined> {\n if (globalThis.crypto?.subtle === undefined) return undefined;\n try {\n const pair = await crypto.subtle.generateKey(KEY_ALGORITHM, false, ['deriveBits']);\n const hostKey = bytes(hostPublicKey);\n if (hostKey === undefined) return undefined;\n const peer = await crypto.subtle.importKey('raw', view(hostKey), KEY_ALGORITHM, false, []);\n const secret = await crypto.subtle.deriveBits({ name: 'ECDH', public: peer }, pair.privateKey, KEY_BITS);\n const clientPublicKey = base64Url(new Uint8Array(await crypto.subtle.exportKey('raw', pair.publicKey)));\n return {\n channel: channelFrom(\n await derive(secret, 'c2s'),\n await derive(secret, 's2c'),\n new Uint8Array(NONCE_PREFIX_BYTES),\n ),\n clientPublicKey,\n };\n } catch {\n // A malformed host key or a context without ECDH; the caller falls back to\n // an unsealed channel and says so rather than failing silently.\n return undefined;\n }\n}\n\n/** Exposed so a test can build the browser side against a known secret. */\nexport async function channelFromSecret(\n secret: ArrayBuffer,\n sendDirection: SealedDirection,\n noncePrefix: Uint8Array,\n): Promise<SealedChannel> {\n const send = await derive(secret, sendDirection);\n const receive = await derive(secret, sendDirection === 'c2s' ? 's2c' : 'c2s');\n return channelFrom(send, receive, noncePrefix);\n}\n"],"mappings":"wGAuBA,MAAMA,EAAgB,CAAE,KAAM,OAAQ,WAAY,OAAQ,EACpDC,EAAS,UAef,SAASC,EAAM,EAAuC,CACpD,IAAIC,EACJ,GAAI,CACF,EAAS,KAAKC,EAAM,WAAW,IAAK,GAAG,CAAC,CAAC,WAAW,IAAK,GAAG,CAAC,CAC/D,MAAQ,CACN,MACF,CACA,IAAMC,EAAM,IAAI,WAAW,IAAI,YAAYF,EAAO,MAAM,CAAC,EACzD,IAAK,IAAIG,EAAQ,EAAGA,EAAQH,EAAO,OAAQ,GAAS,EAAG,EAAIG,GAASH,EAAO,WAAWG,CAAK,EAC3F,OAAOD,CACT,CAEA,SAASE,EAAU,EAA2B,CAC5C,IAAIJ,EAAS,GACb,IAAK,IAAMK,KAAQJ,EAAO,GAAU,OAAO,aAAaI,CAAI,EAC5D,OAAO,KAAKL,CAAM,CAAC,CAAC,WAAW,IAAK,GAAG,CAAC,CAAC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AMkC,CAAa,EACnC,GAAID,IAAY,IAAA,GAAW,OAC3B,IAAME,EAAO,MAAM,OAAO,OAAO,UAAU,MAAO5B,EAAK0B,CAAO,EAAGnC,EAAe,GAAO,CAAC,CAAC,EACnFa,EAAS,MAAM,OAAO,OAAO,WAAW,CAAE,KAAM,OAAQ,OAAQwB,CAAK,EAAGH,EAAK,WAAY,GAAQ,EACjGI,EAAkB/B,EAAU,IAAI,WAAW,MAAM,OAAO,OAAO,UAAU,MAAO2B,EAAK,SAAS,CAAC,CAAC,EACtG,MAAO,CACL,QAASd,EACP,MAAMT,EAAOE,EAAQ,KAAK,EAC1B,MAAMF,EAAOE,EAAQ,KAAK,kBAC1B,IAAI,WAAA,CAA6B,CACnC,EACA,iBACF,CACF,MAAQ,CAGN,MACF,CACF,CAGA,eAAsB0B,EACpB,EACA,EACA,EACwB,CAGxB,OAAOnB,EAAY,MAFAT,EAAOE,EAAQ2B,CAAa,EAEtB,MADH7B,EAAOE,EAAQ2B,IAAkB,MAAQ,MAAQ,KAAK,EAC1ChB,CAAW,CAC/C"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["KEY_ALGORITHM","CIPHER","bytes","binary","value","out","index","base64Url","byte","view","copy","derive","material","secret","infoFor","direction","nonceFor","nonce","prefix","counter","channelFrom","sendCounter","highestReceived","MAX_MESSAGES_PER_KEY","noncePrefix","sealed","sendKey","plaintext","shape","envelope","isSealedEnvelope","body","receiveKey","connectSealedChannel","pair","hostKey","hostPublicKey","peer","clientPublicKey","channelFromSecret","sendDirection"],"sources":["../../../src/services/browserSealedChannel/index.ts"],"sourcesContent":["import {\n MAX_MESSAGES_PER_KEY,\n NONCE_BYTES,\n NONCE_PREFIX_BYTES,\n SEALED_VERSION,\n type SealedDirection,\n type SealedEnvelope,\n type SealedFailure,\n infoFor,\n isSealedEnvelope,\n} from '../../types/sealedChannel';\n\n/**\n * The browser half of the sealed channel.\n *\n * Mirrors `nodeSealedChannel.ts` exactly, on WebCrypto instead of\n * `node:crypto`. Two implementations rather than one because a shared one would\n * drag node builtins into every browser bundle that imports it, and this\n * package is imported by plugins that ship to the page. The envelope contract\n * they both read lives in `../types/sealedChannel.ts`, and a round-trip test\n * pins the two together so they cannot drift.\n */\n\nconst KEY_ALGORITHM = { name: 'ECDH', namedCurve: 'P-256' } as const;\nconst CIPHER = 'AES-GCM';\nconst KEY_BITS = 256;\nconst TAG_BITS = 128;\nconst TAG_BYTES = 16;\nconst HKDF_SALT = 'po/sealed/v1';\n\nexport type SealResult = { ok: true; envelope: SealedEnvelope } | { ok: false; failure: SealedFailure };\nexport type OpenResult = { ok: true; plaintext: Uint8Array } | { ok: false; failure: SealedFailure };\n\nexport interface SealedChannel {\n seal(plaintext: Uint8Array): Promise<SealResult>;\n open(envelope: unknown): Promise<OpenResult>;\n}\n\n/** Undefined rather than a throw: a malformed field is a verdict, not an exception. */\nfunction bytes(value: string): Uint8Array | undefined {\n let binary: string;\n try {\n binary = atob(value.replaceAll('-', '+').replaceAll('_', '/'));\n } catch {\n return undefined;\n }\n const out = new Uint8Array(new ArrayBuffer(binary.length));\n for (let index = 0; index < binary.length; index += 1) out[index] = binary.charCodeAt(index);\n return out;\n}\n\nfunction base64Url(value: Uint8Array): string {\n let binary = '';\n for (const byte of value) binary += String.fromCharCode(byte);\n return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');\n}\n\nfunction view(value: Uint8Array): ArrayBuffer {\n const copy = new Uint8Array(new ArrayBuffer(value.length));\n copy.set(value);\n return copy.buffer;\n}\n\nasync function derive(secret: ArrayBuffer, direction: SealedDirection): Promise<CryptoKey> {\n const material = await crypto.subtle.importKey('raw', secret, 'HKDF', false, ['deriveKey']);\n return await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: view(new TextEncoder().encode(HKDF_SALT)),\n info: view(new TextEncoder().encode(infoFor(direction))),\n },\n material,\n { name: CIPHER, length: KEY_BITS },\n false,\n ['encrypt', 'decrypt'],\n );\n}\n\nfunction nonceFor(prefix: Uint8Array, counter: bigint): Uint8Array {\n const nonce = new Uint8Array(NONCE_BYTES);\n nonce.set(prefix.subarray(0, NONCE_PREFIX_BYTES), 0);\n new DataView(nonce.buffer).setBigUint64(NONCE_PREFIX_BYTES, counter, false);\n return nonce;\n}\n\nfunction channelFrom(sendKey: CryptoKey, receiveKey: CryptoKey, noncePrefix: Uint8Array): SealedChannel {\n let sendCounter = 0n;\n let highestReceived = -1n;\n\n return {\n async seal(plaintext) {\n if (sendCounter >= BigInt(MAX_MESSAGES_PER_KEY)) return { ok: false, failure: 'exhausted' };\n const nonce = nonceFor(noncePrefix, sendCounter);\n const sealed = await crypto.subtle.encrypt(\n { name: CIPHER, iv: view(nonce), tagLength: TAG_BITS },\n sendKey,\n view(plaintext),\n );\n sendCounter += 1n;\n return {\n ok: true,\n envelope: { v: SEALED_VERSION, n: base64Url(nonce), c: base64Url(new Uint8Array(sealed)) },\n };\n },\n\n async open(envelope) {\n // Shape before version, matching the server: something with no `v` at all\n // is malformed rather than a protocol skew.\n const shape = envelope as { v?: unknown; n?: unknown; c?: unknown } | null | undefined;\n if (typeof shape?.n !== 'string' || typeof shape.c !== 'string') return { ok: false, failure: 'malformed' };\n if (shape.v !== SEALED_VERSION) return { ok: false, failure: 'version' };\n if (!isSealedEnvelope(envelope)) return { ok: false, failure: 'malformed' };\n const nonce = bytes(envelope.n);\n const body = bytes(envelope.c);\n if (nonce === undefined || body === undefined) return { ok: false, failure: 'malformed' };\n if (nonce.length !== NONCE_BYTES || body.length < TAG_BYTES) return { ok: false, failure: 'malformed' };\n const counter = new DataView(view(nonce)).getBigUint64(NONCE_PREFIX_BYTES, false);\n if (counter <= highestReceived) return { ok: false, failure: 'replay' };\n let plaintext: ArrayBuffer;\n try {\n plaintext = await crypto.subtle.decrypt(\n { name: CIPHER, iv: view(nonce), tagLength: TAG_BITS },\n receiveKey,\n view(body),\n );\n } catch {\n // A failed tag means the message was altered in transit; there is no\n // partial result worth salvaging.\n return { ok: false, failure: 'auth' };\n }\n // Another open may have finished while decrypt was pending, including\n // after its caller aborted. Never lower the authenticated high-water mark.\n if (counter <= highestReceived) return { ok: false, failure: 'replay' };\n // Only after the tag verified, so a forged high counter cannot lock out\n // every message that legitimately follows it. Keep the recheck and commit synchronous.\n highestReceived = counter;\n return { ok: true, plaintext: new Uint8Array(plaintext) };\n },\n };\n}\n\n/**\n * Completes the handshake against the host key read out of the QR fragment.\n *\n * That key never travelled through the tunnel, which is what makes this\n * authenticated: a relay can watch the client's public key go past and learn\n * nothing, and it cannot substitute the host's because it never carried it.\n */\nexport async function connectSealedChannel(\n hostPublicKey: string,\n): Promise<{ channel: SealedChannel; clientPublicKey: string } | undefined> {\n if (globalThis.crypto?.subtle === undefined) return undefined;\n try {\n const pair = await crypto.subtle.generateKey(KEY_ALGORITHM, false, ['deriveBits']);\n const hostKey = bytes(hostPublicKey);\n if (hostKey === undefined) return undefined;\n const peer = await crypto.subtle.importKey('raw', view(hostKey), KEY_ALGORITHM, false, []);\n const secret = await crypto.subtle.deriveBits({ name: 'ECDH', public: peer }, pair.privateKey, KEY_BITS);\n const clientPublicKey = base64Url(new Uint8Array(await crypto.subtle.exportKey('raw', pair.publicKey)));\n return {\n channel: channelFrom(\n await derive(secret, 'c2s'),\n await derive(secret, 's2c'),\n new Uint8Array(NONCE_PREFIX_BYTES),\n ),\n clientPublicKey,\n };\n } catch {\n // A malformed host key or a context without ECDH; the caller falls back to\n // an unsealed channel and says so rather than failing silently.\n return undefined;\n }\n}\n\n/** Exposed so a test can build the browser side against a known secret. */\nexport async function channelFromSecret(\n secret: ArrayBuffer,\n sendDirection: SealedDirection,\n noncePrefix: Uint8Array,\n): Promise<SealedChannel> {\n const send = await derive(secret, sendDirection);\n const receive = await derive(secret, sendDirection === 'c2s' ? 's2c' : 'c2s');\n return channelFrom(send, receive, noncePrefix);\n}\n"],"mappings":"wGAuBA,MAAMA,EAAgB,CAAE,KAAM,OAAQ,WAAY,OAAQ,EACpDC,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
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("../../types/bundleManifest.cjs");let n=require("node:crypto"),r=require("node:fs");r=e.__toESM(r,1);let i=require("node:path");i=e.__toESM(i,1);const a=`signing.json`,o=`sha256`,s=/* @__PURE__ */ new Set([`.map`]),c=[`web`,`native`],l={".css":`text/css`,".gif":`image/gif`,".html":`text/html`,".ico":`image/x-icon`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".js":`text/javascript`,".json":`application/json`,".mjs":`text/javascript`,".png":`image/png`,".svg":`image/svg+xml`,".txt":`text/plain`,".wasm":`application/wasm`,".webp":`image/webp`,".woff":`font/woff`,".woff2":`font/woff2`};function u(e){r.default.mkdirSync(e,{recursive:!0,mode:448});let t=r.default.lstatSync(e);if(!t.isDirectory()||t.isSymbolicLink())throw Error(`bundle signing state is not a directory: ${e}`);r.default.chmodSync(e,448)}function d(e,t){u(e);let n=i.default.join(e,`signing.lock`),a;for(let e=0;e<500;e+=1)try{a=r.default.openSync(n,`wx`,384);break}catch(e){if(e.code!==`EEXIST`)throw e;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}if(a===void 0)throw Error(`timed out waiting for bundle signing state lock: ${n}`);try{return t()}finally{r.default.closeSync(a),r.default.rmSync(n,{force:!0})}}function f(e,t){let o=i.default.join(e,a),s=i.default.join(e,`.${a}.${process.pid}.${(0,n.randomBytes)(8).toString(`hex`)}`),c=r.default.openSync(s,`wx`,384);try{r.default.writeFileSync(c,`${JSON.stringify(t,void 0,2)}\n`),r.default.fsyncSync(c)}finally{r.default.closeSync(c)}try{r.default.renameSync(s,o),r.default.chmodSync(o,384)}catch(e){throw r.default.rmSync(s,{force:!0}),e}}function p(e,t){if(typeof e!=`object`||!e)throw Error(`invalid bundle signing state: ${t}`);let n=e;if(typeof n.privateKey!=`string`||typeof n.publicKey!=`string`)throw Error(`invalid bundle signing state: ${t}`);let r=n.revision===void 0?0:n.revision;if(!Number.isSafeInteger(r)||r<0)throw Error(`invalid bundle signing revision: ${t}`);let i;try{i=y(n.privateKey)}catch{throw Error(`invalid bundle signing private key: ${t}`)}if(i!==n.publicKey)throw Error(`bundle signing keys do not match: ${t}`);return{privateKey:n.privateKey,publicKey:n.publicKey,revision:r}}function m(e){return d(e,()=>{let t=i.default.join(e,a);try{let n=r.default.lstatSync(t);if(!n.isFile()||n.isSymbolicLink())throw Error(`invalid bundle signing state file: ${t}`);let i=JSON.parse(r.default.readFileSync(t,`utf8`)),a=p(i,t);return r.default.chmodSync(t,384),i.revision===void 0&&f(e,a),a}catch(e){if(e.code!==`ENOENT`)throw e}let o=(0,n.generateKeyPairSync)(`ec`,{namedCurve:`prime256v1`,privateKeyEncoding:{type:`pkcs8`,format:`pem`},publicKeyEncoding:{type:`spki`,format:`der`}}),s={privateKey:o.privateKey,publicKey:Buffer.from(o.publicKey).toString(`base64url`),revision:0};return f(e,s),s})}function h(e,t){return d(e,()=>{let n=i.default.join(e,a),o=p(JSON.parse(r.default.readFileSync(n,`utf8`)),n);if(o.publicKey!==t)throw Error(`bundle signing key changed while the signer was active`);if(o.revision===2**53-1)throw Error(`bundle signing revision is exhausted`);let s={...o,revision:o.revision+1};return f(e,s),s.revision})}function g(e){return l[i.default.extname(e).toLowerCase()]??`application/octet-stream`}function _(e,t,a){let o=r.default.readdirSync(t,{withFileTypes:!0});for(let c of o){let o=i.default.join(t,c.name),l=r.default.lstatSync(o);if(l.isSymbolicLink())throw Error(`refusing to sign symbolic link: ${o}`);if(l.isDirectory()){_(e,o,a);continue}if(!l.isFile())throw Error(`refusing to omit unsupported asset: ${o}`);if(s.has(i.default.extname(c.name)))continue;let u=r.default.readFileSync(o);a.push({path:`/${i.default.relative(e,o).split(i.default.sep).map(e=>encodeURIComponent(e)).join(`/`)}`,sha256:(0,n.createHash)(`sha256`).update(u).digest(`hex`),byteLength:u.byteLength,contentType:g(o)})}}function v(e,a=()=>{}){let s=m(e),l=(0,n.createPrivateKey)(s.privateKey),u=/* @__PURE__ */ new Map,d=(e,t)=>`${t}:${i.default.resolve(e)}`,f=(i,a)=>{let c=r.default.lstatSync(i);if(!c.isDirectory()||c.isSymbolicLink())throw Error(`refusing to sign an unsafe asset root: ${i}`);let u=[];if(_(i,i,u),u.length===0)return;u.sort((e,t)=>e.path.localeCompare(t.path));let d={version:2,revision:h(e,s.publicKey),builtAt:Date.now(),assets:u};if(!t.isBundleManifest(d,a))throw Error(`refusing to sign an invalid ${a} bundle manifest`);return{manifest:d,signature:(0,n.createSign)(o).update(t.canonicalManifest(d)).sign({key:l,dsaEncoding:`ieee-p1363`}).toString(`base64url`),publicKey:s.publicKey}},p=(e,t=`web`)=>{let n=d(e,t);if(u.has(n))return u.get(n);let r=f(i.default.resolve(e),t);return u.set(n,r),r};return{publicKey:()=>s.publicKey,sign:p,refresh(e,t=`web`){return u.delete(d(e,t)),p(e,t)},invalidate(e){if(e===void 0)u.clear();else for(let t of c)u.delete(d(e,t))},attest(e,r){return(0,n.createSign)(o).update(t.attestationBytes(e,r)).sign({key:l,dsaEncoding:`ieee-p1363`}).toString(`base64url`)}}}function y(e){return Buffer.from((0,n.createPublicKey)(e).export({type:`spki`,format:`der`})).toString(`base64url`)}exports.createBundleSigner=v,exports.publicKeyOf=y;
|
|
1
|
+
const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("../../types/bundleManifest.cjs");let n=require("node:crypto"),r=require("node:fs");r=e.__toESM(r,1);let i=require("node:path");i=e.__toESM(i,1);const a=`signing.json`,o=`sha256`,s=/* @__PURE__ */ new Set([`.map`]),c=[`web`,`native`,`app`],l={".css":`text/css`,".gif":`image/gif`,".html":`text/html`,".ico":`image/x-icon`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".js":`text/javascript`,".json":`application/json`,".mjs":`text/javascript`,".png":`image/png`,".svg":`image/svg+xml`,".txt":`text/plain`,".wasm":`application/wasm`,".webp":`image/webp`,".woff":`font/woff`,".woff2":`font/woff2`};function u(e){r.default.mkdirSync(e,{recursive:!0,mode:448});let t=r.default.lstatSync(e);if(!t.isDirectory()||t.isSymbolicLink())throw Error(`bundle signing state is not a directory: ${e}`);r.default.chmodSync(e,448)}function d(e,t){u(e);let n=i.default.join(e,`signing.lock`),a;for(let e=0;e<500;e+=1)try{a=r.default.openSync(n,`wx`,384);break}catch(e){if(e.code!==`EEXIST`)throw e;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}if(a===void 0)throw Error(`timed out waiting for bundle signing state lock: ${n}`);try{return t()}finally{r.default.closeSync(a),r.default.rmSync(n,{force:!0})}}function f(e,t){let o=i.default.join(e,a),s=i.default.join(e,`.${a}.${process.pid}.${(0,n.randomBytes)(8).toString(`hex`)}`),c=r.default.openSync(s,`wx`,384);try{r.default.writeFileSync(c,`${JSON.stringify(t,void 0,2)}\n`),r.default.fsyncSync(c)}finally{r.default.closeSync(c)}try{r.default.renameSync(s,o),r.default.chmodSync(o,384)}catch(e){throw r.default.rmSync(s,{force:!0}),e}}function p(e,t){if(typeof e!=`object`||!e)throw Error(`invalid bundle signing state: ${t}`);let n=e;if(typeof n.privateKey!=`string`||typeof n.publicKey!=`string`)throw Error(`invalid bundle signing state: ${t}`);let r=n.revision===void 0?0:n.revision;if(!Number.isSafeInteger(r)||r<0)throw Error(`invalid bundle signing revision: ${t}`);let i;try{i=y(n.privateKey)}catch{throw Error(`invalid bundle signing private key: ${t}`)}if(i!==n.publicKey)throw Error(`bundle signing keys do not match: ${t}`);return{privateKey:n.privateKey,publicKey:n.publicKey,revision:r}}function m(e){return d(e,()=>{let t=i.default.join(e,a);try{let n=r.default.lstatSync(t);if(!n.isFile()||n.isSymbolicLink())throw Error(`invalid bundle signing state file: ${t}`);let i=JSON.parse(r.default.readFileSync(t,`utf8`)),a=p(i,t);return r.default.chmodSync(t,384),i.revision===void 0&&f(e,a),a}catch(e){if(e.code!==`ENOENT`)throw e}let o=(0,n.generateKeyPairSync)(`ec`,{namedCurve:`prime256v1`,privateKeyEncoding:{type:`pkcs8`,format:`pem`},publicKeyEncoding:{type:`spki`,format:`der`}}),s={privateKey:o.privateKey,publicKey:Buffer.from(o.publicKey).toString(`base64url`),revision:0};return f(e,s),s})}function h(e,t){return d(e,()=>{let n=i.default.join(e,a),o=p(JSON.parse(r.default.readFileSync(n,`utf8`)),n);if(o.publicKey!==t)throw Error(`bundle signing key changed while the signer was active`);if(o.revision===2**53-1)throw Error(`bundle signing revision is exhausted`);let s={...o,revision:o.revision+1};return f(e,s),s.revision})}function g(e){return l[i.default.extname(e).toLowerCase()]??`application/octet-stream`}function _(e,t,a){let o=r.default.readdirSync(t,{withFileTypes:!0});for(let c of o){let o=i.default.join(t,c.name),l=r.default.lstatSync(o);if(l.isSymbolicLink())throw Error(`refusing to sign symbolic link: ${o}`);if(l.isDirectory()){_(e,o,a);continue}if(!l.isFile())throw Error(`refusing to omit unsupported asset: ${o}`);if(s.has(i.default.extname(c.name)))continue;let u=r.default.readFileSync(o);a.push({path:`/${i.default.relative(e,o).split(i.default.sep).map(e=>encodeURIComponent(e)).join(`/`)}`,sha256:(0,n.createHash)(`sha256`).update(u).digest(`hex`),byteLength:u.byteLength,contentType:g(o)})}}function v(e,a=()=>{}){let s=m(e),l=(0,n.createPrivateKey)(s.privateKey),u=/* @__PURE__ */ new Map,d=(e,t)=>`${t}:${i.default.resolve(e)}`,f=(i,a)=>{let c=r.default.lstatSync(i);if(!c.isDirectory()||c.isSymbolicLink())throw Error(`refusing to sign an unsafe asset root: ${i}`);let u=[];if(_(i,i,u),u.length===0)return;u.sort((e,t)=>e.path.localeCompare(t.path));let d={version:2,revision:h(e,s.publicKey),builtAt:Date.now(),assets:u};if(!t.isBundleManifest(d,a))throw Error(`refusing to sign an invalid ${a} bundle manifest`);return{manifest:d,signature:(0,n.createSign)(o).update(t.canonicalManifest(d)).sign({key:l,dsaEncoding:`ieee-p1363`}).toString(`base64url`),publicKey:s.publicKey}},p=(e,t=`web`)=>{let n=d(e,t);if(u.has(n))return u.get(n);let r=f(i.default.resolve(e),t);return u.set(n,r),r};return{publicKey:()=>s.publicKey,sign:p,refresh(e,t=`web`){return u.delete(d(e,t)),p(e,t)},invalidate(e){if(e===void 0)u.clear();else for(let t of c)u.delete(d(e,t))},attest(e,r){return(0,n.createSign)(o).update(t.attestationBytes(e,r)).sign({key:l,dsaEncoding:`ieee-p1363`}).toString(`base64url`)}}}function y(e){return Buffer.from((0,n.createPublicKey)(e).export({type:`spki`,format:`der`})).toString(`base64url`)}exports.createBundleSigner=v,exports.publicKeyOf=y;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["fs","path","randomBytes","generateKeyPairSync","createHash","createPrivateKey","isBundleManifest","createSign","canonicalManifest","attestationBytes","createPublicKey","require_runtime","require_bundleManifest","node_crypto","node_fs","node_path","SIGNING_FILE","SIGN_ALGORITHM","SKIPPED","PROFILES","MIME_TYPES","ensureStateDirectory","stateDir","stat","withStateLock","lockPath","descriptor","attempt","error","operation","atomicWriteState","destination","temporary","state","parseState","value","keyPath","candidate","revision","derived","publicKeyOf","loadOrCreateState","parsed","pair","reserveRevision","expectedPublicKey","next","contentTypeFor","filePath","walk","entries","current","entry","full","root","into","bytes","segment","createBundleSigner","key","privateKey","cache","cacheKeyOf","profile","assetsDir","signFresh","rootStat","assets","left","right","manifest","sign","cacheKey","signed","tag","fields","privateKeyPem"],"sources":["../../../src/services/bundleSigner/index.ts"],"sourcesContent":["import {\n createHash,\n createPrivateKey,\n createPublicKey,\n createSign,\n generateKeyPairSync,\n randomBytes,\n} from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport {\n BUNDLE_MANIFEST_VERSION,\n type BundleAsset,\n type BundleManifest,\n type BundleProfile,\n type SignedBundleManifest,\n attestationBytes,\n canonicalManifest,\n isBundleManifest,\n} from '../../types/bundleManifest';\n\nconst SIGNING_FILE = 'signing.json';\nconst LOCK_FILE = 'signing.lock';\nconst FILE_MODE = 0o600;\nconst DIRECTORY_MODE = 0o700;\nconst CURVE = 'prime256v1';\nconst SIGN_ALGORITHM = 'sha256';\nconst SKIPPED = new Set(['.map']);\nconst PROFILES: readonly BundleProfile[] = ['web', 'native'];\nconst MIME_TYPES: Readonly<Record<string, string>> = {\n '.css': 'text/css',\n '.gif': 'image/gif',\n '.html': 'text/html',\n '.ico': 'image/x-icon',\n '.jpeg': 'image/jpeg',\n '.jpg': 'image/jpeg',\n '.js': 'text/javascript',\n '.json': 'application/json',\n '.mjs': 'text/javascript',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.txt': 'text/plain',\n '.wasm': 'application/wasm',\n '.webp': 'image/webp',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n};\n\nexport interface BundleSigner {\n /** Base64url SPKI for an independently trusted verifier to pin. */\n publicKey(): string;\n /**\n * Hashes and signs once per asset directory and profile. Undefined when the bundle is empty. Throws\n * when the assets do not match the profile.\n */\n sign(assetsDir: string, profile?: BundleProfile): SignedBundleManifest | undefined;\n /** Invalidates and immediately rebuilds one cached manifest. */\n refresh(assetsDir: string, profile?: BundleProfile): SignedBundleManifest | undefined;\n /** Invalidates one cached directory under every profile, or every cached directory when omitted. */\n invalidate(assetsDir?: string): void;\n /**\n * Base64url IEEE P1363 signature over `attestationBytes(tag, fields)` with the bundle key. Throws on a\n * malformed tag.\n */\n attest(tag: string, fields: readonly string[]): string;\n}\n\ninterface StoredState {\n privateKey: string;\n publicKey: string;\n revision: number;\n}\n\nfunction ensureStateDirectory(stateDir: string): void {\n fs.mkdirSync(stateDir, { recursive: true, mode: DIRECTORY_MODE });\n const stat = fs.lstatSync(stateDir);\n if (!stat.isDirectory() || stat.isSymbolicLink())\n throw new Error(`bundle signing state is not a directory: ${stateDir}`);\n fs.chmodSync(stateDir, DIRECTORY_MODE);\n}\n\nfunction withStateLock<T>(stateDir: string, operation: () => T): T {\n ensureStateDirectory(stateDir);\n const lockPath = path.join(stateDir, LOCK_FILE);\n let descriptor: number | undefined;\n for (let attempt = 0; attempt < 500; attempt += 1) {\n try {\n descriptor = fs.openSync(lockPath, 'wx', FILE_MODE);\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);\n }\n }\n if (descriptor === undefined) throw new Error(`timed out waiting for bundle signing state lock: ${lockPath}`);\n try {\n return operation();\n } finally {\n fs.closeSync(descriptor);\n fs.rmSync(lockPath, { force: true });\n }\n}\n\nfunction atomicWriteState(stateDir: string, state: StoredState): void {\n const destination = path.join(stateDir, SIGNING_FILE);\n const temporary = path.join(stateDir, `.${SIGNING_FILE}.${process.pid}.${randomBytes(8).toString('hex')}`);\n const descriptor = fs.openSync(temporary, 'wx', FILE_MODE);\n try {\n fs.writeFileSync(descriptor, `${JSON.stringify(state, undefined, 2)}\\n`);\n fs.fsyncSync(descriptor);\n } finally {\n fs.closeSync(descriptor);\n }\n try {\n fs.renameSync(temporary, destination);\n fs.chmodSync(destination, FILE_MODE);\n } catch (error) {\n fs.rmSync(temporary, { force: true });\n throw error;\n }\n}\n\nfunction parseState(value: unknown, keyPath: string): StoredState {\n if (typeof value !== 'object' || value === null) throw new Error(`invalid bundle signing state: ${keyPath}`);\n const candidate = value as Partial<StoredState>;\n if (typeof candidate.privateKey !== 'string' || typeof candidate.publicKey !== 'string') {\n throw new Error(`invalid bundle signing state: ${keyPath}`);\n }\n const revision = candidate.revision === undefined ? 0 : candidate.revision;\n if (!Number.isSafeInteger(revision) || revision < 0) throw new Error(`invalid bundle signing revision: ${keyPath}`);\n let derived: string;\n try {\n derived = publicKeyOf(candidate.privateKey);\n } catch {\n throw new Error(`invalid bundle signing private key: ${keyPath}`);\n }\n if (derived !== candidate.publicKey) throw new Error(`bundle signing keys do not match: ${keyPath}`);\n return { privateKey: candidate.privateKey, publicKey: candidate.publicKey, revision };\n}\n\nfunction loadOrCreateState(stateDir: string): StoredState {\n return withStateLock(stateDir, () => {\n const keyPath = path.join(stateDir, SIGNING_FILE);\n try {\n const stat = fs.lstatSync(keyPath);\n if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`invalid bundle signing state file: ${keyPath}`);\n const parsed: unknown = JSON.parse(fs.readFileSync(keyPath, 'utf8'));\n const state = parseState(parsed, keyPath);\n fs.chmodSync(keyPath, FILE_MODE);\n if ((parsed as Partial<StoredState>).revision === undefined) atomicWriteState(stateDir, state);\n return state;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n\n const pair = generateKeyPairSync('ec', {\n namedCurve: CURVE,\n privateKeyEncoding: { type: 'pkcs8', format: 'pem' },\n publicKeyEncoding: { type: 'spki', format: 'der' },\n });\n const state: StoredState = {\n privateKey: pair.privateKey,\n publicKey: Buffer.from(pair.publicKey).toString('base64url'),\n revision: 0,\n };\n atomicWriteState(stateDir, state);\n return state;\n });\n}\n\nfunction reserveRevision(stateDir: string, expectedPublicKey: string): number {\n return withStateLock(stateDir, () => {\n const keyPath = path.join(stateDir, SIGNING_FILE);\n const state = parseState(JSON.parse(fs.readFileSync(keyPath, 'utf8')) as unknown, keyPath);\n if (state.publicKey !== expectedPublicKey)\n throw new Error('bundle signing key changed while the signer was active');\n if (state.revision === Number.MAX_SAFE_INTEGER) throw new Error('bundle signing revision is exhausted');\n const next = { ...state, revision: state.revision + 1 };\n atomicWriteState(stateDir, next);\n return next.revision;\n });\n}\n\nfunction contentTypeFor(filePath: string): string {\n return MIME_TYPES[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream';\n}\n\n/** Every servable regular file under the asset root, as browser paths. */\nfunction walk(root: string, current: string, into: BundleAsset[]): void {\n const entries = fs.readdirSync(current, { withFileTypes: true });\n for (const entry of entries) {\n const full = path.join(current, entry.name);\n const stat = fs.lstatSync(full);\n if (stat.isSymbolicLink()) throw new Error(`refusing to sign symbolic link: ${full}`);\n if (stat.isDirectory()) {\n walk(root, full, into);\n continue;\n }\n if (!stat.isFile()) throw new Error(`refusing to omit unsupported asset: ${full}`);\n if (SKIPPED.has(path.extname(entry.name))) continue;\n const bytes = fs.readFileSync(full);\n into.push({\n path: `/${path\n .relative(root, full)\n .split(path.sep)\n .map((segment) => encodeURIComponent(segment))\n .join('/')}`,\n sha256: createHash('sha256').update(bytes).digest('hex'),\n byteLength: bytes.byteLength,\n contentType: contentTypeFor(full),\n });\n }\n}\n\nexport function createBundleSigner(stateDir: string, _onNotice: (message: string) => void = () => {}): BundleSigner {\n const key = loadOrCreateState(stateDir);\n const privateKey = createPrivateKey(key.privateKey);\n const cache = new Map<string, SignedBundleManifest | undefined>();\n const cacheKeyOf = (assetsDir: string, profile: BundleProfile): string => `${profile}:${path.resolve(assetsDir)}`;\n\n const signFresh = (assetsDir: string, profile: BundleProfile): SignedBundleManifest | undefined => {\n const rootStat = fs.lstatSync(assetsDir);\n if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {\n throw new Error(`refusing to sign an unsafe asset root: ${assetsDir}`);\n }\n const assets: BundleAsset[] = [];\n walk(assetsDir, assetsDir, assets);\n if (assets.length === 0) return undefined;\n assets.sort((left, right) => left.path.localeCompare(right.path));\n const manifest: BundleManifest = {\n version: BUNDLE_MANIFEST_VERSION,\n revision: reserveRevision(stateDir, key.publicKey),\n builtAt: Date.now(),\n assets,\n };\n if (!isBundleManifest(manifest, profile)) throw new Error(`refusing to sign an invalid ${profile} bundle manifest`);\n const signature = createSign(SIGN_ALGORITHM)\n .update(canonicalManifest(manifest))\n .sign({ key: privateKey, dsaEncoding: 'ieee-p1363' })\n .toString('base64url');\n return { manifest, signature, publicKey: key.publicKey };\n };\n\n const sign = (assetsDir: string, profile: BundleProfile = 'web'): SignedBundleManifest | undefined => {\n const cacheKey = cacheKeyOf(assetsDir, profile);\n if (cache.has(cacheKey)) return cache.get(cacheKey);\n const signed = signFresh(path.resolve(assetsDir), profile);\n cache.set(cacheKey, signed);\n return signed;\n };\n\n return {\n publicKey: () => key.publicKey,\n sign,\n refresh(assetsDir, profile = 'web') {\n cache.delete(cacheKeyOf(assetsDir, profile));\n return sign(assetsDir, profile);\n },\n invalidate(assetsDir) {\n if (assetsDir === undefined) {\n cache.clear();\n return;\n }\n for (const profile of PROFILES) cache.delete(cacheKeyOf(assetsDir, profile));\n },\n attest(tag, fields) {\n return createSign(SIGN_ALGORITHM)\n .update(attestationBytes(tag, fields))\n .sign({ key: privateKey, dsaEncoding: 'ieee-p1363' })\n .toString('base64url');\n },\n };\n}\n\n/** Re-derives the public key from a stored private key. */\nexport function publicKeyOf(privateKeyPem: string): string {\n return Buffer.from(createPublicKey(privateKeyPem).export({ type: 'spki', format: 'der' }) as Buffer).toString(\n 'base64url',\n );\n}\n"],"mappings":"mNAsBA,MAAMgB,EAAe,eAKfC,EAAiB,SACjBC,kBAAU,IAAI,IAAI,CAAC,MAAM,CAAC,EAC1BC,EAAqC,CAAC,MAAO,QAAQ,EACrDC,EAA+C,CACnD,OAAQ,WACR,OAAQ,YACR,QAAS,YACT,OAAQ,eACR,QAAS,aACT,OAAQ,aACR,MAAO,kBACP,QAAS,mBACT,OAAQ,kBACR,OAAQ,YACR,OAAQ,gBACR,OAAQ,aACR,QAAS,mBACT,QAAS,aACT,QAAS,YACT,SAAU,YACZ,EA2BA,SAASC,EAAqB,EAAwB,CACpDP,EAAA,QAAG,UAAUQ,EAAU,CAAE,UAAW,GAAM,KAAM,GAAe,CAAC,EAChE,IAAMC,EAAOvB,EAAAA,QAAG,UAAUsB,CAAQ,EAClC,GAAI,CAACC,EAAK,YAAY,GAAKA,EAAK,eAAe,EAC7C,MAAU,MAAM,4CAA4CD,GAAU,EACxER,EAAA,QAAG,UAAUQ,EAAU,GAAc,CACvC,CAEA,SAASE,EAAiB,EAAkB,EAAuB,CACjEH,EAAqBC,CAAQ,EAC7B,IAAMG,EAAWxB,EAAAA,QAAK,KAAKqB,EAAU,cAAS,EAC1CI,EACJ,IAAK,IAAIC,EAAU,EAAGA,EAAU,IAAK,GAAW,EAC9C,G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,CAAC,CAAC,CACnC,KAAK,CAAE,IAAKV,EAAY,YAAa,YAAa,CAAC,CAAC,CACpD,SAAS,WACe,EAAG,UAAWD,EAAI,SAAU,CACzD,EAEMY,GAAQ,EAAmB,EAAyB,QAA4C,CACpG,IAAMC,EAAWV,EAAWE,EAAWD,CAAO,EAC9C,GAAIF,EAAM,IAAIW,CAAQ,EAAG,OAAOX,EAAM,IAAIW,CAAQ,EAClD,IAAMC,EAASR,EAAUhE,EAAAA,QAAK,QAAQ+D,CAAS,EAAGD,CAAO,EAEzD,OADAF,EAAM,IAAIW,EAAUC,CAAM,EACnBA,CACT,EAEA,MAAO,CACL,cAAiBd,EAAI,UACrB,OACA,QAAQ,EAAW,EAAU,MAAO,CAElC,OADAE,EAAM,OAAOC,EAAWE,EAAWD,CAAO,CAAC,EACpCQ,EAAKP,EAAWD,CAAO,CAChC,EACA,WAAW,EAAW,CACpB,GAAIC,IAAc,IAAA,GAChBH,EAAM,MAAM,OAGd,IAAK,IAAME,KAAW5C,EAAU0C,EAAM,OAAOC,EAAWE,EAAWD,CAAO,CAAC,CAC7E,EACA,OAAO,EAAK,EAAQ,CAClB,OAAA,EAAOxD,EAAAA,WAAAA,CAAWU,CAAc,CAAC,CAC9B,OAAOR,EAAAA,iBAAiBiE,EAAKC,CAAM,CAAC,CAAC,CACrC,KAAK,CAAE,IAAKf,EAAY,YAAa,YAAa,CAAC,CAAC,CACpD,SAAS,WAAW,CACzB,CACF,CACF,CAGA,SAAgBpB,EAAY,EAA+B,CACzD,OAAO,OAAO,MAAA,EAAK9B,EAAAA,gBAAAA,CAAgBkE,CAAa,CAAC,CAAC,OAAO,CAAE,KAAM,OAAQ,OAAQ,KAAM,CAAC,CAAW,CAAC,CAAC,SACnG,WACF,CACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["fs","path","randomBytes","generateKeyPairSync","createHash","createPrivateKey","isBundleManifest","createSign","canonicalManifest","attestationBytes","createPublicKey","require_runtime","require_bundleManifest","node_crypto","node_fs","node_path","SIGNING_FILE","SIGN_ALGORITHM","SKIPPED","PROFILES","MIME_TYPES","ensureStateDirectory","stateDir","stat","withStateLock","lockPath","descriptor","attempt","error","operation","atomicWriteState","destination","temporary","state","parseState","value","keyPath","candidate","revision","derived","publicKeyOf","loadOrCreateState","parsed","pair","reserveRevision","expectedPublicKey","next","contentTypeFor","filePath","walk","entries","current","entry","full","root","into","bytes","segment","createBundleSigner","key","privateKey","cache","cacheKeyOf","profile","assetsDir","signFresh","rootStat","assets","left","right","manifest","sign","cacheKey","signed","tag","fields","privateKeyPem"],"sources":["../../../src/services/bundleSigner/index.ts"],"sourcesContent":["import {\n createHash,\n createPrivateKey,\n createPublicKey,\n createSign,\n generateKeyPairSync,\n randomBytes,\n} from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport {\n BUNDLE_MANIFEST_VERSION,\n type BundleAsset,\n type BundleManifest,\n type BundleProfile,\n type SignedBundleManifest,\n attestationBytes,\n canonicalManifest,\n isBundleManifest,\n} from '../../types/bundleManifest';\n\nconst SIGNING_FILE = 'signing.json';\nconst LOCK_FILE = 'signing.lock';\nconst FILE_MODE = 0o600;\nconst DIRECTORY_MODE = 0o700;\nconst CURVE = 'prime256v1';\nconst SIGN_ALGORITHM = 'sha256';\nconst SKIPPED = new Set(['.map']);\nconst PROFILES: readonly BundleProfile[] = ['web', 'native', 'app'];\nconst MIME_TYPES: Readonly<Record<string, string>> = {\n '.css': 'text/css',\n '.gif': 'image/gif',\n '.html': 'text/html',\n '.ico': 'image/x-icon',\n '.jpeg': 'image/jpeg',\n '.jpg': 'image/jpeg',\n '.js': 'text/javascript',\n '.json': 'application/json',\n '.mjs': 'text/javascript',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.txt': 'text/plain',\n '.wasm': 'application/wasm',\n '.webp': 'image/webp',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n};\n\nexport interface BundleSigner {\n /** Base64url SPKI for an independently trusted verifier to pin. */\n publicKey(): string;\n /**\n * Hashes and signs once per asset directory and profile. Undefined when the bundle is empty. Throws\n * when the assets do not match the profile.\n */\n sign(assetsDir: string, profile?: BundleProfile): SignedBundleManifest | undefined;\n /** Invalidates and immediately rebuilds one cached manifest. */\n refresh(assetsDir: string, profile?: BundleProfile): SignedBundleManifest | undefined;\n /** Invalidates one cached directory under every profile, or every cached directory when omitted. */\n invalidate(assetsDir?: string): void;\n /**\n * Base64url IEEE P1363 signature over `attestationBytes(tag, fields)` with the bundle key. Throws on a\n * malformed tag.\n */\n attest(tag: string, fields: readonly string[]): string;\n}\n\ninterface StoredState {\n privateKey: string;\n publicKey: string;\n revision: number;\n}\n\nfunction ensureStateDirectory(stateDir: string): void {\n fs.mkdirSync(stateDir, { recursive: true, mode: DIRECTORY_MODE });\n const stat = fs.lstatSync(stateDir);\n if (!stat.isDirectory() || stat.isSymbolicLink())\n throw new Error(`bundle signing state is not a directory: ${stateDir}`);\n fs.chmodSync(stateDir, DIRECTORY_MODE);\n}\n\nfunction withStateLock<T>(stateDir: string, operation: () => T): T {\n ensureStateDirectory(stateDir);\n const lockPath = path.join(stateDir, LOCK_FILE);\n let descriptor: number | undefined;\n for (let attempt = 0; attempt < 500; attempt += 1) {\n try {\n descriptor = fs.openSync(lockPath, 'wx', FILE_MODE);\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);\n }\n }\n if (descriptor === undefined) throw new Error(`timed out waiting for bundle signing state lock: ${lockPath}`);\n try {\n return operation();\n } finally {\n fs.closeSync(descriptor);\n fs.rmSync(lockPath, { force: true });\n }\n}\n\nfunction atomicWriteState(stateDir: string, state: StoredState): void {\n const destination = path.join(stateDir, SIGNING_FILE);\n const temporary = path.join(stateDir, `.${SIGNING_FILE}.${process.pid}.${randomBytes(8).toString('hex')}`);\n const descriptor = fs.openSync(temporary, 'wx', FILE_MODE);\n try {\n fs.writeFileSync(descriptor, `${JSON.stringify(state, undefined, 2)}\\n`);\n fs.fsyncSync(descriptor);\n } finally {\n fs.closeSync(descriptor);\n }\n try {\n fs.renameSync(temporary, destination);\n fs.chmodSync(destination, FILE_MODE);\n } catch (error) {\n fs.rmSync(temporary, { force: true });\n throw error;\n }\n}\n\nfunction parseState(value: unknown, keyPath: string): StoredState {\n if (typeof value !== 'object' || value === null) throw new Error(`invalid bundle signing state: ${keyPath}`);\n const candidate = value as Partial<StoredState>;\n if (typeof candidate.privateKey !== 'string' || typeof candidate.publicKey !== 'string') {\n throw new Error(`invalid bundle signing state: ${keyPath}`);\n }\n const revision = candidate.revision === undefined ? 0 : candidate.revision;\n if (!Number.isSafeInteger(revision) || revision < 0) throw new Error(`invalid bundle signing revision: ${keyPath}`);\n let derived: string;\n try {\n derived = publicKeyOf(candidate.privateKey);\n } catch {\n throw new Error(`invalid bundle signing private key: ${keyPath}`);\n }\n if (derived !== candidate.publicKey) throw new Error(`bundle signing keys do not match: ${keyPath}`);\n return { privateKey: candidate.privateKey, publicKey: candidate.publicKey, revision };\n}\n\nfunction loadOrCreateState(stateDir: string): StoredState {\n return withStateLock(stateDir, () => {\n const keyPath = path.join(stateDir, SIGNING_FILE);\n try {\n const stat = fs.lstatSync(keyPath);\n if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`invalid bundle signing state file: ${keyPath}`);\n const parsed: unknown = JSON.parse(fs.readFileSync(keyPath, 'utf8'));\n const state = parseState(parsed, keyPath);\n fs.chmodSync(keyPath, FILE_MODE);\n if ((parsed as Partial<StoredState>).revision === undefined) atomicWriteState(stateDir, state);\n return state;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n\n const pair = generateKeyPairSync('ec', {\n namedCurve: CURVE,\n privateKeyEncoding: { type: 'pkcs8', format: 'pem' },\n publicKeyEncoding: { type: 'spki', format: 'der' },\n });\n const state: StoredState = {\n privateKey: pair.privateKey,\n publicKey: Buffer.from(pair.publicKey).toString('base64url'),\n revision: 0,\n };\n atomicWriteState(stateDir, state);\n return state;\n });\n}\n\nfunction reserveRevision(stateDir: string, expectedPublicKey: string): number {\n return withStateLock(stateDir, () => {\n const keyPath = path.join(stateDir, SIGNING_FILE);\n const state = parseState(JSON.parse(fs.readFileSync(keyPath, 'utf8')) as unknown, keyPath);\n if (state.publicKey !== expectedPublicKey)\n throw new Error('bundle signing key changed while the signer was active');\n if (state.revision === Number.MAX_SAFE_INTEGER) throw new Error('bundle signing revision is exhausted');\n const next = { ...state, revision: state.revision + 1 };\n atomicWriteState(stateDir, next);\n return next.revision;\n });\n}\n\nfunction contentTypeFor(filePath: string): string {\n return MIME_TYPES[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream';\n}\n\n/** Every servable regular file under the asset root, as browser paths. */\nfunction walk(root: string, current: string, into: BundleAsset[]): void {\n const entries = fs.readdirSync(current, { withFileTypes: true });\n for (const entry of entries) {\n const full = path.join(current, entry.name);\n const stat = fs.lstatSync(full);\n if (stat.isSymbolicLink()) throw new Error(`refusing to sign symbolic link: ${full}`);\n if (stat.isDirectory()) {\n walk(root, full, into);\n continue;\n }\n if (!stat.isFile()) throw new Error(`refusing to omit unsupported asset: ${full}`);\n if (SKIPPED.has(path.extname(entry.name))) continue;\n const bytes = fs.readFileSync(full);\n into.push({\n path: `/${path\n .relative(root, full)\n .split(path.sep)\n .map((segment) => encodeURIComponent(segment))\n .join('/')}`,\n sha256: createHash('sha256').update(bytes).digest('hex'),\n byteLength: bytes.byteLength,\n contentType: contentTypeFor(full),\n });\n }\n}\n\nexport function createBundleSigner(stateDir: string, _onNotice: (message: string) => void = () => {}): BundleSigner {\n const key = loadOrCreateState(stateDir);\n const privateKey = createPrivateKey(key.privateKey);\n const cache = new Map<string, SignedBundleManifest | undefined>();\n const cacheKeyOf = (assetsDir: string, profile: BundleProfile): string => `${profile}:${path.resolve(assetsDir)}`;\n\n const signFresh = (assetsDir: string, profile: BundleProfile): SignedBundleManifest | undefined => {\n const rootStat = fs.lstatSync(assetsDir);\n if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {\n throw new Error(`refusing to sign an unsafe asset root: ${assetsDir}`);\n }\n const assets: BundleAsset[] = [];\n walk(assetsDir, assetsDir, assets);\n if (assets.length === 0) return undefined;\n assets.sort((left, right) => left.path.localeCompare(right.path));\n const manifest: BundleManifest = {\n version: BUNDLE_MANIFEST_VERSION,\n revision: reserveRevision(stateDir, key.publicKey),\n builtAt: Date.now(),\n assets,\n };\n if (!isBundleManifest(manifest, profile)) throw new Error(`refusing to sign an invalid ${profile} bundle manifest`);\n const signature = createSign(SIGN_ALGORITHM)\n .update(canonicalManifest(manifest))\n .sign({ key: privateKey, dsaEncoding: 'ieee-p1363' })\n .toString('base64url');\n return { manifest, signature, publicKey: key.publicKey };\n };\n\n const sign = (assetsDir: string, profile: BundleProfile = 'web'): SignedBundleManifest | undefined => {\n const cacheKey = cacheKeyOf(assetsDir, profile);\n if (cache.has(cacheKey)) return cache.get(cacheKey);\n const signed = signFresh(path.resolve(assetsDir), profile);\n cache.set(cacheKey, signed);\n return signed;\n };\n\n return {\n publicKey: () => key.publicKey,\n sign,\n refresh(assetsDir, profile = 'web') {\n cache.delete(cacheKeyOf(assetsDir, profile));\n return sign(assetsDir, profile);\n },\n invalidate(assetsDir) {\n if (assetsDir === undefined) {\n cache.clear();\n return;\n }\n for (const profile of PROFILES) cache.delete(cacheKeyOf(assetsDir, profile));\n },\n attest(tag, fields) {\n return createSign(SIGN_ALGORITHM)\n .update(attestationBytes(tag, fields))\n .sign({ key: privateKey, dsaEncoding: 'ieee-p1363' })\n .toString('base64url');\n },\n };\n}\n\n/** Re-derives the public key from a stored private key. */\nexport function publicKeyOf(privateKeyPem: string): string {\n return Buffer.from(createPublicKey(privateKeyPem).export({ type: 'spki', format: 'der' }) as Buffer).toString(\n 'base64url',\n );\n}\n"],"mappings":"mNAsBA,MAAMgB,EAAe,eAKfC,EAAiB,SACjBC,kBAAU,IAAI,IAAI,CAAC,MA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AAKP,EAAWD,CAAO,CAChC,EACA,WAAW,EAAW,CACpB,GAAIC,IAAc,IAAA,GAChBH,EAAM,MAAM,OAGd,IAAK,IAAME,KAAW5C,EAAU0C,EAAM,OAAOC,EAAWE,EAAWD,CAAO,CAAC,CAC7E,EACA,OAAO,EAAK,EAAQ,CAClB,OAAA,EAAOxD,EAAAA,WAAAA,CAAWU,CAAc,CAAC,CAC9B,OAAOR,EAAAA,iBAAiBiE,EAAKC,CAAM,CAAC,CAAC,CACrC,KAAK,CAAE,IAAKf,EAAY,YAAa,YAAa,CAAC,CAAC,CACpD,SAAS,WAAW,CACzB,CACF,CACF,CAGA,SAAgBpB,EAAY,EAA+B,CACzD,OAAO,OAAO,MAAA,EAAK9B,EAAAA,gBAAAA,CAAgBkE,CAAa,CAAC,CAAC,OAAO,CAAE,KAAM,OAAQ,OAAQ,KAAM,CAAC,CAAW,CAAC,CAAC,SACnG,WACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{attestationBytes as e,canonicalManifest as t,isBundleManifest as n}from"../../types/bundleManifest.mjs";import{createHash as r,createPrivateKey as i,createPublicKey as a,createSign as o,generateKeyPairSync as s,randomBytes as c}from"node:crypto";import l from"node:fs";import u from"node:path";const d=`signing.json`,f=`sha256`,p=/* @__PURE__ */ new Set([`.map`]),m=[`web`,`native`],h={".css":`text/css`,".gif":`image/gif`,".html":`text/html`,".ico":`image/x-icon`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".js":`text/javascript`,".json":`application/json`,".mjs":`text/javascript`,".png":`image/png`,".svg":`image/svg+xml`,".txt":`text/plain`,".wasm":`application/wasm`,".webp":`image/webp`,".woff":`font/woff`,".woff2":`font/woff2`};function g(e){l.mkdirSync(e,{recursive:!0,mode:448});let t=l.lstatSync(e);if(!t.isDirectory()||t.isSymbolicLink())throw Error(`bundle signing state is not a directory: ${e}`);l.chmodSync(e,448)}function _(e,t){g(e);let n=u.join(e,`signing.lock`),r;for(let e=0;e<500;e+=1)try{r=l.openSync(n,`wx`,384);break}catch(e){if(e.code!==`EEXIST`)throw e;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}if(r===void 0)throw Error(`timed out waiting for bundle signing state lock: ${n}`);try{return t()}finally{l.closeSync(r),l.rmSync(n,{force:!0})}}function v(e,t){let n=u.join(e,d),r=u.join(e,`.${d}.${process.pid}.${c(8).toString(`hex`)}`),i=l.openSync(r,`wx`,384);try{l.writeFileSync(i,`${JSON.stringify(t,void 0,2)}\n`),l.fsyncSync(i)}finally{l.closeSync(i)}try{l.renameSync(r,n),l.chmodSync(n,384)}catch(e){throw l.rmSync(r,{force:!0}),e}}function y(e,t){if(typeof e!=`object`||!e)throw Error(`invalid bundle signing state: ${t}`);let n=e;if(typeof n.privateKey!=`string`||typeof n.publicKey!=`string`)throw Error(`invalid bundle signing state: ${t}`);let r=n.revision===void 0?0:n.revision;if(!Number.isSafeInteger(r)||r<0)throw Error(`invalid bundle signing revision: ${t}`);let i;try{i=T(n.privateKey)}catch{throw Error(`invalid bundle signing private key: ${t}`)}if(i!==n.publicKey)throw Error(`bundle signing keys do not match: ${t}`);return{privateKey:n.privateKey,publicKey:n.publicKey,revision:r}}function b(e){return _(e,()=>{let t=u.join(e,d);try{let n=l.lstatSync(t);if(!n.isFile()||n.isSymbolicLink())throw Error(`invalid bundle signing state file: ${t}`);let r=JSON.parse(l.readFileSync(t,`utf8`)),i=y(r,t);return l.chmodSync(t,384),r.revision===void 0&&v(e,i),i}catch(e){if(e.code!==`ENOENT`)throw e}let n=s(`ec`,{namedCurve:`prime256v1`,privateKeyEncoding:{type:`pkcs8`,format:`pem`},publicKeyEncoding:{type:`spki`,format:`der`}}),r={privateKey:n.privateKey,publicKey:Buffer.from(n.publicKey).toString(`base64url`),revision:0};return v(e,r),r})}function x(e,t){return _(e,()=>{let n=u.join(e,d),r=y(JSON.parse(l.readFileSync(n,`utf8`)),n);if(r.publicKey!==t)throw Error(`bundle signing key changed while the signer was active`);if(r.revision===2**53-1)throw Error(`bundle signing revision is exhausted`);let i={...r,revision:r.revision+1};return v(e,i),i.revision})}function S(e){return h[u.extname(e).toLowerCase()]??`application/octet-stream`}function C(e,t,n){let i=l.readdirSync(t,{withFileTypes:!0});for(let a of i){let i=u.join(t,a.name),o=l.lstatSync(i);if(o.isSymbolicLink())throw Error(`refusing to sign symbolic link: ${i}`);if(o.isDirectory()){C(e,i,n);continue}if(!o.isFile())throw Error(`refusing to omit unsupported asset: ${i}`);if(p.has(u.extname(a.name)))continue;let s=l.readFileSync(i);n.push({path:`/${u.relative(e,i).split(u.sep).map(e=>encodeURIComponent(e)).join(`/`)}`,sha256:r(`sha256`).update(s).digest(`hex`),byteLength:s.byteLength,contentType:S(i)})}}function w(r,a=()=>{}){let s=b(r),c=i(s.privateKey),d=/* @__PURE__ */ new Map,p=(e,t)=>`${t}:${u.resolve(e)}`,h=(e,i)=>{let a=l.lstatSync(e);if(!a.isDirectory()||a.isSymbolicLink())throw Error(`refusing to sign an unsafe asset root: ${e}`);let u=[];if(C(e,e,u),u.length===0)return;u.sort((e,t)=>e.path.localeCompare(t.path));let d={version:2,revision:x(r,s.publicKey),builtAt:Date.now(),assets:u};if(!n(d,i))throw Error(`refusing to sign an invalid ${i} bundle manifest`);return{manifest:d,signature:o(f).update(t(d)).sign({key:c,dsaEncoding:`ieee-p1363`}).toString(`base64url`),publicKey:s.publicKey}},g=(e,t=`web`)=>{let n=p(e,t);if(d.has(n))return d.get(n);let r=h(u.resolve(e),t);return d.set(n,r),r};return{publicKey:()=>s.publicKey,sign:g,refresh(e,t=`web`){return d.delete(p(e,t)),g(e,t)},invalidate(e){if(e===void 0)d.clear();else for(let t of m)d.delete(p(e,t))},attest(t,n){return o(f).update(e(t,n)).sign({key:c,dsaEncoding:`ieee-p1363`}).toString(`base64url`)}}}function T(e){return Buffer.from(a(e).export({type:`spki`,format:`der`})).toString(`base64url`)}export{w as createBundleSigner,T as publicKeyOf};
|
|
1
|
+
import{attestationBytes as e,canonicalManifest as t,isBundleManifest as n}from"../../types/bundleManifest.mjs";import{createHash as r,createPrivateKey as i,createPublicKey as a,createSign as o,generateKeyPairSync as s,randomBytes as c}from"node:crypto";import l from"node:fs";import u from"node:path";const d=`signing.json`,f=`sha256`,p=/* @__PURE__ */ new Set([`.map`]),m=[`web`,`native`,`app`],h={".css":`text/css`,".gif":`image/gif`,".html":`text/html`,".ico":`image/x-icon`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".js":`text/javascript`,".json":`application/json`,".mjs":`text/javascript`,".png":`image/png`,".svg":`image/svg+xml`,".txt":`text/plain`,".wasm":`application/wasm`,".webp":`image/webp`,".woff":`font/woff`,".woff2":`font/woff2`};function g(e){l.mkdirSync(e,{recursive:!0,mode:448});let t=l.lstatSync(e);if(!t.isDirectory()||t.isSymbolicLink())throw Error(`bundle signing state is not a directory: ${e}`);l.chmodSync(e,448)}function _(e,t){g(e);let n=u.join(e,`signing.lock`),r;for(let e=0;e<500;e+=1)try{r=l.openSync(n,`wx`,384);break}catch(e){if(e.code!==`EEXIST`)throw e;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}if(r===void 0)throw Error(`timed out waiting for bundle signing state lock: ${n}`);try{return t()}finally{l.closeSync(r),l.rmSync(n,{force:!0})}}function v(e,t){let n=u.join(e,d),r=u.join(e,`.${d}.${process.pid}.${c(8).toString(`hex`)}`),i=l.openSync(r,`wx`,384);try{l.writeFileSync(i,`${JSON.stringify(t,void 0,2)}\n`),l.fsyncSync(i)}finally{l.closeSync(i)}try{l.renameSync(r,n),l.chmodSync(n,384)}catch(e){throw l.rmSync(r,{force:!0}),e}}function y(e,t){if(typeof e!=`object`||!e)throw Error(`invalid bundle signing state: ${t}`);let n=e;if(typeof n.privateKey!=`string`||typeof n.publicKey!=`string`)throw Error(`invalid bundle signing state: ${t}`);let r=n.revision===void 0?0:n.revision;if(!Number.isSafeInteger(r)||r<0)throw Error(`invalid bundle signing revision: ${t}`);let i;try{i=T(n.privateKey)}catch{throw Error(`invalid bundle signing private key: ${t}`)}if(i!==n.publicKey)throw Error(`bundle signing keys do not match: ${t}`);return{privateKey:n.privateKey,publicKey:n.publicKey,revision:r}}function b(e){return _(e,()=>{let t=u.join(e,d);try{let n=l.lstatSync(t);if(!n.isFile()||n.isSymbolicLink())throw Error(`invalid bundle signing state file: ${t}`);let r=JSON.parse(l.readFileSync(t,`utf8`)),i=y(r,t);return l.chmodSync(t,384),r.revision===void 0&&v(e,i),i}catch(e){if(e.code!==`ENOENT`)throw e}let n=s(`ec`,{namedCurve:`prime256v1`,privateKeyEncoding:{type:`pkcs8`,format:`pem`},publicKeyEncoding:{type:`spki`,format:`der`}}),r={privateKey:n.privateKey,publicKey:Buffer.from(n.publicKey).toString(`base64url`),revision:0};return v(e,r),r})}function x(e,t){return _(e,()=>{let n=u.join(e,d),r=y(JSON.parse(l.readFileSync(n,`utf8`)),n);if(r.publicKey!==t)throw Error(`bundle signing key changed while the signer was active`);if(r.revision===2**53-1)throw Error(`bundle signing revision is exhausted`);let i={...r,revision:r.revision+1};return v(e,i),i.revision})}function S(e){return h[u.extname(e).toLowerCase()]??`application/octet-stream`}function C(e,t,n){let i=l.readdirSync(t,{withFileTypes:!0});for(let a of i){let i=u.join(t,a.name),o=l.lstatSync(i);if(o.isSymbolicLink())throw Error(`refusing to sign symbolic link: ${i}`);if(o.isDirectory()){C(e,i,n);continue}if(!o.isFile())throw Error(`refusing to omit unsupported asset: ${i}`);if(p.has(u.extname(a.name)))continue;let s=l.readFileSync(i);n.push({path:`/${u.relative(e,i).split(u.sep).map(e=>encodeURIComponent(e)).join(`/`)}`,sha256:r(`sha256`).update(s).digest(`hex`),byteLength:s.byteLength,contentType:S(i)})}}function w(r,a=()=>{}){let s=b(r),c=i(s.privateKey),d=/* @__PURE__ */ new Map,p=(e,t)=>`${t}:${u.resolve(e)}`,h=(e,i)=>{let a=l.lstatSync(e);if(!a.isDirectory()||a.isSymbolicLink())throw Error(`refusing to sign an unsafe asset root: ${e}`);let u=[];if(C(e,e,u),u.length===0)return;u.sort((e,t)=>e.path.localeCompare(t.path));let d={version:2,revision:x(r,s.publicKey),builtAt:Date.now(),assets:u};if(!n(d,i))throw Error(`refusing to sign an invalid ${i} bundle manifest`);return{manifest:d,signature:o(f).update(t(d)).sign({key:c,dsaEncoding:`ieee-p1363`}).toString(`base64url`),publicKey:s.publicKey}},g=(e,t=`web`)=>{let n=p(e,t);if(d.has(n))return d.get(n);let r=h(u.resolve(e),t);return d.set(n,r),r};return{publicKey:()=>s.publicKey,sign:g,refresh(e,t=`web`){return d.delete(p(e,t)),g(e,t)},invalidate(e){if(e===void 0)d.clear();else for(let t of m)d.delete(p(e,t))},attest(t,n){return o(f).update(e(t,n)).sign({key:c,dsaEncoding:`ieee-p1363`}).toString(`base64url`)}}}function T(e){return Buffer.from(a(e).export({type:`spki`,format:`der`})).toString(`base64url`)}export{w as createBundleSigner,T as publicKeyOf};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["fs","path","SIGNING_FILE","SIGN_ALGORITHM","SKIPPED","PROFILES","MIME_TYPES","ensureStateDirectory","stateDir","stat","withStateLock","lockPath","descriptor","attempt","error","operation","atomicWriteState","destination","temporary","randomBytes","state","parseState","value","keyPath","candidate","revision","derived","publicKeyOf","loadOrCreateState","parsed","pair","generateKeyPairSync","reserveRevision","expectedPublicKey","next","contentTypeFor","filePath","walk","entries","current","entry","full","root","into","bytes","segment","createHash","createBundleSigner","key","privateKey","createPrivateKey","cache","cacheKeyOf","profile","assetsDir","signFresh","rootStat","assets","left","right","manifest","isBundleManifest","createSign","canonicalManifest","sign","cacheKey","signed","attestationBytes","tag","fields","createPublicKey","privateKeyPem"],"sources":["../../../src/services/bundleSigner/index.ts"],"sourcesContent":["import {\n createHash,\n createPrivateKey,\n createPublicKey,\n createSign,\n generateKeyPairSync,\n randomBytes,\n} from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport {\n BUNDLE_MANIFEST_VERSION,\n type BundleAsset,\n type BundleManifest,\n type BundleProfile,\n type SignedBundleManifest,\n attestationBytes,\n canonicalManifest,\n isBundleManifest,\n} from '../../types/bundleManifest';\n\nconst SIGNING_FILE = 'signing.json';\nconst LOCK_FILE = 'signing.lock';\nconst FILE_MODE = 0o600;\nconst DIRECTORY_MODE = 0o700;\nconst CURVE = 'prime256v1';\nconst SIGN_ALGORITHM = 'sha256';\nconst SKIPPED = new Set(['.map']);\nconst PROFILES: readonly BundleProfile[] = ['web', 'native'];\nconst MIME_TYPES: Readonly<Record<string, string>> = {\n '.css': 'text/css',\n '.gif': 'image/gif',\n '.html': 'text/html',\n '.ico': 'image/x-icon',\n '.jpeg': 'image/jpeg',\n '.jpg': 'image/jpeg',\n '.js': 'text/javascript',\n '.json': 'application/json',\n '.mjs': 'text/javascript',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.txt': 'text/plain',\n '.wasm': 'application/wasm',\n '.webp': 'image/webp',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n};\n\nexport interface BundleSigner {\n /** Base64url SPKI for an independently trusted verifier to pin. */\n publicKey(): string;\n /**\n * Hashes and signs once per asset directory and profile. Undefined when the bundle is empty. Throws\n * when the assets do not match the profile.\n */\n sign(assetsDir: string, profile?: BundleProfile): SignedBundleManifest | undefined;\n /** Invalidates and immediately rebuilds one cached manifest. */\n refresh(assetsDir: string, profile?: BundleProfile): SignedBundleManifest | undefined;\n /** Invalidates one cached directory under every profile, or every cached directory when omitted. */\n invalidate(assetsDir?: string): void;\n /**\n * Base64url IEEE P1363 signature over `attestationBytes(tag, fields)` with the bundle key. Throws on a\n * malformed tag.\n */\n attest(tag: string, fields: readonly string[]): string;\n}\n\ninterface StoredState {\n privateKey: string;\n publicKey: string;\n revision: number;\n}\n\nfunction ensureStateDirectory(stateDir: string): void {\n fs.mkdirSync(stateDir, { recursive: true, mode: DIRECTORY_MODE });\n const stat = fs.lstatSync(stateDir);\n if (!stat.isDirectory() || stat.isSymbolicLink())\n throw new Error(`bundle signing state is not a directory: ${stateDir}`);\n fs.chmodSync(stateDir, DIRECTORY_MODE);\n}\n\nfunction withStateLock<T>(stateDir: string, operation: () => T): T {\n ensureStateDirectory(stateDir);\n const lockPath = path.join(stateDir, LOCK_FILE);\n let descriptor: number | undefined;\n for (let attempt = 0; attempt < 500; attempt += 1) {\n try {\n descriptor = fs.openSync(lockPath, 'wx', FILE_MODE);\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);\n }\n }\n if (descriptor === undefined) throw new Error(`timed out waiting for bundle signing state lock: ${lockPath}`);\n try {\n return operation();\n } finally {\n fs.closeSync(descriptor);\n fs.rmSync(lockPath, { force: true });\n }\n}\n\nfunction atomicWriteState(stateDir: string, state: StoredState): void {\n const destination = path.join(stateDir, SIGNING_FILE);\n const temporary = path.join(stateDir, `.${SIGNING_FILE}.${process.pid}.${randomBytes(8).toString('hex')}`);\n const descriptor = fs.openSync(temporary, 'wx', FILE_MODE);\n try {\n fs.writeFileSync(descriptor, `${JSON.stringify(state, undefined, 2)}\\n`);\n fs.fsyncSync(descriptor);\n } finally {\n fs.closeSync(descriptor);\n }\n try {\n fs.renameSync(temporary, destination);\n fs.chmodSync(destination, FILE_MODE);\n } catch (error) {\n fs.rmSync(temporary, { force: true });\n throw error;\n }\n}\n\nfunction parseState(value: unknown, keyPath: string): StoredState {\n if (typeof value !== 'object' || value === null) throw new Error(`invalid bundle signing state: ${keyPath}`);\n const candidate = value as Partial<StoredState>;\n if (typeof candidate.privateKey !== 'string' || typeof candidate.publicKey !== 'string') {\n throw new Error(`invalid bundle signing state: ${keyPath}`);\n }\n const revision = candidate.revision === undefined ? 0 : candidate.revision;\n if (!Number.isSafeInteger(revision) || revision < 0) throw new Error(`invalid bundle signing revision: ${keyPath}`);\n let derived: string;\n try {\n derived = publicKeyOf(candidate.privateKey);\n } catch {\n throw new Error(`invalid bundle signing private key: ${keyPath}`);\n }\n if (derived !== candidate.publicKey) throw new Error(`bundle signing keys do not match: ${keyPath}`);\n return { privateKey: candidate.privateKey, publicKey: candidate.publicKey, revision };\n}\n\nfunction loadOrCreateState(stateDir: string): StoredState {\n return withStateLock(stateDir, () => {\n const keyPath = path.join(stateDir, SIGNING_FILE);\n try {\n const stat = fs.lstatSync(keyPath);\n if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`invalid bundle signing state file: ${keyPath}`);\n const parsed: unknown = JSON.parse(fs.readFileSync(keyPath, 'utf8'));\n const state = parseState(parsed, keyPath);\n fs.chmodSync(keyPath, FILE_MODE);\n if ((parsed as Partial<StoredState>).revision === undefined) atomicWriteState(stateDir, state);\n return state;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n\n const pair = generateKeyPairSync('ec', {\n namedCurve: CURVE,\n privateKeyEncoding: { type: 'pkcs8', format: 'pem' },\n publicKeyEncoding: { type: 'spki', format: 'der' },\n });\n const state: StoredState = {\n privateKey: pair.privateKey,\n publicKey: Buffer.from(pair.publicKey).toString('base64url'),\n revision: 0,\n };\n atomicWriteState(stateDir, state);\n return state;\n });\n}\n\nfunction reserveRevision(stateDir: string, expectedPublicKey: string): number {\n return withStateLock(stateDir, () => {\n const keyPath = path.join(stateDir, SIGNING_FILE);\n const state = parseState(JSON.parse(fs.readFileSync(keyPath, 'utf8')) as unknown, keyPath);\n if (state.publicKey !== expectedPublicKey)\n throw new Error('bundle signing key changed while the signer was active');\n if (state.revision === Number.MAX_SAFE_INTEGER) throw new Error('bundle signing revision is exhausted');\n const next = { ...state, revision: state.revision + 1 };\n atomicWriteState(stateDir, next);\n return next.revision;\n });\n}\n\nfunction contentTypeFor(filePath: string): string {\n return MIME_TYPES[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream';\n}\n\n/** Every servable regular file under the asset root, as browser paths. */\nfunction walk(root: string, current: string, into: BundleAsset[]): void {\n const entries = fs.readdirSync(current, { withFileTypes: true });\n for (const entry of entries) {\n const full = path.join(current, entry.name);\n const stat = fs.lstatSync(full);\n if (stat.isSymbolicLink()) throw new Error(`refusing to sign symbolic link: ${full}`);\n if (stat.isDirectory()) {\n walk(root, full, into);\n continue;\n }\n if (!stat.isFile()) throw new Error(`refusing to omit unsupported asset: ${full}`);\n if (SKIPPED.has(path.extname(entry.name))) continue;\n const bytes = fs.readFileSync(full);\n into.push({\n path: `/${path\n .relative(root, full)\n .split(path.sep)\n .map((segment) => encodeURIComponent(segment))\n .join('/')}`,\n sha256: createHash('sha256').update(bytes).digest('hex'),\n byteLength: bytes.byteLength,\n contentType: contentTypeFor(full),\n });\n }\n}\n\nexport function createBundleSigner(stateDir: string, _onNotice: (message: string) => void = () => {}): BundleSigner {\n const key = loadOrCreateState(stateDir);\n const privateKey = createPrivateKey(key.privateKey);\n const cache = new Map<string, SignedBundleManifest | undefined>();\n const cacheKeyOf = (assetsDir: string, profile: BundleProfile): string => `${profile}:${path.resolve(assetsDir)}`;\n\n const signFresh = (assetsDir: string, profile: BundleProfile): SignedBundleManifest | undefined => {\n const rootStat = fs.lstatSync(assetsDir);\n if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {\n throw new Error(`refusing to sign an unsafe asset root: ${assetsDir}`);\n }\n const assets: BundleAsset[] = [];\n walk(assetsDir, assetsDir, assets);\n if (assets.length === 0) return undefined;\n assets.sort((left, right) => left.path.localeCompare(right.path));\n const manifest: BundleManifest = {\n version: BUNDLE_MANIFEST_VERSION,\n revision: reserveRevision(stateDir, key.publicKey),\n builtAt: Date.now(),\n assets,\n };\n if (!isBundleManifest(manifest, profile)) throw new Error(`refusing to sign an invalid ${profile} bundle manifest`);\n const signature = createSign(SIGN_ALGORITHM)\n .update(canonicalManifest(manifest))\n .sign({ key: privateKey, dsaEncoding: 'ieee-p1363' })\n .toString('base64url');\n return { manifest, signature, publicKey: key.publicKey };\n };\n\n const sign = (assetsDir: string, profile: BundleProfile = 'web'): SignedBundleManifest | undefined => {\n const cacheKey = cacheKeyOf(assetsDir, profile);\n if (cache.has(cacheKey)) return cache.get(cacheKey);\n const signed = signFresh(path.resolve(assetsDir), profile);\n cache.set(cacheKey, signed);\n return signed;\n };\n\n return {\n publicKey: () => key.publicKey,\n sign,\n refresh(assetsDir, profile = 'web') {\n cache.delete(cacheKeyOf(assetsDir, profile));\n return sign(assetsDir, profile);\n },\n invalidate(assetsDir) {\n if (assetsDir === undefined) {\n cache.clear();\n return;\n }\n for (const profile of PROFILES) cache.delete(cacheKeyOf(assetsDir, profile));\n },\n attest(tag, fields) {\n return createSign(SIGN_ALGORITHM)\n .update(attestationBytes(tag, fields))\n .sign({ key: privateKey, dsaEncoding: 'ieee-p1363' })\n .toString('base64url');\n },\n };\n}\n\n/** Re-derives the public key from a stored private key. */\nexport function publicKeyOf(privateKeyPem: string): string {\n return Buffer.from(createPublicKey(privateKeyPem).export({ type: 'spki', format: 'der' }) as Buffer).toString(\n 'base64url',\n );\n}\n"],"mappings":"6SAsBA,MAAME,EAAe,eAKfC,EAAiB,SACjBC,kBAAU,IAAI,IAAI,CAAC,MAAM,CAAC,EAC1BC,EAAqC,CAAC,MAAO,QAAQ,EACrDC,EAA+C,CACnD,OAAQ,WACR,OAAQ,YACR,QAAS,YACT,OAAQ,eACR,QAAS,aACT,OAAQ,aACR,MAAO,kBACP,QAAS,mBACT,OAAQ,kBACR,OAAQ,YACR,OAAQ,gBACR,OAAQ,aACR,QAAS,mBACT,QAAS,aACT,QAAS,YACT,SAAU,YACZ,EA2BA,SAASC,EAAqB,EAAwB,CACpDP,EAAG,UAAUQ,EAAU,CAAE,UAAW,GAAM,KAAM,GAAe,CAAC,EAChE,IAAMC,EAAOT,EAAG,UAAUQ,CAAQ,EAClC,GAAI,CAACC,EAAK,YAAY,GAAKA,EAAK,eAAe,EAC7C,MAAU,MAAM,4CAA4CD,GAAU,EACxER,EAAG,UAAUQ,EAAU,GAA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G,IAAMC,EAAWb,EAAWE,EAAWD,CAAO,EAC9C,GAAIF,EAAM,IAAIc,CAAQ,EAAG,OAAOd,EAAM,IAAIc,CAAQ,EAClD,IAAMC,EAASX,EAAUtD,EAAK,QAAQqD,CAAS,EAAGD,CAAO,EAEzD,OADAF,EAAM,IAAIc,EAAUC,CAAM,EACnBA,CACT,EAEA,MAAO,CACL,cAAiBlB,EAAI,UACrB,OACA,QAAQ,EAAW,EAAU,MAAO,CAElC,OADAG,EAAM,OAAOC,EAAWE,EAAWD,CAAO,CAAC,EACpCW,EAAKV,EAAWD,CAAO,CAChC,EACA,WAAW,EAAW,CACpB,GAAIC,IAAc,IAAA,GAChBH,EAAM,MAAM,OAGd,IAAK,IAAME,KAAWhD,EAAU8C,EAAM,OAAOC,EAAWE,EAAWD,CAAO,CAAC,CAC7E,EACA,OAAO,EAAK,EAAQ,CAClB,OAAOS,EAAW3D,CAAc,CAAC,CAC9B,OAAOgE,EAAiBC,EAAKC,CAAM,CAAC,CAAC,CACrC,KAAK,CAAE,IAAKpB,EAAY,YAAa,YAAa,CAAC,CAAC,CACpD,SAAS,WAAW,CACzB,CACF,CACF,CAGA,SAAgBtB,EAAY,EAA+B,CACzD,OAAO,OAAO,KAAK2C,EAAgBC,CAAa,CAAC,CAAC,OAAO,CAAE,KAAM,OAAQ,OAAQ,KAAM,CAAC,CAAW,CAAC,CAAC,SACnG,WACF,CACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["fs","path","SIGNING_FILE","SIGN_ALGORITHM","SKIPPED","PROFILES","MIME_TYPES","ensureStateDirectory","stateDir","stat","withStateLock","lockPath","descriptor","attempt","error","operation","atomicWriteState","destination","temporary","randomBytes","state","parseState","value","keyPath","candidate","revision","derived","publicKeyOf","loadOrCreateState","parsed","pair","generateKeyPairSync","reserveRevision","expectedPublicKey","next","contentTypeFor","filePath","walk","entries","current","entry","full","root","into","bytes","segment","createHash","createBundleSigner","key","privateKey","createPrivateKey","cache","cacheKeyOf","profile","assetsDir","signFresh","rootStat","assets","left","right","manifest","isBundleManifest","createSign","canonicalManifest","sign","cacheKey","signed","attestationBytes","tag","fields","createPublicKey","privateKeyPem"],"sources":["../../../src/services/bundleSigner/index.ts"],"sourcesContent":["import {\n createHash,\n createPrivateKey,\n createPublicKey,\n createSign,\n generateKeyPairSync,\n randomBytes,\n} from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport {\n BUNDLE_MANIFEST_VERSION,\n type BundleAsset,\n type BundleManifest,\n type BundleProfile,\n type SignedBundleManifest,\n attestationBytes,\n canonicalManifest,\n isBundleManifest,\n} from '../../types/bundleManifest';\n\nconst SIGNING_FILE = 'signing.json';\nconst LOCK_FILE = 'signing.lock';\nconst FILE_MODE = 0o600;\nconst DIRECTORY_MODE = 0o700;\nconst CURVE = 'prime256v1';\nconst SIGN_ALGORITHM = 'sha256';\nconst SKIPPED = new Set(['.map']);\nconst PROFILES: readonly BundleProfile[] = ['web', 'native', 'app'];\nconst MIME_TYPES: Readonly<Record<string, string>> = {\n '.css': 'text/css',\n '.gif': 'image/gif',\n '.html': 'text/html',\n '.ico': 'image/x-icon',\n '.jpeg': 'image/jpeg',\n '.jpg': 'image/jpeg',\n '.js': 'text/javascript',\n '.json': 'application/json',\n '.mjs': 'text/javascript',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.txt': 'text/plain',\n '.wasm': 'application/wasm',\n '.webp': 'image/webp',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n};\n\nexport interface BundleSigner {\n /** Base64url SPKI for an independently trusted verifier to pin. */\n publicKey(): string;\n /**\n * Hashes and signs once per asset directory and profile. Undefined when the bundle is empty. Throws\n * when the assets do not match the profile.\n */\n sign(assetsDir: string, profile?: BundleProfile): SignedBundleManifest | undefined;\n /** Invalidates and immediately rebuilds one cached manifest. */\n refresh(assetsDir: string, profile?: BundleProfile): SignedBundleManifest | undefined;\n /** Invalidates one cached directory under every profile, or every cached directory when omitted. */\n invalidate(assetsDir?: string): void;\n /**\n * Base64url IEEE P1363 signature over `attestationBytes(tag, fields)` with the bundle key. Throws on a\n * malformed tag.\n */\n attest(tag: string, fields: readonly string[]): string;\n}\n\ninterface StoredState {\n privateKey: string;\n publicKey: string;\n revision: number;\n}\n\nfunction ensureStateDirectory(stateDir: string): void {\n fs.mkdirSync(stateDir, { recursive: true, mode: DIRECTORY_MODE });\n const stat = fs.lstatSync(stateDir);\n if (!stat.isDirectory() || stat.isSymbolicLink())\n throw new Error(`bundle signing state is not a directory: ${stateDir}`);\n fs.chmodSync(stateDir, DIRECTORY_MODE);\n}\n\nfunction withStateLock<T>(stateDir: string, operation: () => T): T {\n ensureStateDirectory(stateDir);\n const lockPath = path.join(stateDir, LOCK_FILE);\n let descriptor: number | undefined;\n for (let attempt = 0; attempt < 500; attempt += 1) {\n try {\n descriptor = fs.openSync(lockPath, 'wx', FILE_MODE);\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);\n }\n }\n if (descriptor === undefined) throw new Error(`timed out waiting for bundle signing state lock: ${lockPath}`);\n try {\n return operation();\n } finally {\n fs.closeSync(descriptor);\n fs.rmSync(lockPath, { force: true });\n }\n}\n\nfunction atomicWriteState(stateDir: string, state: StoredState): void {\n const destination = path.join(stateDir, SIGNING_FILE);\n const temporary = path.join(stateDir, `.${SIGNING_FILE}.${process.pid}.${randomBytes(8).toString('hex')}`);\n const descriptor = fs.openSync(temporary, 'wx', FILE_MODE);\n try {\n fs.writeFileSync(descriptor, `${JSON.stringify(state, undefined, 2)}\\n`);\n fs.fsyncSync(descriptor);\n } finally {\n fs.closeSync(descriptor);\n }\n try {\n fs.renameSync(temporary, destination);\n fs.chmodSync(destination, FILE_MODE);\n } catch (error) {\n fs.rmSync(temporary, { force: true });\n throw error;\n }\n}\n\nfunction parseState(value: unknown, keyPath: string): StoredState {\n if (typeof value !== 'object' || value === null) throw new Error(`invalid bundle signing state: ${keyPath}`);\n const candidate = value as Partial<StoredState>;\n if (typeof candidate.privateKey !== 'string' || typeof candidate.publicKey !== 'string') {\n throw new Error(`invalid bundle signing state: ${keyPath}`);\n }\n const revision = candidate.revision === undefined ? 0 : candidate.revision;\n if (!Number.isSafeInteger(revision) || revision < 0) throw new Error(`invalid bundle signing revision: ${keyPath}`);\n let derived: string;\n try {\n derived = publicKeyOf(candidate.privateKey);\n } catch {\n throw new Error(`invalid bundle signing private key: ${keyPath}`);\n }\n if (derived !== candidate.publicKey) throw new Error(`bundle signing keys do not match: ${keyPath}`);\n return { privateKey: candidate.privateKey, publicKey: candidate.publicKey, revision };\n}\n\nfunction loadOrCreateState(stateDir: string): StoredState {\n return withStateLock(stateDir, () => {\n const keyPath = path.join(stateDir, SIGNING_FILE);\n try {\n const stat = fs.lstatSync(keyPath);\n if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`invalid bundle signing state file: ${keyPath}`);\n const parsed: unknown = JSON.parse(fs.readFileSync(keyPath, 'utf8'));\n const state = parseState(parsed, keyPath);\n fs.chmodSync(keyPath, FILE_MODE);\n if ((parsed as Partial<StoredState>).revision === undefined) atomicWriteState(stateDir, state);\n return state;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n\n const pair = generateKeyPairSync('ec', {\n namedCurve: CURVE,\n privateKeyEncoding: { type: 'pkcs8', format: 'pem' },\n publicKeyEncoding: { type: 'spki', format: 'der' },\n });\n const state: StoredState = {\n privateKey: pair.privateKey,\n publicKey: Buffer.from(pair.publicKey).toString('base64url'),\n revision: 0,\n };\n atomicWriteState(stateDir, state);\n return state;\n });\n}\n\nfunction reserveRevision(stateDir: string, expectedPublicKey: string): number {\n return withStateLock(stateDir, () => {\n const keyPath = path.join(stateDir, SIGNING_FILE);\n const state = parseState(JSON.parse(fs.readFileSync(keyPath, 'utf8')) as unknown, keyPath);\n if (state.publicKey !== expectedPublicKey)\n throw new Error('bundle signing key changed while the signer was active');\n if (state.revision === Number.MAX_SAFE_INTEGER) throw new Error('bundle signing revision is exhausted');\n const next = { ...state, revision: state.revision + 1 };\n atomicWriteState(stateDir, next);\n return next.revision;\n });\n}\n\nfunction contentTypeFor(filePath: string): string {\n return MIME_TYPES[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream';\n}\n\n/** Every servable regular file under the asset root, as browser paths. */\nfunction walk(root: string, current: string, into: BundleAsset[]): void {\n const entries = fs.readdirSync(current, { withFileTypes: true });\n for (const entry of entries) {\n const full = path.join(current, entry.name);\n const stat = fs.lstatSync(full);\n if (stat.isSymbolicLink()) throw new Error(`refusing to sign symbolic link: ${full}`);\n if (stat.isDirectory()) {\n walk(root, full, into);\n continue;\n }\n if (!stat.isFile()) throw new Error(`refusing to omit unsupported asset: ${full}`);\n if (SKIPPED.has(path.extname(entry.name))) continue;\n const bytes = fs.readFileSync(full);\n into.push({\n path: `/${path\n .relative(root, full)\n .split(path.sep)\n .map((segment) => encodeURIComponent(segment))\n .join('/')}`,\n sha256: createHash('sha256').update(bytes).digest('hex'),\n byteLength: bytes.byteLength,\n contentType: contentTypeFor(full),\n });\n }\n}\n\nexport function createBundleSigner(stateDir: string, _onNotice: (message: string) => void = () => {}): BundleSigner {\n const key = loadOrCreateState(stateDir);\n const privateKey = createPrivateKey(key.privateKey);\n const cache = new Map<string, SignedBundleManifest | undefined>();\n const cacheKeyOf = (assetsDir: string, profile: BundleProfile): string => `${profile}:${path.resolve(assetsDir)}`;\n\n const signFresh = (assetsDir: string, profile: BundleProfile): SignedBundleManifest | undefined => {\n const rootStat = fs.lstatSync(assetsDir);\n if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {\n throw new Error(`refusing to sign an unsafe asset root: ${assetsDir}`);\n }\n const assets: BundleAsset[] = [];\n walk(assetsDir, assetsDir, assets);\n if (assets.length === 0) return undefined;\n assets.sort((left, right) => left.path.localeCompare(right.path));\n const manifest: BundleManifest = {\n version: BUNDLE_MANIFEST_VERSION,\n revision: reserveRevision(stateDir, key.publicKey),\n builtAt: Date.now(),\n assets,\n };\n if (!isBundleManifest(manifest, profile)) throw new Error(`refusing to sign an invalid ${profile} bundle manifest`);\n const signature = createSign(SIGN_ALGORITHM)\n .update(canonicalManifest(manifest))\n .sign({ key: privateKey, dsaEncoding: 'ieee-p1363' })\n .toString('base64url');\n return { manifest, signature, publicKey: key.publicKey };\n };\n\n const sign = (assetsDir: string, profile: BundleProfile = 'web'): SignedBundleManifest | undefined => {\n const cacheKey = cacheKeyOf(assetsDir, profile);\n if (cache.has(cacheKey)) return cache.get(cacheKey);\n const signed = signFresh(path.resolve(assetsDir), profile);\n cache.set(cacheKey, signed);\n return signed;\n };\n\n return {\n publicKey: () => key.publicKey,\n sign,\n refresh(assetsDir, profile = 'web') {\n cache.delete(cacheKeyOf(assetsDir, profile));\n return sign(assetsDir, profile);\n },\n invalidate(assetsDir) {\n if (assetsDir === undefined) {\n cache.clear();\n return;\n }\n for (const profile of PROFILES) cache.delete(cacheKeyOf(assetsDir, profile));\n },\n attest(tag, fields) {\n return createSign(SIGN_ALGORITHM)\n .update(attestationBytes(tag, fields))\n .sign({ key: privateKey, dsaEncoding: 'ieee-p1363' })\n .toString('base64url');\n },\n };\n}\n\n/** Re-derives the public key from a stored private key. */\nexport function publicKeyOf(privateKeyPem: string): string {\n return Buffer.from(createPublicKey(privateKeyPem).export({ type: 'spki', format: 'der' }) as Buffer).toString(\n 'base64url',\n );\n}\n"],"mappings":"6SAsBA,MAAME,EAAe,eAKfC,EAAiB,SACjBC,kBAAU,IAAI,IAAI,CAAC,MAAM,CAAC,EAC1BC,EAAqC,CAAC,MAAO,SAAU,KAAK,EAC5DC,EAA+C,CACnD,OAAQ,WACR,OAAQ,YACR,QAAS,YACT,OAAQ,eACR,QAAS,aACT,OAAQ,aACR,MAAO,kBACP,QAAS,mBACT,OAAQ,kBACR,OAAQ,YACR,OAAQ,gBACR,OAAQ,aACR,QAAS,mBACT,QAAS,aACT,QAAS,YACT,SAAU,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index.cjs"),r=new TextEncoder,i=new TextDecoder;function a(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function o(e){let t=atob(e);return Uint8Array.from(t,e=>e.charCodeAt(0))}async function s(e){if(e!=null){if(typeof e==`string`)return r.encode(e);if(e instanceof URLSearchParams)return r.encode(e.toString());if(e instanceof Blob)return new Uint8Array(await e.arrayBuffer());if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error(`The sealed HTTP transport does not support this request body type.`)}}function c(e){if(!e.startsWith(`/`))throw Error(`A sealed HTTP request must use a root-relative URL.`);return e}function l(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.v===1&&typeof t.status==`number`&&Array.isArray(t.headers)&&t.headers.every(e=>Array.isArray(e)&&e.length===2&&e.every(e=>typeof e==`string`))&&typeof t.body==`string`}function u(){let u,d,f=n.createSerialQueue(),
|
|
1
|
+
const e=require("../../types/sealedChannel.cjs"),t=require("../browserSealedChannel/index.cjs"),n=require("../serialQueue/index.cjs"),r=new TextEncoder,i=new TextDecoder;function a(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function o(e){let t=atob(e);return Uint8Array.from(t,e=>e.charCodeAt(0))}async function s(e){if(e!=null){if(typeof e==`string`)return r.encode(e);if(e instanceof URLSearchParams)return r.encode(e.toString());if(e instanceof Blob)return new Uint8Array(await e.arrayBuffer());if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error(`The sealed HTTP transport does not support this request body type.`)}}function c(e){if(!e.startsWith(`/`))throw Error(`A sealed HTTP request must use a root-relative URL.`);return e}function l(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.v===1&&typeof t.status==`number`&&Array.isArray(t.headers)&&t.headers.every(e=>Array.isArray(e)&&e.length===2&&e.every(e=>typeof e==`string`))&&typeof t.body==`string`}function u(){let u,d,f,p=!1,m=n.createSerialQueue(),h=n.createSerialQueue(),g=n.createSerialQueue(),_,v=t=>{d=e.describeSealedFailure(t)},y=async e=>{if(u===void 0)return;let t=await u.seal(e);return t.ok?JSON.stringify(t.envelope):v(t.failure)},b=async e=>{if(u===void 0)return;let t;try{t=JSON.parse(e)}catch{return v(`malformed`)}let n=await u.open(t);return n.ok?n.plaintext:v(n.failure)};return{active:()=>u!==void 0,invalidate(){p=!0},onAuthorizationFailure(e){f=e},lastFailure:()=>d,async connect(e){let n=await t.connectSealedChannel(e);if(n===void 0)d=`This browser could not establish a sealed channel.`;else return u=n.channel,p=!1,d=void 0,n.clientPublicKey},relayRequestsThrough(e){_=e},reset(){p=!1,u=void 0,d=void 0},async sealText(e){if(p)throw Error(`Sign in to Po again.`);return u===void 0?e:await m.run(async()=>{let t=await y(r.encode(e));if(t===void 0)throw Error(d??`The active sealed channel could not encrypt a message.`);return t})},async openText(e){if(p)throw Error(`Sign in to Po again.`);return u===void 0?e:await h.run(async()=>{let t=await b(e);return t===void 0?void 0:i.decode(t)})},async sealBinary(e){if(p)throw Error(`Sign in to Po again.`);return u===void 0?e:await m.run(async()=>{let t=await y(e);if(t===void 0)throw Error(d??`The active sealed channel could not encrypt a message.`);return r.encode(t)})},async openBinary(e){if(p)throw Error(`Sign in to Po again.`);return u===void 0?e:await h.run(async()=>await b(i.decode(e)))},async fetch(e,t){if(t?.signal?.throwIfAborted(),p)throw Error(`Sign in to Po again.`);let n=_;if(u===void 0||n===void 0)return await fetch(e,t);let m=new AbortController,h=()=>m.abort(t?.signal?.reason),v=setTimeout(()=>m.abort(new DOMException(`The request timed out.`,`TimeoutError`)),3e4);t?.signal?.addEventListener(`abort`,h,{once:!0}),t?.signal?.aborted&&h();let x,S=new Promise((e,t)=>{x=()=>t(m.signal.reason),m.signal.addEventListener(`abort`,x,{once:!0}),m.signal.aborted&&x()}),C=u,w=()=>{if(m.signal.throwIfAborted(),p||u!==C)throw Error(`The sealed channel was replaced.`)};try{return w(),await Promise.race([g.run(()=>Promise.race([(async()=>{w();let u=await s(t?.body);w();let h={v:1,method:(t?.method??`GET`).toUpperCase(),target:c(e),headers:Array.from(new Headers(t?.headers).entries()),...u===void 0?{}:{body:a(u)}},g=await y(r.encode(JSON.stringify(h)));if(w(),g===void 0)return new Response(JSON.stringify({error:d}),{status:502});let _=await fetch(n,{method:`POST`,signal:m.signal,credentials:`same-origin`,headers:{"content-type":`application/json`},body:g});if(w(),_.status===401||_.status===403)throw p=!0,d=`Sign in to Po again.`,f?.(),Error(d);let v=await _.text();w();let x=await b(v);if(w(),x===void 0)return new Response(JSON.stringify({error:d}),{status:502});let S;try{S=JSON.parse(i.decode(x))}catch{S=void 0}if(!l(S))return d=`The sealed HTTP response was malformed.`,new Response(JSON.stringify({error:d}),{status:502});let C=o(S.body);return new Response(S.status===204||S.status===205||S.status===304?null:C,{status:S.status,headers:S.headers})})(),S])),S])}finally{clearTimeout(v),t?.signal?.removeEventListener(`abort`,h),x&&m.signal.removeEventListener(`abort`,x)}}}}const d=u();exports.createSealedTransport=u,exports.sealedTransport=d;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["createSerialQueue","describeSealedFailure","connectSealedChannel","require_sealedChannel","require_index","require_index$1","encoder","decoder","encodeBase64","binary","byte","bytes","decodeBase64","value","character","bodyBytes","body","requestTarget","input","isSealedHttpResponse","candidate","header","part","createSealedTransport","channel","failure","outbound","inbound","exchange","relayPath","note","reason","sealBytes","sealed","openBytes","envelope","text","opened","connected","hostPublicKey","path","gateway","init","request","relayResponse","decoded","sealedTransport"],"sources":["../../../src/services/sealedTransport/index.ts"],"sourcesContent":["import { describeSealedFailure, type SealedFailure } from '../../types/sealedChannel';\nimport { connectSealedChannel, type SealedChannel } from '../browserSealedChannel';\nimport { createSerialQueue } from '../serialQueue';\n\n/**\n * The one object the cockpit and every plugin use to talk over a sealed tunnel.\n *\n * Two things make this worth having rather than each caller reaching for the\n * channel directly. First, ordering: sealing advances a nonce counter and\n * opening enforces that it strictly increases, so both directions are pushed\n * through a serial queue and overlapping calls can never reorder into a\n * self-inflicted replay. Second, reach: a plugin that calls `fetch` itself\n * sends plaintext to whoever is relaying the tunnel, and the host cannot stop\n * it. Giving every caller one obvious helper is the only enforcement available.\n *\n * When no channel is established every method is a pass-through, so the same\n * code runs unchanged on the loopback listener where there is nothing to seal.\n */\n\nconst JSON_CONTENT_TYPE = 'application/json';\n\nexport interface SealedTransport {\n /** False on loopback and before the handshake completes, where everything passes through. */\n active(): boolean;\n sealText(text: string): Promise<string>;\n /** Undefined when the message could not be opened; `lastFailure` says why. */\n openText(text: string): Promise<string | undefined>;\n sealBinary(bytes: Uint8Array): Promise<Uint8Array>;\n openBinary(bytes: Uint8Array): Promise<Uint8Array | undefined>;\n /** Drop-in for `fetch`, relaying the complete request through the sealed channel when configured. */\n fetch(input: string, init?: RequestInit): Promise<Response>;\n lastFailure(): string | undefined;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface SealedHttpRequest {\n v: 1;\n method: string;\n target: string;\n headers: Array<[string, string]>;\n body?: string;\n}\n\ninterface SealedHttpResponse {\n v: 1;\n status: number;\n headers: Array<[string, string]>;\n body: string;\n}\n\nfunction encodeBase64(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nfunction decodeBase64(value: string): Uint8Array {\n const binary = atob(value);\n return Uint8Array.from(binary, (character) => character.charCodeAt(0));\n}\n\nasync function bodyBytes(body: RequestInit['body']): Promise<Uint8Array | undefined> {\n if (body === undefined || body === null) return undefined;\n if (typeof body === 'string') return encoder.encode(body);\n if (body instanceof URLSearchParams) return encoder.encode(body.toString());\n if (body instanceof Blob) return new Uint8Array(await body.arrayBuffer());\n if (body instanceof ArrayBuffer) return new Uint8Array(body);\n if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);\n throw new Error('The sealed HTTP transport does not support this request body type.');\n}\n\nfunction requestTarget(input: string): string {\n if (!input.startsWith('/')) throw new Error('A sealed HTTP request must use a root-relative URL.');\n return input;\n}\n\nfunction isSealedHttpResponse(value: unknown): value is SealedHttpResponse {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as Partial<SealedHttpResponse>;\n return (\n candidate.v === 1 &&\n typeof candidate.status === 'number' &&\n Array.isArray(candidate.headers) &&\n candidate.headers.every(\n (header) => Array.isArray(header) && header.length === 2 && header.every((part) => typeof part === 'string'),\n ) &&\n typeof candidate.body === 'string'\n );\n}\nexport function createSealedTransport(): SealedTransport & {\n /** Completes the handshake against the host key from the QR. */\n connect: (hostPublicKey: string) => Promise<string | undefined>;\n /** Drops the channel, so everything falls back to pass-through. */\n reset: () => void;\n /** Selects the same-origin endpoint that carries sealed HTTP exchanges. */\n relayRequestsThrough: (path: string) => void;\n} {\n let channel: SealedChannel | undefined;\n let failure: string | undefined;\n const outbound = createSerialQueue();\n const inbound = createSerialQueue();\n const exchange = createSerialQueue();\n let relayPath: string | undefined;\n const note = (reason: SealedFailure): undefined => {\n // A decryption failure otherwise shows up as a blank page with no cause, so\n // every one of them names itself.\n failure = describeSealedFailure(reason);\n return undefined;\n };\n\n const sealBytes = async (bytes: Uint8Array): Promise<string | undefined> => {\n if (channel === undefined) return undefined;\n const sealed = await channel.seal(bytes);\n if (!sealed.ok) return note(sealed.failure);\n return JSON.stringify(sealed.envelope);\n };\n\n const openBytes = async (text: string): Promise<Uint8Array | undefined> => {\n if (channel === undefined) return undefined;\n let envelope: unknown;\n try {\n envelope = JSON.parse(text);\n } catch {\n return note('malformed');\n }\n const opened = await channel.open(envelope);\n if (!opened.ok) return note(opened.failure);\n return opened.plaintext;\n };\n\n return {\n active: () => channel !== undefined,\n lastFailure: () => failure,\n\n async connect(hostPublicKey) {\n const connected = await connectSealedChannel(hostPublicKey);\n if (connected === undefined) {\n failure = 'This browser could not establish a sealed channel.';\n return undefined;\n }\n channel = connected.channel;\n failure = undefined;\n return connected.clientPublicKey;\n },\n\n relayRequestsThrough(path) {\n relayPath = path;\n },\n\n reset() {\n channel = undefined;\n failure = undefined;\n },\n\n async sealText(text) {\n if (channel === undefined) return text;\n return await outbound.run(async () => {\n const sealed = await sealBytes(encoder.encode(text));\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return sealed;\n });\n },\n\n async openText(text) {\n if (channel === undefined) return text;\n return await inbound.run(async () => {\n const opened = await openBytes(text);\n return opened === undefined ? undefined : decoder.decode(opened);\n });\n },\n\n async sealBinary(bytes) {\n if (channel === undefined) return bytes;\n return await outbound.run(async () => {\n const sealed = await sealBytes(bytes);\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return encoder.encode(sealed);\n });\n },\n\n async openBinary(bytes) {\n if (channel === undefined) return bytes;\n return await inbound.run(async () => await openBytes(decoder.decode(bytes)));\n },\n\n async fetch(input, init) {\n const gateway = relayPath;\n if (channel === undefined || gateway === undefined) return await fetch(input, init);\n return await exchange.run(async () => {\n const bytes = await bodyBytes(init?.body);\n const request: SealedHttpRequest = {\n v: 1,\n method: (init?.method ?? 'GET').toUpperCase(),\n target: requestTarget(input),\n headers: Array.from(new Headers(init?.headers).entries()),\n ...(bytes === undefined ? {} : { body: encodeBase64(bytes) }),\n };\n const sealed = await sealBytes(encoder.encode(JSON.stringify(request)));\n if (sealed === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const relayResponse = await fetch(gateway, {\n method: 'POST',\n credentials: 'same-origin',\n headers: { 'content-type': JSON_CONTENT_TYPE },\n body: sealed,\n });\n const opened = await openBytes(await relayResponse.text());\n if (opened === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n let decoded: unknown;\n try {\n decoded = JSON.parse(decoder.decode(opened));\n } catch {\n decoded = undefined;\n }\n if (!isSealedHttpResponse(decoded)) {\n failure = 'The sealed HTTP response was malformed.';\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const body = decodeBase64(decoded.body);\n return new Response(decoded.status === 204 || decoded.status === 205 || decoded.status === 304 ? null : body, {\n status: decoded.status,\n headers: decoded.headers,\n });\n });\n },\n };\n}\n\n/**\n * The page's one sealed channel.\n *\n * A module singleton rather than an instance per caller, because the cockpit\n * and every plugin are bundled into the same page and all of them must share\n * one pair of nonce counters. Two transports over one handshake would each\n * start counting at zero and the receiver would reject the second as a replay.\n *\n * Inactive until a handshake completes, and inactive forever on the loopback\n * listener, so `sealedTransport.fetch` is a plain `fetch` there.\n */\nexport const sealedTransport = createSealedTransport();\n"],"mappings":"sIAkCMM,EAAU,IAAI,YACdC,EAAU,IAAI,YAiBpB,SAASC,EAAa,EAA2B,CAC/C,IAAIC,EAAS,GACb,IAAK,IAAMC,KAAQC,EAAO,GAAU,OAAO,aAAaD,CAAI,EAC5D,OAAO,KAAKD,CAAM,CACpB,CAEA,SAASG,EAAa,EAA2B,CAC/C,IAAMH,EAAS,KAAKI,CAAK,EACzB,OAAO,WAAW,KAAKJ,EAAS,GAAcK,EAAU,WAAW,CAAC,CAAC,CACvE,CAEA,eAAeC,EAAU,EAA4D,CACnF,GAAIC,GAA+B,KACnC,IAAI,OAAOA,GAAS,SAAU,OAAOV,EAAQ,OAAOU,CAAI,EACxD,GAAIA,aAAgB,gBAAiB,OAAOV,EAAQ,OAAOU,EAAK,SAAS,CAAC,EAC1E,GAAIA,aAAgB,KAAM,OAAO,IAAI,WAAW,MAAMA,EAAK,YAAY,CAAC,EACxE,GAAIA,aAAgB,YAAa,OAAO,IAAI,WAAWA,CAAI,EAC3D,GAAI,YAAY,OAAOA,CAAI,EAAG,OAAO,IAAI,WAAWA,EAAK,OAAQA,EAAK,WAAYA,EAAK,UAAU,EACjG,MAAU,MAAM,oEAAoE,CAL5B,CAM1D,CAEA,SAASC,EAAc,EAAuB,CAC5C,GAAI,CAACC,EAAM,WAAW,GAAG,EAAG,MAAU,MAAM,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3,"file":"index.cjs","names":["createSerialQueue","describeSealedFailure","connectSealedChannel","require_sealedChannel","require_index","require_index$1","encoder","decoder","encodeBase64","binary","byte","bytes","decodeBase64","value","character","bodyBytes","body","requestTarget","input","isSealedHttpResponse","candidate","header","part","createSealedTransport","channel","failure","authorizationFailure","unauthorized","outbound","inbound","exchange","relayPath","note","reason","sealBytes","sealed","openBytes","envelope","text","opened","listener","connected","hostPublicKey","path","init","gateway","controller","cancel","deadline","rejectAbort","aborted","reject","expectedChannel","check","request","relayResponse","responseText","decoded","sealedTransport"],"sources":["../../../src/services/sealedTransport/index.ts"],"sourcesContent":["import { describeSealedFailure, type SealedFailure } from '../../types/sealedChannel';\nimport { connectSealedChannel, type SealedChannel } from '../browserSealedChannel';\nimport { createSerialQueue } from '../serialQueue';\n\n/**\n * The one object the cockpit and every plugin use to talk over a sealed tunnel.\n *\n * Two things make this worth having rather than each caller reaching for the\n * channel directly. First, ordering: sealing advances a nonce counter and\n * opening enforces that it strictly increases, so both directions are pushed\n * through a serial queue and overlapping calls can never reorder into a\n * self-inflicted replay. Second, reach: a plugin that calls `fetch` itself\n * sends plaintext to whoever is relaying the tunnel, and the host cannot stop\n * it. Giving every caller one obvious helper is the only enforcement available.\n *\n * When no channel is established every method is a pass-through, so the same\n * code runs unchanged on the loopback listener where there is nothing to seal.\n */\n\nconst JSON_CONTENT_TYPE = 'application/json';\nconst FETCH_TIMEOUT_MS = 30_000;\n\nexport interface SealedTransport {\n /** False on loopback and before the handshake completes, where everything passes through. */\n active(): boolean;\n sealText(text: string): Promise<string>;\n /** Undefined when the message could not be opened; `lastFailure` says why. */\n openText(text: string): Promise<string | undefined>;\n sealBinary(bytes: Uint8Array): Promise<Uint8Array>;\n openBinary(bytes: Uint8Array): Promise<Uint8Array | undefined>;\n /** Drop-in for `fetch`, relaying the complete request through the sealed channel when configured. */\n fetch(input: string, init?: RequestInit): Promise<Response>;\n lastFailure(): string | undefined;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface SealedHttpRequest {\n v: 1;\n method: string;\n target: string;\n headers: Array<[string, string]>;\n body?: string;\n}\n\ninterface SealedHttpResponse {\n v: 1;\n status: number;\n headers: Array<[string, string]>;\n body: string;\n}\n\nfunction encodeBase64(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nfunction decodeBase64(value: string): Uint8Array {\n const binary = atob(value);\n return Uint8Array.from(binary, (character) => character.charCodeAt(0));\n}\n\nasync function bodyBytes(body: RequestInit['body']): Promise<Uint8Array | undefined> {\n if (body === undefined || body === null) return undefined;\n if (typeof body === 'string') return encoder.encode(body);\n if (body instanceof URLSearchParams) return encoder.encode(body.toString());\n if (body instanceof Blob) return new Uint8Array(await body.arrayBuffer());\n if (body instanceof ArrayBuffer) return new Uint8Array(body);\n if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);\n throw new Error('The sealed HTTP transport does not support this request body type.');\n}\n\nfunction requestTarget(input: string): string {\n if (!input.startsWith('/')) throw new Error('A sealed HTTP request must use a root-relative URL.');\n return input;\n}\n\nfunction isSealedHttpResponse(value: unknown): value is SealedHttpResponse {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as Partial<SealedHttpResponse>;\n return (\n candidate.v === 1 &&\n typeof candidate.status === 'number' &&\n Array.isArray(candidate.headers) &&\n candidate.headers.every(\n (header) => Array.isArray(header) && header.length === 2 && header.every((part) => typeof part === 'string'),\n ) &&\n typeof candidate.body === 'string'\n );\n}\nexport function createSealedTransport(): SealedTransport & {\n /** Completes the handshake against the host key from the QR. */\n connect: (hostPublicKey: string) => Promise<string | undefined>;\n /** Drops the channel, so everything falls back to pass-through. */\n reset: () => void;\n /** Selects the same-origin endpoint that carries sealed HTTP exchanges. */\n relayRequestsThrough: (path: string) => void;\n onAuthorizationFailure: (listener: () => void) => void;\n invalidate: () => void;\n} {\n let channel: SealedChannel | undefined;\n let failure: string | undefined;\n let authorizationFailure: (() => void) | undefined;\n let unauthorized = false;\n const outbound = createSerialQueue();\n const inbound = createSerialQueue();\n const exchange = createSerialQueue();\n let relayPath: string | undefined;\n const note = (reason: SealedFailure): undefined => {\n // A decryption failure otherwise shows up as a blank page with no cause, so\n // every one of them names itself.\n failure = describeSealedFailure(reason);\n return undefined;\n };\n\n const sealBytes = async (bytes: Uint8Array): Promise<string | undefined> => {\n if (channel === undefined) return undefined;\n const sealed = await channel.seal(bytes);\n if (!sealed.ok) return note(sealed.failure);\n return JSON.stringify(sealed.envelope);\n };\n\n const openBytes = async (text: string): Promise<Uint8Array | undefined> => {\n if (channel === undefined) return undefined;\n let envelope: unknown;\n try {\n envelope = JSON.parse(text);\n } catch {\n return note('malformed');\n }\n const opened = await channel.open(envelope);\n if (!opened.ok) return note(opened.failure);\n return opened.plaintext;\n };\n\n return {\n active: () => channel !== undefined,\n invalidate() {\n unauthorized = true;\n },\n onAuthorizationFailure(listener) {\n authorizationFailure = listener;\n },\n lastFailure: () => failure,\n\n async connect(hostPublicKey) {\n const connected = await connectSealedChannel(hostPublicKey);\n if (connected === undefined) {\n failure = 'This browser could not establish a sealed channel.';\n return undefined;\n }\n channel = connected.channel;\n unauthorized = false;\n failure = undefined;\n return connected.clientPublicKey;\n },\n\n relayRequestsThrough(path) {\n relayPath = path;\n },\n\n reset() {\n unauthorized = false;\n channel = undefined;\n failure = undefined;\n },\n\n async sealText(text) {\n if (unauthorized) throw new Error('Sign in to Po again.');\n if (channel === undefined) return text;\n return await outbound.run(async () => {\n const sealed = await sealBytes(encoder.encode(text));\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return sealed;\n });\n },\n\n async openText(text) {\n if (unauthorized) throw new Error('Sign in to Po again.');\n if (channel === undefined) return text;\n return await inbound.run(async () => {\n const opened = await openBytes(text);\n return opened === undefined ? undefined : decoder.decode(opened);\n });\n },\n\n async sealBinary(bytes) {\n if (unauthorized) throw new Error('Sign in to Po again.');\n if (channel === undefined) return bytes;\n return await outbound.run(async () => {\n const sealed = await sealBytes(bytes);\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return encoder.encode(sealed);\n });\n },\n\n async openBinary(bytes) {\n if (unauthorized) throw new Error('Sign in to Po again.');\n if (channel === undefined) return bytes;\n return await inbound.run(async () => await openBytes(decoder.decode(bytes)));\n },\n\n async fetch(input, init) {\n init?.signal?.throwIfAborted();\n if (unauthorized) throw new Error('Sign in to Po again.');\n const gateway = relayPath;\n if (channel === undefined || gateway === undefined) return await fetch(input, init);\n const controller = new AbortController();\n const cancel = () => controller.abort(init?.signal?.reason);\n const deadline = setTimeout(\n () => controller.abort(new DOMException('The request timed out.', 'TimeoutError')),\n FETCH_TIMEOUT_MS,\n );\n init?.signal?.addEventListener('abort', cancel, { once: true });\n if (init?.signal?.aborted) cancel();\n let rejectAbort: (() => void) | undefined;\n const aborted = new Promise<never>((_resolve, reject) => {\n rejectAbort = () => reject(controller.signal.reason);\n controller.signal.addEventListener('abort', rejectAbort, { once: true });\n if (controller.signal.aborted) rejectAbort();\n });\n const expectedChannel = channel;\n const check = () => {\n controller.signal.throwIfAborted();\n if (unauthorized || channel !== expectedChannel) throw new Error('The sealed channel was replaced.');\n };\n try {\n check();\n return await Promise.race([\n exchange.run(() =>\n Promise.race([\n (async () => {\n check();\n const bytes = await bodyBytes(init?.body);\n check();\n const request: SealedHttpRequest = {\n v: 1,\n method: (init?.method ?? 'GET').toUpperCase(),\n target: requestTarget(input),\n headers: Array.from(new Headers(init?.headers).entries()),\n ...(bytes === undefined ? {} : { body: encodeBase64(bytes) }),\n };\n const sealed = await sealBytes(encoder.encode(JSON.stringify(request)));\n check();\n if (sealed === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const relayResponse = await fetch(gateway, {\n method: 'POST',\n signal: controller.signal,\n credentials: 'same-origin',\n headers: { 'content-type': JSON_CONTENT_TYPE },\n body: sealed,\n });\n check();\n // These are unsealed gateway refusals, not the inner application's authorization response.\n if (relayResponse.status === 401 || relayResponse.status === 403) {\n unauthorized = true;\n failure = 'Sign in to Po again.';\n authorizationFailure?.();\n throw new Error(failure);\n }\n const responseText = await relayResponse.text();\n check();\n const opened = await openBytes(responseText);\n check();\n if (opened === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n let decoded: unknown;\n try {\n decoded = JSON.parse(decoder.decode(opened));\n } catch {\n decoded = undefined;\n }\n if (!isSealedHttpResponse(decoded)) {\n failure = 'The sealed HTTP response was malformed.';\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const body = decodeBase64(decoded.body);\n return new Response(\n decoded.status === 204 || decoded.status === 205 || decoded.status === 304 ? null : body,\n {\n status: decoded.status,\n headers: decoded.headers,\n },\n );\n })(),\n aborted,\n ]),\n ),\n aborted,\n ]);\n } finally {\n clearTimeout(deadline);\n init?.signal?.removeEventListener('abort', cancel);\n if (rejectAbort) controller.signal.removeEventListener('abort', rejectAbort);\n }\n },\n };\n}\n\n/**\n * The page's one sealed channel.\n *\n * A module singleton rather than an instance per caller, because the cockpit\n * and every plugin are bundled into the same page and all of them must share\n * one pair of nonce counters. Two transports over one handshake would each\n * start counting at zero and the receiver would reject the second as a replay.\n *\n * Inactive until a handshake completes, and inactive forever on the loopback\n * listener, so `sealedTransport.fetch` is a plain `fetch` there.\n */\nexport const sealedTransport = createSealedTransport();\n"],"mappings":"sIAmCMM,EAAU,IAAI,YACdC,EAAU,IAAI,YAiBpB,SAASC,EAAa,EAA2B,CAC/C,IAAIC,EAAS,GACb,IAAK,IAAMC,KAAQC,EAAO,GAAU,OAAO,aAAaD,CAAI,EAC5D,OAAO,KAAKD,CAAM,CACpB,CAEA,SAASG,EAAa,EAA2B,CAC/C,IAAMH,EAAS,KAAKI,CAAK,EACzB,OAAO,WAAW,KAAKJ,EAAS,GAAcK,EAAU,WAAW,CAAC,CAAC,CACvE,CAEA,eAAeC,EAAU,EAA4D,CACnF,GAAIC,G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CAC7C,MAAQ,CACN,EAAU,IAAA,EACZ,CACA,GAAI,CAACpB,EAAqBsC,CAAO,EAE/B,MADA,GAAU,0CACH,IAAI,SAAS,KAAK,UAAU,CAAE,MAAOhC,CAAQ,CAAC,EAAG,CAAE,OAAQ,GAAI,CAAC,EAEzE,IAAMT,EAAOJ,EAAa6C,EAAQ,IAAI,EACtC,OAAO,IAAI,SACTA,EAAQ,SAAW,KAAOA,EAAQ,SAAW,KAAOA,EAAQ,SAAW,IAAM,KAAOzC,EACpF,CACE,OAAQyC,EAAQ,OAChB,QAASA,EAAQ,OACnB,CACF,CACF,EAAA,CAAG,EACHP,CACF,CAAC,CACH,EACAA,CACF,CAAC,CACH,QAAU,CACR,aAAaF,CAAQ,EACrBJ,GAAM,QAAQ,oBAAoB,QAASG,CAAM,EAC7CE,GAAaH,EAAW,OAAO,oBAAoB,QAASG,CAAW,CAC7E,CACF,CACF,CACF,CAaA,MAAaS,EAAkBnC,EAAsB"}
|
|
@@ -18,6 +18,8 @@ export declare function createSealedTransport(): SealedTransport & {
|
|
|
18
18
|
reset: () => void;
|
|
19
19
|
/** Selects the same-origin endpoint that carries sealed HTTP exchanges. */
|
|
20
20
|
relayRequestsThrough: (path: string) => void;
|
|
21
|
+
onAuthorizationFailure: (listener: () => void) => void;
|
|
22
|
+
invalidate: () => void;
|
|
21
23
|
};
|
|
22
24
|
/**
|
|
23
25
|
* The page's one sealed channel.
|
|
@@ -37,6 +39,8 @@ export declare const sealedTransport: SealedTransport & {
|
|
|
37
39
|
reset: () => void;
|
|
38
40
|
/** Selects the same-origin endpoint that carries sealed HTTP exchanges. */
|
|
39
41
|
relayRequestsThrough: (path: string) => void;
|
|
42
|
+
onAuthorizationFailure: (listener: () => void) => void;
|
|
43
|
+
invalidate: () => void;
|
|
40
44
|
};
|
|
41
45
|
//#endregion
|
|
42
46
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/sealedTransport/index.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/sealedTransport/index.ts"],"mappings":";iBAsBiB;;EAEf;EACA,SAAS,eAAe;;EAExB,SAAS,eAAe;EACxB,WAAW,OAAO,aAAa,QAAQ;EACvC,WAAW,OAAO,aAAa,QAAQ;;EAEvC,MAAM,eAAe,OAAO,cAAc,QAAQ;EAClD;;wBA4Dc,yBAAyB;;EAEvC,UAAU,0BAA0B;;EAEpC;;EAEA,uBAAuB;EACvB,yBAAyB;EACzB;;;;;;;;;;;;;qBAuNW,iBAAe;;EA7NjB,UAAC,0BAA0B;;EAE7B;;EAEe,uBAAC;EACC,yBAAC;EACb"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{describeSealedFailure as e}from"../../types/sealedChannel.mjs";import{connectSealedChannel as t}from"../browserSealedChannel/index.mjs";import{createSerialQueue as n}from"../serialQueue/index.mjs";const r=new TextEncoder,i=new TextDecoder;function a(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function o(e){let t=atob(e);return Uint8Array.from(t,e=>e.charCodeAt(0))}async function s(e){if(e!=null){if(typeof e==`string`)return r.encode(e);if(e instanceof URLSearchParams)return r.encode(e.toString());if(e instanceof Blob)return new Uint8Array(await e.arrayBuffer());if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error(`The sealed HTTP transport does not support this request body type.`)}}function c(e){if(!e.startsWith(`/`))throw Error(`A sealed HTTP request must use a root-relative URL.`);return e}function l(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.v===1&&typeof t.status==`number`&&Array.isArray(t.headers)&&t.headers.every(e=>Array.isArray(e)&&e.length===2&&e.every(e=>typeof e==`string`))&&typeof t.body==`string`}function u(){let u,d,f=n(),
|
|
1
|
+
import{describeSealedFailure as e}from"../../types/sealedChannel.mjs";import{connectSealedChannel as t}from"../browserSealedChannel/index.mjs";import{createSerialQueue as n}from"../serialQueue/index.mjs";const r=new TextEncoder,i=new TextDecoder;function a(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function o(e){let t=atob(e);return Uint8Array.from(t,e=>e.charCodeAt(0))}async function s(e){if(e!=null){if(typeof e==`string`)return r.encode(e);if(e instanceof URLSearchParams)return r.encode(e.toString());if(e instanceof Blob)return new Uint8Array(await e.arrayBuffer());if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error(`The sealed HTTP transport does not support this request body type.`)}}function c(e){if(!e.startsWith(`/`))throw Error(`A sealed HTTP request must use a root-relative URL.`);return e}function l(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.v===1&&typeof t.status==`number`&&Array.isArray(t.headers)&&t.headers.every(e=>Array.isArray(e)&&e.length===2&&e.every(e=>typeof e==`string`))&&typeof t.body==`string`}function u(){let u,d,f,p=!1,m=n(),h=n(),g=n(),_,v=t=>{d=e(t)},y=async e=>{if(u===void 0)return;let t=await u.seal(e);return t.ok?JSON.stringify(t.envelope):v(t.failure)},b=async e=>{if(u===void 0)return;let t;try{t=JSON.parse(e)}catch{return v(`malformed`)}let n=await u.open(t);return n.ok?n.plaintext:v(n.failure)};return{active:()=>u!==void 0,invalidate(){p=!0},onAuthorizationFailure(e){f=e},lastFailure:()=>d,async connect(e){let n=await t(e);if(n===void 0)d=`This browser could not establish a sealed channel.`;else return u=n.channel,p=!1,d=void 0,n.clientPublicKey},relayRequestsThrough(e){_=e},reset(){p=!1,u=void 0,d=void 0},async sealText(e){if(p)throw Error(`Sign in to Po again.`);return u===void 0?e:await m.run(async()=>{let t=await y(r.encode(e));if(t===void 0)throw Error(d??`The active sealed channel could not encrypt a message.`);return t})},async openText(e){if(p)throw Error(`Sign in to Po again.`);return u===void 0?e:await h.run(async()=>{let t=await b(e);return t===void 0?void 0:i.decode(t)})},async sealBinary(e){if(p)throw Error(`Sign in to Po again.`);return u===void 0?e:await m.run(async()=>{let t=await y(e);if(t===void 0)throw Error(d??`The active sealed channel could not encrypt a message.`);return r.encode(t)})},async openBinary(e){if(p)throw Error(`Sign in to Po again.`);return u===void 0?e:await h.run(async()=>await b(i.decode(e)))},async fetch(e,t){if(t?.signal?.throwIfAborted(),p)throw Error(`Sign in to Po again.`);let n=_;if(u===void 0||n===void 0)return await fetch(e,t);let m=new AbortController,h=()=>m.abort(t?.signal?.reason),v=setTimeout(()=>m.abort(new DOMException(`The request timed out.`,`TimeoutError`)),3e4);t?.signal?.addEventListener(`abort`,h,{once:!0}),t?.signal?.aborted&&h();let x,S=new Promise((e,t)=>{x=()=>t(m.signal.reason),m.signal.addEventListener(`abort`,x,{once:!0}),m.signal.aborted&&x()}),C=u,w=()=>{if(m.signal.throwIfAborted(),p||u!==C)throw Error(`The sealed channel was replaced.`)};try{return w(),await Promise.race([g.run(()=>Promise.race([(async()=>{w();let u=await s(t?.body);w();let h={v:1,method:(t?.method??`GET`).toUpperCase(),target:c(e),headers:Array.from(new Headers(t?.headers).entries()),...u===void 0?{}:{body:a(u)}},g=await y(r.encode(JSON.stringify(h)));if(w(),g===void 0)return new Response(JSON.stringify({error:d}),{status:502});let _=await fetch(n,{method:`POST`,signal:m.signal,credentials:`same-origin`,headers:{"content-type":`application/json`},body:g});if(w(),_.status===401||_.status===403)throw p=!0,d=`Sign in to Po again.`,f?.(),Error(d);let v=await _.text();w();let x=await b(v);if(w(),x===void 0)return new Response(JSON.stringify({error:d}),{status:502});let S;try{S=JSON.parse(i.decode(x))}catch{S=void 0}if(!l(S))return d=`The sealed HTTP response was malformed.`,new Response(JSON.stringify({error:d}),{status:502});let C=o(S.body);return new Response(S.status===204||S.status===205||S.status===304?null:C,{status:S.status,headers:S.headers})})(),S])),S])}finally{clearTimeout(v),t?.signal?.removeEventListener(`abort`,h),x&&m.signal.removeEventListener(`abort`,x)}}}}const d=u();export{u as createSealedTransport,d as sealedTransport};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["encoder","decoder","encodeBase64","binary","byte","bytes","decodeBase64","value","character","bodyBytes","body","requestTarget","input","isSealedHttpResponse","candidate","header","part","createSealedTransport","channel","failure","outbound","createSerialQueue","inbound","exchange","relayPath","note","describeSealedFailure","reason","sealBytes","sealed","openBytes","envelope","text","opened","connected","connectSealedChannel","hostPublicKey","path","gateway","init","request","relayResponse","decoded","sealedTransport"],"sources":["../../../src/services/sealedTransport/index.ts"],"sourcesContent":["import { describeSealedFailure, type SealedFailure } from '../../types/sealedChannel';\nimport { connectSealedChannel, type SealedChannel } from '../browserSealedChannel';\nimport { createSerialQueue } from '../serialQueue';\n\n/**\n * The one object the cockpit and every plugin use to talk over a sealed tunnel.\n *\n * Two things make this worth having rather than each caller reaching for the\n * channel directly. First, ordering: sealing advances a nonce counter and\n * opening enforces that it strictly increases, so both directions are pushed\n * through a serial queue and overlapping calls can never reorder into a\n * self-inflicted replay. Second, reach: a plugin that calls `fetch` itself\n * sends plaintext to whoever is relaying the tunnel, and the host cannot stop\n * it. Giving every caller one obvious helper is the only enforcement available.\n *\n * When no channel is established every method is a pass-through, so the same\n * code runs unchanged on the loopback listener where there is nothing to seal.\n */\n\nconst JSON_CONTENT_TYPE = 'application/json';\n\nexport interface SealedTransport {\n /** False on loopback and before the handshake completes, where everything passes through. */\n active(): boolean;\n sealText(text: string): Promise<string>;\n /** Undefined when the message could not be opened; `lastFailure` says why. */\n openText(text: string): Promise<string | undefined>;\n sealBinary(bytes: Uint8Array): Promise<Uint8Array>;\n openBinary(bytes: Uint8Array): Promise<Uint8Array | undefined>;\n /** Drop-in for `fetch`, relaying the complete request through the sealed channel when configured. */\n fetch(input: string, init?: RequestInit): Promise<Response>;\n lastFailure(): string | undefined;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface SealedHttpRequest {\n v: 1;\n method: string;\n target: string;\n headers: Array<[string, string]>;\n body?: string;\n}\n\ninterface SealedHttpResponse {\n v: 1;\n status: number;\n headers: Array<[string, string]>;\n body: string;\n}\n\nfunction encodeBase64(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nfunction decodeBase64(value: string): Uint8Array {\n const binary = atob(value);\n return Uint8Array.from(binary, (character) => character.charCodeAt(0));\n}\n\nasync function bodyBytes(body: RequestInit['body']): Promise<Uint8Array | undefined> {\n if (body === undefined || body === null) return undefined;\n if (typeof body === 'string') return encoder.encode(body);\n if (body instanceof URLSearchParams) return encoder.encode(body.toString());\n if (body instanceof Blob) return new Uint8Array(await body.arrayBuffer());\n if (body instanceof ArrayBuffer) return new Uint8Array(body);\n if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);\n throw new Error('The sealed HTTP transport does not support this request body type.');\n}\n\nfunction requestTarget(input: string): string {\n if (!input.startsWith('/')) throw new Error('A sealed HTTP request must use a root-relative URL.');\n return input;\n}\n\nfunction isSealedHttpResponse(value: unknown): value is SealedHttpResponse {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as Partial<SealedHttpResponse>;\n return (\n candidate.v === 1 &&\n typeof candidate.status === 'number' &&\n Array.isArray(candidate.headers) &&\n candidate.headers.every(\n (header) => Array.isArray(header) && header.length === 2 && header.every((part) => typeof part === 'string'),\n ) &&\n typeof candidate.body === 'string'\n );\n}\nexport function createSealedTransport(): SealedTransport & {\n /** Completes the handshake against the host key from the QR. */\n connect: (hostPublicKey: string) => Promise<string | undefined>;\n /** Drops the channel, so everything falls back to pass-through. */\n reset: () => void;\n /** Selects the same-origin endpoint that carries sealed HTTP exchanges. */\n relayRequestsThrough: (path: string) => void;\n} {\n let channel: SealedChannel | undefined;\n let failure: string | undefined;\n const outbound = createSerialQueue();\n const inbound = createSerialQueue();\n const exchange = createSerialQueue();\n let relayPath: string | undefined;\n const note = (reason: SealedFailure): undefined => {\n // A decryption failure otherwise shows up as a blank page with no cause, so\n // every one of them names itself.\n failure = describeSealedFailure(reason);\n return undefined;\n };\n\n const sealBytes = async (bytes: Uint8Array): Promise<string | undefined> => {\n if (channel === undefined) return undefined;\n const sealed = await channel.seal(bytes);\n if (!sealed.ok) return note(sealed.failure);\n return JSON.stringify(sealed.envelope);\n };\n\n const openBytes = async (text: string): Promise<Uint8Array | undefined> => {\n if (channel === undefined) return undefined;\n let envelope: unknown;\n try {\n envelope = JSON.parse(text);\n } catch {\n return note('malformed');\n }\n const opened = await channel.open(envelope);\n if (!opened.ok) return note(opened.failure);\n return opened.plaintext;\n };\n\n return {\n active: () => channel !== undefined,\n lastFailure: () => failure,\n\n async connect(hostPublicKey) {\n const connected = await connectSealedChannel(hostPublicKey);\n if (connected === undefined) {\n failure = 'This browser could not establish a sealed channel.';\n return undefined;\n }\n channel = connected.channel;\n failure = undefined;\n return connected.clientPublicKey;\n },\n\n relayRequestsThrough(path) {\n relayPath = path;\n },\n\n reset() {\n channel = undefined;\n failure = undefined;\n },\n\n async sealText(text) {\n if (channel === undefined) return text;\n return await outbound.run(async () => {\n const sealed = await sealBytes(encoder.encode(text));\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return sealed;\n });\n },\n\n async openText(text) {\n if (channel === undefined) return text;\n return await inbound.run(async () => {\n const opened = await openBytes(text);\n return opened === undefined ? undefined : decoder.decode(opened);\n });\n },\n\n async sealBinary(bytes) {\n if (channel === undefined) return bytes;\n return await outbound.run(async () => {\n const sealed = await sealBytes(bytes);\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return encoder.encode(sealed);\n });\n },\n\n async openBinary(bytes) {\n if (channel === undefined) return bytes;\n return await inbound.run(async () => await openBytes(decoder.decode(bytes)));\n },\n\n async fetch(input, init) {\n const gateway = relayPath;\n if (channel === undefined || gateway === undefined) return await fetch(input, init);\n return await exchange.run(async () => {\n const bytes = await bodyBytes(init?.body);\n const request: SealedHttpRequest = {\n v: 1,\n method: (init?.method ?? 'GET').toUpperCase(),\n target: requestTarget(input),\n headers: Array.from(new Headers(init?.headers).entries()),\n ...(bytes === undefined ? {} : { body: encodeBase64(bytes) }),\n };\n const sealed = await sealBytes(encoder.encode(JSON.stringify(request)));\n if (sealed === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const relayResponse = await fetch(gateway, {\n method: 'POST',\n credentials: 'same-origin',\n headers: { 'content-type': JSON_CONTENT_TYPE },\n body: sealed,\n });\n const opened = await openBytes(await relayResponse.text());\n if (opened === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n let decoded: unknown;\n try {\n decoded = JSON.parse(decoder.decode(opened));\n } catch {\n decoded = undefined;\n }\n if (!isSealedHttpResponse(decoded)) {\n failure = 'The sealed HTTP response was malformed.';\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const body = decodeBase64(decoded.body);\n return new Response(decoded.status === 204 || decoded.status === 205 || decoded.status === 304 ? null : body, {\n status: decoded.status,\n headers: decoded.headers,\n });\n });\n },\n };\n}\n\n/**\n * The page's one sealed channel.\n *\n * A module singleton rather than an instance per caller, because the cockpit\n * and every plugin are bundled into the same page and all of them must share\n * one pair of nonce counters. Two transports over one handshake would each\n * start counting at zero and the receiver would reject the second as a replay.\n *\n * Inactive until a handshake completes, and inactive forever on the loopback\n * listener, so `sealedTransport.fetch` is a plain `fetch` there.\n */\nexport const sealedTransport = createSealedTransport();\n"],"mappings":"4MAmBA,MAeMA,EAAU,IAAI,YACdC,EAAU,IAAI,YAiBpB,SAASC,EAAa,EAA2B,CAC/C,IAAIC,EAAS,GACb,IAAK,IAAMC,KAAQC,EAAO,GAAU,OAAO,aAAaD,CAAI,EAC5D,OAAO,KAAKD,CAAM,CACpB,CAEA,SAASG,EAAa,EAA2B,CAC/C,IAAMH,EAAS,KAAKI,CAAK,EACzB,OAAO,WAAW,KAAKJ,EAAS,GAAcK,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EAAU,KAAK,MAAMzC,EAAQ,OAAOgC,CAAM,CAAC,CAC7C,MAAQ,CACN,EAAU,IAAA,EACZ,CACA,GAAI,CAACpB,EAAqB6B,CAAO,EAE/B,MADA,GAAU,0CACH,IAAI,SAAS,KAAK,UAAU,CAAE,MAAOvB,CAAQ,CAAC,EAAG,CAAE,OAAQ,GAAI,CAAC,EAEzE,IAAMT,EAAOJ,EAAaoC,EAAQ,IAAI,EACtC,OAAO,IAAI,SAASA,EAAQ,SAAW,KAAOA,EAAQ,SAAW,KAAOA,EAAQ,SAAW,IAAM,KAAOhC,EAAM,CAC5G,OAAQgC,EAAQ,OAChB,QAASA,EAAQ,OACnB,CAAC,CACH,CAAC,CACH,CACF,CACF,CAaA,MAAaC,EAAkB1B,EAAsB"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["encoder","decoder","encodeBase64","binary","byte","bytes","decodeBase64","value","character","bodyBytes","body","requestTarget","input","isSealedHttpResponse","candidate","header","part","createSealedTransport","channel","failure","authorizationFailure","unauthorized","outbound","createSerialQueue","inbound","exchange","relayPath","note","describeSealedFailure","reason","sealBytes","sealed","openBytes","envelope","text","opened","listener","connected","connectSealedChannel","hostPublicKey","path","init","gateway","controller","cancel","deadline","rejectAbort","aborted","reject","expectedChannel","check","request","relayResponse","responseText","decoded","sealedTransport"],"sources":["../../../src/services/sealedTransport/index.ts"],"sourcesContent":["import { describeSealedFailure, type SealedFailure } from '../../types/sealedChannel';\nimport { connectSealedChannel, type SealedChannel } from '../browserSealedChannel';\nimport { createSerialQueue } from '../serialQueue';\n\n/**\n * The one object the cockpit and every plugin use to talk over a sealed tunnel.\n *\n * Two things make this worth having rather than each caller reaching for the\n * channel directly. First, ordering: sealing advances a nonce counter and\n * opening enforces that it strictly increases, so both directions are pushed\n * through a serial queue and overlapping calls can never reorder into a\n * self-inflicted replay. Second, reach: a plugin that calls `fetch` itself\n * sends plaintext to whoever is relaying the tunnel, and the host cannot stop\n * it. Giving every caller one obvious helper is the only enforcement available.\n *\n * When no channel is established every method is a pass-through, so the same\n * code runs unchanged on the loopback listener where there is nothing to seal.\n */\n\nconst JSON_CONTENT_TYPE = 'application/json';\nconst FETCH_TIMEOUT_MS = 30_000;\n\nexport interface SealedTransport {\n /** False on loopback and before the handshake completes, where everything passes through. */\n active(): boolean;\n sealText(text: string): Promise<string>;\n /** Undefined when the message could not be opened; `lastFailure` says why. */\n openText(text: string): Promise<string | undefined>;\n sealBinary(bytes: Uint8Array): Promise<Uint8Array>;\n openBinary(bytes: Uint8Array): Promise<Uint8Array | undefined>;\n /** Drop-in for `fetch`, relaying the complete request through the sealed channel when configured. */\n fetch(input: string, init?: RequestInit): Promise<Response>;\n lastFailure(): string | undefined;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface SealedHttpRequest {\n v: 1;\n method: string;\n target: string;\n headers: Array<[string, string]>;\n body?: string;\n}\n\ninterface SealedHttpResponse {\n v: 1;\n status: number;\n headers: Array<[string, string]>;\n body: string;\n}\n\nfunction encodeBase64(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nfunction decodeBase64(value: string): Uint8Array {\n const binary = atob(value);\n return Uint8Array.from(binary, (character) => character.charCodeAt(0));\n}\n\nasync function bodyBytes(body: RequestInit['body']): Promise<Uint8Array | undefined> {\n if (body === undefined || body === null) return undefined;\n if (typeof body === 'string') return encoder.encode(body);\n if (body instanceof URLSearchParams) return encoder.encode(body.toString());\n if (body instanceof Blob) return new Uint8Array(await body.arrayBuffer());\n if (body instanceof ArrayBuffer) return new Uint8Array(body);\n if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);\n throw new Error('The sealed HTTP transport does not support this request body type.');\n}\n\nfunction requestTarget(input: string): string {\n if (!input.startsWith('/')) throw new Error('A sealed HTTP request must use a root-relative URL.');\n return input;\n}\n\nfunction isSealedHttpResponse(value: unknown): value is SealedHttpResponse {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as Partial<SealedHttpResponse>;\n return (\n candidate.v === 1 &&\n typeof candidate.status === 'number' &&\n Array.isArray(candidate.headers) &&\n candidate.headers.every(\n (header) => Array.isArray(header) && header.length === 2 && header.every((part) => typeof part === 'string'),\n ) &&\n typeof candidate.body === 'string'\n );\n}\nexport function createSealedTransport(): SealedTransport & {\n /** Completes the handshake against the host key from the QR. */\n connect: (hostPublicKey: string) => Promise<string | undefined>;\n /** Drops the channel, so everything falls back to pass-through. */\n reset: () => void;\n /** Selects the same-origin endpoint that carries sealed HTTP exchanges. */\n relayRequestsThrough: (path: string) => void;\n onAuthorizationFailure: (listener: () => void) => void;\n invalidate: () => void;\n} {\n let channel: SealedChannel | undefined;\n let failure: string | undefined;\n let authorizationFailure: (() => void) | undefined;\n let unauthorized = false;\n const outbound = createSerialQueue();\n const inbound = createSerialQueue();\n const exchange = createSerialQueue();\n let relayPath: string | undefined;\n const note = (reason: SealedFailure): undefined => {\n // A decryption failure otherwise shows up as a blank page with no cause, so\n // every one of them names itself.\n failure = describeSealedFailure(reason);\n return undefined;\n };\n\n const sealBytes = async (bytes: Uint8Array): Promise<string | undefined> => {\n if (channel === undefined) return undefined;\n const sealed = await channel.seal(bytes);\n if (!sealed.ok) return note(sealed.failure);\n return JSON.stringify(sealed.envelope);\n };\n\n const openBytes = async (text: string): Promise<Uint8Array | undefined> => {\n if (channel === undefined) return undefined;\n let envelope: unknown;\n try {\n envelope = JSON.parse(text);\n } catch {\n return note('malformed');\n }\n const opened = await channel.open(envelope);\n if (!opened.ok) return note(opened.failure);\n return opened.plaintext;\n };\n\n return {\n active: () => channel !== undefined,\n invalidate() {\n unauthorized = true;\n },\n onAuthorizationFailure(listener) {\n authorizationFailure = listener;\n },\n lastFailure: () => failure,\n\n async connect(hostPublicKey) {\n const connected = await connectSealedChannel(hostPublicKey);\n if (connected === undefined) {\n failure = 'This browser could not establish a sealed channel.';\n return undefined;\n }\n channel = connected.channel;\n unauthorized = false;\n failure = undefined;\n return connected.clientPublicKey;\n },\n\n relayRequestsThrough(path) {\n relayPath = path;\n },\n\n reset() {\n unauthorized = false;\n channel = undefined;\n failure = undefined;\n },\n\n async sealText(text) {\n if (unauthorized) throw new Error('Sign in to Po again.');\n if (channel === undefined) return text;\n return await outbound.run(async () => {\n const sealed = await sealBytes(encoder.encode(text));\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return sealed;\n });\n },\n\n async openText(text) {\n if (unauthorized) throw new Error('Sign in to Po again.');\n if (channel === undefined) return text;\n return await inbound.run(async () => {\n const opened = await openBytes(text);\n return opened === undefined ? undefined : decoder.decode(opened);\n });\n },\n\n async sealBinary(bytes) {\n if (unauthorized) throw new Error('Sign in to Po again.');\n if (channel === undefined) return bytes;\n return await outbound.run(async () => {\n const sealed = await sealBytes(bytes);\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return encoder.encode(sealed);\n });\n },\n\n async openBinary(bytes) {\n if (unauthorized) throw new Error('Sign in to Po again.');\n if (channel === undefined) return bytes;\n return await inbound.run(async () => await openBytes(decoder.decode(bytes)));\n },\n\n async fetch(input, init) {\n init?.signal?.throwIfAborted();\n if (unauthorized) throw new Error('Sign in to Po again.');\n const gateway = relayPath;\n if (channel === undefined || gateway === undefined) return await fetch(input, init);\n const controller = new AbortController();\n const cancel = () => controller.abort(init?.signal?.reason);\n const deadline = setTimeout(\n () => controller.abort(new DOMException('The request timed out.', 'TimeoutError')),\n FETCH_TIMEOUT_MS,\n );\n init?.signal?.addEventListener('abort', cancel, { once: true });\n if (init?.signal?.aborted) cancel();\n let rejectAbort: (() => void) | undefined;\n const aborted = new Promise<never>((_resolve, reject) => {\n rejectAbort = () => reject(controller.signal.reason);\n controller.signal.addEventListener('abort', rejectAbort, { once: true });\n if (controller.signal.aborted) rejectAbort();\n });\n const expectedChannel = channel;\n const check = () => {\n controller.signal.throwIfAborted();\n if (unauthorized || channel !== expectedChannel) throw new Error('The sealed channel was replaced.');\n };\n try {\n check();\n return await Promise.race([\n exchange.run(() =>\n Promise.race([\n (async () => {\n check();\n const bytes = await bodyBytes(init?.body);\n check();\n const request: SealedHttpRequest = {\n v: 1,\n method: (init?.method ?? 'GET').toUpperCase(),\n target: requestTarget(input),\n headers: Array.from(new Headers(init?.headers).entries()),\n ...(bytes === undefined ? {} : { body: encodeBase64(bytes) }),\n };\n const sealed = await sealBytes(encoder.encode(JSON.stringify(request)));\n check();\n if (sealed === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const relayResponse = await fetch(gateway, {\n method: 'POST',\n signal: controller.signal,\n credentials: 'same-origin',\n headers: { 'content-type': JSON_CONTENT_TYPE },\n body: sealed,\n });\n check();\n // These are unsealed gateway refusals, not the inner application's authorization response.\n if (relayResponse.status === 401 || relayResponse.status === 403) {\n unauthorized = true;\n failure = 'Sign in to Po again.';\n authorizationFailure?.();\n throw new Error(failure);\n }\n const responseText = await relayResponse.text();\n check();\n const opened = await openBytes(responseText);\n check();\n if (opened === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n let decoded: unknown;\n try {\n decoded = JSON.parse(decoder.decode(opened));\n } catch {\n decoded = undefined;\n }\n if (!isSealedHttpResponse(decoded)) {\n failure = 'The sealed HTTP response was malformed.';\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const body = decodeBase64(decoded.body);\n return new Response(\n decoded.status === 204 || decoded.status === 205 || decoded.status === 304 ? null : body,\n {\n status: decoded.status,\n headers: decoded.headers,\n },\n );\n })(),\n aborted,\n ]),\n ),\n aborted,\n ]);\n } finally {\n clearTimeout(deadline);\n init?.signal?.removeEventListener('abort', cancel);\n if (rejectAbort) controller.signal.removeEventListener('abort', rejectAbort);\n }\n },\n };\n}\n\n/**\n * The page's one sealed channel.\n *\n * A module singleton rather than an instance per caller, because the cockpit\n * and every plugin are bundled into the same page and all of them must share\n * one pair of nonce counters. Two transports over one handshake would each\n * start counting at zero and the receiver would reject the second as a replay.\n *\n * Inactive until a handshake completes, and inactive forever on the loopback\n * listener, so `sealedTransport.fetch` is a plain `fetch` there.\n */\nexport const sealedTransport = createSealedTransport();\n"],"mappings":"4MAmBA,MAgBMA,EAAU,IAAI,YACdC,EAAU,IAAI,YAiBpB,SAASC,EAAa,EAA2B,CAC/C,IAAIC,EAAS,GACb,IAAK,IAAMC,KAAQC,EAAO,GAAU,OAAO,aAAaD,CAAI,EAC5D,OAAO,KAAKD,CAAM,CACpB,CAEA,SAASG,EAAa,EAA2B,CAC/C,IAAMH,EAAS,KAAKI,CAAK,EACzB,OAAO,WAAW,KAAKJ,EAAS,GAAcK,EAAU,WAAW,CAAC,CAAC,CACvE,CAEA,eAAeC,EAAU,EAA4D,CACnF,GAAIC,GAA+B,KACnC,IAAI,OAAOA,GAAS,SAAU,OAAOV,EAAQ,OAAOU,CAAI,EACxD,GAAIA,aAAgB,gBAAiB,OAAOV,EAAQ,OAAOU,EAAK,SAAS,CAAC,EAC1E,GAAIA,aAAgB,KAAM,OAAO,IAAI,WAAW,MAAMA,EAAK,YAAY,CAAC,EACxE,GAAIA,aAAgB,YAAa,OAAO,IAAI,WAAWA,CAAI,EAC3D,GAAI,YAAY,OAAOA,CAAI,EAAG,OAAO,IAAI,WAAWA,EAAK,OAAQA,EAAK,WAAYA,EAAK,UAAU,EACjG,MAAU,MAAM,oEAAoE,CAL5B,CAM1D,CAEA,SAASC,EAAc,EAAuB,CAC5C,GAAI,CAACC,EAAM,WAAW,GAAG,EAAG,MAAU,MAAM,qDAAqD,EACjG,OAAOA,CACT,CAEA,SAASC,EAAqB,EAA6C,CACzE,GAAI,OAAON,GAAU,WAAYA,EAAgB,MAAO,GACxD,IAAMO,EAAYP,EAClB,OACEO,EAAU,IAAM,GAChB,OAAOA,EAAU,QAAW,UAC5B,MAAM,QAAQA,EAAU,OAAO,GAC/BA,EAAU,QAAQ,MACf,GAAW,MAAM,QAAQC,CAAM,GAAKA,EAAO,SAAW,GAAK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-z0-9!#$&^_.+-]*$/u;function a(e,t){let n=Object.keys(e).sort();return n.length===t.length&&n.every((e,n)=>e===t[n])}function o(e,t){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=t}function s(e){return typeof e!=`string`||e.length<2||!e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)||e.includes(`?`)||e.includes(`#`)||/[^\x21-\x7e]/u.test(e)||e.includes(`//`)||/%(?![0-9a-f]{2})/iu.test(e)||/%(?:2e|2f|5c)/iu.test(e)?!1:e.split(`/`).slice(1).every(e=>e!==``&&e!==`.`&&e!==`..`)}function c(e){let t=[...e.assets].sort((e,t)=>e.path<t.path?-1:+(e.path>t.path)).map(e=>`${e.path}\0${e.sha256}\0${String(e.byteLength)}\0${e.contentType}`);return[String(e.version),String(e.revision),String(e.builtAt),...t].join(`
|
|
2
|
-
`)}function l(e,n){if(!t.test(e))throw Error(`invalid attestation tag: ${e}`);if(!Array.isArray(n)||!n.every(e=>typeof e==`string`))throw Error(`invalid attestation fields for ${e}`);return new TextEncoder().encode(`${e}\n${JSON.stringify(n)}`)}function u(t,n,r){if(r===`web`)return n.has(e);if(r!==`native`||t.length!==1)return!1;let[i]=t;return i!==void 0&&i.path===`/composition.js`&&i.contentType===`text/javascript`&&i.byteLength<=4194304}function d(e,t=`web`){if(typeof e!=`object`||!e||!a(e,[`assets`,`builtAt`,`revision`,`version`]))return!1;let r=e;if(r.version!==2||!o(r.revision,1)||!o(r.builtAt,0)||!Array.isArray(r.assets)||r.assets.length===0)return!1;let c=/* @__PURE__ */ new Set;for(let e of r.assets){if(typeof e!=`object`||!e||!a(e,[`byteLength`,`contentType`,`path`,`sha256`]))return!1;let t=e;if(!s(t.path)||c.has(t.path)||typeof t.sha256!=`string`||!n.test(t.sha256)||!o(t.byteLength,0)||typeof t.contentType!=`string`||!i.test(t.contentType))return!1;c.add(t.path)}return u(r.assets,c,t)}function f(e,t=`web`){if(typeof e!=`object`||!e||!a(e,[`manifest`,`publicKey`,`signature`]))return!1;let n=e;return d(n.manifest,t)&&typeof n.signature==`string`&&n.signature.length===86&&r.test(n.signature)&&typeof n.publicKey==`string`&&n.publicKey.length<=512&&r.test(n.publicKey)}function p(e,t){return e.assets.find(e=>e.path===t)}function m(e,t){return p(e,t)?.sha256}exports.ATTESTATION_TAG=t,exports.BUNDLE_MANIFEST_ROUTE=`/bundle-manifest.json`,exports.BUNDLE_MANIFEST_VERSION=2,exports.NATIVE_COMPOSITION_MAX_BYTES=4194304,exports.NATIVE_ENTRY_CONTENT_TYPE=`text/javascript`,exports.NATIVE_ENTRY_PATH=`/composition.js`,exports.WEB_ENTRY_PATH=e,exports.assetFor=p,exports.attestationBytes=l,exports.canonicalManifest=c,exports.digestFor=m,exports.isBundleManifest=d,exports.isSignedBundleManifest=f;
|
|
2
|
+
`)}function l(e,n){if(!t.test(e))throw Error(`invalid attestation tag: ${e}`);if(!Array.isArray(n)||!n.every(e=>typeof e==`string`))throw Error(`invalid attestation fields for ${e}`);return new TextEncoder().encode(`${e}\n${JSON.stringify(n)}`)}function u(t,n,r){if(r===`web`)return n.has(e);if(r===`app`)return!n.has(`/index.html`)&&!n.has(`/composition.js`)&&n.has(`/app.json`)&&t.some(e=>e.path.startsWith(`/bundle/`))&&t.every(e=>e.byteLength<=2097152);if(r!==`native`||t.length!==1)return!1;let[i]=t;return i!==void 0&&i.path===`/composition.js`&&i.contentType===`text/javascript`&&i.byteLength<=4194304}function d(e,t=`web`){if(typeof e!=`object`||!e||!a(e,[`assets`,`builtAt`,`revision`,`version`]))return!1;let r=e;if(r.version!==2||!o(r.revision,1)||!o(r.builtAt,0)||!Array.isArray(r.assets)||r.assets.length===0)return!1;let c=/* @__PURE__ */ new Set;for(let e of r.assets){if(typeof e!=`object`||!e||!a(e,[`byteLength`,`contentType`,`path`,`sha256`]))return!1;let t=e;if(!s(t.path)||c.has(t.path)||typeof t.sha256!=`string`||!n.test(t.sha256)||!o(t.byteLength,0)||typeof t.contentType!=`string`||!i.test(t.contentType))return!1;c.add(t.path)}return u(r.assets,c,t)}function f(e,t=`web`){if(typeof e!=`object`||!e||!a(e,[`manifest`,`publicKey`,`signature`]))return!1;let n=e;return d(n.manifest,t)&&typeof n.signature==`string`&&n.signature.length===86&&r.test(n.signature)&&typeof n.publicKey==`string`&&n.publicKey.length<=512&&r.test(n.publicKey)}function p(e,t){return e.assets.find(e=>e.path===t)}function m(e,t){return p(e,t)?.sha256}exports.APP_ASSET_MAX_BYTES=2097152,exports.APP_DESCRIPTOR_PATH=`/app.json`,exports.APP_PART_PREFIX=`/bundle/`,exports.ATTESTATION_TAG=t,exports.BUNDLE_MANIFEST_ROUTE=`/bundle-manifest.json`,exports.BUNDLE_MANIFEST_VERSION=2,exports.NATIVE_COMPOSITION_MAX_BYTES=4194304,exports.NATIVE_ENTRY_CONTENT_TYPE=`text/javascript`,exports.NATIVE_ENTRY_PATH=`/composition.js`,exports.WEB_ENTRY_PATH=e,exports.assetFor=p,exports.attestationBytes=l,exports.canonicalManifest=c,exports.digestFor=m,exports.isBundleManifest=d,exports.isSignedBundleManifest=f;
|
|
3
3
|
//# sourceMappingURL=bundleManifest.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundleManifest.cjs","names":["WEB_ENTRY_PATH","ATTESTATION_TAG","SHA256","BASE64URL","CONTENT_TYPE","hasExactKeys","keys","value","expected","key","index","isSafeInteger","minimum","isSafeAssetPath","segment","canonicalManifest","lines","manifest","left","right","asset","attestationBytes","tag","fields","field","matchesProfile","profile","paths","assets","entry","isBundleManifest","candidate","valueAsset","isSignedBundleManifest","assetFor","path","digestFor"],"sources":["../../src/types/bundleManifest.ts"],"sourcesContent":["/**\n * A signed description of cockpit assets for an independently trusted verifier.\n *\n * A manifest does not let a browser SPA defend itself against the server or TLS\n * edge that supplied its executable code. Consumers need a separately trusted\n * bootstrap and key before these signatures become a delivery guarantee.\n */\n\nexport const BUNDLE_MANIFEST_ROUTE = '/bundle-manifest.json';\nexport const BUNDLE_MANIFEST_VERSION = 2;\n\n/**\n * Which asset shape a manifest must have. A web bundle always serves `/index.html`; a native bundle is\n * exactly one composition module and never serves `/index.html`, so no manifest can pass both.\n */\nexport type BundleProfile = 'web' | 'native';\nexport const WEB_ENTRY_PATH = '/index.html';\nexport const NATIVE_ENTRY_PATH = '/composition.js';\nexport const NATIVE_ENTRY_CONTENT_TYPE = 'text/javascript';\n/** Largest native composition a sealed response can carry. */\nexport const NATIVE_COMPOSITION_MAX_BYTES = 4 * 1024 * 1024;\n/** Domain-separation tag for an attestation. Starts with `p`, so it can never collide with a `2\\n` manifest. */\nexport const ATTESTATION_TAG = /^po\\/[a-z0-9-]+\\/v[1-9][0-9]*$/u;\n\nconst SHA256 = /^[0-9a-f]{64}$/u;\nconst BASE64URL = /^[A-Za-z0-9_-]+$/u;\nconst CONTENT_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\\/[a-z0-9][a-z0-9!#$&^_.+-]*$/u;\n\nexport interface BundleAsset {\n /** Normalized absolute URL path, without a query or fragment. */\n path: string;\n /** Lowercase hex SHA-256 of the served bytes. */\n sha256: string;\n byteLength: number;\n /** MIME type of the response, without parameters. */\n contentType: string;\n}\n\nexport interface BundleManifest {\n version: typeof BUNDLE_MANIFEST_VERSION;\n /** Monotonically increasing persistent signer revision. */\n revision: number;\n /** Unix time in milliseconds. */\n builtAt: number;\n assets: BundleAsset[];\n}\n\nexport interface SignedBundleManifest {\n manifest: BundleManifest;\n /** Base64url IEEE P1363 ECDSA P-256 signature over the canonical serialization. */\n signature: string;\n /** Base64url SPKI of the signing key. Trust must be established out of band. */\n publicKey: string;\n}\n\nfunction hasExactKeys(value: object, expected: readonly string[]): boolean {\n const keys = Object.keys(value).sort();\n return keys.length === expected.length && keys.every((key, index) => key === expected[index]);\n}\n\nfunction isSafeInteger(value: unknown, minimum: number): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= minimum;\n}\n\nfunction isSafeAssetPath(value: unknown): value is string {\n if (typeof value !== 'string' || value.length < 2 || !value.startsWith('/')) return false;\n if (value.includes('\\\\') || value.includes('\\0') || value.includes('?') || value.includes('#')) return false;\n if (/[^\\x21-\\x7e]/u.test(value) || value.includes('//') || /%(?![0-9a-f]{2})/iu.test(value)) return false;\n if (/%(?:2e|2f|5c)/iu.test(value)) return false;\n return value\n .split('/')\n .slice(1)\n .every((segment) => segment !== '' && segment !== '.' && segment !== '..');\n}\n\n/** The exact bytes signed by Node and verified by WebCrypto. */\nexport function canonicalManifest(manifest: BundleManifest): string {\n const assets = [...manifest.assets].sort((left, right) =>\n left.path < right.path ? -1 : left.path > right.path ? 1 : 0,\n );\n const lines = assets.map(\n (asset) => `${asset.path}\\0${asset.sha256}\\0${String(asset.byteLength)}\\0${asset.contentType}`,\n );\n return [String(manifest.version), String(manifest.revision), String(manifest.builtAt), ...lines].join('\\n');\n}\n\n/**\n * The exact bytes of a tagged attestation: `UTF-8(tag + \"\\n\" + JSON.stringify(fields))`. Fields are an\n * ordered list of strings, so both sides build the same bytes without relying on object key order.\n * Throws on a malformed tag or a non-string field.\n */\nexport function attestationBytes(tag: string, fields: readonly string[]): Uint8Array<ArrayBuffer> {\n if (!ATTESTATION_TAG.test(tag)) throw new Error(`invalid attestation tag: ${tag}`);\n if (!Array.isArray(fields) || !fields.every((field) => typeof field === 'string')) {\n throw new Error(`invalid attestation fields for ${tag}`);\n }\n return new TextEncoder().encode(`${tag}\\n${JSON.stringify(fields)}`);\n}\n\nfunction matchesProfile(assets: readonly BundleAsset[], paths: ReadonlySet<string>, profile: BundleProfile): boolean {\n if (profile === 'web') return paths.has(WEB_ENTRY_PATH);\n if (profile !== 'native' || assets.length !== 1) return false;\n const [entry] = assets;\n return (\n entry !== undefined &&\n entry.path === NATIVE_ENTRY_PATH &&\n entry.contentType === NATIVE_ENTRY_CONTENT_TYPE &&\n entry.byteLength <= NATIVE_COMPOSITION_MAX_BYTES\n );\n}\n\nexport function isBundleManifest(value: unknown, profile: BundleProfile = 'web'): value is BundleManifest {\n if (typeof value !== 'object' || value === null) return false;\n if (!hasExactKeys(value, ['assets', 'builtAt', 'revision', 'version'])) return false;\n const candidate = value as Partial<BundleManifest>;\n if (candidate.version !== BUNDLE_MANIFEST_VERSION) return false;\n if (!isSafeInteger(candidate.revision, 1) || !isSafeInteger(candidate.builtAt, 0)) return false;\n if (!Array.isArray(candidate.assets) || candidate.assets.length === 0) return false;\n\n const paths = new Set<string>();\n for (const valueAsset of candidate.assets) {\n if (typeof valueAsset !== 'object' || valueAsset === null) return false;\n if (!hasExactKeys(valueAsset, ['byteLength', 'contentType', 'path', 'sha256'])) return false;\n const asset = valueAsset as Partial<BundleAsset>;\n if (!isSafeAssetPath(asset.path) || paths.has(asset.path)) return false;\n if (typeof asset.sha256 !== 'string' || !SHA256.test(asset.sha256)) return false;\n if (!isSafeInteger(asset.byteLength, 0)) return false;\n if (typeof asset.contentType !== 'string' || !CONTENT_TYPE.test(asset.contentType)) return false;\n paths.add(asset.path);\n }\n return matchesProfile(candidate.assets as BundleAsset[], paths, profile);\n}\n\nexport function isSignedBundleManifest(value: unknown, profile: BundleProfile = 'web'): value is SignedBundleManifest {\n if (typeof value !== 'object' || value === null) return false;\n if (!hasExactKeys(value, ['manifest', 'publicKey', 'signature'])) return false;\n const candidate = value as Partial<SignedBundleManifest>;\n return (\n isBundleManifest(candidate.manifest, profile) &&\n typeof candidate.signature === 'string' &&\n candidate.signature.length === 86 &&\n BASE64URL.test(candidate.signature) &&\n typeof candidate.publicKey === 'string' &&\n candidate.publicKey.length <= 512 &&\n BASE64URL.test(candidate.publicKey)\n );\n}\n\n/** The recorded asset for one path, or undefined if the manifest does not cover it. */\nexport function assetFor(manifest: BundleManifest, path: string): BundleAsset | undefined {\n return manifest.assets.find((asset) => asset.path === path);\n}\n\n/** The recorded digest for one asset, or undefined if the manifest does not cover it. */\nexport function digestFor(manifest: BundleManifest, path: string): string | undefined {\n return assetFor(manifest, path)?.sha256;\n}\n"],"mappings":"AAQA,MAQaA,EAAiB,cAMj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AM,GAC7D,CAACT,EAAcS,EAAM,WAAY,CAAC,GAClC,OAAOA,EAAM,aAAgB,UAAY,CAAChB,EAAa,KAAKgB,EAAM,WAAW,EAAG,MAAO,GAC3FO,EAAM,IAAIP,EAAM,IAAI,CACtB,CACA,OAAOK,EAAeM,EAAU,OAAyBJ,EAAOD,CAAO,CACzE,CAEA,SAAgBO,EAAuB,EAAgB,EAAyB,MAAsC,CAEpH,GADI,OAAO1B,GAAU,WAAYA,GAC7B,CAACF,EAAaE,EAAO,CAAC,WAAY,YAAa,WAAW,CAAC,EAAG,MAAO,GACzE,IAAMwB,EAAYxB,EAClB,OACEuB,EAAiBC,EAAU,SAAUL,CAAO,GAC5C,OAAOK,EAAU,WAAc,UAC/BA,EAAU,UAAU,SAAW,IAC/B5B,EAAU,KAAK4B,EAAU,SAAS,GAClC,OAAOA,EAAU,WAAc,UAC/BA,EAAU,UAAU,QAAU,KAC9B5B,EAAU,KAAK4B,EAAU,SAAS,CAEtC,CAGA,SAAgBG,EAAS,EAA0B,EAAuC,CACxF,OAAOjB,EAAS,OAAO,KAAM,GAAUG,EAAM,OAASe,CAAI,CAC5D,CAGA,SAAgBC,EAAU,EAA0B,EAAkC,CACpF,OAAOF,EAASjB,EAAUkB,CAAI,CAAC,EAAE,MACnC"}
|
|
1
|
+
{"version":3,"file":"bundleManifest.cjs","names":["WEB_ENTRY_PATH","ATTESTATION_TAG","SHA256","BASE64URL","CONTENT_TYPE","hasExactKeys","keys","value","expected","key","index","isSafeInteger","minimum","isSafeAssetPath","segment","canonicalManifest","lines","manifest","left","right","asset","attestationBytes","tag","fields","field","matchesProfile","profile","paths","assets","entry","isBundleManifest","candidate","valueAsset","isSignedBundleManifest","assetFor","path","digestFor"],"sources":["../../src/types/bundleManifest.ts"],"sourcesContent":["/**\n * A signed description of cockpit assets for an independently trusted verifier.\n *\n * A manifest does not let a browser SPA defend itself against the server or TLS\n * edge that supplied its executable code. Consumers need a separately trusted\n * bootstrap and key before these signatures become a delivery guarantee.\n */\n\nexport const BUNDLE_MANIFEST_ROUTE = '/bundle-manifest.json';\nexport const BUNDLE_MANIFEST_VERSION = 2;\n\n/**\n * Which asset shape a manifest must have. A web bundle always serves `/index.html`; a native bundle is\n * exactly one composition module and never serves `/index.html`; an app bundle is `/app.json` plus\n * `/bundle/` parts and serves neither entry, so no manifest can pass two profiles.\n */\nexport type BundleProfile = 'web' | 'native' | 'app';\nexport const WEB_ENTRY_PATH = '/index.html';\nexport const NATIVE_ENTRY_PATH = '/composition.js';\nexport const NATIVE_ENTRY_CONTENT_TYPE = 'text/javascript';\n/** Largest native composition a sealed response can carry. */\nexport const NATIVE_COMPOSITION_MAX_BYTES = 4 * 1024 * 1024;\n/** JSON `{ platform, fingerprint }` naming the native binary an app bundle runs on. */\nexport const APP_DESCRIPTOR_PATH = '/app.json';\n/** App JS bundle parts; concatenated in path order they are the bundle. */\nexport const APP_PART_PREFIX = '/bundle/';\n/** Largest app asset, so every part fits one sealed response. */\nexport const APP_ASSET_MAX_BYTES = 2 * 1024 * 1024;\n/** Domain-separation tag for an attestation. Starts with `p`, so it can never collide with a `2\\n` manifest. */\nexport const ATTESTATION_TAG = /^po\\/[a-z0-9-]+\\/v[1-9][0-9]*$/u;\n\nconst SHA256 = /^[0-9a-f]{64}$/u;\nconst BASE64URL = /^[A-Za-z0-9_-]+$/u;\nconst CONTENT_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\\/[a-z0-9][a-z0-9!#$&^_.+-]*$/u;\n\nexport interface BundleAsset {\n /** Normalized absolute URL path, without a query or fragment. */\n path: string;\n /** Lowercase hex SHA-256 of the served bytes. */\n sha256: string;\n byteLength: number;\n /** MIME type of the response, without parameters. */\n contentType: string;\n}\n\nexport interface BundleManifest {\n version: typeof BUNDLE_MANIFEST_VERSION;\n /** Monotonically increasing persistent signer revision. */\n revision: number;\n /** Unix time in milliseconds. */\n builtAt: number;\n assets: BundleAsset[];\n}\n\nexport interface SignedBundleManifest {\n manifest: BundleManifest;\n /** Base64url IEEE P1363 ECDSA P-256 signature over the canonical serialization. */\n signature: string;\n /** Base64url SPKI of the signing key. Trust must be established out of band. */\n publicKey: string;\n}\n\nfunction hasExactKeys(value: object, expected: readonly string[]): boolean {\n const keys = Object.keys(value).sort();\n return keys.length === expected.length && keys.every((key, index) => key === expected[index]);\n}\n\nfunction isSafeInteger(value: unknown, minimum: number): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= minimum;\n}\n\nfunction isSafeAssetPath(value: unknown): value is string {\n if (typeof value !== 'string' || value.length < 2 || !value.startsWith('/')) return false;\n if (value.includes('\\\\') || value.includes('\\0') || value.includes('?') || value.includes('#')) return false;\n if (/[^\\x21-\\x7e]/u.test(value) || value.includes('//') || /%(?![0-9a-f]{2})/iu.test(value)) return false;\n if (/%(?:2e|2f|5c)/iu.test(value)) return false;\n return value\n .split('/')\n .slice(1)\n .every((segment) => segment !== '' && segment !== '.' && segment !== '..');\n}\n\n/** The exact bytes signed by Node and verified by WebCrypto. */\nexport function canonicalManifest(manifest: BundleManifest): string {\n const assets = [...manifest.assets].sort((left, right) =>\n left.path < right.path ? -1 : left.path > right.path ? 1 : 0,\n );\n const lines = assets.map(\n (asset) => `${asset.path}\\0${asset.sha256}\\0${String(asset.byteLength)}\\0${asset.contentType}`,\n );\n return [String(manifest.version), String(manifest.revision), String(manifest.builtAt), ...lines].join('\\n');\n}\n\n/**\n * The exact bytes of a tagged attestation: `UTF-8(tag + \"\\n\" + JSON.stringify(fields))`. Fields are an\n * ordered list of strings, so both sides build the same bytes without relying on object key order.\n * Throws on a malformed tag or a non-string field.\n */\nexport function attestationBytes(tag: string, fields: readonly string[]): Uint8Array<ArrayBuffer> {\n if (!ATTESTATION_TAG.test(tag)) throw new Error(`invalid attestation tag: ${tag}`);\n if (!Array.isArray(fields) || !fields.every((field) => typeof field === 'string')) {\n throw new Error(`invalid attestation fields for ${tag}`);\n }\n return new TextEncoder().encode(`${tag}\\n${JSON.stringify(fields)}`);\n}\n\nfunction matchesProfile(assets: readonly BundleAsset[], paths: ReadonlySet<string>, profile: BundleProfile): boolean {\n if (profile === 'web') return paths.has(WEB_ENTRY_PATH);\n if (profile === 'app') {\n return (\n !paths.has(WEB_ENTRY_PATH) &&\n !paths.has(NATIVE_ENTRY_PATH) &&\n paths.has(APP_DESCRIPTOR_PATH) &&\n assets.some((asset) => asset.path.startsWith(APP_PART_PREFIX)) &&\n assets.every((asset) => asset.byteLength <= APP_ASSET_MAX_BYTES)\n );\n }\n if (profile !== 'native' || assets.length !== 1) return false;\n const [entry] = assets;\n return (\n entry !== undefined &&\n entry.path === NATIVE_ENTRY_PATH &&\n entry.contentType === NATIVE_ENTRY_CONTENT_TYPE &&\n entry.byteLength <= NATIVE_COMPOSITION_MAX_BYTES\n );\n}\n\nexport function isBundleManifest(value: unknown, profile: BundleProfile = 'web'): value is BundleManifest {\n if (typeof value !== 'object' || value === null) return false;\n if (!hasExactKeys(value, ['assets', 'builtAt', 'revision', 'version'])) return false;\n const candidate = value as Partial<BundleManifest>;\n if (candidate.version !== BUNDLE_MANIFEST_VERSION) return false;\n if (!isSafeInteger(candidate.revision, 1) || !isSafeInteger(candidate.builtAt, 0)) return false;\n if (!Array.isArray(candidate.assets) || candidate.assets.length === 0) return false;\n\n const paths = new Set<string>();\n for (const valueAsset of candidate.assets) {\n if (typeof valueAsset !== 'object' || valueAsset === null) return false;\n if (!hasExactKeys(valueAsset, ['byteLength', 'contentType', 'path', 'sha256'])) return false;\n const asset = valueAsset as Partial<BundleAsset>;\n if (!isSafeAssetPath(asset.path) || paths.has(asset.path)) return false;\n if (typeof asset.sha256 !== 'string' || !SHA256.test(asset.sha256)) return false;\n if (!isSafeInteger(asset.byteLength, 0)) return false;\n if (typeof asset.contentType !== 'string' || !CONTENT_TYPE.test(asset.contentType)) return false;\n paths.add(asset.path);\n }\n return matchesProfile(candidate.assets as BundleAsset[], paths, profile);\n}\n\nexport function isSignedBundleManifest(value: unknown, profile: BundleProfile = 'web'): value is SignedBundleManifest {\n if (typeof value !== 'object' || value === null) return false;\n if (!hasExactKeys(value, ['manifest', 'publicKey', 'signature'])) return false;\n const candidate = value as Partial<SignedBundleManifest>;\n return (\n isBundleManifest(candidate.manifest, profile) &&\n typeof candidate.signature === 'string' &&\n candidate.signature.length === 86 &&\n BASE64URL.test(candidate.signature) &&\n typeof candidate.publicKey === 'string' &&\n candidate.publicKey.length <= 512 &&\n BASE64URL.test(candidate.publicKey)\n );\n}\n\n/** The recorded asset for one path, or undefined if the manifest does not cover it. */\nexport function assetFor(manifest: BundleManifest, path: string): BundleAsset | undefined {\n return manifest.assets.find((asset) => asset.path === path);\n}\n\n/** The recorded digest for one asset, or undefined if the manifest does not cover it. */\nexport function digestFor(manifest: BundleManifest, path: string): string | undefined {\n return assetFor(manifest, path)?.sha256;\n}\n"],"mappings":"AAQA,MASaA,EAAiB,cAYjBC,EAAkB,kCAEzBC,EAAS,kBACTC,EAAY,oBACZC,EAAe,4DA6BrB,SAASC,EAAa,EAAe,EAAsC,CACzE,IAAMC,EAAO,OAAO,KAAKC,CAAK,CAAC,CAAC,KAAK,EACrC,OAAOD,EAAK,SAAWE,EAAS,QAAUF,EAAK,OAAO,EAAK,IAAUG,IAAQD,EAASE,EAAM,CAC9F,CAEA,SAASC,EAAc,EAAgB,EAAkC,CACvE,OAAO,OAAOJ,GAAU,UAAY,OAAO,cAAcA,CAAK,GAAKA,GAASK,CAC9E,CAEA,SAASC,EAAgB,EAAiC,CAKxD,OAJI,OAAON,GAAU,UAAYA,EAAM,OAAS,GAAK,CAACA,EAAM,WAAW,GAAG,GACtEA,EAAM,SAAS,IAAI,GAAKA,EAAM,SAAS,IAAI,GAAKA,EAAM,SAAS,GAAG,GAAKA,EAAM,SAAS,GAAG,GACzF,gBAAgB,KAAKA,CAAK,GAAKA,EAAM,SAAS,IAAI,GAAK,qBAAqB,KAAKA,CAAK,GACtF,kBAAkB,KAAKA,CAAK,EAAU,GACnCA,EACJ,MAAM,GAAG,CAAC,CACV,M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AAW,IAC/B5B,EAAU,KAAK4B,EAAU,SAAS,GAClC,OAAOA,EAAU,WAAc,UAC/BA,EAAU,UAAU,QAAU,KAC9B5B,EAAU,KAAK4B,EAAU,SAAS,CAEtC,CAGA,SAAgBG,EAAS,EAA0B,EAAuC,CACxF,OAAOjB,EAAS,OAAO,KAAM,GAAUG,EAAM,OAASe,CAAI,CAC5D,CAGA,SAAgBC,EAAU,EAA0B,EAAkC,CACpF,OAAOF,EAASjB,EAAUkB,CAAI,CAAC,EAAE,MACnC"}
|
|
@@ -10,14 +10,21 @@ export declare const BUNDLE_MANIFEST_ROUTE = "/bundle-manifest.json";
|
|
|
10
10
|
export declare const BUNDLE_MANIFEST_VERSION = 2;
|
|
11
11
|
/**
|
|
12
12
|
* Which asset shape a manifest must have. A web bundle always serves `/index.html`; a native bundle is
|
|
13
|
-
* exactly one composition module and never serves `/index.html
|
|
13
|
+
* exactly one composition module and never serves `/index.html`; an app bundle is `/app.json` plus
|
|
14
|
+
* `/bundle/` parts and serves neither entry, so no manifest can pass two profiles.
|
|
14
15
|
*/
|
|
15
|
-
export type BundleProfile = 'web' | 'native';
|
|
16
|
+
export type BundleProfile = 'web' | 'native' | 'app';
|
|
16
17
|
export declare const WEB_ENTRY_PATH = "/index.html";
|
|
17
18
|
export declare const NATIVE_ENTRY_PATH = "/composition.js";
|
|
18
19
|
export declare const NATIVE_ENTRY_CONTENT_TYPE = "text/javascript";
|
|
19
20
|
/** Largest native composition a sealed response can carry. */
|
|
20
21
|
export declare const NATIVE_COMPOSITION_MAX_BYTES: number;
|
|
22
|
+
/** JSON `{ platform, fingerprint }` naming the native binary an app bundle runs on. */
|
|
23
|
+
export declare const APP_DESCRIPTOR_PATH = "/app.json";
|
|
24
|
+
/** App JS bundle parts; concatenated in path order they are the bundle. */
|
|
25
|
+
export declare const APP_PART_PREFIX = "/bundle/";
|
|
26
|
+
/** Largest app asset, so every part fits one sealed response. */
|
|
27
|
+
export declare const APP_ASSET_MAX_BYTES: number;
|
|
21
28
|
/** Domain-separation tag for an attestation. Starts with `p`, so it can never collide with a `2\n` manifest. */
|
|
22
29
|
export declare const ATTESTATION_TAG: RegExp;
|
|
23
30
|
export interface BundleAsset {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundleManifest.d.mts","names":[],"sources":["../../src/types/bundleManifest.ts"],"mappings":";;;;;;;;qBAQa;qBACA
|
|
1
|
+
{"version":3,"file":"bundleManifest.d.mts","names":[],"sources":["../../src/types/bundleManifest.ts"],"mappings":";;;;;;;;qBAQa;qBACA;;;;;;YAOD;qBACC;qBACA;qBACA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;qBAEA,iBAAe;iBAMX;;EAEf;;EAEA;EACA;;EAEA;;iBAGe;EACf,gBAAgB;;EAEhB;;EAEA;EACA,QAAQ;;iBAGO;EACf,UAAU;;EAEV;;EAEA;;;wBAwBc,kBAAkB,UAAU;;;;;;wBAe5B,iBAAiB,aAAa,4BAA4B,WAAW;wBA6BrE,iBAAiB,gBAAgB,UAAS,gBAAwB,SAAS;wBAsB3E,uBAAuB,gBAAgB,UAAS,gBAAwB,SAAS;;wBAgBjF,SAAS,UAAU,gBAAgB,eAAe;;wBAKlD,UAAU,UAAU,gBAAgB"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
const e=`/bundle-manifest.json`,t=2,n=`/index.html`,r=`/composition.js`,i=`text/javascript`,a=4194304,o=/^po\/[a-z0-9-]+\/v[1-9][0-9]*$/u,
|
|
2
|
-
`)}function
|
|
1
|
+
const e=`/bundle-manifest.json`,t=2,n=`/index.html`,r=`/composition.js`,i=`text/javascript`,a=4194304,o=`/app.json`,s=`/bundle/`,c=2097152,l=/^po\/[a-z0-9-]+\/v[1-9][0-9]*$/u,u=/^[0-9a-f]{64}$/u,d=/^[A-Za-z0-9_-]+$/u,f=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/u;function p(e,t){let n=Object.keys(e).sort();return n.length===t.length&&n.every((e,n)=>e===t[n])}function m(e,t){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=t}function h(e){return typeof e!=`string`||e.length<2||!e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)||e.includes(`?`)||e.includes(`#`)||/[^\x21-\x7e]/u.test(e)||e.includes(`//`)||/%(?![0-9a-f]{2})/iu.test(e)||/%(?:2e|2f|5c)/iu.test(e)?!1:e.split(`/`).slice(1).every(e=>e!==``&&e!==`.`&&e!==`..`)}function g(e){let t=[...e.assets].sort((e,t)=>e.path<t.path?-1:+(e.path>t.path)).map(e=>`${e.path}\0${e.sha256}\0${String(e.byteLength)}\0${e.contentType}`);return[String(e.version),String(e.revision),String(e.builtAt),...t].join(`
|
|
2
|
+
`)}function _(e,t){if(!l.test(e))throw Error(`invalid attestation tag: ${e}`);if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw Error(`invalid attestation fields for ${e}`);return new TextEncoder().encode(`${e}\n${JSON.stringify(t)}`)}function v(e,t,r){if(r===`web`)return t.has(n);if(r===`app`)return!t.has(`/index.html`)&&!t.has(`/composition.js`)&&t.has(`/app.json`)&&e.some(e=>e.path.startsWith(`/bundle/`))&&e.every(e=>e.byteLength<=2097152);if(r!==`native`||e.length!==1)return!1;let[i]=e;return i!==void 0&&i.path===`/composition.js`&&i.contentType===`text/javascript`&&i.byteLength<=4194304}function y(e,t=`web`){if(typeof e!=`object`||!e||!p(e,[`assets`,`builtAt`,`revision`,`version`]))return!1;let n=e;if(n.version!==2||!m(n.revision,1)||!m(n.builtAt,0)||!Array.isArray(n.assets)||n.assets.length===0)return!1;let r=/* @__PURE__ */ new Set;for(let e of n.assets){if(typeof e!=`object`||!e||!p(e,[`byteLength`,`contentType`,`path`,`sha256`]))return!1;let t=e;if(!h(t.path)||r.has(t.path)||typeof t.sha256!=`string`||!u.test(t.sha256)||!m(t.byteLength,0)||typeof t.contentType!=`string`||!f.test(t.contentType))return!1;r.add(t.path)}return v(n.assets,r,t)}function b(e,t=`web`){if(typeof e!=`object`||!e||!p(e,[`manifest`,`publicKey`,`signature`]))return!1;let n=e;return y(n.manifest,t)&&typeof n.signature==`string`&&n.signature.length===86&&d.test(n.signature)&&typeof n.publicKey==`string`&&n.publicKey.length<=512&&d.test(n.publicKey)}function x(e,t){return e.assets.find(e=>e.path===t)}function S(e,t){return x(e,t)?.sha256}export{c as APP_ASSET_MAX_BYTES,o as APP_DESCRIPTOR_PATH,s as APP_PART_PREFIX,l as ATTESTATION_TAG,e as BUNDLE_MANIFEST_ROUTE,t as BUNDLE_MANIFEST_VERSION,a as NATIVE_COMPOSITION_MAX_BYTES,i as NATIVE_ENTRY_CONTENT_TYPE,r as NATIVE_ENTRY_PATH,n as WEB_ENTRY_PATH,x as assetFor,_ as attestationBytes,g as canonicalManifest,S as digestFor,y as isBundleManifest,b as isSignedBundleManifest};
|
|
3
3
|
//# sourceMappingURL=bundleManifest.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundleManifest.mjs","names":["BUNDLE_MANIFEST_ROUTE","BUNDLE_MANIFEST_VERSION","WEB_ENTRY_PATH","NATIVE_ENTRY_PATH","NATIVE_ENTRY_CONTENT_TYPE","NATIVE_COMPOSITION_MAX_BYTES","ATTESTATION_TAG","SHA256","BASE64URL","CONTENT_TYPE","hasExactKeys","keys","value","expected","key","index","isSafeInteger","minimum","isSafeAssetPath","segment","canonicalManifest","lines","manifest","left","right","asset","attestationBytes","tag","fields","field","matchesProfile","profile","paths","assets","entry","isBundleManifest","candidate","valueAsset","isSignedBundleManifest","assetFor","path","digestFor"],"sources":["../../src/types/bundleManifest.ts"],"sourcesContent":["/**\n * A signed description of cockpit assets for an independently trusted verifier.\n *\n * A manifest does not let a browser SPA defend itself against the server or TLS\n * edge that supplied its executable code. Consumers need a separately trusted\n * bootstrap and key before these signatures become a delivery guarantee.\n */\n\nexport const BUNDLE_MANIFEST_ROUTE = '/bundle-manifest.json';\nexport const BUNDLE_MANIFEST_VERSION = 2;\n\n/**\n * Which asset shape a manifest must have. A web bundle always serves `/index.html`; a native bundle is\n * exactly one composition module and never serves `/index.html`, so no manifest can pass both.\n */\nexport type BundleProfile = 'web' | 'native';\nexport const WEB_ENTRY_PATH = '/index.html';\nexport const NATIVE_ENTRY_PATH = '/composition.js';\nexport const NATIVE_ENTRY_CONTENT_TYPE = 'text/javascript';\n/** Largest native composition a sealed response can carry. */\nexport const NATIVE_COMPOSITION_MAX_BYTES = 4 * 1024 * 1024;\n/** Domain-separation tag for an attestation. Starts with `p`, so it can never collide with a `2\\n` manifest. */\nexport const ATTESTATION_TAG = /^po\\/[a-z0-9-]+\\/v[1-9][0-9]*$/u;\n\nconst SHA256 = /^[0-9a-f]{64}$/u;\nconst BASE64URL = /^[A-Za-z0-9_-]+$/u;\nconst CONTENT_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\\/[a-z0-9][a-z0-9!#$&^_.+-]*$/u;\n\nexport interface BundleAsset {\n /** Normalized absolute URL path, without a query or fragment. */\n path: string;\n /** Lowercase hex SHA-256 of the served bytes. */\n sha256: string;\n byteLength: number;\n /** MIME type of the response, without parameters. */\n contentType: string;\n}\n\nexport interface BundleManifest {\n version: typeof BUNDLE_MANIFEST_VERSION;\n /** Monotonically increasing persistent signer revision. */\n revision: number;\n /** Unix time in milliseconds. */\n builtAt: number;\n assets: BundleAsset[];\n}\n\nexport interface SignedBundleManifest {\n manifest: BundleManifest;\n /** Base64url IEEE P1363 ECDSA P-256 signature over the canonical serialization. */\n signature: string;\n /** Base64url SPKI of the signing key. Trust must be established out of band. */\n publicKey: string;\n}\n\nfunction hasExactKeys(value: object, expected: readonly string[]): boolean {\n const keys = Object.keys(value).sort();\n return keys.length === expected.length && keys.every((key, index) => key === expected[index]);\n}\n\nfunction isSafeInteger(value: unknown, minimum: number): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= minimum;\n}\n\nfunction isSafeAssetPath(value: unknown): value is string {\n if (typeof value !== 'string' || value.length < 2 || !value.startsWith('/')) return false;\n if (value.includes('\\\\') || value.includes('\\0') || value.includes('?') || value.includes('#')) return false;\n if (/[^\\x21-\\x7e]/u.test(value) || value.includes('//') || /%(?![0-9a-f]{2})/iu.test(value)) return false;\n if (/%(?:2e|2f|5c)/iu.test(value)) return false;\n return value\n .split('/')\n .slice(1)\n .every((segment) => segment !== '' && segment !== '.' && segment !== '..');\n}\n\n/** The exact bytes signed by Node and verified by WebCrypto. */\nexport function canonicalManifest(manifest: BundleManifest): string {\n const assets = [...manifest.assets].sort((left, right) =>\n left.path < right.path ? -1 : left.path > right.path ? 1 : 0,\n );\n const lines = assets.map(\n (asset) => `${asset.path}\\0${asset.sha256}\\0${String(asset.byteLength)}\\0${asset.contentType}`,\n );\n return [String(manifest.version), String(manifest.revision), String(manifest.builtAt), ...lines].join('\\n');\n}\n\n/**\n * The exact bytes of a tagged attestation: `UTF-8(tag + \"\\n\" + JSON.stringify(fields))`. Fields are an\n * ordered list of strings, so both sides build the same bytes without relying on object key order.\n * Throws on a malformed tag or a non-string field.\n */\nexport function attestationBytes(tag: string, fields: readonly string[]): Uint8Array<ArrayBuffer> {\n if (!ATTESTATION_TAG.test(tag)) throw new Error(`invalid attestation tag: ${tag}`);\n if (!Array.isArray(fields) || !fields.every((field) => typeof field === 'string')) {\n throw new Error(`invalid attestation fields for ${tag}`);\n }\n return new TextEncoder().encode(`${tag}\\n${JSON.stringify(fields)}`);\n}\n\nfunction matchesProfile(assets: readonly BundleAsset[], paths: ReadonlySet<string>, profile: BundleProfile): boolean {\n if (profile === 'web') return paths.has(WEB_ENTRY_PATH);\n if (profile !== 'native' || assets.length !== 1) return false;\n const [entry] = assets;\n return (\n entry !== undefined &&\n entry.path === NATIVE_ENTRY_PATH &&\n entry.contentType === NATIVE_ENTRY_CONTENT_TYPE &&\n entry.byteLength <= NATIVE_COMPOSITION_MAX_BYTES\n );\n}\n\nexport function isBundleManifest(value: unknown, profile: BundleProfile = 'web'): value is BundleManifest {\n if (typeof value !== 'object' || value === null) return false;\n if (!hasExactKeys(value, ['assets', 'builtAt', 'revision', 'version'])) return false;\n const candidate = value as Partial<BundleManifest>;\n if (candidate.version !== BUNDLE_MANIFEST_VERSION) return false;\n if (!isSafeInteger(candidate.revision, 1) || !isSafeInteger(candidate.builtAt, 0)) return false;\n if (!Array.isArray(candidate.assets) || candidate.assets.length === 0) return false;\n\n const paths = new Set<string>();\n for (const valueAsset of candidate.assets) {\n if (typeof valueAsset !== 'object' || valueAsset === null) return false;\n if (!hasExactKeys(valueAsset, ['byteLength', 'contentType', 'path', 'sha256'])) return false;\n const asset = valueAsset as Partial<BundleAsset>;\n if (!isSafeAssetPath(asset.path) || paths.has(asset.path)) return false;\n if (typeof asset.sha256 !== 'string' || !SHA256.test(asset.sha256)) return false;\n if (!isSafeInteger(asset.byteLength, 0)) return false;\n if (typeof asset.contentType !== 'string' || !CONTENT_TYPE.test(asset.contentType)) return false;\n paths.add(asset.path);\n }\n return matchesProfile(candidate.assets as BundleAsset[], paths, profile);\n}\n\nexport function isSignedBundleManifest(value: unknown, profile: BundleProfile = 'web'): value is SignedBundleManifest {\n if (typeof value !== 'object' || value === null) return false;\n if (!hasExactKeys(value, ['manifest', 'publicKey', 'signature'])) return false;\n const candidate = value as Partial<SignedBundleManifest>;\n return (\n isBundleManifest(candidate.manifest, profile) &&\n typeof candidate.signature === 'string' &&\n candidate.signature.length === 86 &&\n BASE64URL.test(candidate.signature) &&\n typeof candidate.publicKey === 'string' &&\n candidate.publicKey.length <= 512 &&\n BASE64URL.test(candidate.publicKey)\n );\n}\n\n/** The recorded asset for one path, or undefined if the manifest does not cover it. */\nexport function assetFor(manifest: BundleManifest, path: string): BundleAsset | undefined {\n return manifest.assets.find((asset) => asset.path === path);\n}\n\n/** The recorded digest for one asset, or undefined if the manifest does not cover it. */\nexport function digestFor(manifest: BundleManifest, path: string): string | undefined {\n return assetFor(manifest, path)?.sha256;\n}\n"],"mappings":"AAQA,MAAaA,EAAwB,wBAC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AAIP,EAAM,IAAI,GACpD,OAAOA,EAAM,QAAW,UAAY,CAAClB,EAAO,KAAKkB,EAAM,MAAM,GAC7D,CAACT,EAAcS,EAAM,WAAY,CAAC,GAClC,OAAOA,EAAM,aAAgB,UAAY,CAAChB,EAAa,KAAKgB,EAAM,WAAW,EAAG,MAAO,GAC3FO,EAAM,IAAIP,EAAM,IAAI,CACtB,CACA,OAAOK,EAAeM,EAAU,OAAyBJ,EAAOD,CAAO,CACzE,CAEA,SAAgBO,EAAuB,EAAgB,EAAyB,MAAsC,CAEpH,GADI,OAAO1B,GAAU,WAAYA,GAC7B,CAACF,EAAaE,EAAO,CAAC,WAAY,YAAa,WAAW,CAAC,EAAG,MAAO,GACzE,IAAMwB,EAAYxB,EAClB,OACEuB,EAAiBC,EAAU,SAAUL,CAAO,GAC5C,OAAOK,EAAU,WAAc,UAC/BA,EAAU,UAAU,SAAW,IAC/B5B,EAAU,KAAK4B,EAAU,SAAS,GAClC,OAAOA,EAAU,WAAc,UAC/BA,EAAU,UAAU,QAAU,KAC9B5B,EAAU,KAAK4B,EAAU,SAAS,CAEtC,CAGA,SAAgBG,EAAS,EAA0B,EAAuC,CACxF,OAAOjB,EAAS,OAAO,KAAM,GAAUG,EAAM,OAASe,CAAI,CAC5D,CAGA,SAAgBC,EAAU,EAA0B,EAAkC,CACpF,OAAOF,EAASjB,EAAUkB,CAAI,CAAC,EAAE,MACnC"}
|
|
1
|
+
{"version":3,"file":"bundleManifest.mjs","names":["BUNDLE_MANIFEST_ROUTE","BUNDLE_MANIFEST_VERSION","WEB_ENTRY_PATH","NATIVE_ENTRY_PATH","NATIVE_ENTRY_CONTENT_TYPE","NATIVE_COMPOSITION_MAX_BYTES","APP_DESCRIPTOR_PATH","APP_PART_PREFIX","APP_ASSET_MAX_BYTES","ATTESTATION_TAG","SHA256","BASE64URL","CONTENT_TYPE","hasExactKeys","keys","value","expected","key","index","isSafeInteger","minimum","isSafeAssetPath","segment","canonicalManifest","lines","manifest","left","right","asset","attestationBytes","tag","fields","field","matchesProfile","profile","paths","assets","entry","isBundleManifest","candidate","valueAsset","isSignedBundleManifest","assetFor","path","digestFor"],"sources":["../../src/types/bundleManifest.ts"],"sourcesContent":["/**\n * A signed description of cockpit assets for an independently trusted verifier.\n *\n * A manifest does not let a browser SPA defend itself against the server or TLS\n * edge that supplied its executable code. Consumers need a separately trusted\n * bootstrap and key before these signatures become a delivery guarantee.\n */\n\nexport const BUNDLE_MANIFEST_ROUTE = '/bundle-manifest.json';\nexport const BUNDLE_MANIFEST_VERSION = 2;\n\n/**\n * Which asset shape a manifest must have. A web bundle always serves `/index.html`; a native bundle is\n * exactly one composition module and never serves `/index.html`; an app bundle is `/app.json` plus\n * `/bundle/` parts and serves neither entry, so no manifest can pass two profiles.\n */\nexport type BundleProfile = 'web' | 'native' | 'app';\nexport const WEB_ENTRY_PATH = '/index.html';\nexport const NATIVE_ENTRY_PATH = '/composition.js';\nexport const NATIVE_ENTRY_CONTENT_TYPE = 'text/javascript';\n/** Largest native composition a sealed response can carry. */\nexport const NATIVE_COMPOSITION_MAX_BYTES = 4 * 1024 * 1024;\n/** JSON `{ platform, fingerprint }` naming the native binary an app bundle runs on. */\nexport const APP_DESCRIPTOR_PATH = '/app.json';\n/** App JS bundle parts; concatenated in path order they are the bundle. */\nexport const APP_PART_PREFIX = '/bundle/';\n/** Largest app asset, so every part fits one sealed response. */\nexport const APP_ASSET_MAX_BYTES = 2 * 1024 * 1024;\n/** Domain-separation tag for an attestation. Starts with `p`, so it can never collide with a `2\\n` manifest. */\nexport const ATTESTATION_TAG = /^po\\/[a-z0-9-]+\\/v[1-9][0-9]*$/u;\n\nconst SHA256 = /^[0-9a-f]{64}$/u;\nconst BASE64URL = /^[A-Za-z0-9_-]+$/u;\nconst CONTENT_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\\/[a-z0-9][a-z0-9!#$&^_.+-]*$/u;\n\nexport interface BundleAsset {\n /** Normalized absolute URL path, without a query or fragment. */\n path: string;\n /** Lowercase hex SHA-256 of the served bytes. */\n sha256: string;\n byteLength: number;\n /** MIME type of the response, without parameters. */\n contentType: string;\n}\n\nexport interface BundleManifest {\n version: typeof BUNDLE_MANIFEST_VERSION;\n /** Monotonically increasing persistent signer revision. */\n revision: number;\n /** Unix time in milliseconds. */\n builtAt: number;\n assets: BundleAsset[];\n}\n\nexport interface SignedBundleManifest {\n manifest: BundleManifest;\n /** Base64url IEEE P1363 ECDSA P-256 signature over the canonical serialization. */\n signature: string;\n /** Base64url SPKI of the signing key. Trust must be established out of band. */\n publicKey: string;\n}\n\nfunction hasExactKeys(value: object, expected: readonly string[]): boolean {\n const keys = Object.keys(value).sort();\n return keys.length === expected.length && keys.every((key, index) => key === expected[index]);\n}\n\nfunction isSafeInteger(value: unknown, minimum: number): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= minimum;\n}\n\nfunction isSafeAssetPath(value: unknown): value is string {\n if (typeof value !== 'string' || value.length < 2 || !value.startsWith('/')) return false;\n if (value.includes('\\\\') || value.includes('\\0') || value.includes('?') || value.includes('#')) return false;\n if (/[^\\x21-\\x7e]/u.test(value) || value.includes('//') || /%(?![0-9a-f]{2})/iu.test(value)) return false;\n if (/%(?:2e|2f|5c)/iu.test(value)) return false;\n return value\n .split('/')\n .slice(1)\n .every((segment) => segment !== '' && segment !== '.' && segment !== '..');\n}\n\n/** The exact bytes signed by Node and verified by WebCrypto. */\nexport function canonicalManifest(manifest: BundleManifest): string {\n const assets = [...manifest.assets].sort((left, right) =>\n left.path < right.path ? -1 : left.path > right.path ? 1 : 0,\n );\n const lines = assets.map(\n (asset) => `${asset.path}\\0${asset.sha256}\\0${String(asset.byteLength)}\\0${asset.contentType}`,\n );\n return [String(manifest.version), String(manifest.revision), String(manifest.builtAt), ...lines].join('\\n');\n}\n\n/**\n * The exact bytes of a tagged attestation: `UTF-8(tag + \"\\n\" + JSON.stringify(fields))`. Fields are an\n * ordered list of strings, so both sides build the same bytes without relying on object key order.\n * Throws on a malformed tag or a non-string field.\n */\nexport function attestationBytes(tag: string, fields: readonly string[]): Uint8Array<ArrayBuffer> {\n if (!ATTESTATION_TAG.test(tag)) throw new Error(`invalid attestation tag: ${tag}`);\n if (!Array.isArray(fields) || !fields.every((field) => typeof field === 'string')) {\n throw new Error(`invalid attestation fields for ${tag}`);\n }\n return new TextEncoder().encode(`${tag}\\n${JSON.stringify(fields)}`);\n}\n\nfunction matchesProfile(assets: readonly BundleAsset[], paths: ReadonlySet<string>, profile: BundleProfile): boolean {\n if (profile === 'web') return paths.has(WEB_ENTRY_PATH);\n if (profile === 'app') {\n return (\n !paths.has(WEB_ENTRY_PATH) &&\n !paths.has(NATIVE_ENTRY_PATH) &&\n paths.has(APP_DESCRIPTOR_PATH) &&\n assets.some((asset) => asset.path.startsWith(APP_PART_PREFIX)) &&\n assets.every((asset) => asset.byteLength <= APP_ASSET_MAX_BYTES)\n );\n }\n if (profile !== 'native' || assets.length !== 1) return false;\n const [entry] = assets;\n return (\n entry !== undefined &&\n entry.path === NATIVE_ENTRY_PATH &&\n entry.contentType === NATIVE_ENTRY_CONTENT_TYPE &&\n entry.byteLength <= NATIVE_COMPOSITION_MAX_BYTES\n );\n}\n\nexport function isBundleManifest(value: unknown, profile: BundleProfile = 'web'): value is BundleManifest {\n if (typeof value !== 'object' || value === null) return false;\n if (!hasExactKeys(value, ['assets', 'builtAt', 'revision', 'version'])) return false;\n const candidate = value as Partial<BundleManifest>;\n if (candidate.version !== BUNDLE_MANIFEST_VERSION) return false;\n if (!isSafeInteger(candidate.revision, 1) || !isSafeInteger(candidate.builtAt, 0)) return false;\n if (!Array.isArray(candidate.assets) || candidate.assets.length === 0) return false;\n\n const paths = new Set<string>();\n for (const valueAsset of candidate.assets) {\n if (typeof valueAsset !== 'object' || valueAsset === null) return false;\n if (!hasExactKeys(valueAsset, ['byteLength', 'contentType', 'path', 'sha256'])) return false;\n const asset = valueAsset as Partial<BundleAsset>;\n if (!isSafeAssetPath(asset.path) || paths.has(asset.path)) return false;\n if (typeof asset.sha256 !== 'string' || !SHA256.test(asset.sha256)) return false;\n if (!isSafeInteger(asset.byteLength, 0)) return false;\n if (typeof asset.contentType !== 'string' || !CONTENT_TYPE.test(asset.contentType)) return false;\n paths.add(asset.path);\n }\n return matchesProfile(candidate.assets as BundleAsset[], paths, profile);\n}\n\nexport function isSignedBundleManifest(value: unknown, profile: BundleProfile = 'web'): value is SignedBundleManifest {\n if (typeof value !== 'object' || value === null) return false;\n if (!hasExactKeys(value, ['manifest', 'publicKey', 'signature'])) return false;\n const candidate = value as Partial<SignedBundleManifest>;\n return (\n isBundleManifest(candidate.manifest, profile) &&\n typeof candidate.signature === 'string' &&\n candidate.signature.length === 86 &&\n BASE64URL.test(candidate.signature) &&\n typeof candidate.publicKey === 'string' &&\n candidate.publicKey.length <= 512 &&\n BASE64URL.test(candidate.publicKey)\n );\n}\n\n/** The recorded asset for one path, or undefined if the manifest does not cover it. */\nexport function assetFor(manifest: BundleManifest, path: string): BundleAsset | undefined {\n return manifest.assets.find((asset) => asset.path === path);\n}\n\n/** The recorded digest for one asset, or undefined if the manifest does not cover it. */\nexport function digestFor(manifest: BundleManifest, path: string): string | undefined {\n return assetFor(manifest, path)?.sha256;\n}\n"],"mappings":"AAQA,MAAaA,EAAwB,wBACxBC,EAA0B,EAQ1BC,EAAiB,cACjBC,EAAoB,kBACpBC,EAA4B,kBAE5BC,EAA+B,QAE/BC,EAAsB,YAEtBC,EAAkB,WAElBC,EAAsB,QAEtBC,EAAkB,kCAEzBC,EAAS,kBACTC,EAAY,oBACZC,EAAe,4DA6BrB,SAASC,EAAa,EAAe,EAAsC,CACzE,IAAMC,EAAO,OAAO,KAAKC,CAAK,CAAC,CAAC,KAAK,EACrC,OAAOD,EAAK,SAAWE,EAAS,QAAUF,EAAK,OAAO,EAAK,IAAUG,IAAQD,EAASE,EAAM,CAC9F,CAEA,SAASC,EAAc,EAAgB,EAAkC,CACvE,OAAO,OAAOJ,GAAU,UAAY,OAAO,cAAc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AAKgB,EAAM,WAAW,EAAG,MAAO,GAC3FO,EAAM,IAAIP,EAAM,IAAI,CACtB,CACA,OAAOK,EAAeM,EAAU,OAAyBJ,EAAOD,CAAO,CACzE,CAEA,SAAgBO,EAAuB,EAAgB,EAAyB,MAAsC,CAEpH,GADI,OAAO1B,GAAU,WAAYA,GAC7B,CAACF,EAAaE,EAAO,CAAC,WAAY,YAAa,WAAW,CAAC,EAAG,MAAO,GACzE,IAAMwB,EAAYxB,EAClB,OACEuB,EAAiBC,EAAU,SAAUL,CAAO,GAC5C,OAAOK,EAAU,WAAc,UAC/BA,EAAU,UAAU,SAAW,IAC/B5B,EAAU,KAAK4B,EAAU,SAAS,GAClC,OAAOA,EAAU,WAAc,UAC/BA,EAAU,UAAU,QAAU,KAC9B5B,EAAU,KAAK4B,EAAU,SAAS,CAEtC,CAGA,SAAgBG,EAAS,EAA0B,EAAuC,CACxF,OAAOjB,EAAS,OAAO,KAAM,GAAUG,EAAM,OAASe,CAAI,CAC5D,CAGA,SAAgBC,EAAU,EAA0B,EAAkC,CACpF,OAAOF,EAASjB,EAAUkB,CAAI,CAAC,EAAE,MACnC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agimon-ai/po-web-security",
|
|
3
|
-
"version": "0.0.0-alpha.
|
|
3
|
+
"version": "0.0.0-alpha.31",
|
|
4
4
|
"description": "Shared security primitives for the Po web cockpit: sealed channels and signed bundle manifests for independently trusted verifiers.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
"bugs": {
|
|
18
18
|
"url": "https://github.com/AgiFlow/po/issues"
|
|
19
19
|
},
|
|
20
|
-
"license": "
|
|
20
|
+
"license": "BUSL-1.1",
|
|
21
21
|
"author": "Vuong Ngo",
|
|
22
22
|
"repository": {
|
|
23
23
|
"type": "git",
|
|
@@ -57,11 +57,11 @@
|
|
|
57
57
|
"access": "public"
|
|
58
58
|
},
|
|
59
59
|
"devDependencies": {
|
|
60
|
-
"@types/node": "
|
|
61
|
-
"@vitest/coverage-v8": "5.0.
|
|
60
|
+
"@types/node": "26.6.5",
|
|
61
|
+
"@vitest/coverage-v8": "5.0.4",
|
|
62
62
|
"tsdown": "0.23.1",
|
|
63
63
|
"typescript": "7.0.2",
|
|
64
|
-
"vitest": "5.0.
|
|
64
|
+
"vitest": "5.0.4"
|
|
65
65
|
},
|
|
66
66
|
"engines": {
|
|
67
67
|
"node": ">=24"
|