@serve.zone/interfaces 32.79.0 → 32.81.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,606 @@
1
+ import { compareWireTokens } from '../private/canonicaljson.js';
2
+ import {
3
+ validateControllerCounter,
4
+ validateControllerIdentifier,
5
+ validateControllerOrigin,
6
+ } from '../private/controllercontract.js';
7
+ import { readDataElements, readExactDataRecord } from '../private/dataproperties.js';
8
+ import type { TCompleteKeyList } from '../private/keylist.js';
9
+ import { controllerPeerSetContract } from './controller.js';
10
+ import { isReleaseVersion } from './releaseversion.js';
11
+
12
+ /*
13
+ * The witness (AGL-1195, Linus rulings 69 Q5, Q6 and 73): a small service of its own, at a third site, that
14
+ * keeps one compare-and-set record per controller. Cloudly is its only caller and reaches it with
15
+ * TypedRequest over HTTPS (`requests.witness`, at `witnessContract.typedRequestPath` below the
16
+ * witness's `https` origin).
17
+ *
18
+ * The record decides two things and nothing else: which site is active in which epoch, and whether
19
+ * the active has a standby in sync with it. An active continues without a standby only after a
20
+ * change that records none, so a standby the record names in sync holds every write the active
21
+ * acknowledged; a promotion must name the standby the record holds in sync, so a stale standby is
22
+ * never promoted. If neither the witness nor the standby can be reached, the active records nothing
23
+ * and acknowledges nothing.
24
+ *
25
+ * A site is named by its site origin (ruling 69 Q3): the canonical `https` origin of one controller
26
+ * site, the value `IControllerPeerSet.activeOrigin` carries while that site is active, never the
27
+ * public origin browsers use. The witness holds no controller data and no controller credential.
28
+ *
29
+ * A member's bearer is a fact about one site (ruling 73 F1, F5). The site creates it, base64url of
30
+ * `witnessContract.bearerRandomBytes` random bytes, and keeps it in that site's own config or secret
31
+ * store, never in the replicated controller database, from which every other site would read it.
32
+ * The witness learns only its SHA-256 (`bearerSha256`, at pairing or enrollment) and checks a
33
+ * presented bearer by hashing it and comparing in constant time; no answer ever carries a bearer.
34
+ * So a pairing or an enrollment whose answer was lost is recovered by reading the record with the
35
+ * bearer the site already holds.
36
+ *
37
+ * The witness checks a request in this order and answers the first refusal: `request-invalid`; then
38
+ * for a pairing the code (`pairing-code-unknown`, `-expired`, `-used`, then `controller-mismatch`,
39
+ * `controller-paired`), for every other request but `getWitnessHealth` the authentication
40
+ * (`credential-invalid`); then `revision-stale` for a request naming `expectedRevision`; then the
41
+ * first refusal of the judge (`judgeWitnessChange`, `judgeWitnessMemberEnrollment`), in the order its
42
+ * doc states. The order of `witnessRefusals` is a vocabulary, not this order.
43
+ */
44
+
45
+ export const witnessContract = Object.freeze({
46
+ /** The path of the witness's TypedRequest endpoint below its `https` origin. */
47
+ typedRequestPath: '/typedrequest',
48
+ /** The longest site origin: the bound of every `IControllerPeerSet` origin. */
49
+ maximumOriginLength: controllerPeerSetContract.maximumOriginLength,
50
+ /** The active site and at most `controllerPeerSetContract.maximumShadowOrigins` shadows. */
51
+ maximumMemberOrigins: controllerPeerSetContract.maximumShadowOrigins + 1,
52
+ /** A member bearer is base64url, unpadded, of this many random bytes: 43 characters. */
53
+ bearerRandomBytes: 32,
54
+ /** The longest pairing code: base64url characters. */
55
+ maximumPairingCodeLength: 64,
56
+ } as const);
57
+
58
+ /** What a change of a witness record decides: the epoch, its active site and that site's in-sync standby. */
59
+ export interface IWitnessState {
60
+ /** A positive safe integer: the controller epoch, the value `IControllerPeerSet.epoch` carries. */
61
+ epoch: number;
62
+ /** The site origin of the controller that is active in `epoch`. */
63
+ activeOrigin: string;
64
+ /**
65
+ * The member site the active records as a standby in sync with it, and so the only site a
66
+ * promotion may name; `null` once the active continues without a standby, and after every epoch
67
+ * raise.
68
+ */
69
+ inSyncStandbyOrigin: string | null;
70
+ }
71
+
72
+ /** The witness record of one controller (`validateWitnessRecord`). */
73
+ export interface IWitnessRecord extends IWitnessState {
74
+ controllerId: string;
75
+ /**
76
+ * A positive safe integer, 1 when the record is paired and raised by one with every accepted
77
+ * change, an enrollment included. A change names the revision it read (`expectedRevision`).
78
+ */
79
+ revision: number;
80
+ /**
81
+ * Every member site, as a canonical list: strictly increasing (`compareWireTokens`, so each once),
82
+ * 1 to `witnessContract.maximumMemberOrigins` origins. The active and the in-sync standby are
83
+ * members. Only a member authenticates, and only `enrollWitnessMember` adds one.
84
+ */
85
+ memberOrigins: string[];
86
+ }
87
+
88
+ /**
89
+ * A member site's credential: the member the caller is and the bearer that site created for itself.
90
+ * Enrolling a member again replaces its bearer hash; the previous bearer stops authenticating.
91
+ */
92
+ export interface IWitnessMemberCredential {
93
+ /** The member's site origin. */
94
+ origin: string;
95
+ /**
96
+ * Base64url, unpadded, of `witnessContract.bearerRandomBytes` random bytes: exactly 43 characters,
97
+ * the canonical encoding. Kept in the site's own config or secret store, never in the replicated
98
+ * controller database; never logged, never part of a refusal.
99
+ */
100
+ bearer: string;
101
+ }
102
+
103
+ /** The body of `pairWitnessController` (`validatePairWitnessControllerRequest`). */
104
+ export interface IPairWitnessControllerRequest {
105
+ /**
106
+ * The one-time code the witness's operator made on the witness host for `controllerId`:
107
+ * 1 to `witnessContract.maximumPairingCodeLength` base64url characters.
108
+ */
109
+ pairingCode: string;
110
+ controllerId: string;
111
+ /** The controller's current epoch. */
112
+ epoch: number;
113
+ /** The caller's own site origin; it becomes the active site and the only member. */
114
+ origin: string;
115
+ /**
116
+ * The SHA-256 of the UTF-8 of the bearer the caller created for itself: 64 lowercase hex
117
+ * characters. The bearer itself never leaves the caller's site.
118
+ */
119
+ bearerSha256: string;
120
+ }
121
+
122
+ /** The body of `enrollWitnessMember` (`validateEnrollWitnessMemberRequest`). */
123
+ export interface IEnrollWitnessMemberRequest {
124
+ controllerId: string;
125
+ /** The active's own credential. */
126
+ member: IWitnessMemberCredential;
127
+ /** The record revision the active read; the enrollment is a compare-and-set on it. */
128
+ expectedRevision: number;
129
+ /**
130
+ * The site to enroll: a new member, or an existing one whose bearer hash is replaced. Never the
131
+ * caller, never the recorded in-sync standby (`judgeWitnessMemberEnrollment`).
132
+ */
133
+ origin: string;
134
+ /**
135
+ * The SHA-256 of the UTF-8 of the bearer that site created for itself: 64 lowercase hex
136
+ * characters. The site hands the active only this hash, never the bearer.
137
+ */
138
+ bearerSha256: string;
139
+ }
140
+
141
+ /** The body of `getWitnessRecord` (`validateGetWitnessRecordRequest`). */
142
+ export interface IGetWitnessRecordRequest {
143
+ controllerId: string;
144
+ member: IWitnessMemberCredential;
145
+ }
146
+
147
+ /** The body of `compareAndSetWitnessRecord` (`validateCompareAndSetWitnessRecordRequest`). */
148
+ export interface ICompareAndSetWitnessRecordRequest {
149
+ controllerId: string;
150
+ member: IWitnessMemberCredential;
151
+ /** The record revision the caller read; any other stored revision refuses the change. */
152
+ expectedRevision: number;
153
+ /** The state the record holds after the change (`judgeWitnessChange`). */
154
+ next: IWitnessState;
155
+ }
156
+
157
+ /** What the witness answers `getWitnessHealth` (`validateWitnessHealth`); it names no controller. */
158
+ export interface IWitnessHealth {
159
+ /** True while the witness can read and write its records. */
160
+ ready: boolean;
161
+ /** The witness release the site runs (`data.isReleaseVersion`). */
162
+ witnessVersion: string;
163
+ /** The release of this package the witness speaks (`data.isReleaseVersion`). */
164
+ interfacesVersion: string;
165
+ }
166
+
167
+ /**
168
+ * Every reason the witness answers instead of a request, as a `TypedResponseError` whose `errorData`
169
+ * is `IWitnessRefusalErrorData` and whose text carries the detail, never a bearer or a pairing code.
170
+ *
171
+ * This list is the closed vocabulary; its order is not the order the witness checks a request in.
172
+ * That order is the gate order this module's header states, then the judge's own.
173
+ *
174
+ * Only `witnessMomentaryRefusals` are momentary. A change whose answer does not arrive at all, like
175
+ * one refused `outcome-unknown`, may have been stored: the caller reads the record before it acts on
176
+ * the change or sends another.
177
+ */
178
+ export const witnessRefusals = Object.freeze([
179
+ /** The request failed its contract validator; the text carries the validator's sentences. */
180
+ 'request-invalid',
181
+ /** No pairing code has the value the controller redeemed. */
182
+ 'pairing-code-unknown',
183
+ /** The pairing code's lifetime ended before the controller redeemed it. */
184
+ 'pairing-code-expired',
185
+ /** The pairing code was redeemed already; a code pairs once. */
186
+ 'pairing-code-used',
187
+ /** The pairing code was made for another controller id; it stays unconsumed. */
188
+ 'controller-mismatch',
189
+ /** The witness holds a record for the controller already; the pairing code stays unconsumed. */
190
+ 'controller-paired',
191
+ /**
192
+ * The caller did not authenticate: the witness holds no record for the controller id, the
193
+ * credential's origin is not a member of it, or the bearer's SHA-256 is not the one last paired or
194
+ * enrolled for that member. One code for all three, so a caller learns nothing about which
195
+ * controllers or members exist (ruling 73 Q8); the witness's log keeps which case it was.
196
+ */
197
+ 'credential-invalid',
198
+ /**
199
+ * `expectedRevision` is not the stored revision, so the record changed since the caller read it;
200
+ * the text names the stored revision. Nothing was changed: read the record and decide again.
201
+ */
202
+ 'revision-stale',
203
+ /**
204
+ * A change only the active site makes, from another member: a change within the epoch, an epoch
205
+ * raise that keeps the active, or an enrollment.
206
+ */
207
+ 'site-not-active',
208
+ /** The next epoch is neither the record's epoch nor the one above it. */
209
+ 'epoch-invalid',
210
+ /**
211
+ * A promotion names an active site the record does not hold as its in-sync standby: a stale
212
+ * standby is never promoted.
213
+ */
214
+ 'standby-not-in-sync',
215
+ /**
216
+ * Any other rule of `judgeWitnessChange`: the active changes within an epoch, an epoch raise
217
+ * records an in-sync standby, a promotion is stated by another site than the one it promotes, or
218
+ * the next state names a site that is not a member. And `judgeWitnessMemberEnrollment`'s: an
219
+ * enrollment of the site the record holds as its in-sync standby, which would replace the bearer of
220
+ * the one site that may promote itself; the active drops that standby by compare-and-set first.
221
+ */
222
+ 'transition-invalid',
223
+ /** An enrollment of a new member while the record holds `witnessContract.maximumMemberOrigins` members. */
224
+ 'member-limit',
225
+ /** Momentary: the witness could not read or write its records; nothing was changed. */
226
+ 'witness-unavailable',
227
+ /**
228
+ * Momentary: the witness sent the change to its storage and does not know whether it was stored.
229
+ * Read the record before acting on the change or sending another.
230
+ */
231
+ 'outcome-unknown',
232
+ ] as const);
233
+
234
+ /** One of the reasons the witness answers instead of a request. */
235
+ export type TWitnessRefusal = typeof witnessRefusals[number];
236
+
237
+ /** The refusals that describe the witness's own state rather than a judgement of the request. */
238
+ export const witnessMomentaryRefusals = Object.freeze([
239
+ 'witness-unavailable',
240
+ 'outcome-unknown',
241
+ ] as const satisfies readonly TWitnessRefusal[]);
242
+
243
+ /** One of the momentary witness refusals. */
244
+ export type TWitnessMomentaryRefusal = typeof witnessMomentaryRefusals[number];
245
+
246
+ /** A witness refusal as `TypedResponseError.errorData`; the error text carries its detail. */
247
+ export interface IWitnessRefusalErrorData {
248
+ code: TWitnessRefusal;
249
+ /**
250
+ * True exactly for `witnessMomentaryRefusals`: the same request may be sent again later. Every
251
+ * other refusal answers the same request again until the state the code names has changed.
252
+ */
253
+ retryable: boolean;
254
+ }
255
+
256
+ /** True for one of `witnessRefusals`. */
257
+ export const isWitnessRefusal = (valueArg: unknown): valueArg is TWitnessRefusal => (
258
+ (witnessRefusals as readonly unknown[]).includes(valueArg)
259
+ );
260
+
261
+ /** True for one of `witnessMomentaryRefusals`. */
262
+ export const isWitnessMomentaryRefusal = (valueArg: unknown): valueArg is TWitnessMomentaryRefusal => (
263
+ (witnessMomentaryRefusals as readonly unknown[]).includes(valueArg)
264
+ );
265
+
266
+ /** The `errorData` the witness answers a refusal with. */
267
+ export const createWitnessRefusalErrorData = (codeArg: TWitnessRefusal): IWitnessRefusalErrorData => (
268
+ Object.freeze({ code: codeArg, retryable: isWitnessMomentaryRefusal(codeArg) })
269
+ );
270
+
271
+ const refusalErrorDataKeyList = ['code', 'retryable'] as const;
272
+ const refusalErrorDataKeys: TCompleteKeyList<IWitnessRefusalErrorData, typeof refusalErrorDataKeyList> =
273
+ refusalErrorDataKeyList;
274
+
275
+ /**
276
+ * The witness refusal an error payload states, or `null` when it is not exactly one: a payload with
277
+ * another member, an unknown code or a `retryable` that disagrees with the code reads as no answer
278
+ * from the witness, never as a verdict.
279
+ */
280
+ export const readWitnessRefusalErrorData = (valueArg: unknown): IWitnessRefusalErrorData | null => {
281
+ const record = readExactDataRecord(valueArg, refusalErrorDataKeys);
282
+ if (record === null || !isWitnessRefusal(record.code)
283
+ || record.retryable !== isWitnessMomentaryRefusal(record.code)) {
284
+ return null;
285
+ }
286
+ return createWitnessRefusalErrorData(record.code);
287
+ };
288
+
289
+ /**
290
+ * Whether a member may change a witness record to `nextArg`: `null` when the change is admissible,
291
+ * otherwise the refusal the witness answers. The witness applies it to the stored record before its
292
+ * compare-and-set, and a controller asks it before it sends one.
293
+ *
294
+ * It judges the decision only, on values that passed `validateWitnessRecord` and
295
+ * `validateWitnessState`. That the caller authenticated as `callerOriginArg` is the witness's to
296
+ * check, and whether `recordArg` is still the stored revision is the compare-and-set's
297
+ * (`revision-stale`); a caller that is no member is refused `credential-invalid`, as the
298
+ * authentication would have.
299
+ *
300
+ * - Within an epoch only the active changes the record, and only its in-sync standby.
301
+ * - An epoch rises by exactly one, and every epoch raise records no in-sync standby: no site has
302
+ * followed an epoch nobody has written in yet.
303
+ * - An epoch raise that keeps the active (a database restore, ruling 30) is the active's own.
304
+ * - A promotion names as active the site the record holds as its in-sync standby, and is stated by
305
+ * that site.
306
+ *
307
+ * An admissible change that leaves the state as it was is still a change: it raises the revision.
308
+ *
309
+ * It answers the first of these that applies, in this order: `credential-invalid` for a caller that
310
+ * is no member; `transition-invalid` for a next state naming a site that is no member, or the active
311
+ * as its own standby; within the epoch `site-not-active` for another caller, then
312
+ * `transition-invalid` for a changed active; `epoch-invalid` for any epoch but this one or the next;
313
+ * `transition-invalid` for a raise that records a standby; for a raise keeping the active
314
+ * `site-not-active` for another caller; `standby-not-in-sync` for a promotion of another site than
315
+ * the recorded in-sync standby; `transition-invalid` for a promotion stated by another site.
316
+ */
317
+ export const judgeWitnessChange = (
318
+ recordArg: Readonly<IWitnessRecord>,
319
+ callerOriginArg: string,
320
+ nextArg: Readonly<IWitnessState>,
321
+ ): TWitnessRefusal | null => {
322
+ const isMember = (originArg: string): boolean => recordArg.memberOrigins.includes(originArg);
323
+ if (!isMember(callerOriginArg)) {
324
+ return 'credential-invalid';
325
+ }
326
+ if (!isMember(nextArg.activeOrigin)
327
+ || (nextArg.inSyncStandbyOrigin !== null && !isMember(nextArg.inSyncStandbyOrigin))
328
+ || nextArg.inSyncStandbyOrigin === nextArg.activeOrigin) {
329
+ return 'transition-invalid';
330
+ }
331
+ if (nextArg.epoch === recordArg.epoch) {
332
+ if (callerOriginArg !== recordArg.activeOrigin) {
333
+ return 'site-not-active';
334
+ }
335
+ return nextArg.activeOrigin === recordArg.activeOrigin ? null : 'transition-invalid';
336
+ }
337
+ if (nextArg.epoch !== recordArg.epoch + 1) {
338
+ return 'epoch-invalid';
339
+ }
340
+ if (nextArg.inSyncStandbyOrigin !== null) {
341
+ return 'transition-invalid';
342
+ }
343
+ if (nextArg.activeOrigin === recordArg.activeOrigin) {
344
+ return callerOriginArg === recordArg.activeOrigin ? null : 'site-not-active';
345
+ }
346
+ if (nextArg.activeOrigin !== recordArg.inSyncStandbyOrigin) {
347
+ return 'standby-not-in-sync';
348
+ }
349
+ return callerOriginArg === nextArg.activeOrigin ? null : 'transition-invalid';
350
+ };
351
+
352
+ /**
353
+ * Whether a member may enroll `originArg` on a witness record: `null` when it may, otherwise the
354
+ * refusal the witness answers. Only the active enrolls, never itself (the request validator refuses
355
+ * that), never the recorded in-sync standby, and a new member only while the record has room for
356
+ * one. Enrolling an existing member replaces its bearer hash and leaves the state as it is; either
357
+ * way the revision rises.
358
+ *
359
+ * The in-sync standby is refused `transition-invalid`: replacing its bearer hash would let the
360
+ * active lock the one site that may promote itself out of the promotion. The active drops that
361
+ * standby by compare-and-set first (`judgeWitnessChange`), then enrolls it again.
362
+ *
363
+ * It answers the first of these that applies, in this order: `credential-invalid` for a caller that
364
+ * is no member, `site-not-active` for a caller that is not the active, `request-invalid` for the
365
+ * caller's own origin, `transition-invalid` for the in-sync standby, `member-limit` for a new member
366
+ * of a full record.
367
+ */
368
+ export const judgeWitnessMemberEnrollment = (
369
+ recordArg: Readonly<IWitnessRecord>,
370
+ callerOriginArg: string,
371
+ originArg: string,
372
+ ): TWitnessRefusal | null => {
373
+ if (!recordArg.memberOrigins.includes(callerOriginArg)) {
374
+ return 'credential-invalid';
375
+ }
376
+ if (callerOriginArg !== recordArg.activeOrigin) {
377
+ return 'site-not-active';
378
+ }
379
+ if (originArg === callerOriginArg) {
380
+ return 'request-invalid';
381
+ }
382
+ if (originArg === recordArg.inSyncStandbyOrigin) {
383
+ return 'transition-invalid';
384
+ }
385
+ return recordArg.memberOrigins.includes(originArg)
386
+ || recordArg.memberOrigins.length < witnessContract.maximumMemberOrigins
387
+ ? null
388
+ : 'member-limit';
389
+ };
390
+
391
+ const stateKeyList = ['epoch', 'activeOrigin', 'inSyncStandbyOrigin'] as const;
392
+ const stateKeys: TCompleteKeyList<IWitnessState, typeof stateKeyList> = stateKeyList;
393
+ const recordKeyList = [
394
+ 'controllerId', 'epoch', 'activeOrigin', 'inSyncStandbyOrigin', 'revision', 'memberOrigins',
395
+ ] as const;
396
+ const recordKeys: TCompleteKeyList<IWitnessRecord, typeof recordKeyList> = recordKeyList;
397
+ const credentialKeyList = ['origin', 'bearer'] as const;
398
+ const credentialKeys: TCompleteKeyList<IWitnessMemberCredential, typeof credentialKeyList> = credentialKeyList;
399
+ const pairKeyList = ['pairingCode', 'controllerId', 'epoch', 'origin', 'bearerSha256'] as const;
400
+ const pairKeys: TCompleteKeyList<IPairWitnessControllerRequest, typeof pairKeyList> = pairKeyList;
401
+ const enrollKeyList = ['controllerId', 'member', 'expectedRevision', 'origin', 'bearerSha256'] as const;
402
+ const enrollKeys: TCompleteKeyList<IEnrollWitnessMemberRequest, typeof enrollKeyList> = enrollKeyList;
403
+ const getKeyList = ['controllerId', 'member'] as const;
404
+ const getKeys: TCompleteKeyList<IGetWitnessRecordRequest, typeof getKeyList> = getKeyList;
405
+ const compareAndSetKeyList = ['controllerId', 'member', 'expectedRevision', 'next'] as const;
406
+ const compareAndSetKeys: TCompleteKeyList<ICompareAndSetWitnessRecordRequest, typeof compareAndSetKeyList> =
407
+ compareAndSetKeyList;
408
+ const healthKeyList = ['ready', 'witnessVersion', 'interfacesVersion'] as const;
409
+ const healthKeys: TCompleteKeyList<IWitnessHealth, typeof healthKeyList> = healthKeyList;
410
+
411
+ const validateOrigin = (valueArg: unknown, pathArg: string): string[] => (
412
+ validateControllerOrigin(valueArg, pathArg, witnessContract.maximumOriginLength)
413
+ );
414
+
415
+ /**
416
+ * The canonical unpadded base64url of 32 bytes: 42 characters of six bits each and a last one that
417
+ * carries the remaining four bits, so its two low bits are zero.
418
+ */
419
+ const bearerPattern = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;
420
+
421
+ /** A bearer as `IWitnessMemberCredential.bearer` states it; the refusal names the field, never the value. */
422
+ const validateBearer = (valueArg: unknown, pathArg: string): string[] => (
423
+ typeof valueArg === 'string' && bearerPattern.test(valueArg)
424
+ ? []
425
+ : [`${pathArg} must be the base64url of ${witnessContract.bearerRandomBytes} random bytes: 43 characters`]
426
+ );
427
+
428
+ const sha256Pattern = /^[0-9a-f]{64}$/;
429
+
430
+ const validateBearerSha256 = (valueArg: unknown, pathArg: string): string[] => (
431
+ typeof valueArg === 'string' && sha256Pattern.test(valueArg)
432
+ ? []
433
+ : [`${pathArg} must be a SHA-256 digest of 64 lowercase hex characters`]
434
+ );
435
+
436
+ const pairingCodePattern = /^[A-Za-z0-9_-]+$/;
437
+
438
+ /** A pairing code of base64url characters; the refusal names the field, never the value. */
439
+ const validatePairingCode = (valueArg: unknown, pathArg: string): string[] => (
440
+ typeof valueArg === 'string' && valueArg.length <= witnessContract.maximumPairingCodeLength
441
+ && pairingCodePattern.test(valueArg)
442
+ ? []
443
+ : [`${pathArg} must be 1 to ${witnessContract.maximumPairingCodeLength} base64url characters`]
444
+ );
445
+
446
+ const validateVersion = (valueArg: unknown, pathArg: string): string[] => (
447
+ isReleaseVersion(valueArg) ? [] : [`${pathArg} must be a release version such as 1.2.3`]
448
+ );
449
+
450
+ /** The decision members of a state or a record, read from a record that has its keys. */
451
+ const validateStateMembers = (recordArg: Record<string, unknown>, pathArg: string): string[] => {
452
+ const errors = [
453
+ ...validateControllerCounter(recordArg.epoch, `${pathArg} epoch`),
454
+ ...validateOrigin(recordArg.activeOrigin, `${pathArg} activeOrigin`),
455
+ ];
456
+ if (recordArg.inSyncStandbyOrigin !== null) {
457
+ errors.push(...validateOrigin(recordArg.inSyncStandbyOrigin, `${pathArg} inSyncStandbyOrigin`));
458
+ if (recordArg.inSyncStandbyOrigin === recordArg.activeOrigin) {
459
+ errors.push(`${pathArg} inSyncStandbyOrigin must not be the active origin`);
460
+ }
461
+ }
462
+ return errors;
463
+ };
464
+
465
+ /**
466
+ * Validates one witness state, the decision a change sets, and names every reason it is refused.
467
+ * Shape only: whether the record admits the change is `judgeWitnessChange`'s to decide.
468
+ */
469
+ export const validateWitnessState = (valueArg: unknown, pathArg = 'witness state'): string[] => {
470
+ const record = readExactDataRecord(valueArg, stateKeys);
471
+ return record === null ? [`${pathArg} must use its exact schema`] : validateStateMembers(record, pathArg);
472
+ };
473
+
474
+ /** Validates one witness record and names every reason it is refused. */
475
+ export const validateWitnessRecord = (valueArg: unknown, pathArg = 'witness record'): string[] => {
476
+ const record = readExactDataRecord(valueArg, recordKeys);
477
+ if (record === null) {
478
+ return [`${pathArg} must use its exact schema`];
479
+ }
480
+ const errors = [
481
+ ...validateControllerIdentifier(record.controllerId, `${pathArg} controllerId`),
482
+ ...validateStateMembers(record, pathArg),
483
+ ...validateControllerCounter(record.revision, `${pathArg} revision`),
484
+ ];
485
+ const { maximumMemberOrigins } = witnessContract;
486
+ const members = readDataElements(record.memberOrigins, maximumMemberOrigins);
487
+ if (members === null || members.length === 0) {
488
+ errors.push(`${pathArg} memberOrigins must be a dense list of 1 to ${maximumMemberOrigins} origins`);
489
+ return errors;
490
+ }
491
+ members.forEach((originArg, indexArg) => {
492
+ errors.push(...validateOrigin(originArg, `${pathArg} memberOrigins[${indexArg}]`));
493
+ });
494
+ // A member that is no string is refused by its own validator, and the order is judged without it.
495
+ const origins = members.filter((originArg): originArg is string => typeof originArg === 'string');
496
+ if (origins.some((originArg, indexArg) => indexArg > 0 && compareWireTokens(origins[indexArg - 1], originArg) >= 0)) {
497
+ errors.push(`${pathArg} memberOrigins must be strictly increasing, each origin once`);
498
+ }
499
+ if (!members.includes(record.activeOrigin)) {
500
+ errors.push(`${pathArg} activeOrigin must be one of memberOrigins`);
501
+ }
502
+ if (record.inSyncStandbyOrigin !== null && !members.includes(record.inSyncStandbyOrigin)) {
503
+ errors.push(`${pathArg} inSyncStandbyOrigin must be one of memberOrigins`);
504
+ }
505
+ return errors;
506
+ };
507
+
508
+ /** Validates one member credential; no refusal carries the bearer. */
509
+ export const validateWitnessMemberCredential = (
510
+ valueArg: unknown,
511
+ pathArg = 'witness member credential',
512
+ ): string[] => {
513
+ const record = readExactDataRecord(valueArg, credentialKeys);
514
+ return record === null
515
+ ? [`${pathArg} must use its exact schema`]
516
+ : [
517
+ ...validateOrigin(record.origin, `${pathArg} origin`),
518
+ ...validateBearer(record.bearer, `${pathArg} bearer`),
519
+ ];
520
+ };
521
+
522
+ /** Validates a `pairWitnessController` body; no refusal carries the pairing code. */
523
+ export const validatePairWitnessControllerRequest = (
524
+ valueArg: unknown,
525
+ pathArg = 'pair witness controller request',
526
+ ): string[] => {
527
+ const record = readExactDataRecord(valueArg, pairKeys);
528
+ return record === null
529
+ ? [`${pathArg} must use its exact schema`]
530
+ : [
531
+ ...validatePairingCode(record.pairingCode, `${pathArg} pairingCode`),
532
+ ...validateControllerIdentifier(record.controllerId, `${pathArg} controllerId`),
533
+ ...validateControllerCounter(record.epoch, `${pathArg} epoch`),
534
+ ...validateOrigin(record.origin, `${pathArg} origin`),
535
+ ...validateBearerSha256(record.bearerSha256, `${pathArg} bearerSha256`),
536
+ ];
537
+ };
538
+
539
+ /** Validates an `enrollWitnessMember` body; no refusal carries the bearer. */
540
+ export const validateEnrollWitnessMemberRequest = (
541
+ valueArg: unknown,
542
+ pathArg = 'enroll witness member request',
543
+ ): string[] => {
544
+ const record = readExactDataRecord(valueArg, enrollKeys);
545
+ if (record === null) {
546
+ return [`${pathArg} must use its exact schema`];
547
+ }
548
+ const errors = [
549
+ ...validateControllerIdentifier(record.controllerId, `${pathArg} controllerId`),
550
+ ...validateWitnessMemberCredential(record.member, `${pathArg} member`),
551
+ ...validateControllerCounter(record.expectedRevision, `${pathArg} expectedRevision`),
552
+ ...validateOrigin(record.origin, `${pathArg} origin`),
553
+ ...validateBearerSha256(record.bearerSha256, `${pathArg} bearerSha256`),
554
+ ];
555
+ const memberOrigin = readExactDataRecord(record.member, credentialKeys)?.origin;
556
+ if (memberOrigin !== undefined && memberOrigin === record.origin) {
557
+ errors.push(`${pathArg} origin must not be the caller's own origin`);
558
+ }
559
+ return errors;
560
+ };
561
+
562
+ /** Validates a `getWitnessRecord` body; no refusal carries the bearer. */
563
+ export const validateGetWitnessRecordRequest = (
564
+ valueArg: unknown,
565
+ pathArg = 'get witness record request',
566
+ ): string[] => {
567
+ const record = readExactDataRecord(valueArg, getKeys);
568
+ return record === null
569
+ ? [`${pathArg} must use its exact schema`]
570
+ : [
571
+ ...validateControllerIdentifier(record.controllerId, `${pathArg} controllerId`),
572
+ ...validateWitnessMemberCredential(record.member, `${pathArg} member`),
573
+ ];
574
+ };
575
+
576
+ /** Validates a `compareAndSetWitnessRecord` body; no refusal carries the bearer. */
577
+ export const validateCompareAndSetWitnessRecordRequest = (
578
+ valueArg: unknown,
579
+ pathArg = 'compare and set witness record request',
580
+ ): string[] => {
581
+ const record = readExactDataRecord(valueArg, compareAndSetKeys);
582
+ return record === null
583
+ ? [`${pathArg} must use its exact schema`]
584
+ : [
585
+ ...validateControllerIdentifier(record.controllerId, `${pathArg} controllerId`),
586
+ ...validateWitnessMemberCredential(record.member, `${pathArg} member`),
587
+ ...validateControllerCounter(record.expectedRevision, `${pathArg} expectedRevision`),
588
+ ...validateWitnessState(record.next, `${pathArg} next`),
589
+ ];
590
+ };
591
+
592
+ /** Validates the witness's `getWitnessHealth` answer. */
593
+ export const validateWitnessHealth = (valueArg: unknown, pathArg = 'witness health'): string[] => {
594
+ const record = readExactDataRecord(valueArg, healthKeys);
595
+ if (record === null) {
596
+ return [`${pathArg} must use its exact schema`];
597
+ }
598
+ const errors = [
599
+ ...validateVersion(record.witnessVersion, `${pathArg} witnessVersion`),
600
+ ...validateVersion(record.interfacesVersion, `${pathArg} interfacesVersion`),
601
+ ];
602
+ if (typeof record.ready !== 'boolean') {
603
+ errors.push(`${pathArg} ready must be a boolean`);
604
+ }
605
+ return errors;
606
+ };
@@ -41,6 +41,7 @@ import * as statusRequests from './status.js';
41
41
  import * as taskRequests from './task.js';
42
42
  import * as versionRequests from './version.js';
43
43
  import * as webPushRequests from './webpush.js';
44
+ import * as witnessRequests from './witness.js';
44
45
 
45
46
  export {
46
47
  adminRequests as admin,
@@ -84,6 +85,7 @@ export {
84
85
  taskRequests as task,
85
86
  versionRequests as version,
86
87
  webPushRequests as webpush,
88
+ witnessRequests as witness,
87
89
  };
88
90
 
89
91
  export * from './inform.js';