@pregen/verify 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +45 -0
  3. package/index.d.ts +43 -0
  4. package/index.js +207 -0
  5. package/package.json +23 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,45 @@
1
+ # @pregen/verify
2
+
3
+ Checks that a PRE-GEN decision or license was really signed by the registry
4
+ that owns its PG code, using the signed registry directory at
5
+ [pregen.org](https://www.pregen.org/registries.json). The PRE-GEN steward key
6
+ is built in; no dependencies (Web Crypto, Node 20+ or a modern browser).
7
+
8
+ ```js
9
+ import { loadDirectory, verifyDecision } from "@pregen/verify";
10
+
11
+ const directory = await loadDirectory({ minSequence: savedSequence });
12
+ saveSequence(directory.sequence); // refuse older copies next time
13
+
14
+ // decision: the JSON a registry returned from /v1/verify
15
+ // code: the PG code you asked about (the license id, or the subject code)
16
+ if (!(await verifyDecision(decision, code, { directory }))) throw new Error("not genuine");
17
+ ```
18
+
19
+ The chain it checks:
20
+
21
+ 1. the directory is signed by the PRE-GEN steward key
22
+ (`pg-ed25519:dcdd244659e6d0e2426f2b504cb11590`) and is not older than one
23
+ you have seen;
24
+ 2. the code's namespace (bare `PG-…` or a four-letter prefix) belongs to one
25
+ listed registry;
26
+ 3. the decision's `operator_key_id` is one of that registry's listed keys, and
27
+ the key its key set serves hashes to that fingerprint;
28
+ 4. the Ed25519 signature over the canonical JSON verifies.
29
+
30
+ What it does **not** check, and you still must (`PRE-GEN-SPEC.md` §5.4):
31
+ that the decision answers your own request (V-4), has not expired (V-3),
32
+ carries a verified user binding when you named a user (V-13), and that
33
+ `disposition` is `allow` before you generate (P-5). A listing in the directory
34
+ proves which registry may issue a code, not that it holds any right over a
35
+ person or a work.
36
+
37
+ Also exported: `verifyDirectory`, `Directory.checkSigner` / `registryFor` /
38
+ `publicKey`, `verifyLicense` (subject signature plus operator countersignature),
39
+ `verifySigned`, `canonicalJson`, `fingerprint`, `issuerOf`.
40
+
41
+ Tests: `npm test` runs the unit tests and the PRE-GEN Level 1 conformance
42
+ vectors with every verifier operation required.
43
+
44
+ Apache-2.0. Part of the PRE-GEN standard,
45
+ [github.com/Pastheroza/PRE-GEN-site](https://github.com/Pastheroza/PRE-GEN-site).
package/index.d.ts ADDED
@@ -0,0 +1,43 @@
1
+ export const STEWARD_PUBLIC_KEY_HEX: string;
2
+ export const DIRECTORY_URL: string;
3
+
4
+ export class PregenError extends Error {}
5
+
6
+ export interface RegistryEntry {
7
+ name: string;
8
+ prefix: string;
9
+ api: string;
10
+ keys: string;
11
+ key_fingerprints: string[];
12
+ [member: string]: unknown;
13
+ }
14
+
15
+ type Fetch = (url: string, init?: { redirect?: "error" }) => Promise<{ ok: boolean; status: number; json(): Promise<any> }>;
16
+
17
+ export class Directory {
18
+ private constructor();
19
+ /** Store it and pass it back as `minSequence`, so an older directory is refused. */
20
+ readonly sequence: number;
21
+ readonly registries: RegistryEntry[];
22
+ /** The registry that owns a code's namespace (resolve codes only there), or null. */
23
+ registryFor(code: string): RegistryEntry | null;
24
+ /** V-10: may this operator key sign objects carrying this code? */
25
+ checkSigner(code: string, signerKeyId: string): "valid" | "unknown_issuer" | "issuer_mismatch";
26
+ /** The owner's public key for `keyId`, fetched from its key set and checked against the listed fingerprint. */
27
+ publicKey(code: string, keyId: string, options?: { fetch?: Fetch }): Promise<string>;
28
+ }
29
+
30
+ export function canonicalJson(value: unknown): string;
31
+ export function sha256Hex(data: string | Uint8Array): Promise<string>;
32
+ export function fingerprint(publicKeyHex: string): Promise<string>;
33
+ export function verifyBytes(publicKeyHex: string, signatureHex: string, message: Uint8Array): Promise<boolean>;
34
+ export function verifySigned(obj: Record<string, unknown>, publicKeyHex: string, signatureField: string, exclude?: string[]): Promise<boolean>;
35
+ export function verifyLicense(license: {
36
+ body: Record<string, unknown>; licenseId: string;
37
+ subjectPublicKeyHex: string; subjectSignatureHex: string;
38
+ operatorPublicKeyHex: string; operatorSignatureHex: string;
39
+ }): Promise<{ subjectValid: boolean; operatorValid: boolean }>;
40
+ export function issuerOf(code: string): string;
41
+ export function verifyDirectory(directory: unknown, options?: { stewardPublicKeyHex?: string; minSequence?: number }): Promise<Directory>;
42
+ export function loadDirectory(options?: { url?: string; minSequence?: number; fetch?: Fetch }): Promise<Directory>;
43
+ export function verifyDecision(decision: Record<string, unknown>, code: string, options?: { directory?: Directory; fetch?: Fetch }): Promise<boolean>;
package/index.js ADDED
@@ -0,0 +1,207 @@
1
+ // @pregen/verify — check PRE-GEN signatures against the signed registry
2
+ // directory (PG-CODE.md §9.1, PRE-GEN-SPEC.md §2, V-9 to V-12).
3
+ // No dependencies: Ed25519 and SHA-256 come from Web Crypto (Node >= 20, browsers).
4
+
5
+ export const STEWARD_PUBLIC_KEY_HEX = "5cb949aab04186e3e216ec541b847c912fc3f78138c0ec3cb2560b2dad0d1f1b";
6
+ export const DIRECTORY_URL = "https://www.pregen.org/registries.json";
7
+ const SCHEMA = "pregen.registries.v2";
8
+ const MAX_INT = 2 ** 53 - 1;
9
+ const PREFIX = /^[ABCDEFGHJKMNPQRSTVWXYZ]{4}$/;
10
+ const FINGERPRINT = /^pg-ed25519:[0-9a-f]{32}$/;
11
+ const ISSUER_IN_CODE = /^PG-([ABCDEFGHJKMNPQRSTVWXYZ]{4})-/;
12
+ const BARE_CODE = /^PG-(?:(?:STD|SUB|PRM|RND)-)?[0-9]/;
13
+
14
+ export class PregenError extends Error {
15
+ constructor(message) { super(message); this.name = "PregenError"; }
16
+ }
17
+ const fail = (message) => { throw new PregenError(message); };
18
+ const utf8 = new TextEncoder();
19
+
20
+ function bytesCompare(a, b) {
21
+ for (let i = 0; i < a.length && i < b.length; i++) if (a[i] !== b[i]) return a[i] - b[i];
22
+ return a.length - b.length;
23
+ }
24
+
25
+ function hexBytes(hex, length) {
26
+ if (typeof hex !== "string" || hex.length !== length * 2 || !/^[0-9a-fA-F]*$/.test(hex)) {
27
+ fail(`expected ${length} bytes of hex`);
28
+ }
29
+ return Uint8Array.from(hex.match(/../g), (h) => parseInt(h, 16));
30
+ }
31
+
32
+ const toHex = (bytes) => Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, "0")).join("");
33
+
34
+ /** Canonical JSON (PRE-GEN-SPEC.md §2) as a string; encode with UTF-8 to sign. */
35
+ export function canonicalJson(value) {
36
+ if (value === null || typeof value === "boolean") return JSON.stringify(value);
37
+ if (typeof value === "number") {
38
+ if (!Number.isSafeInteger(value)) fail("signed JSON numbers must be safe integers");
39
+ return String(value);
40
+ }
41
+ if (typeof value === "string") {
42
+ if (!value.isWellFormed()) fail("invalid Unicode in signed JSON");
43
+ return JSON.stringify(value); // escapes exactly as §2 requires
44
+ }
45
+ if (Array.isArray(value)) {
46
+ for (let i = 0; i < value.length; i++) if (!(i in value)) fail("sparse arrays are not JSON");
47
+ return "[" + value.map(canonicalJson).join(",") + "]";
48
+ }
49
+ if (typeof value === "object" && [Object.prototype, null].includes(Object.getPrototypeOf(value))) {
50
+ // UTF-8 byte order is Unicode code point order.
51
+ const keys = Object.keys(value).sort((a, b) => bytesCompare(utf8.encode(a), utf8.encode(b)));
52
+ return "{" + keys.map((k) => canonicalJson(k) + ":" + canonicalJson(value[k])).join(",") + "}";
53
+ }
54
+ fail("signed JSON must contain only JSON values");
55
+ }
56
+
57
+ export async function sha256Hex(data) {
58
+ return toHex(await crypto.subtle.digest("SHA-256", typeof data === "string" ? utf8.encode(data) : data));
59
+ }
60
+
61
+ /** "pg-ed25519:" + first 32 hex of SHA-256(raw public key) (§2.1). */
62
+ export async function fingerprint(publicKeyHex) {
63
+ return "pg-ed25519:" + (await sha256Hex(hexBytes(publicKeyHex, 32))).slice(0, 32);
64
+ }
65
+
66
+ /** Ed25519 over raw bytes. False on any bad signature or key encoding. */
67
+ export async function verifyBytes(publicKeyHex, signatureHex, message) {
68
+ try {
69
+ const key = await crypto.subtle.importKey("raw", hexBytes(publicKeyHex, 32), { name: "Ed25519" }, false, ["verify"]);
70
+ return await crypto.subtle.verify({ name: "Ed25519" }, key, hexBytes(signatureHex, 64), message);
71
+ } catch {
72
+ return false;
73
+ }
74
+ }
75
+
76
+ /** Verify `obj[signatureField]` over the canonical JSON of `obj` without the excluded fields. */
77
+ export async function verifySigned(obj, publicKeyHex, signatureField, exclude = [signatureField]) {
78
+ if (!obj || typeof obj !== "object") return false;
79
+ const body = Object.fromEntries(Object.entries(obj).filter(([k]) => !exclude.includes(k)));
80
+ return verifyBytes(publicKeyHex, obj[signatureField], utf8.encode(canonicalJson(body)));
81
+ }
82
+
83
+ /** A license (§1.2): subject signature over the body, operator countersignature over
84
+ * canonical body || subject signature (64 raw bytes) || license id (ASCII). */
85
+ export async function verifyLicense({ body, licenseId, subjectPublicKeyHex, subjectSignatureHex,
86
+ operatorPublicKeyHex, operatorSignatureHex }) {
87
+ const bodyBytes = utf8.encode(canonicalJson(body));
88
+ const subjectValid = await verifyBytes(subjectPublicKeyHex, subjectSignatureHex, bodyBytes);
89
+ let operatorValid = false;
90
+ try {
91
+ const sig = hexBytes(subjectSignatureHex, 64);
92
+ const id = utf8.encode(String(licenseId));
93
+ const message = new Uint8Array(bodyBytes.length + 64 + id.length);
94
+ message.set(bodyBytes); message.set(sig, bodyBytes.length); message.set(id, bodyBytes.length + 64);
95
+ operatorValid = await verifyBytes(operatorPublicKeyHex, operatorSignatureHex, message);
96
+ } catch { /* bad encoding: invalid */ }
97
+ return { subjectValid, operatorValid };
98
+ }
99
+
100
+ /** The namespace of a PG code: its four-letter prefix, or "" for the bare namespace. */
101
+ export function issuerOf(code) {
102
+ if (typeof code !== "string") fail("PG code must be a string");
103
+ const c = code.trim().toUpperCase();
104
+ const m = ISSUER_IN_CODE.exec(c);
105
+ if (m) return m[1];
106
+ if (!BARE_CODE.test(c)) fail("unrecognized PG namespace");
107
+ return "";
108
+ }
109
+
110
+ function httpsUrl(value, field) {
111
+ let url;
112
+ try { url = new URL(value); } catch { fail(`registry ${field} must be a URL`); }
113
+ if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash) {
114
+ fail(`registry ${field} must use HTTPS without credentials, query or fragment`);
115
+ }
116
+ }
117
+
118
+ function checkInvariants(d) {
119
+ if (!d || typeof d !== "object" || Array.isArray(d)) fail("directory must be an object");
120
+ if (d.schema !== SCHEMA) fail(`schema must be ${SCHEMA}`);
121
+ if (!Number.isSafeInteger(d.sequence) || d.sequence < 1) fail("sequence must be a positive integer");
122
+ if (!FINGERPRINT.test(String(d.steward_key_id))) fail("steward_key_id must be a pg-ed25519 fingerprint");
123
+ if (!Array.isArray(d.registries) || d.registries.length === 0) fail("registries must be a non-empty list");
124
+ const seen = new Set();
125
+ for (const r of d.registries) {
126
+ if (!r || typeof r !== "object") fail("registry entry must be an object");
127
+ if (typeof r.name !== "string" || !r.name.trim()) fail("registry name must be nonempty");
128
+ httpsUrl(r.api, "api");
129
+ httpsUrl(r.keys, "keys");
130
+ if (r.prefix !== "" && !(typeof r.prefix === "string" && PREFIX.test(r.prefix))) fail(`bad prefix ${r.prefix}`);
131
+ if (seen.has(r.prefix)) fail(r.prefix === "" ? "the bare namespace is listed twice" : `prefix ${r.prefix} is listed twice`);
132
+ seen.add(r.prefix);
133
+ if (!Array.isArray(r.key_fingerprints) || !r.key_fingerprints.length
134
+ || !r.key_fingerprints.every((f) => FINGERPRINT.test(String(f)))) {
135
+ fail(`registry ${r.name}: key_fingerprints must list pg-ed25519 fingerprints`);
136
+ }
137
+ }
138
+ if (!seen.has("")) fail("no registry holds the bare namespace");
139
+ }
140
+
141
+ /** A directory accepted under V-12. Build one with verifyDirectory() or loadDirectory(). */
142
+ export class Directory {
143
+ #d;
144
+ constructor(token, directory) {
145
+ if (token !== Directory.#token) fail("use verifyDirectory() or loadDirectory()");
146
+ this.#d = structuredClone(directory);
147
+ }
148
+ static #token = Symbol();
149
+ static _make(directory) { return new Directory(Directory.#token, directory); }
150
+
151
+ /** Store this and pass it as minSequence next time, so an older copy is refused. */
152
+ get sequence() { return this.#d.sequence; }
153
+ get registries() { return structuredClone(this.#d.registries); }
154
+
155
+ /** The registry that owns a code's namespace (resolve codes only there, V-11), or null. */
156
+ registryFor(code) {
157
+ let issuer;
158
+ try { issuer = issuerOf(code); } catch { return null; }
159
+ const r = this.#d.registries.find((x) => x.prefix === issuer);
160
+ return r ? structuredClone(r) : null;
161
+ }
162
+
163
+ /** V-10: "valid", "unknown_issuer" or "issuer_mismatch". */
164
+ checkSigner(code, signerKeyId) {
165
+ const r = this.registryFor(code);
166
+ if (!r) return "unknown_issuer";
167
+ return r.key_fingerprints.includes(signerKeyId) ? "valid" : "issuer_mismatch";
168
+ }
169
+
170
+ /** The public key behind `keyId`, which must belong to the owner of `code`'s namespace.
171
+ * The key comes from the owner's key set and must hash to the listed fingerprint. */
172
+ async publicKey(code, keyId, { fetch: fetchFn = globalThis.fetch } = {}) {
173
+ const verdict = this.checkSigner(code, keyId);
174
+ if (verdict !== "valid") fail(`${keyId} may not sign ${code}: ${verdict}`);
175
+ const res = await fetchFn(this.registryFor(code).keys, { redirect: "error" });
176
+ if (!res.ok) fail(`key set: HTTP ${res.status}`);
177
+ const entry = ((await res.json()).keys || []).find((k) => k && k.key_id === keyId);
178
+ if (!entry || (await fingerprint(entry.public_key_hex)) !== keyId) fail(`no key ${keyId} in the key set`);
179
+ return entry.public_key_hex;
180
+ }
181
+ }
182
+
183
+ /** V-12: accept the directory only with the pinned steward's signature, its
184
+ * invariants, and a sequence no lower than one already seen. */
185
+ export async function verifyDirectory(directory, { stewardPublicKeyHex = STEWARD_PUBLIC_KEY_HEX, minSequence = 0 } = {}) {
186
+ if (!Number.isSafeInteger(minSequence) || minSequence < 0) fail("minSequence must be a nonnegative integer");
187
+ checkInvariants(directory);
188
+ if (directory.steward_key_id !== (await fingerprint(stewardPublicKeyHex))) fail("signed by a different steward key");
189
+ if (!(await verifySigned(directory, stewardPublicKeyHex, "signature"))) fail("bad steward signature");
190
+ if (directory.sequence < minSequence) fail(`sequence ${directory.sequence} is older than ${minSequence} already seen`);
191
+ return Directory._make(directory);
192
+ }
193
+
194
+ /** Download and verify the directory from pregen.org. */
195
+ export async function loadDirectory({ url = DIRECTORY_URL, minSequence = 0, fetch: fetchFn = globalThis.fetch } = {}) {
196
+ const res = await fetchFn(url, { redirect: "error" });
197
+ if (!res.ok) fail(`directory: HTTP ${res.status}`);
198
+ return verifyDirectory(await res.json(), { minSequence });
199
+ }
200
+
201
+ /** Step 4 in one call: is this registry decision genuine, and signed by a key of the
202
+ * registry that owns `code`? Request matching and expiry (V-3, V-4, V-13) stay with the caller. */
203
+ export async function verifyDecision(decision, code, { directory, fetch: fetchFn = globalThis.fetch } = {}) {
204
+ const dir = directory || (await loadDirectory({ fetch: fetchFn }));
205
+ const key = await dir.publicKey(code, decision && decision.operator_key_id, { fetch: fetchFn });
206
+ return verifySigned(decision, key, "operator_signature");
207
+ }
package/package.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "@pregen/verify",
3
+ "version": "0.1.0",
4
+ "description": "Verify PRE-GEN signatures against the signed registry directory, with the PRE-GEN steward key built in",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./index.d.ts",
9
+ "default": "./index.js"
10
+ }
11
+ },
12
+ "files": ["index.js", "index.d.ts", "README.md", "LICENSE"],
13
+ "engines": { "node": ">=20" },
14
+ "scripts": {
15
+ "test": "node --test test/*.test.js && cd ../.. && python3 spec/conformance/level1/run_conformance.py --adapter \"node packages/verify-js/test/conformance-adapter.js\" --require-op canonical_json --require-op verify_signature --require-op verify_license --require-op verify_directory --require-op check_namespace"
16
+ },
17
+ "keywords": ["pre-gen", "pregen", "pre-generation authorization", "ed25519", "verification"],
18
+ "homepage": "https://www.pregen.org",
19
+ "repository": { "type": "git", "url": "git+https://github.com/Pastheroza/PRE-GEN-site.git", "directory": "packages/verify-js" },
20
+ "license": "Apache-2.0",
21
+ "author": "Valerii Egorov (Pastheroza)",
22
+ "publishConfig": { "access": "public" }
23
+ }