@seed-hypermedia/client 0.0.58 → 0.0.60

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({
@@ -882,10 +876,20 @@ var HMListCommentsByAuthorRequestSchema = z.object({
882
876
  var HMRawCitationSchema = z.object({
883
877
  source: z.string(),
884
878
  sourceType: z.string().optional(),
879
+ sourceContext: z.string().optional(),
880
+ sourceBlob: z.object({
881
+ cid: z.string().optional(),
882
+ author: z.string().optional(),
883
+ createTime: HMTimestampSchema.optional()
884
+ }).optional(),
885
885
  sourceDocument: z.string().optional(),
886
+ target: z.string().optional(),
887
+ targetVersion: z.string().optional(),
886
888
  targetFragment: z.string().optional(),
887
889
  isExactVersion: z.boolean().optional(),
888
- targetBlockRevision: z.string().optional()
890
+ targetBlockRevision: z.string().optional(),
891
+ mentionType: z.string().optional(),
892
+ isExact: z.boolean().optional()
889
893
  });
890
894
  var HMListCitationsOutputSchema = z.object({
891
895
  citations: z.array(HMRawCitationSchema)
@@ -1342,7 +1346,6 @@ function isSurrogate(s, i) {
1342
1346
  }
1343
1347
 
1344
1348
  export {
1345
- __export,
1346
1349
  BlockRangeSchema,
1347
1350
  unpackedHmIdSchema,
1348
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
+ };