@oxy.so/contracts 1.0.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.
Files changed (147) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +16 -0
  3. package/dist/cjs/.tsbuildinfo +1 -0
  4. package/dist/cjs/accountGraph.js +489 -0
  5. package/dist/cjs/agency.js +439 -0
  6. package/dist/cjs/browserHub.js +215 -0
  7. package/dist/cjs/civic.js +163 -0
  8. package/dist/cjs/commonsSignIn.js +59 -0
  9. package/dist/cjs/deviceBoot.js +50 -0
  10. package/dist/cjs/deviceDirectory.js +189 -0
  11. package/dist/cjs/devicePairing.js +138 -0
  12. package/dist/cjs/deviceSession.js +164 -0
  13. package/dist/cjs/emailAgentContext.js +32 -0
  14. package/dist/cjs/followGraph.js +28 -0
  15. package/dist/cjs/identity.js +258 -0
  16. package/dist/cjs/inboxPush.js +24 -0
  17. package/dist/cjs/index.js +618 -0
  18. package/dist/cjs/inference/accountBilling.js +334 -0
  19. package/dist/cjs/inference/aliaModelRelease.js +262 -0
  20. package/dist/cjs/inference/attribution.js +106 -0
  21. package/dist/cjs/inference/catalogue.js +487 -0
  22. package/dist/cjs/inference/entitlement.js +217 -0
  23. package/dist/cjs/inference/errors.js +309 -0
  24. package/dist/cjs/inference/identifiers.js +224 -0
  25. package/dist/cjs/inference/inbox.js +105 -0
  26. package/dist/cjs/inference/modelDocumentation.js +433 -0
  27. package/dist/cjs/inference/money.js +188 -0
  28. package/dist/cjs/inference/priceVersion.js +110 -0
  29. package/dist/cjs/inference/providerConnection.js +455 -0
  30. package/dist/cjs/inference/request.js +477 -0
  31. package/dist/cjs/inference/routingPolicy.js +318 -0
  32. package/dist/cjs/inference/streamEvents.js +258 -0
  33. package/dist/cjs/inference/usage.js +329 -0
  34. package/dist/cjs/inference/version.js +105 -0
  35. package/dist/cjs/keyRecovery.js +91 -0
  36. package/dist/cjs/keyRotation.js +75 -0
  37. package/dist/cjs/links.js +68 -0
  38. package/dist/cjs/moderationReputation.js +298 -0
  39. package/dist/cjs/oauth.js +66 -0
  40. package/dist/cjs/oxyRecordTypes.js +71 -0
  41. package/dist/cjs/protocol.js +53 -0
  42. package/dist/cjs/recommendations.js +168 -0
  43. package/dist/cjs/reputation.js +297 -0
  44. package/dist/cjs/sessionStatus.js +121 -0
  45. package/dist/cjs/transparency.js +89 -0
  46. package/dist/cjs/updates.js +252 -0
  47. package/dist/cjs/userInvalidation.js +89 -0
  48. package/dist/cjs/userResponse.js +245 -0
  49. package/dist/cjs/username.js +290 -0
  50. package/dist/cjs/webauthn.js +71 -0
  51. package/dist/esm/.tsbuildinfo +1 -0
  52. package/dist/esm/accountGraph.js +480 -0
  53. package/dist/esm/agency.js +436 -0
  54. package/dist/esm/browserHub.js +212 -0
  55. package/dist/esm/civic.js +160 -0
  56. package/dist/esm/commonsSignIn.js +56 -0
  57. package/dist/esm/deviceBoot.js +47 -0
  58. package/dist/esm/deviceDirectory.js +186 -0
  59. package/dist/esm/devicePairing.js +135 -0
  60. package/dist/esm/deviceSession.js +161 -0
  61. package/dist/esm/emailAgentContext.js +29 -0
  62. package/dist/esm/followGraph.js +27 -0
  63. package/dist/esm/identity.js +255 -0
  64. package/dist/esm/inboxPush.js +21 -0
  65. package/dist/esm/index.js +172 -0
  66. package/dist/esm/inference/accountBilling.js +331 -0
  67. package/dist/esm/inference/aliaModelRelease.js +259 -0
  68. package/dist/esm/inference/attribution.js +103 -0
  69. package/dist/esm/inference/catalogue.js +484 -0
  70. package/dist/esm/inference/entitlement.js +214 -0
  71. package/dist/esm/inference/errors.js +306 -0
  72. package/dist/esm/inference/identifiers.js +221 -0
  73. package/dist/esm/inference/inbox.js +102 -0
  74. package/dist/esm/inference/modelDocumentation.js +430 -0
  75. package/dist/esm/inference/money.js +185 -0
  76. package/dist/esm/inference/priceVersion.js +107 -0
  77. package/dist/esm/inference/providerConnection.js +452 -0
  78. package/dist/esm/inference/request.js +474 -0
  79. package/dist/esm/inference/routingPolicy.js +315 -0
  80. package/dist/esm/inference/streamEvents.js +255 -0
  81. package/dist/esm/inference/usage.js +326 -0
  82. package/dist/esm/inference/version.js +102 -0
  83. package/dist/esm/keyRecovery.js +88 -0
  84. package/dist/esm/keyRotation.js +72 -0
  85. package/dist/esm/links.js +65 -0
  86. package/dist/esm/moderationReputation.js +295 -0
  87. package/dist/esm/oauth.js +63 -0
  88. package/dist/esm/oxyRecordTypes.js +68 -0
  89. package/dist/esm/protocol.js +50 -0
  90. package/dist/esm/recommendations.js +165 -0
  91. package/dist/esm/reputation.js +293 -0
  92. package/dist/esm/sessionStatus.js +118 -0
  93. package/dist/esm/transparency.js +86 -0
  94. package/dist/esm/updates.js +249 -0
  95. package/dist/esm/userInvalidation.js +85 -0
  96. package/dist/esm/userResponse.js +240 -0
  97. package/dist/esm/username.js +283 -0
  98. package/dist/esm/webauthn.js +68 -0
  99. package/dist/types/.tsbuildinfo +1 -0
  100. package/dist/types/accountGraph.d.ts +378 -0
  101. package/dist/types/agency.d.ts +2162 -0
  102. package/dist/types/browserHub.d.ts +856 -0
  103. package/dist/types/civic.d.ts +338 -0
  104. package/dist/types/commonsSignIn.d.ts +58 -0
  105. package/dist/types/deviceBoot.d.ts +74 -0
  106. package/dist/types/deviceDirectory.d.ts +1317 -0
  107. package/dist/types/devicePairing.d.ts +130 -0
  108. package/dist/types/deviceSession.d.ts +411 -0
  109. package/dist/types/emailAgentContext.d.ts +248 -0
  110. package/dist/types/followGraph.d.ts +150 -0
  111. package/dist/types/identity.d.ts +402 -0
  112. package/dist/types/inboxPush.d.ts +30 -0
  113. package/dist/types/index.d.ts +100 -0
  114. package/dist/types/inference/accountBilling.d.ts +738 -0
  115. package/dist/types/inference/aliaModelRelease.d.ts +609 -0
  116. package/dist/types/inference/attribution.d.ts +176 -0
  117. package/dist/types/inference/catalogue.d.ts +1618 -0
  118. package/dist/types/inference/entitlement.d.ts +519 -0
  119. package/dist/types/inference/errors.d.ts +242 -0
  120. package/dist/types/inference/identifiers.d.ts +182 -0
  121. package/dist/types/inference/inbox.d.ts +374 -0
  122. package/dist/types/inference/modelDocumentation.d.ts +1603 -0
  123. package/dist/types/inference/money.d.ts +185 -0
  124. package/dist/types/inference/priceVersion.d.ts +182 -0
  125. package/dist/types/inference/providerConnection.d.ts +968 -0
  126. package/dist/types/inference/request.d.ts +2800 -0
  127. package/dist/types/inference/routingPolicy.d.ts +616 -0
  128. package/dist/types/inference/streamEvents.d.ts +950 -0
  129. package/dist/types/inference/usage.d.ts +1164 -0
  130. package/dist/types/inference/version.d.ts +102 -0
  131. package/dist/types/keyRecovery.d.ts +138 -0
  132. package/dist/types/keyRotation.d.ts +103 -0
  133. package/dist/types/links.d.ts +96 -0
  134. package/dist/types/moderationReputation.d.ts +487 -0
  135. package/dist/types/oauth.d.ts +86 -0
  136. package/dist/types/oxyRecordTypes.d.ts +62 -0
  137. package/dist/types/protocol.d.ts +86 -0
  138. package/dist/types/recommendations.d.ts +542 -0
  139. package/dist/types/reputation.d.ts +457 -0
  140. package/dist/types/sessionStatus.d.ts +231 -0
  141. package/dist/types/transparency.d.ts +392 -0
  142. package/dist/types/updates.d.ts +545 -0
  143. package/dist/types/userInvalidation.d.ts +94 -0
  144. package/dist/types/userResponse.d.ts +1706 -0
  145. package/dist/types/username.d.ts +265 -0
  146. package/dist/types/webauthn.d.ts +77 -0
  147. package/package.json +87 -0
