@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,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
+ * `@oxy.so/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,118 @@
1
+ /**
2
+ * Canonical contract for `GET /auth/session/status/:sessionToken`.
3
+ *
4
+ * SINGLE SOURCE OF TRUTH for the wire shape of the cross-app device-flow
5
+ * session-status payload and the sanitized public application identity it
6
+ * embeds. The API validates its OUTPUT against these schemas; the auth app
7
+ * (consent UI) validates its INPUT against the same schemas. Because there is
8
+ * exactly one definition, the producer and the consumer cannot drift.
9
+ *
10
+ * The class of bug that motivated moving this into `@oxy.so/contracts`: the auth
11
+ * app's LOCAL `sessionStatusSchema` typed `sessionId` as a non-nullable
12
+ * `z.string().optional()`. The producer emits `sessionId: authorizedSessionId ||
13
+ * null`, so a PENDING session (not yet authorized) carries `sessionId: null` —
14
+ * `.optional()` permits `undefined`/missing but REJECTS `null`, so `safeParse`
15
+ * failed, the whole response collapsed to `null`, and the consent screen showed
16
+ * "Unable to identify the requesting application". Pinning the nullability in one
17
+ * shared place makes that drift impossible.
18
+ *
19
+ * Faithful to the producers:
20
+ * - `packages/api/src/utils/serializeApplication.ts` `serializePublicApplication`
21
+ * — the ONLY shape returned to an unauthenticated consent UI. Optional fields
22
+ * (`description`, `icon`, `websiteUrl`, `privacyPolicyUrl`, `termsUrl`,
23
+ * `developerName`) are OMITTED when absent (never serialized as `null`), so
24
+ * they are `.optional()` — NOT `.nullable()`. `type` is the `Application.type`
25
+ * enum.
26
+ * - `packages/api/src/routes/auth.ts` `GET /session/status/:sessionToken` — the
27
+ * inner object of the API's `{ data: ... }` success envelope. The handler
28
+ * ALWAYS emits `status`, `authorized` (`status === 'authorized'`),
29
+ * `sessionToken`, `expiresAt` (ISO string), and `application` (resolved object
30
+ * OR `null`). It ALWAYS emits `sessionId` / `publicKey` / `userId`, each as a
31
+ * string value OR `null` (`authorizedSessionId || null`, `authorizedBy ||
32
+ * null`, `authorizedUserId?.toString() || null`).
33
+ *
34
+ * Platform-agnostic — zod only, no react/react-native/expo. ESM-safe (no
35
+ * `require()`).
36
+ */
37
+ import { z } from 'zod';
38
+ /**
39
+ * Application `type` enum. Mirrors `APPLICATION_TYPES` in
40
+ * `packages/api/src/models/Application.ts` (`first_party` | `third_party` |
41
+ * `internal` | `system`).
42
+ */
43
+ export const applicationTypeSchema = z.enum([
44
+ 'first_party',
45
+ 'third_party',
46
+ 'internal',
47
+ 'system',
48
+ ]);
49
+ /**
50
+ * The display-safe public identity of a requesting application, exactly as
51
+ * `serializePublicApplication` emits it. Returned by the API inside
52
+ * `GET /auth/session/status/:sessionToken` (device flow) and
53
+ * `GET /auth/oauth/client/:clientId` (OAuth code flow).
54
+ *
55
+ * Optional fields are `.optional()` (NOT `.nullable()`): the serializer OMITS
56
+ * `description` / `icon` / `websiteUrl` / `privacyPolicyUrl` / `termsUrl` /
57
+ * `developerName` when the underlying value is absent — it never writes `null`
58
+ * for them. `developerName` is only attached for non-official apps when a name
59
+ * could be resolved.
60
+ */
61
+ export const publicApplicationSchema = z.object({
62
+ id: z.string(),
63
+ name: z.string(),
64
+ description: z.string().optional(),
65
+ icon: z.string().optional(),
66
+ websiteUrl: z.string().optional(),
67
+ privacyPolicyUrl: z.string().optional(),
68
+ termsUrl: z.string().optional(),
69
+ type: applicationTypeSchema,
70
+ isOfficial: z.boolean(),
71
+ isInternal: z.boolean(),
72
+ scopes: z.array(z.string()),
73
+ developerName: z.string().optional(),
74
+ });
75
+ /**
76
+ * The inner object of `GET /auth/session/status/:sessionToken` (inside the API's
77
+ * `{ data: ... }` envelope).
78
+ *
79
+ * `application` is the resolved {@link publicApplicationSchema} identity of the
80
+ * requesting application, or `null` when the bound app was hard-deleted / is no
81
+ * longer `active` (defensive — normally always present).
82
+ *
83
+ * `sessionId` / `publicKey` / `userId` are `.nullable().optional()`: the producer
84
+ * ALWAYS emits the key, with a string for an AUTHORIZED session or `null` for a
85
+ * PENDING one. `.nullable()` accepts the PENDING `null`; `.optional()` is belt-
86
+ * and-braces so a consumer is never broken by a future projection that drops the
87
+ * key. (`.optional()` alone would REJECT the PENDING `null` — that was the bug.)
88
+ *
89
+ * `authorized` / `sessionToken` / `expiresAt` are emitted unconditionally by the
90
+ * current producer and are never `null`, but stay `.optional()` so the contract
91
+ * tolerates leaner shapes from other producers of this same payload without a
92
+ * coordinated bump.
93
+ *
94
+ * `pushSentAt` / `openedAt` are DELIVERY PROGRESS, not authorization state: they
95
+ * let a waiting surface render "Check Commons on your phone" → "Opened in
96
+ * Commons" without inventing competing statuses. `status` remains the only
97
+ * authority on whether the request is pending, authorized, cancelled or expired.
98
+ * Both are `.nullable().optional()` for the same reason as `sessionId` — the
99
+ * producer always emits the key with `null` until that step happens, and an
100
+ * older API that omits them entirely must degrade, not fail the parse.
101
+ */
102
+ export const sessionStatusSchema = z.object({
103
+ status: z.string(),
104
+ authorized: z.boolean().optional(),
105
+ sessionToken: z.string().optional(),
106
+ application: publicApplicationSchema.nullable().optional(),
107
+ expiresAt: z.string().optional(),
108
+ sessionId: z.string().nullable().optional(),
109
+ publicKey: z.string().nullable().optional(),
110
+ userId: z.string().nullable().optional(),
111
+ /**
112
+ * What approving this request does. Legacy rows read as `device_sign_in`.
113
+ * OAuth-bound sessions finalize into an authorization code (no `sessionId`).
114
+ */
115
+ purpose: z.enum(['device_sign_in', 'oauth_authorization']).optional(),
116
+ pushSentAt: z.string().nullable().optional(),
117
+ openedAt: z.string().nullable().optional(),
118
+ });
@@ -0,0 +1,86 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * Transparency log — the public wire contract of the checkpoint surface.
4
+ *
5
+ * A checkpoint is the operator's signed commitment to EVERY subject's chain head
6
+ * at a point in time: "at `periodEnd` I committed to `root` over `treeSize`
7
+ * subjects, and the previous checkpoint hashed to `prevCheckpointHash`". Anyone
8
+ * can then ask for an inclusion proof of their own head and verify it against
9
+ * that root without trusting the server — which is what closes the one gap a
10
+ * per-subject hash chain cannot close on its own (the server serving two
11
+ * different histories, or quietly dropping a record).
12
+ *
13
+ * The Merkle math, the leaf/checkpoint signing bytes, and the proof verifier all
14
+ * live in `@oxy.so/protocol` (`src/transparency/`); this module only fixes the
15
+ * SHAPES that cross the wire, so a client and the API cannot drift on them.
16
+ *
17
+ * Digest fields are pinned to 64-char LOWERCASE hex on purpose: the digests are
18
+ * compared as strings against locally recomputed hashes, so accepting an
19
+ * upper-case or truncated variant would turn a real mismatch into a confusing
20
+ * verification failure at a distance.
21
+ */
22
+ /** A SHA-256 digest in the exact form the protocol emits: 64 lowercase hex chars. */
23
+ const hexDigestSchema = z.string().regex(/^[0-9a-f]{64}$/, 'Expected a 64-char lowercase hex digest');
24
+ /**
25
+ * One signer's endorsement of a checkpoint's signed fields.
26
+ *
27
+ * The operator and every independent witness produce this same shape over the
28
+ * SAME bytes, so the array on a checkpoint can grow without coordination.
29
+ */
30
+ export const transparencyCheckpointSignatureSchema = z.object({
31
+ /** Uncompressed hex public key of the signer. */
32
+ publicKey: z.string().min(1),
33
+ alg: z.literal('ES256K-DER-SHA256'),
34
+ /** DER-encoded hex secp256k1 signature over the checkpoint signing input. */
35
+ signature: z.string().min(1),
36
+ });
37
+ /** Where a checkpoint root was published on a public chain. */
38
+ export const transparencyAnchorSchema = z.object({
39
+ /** Chain/network identifier, e.g. `faircoin-main`. */
40
+ network: z.string().min(1),
41
+ txid: z.string().min(1),
42
+ confirmations: z.number().int().nonnegative(),
43
+ /** When the anchoring transaction was broadcast (ms epoch). */
44
+ anchoredAt: z.number().int().positive(),
45
+ });
46
+ /**
47
+ * A published checkpoint.
48
+ *
49
+ * `signatures` is non-empty by contract: an unsigned root commits nobody and
50
+ * must never be served as a checkpoint. `anchors` may be empty — a checkpoint is
51
+ * published immediately and anchored asynchronously, so "not yet anchored" is a
52
+ * normal, temporary state rather than an error.
53
+ */
54
+ export const transparencyCheckpointSchema = z.object({
55
+ index: z.number().int().nonnegative(),
56
+ /** End of the committed period (ms epoch). */
57
+ periodEnd: z.number().int().positive(),
58
+ /** Number of subjects (leaves) committed. */
59
+ treeSize: z.number().int().nonnegative(),
60
+ root: hexDigestSchema,
61
+ /** Hash of the previous checkpoint; `null` only at genesis. */
62
+ prevCheckpointHash: hexDigestSchema.nullable(),
63
+ signatures: z.array(transparencyCheckpointSignatureSchema).min(1),
64
+ anchors: z.array(transparencyAnchorSchema),
65
+ });
66
+ /**
67
+ * An inclusion proof for one subject against one checkpoint.
68
+ *
69
+ * Carries the leaf PREIMAGE (`subjectDid`, `seq`, `headRecordId`) as well as the
70
+ * `leaf` digest so the verifier re-derives the leaf itself rather than trusting
71
+ * the server's hash, then walks `proof` up to the checkpoint's `root`.
72
+ */
73
+ export const transparencyInclusionProofSchema = z.object({
74
+ checkpoint: transparencyCheckpointSchema,
75
+ subjectDid: z.string().min(1),
76
+ seq: z.number().int().nonnegative(),
77
+ headRecordId: hexDigestSchema,
78
+ leaf: hexDigestSchema,
79
+ leafIndex: z.number().int().nonnegative(),
80
+ /** Audit path, leaf-adjacent sibling first; empty for a single-leaf tree. */
81
+ proof: z.array(hexDigestSchema),
82
+ });
83
+ /** A page of the checkpoint chain, oldest first, for walking `prevCheckpointHash`. */
84
+ export const transparencyCheckpointListSchema = z.object({
85
+ checkpoints: z.array(transparencyCheckpointSchema),
86
+ });