@celljs/ta-gateway 4.16.0 → 4.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.en.md +5 -2
  2. package/README.md +5 -2
  3. package/esm/node/docker-engine.d.ts +5 -1
  4. package/esm/node/docker-engine.js +7 -1
  5. package/esm/node/docker-sandbox.d.ts +10 -1
  6. package/esm/node/docker-sandbox.js +24 -5
  7. package/esm/node/egress-proxy.d.ts +98 -0
  8. package/esm/node/egress-proxy.js +428 -0
  9. package/esm/node/environments.d.ts +5 -2
  10. package/esm/node/environments.js +4 -2
  11. package/esm/node/gateway-cli.js +12 -5
  12. package/esm/node/gateway-policy.d.ts +6 -1
  13. package/esm/node/gateway-policy.js +10 -1
  14. package/esm/node/gateway-quotas.d.ts +6 -1
  15. package/esm/node/gateway-quotas.js +17 -0
  16. package/esm/node/gateway-server.d.ts +31 -0
  17. package/esm/node/gateway-server.js +131 -13
  18. package/esm/node/gateway-service-util.d.ts +41 -0
  19. package/esm/node/gateway-service-util.js +178 -0
  20. package/esm/node/gateway-service.d.ts +5 -41
  21. package/esm/node/gateway-service.js +19 -173
  22. package/esm/node/gateway-socket.d.ts +1 -1
  23. package/esm/node/gateway-socket.js +1 -1
  24. package/esm/node/index.d.ts +4 -0
  25. package/esm/node/index.js +4 -0
  26. package/esm/node/kubernetes-api.d.ts +35 -0
  27. package/esm/node/kubernetes-api.js +115 -0
  28. package/esm/node/kubernetes-sandbox.d.ts +198 -0
  29. package/esm/node/kubernetes-sandbox.js +279 -0
  30. package/esm/node/sandbox-provider.d.ts +11 -1
  31. package/esm/node/sandbox-provider.js +2 -1
  32. package/esm/node/tenant-store.d.ts +15 -0
  33. package/esm/node/tenant-store.js +15 -0
  34. package/lib/node/docker-engine.d.ts +5 -1
  35. package/lib/node/docker-engine.js +7 -1
  36. package/lib/node/docker-sandbox.d.ts +10 -1
  37. package/lib/node/docker-sandbox.js +24 -5
  38. package/lib/node/egress-proxy.d.ts +99 -0
  39. package/lib/node/egress-proxy.js +433 -0
  40. package/lib/node/environments.d.ts +5 -2
  41. package/lib/node/environments.js +4 -2
  42. package/lib/node/gateway-cli.js +12 -5
  43. package/lib/node/gateway-policy.d.ts +6 -1
  44. package/lib/node/gateway-policy.js +10 -1
  45. package/lib/node/gateway-quotas.d.ts +6 -1
  46. package/lib/node/gateway-quotas.js +17 -0
  47. package/lib/node/gateway-server.d.ts +31 -0
  48. package/lib/node/gateway-server.js +129 -11
  49. package/lib/node/gateway-service-util.d.ts +42 -0
  50. package/lib/node/gateway-service-util.js +182 -0
  51. package/lib/node/gateway-service.d.ts +5 -41
  52. package/lib/node/gateway-service.js +41 -196
  53. package/lib/node/gateway-socket.d.ts +1 -1
  54. package/lib/node/gateway-socket.js +10 -10
  55. package/lib/node/index.d.ts +4 -0
  56. package/lib/node/index.js +4 -0
  57. package/lib/node/kubernetes-api.d.ts +36 -0
  58. package/lib/node/kubernetes-api.js +120 -0
  59. package/lib/node/kubernetes-sandbox.d.ts +199 -0
  60. package/lib/node/kubernetes-sandbox.js +283 -0
  61. package/lib/node/sandbox-provider.d.ts +11 -1
  62. package/lib/node/sandbox-provider.js +2 -1
  63. package/lib/node/tenant-store.d.ts +15 -0
  64. package/lib/node/tenant-store.js +15 -0
  65. package/package.json +4 -4
