@adea-ai/runtime-gateway-protocol 1.11.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,346 @@
1
+ import { z } from 'zod';
2
+ export declare const RELAY_HPKE_SUITE: 'DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_AES_128_GCM';
3
+ export declare const MAX_RELAY_CIPHERTEXT_BYTES: number;
4
+ export declare const MAX_RELAY_CLOCK_SKEW_MS: number;
5
+ export declare const AUTHENTICATED_RELAY_ENVELOPE_VERSION: 2;
6
+ export declare const MAX_AUTHENTICATED_RELAY_COMMAND_LIFETIME_MS: number;
7
+ export declare const MAX_AUTHENTICATED_RELAY_RESULT_LIFETIME_MS: number;
8
+ export declare const AuthenticatedRelayCommandTypeSchema: z.ZodEnum<{
9
+ create_execution: "create_execution";
10
+ device_request: "device_request";
11
+ metadata_command: "metadata_command";
12
+ submit_input: "submit_input";
13
+ }>;
14
+ export declare const AuthenticatedRelayResultTypeSchema: z.ZodEnum<{
15
+ device_response: "device_response";
16
+ execution_result: "execution_result";
17
+ interaction_result: "interaction_result";
18
+ metadata_result: "metadata_result";
19
+ }>;
20
+ export declare const RelayRejectionCodeSchema: z.ZodEnum<{
21
+ RELAY_DEVICE_OFFLINE: "RELAY_DEVICE_OFFLINE";
22
+ RELAY_ENVELOPE_DECRYPTION_FAILED: "RELAY_ENVELOPE_DECRYPTION_FAILED";
23
+ RELAY_ENVELOPE_DIGEST_MISMATCH: "RELAY_ENVELOPE_DIGEST_MISMATCH";
24
+ RELAY_ENVELOPE_EXPIRED: "RELAY_ENVELOPE_EXPIRED";
25
+ RELAY_ENVELOPE_INVALID: "RELAY_ENVELOPE_INVALID";
26
+ RELAY_ENVELOPE_KEY_UNAVAILABLE: "RELAY_ENVELOPE_KEY_UNAVAILABLE";
27
+ RELAY_ENVELOPE_LIFETIME_INVALID: "RELAY_ENVELOPE_LIFETIME_INVALID";
28
+ RELAY_ENVELOPE_REPLAYED: "RELAY_ENVELOPE_REPLAYED";
29
+ RELAY_ENVELOPE_TOO_LARGE: "RELAY_ENVELOPE_TOO_LARGE";
30
+ RELAY_KEYRING_INVALID: "RELAY_KEYRING_INVALID";
31
+ RELAY_SENDER_REVOKED: "RELAY_SENDER_REVOKED";
32
+ RELAY_SENDER_UNAUTHENTICATED: "RELAY_SENDER_UNAUTHENTICATED";
33
+ RELAY_SIGNATURE_INVALID: "RELAY_SIGNATURE_INVALID";
34
+ RELAY_TARGET_MISMATCH: "RELAY_TARGET_MISMATCH";
35
+ }>;
36
+ export type RelayRejectionCode = z.infer<typeof RelayRejectionCodeSchema>;
37
+ export declare class AuthenticatedRelayError extends Error {
38
+ readonly code: RelayRejectionCode;
39
+ constructor(code: RelayRejectionCode);
40
+ }
41
+ export declare const AuthenticatedRelayCommandHeaderSchema: z.ZodObject<{
42
+ envelopeVersion: z.ZodLiteral<2>;
43
+ suite: z.ZodLiteral<"DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_AES_128_GCM">;
44
+ keyId: z.ZodString;
45
+ workspaceId: z.ZodString;
46
+ targetDeviceId: z.ZodString;
47
+ commandId: z.ZodString;
48
+ payloadSchemaVersion: z.ZodNumber;
49
+ issuedAt: z.ZodISODateTime;
50
+ expiresAt: z.ZodISODateTime;
51
+ contentDigest: z.ZodString;
52
+ senderKeyId: z.ZodString;
53
+ senderPrincipalId: z.ZodString;
54
+ nonce: z.ZodString;
55
+ direction: z.ZodLiteral<"command">;
56
+ payloadType: z.ZodEnum<{
57
+ create_execution: "create_execution";
58
+ device_request: "device_request";
59
+ metadata_command: "metadata_command";
60
+ submit_input: "submit_input";
61
+ }>;
62
+ returnKeyId: z.ZodString;
63
+ returnPublicKey: z.ZodString;
64
+ }, z.core.$strict>;
65
+ export declare const AuthenticatedRelayResultHeaderSchema: z.ZodObject<{
66
+ envelopeVersion: z.ZodLiteral<2>;
67
+ suite: z.ZodLiteral<"DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_AES_128_GCM">;
68
+ keyId: z.ZodString;
69
+ workspaceId: z.ZodString;
70
+ targetDeviceId: z.ZodString;
71
+ commandId: z.ZodString;
72
+ payloadSchemaVersion: z.ZodNumber;
73
+ issuedAt: z.ZodISODateTime;
74
+ expiresAt: z.ZodISODateTime;
75
+ contentDigest: z.ZodString;
76
+ senderKeyId: z.ZodString;
77
+ senderPrincipalId: z.ZodString;
78
+ nonce: z.ZodString;
79
+ direction: z.ZodLiteral<"result">;
80
+ payloadType: z.ZodEnum<{
81
+ device_response: "device_response";
82
+ execution_result: "execution_result";
83
+ interaction_result: "interaction_result";
84
+ metadata_result: "metadata_result";
85
+ }>;
86
+ inReplyTo: z.ZodString;
87
+ }, z.core.$strict>;
88
+ export declare const AuthenticatedRelayCommandEnvelopeSchema: z.ZodObject<{
89
+ envelopeVersion: z.ZodLiteral<2>;
90
+ suite: z.ZodLiteral<"DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_AES_128_GCM">;
91
+ keyId: z.ZodString;
92
+ workspaceId: z.ZodString;
93
+ targetDeviceId: z.ZodString;
94
+ commandId: z.ZodString;
95
+ payloadSchemaVersion: z.ZodNumber;
96
+ issuedAt: z.ZodISODateTime;
97
+ expiresAt: z.ZodISODateTime;
98
+ contentDigest: z.ZodString;
99
+ senderKeyId: z.ZodString;
100
+ senderPrincipalId: z.ZodString;
101
+ nonce: z.ZodString;
102
+ direction: z.ZodLiteral<"command">;
103
+ payloadType: z.ZodEnum<{
104
+ create_execution: "create_execution";
105
+ device_request: "device_request";
106
+ metadata_command: "metadata_command";
107
+ submit_input: "submit_input";
108
+ }>;
109
+ returnKeyId: z.ZodString;
110
+ returnPublicKey: z.ZodString;
111
+ encapsulatedKey: z.ZodString;
112
+ ciphertext: z.ZodString;
113
+ signature: z.ZodString;
114
+ }, z.core.$strict>;
115
+ export declare const AuthenticatedRelayResultEnvelopeSchema: z.ZodObject<{
116
+ envelopeVersion: z.ZodLiteral<2>;
117
+ suite: z.ZodLiteral<"DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_AES_128_GCM">;
118
+ keyId: z.ZodString;
119
+ workspaceId: z.ZodString;
120
+ targetDeviceId: z.ZodString;
121
+ commandId: z.ZodString;
122
+ payloadSchemaVersion: z.ZodNumber;
123
+ issuedAt: z.ZodISODateTime;
124
+ expiresAt: z.ZodISODateTime;
125
+ contentDigest: z.ZodString;
126
+ senderKeyId: z.ZodString;
127
+ senderPrincipalId: z.ZodString;
128
+ nonce: z.ZodString;
129
+ direction: z.ZodLiteral<"result">;
130
+ payloadType: z.ZodEnum<{
131
+ device_response: "device_response";
132
+ execution_result: "execution_result";
133
+ interaction_result: "interaction_result";
134
+ metadata_result: "metadata_result";
135
+ }>;
136
+ inReplyTo: z.ZodString;
137
+ encapsulatedKey: z.ZodString;
138
+ ciphertext: z.ZodString;
139
+ signature: z.ZodString;
140
+ }, z.core.$strict>;
141
+ export type AuthenticatedRelayCommandHeader = z.infer<typeof AuthenticatedRelayCommandHeaderSchema>;
142
+ export type AuthenticatedRelayResultHeader = z.infer<typeof AuthenticatedRelayResultHeaderSchema>;
143
+ export type AuthenticatedRelayCommandEnvelope = z.infer<typeof AuthenticatedRelayCommandEnvelopeSchema>;
144
+ export type AuthenticatedRelayResultEnvelope = z.infer<typeof AuthenticatedRelayResultEnvelopeSchema>;
145
+ export declare const AuthorizedSenderKeySchema: z.ZodObject<{
146
+ senderKeyId: z.ZodString;
147
+ kind: z.ZodEnum<{
148
+ device: "device";
149
+ session: "session";
150
+ }>;
151
+ principalId: z.ZodString;
152
+ deviceId: z.ZodOptional<z.ZodString>;
153
+ signingPublicKey: z.ZodString;
154
+ encryptionKeyId: z.ZodOptional<z.ZodString>;
155
+ encryptionPublicKey: z.ZodOptional<z.ZodString>;
156
+ approvedAt: z.ZodISODateTime;
157
+ revokedAt: z.ZodOptional<z.ZodISODateTime>;
158
+ }, z.core.$strict>;
159
+ export declare const AuthorizedSenderKeyringBodySchema: z.ZodObject<{
160
+ keyringVersion: z.ZodLiteral<1>;
161
+ workspaceId: z.ZodString;
162
+ revision: z.ZodNumber;
163
+ issuedAt: z.ZodISODateTime;
164
+ primaryDeviceId: z.ZodString;
165
+ primarySigningKeyId: z.ZodString;
166
+ entries: z.ZodArray<z.ZodObject<{
167
+ senderKeyId: z.ZodString;
168
+ kind: z.ZodEnum<{
169
+ device: "device";
170
+ session: "session";
171
+ }>;
172
+ principalId: z.ZodString;
173
+ deviceId: z.ZodOptional<z.ZodString>;
174
+ signingPublicKey: z.ZodString;
175
+ encryptionKeyId: z.ZodOptional<z.ZodString>;
176
+ encryptionPublicKey: z.ZodOptional<z.ZodString>;
177
+ approvedAt: z.ZodISODateTime;
178
+ revokedAt: z.ZodOptional<z.ZodISODateTime>;
179
+ }, z.core.$strict>>;
180
+ }, z.core.$strict>;
181
+ export declare const AuthorizedSenderKeyringSchema: z.ZodObject<{
182
+ keyringVersion: z.ZodLiteral<1>;
183
+ workspaceId: z.ZodString;
184
+ revision: z.ZodNumber;
185
+ issuedAt: z.ZodISODateTime;
186
+ primaryDeviceId: z.ZodString;
187
+ primarySigningKeyId: z.ZodString;
188
+ entries: z.ZodArray<z.ZodObject<{
189
+ senderKeyId: z.ZodString;
190
+ kind: z.ZodEnum<{
191
+ device: "device";
192
+ session: "session";
193
+ }>;
194
+ principalId: z.ZodString;
195
+ deviceId: z.ZodOptional<z.ZodString>;
196
+ signingPublicKey: z.ZodString;
197
+ encryptionKeyId: z.ZodOptional<z.ZodString>;
198
+ encryptionPublicKey: z.ZodOptional<z.ZodString>;
199
+ approvedAt: z.ZodISODateTime;
200
+ revokedAt: z.ZodOptional<z.ZodISODateTime>;
201
+ }, z.core.$strict>>;
202
+ signature: z.ZodString;
203
+ }, z.core.$strict>;
204
+ export type AuthorizedSenderKey = z.infer<typeof AuthorizedSenderKeySchema>;
205
+ export type AuthorizedSenderKeyringBody = z.infer<typeof AuthorizedSenderKeyringBodySchema>;
206
+ export type AuthorizedSenderKeyring = z.infer<typeof AuthorizedSenderKeyringSchema>;
207
+ export declare const MAX_DEVICE_RELAY_REQUEST_BYTES: number;
208
+ export declare const DeviceRelayRequestSchema: z.ZodObject<{
209
+ method: z.ZodEnum<{
210
+ DELETE: "DELETE";
211
+ GET: "GET";
212
+ PATCH: "PATCH";
213
+ POST: "POST";
214
+ PUT: "PUT";
215
+ }>;
216
+ path: z.ZodString;
217
+ body: z.ZodOptional<z.ZodUnknown>;
218
+ }, z.core.$strict>;
219
+ export declare const DeviceRelayResponseSchema: z.ZodObject<{
220
+ status: z.ZodNumber;
221
+ body: z.ZodUnknown;
222
+ }, z.core.$strict>;
223
+ export type DeviceRelayRequest = z.infer<typeof DeviceRelayRequestSchema>;
224
+ export type DeviceRelayResponse = z.infer<typeof DeviceRelayResponseSchema>;
225
+ export interface RelayEncryptionKeyPair {
226
+ readonly keyId: string;
227
+ readonly publicKey: string;
228
+ readonly privateKey: string;
229
+ }
230
+ export declare function generateRelayEncryptionKeyPair(): Promise<RelayEncryptionKeyPair>;
231
+ export declare function relayEncryptionKeyPairFromPrivateKey(privateKey: string): Promise<RelayEncryptionKeyPair>;
232
+ export declare function relayEncryptionKeyId(publicKey: string): Promise<string>;
233
+ export interface RelaySigningKeyPair {
234
+ readonly keyId: string;
235
+ readonly publicKey: string;
236
+ readonly privateKey: CryptoKey;
237
+ }
238
+ export interface PinnedPrimarySigningKey {
239
+ readonly primaryDeviceId: string;
240
+ readonly keyId: string;
241
+ readonly publicKey: string;
242
+ }
243
+ export declare function generateRelaySigningKeyPair(kind: 'session' | 'device', options?: {
244
+ readonly extractable?: boolean;
245
+ }): Promise<RelaySigningKeyPair>;
246
+ export declare function relaySigningKeyPairFromSeed(kind: 'session' | 'device', seed: string): Promise<RelaySigningKeyPair>;
247
+ export declare function relaySigningKeyId(kind: 'session' | 'device', publicKey: string): Promise<string>;
248
+ export declare function signAuthorizedSenderKeyring(body: AuthorizedSenderKeyringBody, primary: RelaySigningKeyPair): Promise<AuthorizedSenderKeyring>;
249
+ export declare function verifyAuthorizedSenderKeyring(input: {
250
+ readonly keyring: unknown;
251
+ readonly pinned: PinnedPrimarySigningKey;
252
+ readonly workspaceId: string;
253
+ readonly minimumRevision?: number;
254
+ }): Promise<AuthorizedSenderKeyring>;
255
+ export interface SealAuthenticatedRelayCommandInput {
256
+ readonly recipient: {
257
+ readonly keyId: string;
258
+ readonly publicKey: string;
259
+ };
260
+ readonly targetDeviceId: string;
261
+ readonly workspaceId: string;
262
+ readonly commandId: string;
263
+ readonly payloadType: z.infer<typeof AuthenticatedRelayCommandTypeSchema>;
264
+ readonly payloadSchemaVersion: number;
265
+ readonly issuedAt: string;
266
+ readonly expiresAt: string;
267
+ readonly plaintext: Uint8Array;
268
+ readonly returnKey: {
269
+ readonly keyId: string;
270
+ readonly publicKey: string;
271
+ };
272
+ readonly sender: {
273
+ readonly keyId: string;
274
+ readonly principalId: string;
275
+ readonly privateKey: CryptoKey;
276
+ };
277
+ }
278
+ export declare function sealAuthenticatedRelayCommand(input: SealAuthenticatedRelayCommandInput): Promise<AuthenticatedRelayCommandEnvelope>;
279
+ export interface RelayReplayReservation {
280
+ readonly senderKeyId: string;
281
+ readonly nonce: string;
282
+ readonly commandId: string;
283
+ readonly envelopeDigest: `sha256:${string}`;
284
+ readonly expiresAt: string;
285
+ }
286
+ export interface RelayReplayStore {
287
+ reserve(reservation: RelayReplayReservation, now: Date): Promise<'first' | 'duplicate'>;
288
+ }
289
+ export declare class InMemoryRelayReplayStore implements RelayReplayStore {
290
+ #private;
291
+ reserve(reservation: RelayReplayReservation, now: Date): Promise<'first' | 'duplicate'>;
292
+ }
293
+ export interface OpenAuthenticatedRelayCommandInput {
294
+ readonly envelope: unknown;
295
+ readonly recipient: RelayEncryptionKeyPair;
296
+ readonly deviceId: string;
297
+ readonly workspaceId: string;
298
+ readonly keyring: AuthorizedSenderKeyring;
299
+ readonly replay: RelayReplayStore;
300
+ readonly now?: Date;
301
+ }
302
+ export interface OpenedAuthenticatedRelayCommand {
303
+ readonly header: AuthenticatedRelayCommandHeader;
304
+ readonly sender: AuthorizedSenderKey;
305
+ readonly plaintext: Uint8Array;
306
+ readonly delivery: 'first' | 'duplicate';
307
+ }
308
+ export declare function openAuthenticatedRelayCommand(input: OpenAuthenticatedRelayCommandInput): Promise<OpenedAuthenticatedRelayCommand>;
309
+ export interface SealAuthenticatedRelayResultInput {
310
+ readonly command: AuthenticatedRelayCommandHeader;
311
+ readonly payloadType: z.infer<typeof AuthenticatedRelayResultTypeSchema>;
312
+ readonly payloadSchemaVersion: number;
313
+ readonly plaintext: Uint8Array;
314
+ readonly device: {
315
+ readonly keyId: string;
316
+ readonly principalId: string;
317
+ readonly privateKey: CryptoKey;
318
+ };
319
+ readonly issuedAt: string;
320
+ readonly expiresAt: string;
321
+ }
322
+ export declare function sealAuthenticatedRelayResult(input: SealAuthenticatedRelayResultInput): Promise<AuthenticatedRelayResultEnvelope>;
323
+ export interface OpenAuthenticatedRelayResultInput {
324
+ readonly envelope: unknown;
325
+ readonly command: AuthenticatedRelayCommandHeader;
326
+ readonly returnPrivateKey: string;
327
+ readonly keyring: AuthorizedSenderKeyring;
328
+ readonly now?: Date;
329
+ }
330
+ export declare function openAuthenticatedRelayResult(input: OpenAuthenticatedRelayResultInput): Promise<{
331
+ readonly header: AuthenticatedRelayResultHeader;
332
+ readonly plaintext: Uint8Array;
333
+ }>;
334
+ export interface AttestAuthenticatedRelayResultInput {
335
+ readonly envelope: unknown;
336
+ readonly plaintext: Uint8Array;
337
+ readonly deviceId: string;
338
+ readonly workspaceId: string;
339
+ readonly keyring: AuthorizedSenderKeyring;
340
+ readonly now?: Date;
341
+ }
342
+ export declare function attestAuthenticatedRelayResult(input: AttestAuthenticatedRelayResultInput): Promise<AuthenticatedRelayResultHeader>;
343
+ export declare function relayReplayOutcome(existing: readonly (RelayReplayReservation | undefined)[], reservation: RelayReplayReservation): 'first' | 'duplicate';
344
+ export declare function sha256(value: Uint8Array): Promise<`sha256:${string}`>;
345
+ export declare function encodeBase64Url(value: Uint8Array): string;
346
+ export declare function decodeBase64Url(value: string): Uint8Array;
@@ -0,0 +1,522 @@
1
+ import { Aes128Gcm, CipherSuite, HkdfSha256 } from '@hpke/core';
2
+ import { DhkemX25519HkdfSha256 } from '@hpke/dhkem-x25519';
3
+ import { z } from 'zod';
4
+ import { canonicalJsonStringify } from '@adea-ai/contracts/canonical-json';
5
+ export const RELAY_HPKE_SUITE = 'DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_AES_128_GCM';
6
+ export const MAX_RELAY_CIPHERTEXT_BYTES = 1024 * 1024;
7
+ export const MAX_RELAY_CLOCK_SKEW_MS = 5 * 60 * 1000;
8
+ export const AUTHENTICATED_RELAY_ENVELOPE_VERSION = 2;
9
+ export const MAX_AUTHENTICATED_RELAY_COMMAND_LIFETIME_MS = 15 * 60 * 1000;
10
+ export const MAX_AUTHENTICATED_RELAY_RESULT_LIFETIME_MS = 24 * 60 * 60 * 1000;
11
+ const suite = new CipherSuite({
12
+ kem: new DhkemX25519HkdfSha256(),
13
+ kdf: new HkdfSha256(),
14
+ aead: new Aes128Gcm(),
15
+ });
16
+ const HPKE_INFO = new TextEncoder().encode('adea-control-plane-relay-v2');
17
+ const SIGNATURE_CONTEXT = 'adea-control-plane-relay-signature-v2';
18
+ const KEYRING_SIGNATURE_CONTEXT = 'adea-control-plane-relay-keyring-v1';
19
+ const AEAD_TAG_BYTES = 16;
20
+ const NONCE_BYTES = 16;
21
+ const X25519_PKCS8_PREFIX = Uint8Array.of(0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20);
22
+ const ED25519_PKCS8_PREFIX = Uint8Array.of(0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20);
23
+ const IdentifierSchema = z
24
+ .string()
25
+ .min(1)
26
+ .max(128)
27
+ .regex(/^[A-Za-z0-9._:-]+$/);
28
+ const HostKeyIdSchema = z
29
+ .string()
30
+ .min(8)
31
+ .max(96)
32
+ .regex(/^(?:hpk|rpk)_[a-f0-9]+$/);
33
+ const SigningKeyIdSchema = z.string().regex(/^(?:spk|dpk)_[a-f0-9]{32}$/);
34
+ const Base64UrlSchema = z
35
+ .string()
36
+ .min(1)
37
+ .regex(/^[A-Za-z0-9_-]+$/);
38
+ const PublicKeySchema = Base64UrlSchema.length(43);
39
+ const NonceSchema = Base64UrlSchema.length(22);
40
+ const SignatureSchema = Base64UrlSchema.length(86);
41
+ const CiphertextSchema = Base64UrlSchema.max(Math.ceil((MAX_RELAY_CIPHERTEXT_BYTES * 4) / 3));
42
+ export const AuthenticatedRelayCommandTypeSchema = z.enum([
43
+ 'create_execution',
44
+ 'submit_input',
45
+ 'metadata_command',
46
+ 'device_request',
47
+ ]);
48
+ export const AuthenticatedRelayResultTypeSchema = z.enum([
49
+ 'execution_result',
50
+ 'interaction_result',
51
+ 'metadata_result',
52
+ 'device_response',
53
+ ]);
54
+ export const RelayRejectionCodeSchema = z.enum([
55
+ 'RELAY_ENVELOPE_INVALID',
56
+ 'RELAY_ENVELOPE_TOO_LARGE',
57
+ 'RELAY_ENVELOPE_EXPIRED',
58
+ 'RELAY_ENVELOPE_LIFETIME_INVALID',
59
+ 'RELAY_ENVELOPE_KEY_UNAVAILABLE',
60
+ 'RELAY_ENVELOPE_DECRYPTION_FAILED',
61
+ 'RELAY_ENVELOPE_DIGEST_MISMATCH',
62
+ 'RELAY_ENVELOPE_REPLAYED',
63
+ 'RELAY_SENDER_UNAUTHENTICATED',
64
+ 'RELAY_SENDER_REVOKED',
65
+ 'RELAY_SIGNATURE_INVALID',
66
+ 'RELAY_TARGET_MISMATCH',
67
+ 'RELAY_KEYRING_INVALID',
68
+ 'RELAY_DEVICE_OFFLINE',
69
+ ]);
70
+ export class AuthenticatedRelayError extends Error {
71
+ code;
72
+ constructor(code) {
73
+ super('Remote control envelope was rejected');
74
+ this.code = code;
75
+ this.name = 'AuthenticatedRelayError';
76
+ }
77
+ }
78
+ const HeaderFields = {
79
+ envelopeVersion: z.literal(AUTHENTICATED_RELAY_ENVELOPE_VERSION),
80
+ suite: z.literal(RELAY_HPKE_SUITE),
81
+ keyId: HostKeyIdSchema,
82
+ workspaceId: IdentifierSchema,
83
+ targetDeviceId: IdentifierSchema,
84
+ commandId: IdentifierSchema,
85
+ payloadSchemaVersion: z.number().int().min(1).max(65_535),
86
+ issuedAt: z.iso.datetime(),
87
+ expiresAt: z.iso.datetime(),
88
+ contentDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/),
89
+ senderKeyId: SigningKeyIdSchema,
90
+ senderPrincipalId: IdentifierSchema,
91
+ nonce: NonceSchema,
92
+ };
93
+ export const AuthenticatedRelayCommandHeaderSchema = z
94
+ .object({
95
+ ...HeaderFields,
96
+ direction: z.literal('command'),
97
+ payloadType: AuthenticatedRelayCommandTypeSchema,
98
+ returnKeyId: HostKeyIdSchema,
99
+ returnPublicKey: PublicKeySchema,
100
+ })
101
+ .strict();
102
+ export const AuthenticatedRelayResultHeaderSchema = z
103
+ .object({
104
+ ...HeaderFields,
105
+ direction: z.literal('result'),
106
+ payloadType: AuthenticatedRelayResultTypeSchema,
107
+ inReplyTo: IdentifierSchema,
108
+ })
109
+ .strict();
110
+ const SealedFields = {
111
+ encapsulatedKey: PublicKeySchema,
112
+ ciphertext: CiphertextSchema,
113
+ signature: SignatureSchema,
114
+ };
115
+ export const AuthenticatedRelayCommandEnvelopeSchema = AuthenticatedRelayCommandHeaderSchema.extend(SealedFields).strict();
116
+ export const AuthenticatedRelayResultEnvelopeSchema = AuthenticatedRelayResultHeaderSchema.extend(SealedFields).strict();
117
+ export const AuthorizedSenderKeySchema = z
118
+ .object({
119
+ senderKeyId: SigningKeyIdSchema,
120
+ kind: z.enum(['session', 'device']),
121
+ principalId: IdentifierSchema,
122
+ deviceId: IdentifierSchema.optional(),
123
+ signingPublicKey: PublicKeySchema,
124
+ encryptionKeyId: HostKeyIdSchema.optional(),
125
+ encryptionPublicKey: PublicKeySchema.optional(),
126
+ approvedAt: z.iso.datetime(),
127
+ revokedAt: z.iso.datetime().optional(),
128
+ })
129
+ .strict()
130
+ .superRefine((value, context) => {
131
+ if ((value.kind === 'device') !== (value.deviceId !== undefined)) {
132
+ context.addIssue({ code: 'custom', message: 'a device key names its device' });
133
+ }
134
+ if ((value.encryptionKeyId === undefined) !== (value.encryptionPublicKey === undefined)) {
135
+ context.addIssue({ code: 'custom', message: 'encryption key id and key go together' });
136
+ }
137
+ });
138
+ export const AuthorizedSenderKeyringBodySchema = z
139
+ .object({
140
+ keyringVersion: z.literal(1),
141
+ workspaceId: IdentifierSchema,
142
+ revision: z.number().int().min(1),
143
+ issuedAt: z.iso.datetime(),
144
+ primaryDeviceId: IdentifierSchema,
145
+ primarySigningKeyId: SigningKeyIdSchema,
146
+ entries: z.array(AuthorizedSenderKeySchema).max(256),
147
+ })
148
+ .strict();
149
+ export const AuthorizedSenderKeyringSchema = AuthorizedSenderKeyringBodySchema.extend({
150
+ signature: SignatureSchema,
151
+ }).strict();
152
+ export const MAX_DEVICE_RELAY_REQUEST_BYTES = 512 * 1024;
153
+ export const DeviceRelayRequestSchema = z
154
+ .object({
155
+ method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']),
156
+ path: z
157
+ .string()
158
+ .min(1)
159
+ .max(2048)
160
+ .regex(/^\/v[0-9]+\/[A-Za-z0-9/_.:%?=&-]*$/)
161
+ .refine((path) => !/(^|\/)\.{1,2}(\/|\?|$)|%2e|%2f|\/\//iu.test(path)),
162
+ body: z.unknown().optional(),
163
+ })
164
+ .strict();
165
+ export const DeviceRelayResponseSchema = z
166
+ .object({ status: z.number().int().min(100).max(599), body: z.unknown() })
167
+ .strict();
168
+ export async function generateRelayEncryptionKeyPair() {
169
+ const pair = await suite.kem.generateKeyPair();
170
+ return relayEncryptionKeyPairFromPrivateKey(encodeBase64Url(new Uint8Array(await suite.kem.serializePrivateKey(pair.privateKey))));
171
+ }
172
+ export async function relayEncryptionKeyPairFromPrivateKey(privateKey) {
173
+ const publicKey = await rawPublicKey(X25519_PKCS8_PREFIX, privateKey, 'X25519', ['deriveBits']);
174
+ return { keyId: await relayEncryptionKeyId(publicKey), publicKey, privateKey };
175
+ }
176
+ export async function relayEncryptionKeyId(publicKey) {
177
+ const digest = await sha256(decodeBase64Url(publicKey));
178
+ return `hpk_${digest.slice('sha256:'.length, 'sha256:'.length + 32)}`;
179
+ }
180
+ export async function generateRelaySigningKeyPair(kind, options = {}) {
181
+ const pair = (await globalThis.crypto.subtle.generateKey({ name: 'Ed25519' }, options.extractable ?? false, ['sign', 'verify']));
182
+ const publicKey = new Uint8Array(await globalThis.crypto.subtle.exportKey('raw', pair.publicKey));
183
+ return {
184
+ keyId: await relaySigningKeyId(kind, encodeBase64Url(publicKey)),
185
+ publicKey: encodeBase64Url(publicKey),
186
+ privateKey: pair.privateKey,
187
+ };
188
+ }
189
+ export async function relaySigningKeyPairFromSeed(kind, seed) {
190
+ const publicKey = await rawPublicKey(ED25519_PKCS8_PREFIX, seed, 'Ed25519', ['sign']);
191
+ const privateKey = await globalThis.crypto.subtle.importKey('pkcs8', concat(ED25519_PKCS8_PREFIX, decodeBase64Url(seed)), { name: 'Ed25519' }, false, ['sign']);
192
+ return { keyId: await relaySigningKeyId(kind, publicKey), publicKey, privateKey };
193
+ }
194
+ export async function relaySigningKeyId(kind, publicKey) {
195
+ const digest = await sha256(decodeBase64Url(publicKey));
196
+ return `${kind === 'session' ? 'spk' : 'dpk'}_${digest.slice('sha256:'.length, 'sha256:'.length + 32)}`;
197
+ }
198
+ export async function signAuthorizedSenderKeyring(body, primary) {
199
+ const parsed = AuthorizedSenderKeyringBodySchema.parse(body);
200
+ if (parsed.primarySigningKeyId !== primary.keyId) {
201
+ throw new AuthenticatedRelayError('RELAY_KEYRING_INVALID');
202
+ }
203
+ const signature = await sign(primary.privateKey, keyringSigningInput(parsed));
204
+ return AuthorizedSenderKeyringSchema.parse({ ...parsed, signature });
205
+ }
206
+ export async function verifyAuthorizedSenderKeyring(input) {
207
+ const parsed = AuthorizedSenderKeyringSchema.safeParse(input.keyring);
208
+ if (!parsed.success)
209
+ throw new AuthenticatedRelayError('RELAY_KEYRING_INVALID');
210
+ const keyring = parsed.data;
211
+ if (keyring.workspaceId !== input.workspaceId ||
212
+ keyring.primaryDeviceId !== input.pinned.primaryDeviceId ||
213
+ keyring.primarySigningKeyId !== input.pinned.keyId ||
214
+ keyring.revision < (input.minimumRevision ?? 1) ||
215
+ new Set(keyring.entries.map((entry) => entry.senderKeyId)).size !== keyring.entries.length) {
216
+ throw new AuthenticatedRelayError('RELAY_KEYRING_INVALID');
217
+ }
218
+ const { signature, ...body } = keyring;
219
+ if (!(await verify(input.pinned.publicKey, signature, keyringSigningInput(body)))) {
220
+ throw new AuthenticatedRelayError('RELAY_KEYRING_INVALID');
221
+ }
222
+ for (const entry of keyring.entries) {
223
+ if ((await relaySigningKeyId(entry.kind, entry.signingPublicKey)) !== entry.senderKeyId) {
224
+ throw new AuthenticatedRelayError('RELAY_KEYRING_INVALID');
225
+ }
226
+ }
227
+ return keyring;
228
+ }
229
+ export async function sealAuthenticatedRelayCommand(input) {
230
+ validateDuration(input.issuedAt, input.expiresAt, MAX_AUTHENTICATED_RELAY_COMMAND_LIFETIME_MS);
231
+ const header = AuthenticatedRelayCommandHeaderSchema.parse({
232
+ envelopeVersion: AUTHENTICATED_RELAY_ENVELOPE_VERSION,
233
+ suite: RELAY_HPKE_SUITE,
234
+ direction: 'command',
235
+ keyId: input.recipient.keyId,
236
+ workspaceId: input.workspaceId,
237
+ targetDeviceId: input.targetDeviceId,
238
+ commandId: input.commandId,
239
+ payloadType: input.payloadType,
240
+ payloadSchemaVersion: input.payloadSchemaVersion,
241
+ issuedAt: input.issuedAt,
242
+ expiresAt: input.expiresAt,
243
+ contentDigest: await sha256(input.plaintext),
244
+ senderKeyId: input.sender.keyId,
245
+ senderPrincipalId: input.sender.principalId,
246
+ nonce: randomNonce(),
247
+ returnKeyId: input.returnKey.keyId,
248
+ returnPublicKey: input.returnKey.publicKey,
249
+ });
250
+ const sealed = await sealAndSign(header, input.recipient.publicKey, input.plaintext, input.sender);
251
+ return AuthenticatedRelayCommandEnvelopeSchema.parse({ ...header, ...sealed });
252
+ }
253
+ export class InMemoryRelayReplayStore {
254
+ #entries = new Map();
255
+ reserve(reservation, now) {
256
+ for (const [key, entry] of this.#entries) {
257
+ if (Date.parse(entry.expiresAt) + MAX_RELAY_CLOCK_SKEW_MS <= now.getTime()) {
258
+ this.#entries.delete(key);
259
+ }
260
+ }
261
+ const nonceKey = `nonce:${reservation.senderKeyId}:${reservation.nonce}`;
262
+ const commandKey = `command:${reservation.commandId}`;
263
+ const outcome = relayReplayOutcome([this.#entries.get(nonceKey), this.#entries.get(commandKey)], reservation);
264
+ if (outcome === 'first') {
265
+ this.#entries.set(nonceKey, reservation);
266
+ this.#entries.set(commandKey, reservation);
267
+ }
268
+ return Promise.resolve(outcome);
269
+ }
270
+ }
271
+ export async function openAuthenticatedRelayCommand(input) {
272
+ const parsed = AuthenticatedRelayCommandEnvelopeSchema.safeParse(input.envelope);
273
+ if (!parsed.success)
274
+ throw new AuthenticatedRelayError('RELAY_ENVELOPE_INVALID');
275
+ const envelope = parsed.data;
276
+ const { encapsulatedKey, ciphertext, signature, ...header } = envelope;
277
+ if (header.targetDeviceId !== input.deviceId ||
278
+ header.workspaceId !== input.workspaceId ||
279
+ input.keyring.workspaceId !== input.workspaceId) {
280
+ throw new AuthenticatedRelayError('RELAY_TARGET_MISMATCH');
281
+ }
282
+ if (header.keyId !== input.recipient.keyId) {
283
+ throw new AuthenticatedRelayError('RELAY_ENVELOPE_KEY_UNAVAILABLE');
284
+ }
285
+ const now = input.now ?? new Date();
286
+ validateLifetime(header, MAX_AUTHENTICATED_RELAY_COMMAND_LIFETIME_MS, now);
287
+ const sender = authorizedSender(input.keyring, header, now);
288
+ if (!(await verify(sender.signingPublicKey, signature, await envelopeSigningInput(header, encapsulatedKey, ciphertext)))) {
289
+ throw new AuthenticatedRelayError('RELAY_SIGNATURE_INVALID');
290
+ }
291
+ const delivery = await input.replay.reserve({
292
+ senderKeyId: header.senderKeyId,
293
+ nonce: header.nonce,
294
+ commandId: header.commandId,
295
+ envelopeDigest: await sha256(new TextEncoder().encode(signature)),
296
+ expiresAt: header.expiresAt,
297
+ }, now);
298
+ const plaintext = await openSealed(header, encapsulatedKey, ciphertext, input.recipient.privateKey);
299
+ return { header, sender, plaintext, delivery };
300
+ }
301
+ export async function sealAuthenticatedRelayResult(input) {
302
+ validateDuration(input.issuedAt, input.expiresAt, MAX_AUTHENTICATED_RELAY_RESULT_LIFETIME_MS);
303
+ const header = AuthenticatedRelayResultHeaderSchema.parse({
304
+ envelopeVersion: AUTHENTICATED_RELAY_ENVELOPE_VERSION,
305
+ suite: RELAY_HPKE_SUITE,
306
+ direction: 'result',
307
+ keyId: input.command.returnKeyId,
308
+ workspaceId: input.command.workspaceId,
309
+ targetDeviceId: input.command.targetDeviceId,
310
+ commandId: input.command.commandId,
311
+ inReplyTo: input.command.commandId,
312
+ payloadType: input.payloadType,
313
+ payloadSchemaVersion: input.payloadSchemaVersion,
314
+ issuedAt: input.issuedAt,
315
+ expiresAt: input.expiresAt,
316
+ contentDigest: await sha256(input.plaintext),
317
+ senderKeyId: input.device.keyId,
318
+ senderPrincipalId: input.device.principalId,
319
+ nonce: randomNonce(),
320
+ });
321
+ const sealed = await sealAndSign(header, input.command.returnPublicKey, input.plaintext, input.device);
322
+ return AuthenticatedRelayResultEnvelopeSchema.parse({ ...header, ...sealed });
323
+ }
324
+ export async function openAuthenticatedRelayResult(input) {
325
+ const parsed = AuthenticatedRelayResultEnvelopeSchema.safeParse(input.envelope);
326
+ if (!parsed.success)
327
+ throw new AuthenticatedRelayError('RELAY_ENVELOPE_INVALID');
328
+ const { encapsulatedKey, ciphertext, signature, ...header } = parsed.data;
329
+ if (header.inReplyTo !== input.command.commandId ||
330
+ header.commandId !== input.command.commandId ||
331
+ header.targetDeviceId !== input.command.targetDeviceId ||
332
+ header.workspaceId !== input.command.workspaceId ||
333
+ header.keyId !== input.command.returnKeyId) {
334
+ throw new AuthenticatedRelayError('RELAY_TARGET_MISMATCH');
335
+ }
336
+ const now = input.now ?? new Date();
337
+ validateLifetime(header, MAX_AUTHENTICATED_RELAY_RESULT_LIFETIME_MS, now);
338
+ const sender = authorizedSender(input.keyring, header, now);
339
+ if (sender.kind !== 'device' || sender.deviceId !== input.command.targetDeviceId) {
340
+ throw new AuthenticatedRelayError('RELAY_SENDER_UNAUTHENTICATED');
341
+ }
342
+ if (!(await verify(sender.signingPublicKey, signature, await envelopeSigningInput(header, encapsulatedKey, ciphertext)))) {
343
+ throw new AuthenticatedRelayError('RELAY_SIGNATURE_INVALID');
344
+ }
345
+ return {
346
+ header,
347
+ plaintext: await openSealed(header, encapsulatedKey, ciphertext, input.returnPrivateKey),
348
+ };
349
+ }
350
+ export async function attestAuthenticatedRelayResult(input) {
351
+ const parsed = AuthenticatedRelayResultEnvelopeSchema.safeParse(input.envelope);
352
+ if (!parsed.success)
353
+ throw new AuthenticatedRelayError('RELAY_ENVELOPE_INVALID');
354
+ const { encapsulatedKey, ciphertext, signature, ...header } = parsed.data;
355
+ if (header.targetDeviceId !== input.deviceId || header.workspaceId !== input.workspaceId) {
356
+ throw new AuthenticatedRelayError('RELAY_TARGET_MISMATCH');
357
+ }
358
+ const now = input.now ?? new Date();
359
+ validateLifetime(header, MAX_AUTHENTICATED_RELAY_RESULT_LIFETIME_MS, now);
360
+ const sender = authorizedSender(input.keyring, header, now);
361
+ if (sender.kind !== 'device' || sender.deviceId !== input.deviceId) {
362
+ throw new AuthenticatedRelayError('RELAY_SENDER_UNAUTHENTICATED');
363
+ }
364
+ if (!(await verify(sender.signingPublicKey, signature, await envelopeSigningInput(header, encapsulatedKey, ciphertext)))) {
365
+ throw new AuthenticatedRelayError('RELAY_SIGNATURE_INVALID');
366
+ }
367
+ if ((await sha256(input.plaintext)) !== header.contentDigest) {
368
+ throw new AuthenticatedRelayError('RELAY_ENVELOPE_DIGEST_MISMATCH');
369
+ }
370
+ return header;
371
+ }
372
+ function authorizedSender(keyring, header, now) {
373
+ const sender = keyring.entries.find((entry) => entry.senderKeyId === header.senderKeyId);
374
+ if (sender === undefined || sender.principalId !== header.senderPrincipalId) {
375
+ throw new AuthenticatedRelayError('RELAY_SENDER_UNAUTHENTICATED');
376
+ }
377
+ if (sender.revokedAt !== undefined && Date.parse(sender.revokedAt) <= now.getTime()) {
378
+ throw new AuthenticatedRelayError('RELAY_SENDER_REVOKED');
379
+ }
380
+ return sender;
381
+ }
382
+ async function sealAndSign(header, recipientPublicKey, plaintext, signer) {
383
+ if (header.senderKeyId !== signer.keyId) {
384
+ throw new AuthenticatedRelayError('RELAY_SENDER_UNAUTHENTICATED');
385
+ }
386
+ if (plaintext.byteLength + AEAD_TAG_BYTES > MAX_RELAY_CIPHERTEXT_BYTES) {
387
+ throw new AuthenticatedRelayError('RELAY_ENVELOPE_TOO_LARGE');
388
+ }
389
+ let sealed;
390
+ try {
391
+ sealed = await suite.seal({
392
+ recipientPublicKey: await suite.kem.deserializePublicKey(decodeBase64Url(recipientPublicKey)),
393
+ info: HPKE_INFO,
394
+ }, plaintext, canonicalHeader(header));
395
+ }
396
+ catch {
397
+ throw new AuthenticatedRelayError('RELAY_ENVELOPE_INVALID');
398
+ }
399
+ const encapsulatedKey = encodeBase64Url(new Uint8Array(sealed.enc));
400
+ const ciphertext = encodeBase64Url(new Uint8Array(sealed.ct));
401
+ const signature = await sign(signer.privateKey, await envelopeSigningInput(header, encapsulatedKey, ciphertext));
402
+ return { encapsulatedKey, ciphertext, signature };
403
+ }
404
+ async function openSealed(header, encapsulatedKey, ciphertext, privateKey) {
405
+ let plaintext;
406
+ try {
407
+ plaintext = new Uint8Array(await suite.open({
408
+ recipientKey: await suite.kem.deserializePrivateKey(decodeBase64Url(privateKey)),
409
+ enc: decodeBase64Url(encapsulatedKey),
410
+ info: HPKE_INFO,
411
+ }, decodeBase64Url(ciphertext), canonicalHeader(header)));
412
+ }
413
+ catch {
414
+ throw new AuthenticatedRelayError('RELAY_ENVELOPE_DECRYPTION_FAILED');
415
+ }
416
+ if ((await sha256(plaintext)) !== header.contentDigest) {
417
+ plaintext.fill(0);
418
+ throw new AuthenticatedRelayError('RELAY_ENVELOPE_DIGEST_MISMATCH');
419
+ }
420
+ return plaintext;
421
+ }
422
+ function canonicalHeader(header) {
423
+ return new TextEncoder().encode(canonicalJsonStringify(header));
424
+ }
425
+ async function envelopeSigningInput(header, encapsulatedKey, ciphertext) {
426
+ const sealed = await sha256(concat(decodeBase64Url(encapsulatedKey), decodeBase64Url(ciphertext)));
427
+ return new TextEncoder().encode(`${SIGNATURE_CONTEXT}\n${canonicalJsonStringify(header)}\n${sealed}`);
428
+ }
429
+ function keyringSigningInput(body) {
430
+ return new TextEncoder().encode(`${KEYRING_SIGNATURE_CONTEXT}\n${canonicalJsonStringify(body)}`);
431
+ }
432
+ async function sign(privateKey, data) {
433
+ return encodeBase64Url(new Uint8Array(await globalThis.crypto.subtle.sign('Ed25519', privateKey, Uint8Array.from(data))));
434
+ }
435
+ async function verify(publicKey, signature, data) {
436
+ try {
437
+ const key = await globalThis.crypto.subtle.importKey('raw', Uint8Array.from(decodeBase64Url(publicKey)), { name: 'Ed25519' }, false, ['verify']);
438
+ return await globalThis.crypto.subtle.verify('Ed25519', key, Uint8Array.from(decodeBase64Url(signature)), Uint8Array.from(data));
439
+ }
440
+ catch {
441
+ return false;
442
+ }
443
+ }
444
+ export function relayReplayOutcome(existing, reservation) {
445
+ const seen = existing.filter((entry) => entry !== undefined);
446
+ if (seen.length === 0)
447
+ return 'first';
448
+ if (seen.every((entry) => entry.envelopeDigest === reservation.envelopeDigest)) {
449
+ return 'duplicate';
450
+ }
451
+ throw new AuthenticatedRelayError('RELAY_ENVELOPE_REPLAYED');
452
+ }
453
+ function validateLifetime(header, maximumMs, now) {
454
+ const { issued, expires } = validateDuration(header.issuedAt, header.expiresAt, maximumMs);
455
+ if (issued > now.getTime() + MAX_RELAY_CLOCK_SKEW_MS || expires <= now.getTime()) {
456
+ throw new AuthenticatedRelayError('RELAY_ENVELOPE_EXPIRED');
457
+ }
458
+ }
459
+ function validateDuration(issuedAt, expiresAt, maximumMs) {
460
+ const issued = Date.parse(issuedAt);
461
+ const expires = Date.parse(expiresAt);
462
+ if (!Number.isFinite(issued) ||
463
+ !Number.isFinite(expires) ||
464
+ expires <= issued ||
465
+ expires - issued > maximumMs) {
466
+ throw new AuthenticatedRelayError('RELAY_ENVELOPE_LIFETIME_INVALID');
467
+ }
468
+ return { issued, expires };
469
+ }
470
+ function randomNonce() {
471
+ return encodeBase64Url(globalThis.crypto.getRandomValues(new Uint8Array(NONCE_BYTES)));
472
+ }
473
+ async function rawPublicKey(prefix, privateKey, algorithm, usages) {
474
+ const bytes = decodeBase64Url(privateKey);
475
+ if (bytes.byteLength !== 32)
476
+ throw new AuthenticatedRelayError('RELAY_ENVELOPE_KEY_UNAVAILABLE');
477
+ try {
478
+ const key = await globalThis.crypto.subtle.importKey('pkcs8', concat(prefix, bytes), { name: algorithm }, true, usages);
479
+ const jwk = await globalThis.crypto.subtle.exportKey('jwk', key);
480
+ if (typeof jwk.x !== 'string')
481
+ throw new Error('no public key');
482
+ return jwk.x;
483
+ }
484
+ catch {
485
+ throw new AuthenticatedRelayError('RELAY_ENVELOPE_KEY_UNAVAILABLE');
486
+ }
487
+ }
488
+ function concat(left, right) {
489
+ const joined = new Uint8Array(left.byteLength + right.byteLength);
490
+ joined.set(left, 0);
491
+ joined.set(right, left.byteLength);
492
+ return joined;
493
+ }
494
+ export async function sha256(value) {
495
+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', Uint8Array.from(value)));
496
+ return `sha256:${[...digest].map((byte) => byte.toString(16).padStart(2, '0')).join('')}`;
497
+ }
498
+ export function encodeBase64Url(value) {
499
+ let binary = '';
500
+ for (let offset = 0; offset < value.length; offset += 0x8000) {
501
+ binary += String.fromCharCode(...value.subarray(offset, offset + 0x8000));
502
+ }
503
+ return globalThis.btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '');
504
+ }
505
+ export function decodeBase64Url(value) {
506
+ if (!/^[A-Za-z0-9_-]*$/u.test(value) || value.length % 4 === 1) {
507
+ throw new AuthenticatedRelayError('RELAY_ENVELOPE_INVALID');
508
+ }
509
+ const padded = `${value.replaceAll('-', '+').replaceAll('_', '/')}${'='.repeat((4 - (value.length % 4)) % 4)}`;
510
+ let binary;
511
+ try {
512
+ binary = globalThis.atob(padded);
513
+ }
514
+ catch {
515
+ throw new AuthenticatedRelayError('RELAY_ENVELOPE_INVALID');
516
+ }
517
+ const decoded = Uint8Array.from(binary, (character) => character.charCodeAt(0));
518
+ if (encodeBase64Url(decoded) !== value) {
519
+ throw new AuthenticatedRelayError('RELAY_ENVELOPE_INVALID');
520
+ }
521
+ return decoded;
522
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adea-ai/runtime-gateway-protocol",
3
- "version": "1.11.0",
3
+ "version": "1.13.0",
4
4
  "description": "Versioned wire protocol between the Control Plane and external runtimes: schemas, emulator, fixtures, and authentication.",
5
5
  "keywords": [
6
6
  "agents",
@@ -32,6 +32,10 @@
32
32
  "node": "./dist/index.js",
33
33
  "default": "./dist/index.js"
34
34
  },
35
+ "./device-relay": {
36
+ "types": "./dist/device-relay.d.ts",
37
+ "default": "./dist/device-relay.js"
38
+ },
35
39
  "./fixtures": "./fixtures/index.mjs",
36
40
  "./schema/gateway-envelope.v1.json": "./schema/gateway-envelope.v1.json"
37
41
  },
@@ -48,7 +52,10 @@
48
52
  "test": "bun scripts/schema.ts --check && bun test src"
49
53
  },
50
54
  "dependencies": {
51
- "@adea-ai/runtime-sdk": "^1.21.0",
55
+ "@adea-ai/contracts": "^2.1.0",
56
+ "@adea-ai/runtime-sdk": "^1.22.0",
57
+ "@hpke/core": "1.9.0",
58
+ "@hpke/dhkem-x25519": "1.8.0",
52
59
  "zod": "4.6.6"
53
60
  },
54
61
  "engines": {