@oxyhq/contracts 0.19.0 → 0.21.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.
@@ -0,0 +1,293 @@
1
+ /**
2
+ * Oxy Trust — reputation API contracts.
3
+ *
4
+ * SINGLE SOURCE OF TRUTH for the reputation ledger's wire shapes: the closed
5
+ * value sets (`REPUTATION_CATEGORIES`, `TRUST_TIERS`, …), the response entities
6
+ * (`ReputationTransaction`, the two balance views, `ReputationDispute`,
7
+ * `ReputationRule`, the leaderboard entry) and the request bodies the write
8
+ * endpoints accept. The API validates its OUTPUT against these schemas and its
9
+ * INPUT with the same request schemas the SDK's input types are derived from;
10
+ * `@oxyhq/core`'s reputation mixin imports every type from here rather than
11
+ * declaring its own.
12
+ *
13
+ * Why this module exists: the balance endpoint was view-split server-side
14
+ * without the SDK type moving with it, and for hours the SDK affirmatively
15
+ * type-checked a read of `balance.reliability.reportAccuracyScore` against a
16
+ * response that no longer carried `reliability`. Nothing structural connected
17
+ * the API's hand-written serializers (which returned `Record<string, unknown>`)
18
+ * to the SDK's interfaces — only human attention. With the serializers
19
+ * annotated against these definitions, that divergence is a build failure.
20
+ *
21
+ * Design anchors:
22
+ * - **Ids are strings, timestamps are ISO 8601 strings.** The server holds
23
+ * `ObjectId`s and `Date`s; every serializer converts at the boundary, so a
24
+ * `Date` leaking into a field this module types as `string` fails to compile.
25
+ * - **The balance has two views, and the union is the contract.** See
26
+ * {@link ReputationBalanceView} — the compile-time assertions below are what
27
+ * stop the private view's fields becoming reachable on a stranger's balance.
28
+ * - **The closed value sets live here, not beside the mongoose models.** The
29
+ * API's model enums and the SDK's unions are the same `as const` tuple, so a
30
+ * seventh category cannot be added on one side only.
31
+ *
32
+ * The response entities are declared as explicit `interface`s with their runtime
33
+ * schemas annotated `z.ZodType<Interface>`, following `./links` and
34
+ * `./userResponse`: a `z.infer<>` of a nested-object schema can degrade to `{}`
35
+ * under a consumer's `moduleResolution: "node"` (node10) resolution, while a
36
+ * literal interface emits the field types verbatim in the `.d.ts` and survives
37
+ * both `node` and `bundler`.
38
+ *
39
+ * Platform-agnostic — zod only, no react/react-native/expo. ESM-safe (no
40
+ * `require()`).
41
+ */
42
+ import { z } from 'zod';
43
+ import { userNameSchema } from './userResponse.js';
44
+ import { reputationConductSchema, reputationContextualInfluenceSchema, reputationContributionSchema, reputationPersonhoodSchema, reputationReportingSchema, reputationReviewingSchema, } from './moderationReputation.js';
45
+ /* -------------------------------------------------------------------------- */
46
+ /* Closed value sets */
47
+ /* -------------------------------------------------------------------------- */
48
+ /**
49
+ * Category bucket a reputation transaction falls into. Drives the per-category
50
+ * balance breakdown; every rule and transaction carries exactly one.
51
+ *
52
+ * - `content` — posts, comments, media a user authored.
53
+ * - `social` — follows, likes, social interactions.
54
+ * - `trust` — identity / verification / trust-graph signals.
55
+ * - `moderation` — reports filed, moderation actions, review outcomes.
56
+ * - `physical` — real-world signals (event check-ins, verified purchases).
57
+ * - `penalty` — negative adjustments for abuse / policy violations.
58
+ * - `other` — anything that does not fit the buckets above.
59
+ */
60
+ export const REPUTATION_CATEGORIES = [
61
+ 'content',
62
+ 'social',
63
+ 'trust',
64
+ 'moderation',
65
+ 'physical',
66
+ 'penalty',
67
+ 'other',
68
+ ];
69
+ export const reputationCategorySchema = z.enum(REPUTATION_CATEGORIES);
70
+ /**
71
+ * Transaction lifecycle status.
72
+ *
73
+ * - `active` — counts toward the balance.
74
+ * - `disputed` — under dispute; still counts until the dispute resolves.
75
+ * - `reversed` — superseded by a compensating reversal transaction; excluded.
76
+ * - `voided` — administratively excluded with no compensating entry.
77
+ */
78
+ export const REPUTATION_TRANSACTION_STATUSES = [
79
+ 'active',
80
+ 'disputed',
81
+ 'reversed',
82
+ 'voided',
83
+ ];
84
+ export const reputationTransactionStatusSchema = z.enum(REPUTATION_TRANSACTION_STATUSES);
85
+ /**
86
+ * Trust tiers, lowest → highest trust, plus the punitive `restricted`.
87
+ *
88
+ * Publicly visible: this is the contribution ladder the reputation system
89
+ * exists to publish. Note it doubles as the sanction marker — a `restricted`
90
+ * account is publicly identifiable as such.
91
+ */
92
+ export const TRUST_TIERS = ['restricted', 'new', 'trusted', 'high_trust', 'verified'];
93
+ export const trustTierSchema = z.enum(TRUST_TIERS);
94
+ /** Kind of entity a transaction may target. */
95
+ export const REPUTATION_TARGET_ENTITY_TYPES = [
96
+ 'post',
97
+ 'comment',
98
+ 'report',
99
+ 'purchase',
100
+ 'event',
101
+ 'check_in',
102
+ 'manual_review',
103
+ 'user',
104
+ 'other',
105
+ ];
106
+ export const reputationTargetEntityTypeSchema = z.enum(REPUTATION_TARGET_ENTITY_TYPES);
107
+ /** Dispute lifecycle status. */
108
+ export const REPUTATION_DISPUTE_STATUSES = [
109
+ 'open',
110
+ 'accepted',
111
+ 'rejected',
112
+ 'needs_review',
113
+ ];
114
+ export const reputationDisputeStatusSchema = z.enum(REPUTATION_DISPUTE_STATUSES);
115
+ /** Influence context selecting which capped weight axis to read. */
116
+ export const REPUTATION_INFLUENCE_CONTEXTS = [
117
+ 'default',
118
+ 'report',
119
+ 'moderation',
120
+ 'ranking',
121
+ ];
122
+ export const reputationInfluenceContextSchema = z.enum(REPUTATION_INFLUENCE_CONTEXTS);
123
+ export const reputationTransactionSchema = z.object({
124
+ id: z.string(),
125
+ userId: z.string(),
126
+ points: z.number(),
127
+ actionType: z.string(),
128
+ category: reputationCategorySchema,
129
+ applicationId: z.string().optional(),
130
+ credentialId: z.string().optional(),
131
+ sourceActionId: z.string().optional(),
132
+ sourceActionType: z.string().optional(),
133
+ targetEntityId: z.string().optional(),
134
+ targetEntityType: reputationTargetEntityTypeSchema.optional(),
135
+ status: reputationTransactionStatusSchema,
136
+ reversedTransactionId: z.string().optional(),
137
+ reason: z.string().optional(),
138
+ metadata: z.record(z.unknown()).optional(),
139
+ createdByUserId: z.string().optional(),
140
+ reviewedByUserId: z.string().optional(),
141
+ reviewedAt: z.string().optional(),
142
+ createdAt: z.string(),
143
+ updatedAt: z.string(),
144
+ });
145
+ export const reputationBalanceBreakdownSchema = z.object({
146
+ content: z.number(),
147
+ social: z.number(),
148
+ trust: z.number(),
149
+ moderation: z.number(),
150
+ physical: z.number(),
151
+ penalties: z.number(),
152
+ });
153
+ export const reputationInfluenceSchema = z.object({
154
+ defaultWeight: z.number(),
155
+ reportWeight: z.number(),
156
+ moderationWeight: z.number(),
157
+ rankingFeedbackWeight: z.number(),
158
+ });
159
+ export const reputationReliabilitySchema = z.object({
160
+ accurateReports: z.number(),
161
+ rejectedReports: z.number(),
162
+ reportAccuracyScore: z.number(),
163
+ abuseScore: z.number(),
164
+ });
165
+ /** The fields both balance views share. Kept as a shape so the full view can spread it. */
166
+ const balanceSummaryShape = {
167
+ userId: z.string(),
168
+ total: z.number(),
169
+ trustTier: trustTierSchema,
170
+ };
171
+ export const reputationBalanceSummarySchema = z.object(balanceSummaryShape);
172
+ export const reputationBalanceSchema = z.object({
173
+ ...balanceSummaryShape,
174
+ positive: z.number(),
175
+ negative: z.number(),
176
+ breakdown: reputationBalanceBreakdownSchema,
177
+ influence: reputationInfluenceSchema,
178
+ reliability: reputationReliabilitySchema,
179
+ recalculatedAt: z.string(),
180
+ updatedAt: z.string(),
181
+ personhood: reputationPersonhoodSchema.optional(),
182
+ contribution: reputationContributionSchema.optional(),
183
+ conduct: reputationConductSchema.optional(),
184
+ reporting: reputationReportingSchema.optional(),
185
+ reviewing: reputationReviewingSchema.optional(),
186
+ contextualInfluence: reputationContextualInfluenceSchema.optional(),
187
+ });
188
+ /**
189
+ * The fields the full {@link ReputationBalance} carries beyond the public
190
+ * {@link ReputationBalanceSummary} that the API sends ALL-OR-NOTHING. The
191
+ * runtime discriminant between the two views.
192
+ *
193
+ * The V2 blocks (`conduct`, `contribution`, …) are deliberately NOT listed:
194
+ * they are optional on the wire, so requiring them here would make a balance
195
+ * from a server that predates them fail to narrow, hiding the whole private
196
+ * view. Read a V2 block by checking that block.
197
+ */
198
+ const FULL_BALANCE_FIELDS = [
199
+ 'positive',
200
+ 'negative',
201
+ 'breakdown',
202
+ 'influence',
203
+ 'reliability',
204
+ 'recalculatedAt',
205
+ 'updatedAt',
206
+ ];
207
+ /**
208
+ * Whether a balance came back as the SUBJECT view, and so carries the
209
+ * breakdown / influence / reliability blocks.
210
+ *
211
+ * Checks every extra field rather than one representative: the point of the
212
+ * guard is that the caller then dereferences those blocks, so a partial payload
213
+ * must not narrow.
214
+ *
215
+ * @param balance - A balance from `getReputationBalance`.
216
+ */
217
+ export function isFullReputationBalance(balance) {
218
+ return FULL_BALANCE_FIELDS.every((field) => field in balance);
219
+ }
220
+ export const reputationDisputeSchema = z.object({
221
+ id: z.string(),
222
+ transactionId: z.string(),
223
+ userId: z.string(),
224
+ reason: z.string(),
225
+ status: reputationDisputeStatusSchema,
226
+ evidence: z.array(z.string()).optional(),
227
+ resolvedAt: z.string().optional(),
228
+ resolvedByUserId: z.string().optional(),
229
+ createdAt: z.string(),
230
+ updatedAt: z.string(),
231
+ });
232
+ export const reputationRuleSchema = z.object({
233
+ id: z.string(),
234
+ actionType: z.string(),
235
+ points: z.number(),
236
+ category: reputationCategorySchema,
237
+ description: z.string(),
238
+ cooldownInMinutes: z.number(),
239
+ isEnabled: z.boolean(),
240
+ });
241
+ export const reputationLeaderboardUserSchema = z.object({
242
+ id: z.string(),
243
+ username: z.string(),
244
+ name: userNameSchema,
245
+ avatar: z.string().optional(),
246
+ publicKey: z.string().optional(),
247
+ });
248
+ export const reputationLeaderboardEntrySchema = z.object({
249
+ user: reputationLeaderboardUserSchema,
250
+ total: z.number(),
251
+ trustTier: trustTierSchema,
252
+ rank: z.number(),
253
+ });
254
+ export const reputationInfluenceResultSchema = z.object({
255
+ context: reputationInfluenceContextSchema,
256
+ weight: z.number(),
257
+ influence: reputationInfluenceSchema,
258
+ });
259
+ export const reverseReputationTransactionResultSchema = z.object({
260
+ original: reputationTransactionSchema,
261
+ reversal: reputationTransactionSchema,
262
+ });
263
+ export const awardReputationSchema = z.object({
264
+ userId: z.string().trim().min(1),
265
+ actionType: z.string().trim().min(1),
266
+ applicationId: z.string().trim().min(1).optional(),
267
+ credentialId: z.string().trim().min(1).optional(),
268
+ sourceActionId: z.string().trim().min(1).optional(),
269
+ sourceActionType: z.string().trim().min(1).optional(),
270
+ targetEntityId: z.string().trim().min(1).optional(),
271
+ targetEntityType: reputationTargetEntityTypeSchema.optional(),
272
+ reason: z.string().trim().max(500).optional(),
273
+ metadata: z.record(z.unknown()).optional(),
274
+ });
275
+ export const createReputationDisputeSchema = z.object({
276
+ transactionId: z.string().trim().min(1),
277
+ reason: z.string().trim().min(1).max(1000),
278
+ evidence: z.array(z.string().trim().min(1)).max(20).optional(),
279
+ });
280
+ export const resolveReputationDisputeSchema = z.object({
281
+ status: z.enum(['accepted', 'rejected']),
282
+ });
283
+ export const upsertReputationRuleSchema = z.object({
284
+ actionType: z.string().trim().min(1),
285
+ points: z.number(),
286
+ category: reputationCategorySchema,
287
+ description: z.string().trim().min(1).max(500),
288
+ cooldownInMinutes: z.number().int().min(0).default(0),
289
+ isEnabled: z.boolean().default(true),
290
+ });
291
+ export const reverseReputationTransactionSchema = z.object({
292
+ reason: z.string().trim().max(500).optional(),
293
+ });
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Canonical contract for the Oxy user-invalidation broadcast.
3
+ *
4
+ * Oxy owns identity, but consumers cache it: Mention keeps a Redis summary per
5
+ * post author, and every backend using `@oxyhq/core` holds the SDK's own GET
6
+ * response cache. Both go stale the moment a profile is edited, and neither has
7
+ * any way to find out — the writer is a different process in a different repo.
8
+ * This is the signal that tells them.
9
+ *
10
+ * The channel name and the payload shape are wire contracts between oxy-api (the
11
+ * publisher) and every consuming backend (the subscribers), so they live here
12
+ * rather than in either side. A hand-typed copy of the channel name fails as
13
+ * "the invalidation never arrives" — silently, because pub/sub has no delivery
14
+ * receipt and a message nobody is listening for is indistinguishable from a
15
+ * message nobody sent.
16
+ *
17
+ * DELIVERY IS AT-MOST-ONCE, AND THAT IS THE DESIGN. Every consumer's cache still
18
+ * carries its own TTL, so a dropped message degrades to exactly the behaviour
19
+ * before this signal existed and never to something worse. That property is what
20
+ * makes a bare Redis PUBLISH sufficient here and an outbox, retries, delivery
21
+ * receipts and payload signatures unnecessary. Do not treat a received event as
22
+ * authoritative for anything except "re-read this user from Oxy".
23
+ *
24
+ * PRIVACY — the payload carries NO user data, only an id, a reason and a
25
+ * timestamp. The channel rides the shared Valkey that every Oxy backend can
26
+ * subscribe to, so anything placed on it is readable by every service in the
27
+ * ecosystem. Never add a name, handle, email, avatar or any profile field: a
28
+ * subscriber that wants the new values re-reads them from Oxy through its normal
29
+ * authenticated path, where the usual authorization applies.
30
+ *
31
+ * Platform-agnostic — zod only, no react/react-native/expo.
32
+ */
33
+ import { z } from 'zod';
34
+ /** Redis pub/sub channel carrying user-invalidation events. */
35
+ export const OXY_USER_INVALIDATION_CHANNEL = 'oxy:user:invalidate';
36
+ /**
37
+ * Why a user record changed, as classified by the writer in oxy-api.
38
+ *
39
+ * - `profile` — anything a consumer renders or caches as IDENTITY: display name,
40
+ * username, avatar, bio, verification, federation fields, account status. This
41
+ * is the DEFAULT for every writer, so a site that forgets to classify itself
42
+ * over-invalidates (correct, marginally slower) rather than under-invalidates
43
+ * (silently wrong). Keep that asymmetry if you add a reason.
44
+ * - `graph` — follow-edge churn only (follower/following counts). High frequency,
45
+ * and bulk follow/unfollow moves up to 200 edges in one call. Nothing renders
46
+ * identity from it and a stale count is harmless to ranking, so it is NOT
47
+ * broadcast — see {@link OXY_PUBLISHED_USER_CHANGE_REASONS}.
48
+ */
49
+ export const OXY_USER_CHANGE_REASONS = ['profile', 'graph'];
50
+ /**
51
+ * The reasons that are actually put on the wire.
52
+ *
53
+ * A reason absent from this list is a local cache eviction in oxy-api and
54
+ * nothing more: no message is published at all, rather than a message every
55
+ * subscriber receives and discards. The distinction matters at bulk-follow
56
+ * scale, where the discarded variant is a 200-message burst on a channel every
57
+ * Oxy backend is subscribed to.
58
+ *
59
+ * This is deliberately a shared list rather than a check inside the publisher:
60
+ * a subscriber needs to know what it can receive, and the schema below rejects
61
+ * anything else, so publisher and subscriber cannot drift into disagreeing about
62
+ * which events exist. Adding a reason therefore forces an explicit decision about
63
+ * whether it broadcasts.
64
+ */
65
+ export const OXY_PUBLISHED_USER_CHANGE_REASONS = ['profile'];
66
+ /** Whether a change of this kind is broadcast to consumers at all. */
67
+ export function isPublishedOxyUserChangeReason(reason) {
68
+ return OXY_PUBLISHED_USER_CHANGE_REASONS.includes(reason);
69
+ }
70
+ /**
71
+ * A single user-invalidation event.
72
+ *
73
+ * `at` is the publisher's epoch-ms clock, carried for diagnosis (measuring
74
+ * end-to-end propagation, spotting a wedged subscriber) — never for ordering or
75
+ * conflict resolution. Two Oxy tasks publish from unsynchronised clocks, and the
76
+ * event says only "re-read this user", which is idempotent and order-independent.
77
+ */
78
+ export const oxyUserInvalidationEventSchema = z.object({
79
+ /** The Oxy user whose record changed. */
80
+ userId: z.string().min(1),
81
+ /** Why it changed. Only broadcast reasons appear on the wire. */
82
+ reason: z.enum(OXY_PUBLISHED_USER_CHANGE_REASONS),
83
+ /** Publisher's epoch-ms timestamp. Diagnostic only. */
84
+ at: z.number().int().nonnegative(),
85
+ });