@@ -0,0 +1,279 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { DockerSandboxUtil } from './docker-sandbox.js';
3
+ import { KubernetesApi, KubernetesError, KubernetesUtil } from './kubernetes-api.js';
4
+ import { SandboxConfigError, SandboxProviders, } from './sandbox-provider.js';
5
+ /** The resources of kubernetes-sigs/agent-sandbox the provider makes. */
6
+ const GROUP = '/apis/agents.x-k8s.io/v1beta1';
7
+ /** The port of ta serve in the image (its Dockerfile). */
8
+ const PORT = 4100;
9
+ export var KubernetesSandboxUtil;
10
+ (function (KubernetesSandboxUtil) {
11
+ /** The annotation of a Sandbox and its pod that tells the environment the gateway gave it (as `cell.ta.env` of docker). */
12
+ KubernetesSandboxUtil.ENV_ANNOTATION = 'cell.ta/env';
13
+ KubernetesSandboxUtil.COMPONENT = 'ta-sandbox';
14
+ function options(config, inCluster) {
15
+ var _a, _b, _c, _d, _e;
16
+ const text = (key, fallback) => SandboxProviders.string(config, key, fallback);
17
+ const cpus = (_a = config.cpus) !== null && _a !== void 0 ? _a : 2;
18
+ if (typeof cpus !== 'number' || cpus <= 0) {
19
+ throw new SandboxConfigError('"cpus" of a provider of the type kubernetes is a number above 0.');
20
+ }
21
+ const memory = String((_b = config.memory) !== null && _b !== void 0 ? _b : '4Gi');
22
+ const storage = String((_c = config.storage) !== null && _c !== void 0 ? _c : '10Gi');
23
+ for (const [key, value] of [
24
+ ['memory', memory],
25
+ ['storage', storage],
26
+ ]) {
27
+ if (!KubernetesUtil.quantity(value)) {
28
+ throw new SandboxConfigError(`"${key}" of a provider of the type kubernetes is a quantity such as 4Gi.`);
29
+ }
30
+ }
31
+ const strings = (key) => {
32
+ const value = config[key];
33
+ if (value !== undefined && (!Array.isArray(value) || value.some(item => typeof item !== 'string'))) {
34
+ throw new SandboxConfigError(`"${key}" of a provider of the type kubernetes is a list of strings.`);
35
+ }
36
+ return value;
37
+ };
38
+ const selector = config.nodeSelector;
39
+ if (selector !== undefined &&
40
+ (typeof selector !== 'object' || Array.isArray(selector) || Object.values(selector).some(item => typeof item !== 'string'))) {
41
+ throw new SandboxConfigError('"nodeSelector" of a provider of the type kubernetes is an object of strings.');
42
+ }
43
+ const prefix = text('prefix', 'ta-');
44
+ if (!/^[a-z][a-z0-9-]{0,20}$/.test(prefix)) {
45
+ throw new SandboxConfigError('"prefix" of a provider of the type kubernetes starts with a letter: lower-case letters, digits and -.');
46
+ }
47
+ return {
48
+ image: text('image', 'ta:latest'),
49
+ imagePullPolicy: text('imagePullPolicy'),
50
+ namespace: (_e = (_d = text('namespace')) !== null && _d !== void 0 ? _d : inCluster === null || inCluster === void 0 ? void 0 : inCluster().namespace) !== null && _e !== void 0 ? _e : 'default',
51
+ memory,
52
+ cpus,
53
+ storage,
54
+ storageClass: text('storageClass'),
55
+ runtimeClass: text('runtimeClass'),
56
+ prefix,
57
+ env: SandboxProviders.env(config),
58
+ nodeSelector: selector,
59
+ imagePullSecrets: strings('imagePullSecrets'),
60
+ clusterDomain: text('clusterDomain', 'cluster.local'),
61
+ };
62
+ }
63
+ KubernetesSandboxUtil.options = options;
64
+ /** The API: `server` and `token` (`$NAME`: of the gateway's environment) of the configuration, else the pod's own. */
65
+ function api(config, env = process.env) {
66
+ const server = SandboxProviders.string(config, 'server');
67
+ if (!server) {
68
+ return new KubernetesApi(KubernetesApi.inCluster(env));
69
+ }
70
+ const given = SandboxProviders.string(config, 'token');
71
+ const token = (given === null || given === void 0 ? void 0 : given.startsWith('$')) ? env[given.slice(1).replace(/^\{|\}$/g, '')] : given;
72
+ const caFile = SandboxProviders.string(config, 'caFile');
73
+ return new KubernetesApi({ server, token, ...(caFile ? { ca: readFileSync(caFile, 'utf8') } : {}) });
74
+ }
75
+ KubernetesSandboxUtil.api = api;
76
+ function ready(sandbox) {
77
+ var _a, _b;
78
+ var _c;
79
+ return (_c = (_b = (_a = sandbox === null || sandbox === void 0 ? void 0 : sandbox.status) === null || _a === void 0 ? void 0 : _a.conditions) === null || _b === void 0 ? void 0 : _b.some(condition => condition.type === 'Ready' && condition.status === 'True')) !== null && _c !== void 0 ? _c : false;
80
+ }
81
+ KubernetesSandboxUtil.ready = ready;
82
+ })(KubernetesSandboxUtil || (KubernetesSandboxUtil = {}));
83
+ /**
84
+ * `kubernetes`: a Sandbox of kubernetes-sigs/agent-sandbox per tenant (docs/design/ta-deploy.md 6): a pod of ta serve,
85
+ * its home in a volume of its own that stays while it is suspended, a headless Service for a stable address. Stopping
86
+ * suspends it (the pod goes, the volume stays); its token and the environment of the gateway are in a Secret of its
87
+ * own, not in the Sandbox, which more people may read.
88
+ */
89
+ export class KubernetesSandbox {
90
+ constructor(id, config, api, options = KubernetesSandboxUtil.options(config, () => KubernetesApi.inCluster())) {
91
+ this.id = id;
92
+ this.options = options;
93
+ this.type = 'kubernetes';
94
+ /** A first pull of the image and a volume to bind take longer than a container. */
95
+ this.readyTimeoutMs = 5 * 60 * 1000;
96
+ this.name = SandboxProviders.string(config, 'name', 'Kubernetes');
97
+ this.gatewayUrl = SandboxProviders.string(config, 'gatewayUrl');
98
+ this.api = api !== null && api !== void 0 ? api : KubernetesSandboxUtil.api(config);
99
+ }
100
+ async start(tenant) {
101
+ var _a;
102
+ const name = this.resourceName(tenant);
103
+ const hash = DockerSandboxUtil.envHash(tenant.env);
104
+ let sandbox = await this.read(name);
105
+ if (!sandbox) {
106
+ sandbox = await this.api.call('POST', this.path(), this.manifest(tenant));
107
+ await this.putSecret(tenant, sandbox);
108
+ }
109
+ else {
110
+ await this.putSecret(tenant, sandbox);
111
+ const changed = ((_a = sandbox.metadata.annotations) === null || _a === void 0 ? void 0 : _a[KubernetesSandboxUtil.ENV_ANNOTATION]) !== hash;
112
+ if (changed || sandbox.spec.operatingMode === 'Suspended') {
113
+ // Its pod is made from the template when it starts: the one with another environment goes, the volume stays.
114
+ const { metadata, spec } = this.manifest(tenant);
115
+ await this.api.call('PATCH', this.path(name), { metadata: { annotations: metadata.annotations }, spec }, 'application/merge-patch+json');
116
+ if (changed && sandbox.spec.operatingMode !== 'Suspended') {
117
+ await this.deletePod(name);
118
+ }
119
+ }
120
+ }
121
+ return { url: `http://${name}.${this.options.namespace}.svc.${this.options.clusterDomain}:${PORT}`, token: tenant.token };
122
+ }
123
+ async stop(tenant) {
124
+ const name = this.resourceName(tenant);
125
+ if (await this.read(name)) {
126
+ await this.api.call('PATCH', this.path(name), { spec: { operatingMode: 'Suspended' } }, 'application/merge-patch+json');
127
+ }
128
+ }
129
+ async state(tenant) {
130
+ const sandbox = await this.read(this.resourceName(tenant));
131
+ return !sandbox ? 'missing' : sandbox.spec.operatingMode === 'Suspended' ? 'stopped' : 'running';
132
+ }
133
+ /** From metrics.k8s.io, when the cluster has metrics-server. */
134
+ async usage(tenant) {
135
+ var _a, _b;
136
+ const name = this.resourceName(tenant);
137
+ const metrics = await this.api
138
+ .call('GET', `/apis/metrics.k8s.io/v1beta1/namespaces/${this.options.namespace}/pods/${name}`)
139
+ .catch(() => undefined);
140
+ const usage = (_b = (_a = metrics === null || metrics === void 0 ? void 0 : metrics.containers) === null || _a === void 0 ? void 0 : _a.find(container => container.name === 'ta')) === null || _b === void 0 ? void 0 : _b.usage;
141
+ if (!usage) {
142
+ return undefined;
143
+ }
144
+ const cpu = KubernetesUtil.quantity(usage.cpu);
145
+ return {
146
+ cpu: cpu === undefined ? undefined : Math.round(cpu * 1000) / 10,
147
+ memory: KubernetesUtil.quantity(usage.memory),
148
+ memoryLimit: KubernetesUtil.quantity(this.options.memory),
149
+ };
150
+ }
151
+ logs(tenant, lines) {
152
+ const name = this.resourceName(tenant);
153
+ return this.api
154
+ .text(`/api/v1/namespaces/${this.options.namespace}/pods/${name}/log?container=ta&tailLines=${Math.max(1, Math.floor(lines))}`)
155
+ .catch(error => (error instanceof KubernetesError && error.status === 404 ? '' : Promise.reject(error)));
156
+ }
157
+ /** The Sandbox of a tenant, as the API is given it. */
158
+ manifest(tenant) {
159
+ var _a;
160
+ const name = this.resourceName(tenant);
161
+ const hash = DockerSandboxUtil.envHash(tenant.env);
162
+ const labels = { 'app.kubernetes.io/name': 'ta', 'app.kubernetes.io/component': KubernetesSandboxUtil.COMPONENT, 'cell.ta/tenant': tenant.id };
163
+ const options = this.options;
164
+ return {
165
+ apiVersion: 'agents.x-k8s.io/v1beta1',
166
+ kind: 'Sandbox',
167
+ metadata: { name, labels, annotations: { [KubernetesSandboxUtil.ENV_ANNOTATION]: hash, 'cell.ta/account': tenant.account } },
168
+ spec: {
169
+ operatingMode: 'Running',
170
+ service: true,
171
+ failedPodPolicy: 'Recreate',
172
+ podTemplate: {
173
+ metadata: { labels, annotations: { [KubernetesSandboxUtil.ENV_ANNOTATION]: hash } },
174
+ spec: {
175
+ // Nothing of the cluster's API in a sandbox, nor the addresses of its services.
176
+ automountServiceAccountToken: false,
177
+ enableServiceLinks: false,
178
+ // What the Ta of the tenant tells its clients its machine is.
179
+ hostname: DockerSandboxUtil.hostname(tenant.account),
180
+ securityContext: { runAsUser: 1000, runAsGroup: 1000, fsGroup: 1000, seccompProfile: { type: 'RuntimeDefault' } },
181
+ ...(options.runtimeClass ? { runtimeClassName: options.runtimeClass } : {}),
182
+ ...(options.nodeSelector ? { nodeSelector: options.nodeSelector } : {}),
183
+ ...(((_a = options.imagePullSecrets) === null || _a === void 0 ? void 0 : _a.length) ? { imagePullSecrets: options.imagePullSecrets.map(secret => ({ name: secret })) } : {}),
184
+ containers: [
185
+ {
186
+ name: 'ta',
187
+ image: options.image,
188
+ ...(options.imagePullPolicy ? { imagePullPolicy: options.imagePullPolicy } : {}),
189
+ // A new volume is empty: the workspace the image has is made in it, by its user (the
190
+ // runtime would make the image's WORKDIR in the volume as root).
191
+ workingDir: '/home/ta',
192
+ command: [
193
+ 'tini',
194
+ '--',
195
+ 'sh',
196
+ '-c',
197
+ `mkdir -p /home/ta/workspace && cd /home/ta/workspace && exec ta serve --host 0.0.0.0 --port ${PORT}`,
198
+ ],
199
+ envFrom: [{ secretRef: { name } }],
200
+ ports: [{ name: 'ta', containerPort: PORT }],
201
+ resources: {
202
+ limits: { memory: options.memory, cpu: String(options.cpus) },
203
+ requests: { memory: '256Mi', cpu: '100m' },
204
+ },
205
+ // A tenant is root in its sandbox (sudo), as in docker: without raw sockets it cannot forge packets.
206
+ securityContext: { capabilities: { drop: ['NET_RAW'] } },
207
+ readinessProbe: { httpGet: { path: '/', port: PORT }, periodSeconds: 5, failureThreshold: 3 },
208
+ volumeMounts: [{ name: 'home', mountPath: '/home/ta' }],
209
+ },
210
+ ],
211
+ },
212
+ },
213
+ volumeClaimTemplates: [
214
+ {
215
+ metadata: { name: 'home', labels },
216
+ spec: {
217
+ accessModes: ['ReadWriteOnce'],
218
+ resources: { requests: { storage: options.storage } },
219
+ ...(options.storageClass ? { storageClassName: options.storageClass } : {}),
220
+ },
221
+ },
222
+ ],
223
+ },
224
+ };
225
+ }
226
+ /** Its token and the environment of the gateway, owned by its Sandbox, which takes it along when it goes. */
227
+ async putSecret(tenant, sandbox) {
228
+ const name = this.resourceName(tenant);
229
+ const env = { ...this.options.env, ...tenant.env, TA_SERVE_TOKEN: tenant.token };
230
+ const secret = {
231
+ apiVersion: 'v1',
232
+ kind: 'Secret',
233
+ metadata: {
234
+ name,
235
+ labels: { 'app.kubernetes.io/name': 'ta', 'app.kubernetes.io/component': KubernetesSandboxUtil.COMPONENT, 'cell.ta/tenant': tenant.id },
236
+ ...(sandbox.metadata.uid
237
+ ? { ownerReferences: [{ apiVersion: 'agents.x-k8s.io/v1beta1', kind: 'Sandbox', name, uid: sandbox.metadata.uid }] }
238
+ : {}),
239
+ },
240
+ type: 'Opaque',
241
+ stringData: env,
242
+ };
243
+ const path = `/api/v1/namespaces/${this.options.namespace}/secrets`;
244
+ try {
245
+ await this.api.call('PUT', `${path}/${name}`, secret);
246
+ }
247
+ catch (error) {
248
+ if (!(error instanceof KubernetesError && error.status === 404)) {
249
+ throw error;
250
+ }
251
+ await this.api.call('POST', path, secret);
252
+ }
253
+ }
254
+ async deletePod(name) {
255
+ await this.api.call('DELETE', `/api/v1/namespaces/${this.options.namespace}/pods/${name}`).catch(error => {
256
+ if (!(error instanceof KubernetesError && error.status === 404)) {
257
+ throw error;
258
+ }
259
+ });
260
+ }
261
+ async read(name) {
262
+ try {
263
+ return await this.api.call('GET', this.path(name));
264
+ }
265
+ catch (error) {
266
+ if (error instanceof KubernetesError && error.status === 404) {
267
+ return undefined;
268
+ }
269
+ throw error;
270
+ }
271
+ }
272
+ path(name) {
273
+ return `${GROUP}/namespaces/${this.options.namespace}/sandboxes${name ? `/${name}` : ''}`;
274
+ }
275
+ resourceName(tenant) {
276
+ return `${this.options.prefix}${tenant.id}`;
277
+ }
278
+ }
279
+ //# sourceMappingURL=kubernetes-sandbox.js.map
@@ -1,3 +1,4 @@
1
+ import type { EgressConfig } from './egress-proxy.js';
1
2
  /** A tenant, as a provider of sandboxes sees it: `token` is the one its Ta service must take (TA_SERVE_TOKEN). */
