@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,160 @@
1
+ /**
2
+ * Civic / Commons API contracts (Fase 1 — DNI + crypto-owned reputation).
3
+ *
4
+ * SINGLE SOURCE OF TRUTH for the wire shape of the public "DNI" card a Commons
5
+ * user shows (and others scan): the user's DID, display identity, trust tier,
6
+ * personhood status, verified domains, and credential badges — sealed with an
7
+ * Oxy custodial attestation so a scanner can verify it OFFLINE against the Oxy
8
+ * public key (the same `ES256K-DER-SHA256` scheme as the signed data export).
9
+ *
10
+ * The QR encodes ONLY the DID (`oxydni://card?did=…`) — never trust data — so a
11
+ * card cannot be spoofed by crafting a QR; the scanner resolves the signed card
12
+ * server-side and verifies the Oxy signature. The attestation is computed over
13
+ * the canonical-JSON of the `card` object, so a consumer re-canonicalizes the
14
+ * card it received and verifies `attestation.signature` against
15
+ * `attestation.publicKey` (which MUST be a current verification method of the
16
+ * Oxy DID).
17
+ *
18
+ * Explicit-`interface` exports (PublicCard, SignedPublicCard) follow the same
19
+ * node-resolution rationale as `UserNameResponse` / the identity contracts: a
20
+ * nested `z.infer<>` can degrade to `{}` under a consumer's
21
+ * `moduleResolution: "node"`, so the load-bearing shapes are declared as literal
22
+ * interfaces and the runtime schemas are annotated `z.ZodType<Interface>`.
23
+ *
24
+ * The `attestation` reuses the export-bundle `ExportAttestation` shape from
25
+ * `./identity` (mirrored, not duplicated): `{ issuer, publicKey, alg, signature,
26
+ * signedAt }`. It is `null` ONLY when the Oxy signing key is unconfigured (dev).
27
+ *
28
+ * Platform-agnostic — zod only, no react/react-native/expo, ESM-safe.
29
+ */
30
+ import { z } from 'zod';
31
+ import { exportAttestationSchema } from './identity.js';
32
+ export const publicCardSchema = z.object({
33
+ did: z.string(),
34
+ userId: z.string(),
35
+ name: z.string(),
36
+ username: z.string().optional(),
37
+ avatarUrl: z.string().optional(),
38
+ trustTier: z.enum(['restricted', 'new', 'trusted', 'high_trust', 'verified']),
39
+ personhoodStatus: z.enum(['unverified', 'pending', 'verified']),
40
+ verifiedDomains: z.array(z.string()),
41
+ credentialBadges: z.array(z.string()),
42
+ issuedAt: z.number(),
43
+ });
44
+ export const signedPublicCardSchema = z.object({
45
+ card: publicCardSchema,
46
+ attestation: exportAttestationSchema.nullable(),
47
+ });
48
+ export const realLifeAttestationRecordSchema = z.object({
49
+ about: z.string(),
50
+ context: z.string(),
51
+ nonce: z.string(),
52
+ exp: z.number(),
53
+ geohash: z.string().optional(),
54
+ biometricOk: z.boolean().optional(),
55
+ });
56
+ export const realLifeAttestationResultSchema = z.object({
57
+ accepted: z.literal(true),
58
+ recordId: z.string(),
59
+ subjectUserId: z.string(),
60
+ attestorUserId: z.string(),
61
+ points: z.number(),
62
+ });
63
+ export const validationVerdictRecordSchema = z.object({
64
+ requestId: z.string(),
65
+ payloadHash: z.string(),
66
+ verdict: z.enum(['valid', 'invalid', 'abstain']),
67
+ });
68
+ /** Request body for opening a validation request (`POST /civic/validations`). */
69
+ export const validationOpenRequestSchema = z.object({
70
+ subjectUserId: z.string(),
71
+ actionType: z.string().min(1),
72
+ sourceActionId: z.string().min(1),
73
+ payload: z.record(z.unknown()),
74
+ highValue: z.boolean().optional(),
75
+ });
76
+ export const validationOpenResultSchema = z.object({
77
+ requestId: z.string(),
78
+ selectedValidatorCount: z.number(),
79
+ expiresAt: z.string(),
80
+ });
81
+ export const validationRequestSummarySchema = z.object({
82
+ id: z.string(),
83
+ subjectUserId: z.string(),
84
+ actionType: z.string(),
85
+ payload: z.record(z.unknown()),
86
+ payloadHash: z.string(),
87
+ status: z.enum(['pending', 'quorum_met', 'validated', 'rejected', 'expired']),
88
+ highValue: z.boolean(),
89
+ expiresAt: z.string(),
90
+ });
91
+ export const validationVoteResultSchema = z.object({
92
+ recorded: z.literal(true),
93
+ requestId: z.string(),
94
+ verdict: z.enum(['valid', 'invalid', 'abstain']),
95
+ status: z.enum(['pending', 'quorum_met', 'validated', 'rejected', 'expired']),
96
+ });
97
+ export const personhoodVouchRecordSchema = z.object({
98
+ about: z.string(),
99
+ context: z.string().optional(),
100
+ stake: z.number().optional(),
101
+ });
102
+ export const personhoodBreakdownSchema = z.object({
103
+ vouchSignal: z.number(),
104
+ realLifeSignal: z.number(),
105
+ biometricSignal: z.number(),
106
+ evidence: z.number(),
107
+ sybilPenalty: z.number(),
108
+ seed: z.boolean(),
109
+ });
110
+ export const personhoodStatusResultSchema = z.object({
111
+ userId: z.string(),
112
+ score: z.number(),
113
+ isRealPerson: z.boolean(),
114
+ vouchCount: z.number(),
115
+ realLifeCount: z.number(),
116
+ biometricBound: z.boolean(),
117
+ sybilPenalty: z.number(),
118
+ breakdown: personhoodBreakdownSchema.nullable(),
119
+ updatedAt: z.string().nullable(),
120
+ });
121
+ export const vouchResultSchema = z.object({
122
+ accepted: z.literal(true),
123
+ recordId: z.string(),
124
+ subjectUserId: z.string(),
125
+ voucherUserId: z.string(),
126
+ stakeAmount: z.number(),
127
+ points: z.number(),
128
+ });
129
+ export const credentialRecordSchema = z.object({
130
+ about: z.string(),
131
+ types: z.array(z.string().min(1)).min(1),
132
+ claims: z.record(z.unknown()),
133
+ expiresAt: z.number().optional(),
134
+ });
135
+ export const verifiableCredentialResponseSchema = z.object({
136
+ id: z.string(),
137
+ recordId: z.string(),
138
+ holderUserId: z.string(),
139
+ holderDid: z.string(),
140
+ issuerUserId: z.string().optional(),
141
+ issuerDid: z.string(),
142
+ types: z.array(z.string()),
143
+ claims: z.record(z.unknown()),
144
+ status: z.enum(['active', 'revoked', 'expired']),
145
+ issuedAt: z.number(),
146
+ expiresAt: z.number().optional(),
147
+ revokedAt: z.number().optional(),
148
+ });
149
+ export const credentialIssueResultSchema = z.object({
150
+ accepted: z.literal(true),
151
+ credential: verifiableCredentialResponseSchema,
152
+ });
153
+ export const credentialListResultSchema = z.object({
154
+ credentials: z.array(verifiableCredentialResponseSchema),
155
+ });
156
+ export const credentialVerifyResultSchema = z.object({
157
+ valid: z.boolean(),
158
+ reason: z.string().optional(),
159
+ credential: verifiableCredentialResponseSchema.nullable(),
160
+ });
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Canonical contract for the "Sign in with Oxy" approval handoff.
3
+ *
4
+ * SINGLE SOURCE OF TRUTH for the closed set of reasons an approver may attach
5
+ * when it DENIES a pending request via
6
+ * `POST /auth/session/deny/:authorizeCode`.
7
+ *
8
+ * That endpoint is UNAUTHENTICATED — the public `authorizeCode` is the only
9
+ * credential — so a free-form string from it is never stored: it would be an
10
+ * unauthenticated write of arbitrary text onto a record other surfaces read.
11
+ * The set is therefore deliberately tiny, and closed:
12
+ *
13
+ * - `'declined'` the approver rejected a request they recognised ("Not now").
14
+ * - `'not_me'` the approver did not start the request ("This wasn't me").
15
+ * The ONE value that records the denial as suspicious rather
16
+ * than an ordinary cancel, so a UI may only offer it where the
17
+ * user genuinely said so.
18
+ *
19
+ * Why this lives in `@oxy.so/contracts` rather than in either consumer: the same
20
+ * closed set is enforced in three places — the request schema of the API route,
21
+ * the `enum` of the persisted `AuthSession.deniedReason` field, and the client
22
+ * SDK's `denyCommonsSignIn` parameter. Two hand-maintained copies of a wire
23
+ * contract drift the moment a value is added on one side only, and the failure
24
+ * lands at runtime, in an auth path, as a generic validation error. One
25
+ * declaration makes that impossible.
26
+ *
27
+ * Platform-agnostic — zod only, no react/react-native/expo. ESM-safe (no
28
+ * `require()`).
29
+ */
30
+ import { z } from 'zod';
31
+ /**
32
+ * The closed set, as a value — consumed directly where a runtime list is
33
+ * required (e.g. the Mongoose `enum` of `AuthSession.deniedReason`, which is
34
+ * the storage-level guarantee that an unauthenticated caller can never write
35
+ * free-form text into the field).
36
+ */
37
+ export const COMMONS_DENY_REASONS = ['declined', 'not_me'];
38
+ /**
39
+ * The same set as a zod enum — the edge validator. Anything outside it
40
+ * (including free-form text) is rejected with 400 before any handler runs.
41
+ */
42
+ export const commonsDenyReasonSchema = z.enum(COMMONS_DENY_REASONS);
43
+ /**
44
+ * Android notification channel id the identity-approval push is sent on.
45
+ *
46
+ * A wire contract for the same reason the deny set is: Android 8+ DROPS a
47
+ * notification whose channel id the app has not created, silently and with no
48
+ * client-side error. The API attaches this id when it sends, and the vault
49
+ * creates the channel with it before registering a push token — two hand-typed
50
+ * copies of that string would fail as "the notification never arrived", which
51
+ * is the single hardest push symptom to diagnose.
52
+ *
53
+ * The channel's user-visible NAME and description are deliberately NOT here:
54
+ * those are localized app copy, and the vault owns them.
55
+ */
56
+ export const IDENTITY_APPROVAL_PUSH_CHANNEL = 'auth-approval';
@@ -0,0 +1,47 @@
1
+ /**
2
+ * First-party login result contract.
3
+ *
4
+ * SINGLE SOURCE OF TRUTH for the first-party login result (the session arm). The
5
+ * API validates its OUTPUT against this schema; every consumer (`@oxy.so/core`'s
6
+ * auth mixin) validates its INPUT against the same definition, so producer and
7
+ * consumers cannot drift. Sign-in is passkey (WebAuthn) or Commons handoff —
8
+ * password and 2FA were removed, so the only outcome is a completed session.
9
+ *
10
+ * The device transport is `deviceId` + `deviceSecret` + `POST /session/device/token`
11
+ * (see `deviceSession.ts`). The legacy cookie/bootstrap/refresh-family lanes were
12
+ * removed in the zero-cookie cutover — nothing here carries a refresh token or a
13
+ * boot fragment.
14
+ *
15
+ * Nested-object response shapes are declared as explicit `interface`s with the
16
+ * runtime schema annotated `z.ZodType<Interface>` — the same rationale as
17
+ * `identity.ts` / `userResponse.ts`: a `z.infer<>` of a nested object schema can
18
+ * degrade to `{}` under a consumer's `moduleResolution: "node"` (node10), so the
19
+ * load-bearing shapes are pinned by literal interfaces. Flat request/response
20
+ * shapes (no nested-object hazard) are inferred via `z.infer<>`.
21
+ *
22
+ * Platform-agnostic — zod only, no react/react-native/expo. ESM-safe (no
23
+ * `require()`).
24
+ */
25
+ import { z } from 'zod';
26
+ const securityAlertSchema = z.object({
27
+ message: z.string(),
28
+ anomalies: z.array(z.object({
29
+ type: z.string(),
30
+ reason: z.string(),
31
+ details: z.string().optional(),
32
+ })),
33
+ });
34
+ const loginSessionResultSchema = z.object({
35
+ sessionId: z.string(),
36
+ deviceId: z.string(),
37
+ expiresAt: z.string(),
38
+ accessToken: z.string().optional(),
39
+ deviceSecret: z.string().optional(),
40
+ securityAlert: securityAlertSchema.optional(),
41
+ user: z.object({
42
+ id: z.string(),
43
+ username: z.string().optional(),
44
+ avatar: z.string().optional(),
45
+ }),
46
+ });
47
+ export const loginResultSchema = loginSessionResultSchema;
@@ -0,0 +1,186 @@
1
+ import { z } from 'zod';
2
+ import { accountKindSchema } from './accountGraph.js';
3
+ import { activeTokenSchema, deviceSessionStateSchema } from './deviceSession.js';
4
+ import { userNameSchema } from './userResponse.js';
5
+ /**
6
+ * The canonical device directory — the ONE server-authoritative read model an
7
+ * account switcher renders (issue #937, ADR 0002).
8
+ *
9
+ * It replaces the client-side union of `DeviceSessionState.accounts[]` with a
10
+ * separately fetched `AccountNode[]` graph. That union cannot be correct on a
11
+ * device holding more than one person: the client only ever holds ONE caller's
12
+ * account graph, so it cannot enumerate what the OTHER principals may act as.
13
+ * Switchability is an authorization question, so the server answers it.
14
+ *
15
+ * The directory is deterministic and revision-bound: two reads at the same
16
+ * `revision` describe the same device state, and `revision` only advances on a
17
+ * real mutation (an idempotent activation advances nothing — ADR 0002).
18
+ */
19
+ /**
20
+ * How a principal reaches an account.
21
+ *
22
+ * Mirrors `AccountRelationship` in `@oxy.so/core`'s account graph rather than
23
+ * inventing a second vocabulary for the same fact:
24
+ * - `self` — the principal's own personal account (`principal.userId === accountId`)
25
+ * - `owner` — the principal owns this account
26
+ * - `member` — the principal holds a membership granting `account:act_as`
27
+ */
28
+ export const deviceContextRelationshipSchema = z.enum(['self', 'owner', 'member']);
29
+ /**
30
+ * Sanitized display metadata for a principal or an account context.
31
+ *
32
+ * Deliberately NOT `userResponseSchema`: a switcher needs a handle, a name, an
33
+ * avatar and the accent the row is drawn in, and the directory is read by every
34
+ * app on the device — so it carries the minimum that renders a row and nothing
35
+ * that would make it a general profile feed. `name.displayName` stays OPTIONAL;
36
+ * consumers fall back to the handle (`getNormalizedUserHandle`), never to a
37
+ * synthesized name.
38
+ *
39
+ * `color` is here and `email` is not, and the line between them is what the
40
+ * field is FOR rather than how sensitive it looks. An accent is a property of
41
+ * drawing the row — without it every non-active row falls back to the ambient
42
+ * theme accent and a device holding two people renders them identically
43
+ * (issue #961). An address is somebody's contact detail, and the `@handle` the
44
+ * secondary line already shows fills the same slot, so putting one in a payload
45
+ * every installed app reads would widen the profile for no rendering gain.
46
+ */
47
+ export const deviceDirectoryProfileSchema = z.object({
48
+ id: z.string().min(1),
49
+ username: z.string(),
50
+ name: userNameSchema.optional(),
51
+ avatar: z.string().nullable().optional(),
52
+ /**
53
+ * Named Bloom color preset (e.g. `"blue"`), or null when the account has
54
+ * none. Same shape as `userResponseSchema.color` — one spelling of one fact,
55
+ * so a consumer that themes a row from either source reads the same values.
56
+ */
57
+ color: z.string().nullable().optional(),
58
+ });
59
+ /**
60
+ * One `principal acting as account` pair — the globally switchable unit.
61
+ *
62
+ * `id` is the identifier `POST /session/device/activate` takes. It names the
63
+ * PAIR, not the account: the same `accountId` legitimately appears under two
64
+ * principals on a shared device, and those are different sessions, permissions,
65
+ * audit actors and revocation paths.
66
+ *
67
+ * `onDevice` is `false` for a context the principal may act as but has never
68
+ * activated here — it exists as a row so it has a stable id to activate, and
69
+ * its delegated session is minted on first activation rather than eagerly for
70
+ * every organization the principal belongs to.
71
+ *
72
+ * `available` is `principalLive && (personal || live account:act_as)`, and the
73
+ * principal clause is not decoration: a principal whose own personal session
74
+ * has died makes EVERY context of theirs unavailable, including delegated ones
75
+ * whose sessions are perfectly alive. Activation verifies the principal's
76
+ * personal session (ADR 0002 step 3), so a client that models availability as
77
+ * "delegated context has a live session ⇒ activatable" will be refused by the
78
+ * server and the context healed away.
79
+ *
80
+ * A managed account whose membership was revoked is returned with
81
+ * `available: false` rather than silently omitted, so the UI can explain a row
82
+ * disappearing instead of just dropping it.
83
+ *
84
+ * (An earlier version of this comment described `available` as the
85
+ * `account:act_as` verdict alone. It was written before the server existed and
86
+ * was weaker than the code that shipped — the kind of wrong statement nothing
87
+ * recomputes, so it is spelled out here in full.)
88
+ */
89
+ export const deviceAccountContextSchema = z.object({
90
+ id: z.string().min(1),
91
+ accountId: z.string().min(1),
92
+ kind: accountKindSchema,
93
+ relationship: deviceContextRelationshipSchema,
94
+ account: deviceDirectoryProfileSchema,
95
+ onDevice: z.boolean(),
96
+ available: z.boolean(),
97
+ active: z.boolean(),
98
+ lastUsedAt: z.number().nullable(),
99
+ });
100
+ /**
101
+ * A human who authenticated onto this device.
102
+ *
103
+ * Never an organization, project, channel or bot — those are subjects a
104
+ * principal acts as, and they appear only in `contexts`. `authuser` is the
105
+ * Google-style signed-in-human slot and belongs HERE, not to an account: adding
106
+ * an organization must never consume one.
107
+ */
108
+ export const devicePrincipalSchema = z.object({
109
+ id: z.string().min(1),
110
+ userId: z.string().min(1),
111
+ authuser: z.number().int().nonnegative(),
112
+ user: deviceDirectoryProfileSchema,
113
+ contexts: z.array(deviceAccountContextSchema),
114
+ });
115
+ /**
116
+ * Response of `GET /session/device/directory`.
117
+ *
118
+ * `activeContextId` is the authority for what every official app in
119
+ * `sessionMode: 'account'` renders. It is null when the device has no active
120
+ * context — a real state (every context removed, or an active context healed
121
+ * away), not an error.
122
+ */
123
+ export const deviceDirectorySchema = z.object({
124
+ deviceId: z.string().min(1),
125
+ revision: z.number().int().nonnegative(),
126
+ activeContextId: z.string().nullable(),
127
+ principals: z.array(devicePrincipalSchema),
128
+ updatedAt: z.number(),
129
+ });
130
+ /**
131
+ * Request body of `POST /session/device/activate`.
132
+ *
133
+ * `contextId`, never `accountId`: an account id cannot name a context on a
134
+ * device where two people can both reach the same organization, and resolving
135
+ * that ambiguity server-side would mean guessing inside an authorization path.
136
+ */
137
+ export const deviceActivateRequestSchema = z.object({
138
+ contextId: z.string().min(1),
139
+ });
140
+ /**
141
+ * Response of `POST /session/device/activate`.
142
+ *
143
+ * Carries the post-transition directory AND the bearer for the newly active
144
+ * context, because the client's ordering invariant is
145
+ * `commit token → reset caches → publish snapshot → notify` (ADR 0002). Handing
146
+ * the directory back without the token would force a second round trip in the
147
+ * middle of that sequence, which is exactly where a component would render the
148
+ * new subject while still holding the previous subject's bearer.
149
+ *
150
+ * `activeToken` is null when the activation legitimately produced no bearer for
151
+ * THIS caller — an identity-pinned client, or a caller whose application is not
152
+ * entitled to a token for the new context. It is never an error signal.
153
+ */
154
+ export const deviceActivateResponseSchema = z.object({
155
+ directory: deviceDirectorySchema,
156
+ activeToken: activeTokenSchema.nullable(),
157
+ });
158
+ /**
159
+ * Response of the CONTEXT-aware removals — `POST /session/device/signout` with
160
+ * `{ contextId }` (one `principal → account` pair) or `{ principalId }` (one
161
+ * person and every context they reach, and nobody else's).
162
+ *
163
+ * It carries BOTH halves because a removal elects a replacement active context,
164
+ * so both the directory and the flat compatibility projection move in the same
165
+ * transition — and a client that learned only one of them would render one
166
+ * half of a device that no longer exists.
167
+ *
168
+ * This is deliberately NOT {@link deviceSessionSyncSchema} and must never be
169
+ * merged into it. A zod object strips unknown keys, so `{directory, state,
170
+ * activeToken}` parses cleanly as `{state, activeToken}` — silently dropping the
171
+ * directory. One schema covering both shapes would therefore make "the server
172
+ * stopped sending the directory" and "this endpoint never sends one"
173
+ * indistinguishable at the parse, on the exact path that decides which identity
174
+ * the app is running as. Two schemas fail closed instead: `directory` is
175
+ * required here, so a directory-less payload is refused outright.
176
+ *
177
+ * `activeToken` is null on the same terms as everywhere else — an identity-
178
+ * pinned caller, or one not entitled to a bearer for the newly-elected context —
179
+ * and null is also the honest answer when the removal left the device with no
180
+ * active context at all.
181
+ */
182
+ export const deviceDirectorySyncSchema = z.object({
183
+ directory: deviceDirectorySchema,
184
+ state: deviceSessionStateSchema,
185
+ activeToken: activeTokenSchema.nullable(),
186
+ });
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Device-to-device identity transfer contracts (b3 Feature 2 — "add a device").
3
+ *
4
+ * SINGLE SOURCE OF TRUTH for the wire shape of the short-lived, unauthenticated
5
+ * relay that carries E2E-encrypted key material from an existing (old) device to
6
+ * a fresh (new) device so both end up holding the SAME secp256k1 private key
7
+ * (key cloning). The relay is E2E-encrypted via an ephemeral secp256k1 ECDH
8
+ * handshake: the server stores only the two ephemeral public keys plus an opaque
9
+ * AEAD ciphertext + nonce and NEVER holds a decryption key.
10
+ *
11
+ * Flow:
12
+ * 1. New device (no identity) generates an ephemeral pair and calls
13
+ * `POST /identity/device-transfer/init { newEphPub, newDeviceLabel? }` →
14
+ * `{ pairingId, expiresAt }`. The QR carries ONLY `pairingId` (not
15
+ * self-contained — mirrors the QR sign-in `approve-info` resolution).
16
+ * 2. Old device (has identity) scans, resolves the request via
17
+ * `GET /identity/device-transfer/:pairingId` (returns `newEphPub` + label),
18
+ * derives `transferKey = HKDF(ECDH(oldEphPriv, newEphPub), pairingId,
19
+ * 'oxy-device-transfer-v1')`, AEAD-encrypts `{ privateKey, publicKey }`, and
20
+ * calls `POST /identity/device-transfer/:pairingId/approve` with the
21
+ * ciphertext PLUS a fresh signature over
22
+ * `{ action:'approve_device_transfer', pairingId, timestamp }` made with the
23
+ * CURRENT identity key (dual-proof: a bearer alone cannot exfiltrate the key).
24
+ * 3. New device (socket push or poll fallback) re-derives the same
25
+ * `transferKey` from `ECDH(newEphPriv, oldEphPub)`, decrypts, and imports the
26
+ * private key, then completes a NORMAL challenge/verify sign-in.
27
+ *
28
+ * The load-bearing response shapes are declared as explicit `interface`s (same
29
+ * `moduleResolution: node` rationale as `UserNameResponse` / the identity/civic
30
+ * contracts: a nested `z.infer<>` can degrade to `{}` under a consumer's
31
+ * `moduleResolution: "node"`), with the runtime schemas annotated
32
+ * `z.ZodType<Interface>`.
33
+ *
34
+ * Platform-agnostic — zod only, no react/react-native/expo, ESM-safe.
35
+ */
36
+ import { z } from 'zod';
37
+ /* -------------------------------------------------------------------------- */
38
+ /* Shared field validators */
39
+ /* -------------------------------------------------------------------------- */
40
+ /** Lowercase/uppercase hex string (no `0x` prefix). */
41
+ const hexString = z
42
+ .string()
43
+ .trim()
44
+ .regex(/^[0-9a-fA-F]+$/, 'must be a hex string');
45
+ /**
46
+ * A secp256k1 public key, hex-encoded — compressed (`02`/`03` + 32 bytes = 66
47
+ * chars) or uncompressed (`04` + 64 bytes = 130 chars). The exact curve-point
48
+ * validity is re-checked server-side; this only bounds the shape/length.
49
+ */
50
+ const publicKeyHex = hexString.min(66).max(130);
51
+ /** DER-encoded ECDSA signature, hex (variable length, ~140–144 chars). */
52
+ const signatureHex = hexString.min(2).max(256);
53
+ /**
54
+ * The 24-byte XChaCha20-Poly1305 nonce, hex (exactly 48 chars). Matches
55
+ * `@oxy.so/core` `AEAD_NONCE_LENGTH` (24 bytes).
56
+ */
57
+ const nonceHex = hexString.length(48);
58
+ /**
59
+ * The AEAD ciphertext (Poly1305 tag appended), hex. The plaintext is the small
60
+ * JSON `{ privateKey, publicKey }` (~200 bytes), so the ciphertext stays well
61
+ * under the cap; the bound blunts relay-abuse via oversized blobs.
62
+ */
63
+ const ciphertextHex = hexString.min(2).max(8192);
64
+ /* -------------------------------------------------------------------------- */
65
+ /* Status */
66
+ /* -------------------------------------------------------------------------- */
67
+ /**
68
+ * Pairing lifecycle:
69
+ * - `pending` — created by the new device, awaiting the old device's approval.
70
+ * - `approved` — the old device sealed and posted the encrypted key material.
71
+ * - `denied` — the old device explicitly cancelled the transfer.
72
+ * - `expired` — the 3-minute TTL elapsed before approval.
73
+ */
74
+ export const devicePairingStatusSchema = z.enum([
75
+ 'pending',
76
+ 'approved',
77
+ 'denied',
78
+ 'expired',
79
+ ]);
80
+ /* -------------------------------------------------------------------------- */
81
+ /* POST /identity/device-transfer/init */
82
+ /* -------------------------------------------------------------------------- */
83
+ /** Request body for `POST /identity/device-transfer/init` (public). */
84
+ export const deviceTransferInitRequestSchema = z.object({
85
+ /** The new device's ephemeral secp256k1 public key (single-use). */
86
+ newEphPub: publicKeyHex,
87
+ /** Optional human-readable label for the new device (e.g. "iPhone 15"). */
88
+ newDeviceLabel: z.string().trim().min(1).max(120).optional(),
89
+ });
90
+ export const deviceTransferInitResponseSchema = z.object({
91
+ pairingId: z.string(),
92
+ expiresAt: z.string(),
93
+ });
94
+ export const deviceTransferInfoResponseSchema = z.object({
95
+ pairingId: z.string(),
96
+ newDeviceEphemeralPublicKey: z.string(),
97
+ newDeviceLabel: z.string().nullable(),
98
+ status: devicePairingStatusSchema,
99
+ expiresAt: z.string(),
100
+ oldDeviceEphemeralPublicKey: z.string().nullable(),
101
+ ciphertext: z.string().nullable(),
102
+ nonce: z.string().nullable(),
103
+ });
104
+ /* -------------------------------------------------------------------------- */
105
+ /* POST /identity/device-transfer/:pairingId/approve */
106
+ /* -------------------------------------------------------------------------- */
107
+ /**
108
+ * Request body for `POST /identity/device-transfer/:pairingId/approve`
109
+ * (bearer-authenticated AND signature-proven). The `signature` covers
110
+ * `JSON.stringify({ action:'approve_device_transfer', pairingId, timestamp })`
111
+ * made with the caller's CURRENT identity key — dual-proof so a bearer token
112
+ * alone can never exfiltrate the private key.
113
+ */
114
+ export const deviceTransferApproveRequestSchema = z.object({
115
+ /** The old device's ephemeral secp256k1 public key (single-use). */
116
+ oldEphPub: publicKeyHex,
117
+ /** AEAD ciphertext of `{ privateKey, publicKey }`, hex. */
118
+ ciphertext: ciphertextHex,
119
+ /** AEAD nonce, hex (24 bytes). */
120
+ nonce: nonceHex,
121
+ /** ECDSA (DER, hex) signature proving control of the CURRENT identity key. */
122
+ signature: signatureHex,
123
+ /** Signing timestamp (ms since epoch) — freshness-checked server-side. */
124
+ timestamp: z.number().int().positive(),
125
+ });
126
+ export const deviceTransferApproveResponseSchema = z.object({
127
+ success: z.boolean(),
128
+ pairingId: z.string(),
129
+ status: devicePairingStatusSchema,
130
+ });
131
+ export const deviceTransferDenyResponseSchema = z.object({
132
+ success: z.boolean(),
133
+ pairingId: z.string(),
134
+ status: devicePairingStatusSchema,
135
+ });