@ggui-ai/gadget-signing 0.1.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Support. While redistributing the Work or
166
+ Derivative Works thereof, You may choose to offer, and charge a
167
+ fee for, acceptance of support, warranty, indemnity, or other
168
+ liability obligations and/or rights consistent with this License.
169
+ However, in accepting such obligations, You may act only on Your
170
+ own behalf and on Your sole responsibility, not on behalf of any
171
+ other Contributor, and only if You agree to indemnify, defend,
172
+ and hold each Contributor harmless for any liability incurred by,
173
+ or claims asserted against, such Contributor by reason of your
174
+ accepting any such warranty or support.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Loqu, Inc. (Guuey)
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
200
+ implied. See the License for the specific language governing
201
+ permissions and limitations under the License.
package/README.md ADDED
@@ -0,0 +1,86 @@
1
+ # @ggui-ai/gadget-signing
2
+
3
+ > Gadget bundle signing + verification for the ggui gadget marketplace.
4
+
5
+ Signs and verifies the `bundle.js` files that authors publish to a ggui
6
+ gadget registry. The Ed25519 path is pure-TS via `@noble/ed25519` +
7
+ `@noble/hashes` — no `node:crypto` dependency, so that path is safe to
8
+ import from browser contexts (e.g. client-side signature verification in
9
+ the iframe runtime).
10
+
11
+ ## Two signing paths
12
+
13
+ | Path | Audience | Trust root |
14
+ | ----------------------------- | --------------- | --------------------------------------------------------- |
15
+ | **Ed25519 author key** | private gadgets | Author's local private key; public key stored by registry |
16
+ | **sigstore (cosign + Rekor)** | public gadgets | Keyless Fulcio cert via OIDC + Rekor transparency log |
17
+
18
+ The sigstore path is a full implementation built on the upstream
19
+ `sigstore` package. The publisher acquires an OIDC token out-of-band and
20
+ passes it in; signing walks the keyless Fulcio + Rekor flow, and
21
+ verification resolves trust material via TUF and enforces an optional
22
+ caller-supplied identity policy.
23
+
24
+ ## Wire format
25
+
26
+ ```ts
27
+ type GadgetSignature = Ed25519Signature | SigstoreSignature;
28
+
29
+ interface Ed25519Signature {
30
+ readonly algorithm: "ed25519";
31
+ readonly bundleSha384: string; // base64(sha384(bundleBytes))
32
+ readonly signature: string; // base64(ed25519.sign(digest, privateKey))
33
+ readonly publicKeyId: string; // stable id derived from the public key
34
+ readonly signedAt: string; // ISO 8601
35
+ }
36
+ ```
37
+
38
+ SHA-384 (not 512) matches the SRI hash the iframe runtime enforces on
39
+ `<script>` tags, so the signature attests to the exact digest the browser
40
+ recomputes at load time.
41
+
42
+ ## Usage
43
+
44
+ ### Ed25519 author-key path
45
+
46
+ ```ts
47
+ import {
48
+ generateEd25519Keypair,
49
+ signBundleEd25519,
50
+ verifyBundleEd25519,
51
+ } from "@ggui-ai/gadget-signing";
52
+
53
+ // Author (keygen)
54
+ const { publicKey, privateKey, publicKeyId } = await generateEd25519Keypair();
55
+ // publicKey + publicKeyId go to the registry; privateKey stays local.
56
+
57
+ // Publisher
58
+ const signature = await signBundleEd25519({
59
+ bundleBytes,
60
+ privateKey,
61
+ publicKeyId,
62
+ });
63
+
64
+ // Install / runtime
65
+ const result = await verifyBundleEd25519({ bundleBytes, signature, publicKey });
66
+ if (!result.valid) throw new Error(`signature invalid: ${result.reason}`);
67
+ ```
68
+
69
+ ### Sigstore keyless path
70
+
71
+ ```ts
72
+ import { signBundleSigstore, verifyBundleSigstore } from "@ggui-ai/gadget-signing";
73
+
74
+ // Publisher — identityToken is a pre-acquired OIDC JWT.
75
+ const signature = await signBundleSigstore({ bundleBytes, identityToken });
76
+
77
+ // Install — optionally pin the expected signer identity.
78
+ const result = await verifyBundleSigstore({
79
+ bundleBytes,
80
+ signature,
81
+ expectedIdentity: { subject: /^https:\/\/github\.com\/my-org\// },
82
+ });
83
+ ```
84
+
85
+ The sigstore code path uses `node:crypto` transitively and is therefore
86
+ Node-only. The Ed25519 path stays browser-safe.
@@ -0,0 +1,283 @@
1
+ /**
2
+ * `@ggui-ai/gadget-signing` — gadget bundle signing + verification for the
3
+ * ggui gadget marketplace.
4
+ *
5
+ * Two signing schemes:
6
+ * 1. **Ed25519 author keys** (private gadgets) — full implementation. The
7
+ * author manages a 32-byte Ed25519 private key locally; the registry
8
+ * stores the public key per author identity. The publisher hashes the
9
+ * bundle with SHA-384, signs the hash with their private key, and
10
+ * uploads `bundle.js` + `bundle.js.sig`. The install CLI downloads
11
+ * both, looks up the author's public key, and verifies. The SRI hash
12
+ * on the `<script>` tag closes the loop end-to-end.
13
+ *
14
+ * 2. **sigstore (cosign + Rekor)** (public gadgets) — full implementation
15
+ * via the upstream `sigstore` package (which composes
16
+ * `@sigstore/sign` + `@sigstore/verify` + `@sigstore/tuf`). The
17
+ * publisher acquires an OIDC token out-of-band (env var or browser
18
+ * flow at the CLI seam), passes it in, and the `sign` call walks the
19
+ * keyless Fulcio + Rekor flow. The serialized cosign Bundle (per
20
+ * `@sigstore/bundle` v0.3 spec) becomes `SigstoreSignature.bundle`.
21
+ * Verification calls `sigstore.verify` which uses TUF to resolve the
22
+ * trust material at runtime, then enforces an optional caller-supplied
23
+ * identity policy.
24
+ *
25
+ * Cryptography for the Ed25519 path uses `@noble/ed25519` +
26
+ * `@noble/hashes` — pure-TS, audited, browser-safe; no `node:crypto`.
27
+ * The sigstore path uses `node:crypto` transitively through the
28
+ * `sigstore` package, so the sigstore code path is Node-only. Ed25519
29
+ * remains browser-safe.
30
+ */
31
+ /** Ed25519 signature over the SHA-384 hash of a gadget bundle. */
32
+ export interface Ed25519Signature {
33
+ readonly algorithm: "ed25519";
34
+ /** Base64 SHA-384 digest of the bundle bytes. */
35
+ readonly bundleSha384: string;
36
+ /** Base64 Ed25519 signature over `bundleSha384` decoded bytes. */
37
+ readonly signature: string;
38
+ /** Public-key identifier — the registry's stable handle for the key. */
39
+ readonly publicKeyId: string;
40
+ /** ISO 8601 timestamp at signing time. */
41
+ readonly signedAt: string;
42
+ }
43
+ /**
44
+ * Sigstore/cosign signature.
45
+ *
46
+ * Carries a full serialized Sigstore bundle (per
47
+ * `@sigstore/bundle` v0.3 spec) — including the cert chain, the
48
+ * Rekor inclusion proof, and the messageSignature payload. Verify
49
+ * reconstitutes via `@sigstore/verify` and runs the canonical
50
+ * Sigstore verification flow (Fulcio cert chain + Rekor inclusion +
51
+ * signature over the digest).
52
+ *
53
+ * `bundleSha384` is intentionally retained alongside the cosign
54
+ * bundle (redundant with `messageSignature.messageDigest` inside the
55
+ * bundle) so the server can run a fast tamper-detection pass before
56
+ * paying for the full Sigstore-verify path.
57
+ */
58
+ export interface SigstoreSignature {
59
+ readonly algorithm: "sigstore-cosign";
60
+ /** Base64 SHA-384 digest of the bundle bytes — fast tamper check. */
61
+ readonly bundleSha384: string;
62
+ /**
63
+ * Serialized cosign bundle (JSON-encoded per `@sigstore/bundle`'s
64
+ * `Bundle` schema, v0.3 mediaType
65
+ * `application/vnd.dev.sigstore.bundle+json;version=0.3`). Opaque
66
+ * at the wire layer; deserialized by `verifyBundleSigstore` via
67
+ * `@sigstore/bundle`'s parser.
68
+ */
69
+ readonly bundle: string;
70
+ /** ISO 8601 timestamp at signing time. */
71
+ readonly signedAt: string;
72
+ }
73
+ /** Discriminated union of all signature shapes. */
74
+ export type GadgetSignature = Ed25519Signature | SigstoreSignature;
75
+ /**
76
+ * Runtime check that `value` is a well-formed {@link Ed25519Signature}.
77
+ * Structural shape only — does NOT cryptographically verify.
78
+ */
79
+ export declare function isEd25519Signature(value: unknown): value is Ed25519Signature;
80
+ /**
81
+ * Runtime check that `value` is a well-formed {@link SigstoreSignature}.
82
+ * Structural shape only — does NOT cryptographically verify the embedded
83
+ * bundle. Use {@link verifyBundleSigstore} for the full trust-chain check.
84
+ */
85
+ export declare function isSigstoreSignature(value: unknown): value is SigstoreSignature;
86
+ /**
87
+ * Discriminated guard over the {@link GadgetSignature} union. Use this
88
+ * at request boundaries — switching on `value.algorithm` after the
89
+ * guard passes narrows to the correct variant for downstream dispatch.
90
+ */
91
+ export declare function isGadgetSignature(value: unknown): value is GadgetSignature;
92
+ /**
93
+ * Canonical-JSON serialization for blueprint signatures. Recursive
94
+ * lexicographic key-sort at every nesting depth, then `JSON.stringify`.
95
+ *
96
+ * Lives here (not in publish/install/server) because all three sites
97
+ * sign or verify against the same byte sequence. Any drift between
98
+ * server-side canonicalization and CLI-side canonicalization breaks
99
+ * blueprint signatures silently — pulling the impl into one place
100
+ * eliminates that drift class.
101
+ *
102
+ * NOT RFC-8785 compliant: the v1 manifest schema doesn't carry
103
+ * non-ASCII strings, exotic numbers, or unicode normalization
104
+ * surfaces, so the simpler shape suffices. If a future blueprint
105
+ * manifest grows nested objects with order-sensitive content that
106
+ * RFC-8785 would canonicalize differently, both this function and
107
+ * the publish + install sites need to swap to a real RFC-8785 impl
108
+ * in lock-step.
109
+ */
110
+ export declare function canonicalJson(value: unknown): string;
111
+ /**
112
+ * Derive a stable public-key identifier from a 32-byte Ed25519 public key.
113
+ * `base64(sha256(publicKey))[:16]`. Used as the registry's stable handle
114
+ * for a stored author public key.
115
+ */
116
+ export declare function derivePublicKeyId(publicKey: Uint8Array): string;
117
+ /**
118
+ * Derive the Ed25519 public key from a 32-byte private key. Deterministic
119
+ * (Ed25519 public keys are functions of the private key). Used by the
120
+ * publish CLI when re-reading a stored private key from disk between
121
+ * sessions — recompute the public half rather than store both halves.
122
+ */
123
+ export declare function publicKeyFromPrivate(privateKey: Uint8Array): Promise<Uint8Array>;
124
+ /**
125
+ * Generate a fresh 32-byte Ed25519 keypair plus its derived `publicKeyId`.
126
+ *
127
+ * Use only in CLI flows (`ggui gadget keygen`) — the private key MUST be
128
+ * stored by the author locally and NEVER uploaded to the registry.
129
+ */
130
+ export declare function generateEd25519Keypair(): Promise<{
131
+ publicKey: Uint8Array;
132
+ privateKey: Uint8Array;
133
+ publicKeyId: string;
134
+ }>;
135
+ /**
136
+ * Sign a gadget bundle with an Ed25519 author key.
137
+ *
138
+ * Hashes the bundle with SHA-384 and signs the digest. SHA-384 (not 512)
139
+ * matches the SRI hash that the iframe-runtime enforces on `<script>` tags,
140
+ * so the signature attests to the exact same digest the browser will
141
+ * recompute at install/load time.
142
+ */
143
+ export declare function signBundleEd25519(input: {
144
+ bundleBytes: Uint8Array;
145
+ privateKey: Uint8Array;
146
+ publicKeyId: string;
147
+ }): Promise<Ed25519Signature>;
148
+ /** Result of a verification call. Discriminated by `valid`. */
149
+ export type VerifyResult = {
150
+ valid: true;
151
+ } | {
152
+ valid: false;
153
+ reason: string;
154
+ };
155
+ /**
156
+ * Verify a gadget bundle against an Ed25519 author key.
157
+ *
158
+ * Checks (in order):
159
+ * 1. Recompute SHA-384 of `bundleBytes` and confirm it matches
160
+ * `signature.bundleSha384`. Catches bundle tampering.
161
+ * 2. Confirm `signature.publicKeyId === derivePublicKeyId(publicKey)`.
162
+ * Catches `publicKeyId` substitution (e.g., the registry returning a
163
+ * different author's public key alongside the original sig).
164
+ * 3. Run the Ed25519 verify over the digest. Catches signature tampering
165
+ * and wrong-key cases.
166
+ */
167
+ export declare function verifyBundleEd25519(input: {
168
+ bundleBytes: Uint8Array;
169
+ signature: Ed25519Signature;
170
+ publicKey: Uint8Array;
171
+ }): Promise<VerifyResult>;
172
+ /** Discriminated error codes thrown by {@link signBundleSigstore}. */
173
+ export type SigstoreSigningErrorCode = "oidc_invalid" | "fulcio_error" | "rekor_error" | "unknown";
174
+ /**
175
+ * Error class thrown by {@link signBundleSigstore} on signing failure.
176
+ * The `code` field is enumerated so callers can route to recovery paths
177
+ * (re-acquire OIDC token, retry against a different Rekor instance, …).
178
+ *
179
+ * Verification failures DO NOT throw — they project to
180
+ * `{ valid: false, reason }` instead. Only the signing seam exposes
181
+ * structured errors, since signing failure modes (network down, OIDC
182
+ * expired, Rekor 5xx) drive caller retry behavior and the verification
183
+ * seam wants the `VerifyResult` discriminator at every callsite.
184
+ */
185
+ export declare class SigstoreSigningError extends Error {
186
+ readonly code: SigstoreSigningErrorCode;
187
+ readonly cause?: unknown;
188
+ constructor(code: SigstoreSigningErrorCode, message: string, cause?: unknown);
189
+ }
190
+ /** Input to {@link signBundleSigstore}. */
191
+ export interface SignBundleSigstoreInput {
192
+ /** Raw gadget bundle bytes — the signature attests to these bytes. */
193
+ readonly bundleBytes: Uint8Array;
194
+ /**
195
+ * Pre-acquired OIDC JWT. Caller is responsible for obtaining it
196
+ * (env var, `--identity-token` flag, interactive browser flow) — all
197
+ * resolved at the CLI seam, not here. Keeping the token at the call
198
+ * site (rather than reading env in this package) keeps the signing
199
+ * function pure + testable.
200
+ */
201
+ readonly identityToken: string;
202
+ /**
203
+ * Optional override of the Sigstore endpoint set. Defaults to the
204
+ * production Fulcio + Rekor URLs (`sigstore.dev`). Tests pass mock
205
+ * URLs via `@sigstore/mock`; staging traffic points at the
206
+ * sigstaging.dev instances.
207
+ */
208
+ readonly endpoints?: {
209
+ readonly fulcioURL?: string;
210
+ readonly rekorURL?: string;
211
+ };
212
+ }
213
+ /**
214
+ * Sign a gadget bundle via the Sigstore keyless flow.
215
+ *
216
+ * 1. SHA-384 the bundle bytes (matches the Ed25519 path and the SRI hash
217
+ * the iframe-runtime enforces). The digest becomes the fast
218
+ * tamper-check payload stored in `bundleSha384`.
219
+ * 2. Hand the bundle bytes + OIDC token to `sigstore.sign()`. Under the
220
+ * hood: ephemeral keypair → Fulcio short-lived signing cert tied to
221
+ * the OIDC identity → Rekor inclusion entry → bundle assembled.
222
+ * 3. Serialize the bundle to JSON (per `@sigstore/bundle` v0.3 schema)
223
+ * and pack into `SigstoreSignature`.
224
+ */
225
+ export declare function signBundleSigstore(input: SignBundleSigstoreInput): Promise<SigstoreSignature>;
226
+ /** Input to {@link verifyBundleSigstore}. */
227
+ export interface VerifyBundleSigstoreInput {
228
+ /** Raw bundle bytes — must match the bytes that were signed. */
229
+ readonly bundleBytes: Uint8Array;
230
+ /** The signature returned by {@link signBundleSigstore}. */
231
+ readonly signature: SigstoreSignature;
232
+ /**
233
+ * Optional identity-claim assertion. When present, the verifier rejects
234
+ * bundles whose embedded Fulcio cert doesn't claim the expected OIDC
235
+ * identity — `subject` is matched against the cert's
236
+ * `subjectAlternativeName`. Use this to encode "publisher X is the
237
+ * only legitimate signer" trust models at install time.
238
+ *
239
+ * The `subject` may be a string (literal equality, per Sigstore's
240
+ * `certificateIdentityURI` / `certificateIdentityEmail` semantics) or
241
+ * a RegExp (the verifier pre-validates against the deserialized
242
+ * bundle SAN before delegating to upstream, since the upstream API
243
+ * supports only string equality).
244
+ */
245
+ readonly expectedIdentity?: {
246
+ readonly subject: string | RegExp;
247
+ /** OIDC issuer URL (e.g. `https://token.actions.githubusercontent.com`). */
248
+ readonly issuer?: string;
249
+ };
250
+ /**
251
+ * Optional endpoint overrides — only meaningful when paired with a
252
+ * non-prod TUF mirror. Production gadgets verify against the prod
253
+ * Sigstore TUF root.
254
+ */
255
+ readonly endpoints?: {
256
+ readonly fulcioURL?: string;
257
+ readonly rekorURL?: string;
258
+ };
259
+ }
260
+ /**
261
+ * Verify a sigstore-signed gadget bundle.
262
+ *
263
+ * 1. **Fast tamper check** — recompute SHA-384 of `bundleBytes` and
264
+ * compare to `signature.bundleSha384`. Mismatch short-circuits the
265
+ * full Sigstore-verify path. (Redundant with `messageDigest` inside
266
+ * the bundle, but cheap.)
267
+ * 2. **Deserialize** the embedded bundle via `bundleFromJSON`.
268
+ * 3. **RegExp identity pre-check** — when `expectedIdentity.subject` is
269
+ * a RegExp, walk the bundle's verification material to extract the
270
+ * SAN URI and assert the match here (upstream `sigstore.verify` only
271
+ * accepts literal strings).
272
+ * 4. **Upstream verify** — `sigstore.verify(bundle, data, opts)` runs
273
+ * the full Sigstore flow: TUF trust material, Fulcio cert-chain
274
+ * validation, Rekor inclusion proof, signature over the digest, and
275
+ * (if `expectedIdentity` was provided as a string) the identity
276
+ * policy. Throws on any failure.
277
+ *
278
+ * Returns a {@link VerifyResult} discriminated by `valid` — never
279
+ * throws on policy failure (only on programmer error like a malformed
280
+ * `signature.bundle` JSON).
281
+ */
282
+ export declare function verifyBundleSigstore(input: VerifyBundleSigstoreInput): Promise<VerifyResult>;
283
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"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"}
package/dist/index.js ADDED
@@ -0,0 +1,536 @@
1
+ /**
2
+ * `@ggui-ai/gadget-signing` — gadget bundle signing + verification for the
3
+ * ggui gadget marketplace.
4
+ *
5
+ * Two signing schemes:
6
+ * 1. **Ed25519 author keys** (private gadgets) — full implementation. The
7
+ * author manages a 32-byte Ed25519 private key locally; the registry
8
+ * stores the public key per author identity. The publisher hashes the
9
+ * bundle with SHA-384, signs the hash with their private key, and
10
+ * uploads `bundle.js` + `bundle.js.sig`. The install CLI downloads
11
+ * both, looks up the author's public key, and verifies. The SRI hash
12
+ * on the `<script>` tag closes the loop end-to-end.
13
+ *
14
+ * 2. **sigstore (cosign + Rekor)** (public gadgets) — full implementation
15
+ * via the upstream `sigstore` package (which composes
16
+ * `@sigstore/sign` + `@sigstore/verify` + `@sigstore/tuf`). The
17
+ * publisher acquires an OIDC token out-of-band (env var or browser
18
+ * flow at the CLI seam), passes it in, and the `sign` call walks the
19
+ * keyless Fulcio + Rekor flow. The serialized cosign Bundle (per
20
+ * `@sigstore/bundle` v0.3 spec) becomes `SigstoreSignature.bundle`.
21
+ * Verification calls `sigstore.verify` which uses TUF to resolve the
22
+ * trust material at runtime, then enforces an optional caller-supplied
23
+ * identity policy.
24
+ *
25
+ * Cryptography for the Ed25519 path uses `@noble/ed25519` +
26
+ * `@noble/hashes` — pure-TS, audited, browser-safe; no `node:crypto`.
27
+ * The sigstore path uses `node:crypto` transitively through the
28
+ * `sigstore` package, so the sigstore code path is Node-only. Ed25519
29
+ * remains browser-safe.
30
+ */
31
+ import { signAsync, verifyAsync, getPublicKeyAsync, utils } from "@noble/ed25519";
32
+ import { sha384, sha256 } from "@noble/hashes/sha2";
33
+ import { bundleFromJSON, bundleToJSON, } from "@sigstore/bundle";
34
+ import * as sigstoreClient from "sigstore";
35
+ // ---------------------------------------------------------------------------
36
+ // Canonical type guards.
37
+ //
38
+ // The signature guards live in one canonical home so wire-shape
39
+ // changes flow uniformly to every consumer (registry publish op,
40
+ // install path). `isGadgetSignature` is the discriminated guard
41
+ // callers use at the request boundary.
42
+ // ---------------------------------------------------------------------------
43
+ /**
44
+ * Runtime check that `value` is a well-formed {@link Ed25519Signature}.
45
+ * Structural shape only — does NOT cryptographically verify.
46
+ */
47
+ export function isEd25519Signature(value) {
48
+ if (value === null || typeof value !== "object")
49
+ return false;
50
+ // `as Partial<Ed25519Signature>` (not `Record<string, unknown>`) is
51
+ // the honest narrow: it makes each field optional with the correct
52
+ // declared type, so the typeof checks below catch shape mismatches
53
+ // without lying about what the input MAY be.
54
+ const v = value;
55
+ return (v.algorithm === "ed25519" &&
56
+ typeof v.bundleSha384 === "string" &&
57
+ typeof v.signature === "string" &&
58
+ typeof v.publicKeyId === "string" &&
59
+ typeof v.signedAt === "string");
60
+ }
61
+ /**
62
+ * Runtime check that `value` is a well-formed {@link SigstoreSignature}.
63
+ * Structural shape only — does NOT cryptographically verify the embedded
64
+ * bundle. Use {@link verifyBundleSigstore} for the full trust-chain check.
65
+ */
66
+ export function isSigstoreSignature(value) {
67
+ if (value === null || typeof value !== "object")
68
+ return false;
69
+ const v = value;
70
+ return (v.algorithm === "sigstore-cosign" &&
71
+ typeof v.bundleSha384 === "string" &&
72
+ typeof v.bundle === "string" &&
73
+ typeof v.signedAt === "string");
74
+ }
75
+ /**
76
+ * Discriminated guard over the {@link GadgetSignature} union. Use this
77
+ * at request boundaries — switching on `value.algorithm` after the
78
+ * guard passes narrows to the correct variant for downstream dispatch.
79
+ */
80
+ export function isGadgetSignature(value) {
81
+ return isEd25519Signature(value) || isSigstoreSignature(value);
82
+ }
83
+ // ---------------------------------------------------------------------------
84
+ // Base64 helpers — browser-safe, no `node:buffer` dependency.
85
+ // ---------------------------------------------------------------------------
86
+ function bytesToBase64(bytes) {
87
+ let binary = "";
88
+ for (let i = 0; i < bytes.length; i++) {
89
+ binary += String.fromCharCode(bytes[i]);
90
+ }
91
+ // `btoa` exists in browsers and modern Node (>=16) globals.
92
+ return btoa(binary);
93
+ }
94
+ function base64ToBytes(b64) {
95
+ const binary = atob(b64);
96
+ const out = new Uint8Array(binary.length);
97
+ for (let i = 0; i < binary.length; i++) {
98
+ out[i] = binary.charCodeAt(i);
99
+ }
100
+ return out;
101
+ }
102
+ // ---------------------------------------------------------------------------
103
+ // Canonical JSON — the bit-stable form blueprint signatures cover.
104
+ // ---------------------------------------------------------------------------
105
+ /**
106
+ * Canonical-JSON serialization for blueprint signatures. Recursive
107
+ * lexicographic key-sort at every nesting depth, then `JSON.stringify`.
108
+ *
109
+ * Lives here (not in publish/install/server) because all three sites
110
+ * sign or verify against the same byte sequence. Any drift between
111
+ * server-side canonicalization and CLI-side canonicalization breaks
112
+ * blueprint signatures silently — pulling the impl into one place
113
+ * eliminates that drift class.
114
+ *
115
+ * NOT RFC-8785 compliant: the v1 manifest schema doesn't carry
116
+ * non-ASCII strings, exotic numbers, or unicode normalization
117
+ * surfaces, so the simpler shape suffices. If a future blueprint
118
+ * manifest grows nested objects with order-sensitive content that
119
+ * RFC-8785 would canonicalize differently, both this function and
120
+ * the publish + install sites need to swap to a real RFC-8785 impl
121
+ * in lock-step.
122
+ */
123
+ export function canonicalJson(value) {
124
+ return JSON.stringify(canonicalSort(value));
125
+ }
126
+ function canonicalSort(value) {
127
+ if (Array.isArray(value)) {
128
+ return value.map(canonicalSort);
129
+ }
130
+ if (value !== null && typeof value === "object") {
131
+ const entries = Object.entries(value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
132
+ const out = {};
133
+ for (const [k, v] of entries)
134
+ out[k] = canonicalSort(v);
135
+ return out;
136
+ }
137
+ return value;
138
+ }
139
+ // ---------------------------------------------------------------------------
140
+ // Public-key ID derivation — stable, deterministic.
141
+ // ---------------------------------------------------------------------------
142
+ /**
143
+ * Derive a stable public-key identifier from a 32-byte Ed25519 public key.
144
+ * `base64(sha256(publicKey))[:16]`. Used as the registry's stable handle
145
+ * for a stored author public key.
146
+ */
147
+ export function derivePublicKeyId(publicKey) {
148
+ if (publicKey.length !== 32) {
149
+ throw new Error(`derivePublicKeyId: expected 32-byte Ed25519 public key, got ${publicKey.length}`);
150
+ }
151
+ const digest = sha256(publicKey);
152
+ return bytesToBase64(digest).slice(0, 16);
153
+ }
154
+ /**
155
+ * Derive the Ed25519 public key from a 32-byte private key. Deterministic
156
+ * (Ed25519 public keys are functions of the private key). Used by the
157
+ * publish CLI when re-reading a stored private key from disk between
158
+ * sessions — recompute the public half rather than store both halves.
159
+ */
160
+ export async function publicKeyFromPrivate(privateKey) {
161
+ if (privateKey.length !== 32) {
162
+ throw new Error(`publicKeyFromPrivate: expected 32-byte Ed25519 private key, got ${privateKey.length}`);
163
+ }
164
+ return getPublicKeyAsync(privateKey);
165
+ }
166
+ // ---------------------------------------------------------------------------
167
+ // Ed25519 path — full implementation.
168
+ // ---------------------------------------------------------------------------
169
+ /**
170
+ * Generate a fresh 32-byte Ed25519 keypair plus its derived `publicKeyId`.
171
+ *
172
+ * Use only in CLI flows (`ggui gadget keygen`) — the private key MUST be
173
+ * stored by the author locally and NEVER uploaded to the registry.
174
+ */
175
+ export async function generateEd25519Keypair() {
176
+ const privateKey = utils.randomPrivateKey();
177
+ const publicKey = await getPublicKeyAsync(privateKey);
178
+ return {
179
+ publicKey,
180
+ privateKey,
181
+ publicKeyId: derivePublicKeyId(publicKey),
182
+ };
183
+ }
184
+ /**
185
+ * Sign a gadget bundle with an Ed25519 author key.
186
+ *
187
+ * Hashes the bundle with SHA-384 and signs the digest. SHA-384 (not 512)
188
+ * matches the SRI hash that the iframe-runtime enforces on `<script>` tags,
189
+ * so the signature attests to the exact same digest the browser will
190
+ * recompute at install/load time.
191
+ */
192
+ export async function signBundleEd25519(input) {
193
+ const { bundleBytes, privateKey, publicKeyId } = input;
194
+ if (privateKey.length !== 32) {
195
+ throw new Error(`signBundleEd25519: expected 32-byte Ed25519 private key, got ${privateKey.length}`);
196
+ }
197
+ const digest = sha384(bundleBytes);
198
+ const sigBytes = await signAsync(digest, privateKey);
199
+ return {
200
+ algorithm: "ed25519",
201
+ bundleSha384: bytesToBase64(digest),
202
+ signature: bytesToBase64(sigBytes),
203
+ publicKeyId,
204
+ signedAt: new Date().toISOString(),
205
+ };
206
+ }
207
+ /**
208
+ * Verify a gadget bundle against an Ed25519 author key.
209
+ *
210
+ * Checks (in order):
211
+ * 1. Recompute SHA-384 of `bundleBytes` and confirm it matches
212
+ * `signature.bundleSha384`. Catches bundle tampering.
213
+ * 2. Confirm `signature.publicKeyId === derivePublicKeyId(publicKey)`.
214
+ * Catches `publicKeyId` substitution (e.g., the registry returning a
215
+ * different author's public key alongside the original sig).
216
+ * 3. Run the Ed25519 verify over the digest. Catches signature tampering
217
+ * and wrong-key cases.
218
+ */
219
+ export async function verifyBundleEd25519(input) {
220
+ const { bundleBytes, signature, publicKey } = input;
221
+ if (publicKey.length !== 32) {
222
+ return {
223
+ valid: false,
224
+ reason: `expected 32-byte Ed25519 public key, got ${publicKey.length}`,
225
+ };
226
+ }
227
+ const recomputed = sha384(bundleBytes);
228
+ const recomputedB64 = bytesToBase64(recomputed);
229
+ if (recomputedB64 !== signature.bundleSha384) {
230
+ return {
231
+ valid: false,
232
+ reason: "bundle hash mismatch (bundleBytes tampered or wrong bundle)",
233
+ };
234
+ }
235
+ const expectedKeyId = derivePublicKeyId(publicKey);
236
+ if (expectedKeyId !== signature.publicKeyId) {
237
+ return {
238
+ valid: false,
239
+ reason: `publicKeyId mismatch: signature claims '${signature.publicKeyId}', provided key derives '${expectedKeyId}'`,
240
+ };
241
+ }
242
+ let sigBytes;
243
+ try {
244
+ sigBytes = base64ToBytes(signature.signature);
245
+ }
246
+ catch (err) {
247
+ return {
248
+ valid: false,
249
+ reason: `malformed signature base64: ${err.message}`,
250
+ };
251
+ }
252
+ let ok;
253
+ try {
254
+ ok = await verifyAsync(sigBytes, recomputed, publicKey);
255
+ }
256
+ catch (err) {
257
+ return {
258
+ valid: false,
259
+ reason: `signature verification threw: ${err.message}`,
260
+ };
261
+ }
262
+ if (!ok) {
263
+ return { valid: false, reason: "Ed25519 signature does not verify" };
264
+ }
265
+ return { valid: true };
266
+ }
267
+ /**
268
+ * Error class thrown by {@link signBundleSigstore} on signing failure.
269
+ * The `code` field is enumerated so callers can route to recovery paths
270
+ * (re-acquire OIDC token, retry against a different Rekor instance, …).
271
+ *
272
+ * Verification failures DO NOT throw — they project to
273
+ * `{ valid: false, reason }` instead. Only the signing seam exposes
274
+ * structured errors, since signing failure modes (network down, OIDC
275
+ * expired, Rekor 5xx) drive caller retry behavior and the verification
276
+ * seam wants the `VerifyResult` discriminator at every callsite.
277
+ */
278
+ export class SigstoreSigningError extends Error {
279
+ code;
280
+ cause;
281
+ constructor(code, message, cause) {
282
+ super(message);
283
+ this.name = "SigstoreSigningError";
284
+ this.code = code;
285
+ if (cause !== undefined)
286
+ this.cause = cause;
287
+ }
288
+ }
289
+ /**
290
+ * Sign a gadget bundle via the Sigstore keyless flow.
291
+ *
292
+ * 1. SHA-384 the bundle bytes (matches the Ed25519 path and the SRI hash
293
+ * the iframe-runtime enforces). The digest becomes the fast
294
+ * tamper-check payload stored in `bundleSha384`.
295
+ * 2. Hand the bundle bytes + OIDC token to `sigstore.sign()`. Under the
296
+ * hood: ephemeral keypair → Fulcio short-lived signing cert tied to
297
+ * the OIDC identity → Rekor inclusion entry → bundle assembled.
298
+ * 3. Serialize the bundle to JSON (per `@sigstore/bundle` v0.3 schema)
299
+ * and pack into `SigstoreSignature`.
300
+ */
301
+ export async function signBundleSigstore(input) {
302
+ const { bundleBytes, identityToken, endpoints } = input;
303
+ const digest = sha384(bundleBytes);
304
+ const bundleSha384 = bytesToBase64(digest);
305
+ let serialized;
306
+ try {
307
+ serialized = await sigstoreClient.sign(Buffer.from(bundleBytes), {
308
+ identityToken,
309
+ ...(endpoints?.fulcioURL ? { fulcioURL: endpoints.fulcioURL } : {}),
310
+ ...(endpoints?.rekorURL ? { rekorURL: endpoints.rekorURL } : {}),
311
+ tlogUpload: true,
312
+ });
313
+ }
314
+ catch (err) {
315
+ throw classifySigstoreSigningError(err);
316
+ }
317
+ return {
318
+ algorithm: "sigstore-cosign",
319
+ bundleSha384,
320
+ bundle: JSON.stringify(serialized),
321
+ signedAt: new Date().toISOString(),
322
+ };
323
+ }
324
+ /**
325
+ * Heuristic classifier mapping upstream sigstore errors onto our
326
+ * enumerated `SigstoreSigningErrorCode`. The upstream library throws a
327
+ * mix of `InternalError` (network-level) and `Error` subclasses; the
328
+ * codes attached to `InternalError` (`CA_*`, `TLOG_*`, …) are stable
329
+ * enough to map onto our coarser categories.
330
+ */
331
+ function classifySigstoreSigningError(err) {
332
+ const message = err instanceof Error ? err.message : String(err);
333
+ // `InternalError` from `@sigstore/sign` carries a string `code` field
334
+ // like `'CA_CREATE_SIGNING_CERTIFICATE_ERROR'` or `'TLOG_CREATE_ENTRY_ERROR'`.
335
+ const upstreamCode = err !== null &&
336
+ typeof err === "object" &&
337
+ "code" in err &&
338
+ typeof err.code === "string"
339
+ ? err.code
340
+ : undefined;
341
+ if (upstreamCode?.includes("IDENTITY") || /identity|oidc|jwt/i.test(message)) {
342
+ return new SigstoreSigningError("oidc_invalid", `OIDC identity token rejected: ${message}`, err);
343
+ }
344
+ if (upstreamCode?.includes("CA_") || /fulcio/i.test(message)) {
345
+ return new SigstoreSigningError("fulcio_error", `Fulcio signing-cert issuance failed: ${message}`, err);
346
+ }
347
+ if (upstreamCode?.includes("TLOG") || /rekor|tlog/i.test(message)) {
348
+ return new SigstoreSigningError("rekor_error", `Rekor transparency-log write failed: ${message}`, err);
349
+ }
350
+ return new SigstoreSigningError("unknown", `sigstore signing failed: ${message}`, err);
351
+ }
352
+ /**
353
+ * Verify a sigstore-signed gadget bundle.
354
+ *
355
+ * 1. **Fast tamper check** — recompute SHA-384 of `bundleBytes` and
356
+ * compare to `signature.bundleSha384`. Mismatch short-circuits the
357
+ * full Sigstore-verify path. (Redundant with `messageDigest` inside
358
+ * the bundle, but cheap.)
359
+ * 2. **Deserialize** the embedded bundle via `bundleFromJSON`.
360
+ * 3. **RegExp identity pre-check** — when `expectedIdentity.subject` is
361
+ * a RegExp, walk the bundle's verification material to extract the
362
+ * SAN URI and assert the match here (upstream `sigstore.verify` only
363
+ * accepts literal strings).
364
+ * 4. **Upstream verify** — `sigstore.verify(bundle, data, opts)` runs
365
+ * the full Sigstore flow: TUF trust material, Fulcio cert-chain
366
+ * validation, Rekor inclusion proof, signature over the digest, and
367
+ * (if `expectedIdentity` was provided as a string) the identity
368
+ * policy. Throws on any failure.
369
+ *
370
+ * Returns a {@link VerifyResult} discriminated by `valid` — never
371
+ * throws on policy failure (only on programmer error like a malformed
372
+ * `signature.bundle` JSON).
373
+ */
374
+ export async function verifyBundleSigstore(input) {
375
+ const { bundleBytes, signature, expectedIdentity } = input;
376
+ // 1. Fast tamper check.
377
+ const recomputed = sha384(bundleBytes);
378
+ const recomputedB64 = bytesToBase64(recomputed);
379
+ if (recomputedB64 !== signature.bundleSha384) {
380
+ return {
381
+ valid: false,
382
+ reason: "bundle hash mismatch (bundleBytes tampered or wrong bundle)",
383
+ };
384
+ }
385
+ // 2. Deserialize cosign bundle. The wire shape stores the JSON-encoded
386
+ // bundle as a string; `bundleFromJSON` takes the parsed object.
387
+ let parsedBundle;
388
+ try {
389
+ parsedBundle = JSON.parse(signature.bundle);
390
+ }
391
+ catch (err) {
392
+ return {
393
+ valid: false,
394
+ reason: `malformed bundle JSON: ${err.message}`,
395
+ };
396
+ }
397
+ try {
398
+ // Validate-only round-trip — throws ValidationError on bad shape.
399
+ bundleToJSON(bundleFromJSON(parsedBundle));
400
+ }
401
+ catch (err) {
402
+ return {
403
+ valid: false,
404
+ reason: `invalid sigstore bundle shape: ${err.message}`,
405
+ };
406
+ }
407
+ // 3. RegExp identity pre-check. Upstream `sigstore.verify` accepts
408
+ // only literal-equality identity strings, so a RegExp expectation
409
+ // must be enforced here against the bundle's embedded SAN.
410
+ if (expectedIdentity && expectedIdentity.subject instanceof RegExp) {
411
+ const san = extractSANFromBundle(parsedBundle);
412
+ if (san === undefined) {
413
+ return {
414
+ valid: false,
415
+ reason: "expectedIdentity.subject is RegExp but bundle has no subjectAlternativeName to match against",
416
+ };
417
+ }
418
+ if (!expectedIdentity.subject.test(san)) {
419
+ return {
420
+ valid: false,
421
+ reason: `identity mismatch: bundle SAN '${san}' does not match expected pattern ${expectedIdentity.subject}`,
422
+ };
423
+ }
424
+ }
425
+ // 4. Run the full upstream verify.
426
+ try {
427
+ const verifyOpts = {};
428
+ if (expectedIdentity) {
429
+ if (typeof expectedIdentity.subject === "string") {
430
+ // Use email-shaped vs URI-shaped routing per upstream's two
431
+ // policy fields. Both enforce a SAN match.
432
+ if (expectedIdentity.subject.includes("@")) {
433
+ verifyOpts.certificateIdentityEmail =
434
+ expectedIdentity.subject;
435
+ }
436
+ else {
437
+ verifyOpts.certificateIdentityURI =
438
+ expectedIdentity.subject;
439
+ }
440
+ }
441
+ if (expectedIdentity.issuer) {
442
+ verifyOpts.certificateIssuer =
443
+ expectedIdentity.issuer;
444
+ }
445
+ }
446
+ await sigstoreClient.verify(parsedBundle, Buffer.from(bundleBytes), verifyOpts);
447
+ return { valid: true };
448
+ }
449
+ catch (err) {
450
+ return {
451
+ valid: false,
452
+ reason: `sigstore verification failed: ${err.message}`,
453
+ };
454
+ }
455
+ }
456
+ /**
457
+ * Reach into a serialized sigstore Bundle and pull the
458
+ * `subjectAlternativeName` from the embedded X.509 cert (if any). Used
459
+ * by the RegExp-identity pre-check; production verification still goes
460
+ * through the upstream verifier for the actual cryptographic check.
461
+ *
462
+ * Returns `undefined` if the bundle has no cert (e.g. publicKey-only
463
+ * bundle) or no extractable SAN. Uses lightweight base64-DER scanning —
464
+ * defers to the upstream verifier for the trust-chain semantics.
465
+ */
466
+ function extractSANFromBundle(bundle) {
467
+ const material = bundle.verificationMaterial;
468
+ if (!material)
469
+ return undefined;
470
+ let certB64;
471
+ if ("certificate" in material && material.certificate) {
472
+ certB64 = material.certificate.rawBytes;
473
+ }
474
+ else if ("x509CertificateChain" in material &&
475
+ material.x509CertificateChain &&
476
+ material.x509CertificateChain.certificates.length > 0) {
477
+ certB64 = material.x509CertificateChain.certificates[0]?.rawBytes;
478
+ }
479
+ if (!certB64)
480
+ return undefined;
481
+ // Very lightweight SAN extraction: decode DER, locate the SAN
482
+ // extension OID (2.5.29.17), and pull the first URI/email-shaped
483
+ // ASCII run. This is intentionally tolerant — exact parsing happens
484
+ // in `@sigstore/verify` downstream.
485
+ let der;
486
+ try {
487
+ der = base64ToBytes(certB64);
488
+ }
489
+ catch {
490
+ return undefined;
491
+ }
492
+ // OID 2.5.29.17 (subjectAltName) DER prefix: 06 03 55 1d 11.
493
+ const sanOid = [0x06, 0x03, 0x55, 0x1d, 0x11];
494
+ let idx = -1;
495
+ for (let i = 0; i < der.length - sanOid.length; i++) {
496
+ let match = true;
497
+ for (let j = 0; j < sanOid.length; j++) {
498
+ if (der[i + j] !== sanOid[j]) {
499
+ match = false;
500
+ break;
501
+ }
502
+ }
503
+ if (match) {
504
+ idx = i;
505
+ break;
506
+ }
507
+ }
508
+ if (idx === -1)
509
+ return undefined;
510
+ // After the OID DER there's a BOOLEAN (critical, optional) then an
511
+ // OCTET STRING wrapping a SEQUENCE of GeneralName. Scan forward for
512
+ // the first printable ASCII run containing a URI or email shape.
513
+ const tail = der.subarray(idx + sanOid.length);
514
+ let buf = "";
515
+ const uriPattern = /[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]+|[\w.+-]+@[\w.-]+/;
516
+ for (let i = 0; i < tail.length; i++) {
517
+ const b = tail[i];
518
+ if (b >= 0x20 && b <= 0x7e) {
519
+ buf += String.fromCharCode(b);
520
+ }
521
+ else {
522
+ if (buf.length >= 3) {
523
+ const m = buf.match(uriPattern);
524
+ if (m)
525
+ return m[0];
526
+ }
527
+ buf = "";
528
+ }
529
+ }
530
+ if (buf.length >= 3) {
531
+ const m = buf.match(uriPattern);
532
+ if (m)
533
+ return m[0];
534
+ }
535
+ return undefined;
536
+ }
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "@ggui-ai/gadget-signing",
3
+ "version": "0.1.0-rc.1",
4
+ "description": "Gadget bundle signing + verification for the ggui gadget marketplace. Ed25519 author-key path + sigstore/cosign keyless path. Pure-TS @noble crypto for Ed25519 — browser-safe.",
5
+ "license": "Apache-2.0",
6
+ "keywords": [
7
+ "ggui",
8
+ "gadgets",
9
+ "code-signing",
10
+ "ed25519",
11
+ "sigstore",
12
+ "cosign",
13
+ "supply-chain"
14
+ ],
15
+ "type": "module",
16
+ "main": "dist/index.js",
17
+ "types": "dist/index.d.ts",
18
+ "files": [
19
+ "dist",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "import": "./dist/index.js",
27
+ "default": "./dist/index.js"
28
+ }
29
+ },
30
+ "dependencies": {
31
+ "@noble/ed25519": "^2.2.0",
32
+ "@noble/hashes": "^1.6.0",
33
+ "@sigstore/bundle": "^4.0.0",
34
+ "sigstore": "^4.0.0"
35
+ },
36
+ "devDependencies": {
37
+ "@types/node": "^24.0.0",
38
+ "typescript": "^5.0.0",
39
+ "vitest": "^3.0.0"
40
+ },
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "https://github.com/ggui-ai/ggui.git",
44
+ "directory": "packages/gadget-signing"
45
+ },
46
+ "homepage": "https://github.com/ggui-ai/ggui/tree/main/packages/gadget-signing",
47
+ "bugs": {
48
+ "url": "https://github.com/ggui-ai/ggui/issues"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public"
52
+ },
53
+ "engines": {
54
+ "node": ">=20.0.0"
55
+ },
56
+ "author": "ggui contributors <hello@ggui.ai>",
57
+ "scripts": {
58
+ "build": "tsc -p tsconfig.build.json",
59
+ "dev": "tsc --watch",
60
+ "typecheck": "tsc --noEmit",
61
+ "test": "vitest run",
62
+ "test:watch": "vitest",
63
+ "lint": "eslint src --ext .ts --max-warnings 0",
64
+ "clean": "rm -rf dist"
65
+ }
66
+ }