@adea-ai/runtime-gateway-protocol 1.10.1 → 1.12.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/dist/acp-remote-sealed-channel.d.ts +0 -22
- package/dist/authentication.d.ts +0 -8
- package/dist/authentication.js +0 -5
- package/dist/device-relay.d.ts +337 -0
- package/dist/device-relay.js +500 -0
- package/dist/protocol.d.ts +0 -5
- package/dist/protocol.js +0 -5
- package/dist/public-identity-validation-compatibility.js +0 -1
- package/package.json +13 -6
|
@@ -1,32 +1,10 @@
|
|
|
1
1
|
import type { GatewayCommandEnvelope } from './protocol.js';
|
|
2
|
-
/**
|
|
3
|
-
* The gateway channel that carries ONE opaque sealed ACP command.
|
|
4
|
-
*
|
|
5
|
-
* A sealed ACP command is HPKE ciphertext bound to the device recipient key. The gateway relays
|
|
6
|
-
* it without being able to read it: it sees the route, the command identity and the timing, and
|
|
7
|
-
* never the prompt. The channel therefore hands the carrier command to the gateway's ordinary
|
|
8
|
-
* durable command path and resolves with the device's opaque sealed reply.
|
|
9
|
-
*
|
|
10
|
-
* Both sides of the seam depend on this package, so the contract is declared once and checked by
|
|
11
|
-
* the compiler on both ends: the controller wire consumes it, and the gateway channel adapter
|
|
12
|
-
* declares that it returns exactly this shape.
|
|
13
|
-
*/
|
|
14
2
|
export interface AcpRemoteSealedCarrierChannel {
|
|
15
|
-
/**
|
|
16
|
-
* The channel's CURRENT authenticated node/connection channel generation, or `undefined` when the
|
|
17
|
-
* device is not reachable on an authenticated channel. A wire refuses to send without one.
|
|
18
|
-
*/
|
|
19
3
|
readonly currentChannelGeneration: () => number | undefined;
|
|
20
|
-
/** Delivers one carrier command and resolves with the device's opaque sealed reply. */
|
|
21
4
|
readonly dispatchSealed: (input: {
|
|
22
5
|
readonly command: GatewayCommandEnvelope;
|
|
23
6
|
readonly signal?: AbortSignal;
|
|
24
7
|
}) => Promise<unknown>;
|
|
25
|
-
/**
|
|
26
|
-
* The inventory the gateway pushed on the authenticated channel, together with the channel
|
|
27
|
-
* generation it was pushed at. The controller compares that generation with the current one, so
|
|
28
|
-
* a stale push is denied instead of published.
|
|
29
|
-
*/
|
|
30
8
|
readonly pushedInventory: () => Promise<{
|
|
31
9
|
readonly inventory: unknown;
|
|
32
10
|
readonly channelGeneration: number;
|
package/dist/authentication.d.ts
CHANGED
|
@@ -29,21 +29,13 @@ export declare class RuntimeNodeIdentityValidationError extends Error {
|
|
|
29
29
|
readonly reason: 'credential' | 'proof';
|
|
30
30
|
constructor(reason: 'credential' | 'proof');
|
|
31
31
|
}
|
|
32
|
-
/** Result of the durable, atomic one-time credential-consumption fence. */
|
|
33
32
|
export type RuntimeNodeCredentialConsumptionResult = 'consumed' | 'replayed' | 'revoked' | 'expired' | 'unknown';
|
|
34
|
-
/**
|
|
35
|
-
* Produces the proof challenge bound to one RFC 6455 upgrade request. Both the
|
|
36
|
-
* RuntimeNode client and gateway derive this from the client-generated 128-bit
|
|
37
|
-
* `Sec-WebSocket-Key`; the result is URL-safe for the bounded proof schema.
|
|
38
|
-
*/
|
|
39
33
|
export declare function runtimeNodeWebSocketChallenge(secWebSocketKey: string): string;
|
|
40
34
|
export interface RuntimeNodeIdentityValidationPort {
|
|
41
35
|
verify(attempt: RuntimeNodeAuthenticationAttempt): Promise<unknown>;
|
|
42
36
|
isRevoked(credentialId: string, revocationVersion: number): Promise<boolean>;
|
|
43
|
-
/** Legacy 1.x listener contract; retained for source compatibility. */
|
|
44
37
|
subscribeRevocations(listener: (credentialId: string) => void): () => void;
|
|
45
38
|
}
|
|
46
|
-
/** Durable identity state changes that should immediately invalidate open channels. */
|
|
47
39
|
export type RuntimeNodeIdentityInvalidation = {
|
|
48
40
|
readonly kind: 'credential';
|
|
49
41
|
readonly credentialId: string;
|
package/dist/authentication.js
CHANGED
|
@@ -63,11 +63,6 @@ export class RuntimeNodeIdentityValidationError extends Error {
|
|
|
63
63
|
this.name = 'RuntimeNodeIdentityValidationError';
|
|
64
64
|
}
|
|
65
65
|
}
|
|
66
|
-
/**
|
|
67
|
-
* Produces the proof challenge bound to one RFC 6455 upgrade request. Both the
|
|
68
|
-
* RuntimeNode client and gateway derive this from the client-generated 128-bit
|
|
69
|
-
* `Sec-WebSocket-Key`; the result is URL-safe for the bounded proof schema.
|
|
70
|
-
*/
|
|
71
66
|
export function runtimeNodeWebSocketChallenge(secWebSocketKey) {
|
|
72
67
|
if (!/^[A-Za-z0-9+/]{22}==$/.test(secWebSocketKey)) {
|
|
73
68
|
throw new Error('RUNTIME_NODE_WEBSOCKET_KEY_INVALID');
|
|
@@ -0,0 +1,337 @@
|
|
|
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 declare function relayReplayOutcome(existing: readonly (RelayReplayReservation | undefined)[], reservation: RelayReplayReservation): 'first' | 'duplicate';
|
|
335
|
+
export declare function sha256(value: Uint8Array): Promise<`sha256:${string}`>;
|
|
336
|
+
export declare function encodeBase64Url(value: Uint8Array): string;
|
|
337
|
+
export declare function decodeBase64Url(value: string): Uint8Array;
|
|
@@ -0,0 +1,500 @@
|
|
|
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
|
+
function authorizedSender(keyring, header, now) {
|
|
351
|
+
const sender = keyring.entries.find((entry) => entry.senderKeyId === header.senderKeyId);
|
|
352
|
+
if (sender === undefined || sender.principalId !== header.senderPrincipalId) {
|
|
353
|
+
throw new AuthenticatedRelayError('RELAY_SENDER_UNAUTHENTICATED');
|
|
354
|
+
}
|
|
355
|
+
if (sender.revokedAt !== undefined && Date.parse(sender.revokedAt) <= now.getTime()) {
|
|
356
|
+
throw new AuthenticatedRelayError('RELAY_SENDER_REVOKED');
|
|
357
|
+
}
|
|
358
|
+
return sender;
|
|
359
|
+
}
|
|
360
|
+
async function sealAndSign(header, recipientPublicKey, plaintext, signer) {
|
|
361
|
+
if (header.senderKeyId !== signer.keyId) {
|
|
362
|
+
throw new AuthenticatedRelayError('RELAY_SENDER_UNAUTHENTICATED');
|
|
363
|
+
}
|
|
364
|
+
if (plaintext.byteLength + AEAD_TAG_BYTES > MAX_RELAY_CIPHERTEXT_BYTES) {
|
|
365
|
+
throw new AuthenticatedRelayError('RELAY_ENVELOPE_TOO_LARGE');
|
|
366
|
+
}
|
|
367
|
+
let sealed;
|
|
368
|
+
try {
|
|
369
|
+
sealed = await suite.seal({
|
|
370
|
+
recipientPublicKey: await suite.kem.deserializePublicKey(decodeBase64Url(recipientPublicKey)),
|
|
371
|
+
info: HPKE_INFO,
|
|
372
|
+
}, plaintext, canonicalHeader(header));
|
|
373
|
+
}
|
|
374
|
+
catch {
|
|
375
|
+
throw new AuthenticatedRelayError('RELAY_ENVELOPE_INVALID');
|
|
376
|
+
}
|
|
377
|
+
const encapsulatedKey = encodeBase64Url(new Uint8Array(sealed.enc));
|
|
378
|
+
const ciphertext = encodeBase64Url(new Uint8Array(sealed.ct));
|
|
379
|
+
const signature = await sign(signer.privateKey, await envelopeSigningInput(header, encapsulatedKey, ciphertext));
|
|
380
|
+
return { encapsulatedKey, ciphertext, signature };
|
|
381
|
+
}
|
|
382
|
+
async function openSealed(header, encapsulatedKey, ciphertext, privateKey) {
|
|
383
|
+
let plaintext;
|
|
384
|
+
try {
|
|
385
|
+
plaintext = new Uint8Array(await suite.open({
|
|
386
|
+
recipientKey: await suite.kem.deserializePrivateKey(decodeBase64Url(privateKey)),
|
|
387
|
+
enc: decodeBase64Url(encapsulatedKey),
|
|
388
|
+
info: HPKE_INFO,
|
|
389
|
+
}, decodeBase64Url(ciphertext), canonicalHeader(header)));
|
|
390
|
+
}
|
|
391
|
+
catch {
|
|
392
|
+
throw new AuthenticatedRelayError('RELAY_ENVELOPE_DECRYPTION_FAILED');
|
|
393
|
+
}
|
|
394
|
+
if ((await sha256(plaintext)) !== header.contentDigest) {
|
|
395
|
+
plaintext.fill(0);
|
|
396
|
+
throw new AuthenticatedRelayError('RELAY_ENVELOPE_DIGEST_MISMATCH');
|
|
397
|
+
}
|
|
398
|
+
return plaintext;
|
|
399
|
+
}
|
|
400
|
+
function canonicalHeader(header) {
|
|
401
|
+
return new TextEncoder().encode(canonicalJsonStringify(header));
|
|
402
|
+
}
|
|
403
|
+
async function envelopeSigningInput(header, encapsulatedKey, ciphertext) {
|
|
404
|
+
const sealed = await sha256(concat(decodeBase64Url(encapsulatedKey), decodeBase64Url(ciphertext)));
|
|
405
|
+
return new TextEncoder().encode(`${SIGNATURE_CONTEXT}\n${canonicalJsonStringify(header)}\n${sealed}`);
|
|
406
|
+
}
|
|
407
|
+
function keyringSigningInput(body) {
|
|
408
|
+
return new TextEncoder().encode(`${KEYRING_SIGNATURE_CONTEXT}\n${canonicalJsonStringify(body)}`);
|
|
409
|
+
}
|
|
410
|
+
async function sign(privateKey, data) {
|
|
411
|
+
return encodeBase64Url(new Uint8Array(await globalThis.crypto.subtle.sign('Ed25519', privateKey, Uint8Array.from(data))));
|
|
412
|
+
}
|
|
413
|
+
async function verify(publicKey, signature, data) {
|
|
414
|
+
try {
|
|
415
|
+
const key = await globalThis.crypto.subtle.importKey('raw', Uint8Array.from(decodeBase64Url(publicKey)), { name: 'Ed25519' }, false, ['verify']);
|
|
416
|
+
return await globalThis.crypto.subtle.verify('Ed25519', key, Uint8Array.from(decodeBase64Url(signature)), Uint8Array.from(data));
|
|
417
|
+
}
|
|
418
|
+
catch {
|
|
419
|
+
return false;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
export function relayReplayOutcome(existing, reservation) {
|
|
423
|
+
const seen = existing.filter((entry) => entry !== undefined);
|
|
424
|
+
if (seen.length === 0)
|
|
425
|
+
return 'first';
|
|
426
|
+
if (seen.every((entry) => entry.envelopeDigest === reservation.envelopeDigest)) {
|
|
427
|
+
return 'duplicate';
|
|
428
|
+
}
|
|
429
|
+
throw new AuthenticatedRelayError('RELAY_ENVELOPE_REPLAYED');
|
|
430
|
+
}
|
|
431
|
+
function validateLifetime(header, maximumMs, now) {
|
|
432
|
+
const { issued, expires } = validateDuration(header.issuedAt, header.expiresAt, maximumMs);
|
|
433
|
+
if (issued > now.getTime() + MAX_RELAY_CLOCK_SKEW_MS || expires <= now.getTime()) {
|
|
434
|
+
throw new AuthenticatedRelayError('RELAY_ENVELOPE_EXPIRED');
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
function validateDuration(issuedAt, expiresAt, maximumMs) {
|
|
438
|
+
const issued = Date.parse(issuedAt);
|
|
439
|
+
const expires = Date.parse(expiresAt);
|
|
440
|
+
if (!Number.isFinite(issued) ||
|
|
441
|
+
!Number.isFinite(expires) ||
|
|
442
|
+
expires <= issued ||
|
|
443
|
+
expires - issued > maximumMs) {
|
|
444
|
+
throw new AuthenticatedRelayError('RELAY_ENVELOPE_LIFETIME_INVALID');
|
|
445
|
+
}
|
|
446
|
+
return { issued, expires };
|
|
447
|
+
}
|
|
448
|
+
function randomNonce() {
|
|
449
|
+
return encodeBase64Url(globalThis.crypto.getRandomValues(new Uint8Array(NONCE_BYTES)));
|
|
450
|
+
}
|
|
451
|
+
async function rawPublicKey(prefix, privateKey, algorithm, usages) {
|
|
452
|
+
const bytes = decodeBase64Url(privateKey);
|
|
453
|
+
if (bytes.byteLength !== 32)
|
|
454
|
+
throw new AuthenticatedRelayError('RELAY_ENVELOPE_KEY_UNAVAILABLE');
|
|
455
|
+
try {
|
|
456
|
+
const key = await globalThis.crypto.subtle.importKey('pkcs8', concat(prefix, bytes), { name: algorithm }, true, usages);
|
|
457
|
+
const jwk = await globalThis.crypto.subtle.exportKey('jwk', key);
|
|
458
|
+
if (typeof jwk.x !== 'string')
|
|
459
|
+
throw new Error('no public key');
|
|
460
|
+
return jwk.x;
|
|
461
|
+
}
|
|
462
|
+
catch {
|
|
463
|
+
throw new AuthenticatedRelayError('RELAY_ENVELOPE_KEY_UNAVAILABLE');
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
function concat(left, right) {
|
|
467
|
+
const joined = new Uint8Array(left.byteLength + right.byteLength);
|
|
468
|
+
joined.set(left, 0);
|
|
469
|
+
joined.set(right, left.byteLength);
|
|
470
|
+
return joined;
|
|
471
|
+
}
|
|
472
|
+
export async function sha256(value) {
|
|
473
|
+
const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', Uint8Array.from(value)));
|
|
474
|
+
return `sha256:${[...digest].map((byte) => byte.toString(16).padStart(2, '0')).join('')}`;
|
|
475
|
+
}
|
|
476
|
+
export function encodeBase64Url(value) {
|
|
477
|
+
let binary = '';
|
|
478
|
+
for (let offset = 0; offset < value.length; offset += 0x8000) {
|
|
479
|
+
binary += String.fromCharCode(...value.subarray(offset, offset + 0x8000));
|
|
480
|
+
}
|
|
481
|
+
return globalThis.btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '');
|
|
482
|
+
}
|
|
483
|
+
export function decodeBase64Url(value) {
|
|
484
|
+
if (!/^[A-Za-z0-9_-]*$/u.test(value) || value.length % 4 === 1) {
|
|
485
|
+
throw new AuthenticatedRelayError('RELAY_ENVELOPE_INVALID');
|
|
486
|
+
}
|
|
487
|
+
const padded = `${value.replaceAll('-', '+').replaceAll('_', '/')}${'='.repeat((4 - (value.length % 4)) % 4)}`;
|
|
488
|
+
let binary;
|
|
489
|
+
try {
|
|
490
|
+
binary = globalThis.atob(padded);
|
|
491
|
+
}
|
|
492
|
+
catch {
|
|
493
|
+
throw new AuthenticatedRelayError('RELAY_ENVELOPE_INVALID');
|
|
494
|
+
}
|
|
495
|
+
const decoded = Uint8Array.from(binary, (character) => character.charCodeAt(0));
|
|
496
|
+
if (encodeBase64Url(decoded) !== value) {
|
|
497
|
+
throw new AuthenticatedRelayError('RELAY_ENVELOPE_INVALID');
|
|
498
|
+
}
|
|
499
|
+
return decoded;
|
|
500
|
+
}
|
package/dist/protocol.d.ts
CHANGED
|
@@ -695,11 +695,6 @@ export type GatewayErrorEnvelope = z.output<typeof GatewayErrorEnvelopeSchema>;
|
|
|
695
695
|
export type GatewayInventoryEnvelope = z.output<typeof GatewayInventoryEnvelopeSchema>;
|
|
696
696
|
export type GatewayHelloEnvelope = z.output<typeof GatewayHelloEnvelopeSchema>;
|
|
697
697
|
export type GatewayRetainedCommandOutcome = z.output<typeof GatewayRetainedCommandOutcomeSchema>;
|
|
698
|
-
/**
|
|
699
|
-
* Shared gateway protocol schemas (M13 #405 hoist): the grant reference shape
|
|
700
|
-
* and the canonical runtime-error envelope, byte-identical across the ACP and
|
|
701
|
-
* managed-Pi gateway clients.
|
|
702
|
-
*/
|
|
703
698
|
export declare const GrantReferenceSchema: z.ZodString;
|
|
704
699
|
export type GrantReference = z.output<typeof GrantReferenceSchema>;
|
|
705
700
|
export declare const RuntimeErrorDataSchema: z.ZodObject<{
|
package/dist/protocol.js
CHANGED
|
@@ -497,11 +497,6 @@ function forbiddenKeyMatches(normalizedKey, forbidden) {
|
|
|
497
497
|
'sessiontoken',
|
|
498
498
|
].includes(normalizedKey));
|
|
499
499
|
}
|
|
500
|
-
/**
|
|
501
|
-
* Shared gateway protocol schemas (M13 #405 hoist): the grant reference shape
|
|
502
|
-
* and the canonical runtime-error envelope, byte-identical across the ACP and
|
|
503
|
-
* managed-Pi gateway clients.
|
|
504
|
-
*/
|
|
505
500
|
export const GrantReferenceSchema = z
|
|
506
501
|
.string()
|
|
507
502
|
.min(16)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adea-ai/runtime-gateway-protocol",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.12.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
|
},
|
|
@@ -41,14 +45,17 @@
|
|
|
41
45
|
},
|
|
42
46
|
"scripts": {
|
|
43
47
|
"build": "tsc -p tsconfig.json",
|
|
44
|
-
"typecheck": "bun check -p tsconfig.json",
|
|
48
|
+
"typecheck": "bun check -p tsconfig.json && bun check -p tsconfig.scripts.json",
|
|
45
49
|
"lint": "oxlint src",
|
|
46
|
-
"schema:check": "bun scripts/schema.
|
|
47
|
-
"schema:generate": "bun scripts/schema.
|
|
48
|
-
"test": "bun scripts/schema.
|
|
50
|
+
"schema:check": "bun scripts/schema.ts --check",
|
|
51
|
+
"schema:generate": "bun scripts/schema.ts",
|
|
52
|
+
"test": "bun scripts/schema.ts --check && bun test src"
|
|
49
53
|
},
|
|
50
54
|
"dependencies": {
|
|
51
|
-
"@adea-ai/
|
|
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": {
|