@adea-ai/runtime-gateway-protocol 1.17.4 → 1.18.1
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.
- package/README.md +24 -2
- package/dist/content-key.js +3 -18
- package/dist/device-relay.d.ts +10 -1
- package/dist/device-relay.js +138 -57
- package/dist/device-sync.d.ts +273 -4
- package/dist/device-sync.js +257 -27
- package/dist/shared.d.ts +5 -0
- package/dist/shared.js +16 -0
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -3,9 +3,13 @@
|
|
|
3
3
|
End-to-end device relay envelopes and workspace content keys. A browser, phone
|
|
4
4
|
or device seals a payload to the target device with HPKE and signs it with
|
|
5
5
|
Ed25519; the relay stores and forwards envelopes it cannot read. Pure WebCrypto,
|
|
6
|
-
`@hpke
|
|
6
|
+
`@hpke/core`, Zod and `@adea-ai/contracts`, so the same modules run in pi-host, the browser, the phone and
|
|
7
7
|
the relay worker, no transport, no credentials, no secrets.
|
|
8
8
|
|
|
9
|
+
The runtime must provide WebCrypto Ed25519 and X25519. HPKE uses the WebCrypto
|
|
10
|
+
X25519 KEM from `@hpke/core`; its sealed bytes are standard RFC 9180, so older
|
|
11
|
+
senders and receivers interoperate.
|
|
12
|
+
|
|
9
13
|
## Install
|
|
10
14
|
|
|
11
15
|
```sh
|
|
@@ -18,7 +22,8 @@ bun add @adea-ai/runtime-gateway-protocol
|
|
|
18
22
|
| ---------------- | ----------------------------------------------------------------------- |
|
|
19
23
|
| `./device-relay` | Authenticated relay envelopes, signed sender keyrings and replay checks |
|
|
20
24
|
| `./content-key` | Workspace content keys: derivation, sealing and signed key wraps |
|
|
21
|
-
|
|
|
25
|
+
| `./device-sync` | Encrypted cross-device sync objects and the signed append-only log |
|
|
26
|
+
| `.` | `./device-relay` and `./content-key` (not `./device-sync`) |
|
|
22
27
|
|
|
23
28
|
## Usage
|
|
24
29
|
|
|
@@ -27,6 +32,23 @@ import { sealAuthenticatedRelayCommand } from '@adea-ai/runtime-gateway-protocol
|
|
|
27
32
|
import { sealContent } from '@adea-ai/runtime-gateway-protocol/content-key'
|
|
28
33
|
```
|
|
29
34
|
|
|
35
|
+
## Relay intent window
|
|
36
|
+
|
|
37
|
+
An intent may live at most `MAX_RELAY_INTENT_LIFETIME_MS` (30 minutes) after the
|
|
38
|
+
signed `issuedAt` of the envelope that carries it, with a 5 minute clock skew.
|
|
39
|
+
`relayIntentWindow()` answers `live`, `expired` or `invalid`; a sender checks its
|
|
40
|
+
own intents with `skewMs: 0` before handing them to the relay. Receivers keep a
|
|
41
|
+
turn record and drop the prompt `RELAY_INTENT_COMPACT_AFTER_MS` (24 hours) after
|
|
42
|
+
expiry.
|
|
43
|
+
|
|
44
|
+
## Sync log checkpoints
|
|
45
|
+
|
|
46
|
+
The `./device-sync` log carries checkpoint entries (`SYNC_CHECKPOINT_ENTRY_VERSION` 2) that point at an encrypted snapshot split into at most 32 parts.
|
|
47
|
+
`encodeSyncSnapshot()`, `splitSyncSnapshot()` and `parseSyncSnapshot()` build and
|
|
48
|
+
read the snapshot, `assertSyncCheckpoint()` checks a checkpoint against the
|
|
49
|
+
entries it replaces, and `assertSyncLogContiguous()` rejects a page with gaps.
|
|
50
|
+
The server never sees snapshot plaintext.
|
|
51
|
+
|
|
30
52
|
## License
|
|
31
53
|
|
|
32
54
|
Apache-2.0
|
package/dist/content-key.js
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import { Aes128Gcm, CipherSuite, HkdfSha256 } from '@hpke/core';
|
|
2
|
-
import { DhkemX25519HkdfSha256 } from '@hpke/dhkem-x25519';
|
|
3
1
|
import { z } from 'zod';
|
|
4
2
|
import { canonicalJsonStringify } from '@adea-ai/contracts/canonical-json';
|
|
5
3
|
import { decodeBase64Url, encodeBase64Url, signRelayBytes, verifyRelayBytes, } from './device-relay.js';
|
|
6
4
|
import { SyncAuthorKeyIdSchema } from '@adea-ai/contracts/device-sync';
|
|
7
5
|
import { TimestampSchema } from '@adea-ai/contracts/primitives';
|
|
6
|
+
import { Base64UrlSchema, IdentifierSchema, hpkeSuite as wrapSuite } from './shared.js';
|
|
8
7
|
export const CONTENT_KEY_BYTES = 32;
|
|
9
8
|
export const CONTENT_SEAL_VERSION = 1;
|
|
10
9
|
export const CONTENT_KEY_WRAP_VERSION = 1;
|
|
@@ -13,11 +12,6 @@ const CONTENT_NONCE_BYTES = 12;
|
|
|
13
12
|
const AEAD_TAG_BYTES = 16;
|
|
14
13
|
const WRAP_INFO = new TextEncoder().encode('adea-content-key-wrap-v1');
|
|
15
14
|
const WRAP_SIGNATURE_CONTEXT = 'adea-content-key-wrap-signature-v1';
|
|
16
|
-
const wrapSuite = new CipherSuite({
|
|
17
|
-
kem: new DhkemX25519HkdfSha256(),
|
|
18
|
-
kdf: new HkdfSha256(),
|
|
19
|
-
aead: new Aes128Gcm(),
|
|
20
|
-
});
|
|
21
15
|
export const ContentKeyErrorCodeSchema = z.enum([
|
|
22
16
|
'CONTENT_SEAL_INVALID',
|
|
23
17
|
'CONTENT_TOO_LARGE',
|
|
@@ -34,16 +28,7 @@ export class ContentKeyError extends Error {
|
|
|
34
28
|
this.name = 'ContentKeyError';
|
|
35
29
|
}
|
|
36
30
|
}
|
|
37
|
-
const IdentifierSchema = z
|
|
38
|
-
.string()
|
|
39
|
-
.min(1)
|
|
40
|
-
.max(128)
|
|
41
|
-
.regex(/^[A-Za-z0-9._:-]+$/);
|
|
42
31
|
const VersionSchema = z.number().int().min(1);
|
|
43
|
-
const Base64UrlSchema = z
|
|
44
|
-
.string()
|
|
45
|
-
.min(1)
|
|
46
|
-
.regex(/^[A-Za-z0-9_-]+$/);
|
|
47
32
|
export const ContentSealSchema = z
|
|
48
33
|
.object({
|
|
49
34
|
ckv: VersionSchema,
|
|
@@ -113,9 +98,9 @@ export async function openContent(key, binding, sealed) {
|
|
|
113
98
|
try {
|
|
114
99
|
plaintext = await globalThis.crypto.subtle.decrypt({
|
|
115
100
|
name: 'AES-GCM',
|
|
116
|
-
iv:
|
|
101
|
+
iv: decodeBase64Url(parsed.data.nonce),
|
|
117
102
|
additionalData: contentAad(binding, key.ckv),
|
|
118
|
-
}, key.key,
|
|
103
|
+
}, key.key, decodeBase64Url(parsed.data.ciphertext));
|
|
119
104
|
}
|
|
120
105
|
catch {
|
|
121
106
|
throw new ContentKeyError('CONTENT_DECRYPTION_FAILED');
|
package/dist/device-relay.d.ts
CHANGED
|
@@ -5,6 +5,15 @@ export declare const MAX_RELAY_CLOCK_SKEW_MS: number;
|
|
|
5
5
|
export declare const AUTHENTICATED_RELAY_ENVELOPE_VERSION: 2;
|
|
6
6
|
export declare const MAX_AUTHENTICATED_RELAY_COMMAND_LIFETIME_MS: number;
|
|
7
7
|
export declare const MAX_AUTHENTICATED_RELAY_RESULT_LIFETIME_MS: number;
|
|
8
|
+
export declare const MAX_RELAY_INTENT_LIFETIME_MS: number;
|
|
9
|
+
export declare const RELAY_INTENT_COMPACT_AFTER_MS: number;
|
|
10
|
+
export declare function relayIntentWindow(input: {
|
|
11
|
+
readonly expiresAt: string;
|
|
12
|
+
readonly now: Date;
|
|
13
|
+
readonly issuedAt?: string;
|
|
14
|
+
readonly watermarkMs?: number;
|
|
15
|
+
readonly skewMs?: number;
|
|
16
|
+
}): 'live' | 'expired' | 'invalid';
|
|
8
17
|
export declare const AuthenticatedRelayCommandTypeSchema: z.ZodEnum<{
|
|
9
18
|
create_execution: "create_execution";
|
|
10
19
|
device_request: "device_request";
|
|
@@ -351,4 +360,4 @@ export declare function verifyRelayBytes(publicKey: string, signature: string, d
|
|
|
351
360
|
export declare function relayReplayOutcome(existing: readonly (RelayReplayReservation | undefined)[], reservation: RelayReplayReservation): 'first' | 'duplicate';
|
|
352
361
|
export declare function sha256(value: Uint8Array): Promise<`sha256:${string}`>;
|
|
353
362
|
export declare function encodeBase64Url(value: Uint8Array): string;
|
|
354
|
-
export declare function decodeBase64Url(value: string): Uint8Array
|
|
363
|
+
export declare function decodeBase64Url(value: string): Uint8Array<ArrayBuffer>;
|
package/dist/device-relay.js
CHANGED
|
@@ -1,20 +1,34 @@
|
|
|
1
|
-
import { Aes128Gcm, CipherSuite, HkdfSha256 } from '@hpke/core';
|
|
2
|
-
import { DhkemX25519HkdfSha256 } from '@hpke/dhkem-x25519';
|
|
3
1
|
import { z } from 'zod';
|
|
4
2
|
import { canonicalJsonStringify } from '@adea-ai/contracts/canonical-json';
|
|
5
3
|
import { SyncAuthorKeyIdSchema } from '@adea-ai/contracts/device-sync';
|
|
6
4
|
import { Sha256DigestSchema, TimestampSchema } from '@adea-ai/contracts/primitives';
|
|
5
|
+
import { Base64UrlSchema, IdentifierSchema, hpkeSuite as suite } from './shared.js';
|
|
7
6
|
export const RELAY_HPKE_SUITE = 'DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_AES_128_GCM';
|
|
8
7
|
export const MAX_RELAY_CIPHERTEXT_BYTES = 1024 * 1024;
|
|
9
8
|
export const MAX_RELAY_CLOCK_SKEW_MS = 5 * 60 * 1000;
|
|
10
9
|
export const AUTHENTICATED_RELAY_ENVELOPE_VERSION = 2;
|
|
11
10
|
export const MAX_AUTHENTICATED_RELAY_COMMAND_LIFETIME_MS = 15 * 60 * 1000;
|
|
12
11
|
export const MAX_AUTHENTICATED_RELAY_RESULT_LIFETIME_MS = 24 * 60 * 60 * 1000;
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
12
|
+
export const MAX_RELAY_INTENT_LIFETIME_MS = 30 * 60 * 1000;
|
|
13
|
+
export const RELAY_INTENT_COMPACT_AFTER_MS = 24 * 60 * 60 * 1000;
|
|
14
|
+
export function relayIntentWindow(input) {
|
|
15
|
+
const expires = Date.parse(input.expiresAt);
|
|
16
|
+
if (!Number.isFinite(expires))
|
|
17
|
+
return 'invalid';
|
|
18
|
+
const skew = input.skewMs ?? MAX_RELAY_CLOCK_SKEW_MS;
|
|
19
|
+
if (input.watermarkMs !== undefined && !(expires > input.watermarkMs))
|
|
20
|
+
return 'expired';
|
|
21
|
+
if (expires + skew <= input.now.getTime())
|
|
22
|
+
return 'expired';
|
|
23
|
+
if (expires > input.now.getTime() + MAX_RELAY_INTENT_LIFETIME_MS + skew)
|
|
24
|
+
return 'invalid';
|
|
25
|
+
if (input.issuedAt !== undefined) {
|
|
26
|
+
const issued = Date.parse(input.issuedAt);
|
|
27
|
+
if (!Number.isFinite(issued) || expires > issued + MAX_RELAY_INTENT_LIFETIME_MS + skew)
|
|
28
|
+
return 'invalid';
|
|
29
|
+
}
|
|
30
|
+
return 'live';
|
|
31
|
+
}
|
|
18
32
|
const HPKE_INFO = new TextEncoder().encode('adea-control-plane-relay-v2');
|
|
19
33
|
const SIGNATURE_CONTEXT = 'adea-control-plane-relay-signature-v2';
|
|
20
34
|
const KEYRING_SIGNATURE_CONTEXT = 'adea-control-plane-relay-keyring-v1';
|
|
@@ -22,20 +36,11 @@ const AEAD_TAG_BYTES = 16;
|
|
|
22
36
|
const NONCE_BYTES = 16;
|
|
23
37
|
const X25519_PKCS8_PREFIX = Uint8Array.of(0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20);
|
|
24
38
|
const ED25519_PKCS8_PREFIX = Uint8Array.of(0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20);
|
|
25
|
-
const IdentifierSchema = z
|
|
26
|
-
.string()
|
|
27
|
-
.min(1)
|
|
28
|
-
.max(128)
|
|
29
|
-
.regex(/^[A-Za-z0-9._:-]+$/);
|
|
30
39
|
const HostKeyIdSchema = z
|
|
31
40
|
.string()
|
|
32
41
|
.min(8)
|
|
33
42
|
.max(96)
|
|
34
43
|
.regex(/^(?:hpk|rpk)_[a-f0-9]+$/);
|
|
35
|
-
const Base64UrlSchema = z
|
|
36
|
-
.string()
|
|
37
|
-
.min(1)
|
|
38
|
-
.regex(/^[A-Za-z0-9_-]+$/);
|
|
39
44
|
const PublicKeySchema = Base64UrlSchema.length(43);
|
|
40
45
|
const NonceSchema = Base64UrlSchema.length(22);
|
|
41
46
|
const SignatureSchema = Base64UrlSchema.length(86);
|
|
@@ -140,6 +145,8 @@ export const AuthorizedSenderKeySchema = z
|
|
|
140
145
|
if ((value.encryptionKeyId === undefined) !== (value.encryptionPublicKey === undefined)) {
|
|
141
146
|
context.addIssue({ code: 'custom', message: 'encryption key id and key go together' });
|
|
142
147
|
}
|
|
148
|
+
}, {
|
|
149
|
+
id: 'runtime-gateway-protocol/device-relay:AuthorizedSenderKeySchema',
|
|
143
150
|
});
|
|
144
151
|
export const AuthorizedSenderKeyringBodySchema = z
|
|
145
152
|
.object({
|
|
@@ -305,7 +312,8 @@ export async function openAuthenticatedRelayCommand(input) {
|
|
|
305
312
|
const now = input.now ?? new Date();
|
|
306
313
|
validateLifetime(header, MAX_AUTHENTICATED_RELAY_COMMAND_LIFETIME_MS, now);
|
|
307
314
|
const sender = authorizedSender(input.keyring, header, now);
|
|
308
|
-
|
|
315
|
+
const sealed = decodeSealed(encapsulatedKey, ciphertext);
|
|
316
|
+
if (!(await verifyRelayBytes(sender.signingPublicKey, signature, await envelopeSigningInput(header, sealed)))) {
|
|
309
317
|
throw new AuthenticatedRelayError('RELAY_SIGNATURE_INVALID');
|
|
310
318
|
}
|
|
311
319
|
if (sender.scope === 'content')
|
|
@@ -317,7 +325,7 @@ export async function openAuthenticatedRelayCommand(input) {
|
|
|
317
325
|
envelopeDigest: await sha256(new TextEncoder().encode(signature)),
|
|
318
326
|
expiresAt: header.expiresAt,
|
|
319
327
|
}, now);
|
|
320
|
-
const plaintext = await openSealed(header,
|
|
328
|
+
const plaintext = await openSealed(header, sealed, input.recipient.privateKey);
|
|
321
329
|
return { header, sender, plaintext, delivery };
|
|
322
330
|
}
|
|
323
331
|
export async function sealAuthenticatedRelayResult(input) {
|
|
@@ -361,13 +369,11 @@ export async function openAuthenticatedRelayResult(input) {
|
|
|
361
369
|
if (sender.kind !== 'device' || sender.deviceId !== input.command.targetDeviceId) {
|
|
362
370
|
throw new AuthenticatedRelayError('RELAY_SENDER_UNAUTHENTICATED');
|
|
363
371
|
}
|
|
364
|
-
|
|
372
|
+
const sealed = decodeSealed(encapsulatedKey, ciphertext);
|
|
373
|
+
if (!(await verifyRelayBytes(sender.signingPublicKey, signature, await envelopeSigningInput(header, sealed)))) {
|
|
365
374
|
throw new AuthenticatedRelayError('RELAY_SIGNATURE_INVALID');
|
|
366
375
|
}
|
|
367
|
-
return {
|
|
368
|
-
header,
|
|
369
|
-
plaintext: await openSealed(header, encapsulatedKey, ciphertext, input.returnPrivateKey),
|
|
370
|
-
};
|
|
376
|
+
return { header, plaintext: await openSealed(header, sealed, input.returnPrivateKey) };
|
|
371
377
|
}
|
|
372
378
|
export async function attestAuthenticatedRelayResult(input) {
|
|
373
379
|
const parsed = AuthenticatedRelayResultEnvelopeSchema.safeParse(input.envelope);
|
|
@@ -383,7 +389,7 @@ export async function attestAuthenticatedRelayResult(input) {
|
|
|
383
389
|
if (sender.kind !== 'device' || sender.deviceId !== input.deviceId) {
|
|
384
390
|
throw new AuthenticatedRelayError('RELAY_SENDER_UNAUTHENTICATED');
|
|
385
391
|
}
|
|
386
|
-
if (!(await verifyRelayBytes(sender.signingPublicKey, signature, await envelopeSigningInput(header, encapsulatedKey, ciphertext)))) {
|
|
392
|
+
if (!(await verifyRelayBytes(sender.signingPublicKey, signature, await envelopeSigningInput(header, decodeSealed(encapsulatedKey, ciphertext))))) {
|
|
387
393
|
throw new AuthenticatedRelayError('RELAY_SIGNATURE_INVALID');
|
|
388
394
|
}
|
|
389
395
|
if ((await sha256(input.plaintext)) !== header.contentDigest) {
|
|
@@ -418,19 +424,25 @@ async function sealAndSign(header, recipientPublicKey, plaintext, signer) {
|
|
|
418
424
|
catch {
|
|
419
425
|
throw new AuthenticatedRelayError('RELAY_ENVELOPE_INVALID');
|
|
420
426
|
}
|
|
421
|
-
const
|
|
422
|
-
const
|
|
423
|
-
|
|
424
|
-
|
|
427
|
+
const raw = { enc: new Uint8Array(sealed.enc), ct: new Uint8Array(sealed.ct) };
|
|
428
|
+
const signature = await signRelayBytes(signer.privateKey, await envelopeSigningInput(header, raw));
|
|
429
|
+
return {
|
|
430
|
+
encapsulatedKey: encodeBase64Url(raw.enc),
|
|
431
|
+
ciphertext: encodeBase64Url(raw.ct),
|
|
432
|
+
signature,
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
function decodeSealed(encapsulatedKey, ciphertext) {
|
|
436
|
+
return { enc: decodeBase64Url(encapsulatedKey), ct: decodeBase64Url(ciphertext) };
|
|
425
437
|
}
|
|
426
|
-
async function openSealed(header,
|
|
438
|
+
async function openSealed(header, sealed, privateKey) {
|
|
427
439
|
let plaintext;
|
|
428
440
|
try {
|
|
429
441
|
plaintext = new Uint8Array(await suite.open({
|
|
430
442
|
recipientKey: await suite.kem.deserializePrivateKey(decodeBase64Url(privateKey)),
|
|
431
|
-
enc:
|
|
443
|
+
enc: sealed.enc,
|
|
432
444
|
info: HPKE_INFO,
|
|
433
|
-
},
|
|
445
|
+
}, sealed.ct, canonicalHeader(header)));
|
|
434
446
|
}
|
|
435
447
|
catch {
|
|
436
448
|
throw new AuthenticatedRelayError('RELAY_ENVELOPE_DECRYPTION_FAILED');
|
|
@@ -444,20 +456,20 @@ async function openSealed(header, encapsulatedKey, ciphertext, privateKey) {
|
|
|
444
456
|
function canonicalHeader(header) {
|
|
445
457
|
return new TextEncoder().encode(canonicalJsonStringify(header));
|
|
446
458
|
}
|
|
447
|
-
async function envelopeSigningInput(header,
|
|
448
|
-
const
|
|
449
|
-
return new TextEncoder().encode(`${SIGNATURE_CONTEXT}\n${canonicalJsonStringify(header)}\n${
|
|
459
|
+
async function envelopeSigningInput(header, sealed) {
|
|
460
|
+
const digest = await sha256(concat(sealed.enc, sealed.ct));
|
|
461
|
+
return new TextEncoder().encode(`${SIGNATURE_CONTEXT}\n${canonicalJsonStringify(header)}\n${digest}`);
|
|
450
462
|
}
|
|
451
463
|
function keyringSigningInput(body) {
|
|
452
464
|
return new TextEncoder().encode(`${KEYRING_SIGNATURE_CONTEXT}\n${canonicalJsonStringify(body)}`);
|
|
453
465
|
}
|
|
454
466
|
export async function signRelayBytes(privateKey, data) {
|
|
455
|
-
return encodeBase64Url(new Uint8Array(await globalThis.crypto.subtle.sign('Ed25519', privateKey,
|
|
467
|
+
return encodeBase64Url(new Uint8Array(await globalThis.crypto.subtle.sign('Ed25519', privateKey, ownBuffer(data))));
|
|
456
468
|
}
|
|
457
469
|
export async function verifyRelayBytes(publicKey, signature, data) {
|
|
458
470
|
try {
|
|
459
|
-
const key = await globalThis.crypto.subtle.importKey('raw',
|
|
460
|
-
return await globalThis.crypto.subtle.verify('Ed25519', key,
|
|
471
|
+
const key = await globalThis.crypto.subtle.importKey('raw', decodeBase64Url(publicKey), { name: 'Ed25519' }, false, ['verify']);
|
|
472
|
+
return await globalThis.crypto.subtle.verify('Ed25519', key, decodeBase64Url(signature), ownBuffer(data));
|
|
461
473
|
}
|
|
462
474
|
catch {
|
|
463
475
|
return false;
|
|
@@ -514,31 +526,100 @@ function concat(left, right) {
|
|
|
514
526
|
return joined;
|
|
515
527
|
}
|
|
516
528
|
export async function sha256(value) {
|
|
517
|
-
const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256',
|
|
529
|
+
const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', ownBuffer(value)));
|
|
518
530
|
return `sha256:${[...digest].map((byte) => byte.toString(16).padStart(2, '0')).join('')}`;
|
|
519
531
|
}
|
|
532
|
+
const BASE64URL_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
|
|
533
|
+
const BASE64URL_CODES = Uint8Array.from(BASE64URL_ALPHABET, (character) => character.charCodeAt(0));
|
|
534
|
+
const BASE64URL_VALUES = (() => {
|
|
535
|
+
const values = new Uint8Array(128).fill(255);
|
|
536
|
+
for (let index = 0; index < BASE64URL_CODES.length; index += 1) {
|
|
537
|
+
values[BASE64URL_CODES[index]] = index;
|
|
538
|
+
}
|
|
539
|
+
return values;
|
|
540
|
+
})();
|
|
541
|
+
const ascii = new TextDecoder('latin1');
|
|
542
|
+
const BASE64URL_TEXT = /^[A-Za-z0-9_-]*$/;
|
|
543
|
+
function ownBuffer(value) {
|
|
544
|
+
return value.buffer instanceof ArrayBuffer
|
|
545
|
+
? new Uint8Array(value.buffer, value.byteOffset, value.byteLength)
|
|
546
|
+
: Uint8Array.from(value);
|
|
547
|
+
}
|
|
548
|
+
const nativeToBase64 = nativeFunction(Uint8Array.prototype, 'toBase64');
|
|
549
|
+
const nativeFromBase64 = nativeFunction(Uint8Array, 'fromBase64');
|
|
550
|
+
function nativeFunction(target, name) {
|
|
551
|
+
const value = Reflect.get(target, name);
|
|
552
|
+
return typeof value === 'function' ? value : undefined;
|
|
553
|
+
}
|
|
520
554
|
export function encodeBase64Url(value) {
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
555
|
+
if (nativeToBase64 !== undefined) {
|
|
556
|
+
return nativeToBase64.call(value, { alphabet: 'base64url', omitPadding: true });
|
|
557
|
+
}
|
|
558
|
+
const length = value.byteLength;
|
|
559
|
+
const out = new Uint8Array(Math.ceil((length * 4) / 3));
|
|
560
|
+
let at = 0;
|
|
561
|
+
let index = 0;
|
|
562
|
+
for (; index + 2 < length; index += 3) {
|
|
563
|
+
const bits = (value[index] << 16) | (value[index + 1] << 8) | value[index + 2];
|
|
564
|
+
out[at++] = BASE64URL_CODES[bits >>> 18];
|
|
565
|
+
out[at++] = BASE64URL_CODES[(bits >>> 12) & 63];
|
|
566
|
+
out[at++] = BASE64URL_CODES[(bits >>> 6) & 63];
|
|
567
|
+
out[at++] = BASE64URL_CODES[bits & 63];
|
|
568
|
+
}
|
|
569
|
+
if (index < length) {
|
|
570
|
+
const bits = (value[index] << 16) | ((value[index + 1] ?? 0) << 8);
|
|
571
|
+
out[at++] = BASE64URL_CODES[bits >>> 18];
|
|
572
|
+
out[at++] = BASE64URL_CODES[(bits >>> 12) & 63];
|
|
573
|
+
if (index + 1 < length)
|
|
574
|
+
out[at++] = BASE64URL_CODES[(bits >>> 6) & 63];
|
|
575
|
+
}
|
|
576
|
+
return ascii.decode(out);
|
|
526
577
|
}
|
|
527
578
|
export function decodeBase64Url(value) {
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
const padded = `${value.replaceAll('-', '+').replaceAll('_', '/')}${'='.repeat((4 - (value.length % 4)) % 4)}`;
|
|
532
|
-
let binary;
|
|
533
|
-
try {
|
|
534
|
-
binary = globalThis.atob(padded);
|
|
535
|
-
}
|
|
536
|
-
catch {
|
|
537
|
-
throw new AuthenticatedRelayError('RELAY_ENVELOPE_INVALID');
|
|
538
|
-
}
|
|
539
|
-
const decoded = Uint8Array.from(binary, (character) => character.charCodeAt(0));
|
|
540
|
-
if (encodeBase64Url(decoded) !== value) {
|
|
579
|
+
const length = value.length;
|
|
580
|
+
const tail = length % 4;
|
|
581
|
+
if (tail === 1)
|
|
541
582
|
throw new AuthenticatedRelayError('RELAY_ENVELOPE_INVALID');
|
|
583
|
+
if (nativeFromBase64 !== undefined) {
|
|
584
|
+
if (!BASE64URL_TEXT.test(value))
|
|
585
|
+
throw new AuthenticatedRelayError('RELAY_ENVELOPE_INVALID');
|
|
586
|
+
try {
|
|
587
|
+
return nativeFromBase64(value + '=='.slice(0, (4 - tail) % 4), {
|
|
588
|
+
alphabet: 'base64url',
|
|
589
|
+
lastChunkHandling: 'strict',
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
catch {
|
|
593
|
+
throw new AuthenticatedRelayError('RELAY_ENVELOPE_INVALID');
|
|
594
|
+
}
|
|
542
595
|
}
|
|
543
|
-
|
|
596
|
+
const out = new Uint8Array(Math.floor((length * 3) / 4));
|
|
597
|
+
const sextet = (offset) => {
|
|
598
|
+
const code = value.charCodeAt(offset);
|
|
599
|
+
const bits = code < 128 ? BASE64URL_VALUES[code] : 255;
|
|
600
|
+
if (bits === 255)
|
|
601
|
+
throw new AuthenticatedRelayError('RELAY_ENVELOPE_INVALID');
|
|
602
|
+
return bits;
|
|
603
|
+
};
|
|
604
|
+
let at = 0;
|
|
605
|
+
let index = 0;
|
|
606
|
+
for (const whole = length - tail; index < whole; index += 4) {
|
|
607
|
+
const bits = (sextet(index) << 18) |
|
|
608
|
+
(sextet(index + 1) << 12) |
|
|
609
|
+
(sextet(index + 2) << 6) |
|
|
610
|
+
sextet(index + 3);
|
|
611
|
+
out[at++] = bits >>> 16;
|
|
612
|
+
out[at++] = (bits >>> 8) & 255;
|
|
613
|
+
out[at++] = bits & 255;
|
|
614
|
+
}
|
|
615
|
+
if (tail !== 0) {
|
|
616
|
+
const last = tail === 2 ? sextet(index + 1) : sextet(index + 2);
|
|
617
|
+
if ((last & (tail === 2 ? 15 : 3)) !== 0)
|
|
618
|
+
throw new AuthenticatedRelayError('RELAY_ENVELOPE_INVALID');
|
|
619
|
+
const bits = (sextet(index) << 18) | (sextet(index + 1) << 12) | (tail === 3 ? last << 6 : 0);
|
|
620
|
+
out[at++] = bits >>> 16;
|
|
621
|
+
if (tail === 3)
|
|
622
|
+
out[at++] = (bits >>> 8) & 255;
|
|
623
|
+
}
|
|
624
|
+
return out;
|
|
544
625
|
}
|
package/dist/device-sync.d.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { type DeviceSyncErrorCode, type SignedSyncEntry } from '@adea-ai/contracts/device-sync';
|
|
2
|
+
import { type DeviceSyncErrorCode, type SignedSyncEntry, type SyncRegisteredCheckpoint } from '@adea-ai/contracts/device-sync';
|
|
3
3
|
import { ContentSealSchema, type ContentKey } from './content-key.js';
|
|
4
4
|
import { type AuthorizedSenderKey, type AuthorizedSenderKeyring, type RelaySigningKeyPair } from './device-relay.js';
|
|
5
|
-
export { DeviceSyncErrorCodeSchema, MAX_SYNC_BATCH, MAX_SYNC_CIPHERTEXT_BYTES, MAX_SYNC_ENTRY_BYTES, MAX_SYNC_LOG_PAGE, MIN_SYNC_CIPHERTEXT_BYTES, SignedSyncEntrySchema, StoredSyncEntrySchema, SyncAppendRequestSchema, SyncAppendResponseSchema, SyncCommitResponseSchema, SyncDownloadRequestSchema, SyncDownloadResponseSchema, SyncEntryIdSchema, SyncLogPageSchema, SyncLogRequestSchema, SyncObjectIdSchema, SyncObjectRequestSchema, SyncReleaseResponseSchema, SyncUploadRequestSchema, SyncUploadResponseSchema, SyncUsageSchema, type DeviceSyncErrorCode, type SignedSyncEntry, type StoredSyncEntry, } from '@adea-ai/contracts/device-sync';
|
|
5
|
+
export { DeviceSyncErrorCodeSchema, MAX_SYNC_BATCH, MAX_SYNC_CIPHERTEXT_BYTES, MAX_SYNC_ENTRY_BYTES, MAX_SYNC_LOG_PAGE, MAX_SYNC_SNAPSHOT_PARTS, MIN_SYNC_CIPHERTEXT_BYTES, SignedSyncEntrySchema, StoredSyncEntrySchema, SyncAckRequestSchema, SyncAckResponseSchema, SyncAppendRequestSchema, SyncAppendResponseSchema, SyncCheckpointRegisterRequestSchema, SyncCheckpointRegisterResponseSchema, SyncCheckpointRequestSchema, SyncCheckpointResponseSchema, SyncCommitResponseSchema, SyncDownloadRequestSchema, SyncDownloadResponseSchema, SyncEntryIdSchema, SyncLogPageSchema, SyncLogRequestSchema, SyncObjectIdSchema, SyncObjectRequestSchema, SyncRegisteredCheckpointSchema, SyncReleaseResponseSchema, SyncUploadRequestSchema, SyncUploadResponseSchema, SyncUsageSchema, type DeviceSyncErrorCode, type SignedSyncEntry, type StoredSyncEntry, type SyncRegisteredCheckpoint, } from '@adea-ai/contracts/device-sync';
|
|
6
6
|
export declare const SYNC_BLOB_VERSION: 1;
|
|
7
7
|
export declare const SYNC_ENTRY_VERSION: 1;
|
|
8
|
+
export declare const SYNC_CHECKPOINT_ENTRY_VERSION: 2;
|
|
8
9
|
export declare const SYNC_CHUNK_BYTES: number;
|
|
9
10
|
export declare const MAX_SYNC_OBJECT_BYTES: number;
|
|
10
11
|
export declare const SYNC_REQUEST_HEADER = "adea-sync-signature";
|
|
@@ -182,10 +183,244 @@ export declare const SyncEntrySchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
182
183
|
}, z.core.$strict>], "kind">;
|
|
183
184
|
export type SyncEntry = z.infer<typeof SyncEntrySchema>;
|
|
184
185
|
export type SyncPutEntry = z.infer<typeof SyncPutEntrySchema>;
|
|
186
|
+
export declare const SyncSnapshotPartSchema: z.ZodObject<{
|
|
187
|
+
objectId: z.ZodString;
|
|
188
|
+
dataKey: z.ZodObject<{
|
|
189
|
+
ckv: z.ZodNumber;
|
|
190
|
+
nonce: z.ZodString;
|
|
191
|
+
ciphertext: z.ZodString;
|
|
192
|
+
}, z.core.$strict>;
|
|
193
|
+
plaintextSha256: z.ZodString;
|
|
194
|
+
size: z.ZodNumber;
|
|
195
|
+
}, z.core.$strict>;
|
|
196
|
+
export declare const SyncCheckpointEntrySchema: z.ZodObject<{
|
|
197
|
+
entryVersion: z.ZodLiteral<2>;
|
|
198
|
+
entryId: z.ZodString;
|
|
199
|
+
kind: z.ZodLiteral<"checkpoint">;
|
|
200
|
+
namespace: z.ZodLiteral<"files">;
|
|
201
|
+
itemId: z.ZodString;
|
|
202
|
+
hlc: z.ZodObject<{
|
|
203
|
+
wallMs: z.ZodNumber;
|
|
204
|
+
counter: z.ZodNumber;
|
|
205
|
+
node: z.ZodString;
|
|
206
|
+
}, z.core.$strict>;
|
|
207
|
+
throughSeq: z.ZodNumber;
|
|
208
|
+
prev: z.ZodNullable<z.ZodObject<{
|
|
209
|
+
entryId: z.ZodString;
|
|
210
|
+
throughSeq: z.ZodNumber;
|
|
211
|
+
}, z.core.$strict>>;
|
|
212
|
+
snapshot: z.ZodObject<{
|
|
213
|
+
plaintextSha256: z.ZodString;
|
|
214
|
+
size: z.ZodNumber;
|
|
215
|
+
parts: z.ZodArray<z.ZodObject<{
|
|
216
|
+
objectId: z.ZodString;
|
|
217
|
+
dataKey: z.ZodObject<{
|
|
218
|
+
ckv: z.ZodNumber;
|
|
219
|
+
nonce: z.ZodString;
|
|
220
|
+
ciphertext: z.ZodString;
|
|
221
|
+
}, z.core.$strict>;
|
|
222
|
+
plaintextSha256: z.ZodString;
|
|
223
|
+
size: z.ZodNumber;
|
|
224
|
+
}, z.core.$strict>>;
|
|
225
|
+
}, z.core.$strict>;
|
|
226
|
+
itemCount: z.ZodNumber;
|
|
227
|
+
headCount: z.ZodNumber;
|
|
228
|
+
tombstonesSince: z.ZodISODateTime;
|
|
229
|
+
}, z.core.$strict>;
|
|
230
|
+
export type SyncCheckpointEntry = z.infer<typeof SyncCheckpointEntrySchema>;
|
|
231
|
+
export declare const SyncLogEntrySchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
232
|
+
entryVersion: z.ZodLiteral<1>;
|
|
233
|
+
entryId: z.ZodString;
|
|
234
|
+
namespace: z.ZodEnum<{
|
|
235
|
+
artifacts: "artifacts";
|
|
236
|
+
files: "files";
|
|
237
|
+
sessions: "sessions";
|
|
238
|
+
}>;
|
|
239
|
+
itemId: z.ZodString;
|
|
240
|
+
hlc: z.ZodObject<{
|
|
241
|
+
wallMs: z.ZodNumber;
|
|
242
|
+
counter: z.ZodNumber;
|
|
243
|
+
node: z.ZodString;
|
|
244
|
+
}, z.core.$strict>;
|
|
245
|
+
kind: z.ZodLiteral<"put">;
|
|
246
|
+
path: z.ZodString;
|
|
247
|
+
objectId: z.ZodString;
|
|
248
|
+
dataKey: z.ZodObject<{
|
|
249
|
+
ckv: z.ZodNumber;
|
|
250
|
+
nonce: z.ZodString;
|
|
251
|
+
ciphertext: z.ZodString;
|
|
252
|
+
}, z.core.$strict>;
|
|
253
|
+
plaintextSha256: z.ZodString;
|
|
254
|
+
size: z.ZodNumber;
|
|
255
|
+
contentType: z.ZodOptional<z.ZodString>;
|
|
256
|
+
mtimeMs: z.ZodOptional<z.ZodNumber>;
|
|
257
|
+
parents: z.ZodArray<z.ZodString>;
|
|
258
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
259
|
+
entryVersion: z.ZodLiteral<1>;
|
|
260
|
+
entryId: z.ZodString;
|
|
261
|
+
namespace: z.ZodEnum<{
|
|
262
|
+
artifacts: "artifacts";
|
|
263
|
+
files: "files";
|
|
264
|
+
sessions: "sessions";
|
|
265
|
+
}>;
|
|
266
|
+
itemId: z.ZodString;
|
|
267
|
+
hlc: z.ZodObject<{
|
|
268
|
+
wallMs: z.ZodNumber;
|
|
269
|
+
counter: z.ZodNumber;
|
|
270
|
+
node: z.ZodString;
|
|
271
|
+
}, z.core.$strict>;
|
|
272
|
+
kind: z.ZodLiteral<"delete">;
|
|
273
|
+
parents: z.ZodArray<z.ZodString>;
|
|
274
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
275
|
+
entryVersion: z.ZodLiteral<1>;
|
|
276
|
+
entryId: z.ZodString;
|
|
277
|
+
namespace: z.ZodEnum<{
|
|
278
|
+
artifacts: "artifacts";
|
|
279
|
+
files: "files";
|
|
280
|
+
sessions: "sessions";
|
|
281
|
+
}>;
|
|
282
|
+
itemId: z.ZodString;
|
|
283
|
+
hlc: z.ZodObject<{
|
|
284
|
+
wallMs: z.ZodNumber;
|
|
285
|
+
counter: z.ZodNumber;
|
|
286
|
+
node: z.ZodString;
|
|
287
|
+
}, z.core.$strict>;
|
|
288
|
+
kind: z.ZodLiteral<"rewrap">;
|
|
289
|
+
objectId: z.ZodString;
|
|
290
|
+
dataKey: z.ZodObject<{
|
|
291
|
+
ckv: z.ZodNumber;
|
|
292
|
+
nonce: z.ZodString;
|
|
293
|
+
ciphertext: z.ZodString;
|
|
294
|
+
}, z.core.$strict>;
|
|
295
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
296
|
+
entryVersion: z.ZodLiteral<2>;
|
|
297
|
+
entryId: z.ZodString;
|
|
298
|
+
kind: z.ZodLiteral<"checkpoint">;
|
|
299
|
+
namespace: z.ZodLiteral<"files">;
|
|
300
|
+
itemId: z.ZodString;
|
|
301
|
+
hlc: z.ZodObject<{
|
|
302
|
+
wallMs: z.ZodNumber;
|
|
303
|
+
counter: z.ZodNumber;
|
|
304
|
+
node: z.ZodString;
|
|
305
|
+
}, z.core.$strict>;
|
|
306
|
+
throughSeq: z.ZodNumber;
|
|
307
|
+
prev: z.ZodNullable<z.ZodObject<{
|
|
308
|
+
entryId: z.ZodString;
|
|
309
|
+
throughSeq: z.ZodNumber;
|
|
310
|
+
}, z.core.$strict>>;
|
|
311
|
+
snapshot: z.ZodObject<{
|
|
312
|
+
plaintextSha256: z.ZodString;
|
|
313
|
+
size: z.ZodNumber;
|
|
314
|
+
parts: z.ZodArray<z.ZodObject<{
|
|
315
|
+
objectId: z.ZodString;
|
|
316
|
+
dataKey: z.ZodObject<{
|
|
317
|
+
ckv: z.ZodNumber;
|
|
318
|
+
nonce: z.ZodString;
|
|
319
|
+
ciphertext: z.ZodString;
|
|
320
|
+
}, z.core.$strict>;
|
|
321
|
+
plaintextSha256: z.ZodString;
|
|
322
|
+
size: z.ZodNumber;
|
|
323
|
+
}, z.core.$strict>>;
|
|
324
|
+
}, z.core.$strict>;
|
|
325
|
+
itemCount: z.ZodNumber;
|
|
326
|
+
headCount: z.ZodNumber;
|
|
327
|
+
tombstonesSince: z.ZodISODateTime;
|
|
328
|
+
}, z.core.$strict>], "kind">;
|
|
329
|
+
export type SyncLogEntry = z.infer<typeof SyncLogEntrySchema>;
|
|
330
|
+
export declare const SyncSnapshotHeadSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
331
|
+
seq: z.ZodNumber;
|
|
332
|
+
entryId: z.ZodString;
|
|
333
|
+
authorKeyId: z.ZodString;
|
|
334
|
+
hlc: z.ZodObject<{
|
|
335
|
+
wallMs: z.ZodNumber;
|
|
336
|
+
counter: z.ZodNumber;
|
|
337
|
+
node: z.ZodString;
|
|
338
|
+
}, z.core.$strict>;
|
|
339
|
+
kind: z.ZodLiteral<"put">;
|
|
340
|
+
parents: z.ZodArray<z.ZodString>;
|
|
341
|
+
path: z.ZodString;
|
|
342
|
+
objectId: z.ZodString;
|
|
343
|
+
dataKey: z.ZodObject<{
|
|
344
|
+
ckv: z.ZodNumber;
|
|
345
|
+
nonce: z.ZodString;
|
|
346
|
+
ciphertext: z.ZodString;
|
|
347
|
+
}, z.core.$strict>;
|
|
348
|
+
plaintextSha256: z.ZodString;
|
|
349
|
+
size: z.ZodNumber;
|
|
350
|
+
contentType: z.ZodOptional<z.ZodString>;
|
|
351
|
+
mtimeMs: z.ZodOptional<z.ZodNumber>;
|
|
352
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
353
|
+
seq: z.ZodNumber;
|
|
354
|
+
entryId: z.ZodString;
|
|
355
|
+
authorKeyId: z.ZodString;
|
|
356
|
+
hlc: z.ZodObject<{
|
|
357
|
+
wallMs: z.ZodNumber;
|
|
358
|
+
counter: z.ZodNumber;
|
|
359
|
+
node: z.ZodString;
|
|
360
|
+
}, z.core.$strict>;
|
|
361
|
+
kind: z.ZodLiteral<"delete">;
|
|
362
|
+
parents: z.ZodArray<z.ZodString>;
|
|
363
|
+
}, z.core.$strict>], "kind">;
|
|
364
|
+
export type SyncSnapshotHead = z.infer<typeof SyncSnapshotHeadSchema>;
|
|
365
|
+
export declare const SYNC_SNAPSHOT_FORMAT: 'adea.sync-snapshot';
|
|
366
|
+
export declare const SyncSnapshotSchema: z.ZodObject<{
|
|
367
|
+
format: z.ZodLiteral<"adea.sync-snapshot">;
|
|
368
|
+
version: z.ZodLiteral<1>;
|
|
369
|
+
workspaceId: z.ZodString;
|
|
370
|
+
checkpointEntryId: z.ZodString;
|
|
371
|
+
throughSeq: z.ZodNumber;
|
|
372
|
+
prev: z.ZodNullable<z.ZodObject<{
|
|
373
|
+
entryId: z.ZodString;
|
|
374
|
+
throughSeq: z.ZodNumber;
|
|
375
|
+
}, z.core.$strict>>;
|
|
376
|
+
items: z.ZodArray<z.ZodObject<{
|
|
377
|
+
itemId: z.ZodString;
|
|
378
|
+
namespace: z.ZodEnum<{
|
|
379
|
+
artifacts: "artifacts";
|
|
380
|
+
files: "files";
|
|
381
|
+
sessions: "sessions";
|
|
382
|
+
}>;
|
|
383
|
+
heads: z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
384
|
+
seq: z.ZodNumber;
|
|
385
|
+
entryId: z.ZodString;
|
|
386
|
+
authorKeyId: z.ZodString;
|
|
387
|
+
hlc: z.ZodObject<{
|
|
388
|
+
wallMs: z.ZodNumber;
|
|
389
|
+
counter: z.ZodNumber;
|
|
390
|
+
node: z.ZodString;
|
|
391
|
+
}, z.core.$strict>;
|
|
392
|
+
kind: z.ZodLiteral<"put">;
|
|
393
|
+
parents: z.ZodArray<z.ZodString>;
|
|
394
|
+
path: z.ZodString;
|
|
395
|
+
objectId: z.ZodString;
|
|
396
|
+
dataKey: z.ZodObject<{
|
|
397
|
+
ckv: z.ZodNumber;
|
|
398
|
+
nonce: z.ZodString;
|
|
399
|
+
ciphertext: z.ZodString;
|
|
400
|
+
}, z.core.$strict>;
|
|
401
|
+
plaintextSha256: z.ZodString;
|
|
402
|
+
size: z.ZodNumber;
|
|
403
|
+
contentType: z.ZodOptional<z.ZodString>;
|
|
404
|
+
mtimeMs: z.ZodOptional<z.ZodNumber>;
|
|
405
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
406
|
+
seq: z.ZodNumber;
|
|
407
|
+
entryId: z.ZodString;
|
|
408
|
+
authorKeyId: z.ZodString;
|
|
409
|
+
hlc: z.ZodObject<{
|
|
410
|
+
wallMs: z.ZodNumber;
|
|
411
|
+
counter: z.ZodNumber;
|
|
412
|
+
node: z.ZodString;
|
|
413
|
+
}, z.core.$strict>;
|
|
414
|
+
kind: z.ZodLiteral<"delete">;
|
|
415
|
+
parents: z.ZodArray<z.ZodString>;
|
|
416
|
+
}, z.core.$strict>], "kind">>;
|
|
417
|
+
}, z.core.$strict>>;
|
|
418
|
+
}, z.core.$strict>;
|
|
419
|
+
export type SyncSnapshot = z.infer<typeof SyncSnapshotSchema>;
|
|
185
420
|
export declare function sealSyncEntry(input: {
|
|
186
421
|
readonly contentKey: ContentKey;
|
|
187
422
|
readonly workspaceId: string;
|
|
188
|
-
readonly entry:
|
|
423
|
+
readonly entry: SyncLogEntry;
|
|
189
424
|
readonly author: RelaySigningKeyPair;
|
|
190
425
|
}): Promise<SignedSyncEntry>;
|
|
191
426
|
export declare function syncAuthor(keyring: AuthorizedSenderKeyring, workspaceId: string, keyId: string, at: number): AuthorizedSenderKey;
|
|
@@ -197,9 +432,41 @@ export declare function openSyncEntry(input: {
|
|
|
197
432
|
}): Promise<SyncEntry & {
|
|
198
433
|
readonly authorKeyId: string;
|
|
199
434
|
}>;
|
|
435
|
+
export declare function openSyncLogEntry(input: {
|
|
436
|
+
readonly workspaceId: string;
|
|
437
|
+
readonly keyring: AuthorizedSenderKeyring;
|
|
438
|
+
readonly entry: unknown;
|
|
439
|
+
readonly contentKey: (ckv: number) => Promise<ContentKey | undefined> | ContentKey | undefined;
|
|
440
|
+
}): Promise<SyncLogEntry & {
|
|
441
|
+
readonly authorKeyId: string;
|
|
442
|
+
}>;
|
|
200
443
|
export declare function assertSyncLogAdvances(lastSeenSeq: number, page: readonly {
|
|
201
444
|
seq: number;
|
|
202
445
|
}[]): void;
|
|
446
|
+
export declare function assertSyncLogContiguous(cursor: number, page: readonly {
|
|
447
|
+
seq: number;
|
|
448
|
+
}[], headSeq?: number): void;
|
|
449
|
+
export declare function assertSyncCheckpoint(input: {
|
|
450
|
+
readonly keyring: AuthorizedSenderKeyring;
|
|
451
|
+
readonly entry: SyncCheckpointEntry & {
|
|
452
|
+
readonly authorKeyId: string;
|
|
453
|
+
};
|
|
454
|
+
readonly registered: Pick<SyncRegisteredCheckpoint, 'seq' | 'entryId' | 'throughSeq' | 'prevEntryId' | 'partObjectIds'>;
|
|
455
|
+
readonly floorSeq: number;
|
|
456
|
+
readonly cursor: number;
|
|
457
|
+
}): void;
|
|
458
|
+
export declare function encodeSyncSnapshot(snapshot: SyncSnapshot): Uint8Array;
|
|
459
|
+
export declare function splitSyncSnapshot(bytes: Uint8Array): Uint8Array[];
|
|
460
|
+
export declare function parseSyncSnapshot(input: {
|
|
461
|
+
readonly workspaceId: string;
|
|
462
|
+
readonly checkpoint: SyncCheckpointEntry;
|
|
463
|
+
readonly parts: readonly Uint8Array[];
|
|
464
|
+
}): Promise<{
|
|
465
|
+
readonly snapshot: SyncSnapshot;
|
|
466
|
+
readonly heads: (SyncEntry & {
|
|
467
|
+
readonly authorKeyId: string;
|
|
468
|
+
})[];
|
|
469
|
+
}>;
|
|
203
470
|
export interface SyncItemVersion {
|
|
204
471
|
readonly entryId: string;
|
|
205
472
|
readonly path: string;
|
|
@@ -222,7 +489,9 @@ export interface SyncItemState {
|
|
|
222
489
|
type OpenedEntry = SyncEntry & {
|
|
223
490
|
readonly authorKeyId: string;
|
|
224
491
|
};
|
|
225
|
-
export declare function foldSyncItems(entries: Iterable<OpenedEntry
|
|
492
|
+
export declare function foldSyncItems(entries: Iterable<OpenedEntry>, options?: {
|
|
493
|
+
readonly primarySigningKeyId?: string;
|
|
494
|
+
}): Map<string, SyncItemState>;
|
|
226
495
|
export declare function signSyncRequest(input: {
|
|
227
496
|
readonly key: RelaySigningKeyPair;
|
|
228
497
|
readonly method: string;
|
package/dist/device-sync.js
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { canonicalJsonStringify } from '@adea-ai/contracts/canonical-json';
|
|
3
|
-
import { MAX_SYNC_ENTRY_BYTES, SignedSyncEntrySchema, SyncObjectIdSchema, SyncEntryIdSchema, } from '@adea-ai/contracts/device-sync';
|
|
3
|
+
import { MAX_SYNC_ENTRY_BYTES, MAX_SYNC_SNAPSHOT_PARTS, SignedSyncEntrySchema, SyncObjectIdSchema, SyncEntryIdSchema, } from '@adea-ai/contracts/device-sync';
|
|
4
4
|
import { ContentKeyError, ContentSealSchema, openContent, sealContent, } from './content-key.js';
|
|
5
5
|
import { MAX_RELAY_CLOCK_SKEW_MS, decodeBase64Url, encodeBase64Url, sha256, signRelayBytes, verifyRelayBytes, } from './device-relay.js';
|
|
6
6
|
import { SyncAuthorKeyIdSchema } from '@adea-ai/contracts/device-sync';
|
|
7
7
|
import { Sha256DigestSchema, TimestampSchema } from '@adea-ai/contracts/primitives';
|
|
8
|
-
|
|
8
|
+
import { IdentifierSchema } from './shared.js';
|
|
9
|
+
export { DeviceSyncErrorCodeSchema, MAX_SYNC_BATCH, MAX_SYNC_CIPHERTEXT_BYTES, MAX_SYNC_ENTRY_BYTES, MAX_SYNC_LOG_PAGE, MAX_SYNC_SNAPSHOT_PARTS, MIN_SYNC_CIPHERTEXT_BYTES, SignedSyncEntrySchema, StoredSyncEntrySchema, SyncAckRequestSchema, SyncAckResponseSchema, SyncAppendRequestSchema, SyncAppendResponseSchema, SyncCheckpointRegisterRequestSchema, SyncCheckpointRegisterResponseSchema, SyncCheckpointRequestSchema, SyncCheckpointResponseSchema, SyncCommitResponseSchema, SyncDownloadRequestSchema, SyncDownloadResponseSchema, SyncEntryIdSchema, SyncLogPageSchema, SyncLogRequestSchema, SyncObjectIdSchema, SyncObjectRequestSchema, SyncRegisteredCheckpointSchema, SyncReleaseResponseSchema, SyncUploadRequestSchema, SyncUploadResponseSchema, SyncUsageSchema, } from '@adea-ai/contracts/device-sync';
|
|
9
10
|
export const SYNC_BLOB_VERSION = 1;
|
|
10
11
|
export const SYNC_ENTRY_VERSION = 1;
|
|
12
|
+
export const SYNC_CHECKPOINT_ENTRY_VERSION = 2;
|
|
11
13
|
export const SYNC_CHUNK_BYTES = 1024 * 1024;
|
|
12
14
|
export const MAX_SYNC_OBJECT_BYTES = 256 * 1024 * 1024;
|
|
13
15
|
export const SYNC_REQUEST_HEADER = 'adea-sync-signature';
|
|
@@ -29,11 +31,6 @@ export class DeviceSyncError extends Error {
|
|
|
29
31
|
this.name = 'DeviceSyncError';
|
|
30
32
|
}
|
|
31
33
|
}
|
|
32
|
-
const IdentifierSchema = z
|
|
33
|
-
.string()
|
|
34
|
-
.min(1)
|
|
35
|
-
.max(128)
|
|
36
|
-
.regex(/^[A-Za-z0-9._:-]+$/);
|
|
37
34
|
export const SyncItemIdSchema = z.string().regex(/^sit_[a-f0-9]{32}$/);
|
|
38
35
|
function randomId(prefix) {
|
|
39
36
|
const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));
|
|
@@ -71,11 +68,11 @@ async function importDataKey(raw) {
|
|
|
71
68
|
'decrypt',
|
|
72
69
|
]);
|
|
73
70
|
}
|
|
71
|
+
const SyncBlobBindingSchema = z
|
|
72
|
+
.object({ workspaceId: IdentifierSchema, objectId: SyncObjectIdSchema })
|
|
73
|
+
.strict();
|
|
74
74
|
function parseBinding(binding) {
|
|
75
|
-
const parsed =
|
|
76
|
-
.object({ workspaceId: IdentifierSchema, objectId: SyncObjectIdSchema })
|
|
77
|
-
.strict()
|
|
78
|
-
.safeParse(binding);
|
|
75
|
+
const parsed = SyncBlobBindingSchema.safeParse(binding);
|
|
79
76
|
if (!parsed.success)
|
|
80
77
|
throw new DeviceSyncError('SYNC_BLOB_INVALID');
|
|
81
78
|
return parsed.data;
|
|
@@ -161,7 +158,8 @@ export async function* sealSyncBlobStream(dataKey, binding, plaintextBytes, sour
|
|
|
161
158
|
header[4] = SYNC_BLOB_VERSION;
|
|
162
159
|
new DataView(header.buffer).setUint32(8, count);
|
|
163
160
|
yield header;
|
|
164
|
-
const
|
|
161
|
+
const chunkBytes = Math.min(SYNC_CHUNK_BYTES, padded);
|
|
162
|
+
const buffer = new Uint8Array(chunkBytes);
|
|
165
163
|
let filled = 0;
|
|
166
164
|
let index = 0;
|
|
167
165
|
async function seal() {
|
|
@@ -173,11 +171,11 @@ export async function* sealSyncBlobStream(dataKey, binding, plaintextBytes, sour
|
|
|
173
171
|
async function* push(bytes) {
|
|
174
172
|
let offset = 0;
|
|
175
173
|
while (offset < bytes.byteLength) {
|
|
176
|
-
const take = Math.min(bytes.byteLength - offset,
|
|
174
|
+
const take = Math.min(bytes.byteLength - offset, chunkBytes - filled);
|
|
177
175
|
buffer.set(bytes.subarray(offset, offset + take), filled);
|
|
178
176
|
filled += take;
|
|
179
177
|
offset += take;
|
|
180
|
-
if (filled ===
|
|
178
|
+
if (filled === chunkBytes)
|
|
181
179
|
yield await seal();
|
|
182
180
|
}
|
|
183
181
|
}
|
|
@@ -194,9 +192,10 @@ export async function* sealSyncBlobStream(dataKey, binding, plaintextBytes, sour
|
|
|
194
192
|
}
|
|
195
193
|
if (received !== plaintextBytes)
|
|
196
194
|
throw new DeviceSyncError('SYNC_BLOB_INVALID');
|
|
197
|
-
const
|
|
198
|
-
|
|
199
|
-
|
|
195
|
+
const padding = padded - LENGTH_PREFIX_BYTES - plaintextBytes;
|
|
196
|
+
const zeros = new Uint8Array(Math.min(padding, chunkBytes));
|
|
197
|
+
for (let remaining = padding; remaining > 0; remaining -= zeros.byteLength) {
|
|
198
|
+
yield* push(zeros.subarray(0, Math.min(remaining, zeros.byteLength)));
|
|
200
199
|
}
|
|
201
200
|
if (filled > 0)
|
|
202
201
|
yield await seal();
|
|
@@ -378,14 +377,109 @@ export const SyncEntrySchema = z.discriminatedUnion('kind', [
|
|
|
378
377
|
SyncDeleteEntrySchema,
|
|
379
378
|
SyncRewrapEntrySchema,
|
|
380
379
|
]);
|
|
380
|
+
const SyncSeqSchema = z.number().int().min(0);
|
|
381
|
+
const SyncCheckpointLinkSchema = z
|
|
382
|
+
.object({ entryId: SyncEntryIdSchema, throughSeq: SyncSeqSchema })
|
|
383
|
+
.strict();
|
|
384
|
+
export const SyncSnapshotPartSchema = z
|
|
385
|
+
.object({
|
|
386
|
+
objectId: SyncObjectIdSchema,
|
|
387
|
+
dataKey: ContentSealSchema,
|
|
388
|
+
plaintextSha256: Sha256DigestSchema,
|
|
389
|
+
size: z.number().int().min(1).max(MAX_SYNC_OBJECT_BYTES),
|
|
390
|
+
})
|
|
391
|
+
.strict();
|
|
392
|
+
export const SyncCheckpointEntrySchema = z
|
|
393
|
+
.object({
|
|
394
|
+
entryVersion: z.literal(SYNC_CHECKPOINT_ENTRY_VERSION),
|
|
395
|
+
entryId: SyncEntryIdSchema,
|
|
396
|
+
kind: z.literal('checkpoint'),
|
|
397
|
+
namespace: z.literal('files'),
|
|
398
|
+
itemId: SyncItemIdSchema,
|
|
399
|
+
hlc: SyncHlcSchema,
|
|
400
|
+
throughSeq: SyncSeqSchema,
|
|
401
|
+
prev: SyncCheckpointLinkSchema.nullable(),
|
|
402
|
+
snapshot: z
|
|
403
|
+
.object({
|
|
404
|
+
plaintextSha256: Sha256DigestSchema,
|
|
405
|
+
size: z
|
|
406
|
+
.number()
|
|
407
|
+
.int()
|
|
408
|
+
.min(1)
|
|
409
|
+
.max(MAX_SYNC_SNAPSHOT_PARTS * MAX_SYNC_OBJECT_BYTES),
|
|
410
|
+
parts: z.array(SyncSnapshotPartSchema).min(1).max(MAX_SYNC_SNAPSHOT_PARTS),
|
|
411
|
+
})
|
|
412
|
+
.strict(),
|
|
413
|
+
itemCount: z.number().int().min(0),
|
|
414
|
+
headCount: z.number().int().min(0),
|
|
415
|
+
tombstonesSince: TimestampSchema,
|
|
416
|
+
})
|
|
417
|
+
.strict();
|
|
418
|
+
export const SyncLogEntrySchema = z.discriminatedUnion('kind', [
|
|
419
|
+
SyncPutEntrySchema,
|
|
420
|
+
SyncDeleteEntrySchema,
|
|
421
|
+
SyncRewrapEntrySchema,
|
|
422
|
+
SyncCheckpointEntrySchema,
|
|
423
|
+
]);
|
|
424
|
+
const SnapshotHeadCommonSchema = {
|
|
425
|
+
seq: z.number().int().min(1),
|
|
426
|
+
entryId: SyncEntryIdSchema,
|
|
427
|
+
authorKeyId: SyncAuthorKeyIdSchema,
|
|
428
|
+
hlc: SyncHlcSchema,
|
|
429
|
+
};
|
|
430
|
+
export const SyncSnapshotHeadSchema = z.discriminatedUnion('kind', [
|
|
431
|
+
z
|
|
432
|
+
.object({
|
|
433
|
+
...SnapshotHeadCommonSchema,
|
|
434
|
+
kind: z.literal('put'),
|
|
435
|
+
parents: SyncPutEntrySchema.shape.parents,
|
|
436
|
+
path: SyncPathSchema,
|
|
437
|
+
objectId: SyncObjectIdSchema,
|
|
438
|
+
dataKey: ContentSealSchema,
|
|
439
|
+
plaintextSha256: Sha256DigestSchema,
|
|
440
|
+
size: z.number().int().min(0).max(MAX_SYNC_OBJECT_BYTES),
|
|
441
|
+
contentType: z.string().min(1).max(255).optional(),
|
|
442
|
+
mtimeMs: z.number().int().min(0).optional(),
|
|
443
|
+
})
|
|
444
|
+
.strict(),
|
|
445
|
+
z
|
|
446
|
+
.object({
|
|
447
|
+
...SnapshotHeadCommonSchema,
|
|
448
|
+
kind: z.literal('delete'),
|
|
449
|
+
parents: SyncDeleteEntrySchema.shape.parents,
|
|
450
|
+
})
|
|
451
|
+
.strict(),
|
|
452
|
+
]);
|
|
453
|
+
export const SYNC_SNAPSHOT_FORMAT = 'adea.sync-snapshot';
|
|
454
|
+
export const SyncSnapshotSchema = z
|
|
455
|
+
.object({
|
|
456
|
+
format: z.literal(SYNC_SNAPSHOT_FORMAT),
|
|
457
|
+
version: z.literal(1),
|
|
458
|
+
workspaceId: IdentifierSchema,
|
|
459
|
+
checkpointEntryId: SyncEntryIdSchema,
|
|
460
|
+
throughSeq: SyncSeqSchema,
|
|
461
|
+
prev: SyncCheckpointLinkSchema.nullable(),
|
|
462
|
+
items: z.array(z
|
|
463
|
+
.object({
|
|
464
|
+
itemId: SyncItemIdSchema,
|
|
465
|
+
namespace: SyncNamespaceSchema,
|
|
466
|
+
heads: z.array(SyncSnapshotHeadSchema).min(1),
|
|
467
|
+
})
|
|
468
|
+
.strict()),
|
|
469
|
+
})
|
|
470
|
+
.strict();
|
|
381
471
|
function entrySigningInput(workspaceId, entry) {
|
|
382
472
|
return new TextEncoder().encode(`${ENTRY_SIGNATURE_CONTEXT}\n${canonicalJsonStringify({ workspaceId, ...entry })}`);
|
|
383
473
|
}
|
|
384
474
|
function entryObjectIds(entry) {
|
|
385
|
-
|
|
475
|
+
if (entry.kind === 'delete')
|
|
476
|
+
return [];
|
|
477
|
+
if (entry.kind === 'checkpoint')
|
|
478
|
+
return [entry.snapshot.parts[0].objectId];
|
|
479
|
+
return [entry.objectId];
|
|
386
480
|
}
|
|
387
481
|
export async function sealSyncEntry(input) {
|
|
388
|
-
const parsed =
|
|
482
|
+
const parsed = SyncLogEntrySchema.safeParse(input.entry);
|
|
389
483
|
if (!parsed.success || parsed.data.hlc.node !== input.author.keyId) {
|
|
390
484
|
throw new DeviceSyncError('SYNC_ENTRY_INVALID');
|
|
391
485
|
}
|
|
@@ -416,13 +510,18 @@ export function syncAuthor(keyring, workspaceId, keyId, at) {
|
|
|
416
510
|
}
|
|
417
511
|
return author;
|
|
418
512
|
}
|
|
513
|
+
const OpenableSyncEntrySchema = SignedSyncEntrySchema.extend({
|
|
514
|
+
seq: z.number().int().min(1).optional(),
|
|
515
|
+
createdAt: TimestampSchema.optional(),
|
|
516
|
+
}).strict();
|
|
419
517
|
export async function openSyncEntry(input) {
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
518
|
+
return openEntry(input, SyncEntrySchema);
|
|
519
|
+
}
|
|
520
|
+
export async function openSyncLogEntry(input) {
|
|
521
|
+
return openEntry(input, SyncLogEntrySchema);
|
|
522
|
+
}
|
|
523
|
+
async function openEntry(input, schema) {
|
|
524
|
+
const stored = OpenableSyncEntrySchema.safeParse(input.entry);
|
|
426
525
|
if (!stored.success)
|
|
427
526
|
throw new DeviceSyncError('SYNC_ENTRY_INVALID');
|
|
428
527
|
const { signature, seq: _seq, createdAt, ...unsigned } = stored.data;
|
|
@@ -442,7 +541,7 @@ export async function openSyncEntry(input) {
|
|
|
442
541
|
}
|
|
443
542
|
let entry;
|
|
444
543
|
try {
|
|
445
|
-
entry =
|
|
544
|
+
entry = schema.parse(JSON.parse(plaintext));
|
|
446
545
|
}
|
|
447
546
|
catch {
|
|
448
547
|
throw new DeviceSyncError('SYNC_ENTRY_INVALID');
|
|
@@ -471,9 +570,140 @@ export function assertSyncLogAdvances(lastSeenSeq, page) {
|
|
|
471
570
|
previous = entry.seq;
|
|
472
571
|
}
|
|
473
572
|
}
|
|
474
|
-
export function
|
|
573
|
+
export function assertSyncLogContiguous(cursor, page, headSeq) {
|
|
574
|
+
let previous = cursor;
|
|
575
|
+
for (const entry of page) {
|
|
576
|
+
if (entry.seq <= previous)
|
|
577
|
+
throw new DeviceSyncError('SYNC_LOG_ROLLED_BACK');
|
|
578
|
+
if (entry.seq !== previous + 1)
|
|
579
|
+
throw new DeviceSyncError('SYNC_LOG_TRUNCATED');
|
|
580
|
+
previous = entry.seq;
|
|
581
|
+
}
|
|
582
|
+
if (headSeq !== undefined) {
|
|
583
|
+
if (headSeq < previous)
|
|
584
|
+
throw new DeviceSyncError('SYNC_LOG_ROLLED_BACK');
|
|
585
|
+
if (page.length === 0 && headSeq > cursor)
|
|
586
|
+
throw new DeviceSyncError('SYNC_LOG_TRUNCATED');
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
export function assertSyncCheckpoint(input) {
|
|
590
|
+
const { entry, registered } = input;
|
|
591
|
+
if (entry.authorKeyId !== input.keyring.primarySigningKeyId)
|
|
592
|
+
throw new DeviceSyncError('SYNC_AUTHOR_NOT_PRIMARY');
|
|
593
|
+
const parts = entry.snapshot.parts.slice(1).map((part) => part.objectId);
|
|
594
|
+
if (registered.entryId !== entry.entryId ||
|
|
595
|
+
entry.throughSeq >= registered.seq ||
|
|
596
|
+
registered.throughSeq !== entry.throughSeq ||
|
|
597
|
+
registered.prevEntryId !== (entry.prev?.entryId ?? null) ||
|
|
598
|
+
registered.partObjectIds.length !== parts.length ||
|
|
599
|
+
parts.some((objectId, index) => registered.partObjectIds[index] !== objectId) ||
|
|
600
|
+
input.floorSeq > entry.throughSeq)
|
|
601
|
+
throw new DeviceSyncError('SYNC_CHECKPOINT_INVALID');
|
|
602
|
+
if (entry.throughSeq < input.cursor)
|
|
603
|
+
throw new DeviceSyncError('SYNC_LOG_ROLLED_BACK');
|
|
604
|
+
}
|
|
605
|
+
export function encodeSyncSnapshot(snapshot) {
|
|
606
|
+
const parsed = SyncSnapshotSchema.safeParse(snapshot);
|
|
607
|
+
if (!parsed.success)
|
|
608
|
+
throw new DeviceSyncError('SYNC_BLOB_INVALID');
|
|
609
|
+
const items = parsed.data.items
|
|
610
|
+
.map((item) => ({
|
|
611
|
+
...item,
|
|
612
|
+
heads: item.heads.toSorted((left, right) => compareIds(left.entryId, right.entryId)),
|
|
613
|
+
}))
|
|
614
|
+
.toSorted((left, right) => compareIds(left.itemId, right.itemId));
|
|
615
|
+
return new TextEncoder().encode(canonicalJsonStringify({ ...parsed.data, items }));
|
|
616
|
+
}
|
|
617
|
+
export function splitSyncSnapshot(bytes) {
|
|
618
|
+
const count = Math.max(1, Math.ceil(bytes.byteLength / MAX_SYNC_OBJECT_BYTES));
|
|
619
|
+
if (count > MAX_SYNC_SNAPSHOT_PARTS)
|
|
620
|
+
throw new DeviceSyncError('SYNC_BLOB_TOO_LARGE');
|
|
621
|
+
return Array.from({ length: count }, (_, index) => bytes.subarray(index * MAX_SYNC_OBJECT_BYTES, (index + 1) * MAX_SYNC_OBJECT_BYTES));
|
|
622
|
+
}
|
|
623
|
+
export async function parseSyncSnapshot(input) {
|
|
624
|
+
const { checkpoint } = input;
|
|
625
|
+
if (input.parts.length !== checkpoint.snapshot.parts.length)
|
|
626
|
+
throw new DeviceSyncError('SYNC_CHECKPOINT_INVALID');
|
|
627
|
+
const bytes = concatBytes(input.parts, input.parts.reduce((sum, part) => sum + part.byteLength, 0));
|
|
628
|
+
if (bytes.byteLength !== checkpoint.snapshot.size ||
|
|
629
|
+
(await sha256(bytes)) !== checkpoint.snapshot.plaintextSha256)
|
|
630
|
+
throw new DeviceSyncError('SYNC_CHECKPOINT_INVALID');
|
|
631
|
+
let snapshot;
|
|
632
|
+
try {
|
|
633
|
+
snapshot = SyncSnapshotSchema.parse(JSON.parse(new TextDecoder().decode(bytes)));
|
|
634
|
+
}
|
|
635
|
+
catch {
|
|
636
|
+
throw new DeviceSyncError('SYNC_CHECKPOINT_INVALID');
|
|
637
|
+
}
|
|
638
|
+
const sameLink = (snapshot.prev === null && checkpoint.prev === null) ||
|
|
639
|
+
(snapshot.prev !== null &&
|
|
640
|
+
checkpoint.prev !== null &&
|
|
641
|
+
snapshot.prev.entryId === checkpoint.prev.entryId &&
|
|
642
|
+
snapshot.prev.throughSeq === checkpoint.prev.throughSeq);
|
|
643
|
+
if (snapshot.workspaceId !== input.workspaceId ||
|
|
644
|
+
snapshot.checkpointEntryId !== checkpoint.entryId ||
|
|
645
|
+
snapshot.throughSeq !== checkpoint.throughSeq ||
|
|
646
|
+
!sameLink ||
|
|
647
|
+
snapshot.items.length !== checkpoint.itemCount)
|
|
648
|
+
throw new DeviceSyncError('SYNC_CHECKPOINT_INVALID');
|
|
649
|
+
const heads = [];
|
|
650
|
+
let previousItem;
|
|
651
|
+
for (const item of snapshot.items) {
|
|
652
|
+
if (previousItem !== undefined && compareIds(previousItem, item.itemId) >= 0)
|
|
653
|
+
throw new DeviceSyncError('SYNC_CHECKPOINT_INVALID');
|
|
654
|
+
previousItem = item.itemId;
|
|
655
|
+
let previousHead;
|
|
656
|
+
for (const head of item.heads) {
|
|
657
|
+
if (head.seq > snapshot.throughSeq ||
|
|
658
|
+
head.hlc.node !== head.authorKeyId ||
|
|
659
|
+
(previousHead !== undefined && compareIds(previousHead, head.entryId) >= 0))
|
|
660
|
+
throw new DeviceSyncError('SYNC_CHECKPOINT_INVALID');
|
|
661
|
+
previousHead = head.entryId;
|
|
662
|
+
heads.push(snapshotHeadEntry(item, head));
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
if (heads.length !== checkpoint.headCount)
|
|
666
|
+
throw new DeviceSyncError('SYNC_CHECKPOINT_INVALID');
|
|
667
|
+
return { snapshot, heads };
|
|
668
|
+
}
|
|
669
|
+
function snapshotHeadEntry(item, head) {
|
|
670
|
+
const common = {
|
|
671
|
+
entryVersion: SYNC_ENTRY_VERSION,
|
|
672
|
+
entryId: head.entryId,
|
|
673
|
+
namespace: item.namespace,
|
|
674
|
+
itemId: item.itemId,
|
|
675
|
+
hlc: head.hlc,
|
|
676
|
+
parents: head.parents,
|
|
677
|
+
authorKeyId: head.authorKeyId,
|
|
678
|
+
};
|
|
679
|
+
if (head.kind === 'delete')
|
|
680
|
+
return { ...common, kind: 'delete' };
|
|
681
|
+
return {
|
|
682
|
+
...common,
|
|
683
|
+
kind: 'put',
|
|
684
|
+
path: head.path,
|
|
685
|
+
objectId: head.objectId,
|
|
686
|
+
dataKey: head.dataKey,
|
|
687
|
+
plaintextSha256: head.plaintextSha256,
|
|
688
|
+
size: head.size,
|
|
689
|
+
...(head.contentType === undefined ? {} : { contentType: head.contentType }),
|
|
690
|
+
...(head.mtimeMs === undefined ? {} : { mtimeMs: head.mtimeMs }),
|
|
691
|
+
};
|
|
692
|
+
}
|
|
693
|
+
function compareIds(left, right) {
|
|
694
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
695
|
+
}
|
|
696
|
+
export function foldSyncItems(entries, options = {}) {
|
|
475
697
|
const byItem = new Map();
|
|
698
|
+
const once = new Set();
|
|
476
699
|
for (const entry of entries) {
|
|
700
|
+
if (once.has(entry.entryId))
|
|
701
|
+
continue;
|
|
702
|
+
once.add(entry.entryId);
|
|
703
|
+
if (entry.kind === 'rewrap' &&
|
|
704
|
+
options.primarySigningKeyId !== undefined &&
|
|
705
|
+
entry.authorKeyId !== options.primarySigningKeyId)
|
|
706
|
+
continue;
|
|
477
707
|
const list = byItem.get(entry.itemId) ?? [];
|
|
478
708
|
list.push(entry);
|
|
479
709
|
byItem.set(entry.itemId, list);
|
package/dist/shared.d.ts
ADDED
package/dist/shared.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Aes128Gcm, CipherSuite, DhkemX25519HkdfSha256, HkdfSha256 } from '@hpke/core';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
export const hpkeSuite = new CipherSuite({
|
|
4
|
+
kem: new DhkemX25519HkdfSha256(),
|
|
5
|
+
kdf: new HkdfSha256(),
|
|
6
|
+
aead: new Aes128Gcm(),
|
|
7
|
+
});
|
|
8
|
+
export const IdentifierSchema = z
|
|
9
|
+
.string()
|
|
10
|
+
.min(1)
|
|
11
|
+
.max(128)
|
|
12
|
+
.regex(/^[A-Za-z0-9._:-]+$/);
|
|
13
|
+
export const Base64UrlSchema = z
|
|
14
|
+
.string()
|
|
15
|
+
.min(1)
|
|
16
|
+
.regex(/^[A-Za-z0-9_-]+$/);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adea-ai/runtime-gateway-protocol",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.18.1",
|
|
4
4
|
"description": "Device relay envelopes and workspace content keys shared by the Control Plane and Adea clients.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agents",
|
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
"dist"
|
|
22
22
|
],
|
|
23
23
|
"type": "module",
|
|
24
|
+
"sideEffects": false,
|
|
24
25
|
"browser": false,
|
|
25
26
|
"types": "./dist/index.d.ts",
|
|
26
27
|
"exports": {
|
|
@@ -52,10 +53,9 @@
|
|
|
52
53
|
"test": "bun test src"
|
|
53
54
|
},
|
|
54
55
|
"dependencies": {
|
|
55
|
-
"@adea-ai/contracts": "^5.0
|
|
56
|
+
"@adea-ai/contracts": "^5.2.0",
|
|
56
57
|
"@hpke/core": "1.10.1",
|
|
57
|
-
"
|
|
58
|
-
"zod": "4.6.6"
|
|
58
|
+
"zod": "4.6.7"
|
|
59
59
|
},
|
|
60
60
|
"engines": {
|
|
61
61
|
"node": "24.21.0"
|