@seed-hypermedia/client 0.0.123 → 0.0.124

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.
package/dist/apps.d.ts CHANGED
@@ -75,42 +75,48 @@ export declare function createDocumentUpdateBlobs({ client, signer, id, ops, cap
75
75
  }>;
76
76
  /**
77
77
  * A trigger document (`type: hm://hyper.media/trigger`) is a child of an app or an agent, listed in
78
- * it as a card embed like a tool. Its metadata says when it fires and what it does:
78
+ * it as a card embed like a tool. Its metadata holds the whole trigger, readable and editable in
79
+ * place:
79
80
  *
80
- * - `source`: `ipfs://<cid>` of a DAG-CBOR trigger source (activity conditions, a schedule, a
81
- * webhook, or run-completed), the same shape agents' triggers have always used.
81
+ * - `source`: when it fires (activity conditions, a schedule, a webhook, or a run finishing).
82
82
  * - `tool`: optionally the hm:// URL of one of its host's tools to call when it fires.
83
- * - `input`: optionally `ipfs://<cid>` of a DAG-CBOR input template for that tool; string values
84
- * `"$event"` and `"$event.<path>"` are replaced from the event.
83
+ * - `input`: optionally the tool's input template; string values `"$event"` and `"$event.<path>"`
84
+ * are replaced from the event.
85
85
  * - `enabled`: `false` turns it off; any other value (or none) leaves it on.
86
86
  *
87
87
  * With no `tool`, a trigger under an agent starts a session with the agent and the trigger's body
88
- * (its content) is the first message. A trigger under an app must name a tool.
88
+ * (its content) is the first message. A trigger under an app calls one of the app's tools.
89
+ *
90
+ * Document attributes merge key by key, and a list is one value that can only be replaced whole, so
91
+ * the source stores its sets as maps (see {@link triggerSourceToMetadata}): `daysOfWeek: {mon: true}`,
92
+ * `timesOfDay: {"08:00": true}`, account lists as `{<account>: true}`, `eventTypes: {comment: true}`,
93
+ * and `conditions` keyed by their ids. Each entry is then its own key, edited without touching the
94
+ * others.
89
95
  */
90
96
  export type TriggerDocumentFields = {
91
- /** The trigger source; published as a DAG-CBOR blob. */
97
+ /** The trigger source, in the engine's shape (lists); stored as maps. */
92
98
  source: unknown;
93
99
  /** hm:// URL of the host's tool to call, or null to start an agent session. */
94
100
  tool?: string | null;
95
- /** Input template for the tool; published as a DAG-CBOR blob. */
101
+ /** Input template for the tool. */
96
102
  input?: unknown;
97
103
  enabled?: boolean;
98
104
  };
99
- /** A trigger document's metadata as stored: references to its source and input blobs. */
100
- export type TriggerDocumentRefs = {
101
- sourceCid: string | null;
105
+ /** A trigger source as document metadata: its lists as maps, so each entry is its own key. */
106
+ export declare function triggerSourceToMetadata(source: unknown): unknown;
107
+ /** A trigger source read from document metadata, in the engine's shape. */
108
+ export declare function triggerSourceFromMetadata(metadata: unknown): unknown;
109
+ /** A trigger document's fields, read from its metadata. */
110
+ export declare function triggerDocumentFields(metadata: Record<string, unknown> | undefined): {
111
+ source: unknown;
102
112
  tool: string | null;
103
- inputCid: string | null;
113
+ input: unknown;
104
114
  enabled: boolean;
105
115
  };
106
- /** The CID inside an `ipfs://<cid>` reference (or a bare CID), or null. */
107
- export declare function ipfsRefCid(value: unknown): string | null;
108
- /** Reads a trigger document's metadata references. */
109
- export declare function triggerDocumentRefs(metadata: Record<string, unknown> | undefined): TriggerDocumentRefs;
110
116
  /**
111
- * The `SetAttributes` op that writes a trigger's fields, with the DAG-CBOR blobs it references
112
- * (publish them with the change). Fields left `undefined` are not touched; `tool: null` and
113
- * `input: null` clear them.
117
+ * The `SetAttributes` op that writes a trigger's fields into its document. Fields left `undefined`
118
+ * are not touched; `tool: null` and `input: null` clear them. A field that is written replaces what
119
+ * was there: it is cleared first, then set entry by entry.
114
120
  */
115
121
  export declare function triggerDocumentOps(fields: Partial<TriggerDocumentFields>): Promise<{
116
122
  ops: DocumentOperation[];
package/dist/apps.mjs CHANGED
@@ -1,9 +1,3 @@
1
- import {
2
- encodeDagCbor
3
- } from "./chunk-S5FIYL5M.mjs";
4
- import "./chunk-UBZRS3WZ.mjs";
5
- import "./chunk-5AZOE4Q5.mjs";
6
- import "./chunk-VWSAFDOL.mjs";
7
1
  import {
8
2
  createChange,
9
3
  createChangeOps
@@ -21,7 +15,6 @@ import {
21
15
  toAPIBlockNode
22
16
  } from "./chunk-3KLY2B27.mjs";
23
17
  import "./chunk-LVAHHQIK.mjs";
24
- import "./chunk-3TPCJCVO.mjs";
25
18
  import "./chunk-DR3HJ6BV.mjs";
26
19
  import {
27
20
  hmIdPathToEntityQueryPath,
@@ -173,38 +166,74 @@ function newBlockId() {
173
166
  const bytes = crypto.getRandomValues(new Uint8Array(8));
174
167
  return Array.from(bytes, (byte) => alphabet[byte & 63]).join("");
175
168
  }
176
- function ipfsRefCid(value) {
177
- if (typeof value !== "string" || !value) return null;
178
- const cid = value.replace(/^ipfs:\/\//i, "").split("/")[0] ?? "";
179
- return cid || null;
169
+ var DAY_NAMES = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
170
+ var SET_FIELDS = ["timesOfDay", "mentionedAccounts", "repliedToAccounts", "documentAuthors", "eventTypes"];
171
+ function isPlainRecord(value) {
172
+ return !!value && typeof value === "object" && !Array.isArray(value);
173
+ }
174
+ function triggerSourceToMetadata(source) {
175
+ if (!isPlainRecord(source)) return source;
176
+ const out = {};
177
+ for (const [key, value] of Object.entries(source)) {
178
+ if (key === "daysOfWeek" && Array.isArray(value))
179
+ out[key] = Object.fromEntries(value.map((day) => [DAY_NAMES[Number(day)] ?? String(day), true]));
180
+ else if (SET_FIELDS.includes(key) && Array.isArray(value))
181
+ out[key] = Object.fromEntries(value.map((item) => [String(item), true]));
182
+ else if (key === "conditions" && Array.isArray(value))
183
+ out[key] = Object.fromEntries(
184
+ value.map((condition, index) => {
185
+ const { id, source: conditionSource } = condition ?? {};
186
+ return [
187
+ typeof id === "string" && id ? id : `condition-${index + 1}`,
188
+ triggerSourceToMetadata(conditionSource)
189
+ ];
190
+ })
191
+ );
192
+ else out[key] = isPlainRecord(value) ? triggerSourceToMetadata(value) : value;
193
+ }
194
+ return out;
195
+ }
196
+ function triggerSourceFromMetadata(metadata) {
197
+ if (!isPlainRecord(metadata)) return metadata;
198
+ const members = (value) => isPlainRecord(value) ? Object.entries(value).filter(([, on]) => on === true || on === "true").map(([item]) => item) : Array.isArray(value) ? value : [];
199
+ const out = {};
200
+ for (const [key, value] of Object.entries(metadata)) {
201
+ if (key === "daysOfWeek")
202
+ out[key] = members(value).map((day) => typeof day === "number" ? day : DAY_NAMES.indexOf(String(day).toLowerCase())).filter((day) => day >= 0).sort((a, b) => a - b);
203
+ else if (SET_FIELDS.includes(key)) out[key] = key === "timesOfDay" ? members(value).sort() : members(value);
204
+ else if (key === "conditions" && isPlainRecord(value))
205
+ out[key] = Object.entries(value).map(([id, condition]) => ({ id, source: triggerSourceFromMetadata(condition) }));
206
+ else out[key] = isPlainRecord(value) ? triggerSourceFromMetadata(value) : value;
207
+ }
208
+ return out;
180
209
  }
181
- function triggerDocumentRefs(metadata) {
210
+ function triggerDocumentFields(metadata) {
182
211
  return {
183
- sourceCid: ipfsRefCid(metadata == null ? void 0 : metadata.source),
212
+ source: isPlainRecord(metadata == null ? void 0 : metadata.source) ? triggerSourceFromMetadata(metadata.source) : void 0,
184
213
  tool: typeof (metadata == null ? void 0 : metadata.tool) === "string" && metadata.tool ? metadata.tool : null,
185
- inputCid: ipfsRefCid(metadata == null ? void 0 : metadata.input),
214
+ input: (metadata == null ? void 0 : metadata.input) ?? void 0,
186
215
  enabled: (metadata == null ? void 0 : metadata.enabled) !== false && (metadata == null ? void 0 : metadata.enabled) !== "false"
187
216
  };
188
217
  }
218
+ function leafAttributes(key, value) {
219
+ if (!isPlainRecord(value)) return [{ key, value }];
220
+ const leaves = Object.entries(value).flatMap(([child, childValue]) => leafAttributes([...key, child], childValue));
221
+ return leaves;
222
+ }
189
223
  async function triggerDocumentOps(fields) {
190
224
  const attrs = [];
191
- const blobs = [];
192
- if (fields.source !== void 0) {
193
- const encoded = await encodeDagCbor(fields.source);
194
- blobs.push({ cid: encoded.cid, data: encoded.data });
195
- attrs.push({ key: ["source"], value: `ipfs://${encoded.cid}` });
196
- }
225
+ const replace = (key, value) => {
226
+ attrs.push({ key: [key], value: null });
227
+ if (value !== null) attrs.push(...leafAttributes([key], value));
228
+ };
229
+ if (fields.source !== void 0) replace("source", triggerSourceToMetadata(fields.source));
197
230
  if (fields.tool !== void 0) attrs.push({ key: ["tool"], value: fields.tool || null });
198
- if (fields.input !== void 0) {
199
- if (fields.input === null) attrs.push({ key: ["input"], value: null });
200
- else {
201
- const encoded = await encodeDagCbor(fields.input);
202
- blobs.push({ cid: encoded.cid, data: encoded.data });
203
- attrs.push({ key: ["input"], value: `ipfs://${encoded.cid}` });
204
- }
205
- }
231
+ if (fields.input !== void 0) replace("input", fields.input);
206
232
  if (fields.enabled !== void 0) attrs.push({ key: ["enabled"], value: fields.enabled });
207
- return { ops: attrs.length ? [{ type: "SetAttributes", attrs }] : [], blobs };
233
+ return {
234
+ ops: attrs.length ? [{ type: "SetAttributes", attrs }] : [],
235
+ blobs: []
236
+ };
208
237
  }
209
238
  export {
210
239
  HM_AGENT_TYPE,
@@ -219,12 +248,13 @@ export {
219
248
  appChildrenOps,
220
249
  appEmbeddedChildren,
221
250
  createDocumentUpdateBlobs,
222
- ipfsRefCid,
223
251
  isAppChildId,
224
252
  isToolHostType,
225
253
  parentDocumentId,
226
254
  removeAppChildOps,
227
255
  replaceContentOps,
256
+ triggerDocumentFields,
228
257
  triggerDocumentOps,
229
- triggerDocumentRefs
258
+ triggerSourceFromMetadata,
259
+ triggerSourceToMetadata
230
260
  };
package/dist/auth.mjs CHANGED
@@ -14,9 +14,9 @@ import {
14
14
  parseEmailPrevalidation,
15
15
  validateClientId,
16
16
  validateRedirectUri
17
- } from "./chunk-WN25ZBDL.mjs";
17
+ } from "./chunk-XJ4BKTVL.mjs";
18
18
  import {
19
- decode as decode2,
19
+ decode,
20
20
  encode
21
21
  } from "./chunk-2MD3FXKB.mjs";
22
22
  import {
@@ -28,7 +28,7 @@ import {
28
28
  verify
29
29
  } from "./chunk-GBSWXJGU.mjs";
30
30
  import {
31
- decode
31
+ decode as decode2
32
32
  } from "./chunk-3TPCJCVO.mjs";
33
33
  import "./chunk-DR3HJ6BV.mjs";
34
34
  import "./chunk-7P6ASYW6.mjs";
@@ -197,7 +197,7 @@ async function handleCallback(config, options = {}) {
197
197
  vaultUrl: record.vaultUrl,
198
198
  createdAt: record.createTime
199
199
  };
200
- const callbackData = decode(await decompress(decode2(dataParam)));
200
+ const callbackData = decode2(await decompress(decode(dataParam)));
201
201
  let notifyServerUrl;
202
202
  if (callbackData.notifyServerUrl && typeof callbackData.notifyServerUrl === "string") {
203
203
  try {
@@ -236,7 +236,7 @@ async function handleCallback(config, options = {}) {
236
236
  let emailPrevalidation;
237
237
  if (emailProof) {
238
238
  try {
239
- emailPrevalidation = parseEmailPrevalidation(decode(decode2(emailProof)), vaultUrl);
239
+ emailPrevalidation = parseEmailPrevalidation(decode2(decode(emailProof)), vaultUrl);
240
240
  } catch {
241
241
  }
242
242
  }
@@ -4,7 +4,7 @@ import {
4
4
  documentContainsLinkToChild,
5
5
  documentHasSelfQuery,
6
6
  shouldAutoLinkParent
7
- } from "./chunk-CBCMOIFJ.mjs";
7
+ } from "./chunk-4OSIHGZS.mjs";
8
8
  import "./chunk-O5MHN2EO.mjs";
9
9
  import "./chunk-PJ2RFT5A.mjs";
10
10
  import "./chunk-QTPHQIZJ.mjs";
@@ -69,6 +69,7 @@ function documentHasSelfQuery(document, documentId) {
69
69
  return searchBlocks(document.content || []);
70
70
  }
71
71
  function shouldAutoLinkParent(isPrivate, parentDocument, editableLocation, parentId) {
72
+ var _a;
72
73
  if (isPrivate) return false;
73
74
  if (parentDocument) {
74
75
  if (documentContainsLinkToChild(parentDocument, editableLocation)) {
@@ -77,6 +78,9 @@ function shouldAutoLinkParent(isPrivate, parentDocument, editableLocation, paren
77
78
  if (documentHasSelfQuery(parentDocument, parentId)) {
78
79
  return false;
79
80
  }
81
+ if ((_a = parentDocument.metadata) == null ? void 0 : _a.childAttributesSchema) {
82
+ return false;
83
+ }
80
84
  }
81
85
  return true;
82
86
  }
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  decode,
3
- encode as encode2
3
+ encode
4
4
  } from "./chunk-2MD3FXKB.mjs";
5
5
  import {
6
6
  ED25519_VARINT_PREFIX,
@@ -10,7 +10,7 @@ import {
10
10
  principalToString
11
11
  } from "./chunk-GBSWXJGU.mjs";
12
12
  import {
13
- encode
13
+ encode as encode2
14
14
  } from "./chunk-3TPCJCVO.mjs";
15
15
 
16
16
  // src/hmauth.ts
@@ -270,9 +270,9 @@ async function buildCallbackUrl(redirectUri, state, accountPrincipal, capability
270
270
  profileCid: profile.cid,
271
271
  ...notifyServerUrl ? { notifyServerUrl } : {}
272
272
  };
273
- const encodedCbor = encode(callbackData);
273
+ const encodedCbor = encode2(callbackData);
274
274
  const compressed = await compress(new Uint8Array(encodedCbor));
275
- url.searchParams.set(PARAM_DATA, encode2(compressed));
275
+ url.searchParams.set(PARAM_DATA, encode(compressed));
276
276
  url.searchParams.set(PARAM_STATE, state);
277
277
  return url.toString();
278
278
  }
package/dist/hmauth.mjs CHANGED
@@ -24,7 +24,7 @@ import {
24
24
  validateSessionKeyPrincipal,
25
25
  validateState,
26
26
  verifyDelegationRequestProof
27
- } from "./chunk-WN25ZBDL.mjs";
27
+ } from "./chunk-XJ4BKTVL.mjs";
28
28
  import "./chunk-2MD3FXKB.mjs";
29
29
  import "./chunk-GBSWXJGU.mjs";
30
30
  import "./chunk-3TPCJCVO.mjs";
package/dist/index.mjs CHANGED
@@ -88,7 +88,7 @@ import {
88
88
  documentContainsLinkToChild,
89
89
  documentHasSelfQuery,
90
90
  shouldAutoLinkParent
91
- } from "./chunk-CBCMOIFJ.mjs";
91
+ } from "./chunk-4OSIHGZS.mjs";
92
92
  import {
93
93
  createChange,
94
94
  createChangeOps,
@@ -1,22 +1,112 @@
1
1
  import {
2
- SIGNED_BLOB_ENVELOPE,
3
- ZERO_SIGNATURE_LENGTH,
4
- encodeDagCbor,
5
- hasSignedEnvelope,
6
- isSignedBlobSchema,
7
- principalToPublicKey,
8
- publishSignedBlob,
9
- signBlob,
10
- signedBlobMessage,
11
- signedBlobTypeTag,
12
- stripSignedBlobEnvelope,
13
- verifySignedBlob
14
- } from "./chunk-S5FIYL5M.mjs";
15
- import "./chunk-UBZRS3WZ.mjs";
2
+ fieldSchema,
3
+ fieldsToProperties,
4
+ isLiteralSchema,
5
+ literalValue,
6
+ resolveSchema,
7
+ structFields
8
+ } from "./chunk-UBZRS3WZ.mjs";
16
9
  import "./chunk-5AZOE4Q5.mjs";
17
- import "./chunk-VWSAFDOL.mjs";
18
- import "./chunk-3TPCJCVO.mjs";
10
+ import {
11
+ dagJsonToIpld,
12
+ findSeedIndexerCollision
13
+ } from "./chunk-VWSAFDOL.mjs";
14
+ import {
15
+ code,
16
+ encode
17
+ } from "./chunk-3TPCJCVO.mjs";
19
18
  import "./chunk-7P6ASYW6.mjs";
19
+
20
+ // src/signed-blob.ts
21
+ import { ed25519 } from "@noble/curves/ed25519.js";
22
+ import { base58btc } from "multiformats/bases/base58";
23
+ import { CID } from "multiformats/cid";
24
+ import { sha256 } from "multiformats/hashes/sha2";
25
+ var SIGNED_BLOB_ENVELOPE = ["signer", "sig", "ts"];
26
+ var ZERO_SIGNATURE_LENGTH = 64;
27
+ function isSignedBlobSchema(schema, reg = {}) {
28
+ if (!schema) return false;
29
+ const { schema: resolved } = resolveSchema(schema, {}, reg);
30
+ const props = resolved.properties;
31
+ return !!props && SIGNED_BLOB_ENVELOPE.every((k) => fieldSchema(resolved, k) !== void 0);
32
+ }
33
+ function signedBlobTypeTag(schema, reg = {}) {
34
+ const { schema: resolved } = resolveSchema(schema, {}, reg);
35
+ const t = fieldSchema(resolved, "type");
36
+ const tag = t !== void 0 && isLiteralSchema(t) ? literalValue(t) : void 0;
37
+ return typeof tag === "string" ? tag : void 0;
38
+ }
39
+ function stripSignedBlobEnvelope(schema, reg = {}) {
40
+ const { schema: resolved } = resolveSchema(schema, {}, reg);
41
+ const hidden = new Set(SIGNED_BLOB_ENVELOPE);
42
+ if (signedBlobTypeTag(schema, reg)) hidden.add("type");
43
+ const { required: _legacy, ...rest } = resolved;
44
+ return { ...rest, properties: fieldsToProperties(structFields(resolved).filter((f) => !hidden.has(f.name))) };
45
+ }
46
+ function signedBlobMessage(blob) {
47
+ return new Uint8Array(encode({ ...blob, sig: new Uint8Array(ZERO_SIGNATURE_LENGTH) }));
48
+ }
49
+ async function signBlob(signer, body, opts = {}) {
50
+ const ipld = dagJsonToIpld(body);
51
+ const principal = new Uint8Array(await signer.getPublicKey());
52
+ const ts = opts.ts ?? Date.now();
53
+ const blob = { ...ipld };
54
+ if (opts.typeTag) blob.type = opts.typeTag;
55
+ blob.signer = principal;
56
+ blob.ts = ts;
57
+ blob.sig = new Uint8Array(await signer.sign(signedBlobMessage(blob)));
58
+ const data = new Uint8Array(encode(blob));
59
+ const digest = await sha256.digest(data);
60
+ return { cid: CID.createV1(code, digest).toString(), data, ts, signer: principal };
61
+ }
62
+ async function publishSignedBlob(client, signer, body, opts = {}) {
63
+ const result = await signBlob(signer, body, opts);
64
+ const collision = findSeedIndexerCollision(result.data);
65
+ if (collision) {
66
+ throw new Error(
67
+ `This blob can't be published: its "type" collides with the built-in Seed "${collision}" blob type but does not match its shape. Use a different type tag.`
68
+ );
69
+ }
70
+ await client.request("PublishBlobs", { blobs: [{ cid: result.cid, data: result.data }] });
71
+ return result;
72
+ }
73
+ function hasSignedEnvelope(value) {
74
+ return !!value && typeof value === "object" && !Array.isArray(value) && SIGNED_BLOB_ENVELOPE.every((k) => k in value);
75
+ }
76
+ function principalToPublicKey(principal) {
77
+ if (principal.length !== 34 || principal[0] !== 237 || principal[1] !== 1) {
78
+ throw new Error(
79
+ `Unsupported principal: expected an Ed25519 multicodec key (34 bytes), got ${principal.length} bytes`
80
+ );
81
+ }
82
+ return principal.slice(2);
83
+ }
84
+ async function verifySignedBlob(value) {
85
+ const ipld = dagJsonToIpld(value);
86
+ const signer = ipld.signer;
87
+ const sig = ipld.sig;
88
+ if (!(signer instanceof Uint8Array)) return { ok: false, signer: "", reason: "signer is not bytes" };
89
+ const signerId = base58btc.encode(signer);
90
+ if (!(sig instanceof Uint8Array)) return { ok: false, signer: signerId, reason: "sig is not bytes" };
91
+ let publicKey;
92
+ try {
93
+ publicKey = principalToPublicKey(signer);
94
+ } catch (error) {
95
+ return { ok: false, signer: signerId, reason: error.message };
96
+ }
97
+ const ts = typeof ipld.ts === "number" ? ipld.ts : void 0;
98
+ try {
99
+ const ok = ed25519.verify(sig, signedBlobMessage(ipld), publicKey);
100
+ return ok ? { ok, signer: signerId, ts } : { ok, signer: signerId, ts, reason: "signature does not verify" };
101
+ } catch (error) {
102
+ return { ok: false, signer: signerId, ts, reason: error.message };
103
+ }
104
+ }
105
+ async function encodeDagCbor(value) {
106
+ const data = new Uint8Array(encode(dagJsonToIpld(value)));
107
+ const digest = await sha256.digest(data);
108
+ return { data, cid: CID.createV1(code, digest).toString() };
109
+ }
20
110
  export {
21
111
  SIGNED_BLOB_ENVELOPE,
22
112
  ZERO_SIGNATURE_LENGTH,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seed-hypermedia/client",
3
- "version": "0.0.123",
3
+ "version": "0.0.124",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/seed-hypermedia/seed",
@@ -1,122 +0,0 @@
1
- import {
2
- fieldSchema,
3
- fieldsToProperties,
4
- isLiteralSchema,
5
- literalValue,
6
- resolveSchema,
7
- structFields
8
- } from "./chunk-UBZRS3WZ.mjs";
9
- import {
10
- dagJsonToIpld,
11
- findSeedIndexerCollision
12
- } from "./chunk-VWSAFDOL.mjs";
13
- import {
14
- code,
15
- encode
16
- } from "./chunk-3TPCJCVO.mjs";
17
-
18
- // src/signed-blob.ts
19
- import { ed25519 } from "@noble/curves/ed25519.js";
20
- import { base58btc } from "multiformats/bases/base58";
21
- import { CID } from "multiformats/cid";
22
- import { sha256 } from "multiformats/hashes/sha2";
23
- var SIGNED_BLOB_ENVELOPE = ["signer", "sig", "ts"];
24
- var ZERO_SIGNATURE_LENGTH = 64;
25
- function isSignedBlobSchema(schema, reg = {}) {
26
- if (!schema) return false;
27
- const { schema: resolved } = resolveSchema(schema, {}, reg);
28
- const props = resolved.properties;
29
- return !!props && SIGNED_BLOB_ENVELOPE.every((k) => fieldSchema(resolved, k) !== void 0);
30
- }
31
- function signedBlobTypeTag(schema, reg = {}) {
32
- const { schema: resolved } = resolveSchema(schema, {}, reg);
33
- const t = fieldSchema(resolved, "type");
34
- const tag = t !== void 0 && isLiteralSchema(t) ? literalValue(t) : void 0;
35
- return typeof tag === "string" ? tag : void 0;
36
- }
37
- function stripSignedBlobEnvelope(schema, reg = {}) {
38
- const { schema: resolved } = resolveSchema(schema, {}, reg);
39
- const hidden = new Set(SIGNED_BLOB_ENVELOPE);
40
- if (signedBlobTypeTag(schema, reg)) hidden.add("type");
41
- const { required: _legacy, ...rest } = resolved;
42
- return { ...rest, properties: fieldsToProperties(structFields(resolved).filter((f) => !hidden.has(f.name))) };
43
- }
44
- function signedBlobMessage(blob) {
45
- return new Uint8Array(encode({ ...blob, sig: new Uint8Array(ZERO_SIGNATURE_LENGTH) }));
46
- }
47
- async function signBlob(signer, body, opts = {}) {
48
- const ipld = dagJsonToIpld(body);
49
- const principal = new Uint8Array(await signer.getPublicKey());
50
- const ts = opts.ts ?? Date.now();
51
- const blob = { ...ipld };
52
- if (opts.typeTag) blob.type = opts.typeTag;
53
- blob.signer = principal;
54
- blob.ts = ts;
55
- blob.sig = new Uint8Array(await signer.sign(signedBlobMessage(blob)));
56
- const data = new Uint8Array(encode(blob));
57
- const digest = await sha256.digest(data);
58
- return { cid: CID.createV1(code, digest).toString(), data, ts, signer: principal };
59
- }
60
- async function publishSignedBlob(client, signer, body, opts = {}) {
61
- const result = await signBlob(signer, body, opts);
62
- const collision = findSeedIndexerCollision(result.data);
63
- if (collision) {
64
- throw new Error(
65
- `This blob can't be published: its "type" collides with the built-in Seed "${collision}" blob type but does not match its shape. Use a different type tag.`
66
- );
67
- }
68
- await client.request("PublishBlobs", { blobs: [{ cid: result.cid, data: result.data }] });
69
- return result;
70
- }
71
- function hasSignedEnvelope(value) {
72
- return !!value && typeof value === "object" && !Array.isArray(value) && SIGNED_BLOB_ENVELOPE.every((k) => k in value);
73
- }
74
- function principalToPublicKey(principal) {
75
- if (principal.length !== 34 || principal[0] !== 237 || principal[1] !== 1) {
76
- throw new Error(
77
- `Unsupported principal: expected an Ed25519 multicodec key (34 bytes), got ${principal.length} bytes`
78
- );
79
- }
80
- return principal.slice(2);
81
- }
82
- async function verifySignedBlob(value) {
83
- const ipld = dagJsonToIpld(value);
84
- const signer = ipld.signer;
85
- const sig = ipld.sig;
86
- if (!(signer instanceof Uint8Array)) return { ok: false, signer: "", reason: "signer is not bytes" };
87
- const signerId = base58btc.encode(signer);
88
- if (!(sig instanceof Uint8Array)) return { ok: false, signer: signerId, reason: "sig is not bytes" };
89
- let publicKey;
90
- try {
91
- publicKey = principalToPublicKey(signer);
92
- } catch (error) {
93
- return { ok: false, signer: signerId, reason: error.message };
94
- }
95
- const ts = typeof ipld.ts === "number" ? ipld.ts : void 0;
96
- try {
97
- const ok = ed25519.verify(sig, signedBlobMessage(ipld), publicKey);
98
- return ok ? { ok, signer: signerId, ts } : { ok, signer: signerId, ts, reason: "signature does not verify" };
99
- } catch (error) {
100
- return { ok: false, signer: signerId, ts, reason: error.message };
101
- }
102
- }
103
- async function encodeDagCbor(value) {
104
- const data = new Uint8Array(encode(dagJsonToIpld(value)));
105
- const digest = await sha256.digest(data);
106
- return { data, cid: CID.createV1(code, digest).toString() };
107
- }
108
-
109
- export {
110
- SIGNED_BLOB_ENVELOPE,
111
- ZERO_SIGNATURE_LENGTH,
112
- isSignedBlobSchema,
113
- signedBlobTypeTag,
114
- stripSignedBlobEnvelope,
115
- signedBlobMessage,
116
- signBlob,
117
- publishSignedBlob,
118
- hasSignedEnvelope,
119
- principalToPublicKey,
120
- verifySignedBlob,
121
- encodeDagCbor
122
- };