@adea-ai/runtime-gateway-protocol 1.15.0 → 1.16.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 +12 -23
- package/dist/device-relay.d.ts +6 -0
- package/dist/device-relay.js +21 -0
- package/dist/device-sync.d.ts +239 -0
- package/dist/device-sync.js +437 -0
- package/dist/index.d.ts +2 -6
- package/dist/index.js +2 -6
- package/package.json +13 -18
- 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,437 @@
|
|
|
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
|
+
export async function sealSyncBlob(dataKey, binding, plaintext) {
|
|
98
|
+
const bound = parseBinding(binding);
|
|
99
|
+
const total = sealedBlobLength(plaintext.byteLength);
|
|
100
|
+
const padded = new Uint8Array(padmeLength(plaintext.byteLength + LENGTH_PREFIX_BYTES));
|
|
101
|
+
new DataView(padded.buffer).setBigUint64(0, BigInt(plaintext.byteLength));
|
|
102
|
+
padded.set(plaintext, LENGTH_PREFIX_BYTES);
|
|
103
|
+
const count = Math.max(1, Math.ceil(padded.byteLength / SYNC_CHUNK_BYTES));
|
|
104
|
+
const key = await importDataKey(dataKey);
|
|
105
|
+
const out = new Uint8Array(total);
|
|
106
|
+
out.set(MAGIC, 0);
|
|
107
|
+
out[4] = SYNC_BLOB_VERSION;
|
|
108
|
+
new DataView(out.buffer).setUint32(8, count);
|
|
109
|
+
let offset = HEADER_BYTES;
|
|
110
|
+
for (let index = 0; index < count; index += 1) {
|
|
111
|
+
const chunk = padded.subarray(index * SYNC_CHUNK_BYTES, (index + 1) * SYNC_CHUNK_BYTES);
|
|
112
|
+
const sealed = new Uint8Array(await globalThis.crypto.subtle.encrypt({ name: 'AES-GCM', iv: chunkNonce(index), additionalData: chunkAad(bound, index, count) }, key, chunk));
|
|
113
|
+
out.set(sealed, offset);
|
|
114
|
+
offset += sealed.byteLength;
|
|
115
|
+
}
|
|
116
|
+
padded.fill(0);
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
export async function openSyncBlob(dataKey, binding, sealed) {
|
|
120
|
+
const bound = parseBinding(binding);
|
|
121
|
+
if (sealed.byteLength < HEADER_BYTES + AEAD_TAG_BYTES ||
|
|
122
|
+
MAGIC.some((byte, index) => sealed[index] !== byte) ||
|
|
123
|
+
sealed[4] !== SYNC_BLOB_VERSION ||
|
|
124
|
+
sealed[5] !== 0 ||
|
|
125
|
+
sealed[6] !== 0 ||
|
|
126
|
+
sealed[7] !== 0) {
|
|
127
|
+
throw new DeviceSyncError('SYNC_BLOB_INVALID');
|
|
128
|
+
}
|
|
129
|
+
const count = new DataView(sealed.buffer, sealed.byteOffset, sealed.byteLength).getUint32(8);
|
|
130
|
+
const body = sealed.byteLength - HEADER_BYTES - count * AEAD_TAG_BYTES;
|
|
131
|
+
if (count < 1 ||
|
|
132
|
+
body < LENGTH_PREFIX_BYTES ||
|
|
133
|
+
body > padmeLength(MAX_SYNC_OBJECT_BYTES + LENGTH_PREFIX_BYTES) ||
|
|
134
|
+
Math.max(1, Math.ceil(body / SYNC_CHUNK_BYTES)) !== count) {
|
|
135
|
+
throw new DeviceSyncError('SYNC_BLOB_INVALID');
|
|
136
|
+
}
|
|
137
|
+
const key = await importDataKey(dataKey);
|
|
138
|
+
const padded = new Uint8Array(body);
|
|
139
|
+
let offset = HEADER_BYTES;
|
|
140
|
+
for (let index = 0; index < count; index += 1) {
|
|
141
|
+
const plainBytes = Math.min(SYNC_CHUNK_BYTES, body - index * SYNC_CHUNK_BYTES);
|
|
142
|
+
const chunk = sealed.subarray(offset, offset + plainBytes + AEAD_TAG_BYTES);
|
|
143
|
+
offset += chunk.byteLength;
|
|
144
|
+
let opened;
|
|
145
|
+
try {
|
|
146
|
+
opened = await globalThis.crypto.subtle.decrypt({ name: 'AES-GCM', iv: chunkNonce(index), additionalData: chunkAad(bound, index, count) }, key, Uint8Array.from(chunk));
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
throw new DeviceSyncError('SYNC_DECRYPTION_FAILED');
|
|
150
|
+
}
|
|
151
|
+
padded.set(new Uint8Array(opened), index * SYNC_CHUNK_BYTES);
|
|
152
|
+
}
|
|
153
|
+
const length = Number(new DataView(padded.buffer).getBigUint64(0));
|
|
154
|
+
if (length > body - LENGTH_PREFIX_BYTES ||
|
|
155
|
+
padmeLength(length + LENGTH_PREFIX_BYTES) !== body ||
|
|
156
|
+
padded.subarray(LENGTH_PREFIX_BYTES + length).some((byte) => byte !== 0)) {
|
|
157
|
+
throw new DeviceSyncError('SYNC_BLOB_INVALID');
|
|
158
|
+
}
|
|
159
|
+
return padded.slice(LENGTH_PREFIX_BYTES, LENGTH_PREFIX_BYTES + length);
|
|
160
|
+
}
|
|
161
|
+
export async function sealSyncDataKey(contentKey, binding, dataKey) {
|
|
162
|
+
const bound = parseBinding(binding);
|
|
163
|
+
if (dataKey.byteLength !== DATA_KEY_BYTES)
|
|
164
|
+
throw new DeviceSyncError('SYNC_KEY_UNAVAILABLE');
|
|
165
|
+
return sealContent(contentKey, { workspaceId: bound.workspaceId, messageId: bound.objectId, field: DEK_FIELD }, encodeBase64Url(dataKey));
|
|
166
|
+
}
|
|
167
|
+
export async function openSyncDataKey(contentKey, binding, sealed) {
|
|
168
|
+
const bound = parseBinding(binding);
|
|
169
|
+
let encoded;
|
|
170
|
+
try {
|
|
171
|
+
encoded = await openContent(contentKey, { workspaceId: bound.workspaceId, messageId: bound.objectId, field: DEK_FIELD }, sealed);
|
|
172
|
+
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
throw new DeviceSyncError(error instanceof ContentKeyError && error.code === 'CONTENT_KEY_VERSION_MISMATCH'
|
|
175
|
+
? 'SYNC_KEY_UNAVAILABLE'
|
|
176
|
+
: 'SYNC_DECRYPTION_FAILED');
|
|
177
|
+
}
|
|
178
|
+
let raw;
|
|
179
|
+
try {
|
|
180
|
+
raw = decodeBase64Url(encoded);
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
throw new DeviceSyncError('SYNC_DECRYPTION_FAILED');
|
|
184
|
+
}
|
|
185
|
+
if (raw.byteLength !== DATA_KEY_BYTES)
|
|
186
|
+
throw new DeviceSyncError('SYNC_DECRYPTION_FAILED');
|
|
187
|
+
return raw;
|
|
188
|
+
}
|
|
189
|
+
export const SyncNamespaceSchema = z.enum(['files', 'sessions', 'artifacts']);
|
|
190
|
+
export const SyncHlcSchema = z
|
|
191
|
+
.object({
|
|
192
|
+
wallMs: z.number().int().min(0),
|
|
193
|
+
counter: z.number().int().min(0).max(0xffff),
|
|
194
|
+
node: AuthorKeyIdSchema,
|
|
195
|
+
})
|
|
196
|
+
.strict();
|
|
197
|
+
export function nextSyncHlc(previous, nowMs, node) {
|
|
198
|
+
if (!previous || nowMs > previous.wallMs)
|
|
199
|
+
return SyncHlcSchema.parse({ wallMs: nowMs, counter: 0, node });
|
|
200
|
+
return SyncHlcSchema.parse({ wallMs: previous.wallMs, counter: previous.counter + 1, node });
|
|
201
|
+
}
|
|
202
|
+
export function observeSyncHlc(local, seen) {
|
|
203
|
+
return local === undefined || compareSyncHlc(seen, local) > 0 ? seen : local;
|
|
204
|
+
}
|
|
205
|
+
export function compareSyncHlc(left, right) {
|
|
206
|
+
if (left.wallMs !== right.wallMs)
|
|
207
|
+
return left.wallMs < right.wallMs ? -1 : 1;
|
|
208
|
+
if (left.counter !== right.counter)
|
|
209
|
+
return left.counter < right.counter ? -1 : 1;
|
|
210
|
+
return left.node < right.node ? -1 : left.node > right.node ? 1 : 0;
|
|
211
|
+
}
|
|
212
|
+
const SyncPathSchema = z
|
|
213
|
+
.string()
|
|
214
|
+
.min(1)
|
|
215
|
+
.max(1024)
|
|
216
|
+
.refine((path) => !path.startsWith('/') &&
|
|
217
|
+
!path.includes('\\') &&
|
|
218
|
+
!path.includes('\u0000') &&
|
|
219
|
+
path.split('/').every((part) => part !== '' && part !== '.' && part !== '..'), 'a relative path without empty, . or .. segments');
|
|
220
|
+
const EntryCommonSchema = {
|
|
221
|
+
entryVersion: z.literal(SYNC_ENTRY_VERSION),
|
|
222
|
+
entryId: SyncEntryIdSchema,
|
|
223
|
+
namespace: SyncNamespaceSchema,
|
|
224
|
+
itemId: SyncItemIdSchema,
|
|
225
|
+
hlc: SyncHlcSchema,
|
|
226
|
+
};
|
|
227
|
+
export const SyncPutEntrySchema = z
|
|
228
|
+
.object({
|
|
229
|
+
...EntryCommonSchema,
|
|
230
|
+
kind: z.literal('put'),
|
|
231
|
+
path: SyncPathSchema,
|
|
232
|
+
objectId: SyncObjectIdSchema,
|
|
233
|
+
dataKey: ContentSealSchema,
|
|
234
|
+
plaintextSha256: Sha256Schema,
|
|
235
|
+
size: z.number().int().min(0).max(MAX_SYNC_OBJECT_BYTES),
|
|
236
|
+
contentType: z.string().min(1).max(255).optional(),
|
|
237
|
+
mtimeMs: z.number().int().min(0).optional(),
|
|
238
|
+
parents: z.array(SyncEntryIdSchema).max(16),
|
|
239
|
+
})
|
|
240
|
+
.strict();
|
|
241
|
+
export const SyncDeleteEntrySchema = z
|
|
242
|
+
.object({
|
|
243
|
+
...EntryCommonSchema,
|
|
244
|
+
kind: z.literal('delete'),
|
|
245
|
+
parents: z.array(SyncEntryIdSchema).min(1).max(16),
|
|
246
|
+
})
|
|
247
|
+
.strict();
|
|
248
|
+
export const SyncRewrapEntrySchema = z
|
|
249
|
+
.object({
|
|
250
|
+
...EntryCommonSchema,
|
|
251
|
+
kind: z.literal('rewrap'),
|
|
252
|
+
objectId: SyncObjectIdSchema,
|
|
253
|
+
dataKey: ContentSealSchema,
|
|
254
|
+
})
|
|
255
|
+
.strict();
|
|
256
|
+
export const SyncEntrySchema = z.discriminatedUnion('kind', [
|
|
257
|
+
SyncPutEntrySchema,
|
|
258
|
+
SyncDeleteEntrySchema,
|
|
259
|
+
SyncRewrapEntrySchema,
|
|
260
|
+
]);
|
|
261
|
+
function entrySigningInput(workspaceId, entry) {
|
|
262
|
+
return new TextEncoder().encode(`${ENTRY_SIGNATURE_CONTEXT}\n${canonicalJsonStringify({ workspaceId, ...entry })}`);
|
|
263
|
+
}
|
|
264
|
+
function entryObjectIds(entry) {
|
|
265
|
+
return entry.kind === 'delete' ? [] : [entry.objectId];
|
|
266
|
+
}
|
|
267
|
+
export async function sealSyncEntry(input) {
|
|
268
|
+
const parsed = SyncEntrySchema.safeParse(input.entry);
|
|
269
|
+
if (!parsed.success || parsed.data.hlc.node !== input.author.keyId) {
|
|
270
|
+
throw new DeviceSyncError('SYNC_ENTRY_INVALID');
|
|
271
|
+
}
|
|
272
|
+
const plaintext = canonicalJsonStringify(parsed.data);
|
|
273
|
+
if (new TextEncoder().encode(plaintext).byteLength > MAX_SYNC_ENTRY_BYTES) {
|
|
274
|
+
throw new DeviceSyncError('SYNC_ENTRY_TOO_LARGE');
|
|
275
|
+
}
|
|
276
|
+
const seal = await sealContent(input.contentKey, { workspaceId: input.workspaceId, messageId: parsed.data.entryId, field: ENTRY_FIELD }, plaintext);
|
|
277
|
+
const unsigned = {
|
|
278
|
+
entryId: parsed.data.entryId,
|
|
279
|
+
authorKeyId: input.author.keyId,
|
|
280
|
+
objectIds: entryObjectIds(parsed.data),
|
|
281
|
+
ckv: seal.ckv,
|
|
282
|
+
nonce: seal.nonce,
|
|
283
|
+
ciphertext: seal.ciphertext,
|
|
284
|
+
};
|
|
285
|
+
const signature = await signRelayBytes(input.author.privateKey, entrySigningInput(input.workspaceId, unsigned));
|
|
286
|
+
return SignedSyncEntrySchema.parse({ ...unsigned, signature });
|
|
287
|
+
}
|
|
288
|
+
export function syncAuthor(keyring, workspaceId, keyId, at) {
|
|
289
|
+
if (keyring.workspaceId !== workspaceId)
|
|
290
|
+
throw new DeviceSyncError('SYNC_AUTHOR_UNKNOWN');
|
|
291
|
+
const author = keyring.entries.find((entry) => entry.senderKeyId === keyId);
|
|
292
|
+
if (!author)
|
|
293
|
+
throw new DeviceSyncError('SYNC_AUTHOR_UNKNOWN');
|
|
294
|
+
if (author.revokedAt !== undefined && Date.parse(author.revokedAt) <= at) {
|
|
295
|
+
throw new DeviceSyncError('SYNC_AUTHOR_REVOKED');
|
|
296
|
+
}
|
|
297
|
+
return author;
|
|
298
|
+
}
|
|
299
|
+
export async function openSyncEntry(input) {
|
|
300
|
+
const stored = SignedSyncEntrySchema.extend({
|
|
301
|
+
seq: z.number().int().min(1).optional(),
|
|
302
|
+
createdAt: z.iso.datetime().optional(),
|
|
303
|
+
})
|
|
304
|
+
.strict()
|
|
305
|
+
.safeParse(input.entry);
|
|
306
|
+
if (!stored.success)
|
|
307
|
+
throw new DeviceSyncError('SYNC_ENTRY_INVALID');
|
|
308
|
+
const { signature, seq: _seq, createdAt, ...unsigned } = stored.data;
|
|
309
|
+
const author = syncAuthor(input.keyring, input.workspaceId, unsigned.authorKeyId, -Infinity);
|
|
310
|
+
if (!(await verifyRelayBytes(author.signingPublicKey, signature, entrySigningInput(input.workspaceId, unsigned)))) {
|
|
311
|
+
throw new DeviceSyncError('SYNC_SIGNATURE_INVALID');
|
|
312
|
+
}
|
|
313
|
+
const key = await input.contentKey(unsigned.ckv);
|
|
314
|
+
if (!key)
|
|
315
|
+
throw new DeviceSyncError('SYNC_KEY_UNAVAILABLE');
|
|
316
|
+
let plaintext;
|
|
317
|
+
try {
|
|
318
|
+
plaintext = await openContent(key, { workspaceId: input.workspaceId, messageId: unsigned.entryId, field: ENTRY_FIELD }, { ckv: unsigned.ckv, nonce: unsigned.nonce, ciphertext: unsigned.ciphertext });
|
|
319
|
+
}
|
|
320
|
+
catch {
|
|
321
|
+
throw new DeviceSyncError('SYNC_DECRYPTION_FAILED');
|
|
322
|
+
}
|
|
323
|
+
let entry;
|
|
324
|
+
try {
|
|
325
|
+
entry = SyncEntrySchema.parse(JSON.parse(plaintext));
|
|
326
|
+
}
|
|
327
|
+
catch {
|
|
328
|
+
throw new DeviceSyncError('SYNC_ENTRY_INVALID');
|
|
329
|
+
}
|
|
330
|
+
const objectIds = entryObjectIds(entry);
|
|
331
|
+
if (entry.entryId !== unsigned.entryId ||
|
|
332
|
+
entry.hlc.node !== unsigned.authorKeyId ||
|
|
333
|
+
objectIds.length !== unsigned.objectIds.length ||
|
|
334
|
+
objectIds.some((id, index) => unsigned.objectIds[index] !== id)) {
|
|
335
|
+
throw new DeviceSyncError('SYNC_ENTRY_INVALID');
|
|
336
|
+
}
|
|
337
|
+
if (author.revokedAt !== undefined) {
|
|
338
|
+
const revokedAt = Date.parse(author.revokedAt);
|
|
339
|
+
if (entry.hlc.wallMs >= revokedAt ||
|
|
340
|
+
(createdAt !== undefined && Date.parse(createdAt) >= revokedAt + MAX_RELAY_CLOCK_SKEW_MS)) {
|
|
341
|
+
throw new DeviceSyncError('SYNC_AUTHOR_REVOKED');
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
return { ...entry, authorKeyId: unsigned.authorKeyId };
|
|
345
|
+
}
|
|
346
|
+
export function assertSyncLogAdvances(lastSeenSeq, page) {
|
|
347
|
+
let previous = lastSeenSeq;
|
|
348
|
+
for (const entry of page) {
|
|
349
|
+
if (entry.seq <= previous)
|
|
350
|
+
throw new DeviceSyncError('SYNC_LOG_ROLLED_BACK');
|
|
351
|
+
previous = entry.seq;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
export function foldSyncItems(entries) {
|
|
355
|
+
const byItem = new Map();
|
|
356
|
+
for (const entry of entries) {
|
|
357
|
+
const list = byItem.get(entry.itemId) ?? [];
|
|
358
|
+
list.push(entry);
|
|
359
|
+
byItem.set(entry.itemId, list);
|
|
360
|
+
}
|
|
361
|
+
const states = new Map();
|
|
362
|
+
for (const [itemId, list] of byItem) {
|
|
363
|
+
const writes = list.filter((entry) => entry.kind !== 'rewrap');
|
|
364
|
+
const first = writes[0] ?? list[0];
|
|
365
|
+
if (!first)
|
|
366
|
+
continue;
|
|
367
|
+
const namespace = first.namespace;
|
|
368
|
+
const seen = new Set(writes.map((entry) => entry.entryId));
|
|
369
|
+
const named = new Set(writes.flatMap((entry) => entry.parents));
|
|
370
|
+
const rewraps = new Map();
|
|
371
|
+
for (const entry of list) {
|
|
372
|
+
if (entry.kind !== 'rewrap')
|
|
373
|
+
continue;
|
|
374
|
+
const known = rewraps.get(entry.objectId);
|
|
375
|
+
if (!known || compareSyncHlc(entry.hlc, known.hlc) > 0)
|
|
376
|
+
rewraps.set(entry.objectId, { hlc: entry.hlc, dataKey: entry.dataKey });
|
|
377
|
+
}
|
|
378
|
+
const heads = writes
|
|
379
|
+
.filter((entry) => !named.has(entry.entryId) && entry.namespace === namespace)
|
|
380
|
+
.toSorted((left, right) => compareSyncHlc(right.hlc, left.hlc));
|
|
381
|
+
const version = (entry) => {
|
|
382
|
+
if (entry.kind !== 'put')
|
|
383
|
+
return undefined;
|
|
384
|
+
return {
|
|
385
|
+
entryId: entry.entryId,
|
|
386
|
+
path: entry.path,
|
|
387
|
+
objectId: entry.objectId,
|
|
388
|
+
dataKey: rewraps.get(entry.objectId)?.dataKey ?? entry.dataKey,
|
|
389
|
+
plaintextSha256: entry.plaintextSha256,
|
|
390
|
+
size: entry.size,
|
|
391
|
+
...(entry.contentType === undefined ? {} : { contentType: entry.contentType }),
|
|
392
|
+
...(entry.mtimeMs === undefined ? {} : { mtimeMs: entry.mtimeMs }),
|
|
393
|
+
hlc: entry.hlc,
|
|
394
|
+
authorKeyId: entry.authorKeyId,
|
|
395
|
+
};
|
|
396
|
+
};
|
|
397
|
+
const [winner, ...rest] = heads;
|
|
398
|
+
const current = winner ? version(winner) : undefined;
|
|
399
|
+
states.set(itemId, {
|
|
400
|
+
itemId,
|
|
401
|
+
namespace,
|
|
402
|
+
...(current ? { current } : {}),
|
|
403
|
+
conflicts: rest.flatMap((head) => {
|
|
404
|
+
const value = version(head);
|
|
405
|
+
return value ? [value] : [];
|
|
406
|
+
}),
|
|
407
|
+
missingParents: [...named].filter((id) => !seen.has(id)),
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
return states;
|
|
411
|
+
}
|
|
412
|
+
export async function signSyncRequest(input) {
|
|
413
|
+
const seconds = Math.floor(input.now.getTime() / 1000);
|
|
414
|
+
const signature = await signRelayBytes(input.key.privateKey, await requestSigningInput(input.method, input.path, seconds, input.body));
|
|
415
|
+
return `${input.key.keyId}.${seconds}.${signature}`;
|
|
416
|
+
}
|
|
417
|
+
export async function verifySyncRequest(input) {
|
|
418
|
+
const match = /^((?:spk|dpk)_[a-f0-9]{32})\.(\d{1,12})\.([A-Za-z0-9_-]{86})$/.exec(input.header ?? '');
|
|
419
|
+
if (!match)
|
|
420
|
+
throw new DeviceSyncError('SYNC_REQUEST_INVALID');
|
|
421
|
+
const [, keyId = '', secondsText = '', signature = ''] = match;
|
|
422
|
+
const seconds = Number(secondsText);
|
|
423
|
+
if (Math.abs(seconds * 1000 - input.now.getTime()) > MAX_RELAY_CLOCK_SKEW_MS) {
|
|
424
|
+
throw new DeviceSyncError('SYNC_REQUEST_EXPIRED');
|
|
425
|
+
}
|
|
426
|
+
const author = syncAuthor(input.keyring, input.workspaceId, keyId, Infinity);
|
|
427
|
+
if (!(await verifyRelayBytes(author.signingPublicKey, signature, await requestSigningInput(input.method, input.path, seconds, input.body)))) {
|
|
428
|
+
throw new DeviceSyncError('SYNC_SIGNATURE_INVALID');
|
|
429
|
+
}
|
|
430
|
+
return author;
|
|
431
|
+
}
|
|
432
|
+
async function requestSigningInput(method, path, seconds, body) {
|
|
433
|
+
if (!/^[A-Z]{3,7}$/.test(method) || !path.startsWith('/') || /[\s]/.test(path)) {
|
|
434
|
+
throw new DeviceSyncError('SYNC_REQUEST_INVALID');
|
|
435
|
+
}
|
|
436
|
+
return new TextEncoder().encode(`${REQUEST_SIGNATURE_CONTEXT}\n${method}\n${path}\n${seconds}\n${await sha256(body)}`);
|
|
437
|
+
}
|
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.16.1",
|
|
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,24 +37,22 @@
|
|
|
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
|
-
"access": "public"
|
|
48
|
-
"provenance": true
|
|
46
|
+
"access": "public"
|
|
49
47
|
},
|
|
50
48
|
"scripts": {
|
|
51
49
|
"build": "tsc -p tsconfig.json",
|
|
52
|
-
"typecheck": "bun check -p tsconfig.json
|
|
50
|
+
"typecheck": "bun check -p tsconfig.json",
|
|
53
51
|
"lint": "oxlint src",
|
|
54
|
-
"
|
|
55
|
-
"schema:generate": "bun scripts/schema.ts",
|
|
56
|
-
"test": "bun scripts/schema.ts --check && bun test src"
|
|
52
|
+
"test": "bun test src"
|
|
57
53
|
},
|
|
58
54
|
"dependencies": {
|
|
59
|
-
"@adea-ai/contracts": "^
|
|
60
|
-
"@adea-ai/runtime-sdk": "^1.22.0",
|
|
55
|
+
"@adea-ai/contracts": "^3.0.1",
|
|
61
56
|
"@hpke/core": "1.9.0",
|
|
62
57
|
"@hpke/dhkem-x25519": "1.8.0",
|
|
63
58
|
"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 {};
|
package/dist/authentication.d.ts
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import { z } from 'zod';
|
|
2
|
-
export declare const RuntimeNodeIdSchema: z.ZodString;
|
|
3
|
-
export declare const RuntimeNodeWorkspaceIdSchema: z.ZodString;
|
|
4
|
-
export declare const RuntimeNodeCredentialClaimsSchema: z.ZodObject<{
|
|
5
|
-
schemaVersion: z.ZodLiteral<1>;
|
|
6
|
-
credentialKind: z.ZodLiteral<"runtime_node">;
|
|
7
|
-
credentialId: z.ZodString;
|
|
8
|
-
issuer: z.ZodURL;
|
|
9
|
-
audience: z.ZodString;
|
|
10
|
-
nodeId: z.ZodString;
|
|
11
|
-
workspaceId: z.ZodString;
|
|
12
|
-
keyId: z.ZodString;
|
|
13
|
-
proofKeyThumbprint: z.ZodString;
|
|
14
|
-
revocationVersion: z.ZodNumber;
|
|
15
|
-
channelGeneration: z.ZodNumber;
|
|
16
|
-
issuedAt: z.ZodISODateTime;
|
|
17
|
-
expiresAt: z.ZodISODateTime;
|
|
18
|
-
}, z.core.$strict>;
|
|
19
|
-
export type RuntimeNodeCredentialClaims = z.output<typeof RuntimeNodeCredentialClaimsSchema>;
|
|
20
|
-
export declare const RuntimeNodeAuthenticationAttemptSchema: z.ZodObject<{
|
|
21
|
-
credential: z.ZodString;
|
|
22
|
-
proof: z.ZodObject<{
|
|
23
|
-
challenge: z.ZodString;
|
|
24
|
-
signature: z.ZodString;
|
|
25
|
-
}, z.core.$strict>;
|
|
26
|
-
}, z.core.$strict>;
|
|
27
|
-
export type RuntimeNodeAuthenticationAttempt = z.output<typeof RuntimeNodeAuthenticationAttemptSchema>;
|
|
28
|
-
export declare class RuntimeNodeIdentityValidationError extends Error {
|
|
29
|
-
readonly reason: 'credential' | 'proof';
|
|
30
|
-
constructor(reason: 'credential' | 'proof');
|
|
31
|
-
}
|
|
32
|
-
export type RuntimeNodeCredentialConsumptionResult = 'consumed' | 'replayed' | 'revoked' | 'expired' | 'unknown';
|
|
33
|
-
export declare function runtimeNodeWebSocketChallenge(secWebSocketKey: string): string;
|
|
34
|
-
export interface RuntimeNodeIdentityValidationPort {
|
|
35
|
-
verify(attempt: RuntimeNodeAuthenticationAttempt): Promise<unknown>;
|
|
36
|
-
isRevoked(credentialId: string, revocationVersion: number): Promise<boolean>;
|
|
37
|
-
subscribeRevocations(listener: (credentialId: string) => void): () => void;
|
|
38
|
-
}
|
|
39
|
-
export type RuntimeNodeIdentityInvalidation = {
|
|
40
|
-
readonly kind: 'credential';
|
|
41
|
-
readonly credentialId: string;
|
|
42
|
-
} | {
|
|
43
|
-
readonly kind: 'key';
|
|
44
|
-
readonly keyId: string;
|
|
45
|
-
};
|
package/dist/authentication.js
DELETED
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
import { z } from 'zod';
|
|
2
|
-
const TimestampSchema = z.iso.datetime();
|
|
3
|
-
const compactPart = z
|
|
4
|
-
.string()
|
|
5
|
-
.min(2)
|
|
6
|
-
.max(4096)
|
|
7
|
-
.regex(/^[A-Za-z0-9_-]+$/);
|
|
8
|
-
export const RuntimeNodeIdSchema = z.string().regex(/^rnr_[0-9A-HJKMNP-TV-Z]{26}$/);
|
|
9
|
-
export const RuntimeNodeWorkspaceIdSchema = z.string().regex(/^wsp_[0-9A-HJKMNP-TV-Z]{26}$/);
|
|
10
|
-
export const RuntimeNodeCredentialClaimsSchema = z
|
|
11
|
-
.object({
|
|
12
|
-
schemaVersion: z.literal(1),
|
|
13
|
-
credentialKind: z.literal('runtime_node'),
|
|
14
|
-
credentialId: z
|
|
15
|
-
.string()
|
|
16
|
-
.min(8)
|
|
17
|
-
.max(128)
|
|
18
|
-
.regex(/^rgc_[A-Za-z0-9_-]+$/),
|
|
19
|
-
issuer: z.url().max(512),
|
|
20
|
-
audience: z.string().min(3).max(256),
|
|
21
|
-
nodeId: RuntimeNodeIdSchema,
|
|
22
|
-
workspaceId: RuntimeNodeWorkspaceIdSchema,
|
|
23
|
-
keyId: z
|
|
24
|
-
.string()
|
|
25
|
-
.min(4)
|
|
26
|
-
.max(128)
|
|
27
|
-
.regex(/^rgk_[A-Za-z0-9_-]+$/),
|
|
28
|
-
proofKeyThumbprint: z.string().regex(/^sha256:[a-f0-9]{64}$/),
|
|
29
|
-
revocationVersion: z.number().int().positive(),
|
|
30
|
-
channelGeneration: z.number().int().positive(),
|
|
31
|
-
issuedAt: TimestampSchema,
|
|
32
|
-
expiresAt: TimestampSchema,
|
|
33
|
-
})
|
|
34
|
-
.strict()
|
|
35
|
-
.refine((claims) => Date.parse(claims.expiresAt) > Date.parse(claims.issuedAt), {
|
|
36
|
-
message: 'Credential expiry must follow issuance',
|
|
37
|
-
path: ['expiresAt'],
|
|
38
|
-
});
|
|
39
|
-
export const RuntimeNodeAuthenticationAttemptSchema = z
|
|
40
|
-
.object({
|
|
41
|
-
credential: z
|
|
42
|
-
.string()
|
|
43
|
-
.min(32)
|
|
44
|
-
.max(16_384)
|
|
45
|
-
.refine((value) => value.split('.').length === 3),
|
|
46
|
-
proof: z
|
|
47
|
-
.object({
|
|
48
|
-
challenge: z
|
|
49
|
-
.string()
|
|
50
|
-
.min(16)
|
|
51
|
-
.max(256)
|
|
52
|
-
.regex(/^[A-Za-z0-9._:-]+$/),
|
|
53
|
-
signature: compactPart,
|
|
54
|
-
})
|
|
55
|
-
.strict(),
|
|
56
|
-
})
|
|
57
|
-
.strict();
|
|
58
|
-
export class RuntimeNodeIdentityValidationError extends Error {
|
|
59
|
-
reason;
|
|
60
|
-
constructor(reason) {
|
|
61
|
-
super('RuntimeNode identity validation failed');
|
|
62
|
-
this.reason = reason;
|
|
63
|
-
this.name = 'RuntimeNodeIdentityValidationError';
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
export function runtimeNodeWebSocketChallenge(secWebSocketKey) {
|
|
67
|
-
if (!/^[A-Za-z0-9+/]{22}==$/.test(secWebSocketKey)) {
|
|
68
|
-
throw new Error('RUNTIME_NODE_WEBSOCKET_KEY_INVALID');
|
|
69
|
-
}
|
|
70
|
-
return secWebSocketKey.slice(0, -2).replaceAll('+', '-').replaceAll('/', '_');
|
|
71
|
-
}
|
package/dist/emulator.d.ts
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import { type GatewayAcknowledgementEnvelope, type GatewayResultEnvelope } from './protocol.js';
|
|
2
|
-
export interface ReferenceRuntimeNodeOptions {
|
|
3
|
-
readonly maxLedgerEntries?: number;
|
|
4
|
-
readonly now?: () => Date;
|
|
5
|
-
}
|
|
6
|
-
export declare class GatewayProtocolError extends Error {
|
|
7
|
-
readonly code: string;
|
|
8
|
-
constructor(code: string);
|
|
9
|
-
}
|
|
10
|
-
export declare class ReferenceRuntimeNode {
|
|
11
|
-
#private;
|
|
12
|
-
constructor(options?: ReferenceRuntimeNodeOptions);
|
|
13
|
-
observe(envelopeValue: unknown): string;
|
|
14
|
-
lastObservedSequence(): number;
|
|
15
|
-
receive(commandValue: unknown): {
|
|
16
|
-
readonly ack: GatewayAcknowledgementEnvelope;
|
|
17
|
-
readonly result?: GatewayResultEnvelope;
|
|
18
|
-
};
|
|
19
|
-
effectCount(commandId: string): number;
|
|
20
|
-
}
|
|
21
|
-
export declare function runGatewayProtocolConformance(): {
|
|
22
|
-
readonly scenarios: 9;
|
|
23
|
-
readonly passed: 9;
|
|
24
|
-
};
|