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