@oxy.so/contracts 6.18.0 → 6.20.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,334 @@
1
+ "use strict";
2
+ /**
3
+ * The Oxy Keychain's wire contract (ADR 0063, `docs/identity/keychain.md`).
4
+ *
5
+ * The API parses every `/keychain` request with these schemas and its answers
6
+ * with the response schemas; clients check answers with the Zod-free checks in
7
+ * `./client/keychain.ts` (`@oxy.so/contracts/client`), which mirror them.
8
+ *
9
+ * Every request object is STRICT (an unknown key is refused). Every binary
10
+ * value is canonical base64url without padding, with its length fixed where the
11
+ * bytes are (keys and enrollment nonces 32, AEAD nonces 24, signatures 64).
12
+ *
13
+ * The roster body schemas TRANSFORM NOTHING: the server requires an entry's
14
+ * `body` to equal the JCS of its own parse, so a parse that trimmed, defaulted
15
+ * or lower-cased a value would refuse a canonical body.
16
+ *
17
+ * Platform-agnostic — zod only, no react/react-native/expo. ESM-safe.
18
+ */
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.keychainItemsResponseSchema = exports.keychainItemResponseSchema = exports.keychainEnrollmentsResponseSchema = exports.keychainEnrollmentResponseSchema = exports.keychainWrapResponseSchema = exports.keychainStateResponseSchema = exports.keychainResetRequestSchema = exports.keychainItemParamsSchema = exports.keychainEnrollmentParamsSchema = exports.keychainItemsQuerySchema = exports.keychainItemDeleteRequestSchema = exports.keychainItemPutRequestSchema = exports.keychainApproveRequestSchema = exports.keychainRevealRequestSchema = exports.keychainApproverNonceRequestSchema = exports.keychainEnrollmentCreateRequestSchema = exports.keychainRosterAppendRequestSchema = exports.keychainCreateRequestSchema = exports.keychainWrapSchema = exports.keychainEntrySchema = exports.keychainSignatureSchema = exports.keychainRosterBodySchema = exports.keychainRecoveryKeysSchema = exports.keychainMemberSchema = exports.keychainCiphertextSchema = exports.keychainSignatureValueSchema = exports.keychainNonceSchema = exports.keychainBytes32Schema = exports.keychainPrincipalSchema = exports.keychainIdSchema = exports.KEYCHAIN_TIMESTAMP_PATTERN = exports.KEYCHAIN_HASH_PATTERN = exports.KEYCHAIN_BASE64URL_PATTERN = exports.KEYCHAIN_SIGNATURE_PATTERN = exports.KEYCHAIN_NONCE_PATTERN = exports.KEYCHAIN_BYTES32_PATTERN = exports.KEYCHAIN_ID_PATTERN = exports.KEYCHAIN_ERROR_CODES = exports.KEYCHAIN_LIMITS = exports.KEYCHAIN_DOMAINS = exports.KEYCHAIN_RECOVERY = exports.KEYCHAIN_ENROLLMENT_STATUSES = exports.KEYCHAIN_ROSTER_OPS = exports.KEYCHAIN_PLATFORMS = void 0;
21
+ const zod_1 = require("zod");
22
+ const keychain_1 = require("./client/keychain");
23
+ const numberChecks_1 = require("./numberChecks");
24
+ const identityProof_1 = require("./identityProof");
25
+ const signIn_1 = require("./signIn");
26
+ const stringChecks_1 = require("./stringChecks");
27
+ var keychain_2 = require("./client/keychain");
28
+ Object.defineProperty(exports, "KEYCHAIN_PLATFORMS", { enumerable: true, get: function () { return keychain_2.KEYCHAIN_PLATFORMS; } });
29
+ Object.defineProperty(exports, "KEYCHAIN_ROSTER_OPS", { enumerable: true, get: function () { return keychain_2.KEYCHAIN_ROSTER_OPS; } });
30
+ Object.defineProperty(exports, "KEYCHAIN_ENROLLMENT_STATUSES", { enumerable: true, get: function () { return keychain_2.KEYCHAIN_ENROLLMENT_STATUSES; } });
31
+ Object.defineProperty(exports, "KEYCHAIN_RECOVERY", { enumerable: true, get: function () { return keychain_2.KEYCHAIN_RECOVERY; } });
32
+ Object.defineProperty(exports, "KEYCHAIN_DOMAINS", { enumerable: true, get: function () { return keychain_2.KEYCHAIN_DOMAINS; } });
33
+ Object.defineProperty(exports, "KEYCHAIN_LIMITS", { enumerable: true, get: function () { return keychain_2.KEYCHAIN_LIMITS; } });
34
+ Object.defineProperty(exports, "KEYCHAIN_ERROR_CODES", { enumerable: true, get: function () { return keychain_2.KEYCHAIN_ERROR_CODES; } });
35
+ Object.defineProperty(exports, "KEYCHAIN_ID_PATTERN", { enumerable: true, get: function () { return keychain_2.KEYCHAIN_ID_PATTERN; } });
36
+ Object.defineProperty(exports, "KEYCHAIN_BYTES32_PATTERN", { enumerable: true, get: function () { return keychain_2.KEYCHAIN_BYTES32_PATTERN; } });
37
+ Object.defineProperty(exports, "KEYCHAIN_NONCE_PATTERN", { enumerable: true, get: function () { return keychain_2.KEYCHAIN_NONCE_PATTERN; } });
38
+ Object.defineProperty(exports, "KEYCHAIN_SIGNATURE_PATTERN", { enumerable: true, get: function () { return keychain_2.KEYCHAIN_SIGNATURE_PATTERN; } });
39
+ Object.defineProperty(exports, "KEYCHAIN_BASE64URL_PATTERN", { enumerable: true, get: function () { return keychain_2.KEYCHAIN_BASE64URL_PATTERN; } });
40
+ Object.defineProperty(exports, "KEYCHAIN_HASH_PATTERN", { enumerable: true, get: function () { return keychain_2.KEYCHAIN_HASH_PATTERN; } });
41
+ Object.defineProperty(exports, "KEYCHAIN_TIMESTAMP_PATTERN", { enumerable: true, get: function () { return keychain_2.KEYCHAIN_TIMESTAMP_PATTERN; } });
42
+ /* -------------------------------------------------------------------------- */
43
+ /* Building blocks */
44
+ /* -------------------------------------------------------------------------- */
45
+ /** A lowercase uuid: vault, member, item and enrollment ids. */
46
+ exports.keychainIdSchema = zod_1.z.string().regex(keychain_1.KEYCHAIN_ID_PATTERN, 'Expected a lowercase uuid');
47
+ /** A member id or `recovery`: a wrap's recipient, a signature's signer. */
48
+ exports.keychainPrincipalSchema = zod_1.z.union([exports.keychainIdSchema, zod_1.z.literal(keychain_1.KEYCHAIN_RECOVERY)]);
49
+ /** 32 bytes as canonical base64url: an Ed25519 or X25519 public key, a 32-byte nonce, a commitment. */
50
+ exports.keychainBytes32Schema = zod_1.z
51
+ .string()
52
+ .regex(keychain_1.KEYCHAIN_BYTES32_PATTERN, 'Expected 32 bytes as canonical base64url');
53
+ /** A 24-byte XChaCha20-Poly1305 nonce as base64url. */
54
+ exports.keychainNonceSchema = zod_1.z
55
+ .string()
56
+ .regex(keychain_1.KEYCHAIN_NONCE_PATTERN, 'Expected 24 bytes as base64url');
57
+ /** A 64-byte Ed25519 signature as canonical base64url. */
58
+ exports.keychainSignatureValueSchema = zod_1.z
59
+ .string()
60
+ .regex(keychain_1.KEYCHAIN_SIGNATURE_PATTERN, 'Expected 64 bytes as canonical base64url');
61
+ /** A ciphertext (tag included) as canonical base64url, at most 64 KiB of characters. */
62
+ exports.keychainCiphertextSchema = zod_1.z
63
+ .string()
64
+ .check((0, stringChecks_1.utf16MinLength)(22))
65
+ .check((0, stringChecks_1.utf16MaxLength)(keychain_1.KEYCHAIN_LIMITS.maxCiphertextLength))
66
+ .regex(keychain_1.KEYCHAIN_BASE64URL_PATTERN, 'Expected canonical base64url');
67
+ const hashSchema = zod_1.z.string().regex(keychain_1.KEYCHAIN_HASH_PATTERN, 'Expected a lowercase SHA-256 hex');
68
+ const generationSchema = zod_1.z.number().check((0, numberChecks_1.integerCheck)()).min(1).max(Number.MAX_SAFE_INTEGER);
69
+ const revisionSchema = zod_1.z.number().check((0, numberChecks_1.integerCheck)()).min(1).max(Number.MAX_SAFE_INTEGER);
70
+ /**
71
+ * A member's name: 1 to 256 bytes of UTF-8, any characters (a device's UI
72
+ * sanitizes it for display), but well-formed: no lone surrogate, which JCS
73
+ * cannot carry.
74
+ */
75
+ function isMemberName(name) {
76
+ let bytes = 0;
77
+ for (let index = 0; index < name.length; index++) {
78
+ const unit = name.charCodeAt(index);
79
+ if (unit >= 0xd800 && unit <= 0xdbff) {
80
+ const next = name.charCodeAt(index + 1);
81
+ if (!(next >= 0xdc00 && next <= 0xdfff))
82
+ return false;
83
+ bytes += 4;
84
+ index++;
85
+ }
86
+ else if (unit >= 0xdc00 && unit <= 0xdfff) {
87
+ return false;
88
+ }
89
+ else {
90
+ bytes += unit < 0x80 ? 1 : unit < 0x800 ? 2 : 3;
91
+ }
92
+ }
93
+ return bytes >= 1 && bytes <= keychain_1.KEYCHAIN_LIMITS.maxMemberNameBytes;
94
+ }
95
+ /** `Date#toISOString`'s spelling, and a real instant. */
96
+ function isKeychainTimestamp(value) {
97
+ if (!keychain_1.KEYCHAIN_TIMESTAMP_PATTERN.test(value))
98
+ return false;
99
+ const ms = Date.parse(value);
100
+ return Number.isFinite(ms) && new Date(ms).toISOString() === value;
101
+ }
102
+ exports.keychainMemberSchema = zod_1.z
103
+ .object({
104
+ id: exports.keychainIdSchema,
105
+ name: zod_1.z.string().refine(isMemberName, {
106
+ message: 'A member name is 1 to 256 bytes of well-formed UTF-8',
107
+ }),
108
+ platform: zod_1.z.enum(keychain_1.KEYCHAIN_PLATFORMS),
109
+ signingKey: exports.keychainBytes32Schema,
110
+ boxKey: exports.keychainBytes32Schema,
111
+ })
112
+ .strict();
113
+ exports.keychainRecoveryKeysSchema = zod_1.z
114
+ .object({ signingKey: exports.keychainBytes32Schema, boxKey: exports.keychainBytes32Schema })
115
+ .strict();
116
+ const rosterBodyBase = {
117
+ v: zod_1.z.literal(1),
118
+ vaultId: exports.keychainIdSchema,
119
+ seq: zod_1.z.number().check((0, numberChecks_1.integerCheck)()).min(0).max(Number.MAX_SAFE_INTEGER),
120
+ prev: hashSchema.nullable(),
121
+ createdAt: zod_1.z.string().refine(isKeychainTimestamp, {
122
+ message: 'Expected an ISO 8601 UTC timestamp with milliseconds',
123
+ }),
124
+ };
125
+ /**
126
+ * The parse of an entry's `body` (ADR 0063 D3). `seq`/`prev` continuity, the
127
+ * signatures and the signer rules are the server's and every device's
128
+ * verifier's, not the schema's; the schema only refuses a body that is not
129
+ * one of the five shapes exactly.
130
+ */
131
+ exports.keychainRosterBodySchema = zod_1.z.discriminatedUnion('op', [
132
+ zod_1.z
133
+ .object({
134
+ ...rosterBodyBase,
135
+ op: zod_1.z.literal('genesis'),
136
+ member: exports.keychainMemberSchema,
137
+ recovery: exports.keychainRecoveryKeysSchema,
138
+ })
139
+ .strict(),
140
+ zod_1.z.object({ ...rosterBodyBase, op: zod_1.z.literal('add'), member: exports.keychainMemberSchema }).strict(),
141
+ zod_1.z.object({ ...rosterBodyBase, op: zod_1.z.literal('remove'), memberId: exports.keychainIdSchema }).strict(),
142
+ zod_1.z
143
+ .object({
144
+ ...rosterBodyBase,
145
+ op: zod_1.z.literal('generation'),
146
+ generation: generationSchema.min(2),
147
+ })
148
+ .strict(),
149
+ zod_1.z
150
+ .object({ ...rosterBodyBase, op: zod_1.z.literal('recovery'), recovery: exports.keychainRecoveryKeysSchema })
151
+ .strict(),
152
+ ]);
153
+ exports.keychainSignatureSchema = zod_1.z
154
+ .object({ signer: exports.keychainPrincipalSchema, signature: exports.keychainSignatureValueSchema })
155
+ .strict();
156
+ /** A roster entry as it travels. One or two signatures (genesis has exactly two). */
157
+ exports.keychainEntrySchema = zod_1.z
158
+ .object({
159
+ body: zod_1.z
160
+ .string()
161
+ .check((0, stringChecks_1.utf16MinLength)(2))
162
+ .check((0, stringChecks_1.utf16MaxLength)(keychain_1.KEYCHAIN_LIMITS.maxEntryBodyLength)),
163
+ signatures: zod_1.z.array(exports.keychainSignatureSchema).min(1).max(2),
164
+ })
165
+ .strict();
166
+ exports.keychainWrapSchema = zod_1.z
167
+ .object({
168
+ recipient: exports.keychainPrincipalSchema,
169
+ generation: generationSchema,
170
+ epk: exports.keychainBytes32Schema,
171
+ nonce: exports.keychainNonceSchema,
172
+ ciphertext: exports.keychainCiphertextSchema,
173
+ signer: exports.keychainPrincipalSchema,
174
+ signature: exports.keychainSignatureValueSchema,
175
+ })
176
+ .strict();
177
+ /* -------------------------------------------------------------------------- */
178
+ /* Requests */
179
+ /* -------------------------------------------------------------------------- */
180
+ /** `POST /keychain`: the genesis entry, and the member's and the recovery wraps. */
181
+ exports.keychainCreateRequestSchema = zod_1.z
182
+ .object({
183
+ genesis: exports.keychainEntrySchema,
184
+ wraps: zod_1.z.array(exports.keychainWrapSchema).length(2),
185
+ })
186
+ .strict();
187
+ /** `POST /keychain/roster`: entries continuing the head, and the wraps they require. */
188
+ exports.keychainRosterAppendRequestSchema = zod_1.z
189
+ .object({
190
+ entries: zod_1.z.array(exports.keychainEntrySchema).min(1).max(keychain_1.KEYCHAIN_LIMITS.maxEntriesPerAppend),
191
+ wraps: zod_1.z
192
+ .array(exports.keychainWrapSchema)
193
+ .max(keychain_1.KEYCHAIN_LIMITS.maxLiveMembers + 1)
194
+ .default([]),
195
+ })
196
+ .strict();
197
+ /** `POST /keychain/enrollments`: the new device's member and its commitment. */
198
+ exports.keychainEnrollmentCreateRequestSchema = zod_1.z
199
+ .object({ member: exports.keychainMemberSchema, commitment: exports.keychainBytes32Schema })
200
+ .strict();
201
+ /** `POST /keychain/enrollments/:id/approver-nonce`. */
202
+ exports.keychainApproverNonceRequestSchema = zod_1.z
203
+ .object({ memberId: exports.keychainIdSchema, approverNonce: exports.keychainBytes32Schema })
204
+ .strict();
205
+ /** `POST /keychain/enrollments/:id/reveal`. */
206
+ exports.keychainRevealRequestSchema = zod_1.z
207
+ .object({ deviceNonce: exports.keychainBytes32Schema })
208
+ .strict();
209
+ /** `POST /keychain/enrollments/:id/approve`: the `add` entry and the new member's wrap. */
210
+ exports.keychainApproveRequestSchema = zod_1.z
211
+ .object({ entry: exports.keychainEntrySchema, wrap: exports.keychainWrapSchema })
212
+ .strict();
213
+ /** `PUT /keychain/items/:itemId`. `baseRevision` is `null` only for an item that never existed. */
214
+ exports.keychainItemPutRequestSchema = zod_1.z
215
+ .object({
216
+ baseRevision: revisionSchema.nullable(),
217
+ generation: generationSchema,
218
+ nonce: exports.keychainNonceSchema,
219
+ ciphertext: exports.keychainCiphertextSchema,
220
+ })
221
+ .strict();
222
+ /** `DELETE /keychain/items/:itemId`. */
223
+ exports.keychainItemDeleteRequestSchema = zod_1.z.object({ baseRevision: revisionSchema }).strict();
224
+ /** `GET /keychain/items?since=&limit=`. */
225
+ exports.keychainItemsQuerySchema = zod_1.z
226
+ .object({
227
+ since: zod_1.z.coerce.number().check((0, numberChecks_1.integerCheck)()).min(0).max(Number.MAX_SAFE_INTEGER).default(0),
228
+ limit: zod_1.z.coerce
229
+ .number()
230
+ .check((0, numberChecks_1.integerCheck)())
231
+ .min(1)
232
+ .max(keychain_1.KEYCHAIN_LIMITS.maxItemsPage)
233
+ .default(keychain_1.KEYCHAIN_LIMITS.maxItemsPage),
234
+ })
235
+ .strict();
236
+ exports.keychainEnrollmentParamsSchema = zod_1.z.object({ id: exports.keychainIdSchema }).strict();
237
+ exports.keychainItemParamsSchema = zod_1.z.object({ itemId: exports.keychainIdSchema }).strict();
238
+ /**
239
+ * `DELETE /keychain` — the reset (ADR 0063 D6), with a fresh re-verification.
240
+ *
241
+ * - An account WITHOUT a linked root: `reauth` for `reset_keychain` (ADR 0030:
242
+ * its email code, or its password when it has no email; plus its
243
+ * authenticator's code when it has one).
244
+ * - An account WITH a linked root (Commons, which has no email or password to
245
+ * re-verify with): `rootProof`, a root proof for the `keychain_reset` action
246
+ * over the payload `{ vaultId }` (ADR 0024 D7, challenge from
247
+ * `POST /identity/proof-challenge`), plus `totpCode` when it has an
248
+ * authenticator.
249
+ */
250
+ exports.keychainResetRequestSchema = zod_1.z
251
+ .object({
252
+ reauth: signIn_1.reauthProofSchema.optional(),
253
+ rootProof: identityProof_1.identityProofSchema.optional(),
254
+ totpCode: signIn_1.secondFactorCodeSchema.optional(),
255
+ })
256
+ .strict();
257
+ /* -------------------------------------------------------------------------- */
258
+ /* Responses (mirrored by the checks in ./client/keychain.ts) */
259
+ /* -------------------------------------------------------------------------- */
260
+ const counterSchema = zod_1.z.number().check((0, numberChecks_1.integerCheck)()).nonnegative();
261
+ const positiveIntSchema = zod_1.z.number().check((0, numberChecks_1.integerCheck)()).positive();
262
+ const entryResponseSchema = zod_1.z.object({
263
+ body: zod_1.z.string(),
264
+ signatures: zod_1.z.array(zod_1.z.object({ signer: zod_1.z.string(), signature: zod_1.z.string() })),
265
+ });
266
+ const wrapResponseSchema = zod_1.z.object({
267
+ recipient: zod_1.z.string(),
268
+ generation: positiveIntSchema,
269
+ epk: zod_1.z.string(),
270
+ nonce: zod_1.z.string(),
271
+ ciphertext: zod_1.z.string(),
272
+ signer: zod_1.z.string(),
273
+ signature: zod_1.z.string(),
274
+ });
275
+ const memberResponseSchema = zod_1.z.object({
276
+ id: zod_1.z.string(),
277
+ name: zod_1.z.string(),
278
+ platform: zod_1.z.enum(keychain_1.KEYCHAIN_PLATFORMS),
279
+ signingKey: zod_1.z.string(),
280
+ boxKey: zod_1.z.string(),
281
+ });
282
+ const enrollmentResponseSchema = zod_1.z.object({
283
+ id: zod_1.z.string(),
284
+ vaultId: zod_1.z.string(),
285
+ member: memberResponseSchema,
286
+ commitment: zod_1.z.string(),
287
+ approverNonce: zod_1.z.string().nullable(),
288
+ approverMemberId: zod_1.z.string().nullable(),
289
+ deviceNonce: zod_1.z.string().nullable(),
290
+ status: zod_1.z.enum(keychain_1.KEYCHAIN_ENROLLMENT_STATUSES),
291
+ expiresAt: zod_1.z.string(),
292
+ createdAt: zod_1.z.string(),
293
+ });
294
+ const itemResponseSchema = zod_1.z.object({
295
+ id: zod_1.z.string(),
296
+ revision: counterSchema,
297
+ generation: positiveIntSchema,
298
+ nonce: zod_1.z.string().nullable(),
299
+ ciphertext: zod_1.z.string().nullable(),
300
+ deletedAt: zod_1.z.string().nullable(),
301
+ updatedAt: zod_1.z.string(),
302
+ });
303
+ exports.keychainStateResponseSchema = zod_1.z.object({
304
+ vault: zod_1.z
305
+ .object({
306
+ id: zod_1.z.string(),
307
+ genesisHash: zod_1.z.string(),
308
+ rosterSeq: counterSchema,
309
+ rosterHead: zod_1.z.string(),
310
+ generation: positiveIntSchema,
311
+ revision: counterSchema,
312
+ })
313
+ .nullable(),
314
+ roster: zod_1.z.array(entryResponseSchema),
315
+ members: zod_1.z.array(zod_1.z.object({ id: zod_1.z.string(), orphaned: zod_1.z.boolean(), removed: zod_1.z.boolean() })),
316
+ self: zod_1.z.string().nullable(),
317
+ });
318
+ exports.keychainWrapResponseSchema = zod_1.z.object({
319
+ wrap: wrapResponseSchema,
320
+ });
321
+ exports.keychainEnrollmentResponseSchema = zod_1.z.object({
322
+ enrollment: enrollmentResponseSchema,
323
+ });
324
+ exports.keychainEnrollmentsResponseSchema = zod_1.z.object({
325
+ enrollments: zod_1.z.array(enrollmentResponseSchema),
326
+ });
327
+ exports.keychainItemResponseSchema = zod_1.z.object({
328
+ item: itemResponseSchema,
329
+ });
330
+ exports.keychainItemsResponseSchema = zod_1.z.object({
331
+ items: zod_1.z.array(itemResponseSchema),
332
+ revision: counterSchema,
333
+ more: zod_1.z.boolean(),
334
+ });
@@ -30,6 +30,12 @@ export const IDENTITY_PROOF_ACTIONS = {
30
30
  * root and the new key, and by the current key when the device holds it.
31
31
  */
32
32
  organizationKeyReplace: 'organization_key_replace',
33
+ /**
34
+ * Reset the account's Oxy Keychain (`DELETE /keychain`, ADR 0063 D6) on an
35
+ * account whose root is linked: it has no email or password to re-verify
36
+ * with, so its root confirms the reset. The payload is `{ vaultId }`.
37
+ */
38
+ keychainReset: 'keychain_reset',
33
39
  };
