@agimon-ai/po-web-security 0.0.0-alpha.11 → 0.0.0-alpha.110
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/README.md +22 -2
- package/dist/browser.cjs +1 -1
- package/dist/browser.d.mts +3 -2
- package/dist/browser.mjs +1 -1
- package/dist/deviceProof.cjs +1 -0
- package/dist/deviceProof.d.mts +7 -0
- package/dist/deviceProof.mjs +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.mts +2 -1
- package/dist/index.mjs +1 -1
- package/dist/node.cjs +1 -1
- package/dist/node.d.mts +3 -2
- package/dist/node.mjs +1 -1
- package/dist/nodeSealedChannel.cjs +1 -0
- package/dist/nodeSealedChannel.d.mts +2 -0
- package/dist/nodeSealedChannel.mjs +1 -0
- package/dist/outboundHost.cjs +1 -0
- package/dist/outboundHost.d.mts +3 -0
- package/dist/outboundHost.mjs +1 -0
- 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.map +1 -1
- package/dist/services/bundleSigner/index.d.mts.map +1 -1
- package/dist/services/bundleSigner/index.mjs.map +1 -1
- package/dist/services/deviceSignature/index.cjs +1 -1
- package/dist/services/deviceSignature/index.cjs.map +1 -1
- package/dist/services/deviceSignature/index.mjs +1 -1
- package/dist/services/deviceSignature/index.mjs.map +1 -1
- package/dist/services/federationEnvelope/index.cjs +2 -0
- package/dist/services/federationEnvelope/index.cjs.map +1 -0
- package/dist/services/federationEnvelope/index.d.mts +13 -0
- package/dist/services/federationEnvelope/index.d.mts.map +1 -0
- package/dist/services/federationEnvelope/index.mjs +2 -0
- package/dist/services/federationEnvelope/index.mjs.map +1 -0
- package/dist/services/federationIssuerHttp/index.cjs +2 -0
- package/dist/services/federationIssuerHttp/index.cjs.map +1 -0
- package/dist/services/federationIssuerHttp/index.d.mts +13 -0
- package/dist/services/federationIssuerHttp/index.d.mts.map +1 -0
- package/dist/services/federationIssuerHttp/index.mjs +2 -0
- package/dist/services/federationIssuerHttp/index.mjs.map +1 -0
- package/dist/services/federationIssuerHttp/type.d.mts +46 -0
- package/dist/services/federationIssuerHttp/type.d.mts.map +1 -0
- package/dist/services/federationVerifier/index.cjs +2 -0
- package/dist/services/federationVerifier/index.cjs.map +1 -0
- package/dist/services/federationVerifier/index.d.mts +12 -0
- package/dist/services/federationVerifier/index.d.mts.map +1 -0
- package/dist/services/federationVerifier/index.mjs +2 -0
- package/dist/services/federationVerifier/index.mjs.map +1 -0
- package/dist/services/federationVerifier/type.d.mts +129 -0
- package/dist/services/federationVerifier/type.d.mts.map +1 -0
- package/dist/services/outboundHost/index.cjs +2 -0
- package/dist/services/outboundHost/index.cjs.map +1 -0
- package/dist/services/outboundHost/index.d.mts +20 -0
- package/dist/services/outboundHost/index.d.mts.map +1 -0
- package/dist/services/outboundHost/index.mjs +2 -0
- package/dist/services/outboundHost/index.mjs.map +1 -0
- package/dist/services/outboundHost/type.d.mts +19 -0
- package/dist/services/outboundHost/type.d.mts.map +1 -0
- package/dist/services/sealedTransport/index.cjs +1 -1
- package/dist/services/sealedTransport/index.cjs.map +1 -1
- package/dist/services/sealedTransport/index.d.mts +11 -19
- 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 +2 -2
- package/dist/types/bundleManifest.cjs.map +1 -1
- package/dist/types/bundleManifest.d.mts +3 -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/dist/types/federation.cjs +2 -0
- package/dist/types/federation.cjs.map +1 -0
- package/dist/types/federation.d.mts +40 -0
- package/dist/types/federation.d.mts.map +1 -0
- package/dist/types/federation.mjs +2 -0
- package/dist/types/federation.mjs.map +1 -0
- package/package.json +19 -4
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/README.md
CHANGED
|
@@ -52,8 +52,8 @@ go on.
|
|
|
52
52
|
|
|
53
53
|
The Node signer traverses a public asset root without following symlinks, hashes each byte sequence, and signs
|
|
54
54
|
a strict canonical manifest v2 with ECDSA P-256. Every manifest is checked against a profile. The `web` profile
|
|
55
|
-
requires `/index.html`. The `native` profile requires
|
|
56
|
-
|
|
55
|
+
requires `/index.html`. The `native` profile requires one or more top-level `.js` modules (such as `/<hash>.js`), each
|
|
56
|
+
`text/javascript` and at most 4 MiB, so a manifest can never pass both profiles. Signer and verifier take the same profile. Revision state and the private key
|
|
57
57
|
are persisted atomically at mode `0600`; malformed or replaced state fails closed instead of rotating
|
|
58
58
|
silently.
|
|
59
59
|
|
|
@@ -85,6 +85,26 @@ import { sealedTransport } from '@agimon-ai/po-web-security/browser';
|
|
|
85
85
|
import { createBundleSigner, createHostHandshake } from '@agimon-ai/po-web-security/node';
|
|
86
86
|
```
|
|
87
87
|
|
|
88
|
+
## Federation destination verification
|
|
89
|
+
|
|
90
|
+
`deviceProof` exports `createFederationVerifier`, `FederationReplayStore`, and
|
|
91
|
+
`createFederationIssuerHttp`. The verifier checks ES256 issuer JWTs, C3 device proofs,
|
|
92
|
+
C4 host proofs and C5 grants, exact recovery epochs, request scope/body binding and
|
|
93
|
+
atomic durable nonce admission. C1 binds the device key thumbprint; C2 binds the
|
|
94
|
+
calling host key thumbprint. Token org/role authority lasts only until its conservative
|
|
95
|
+
expiry. It does not create membership or authorize a workspace by itself.
|
|
96
|
+
|
|
97
|
+
Issuer origins and initial JWKS must be locally pinned at claim/join. Unknown `kid`
|
|
98
|
+
rotation and device-key/feed HTTP requests use only that origin with redirects refused.
|
|
99
|
+
The HTTP adapter persists cursor/feed state through injected ports; missing state or
|
|
100
|
+
state older than ten minutes fails closed when the issuer is unavailable. Device keys
|
|
101
|
+
come from a trusted local registry or the host-authenticated issuer lookup, not envelopes.
|
|
102
|
+
The destination supplies its home-host ACL/provider-consent authorization callback.
|
|
103
|
+
|
|
104
|
+
All replay times and envelope dates are milliseconds; JWT NumericDate claims are seconds.
|
|
105
|
+
Browser/native signers use `federationEnvelopeFields` from `browser` with
|
|
106
|
+
`attestationBytes(tag, fields)`. `browser` also exports `FEDERATION_FRESHNESS`.
|
|
107
|
+
|
|
88
108
|
## Development
|
|
89
109
|
|
|
90
110
|
```bash
|
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.
|
|
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"),i=require("./types/federation.cjs");exports.ATTESTATION_TAG=e.ATTESTATION_TAG,exports.BUNDLE_MANIFEST_ROUTE=e.BUNDLE_MANIFEST_ROUTE,exports.BUNDLE_MANIFEST_VERSION=e.BUNDLE_MANIFEST_VERSION,exports.FEDERATION_FRESHNESS=i.FEDERATION_FRESHNESS,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.bindBrowserTransport=r.bindBrowserTransport,exports.browserTransport=r.browserTransport,exports.browserTransportForHost=r.browserTransportForHost,exports.canonicalManifest=e.canonicalManifest,exports.channelFromSecret=n.channelFromSecret,exports.connectSealedChannel=n.connectSealedChannel,exports.createSealedTransport=r.createSealedTransport,exports.digestFor=e.digestFor,exports.federationEnvelopeFields=i.federationEnvelopeFields,exports.isBundleManifest=e.isBundleManifest,exports.isSignedBundleManifest=e.isSignedBundleManifest,exports.verifyAttestation=t.verifyAttestation,exports.verifyBundleAsset=t.verifyBundleAsset,exports.verifySignedBundleManifest=t.verifySignedBundleManifest;
|
package/dist/browser.d.mts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
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";
|
|
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
|
-
import { SealedTransport,
|
|
5
|
-
|
|
4
|
+
import { SealedTransport, bindBrowserTransport, browserTransport, browserTransportForHost, createSealedTransport } from "./services/sealedTransport/index.mjs";
|
|
5
|
+
import { FEDERATION_FRESHNESS, federationEnvelopeFields } from "./types/federation.mjs";
|
|
6
|
+
export { ATTESTATION_TAG, BUNDLE_MANIFEST_ROUTE, BUNDLE_MANIFEST_VERSION, type BundleAsset, type BundleAssetVerificationFailure, type BundleAssetVerificationResult, type BundleManifest, type BundleProfile, type BundleVerificationFailure, type BundleVerificationResult, FEDERATION_FRESHNESS, 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, bindBrowserTransport, browserTransport, browserTransportForHost, canonicalManifest, channelFromSecret, connectSealedChannel, createSealedTransport, digestFor, federationEnvelopeFields, isBundleManifest, isSignedBundleManifest, verifyAttestation, verifyBundleAsset, verifySignedBundleManifest };
|
package/dist/browser.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ATTESTATION_TAG as e,BUNDLE_MANIFEST_ROUTE as t,BUNDLE_MANIFEST_VERSION as n,NATIVE_COMPOSITION_MAX_BYTES as r,NATIVE_ENTRY_CONTENT_TYPE as i,NATIVE_ENTRY_PATH as a,WEB_ENTRY_PATH as o,assetFor as s,attestationBytes as c,canonicalManifest as l,digestFor as u,isBundleManifest as d,isSignedBundleManifest as f}from"./types/bundleManifest.mjs";import{verifyAttestation as p,verifyBundleAsset as m,verifySignedBundleManifest as h}from"./services/browserBundleVerifier/index.mjs";import{channelFromSecret as g,connectSealedChannel as _}from"./services/browserSealedChannel/index.mjs";import{
|
|
1
|
+
import{ATTESTATION_TAG as e,BUNDLE_MANIFEST_ROUTE as t,BUNDLE_MANIFEST_VERSION as n,NATIVE_COMPOSITION_MAX_BYTES as r,NATIVE_ENTRY_CONTENT_TYPE as i,NATIVE_ENTRY_PATH as a,WEB_ENTRY_PATH as o,assetFor as s,attestationBytes as c,canonicalManifest as l,digestFor as u,isBundleManifest as d,isSignedBundleManifest as f}from"./types/bundleManifest.mjs";import{verifyAttestation as p,verifyBundleAsset as m,verifySignedBundleManifest as h}from"./services/browserBundleVerifier/index.mjs";import{channelFromSecret as g,connectSealedChannel as _}from"./services/browserSealedChannel/index.mjs";import{bindBrowserTransport as v,browserTransport as y,browserTransportForHost as b,createSealedTransport as x}from"./services/sealedTransport/index.mjs";import{FEDERATION_FRESHNESS as S,federationEnvelopeFields as C}from"./types/federation.mjs";export{e as ATTESTATION_TAG,t as BUNDLE_MANIFEST_ROUTE,n as BUNDLE_MANIFEST_VERSION,S as FEDERATION_FRESHNESS,r as NATIVE_COMPOSITION_MAX_BYTES,i as NATIVE_ENTRY_CONTENT_TYPE,a as NATIVE_ENTRY_PATH,o as WEB_ENTRY_PATH,s as assetFor,c as attestationBytes,v as bindBrowserTransport,y as browserTransport,b as browserTransportForHost,l as canonicalManifest,g as channelFromSecret,_ as connectSealedChannel,x as createSealedTransport,u as digestFor,C as federationEnvelopeFields,d as isBundleManifest,f as isSignedBundleManifest,p as verifyAttestation,m as verifyBundleAsset,h as verifySignedBundleManifest};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./services/deviceSignature/index.cjs"),t=require("./services/federationEnvelope/index.cjs"),n=require("./services/federationVerifier/index.cjs"),r=require("./services/federationIssuerHttp/index.cjs");exports.createFederationIssuerHttp=r.createFederationIssuerHttp,exports.createFederationVerifier=n.createFederationVerifier,exports.federationDigest=n.federationDigest,exports.federationKeyThumbprint=n.federationKeyThumbprint,exports.isFederationIssuerOrigin=n.isFederationIssuerOrigin,exports.signEnvelope=t.signEnvelope,exports.verifyDeviceSignature=e.verifyDeviceSignature,exports.verifyEnvelope=t.verifyEnvelope;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { verifyDeviceSignature } from "./services/deviceSignature/index.mjs";
|
|
2
|
+
import { signEnvelope, verifyEnvelope } from "./services/federationEnvelope/index.mjs";
|
|
3
|
+
import { FederationAuthority, FederationCaller, FederationConsentGrant, FederationIssuerPin, FederationJwk, FederationReplayStore, FederationRequestProof, FederationTokenClaims, FederationVerifierPorts, FederationVerifyInput } from "./services/federationVerifier/type.mjs";
|
|
4
|
+
import { createFederationVerifier, federationDigest, federationKeyThumbprint, isFederationIssuerOrigin } from "./services/federationVerifier/index.mjs";
|
|
5
|
+
import { FederationDeviceKeyProof, FederationDeviceKeyResponse, FederationFeedState, FederationIssuerHttpPorts, FederationRevocation } from "./services/federationIssuerHttp/type.mjs";
|
|
6
|
+
import { createFederationIssuerHttp } from "./services/federationIssuerHttp/index.mjs";
|
|
7
|
+
export { type FederationAuthority, type FederationCaller, type FederationConsentGrant, type FederationDeviceKeyProof, type FederationDeviceKeyResponse, type FederationFeedState, type FederationIssuerHttpPorts, type FederationIssuerPin, type FederationJwk, type FederationReplayStore, type FederationRequestProof, type FederationRevocation, type FederationTokenClaims, type FederationVerifierPorts, type FederationVerifyInput, createFederationIssuerHttp, createFederationVerifier, federationDigest, federationKeyThumbprint, isFederationIssuerOrigin, signEnvelope, verifyDeviceSignature, verifyEnvelope };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{verifyDeviceSignature as e}from"./services/deviceSignature/index.mjs";import{signEnvelope as t,verifyEnvelope as n}from"./services/federationEnvelope/index.mjs";import{createFederationVerifier as r,federationDigest as i,federationKeyThumbprint as a,isFederationIssuerOrigin as o}from"./services/federationVerifier/index.mjs";import{createFederationIssuerHttp as s}from"./services/federationIssuerHttp/index.mjs";export{s as createFederationIssuerHttp,r as createFederationVerifier,i as federationDigest,a as federationKeyThumbprint,o as isFederationIssuerOrigin,t as signEnvelope,e as verifyDeviceSignature,n as verifyEnvelope};
|
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"),r=require("./types/federation.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.FEDERATION_FRESHNESS=r.FEDERATION_FRESHNESS,exports.FEDERATION_TAGS=r.FEDERATION_TAGS,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.federationEnvelopeFields=r.federationEnvelopeFields,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,5 @@
|
|
|
1
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";
|
|
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
|
+
import { FEDERATION_FRESHNESS, FEDERATION_TAGS, FederationTag, FederationValidity, SignedFederationEnvelope, federationEnvelopeFields } from "./types/federation.mjs";
|
|
3
4
|
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 };
|
|
5
|
+
export { ATTESTATION_TAG, BUNDLE_MANIFEST_ROUTE, BUNDLE_MANIFEST_VERSION, type BundleAsset, type BundleManifest, type BundleProfile, CLIENT_TO_SERVER_INFO, FEDERATION_FRESHNESS, FEDERATION_TAGS, type FederationTag, type FederationValidity, 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, type SignedFederationEnvelope, WEB_ENTRY_PATH, assetFor, attestationBytes, canonicalManifest, createSerialQueue, describeSealedFailure, digestFor, federationEnvelopeFields, infoFor, isBundleManifest, isSealedEnvelope, isSignedBundleManifest };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ATTESTATION_TAG as e,BUNDLE_MANIFEST_ROUTE as t,BUNDLE_MANIFEST_VERSION as n,NATIVE_COMPOSITION_MAX_BYTES as r,NATIVE_ENTRY_CONTENT_TYPE as i,NATIVE_ENTRY_PATH as a,WEB_ENTRY_PATH as o,assetFor as s,attestationBytes as c,canonicalManifest as l,digestFor as u,isBundleManifest as d,isSignedBundleManifest as f}from"./types/bundleManifest.mjs";import{CLIENT_TO_SERVER_INFO as p,MAX_MESSAGES_PER_KEY as m,NONCE_BYTES as h,NONCE_COUNTER_BYTES as g,NONCE_PREFIX_BYTES as _,SEALED_BODY_HEADER as v,SEALED_CLIENT_KEY_HEADER as y,SEALED_KEY_PARAM as b,SEALED_VERSION as x,SERVER_TO_CLIENT_INFO as S,describeSealedFailure as C,infoFor as w,isSealedEnvelope as T}from"./types/sealedChannel.mjs";import{createSerialQueue as E}from"./services/serialQueue/index.mjs";export{e as ATTESTATION_TAG,t as BUNDLE_MANIFEST_ROUTE,n as BUNDLE_MANIFEST_VERSION,p as CLIENT_TO_SERVER_INFO,m as MAX_MESSAGES_PER_KEY,r as NATIVE_COMPOSITION_MAX_BYTES,i as NATIVE_ENTRY_CONTENT_TYPE,a as NATIVE_ENTRY_PATH,h as NONCE_BYTES,g as NONCE_COUNTER_BYTES,_ as NONCE_PREFIX_BYTES,v as SEALED_BODY_HEADER,y as SEALED_CLIENT_KEY_HEADER,b as SEALED_KEY_PARAM,x as SEALED_VERSION,S as SERVER_TO_CLIENT_INFO,o as WEB_ENTRY_PATH,s as assetFor,c as attestationBytes,l as canonicalManifest,E as createSerialQueue,C as describeSealedFailure,u as digestFor,w as infoFor,d as isBundleManifest,T as isSealedEnvelope,f as isSignedBundleManifest};
|
|
1
|
+
import{ATTESTATION_TAG as e,BUNDLE_MANIFEST_ROUTE as t,BUNDLE_MANIFEST_VERSION as n,NATIVE_COMPOSITION_MAX_BYTES as r,NATIVE_ENTRY_CONTENT_TYPE as i,NATIVE_ENTRY_PATH as a,WEB_ENTRY_PATH as o,assetFor as s,attestationBytes as c,canonicalManifest as l,digestFor as u,isBundleManifest as d,isSignedBundleManifest as f}from"./types/bundleManifest.mjs";import{CLIENT_TO_SERVER_INFO as p,MAX_MESSAGES_PER_KEY as m,NONCE_BYTES as h,NONCE_COUNTER_BYTES as g,NONCE_PREFIX_BYTES as _,SEALED_BODY_HEADER as v,SEALED_CLIENT_KEY_HEADER as y,SEALED_KEY_PARAM as b,SEALED_VERSION as x,SERVER_TO_CLIENT_INFO as S,describeSealedFailure as C,infoFor as w,isSealedEnvelope as T}from"./types/sealedChannel.mjs";import{createSerialQueue as E}from"./services/serialQueue/index.mjs";import{FEDERATION_FRESHNESS as D,FEDERATION_TAGS as O,federationEnvelopeFields as k}from"./types/federation.mjs";export{e as ATTESTATION_TAG,t as BUNDLE_MANIFEST_ROUTE,n as BUNDLE_MANIFEST_VERSION,p as CLIENT_TO_SERVER_INFO,D as FEDERATION_FRESHNESS,O as FEDERATION_TAGS,m as MAX_MESSAGES_PER_KEY,r as NATIVE_COMPOSITION_MAX_BYTES,i as NATIVE_ENTRY_CONTENT_TYPE,a as NATIVE_ENTRY_PATH,h as NONCE_BYTES,g as NONCE_COUNTER_BYTES,_ as NONCE_PREFIX_BYTES,v as SEALED_BODY_HEADER,y as SEALED_CLIENT_KEY_HEADER,b as SEALED_KEY_PARAM,x as SEALED_VERSION,S as SERVER_TO_CLIENT_INFO,o as WEB_ENTRY_PATH,s as assetFor,c as attestationBytes,l as canonicalManifest,E as createSerialQueue,C as describeSealedFailure,u as digestFor,k as federationEnvelopeFields,w as infoFor,d as isBundleManifest,T as isSealedEnvelope,f as isSignedBundleManifest};
|
package/dist/node.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./services/
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./services/deviceSignature/index.cjs"),t=require("./services/federationEnvelope/index.cjs"),n=require("./services/nodeSealedChannel/index.cjs"),r=require("./services/bundleSigner/index.cjs");exports.createBundleSigner=r.createBundleSigner,exports.createClientHandshake=n.createClientHandshake,exports.createHostHandshake=n.createHostHandshake,exports.publicKeyOf=r.publicKeyOf,exports.signEnvelope=t.signEnvelope,exports.verifyDeviceSignature=e.verifyDeviceSignature,exports.verifyEnvelope=t.verifyEnvelope;
|
package/dist/node.d.mts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
+
import { verifyDeviceSignature } from "./services/deviceSignature/index.mjs";
|
|
2
|
+
import { signEnvelope, verifyEnvelope } from "./services/federationEnvelope/index.mjs";
|
|
1
3
|
import { ClientHandshake, HostHandshake, OpenResult, SealResult, SealedChannel, createClientHandshake, createHostHandshake } from "./services/nodeSealedChannel/index.mjs";
|
|
2
4
|
import { BundleSigner, createBundleSigner, publicKeyOf } from "./services/bundleSigner/index.mjs";
|
|
3
|
-
|
|
4
|
-
export { type BundleSigner, type ClientHandshake, type HostHandshake, type OpenResult, type SealResult, type SealedChannel, createBundleSigner, createClientHandshake, createHostHandshake, publicKeyOf, verifyDeviceSignature };
|
|
5
|
+
export { type BundleSigner, type ClientHandshake, type HostHandshake, type OpenResult, type SealResult, type SealedChannel, createBundleSigner, createClientHandshake, createHostHandshake, publicKeyOf, signEnvelope, verifyDeviceSignature, verifyEnvelope };
|
package/dist/node.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{verifyDeviceSignature as e}from"./services/deviceSignature/index.mjs";import{signEnvelope as t,verifyEnvelope as n}from"./services/federationEnvelope/index.mjs";import{createClientHandshake as r,createHostHandshake as i}from"./services/nodeSealedChannel/index.mjs";import{createBundleSigner as a,publicKeyOf as o}from"./services/bundleSigner/index.mjs";export{a as createBundleSigner,r as createClientHandshake,i as createHostHandshake,o as publicKeyOf,t as signEnvelope,e as verifyDeviceSignature,n as verifyEnvelope};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./services/nodeSealedChannel/index.cjs");exports.createClientHandshake=e.createClientHandshake,exports.createHostHandshake=e.createHostHandshake;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { ClientHandshake, HostHandshake, OpenResult, SealResult, SealedChannel, createClientHandshake, createHostHandshake } from "./services/nodeSealedChannel/index.mjs";
|
|
2
|
+
export { type ClientHandshake, type HostHandshake, type OpenResult, type SealResult, type SealedChannel, createClientHandshake, createHostHandshake };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{createClientHandshake,createHostHandshake}from"./services/nodeSealedChannel/index.mjs";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./services/outboundHost/index.cjs");exports.OutboundRefusedError=e.OutboundRefusedError,exports.guardedFetch=e.guardedFetch,exports.outboundHostRefusal=e.outboundHostRefusal,exports.ownZone=e.ownZone;
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { GuardedFetchOptions, OutboundHostPolicy } from "./services/outboundHost/type.mjs";
|
|
2
|
+
import { OutboundRefusedError, guardedFetch, outboundHostRefusal, ownZone } from "./services/outboundHost/index.mjs";
|
|
3
|
+
export { type GuardedFetchOptions, type OutboundHostPolicy, OutboundRefusedError, guardedFetch, outboundHostRefusal, ownZone };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{OutboundRefusedError,guardedFetch,outboundHostRefusal,ownZone}from"./services/outboundHost/index.mjs";
|
|
@@ -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,K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,OAAO,OAAO,YAAY/B,EAAe,GAAO,CAAC,YAAY,CAAC,EAC3EgC,EAAU9B,EAAM+B,CAAa,EACnC,GAAID,IAAY,IAAA,GAAW,OAC3B,IAAME,EAAO,MAAM,OAAO,OAAO,UAAU,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, noncePr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,CAAa,EAEtB,MADH1B,EAAOE,EAAQwB,IAAkB,MAAQ,MAAQ,KAAK,EAC1Cf,CAAW,CAC/C"}
|
|
@@ -1 +1 @@
|
|
|
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;;;;;;;;;
|
|
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,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,EAC0E,CAC1E,GAAI,WAAW,QAAQ,SAAW,IAAA,GAClC,GAAI,CACF,IAAMC,EAAO,MAAM,OAAO,OAAO,YAAYlC,EAAe,GAAO,CAAC,YAAY,CAAC,EAC3EmC,EAAUjC,EAAMkC,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, sendD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ACA,EACA,EACwB,CAGxB,OAAOnB,EAAY,MAFAT,EAAOE,EAAQ2B,CAAa,EAEtB,MADH7B,EAAOE,EAAQ2B,IAAkB,MAAQ,MAAQ,KAAK,EAC1ChB,CAAW,CAC/C"}
|
|
@@ -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,GAAI,CACF,EAAa3B,EAAAA,QAAG,SAASyB,EAAU,KAAM,GAAS,EAClD,KACF,OAASG,EAAO,CACd,GAAKA,EAAgC,OAAS,SAAU,MAAMA,EAC9D,QAAQ,KAAK,IAAI,WAAW,IAAI,kBAAkB,CAAC,CAAC,EAAG,EAAG,EAAG,EAAE,CACjE,CAEF,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M,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';\n// sync: Public createBundleSigner and BundleSigner.sign/refresh contracts must remain synchronous until phase 2.\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":"mNAuBA,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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