@@ -0,0 +1,295 @@
1
+ /**
2
+ * Oxy Trust — the moderation reputation bridge (CrowdSource → Oxy Trust).
3
+ *
4
+ * SINGLE SOURCE OF TRUTH for the wire shapes crossing the one-way boundary
5
+ * between a participatory-moderation service and the Oxy reputation ledger.
6
+ *
7
+ * The direction is not negotiable: a moderation service NEVER writes reputation.
8
+ * It emits an authenticated internal event describing a decision it published,
9
+ * and Oxy's own consequence engine validates that event and derives the effect.
10
+ * Everything in this module is therefore either (a) the event, (b) the receipt
11
+ * the engine returns, or (c) the derived state the engine publishes back to the
12
+ * subject.
13
+ *
14
+ * Design anchors, all load-bearing:
15
+ *
16
+ * - **Conduct is a separate axis from contribution.** A conduct penalty raises
17
+ * `activeRisk` and creates a strike; positive contribution points can never
18
+ * cancel a strike, because standing is derived from active risk and not from
19
+ * the point total. See {@link ReputationConduct}.
20
+ * - **The reporting axis carries only reporting signals.** `abuseScore` on the
21
+ * legacy reliability block conflated rejected reports with every negative
22
+ * transaction; {@link ReputationReporting} exists so a conduct penalty can
23
+ * never inflate a report-abuse figure.
24
+ * - **No binding proof, no effect.** {@link ModerationDecisionEventSubject}
25
+ * requires a `bindingProofId`, and the engine rejects an event whose binding
26
+ * does not resolve to the claimed principal at or before `occurredAt`. An
27
+ * application cannot move a reputation figure by naming a user id.
28
+ * - **One penalty per incident.** The idempotency key is
29
+ * `moderation:<incidentId>:<decisionRevision>:<effectType>`; a hundred
30
+ * reports about the same material produce one effect.
31
+ * - **Every effect carries the policy version it was decided under**, so a
32
+ * consequence can be recomputed under the original policy rather than under
33
+ * whatever the current tuning happens to be.
34
+ *
35
+ * Platform-agnostic — zod only. ESM-safe (no `require()`).
36
+ */
37
+ import { z } from 'zod';
38
+ /* -------------------------------------------------------------------------- */
39
+ /* Closed value sets */
40
+ /* -------------------------------------------------------------------------- */
41
+ /**
42
+ * Severity band of a moderation finding, lowest → highest.
43
+ *
44
+ * The band — not the taxonomy code — is what the consequence engine consumes:
45
+ * points, active risk and expiry are all keyed by severity in the versioned
46
+ * conduct policy, so a new taxonomy code needs no engine change and no
47
+ * intimate category ever reaches the ledger.
48
+ */
49
+ export const MODERATION_SEVERITIES = ['low', 'medium', 'high', 'critical'];
50
+ export const moderationSeveritySchema = z.enum(MODERATION_SEVERITIES);
51
+ /**
52
+ * How far a finding reaches.
53
+ *
54
+ * - `application_local` — the application enforces locally; Oxy Trust is NOT
55
+ * touched. Emitted for completeness; the engine rejects the effect.
56
+ * - `oxy_network` — conduct against the Oxy network as a whole.
57
+ * - `identity_integrity` — impersonation, sybil behaviour, credential abuse.
58
+ *
59
+ * Only `oxy_network` and `identity_integrity` can produce a global effect.
60
+ */
61
+ export const MODERATION_FINDING_SCOPES = [
62
+ 'application_local',
63
+ 'oxy_network',
64
+ 'identity_integrity',
65
+ ];
66
+ export const moderationFindingScopeSchema = z.enum(MODERATION_FINDING_SCOPES);
67
+ /** Which participant in the reported material the finding attributes to. */
68
+ export const MODERATION_ATTRIBUTIONS = ['author', 'sharer', 'reporter', 'reviewer'];
69
+ export const moderationAttributionSchema = z.enum(MODERATION_ATTRIBUTIONS);
70
+ /**
71
+ * Lifecycle of the decision the event describes.
72
+ *
73
+ * `inconclusive` is its own outcome and never collapses into "no violation";
74
+ * it simply produces no effect. `superseded` and `corrected` describe a
75
+ * revision that a later one replaced — an event in either state is rejected,
76
+ * because applying it would resurrect a consequence the appeal removed.
77
+ */
78
+ export const MODERATION_DECISION_STATUSES = [
79
+ 'provisional',
80
+ 'final',
81
+ 'inconclusive',
82
+ 'superseded',
83
+ 'corrected',
84
+ ];
85
+ export const moderationDecisionStatusSchema = z.enum(MODERATION_DECISION_STATUSES);
86
+ /**
87
+ * The kind of consequence an effect carries. Each is its own axis, and the
88
+ * idempotency key includes it — one incident may legitimately produce a conduct
89
+ * effect for the author AND a report-abuse effect for a malicious reporter.
90
+ */
91
+ export const MODERATION_EFFECT_TYPES = [
92
+ 'conduct_penalty',
93
+ 'report_abuse_penalty',
94
+ 'review_abuse_penalty',
95
+ ];
96
+ export const moderationEffectTypeSchema = z.enum(MODERATION_EFFECT_TYPES);
97
+ /** Lifecycle of a stored effect. */
98
+ export const MODERATION_EFFECT_STATUSES = ['applied', 'reversed'];
99
+ export const moderationEffectStatusSchema = z.enum(MODERATION_EFFECT_STATUSES);
100
+ /** Lifecycle of a conduct strike. Only `active` strikes carry active risk. */
101
+ export const CONDUCT_STRIKE_STATUSES = ['active', 'expired', 'reversed'];
102
+ export const conductStrikeStatusSchema = z.enum(CONDUCT_STRIKE_STATUSES);
103
+ /**
104
+ * Conduct standing, derived from ACTIVE RISK and nothing else.
105
+ *
106
+ * Deliberately independent of the point total: a person may hold a high
107
+ * contribution tier and a `limited` standing at the same time, and earning
108
+ * points cannot move standing back toward `good`. Only expiry or reversal can.
109
+ */
110
+ export const CONDUCT_STANDINGS = ['good', 'watch', 'limited', 'restricted'];
111
+ export const conductStandingSchema = z.enum(CONDUCT_STANDINGS);
112
+ /** Contribution tier, derived from contribution points only. */
113
+ export const CONTRIBUTION_TIERS = ['new', 'trusted', 'high_trust'];
114
+ export const contributionTierSchema = z.enum(CONTRIBUTION_TIERS);
115
+ /** Personhood status. Being a real person proves neither conduct nor competence. */
116
+ export const PERSONHOOD_STATUSES = ['unknown', 'probable', 'verified'];
117
+ export const personhoodStatusSchema = z.enum(PERSONHOOD_STATUSES);
118
+ /**
119
+ * How an Oxy identity was bound to the actor an application reported.
120
+ *
121
+ * - `oauth_grant` — the user authorized the application through Oxy's own
122
+ * OAuth flow. Oxy wrote the record; the application asserts nothing.
123
+ * - `session_proof` — the application presented the USER'S OWN Oxy access
124
+ * token alongside its service credential, proving the user was present in
125
+ * that application under a named local principal id.
126
+ * - `commons_signature` — a DID-verifiable signature over a server-issued nonce.
127
+ * - `federated_actor` — a resolvable, authorized federated actor link.
128
+ */
129
+ export const IDENTITY_BINDING_TYPES = [
130
+ 'oauth_grant',
131
+ 'session_proof',
132
+ 'commons_signature',
133
+ 'federated_actor',
134
+ ];
135
+ export const identityBindingTypeSchema = z.enum(IDENTITY_BINDING_TYPES);
136
+ /** Binding lifecycle. A revoked binding proves nothing about a later action. */
137
+ export const IDENTITY_BINDING_STATUSES = ['active', 'revoked'];
138
+ export const identityBindingStatusSchema = z.enum(IDENTITY_BINDING_STATUSES);
139
+ /**
140
+ * An application's own moderation standing. An external application can abuse
141
+ * the system too, so it carries standing exactly like a person does.
142
+ *
143
+ * `sandbox` applications moderate locally and produce NO global effect.
144
+ */
145
+ export const APPLICATION_MODERATION_STANDINGS = ['sandbox', 'trusted', 'restricted'];
146
+ export const applicationModerationStandingSchema = z.enum(APPLICATION_MODERATION_STANDINGS);
147
+ /**
148
+ * Why the engine declined to apply an effect.
149
+ *
150
+ * Returned rather than thrown for the cases that are a legitimate outcome of a
151
+ * well-formed event (a sandboxed application, a local-only finding, an
152
+ * inconclusive decision): the emitter must be able to record "delivered, no
153
+ * effect" and stop retrying. Malformed or unauthorized events are HTTP errors,
154
+ * not skip reasons.
155
+ */
156
+ export const MODERATION_EFFECT_SKIP_REASONS = [
157
+ 'no_binding_proof',
158
+ 'binding_after_action',
159
+ 'binding_principal_mismatch',
160
+ 'binding_revoked',
161
+ 'decision_not_effective',
162
+ 'decision_superseded',
163
+ 'finding_scope_local',
164
+ 'finding_not_in_policy',
165
+ 'application_not_permitted',
166
+ 'no_effective_finding',
167
+ ];
168
+ export const moderationEffectSkipReasonSchema = z.enum(MODERATION_EFFECT_SKIP_REASONS);
169
+ export const moderationFindingSchema = z.object({
170
+ code: z.string().trim().min(1).max(200),
171
+ severity: moderationSeveritySchema,
172
+ scope: moderationFindingScopeSchema,
173
+ attribution: moderationAttributionSchema,
174
+ family: z.string().trim().min(1).max(100),
175
+ });
176
+ export const moderationDecisionEventSubjectSchema = z.object({
177
+ principalType: z.literal('oxy_user'),
178
+ principalId: z.string().trim().min(1),
179
+ bindingProofId: z.string().trim().min(1),
180
+ });
181
+ export const moderationPolicyVersionsSchema = z.object({
182
+ universal: z.string().trim().min(1).max(100),
183
+ application: z.string().trim().min(1).max(100),
184
+ oxyConduct: z.string().trim().min(1).max(100),
185
+ });
186
+ export const moderationDecisionEventSchema = z.object({
187
+ eventId: z.string().trim().min(1).max(200),
188
+ reportedApplicationId: z.string().trim().min(1).max(200),
189
+ type: z.string().trim().min(1).max(200),
190
+ caseId: z.string().trim().min(1).max(200),
191
+ incidentId: z.string().trim().min(1).max(200),
192
+ decisionId: z.string().trim().min(1).max(200),
193
+ decisionRevision: z.number().int().min(1),
194
+ subject: moderationDecisionEventSubjectSchema,
195
+ findings: z.array(moderationFindingSchema).min(1).max(20),
196
+ decisionStatus: moderationDecisionStatusSchema,
197
+ policyVersions: moderationPolicyVersionsSchema,
198
+ occurredAt: z.string().trim().min(1),
199
+ proofHash: z.string().trim().min(1).max(200),
200
+ });
201
+ export const finalizeModerationDecisionSchema = z.object({
202
+ decisionId: z.string().trim().min(1).max(200),
203
+ decisionRevision: z.number().int().min(1),
204
+ });
205
+ export const reverseModerationEffectSchema = z.object({
206
+ decisionId: z.string().trim().min(1).max(200),
207
+ decisionRevision: z.number().int().min(1),
208
+ reason: z.string().trim().min(1).max(500),
209
+ });
210
+ export const moderationEffectSchema = z.object({
211
+ id: z.string(),
212
+ incidentId: z.string(),
213
+ caseId: z.string(),
214
+ decisionId: z.string(),
215
+ decisionRevision: z.number(),
216
+ principalId: z.string(),
217
+ effectType: moderationEffectTypeSchema,
218
+ status: moderationEffectStatusSchema,
219
+ points: z.number(),
220
+ activeRisk: z.number(),
221
+ severity: moderationSeveritySchema,
222
+ repetitionMultiplier: z.number(),
223
+ multiFindingMultiplier: z.number(),
224
+ idempotencyKey: z.string(),
225
+ transactionId: z.string(),
226
+ strikeId: z.string().optional(),
227
+ reversalTransactionId: z.string().optional(),
228
+ policyVersions: moderationPolicyVersionsSchema,
229
+ appliedAt: z.string(),
230
+ reversedAt: z.string().optional(),
231
+ });
232
+ export const applyModerationDecisionResultSchema = z.object({
233
+ applied: z.boolean(),
234
+ effect: moderationEffectSchema.optional(),
235
+ skipReason: moderationEffectSkipReasonSchema.optional(),
236
+ idempotent: z.boolean(),
237
+ });
238
+ export const reverseModerationEffectResultSchema = z.object({
239
+ reversed: z.array(moderationEffectSchema),
240
+ idempotent: z.boolean(),
241
+ });
242
+ export const registerIdentityBindingSchema = z.object({
243
+ localPrincipalId: z.string().trim().min(1).max(200),
244
+ userProofToken: z.string().trim().min(1),
245
+ });
246
+ export const identityBindingSchema = z.object({
247
+ id: z.string(),
248
+ applicationId: z.string(),
249
+ userId: z.string(),
250
+ localPrincipalId: z.string(),
251
+ bindingType: identityBindingTypeSchema,
252
+ status: identityBindingStatusSchema,
253
+ verifiedAt: z.string(),
254
+ createdAt: z.string(),
255
+ });
256
+ export const reputationPersonhoodSchema = z.object({
257
+ status: personhoodStatusSchema,
258
+ score: z.number(),
259
+ });
260
+ export const reputationContributionSchema = z.object({
261
+ points: z.number(),
262
+ tier: contributionTierSchema,
263
+ });
264
+ export const reputationConductSchema = z.object({
265
+ standing: conductStandingSchema,
266
+ activeRisk: z.number(),
267
+ activeStrikes: z.number(),
268
+ nextExpiryAt: z.string().optional(),
269
+ });
270
+ export const reputationReportingSchema = z.object({
271
+ reliability: z.number(),
272
+ confidence: z.number(),
273
+ confirmed: z.number(),
274
+ rejected: z.number(),
275
+ malicious: z.number(),
276
+ });
277
+ export const reputationReviewingSchema = z.object({
278
+ globalReliability: z.number(),
279
+ categoryReliability: z.record(z.number()),
280
+ languageReliability: z.record(z.number()),
281
+ });
282
+ export const reputationContextualInfluenceSchema = z.object({
283
+ reportPriorityWeight: z.number(),
284
+ reviewSelectionWeight: z.number(),
285
+ rankingWeight: z.number(),
286
+ });
287
+ export const applicationModerationTrustSchema = z.object({
288
+ applicationId: z.string(),
289
+ standing: applicationModerationStandingSchema,
290
+ evidenceIntegrity: z.number(),
291
+ identityBindingReliability: z.number(),
292
+ decisionOverturnRate: z.number(),
293
+ policyQuality: z.number(),
294
+ globalReputationEffectsAllowed: z.boolean(),
295
+ });
@@ -0,0 +1,63 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * The two `/auth/oauth/*` responses the browser hub's edge layer reads.
4
+ *
5
+ * They existed on the wire long before this file — `GET /auth/oauth/consent`
6
+ * and `POST /auth/oauth/authorize` are the surface `auth.oxy.so` has always
7
+ * driven with a bearer. What is new (issue #937 Phase 5) is a SECOND consumer
8
+ * that is not the SPA: the IdP's edge layer runs both calls server-side so the
9
+ * device-wide bearer never enters the browser's script context. A shape read by
10
+ * two independently deployed consumers is a contract, so it is written down
11
+ * once here and validated on both sides rather than transcribed into the edge.
12
+ *
13
+ * These are NOT the RFC 6749 token/userinfo responses. Those two speak flat
14
+ * OAuth/OIDC on the wire and are the one place in the API that does not use the
15
+ * `{ data }` envelope; these two are ordinary internal API responses that happen
16
+ * to be about OAuth.
17
+ */
18
+ /**
19
+ * Server-authoritative answer to "must this user be shown a consent screen".
20
+ *
21
+ * Discriminated on `consentRequired` so the two arms cannot be confused by a
22
+ * consumer that reads `reason` first: `trusted`/`granted` are reasons NOT to
23
+ * ask, `new`/`scope_changed` are reasons to ask, and a flat object would let a
24
+ * typo in one produce a plausible value of the other.
25
+ *
26
+ * - `trusted` — the application is first-party/internal/system/official
27
+ * by the REGISTRY's verdict (`isTrustedApplication`), and
28
+ * the request names no scope over the user's own follow
29
+ * graph. Never inferred from a hostname.
30
+ * - `granted` — a prior `AppGrant` already covers every requested scope.
31
+ * - `scope_changed` — a prior grant exists and is missing one.
32
+ * - `new` — no prior grant.
33
+ *
34
+ * `userConsentScopes` names the scopes that FORCED the screen, so the consent UI
35
+ * can say which one it is asking about. Present only on the `true` arm, and only
36
+ * when such a scope exists — a trusted app asked for one is still asked.
37
+ */
38
+ export const oauthConsentDecisionSchema = z.discriminatedUnion('consentRequired', [
39
+ z.object({
40
+ consentRequired: z.literal(false),
41
+ reason: z.enum(['trusted', 'granted']),
42
+ }),
43
+ z.object({
44
+ consentRequired: z.literal(true),
45
+ reason: z.enum(['new', 'scope_changed']),
46
+ userConsentScopes: z.array(z.string()).optional(),
47
+ }),
48
+ ]);
49
+ /**
50
+ * A minted authorization code.
51
+ *
52
+ * `state` is echoed back as the caller sent it and is `null` when they sent
53
+ * none — never omitted, so a consumer cannot read "the server dropped my state"
54
+ * as "I sent none". `redirectUri` is echoed for the same reason the code is
55
+ * bound to it server-side: the caller must be able to see that the value the
56
+ * code was issued against is the one it registered.
57
+ */
58
+ export const oauthAuthorizeCodeResponseSchema = z.object({
59
+ code: z.string().min(1),
60
+ state: z.string().nullable(),
61
+ redirectUri: z.string(),
62
+ expiresIn: z.number().int().positive(),
63
+ });
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Oxy-scoped signed-record types.
3
+ *
4
+ * The base `signedRecordEnvelopeSchema` (`./identity`) treats `type` as an OPEN,
5
+ * non-empty string so ANY Oxy app may sign on the shared envelope grammar. The
6
+ * Oxy STORE re-narrows it to the closed set in this module — a `type` outside it
7
+ * is rejected as `invalid_envelope`.
8
+ *
9
+ * `oxySignedRecordTypeSchema` is that runtime gate (the API's `verifyEnvelope`
10
+ * re-narrows with it; the Mongoose `SignedRecord.type` enum and the Postgres
11
+ * CHECK on `signed_records.type` are both derived from `.options`);
12
+ * `OxySignedRecordType` is the matching compile-time union the SDK
13
+ * identity/civic mixins type against.
14
+ *
15
+ * The signing input INCLUDES `type`, so this set is part of the signed bytes —
16
+ * a record cannot have its category swapped after signing, and a value once
17
+ * signed can never be renamed.
18
+ *
19
+ * v1 only ever carried `identity` / `profile` (already in production); v2 added
20
+ * the civic record types (reputation attestations, real-life / peer validations,
21
+ * personhood vouches, verifiable credentials) and the user-node registration
22
+ * record.
23
+ *
24
+ * ## Why `app_record` is here, when it deliberately was not
25
+ *
26
+ * This set used to hold Oxy's own categories only, and said so: an app's `type`
27
+ * was "intentionally NOT in this set". The reason given was that the store
28
+ * accepts only what it knows how to **verify and materialize**. Verification
29
+ * turned out not to argue for the exclusion — the engine verifies a signature
30
+ * against the subject's keys whatever the category says — and materialization
31
+ * is the app's job, not the store's: an app projects its own feed tables from
32
+ * records it reads back.
33
+ *
34
+ * What changed is the decision the exclusion blocked. One chain per PERSON, held
35
+ * by Oxy, is the ecosystem substrate: apps append their records to the subject's
36
+ * one chain instead of each keeping a private chain for the same person. A
37
+ * closed set that admits no app category makes that unrepresentable.
38
+ *
39
+ * `app_record` is ONE value rather than an open lane, and the lexicon lives in
40
+ * the envelope's `collection` (`app.mention.feed.post`, `app.syra.*`), which the
41
+ * store denormalizes to `signed_records.nsid` and indexes. So a new app needs no
42
+ * change here — it picks its own collection namespace and signs `app_record`,
43
+ * exactly as Mention already does in production. Keeping the set closed is what
44
+ * keeps the CHECK a real constraint.
45
+ *
46
+ * **Admitting the category is not the whole of that decision.** Two gates sit
47
+ * beside it and are unchanged: an app record must arrive as a v2 (chained)
48
+ * envelope, and `oxyVerificationResolver` accepts exactly one custodial issuer
49
+ * (`OXY_DID`). So a record a user signs themselves verifies here today, while
50
+ * one an app signs custodially under its OWN issuer DID does not — that needs a
51
+ * separate, deliberate answer about which issuers may write to a person's chain.
52
+ *
53
+ * Platform-agnostic — zod only, no react/react-native/expo, ESM-safe.
54
+ */
55
+ import { z } from 'zod';
56
+ export const oxySignedRecordTypeSchema = z.enum([
57
+ 'identity',
58
+ 'profile',
59
+ 'reputation_attestation',
60
+ 'real_life_attestation',
61
+ 'validation_verdict',
62
+ 'personhood_vouch',
63
+ 'credential',
64
+ 'node',
65
+ // Any Oxy app's own record. The LEXICON is the envelope's `collection`, not
66
+ // this value — see the header.
67
+ 'app_record',
68
+ ]);
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Generic "Oxy Protocol" record surface — the app-agnostic conventions every app
3
+ * follows to decentralize its own content on the shared signed-record substrate.
4
+ *
5
+ * The base `signedRecordEnvelopeSchema` (`./identity`) is the WIRE grammar: a
6
+ * signed envelope whose `type` is an open string and whose `record` is an opaque
7
+ * `Record<string, unknown>`. An app layers its own LEXICON on top of that
8
+ * grammar — a typed projection of the `record` payload, addressed by an
9
+ * AtProto-style `(collection, rkey)` key — WITHOUT forking the envelope schema.
10
+ *
11
+ * ## Recipe — defining an app lexicon record
12
+ *
13
+ * For each record kind an app wants to publish:
14
+ *
15
+ * 1. Define the `record` PAYLOAD schema as a `z.ZodType<XPayload>` (e.g.
16
+ * `app.mention.feed.post` → `mentionPostRecordSchema: z.ZodType<MentionPost>`).
17
+ * This validates ONLY the inner `record`, not the envelope.
18
+ * 2. Declare the `collection` NSID as a constant (e.g.
19
+ * `export const MENTION_POST_COLLECTION = 'app.mention.feed.post'`).
20
+ * 3. Reuse the UNCHANGED {@link signedRecordEnvelopeSchema} for the envelope. The
21
+ * base treats `record` as `z.record(z.unknown())`, so the app validates the
22
+ * envelope with the base schema first, then parses `envelope.record` with its
23
+ * own payload schema. {@link LexiconRecord} is the typed projection that pairs
24
+ * the `(collection, rkey)` key with the parsed payload.
25
+ *
26
+ * The Oxy civic contracts (`./civic`) already follow this convention implicitly:
27
+ * each civic record (`real_life_attestation`, `personhood_vouch`, `credential`,
28
+ * …) ships a `record`-payload schema and is carried by the base envelope.
29
+ *
30
+ * ## Chain-wire shapes
31
+ *
32
+ * {@link ChainHeadResponse} and {@link LogPageResponse} are the shared response
33
+ * shapes every chain store exposes (Oxy's `GET /identity/records/:userId/chain/head`,
34
+ * `GET /identity/head/:userId`, `GET /identity/log/:userId`, and any app node's
35
+ * equivalents). They are defined ONCE here so producers and consumers (the API
36
+ * handlers, the SDK identity/nodes mixins, app nodes) cannot drift.
37
+ *
38
+ * Platform-agnostic — zod only, no react/react-native/expo, ESM-safe.
39
+ */
40
+ import { z } from 'zod';
41
+ import { signedRecordEnvelopeSchema } from './identity.js';
42
+ export const chainHeadResponseSchema = z.object({
43
+ headRecordId: z.string().nullable(),
44
+ seq: z.number().int(),
45
+ recordCount: z.number().int().nonnegative(),
46
+ });
47
+ export const logPageResponseSchema = z.object({
48
+ records: z.array(signedRecordEnvelopeSchema),
49
+ count: z.number().int().nonnegative(),
50
+ });
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Recommendation-engine API contracts.
3
+ *
4
+ * SINGLE SOURCE OF TRUTH for the wire shape of the reputation-weighted
5
+ * profile-recommendation surface (`POST /profiles/recommendations`) and the
6
+ * cross-app signal-ingest endpoint (`POST /app-signals/ingest`). The API
7
+ * validates its INPUT/OUTPUT against these schemas; consumer SDKs validate the
8
+ * same definitions, so the producer and every consumer cannot drift.
9
+ *
10
+ * Platform-agnostic — zod is the only runtime dependency (no react / react-native
11
+ * / expo, ESM-safe).
12
+ */
13
+ import { z } from 'zod';
14
+ import { userNameSchema } from './userResponse.js';
15
+ /** User-type filters a caller may exclude from the recommendation surface. */
16
+ export const recommendationExcludeTypeSchema = z.enum([
17
+ 'federated',
18
+ 'agent',
19
+ 'automated',
20
+ ]);
21
+ /**
22
+ * A caller-supplied editorial boost. `userIds` are nudged up (or down, for a
23
+ * negative weight) in the ranking; the optional `reason` is for audit/telemetry
24
+ * only and never surfaced to end users. Boost members still pass the eligibility
25
+ * gate — a boost cannot resurrect a private/restricted/ineligible account.
26
+ */
27
+ export const recommendationBoostSchema = z.object({
28
+ userIds: z.array(z.string().trim().min(1)).min(1).max(200),
29
+ weight: z.number().min(-5).max(5),
30
+ reason: z.string().trim().max(120).optional(),
31
+ });
32
+ /**
33
+ * Per-request overrides for the scoring signal weights. Every key is optional
34
+ * and clamped server-side to the resolved weight profile's allowed range — a
35
+ * caller can re-weight signals but never escape the profile's bounds.
36
+ */
37
+ export const recommendationSignalWeightsSchema = z
38
+ .object({
39
+ graph: z.number().min(0).max(10).optional(),
40
+ completeness: z.number().min(0).max(10).optional(),
41
+ verified: z.number().min(0).max(10).optional(),
42
+ curation: z.number().min(0).max(10).optional(),
43
+ interest: z.number().min(0).max(10).optional(),
44
+ appBoost: z.number().min(0).max(10).optional(),
45
+ repCandidate: z.number().min(0).max(10).optional(),
46
+ affinity: z.number().min(0).max(10).optional(),
47
+ })
48
+ .partial();
49
+ /**
50
+ * Request body for `POST /profiles/recommendations`.
51
+ *
52
+ * `clientId` selects the per-app weight profile (the Application `_id`); when
53
+ * omitted the default profile is used. `excludeIds` removes accounts the caller
54
+ * has already seen/handled; `boosts` and `signalWeights` let the caller bias the
55
+ * ranking within server-enforced bounds.
56
+ */
57
+ export const recommendationRequestSchema = z.object({
58
+ clientId: z.string().trim().min(1).optional(),
59
+ limit: z.number().int().min(1).max(100).optional(),
60
+ offset: z.number().int().min(0).optional(),
61
+ excludeTypes: z.array(recommendationExcludeTypeSchema).optional(),
62
+ excludeIds: z.array(z.string().trim().min(1)).max(500).optional(),
63
+ boosts: z.array(recommendationBoostSchema).max(50).optional(),
64
+ signalWeights: recommendationSignalWeightsSchema.optional(),
65
+ });
66
+ /** Follower/following counts attached to a recommendation item. */
67
+ export const recommendationCountSchema = z.object({
68
+ followers: z.number().int().nonnegative(),
69
+ following: z.number().int().nonnegative(),
70
+ });
71
+ /**
72
+ * A single recommended profile.
73
+ *
74
+ * `name` reuses the canonical {@link userNameSchema} so `name.displayName` is the
75
+ * already-resolved server-side value. `score` and `matchedSignals` are present
76
+ * only on the scored (v2) path; `mutualCount` and `_count` are always present.
77
+ */
78
+ export const recommendationItemSchema = z
79
+ .object({
80
+ id: z.string(),
81
+ username: z.string().optional(),
82
+ name: userNameSchema,
83
+ avatar: z.string().nullable().optional(),
84
+ description: z.string().nullable().optional(),
85
+ verified: z.boolean().optional(),
86
+ trustTier: z.string().optional(),
87
+ mutualCount: z.number().int().nonnegative(),
88
+ score: z.number().optional(),
89
+ matchedSignals: z.array(z.string()).optional(),
90
+ isFederated: z.boolean().optional(),
91
+ isAgent: z.boolean().optional(),
92
+ isAutomated: z.boolean().optional(),
93
+ instance: z.string().optional(),
94
+ _count: recommendationCountSchema,
95
+ })
96
+ .passthrough();
97
+ /** Wire shape of the recommendation response — an array of items. */
98
+ export const recommendationResponseSchema = z.array(recommendationItemSchema);
99
+ /** One endorsement edge an app reports: `ownerId` endorses `memberId`. */
100
+ export const appEndorsementInputSchema = z.object({
101
+ ownerId: z.string().trim().min(1),
102
+ memberId: z.string().trim().min(1),
103
+ op: z.enum(['add', 'remove']).default('add'),
104
+ sourceId: z.string().trim().min(1).optional(),
105
+ });
106
+ /** One interest signal an app reports: how interested `userId` is in a topic. */
107
+ export const appInterestInputSchema = z.object({
108
+ userId: z.string().trim().min(1),
109
+ interestScore: z.number().min(0).max(1),
110
+ });
111
+ /**
112
+ * Request body for `POST /app-signals/ingest` (service token, `signals:write`).
113
+ *
114
+ * At least one of `endorsements` / `interests` must be non-empty — an ingest
115
+ * with neither is a no-op and rejected so a misconfigured caller is surfaced
116
+ * rather than silently succeeding.
117
+ */
118
+ export const appUserSignalIngestSchema = z
119
+ .object({
120
+ endorsements: z.array(appEndorsementInputSchema).max(500).optional(),
121
+ interests: z.array(appInterestInputSchema).max(500).optional(),
122
+ })
123
+ .refine((value) => (value.endorsements?.length ?? 0) > 0 || (value.interests?.length ?? 0) > 0, { message: 'At least one of endorsements or interests must be non-empty' });
124
+ /**
125
+ * The directed interaction types a consuming app may report between two users.
126
+ * Each type carries a server-side default weight (see the API's
127
+ * `AFFINITY_EVENT_WEIGHTS`); a caller may override the applied weight per event.
128
+ */
129
+ export const appAffinityEventTypeSchema = z.enum([
130
+ 'like',
131
+ 'reply',
132
+ 'boost',
133
+ 'follow',
134
+ 'mention',
135
+ 'profile_view',
136
+ 'quote',
137
+ 'repost',
138
+ ]);
139
+ /**
140
+ * One directed interaction event: `fromUserId` interacted with `toUserId`
141
+ * (`type`) at `occurredAt`. The Oxy affinity-graph folds these into a per-app,
142
+ * time-decayed directed affinity edge (`fromUserId → toUserId`).
143
+ *
144
+ * - `weight` (optional) overrides the per-type default weight for this event.
145
+ * - `occurredAt` (optional, ISO) is the event time; absent means "now" at ingest.
146
+ * - `eventId` (optional) makes an event idempotent — a repeated `eventId` for the
147
+ * same application is folded at most once (bounded dedup window).
148
+ */
149
+ export const appAffinityEventSchema = z.object({
150
+ fromUserId: z.string().trim().min(1),
151
+ toUserId: z.string().trim().min(1),
152
+ type: appAffinityEventTypeSchema,
153
+ weight: z.number().min(0).max(100).optional(),
154
+ occurredAt: z.string().datetime().optional(),
155
+ eventId: z.string().trim().min(1).max(200).optional(),
156
+ });
157
+ /**
158
+ * Request body for `POST /app-signals/events` (service token, `signals:write`).
159
+ *
160
+ * A non-empty batch (1..1000) of directed interaction events for the requesting
161
+ * application. Self-edges (`fromUserId === toUserId`) are dropped server-side.
162
+ */
163
+ export const appAffinityEventsIngestSchema = z.object({
164
+ events: z.array(appAffinityEventSchema).min(1).max(1000),
165
+ });