34
40
  export const IDENTITY_PROOF_ACTION_VALUES = Object.values(IDENTITY_PROOF_ACTIONS);
35
41
  export const HEX_DIGEST = /^[0-9a-f]{64}$/;
@@ -130,4 +136,14 @@ export const IDENTITY_ERROR_CODES = {
130
136
  * person deleted (owner's decision, 2026-11-07).
131
137
  */
132
138
  backupOptedOut: 'IDENTITY_BACKUP_OPTED_OUT',
139
+ /**
140
+ * `POST /identity/backup`: the account has no backup on record (never made
141
+ * one, or deleted it before deletions were recorded) and the upload is not
142
+ * the person's explicit choice to create one (`optIn`). Only re-sealing a
143
+ * backup the account HAS (current or superseded) needs no opt-in, so a
144
+ * client too old to send it (Commons 1.12 or older) never creates one
145
+ * silently after a key rotation; the message asks the person to update
146
+ * Commons (owner's decision, 2026-11-07).
147
+ */
148
+ backupOptInRequired: 'IDENTITY_BACKUP_OPT_IN_REQUIRED',
133
149
  };
@@ -48,3 +48,4 @@ export { USER_PROFILE_COLORS, USER_PROFILE_COLOR_PRESETS, FREE_USER_PROFILE_COLO
48
48
  export * from '../products/one.js';
49
49
  export { CAMPAIGN_LABEL_MAX_LENGTH, CAMPAIGN_CLICK_ID_MAX_LENGTH, hasCampaignControlCharacters, } from './campaignAttribution.js';
50
50
  export { isLanguageTag } from './language.js';
51
+ export { KEYCHAIN_PLATFORMS, KEYCHAIN_ROSTER_OPS, KEYCHAIN_ENROLLMENT_STATUSES, KEYCHAIN_RECOVERY, KEYCHAIN_DOMAINS, KEYCHAIN_LIMITS, KEYCHAIN_ERROR_CODES, KEYCHAIN_ID_PATTERN, KEYCHAIN_BYTES32_PATTERN, KEYCHAIN_NONCE_PATTERN, KEYCHAIN_SIGNATURE_PATTERN, KEYCHAIN_BASE64URL_PATTERN, KEYCHAIN_HASH_PATTERN, KEYCHAIN_TIMESTAMP_PATTERN, keychainStateResponseCheck, keychainWrapResponseCheck, keychainEnrollmentResponseCheck, keychainEnrollmentsResponseCheck, keychainItemResponseCheck, keychainItemsResponseCheck, } from './keychain.js';
@@ -0,0 +1,200 @@
1
+ /**
2
+ * The Oxy Keychain's wire contract, without Zod (ADR 0063,
3
+ * `docs/identity/keychain.md`). Schemas: `../keychain.ts`.
4
+ *
5
+ * Oxy stores only ciphertext, public keys, signatures and counters. Every
6
+ * binary value is base64url WITHOUT padding, in its one canonical spelling
7
+ * (the unused low bits of the last character are zero), so no two strings name
8
+ * the same bytes.
9
+ *
10
+ * Part of `@oxy.so/contracts/client`: never import `zod` here (see `./check.ts`).
11
+ */
12
+ import { array, boolean, exact, int, nonnegative, nullable, number, object, oneOf, positive, string, } from './check.js';
13
+ /* -------------------------------------------------------------------------- */
14
+ /* Closed sets and constants */
15
+ /* -------------------------------------------------------------------------- */
16
+ /** The platforms a member may name: a closed set, for display only (ADR 0063 D3). */
17
+ export const KEYCHAIN_PLATFORMS = [
18
+ 'oxyos',
19
+ 'ios',
20
+ 'android',
21
+ 'macos',
22
+ 'windows',
23
+ 'linux',
24
+ 'web',
25
+ ];
26
+ /** The roster's operations (ADR 0063 D3). */
27
+ export const KEYCHAIN_ROSTER_OPS = ['genesis', 'add', 'remove', 'generation', 'recovery'];
28
+ /** An enrollment's states. An expired pending one is answered `410`, never served as pending. */
29
+ export const KEYCHAIN_ENROLLMENT_STATUSES = ['pending', 'approved', 'denied'];
30
+ /**
31
+ * The recipient of the recovery wrap, and the signer named by a signature made
32
+ * with the recovery signing key.
33
+ */
34
+ export const KEYCHAIN_RECOVERY = 'recovery';
35
+ /**
36
+ * Every domain string (ADR 0063 D8). Each signing input, AAD and derivation
37
+ * starts with one, so nothing signed or sealed as one kind can be replayed as
38
+ * another.
39
+ */
40
+ export const KEYCHAIN_DOMAINS = {
41
+ roster: 'oxy.keychain.roster.v1',
42
+ wrap: 'oxy.keychain.wrap.v1',
43
+ item: 'oxy.keychain.item.v1',
44
+ seal: 'oxy.keychain.seal.v1',
45
+ enrollCommit: 'oxy.keychain.enroll.commit.v1',
46
+ enrollCode: 'oxy.keychain.enroll.code.v1',
47
+ recovery: 'oxy.keychain.recovery.v1',
48
+ };
49
+ /** The server's limits (`docs/identity/keychain.md`). */
50
+ export const KEYCHAIN_LIMITS = {
51
+ /** Live (non-deleted) items in one vault. */
52
+ maxLiveItems: 10000,
53
+ /** An item's or a wrap's ciphertext, in base64url characters (64 KiB). */
54
+ maxCiphertextLength: 65536,
55
+ /** Entries in one roster, genesis included. */
56
+ maxRosterEntries: 1000,
57
+ /** Members not removed. */
58
+ maxLiveMembers: 32,
59
+ /** Unexpired pending enrollments per vault. */
60
+ maxPendingEnrollments: 4,
61
+ /** How long an enrollment waits for its approval. */
62
+ enrollmentTtlMs: 10 * 60 * 1000,
63
+ /** Items in one `GET /keychain/items` page. */
64
+ maxItemsPage: 500,
65
+ /** Entries in one roster append. */
66
+ maxEntriesPerAppend: 64,
67
+ /** One roster entry's `body`, in characters. */
68
+ maxEntryBodyLength: 4096,
69
+ /** A member's display name, in bytes of UTF-8 (at least 1; any characters). */
70
+ maxMemberNameBytes: 256,
71
+ };
72
+ /**
73
+ * Stable error codes the `/keychain` routes answer with (`error` in the API's
74
+ * error body). Clients map these through their localization, never the English
75
+ * message.
76
+ */
77
+ export const KEYCHAIN_ERROR_CODES = {
78
+ /** Not a personal account acting as itself. */
79
+ notAvailable: 'KEYCHAIN_NOT_AVAILABLE',
80
+ /** The bearer carries no device session, which a member is bound to. */
81
+ deviceRequired: 'KEYCHAIN_DEVICE_REQUIRED',
82
+ /** `POST /keychain`: the account already has a vault. */
83
+ exists: 'KEYCHAIN_EXISTS',
84
+ /** The account has no vault. */
85
+ notFound: 'KEYCHAIN_NOT_FOUND',
86
+ /** The caller's device session is bound to no live member of the vault. */
87
+ notMember: 'KEYCHAIN_NOT_MEMBER',
88
+ /** The caller's device session is already bound to a live member. */
89
+ alreadyMember: 'KEYCHAIN_ALREADY_MEMBER',
90
+ /** The entries do not continue the roster's head (a fork, a race, a stale head). */
91
+ rosterConflict: 'KEYCHAIN_ROSTER_CONFLICT',
92
+ /** An entry is malformed, non-canonical, badly signed, or breaks a roster rule. */
93
+ rosterInvalid: 'KEYCHAIN_ROSTER_INVALID',
94
+ /** A wrap is malformed, badly signed, or not the one the entries require. */
95
+ wrapInvalid: 'KEYCHAIN_WRAP_INVALID',
96
+ /**
97
+ * A `remove` without its `generation`, or a `generation` without a wrap at
98
+ * that generation for every remaining member and `recovery`.
99
+ */
100
+ rotationIncomplete: 'KEYCHAIN_ROTATION_INCOMPLETE',
101
+ /** A limit of `KEYCHAIN_LIMITS` would be exceeded. */
102
+ limitReached: 'KEYCHAIN_LIMIT_REACHED',
103
+ /** No such enrollment for this vault. */
104
+ enrollmentNotFound: 'KEYCHAIN_ENROLLMENT_NOT_FOUND',
105
+ /** The enrollment's ten minutes are over. */
106
+ enrollmentExpired: 'KEYCHAIN_ENROLLMENT_EXPIRED',
107
+ /** The enrollment is not at the step this request takes (or was decided). */
108
+ enrollmentState: 'KEYCHAIN_ENROLLMENT_STATE',
109
+ /** The revealed device nonce does not open the commitment; the enrollment is denied. */
110
+ commitmentMismatch: 'KEYCHAIN_COMMITMENT_MISMATCH',
111
+ /** No such item, or it is deleted. */
112
+ itemNotFound: 'KEYCHAIN_ITEM_NOT_FOUND',
113
+ /** `baseRevision` is not the item's stored revision: re-read, merge, retry. */
114
+ itemConflict: 'KEYCHAIN_ITEM_CONFLICT',
115
+ /** An item's generation is not between 1 and the vault's. */
116
+ generationInvalid: 'KEYCHAIN_GENERATION_INVALID',
117
+ /** `DELETE /keychain` on an account with a linked root: a root proof is required. */
118
+ resetProofRequired: 'KEYCHAIN_RESET_PROOF_REQUIRED',
119
+ };
120
+ /* -------------------------------------------------------------------------- */
121
+ /* Encodings */
122
+ /* -------------------------------------------------------------------------- */
123
+ /** A lowercase uuid in its 8-4-4-4-12 form, any version: vault, member, item and enrollment ids. */
124
+ export const KEYCHAIN_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
125
+ /** A roster timestamp in its one spelling: UTC with milliseconds, as `Date#toISOString` writes it. */
126
+ export const KEYCHAIN_TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
127
+ /** 32 bytes, canonical base64url (43 characters): keys, enrollment nonces, commitments. */
128
+ export const KEYCHAIN_BYTES32_PATTERN = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;
129
+ /** 24 bytes, base64url (32 characters): an XChaCha20-Poly1305 nonce. */
130
+ export const KEYCHAIN_NONCE_PATTERN = /^[A-Za-z0-9_-]{32}$/;
131
+ /** 64 bytes, canonical base64url (86 characters): an Ed25519 signature. */
132
+ export const KEYCHAIN_SIGNATURE_PATTERN = /^[A-Za-z0-9_-]{85}[AQgw]$/;
133
+ /** Any length of canonical base64url without padding. */
134
+ export const KEYCHAIN_BASE64URL_PATTERN = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2}[AEIMQUYcgkosw048]|[A-Za-z0-9_-][AQgw])?$/;
135
+ /** A roster entry's hash: lowercase hex SHA-256. */
136
+ export const KEYCHAIN_HASH_PATTERN = /^[0-9a-f]{64}$/;
137
+ /* -------------------------------------------------------------------------- */
138
+ /* Response checks */
139
+ /* -------------------------------------------------------------------------- */
140
+ const counter = number(int, nonnegative);
141
+ const generation = number(int, positive);
142
+ const entryCheck = object({
143
+ body: string(),
144
+ signatures: array(object({ signer: string(), signature: string() })),
145
+ });
146
+ const wrapCheck = object({
147
+ recipient: string(),
148
+ generation,
149
+ epk: string(),
150
+ nonce: string(),
151
+ ciphertext: string(),
152
+ signer: string(),
153
+ signature: string(),
154
+ });
155
+ const memberCheck = object({
156
+ id: string(),
157
+ name: string(),
158
+ platform: oneOf(KEYCHAIN_PLATFORMS),
159
+ signingKey: string(),
160
+ boxKey: string(),
161
+ });
162
+ const enrollmentCheck = object({
163
+ id: string(),
164
+ vaultId: string(),
165
+ member: memberCheck,
166
+ commitment: string(),
167
+ approverNonce: nullable(string()),
168
+ approverMemberId: nullable(string()),
169
+ deviceNonce: nullable(string()),
170
+ status: oneOf(KEYCHAIN_ENROLLMENT_STATUSES),
171
+ expiresAt: string(),
172
+ createdAt: string(),
173
+ });
174
+ const itemCheck = object({
175
+ id: string(),
176
+ revision: counter,
177
+ generation,
178
+ nonce: nullable(string()),
179
+ ciphertext: nullable(string()),
180
+ deletedAt: nullable(string()),
181
+ updatedAt: string(),
182
+ });
183
+ export const keychainStateResponseCheck = exact()(object({
184
+ vault: nullable(object({
185
+ id: string(),
186
+ genesisHash: string(),
187
+ rosterSeq: counter,
188
+ rosterHead: string(),
189
+ generation,
190
+ revision: counter,
191
+ })),
192
+ roster: array(entryCheck),
193
+ members: array(object({ id: string(), orphaned: boolean, removed: boolean })),
194
+ self: nullable(string()),
195
+ }));
196
+ export const keychainWrapResponseCheck = exact()(object({ wrap: wrapCheck }));
197
+ export const keychainEnrollmentResponseCheck = exact()(object({ enrollment: enrollmentCheck }));
198
+ export const keychainEnrollmentsResponseCheck = exact()(object({ enrollments: array(enrollmentCheck) }));
199
+ export const keychainItemResponseCheck = exact()(object({ item: itemCheck }));
200
+ export const keychainItemsResponseCheck = exact()(object({ items: array(itemCheck), revision: counter, more: boolean }));
@@ -71,6 +71,8 @@ export const REAUTH_ACTIONS = [
71
71
  'credentials_manage',
72
72
  'supervision',
73
73
  'supervision_purchase',
74
+ /** `DELETE /keychain`: reset the Oxy Keychain, deleting every item (ADR 0063 D6). */
75
+ 'reset_keychain',
74
76
  ];
