@seed-hypermedia/client 0.0.59 → 0.0.61

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.
@@ -0,0 +1,9 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ export {
8
+ __export
9
+ };
@@ -1,9 +1,3 @@
1
- var __defProp = Object.defineProperty;
2
- var __export = (target, all) => {
3
- for (var name in all)
4
- __defProp(target, name, { get: all[name], enumerable: true });
5
- };
6
-
7
1
  // src/hm-types.ts
8
2
  import * as z from "zod";
9
3
  var BlockRangeSchema = z.object({
@@ -1352,7 +1346,6 @@ function isSurrogate(s, i) {
1352
1346
  }
1353
1347
 
1354
1348
  export {
1355
- __export,
1356
1349
  BlockRangeSchema,
1357
1350
  unpackedHmIdSchema,
1358
1351
  HMBlockChildrenTypeSchema,
@@ -0,0 +1,65 @@
1
+ import {
2
+ __export
3
+ } from "./chunk-7P6ASYW6.mjs";
4
+
5
+ // src/base64.ts
6
+ import "core-js/modules/es.uint8-array.from-base64.js";
7
+ import "core-js/modules/es.uint8-array.to-base64.js";
8
+ function encode(data) {
9
+ return data.toBase64({ alphabet: "base64url", omitPadding: true });
10
+ }
11
+ function decode(data) {
12
+ return Uint8Array.fromBase64(data, { alphabet: "base64url" });
13
+ }
14
+
15
+ // src/encryption.ts
16
+ var encryption_exports = {};
17
+ __export(encryption_exports, {
18
+ DEFAULT_PARAMS: () => DEFAULT_PARAMS,
19
+ decrypt: () => decrypt,
20
+ deriveKeyFromPassword: () => deriveKeyFromPassword,
21
+ encrypt: () => encrypt
22
+ });
23
+ import { xchacha20poly1305 } from "@noble/ciphers/chacha.js";
24
+ import { argon2id } from "hash-wasm";
25
+ var DEFAULT_PARAMS = {
26
+ memoryCost: 65536,
27
+ timeCost: 3,
28
+ parallelism: 4
29
+ };
30
+ async function deriveKeyFromPassword(password, salt, params = DEFAULT_PARAMS) {
31
+ const hash = await argon2id({
32
+ password,
33
+ salt,
34
+ parallelism: params.parallelism,
35
+ iterations: params.timeCost,
36
+ memorySize: params.memoryCost,
37
+ hashLength: 32,
38
+ outputType: "binary"
39
+ });
40
+ return new Uint8Array(hash);
41
+ }
42
+ async function encrypt(plaintext, key, nonce = crypto.getRandomValues(new Uint8Array(24))) {
43
+ const xc = xchacha20poly1305(key.subarray(0, 32), nonce);
44
+ const ciphertext = xc.encrypt(plaintext);
45
+ const output = new Uint8Array(nonce.length + ciphertext.length);
46
+ output.set(nonce);
47
+ output.set(ciphertext, nonce.length);
48
+ return output;
49
+ }
50
+ async function decrypt(data, key) {
51
+ const nonce = data.subarray(0, 24);
52
+ const ciphertext = data.subarray(24);
53
+ const xc = xchacha20poly1305(key.subarray(0, 32), nonce);
54
+ return xc.decrypt(ciphertext);
55
+ }
56
+
57
+ export {
58
+ encode,
59
+ decode,
60
+ DEFAULT_PARAMS,
61
+ deriveKeyFromPassword,
62
+ encrypt,
63
+ decrypt,
64
+ encryption_exports
65
+ };
@@ -0,0 +1,330 @@
1
+ import {
2
+ decrypt
3
+ } from "./chunk-EGCUJ6D6.mjs";
4
+
5
+ // src/vault.ts
6
+ import * as dagCBOR from "@ipld/dag-cbor";
7
+ import { ed25519 } from "@noble/curves/ed25519.js";
8
+ import * as cborg from "cborg";
9
+ import { base58btc } from "multiformats/bases/base58";
10
+ var VAULT_VERSION = 2;
11
+ var cborEncodeOpts = {
12
+ ...dagCBOR.encodeOptions,
13
+ typeEncoders: {
14
+ ...dagCBOR.encodeOptions.typeEncoders,
15
+ undefined: () => null
16
+ }
17
+ };
18
+ var stateExtraKey = /* @__PURE__ */ Symbol("vault-state-extra");
19
+ var accountExtraKey = /* @__PURE__ */ Symbol("vault-account-extra");
20
+ var delegationExtraKey = /* @__PURE__ */ Symbol("vault-delegation-extra");
21
+ var capabilityExtraKey = /* @__PURE__ */ Symbol("vault-capability-extra");
22
+ var accountNamePattern = /^[A-Za-z0-9_-]+$/;
23
+ var ED25519_MULTICODEC_PREFIX = new Uint8Array([237, 1]);
24
+ function principalFromPublicKey(publicKey) {
25
+ const principal = new Uint8Array(ED25519_MULTICODEC_PREFIX.length + publicKey.length);
26
+ principal.set(ED25519_MULTICODEC_PREFIX, 0);
27
+ principal.set(publicKey, ED25519_MULTICODEC_PREFIX.length);
28
+ return principal;
29
+ }
30
+ function principalToString(principal) {
31
+ return base58btc.encode(principal);
32
+ }
33
+ function accountIdFromSeed(seed) {
34
+ return principalToString(principalFromPublicKey(new Uint8Array(ed25519.getPublicKey(seed))));
35
+ }
36
+ function createEmpty() {
37
+ return { version: VAULT_VERSION, accounts: [] };
38
+ }
39
+ async function serialize(data) {
40
+ const encodedCb = cborg.encode(encodeState(data), cborEncodeOpts);
41
+ return compress(new Uint8Array(encodedCb));
42
+ }
43
+ async function deserialize(compressed) {
44
+ const decodedCb = await decompress(compressed);
45
+ const decoded = dagCBOR.decode(decodedCb);
46
+ if (decoded.version !== VAULT_VERSION) {
47
+ throw new Error(
48
+ `Vault schema version mismatch: stored version is ${decoded.version}, but this client expects version ${VAULT_VERSION}. The vault data is incompatible with this version of the application.`
49
+ );
50
+ }
51
+ return decodeState(decoded);
52
+ }
53
+ function getAccountName(account) {
54
+ const normalized = typeof account.name === "string" ? account.name.trim() : "";
55
+ if (normalized && accountNamePattern.test(normalized)) {
56
+ return normalized;
57
+ }
58
+ return accountIdFromSeed(account.seed);
59
+ }
60
+ function normalizeAccount(account) {
61
+ return {
62
+ ...account,
63
+ name: getAccountName(account)
64
+ };
65
+ }
66
+ function accountWinsByTiebreak(current, candidate) {
67
+ if (candidate.createTime > current.createTime) return true;
68
+ if (candidate.createTime < current.createTime) return false;
69
+ return accountIdFromSeed(candidate.seed).localeCompare(accountIdFromSeed(current.seed)) > 0;
70
+ }
71
+ function normalizeAccounts(accounts) {
72
+ const deduped = /* @__PURE__ */ new Map();
73
+ const order = [];
74
+ for (const rawAccount of accounts) {
75
+ const account = normalizeAccount(rawAccount);
76
+ const name = account.name;
77
+ const existing = deduped.get(name);
78
+ if (!existing) {
79
+ order.push(name);
80
+ deduped.set(name, account);
81
+ continue;
82
+ }
83
+ if (accountWinsByTiebreak(existing, account)) {
84
+ deduped.set(name, account);
85
+ }
86
+ }
87
+ return order.map((name) => deduped.get(name));
88
+ }
89
+ function decodeState(decoded) {
90
+ const accounts = normalizeAccounts(
91
+ Array.isArray(decoded.accounts) ? decoded.accounts.map((account) => decodeAccount(account)) : []
92
+ );
93
+ const restored = {
94
+ version: VAULT_VERSION,
95
+ accounts
96
+ };
97
+ if (typeof decoded.notificationServerUrl === "string") {
98
+ restored.notificationServerUrl = decoded.notificationServerUrl;
99
+ }
100
+ if (isDeletedAccounts(decoded.deletedAccounts)) {
101
+ restored.deletedAccounts = { ...decoded.deletedAccounts };
102
+ }
103
+ restored[stateExtraKey] = omitKnown(decoded, ["version", "notificationServerUrl", "deletedAccounts", "accounts"]);
104
+ return restored;
105
+ }
106
+ function decodeAccount(decoded) {
107
+ const account = {
108
+ name: typeof decoded.name === "string" ? decoded.name : void 0,
109
+ seed: new Uint8Array(decoded.seed),
110
+ createTime: Number(decoded.createTime ?? 0),
111
+ delegations: Array.isArray(decoded.delegations) ? decoded.delegations.map((delegation) => decodeDelegation(delegation)) : []
112
+ };
113
+ account[accountExtraKey] = omitKnown(decoded, ["name", "seed", "createTime", "delegations"]);
114
+ return normalizeAccount(account);
115
+ }
116
+ function decodeDelegation(decoded) {
117
+ const delegation = {
118
+ clientId: String(decoded.clientId ?? ""),
119
+ deviceType: typeof decoded.deviceType === "string" ? decoded.deviceType : void 0,
120
+ capability: decodeCapability(decoded.capability),
121
+ createTime: Number(decoded.createTime ?? 0)
122
+ };
123
+ delegation[delegationExtraKey] = omitKnown(decoded, ["clientId", "deviceType", "capability", "createTime"]);
124
+ return delegation;
125
+ }
126
+ function decodeCapability(decoded) {
127
+ const capability = {
128
+ cid: decoded.cid,
129
+ delegate: decoded.delegate
130
+ };
131
+ capability[capabilityExtraKey] = omitKnown(decoded, ["cid", "delegate"]);
132
+ return capability;
133
+ }
134
+ function encodeState(data) {
135
+ const encoded = {
136
+ ...data[stateExtraKey],
137
+ version: VAULT_VERSION,
138
+ accounts: normalizeAccounts(data.accounts).map((account) => encodeAccount(account))
139
+ };
140
+ if (data.notificationServerUrl) {
141
+ encoded.notificationServerUrl = data.notificationServerUrl;
142
+ }
143
+ if (data.deletedAccounts && Object.keys(data.deletedAccounts).length > 0) {
144
+ encoded.deletedAccounts = data.deletedAccounts;
145
+ }
146
+ return encoded;
147
+ }
148
+ function encodeAccount(account) {
149
+ const normalizedAccount = normalizeAccount(account);
150
+ const encoded = {
151
+ ...normalizedAccount[accountExtraKey],
152
+ seed: normalizedAccount.seed,
153
+ createTime: normalizedAccount.createTime,
154
+ delegations: normalizedAccount.delegations.map((delegation) => encodeDelegation(delegation))
155
+ };
156
+ encoded.name = normalizedAccount.name;
157
+ return encoded;
158
+ }
159
+ function encodeDelegation(delegation) {
160
+ const encoded = {
161
+ ...delegation[delegationExtraKey],
162
+ clientId: delegation.clientId,
163
+ capability: encodeCapability(delegation.capability),
164
+ createTime: delegation.createTime
165
+ };
166
+ if (delegation.deviceType) {
167
+ encoded.deviceType = delegation.deviceType;
168
+ }
169
+ return encoded;
170
+ }
171
+ function encodeCapability(capability) {
172
+ return {
173
+ ...capability[capabilityExtraKey],
174
+ cid: capability.cid,
175
+ delegate: capability.delegate
176
+ };
177
+ }
178
+ function omitKnown(decoded, keys) {
179
+ const extras = {};
180
+ for (const [key, value] of Object.entries(decoded)) {
181
+ if (keys.includes(key)) continue;
182
+ extras[key] = value;
183
+ }
184
+ return extras;
185
+ }
186
+ function isDeletedAccounts(value) {
187
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
188
+ return Object.values(value).every((entry) => typeof entry === "number");
189
+ }
190
+ async function compress(data) {
191
+ const cs = new CompressionStream("gzip");
192
+ const writer = cs.writable.getWriter();
193
+ writer.write(data);
194
+ writer.close();
195
+ return collectStream(cs.readable);
196
+ }
197
+ async function decompress(data) {
198
+ const ds = new DecompressionStream("gzip");
199
+ const writer = ds.writable.getWriter();
200
+ writer.write(data);
201
+ writer.close();
202
+ return collectStream(ds.readable);
203
+ }
204
+ async function collectStream(readable) {
205
+ const chunks = [];
206
+ const reader = readable.getReader();
207
+ for (; ; ) {
208
+ const { done, value } = await reader.read();
209
+ if (done) break;
210
+ chunks.push(value);
211
+ }
212
+ const total = chunks.reduce((sum, c) => sum + c.length, 0);
213
+ const result = new Uint8Array(total);
214
+ let offset = 0;
215
+ for (const chunk of chunks) {
216
+ result.set(chunk, offset);
217
+ offset += chunk.length;
218
+ }
219
+ return result;
220
+ }
221
+ async function deriveHKDFKey(rootKey, info) {
222
+ const baseKey = await crypto.subtle.importKey("raw", rootKey.buffer, { name: "HKDF" }, false, [
223
+ "deriveBits"
224
+ ]);
225
+ const derived = await crypto.subtle.deriveBits(
226
+ {
227
+ name: "HKDF",
228
+ hash: "SHA-256",
229
+ salt: new Uint8Array(0),
230
+ info: new TextEncoder().encode(info)
231
+ },
232
+ baseKey,
233
+ 256
234
+ );
235
+ return new Uint8Array(derived);
236
+ }
237
+ async function deriveEncryptionKey(rootKey) {
238
+ return deriveHKDFKey(rootKey, "seed-hypermedia-vault-encryption");
239
+ }
240
+ async function deriveAuthKey(rootKey) {
241
+ return deriveHKDFKey(rootKey, "seed-hypermedia-vault-authentication");
242
+ }
243
+ async function deriveSecretCredentialAuthKey(secret) {
244
+ return deriveHKDFKey(secret, "seed-hypermedia-vault-secret-authentication");
245
+ }
246
+ function parseVaultEnvelope(json) {
247
+ let raw;
248
+ try {
249
+ raw = JSON.parse(json);
250
+ } catch {
251
+ throw new Error("Failed to decode vault envelope: not valid JSON.");
252
+ }
253
+ if (!raw || typeof raw !== "object") {
254
+ throw new Error("Failed to decode vault envelope: expected a JSON object.");
255
+ }
256
+ const encryptedData = decodeStdBase64Field(raw.encryptedData, "encryptedData");
257
+ const wrappedDEK = decodeStdBase64Field(raw.wrappedDEK, "wrappedDEK");
258
+ if (encryptedData.length === 0) {
259
+ throw new Error("Vault encrypted data must not be empty.");
260
+ }
261
+ if (wrappedDEK.length === 0) {
262
+ throw new Error("Vault wrapped DEK must not be empty.");
263
+ }
264
+ const credentials = Array.isArray(raw.credentials) ? raw.credentials.map((entry) => ({
265
+ kind: String(entry.kind ?? ""),
266
+ credentialId: String(entry.credentialId ?? ""),
267
+ wrappedDEK: Uint8Array.fromBase64(String(entry.wrappedDEK ?? ""), { alphabet: "base64url" })
268
+ })) : [];
269
+ let remote = null;
270
+ const rawRemote = raw.remote;
271
+ if (rawRemote && typeof rawRemote === "object") {
272
+ if (typeof rawRemote.vaultUrl !== "string" || rawRemote.vaultUrl === "") {
273
+ throw new Error("Remote vault URL is required.");
274
+ }
275
+ if (typeof rawRemote.userId !== "string" || rawRemote.userId === "") {
276
+ throw new Error("Remote vault user ID is required.");
277
+ }
278
+ remote = {
279
+ vaultUrl: rawRemote.vaultUrl,
280
+ userId: rawRemote.userId,
281
+ credentialId: typeof rawRemote.credentialId === "string" ? rawRemote.credentialId : ""
282
+ };
283
+ }
284
+ return { encryptedData, wrappedDEK, credentials, remote };
285
+ }
286
+ function decodeStdBase64Field(value, field) {
287
+ if (value == null) return new Uint8Array(0);
288
+ if (typeof value !== "string") {
289
+ throw new Error(`Failed to decode vault envelope: "${field}" must be a base64 string.`);
290
+ }
291
+ try {
292
+ return Uint8Array.fromBase64(value, { alphabet: "base64" });
293
+ } catch {
294
+ throw new Error(`Failed to decode vault envelope: "${field}" is not valid base64.`);
295
+ }
296
+ }
297
+ async function unwrapDEK(envelope, wrappingKey) {
298
+ try {
299
+ return await decrypt(envelope.wrappedDEK, wrappingKey);
300
+ } catch {
301
+ throw new Error("Failed to unwrap the vault data encryption key: wrong vault secret.");
302
+ }
303
+ }
304
+ async function decryptVaultState(envelope, dek) {
305
+ let compressed;
306
+ try {
307
+ compressed = await decrypt(envelope.encryptedData, dek);
308
+ } catch {
309
+ throw new Error("Failed to decrypt the vault payload: wrong data encryption key.");
310
+ }
311
+ return deserialize(compressed);
312
+ }
313
+
314
+ export {
315
+ VAULT_VERSION,
316
+ principalFromPublicKey,
317
+ principalToString,
318
+ accountIdFromSeed,
319
+ createEmpty,
320
+ serialize,
321
+ deserialize,
322
+ getAccountName,
323
+ deriveHKDFKey,
324
+ deriveEncryptionKey,
325
+ deriveAuthKey,
326
+ deriveSecretCredentialAuthKey,
327
+ parseVaultEnvelope,
328
+ unwrapDEK,
329
+ decryptVaultState
330
+ };
@@ -0,0 +1,48 @@
1
+ // src/os-keychain.ts
2
+ import { execSync } from "child_process";
3
+ import { platform } from "os";
4
+ var GO_KEYRING_PREFIX = "go-keyring-base64:";
5
+ function readOSSecret(service, account) {
6
+ const os = platform();
7
+ try {
8
+ if (os === "linux") {
9
+ const result = execSync(`secret-tool lookup service ${esc(service)} username ${esc(account)}`, {
10
+ encoding: "utf-8",
11
+ stdio: ["pipe", "pipe", "pipe"]
12
+ });
13
+ return result.trim();
14
+ }
15
+ if (os === "darwin") {
16
+ const result = execSync(`security find-generic-password -s ${esc(service)} -a ${esc(account)} -w`, {
17
+ encoding: "utf-8",
18
+ stdio: ["pipe", "pipe", "pipe"]
19
+ });
20
+ return result.trim();
21
+ }
22
+ throw new Error(`Unsupported platform: ${os}. Only linux and darwin are supported.`);
23
+ } catch (err) {
24
+ const status = err == null ? void 0 : err.status;
25
+ if (status === 1 || status === 44) {
26
+ return null;
27
+ }
28
+ const msg = err instanceof Error ? err.message : String(err);
29
+ if (msg.includes("not found") || msg.includes("No matching") || msg.includes("could not be found") || msg.includes("SecKeychainSearchCopyNext") || msg.includes("The specified item could not be found")) {
30
+ return null;
31
+ }
32
+ throw err;
33
+ }
34
+ }
35
+ function stripGoKeyringPrefix(raw) {
36
+ if (raw.startsWith(GO_KEYRING_PREFIX)) {
37
+ return Buffer.from(raw.slice(GO_KEYRING_PREFIX.length), "base64").toString("utf-8");
38
+ }
39
+ return raw;
40
+ }
41
+ function esc(s) {
42
+ return `'${s.replace(/'/g, "'\\''")}'`;
43
+ }
44
+
45
+ export {
46
+ readOSSecret,
47
+ stripGoKeyringPrefix
48
+ };
package/dist/hm-types.mjs CHANGED
@@ -184,7 +184,8 @@ import {
184
184
  toNumber,
185
185
  unpackHmId,
186
186
  unpackedHmIdSchema
187
- } from "./chunk-5XIADAA7.mjs";
187
+ } from "./chunk-DBW6Z7HZ.mjs";
188
+ import "./chunk-7P6ASYW6.mjs";
188
189
  export {
189
190
  BUILTIN_METADATA_KEYS,
190
191
  BackgroundColorAnnotationSchema,
package/dist/index.mjs CHANGED
@@ -4,7 +4,6 @@ import {
4
4
  HMBlockSchema,
5
5
  HMRequestSchema,
6
6
  HYPERMEDIA_SCHEME,
7
- __export,
8
7
  codePointLength,
9
8
  entityQueryPathToHmIdPath,
10
9
  getHMQueryString,
@@ -17,7 +16,19 @@ import {
17
16
  serializeBlockRange,
18
17
  toNumber,
19
18
  unpackHmId
20
- } from "./chunk-5XIADAA7.mjs";
19
+ } from "./chunk-DBW6Z7HZ.mjs";
20
+ import {
21
+ DEFAULT_PARAMS,
22
+ decode,
23
+ decrypt,
24
+ deriveKeyFromPassword,
25
+ encode,
26
+ encrypt,
27
+ encryption_exports
28
+ } from "./chunk-EGCUJ6D6.mjs";
29
+ import {
30
+ __export
31
+ } from "./chunk-7P6ASYW6.mjs";
21
32
 
22
33
  // src/capability.ts
23
34
  import { encode as cborEncode2 } from "@ipld/dag-cbor";
@@ -4898,60 +4909,6 @@ __export(keyfile_exports, {
4898
4909
  });
4899
4910
  import { ed25519 } from "@noble/curves/ed25519.js";
4900
4911
  import { base58btc as base58btc5 } from "multiformats/bases/base58";
4901
-
4902
- // src/base64.ts
4903
- import "core-js/modules/es.uint8-array.from-base64.js";
4904
- import "core-js/modules/es.uint8-array.to-base64.js";
4905
- function encode2(data) {
4906
- return data.toBase64({ alphabet: "base64url", omitPadding: true });
4907
- }
4908
- function decode(data) {
4909
- return Uint8Array.fromBase64(data, { alphabet: "base64url" });
4910
- }
4911
-
4912
- // src/encryption.ts
4913
- var encryption_exports = {};
4914
- __export(encryption_exports, {
4915
- DEFAULT_PARAMS: () => DEFAULT_PARAMS,
4916
- decrypt: () => decrypt,
4917
- deriveKeyFromPassword: () => deriveKeyFromPassword,
4918
- encrypt: () => encrypt
4919
- });
4920
- import { xchacha20poly1305 } from "@noble/ciphers/chacha.js";
4921
- import { argon2id } from "hash-wasm";
4922
- var DEFAULT_PARAMS = {
4923
- memoryCost: 65536,
4924
- timeCost: 3,
4925
- parallelism: 4
4926
- };
4927
- async function deriveKeyFromPassword(password, salt, params = DEFAULT_PARAMS) {
4928
- const hash = await argon2id({
4929
- password,
4930
- salt,
4931
- parallelism: params.parallelism,
4932
- iterations: params.timeCost,
4933
- memorySize: params.memoryCost,
4934
- hashLength: 32,
4935
- outputType: "binary"
4936
- });
4937
- return new Uint8Array(hash);
4938
- }
4939
- async function encrypt(plaintext, key, nonce = crypto.getRandomValues(new Uint8Array(24))) {
4940
- const xc = xchacha20poly1305(key.subarray(0, 32), nonce);
4941
- const ciphertext = xc.encrypt(plaintext);
4942
- const output = new Uint8Array(nonce.length + ciphertext.length);
4943
- output.set(nonce);
4944
- output.set(ciphertext, nonce.length);
4945
- return output;
4946
- }
4947
- async function decrypt(data, key) {
4948
- const nonce = data.subarray(0, 24);
4949
- const ciphertext = data.subarray(24);
4950
- const xc = xchacha20poly1305(key.subarray(0, 32), nonce);
4951
- return xc.decrypt(ciphertext);
4952
- }
4953
-
4954
- // src/keyfile.ts
4955
4912
  var ED25519_VARINT_PREFIX = new Uint8Array([237, 1]);
4956
4913
  function principalStringFromSeed(seed) {
4957
4914
  const pub = ed25519.getPublicKey(seed);
@@ -4967,7 +4924,7 @@ async function create(input) {
4967
4924
  return {
4968
4925
  createTime,
4969
4926
  publicKey: input.publicKey,
4970
- keyB64: encode2(input.key),
4927
+ keyB64: encode(input.key),
4971
4928
  ...includedProfile ? { profile: includedProfile } : {}
4972
4929
  };
4973
4930
  }
@@ -4977,14 +4934,14 @@ async function create(input) {
4977
4934
  return {
4978
4935
  createTime,
4979
4936
  publicKey: input.publicKey,
4980
- keyB64: encode2(encrypted),
4937
+ keyB64: encode(encrypted),
4981
4938
  encryption: {
4982
4939
  kdf: "argon2id",
4983
4940
  argon2: {
4984
4941
  memoryCost: DEFAULT_PARAMS.memoryCost,
4985
4942
  timeCost: DEFAULT_PARAMS.timeCost,
4986
4943
  parallelism: DEFAULT_PARAMS.parallelism,
4987
- saltB64: encode2(salt)
4944
+ saltB64: encode(salt)
4988
4945
  },
4989
4946
  cipher: "xchacha20poly1305"
4990
4947
  },
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Read-only access to the OS keychain / Secret Service.
3
+ *
4
+ * Node/Bun only — shells out to the platform's native secret tool, the same
5
+ * stores the Go daemon writes to via zalando/go-keyring:
6
+ *
7
+ * Linux: `secret-tool` (libsecret / D-Bus Secret Service).
8
+ * macOS: `security` (Keychain).
9
+ *
10
+ * Do not import this module from browser code; use it via a Node-only entry
11
+ * point such as `vault-local.ts`.
12
+ */
13
+ /**
14
+ * Reads a raw secret value from the OS keychain.
15
+ * Returns null when no matching item exists.
16
+ */
17
+ export declare function readOSSecret(service: string, account: string): string | null;
18
+ /**
19
+ * Strips the `go-keyring-base64:` wrapping that zalando/go-keyring applies to
20
+ * some stored values, returning the decoded plain string.
21
+ */
22
+ export declare function stripGoKeyringPrefix(raw: string): string;
@@ -0,0 +1,9 @@
1
+ import {
2
+ readOSSecret,
3
+ stripGoKeyringPrefix
4
+ } from "./chunk-KNP335NP.mjs";
5
+ import "./chunk-7P6ASYW6.mjs";
6
+ export {
7
+ readOSSecret,
8
+ stripGoKeyringPrefix
9
+ };
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Load Hypermedia identities from a local daemon/desktop vault (`vault.json`).
3
+ *
4
+ * Node/Bun only — reads the filesystem and the OS keychain. This is the
5
+ * one-call entry point for tools (CLI, scripts) that need read-only access to
6
+ * the accounts a Seed daemon or desktop app manages:
7
+ *
8
+ * const accounts = await loadLocalVaultAccounts({})
9
+ *
10
+ * Discovery order for the vault file:
11
+ * 1. explicit `path` option (e.g. from a --vault flag or config file)
12
+ * 2. `SEED_VAULT_PATH` environment variable
13
+ * 3. well-known locations: the desktop app's data dir
14
+ * (`~/.config/Seed[-dev]/daemon/vault.json` on Linux,
15
+ * `~/Library/Application Support/Seed[-dev]/daemon/vault.json` on macOS),
16
+ * then the bare daemon default `~/.mtt/vault.json`.
17
+ *
18
+ * The unlock secret (KEK) comes from the OS keychain (the same record the
19
+ * daemon uses), or from the `SEED_VAULT_KEK` environment variable (base64)
20
+ * on headless machines without a keychain.
21
+ */
22
+ import './base64';
23
+ import { type VaultEnvelope } from './vault';
24
+ /** The vault file could not be found at an explicitly requested path. */
25
+ export declare class VaultFileNotFoundError extends Error {
26
+ constructor(path: string);
27
+ }
28
+ /** The vault unlock secret (KEK) is not available in the OS keychain. */
29
+ export declare class VaultSecretMissingError extends Error {
30
+ constructor(detail: string);
31
+ }
32
+ /** An identity loaded from the vault, with derived key material. */
33
+ export type VaultLocalAccount = {
34
+ name: string;
35
+ /** Raw 32-byte Ed25519 seed (the account private key). */
36
+ seed: Uint8Array;
37
+ publicKey: Uint8Array;
38
+ /** Public key with the Ed25519 multicodec prefix (the principal). */
39
+ publicKeyWithPrefix: Uint8Array;
40
+ /** base58btc principal string, e.g. "z6Mk...". */
41
+ accountId: string;
42
+ createTime: number;
43
+ };
44
+ export type LoadLocalVaultOptions = {
45
+ /** Explicit path to vault.json. Missing file is an error when set. */
46
+ path?: string;
47
+ /** Look in the dev desktop app's data dir (Seed-dev) instead of the production one. */
48
+ dev?: boolean;
49
+ };
50
+ /**
51
+ * Resolves the vault.json path.
52
+ * Returns `{path, explicit: true}` for a path the caller (or env) named, even
53
+ * if the file does not exist, and `{path, explicit: false}` for the first
54
+ * existing well-known location. Returns null when nothing is found.
55
+ */
56
+ export declare function resolveVaultPath(opts?: LoadLocalVaultOptions): {
57
+ path: string;
58
+ explicit: boolean;
59
+ } | null;
60
+ /**
61
+ * Well-known vault.json locations, most specific first.
62
+ */
63
+ export declare function wellKnownVaultPaths(dev: boolean): string[];
64
+ /**
65
+ * Reads the wrapping key (KEK) for a vault envelope.
66
+ *
67
+ * `SEED_VAULT_KEK` (base64, 32 bytes) bypasses the keychain entirely —
68
+ * intended for headless machines. Otherwise the secret comes from the OS
69
+ * keychain record the daemon maintains: account "local" for local vaults, or
70
+ * "<vaultUrl>|<userId>" for remote-connected vaults, resolved by credential ID.
71
+ */
72
+ export declare function readVaultWrappingKey(envelope: VaultEnvelope): Uint8Array;
73
+ /**
74
+ * Loads and decrypts all identities from the local vault.
75
+ * Returns null when no vault file exists at any known location (and none was
76
+ * explicitly requested). Throws descriptive errors for everything else.
77
+ */
78
+ export declare function loadLocalVaultAccounts(opts?: LoadLocalVaultOptions): Promise<VaultLocalAccount[] | null>;
@@ -0,0 +1,175 @@
1
+ import {
2
+ readOSSecret,
3
+ stripGoKeyringPrefix
4
+ } from "./chunk-KNP335NP.mjs";
5
+ import {
6
+ decryptVaultState,
7
+ getAccountName,
8
+ parseVaultEnvelope,
9
+ principalFromPublicKey,
10
+ principalToString,
11
+ unwrapDEK
12
+ } from "./chunk-KCR3277A.mjs";
13
+ import "./chunk-EGCUJ6D6.mjs";
14
+ import "./chunk-7P6ASYW6.mjs";
15
+
16
+ // src/vault-local.ts
17
+ import { ed25519 } from "@noble/curves/ed25519.js";
18
+ import { existsSync, readFileSync } from "fs";
19
+ import { homedir, platform } from "os";
20
+ import { join } from "path";
21
+ var VAULT_KEK_SERVICE = "seed-hypermedia-vault-secret-v2";
22
+ var LEGACY_VAULT_KEK_SERVICE = "seed-hypermedia-vault-secret";
23
+ var LOCAL_KEK_ACCOUNT = "local";
24
+ var VAULT_SECRET_SIZE = 32;
25
+ var VaultFileNotFoundError = class extends Error {
26
+ constructor(path) {
27
+ super(`Vault file not found at "${path}".`);
28
+ this.name = "VaultFileNotFoundError";
29
+ }
30
+ };
31
+ var VaultSecretMissingError = class extends Error {
32
+ constructor(detail) {
33
+ super(
34
+ `The vault unlock secret was not found in the OS keychain (${detail}). Run the Seed desktop app or daemon once on this machine, or set the SEED_VAULT_KEK environment variable (base64).`
35
+ );
36
+ this.name = "VaultSecretMissingError";
37
+ }
38
+ };
39
+ function resolveVaultPath(opts = {}) {
40
+ if (opts.path) {
41
+ return { path: opts.path, explicit: true };
42
+ }
43
+ const envPath = process.env.SEED_VAULT_PATH;
44
+ if (envPath) {
45
+ return { path: envPath, explicit: true };
46
+ }
47
+ for (const candidate of wellKnownVaultPaths(opts.dev ?? false)) {
48
+ if (existsSync(candidate)) {
49
+ return { path: candidate, explicit: false };
50
+ }
51
+ }
52
+ return null;
53
+ }
54
+ function wellKnownVaultPaths(dev) {
55
+ const os = platform();
56
+ const appDataDir = os === "darwin" ? join(homedir(), "Library", "Application Support") : process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
57
+ const desktopDir = dev ? "Seed-dev" : "Seed";
58
+ const paths = [join(appDataDir, desktopDir, "daemon", "vault.json")];
59
+ if (!dev) {
60
+ paths.push(join(homedir(), ".mtt", "vault.json"));
61
+ }
62
+ return paths;
63
+ }
64
+ function readVaultWrappingKey(envelope) {
65
+ const envKek = process.env.SEED_VAULT_KEK;
66
+ if (envKek) {
67
+ const secret = decodeBase64Secret(envKek.trim());
68
+ if (!secret) {
69
+ throw new Error("SEED_VAULT_KEK must be a base64-encoded 32-byte secret.");
70
+ }
71
+ return secret;
72
+ }
73
+ if (envelope.remote == null) {
74
+ return loadKeychainSecret(LOCAL_KEK_ACCOUNT, "");
75
+ }
76
+ const account = `${envelope.remote.vaultUrl.trim()}|${envelope.remote.userId.trim()}`;
77
+ return loadKeychainSecret(account, envelope.remote.credentialId.trim());
78
+ }
79
+ function loadKeychainSecret(account, credentialId) {
80
+ const raw = readOSSecret(VAULT_KEK_SERVICE, account);
81
+ if (raw !== null) {
82
+ const bundle = decodeSecretBundle(stripGoKeyringPrefix(raw));
83
+ const secret = bundle[credentialId];
84
+ if (!secret) {
85
+ throw new VaultSecretMissingError(
86
+ `service "${VAULT_KEK_SERVICE}", account "${account}", credential "${credentialId}"`
87
+ );
88
+ }
89
+ return secret;
90
+ }
91
+ const legacyRaw = readOSSecret(LEGACY_VAULT_KEK_SERVICE, account);
92
+ if (legacyRaw !== null) {
93
+ if (credentialId !== "") {
94
+ throw new VaultSecretMissingError(
95
+ `legacy record at service "${LEGACY_VAULT_KEK_SERVICE}" cannot hold credential "${credentialId}"`
96
+ );
97
+ }
98
+ const secret = decodeBase64Secret(stripGoKeyringPrefix(legacyRaw).trim());
99
+ if (!secret) {
100
+ throw new Error("The legacy vault keychain record is corrupted (expected a base64 32-byte secret).");
101
+ }
102
+ return secret;
103
+ }
104
+ throw new VaultSecretMissingError(`service "${VAULT_KEK_SERVICE}", account "${account}"`);
105
+ }
106
+ function decodeSecretBundle(encoded) {
107
+ let parsed;
108
+ try {
109
+ parsed = JSON.parse(encoded);
110
+ } catch {
111
+ parsed = null;
112
+ }
113
+ const credentials = parsed == null ? void 0 : parsed.credentials;
114
+ if (credentials && typeof credentials === "object") {
115
+ const bundle = {};
116
+ for (const [credentialId, value] of Object.entries(credentials)) {
117
+ const secret2 = decodeBase64Secret(value);
118
+ if (!secret2) {
119
+ throw new Error("The vault keychain credential bundle is corrupted (invalid secret length or encoding).");
120
+ }
121
+ bundle[credentialId] = secret2;
122
+ }
123
+ return bundle;
124
+ }
125
+ const secret = decodeBase64Secret(encoded.trim());
126
+ if (!secret) {
127
+ throw new Error("The vault keychain record is corrupted (expected a credential bundle or a base64 secret).");
128
+ }
129
+ return { "": secret };
130
+ }
131
+ function decodeBase64Secret(value) {
132
+ for (const alphabet of ["base64", "base64url"]) {
133
+ try {
134
+ const decoded = Uint8Array.fromBase64(value, { alphabet });
135
+ if (decoded.length === VAULT_SECRET_SIZE) return decoded;
136
+ } catch {
137
+ continue;
138
+ }
139
+ }
140
+ return null;
141
+ }
142
+ async function loadLocalVaultAccounts(opts = {}) {
143
+ const resolved = resolveVaultPath(opts);
144
+ if (!resolved) return null;
145
+ if (!existsSync(resolved.path)) {
146
+ if (resolved.explicit) {
147
+ throw new VaultFileNotFoundError(resolved.path);
148
+ }
149
+ return null;
150
+ }
151
+ const envelope = parseVaultEnvelope(readFileSync(resolved.path, "utf-8"));
152
+ const wrappingKey = readVaultWrappingKey(envelope);
153
+ const dek = await unwrapDEK(envelope, wrappingKey);
154
+ const state = await decryptVaultState(envelope, dek);
155
+ return state.accounts.map((account) => {
156
+ const publicKey = new Uint8Array(ed25519.getPublicKey(account.seed));
157
+ const publicKeyWithPrefix = principalFromPublicKey(publicKey);
158
+ return {
159
+ name: getAccountName(account),
160
+ seed: account.seed,
161
+ publicKey,
162
+ publicKeyWithPrefix,
163
+ accountId: principalToString(publicKeyWithPrefix),
164
+ createTime: account.createTime
165
+ };
166
+ });
167
+ }
168
+ export {
169
+ VaultFileNotFoundError,
170
+ VaultSecretMissingError,
171
+ loadLocalVaultAccounts,
172
+ readVaultWrappingKey,
173
+ resolveVaultPath,
174
+ wellKnownVaultPaths
175
+ };
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Vault data model, CBOR+gzip serialization, and vault.json envelope access.
3
+ *
4
+ * The vault is the encrypted store for Hypermedia identity accounts, shared by
5
+ * the daemon (Go, backend/storage/vault), the vault web app, and CLI tools.
6
+ * This module is isomorphic (browser/Node/Bun): it has no filesystem or OS
7
+ * keychain access — see `vault-local.ts` for the Node-only local-vault loader.
8
+ *
9
+ * Byte-compatible with:
10
+ * - Go: backend/storage/vault (state.go CBOR atlas, file.go envelope, vault.go crypto)
11
+ * - TS: vault/src/frontend/vault.ts + crypto.ts (the original implementation this was hoisted from)
12
+ */
13
+ import { CID } from 'multiformats/cid';
14
+ import './base64';
15
+ /** Current vault schema version. Bump on every incompatible schema change. */
16
+ export declare const VAULT_VERSION = 2;
17
+ /** A principal: multicodec prefix + raw Ed25519 public key. */
18
+ export type Principal = Uint8Array;
19
+ /** Build a Principal from a raw 32-byte Ed25519 public key. */
20
+ export declare function principalFromPublicKey(publicKey: Uint8Array): Principal;
21
+ /** Encode a Principal to its base58btc multibase string (starts with 'z'). */
22
+ export declare function principalToString(principal: Principal): string;
23
+ /** Derive the account ID (base58btc principal string) from a 32-byte Ed25519 seed. */
24
+ export declare function accountIdFromSeed(seed: Uint8Array): string;
25
+ /**
26
+ * Minimal capability metadata stored per delegation.
27
+ * The raw CBOR blob bytes live in the external blockstore, keyed by cid.
28
+ */
29
+ export interface CapabilityMeta {
30
+ /** CID (content address) of the capability blob in the blockstore. */
31
+ cid: CID;
32
+ /** Delegate principal (packed Ed25519 public key) that received the rights. */
33
+ delegate: Principal;
34
+ }
35
+ /** A single Hypermedia account stored in the vault. */
36
+ export interface Account {
37
+ /** Optional private key label used for daemon key-name lookups. */
38
+ name?: string;
39
+ /** The 32-byte Ed25519 seed to reconstruct the key pair. */
40
+ seed: Uint8Array;
41
+ /** Account creation timestamp. */
42
+ createTime: number;
43
+ /** Allowed cross-device web application sessions. */
44
+ delegations: DelegatedSession[];
45
+ }
46
+ /** Record of a delegation issued to a third-party site's session key. */
47
+ export interface DelegatedSession {
48
+ /** The origin (client_id) the delegation was issued to, e.g. "https://example.com". */
49
+ clientId: string;
50
+ /** Type of device that requested the session. */
51
+ deviceType?: 'desktop' | 'mobile' | 'tablet';
52
+ /** Minimal capability metadata (full blob bytes are stored externally). */
53
+ capability: CapabilityMeta;
54
+ /** Unix timestamp ms when the delegation was created. */
55
+ createTime: number;
56
+ }
57
+ /** Top-level vault state. The actual encrypted data. */
58
+ export interface State {
59
+ /**
60
+ * Schema version for future migrations.
61
+ * Do not confuse with version for concurrency control which is stored in the database separately.
62
+ */
63
+ version: 2;
64
+ /** Optional notification server override for delegated sessions and UI display. */
65
+ notificationServerUrl?: string;
66
+ /** Tombstones for deleted accounts, keyed by canonical account name. */
67
+ deletedAccounts?: Record<string, number>;
68
+ /** List of Hypermedia accounts. */
69
+ accounts: Account[];
70
+ }
71
+ /** Create an empty vault. */
72
+ export declare function createEmpty(): State;
73
+ /** Serialize vault data: CBOR encode → gzip compress. Returns compressed bytes. */
74
+ export declare function serialize(data: State): Promise<Uint8Array>;
75
+ /** Deserialize vault data: gzip decompress → CBOR decode. Throws if version mismatches. */
76
+ export declare function deserialize(compressed: Uint8Array): Promise<State>;
77
+ /** Ensure account name compatibility for older vault records that have no label. */
78
+ export declare function getAccountName(account: Pick<Account, 'name' | 'seed'>): string;
79
+ /**
80
+ * Derive a 256-bit key from the root key using HKDF-SHA256.
81
+ */
82
+ export declare function deriveHKDFKey(rootKey: Uint8Array, info: string): Promise<Uint8Array>;
83
+ /**
84
+ * Derive the vault encryption key from the root key.
85
+ */
86
+ export declare function deriveEncryptionKey(rootKey: Uint8Array): Promise<Uint8Array>;
87
+ /**
88
+ * Derive the password authentication key from the root key.
89
+ */
90
+ export declare function deriveAuthKey(rootKey: Uint8Array): Promise<Uint8Array>;
91
+ /**
92
+ * Derive the authentication key for a secret credential from its KEK.
93
+ */
94
+ export declare function deriveSecretCredentialAuthKey(secret: Uint8Array): Promise<Uint8Array>;
95
+ /** A DEK-wrapping credential stored in the envelope (e.g. a master password). */
96
+ export interface VaultCredentialRef {
97
+ kind: string;
98
+ credentialId: string;
99
+ /** base64url (no padding) XChaCha20-Poly1305 wrapping of the DEK. */
100
+ wrappedDEK: Uint8Array;
101
+ }
102
+ /** Remote vault connection metadata stored in the envelope. */
103
+ export interface VaultRemoteRef {
104
+ vaultUrl: string;
105
+ userId: string;
106
+ credentialId: string;
107
+ }
108
+ /** Parsed contents of a `vault.json` file. */
109
+ export interface VaultEnvelope {
110
+ /** XChaCha20-Poly1305(gzip(cbor(State)), DEK), nonce prepended. */
111
+ encryptedData: Uint8Array;
112
+ /** XChaCha20-Poly1305(DEK, KEK), nonce prepended. */
113
+ wrappedDEK: Uint8Array;
114
+ credentials: VaultCredentialRef[];
115
+ remote: VaultRemoteRef | null;
116
+ }
117
+ /**
118
+ * Parse the JSON contents of a `vault.json` envelope file.
119
+ * Mirrors the validation in backend/storage/vault/file.go.
120
+ */
121
+ export declare function parseVaultEnvelope(json: string): VaultEnvelope;
122
+ /**
123
+ * Unwrap the vault's data encryption key using the wrapping key (KEK).
124
+ * The KEK is the local vault secret, or the remote credential secret for
125
+ * remote-connected vaults.
126
+ */
127
+ export declare function unwrapDEK(envelope: VaultEnvelope, wrappingKey: Uint8Array): Promise<Uint8Array>;
128
+ /**
129
+ * Decrypt and decode the vault state from an envelope using the unwrapped DEK.
130
+ */
131
+ export declare function decryptVaultState(envelope: VaultEnvelope, dek: Uint8Array): Promise<State>;
package/dist/vault.mjs ADDED
@@ -0,0 +1,36 @@
1
+ import {
2
+ VAULT_VERSION,
3
+ accountIdFromSeed,
4
+ createEmpty,
5
+ decryptVaultState,
6
+ deriveAuthKey,
7
+ deriveEncryptionKey,
8
+ deriveHKDFKey,
9
+ deriveSecretCredentialAuthKey,
10
+ deserialize,
11
+ getAccountName,
12
+ parseVaultEnvelope,
13
+ principalFromPublicKey,
14
+ principalToString,
15
+ serialize,
16
+ unwrapDEK
17
+ } from "./chunk-KCR3277A.mjs";
18
+ import "./chunk-EGCUJ6D6.mjs";
19
+ import "./chunk-7P6ASYW6.mjs";
20
+ export {
21
+ VAULT_VERSION,
22
+ accountIdFromSeed,
23
+ createEmpty,
24
+ decryptVaultState,
25
+ deriveAuthKey,
26
+ deriveEncryptionKey,
27
+ deriveHKDFKey,
28
+ deriveSecretCredentialAuthKey,
29
+ deserialize,
30
+ getAccountName,
31
+ parseVaultEnvelope,
32
+ principalFromPublicKey,
33
+ principalToString,
34
+ serialize,
35
+ unwrapDEK
36
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seed-hypermedia/client",
3
- "version": "0.0.59",
3
+ "version": "0.0.61",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/seed-hypermedia/seed",
@@ -49,6 +49,7 @@
49
49
  "@noble/ciphers": "^2.1.1",
50
50
  "@noble/curves": "^2.0.1",
51
51
  "blockstore-core": "^5.0.2",
52
+ "cborg": "^4.5.8",
52
53
  "cheerio": "^1.2.0",
53
54
  "core-js": "^3.48.0",
54
55
  "hash-wasm": "^4.12.0",