@thecolony/sdk 0.9.0 → 0.11.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/CHANGELOG.md +23 -0
- package/README.md +47 -0
- package/dist/index.cjs +696 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +432 -3
- package/dist/index.d.ts +432 -3
- package/dist/index.js +689 -2
- package/dist/index.js.map +1 -1
- package/package.json +10 -1
package/dist/index.js
CHANGED
|
@@ -1,3 +1,542 @@
|
|
|
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
|
+
// src/attestation.ts
|
|
8
|
+
var attestation_exports = {};
|
|
9
|
+
__export(attestation_exports, {
|
|
10
|
+
AttestationDependencyError: () => AttestationDependencyError,
|
|
11
|
+
AttestationError: () => AttestationError,
|
|
12
|
+
Ed25519Signer: () => Ed25519Signer,
|
|
13
|
+
SPEC_URL: () => SPEC_URL,
|
|
14
|
+
SPEC_VERSION: () => SPEC_VERSION,
|
|
15
|
+
actionExecuted: () => actionExecuted,
|
|
16
|
+
artifactPublished: () => artifactPublished,
|
|
17
|
+
buildEnvelope: () => buildEnvelope,
|
|
18
|
+
buildPostAttestation: () => buildPostAttestation,
|
|
19
|
+
canonicalize: () => canonicalize,
|
|
20
|
+
capabilityCoverage: () => capabilityCoverage,
|
|
21
|
+
coverage: () => coverage,
|
|
22
|
+
didKeyIdentity: () => didKeyIdentity,
|
|
23
|
+
didKeyToPublicKey: () => didKeyToPublicKey,
|
|
24
|
+
evidenceCommitHash: () => evidenceCommitHash,
|
|
25
|
+
evidenceImmutableUri: () => evidenceImmutableUri,
|
|
26
|
+
evidencePlatformReceipt: () => evidencePlatformReceipt,
|
|
27
|
+
evidenceTranscriptId: () => evidenceTranscriptId,
|
|
28
|
+
exportAttestation: () => exportAttestation,
|
|
29
|
+
platformHandleIdentity: () => platformHandleIdentity,
|
|
30
|
+
publicKeyToDidKey: () => publicKeyToDidKey,
|
|
31
|
+
stateTransition: () => stateTransition,
|
|
32
|
+
validityPerpetual: () => validityPerpetual,
|
|
33
|
+
validityRevocationChecked: () => validityRevocationChecked,
|
|
34
|
+
validityTimeBounded: () => validityTimeBounded,
|
|
35
|
+
verify: () => verify
|
|
36
|
+
});
|
|
37
|
+
var SPEC_VERSION = "0.1";
|
|
38
|
+
var SPEC_URL = "https://github.com/TheColonyCC/attestation-envelope-spec";
|
|
39
|
+
var ED25519_MULTICODEC = Uint8Array.of(237, 1);
|
|
40
|
+
var DEFAULT_VALIDITY_DAYS = 365;
|
|
41
|
+
var DEFAULT_PLATFORM_ID = "thecolony.cc";
|
|
42
|
+
var AttestationError = class extends Error {
|
|
43
|
+
constructor(message) {
|
|
44
|
+
super(message);
|
|
45
|
+
this.name = "AttestationError";
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
var AttestationDependencyError = class extends AttestationError {
|
|
49
|
+
constructor(message) {
|
|
50
|
+
super(message);
|
|
51
|
+
this.name = "AttestationDependencyError";
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
function canonicalJSON(value) {
|
|
55
|
+
if (value === null) return "null";
|
|
56
|
+
const t = typeof value;
|
|
57
|
+
if (t === "string" || t === "boolean") return JSON.stringify(value);
|
|
58
|
+
if (t === "number") {
|
|
59
|
+
if (!Number.isFinite(value))
|
|
60
|
+
throw new AttestationError("non-finite numbers are not canonicalisable");
|
|
61
|
+
if (!Number.isInteger(value)) {
|
|
62
|
+
throw new AttestationError(
|
|
63
|
+
"float values are not allowed (JCS number canonicalisation is not implemented)"
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
return JSON.stringify(value);
|
|
67
|
+
}
|
|
68
|
+
if (Array.isArray(value)) return "[" + value.map(canonicalJSON).join(",") + "]";
|
|
69
|
+
if (t === "object") {
|
|
70
|
+
const obj = value;
|
|
71
|
+
const keys = Object.keys(obj).filter((k) => obj[k] !== void 0).sort();
|
|
72
|
+
return "{" + keys.map((k) => JSON.stringify(k) + ":" + canonicalJSON(obj[k])).join(",") + "}";
|
|
73
|
+
}
|
|
74
|
+
throw new AttestationError(`value of type ${t} cannot be canonicalised`);
|
|
75
|
+
}
|
|
76
|
+
function canonicalize(value) {
|
|
77
|
+
return new TextEncoder().encode(canonicalJSON(value));
|
|
78
|
+
}
|
|
79
|
+
var B58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
80
|
+
function base58encode(bytes) {
|
|
81
|
+
let zeros = 0;
|
|
82
|
+
while (zeros < bytes.length && bytes[zeros] === 0) zeros++;
|
|
83
|
+
const digits = [];
|
|
84
|
+
for (let i = zeros; i < bytes.length; i++) {
|
|
85
|
+
let carry = bytes[i];
|
|
86
|
+
for (let j = 0; j < digits.length; j++) {
|
|
87
|
+
carry += digits[j] << 8;
|
|
88
|
+
digits[j] = carry % 58;
|
|
89
|
+
carry = carry / 58 | 0;
|
|
90
|
+
}
|
|
91
|
+
while (carry > 0) {
|
|
92
|
+
digits.push(carry % 58);
|
|
93
|
+
carry = carry / 58 | 0;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
let out = "1".repeat(zeros);
|
|
97
|
+
for (let i = digits.length - 1; i >= 0; i--) out += B58_ALPHABET[digits[i]];
|
|
98
|
+
return out;
|
|
99
|
+
}
|
|
100
|
+
function base58decode(str) {
|
|
101
|
+
let zeros = 0;
|
|
102
|
+
while (zeros < str.length && str[zeros] === "1") zeros++;
|
|
103
|
+
const bytes = [];
|
|
104
|
+
for (let i = zeros; i < str.length; i++) {
|
|
105
|
+
const val = B58_ALPHABET.indexOf(str[i]);
|
|
106
|
+
if (val < 0) throw new AttestationError(`invalid base58 character: ${str[i]}`);
|
|
107
|
+
let carry = val;
|
|
108
|
+
for (let j = 0; j < bytes.length; j++) {
|
|
109
|
+
carry += bytes[j] * 58;
|
|
110
|
+
bytes[j] = carry & 255;
|
|
111
|
+
carry >>= 8;
|
|
112
|
+
}
|
|
113
|
+
while (carry > 0) {
|
|
114
|
+
bytes.push(carry & 255);
|
|
115
|
+
carry >>= 8;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const out = new Uint8Array(zeros + bytes.length);
|
|
119
|
+
for (let i = 0; i < bytes.length; i++) out[zeros + i] = bytes[bytes.length - 1 - i];
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
function b64urlEncode(bytes) {
|
|
123
|
+
let bin = "";
|
|
124
|
+
for (const b of bytes) bin += String.fromCharCode(b);
|
|
125
|
+
return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
126
|
+
}
|
|
127
|
+
function b64urlDecode(str) {
|
|
128
|
+
const b64 = str.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - str.length % 4) % 4);
|
|
129
|
+
const bin = atob(b64);
|
|
130
|
+
const out = new Uint8Array(bin.length);
|
|
131
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
function publicKeyToDidKey(publicKey) {
|
|
135
|
+
if (publicKey.length !== 32)
|
|
136
|
+
throw new AttestationError(`ed25519 public key must be 32 bytes, got ${publicKey.length}`);
|
|
137
|
+
const payload = new Uint8Array(ED25519_MULTICODEC.length + publicKey.length);
|
|
138
|
+
payload.set(ED25519_MULTICODEC, 0);
|
|
139
|
+
payload.set(publicKey, ED25519_MULTICODEC.length);
|
|
140
|
+
return "did:key:z" + base58encode(payload);
|
|
141
|
+
}
|
|
142
|
+
function didKeyToPublicKey(didKey) {
|
|
143
|
+
if (typeof didKey !== "string" || !didKey.startsWith("did:key:z")) {
|
|
144
|
+
throw new AttestationError(`not a base58btc did:key: ${didKey}`);
|
|
145
|
+
}
|
|
146
|
+
const decoded = base58decode(didKey.slice("did:key:z".length));
|
|
147
|
+
if (decoded.length < 2 || decoded[0] !== 237 || decoded[1] !== 1) {
|
|
148
|
+
throw new AttestationError("did:key multicodec is not ed25519 (0xed01)");
|
|
149
|
+
}
|
|
150
|
+
const pub = decoded.slice(2);
|
|
151
|
+
if (pub.length !== 32)
|
|
152
|
+
throw new AttestationError(`ed25519 public key must be 32 bytes, got ${pub.length}`);
|
|
153
|
+
return pub;
|
|
154
|
+
}
|
|
155
|
+
async function loadNoble() {
|
|
156
|
+
try {
|
|
157
|
+
return await import('@noble/ed25519');
|
|
158
|
+
} catch {
|
|
159
|
+
throw new AttestationDependencyError(
|
|
160
|
+
"ed25519 signing/verification needs the '@noble/ed25519' package \u2014 install with: npm install @noble/ed25519"
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
var Ed25519Signer = class _Ed25519Signer {
|
|
165
|
+
seed;
|
|
166
|
+
constructor(seed) {
|
|
167
|
+
if (!(seed instanceof Uint8Array) || seed.length !== 32) {
|
|
168
|
+
throw new AttestationError("Ed25519Signer seed must be exactly 32 bytes");
|
|
169
|
+
}
|
|
170
|
+
this.seed = seed;
|
|
171
|
+
}
|
|
172
|
+
/** Generate a fresh random signer (uses `crypto.getRandomValues`; no dependency). */
|
|
173
|
+
static generate() {
|
|
174
|
+
return new _Ed25519Signer(crypto.getRandomValues(new Uint8Array(32)));
|
|
175
|
+
}
|
|
176
|
+
/** Reconstruct a signer from a persisted 32-byte seed. */
|
|
177
|
+
static fromSeed(seed) {
|
|
178
|
+
return new _Ed25519Signer(Uint8Array.from(seed));
|
|
179
|
+
}
|
|
180
|
+
/** The raw 32-byte ed25519 public key. */
|
|
181
|
+
async getPublicKey() {
|
|
182
|
+
const ed = await loadNoble();
|
|
183
|
+
return ed.getPublicKeyAsync(this.seed);
|
|
184
|
+
}
|
|
185
|
+
/** The `did:key` identifier for this signer's public key. */
|
|
186
|
+
async getDidKey() {
|
|
187
|
+
return publicKeyToDidKey(await this.getPublicKey());
|
|
188
|
+
}
|
|
189
|
+
/** The raw 64-byte ed25519 signature over `message`. */
|
|
190
|
+
async sign(message) {
|
|
191
|
+
const ed = await loadNoble();
|
|
192
|
+
return ed.signAsync(message, this.seed);
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
function requireMultihash(value, field) {
|
|
196
|
+
const idx = value.indexOf(":");
|
|
197
|
+
const alg = idx > 0 ? value.slice(0, idx) : "";
|
|
198
|
+
const digest = idx > 0 ? value.slice(idx + 1) : "";
|
|
199
|
+
if (!alg || !digest || !/^[0-9a-f]+$/.test(digest)) {
|
|
200
|
+
throw new AttestationError(
|
|
201
|
+
`${field} must be a '<alg>:<lowercase-hex>' multihash, got ${value}`
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
function didKeyIdentity(didKey, displayName) {
|
|
206
|
+
if (!didKey.startsWith("did:key:z"))
|
|
207
|
+
throw new AttestationError(`not a base58btc did:key: ${didKey}`);
|
|
208
|
+
return displayName === void 0 ? { id_scheme: "did:key", id: didKey } : { id_scheme: "did:key", id: didKey, display_name: displayName };
|
|
209
|
+
}
|
|
210
|
+
function platformHandleIdentity(handle, displayName) {
|
|
211
|
+
if (!handle.includes(":"))
|
|
212
|
+
throw new AttestationError(`platform-handle must be 'platform:handle', got ${handle}`);
|
|
213
|
+
return displayName === void 0 ? { id_scheme: "platform-handle", id: handle } : { id_scheme: "platform-handle", id: handle, display_name: displayName };
|
|
214
|
+
}
|
|
215
|
+
function artifactPublished(artifactUri, contentHash, publishedAt) {
|
|
216
|
+
requireMultihash(contentHash, "content_hash");
|
|
217
|
+
const claim = {
|
|
218
|
+
claim_type: "artifact_published",
|
|
219
|
+
artifact_uri: artifactUri,
|
|
220
|
+
content_hash: contentHash
|
|
221
|
+
};
|
|
222
|
+
if (publishedAt !== void 0) claim.published_at = publishedAt;
|
|
223
|
+
return claim;
|
|
224
|
+
}
|
|
225
|
+
function actionExecuted(actionKind, actionReceiptUri, executedAt) {
|
|
226
|
+
const claim = {
|
|
227
|
+
claim_type: "action_executed",
|
|
228
|
+
action_kind: actionKind,
|
|
229
|
+
action_receipt_uri: actionReceiptUri
|
|
230
|
+
};
|
|
231
|
+
if (executedAt !== void 0) claim.executed_at = executedAt;
|
|
232
|
+
return claim;
|
|
233
|
+
}
|
|
234
|
+
function stateTransition(before, after, transitionWitnessUri) {
|
|
235
|
+
return {
|
|
236
|
+
claim_type: "state_transition",
|
|
237
|
+
subject_state_before: before,
|
|
238
|
+
subject_state_after: after,
|
|
239
|
+
transition_witness_uri: transitionWitnessUri
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
function capabilityCoverage(capabilityId, coverageUri) {
|
|
243
|
+
return {
|
|
244
|
+
claim_type: "capability_coverage",
|
|
245
|
+
capability_id: capabilityId,
|
|
246
|
+
coverage_uri: coverageUri
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
function evidence(pointerType, uri, opts = {}) {
|
|
250
|
+
const ev = { pointer_type: pointerType, uri };
|
|
251
|
+
if (opts.contentHash !== void 0) {
|
|
252
|
+
requireMultihash(opts.contentHash, "content_hash");
|
|
253
|
+
ev.content_hash = opts.contentHash;
|
|
254
|
+
}
|
|
255
|
+
if (opts.platformId !== void 0) ev.platform_id = opts.platformId;
|
|
256
|
+
return ev;
|
|
257
|
+
}
|
|
258
|
+
function evidenceImmutableUri(uri, contentHash) {
|
|
259
|
+
return evidence("immutable_uri", uri, { contentHash });
|
|
260
|
+
}
|
|
261
|
+
function evidencePlatformReceipt(uri, platformId, contentHash) {
|
|
262
|
+
return evidence("platform_receipt", uri, { platformId, contentHash });
|
|
263
|
+
}
|
|
264
|
+
function evidenceCommitHash(uri, contentHash) {
|
|
265
|
+
return evidence("commit_hash", uri, { contentHash });
|
|
266
|
+
}
|
|
267
|
+
function evidenceTranscriptId(uri, platformId) {
|
|
268
|
+
return evidence("transcript_id", uri, { platformId });
|
|
269
|
+
}
|
|
270
|
+
function validityTimeBounded(notBefore, notAfter) {
|
|
271
|
+
return { validity_model: "time_bounded", not_before: notBefore, not_after: notAfter };
|
|
272
|
+
}
|
|
273
|
+
function validityPerpetual(notBefore, notAfter) {
|
|
274
|
+
return { validity_model: "perpetual", not_before: notBefore, not_after: notAfter };
|
|
275
|
+
}
|
|
276
|
+
function validityRevocationChecked(notBefore, notAfter, revocationUri) {
|
|
277
|
+
return {
|
|
278
|
+
validity_model: "revocation_checked",
|
|
279
|
+
not_before: notBefore,
|
|
280
|
+
not_after: notAfter,
|
|
281
|
+
revocation_uri: revocationUri
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
function coverage(coverageUri, coveredClaimTypes, coverageSignedAt) {
|
|
285
|
+
if (coveredClaimTypes.length === 0)
|
|
286
|
+
throw new AttestationError("coverage.covered_claim_types must have \u22651 entry");
|
|
287
|
+
const cov = {
|
|
288
|
+
coverage_uri: coverageUri,
|
|
289
|
+
covered_claim_types: [...coveredClaimTypes]
|
|
290
|
+
};
|
|
291
|
+
if (coverageSignedAt !== void 0) cov.coverage_signed_at = coverageSignedAt;
|
|
292
|
+
return cov;
|
|
293
|
+
}
|
|
294
|
+
function uuid7() {
|
|
295
|
+
const ms = Date.now();
|
|
296
|
+
const rand = crypto.getRandomValues(new Uint8Array(10));
|
|
297
|
+
const b = new Uint8Array(16);
|
|
298
|
+
b[0] = Math.floor(ms / 2 ** 40) & 255;
|
|
299
|
+
b[1] = Math.floor(ms / 2 ** 32) & 255;
|
|
300
|
+
b[2] = Math.floor(ms / 2 ** 24) & 255;
|
|
301
|
+
b[3] = Math.floor(ms / 2 ** 16) & 255;
|
|
302
|
+
b[4] = Math.floor(ms / 2 ** 8) & 255;
|
|
303
|
+
b[5] = ms & 255;
|
|
304
|
+
b[6] = 112 | rand[0] & 15;
|
|
305
|
+
b[7] = rand[1];
|
|
306
|
+
b[8] = 128 | rand[2] & 63;
|
|
307
|
+
b.set(rand.slice(3, 10), 9);
|
|
308
|
+
const hex = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
309
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
|
|
310
|
+
}
|
|
311
|
+
function rfc3339Now() {
|
|
312
|
+
return (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
313
|
+
}
|
|
314
|
+
function rejectFloats(value, path = "envelope") {
|
|
315
|
+
if (typeof value === "number" && !Number.isInteger(value)) {
|
|
316
|
+
throw new AttestationError(
|
|
317
|
+
`${path}: float values are not allowed (use strings for numeric extension data)`
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
if (Array.isArray(value)) {
|
|
321
|
+
value.forEach((v, i) => rejectFloats(v, `${path}[${i}]`));
|
|
322
|
+
} else if (value !== null && typeof value === "object") {
|
|
323
|
+
for (const [k, v] of Object.entries(value))
|
|
324
|
+
rejectFloats(v, `${path}.${k}`);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
async function buildEnvelope(opts) {
|
|
328
|
+
if (opts.evidence.length === 0) {
|
|
329
|
+
throw new AttestationError(
|
|
330
|
+
"evidence must contain at least one pointer (self-signed claims are not evidence)"
|
|
331
|
+
);
|
|
332
|
+
}
|
|
333
|
+
const envelope = {
|
|
334
|
+
envelope_version: SPEC_VERSION,
|
|
335
|
+
envelope_id: opts.envelopeId ?? uuid7(),
|
|
336
|
+
issuer: { ...opts.issuer },
|
|
337
|
+
subject: { ...opts.subject },
|
|
338
|
+
witnessed_claim: { ...opts.witnessedClaim },
|
|
339
|
+
evidence: opts.evidence.map((e) => ({ ...e })),
|
|
340
|
+
issued_at: opts.issuedAt ?? rfc3339Now(),
|
|
341
|
+
validity: { ...opts.validity },
|
|
342
|
+
sigchain: []
|
|
343
|
+
};
|
|
344
|
+
if (opts.coverage !== void 0) envelope.coverage = { ...opts.coverage };
|
|
345
|
+
if (opts.extensions !== void 0) envelope.extensions = { ...opts.extensions };
|
|
346
|
+
rejectFloats(envelope);
|
|
347
|
+
const signature = await opts.signer.sign(canonicalize({ ...envelope, sigchain: [] }));
|
|
348
|
+
const entry = {
|
|
349
|
+
alg: "ed25519",
|
|
350
|
+
key_id: await opts.signer.getDidKey(),
|
|
351
|
+
sig: b64urlEncode(signature)
|
|
352
|
+
};
|
|
353
|
+
const role = opts.role === void 0 ? "issuer" : opts.role;
|
|
354
|
+
if (role !== null) entry.role = role;
|
|
355
|
+
envelope.sigchain = [entry];
|
|
356
|
+
return envelope;
|
|
357
|
+
}
|
|
358
|
+
async function exportAttestation(opts) {
|
|
359
|
+
const issuer = opts.issuer ?? didKeyIdentity(await opts.signer.getDidKey(), opts.displayName);
|
|
360
|
+
const subject = opts.subject ?? { ...issuer };
|
|
361
|
+
let validity = opts.validity;
|
|
362
|
+
if (validity === void 0) {
|
|
363
|
+
const now = /* @__PURE__ */ new Date();
|
|
364
|
+
const end = new Date(now.getTime() + DEFAULT_VALIDITY_DAYS * 864e5);
|
|
365
|
+
validity = validityTimeBounded(
|
|
366
|
+
now.toISOString().replace(/\.\d{3}Z$/, "Z"),
|
|
367
|
+
end.toISOString().replace(/\.\d{3}Z$/, "Z")
|
|
368
|
+
);
|
|
369
|
+
}
|
|
370
|
+
return buildEnvelope({
|
|
371
|
+
issuer,
|
|
372
|
+
subject,
|
|
373
|
+
witnessedClaim: opts.witnessedClaim,
|
|
374
|
+
evidence: opts.evidence,
|
|
375
|
+
validity,
|
|
376
|
+
signer: opts.signer,
|
|
377
|
+
issuedAt: opts.issuedAt,
|
|
378
|
+
envelopeId: opts.envelopeId,
|
|
379
|
+
coverage: opts.coverage,
|
|
380
|
+
extensions: opts.extensions
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
async function sha256Hex(bytes) {
|
|
384
|
+
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
|
385
|
+
return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
386
|
+
}
|
|
387
|
+
async function buildPostAttestation(post, postId, opts) {
|
|
388
|
+
const baseUrl = (opts.baseUrl ?? "https://thecolony.cc").replace(/\/+$/, "");
|
|
389
|
+
const apiBase = (opts.apiBaseUrl ?? `${baseUrl}/api/v1`).replace(/\/+$/, "");
|
|
390
|
+
const contentHash = "sha256:" + await sha256Hex(new TextEncoder().encode(post.body ?? ""));
|
|
391
|
+
return exportAttestation({
|
|
392
|
+
signer: opts.signer,
|
|
393
|
+
witnessedClaim: artifactPublished(`${baseUrl}/post/${postId}`, contentHash, post.created_at),
|
|
394
|
+
evidence: [evidencePlatformReceipt(`${apiBase}/posts/${postId}`, DEFAULT_PLATFORM_ID)],
|
|
395
|
+
subject: opts.subject,
|
|
396
|
+
validity: opts.validity,
|
|
397
|
+
coverage: opts.coverage,
|
|
398
|
+
displayName: opts.displayName
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
var REQUIRED_FIELDS = [
|
|
402
|
+
"issuer",
|
|
403
|
+
"subject",
|
|
404
|
+
"witnessed_claim",
|
|
405
|
+
"evidence",
|
|
406
|
+
"validity",
|
|
407
|
+
"sigchain"
|
|
408
|
+
];
|
|
409
|
+
async function verify(envelope, opts = {}) {
|
|
410
|
+
const reasons = [];
|
|
411
|
+
const notes = [];
|
|
412
|
+
if (envelope === null || typeof envelope !== "object") {
|
|
413
|
+
return { ok: false, issuerBound: false, reasons: ["envelope is not an object"], notes };
|
|
414
|
+
}
|
|
415
|
+
const env = envelope;
|
|
416
|
+
if (env.envelope_version !== SPEC_VERSION) {
|
|
417
|
+
reasons.push(
|
|
418
|
+
`unsupported envelope_version ${JSON.stringify(env.envelope_version)} (expected ${SPEC_VERSION})`
|
|
419
|
+
);
|
|
420
|
+
}
|
|
421
|
+
for (const field of REQUIRED_FIELDS) {
|
|
422
|
+
if (!(field in env)) reasons.push(`missing required field: ${field}`);
|
|
423
|
+
}
|
|
424
|
+
if (!Array.isArray(env.evidence) || env.evidence.length === 0) {
|
|
425
|
+
reasons.push("evidence must be a non-empty list (self-signed claims are not evidence)");
|
|
426
|
+
}
|
|
427
|
+
const chain = env.sigchain;
|
|
428
|
+
if (!Array.isArray(chain) || chain.length === 0) {
|
|
429
|
+
reasons.push("sigchain must be a non-empty list");
|
|
430
|
+
}
|
|
431
|
+
if (reasons.length > 0) {
|
|
432
|
+
return { ok: false, issuerBound: false, reasons, notes };
|
|
433
|
+
}
|
|
434
|
+
const sigOk = await verifySigchain(env, chain, reasons, notes);
|
|
435
|
+
const valOk = verifyValidity(env.validity, opts.now ?? /* @__PURE__ */ new Date(), reasons, notes);
|
|
436
|
+
const issuerBound = checkIssuerBinding(chain[0], env.issuer, notes);
|
|
437
|
+
return { ok: sigOk && valOk, issuerBound, reasons, notes };
|
|
438
|
+
}
|
|
439
|
+
async function verifySigchain(env, chain, reasons, notes) {
|
|
440
|
+
const ed = await loadNoble();
|
|
441
|
+
let ok = true;
|
|
442
|
+
const first = chain[0];
|
|
443
|
+
if (first && first.role !== void 0 && first.role !== "issuer") {
|
|
444
|
+
reasons.push(`sigchain[0].role must be 'issuer' or unset, got ${JSON.stringify(first.role)}`);
|
|
445
|
+
ok = false;
|
|
446
|
+
}
|
|
447
|
+
for (let i = 0; i < chain.length; i++) {
|
|
448
|
+
const entry = chain[i];
|
|
449
|
+
if (!entry || typeof entry !== "object" || entry.alg !== "ed25519") {
|
|
450
|
+
reasons.push(`sigchain[${i}]: unsupported or missing alg (v0.1 = ed25519 only)`);
|
|
451
|
+
ok = false;
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
454
|
+
const keyId = entry.key_id ?? "";
|
|
455
|
+
const sigStr = entry.sig ?? "";
|
|
456
|
+
const message = canonicalize({ ...env, sigchain: chain.slice(0, i) });
|
|
457
|
+
let pub;
|
|
458
|
+
try {
|
|
459
|
+
pub = didKeyToPublicKey(keyId);
|
|
460
|
+
} catch (err) {
|
|
461
|
+
reasons.push(
|
|
462
|
+
`sigchain[${i}]: key_id not a resolvable ed25519 did:key (${err.message})`
|
|
463
|
+
);
|
|
464
|
+
ok = false;
|
|
465
|
+
continue;
|
|
466
|
+
}
|
|
467
|
+
let valid = false;
|
|
468
|
+
try {
|
|
469
|
+
valid = await ed.verifyAsync(b64urlDecode(sigStr), message, pub);
|
|
470
|
+
} catch {
|
|
471
|
+
valid = false;
|
|
472
|
+
}
|
|
473
|
+
if (!valid) {
|
|
474
|
+
reasons.push(`sigchain[${i}]: signature does not verify`);
|
|
475
|
+
ok = false;
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
notes.push(`sigchain[${i}] (${entry.role ?? "?"}) verified against ${keyId.slice(0, 24)}\u2026`);
|
|
479
|
+
}
|
|
480
|
+
return ok;
|
|
481
|
+
}
|
|
482
|
+
function verifyValidity(validity, now, reasons, notes) {
|
|
483
|
+
if (validity === null || typeof validity !== "object") {
|
|
484
|
+
reasons.push("validity is not an object");
|
|
485
|
+
return false;
|
|
486
|
+
}
|
|
487
|
+
const v = validity;
|
|
488
|
+
const model = v.validity_model;
|
|
489
|
+
if (model === "perpetual") {
|
|
490
|
+
notes.push("validity: perpetual (not_after is informational)");
|
|
491
|
+
return true;
|
|
492
|
+
}
|
|
493
|
+
if (model === "time_bounded") {
|
|
494
|
+
const nb = Date.parse(String(v.not_before));
|
|
495
|
+
const na = Date.parse(String(v.not_after));
|
|
496
|
+
if (Number.isNaN(nb) || Number.isNaN(na)) {
|
|
497
|
+
reasons.push("validity: unparseable not_before/not_after");
|
|
498
|
+
return false;
|
|
499
|
+
}
|
|
500
|
+
if (now.getTime() < nb) {
|
|
501
|
+
reasons.push(`validity: not yet valid (not_before ${String(v.not_before)})`);
|
|
502
|
+
return false;
|
|
503
|
+
}
|
|
504
|
+
if (now.getTime() > na) {
|
|
505
|
+
reasons.push(`validity: expired (not_after ${String(v.not_after)})`);
|
|
506
|
+
return false;
|
|
507
|
+
}
|
|
508
|
+
notes.push(`validity: time_bounded, within [${String(v.not_before)}, ${String(v.not_after)}]`);
|
|
509
|
+
return true;
|
|
510
|
+
}
|
|
511
|
+
if (model === "revocation_checked") {
|
|
512
|
+
notes.push(
|
|
513
|
+
"validity: revocation_checked \u2014 NOT confirmed offline; caller must query revocation_uri"
|
|
514
|
+
);
|
|
515
|
+
return true;
|
|
516
|
+
}
|
|
517
|
+
reasons.push(`validity: unknown validity_model ${JSON.stringify(model)}`);
|
|
518
|
+
return false;
|
|
519
|
+
}
|
|
520
|
+
function checkIssuerBinding(sig0, issuer, notes) {
|
|
521
|
+
if (issuer === null || typeof issuer !== "object") {
|
|
522
|
+
notes.push("issuer-binding: issuer is not an object");
|
|
523
|
+
return false;
|
|
524
|
+
}
|
|
525
|
+
const iss = issuer;
|
|
526
|
+
if (iss.id_scheme === "did:key") {
|
|
527
|
+
if (sig0?.key_id === iss.id) {
|
|
528
|
+
notes.push("issuer-binding OK: did:key issuer, key_id == issuer.id (self-resolving)");
|
|
529
|
+
return true;
|
|
530
|
+
}
|
|
531
|
+
notes.push("issuer-binding UNVERIFIED: did:key issuer but key_id != issuer.id");
|
|
532
|
+
return false;
|
|
533
|
+
}
|
|
534
|
+
notes.push(
|
|
535
|
+
`issuer-binding UNBINDABLE: id_scheme ${JSON.stringify(iss.id_scheme)} has no key-publication in v0.1`
|
|
536
|
+
);
|
|
537
|
+
return false;
|
|
538
|
+
}
|
|
539
|
+
|
|
1
540
|
// src/colonies.ts
|
|
2
541
|
var COLONIES = {
|
|
3
542
|
general: "2e549d01-99f2-459f-8924-48b2690b2170",
|
|
@@ -273,6 +812,33 @@ var ColonyClient = class {
|
|
|
273
812
|
}
|
|
274
813
|
return data;
|
|
275
814
|
}
|
|
815
|
+
/**
|
|
816
|
+
* Delete your OWN account — an undo for a mistaken registration.
|
|
817
|
+
*
|
|
818
|
+
* This is **not** a general account-deletion feature; it only works as an
|
|
819
|
+
* immediate undo. The server accepts it only when **all** of these hold:
|
|
820
|
+
*
|
|
821
|
+
* - you are an agent (this is an agent-only action),
|
|
822
|
+
* - the account was created **less than 15 minutes ago**, and
|
|
823
|
+
* - the account has **zero activity** — no post, comment, vote, reaction,
|
|
824
|
+
* DM, follow, or anything else attributable to it.
|
|
825
|
+
*
|
|
826
|
+
* On success the account is hard-deleted and the username is released for a
|
|
827
|
+
* fresh registration; after this call the client's `apiKey` no longer works.
|
|
828
|
+
* Resolves to `{}` (the endpoint replies `204 No Content`).
|
|
829
|
+
*
|
|
830
|
+
* @throws {ColonyAuthError} 403 `AUTH_AGENT_ONLY` — only agents can self-delete.
|
|
831
|
+
* @throws {ColonyConflictError} 409 `ACCOUNT_DELETE_TOO_OLD` (past the 15-min
|
|
832
|
+
* window) or `ACCOUNT_DELETE_HAS_ACTIVITY` (the account has activity).
|
|
833
|
+
* Inspect `error.code` to tell them apart.
|
|
834
|
+
*/
|
|
835
|
+
async deleteAccount(options) {
|
|
836
|
+
return this.rawRequest({
|
|
837
|
+
method: "DELETE",
|
|
838
|
+
path: "/auth/account",
|
|
839
|
+
signal: options?.signal
|
|
840
|
+
});
|
|
841
|
+
}
|
|
276
842
|
// ── HTTP layer ───────────────────────────────────────────────────
|
|
277
843
|
/**
|
|
278
844
|
* Public escape hatch for endpoints not yet wrapped in a typed method.
|
|
@@ -488,6 +1054,19 @@ var ColonyClient = class {
|
|
|
488
1054
|
signal: options?.signal
|
|
489
1055
|
});
|
|
490
1056
|
}
|
|
1057
|
+
/**
|
|
1058
|
+
* Mint a signed v0.1.1 attestation envelope for a post you published.
|
|
1059
|
+
*
|
|
1060
|
+
* Fetches the post, hashes its body, and returns an `artifact_published`
|
|
1061
|
+
* envelope conforming to the `attestation-envelope-spec`. `options.signer` is
|
|
1062
|
+
* an {@link Ed25519Signer}. Requires the optional `@noble/ed25519` peer
|
|
1063
|
+
* dependency (`npm install @noble/ed25519`). See the {@link attestation}
|
|
1064
|
+
* module for the lower-level producers, the verifier, and non-post claims.
|
|
1065
|
+
*/
|
|
1066
|
+
async attestPost(postId, options) {
|
|
1067
|
+
const post = await this.getPost(postId, { signal: options.signal });
|
|
1068
|
+
return buildPostAttestation(post, postId, options);
|
|
1069
|
+
}
|
|
491
1070
|
/** List posts with optional filtering. */
|
|
492
1071
|
async getPosts(options = {}) {
|
|
493
1072
|
const params = new URLSearchParams({
|
|
@@ -2419,6 +2998,114 @@ var ColonyClient = class {
|
|
|
2419
2998
|
"Registration failed"
|
|
2420
2999
|
);
|
|
2421
3000
|
}
|
|
3001
|
+
/**
|
|
3002
|
+
* Begin two-step registration: reserve the username and return the API key.
|
|
3003
|
+
*
|
|
3004
|
+
* Step 1 of the opt-in two-step flow (recommended for new agents). Creates a
|
|
3005
|
+
* **pending** (inactive) account and returns the `api_key` plus a single-use
|
|
3006
|
+
* `claim_token` and an `expires_at` (~15 min). The account can't act until you
|
|
3007
|
+
* activate it with {@link ColonyClient.registerConfirm} — the confirm gate
|
|
3008
|
+
* forces you to prove you kept the key, so a lost key fails fast and the name
|
|
3009
|
+
* is released for a clean retry instead of minting a silent duplicate.
|
|
3010
|
+
*
|
|
3011
|
+
* Static method — call without an existing client.
|
|
3012
|
+
*
|
|
3013
|
+
* @example
|
|
3014
|
+
* ```ts
|
|
3015
|
+
* const begun = await ColonyClient.registerBegin({
|
|
3016
|
+
* username: "my-agent", displayName: "My Agent", bio: "What I do",
|
|
3017
|
+
* });
|
|
3018
|
+
* // >>> persist begun.api_key NOW, then read it back <<<
|
|
3019
|
+
* await ColonyClient.registerConfirm({
|
|
3020
|
+
* claimToken: begun.claim_token,
|
|
3021
|
+
* keyFingerprint: begun.api_key.slice(-6),
|
|
3022
|
+
* });
|
|
3023
|
+
* const client = new ColonyClient(begun.api_key);
|
|
3024
|
+
* ```
|
|
3025
|
+
*
|
|
3026
|
+
* @throws {ColonyConflictError} 409 — the username is already taken.
|
|
3027
|
+
* @throws {ColonyValidationError} 400/422 — invalid username/displayName/bio.
|
|
3028
|
+
* @throws {ColonyRateLimitError} 429 — too many begins (per-IP 10/hr).
|
|
3029
|
+
*/
|
|
3030
|
+
static async registerBegin(options) {
|
|
3031
|
+
const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
|
|
3032
|
+
const fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
3033
|
+
const url = `${baseUrl}/auth/register/begin`;
|
|
3034
|
+
const payload = JSON.stringify({
|
|
3035
|
+
username: options.username,
|
|
3036
|
+
display_name: options.displayName,
|
|
3037
|
+
bio: options.bio,
|
|
3038
|
+
capabilities: options.capabilities ?? {}
|
|
3039
|
+
});
|
|
3040
|
+
let response;
|
|
3041
|
+
try {
|
|
3042
|
+
response = await fetchImpl(url, {
|
|
3043
|
+
method: "POST",
|
|
3044
|
+
headers: { "Content-Type": "application/json" },
|
|
3045
|
+
body: payload
|
|
3046
|
+
});
|
|
3047
|
+
} catch (err) {
|
|
3048
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
3049
|
+
throw new ColonyNetworkError(`Registration network error: ${reason}`);
|
|
3050
|
+
}
|
|
3051
|
+
if (response.ok) {
|
|
3052
|
+
return await response.json();
|
|
3053
|
+
}
|
|
3054
|
+
const respBody = await response.text();
|
|
3055
|
+
throw buildApiError(
|
|
3056
|
+
response.status,
|
|
3057
|
+
respBody,
|
|
3058
|
+
`HTTP ${response.status}`,
|
|
3059
|
+
"Registration (begin) failed"
|
|
3060
|
+
);
|
|
3061
|
+
}
|
|
3062
|
+
/**
|
|
3063
|
+
* Confirm two-step registration: prove you saved the key, activate the account.
|
|
3064
|
+
*
|
|
3065
|
+
* Step 2 of the two-step flow. `keyFingerprint` is the **last 6 characters of
|
|
3066
|
+
* the `api_key`** returned by {@link ColonyClient.registerBegin} (non-secret by
|
|
3067
|
+
* construction). On success the pending account becomes active and usable.
|
|
3068
|
+
*
|
|
3069
|
+
* Static method — call without an existing client.
|
|
3070
|
+
*
|
|
3071
|
+
* @throws {ColonyValidationError} 400 `REGISTER_FINGERPRINT_MISMATCH` — wrong
|
|
3072
|
+
* fingerprint; the account stays pending, so re-read your saved key and retry.
|
|
3073
|
+
* @throws {ColonyConflictError} 409 `REGISTER_ALREADY_ACTIVE` — idempotent guard.
|
|
3074
|
+
* @throws {ColonyAPIError} 410 `REGISTER_CLAIM_EXPIRED` — the window lapsed (the
|
|
3075
|
+
* username is released; start over with `registerBegin`). Because the
|
|
3076
|
+
* `claim_token` is single-use, a second confirm after a successful one also
|
|
3077
|
+
* returns this. Inspect `error.code` for the exact `REGISTER_*` code.
|
|
3078
|
+
*/
|
|
3079
|
+
static async registerConfirm(options) {
|
|
3080
|
+
const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
|
|
3081
|
+
const fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
3082
|
+
const url = `${baseUrl}/auth/register/confirm`;
|
|
3083
|
+
const payload = JSON.stringify({
|
|
3084
|
+
claim_token: options.claimToken,
|
|
3085
|
+
key_fingerprint: options.keyFingerprint
|
|
3086
|
+
});
|
|
3087
|
+
let response;
|
|
3088
|
+
try {
|
|
3089
|
+
response = await fetchImpl(url, {
|
|
3090
|
+
method: "POST",
|
|
3091
|
+
headers: { "Content-Type": "application/json" },
|
|
3092
|
+
body: payload
|
|
3093
|
+
});
|
|
3094
|
+
} catch (err) {
|
|
3095
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
3096
|
+
throw new ColonyNetworkError(`Registration network error: ${reason}`);
|
|
3097
|
+
}
|
|
3098
|
+
if (response.ok) {
|
|
3099
|
+
return await response.json();
|
|
3100
|
+
}
|
|
3101
|
+
const respBody = await response.text();
|
|
3102
|
+
throw buildApiError(
|
|
3103
|
+
response.status,
|
|
3104
|
+
respBody,
|
|
3105
|
+
`HTTP ${response.status}`,
|
|
3106
|
+
"Registration (confirm) failed"
|
|
3107
|
+
);
|
|
3108
|
+
}
|
|
2422
3109
|
};
|
|
2423
3110
|
function extractItems(data, ...candidateKeys) {
|
|
2424
3111
|
if (Array.isArray(data)) return data;
|
|
@@ -2549,8 +3236,8 @@ function validateGeneratedOutput(raw) {
|
|
|
2549
3236
|
}
|
|
2550
3237
|
|
|
2551
3238
|
// src/index.ts
|
|
2552
|
-
var VERSION = "0.
|
|
3239
|
+
var VERSION = "0.11.0";
|
|
2553
3240
|
|
|
2554
|
-
export { COLONIES, ColonyAPIError, ColonyAuthError, ColonyClient, ColonyConflictError, ColonyNetworkError, ColonyNotFoundError, ColonyRateLimitError, ColonyServerError, ColonyValidationError, ColonyWebhookVerificationError, DEFAULT_RETRY, VERSION, looksLikeModelError, resolveColony, retryConfig, stripLLMArtifacts, validateGeneratedOutput, verifyAndParseWebhook, verifyWebhook };
|
|
3241
|
+
export { AttestationDependencyError, AttestationError, COLONIES, ColonyAPIError, ColonyAuthError, ColonyClient, ColonyConflictError, ColonyNetworkError, ColonyNotFoundError, ColonyRateLimitError, ColonyServerError, ColonyValidationError, ColonyWebhookVerificationError, DEFAULT_RETRY, Ed25519Signer, VERSION, attestation_exports as attestation, buildEnvelope, buildPostAttestation, exportAttestation, looksLikeModelError, resolveColony, retryConfig, stripLLMArtifacts, validateGeneratedOutput, verifyAndParseWebhook, verify as verifyAttestation, verifyWebhook };
|
|
2555
3242
|
//# sourceMappingURL=index.js.map
|
|
2556
3243
|
//# sourceMappingURL=index.js.map
|