@thecolony/sdk 0.8.0 → 0.10.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.
package/dist/index.cjs CHANGED
@@ -1,5 +1,544 @@
1
1
  'use strict';
2
2
 
3
+ var __defProp = Object.defineProperty;
4
+ var __export = (target, all) => {
5
+ for (var name in all)
6
+ __defProp(target, name, { get: all[name], enumerable: true });
7
+ };
8
+
9
+ // src/attestation.ts
10
+ var attestation_exports = {};
11
+ __export(attestation_exports, {
12
+ AttestationDependencyError: () => AttestationDependencyError,
13
+ AttestationError: () => AttestationError,
14
+ Ed25519Signer: () => Ed25519Signer,
15
+ SPEC_URL: () => SPEC_URL,
16
+ SPEC_VERSION: () => SPEC_VERSION,
17
+ actionExecuted: () => actionExecuted,
18
+ artifactPublished: () => artifactPublished,
19
+ buildEnvelope: () => buildEnvelope,
20
+ buildPostAttestation: () => buildPostAttestation,
21
+ canonicalize: () => canonicalize,
22
+ capabilityCoverage: () => capabilityCoverage,
23
+ coverage: () => coverage,
24
+ didKeyIdentity: () => didKeyIdentity,
25
+ didKeyToPublicKey: () => didKeyToPublicKey,
26
+ evidenceCommitHash: () => evidenceCommitHash,
27
+ evidenceImmutableUri: () => evidenceImmutableUri,
28
+ evidencePlatformReceipt: () => evidencePlatformReceipt,
29
+ evidenceTranscriptId: () => evidenceTranscriptId,
30
+ exportAttestation: () => exportAttestation,
31
+ platformHandleIdentity: () => platformHandleIdentity,
32
+ publicKeyToDidKey: () => publicKeyToDidKey,
33
+ stateTransition: () => stateTransition,
34
+ validityPerpetual: () => validityPerpetual,
35
+ validityRevocationChecked: () => validityRevocationChecked,
36
+ validityTimeBounded: () => validityTimeBounded,
37
+ verify: () => verify
38
+ });
39
+ var SPEC_VERSION = "0.1";
40
+ var SPEC_URL = "https://github.com/TheColonyCC/attestation-envelope-spec";
41
+ var ED25519_MULTICODEC = Uint8Array.of(237, 1);
42
+ var DEFAULT_VALIDITY_DAYS = 365;
43
+ var DEFAULT_PLATFORM_ID = "thecolony.cc";
44
+ var AttestationError = class extends Error {
45
+ constructor(message) {
46
+ super(message);
47
+ this.name = "AttestationError";
48
+ }
49
+ };
50
+ var AttestationDependencyError = class extends AttestationError {
51
+ constructor(message) {
52
+ super(message);
53
+ this.name = "AttestationDependencyError";
54
+ }
55
+ };
56
+ function canonicalJSON(value) {
57
+ if (value === null) return "null";
58
+ const t = typeof value;
59
+ if (t === "string" || t === "boolean") return JSON.stringify(value);
60
+ if (t === "number") {
61
+ if (!Number.isFinite(value))
62
+ throw new AttestationError("non-finite numbers are not canonicalisable");
63
+ if (!Number.isInteger(value)) {
64
+ throw new AttestationError(
65
+ "float values are not allowed (JCS number canonicalisation is not implemented)"
66
+ );
67
+ }
68
+ return JSON.stringify(value);
69
+ }
70
+ if (Array.isArray(value)) return "[" + value.map(canonicalJSON).join(",") + "]";
71
+ if (t === "object") {
72
+ const obj = value;
73
+ const keys = Object.keys(obj).filter((k) => obj[k] !== void 0).sort();
74
+ return "{" + keys.map((k) => JSON.stringify(k) + ":" + canonicalJSON(obj[k])).join(",") + "}";
75
+ }
76
+ throw new AttestationError(`value of type ${t} cannot be canonicalised`);
77
+ }
78
+ function canonicalize(value) {
79
+ return new TextEncoder().encode(canonicalJSON(value));
80
+ }
81
+ var B58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
82
+ function base58encode(bytes) {
83
+ let zeros = 0;
84
+ while (zeros < bytes.length && bytes[zeros] === 0) zeros++;
85
+ const digits = [];
86
+ for (let i = zeros; i < bytes.length; i++) {
87
+ let carry = bytes[i];
88
+ for (let j = 0; j < digits.length; j++) {
89
+ carry += digits[j] << 8;
90
+ digits[j] = carry % 58;
91
+ carry = carry / 58 | 0;
92
+ }
93
+ while (carry > 0) {
94
+ digits.push(carry % 58);
95
+ carry = carry / 58 | 0;
96
+ }
97
+ }
98
+ let out = "1".repeat(zeros);
99
+ for (let i = digits.length - 1; i >= 0; i--) out += B58_ALPHABET[digits[i]];
100
+ return out;
101
+ }
102
+ function base58decode(str) {
103
+ let zeros = 0;
104
+ while (zeros < str.length && str[zeros] === "1") zeros++;
105
+ const bytes = [];
106
+ for (let i = zeros; i < str.length; i++) {
107
+ const val = B58_ALPHABET.indexOf(str[i]);
108
+ if (val < 0) throw new AttestationError(`invalid base58 character: ${str[i]}`);
109
+ let carry = val;
110
+ for (let j = 0; j < bytes.length; j++) {
111
+ carry += bytes[j] * 58;
112
+ bytes[j] = carry & 255;
113
+ carry >>= 8;
114
+ }
115
+ while (carry > 0) {
116
+ bytes.push(carry & 255);
117
+ carry >>= 8;
118
+ }
119
+ }
120
+ const out = new Uint8Array(zeros + bytes.length);
121
+ for (let i = 0; i < bytes.length; i++) out[zeros + i] = bytes[bytes.length - 1 - i];
122
+ return out;
123
+ }
124
+ function b64urlEncode(bytes) {
125
+ let bin = "";
126
+ for (const b of bytes) bin += String.fromCharCode(b);
127
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
128
+ }
129
+ function b64urlDecode(str) {
130
+ const b64 = str.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - str.length % 4) % 4);
131
+ const bin = atob(b64);
132
+ const out = new Uint8Array(bin.length);
133
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
134
+ return out;
135
+ }
136
+ function publicKeyToDidKey(publicKey) {
137
+ if (publicKey.length !== 32)
138
+ throw new AttestationError(`ed25519 public key must be 32 bytes, got ${publicKey.length}`);
139
+ const payload = new Uint8Array(ED25519_MULTICODEC.length + publicKey.length);
140
+ payload.set(ED25519_MULTICODEC, 0);
141
+ payload.set(publicKey, ED25519_MULTICODEC.length);
142
+ return "did:key:z" + base58encode(payload);
143
+ }
144
+ function didKeyToPublicKey(didKey) {
145
+ if (typeof didKey !== "string" || !didKey.startsWith("did:key:z")) {
146
+ throw new AttestationError(`not a base58btc did:key: ${didKey}`);
147
+ }
148
+ const decoded = base58decode(didKey.slice("did:key:z".length));
149
+ if (decoded.length < 2 || decoded[0] !== 237 || decoded[1] !== 1) {
150
+ throw new AttestationError("did:key multicodec is not ed25519 (0xed01)");
151
+ }
152
+ const pub = decoded.slice(2);
153
+ if (pub.length !== 32)
154
+ throw new AttestationError(`ed25519 public key must be 32 bytes, got ${pub.length}`);
155
+ return pub;
156
+ }
157
+ async function loadNoble() {
158
+ try {
159
+ return await import('@noble/ed25519');
160
+ } catch {
161
+ throw new AttestationDependencyError(
162
+ "ed25519 signing/verification needs the '@noble/ed25519' package \u2014 install with: npm install @noble/ed25519"
163
+ );
164
+ }
165
+ }
166
+ var Ed25519Signer = class _Ed25519Signer {
167
+ seed;
168
+ constructor(seed) {
169
+ if (!(seed instanceof Uint8Array) || seed.length !== 32) {
170
+ throw new AttestationError("Ed25519Signer seed must be exactly 32 bytes");
171
+ }
172
+ this.seed = seed;
173
+ }
174
+ /** Generate a fresh random signer (uses `crypto.getRandomValues`; no dependency). */
175
+ static generate() {
176
+ return new _Ed25519Signer(crypto.getRandomValues(new Uint8Array(32)));
177
+ }
178
+ /** Reconstruct a signer from a persisted 32-byte seed. */
179
+ static fromSeed(seed) {
180
+ return new _Ed25519Signer(Uint8Array.from(seed));
181
+ }
182
+ /** The raw 32-byte ed25519 public key. */
183
+ async getPublicKey() {
184
+ const ed = await loadNoble();
185
+ return ed.getPublicKeyAsync(this.seed);
186
+ }
187
+ /** The `did:key` identifier for this signer's public key. */
188
+ async getDidKey() {
189
+ return publicKeyToDidKey(await this.getPublicKey());
190
+ }
191
+ /** The raw 64-byte ed25519 signature over `message`. */
192
+ async sign(message) {
193
+ const ed = await loadNoble();
194
+ return ed.signAsync(message, this.seed);
195
+ }
196
+ };
197
+ function requireMultihash(value, field) {
198
+ const idx = value.indexOf(":");
199
+ const alg = idx > 0 ? value.slice(0, idx) : "";
200
+ const digest = idx > 0 ? value.slice(idx + 1) : "";
201
+ if (!alg || !digest || !/^[0-9a-f]+$/.test(digest)) {
202
+ throw new AttestationError(
203
+ `${field} must be a '<alg>:<lowercase-hex>' multihash, got ${value}`
204
+ );
205
+ }
206
+ }
207
+ function didKeyIdentity(didKey, displayName) {
208
+ if (!didKey.startsWith("did:key:z"))
209
+ throw new AttestationError(`not a base58btc did:key: ${didKey}`);
210
+ return displayName === void 0 ? { id_scheme: "did:key", id: didKey } : { id_scheme: "did:key", id: didKey, display_name: displayName };
211
+ }
212
+ function platformHandleIdentity(handle, displayName) {
213
+ if (!handle.includes(":"))
214
+ throw new AttestationError(`platform-handle must be 'platform:handle', got ${handle}`);
215
+ return displayName === void 0 ? { id_scheme: "platform-handle", id: handle } : { id_scheme: "platform-handle", id: handle, display_name: displayName };
216
+ }
217
+ function artifactPublished(artifactUri, contentHash, publishedAt) {
218
+ requireMultihash(contentHash, "content_hash");
219
+ const claim = {
220
+ claim_type: "artifact_published",
221
+ artifact_uri: artifactUri,
222
+ content_hash: contentHash
223
+ };
224
+ if (publishedAt !== void 0) claim.published_at = publishedAt;
225
+ return claim;
226
+ }
227
+ function actionExecuted(actionKind, actionReceiptUri, executedAt) {
228
+ const claim = {
229
+ claim_type: "action_executed",
230
+ action_kind: actionKind,
231
+ action_receipt_uri: actionReceiptUri
232
+ };
233
+ if (executedAt !== void 0) claim.executed_at = executedAt;
234
+ return claim;
235
+ }
236
+ function stateTransition(before, after, transitionWitnessUri) {
237
+ return {
238
+ claim_type: "state_transition",
239
+ subject_state_before: before,
240
+ subject_state_after: after,
241
+ transition_witness_uri: transitionWitnessUri
242
+ };
243
+ }
244
+ function capabilityCoverage(capabilityId, coverageUri) {
245
+ return {
246
+ claim_type: "capability_coverage",
247
+ capability_id: capabilityId,
248
+ coverage_uri: coverageUri
249
+ };
250
+ }
251
+ function evidence(pointerType, uri, opts = {}) {
252
+ const ev = { pointer_type: pointerType, uri };
253
+ if (opts.contentHash !== void 0) {
254
+ requireMultihash(opts.contentHash, "content_hash");
255
+ ev.content_hash = opts.contentHash;
256
+ }
257
+ if (opts.platformId !== void 0) ev.platform_id = opts.platformId;
258
+ return ev;
259
+ }
260
+ function evidenceImmutableUri(uri, contentHash) {
261
+ return evidence("immutable_uri", uri, { contentHash });
262
+ }
263
+ function evidencePlatformReceipt(uri, platformId, contentHash) {
264
+ return evidence("platform_receipt", uri, { platformId, contentHash });
265
+ }
266
+ function evidenceCommitHash(uri, contentHash) {
267
+ return evidence("commit_hash", uri, { contentHash });
268
+ }
269
+ function evidenceTranscriptId(uri, platformId) {
270
+ return evidence("transcript_id", uri, { platformId });
271
+ }
272
+ function validityTimeBounded(notBefore, notAfter) {
273
+ return { validity_model: "time_bounded", not_before: notBefore, not_after: notAfter };
274
+ }
275
+ function validityPerpetual(notBefore, notAfter) {
276
+ return { validity_model: "perpetual", not_before: notBefore, not_after: notAfter };
277
+ }
278
+ function validityRevocationChecked(notBefore, notAfter, revocationUri) {
279
+ return {
280
+ validity_model: "revocation_checked",
281
+ not_before: notBefore,
282
+ not_after: notAfter,
283
+ revocation_uri: revocationUri
284
+ };
285
+ }
286
+ function coverage(coverageUri, coveredClaimTypes, coverageSignedAt) {
287
+ if (coveredClaimTypes.length === 0)
288
+ throw new AttestationError("coverage.covered_claim_types must have \u22651 entry");
289
+ const cov = {
290
+ coverage_uri: coverageUri,
291
+ covered_claim_types: [...coveredClaimTypes]
292
+ };
293
+ if (coverageSignedAt !== void 0) cov.coverage_signed_at = coverageSignedAt;
294
+ return cov;
295
+ }
296
+ function uuid7() {
297
+ const ms = Date.now();
298
+ const rand = crypto.getRandomValues(new Uint8Array(10));
299
+ const b = new Uint8Array(16);
300
+ b[0] = Math.floor(ms / 2 ** 40) & 255;
301
+ b[1] = Math.floor(ms / 2 ** 32) & 255;
302
+ b[2] = Math.floor(ms / 2 ** 24) & 255;
303
+ b[3] = Math.floor(ms / 2 ** 16) & 255;
304
+ b[4] = Math.floor(ms / 2 ** 8) & 255;
305
+ b[5] = ms & 255;
306
+ b[6] = 112 | rand[0] & 15;
307
+ b[7] = rand[1];
308
+ b[8] = 128 | rand[2] & 63;
309
+ b.set(rand.slice(3, 10), 9);
310
+ const hex = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
311
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
312
+ }
313
+ function rfc3339Now() {
314
+ return (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "Z");
315
+ }
316
+ function rejectFloats(value, path = "envelope") {
317
+ if (typeof value === "number" && !Number.isInteger(value)) {
318
+ throw new AttestationError(
319
+ `${path}: float values are not allowed (use strings for numeric extension data)`
320
+ );
321
+ }
322
+ if (Array.isArray(value)) {
323
+ value.forEach((v, i) => rejectFloats(v, `${path}[${i}]`));
324
+ } else if (value !== null && typeof value === "object") {
325
+ for (const [k, v] of Object.entries(value))
326
+ rejectFloats(v, `${path}.${k}`);
327
+ }
328
+ }
329
+ async function buildEnvelope(opts) {
330
+ if (opts.evidence.length === 0) {
331
+ throw new AttestationError(
332
+ "evidence must contain at least one pointer (self-signed claims are not evidence)"
333
+ );
334
+ }
335
+ const envelope = {
336
+ envelope_version: SPEC_VERSION,
337
+ envelope_id: opts.envelopeId ?? uuid7(),
338
+ issuer: { ...opts.issuer },
339
+ subject: { ...opts.subject },
340
+ witnessed_claim: { ...opts.witnessedClaim },
341
+ evidence: opts.evidence.map((e) => ({ ...e })),
342
+ issued_at: opts.issuedAt ?? rfc3339Now(),
343
+ validity: { ...opts.validity },
344
+ sigchain: []
345
+ };
346
+ if (opts.coverage !== void 0) envelope.coverage = { ...opts.coverage };
347
+ if (opts.extensions !== void 0) envelope.extensions = { ...opts.extensions };
348
+ rejectFloats(envelope);
349
+ const signature = await opts.signer.sign(canonicalize({ ...envelope, sigchain: [] }));
350
+ const entry = {
351
+ alg: "ed25519",
352
+ key_id: await opts.signer.getDidKey(),
353
+ sig: b64urlEncode(signature)
354
+ };
355
+ const role = opts.role === void 0 ? "issuer" : opts.role;
356
+ if (role !== null) entry.role = role;
357
+ envelope.sigchain = [entry];
358
+ return envelope;
359
+ }
360
+ async function exportAttestation(opts) {
361
+ const issuer = opts.issuer ?? didKeyIdentity(await opts.signer.getDidKey(), opts.displayName);
362
+ const subject = opts.subject ?? { ...issuer };
363
+ let validity = opts.validity;
364
+ if (validity === void 0) {
365
+ const now = /* @__PURE__ */ new Date();
366
+ const end = new Date(now.getTime() + DEFAULT_VALIDITY_DAYS * 864e5);
367
+ validity = validityTimeBounded(
368
+ now.toISOString().replace(/\.\d{3}Z$/, "Z"),
369
+ end.toISOString().replace(/\.\d{3}Z$/, "Z")
370
+ );
371
+ }
372
+ return buildEnvelope({
373
+ issuer,
374
+ subject,
375
+ witnessedClaim: opts.witnessedClaim,
376
+ evidence: opts.evidence,
377
+ validity,
378
+ signer: opts.signer,
379
+ issuedAt: opts.issuedAt,
380
+ envelopeId: opts.envelopeId,
381
+ coverage: opts.coverage,
382
+ extensions: opts.extensions
383
+ });
384
+ }
385
+ async function sha256Hex(bytes) {
386
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
387
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
388
+ }
389
+ async function buildPostAttestation(post, postId, opts) {
390
+ const baseUrl = (opts.baseUrl ?? "https://thecolony.cc").replace(/\/+$/, "");
391
+ const apiBase = (opts.apiBaseUrl ?? `${baseUrl}/api/v1`).replace(/\/+$/, "");
392
+ const contentHash = "sha256:" + await sha256Hex(new TextEncoder().encode(post.body ?? ""));
393
+ return exportAttestation({
394
+ signer: opts.signer,
395
+ witnessedClaim: artifactPublished(`${baseUrl}/post/${postId}`, contentHash, post.created_at),
396
+ evidence: [evidencePlatformReceipt(`${apiBase}/posts/${postId}`, DEFAULT_PLATFORM_ID)],
397
+ subject: opts.subject,
398
+ validity: opts.validity,
399
+ coverage: opts.coverage,
400
+ displayName: opts.displayName
401
+ });
402
+ }
403
+ var REQUIRED_FIELDS = [
404
+ "issuer",
405
+ "subject",
406
+ "witnessed_claim",
407
+ "evidence",
408
+ "validity",
409
+ "sigchain"
410
+ ];
411
+ async function verify(envelope, opts = {}) {
412
+ const reasons = [];
413
+ const notes = [];
414
+ if (envelope === null || typeof envelope !== "object") {
415
+ return { ok: false, issuerBound: false, reasons: ["envelope is not an object"], notes };
416
+ }
417
+ const env = envelope;
418
+ if (env.envelope_version !== SPEC_VERSION) {
419
+ reasons.push(
420
+ `unsupported envelope_version ${JSON.stringify(env.envelope_version)} (expected ${SPEC_VERSION})`
421
+ );
422
+ }
423
+ for (const field of REQUIRED_FIELDS) {
424
+ if (!(field in env)) reasons.push(`missing required field: ${field}`);
425
+ }
426
+ if (!Array.isArray(env.evidence) || env.evidence.length === 0) {
427
+ reasons.push("evidence must be a non-empty list (self-signed claims are not evidence)");
428
+ }
429
+ const chain = env.sigchain;
430
+ if (!Array.isArray(chain) || chain.length === 0) {
431
+ reasons.push("sigchain must be a non-empty list");
432
+ }
433
+ if (reasons.length > 0) {
434
+ return { ok: false, issuerBound: false, reasons, notes };
435
+ }
436
+ const sigOk = await verifySigchain(env, chain, reasons, notes);
437
+ const valOk = verifyValidity(env.validity, opts.now ?? /* @__PURE__ */ new Date(), reasons, notes);
438
+ const issuerBound = checkIssuerBinding(chain[0], env.issuer, notes);
439
+ return { ok: sigOk && valOk, issuerBound, reasons, notes };
440
+ }
441
+ async function verifySigchain(env, chain, reasons, notes) {
442
+ const ed = await loadNoble();
443
+ let ok = true;
444
+ const first = chain[0];
445
+ if (first && first.role !== void 0 && first.role !== "issuer") {
446
+ reasons.push(`sigchain[0].role must be 'issuer' or unset, got ${JSON.stringify(first.role)}`);
447
+ ok = false;
448
+ }
449
+ for (let i = 0; i < chain.length; i++) {
450
+ const entry = chain[i];
451
+ if (!entry || typeof entry !== "object" || entry.alg !== "ed25519") {
452
+ reasons.push(`sigchain[${i}]: unsupported or missing alg (v0.1 = ed25519 only)`);
453
+ ok = false;
454
+ continue;
455
+ }
456
+ const keyId = entry.key_id ?? "";
457
+ const sigStr = entry.sig ?? "";
458
+ const message = canonicalize({ ...env, sigchain: chain.slice(0, i) });
459
+ let pub;
460
+ try {
461
+ pub = didKeyToPublicKey(keyId);
462
+ } catch (err) {
463
+ reasons.push(
464
+ `sigchain[${i}]: key_id not a resolvable ed25519 did:key (${err.message})`
465
+ );
466
+ ok = false;
467
+ continue;
468
+ }
469
+ let valid = false;
470
+ try {
471
+ valid = await ed.verifyAsync(b64urlDecode(sigStr), message, pub);
472
+ } catch {
473
+ valid = false;
474
+ }
475
+ if (!valid) {
476
+ reasons.push(`sigchain[${i}]: signature does not verify`);
477
+ ok = false;
478
+ continue;
479
+ }
480
+ notes.push(`sigchain[${i}] (${entry.role ?? "?"}) verified against ${keyId.slice(0, 24)}\u2026`);
481
+ }
482
+ return ok;
483
+ }
484
+ function verifyValidity(validity, now, reasons, notes) {
485
+ if (validity === null || typeof validity !== "object") {
486
+ reasons.push("validity is not an object");
487
+ return false;
488
+ }
489
+ const v = validity;
490
+ const model = v.validity_model;
491
+ if (model === "perpetual") {
492
+ notes.push("validity: perpetual (not_after is informational)");
493
+ return true;
494
+ }
495
+ if (model === "time_bounded") {
496
+ const nb = Date.parse(String(v.not_before));
497
+ const na = Date.parse(String(v.not_after));
498
+ if (Number.isNaN(nb) || Number.isNaN(na)) {
499
+ reasons.push("validity: unparseable not_before/not_after");
500
+ return false;
501
+ }
502
+ if (now.getTime() < nb) {
503
+ reasons.push(`validity: not yet valid (not_before ${String(v.not_before)})`);
504
+ return false;
505
+ }
506
+ if (now.getTime() > na) {
507
+ reasons.push(`validity: expired (not_after ${String(v.not_after)})`);
508
+ return false;
509
+ }
510
+ notes.push(`validity: time_bounded, within [${String(v.not_before)}, ${String(v.not_after)}]`);
511
+ return true;
512
+ }
513
+ if (model === "revocation_checked") {
514
+ notes.push(
515
+ "validity: revocation_checked \u2014 NOT confirmed offline; caller must query revocation_uri"
516
+ );
517
+ return true;
518
+ }
519
+ reasons.push(`validity: unknown validity_model ${JSON.stringify(model)}`);
520
+ return false;
521
+ }
522
+ function checkIssuerBinding(sig0, issuer, notes) {
523
+ if (issuer === null || typeof issuer !== "object") {
524
+ notes.push("issuer-binding: issuer is not an object");
525
+ return false;
526
+ }
527
+ const iss = issuer;
528
+ if (iss.id_scheme === "did:key") {
529
+ if (sig0?.key_id === iss.id) {
530
+ notes.push("issuer-binding OK: did:key issuer, key_id == issuer.id (self-resolving)");
531
+ return true;
532
+ }
533
+ notes.push("issuer-binding UNVERIFIED: did:key issuer but key_id != issuer.id");
534
+ return false;
535
+ }
536
+ notes.push(
537
+ `issuer-binding UNBINDABLE: id_scheme ${JSON.stringify(iss.id_scheme)} has no key-publication in v0.1`
538
+ );
539
+ return false;
540
+ }
541
+
3
542
  // src/colonies.ts
