@adea-ai/runtime-gateway-protocol 1.16.0 → 1.17.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.
- package/README.md +12 -23
- package/dist/device-relay.d.ts +2 -0
- package/dist/device-relay.js +14 -0
- package/dist/device-sync.d.ts +241 -0
- package/dist/device-sync.js +557 -0
- package/dist/index.d.ts +2 -6
- package/dist/index.js +2 -6
- package/package.json +12 -16
- package/dist/acp-remote-sealed-channel.d.ts +0 -12
- package/dist/acp-remote-sealed-channel.js +0 -1
- package/dist/authentication.d.ts +0 -45
- package/dist/authentication.js +0 -71
- package/dist/emulator.d.ts +0 -24
- package/dist/emulator.js +0 -137
- package/dist/fixtures.d.ts +0 -149
- package/dist/fixtures.js +0 -48
- package/dist/protocol.d.ts +0 -716
- package/dist/protocol.js +0 -522
- package/dist/public-identity-validation-compatibility.d.ts +0 -1
- package/dist/public-identity-validation-compatibility.js +0 -10
- package/fixtures/golden/envelopes.json +0 -153
- package/fixtures/index.mjs +0 -4
- package/fixtures/malformed/envelopes.json +0 -70
- package/schema/gateway-envelope.v1.json +0 -990
|
@@ -0,0 +1,557 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { canonicalJsonStringify } from '@adea-ai/contracts/canonical-json';
|
|
3
|
+
import { MAX_SYNC_ENTRY_BYTES, SignedSyncEntrySchema, SyncObjectIdSchema, SyncEntryIdSchema, } from '@adea-ai/contracts/device-sync';
|
|
4
|
+
import { ContentKeyError, ContentSealSchema, openContent, sealContent, } from './content-key.js';
|
|
5
|
+
import { MAX_RELAY_CLOCK_SKEW_MS, decodeBase64Url, encodeBase64Url, sha256, signRelayBytes, verifyRelayBytes, } from './device-relay.js';
|
|
6
|
+
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, } from '@adea-ai/contracts/device-sync';
|
|
7
|
+
export const SYNC_BLOB_VERSION = 1;
|
|
8
|
+
export const SYNC_ENTRY_VERSION = 1;
|
|
9
|
+
export const SYNC_CHUNK_BYTES = 1024 * 1024;
|
|
10
|
+
export const MAX_SYNC_OBJECT_BYTES = 256 * 1024 * 1024;
|
|
11
|
+
export const SYNC_REQUEST_HEADER = 'adea-sync-signature';
|
|
12
|
+
const DATA_KEY_BYTES = 32;
|
|
13
|
+
const AEAD_TAG_BYTES = 16;
|
|
14
|
+
const NONCE_BYTES = 12;
|
|
15
|
+
const LENGTH_PREFIX_BYTES = 8;
|
|
16
|
+
const HEADER_BYTES = 12;
|
|
17
|
+
const MAGIC = [0x41, 0x53, 0x42, 0x31];
|
|
18
|
+
const ENTRY_SIGNATURE_CONTEXT = 'adea-device-sync-entry-v1';
|
|
19
|
+
const REQUEST_SIGNATURE_CONTEXT = 'adea-device-sync-request-v1';
|
|
20
|
+
const DEK_FIELD = 'sync:dek';
|
|
21
|
+
const ENTRY_FIELD = 'sync:entry';
|
|
22
|
+
export class DeviceSyncError extends Error {
|
|
23
|
+
code;
|
|
24
|
+
constructor(code) {
|
|
25
|
+
super('Device sync data was rejected');
|
|
26
|
+
this.code = code;
|
|
27
|
+
this.name = 'DeviceSyncError';
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const IdentifierSchema = z
|
|
31
|
+
.string()
|
|
32
|
+
.min(1)
|
|
33
|
+
.max(128)
|
|
34
|
+
.regex(/^[A-Za-z0-9._:-]+$/);
|
|
35
|
+
const AuthorKeyIdSchema = z.string().regex(/^(?:spk|dpk)_[a-f0-9]{32}$/);
|
|
36
|
+
const Sha256Schema = z.string().regex(/^sha256:[a-f0-9]{64}$/);
|
|
37
|
+
export const SyncItemIdSchema = z.string().regex(/^sit_[a-f0-9]{32}$/);
|
|
38
|
+
function randomId(prefix) {
|
|
39
|
+
const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));
|
|
40
|
+
return `${prefix}_${[...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('')}`;
|
|
41
|
+
}
|
|
42
|
+
export const newSyncObjectId = () => randomId('sob');
|
|
43
|
+
export const newSyncEntryId = () => randomId('sen');
|
|
44
|
+
export const newSyncItemId = () => randomId('sit');
|
|
45
|
+
export function padmeLength(length) {
|
|
46
|
+
if (!Number.isSafeInteger(length) || length < 0)
|
|
47
|
+
throw new DeviceSyncError('SYNC_BLOB_INVALID');
|
|
48
|
+
if (length < 2)
|
|
49
|
+
return length;
|
|
50
|
+
const exponent = Math.floor(Math.log2(length));
|
|
51
|
+
const bits = Math.floor(Math.log2(exponent)) + 1;
|
|
52
|
+
const zeroBits = exponent - bits;
|
|
53
|
+
const mask = 2 ** zeroBits - 1;
|
|
54
|
+
return Math.ceil(length / (mask + 1)) * (mask + 1);
|
|
55
|
+
}
|
|
56
|
+
export function sealedBlobLength(plaintextBytes) {
|
|
57
|
+
if (plaintextBytes > MAX_SYNC_OBJECT_BYTES)
|
|
58
|
+
throw new DeviceSyncError('SYNC_BLOB_TOO_LARGE');
|
|
59
|
+
const padded = padmeLength(plaintextBytes + LENGTH_PREFIX_BYTES);
|
|
60
|
+
const chunks = Math.max(1, Math.ceil(padded / SYNC_CHUNK_BYTES));
|
|
61
|
+
return HEADER_BYTES + padded + chunks * AEAD_TAG_BYTES;
|
|
62
|
+
}
|
|
63
|
+
export function generateSyncDataKey() {
|
|
64
|
+
return globalThis.crypto.getRandomValues(new Uint8Array(DATA_KEY_BYTES));
|
|
65
|
+
}
|
|
66
|
+
async function importDataKey(raw) {
|
|
67
|
+
if (raw.byteLength !== DATA_KEY_BYTES)
|
|
68
|
+
throw new DeviceSyncError('SYNC_KEY_UNAVAILABLE');
|
|
69
|
+
return globalThis.crypto.subtle.importKey('raw', Uint8Array.from(raw), 'AES-GCM', false, [
|
|
70
|
+
'encrypt',
|
|
71
|
+
'decrypt',
|
|
72
|
+
]);
|
|
73
|
+
}
|
|
74
|
+
function parseBinding(binding) {
|
|
75
|
+
const parsed = z
|
|
76
|
+
.object({ workspaceId: IdentifierSchema, objectId: SyncObjectIdSchema })
|
|
77
|
+
.strict()
|
|
78
|
+
.safeParse(binding);
|
|
79
|
+
if (!parsed.success)
|
|
80
|
+
throw new DeviceSyncError('SYNC_BLOB_INVALID');
|
|
81
|
+
return parsed.data;
|
|
82
|
+
}
|
|
83
|
+
function chunkNonce(index) {
|
|
84
|
+
const nonce = new Uint8Array(NONCE_BYTES);
|
|
85
|
+
new DataView(nonce.buffer).setBigUint64(4, BigInt(index));
|
|
86
|
+
return nonce;
|
|
87
|
+
}
|
|
88
|
+
function chunkAad(binding, index, count) {
|
|
89
|
+
return new TextEncoder().encode(canonicalJsonStringify({
|
|
90
|
+
blob: SYNC_BLOB_VERSION,
|
|
91
|
+
workspaceId: binding.workspaceId,
|
|
92
|
+
objectId: binding.objectId,
|
|
93
|
+
index,
|
|
94
|
+
count,
|
|
95
|
+
}));
|
|
96
|
+
}
|
|
97
|
+
class ByteReader {
|
|
98
|
+
iterator;
|
|
99
|
+
pending = new Uint8Array(0);
|
|
100
|
+
done = false;
|
|
101
|
+
constructor(source) {
|
|
102
|
+
this.iterator = source[Symbol.asyncIterator]();
|
|
103
|
+
}
|
|
104
|
+
async read(size) {
|
|
105
|
+
const parts = [];
|
|
106
|
+
let have = 0;
|
|
107
|
+
while (have < size) {
|
|
108
|
+
if (this.pending.byteLength === 0) {
|
|
109
|
+
if (this.done)
|
|
110
|
+
break;
|
|
111
|
+
const next = await this.iterator.next();
|
|
112
|
+
if (next.done) {
|
|
113
|
+
this.done = true;
|
|
114
|
+
break;
|
|
115
|
+
}
|
|
116
|
+
this.pending = next.value;
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
const take = Math.min(size - have, this.pending.byteLength);
|
|
120
|
+
parts.push(this.pending.subarray(0, take));
|
|
121
|
+
this.pending = this.pending.subarray(take);
|
|
122
|
+
have += take;
|
|
123
|
+
}
|
|
124
|
+
return concatBytes(parts, have);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function concatBytes(parts, total) {
|
|
128
|
+
if (parts.length === 1)
|
|
129
|
+
return parts[0];
|
|
130
|
+
const out = new Uint8Array(total);
|
|
131
|
+
let offset = 0;
|
|
132
|
+
for (const part of parts) {
|
|
133
|
+
out.set(part, offset);
|
|
134
|
+
offset += part.byteLength;
|
|
135
|
+
}
|
|
136
|
+
return out;
|
|
137
|
+
}
|
|
138
|
+
async function collect(stream) {
|
|
139
|
+
const parts = [];
|
|
140
|
+
let total = 0;
|
|
141
|
+
for await (const part of stream) {
|
|
142
|
+
parts.push(part);
|
|
143
|
+
total += part.byteLength;
|
|
144
|
+
}
|
|
145
|
+
return concatBytes(parts, total);
|
|
146
|
+
}
|
|
147
|
+
async function* once(bytes) {
|
|
148
|
+
yield bytes;
|
|
149
|
+
}
|
|
150
|
+
export async function* sealSyncBlobStream(dataKey, binding, plaintextBytes, source) {
|
|
151
|
+
const bound = parseBinding(binding);
|
|
152
|
+
if (!Number.isSafeInteger(plaintextBytes) || plaintextBytes < 0) {
|
|
153
|
+
throw new DeviceSyncError('SYNC_BLOB_INVALID');
|
|
154
|
+
}
|
|
155
|
+
sealedBlobLength(plaintextBytes);
|
|
156
|
+
const padded = padmeLength(plaintextBytes + LENGTH_PREFIX_BYTES);
|
|
157
|
+
const count = Math.max(1, Math.ceil(padded / SYNC_CHUNK_BYTES));
|
|
158
|
+
const key = await importDataKey(dataKey);
|
|
159
|
+
const header = new Uint8Array(HEADER_BYTES);
|
|
160
|
+
header.set(MAGIC, 0);
|
|
161
|
+
header[4] = SYNC_BLOB_VERSION;
|
|
162
|
+
new DataView(header.buffer).setUint32(8, count);
|
|
163
|
+
yield header;
|
|
164
|
+
const buffer = new Uint8Array(SYNC_CHUNK_BYTES);
|
|
165
|
+
let filled = 0;
|
|
166
|
+
let index = 0;
|
|
167
|
+
async function seal() {
|
|
168
|
+
const sealed = new Uint8Array(await globalThis.crypto.subtle.encrypt({ name: 'AES-GCM', iv: chunkNonce(index), additionalData: chunkAad(bound, index, count) }, key, buffer.subarray(0, filled)));
|
|
169
|
+
index += 1;
|
|
170
|
+
filled = 0;
|
|
171
|
+
return sealed;
|
|
172
|
+
}
|
|
173
|
+
async function* push(bytes) {
|
|
174
|
+
let offset = 0;
|
|
175
|
+
while (offset < bytes.byteLength) {
|
|
176
|
+
const take = Math.min(bytes.byteLength - offset, SYNC_CHUNK_BYTES - filled);
|
|
177
|
+
buffer.set(bytes.subarray(offset, offset + take), filled);
|
|
178
|
+
filled += take;
|
|
179
|
+
offset += take;
|
|
180
|
+
if (filled === SYNC_CHUNK_BYTES)
|
|
181
|
+
yield await seal();
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
try {
|
|
185
|
+
const prefix = new Uint8Array(LENGTH_PREFIX_BYTES);
|
|
186
|
+
new DataView(prefix.buffer).setBigUint64(0, BigInt(plaintextBytes));
|
|
187
|
+
yield* push(prefix);
|
|
188
|
+
let received = 0;
|
|
189
|
+
for await (const part of source) {
|
|
190
|
+
received += part.byteLength;
|
|
191
|
+
if (received > plaintextBytes)
|
|
192
|
+
throw new DeviceSyncError('SYNC_BLOB_INVALID');
|
|
193
|
+
yield* push(part);
|
|
194
|
+
}
|
|
195
|
+
if (received !== plaintextBytes)
|
|
196
|
+
throw new DeviceSyncError('SYNC_BLOB_INVALID');
|
|
197
|
+
const zeros = new Uint8Array(SYNC_CHUNK_BYTES);
|
|
198
|
+
for (let remaining = padded - LENGTH_PREFIX_BYTES - plaintextBytes; remaining > 0; remaining -= SYNC_CHUNK_BYTES) {
|
|
199
|
+
yield* push(zeros.subarray(0, Math.min(remaining, SYNC_CHUNK_BYTES)));
|
|
200
|
+
}
|
|
201
|
+
if (filled > 0)
|
|
202
|
+
yield await seal();
|
|
203
|
+
if (index !== count)
|
|
204
|
+
throw new DeviceSyncError('SYNC_BLOB_INVALID');
|
|
205
|
+
}
|
|
206
|
+
finally {
|
|
207
|
+
buffer.fill(0);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
export async function sealSyncBlob(dataKey, binding, plaintext) {
|
|
211
|
+
return collect(sealSyncBlobStream(dataKey, binding, plaintext.byteLength, once(plaintext)));
|
|
212
|
+
}
|
|
213
|
+
export async function* openSyncBlobStream(dataKey, binding, sealed) {
|
|
214
|
+
const bound = parseBinding(binding);
|
|
215
|
+
const reader = new ByteReader(sealed);
|
|
216
|
+
const header = await reader.read(HEADER_BYTES);
|
|
217
|
+
if (header.byteLength !== HEADER_BYTES ||
|
|
218
|
+
MAGIC.some((byte, index) => header[index] !== byte) ||
|
|
219
|
+
header[4] !== SYNC_BLOB_VERSION ||
|
|
220
|
+
header[5] !== 0 ||
|
|
221
|
+
header[6] !== 0 ||
|
|
222
|
+
header[7] !== 0) {
|
|
223
|
+
throw new DeviceSyncError('SYNC_BLOB_INVALID');
|
|
224
|
+
}
|
|
225
|
+
const count = new DataView(header.buffer, header.byteOffset, header.byteLength).getUint32(8);
|
|
226
|
+
const largestBody = padmeLength(MAX_SYNC_OBJECT_BYTES + LENGTH_PREFIX_BYTES);
|
|
227
|
+
if (count < 1 || count > Math.ceil(largestBody / SYNC_CHUNK_BYTES)) {
|
|
228
|
+
throw new DeviceSyncError('SYNC_BLOB_INVALID');
|
|
229
|
+
}
|
|
230
|
+
const key = await importDataKey(dataKey);
|
|
231
|
+
let body = 0;
|
|
232
|
+
let length = 0;
|
|
233
|
+
let remaining = 0;
|
|
234
|
+
for (let index = 0; index < count; index += 1) {
|
|
235
|
+
const last = index === count - 1;
|
|
236
|
+
const fullChunk = SYNC_CHUNK_BYTES + AEAD_TAG_BYTES;
|
|
237
|
+
const chunk = await reader.read(last ? fullChunk + 1 : fullChunk);
|
|
238
|
+
if (chunk.byteLength < AEAD_TAG_BYTES + (index === 0 ? LENGTH_PREFIX_BYTES : 0) ||
|
|
239
|
+
chunk.byteLength > fullChunk ||
|
|
240
|
+
(!last && chunk.byteLength !== fullChunk)) {
|
|
241
|
+
throw new DeviceSyncError('SYNC_BLOB_INVALID');
|
|
242
|
+
}
|
|
243
|
+
let opened;
|
|
244
|
+
try {
|
|
245
|
+
opened = new Uint8Array(await globalThis.crypto.subtle.decrypt({ name: 'AES-GCM', iv: chunkNonce(index), additionalData: chunkAad(bound, index, count) }, key, Uint8Array.from(chunk)));
|
|
246
|
+
}
|
|
247
|
+
catch {
|
|
248
|
+
throw new DeviceSyncError('SYNC_DECRYPTION_FAILED');
|
|
249
|
+
}
|
|
250
|
+
let payload = opened;
|
|
251
|
+
if (index === 0) {
|
|
252
|
+
length = Number(new DataView(opened.buffer).getBigUint64(0));
|
|
253
|
+
if (length > MAX_SYNC_OBJECT_BYTES)
|
|
254
|
+
throw new DeviceSyncError('SYNC_BLOB_INVALID');
|
|
255
|
+
body = padmeLength(length + LENGTH_PREFIX_BYTES);
|
|
256
|
+
if (Math.max(1, Math.ceil(body / SYNC_CHUNK_BYTES)) !== count) {
|
|
257
|
+
throw new DeviceSyncError('SYNC_BLOB_INVALID');
|
|
258
|
+
}
|
|
259
|
+
remaining = length;
|
|
260
|
+
payload = opened.subarray(LENGTH_PREFIX_BYTES);
|
|
261
|
+
}
|
|
262
|
+
const expected = Math.min(SYNC_CHUNK_BYTES, body - index * SYNC_CHUNK_BYTES);
|
|
263
|
+
if (opened.byteLength !== expected)
|
|
264
|
+
throw new DeviceSyncError('SYNC_BLOB_INVALID');
|
|
265
|
+
const data = payload.subarray(0, Math.min(remaining, payload.byteLength));
|
|
266
|
+
if (payload.subarray(data.byteLength).some((byte) => byte !== 0)) {
|
|
267
|
+
throw new DeviceSyncError('SYNC_BLOB_INVALID');
|
|
268
|
+
}
|
|
269
|
+
remaining -= data.byteLength;
|
|
270
|
+
if (data.byteLength > 0)
|
|
271
|
+
yield data.slice();
|
|
272
|
+
opened.fill(0);
|
|
273
|
+
}
|
|
274
|
+
if (remaining !== 0) {
|
|
275
|
+
throw new DeviceSyncError('SYNC_BLOB_INVALID');
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
export async function openSyncBlob(dataKey, binding, sealed) {
|
|
279
|
+
return collect(openSyncBlobStream(dataKey, binding, once(sealed)));
|
|
280
|
+
}
|
|
281
|
+
export async function sealSyncDataKey(contentKey, binding, dataKey) {
|
|
282
|
+
const bound = parseBinding(binding);
|
|
283
|
+
if (dataKey.byteLength !== DATA_KEY_BYTES)
|
|
284
|
+
throw new DeviceSyncError('SYNC_KEY_UNAVAILABLE');
|
|
285
|
+
return sealContent(contentKey, { workspaceId: bound.workspaceId, messageId: bound.objectId, field: DEK_FIELD }, encodeBase64Url(dataKey));
|
|
286
|
+
}
|
|
287
|
+
export async function openSyncDataKey(contentKey, binding, sealed) {
|
|
288
|
+
const bound = parseBinding(binding);
|
|
289
|
+
let encoded;
|
|
290
|
+
try {
|
|
291
|
+
encoded = await openContent(contentKey, { workspaceId: bound.workspaceId, messageId: bound.objectId, field: DEK_FIELD }, sealed);
|
|
292
|
+
}
|
|
293
|
+
catch (error) {
|
|
294
|
+
throw new DeviceSyncError(error instanceof ContentKeyError && error.code === 'CONTENT_KEY_VERSION_MISMATCH'
|
|
295
|
+
? 'SYNC_KEY_UNAVAILABLE'
|
|
296
|
+
: 'SYNC_DECRYPTION_FAILED');
|
|
297
|
+
}
|
|
298
|
+
let raw;
|
|
299
|
+
try {
|
|
300
|
+
raw = decodeBase64Url(encoded);
|
|
301
|
+
}
|
|
302
|
+
catch {
|
|
303
|
+
throw new DeviceSyncError('SYNC_DECRYPTION_FAILED');
|
|
304
|
+
}
|
|
305
|
+
if (raw.byteLength !== DATA_KEY_BYTES)
|
|
306
|
+
throw new DeviceSyncError('SYNC_DECRYPTION_FAILED');
|
|
307
|
+
return raw;
|
|
308
|
+
}
|
|
309
|
+
export const SyncNamespaceSchema = z.enum(['files', 'sessions', 'artifacts']);
|
|
310
|
+
export const SyncHlcSchema = z
|
|
311
|
+
.object({
|
|
312
|
+
wallMs: z.number().int().min(0),
|
|
313
|
+
counter: z.number().int().min(0).max(0xffff),
|
|
314
|
+
node: AuthorKeyIdSchema,
|
|
315
|
+
})
|
|
316
|
+
.strict();
|
|
317
|
+
export function nextSyncHlc(previous, nowMs, node) {
|
|
318
|
+
if (!previous || nowMs > previous.wallMs)
|
|
319
|
+
return SyncHlcSchema.parse({ wallMs: nowMs, counter: 0, node });
|
|
320
|
+
return SyncHlcSchema.parse({ wallMs: previous.wallMs, counter: previous.counter + 1, node });
|
|
321
|
+
}
|
|
322
|
+
export function observeSyncHlc(local, seen) {
|
|
323
|
+
return local === undefined || compareSyncHlc(seen, local) > 0 ? seen : local;
|
|
324
|
+
}
|
|
325
|
+
export function compareSyncHlc(left, right) {
|
|
326
|
+
if (left.wallMs !== right.wallMs)
|
|
327
|
+
return left.wallMs < right.wallMs ? -1 : 1;
|
|
328
|
+
if (left.counter !== right.counter)
|
|
329
|
+
return left.counter < right.counter ? -1 : 1;
|
|
330
|
+
return left.node < right.node ? -1 : left.node > right.node ? 1 : 0;
|
|
331
|
+
}
|
|
332
|
+
const SyncPathSchema = z
|
|
333
|
+
.string()
|
|
334
|
+
.min(1)
|
|
335
|
+
.max(1024)
|
|
336
|
+
.refine((path) => !path.startsWith('/') &&
|
|
337
|
+
!path.includes('\\') &&
|
|
338
|
+
!path.includes('\u0000') &&
|
|
339
|
+
path.split('/').every((part) => part !== '' && part !== '.' && part !== '..'), 'a relative path without empty, . or .. segments');
|
|
340
|
+
const EntryCommonSchema = {
|
|
341
|
+
entryVersion: z.literal(SYNC_ENTRY_VERSION),
|
|
342
|
+
entryId: SyncEntryIdSchema,
|
|
343
|
+
namespace: SyncNamespaceSchema,
|
|
344
|
+
itemId: SyncItemIdSchema,
|
|
345
|
+
hlc: SyncHlcSchema,
|
|
346
|
+
};
|
|
347
|
+
export const SyncPutEntrySchema = z
|
|
348
|
+
.object({
|
|
349
|
+
...EntryCommonSchema,
|
|
350
|
+
kind: z.literal('put'),
|
|
351
|
+
path: SyncPathSchema,
|
|
352
|
+
objectId: SyncObjectIdSchema,
|
|
353
|
+
dataKey: ContentSealSchema,
|
|
354
|
+
plaintextSha256: Sha256Schema,
|
|
355
|
+
size: z.number().int().min(0).max(MAX_SYNC_OBJECT_BYTES),
|
|
356
|
+
contentType: z.string().min(1).max(255).optional(),
|
|
357
|
+
mtimeMs: z.number().int().min(0).optional(),
|
|
358
|
+
parents: z.array(SyncEntryIdSchema).max(16),
|
|
359
|
+
})
|
|
360
|
+
.strict();
|
|
361
|
+
export const SyncDeleteEntrySchema = z
|
|
362
|
+
.object({
|
|
363
|
+
...EntryCommonSchema,
|
|
364
|
+
kind: z.literal('delete'),
|
|
365
|
+
parents: z.array(SyncEntryIdSchema).min(1).max(16),
|
|
366
|
+
})
|
|
367
|
+
.strict();
|
|
368
|
+
export const SyncRewrapEntrySchema = z
|
|
369
|
+
.object({
|
|
370
|
+
...EntryCommonSchema,
|
|
371
|
+
kind: z.literal('rewrap'),
|
|
372
|
+
objectId: SyncObjectIdSchema,
|
|
373
|
+
dataKey: ContentSealSchema,
|
|
374
|
+
})
|
|
375
|
+
.strict();
|
|
376
|
+
export const SyncEntrySchema = z.discriminatedUnion('kind', [
|
|
377
|
+
SyncPutEntrySchema,
|
|
378
|
+
SyncDeleteEntrySchema,
|
|
379
|
+
SyncRewrapEntrySchema,
|
|
380
|
+
]);
|
|
381
|
+
function entrySigningInput(workspaceId, entry) {
|
|
382
|
+
return new TextEncoder().encode(`${ENTRY_SIGNATURE_CONTEXT}\n${canonicalJsonStringify({ workspaceId, ...entry })}`);
|
|
383
|
+
}
|
|
384
|
+
function entryObjectIds(entry) {
|
|
385
|
+
return entry.kind === 'delete' ? [] : [entry.objectId];
|
|
386
|
+
}
|
|
387
|
+
export async function sealSyncEntry(input) {
|
|
388
|
+
const parsed = SyncEntrySchema.safeParse(input.entry);
|
|
389
|
+
if (!parsed.success || parsed.data.hlc.node !== input.author.keyId) {
|
|
390
|
+
throw new DeviceSyncError('SYNC_ENTRY_INVALID');
|
|
391
|
+
}
|
|
392
|
+
const plaintext = canonicalJsonStringify(parsed.data);
|
|
393
|
+
if (new TextEncoder().encode(plaintext).byteLength > MAX_SYNC_ENTRY_BYTES) {
|
|
394
|
+
throw new DeviceSyncError('SYNC_ENTRY_TOO_LARGE');
|
|
395
|
+
}
|
|
396
|
+
const seal = await sealContent(input.contentKey, { workspaceId: input.workspaceId, messageId: parsed.data.entryId, field: ENTRY_FIELD }, plaintext);
|
|
397
|
+
const unsigned = {
|
|
398
|
+
entryId: parsed.data.entryId,
|
|
399
|
+
authorKeyId: input.author.keyId,
|
|
400
|
+
objectIds: entryObjectIds(parsed.data),
|
|
401
|
+
ckv: seal.ckv,
|
|
402
|
+
nonce: seal.nonce,
|
|
403
|
+
ciphertext: seal.ciphertext,
|
|
404
|
+
};
|
|
405
|
+
const signature = await signRelayBytes(input.author.privateKey, entrySigningInput(input.workspaceId, unsigned));
|
|
406
|
+
return SignedSyncEntrySchema.parse({ ...unsigned, signature });
|
|
407
|
+
}
|
|
408
|
+
export function syncAuthor(keyring, workspaceId, keyId, at) {
|
|
409
|
+
if (keyring.workspaceId !== workspaceId)
|
|
410
|
+
throw new DeviceSyncError('SYNC_AUTHOR_UNKNOWN');
|
|
411
|
+
const author = keyring.entries.find((entry) => entry.senderKeyId === keyId);
|
|
412
|
+
if (!author)
|
|
413
|
+
throw new DeviceSyncError('SYNC_AUTHOR_UNKNOWN');
|
|
414
|
+
if (author.revokedAt !== undefined && Date.parse(author.revokedAt) <= at) {
|
|
415
|
+
throw new DeviceSyncError('SYNC_AUTHOR_REVOKED');
|
|
416
|
+
}
|
|
417
|
+
return author;
|
|
418
|
+
}
|
|
419
|
+
export async function openSyncEntry(input) {
|
|
420
|
+
const stored = SignedSyncEntrySchema.extend({
|
|
421
|
+
seq: z.number().int().min(1).optional(),
|
|
422
|
+
createdAt: z.iso.datetime().optional(),
|
|
423
|
+
})
|
|
424
|
+
.strict()
|
|
425
|
+
.safeParse(input.entry);
|
|
426
|
+
if (!stored.success)
|
|
427
|
+
throw new DeviceSyncError('SYNC_ENTRY_INVALID');
|
|
428
|
+
const { signature, seq: _seq, createdAt, ...unsigned } = stored.data;
|
|
429
|
+
const author = syncAuthor(input.keyring, input.workspaceId, unsigned.authorKeyId, -Infinity);
|
|
430
|
+
if (!(await verifyRelayBytes(author.signingPublicKey, signature, entrySigningInput(input.workspaceId, unsigned)))) {
|
|
431
|
+
throw new DeviceSyncError('SYNC_SIGNATURE_INVALID');
|
|
432
|
+
}
|
|
433
|
+
const key = await input.contentKey(unsigned.ckv);
|
|
434
|
+
if (!key)
|
|
435
|
+
throw new DeviceSyncError('SYNC_KEY_UNAVAILABLE');
|
|
436
|
+
let plaintext;
|
|
437
|
+
try {
|
|
438
|
+
plaintext = await openContent(key, { workspaceId: input.workspaceId, messageId: unsigned.entryId, field: ENTRY_FIELD }, { ckv: unsigned.ckv, nonce: unsigned.nonce, ciphertext: unsigned.ciphertext });
|
|
439
|
+
}
|
|
440
|
+
catch {
|
|
441
|
+
throw new DeviceSyncError('SYNC_DECRYPTION_FAILED');
|
|
442
|
+
}
|
|
443
|
+
let entry;
|
|
444
|
+
try {
|
|
445
|
+
entry = SyncEntrySchema.parse(JSON.parse(plaintext));
|
|
446
|
+
}
|
|
447
|
+
catch {
|
|
448
|
+
throw new DeviceSyncError('SYNC_ENTRY_INVALID');
|
|
449
|
+
}
|
|
450
|
+
const objectIds = entryObjectIds(entry);
|
|
451
|
+
if (entry.entryId !== unsigned.entryId ||
|
|
452
|
+
entry.hlc.node !== unsigned.authorKeyId ||
|
|
453
|
+
objectIds.length !== unsigned.objectIds.length ||
|
|
454
|
+
objectIds.some((id, index) => unsigned.objectIds[index] !== id)) {
|
|
455
|
+
throw new DeviceSyncError('SYNC_ENTRY_INVALID');
|
|
456
|
+
}
|
|
457
|
+
if (author.revokedAt !== undefined) {
|
|
458
|
+
const revokedAt = Date.parse(author.revokedAt);
|
|
459
|
+
if (entry.hlc.wallMs >= revokedAt ||
|
|
460
|
+
(createdAt !== undefined && Date.parse(createdAt) >= revokedAt + MAX_RELAY_CLOCK_SKEW_MS)) {
|
|
461
|
+
throw new DeviceSyncError('SYNC_AUTHOR_REVOKED');
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
return { ...entry, authorKeyId: unsigned.authorKeyId };
|
|
465
|
+
}
|
|
466
|
+
export function assertSyncLogAdvances(lastSeenSeq, page) {
|
|
467
|
+
let previous = lastSeenSeq;
|
|
468
|
+
for (const entry of page) {
|
|
469
|
+
if (entry.seq <= previous)
|
|
470
|
+
throw new DeviceSyncError('SYNC_LOG_ROLLED_BACK');
|
|
471
|
+
previous = entry.seq;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
export function foldSyncItems(entries) {
|
|
475
|
+
const byItem = new Map();
|
|
476
|
+
for (const entry of entries) {
|
|
477
|
+
const list = byItem.get(entry.itemId) ?? [];
|
|
478
|
+
list.push(entry);
|
|
479
|
+
byItem.set(entry.itemId, list);
|
|
480
|
+
}
|
|
481
|
+
const states = new Map();
|
|
482
|
+
for (const [itemId, list] of byItem) {
|
|
483
|
+
const writes = list.filter((entry) => entry.kind !== 'rewrap');
|
|
484
|
+
const first = writes[0] ?? list[0];
|
|
485
|
+
if (!first)
|
|
486
|
+
continue;
|
|
487
|
+
const namespace = first.namespace;
|
|
488
|
+
const seen = new Set(writes.map((entry) => entry.entryId));
|
|
489
|
+
const named = new Set(writes.flatMap((entry) => entry.parents));
|
|
490
|
+
const rewraps = new Map();
|
|
491
|
+
for (const entry of list) {
|
|
492
|
+
if (entry.kind !== 'rewrap')
|
|
493
|
+
continue;
|
|
494
|
+
const known = rewraps.get(entry.objectId);
|
|
495
|
+
if (!known || compareSyncHlc(entry.hlc, known.hlc) > 0)
|
|
496
|
+
rewraps.set(entry.objectId, { hlc: entry.hlc, dataKey: entry.dataKey });
|
|
497
|
+
}
|
|
498
|
+
const heads = writes
|
|
499
|
+
.filter((entry) => !named.has(entry.entryId) && entry.namespace === namespace)
|
|
500
|
+
.toSorted((left, right) => compareSyncHlc(right.hlc, left.hlc));
|
|
501
|
+
const version = (entry) => {
|
|
502
|
+
if (entry.kind !== 'put')
|
|
503
|
+
return undefined;
|
|
504
|
+
return {
|
|
505
|
+
entryId: entry.entryId,
|
|
506
|
+
path: entry.path,
|
|
507
|
+
objectId: entry.objectId,
|
|
508
|
+
dataKey: rewraps.get(entry.objectId)?.dataKey ?? entry.dataKey,
|
|
509
|
+
plaintextSha256: entry.plaintextSha256,
|
|
510
|
+
size: entry.size,
|
|
511
|
+
...(entry.contentType === undefined ? {} : { contentType: entry.contentType }),
|
|
512
|
+
...(entry.mtimeMs === undefined ? {} : { mtimeMs: entry.mtimeMs }),
|
|
513
|
+
hlc: entry.hlc,
|
|
514
|
+
authorKeyId: entry.authorKeyId,
|
|
515
|
+
};
|
|
516
|
+
};
|
|
517
|
+
const [winner, ...rest] = heads;
|
|
518
|
+
const current = winner ? version(winner) : undefined;
|
|
519
|
+
states.set(itemId, {
|
|
520
|
+
itemId,
|
|
521
|
+
namespace,
|
|
522
|
+
...(current ? { current } : {}),
|
|
523
|
+
conflicts: rest.flatMap((head) => {
|
|
524
|
+
const value = version(head);
|
|
525
|
+
return value ? [value] : [];
|
|
526
|
+
}),
|
|
527
|
+
missingParents: [...named].filter((id) => !seen.has(id)),
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
return states;
|
|
531
|
+
}
|
|
532
|
+
export async function signSyncRequest(input) {
|
|
533
|
+
const seconds = Math.floor(input.now.getTime() / 1000);
|
|
534
|
+
const signature = await signRelayBytes(input.key.privateKey, await requestSigningInput(input.method, input.path, seconds, input.body));
|
|
535
|
+
return `${input.key.keyId}.${seconds}.${signature}`;
|
|
536
|
+
}
|
|
537
|
+
export async function verifySyncRequest(input) {
|
|
538
|
+
const match = /^((?:spk|dpk)_[a-f0-9]{32})\.(\d{1,12})\.([A-Za-z0-9_-]{86})$/.exec(input.header ?? '');
|
|
539
|
+
if (!match)
|
|
540
|
+
throw new DeviceSyncError('SYNC_REQUEST_INVALID');
|
|
541
|
+
const [, keyId = '', secondsText = '', signature = ''] = match;
|
|
542
|
+
const seconds = Number(secondsText);
|
|
543
|
+
if (Math.abs(seconds * 1000 - input.now.getTime()) > MAX_RELAY_CLOCK_SKEW_MS) {
|
|
544
|
+
throw new DeviceSyncError('SYNC_REQUEST_EXPIRED');
|
|
545
|
+
}
|
|
546
|
+
const author = syncAuthor(input.keyring, input.workspaceId, keyId, Infinity);
|
|
547
|
+
if (!(await verifyRelayBytes(author.signingPublicKey, signature, await requestSigningInput(input.method, input.path, seconds, input.body)))) {
|
|
548
|
+
throw new DeviceSyncError('SYNC_SIGNATURE_INVALID');
|
|
549
|
+
}
|
|
550
|
+
return author;
|
|
551
|
+
}
|
|
552
|
+
async function requestSigningInput(method, path, seconds, body) {
|
|
553
|
+
if (!/^[A-Z]{3,7}$/.test(method) || !path.startsWith('/') || /[\s]/.test(path)) {
|
|
554
|
+
throw new DeviceSyncError('SYNC_REQUEST_INVALID');
|
|
555
|
+
}
|
|
556
|
+
return new TextEncoder().encode(`${REQUEST_SIGNATURE_CONTEXT}\n${method}\n${path}\n${seconds}\n${await sha256(body)}`);
|
|
557
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,2 @@
|
|
|
1
|
-
export * from './
|
|
2
|
-
export * from './
|
|
3
|
-
export * from './fixtures.js';
|
|
4
|
-
export * from './authentication.js';
|
|
5
|
-
export * from './acp-remote-sealed-channel.js';
|
|
6
|
-
export declare const packageName = "runtime-gateway-protocol";
|
|
1
|
+
export * from './content-key.js';
|
|
2
|
+
export * from './device-relay.js';
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,2 @@
|
|
|
1
|
-
export * from './
|
|
2
|
-
export * from './
|
|
3
|
-
export * from './fixtures.js';
|
|
4
|
-
export * from './authentication.js';
|
|
5
|
-
export * from './acp-remote-sealed-channel.js';
|
|
6
|
-
export const packageName = 'runtime-gateway-protocol';
|
|
1
|
+
export * from './content-key.js';
|
|
2
|
+
export * from './device-relay.js';
|
package/package.json
CHANGED
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adea-ai/runtime-gateway-protocol",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "1.17.0",
|
|
4
|
+
"description": "Device relay envelopes and workspace content keys shared by the Control Plane and Adea clients.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agents",
|
|
7
|
-
"
|
|
8
|
-
"
|
|
7
|
+
"device-relay",
|
|
8
|
+
"hpke",
|
|
9
9
|
"runtime",
|
|
10
|
-
"schemas",
|
|
11
10
|
"zod"
|
|
12
11
|
],
|
|
13
12
|
"homepage": "https://github.com/adea-ai/control-plane#readme",
|
|
@@ -19,9 +18,7 @@
|
|
|
19
18
|
"directory": "packages/runtime-gateway-protocol"
|
|
20
19
|
},
|
|
21
20
|
"files": [
|
|
22
|
-
"dist"
|
|
23
|
-
"fixtures",
|
|
24
|
-
"schema"
|
|
21
|
+
"dist"
|
|
25
22
|
],
|
|
26
23
|
"type": "module",
|
|
27
24
|
"browser": false,
|
|
@@ -40,8 +37,10 @@
|
|
|
40
37
|
"types": "./dist/device-relay.d.ts",
|
|
41
38
|
"default": "./dist/device-relay.js"
|
|
42
39
|
},
|
|
43
|
-
"./
|
|
44
|
-
|
|
40
|
+
"./device-sync": {
|
|
41
|
+
"types": "./dist/device-sync.d.ts",
|
|
42
|
+
"default": "./dist/device-sync.js"
|
|
43
|
+
}
|
|
45
44
|
},
|
|
46
45
|
"publishConfig": {
|
|
47
46
|
"access": "public",
|
|
@@ -49,15 +48,12 @@
|
|
|
49
48
|
},
|
|
50
49
|
"scripts": {
|
|
51
50
|
"build": "tsc -p tsconfig.json",
|
|
52
|
-
"typecheck": "bun check -p tsconfig.json
|
|
51
|
+
"typecheck": "bun check -p tsconfig.json",
|
|
53
52
|
"lint": "oxlint src",
|
|
54
|
-
"
|
|
55
|
-
"schema:generate": "bun scripts/schema.ts",
|
|
56
|
-
"test": "bun scripts/schema.ts --check && bun test src"
|
|
53
|
+
"test": "bun test src"
|
|
57
54
|
},
|
|
58
55
|
"dependencies": {
|
|
59
|
-
"@adea-ai/contracts": "^
|
|
60
|
-
"@adea-ai/runtime-sdk": "^1.22.0",
|
|
56
|
+
"@adea-ai/contracts": "^4.0.0",
|
|
61
57
|
"@hpke/core": "1.9.0",
|
|
62
58
|
"@hpke/dhkem-x25519": "1.8.0",
|
|
63
59
|
"zod": "4.6.6"
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import type { GatewayCommandEnvelope } from './protocol.js';
|
|
2
|
-
export interface AcpRemoteSealedCarrierChannel {
|
|
3
|
-
readonly currentChannelGeneration: () => number | undefined;
|
|
4
|
-
readonly dispatchSealed: (input: {
|
|
5
|
-
readonly command: GatewayCommandEnvelope;
|
|
6
|
-
readonly signal?: AbortSignal;
|
|
7
|
-
}) => Promise<unknown>;
|
|
8
|
-
readonly pushedInventory: () => Promise<{
|
|
9
|
-
readonly inventory: unknown;
|
|
10
|
-
readonly channelGeneration: number;
|
|
11
|
-
}>;
|
|
12
|
-
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|