@kya-os/contracts 1.6.17 → 1.6.19

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,302 @@
1
+ "use strict";
2
+ /**
3
+ * Reputation Credential Schemas
4
+ *
5
+ * W3C Verifiable Credential schemas for reputation attestations.
6
+ * These credentials allow reputation scores to be cryptographically signed
7
+ * and verified as portable, tamper-proof attestations.
8
+ *
9
+ * Credential Types:
10
+ * - ReputationCredential: Attests to an agent's reputation score at a point in time
11
+ * - ReputationAttestation: Lighter-weight attestation for specific contexts
12
+ *
13
+ * Related Spec: MCP-I §3.1 (VC Structure), §5.3 (Reputation Credentials)
14
+ * W3C Reference: Verifiable Credentials Data Model 1.1
15
+ */
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.RECOMMENDED_REPUTATION_FRESHNESS_MS = exports.DEFAULT_REPUTATION_CREDENTIAL_VALIDITY_MS = exports.ReputationAttestationSchema = exports.ReputationAttestationSubjectSchema = exports.ReputationCredentialSchema = exports.ReputationCredentialSubjectSchema = exports.REPUTATION_ATTESTATION_TYPE = exports.REPUTATION_CREDENTIAL_TYPE = exports.REPUTATION_CREDENTIAL_CONTEXT = void 0;
18
+ exports.validateReputationCredential = validateReputationCredential;
19
+ exports.validateReputationAttestation = validateReputationAttestation;
20
+ exports.createUnsignedReputationCredential = createUnsignedReputationCredential;
21
+ exports.extractReputationFromCredential = extractReputationFromCredential;
22
+ exports.isReputationCredentialExpired = isReputationCredentialExpired;
23
+ exports.isReputationCredentialStale = isReputationCredentialStale;
24
+ const zod_1 = require("zod");
25
+ const schemas_js_1 = require("../vc/schemas.js");
26
+ const schemas_js_2 = require("./schemas.js");
27
+ // ============================================================================
28
+ // CONTEXTS
29
+ // ============================================================================
30
+ /**
31
+ * Reputation Credential JSON-LD Context
32
+ */
33
+ exports.REPUTATION_CREDENTIAL_CONTEXT = "https://schemas.kya-os.ai/xmcp-i/credentials/reputation.v1.0.0.json";
34
+ /**
35
+ * Reputation Credential Type
36
+ */
37
+ exports.REPUTATION_CREDENTIAL_TYPE = "ReputationCredential";
38
+ /**
39
+ * Reputation Attestation Type
40
+ */
41
+ exports.REPUTATION_ATTESTATION_TYPE = "ReputationAttestation";
42
+ // ============================================================================
43
+ // CREDENTIAL SUBJECT
44
+ // ============================================================================
45
+ /**
46
+ * Reputation Credential Subject Schema
47
+ *
48
+ * The credentialSubject of a ReputationCredential contains:
49
+ * - id: The agent DID being attested
50
+ * - reputation: The complete reputation score at time of issuance
51
+ */
52
+ exports.ReputationCredentialSubjectSchema = zod_1.z.object({
53
+ /** Subject DID (the agent whose reputation is being attested) */
54
+ id: zod_1.z
55
+ .string()
56
+ .min(1)
57
+ .refine((val) => val.startsWith("did:"), {
58
+ message: "Subject ID must be a valid DID",
59
+ }),
60
+ /** The reputation score being attested */
61
+ reputation: zod_1.z.object({
62
+ /** Final reputation score (0-100) */
63
+ score: zod_1.z.number().min(0).max(100),
64
+ /** Confidence in the score (0-1) */
65
+ confidence: zod_1.z.number().min(0).max(1),
66
+ /** Human-readable confidence level */
67
+ confidenceLevel: schemas_js_2.ConfidenceLevelSchema,
68
+ /** Human-readable reputation level */
69
+ level: schemas_js_2.ReputationLevelSchema,
70
+ /** Whether this is a provisional score */
71
+ isProvisional: zod_1.z.boolean(),
72
+ /** Timestamp when the score was calculated (ISO 8601) */
73
+ calculatedAt: zod_1.z.string().datetime(),
74
+ /** Optional score components (for transparency) */
75
+ components: zod_1.z
76
+ .object({
77
+ priorScore: zod_1.z.number().min(0).max(100),
78
+ empiricalScore: zod_1.z.number().min(0).max(100),
79
+ confidenceWeight: zod_1.z.number().min(0).max(1),
80
+ priorWeight: zod_1.z.number().min(0).max(1),
81
+ })
82
+ .optional(),
83
+ }),
84
+ /** Context in which this reputation applies */
85
+ context: zod_1.z
86
+ .object({
87
+ /** Scope of the reputation (e.g., 'global', 'domain-specific') */
88
+ scope: zod_1.z.string().default("global"),
89
+ /** Domain or category (e.g., 'e-commerce', 'healthcare') */
90
+ domain: zod_1.z.string().optional(),
91
+ /** Geographic region (if applicable) */
92
+ region: zod_1.z.string().optional(),
93
+ })
94
+ .optional(),
95
+ });
96
+ // ============================================================================
97
+ // REPUTATION CREDENTIAL (W3C VC)
98
+ // ============================================================================
99
+ /**
100
+ * Reputation Credential Schema
101
+ *
102
+ * W3C Verifiable Credential for reputation attestation.
103
+ * This is the PRIMARY format for portable reputation scores.
104
+ *
105
+ * Structure:
106
+ * - @context: [...W3C VC contexts, reputation context]
107
+ * - type: ['VerifiableCredential', 'ReputationCredential']
108
+ * - issuer: Reputation authority DID (e.g., KYA platform)
109
+ * - issuanceDate: When the reputation was calculated
110
+ * - expirationDate: When this attestation expires
111
+ * - credentialSubject: Contains agent DID + reputation data
112
+ * - credentialStatus: StatusList2021Entry for revocation
113
+ * - proof: Ed25519Signature2020 or similar
114
+ */
115
+ exports.ReputationCredentialSchema = schemas_js_1.VerifiableCredentialSchema.extend({
116
+ /** @context MUST include reputation context */
117
+ "@context": zod_1.z.array(zod_1.z.union([zod_1.z.string().url(), zod_1.z.record(zod_1.z.any())])).refine((contexts) => {
118
+ // First context must be W3C VC context
119
+ const firstContext = contexts[0];
120
+ return (typeof firstContext === "string" &&
121
+ firstContext === "https://www.w3.org/2018/credentials/v1");
122
+ }, {
123
+ message: "First @context must be W3C VC context",
124
+ }),
125
+ /** type MUST include both VerifiableCredential and ReputationCredential */
126
+ type: zod_1.z
127
+ .array(zod_1.z.string())
128
+ .refine((types) => types.includes("VerifiableCredential") &&
129
+ types.includes(exports.REPUTATION_CREDENTIAL_TYPE), {
130
+ message: `type must include both "VerifiableCredential" and "${exports.REPUTATION_CREDENTIAL_TYPE}"`,
131
+ }),
132
+ /** issuer is the reputation authority DID */
133
+ issuer: schemas_js_1.IssuerSchema,
134
+ /** issuanceDate is when the reputation was calculated */
135
+ issuanceDate: zod_1.z.string().datetime(),
136
+ /** expirationDate is when this attestation expires */
137
+ expirationDate: zod_1.z.string().datetime().optional(),
138
+ /** credentialSubject contains agent DID + reputation data */
139
+ credentialSubject: exports.ReputationCredentialSubjectSchema,
140
+ /** credentialStatus for StatusList2021 revocation checking */
141
+ credentialStatus: schemas_js_1.CredentialStatusSchema.optional(),
142
+ /** proof is Ed25519Signature2020 or similar */
143
+ proof: schemas_js_1.ProofSchema.optional(),
144
+ });
145
+ // ============================================================================
146
+ // REPUTATION ATTESTATION (LIGHTWEIGHT)
147
+ // ============================================================================
148
+ /**
149
+ * Reputation Attestation Subject Schema
150
+ *
151
+ * Lighter-weight attestation for specific use cases.
152
+ * Contains only essential reputation information.
153
+ */
154
+ exports.ReputationAttestationSubjectSchema = zod_1.z.object({
155
+ /** Subject DID */
156
+ id: zod_1.z.string().min(1),
157
+ /** Reputation level (human-readable) */
158
+ level: schemas_js_2.ReputationLevelSchema,
159
+ /** Numeric score (0-100) */
160
+ score: zod_1.z.number().min(0).max(100),
161
+ /** Whether the attestation issuer has high confidence */
162
+ highConfidence: zod_1.z.boolean(),
163
+ /** Specific capability or context being attested */
164
+ capability: zod_1.z.string().optional(),
165
+ });
166
+ /**
167
+ * Reputation Attestation Schema
168
+ *
169
+ * Lightweight attestation for embedding in other contexts.
170
+ */
171
+ exports.ReputationAttestationSchema = schemas_js_1.VerifiableCredentialSchema.extend({
172
+ type: zod_1.z
173
+ .array(zod_1.z.string())
174
+ .refine((types) => types.includes("VerifiableCredential") &&
175
+ types.includes(exports.REPUTATION_ATTESTATION_TYPE), {
176
+ message: `type must include both "VerifiableCredential" and "${exports.REPUTATION_ATTESTATION_TYPE}"`,
177
+ }),
178
+ credentialSubject: exports.ReputationAttestationSubjectSchema,
179
+ });
180
+ // ============================================================================
181
+ // CREDENTIAL HELPERS
182
+ // ============================================================================
183
+ /**
184
+ * Validate a reputation credential
185
+ *
186
+ * @param credential - The credential to validate
187
+ * @returns Validation result
188
+ */
189
+ function validateReputationCredential(credential) {
190
+ return exports.ReputationCredentialSchema.safeParse(credential);
191
+ }
192
+ /**
193
+ * Validate a reputation attestation
194
+ *
195
+ * @param attestation - The attestation to validate
196
+ * @returns Validation result
197
+ */
198
+ function validateReputationAttestation(attestation) {
199
+ return exports.ReputationAttestationSchema.safeParse(attestation);
200
+ }
201
+ /**
202
+ * Create an unsigned reputation credential (requires signing)
203
+ *
204
+ * @param agentDid - DID of the agent
205
+ * @param score - Reputation score
206
+ * @param issuerDid - DID of the issuing authority
207
+ * @param options - Optional credential options
208
+ * @returns Unsigned ReputationCredential
209
+ */
210
+ function createUnsignedReputationCredential(agentDid, score, issuerDid, options) {
211
+ const now = new Date().toISOString();
212
+ return {
213
+ "@context": [
214
+ "https://www.w3.org/2018/credentials/v1",
215
+ exports.REPUTATION_CREDENTIAL_CONTEXT,
216
+ ],
217
+ id: options?.id ||
218
+ `urn:uuid:rep-${agentDid.replace(/[^a-zA-Z0-9]/g, "-")}-${Date.now()}`,
219
+ type: ["VerifiableCredential", exports.REPUTATION_CREDENTIAL_TYPE],
220
+ issuer: issuerDid,
221
+ issuanceDate: now,
222
+ expirationDate: options?.expirationDate,
223
+ credentialSubject: {
224
+ id: agentDid,
225
+ reputation: {
226
+ score: score.score,
227
+ confidence: score.confidence,
228
+ confidenceLevel: score.confidenceLevel,
229
+ level: score.level,
230
+ isProvisional: score.isProvisional,
231
+ calculatedAt: score.calculatedAt,
232
+ components: score.components,
233
+ },
234
+ context: options?.context,
235
+ },
236
+ credentialStatus: options?.credentialStatus,
237
+ };
238
+ }
239
+ /**
240
+ * Extract reputation score from a reputation credential
241
+ *
242
+ * @param credential - The reputation credential
243
+ * @returns Reputation score data
244
+ */
245
+ function extractReputationFromCredential(credential) {
246
+ const rep = credential.credentialSubject.reputation;
247
+ return {
248
+ score: rep.score,
249
+ confidence: rep.confidence,
250
+ confidenceLevel: rep.confidenceLevel,
251
+ level: rep.level,
252
+ isProvisional: rep.isProvisional,
253
+ calculatedAt: rep.calculatedAt,
254
+ agentDid: credential.credentialSubject.id,
255
+ components: rep.components || {
256
+ priorScore: 50,
257
+ empiricalScore: rep.score,
258
+ confidenceWeight: rep.confidence,
259
+ priorWeight: 1 - rep.confidence,
260
+ },
261
+ };
262
+ }
263
+ /**
264
+ * Check if a reputation credential has expired
265
+ *
266
+ * @param credential - The credential to check
267
+ * @returns true if expired
268
+ */
269
+ function isReputationCredentialExpired(credential) {
270
+ if (!credential.expirationDate) {
271
+ return false;
272
+ }
273
+ const expiration = new Date(credential.expirationDate);
274
+ const now = new Date();
275
+ return expiration < now;
276
+ }
277
+ /**
278
+ * Check if the reputation score in a credential is stale
279
+ * (calculated too long ago to be reliable)
280
+ *
281
+ * @param credential - The credential to check
282
+ * @param maxAgeMs - Maximum age in milliseconds (default: 24 hours)
283
+ * @returns true if stale
284
+ */
285
+ function isReputationCredentialStale(credential, maxAgeMs = 24 * 60 * 60 * 1000 // 24 hours
286
+ ) {
287
+ const calculatedAt = new Date(credential.credentialSubject.reputation.calculatedAt);
288
+ const now = new Date();
289
+ const age = now.getTime() - calculatedAt.getTime();
290
+ return age > maxAgeMs;
291
+ }
292
+ // ============================================================================
293
+ // CONSTANTS
294
+ // ============================================================================
295
+ /**
296
+ * Default reputation credential validity period (7 days)
297
+ */
298
+ exports.DEFAULT_REPUTATION_CREDENTIAL_VALIDITY_MS = 7 * 24 * 60 * 60 * 1000;
299
+ /**
300
+ * Recommended maximum age for reputation scores (24 hours)
301
+ */
302
+ exports.RECOMMENDED_REPUTATION_FRESHNESS_MS = 24 * 60 * 60 * 1000;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Reputation Module Exports
3
+ *
4
+ * This module provides types, schemas, and utilities for the Bayesian
5
+ * reputation scoring system. It includes:
6
+ *
7
+ * - Core schemas for AgentData, ReputationScore, and components
8
+ * - API request/response schemas for REST endpoints
9
+ * - W3C Verifiable Credential schemas for reputation attestations
10
+ * - Configuration constants and presets
11
+ *
12
+ * Usage:
13
+ * import { AgentDataSchema, ReputationScore } from '@kya-os/contracts/reputation';
14
+ *
15
+ * Related Spec: MCP-I §5 (Reputation)
16
+ */
17
+ export * from "./schemas.js";
18
+ export * from "./api.js";
19
+ export * from "./credentials.js";
20
+ export * from "./constants.js";
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ /**
3
+ * Reputation Module Exports
4
+ *
5
+ * This module provides types, schemas, and utilities for the Bayesian
6
+ * reputation scoring system. It includes:
7
+ *
8
+ * - Core schemas for AgentData, ReputationScore, and components
9
+ * - API request/response schemas for REST endpoints
10
+ * - W3C Verifiable Credential schemas for reputation attestations
11
+ * - Configuration constants and presets
12
+ *
13
+ * Usage:
14
+ * import { AgentDataSchema, ReputationScore } from '@kya-os/contracts/reputation';
15
+ *
16
+ * Related Spec: MCP-I §5 (Reputation)
17
+ */
18
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
19
+ if (k2 === undefined) k2 = k;
20
+ var desc = Object.getOwnPropertyDescriptor(m, k);
21
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
22
+ desc = { enumerable: true, get: function() { return m[k]; } };
23
+ }
24
+ Object.defineProperty(o, k2, desc);
25
+ }) : (function(o, m, k, k2) {
26
+ if (k2 === undefined) k2 = k;
27
+ o[k2] = m[k];
28
+ }));
29
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
30
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
31
+ };
32
+ Object.defineProperty(exports, "__esModule", { value: true });
33
+ // Core schemas and types
34
+ __exportStar(require("./schemas.js"), exports);
35
+ // API schemas
36
+ __exportStar(require("./api.js"), exports);
37
+ // Credential schemas (W3C VC)
38
+ __exportStar(require("./credentials.js"), exports);
39
+ // Constants and configuration
40
+ __exportStar(require("./constants.js"), exports);