@haex-space/vault-sdk 3.6.0 → 4.0.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 (51) hide show
  1. package/README.md +51 -19
  2. package/dist/cli/index.js +437 -355
  3. package/dist/cli/index.js.map +1 -1
  4. package/dist/cli/index.mjs +428 -339
  5. package/dist/cli/index.mjs.map +1 -1
  6. package/dist/{client-DnCZ3KyI.d.mts → client-C6pEREPM.d.ts} +63 -3
  7. package/dist/{client-uuhuCPDu.d.ts → client-GdCi-m2s.d.mts} +63 -3
  8. package/dist/haex_bundle_bg.wasm +0 -0
  9. package/dist/index.d.mts +14 -59
  10. package/dist/index.d.ts +14 -59
  11. package/dist/index.js +139 -105
  12. package/dist/index.js.map +1 -1
  13. package/dist/index.mjs +158 -123
  14. package/dist/index.mjs.map +1 -1
  15. package/dist/node.d.mts +53 -2
  16. package/dist/node.d.ts +53 -2
  17. package/dist/node.js +319 -2
  18. package/dist/node.js.map +1 -1
  19. package/dist/node.mjs +320 -5
  20. package/dist/node.mjs.map +1 -1
  21. package/dist/nuxt.js +7 -5
  22. package/dist/nuxt.js.map +1 -1
  23. package/dist/nuxt.mjs +3 -2
  24. package/dist/nuxt.mjs.map +1 -1
  25. package/dist/react.d.mts +2 -2
  26. package/dist/react.d.ts +2 -2
  27. package/dist/react.js +146 -7
  28. package/dist/react.js.map +1 -1
  29. package/dist/react.mjs +166 -27
  30. package/dist/react.mjs.map +1 -1
  31. package/dist/runtime/nuxt.plugin.client.d.mts +2 -2
  32. package/dist/runtime/nuxt.plugin.client.d.ts +2 -2
  33. package/dist/runtime/nuxt.plugin.client.js +54 -7
  34. package/dist/runtime/nuxt.plugin.client.js.map +1 -1
  35. package/dist/runtime/nuxt.plugin.client.mjs +54 -7
  36. package/dist/runtime/nuxt.plugin.client.mjs.map +1 -1
  37. package/dist/svelte.d.mts +2 -2
  38. package/dist/svelte.d.ts +2 -2
  39. package/dist/svelte.js +146 -7
  40. package/dist/svelte.js.map +1 -1
  41. package/dist/svelte.mjs +166 -27
  42. package/dist/svelte.mjs.map +1 -1
  43. package/dist/{types-DQZCRfC-.d.mts → types-Ba4G6ZpC.d.mts} +10 -2
  44. package/dist/{types-DQZCRfC-.d.ts → types-Ba4G6ZpC.d.ts} +10 -2
  45. package/dist/vue.d.mts +2 -2
  46. package/dist/vue.d.ts +2 -2
  47. package/dist/vue.js +146 -7
  48. package/dist/vue.js.map +1 -1
  49. package/dist/vue.mjs +166 -27
  50. package/dist/vue.mjs.map +1 -1
  51. package/package.json +8 -6
package/dist/cli/index.js CHANGED
@@ -2,13 +2,10 @@
2
2
  'use strict';
3
3
 
4
4
  var commander = require('commander');
5
- var fs = require('fs/promises');
6
- var path = require('path');
5
+ var fs2 = require('fs/promises');
6
+ var path2 = require('path');
7
7
  var crypto = require('crypto');
8
- var fsSync = require('fs');
9
- var archiver = require('archiver');
10
-
11
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
+ var fs = require('fs');
12
9
 
