@oxyhq/contracts 0.16.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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
+ * `@oxyhq/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
+ });
@@ -29,10 +29,19 @@ export const deviceSessionSyncSchema = z.object({
29
29
  * possession of the secret IS the proof of device ownership. The server matches
30
30
  * `sha256(deviceSecret)` against the device's stored `secretHash` (constant-time)
31
31
  * and mints a short access token for the device's active account.
32
+ *
33
+ * `accountId` pins the mint to ONE account of that device instead of whichever
34
+ * account is currently active. It exists for identity-bound clients (Commons),
35
+ * whose authenticated user is determined by a local cryptographic key and must
36
+ * never follow an account switch made by another app on the same device. The
37
+ * account must already be a member of the device session; the mint NEVER
38
+ * mutates `activeAccountId`, so pinning is read-only with respect to the device
39
+ * state every other app observes.
32
40
  */
33
41
  export const deviceTokenMintRequestSchema = z.object({
34
42
  deviceId: z.string().min(1),
35
43
  deviceSecret: z.string().min(1),
44
+ accountId: z.string().min(1).optional(),
36
45
  });
37
46
  /**
38
47
  * Wire shape of a successful `POST /session/device/token`: the freshly-minted
package/dist/esm/index.js CHANGED
@@ -12,7 +12,7 @@
12
12
  export { ORGANIZATION_CATEGORIES, organizationCategorySchema, createAccountRequestSchema, } from './accountGraph.js';
13
13
  export {
14
14
  // Schemas
15
- userNameSchema, userResponseSchema, userProfileUpdateSchema, currentUserResponseSchema, deviceLinkedSessionSchema, deviceLinkedSessionsResponseSchema,
15
+ userNameSchema, userRelationshipSchema, themePreferenceSchema, userResponseSchema, userProfileUpdateSchema, currentUserResponseSchema, deviceLinkedSessionSchema, deviceLinkedSessionsResponseSchema,
16
16
  // Helpers
17
17
  resolveUserId, safeParseContract, } from './userResponse.js';
18
18
  export {
@@ -62,3 +62,9 @@ rollbackRequestSchema, rollbackToEmbeddedRequestSchema, promoteRequestSchema, up
62
62
  export {
63
63
  // Schemas
64
64
  webauthnRegisterOptionsRequestSchema, webauthnLoginOptionsRequestSchema, webauthnRegisterVerifyRequestSchema, webauthnLoginVerifyRequestSchema, } from './webauthn.js';
65
+ export {
66
+ // Schemas
67
+ devicePairingStatusSchema, deviceTransferInitRequestSchema, deviceTransferInitResponseSchema, deviceTransferInfoResponseSchema, deviceTransferApproveRequestSchema, deviceTransferApproveResponseSchema, deviceTransferDenyResponseSchema, } from './devicePairing.js';
68
+ export {
69
+ // Schemas — transparency log (checkpoints + inclusion proofs)
70
+ transparencyCheckpointSignatureSchema, transparencyAnchorSchema, transparencyCheckpointSchema, transparencyInclusionProofSchema, transparencyCheckpointListSchema, } from './transparency.js';
@@ -90,6 +90,14 @@ export const publicApplicationSchema = z.object({
90
90
  * current producer and are never `null`, but stay `.optional()` so the contract
91
91
  * tolerates leaner shapes from other producers of this same payload without a
92
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.
93
101
  */
94
102
  export const sessionStatusSchema = z.object({
95
103
  status: z.string(),
@@ -100,4 +108,11 @@ export const sessionStatusSchema = z.object({
100
108
  sessionId: z.string().nullable().optional(),
101
109
  publicKey: z.string().nullable().optional(),
102
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(),
103
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 `@oxyhq/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
+ });
@@ -39,6 +39,14 @@ export const userNameSchema = z
39
39
  displayName: z.string().optional(),
40
40
  })
41
41
  .passthrough();
42
+ export const userRelationshipSchema = z.object({
43
+ isFollowing: z.boolean(),
44
+ followsYou: z.boolean(),
45
+ });
46
+ export const themePreferenceSchema = z.object({
47
+ mode: z.enum(['light', 'dark', 'system']),
48
+ colorPreset: z.string(),
49
+ });
42
50
  /**
43
51
  * The canonical user object emitted by `formatUserResponse`.
44
52
  *
@@ -97,6 +105,19 @@ export const userResponseSchema = z
97
105
  * Absent on personal, project, and bot accounts.
98
106
  */
99
107
  organizationCategory: organizationCategorySchema.optional(),
108
+ /**
109
+ * The authenticated viewer's relationship to this profile. Present ONLY
110
+ * on single-profile fetches (`GET /profiles/username/:username`,
111
+ * `GET /users/:userId`) when the request is authenticated; OMITTED for
112
+ * anonymous requests and for the bulk `POST /users/by-ids` fan-out.
113
+ */
114
+ relationship: userRelationshipSchema.optional(),
115
+ /**
116
+ * Portable theme preference. Rides the self/session payload (cold boot),
117
+ * so it is present on the current-user DTO (`GET /users/me`,
118
+ * `GET /session/user/:sessionId`) and absent until the user sets it.
119
+ */
120
+ themePreference: themePreferenceSchema.optional(),
100
121
  })
101
122
  .passthrough();
102
123
  export const userProfileUpdateSchema = z
@@ -137,6 +158,11 @@ export const userProfileUpdateSchema = z
137
158
  notificationPreferences: z.record(z.unknown()).optional(),
138
159
  userPreferences: z.record(z.unknown()).optional(),
139
160
  privacySettings: z.record(z.unknown()).optional(),
161
+ /**
162
+ * Portable theme preference. Written through the same `PUT /users/me`
163
+ * settings-update path as `languages`/`userPreferences`.
164
+ */
165
+ themePreference: themePreferenceSchema.optional(),
140
166
  })
141
167
  .passthrough();
142
168
  /**