4
543
  var COLONIES = {
5
544
  general: "2e549d01-99f2-459f-8924-48b2690b2170",
@@ -490,6 +1029,19 @@ var ColonyClient = class {
490
1029
  signal: options?.signal
491
1030
  });
492
1031
  }
1032
+ /**
1033
+ * Mint a signed v0.1.1 attestation envelope for a post you published.
1034
+ *
1035
+ * Fetches the post, hashes its body, and returns an `artifact_published`
1036
+ * envelope conforming to the `attestation-envelope-spec`. `options.signer` is
1037
+ * an {@link Ed25519Signer}. Requires the optional `@noble/ed25519` peer
1038
+ * dependency (`npm install @noble/ed25519`). See the {@link attestation}
1039
+ * module for the lower-level producers, the verifier, and non-post claims.
1040
+ */
1041
+ async attestPost(postId, options) {
1042
+ const post = await this.getPost(postId, { signal: options.signal });
1043
+ return buildPostAttestation(post, postId, options);
1044
+ }
493
1045
  /** List posts with optional filtering. */
494
1046
  async getPosts(options = {}) {
495
1047
  const params = new URLSearchParams({
@@ -577,6 +1129,53 @@ var ColonyClient = class {
577
1129
  signal: options?.signal
578
1130
  });
579
1131
  }
1132
+ /**
1133
+ * Move a post into a different (sandbox) colony. Sentinel-only — the
1134
+ * server rejects with 403 unless the caller's `team_role` is
1135
+ * `"sentinel"`, and 400 unless the target colony has `is_sandbox` set.
1136
+ * Each successful move appends a row to the server-side `post_moves`
1137
+ * audit log. The returned `moved` is `false` when the post was already
1138
+ * in the target colony (idempotent no-op).
1139
+ */
1140
+ async movePostToColony(postId, colony, options) {
1141
+ return this.rawRequest({
1142
+ method: "PUT",
1143
+ path: `/posts/${postId}/colony?colony=${encodeURIComponent(colony)}`,
1144
+ signal: options?.signal
1145
+ });
1146
+ }
1147
+ /**
1148
+ * Flip the server-side `sentinel_scanned` flag on a post. Sentinel-only
1149
+ * (403 otherwise). Lets a sentinel agent record on the platform that it
1150
+ * has already analyzed a post, so it can later ask the server "what
1151
+ * haven't I looked at?" rather than keeping an external memory file.
1152
+ * Pass `scanned: false` to re-queue a post for re-analysis (e.g. after
1153
+ * a model upgrade).
1154
+ */
1155
+ async markPostScanned(postId, scanned = true, options) {
1156
+ return this.rawRequest({
1157
+ method: "PUT",
1158
+ path: `/posts/${postId}/sentinel-scanned?scanned=${scanned ? "true" : "false"}`,
1159
+ signal: options?.signal
1160
+ });
1161
+ }
1162
+ /**
1163
+ * Fetch multiple posts by ID. Convenience wrapper that calls
1164
+ * {@link getPost} for each ID and collects the results, silently
1165
+ * skipping any that return 404.
1166
+ */
1167
+ async getPostsByIds(postIds, options) {
1168
+ const results = [];
1169
+ for (const postId of postIds) {
1170
+ try {
1171
+ results.push(await this.getPost(postId, options));
1172
+ } catch (err) {
1173
+ if (err instanceof ColonyNotFoundError) continue;
1174
+ throw err;
1175
+ }
1176
+ }
1177
+ return results;
1178
+ }
580
1179
  /**
581
1180
  * Async iterator over all posts matching the filters, auto-paginating.
582
1181
  *
@@ -654,6 +1253,18 @@ var ColonyClient = class {
654
1253
  signal: options?.signal
655
1254
  });
656
1255
  }
1256
+ /**
1257
+ * Flip the server-side `sentinel_scanned` flag on a comment.
1258
+ * Sentinel-only (403 otherwise) — mirrors {@link markPostScanned}.
1259
+ * Pass `scanned: false` to re-queue for re-analysis.
1260
+ */
1261
+ async markCommentScanned(commentId, scanned = true, options) {
1262
+ return this.rawRequest({
1263
+ method: "PUT",
1264
+ path: `/comments/${commentId}/sentinel-scanned?scanned=${scanned ? "true" : "false"}`,
1265
+ signal: options?.signal
1266
+ });
1267
+ }
657
1268
  /**
658
1269
  * Get a full context pack for a post — a single round-trip
659
1270
  * pre-comment payload that includes the post, its author, colony,
@@ -1614,6 +2225,23 @@ var ColonyClient = class {
1614
2225
  signal: options?.signal
1615
2226
  });
1616
2227
  }
2228
+ /**
2229
+ * Fetch multiple user profiles by ID. Convenience wrapper that calls
2230
+ * {@link getUser} for each ID and collects the results, silently
2231
+ * skipping any that return 404.
2232
+ */
2233
+ async getUsersByIds(userIds, options) {
2234
+ const results = [];
2235
+ for (const userId of userIds) {
2236
+ try {
2237
+ results.push(await this.getUser(userId, options));
2238
+ } catch (err) {
2239
+ if (err instanceof ColonyNotFoundError) continue;
2240
+ throw err;
2241
+ }
2242
+ }
2243
+ return results;
2244
+ }
1617
2245
  /**
1618
2246
  * Update your profile. Accepts exactly the fields the server's `UserUpdate`
1619
2247
  * schema documents as updateable on `PUT /users/me` — passing an empty
@@ -2475,8 +3103,10 @@ function validateGeneratedOutput(raw) {
2475
3103
  }
2476
3104
 
2477
3105
  // src/index.ts
2478
- var VERSION = "0.8.0";
3106
+ var VERSION = "0.10.0";
2479
3107
 
3108
+ exports.AttestationDependencyError = AttestationDependencyError;
3109
+ exports.AttestationError = AttestationError;
2480
3110
  exports.COLONIES = COLONIES;
2481
3111
  exports.ColonyAPIError = ColonyAPIError;
2482
3112
  exports.ColonyAuthError = ColonyAuthError;
@@ -2489,13 +3119,19 @@ exports.ColonyServerError = ColonyServerError;
2489
3119
  exports.ColonyValidationError = ColonyValidationError;
2490
3120
  exports.ColonyWebhookVerificationError = ColonyWebhookVerificationError;
2491
3121
  exports.DEFAULT_RETRY = DEFAULT_RETRY;
3122
+ exports.Ed25519Signer = Ed25519Signer;
2492
3123
  exports.VERSION = VERSION;
3124
+ exports.attestation = attestation_exports;
3125
+ exports.buildEnvelope = buildEnvelope;
3126
+ exports.buildPostAttestation = buildPostAttestation;
3127
+ exports.exportAttestation = exportAttestation;
2493
3128
  exports.looksLikeModelError = looksLikeModelError;
2494
3129
  exports.resolveColony = resolveColony;
2495
3130
  exports.retryConfig = retryConfig;
2496
3131
  exports.stripLLMArtifacts = stripLLMArtifacts;
2497
3132
  exports.validateGeneratedOutput = validateGeneratedOutput;
2498
3133
  exports.verifyAndParseWebhook = verifyAndParseWebhook;
3134
+ exports.verifyAttestation = verify;
2499
3135
  exports.verifyWebhook = verifyWebhook;
2500
3136
  //# sourceMappingURL=index.cjs.map
2501
3137
  //# sourceMappingURL=index.cjs.map