13
10
  function _interopNamespace(e) {
14
11
  if (e && e.__esModule) return e;
@@ -28,18 +25,16 @@ function _interopNamespace(e) {
28
25
  return Object.freeze(n);
29
26
  }
30
27
 
31
- var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
32
- var path__namespace = /*#__PURE__*/_interopNamespace(path);
33
- var fsSync__namespace = /*#__PURE__*/_interopNamespace(fsSync);
34
- var archiver__default = /*#__PURE__*/_interopDefault(archiver);
28
+ var fs2__namespace = /*#__PURE__*/_interopNamespace(fs2);
29
+ var path2__namespace = /*#__PURE__*/_interopNamespace(path2);
35
30
 
36
31
  function readHaextensionConfig(rootDir = process.cwd()) {
37
- const configPath = path.resolve(rootDir, "haextension.config.json");
38
- if (!fsSync.existsSync(configPath)) {
32
+ const configPath = path2.resolve(rootDir, "haextension.config.json");
33
+ if (!fs.existsSync(configPath)) {
39
34
  return null;
40
35
  }
41
36
  try {
42
- const content = fsSync.readFileSync(configPath, "utf-8");
37
+ const content = fs.readFileSync(configPath, "utf-8");
43
38
  return JSON.parse(content);
44
39
  } catch (error) {
45
40
  console.warn(`Failed to parse haextension.config.json: ${error}`);
@@ -52,14 +47,14 @@ function getExtensionDir(rootDir = process.cwd()) {
52
47
  }
53
48
  function readManifest(options) {
54
49
  const { rootDir, manifestPath, extensionDir = "haextension" } = options;
55
- const resolvedManifestPath = manifestPath ? path.resolve(rootDir, manifestPath) : path.resolve(rootDir, extensionDir, "manifest.json");
50
+ const resolvedManifestPath = manifestPath ? path2.resolve(rootDir, manifestPath) : path2.resolve(rootDir, extensionDir, "manifest.json");
56
51
  try {
57
- const manifestContent = fsSync.readFileSync(resolvedManifestPath, "utf-8");
58
- const parsed = JSON.parse(manifestContent);
52
+ const manifestContent = fs.readFileSync(resolvedManifestPath, "utf-8");
53
+ const { signature: _legacySignature, ...parsed } = JSON.parse(manifestContent);
59
54
  let packageJson = {};
60
55
  try {
61
- const packageJsonPath = path.resolve(rootDir, "package.json");
62
- packageJson = JSON.parse(fsSync.readFileSync(packageJsonPath, "utf-8"));
56
+ const packageJsonPath = path2.resolve(rootDir, "package.json");
57
+ packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
63
58
  } catch {
64
59
  console.warn(`[@haex-space/vault-sdk] Warning: Could not read package.json`);
65
60
  }
@@ -76,13 +71,14 @@ function readManifest(options) {
76
71
  return null;
77
72
  }
78
73
  const manifest = {
74
+ // Keep every field the developer wrote (e.g. displayName); the fallbacks below win.
75
+ ...parsed,
79
76
  name,
80
77
  version,
81
78
  author,
82
79
  entry: parsed.entry ?? null,
83
80
  icon: parsed.icon ?? null,
84
81
  publicKey: parsed.publicKey ?? "",
85
- signature: parsed.signature ?? "",
86
82
  permissions: parsed.permissions ?? {
87
83
  database: [],
88
84
  filesystem: [],
@@ -106,366 +102,440 @@ function readManifest(options) {
106
102
  }
107
103
  }
108
104
 
109
- // src/crypto/signing.ts
110
- var EXTENSION_FILE_EXTENSION = ".xt";
111
- var ExtensionSigner = class {
105
+ // src/bundle/wasm/haex_bundle.js
106
+ var BundleBuilder = class {
107
+ __destroy_into_raw() {
108
+ const ptr = this.__wbg_ptr;
109
+ this.__wbg_ptr = 0;
110
+ BundleBuilderFinalization.unregister(this);
111
+ return ptr;
112
+ }
113
+ free() {
114
+ const ptr = this.__destroy_into_raw();
115
+ wasm.__wbg_bundlebuilder_free(ptr, 0);
116
+ }
112
117
  /**
113
- * Generates an Ed25519 keypair
118
+ * Adds an app file (no control file).
119
+ * @param {string} path
120
+ * @param {Uint8Array} data
114
121
  */
115
- static async generateKeypair() {
116
- const keypair = await crypto.webcrypto.subtle.generateKey(
117
- {
118
- name: "Ed25519",
119
- namedCurve: "Ed25519"
120
- },
121
- true,
122
- ["sign", "verify"]
123
- );
124
- const publicKeyBuffer = await crypto.webcrypto.subtle.exportKey(
125
- "raw",
126
- keypair.publicKey
127
- );
128
- const privateKeyBuffer = await crypto.webcrypto.subtle.exportKey(
129
- "pkcs8",
130
- keypair.privateKey
131
- );
132
- return {
133
- publicKey: Buffer.from(publicKeyBuffer).toString("hex"),
134
- privateKey: Buffer.from(privateKeyBuffer).toString("hex")
135
- };
122
+ addFile(path3, data) {
123
+ const ptr0 = passStringToWasm0(path3, wasm.__wbindgen_export, wasm.__wbindgen_export2);
124
+ const len0 = WASM_VECTOR_LEN;
125
+ const ptr1 = passArray8ToWasm0(data, wasm.__wbindgen_export);
126
+ const len1 = WASM_VECTOR_LEN;
127
+ wasm.bundlebuilder_addFile(this.__wbg_ptr, ptr0, len0, ptr1, len1);
136
128
  }
137
129
  /**
138
- * Computes SHA-256 hash of all files in a directory
130
+ * Signs with the PKCS#8 Ed25519 key, writes the archive and verifies it. `manifest_json` is
131
+ * the manifest without `signature`; its `publicKey` is set from the key. Throws the JSON of a
132
+ * `BundleError` (`{kind, message, path?}`).
133
+ * @param {string} manifest_json
134
+ * @param {Uint8Array} private_key_pkcs8
135
+ * @returns {Uint8Array}
139
136
  */
140
- static async hashDirectory(dirPath) {
141
- const files = await this.getAllFiles(dirPath);
142
- const sortedFiles = files.sort();
143
- console.log(`=== Files to hash (${sortedFiles.length}): ===`);
144
- for (const file of sortedFiles) {
145
- console.log(` - ${path__namespace.relative(dirPath, file)}`);
137
+ build(manifest_json, private_key_pkcs8) {
138
+ try {
139
+ const ptr = this.__destroy_into_raw();
140
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
141
+ const ptr0 = passStringToWasm0(manifest_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);
142
+ const len0 = WASM_VECTOR_LEN;
143
+ const ptr1 = passArray8ToWasm0(private_key_pkcs8, wasm.__wbindgen_export);
144
+ const len1 = WASM_VECTOR_LEN;
145
+ wasm.bundlebuilder_build(retptr, ptr, ptr0, len0, ptr1, len1);
146
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
147
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
148
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
149
+ var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
150
+ if (r3) {
151
+ throw takeObject(r2);
152
+ }
153
+ var v3 = getArrayU8FromWasm0(r0, r1).slice();
154
+ wasm.__wbindgen_export3(r0, r1 * 1, 1);
155
+ return v3;
156
+ } finally {
157
+ wasm.__wbindgen_add_to_stack_pointer(16);
146
158
  }
147
- const contents = [];
148
- for (const file of sortedFiles) {
149
- const content = await fs__namespace.readFile(file);
150
- contents.push(content);
159
+ }
160
+ constructor() {
161
+ const ret = wasm.bundlebuilder_new();
162
+ this.__wbg_ptr = ret;
163
+ BundleBuilderFinalization.register(this, this.__wbg_ptr, this);
164
+ return this;
165
+ }
166
+ };
167
+ if (Symbol.dispose) BundleBuilder.prototype[Symbol.dispose] = BundleBuilder.prototype.free;
168
+ function maxArchiveBytes() {
169
+ const ret = wasm.maxArchiveBytes();
170
+ return ret;
171
+ }
172
+ function verifyArchive(archive) {
173
+ let deferred2_0;
174
+ let deferred2_1;
175
+ try {
176
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
177
+ const ptr0 = passArray8ToWasm0(archive, wasm.__wbindgen_export);
178
+ const len0 = WASM_VECTOR_LEN;
179
+ wasm.verifyArchive(retptr, ptr0, len0);
180
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
181
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
182
+ deferred2_0 = r0;
183
+ deferred2_1 = r1;
184
+ return getStringFromWasm0(r0, r1);
185
+ } finally {
186
+ wasm.__wbindgen_add_to_stack_pointer(16);
187
+ wasm.__wbindgen_export3(deferred2_0, deferred2_1, 1);
188
+ }
189
+ }
190
+ function __wbg_get_imports() {
191
+ const import0 = {
192
+ __proto__: null,
193
+ __wbg___wbindgen_throw_41e9ee4f547fc59a: function(arg0, arg1) {
194
+ throw new Error(getStringFromWasm0(arg0, arg1));
195
+ },
196
+ __wbindgen_generic_0000000000000001: function(arg0, arg1) {
197
+ const ret = getStringFromWasm0(arg0, arg1);
198
+ return addHeapObject(ret);
151
199
  }
152
- const combined = Buffer.concat(contents);
153
- const hashBuffer = await crypto.webcrypto.subtle.digest("SHA-256", combined);
154
- return Buffer.from(hashBuffer);
200
+ };
201
+ return {
202
+ __proto__: null,
203
+ "./haex_bundle_bg.js": import0
204
+ };
205
+ }
206
+ var BundleBuilderFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
207
+ }, unregister: () => {
208
+ } } : new FinalizationRegistry((ptr) => wasm.__wbg_bundlebuilder_free(ptr, 1));
209
+ function addHeapObject(obj) {
210
+ if (heap_next === heap.length) heap.push(heap.length + 1);
211
+ const idx = heap_next;
212
+ heap_next = heap[idx];
213
+ heap[idx] = obj;
214
+ return idx;
215
+ }
216
+ function dropObject(idx) {
217
+ if (idx < 1028) return;
218
+ heap[idx] = heap_next;
219
+ heap_next = idx;
220
+ }
221
+ function getArrayU8FromWasm0(ptr, len) {
222
+ ptr = ptr >>> 0;
223
+ return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
224
+ }
225
+ var cachedDataViewMemory0 = null;
226
+ function getDataViewMemory0() {
227
+ if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || cachedDataViewMemory0.buffer.detached === void 0 && cachedDataViewMemory0.buffer !== wasm.memory.buffer) {
228
+ cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
155
229
  }
156
- /**
157
- * Signs an extension
158
- */
159
- static async signExtension(extensionPath, privateKeyHex) {
160
- const privateKeyBuffer = Buffer.from(privateKeyHex, "hex");
161
- const privateKey = await crypto.webcrypto.subtle.importKey(
162
- "pkcs8",
163
- privateKeyBuffer,
164
- {
165
- name: "Ed25519",
166
- namedCurve: "Ed25519"
167
- },
168
- true,
169
- ["sign"]
170
- );
171
- const publicKeyBuffer = await this.derivePublicKey(privateKeyBuffer);
172
- const publicKeyHex = Buffer.from(publicKeyBuffer).toString("hex");
173
- const hash = await this.hashDirectory(extensionPath);
174
- const signatureBuffer = await crypto.webcrypto.subtle.sign(
175
- "Ed25519",
176
- privateKey,
177
- new Uint8Array(hash)
178
- );
230
+ return cachedDataViewMemory0;
231
+ }
232
+ function getStringFromWasm0(ptr, len) {
233
+ return decodeText(ptr >>> 0, len);
234
+ }
235
+ var cachedUint8ArrayMemory0 = null;
236
+ function getUint8ArrayMemory0() {
237
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
238
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
239
+ }
240
+ return cachedUint8ArrayMemory0;
241
+ }
242
+ function getObject(idx) {
243
+ return heap[idx];
244
+ }
245
+ var heap = new Array(1024).fill(void 0);
246
+ heap.push(void 0, null, true, false);
247
+ var heap_next = heap.length;
248
+ function passArray8ToWasm0(arg, malloc) {
249
+ const ptr = malloc(arg.length * 1, 1) >>> 0;
250
+ getUint8ArrayMemory0().set(arg, ptr / 1);
251
+ WASM_VECTOR_LEN = arg.length;
252
+ return ptr;
253
+ }
254
+ function passStringToWasm0(arg, malloc, realloc) {
255
+ if (realloc === void 0) {
256
+ const buf = cachedTextEncoder.encode(arg);
257
+ const ptr2 = malloc(buf.length, 1) >>> 0;
258
+ getUint8ArrayMemory0().subarray(ptr2, ptr2 + buf.length).set(buf);
259
+ WASM_VECTOR_LEN = buf.length;
260
+ return ptr2;
261
+ }
262
+ let len = arg.length;
263
+ let ptr = malloc(len, 1) >>> 0;
264
+ const mem = getUint8ArrayMemory0();
265
+ let offset = 0;
266
+ for (; offset < len; offset++) {
267
+ const code = arg.charCodeAt(offset);
268
+ if (code > 127) break;
269
+ mem[ptr + offset] = code;
270
+ }
271
+ if (offset !== len) {
272
+ if (offset !== 0) {
273
+ arg = arg.slice(offset);
274
+ }
275
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
276
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
277
+ const ret = cachedTextEncoder.encodeInto(arg, view);
278
+ offset += ret.written;
279
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
280
+ }
281
+ WASM_VECTOR_LEN = offset;
282
+ return ptr;
283
+ }
284
+ function takeObject(idx) {
285
+ const ret = getObject(idx);
286
+ dropObject(idx);
287
+ return ret;
288
+ }
289
+ var cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true });
290
+ cachedTextDecoder.decode();
291
+ var MAX_SAFARI_DECODE_BYTES = 2146435072;
292
+ var numBytesDecoded = 0;
293
+ function decodeText(ptr, len) {
294
+ numBytesDecoded += len;
295
+ if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
296
+ cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true });
297
+ cachedTextDecoder.decode();
298
+ numBytesDecoded = len;
299
+ }
300
+ return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
301
+ }
302
+ var cachedTextEncoder = new TextEncoder();
303
+ if (!("encodeInto" in cachedTextEncoder)) {
304
+ cachedTextEncoder.encodeInto = function(arg, view) {
305
+ const buf = cachedTextEncoder.encode(arg);
306
+ view.set(buf);
179
307
  return {
180
- signature: Buffer.from(signatureBuffer).toString("hex"),
181
- publicKey: publicKeyHex,
182
- hash: hash.toString("hex")
308
+ read: arg.length,
309
+ written: buf.length
183
310
  };
311
+ };
312
+ }
313
+ var WASM_VECTOR_LEN = 0;
314
+ var wasm;
315
+ function __wbg_finalize_init(instance, module) {
316
+ wasm = instance.exports;
317
+ cachedDataViewMemory0 = null;
318
+ cachedUint8ArrayMemory0 = null;
319
+ return wasm;
320
+ }
321
+ function initSync(module) {
322
+ if (wasm !== void 0) return wasm;
323
+ if (module !== void 0) {
324
+ if (Object.getPrototypeOf(module) === Object.prototype) {
325
+ ({ module } = module);
326
+ } else {
327
+ console.warn("using deprecated parameters for `initSync()`; pass a single object instead");
328
+ }
184
329
  }
185
- /**
186
- * Packages and signs an extension
187
- */
188
- static async packageExtension(extensionPath, privateKeyHex, outputPath) {
189
- const extensionDir = getExtensionDir();
190
- const manifestPath = path__namespace.join(extensionDir, "manifest.json");
191
- const originalManifestContent = await fs__namespace.readFile(manifestPath, "utf-8");
192
- const manifestObject = readManifest({
193
- rootDir: process.cwd(),
194
- extensionDir
195
- });
196
- if (!manifestObject) {
197
- throw new Error("Failed to read manifest.json");
330
+ const imports = __wbg_get_imports();
331
+ if (!(module instanceof WebAssembly.Module)) {
332
+ module = new WebAssembly.Module(module);
333
+ }
334
+ const instance = new WebAssembly.Instance(module, imports);
335
+ return __wbg_finalize_init(instance);
336
+ }
337
+
338
+ // src/bundle/index.ts
339
+ var BUNDLE_FILE_EXTENSION = ".xt";
340
+ var BundleError = class extends Error {
341
+ constructor(kind, message, path3) {
342
+ super(`${kind}: ${message}`);
343
+ this.kind = kind;
344
+ this.path = path3;
345
+ this.name = "BundleError";
346
+ }
347
+ };
348
+ var WASM_FILE = "haex_bundle_bg.wasm";
349
+ function wasmPath() {
350
+ const candidates = [path2.join(__dirname, WASM_FILE), path2.join(__dirname, "..", WASM_FILE), path2.join(__dirname, "wasm", WASM_FILE)];
351
+ const found = candidates.find((candidate) => fs.existsSync(candidate));
352
+ if (!found) throw new Error(`${WASM_FILE} not found next to ${__dirname}; run \`pnpm build:wasm\``);
353
+ return found;
354
+ }
355
+ var state = "new";
356
+ function inModule(call) {
357
+ if (state === "crashed") throw new Error("haex-bundle crashed earlier in this process; restart it");
358
+ if (state === "new") {
359
+ initSync({ module: fs.readFileSync(wasmPath()) });
360
+ state = "ready";
361
+ }
362
+ try {
363
+ return call();
364
+ } catch (error) {
365
+ if (error instanceof WebAssembly.RuntimeError) {
366
+ state = "crashed";
367
+ throw new Error(`haex-bundle crashed (a bug, please report it): ${error.message}`, { cause: error });
198
368
  }
199
- const manifest = { ...manifestObject };
200
- const privateKeyBuffer = Buffer.from(privateKeyHex, "hex");
201
- const privateKey = await crypto.webcrypto.subtle.importKey(
202
- "pkcs8",
203
- privateKeyBuffer,
204
- { name: "Ed25519", namedCurve: "Ed25519" },
205
- true,
206
- ["sign"]
207
- );
208
- const publicKeyBuffer = await this.derivePublicKey(privateKeyBuffer);
209
- const publicKeyHex = Buffer.from(publicKeyBuffer).toString("hex");
210
- manifest.publicKey = publicKeyHex;
211
- manifest.signature = "";
212
- const canonicalManifestForHashing = this.sortObjectKeysRecursively(manifest);
213
- const { tmpdir } = await import('os');
214
- const tempDir = path__namespace.join(tmpdir(), `haex-signing-${Date.now()}`);
215
- await fs__namespace.mkdir(tempDir, { recursive: true });
216
- let contentHash;
369
+ throw error;
370
+ }
371
+ }
372
+ function maxBundleBytes() {
373
+ return inModule(() => maxArchiveBytes());
374
+ }
375
+ function verifyBundle(archive) {
376
+ const result = JSON.parse(inModule(() => verifyArchive(archive)));
377
+ if (!result.valid) throw new BundleError(result.kind, result.message, result.path);
378
+ return { manifest: result.manifest, files: result.files, migrations: result.migrations };
379
+ }
380
+ var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
381
+ function buildBundle(files, manifest, privateKeyPkcs8) {
382
+ for (const file of files) {
383
+ if (LONE_SURROGATE.test(file.path)) {
384
+ throw new BundleError("entry_path_invalid", "path is not valid Unicode (lone surrogate)", file.path);
385
+ }
386
+ }
387
+ return inModule(() => {
388
+ const builder = new BundleBuilder();
389
+ for (const file of files) builder.addFile(file.path, file.data);
217
390
  try {
218
- await fs__namespace.cp(extensionPath, tempDir, { recursive: true });
219
- const tempExtensionDir = path__namespace.join(tempDir, extensionDir);
220
- await fs__namespace.mkdir(tempExtensionDir, { recursive: true });
221
- await this.copyDirectory(extensionDir, tempExtensionDir, ["private.key"]);
222
- const tempManifestPath = path__namespace.join(tempExtensionDir, "manifest.json");
223
- await fs__namespace.writeFile(
224
- tempManifestPath,
225
- JSON.stringify(canonicalManifestForHashing, null, 2)
226
- );
227
- const configPath = path__namespace.join(process.cwd(), "haextension.config.json");
228
- if (fsSync__namespace.existsSync(configPath)) {
229
- await fs__namespace.copyFile(configPath, path__namespace.join(tempDir, "haextension.config.json"));
230
- }
231
- if (manifest.migrationsDir) {
232
- const config = readHaextensionConfig(process.cwd());
233
- const migrationsSourceDir = config?.build?.migrationsSourceDir || `app/${manifest.migrationsDir}`;
234
- const migrationsSourcePath = path__namespace.join(process.cwd(), migrationsSourceDir);
235
- if (fsSync__namespace.existsSync(migrationsSourcePath)) {
236
- const tempMigrationsPath = path__namespace.join(tempDir, manifest.migrationsDir);
237
- await fs__namespace.mkdir(path__namespace.dirname(tempMigrationsPath), { recursive: true });
238
- await fs__namespace.cp(migrationsSourcePath, tempMigrationsPath, { recursive: true });
239
- console.log(`\u2713 Migrations copied from ${migrationsSourceDir} to ${manifest.migrationsDir}`);
240
- } else {
241
- console.warn(`\u26A0 Migrations directory not found: ${migrationsSourcePath}`);
242
- }
243
- }
244
- contentHash = await this.hashDirectory(tempDir);
245
- } finally {
246
- await fs__namespace.rm(tempDir, { recursive: true, force: true }).catch(() => {
247
- });
391
+ return builder.build(JSON.stringify(manifest), privateKeyPkcs8);
392
+ } catch (error) {
393
+ if (typeof error !== "string") throw error;
394
+ const { kind, message, path: path3 } = JSON.parse(error);
395
+ throw new BundleError(kind, message, path3);
248
396
  }
249
- const signatureBuffer = await crypto.webcrypto.subtle.sign(
250
- "Ed25519",
251
- privateKey,
252
- new Uint8Array(contentHash)
253
- );
254
- const signatureHex = Buffer.from(signatureBuffer).toString("hex");
255
- manifest.signature = signatureHex;
256
- await fs__namespace.writeFile(manifestPath, JSON.stringify(manifest, null, 2));
257
- const finalOutputPath = outputPath || `${manifest.name}-${manifest.version}${EXTENSION_FILE_EXTENSION}`;
258
- const output = fsSync__namespace.createWriteStream(finalOutputPath);
259
- const archive = archiver__default.default("zip", { zlib: { level: 9 } });
260
- return new Promise((resolve3, reject) => {
261
- output.on("close", async () => {
262
- await fs__namespace.writeFile(manifestPath, originalManifestContent);
263
- console.log("content_hash:", contentHash);
264
- console.log(
265
- `\u2713 Extension packaged: ${finalOutputPath} (${archive.pointer()} bytes)`
266
- );
267
- console.log("\n\u{1F50D} Verifying signature...");
268
- const verifyResult = await this.verifyPackage(finalOutputPath);
269
- if (!verifyResult.valid) {
270
- console.error(`\u274C Signature verification failed: ${verifyResult.error}`);
271
- reject(new Error(`Signature verification failed: ${verifyResult.error}`));
272
- return;
273
- }
274
- console.log("\u2713 Signature verified successfully!");
275
- resolve3(finalOutputPath);
276
- });
277
- output.on("error", (err) => {
278
- fs__namespace.writeFile(manifestPath, originalManifestContent).finally(
279
- () => reject(err)
280
- );
281
- });
282
- archive.on("error", reject);
283
- archive.pipe(output);
284
- archive.directory(extensionPath, false);
285
- archive.glob("**/*", {
286
- cwd: extensionDir,
287
- ignore: ["private.key"],
288
- dot: false
289
- }, { prefix: extensionDir });
290
- const configPath = path__namespace.join(process.cwd(), "haextension.config.json");
291
- if (fsSync__namespace.existsSync(configPath)) {
292
- archive.file(configPath, { name: "haextension.config.json" });
293
- }
294
- if (manifest.migrationsDir) {
295
- const config = readHaextensionConfig(process.cwd());
296
- const migrationsSourceDir = config?.build?.migrationsSourceDir || `app/${manifest.migrationsDir}`;
297
- const migrationsSourcePath = path__namespace.join(process.cwd(), migrationsSourceDir);
298
- if (fsSync__namespace.existsSync(migrationsSourcePath)) {
299
- archive.directory(migrationsSourcePath, manifest.migrationsDir);
300
- console.log(`\u2713 Adding migrations to bundle: ${manifest.migrationsDir}`);
301
- }
302
- }
303
- archive.finalize();
304
- });
397
+ });
398
+ }
399
+
400
+ // src/crypto/signing.ts
401
+ var EXTENSION_FILE_EXTENSION = BUNDLE_FILE_EXTENSION;
402
+ var EXTENSION_DIR_SKIPPED = /* @__PURE__ */ new Set(["manifest.json", "signature.json", "public.key", "private.key"]);
403
+ var ExtensionSigner = class {
404
+ /** Generates an Ed25519 keypair: raw public key and PKCS#8 private key, both hex. */
405
+ static async generateKeypair() {
406
+ const keypair = await crypto.webcrypto.subtle.generateKey({ name: "Ed25519" }, true, [
407
+ "sign",
408
+ "verify"
409
+ ]);
410
+ const publicKeyBuffer = await crypto.webcrypto.subtle.exportKey("raw", keypair.publicKey);
411
+ const privateKeyBuffer = await crypto.webcrypto.subtle.exportKey("pkcs8", keypair.privateKey);
412
+ return {
413
+ publicKey: Buffer.from(publicKeyBuffer).toString("hex"),
414
+ privateKey: Buffer.from(privateKeyBuffer).toString("hex")
415
+ };
305
416
  }
306
- // Helper Methods
307
417
  /**
308
- * Recursively sorts all object keys in a data structure alphabetically
309
- * to produce a canonical, deterministic JSON string.
418
+ * Collects the regular files below `rootDir` with `lstat`, so a symlink is
419
+ * never followed: it aborts packaging, as does any other non-regular file.
420
+ * Paths are relative to `rootDir`, `/`-separated and prefixed with `prefix`.
310
421
  */
311
- static sortObjectKeysRecursively(obj) {
312
- if (typeof obj !== "object" || obj === null) {
313
- return obj;
314
- }
315
- if (Array.isArray(obj)) {
316
- return obj.map((item) => this.sortObjectKeysRecursively(item));
317
- }
318
- return Object.keys(obj).sort().reduce((result, key) => {
319
- result[key] = this.sortObjectKeysRecursively(obj[key]);
320
- return result;
321
- }, {});
422
+ static async collectFilesAsync(rootDir, prefix = "", skip = () => false) {
423
+ const entries = [];
424
+ const walk = async (dir) => {
425
+ for (const name of await fs2__namespace.readdir(dir)) {
426
+ const fullPath = path2__namespace.join(dir, name);
427
+ const relative2 = path2__namespace.relative(rootDir, fullPath).split(path2__namespace.sep).join("/");
428
+ const stats = await fs2__namespace.lstat(fullPath);
429
+ if (stats.isSymbolicLink()) {
430
+ throw new BundleError("entry_kind", `symlinks are not allowed in a bundle: ${fullPath}`, relative2);
431
+ }
432
+ if (stats.isDirectory()) {
433
+ await walk(fullPath);
434
+ } else if (!stats.isFile()) {
435
+ throw new BundleError("entry_kind", `not a regular file: ${fullPath}`, relative2);
436
+ } else if (!skip(relative2)) {
437
+ entries.push({ path: `${prefix}${relative2}`, data: new Uint8Array(await fs2__namespace.readFile(fullPath)) });
438
+ }
439
+ }
440
+ };
441
+ await walk(rootDir);
442
+ return entries;
322
443
  }
323
444
  /**
324
- * Recursively copies a directory, excluding specified files
445
+ * Builds, signs and writes a v2 bundle from the build output `extensionPath`,
446
+ * the extension directory (manifest and extra files, never keys) and the
447
+ * migrations, then verifies the written file. Returns the output path.
325
448
  */
326
- static async copyDirectory(src, dest, excludeFiles = []) {
327
- const entries = await fs__namespace.readdir(src, { withFileTypes: true });
328
- for (const entry of entries) {
329
- if (excludeFiles.includes(entry.name)) continue;
330
- const srcPath = path__namespace.join(src, entry.name);
331
- const destPath = path__namespace.join(dest, entry.name);
332
- if (entry.isDirectory()) {
333
- await fs__namespace.mkdir(destPath, { recursive: true });
334
- await this.copyDirectory(srcPath, destPath, excludeFiles);
449
+ static async packageExtension(extensionPath, privateKeyHex, outputPath) {
450
+ const rootDir = process.cwd();
451
+ const extensionDir = getExtensionDir(rootDir);
452
+ const manifest = readManifest({ rootDir, extensionDir });
453
+ if (!manifest) throw new Error("Failed to read manifest.json");
454
+ const files = await this.collectFilesAsync(extensionPath);
455
+ files.push(
456
+ ...await this.collectFilesAsync(
457
+ path2__namespace.resolve(rootDir, extensionDir),
458
+ "haextension/",
459
+ (relative2) => EXTENSION_DIR_SKIPPED.has(relative2)
460
+ )
461
+ );
462
+ manifest.migrationsDir = manifest.migrationsDir?.replace(/^(?:\.\/)+/, "").replace(/\/+$/, "") || null;
463
+ if (manifest.migrationsDir) {
464
+ const config = readHaextensionConfig(rootDir);
465
+ const sourceDir = config?.build?.migrationsSourceDir || `app/${manifest.migrationsDir}`;
466
+ const sourcePath = path2__namespace.resolve(rootDir, sourceDir);
467
+ const exists = await fs2__namespace.stat(sourcePath).then(
468
+ (stats) => stats.isDirectory(),
469
+ () => false
470
+ );
471
+ if (exists) {
472
+ files.push(...await this.collectFilesAsync(sourcePath, `${manifest.migrationsDir}/`));
473
+ console.log(`\u2713 Adding migrations from ${sourceDir} as ${manifest.migrationsDir}`);
335
474
  } else {
336
- await fs__namespace.copyFile(srcPath, destPath);
475
+ console.warn(`\u26A0 Migrations directory not found: ${sourcePath}`);
337
476
  }
338
477
  }
339
- }
340
- static async getAllFiles(dirPath) {
341
- const entries = await fs__namespace.readdir(dirPath, { withFileTypes: true });
342
- const files = await Promise.all(
343
- entries.map(async (entry) => {
344
- const fullPath = path__namespace.join(dirPath, entry.name);
345
- if (entry.isDirectory()) {
346
- return this.getAllFiles(fullPath);
347
- }
348
- return [fullPath];
349
- })
478
+ const privateKey = privateKeyHex.trim();
479
+ if (!/^(?:[0-9a-fA-F]{2})+$/.test(privateKey)) throw new Error("private key is not hex");
480
+ const archive = buildBundle(
481
+ files,
482
+ manifest,
483
+ Buffer.from(privateKey, "hex")
350
484
  );
351
- return files.flat();
485
+ const finalOutputPath = outputPath || `${manifest.name}-${manifest.version}${BUNDLE_FILE_EXTENSION}`;
486
+ await fs2__namespace.writeFile(finalOutputPath, archive);
487
+ console.log(`\u2713 Extension packaged: ${finalOutputPath} (${files.length + 2} files)`);
488
+ return finalOutputPath;
352
489
  }
353
- static async derivePublicKey(privateKeyBuffer) {
354
- const privateKey = await crypto.webcrypto.subtle.importKey(
355
- "pkcs8",
356
- new Uint8Array(privateKeyBuffer),
357
- { name: "Ed25519", namedCurve: "Ed25519" },
358
- true,
359
- ["sign"]
360
- );
361
- const jwk = await crypto.webcrypto.subtle.exportKey("jwk", privateKey);
362
- const publicKeyJwk = { ...jwk, d: void 0, key_ops: ["verify"] };
363
- const publicKey = await crypto.webcrypto.subtle.importKey(
364
- "jwk",
365
- publicKeyJwk,
366
- { name: "Ed25519", namedCurve: "Ed25519" },
367
- true,
368
- ["verify"]
369
- );
370
- return new Uint8Array(await crypto.webcrypto.subtle.exportKey("raw", publicKey));
490
+ /** Reads and verifies a `.xt` file; throws a `BundleError` naming the first failing rule. */
491
+ static async verifyFileAsync(packagePath) {
492
+ const { size } = await fs2__namespace.stat(packagePath);
493
+ if (size > maxBundleBytes()) {
494
+ throw new BundleError("archive_too_large", `archive is larger than ${maxBundleBytes()} bytes`);
495
+ }
496
+ return verifyBundle(await fs2__namespace.readFile(packagePath));
371
497
  }
372
- /**
373
- * Verifies the signature of a packaged extension (.xt file)
374
- */
498
+ /** Verifies a `.xt` file exactly like a host does (bundle format v2). */
375
499
  static async verifyPackage(packagePath) {
376
- const JSZip = (await import('jszip')).default;
377
500
  try {
378
- const zipBuffer = await fs__namespace.readFile(packagePath);
379
- const zip = await JSZip.loadAsync(zipBuffer);
380
- const manifestFile = zip.file("haextension/manifest.json");
381
- if (!manifestFile) {
382
- return { valid: false, error: "manifest.json not found in package" };
383
- }
384
- const manifestContent = await manifestFile.async("string");
385
- const manifest = JSON.parse(manifestContent);
386
- const { publicKey: publicKeyHex, signature: signatureHex } = manifest;
387
- if (!publicKeyHex || !signatureHex) {
388
- return { valid: false, error: "Missing publicKey or signature in manifest" };
501
+ const { manifest, files } = await this.verifyFileAsync(packagePath);
502
+ return { valid: true, manifest, files };
503
+ } catch (error) {
504
+ if (error instanceof BundleError) {
505
+ return { valid: false, kind: error.kind, path: error.path, error: error.message };
389
506
  }
390
- const files = [];
391
- for (const filePath of Object.keys(zip.files)) {
392
- const entry = zip.files[filePath];
393
- if (entry && !entry.dir) {
394
- const content = await entry.async("uint8array");
395
- files.push({ path: filePath, content });
396
- }
397
- }
398
- const manifestForHashing = this.sortObjectKeysRecursively({
399
- ...manifest,
400
- signature: ""
401
- });
402
- const manifestBytes = new TextEncoder().encode(JSON.stringify(manifestForHashing, null, 2));
403
- const filesForHashing = files.map((file) => {
404
- if (file.path === "haextension/manifest.json") {
405
- return { path: file.path, content: manifestBytes };
406
- }
407
- return file;
408
- });
409
- filesForHashing.sort((a, b) => {
410
- if (a.path < b.path) return -1;
411
- if (a.path > b.path) return 1;
412
- return 0;
413
- });
414
- const totalLength = filesForHashing.reduce((sum, f) => sum + f.content.length, 0);
415
- const combined = new Uint8Array(totalLength);
416
- let offset = 0;
417
- for (const file of filesForHashing) {
418
- combined.set(file.content, offset);
419
- offset += file.content.length;
507
+ if (error instanceof Error && "code" in error) {
508
+ return { valid: false, kind: "io_error", error: error.message };
420
509
  }
421
- const hashBuffer = await crypto.webcrypto.subtle.digest("SHA-256", combined);
422
- const publicKeyBuffer = Buffer.from(publicKeyHex, "hex");
423
- const publicKey = await crypto.webcrypto.subtle.importKey(
424
- "raw",
425
- publicKeyBuffer,
426
- { name: "Ed25519", namedCurve: "Ed25519" },
427
- false,
428
- ["verify"]
429
- );
430
- const signatureBuffer = Buffer.from(signatureHex, "hex");
431
- const isValid = await crypto.webcrypto.subtle.verify(
432
- "Ed25519",
433
- publicKey,
434
- signatureBuffer,
435
- hashBuffer
436
- );
437
- return { valid: isValid, error: isValid ? void 0 : "Signature does not match" };
438
- } catch (err) {
439
- return { valid: false, error: err instanceof Error ? err.message : "Unknown error" };
510
+ throw error;
440
511
  }
441
512
  }
442
513
  };
443
514
  var program = new commander.Command();
444
- program.name("haexhub").description("HaexHub Extension Development Tools").version("1.0.0");
445
- program.command("init").description("Initialize a new HaexHub extension in your project").option("-n, --name <name>", "Extension name").option("-d, --description <desc>", "Extension description").option("--author <author>", "Extension author").option("--dir <dir>", "Extension directory", "./haextension").action(async (options) => {
515
+ program.name("haex").description("haex extension development tools").version("1.0.0");
516
+ program.command("init").description("Initialize a new haex extension in your project").option("-n, --name <name>", "Extension name").option("-d, --description <desc>", "Extension description").option("--author <author>", "Extension author").option("--dir <dir>", "Extension directory", "./haextension").action(async (options) => {
446
517
  try {
447
518
  const cwd = process.cwd();
448
- const extDir = path__namespace.resolve(cwd, options.dir);
449
- if (fsSync.existsSync(extDir)) {
519
+ const extDir = path2__namespace.resolve(cwd, options.dir);
520
+ if (fs.existsSync(extDir)) {
450
521
  console.error(`\u274C Directory ${options.dir} already exists!`);
451
522
  process.exit(1);
452
523
  }
453
524
  let packageJson = {};
454
- const packageJsonPath = path__namespace.join(cwd, "package.json");
455
- if (fsSync.existsSync(packageJsonPath)) {
456
- const content = await fs__namespace.readFile(packageJsonPath, "utf-8");
525
+ const packageJsonPath = path2__namespace.join(cwd, "package.json");
526
+ if (fs.existsSync(packageJsonPath)) {
527
+ const content = await fs2__namespace.readFile(packageJsonPath, "utf-8");
457
528
  packageJson = JSON.parse(content);
458
529
  }
459
- console.log("\u{1F680} Initializing HaexHub Extension...\n");
460
- await fs__namespace.mkdir(extDir, { recursive: true });
530
+ console.log("\u{1F680} Initializing haex extension...\n");
531
+ await fs2__namespace.mkdir(extDir, { recursive: true });
461
532
  console.log(`\u2713 Created directory: ${options.dir}`);
462
533
  const { publicKey, privateKey } = await ExtensionSigner.generateKeypair();
463
- await fs__namespace.writeFile(path__namespace.join(extDir, "public.key"), publicKey);
464
- await fs__namespace.writeFile(path__namespace.join(extDir, "private.key"), privateKey);
534
+ await fs2__namespace.writeFile(path2__namespace.join(extDir, "public.key"), publicKey);
535
+ await fs2__namespace.writeFile(path2__namespace.join(extDir, "private.key"), privateKey);
465
536
  console.log("\u2713 Generated keypair");
466
537
  const manifest = {
467
538
  publicKey,
468
- signature: "",
469
539
  permissions: {
470
540
  database: [],
471
541
  filesystem: [],
@@ -478,28 +548,28 @@ program.command("init").description("Initialize a new HaexHub extension in your
478
548
  if (options.description) {
479
549
  manifest.description = options.description;
480
550
  } else if (!packageJson.description) {
481
- manifest.description = "A HaexHub extension";
551
+ manifest.description = "A haex extension";
482
552
  }
483
- await fs__namespace.writeFile(
484
- path__namespace.join(extDir, "manifest.json"),
553
+ await fs2__namespace.writeFile(
554
+ path2__namespace.join(extDir, "manifest.json"),
485
555
  JSON.stringify(manifest, null, 2)
486
556
  );
487
557
  console.log("\u2713 Created manifest.json");
488
- const gitignorePath = path__namespace.join(cwd, ".gitignore");
558
+ const gitignorePath = path2__namespace.join(cwd, ".gitignore");
489
559
  const gitignoreDir = options.dir.replace(/^\.\//, "");
490
560
  const gitignoreEntries = [
491
- "\n# HaexHub Extension",
561
+ "\n# haex extension",
492
562
  `${gitignoreDir}/private.key`,
493
563
  `*${EXTENSION_FILE_EXTENSION}`
494
564
  ];
495
- if (fsSync.existsSync(gitignorePath)) {
496
- const existing = await fs__namespace.readFile(gitignorePath, "utf-8");
565
+ if (fs.existsSync(gitignorePath)) {
566
+ const existing = await fs2__namespace.readFile(gitignorePath, "utf-8");
497
567
  if (!existing.includes(`${gitignoreDir}/private.key`)) {
498
- await fs__namespace.appendFile(gitignorePath, gitignoreEntries.join("\n"));
568
+ await fs2__namespace.appendFile(gitignorePath, gitignoreEntries.join("\n"));
499
569
  console.log("\u2713 Updated .gitignore");
500
570
  }
501
571
  } else {
502
- await fs__namespace.writeFile(gitignorePath, gitignoreEntries.join("\n"));
572
+ await fs2__namespace.writeFile(gitignorePath, gitignoreEntries.join("\n"));
503
573
  console.log("\u2713 Created .gitignore");
504
574
  }
505
575
  const config = {
@@ -516,16 +586,16 @@ program.command("init").description("Initialize a new HaexHub extension in your
516
586
  distDir: "dist"
517
587
  }
518
588
  };
519
- await fs__namespace.writeFile(
520
- path__namespace.join(cwd, "haextension.config.json"),
589
+ await fs2__namespace.writeFile(
590
+ path2__namespace.join(cwd, "haextension.config.json"),
521
591
  JSON.stringify(config, null, 2)
522
592
  );
523
593
  console.log("\u2713 Created haextension.config.json");
524
- if (fsSync.existsSync(packageJsonPath)) {
594
+ if (fs.existsSync(packageJsonPath)) {
525
595
  packageJson.scripts = packageJson.scripts || {};
526
- packageJson.scripts["ext:dev"] = packageJson.scripts["ext:dev"] || "haexhub dev";
527
- packageJson.scripts["ext:build"] = packageJson.scripts["ext:build"] || `${packageJson.scripts.build || "vite build"} && haexhub sign dist -k ${options.dir}/private.key`;
528
- await fs__namespace.writeFile(
596
+ packageJson.scripts["ext:dev"] = packageJson.scripts["ext:dev"] || packageJson.scripts.dev || "vite";
597
+ packageJson.scripts["ext:build"] = packageJson.scripts["ext:build"] || `${packageJson.scripts.build || "vite build"} && haex sign dist -k ${options.dir}/private.key`;
598
+ await fs2__namespace.writeFile(
529
599
  packageJsonPath,
530
600
  JSON.stringify(packageJson, null, 2)
531
601
  );
@@ -546,18 +616,18 @@ program.command("init").description("Initialize a new HaexHub extension in your
546
616
  });
547
617
  program.command("keygen").description("Generate a new keypair for signing extensions").option("-o, --output <path>", "Output directory", "./haextension").action(async (options) => {
548
618
  const { publicKey, privateKey } = await ExtensionSigner.generateKeypair();
549
- const keyDir = path__namespace.resolve(options.output);
550
- await fs__namespace.mkdir(keyDir, { recursive: true });
551
- await fs__namespace.writeFile(path__namespace.join(keyDir, "public.key"), publicKey);
552
- await fs__namespace.writeFile(path__namespace.join(keyDir, "private.key"), privateKey);
619
+ const keyDir = path2__namespace.resolve(options.output);
620
+ await fs2__namespace.mkdir(keyDir, { recursive: true });
621
+ await fs2__namespace.writeFile(path2__namespace.join(keyDir, "public.key"), publicKey);
622
+ await fs2__namespace.writeFile(path2__namespace.join(keyDir, "private.key"), privateKey);
553
623
  console.log("\u2713 Keypair generated:");
554
- console.log(` Public: ${path__namespace.join(keyDir, "public.key")}`);
555
- console.log(` Private: ${path__namespace.join(keyDir, "private.key")}`);
624
+ console.log(` Public: ${path2__namespace.join(keyDir, "public.key")}`);
625
+ console.log(` Private: ${path2__namespace.join(keyDir, "private.key")}`);
556
626
  console.log("\n\u26A0\uFE0F Keep your private key safe and never commit it!");
557
627
  });
558
- program.command("sign <extension-path>").description("Sign and package an extension").option("-k, --key <path>", "Private key file", "./haextension/private.key").option("-o, --output <path>", "Output path for .haextension file").action(async (extensionPath, options) => {
628
+ program.command("sign <extension-path>").description("Sign and package an extension").option("-k, --key <path>", "Private key file", "./haextension/private.key").option("-o, --output <path>", `Output path for the ${EXTENSION_FILE_EXTENSION} file`).action(async (extensionPath, options) => {
559
629
  try {
560
- const privateKey = await fs__namespace.readFile(options.key, "utf-8");
630
+ const privateKey = await fs2__namespace.readFile(options.key, "utf-8");
561
631
  const outputPath = await ExtensionSigner.packageExtension(
562
632
  extensionPath,
563
633
  privateKey.trim(),
@@ -570,6 +640,18 @@ program.command("sign <extension-path>").description("Sign and package an extens
570
640
  process.exit(1);
571
641
  }
572
642
  });
643
+ program.command("verify <file>").description(`Verify a signed ${EXTENSION_FILE_EXTENSION} bundle exactly like the host does`).action(async (file) => {
644
+ const result = await ExtensionSigner.verifyPackage(file);
645
+ if (result.valid) {
646
+ const { name, version, publicKey } = result.manifest;
647
+ console.log(`valid: ${String(name)} ${String(version)}, ${result.files.length} files, key ${String(publicKey)}`);
648
+ return;
649
+ }
650
+ const where = result.kind === "file_mismatch" ? ` { path: ${JSON.stringify(result.path)} }` : "";
651
+ console.error(`invalid: ${result.kind}${where}
652
+ ${result.error}`);
653
+ process.exit(1);
654
+ });
573
655
  program.parse();
574
656
  //# sourceMappingURL=index.js.map
575
657
  //# sourceMappingURL=index.js.map