75
77
  /**
76
78
  * Stable error codes (`error.code` in the API error body). Clients map these
package/dist/esm/index.js CHANGED
@@ -219,3 +219,4 @@ export { integerCheck, safeNumberCheck } from './numberChecks.js';
219
219
  export { campaignAttributionSchema } from './campaignAttribution.js';
220
220
  export { APPLICATION_ACCOUNT_REGISTRATION_BATCH_MAX, APPLICATION_ACCOUNT_TOTAL_MAX_AGE_SECONDS, applicationAccountRegistrationRequestSchema, applicationAccountRegistrationResponseSchema, applicationAccountTotalSchema, } from './applicationAccounts.js';
221
221
  export * from './postalAddresses.js';
222
+ export * from './keychain.js';
@@ -114,13 +114,17 @@ export const backupUploadRequestSchema = backupEnvelopeFields.extend({
114
114
  replacesLookupId: backupLookupIdSchema.optional(),
115
115
  /**
116
116
  * The person's explicit choice to have a backup (owner's decision,
117
- * 2026-11-07). A person who deleted their backup (`status.optedOut`) gets a
118
- * new one only with it: an upload without it is refused (409
119
- * `IDENTITY_BACKUP_OPTED_OUT`), so a key rotation, a re-seal or another
120
- * device never re-uploads silently. An accepted upload with it clears the
121
- * deletion in the same transaction. Ignored when the person never deleted
122
- * one. Clients send it only from a control the person pressed ("Create
123
- * backup", or the rotation's "Create a backup" choice).
117
+ * 2026-11-07). Required whenever the account has NO backup row: a person
118
+ * who deleted theirs (`status.optedOut`; refused without it, 409
119
+ * `IDENTITY_BACKUP_OPTED_OUT`) and a person with none on record (never
120
+ * made one, or deleted it before deletions were recorded; 409
121
+ * `IDENTITY_BACKUP_OPT_IN_REQUIRED`), so a key rotation, a re-seal, another
122
+ * device or an older client never creates one silently. An accepted upload
123
+ * with it clears a recorded deletion in the same transaction. Not needed to
124
+ * re-seal a backup the account has (current, or superseded with
125
+ * `replacesLookupId`). Clients send it only from a control the person
126
+ * pressed ("Create backup", or the rotation's "Create an encrypted backup"
127
+ * choice).
124
128
  */
125
129
  optIn: z.boolean().optional(),
126
130
  });