2
3
  export interface SandboxTenant {
3
4
  id: string;
@@ -5,7 +6,8 @@ export interface SandboxTenant {
5
6
  token: string;
6
7
  /**
7
8
  * More of the environment of its Ta service: TA_MODEL_PROXY_URL and TA_MODEL_PROXY_KEY, by which it takes the
8
- * models of the gateway (ta-host GatewayModels). A provider that makes a sandbox once remakes it when they change.
9
+ * models of the gateway (ta-host GatewayModels), and HTTPS_PROXY and the like, by which it goes out through the
10
+ * gateway. A provider that makes a sandbox once remakes it when they change.
9
11
  */
10
12
  env?: Record<string, string>;
11
13
  }
@@ -53,6 +55,8 @@ export interface SandboxProvider {
53
55
  export interface SandboxContext {
54
56
  /** The directory of the gateway: a module's path is relative to it, `local` keeps its tenants there. */
55
57
  dir: string;
58
+ /** Where sandboxes.json is, when not in `dir`: a module's path is relative to it then. */
59
+ config?: string;
56
60
  /** How to run `ta`: the Node.js executable and the entry of the command. */
57
61
  taCommand: string[];
58
62
  }
@@ -72,6 +76,12 @@ export interface SandboxesConfig {
72
76
  ownEnvironments?: boolean;
73
77
  /** Stops a sandbox nobody is connected to after this long; 0, the default, keeps it running (scheduled tasks, the double's work). */
74
78
  idleMinutes?: number;
79
+ /**
80
+ * Whether the sandboxes go out through the proxy of the gateway, with credentials of their epoch, and the private
81
+ * networks they may reach too: `true` or `{ "networks": ["10.0.0.0/8"] }`. The firewall of the machine is to let
82
+ * them out to the gateway only (docs/design/ta-cloud.md 3.5).
83
+ */
84
+ egress?: EgressConfig;
75
85
  }
76
86
  export declare class SandboxConfigError extends Error {
77
87
  }
@@ -49,10 +49,11 @@ export var SandboxProviders;
49
49
  SandboxProviders.create = create;
50
50
  /** `{ "type": "module", "path": "./my-sandbox.mjs" }`: its default export is a SandboxProviderFactory. */
51
51
  async function loadModule(entry, context) {
52
+ var _a;
52
53
  if (typeof entry.path !== 'string' || !entry.path) {
53
54
  throw new SandboxConfigError('A provider of the type "module" names its file in "path".');
54
55
  }
55
- const path = isAbsolute(entry.path) ? entry.path : join(context.dir, entry.path);
56
+ const path = isAbsolute(entry.path) ? entry.path : join((_a = context.config) !== null && _a !== void 0 ? _a : context.dir, entry.path);
56
57
  const loaded = (await import(pathToFileURL(path).href));
57
58
  if (typeof loaded.default !== 'function') {
58
59
  throw new SandboxConfigError(`${path} has no default export of a function (id, config, context) => SandboxProvider.`);
@@ -8,6 +8,8 @@ export interface TenantMeter {
8
8
  /** Tokens and dollars of calls of models through the gateway. */
9
9
  tokens?: number;
10
10
  cost?: number;
11
+ /** Bytes its sandbox moved through the proxy of the gateway. */
12
+ egressBytes?: number;
11
13
  }
12
14
  /** A tenant: an account and its Ta, wherever it runs. */
13
15
  export interface Tenant {
@@ -27,6 +29,14 @@ export interface Tenant {
27
29
  meter?: TenantMeter;
28
30
  /** What its sandbox calls the models of the gateway with: it reaches no key of a provider. */
29
31
  modelKey?: string;
32
+ /**
33
+ * What its sandbox goes out through the proxy of the gateway with: the epoch of the sandbox, one more each time
34
+ * the gateway makes it anew, and its secret. Those of an epoch before are refused.
35
+ */
36
+ egress?: {
37
+ epoch: number;
38
+ secret: string;
39
+ };
30
40
  }
31
41
  /** Files written whole or not at all, readable by this user only. */
32
42
  export declare function writePrivate(file: string, data: unknown): void;
@@ -49,6 +59,11 @@ export declare class TenantStore {
49
59
  update(id: string, change: Partial<Omit<Tenant, 'id' | 'account' | 'token'>>): Tenant;
50
60
  /** Its model key, made for a tenant of before. */
51
61
  modelKey(id: string): string;
62
+ /** The credentials of its sandbox's way out: of a new epoch when `renew` (a sandbox made anew), or when it has none. */
63
+ egressKey(id: string, renew: boolean): {
64
+ epoch: number;
65
+ secret: string;
66
+ };
52
67
  list(): Tenant[];
53
68
  protected save(tenant: Tenant): void;
54
69
  }
@@ -79,6 +79,21 @@ export class TenantStore {
79
79
  }
80
80
  return (_a = tenant.modelKey) !== null && _a !== void 0 ? _a : this.update(id, { modelKey: `tam-${randomBytes(24).toString('base64url')}` }).modelKey;
81
81
  }
82
+ /** The credentials of its sandbox's way out: of a new epoch when `renew` (a sandbox made anew), or when it has none. */
83
+ egressKey(id, renew) {
84
+ var _a;
85
+ var _b;
86
+ const tenant = this.get(id);
87
+ if (!tenant) {
88
+ throw new Error(`No tenant ${id}`);
89
+ }
90
+ if (tenant.egress && !renew) {
91
+ return tenant.egress;
92
+ }
93
+ const egress = { epoch: ((_b = (_a = tenant.egress) === null || _a === void 0 ? void 0 : _a.epoch) !== null && _b !== void 0 ? _b : 0) + 1, secret: randomBytes(24).toString('base64url') };
94
+ this.update(id, { egress });
95
+ return egress;
96
+ }
82
97
  list() {
83
98
  return readdirSync(this.dir)
84
99
  .filter(name => /^[0-9a-f]{16}\.json$/.test(name))
@@ -45,7 +45,10 @@ export declare class DockerEngine {
45
45
  logs(name: string, lines: number): Promise<string>;
46
46
  /** Removed, its volumes kept; nothing when it is not there. */
47
47
  remove(name: string): Promise<void>;
48
- /** A bridge network, made when missing; `isolated`: its containers cannot reach each other. */
48
+ /**
49
+ * A bridge network, made when missing; `isolated`: its containers cannot reach each other. Its interface on the
50
+ * host has its name (when it fits one), for the firewall to name it (deploy/compose/isolate.sh: `-i ta-sandbox`).
51
+ */
49
52
  ensureNetwork(name: string, isolated: boolean): Promise<void>;
50
53
  /** Pulled when it is not here; one built here (ta:latest) is. */
51
54
  ensureImage(image: string): Promise<void>;
@@ -54,6 +57,7 @@ export interface DockerContainer {
54
57
  Id: string;
55
58
  Config?: {
56
59
  Env?: string[];
60
+ Labels?: Record<string, string>;
57
61
  };
58
62
  State: {
59
63
  Running: boolean;
@@ -147,7 +147,10 @@ class DockerEngine {
147
147
  }
148
148
  }
149
149
  }
150
- /** A bridge network, made when missing; `isolated`: its containers cannot reach each other. */
150
+ /**
151
+ * A bridge network, made when missing; `isolated`: its containers cannot reach each other. Its interface on the
152
+ * host has its name (when it fits one), for the firewall to name it (deploy/compose/isolate.sh: `-i ta-sandbox`).
153
+ */
151
154
  async ensureNetwork(name, isolated) {
152
155
  try {
153
156
  await this.call('GET', `/networks/${encodeURIComponent(name)}`);
@@ -159,6 +162,9 @@ class DockerEngine {
159
162
  }
160
163
  }
161
164
  const options = isolated ? { 'com.docker.network.bridge.enable_icc': 'false' } : {};
165
+ if (/^[a-zA-Z0-9_.-]{1,15}$/.test(name)) {
166
+ options['com.docker.network.bridge.name'] = name;
167
+ }
162
168
  await this.call('POST', '/networks/create', { Name: name, Driver: 'bridge', Options: options, Labels: { 'cell.ta.gateway': '1' } });
163
169
  }
164
170
  /** Pulled when it is not here; one built here (ta:latest) is. */
@@ -1,6 +1,15 @@
1
- import { DockerEngine } from './docker-engine';
1
+ import { type DockerContainer, DockerEngine } from './docker-engine';
2
2
  import { type SandboxEndpoint, type SandboxProvider, type SandboxProviderConfig, type SandboxState, type SandboxTenant, type SandboxUsage } from './sandbox-provider';
3
3
  export declare namespace DockerSandboxUtil {
4
+ /** The label of a container that tells the environment the gateway gave it. */
5
+ const ENV_LABEL = "cell.ta.env";
6
+ /** Of the environment the gateway gives a sandbox, whatever its order. */
7
+ function envHash(env: Record<string, string> | undefined): string;
8
+ /**
9
+ * Whether a container was made with the environment the gateway gives it now: by its label, so that a variable
10
+ * taken away (the way out turned off) counts too; one made before the label, by its variables.
11
+ */
12
+ function sameEnv(config: DockerContainer['Config'], want: Record<string, string> | undefined): boolean;
4
13
  /** Whether a container has each variable of `env` as it is. */
5
14
  function hasEnv(have: string[] | undefined, want: Record<string, string> | undefined): boolean;
6
15
  /** `github:Octo.Cat` → `octo-cat`: a name of a host from the account, `ta` when nothing is left. */
@@ -1,10 +1,29 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DockerSandbox = exports.DockerSandboxUtil = void 0;
4
+ const node_crypto_1 = require("node:crypto");
4
5
  const docker_engine_1 = require("./docker-engine");
5
6
  const sandbox_provider_1 = require("./sandbox-provider");
6
7
  var DockerSandboxUtil;
7
8
  (function (DockerSandboxUtil) {
9
+ /** The label of a container that tells the environment the gateway gave it. */
10
+ DockerSandboxUtil.ENV_LABEL = 'cell.ta.env';
11
+ /** Of the environment the gateway gives a sandbox, whatever its order. */
12
+ function envHash(env) {
13
+ const entries = Object.entries(env !== null && env !== void 0 ? env : {}).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
14
+ return (0, node_crypto_1.createHash)('sha256').update(JSON.stringify(entries)).digest('hex').slice(0, 16);
15
+ }
16
+ DockerSandboxUtil.envHash = envHash;
17
+ /**
18
+ * Whether a container was made with the environment the gateway gives it now: by its label, so that a variable
19
+ * taken away (the way out turned off) counts too; one made before the label, by its variables.
20
+ */
21
+ function sameEnv(config, want) {
22
+ var _a;
23
+ const made = (_a = config === null || config === void 0 ? void 0 : config.Labels) === null || _a === void 0 ? void 0 : _a[DockerSandboxUtil.ENV_LABEL];
24
+ return made !== undefined ? made === envHash(want) : hasEnv(config === null || config === void 0 ? void 0 : config.Env, want);
25
+ }
26
+ DockerSandboxUtil.sameEnv = sameEnv;
8
27
  /** Whether a container has each variable of `env` as it is. */
9
28
  function hasEnv(have, want) {
10
29
  const set = new Set(have !== null && have !== void 0 ? have : []);
@@ -65,11 +84,11 @@ class DockerSandbox {
65
84
  this.engine = engine !== null && engine !== void 0 ? engine : new docker_engine_1.DockerEngine({ host: options.host });
66
85
  }
67
86
  async start(tenant) {
68
- var _a, _b, _c, _d;
87
+ var _a, _b, _c;
69
88
  const name = this.containerName(tenant);
70
89
  let container = await this.engine.inspect(name);
71
- if (container && !DockerSandboxUtil.hasEnv((_a = container.Config) === null || _a === void 0 ? void 0 : _a.Env, tenant.env)) {
72
- // Made before the gateway gave it this environment (the models of the gateway): made again, its volume kept.
90
+ if (container && !DockerSandboxUtil.sameEnv(container.Config, tenant.env)) {
91
+ // Made with another environment (the models of the gateway, its way out): made again, its volume kept.
73
92
  await this.engine.remove(name);
74
93
  container = undefined;
75
94
  }
@@ -83,7 +102,7 @@ class DockerSandbox {
83
102
  await this.engine.start(name);
84
103
  container = await this.engine.inspect(name);
85
104
  }
86
- const port = (_d = (_c = (_b = container === null || container === void 0 ? void 0 : container.NetworkSettings.Ports) === null || _b === void 0 ? void 0 : _b[PORT]) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.HostPort;
105
+ const port = (_c = (_b = (_a = container === null || container === void 0 ? void 0 : container.NetworkSettings.Ports) === null || _a === void 0 ? void 0 : _a[PORT]) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.HostPort;
87
106
  if (!port) {
88
107
  throw new Error(`The container ${name} publishes no port for ${PORT}.`);
89
108
  }
@@ -110,7 +129,7 @@ class DockerSandbox {
110
129
  // What the Ta of the tenant tells its clients its machine is, as the list of computers of the phone shows it.
111
130
  Hostname: DockerSandboxUtil.hostname(tenant.account),
112
131
  Env: [`TA_SERVE_TOKEN=${tenant.token}`, ...Object.entries({ ...this.options.env, ...tenant.env }).map(([key, value]) => `${key}=${value}`)],
113
- Labels: { 'cell.ta.tenant': tenant.id, 'cell.ta.account': tenant.account },
132
+ Labels: { 'cell.ta.tenant': tenant.id, 'cell.ta.account': tenant.account, [DockerSandboxUtil.ENV_LABEL]: DockerSandboxUtil.envHash(tenant.env) },
114
133
  ExposedPorts: { [PORT]: {} },
115
134
  HostConfig: {
116
135
  PortBindings: { [PORT]: [{ HostIp: this.options.bind, HostPort: '' }] },
@@ -0,0 +1,99 @@
1
+ import { type IncomingHttpHeaders, type IncomingMessage, type ServerResponse } from 'node:http';
2
+ import { BlockList } from 'node:net';
3
+ import type { Duplex } from 'node:stream';
4
+ import type { TaEgressRefusal } from '@celljs/ta-protocol';
5
+ /** `egress` of sandboxes.json: true, or the private networks the sandboxes may reach too. */
6
+ export type EgressConfig = boolean | {
7
+ networks?: string[];
8
+ };
9
+ export interface EgressSettings {
10
+ enabled: boolean;
11
+ /** Private networks (CIDR) the sandboxes may reach too: never this machine, loopback or link-local. */
12
+ networks: string[];
13
+ }
14
+ export declare class EgressConfigError extends Error {
15
+ }
16
+ /** Where a sandbox wants to go. */
17
+ export interface EgressTarget {
18
+ host: string;
19
+ port: number;
20
+ }
21
+ /** Whom the credentials of a request are: their hosts (none: any public host), or why they are refused. */
22
+ export type EgressAuthorization = {
23
+ tenantId: string;
24
+ hosts?: string[];
25
+ } | {
26
+ status: 403 | 407;
27
+ message: string;
28
+ };
29
+ export interface EgressHooks {
30
+ authorize(user: string, password: string): EgressAuthorization;
31
+ }
32
+ export declare namespace EgressProxyUtil {
33
+ function settings(config: EgressConfig | undefined): EgressSettings;
34
+ /** `10.0.0.0/8`, `fd00::/8` or one address, as a list to check addresses against. */
35
+ function networksOf(networks: readonly string[]): BlockList;
36
+ /** The hosts an owner lets members reach, cleaned: lower-case, one each, at most 200. */
37
+ function hosts(value: unknown): string[];
38
+ /** The user and password of `Proxy-Authorization: Basic …`. */
39
+ function credentials(header: string | undefined): {
40
+ user: string;
41
+ password: string;
42
+ } | undefined;
43
+ /** `host:port` of CONNECT, `[::1]:443` too. */
44
+ function target(authority: string, fallbackPort: number): EgressTarget | undefined;
45
+ /** Why the policy refuses the target: not among its hosts, or a port of none of them; none: any public host, on 80 and 443. */
46
+ function refusal(hosts: readonly string[] | undefined, target: EgressTarget): 'host' | 'port' | undefined;
47
+ /** `::ffff:10.0.0.1` is 10.0.0.1. */
48
+ function plain(address: string): string;
49
+ /** Whether a sandbox may reach the address: a public one, or one of `networks`; never this machine. */
50
+ function reachable(address: string, networks: BlockList, own?: ReadonlySet<string>): boolean;
51
+ function ownAddresses(): Set<string>;
52
+ /**
53
+ * What a sandbox goes out with: the proxy of the gateway at `url`, by the credentials of its epoch, for the
54
+ * commands that read the variables of a proxy (curl, git, npm, pip, apt, and Node.js with NODE_USE_ENV_PROXY);
55
+ * the gateway itself, for its models, directly.
56
+ */
57
+ function env(url: string, user: string, password: string): Record<string, string>;
58
+ function sameSecret(given: string, known: string): boolean;
59
+ function headers(given: IncomingHttpHeaders): Record<string, string | string[]>;
60
+ }
61
+ /**
62
+ * The way out of the sandboxes (docs/design/ta-cloud.md 3.5): an HTTP proxy on the port of the gateway, CONNECT
63
+ * for https and absolute URLs for http. A sandbox comes with the credentials of its tenant and epoch (those of
64
+ * a sandbox replaced since are refused); the gateway reaches only public addresses (and the private networks of
65
+ * the configuration), resolved once and checked, never this machine nor the metadata service; members only the
66
+ * hosts of the policy. It counts the bytes each tenant moved, and keeps the latest refusals for the console.
67
+ */
68
+ export declare class EgressProxy {
69
+ readonly settings: EgressSettings;
70
+ protected readonly hooks: EgressHooks;
71
+ protected readonly networks: BlockList;
72
+ protected readonly pending: Map<string, number>;
73
+ protected readonly refusals: Map<string, TaEgressRefusal[]>;
74
+ constructor(settings: EgressSettings, hooks: EgressHooks);
75
+ get enabled(): boolean;
76
+ /** The bytes moved since the last time, by tenant. */
77
+ flush(): Map<string, number>;
78
+ /** The latest refusals of a tenant, newest first. */
79
+ refused(tenantId: string): TaEgressRefusal[];
80
+ /** CONNECT: a tunnel to the target, once its tenant may reach it. */
81
+ connect(request: IncomingMessage, socket: Duplex, head: Buffer): Promise<void>;
82
+ /** An absolute `http://` URL: the request forwarded, once its tenant may reach the host. */
83
+ request(request: IncomingMessage, response: ServerResponse): Promise<void>;
84
+ protected authorize(request: IncomingMessage): EgressAuthorization;
85
+ /** The address to connect to, resolved once and checked (no rebinding between the check and the connection), or why not. */
86
+ protected resolve(who: {
87
+ tenantId: string;
88
+ hosts?: string[];
89
+ }, target: EgressTarget): Promise<string | {
90
+ status: number;
91
+ message: string;
92
+ }>;
93
+ protected reachable(address: string, own: ReadonlySet<string>): boolean;
94
+ protected refuse(tenantId: string, target: EgressTarget, reason: TaEgressRefusal['reason']): void;
95
+ protected count(tenantId: string, bytes: number): void;
96
+ protected reply(socket: Duplex, status: number, message: string): void;
97
+ protected end(response: ServerResponse, status: number, message: string): void;
98
+ }
99
+ //# sourceMappingURL=egress-proxy.d.ts.map