@celljs/ta-gateway 0.0.0-stage → 4.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +80 -0
- package/README.md +79 -2
- package/esm/node/command-sandbox.d.ts +28 -0
- package/esm/node/command-sandbox.js +83 -0
- package/esm/node/docker-engine.d.ts +56 -0
- package/esm/node/docker-engine.js +151 -0
- package/esm/node/docker-sandbox.d.ts +45 -0
- package/esm/node/docker-sandbox.js +110 -0
- package/esm/node/environments.d.ts +68 -0
- package/esm/node/environments.js +237 -0
- package/esm/node/gateway-cli.d.ts +9 -0
- package/esm/node/gateway-cli.js +99 -0
- package/esm/node/gateway-server.d.ts +67 -0
- package/esm/node/gateway-server.js +288 -0
- package/esm/node/gateway-service.d.ts +58 -0
- package/esm/node/gateway-service.js +187 -0
- package/esm/node/gateway-socket.d.ts +33 -0
- package/esm/node/gateway-socket.js +143 -0
- package/esm/node/index.d.ts +13 -0
- package/esm/node/index.js +14 -0
- package/esm/node/local-sandbox.d.ts +23 -0
- package/esm/node/local-sandbox.js +73 -0
- package/esm/node/sandbox-provider.d.ts +72 -0
- package/esm/node/sandbox-provider.js +83 -0
- package/esm/node/sign-in-links.d.ts +25 -0
- package/esm/node/sign-in-links.js +44 -0
- package/esm/node/ta-sandbox.d.ts +23 -0
- package/esm/node/ta-sandbox.js +47 -0
- package/esm/node/tenant-store.d.ts +36 -0
- package/esm/node/tenant-store.js +83 -0
- package/esm/package.json +3 -0
- package/lib/node/command-sandbox.d.ts +29 -0
- package/lib/node/command-sandbox.js +87 -0
- package/lib/node/docker-engine.d.ts +57 -0
- package/lib/node/docker-engine.js +156 -0
- package/lib/node/docker-sandbox.d.ts +46 -0
- package/lib/node/docker-sandbox.js +114 -0
- package/lib/node/environments.d.ts +69 -0
- package/lib/node/environments.js +242 -0
- package/lib/node/gateway-cli.d.ts +10 -0
- package/lib/node/gateway-cli.js +102 -0
- package/lib/node/gateway-server.d.ts +68 -0
- package/lib/node/gateway-server.js +292 -0
- package/lib/node/gateway-service.d.ts +59 -0
- package/lib/node/gateway-service.js +192 -0
- package/lib/node/gateway-socket.d.ts +34 -0
- package/lib/node/gateway-socket.js +147 -0
- package/lib/node/index.d.ts +14 -0
- package/lib/node/index.js +30 -0
- package/lib/node/local-sandbox.d.ts +24 -0
- package/lib/node/local-sandbox.js +77 -0
- package/lib/node/sandbox-provider.d.ts +73 -0
- package/lib/node/sandbox-provider.js +87 -0
- package/lib/node/sign-in-links.d.ts +26 -0
- package/lib/node/sign-in-links.js +48 -0
- package/lib/node/ta-sandbox.d.ts +24 -0
- package/lib/node/ta-sandbox.js +51 -0
- package/lib/node/tenant-store.d.ts +37 -0
- package/lib/node/tenant-store.js +88 -0
- package/package.json +57 -4
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { TA_WEBSOCKET_PATH, TaErrorCode } from '@celljs/ta-protocol';
|
|
2
|
+
import { GatewayCallError, GatewayServiceUtil } from './gateway-service.js';
|
|
3
|
+
/** What a browser sends before the Ta of its tenant answers, at most: then it is cut off, to connect again. */
|
|
4
|
+
const MAX_QUEUED = 256;
|
|
5
|
+
/**
|
|
6
|
+
* One browser's WebSocket: the calls of the gateway's services answered here, everything else forwarded to
|
|
7
|
+
* the Ta of its tenant, whose token only the gateway has, and back. Until that Ta answers, what the browser
|
|
8
|
+
* sends waits; if it does not start, its calls fail with ENVIRONMENT_FAILED, while those of the gateway
|
|
9
|
+
* still work, so that the page can change or restart the environment.
|
|
10
|
+
*/
|
|
11
|
+
export class GatewaySocket {
|
|
12
|
+
constructor(browser, caller, environments, service) {
|
|
13
|
+
this.browser = browser;
|
|
14
|
+
this.caller = caller;
|
|
15
|
+
this.environments = environments;
|
|
16
|
+
this.service = service;
|
|
17
|
+
this.queued = [];
|
|
18
|
+
this.closed = false;
|
|
19
|
+
/** Calls of the gateway being answered: a change of environment stops the one this socket is on meanwhile. */
|
|
20
|
+
this.answering = 0;
|
|
21
|
+
this.release = environments.connect(caller.tenant.id);
|
|
22
|
+
browser.onMessage(text => this.fromBrowser(text));
|
|
23
|
+
browser.onClose(() => this.dispose());
|
|
24
|
+
void this.open();
|
|
25
|
+
}
|
|
26
|
+
get tenantId() {
|
|
27
|
+
return this.caller.tenant.id;
|
|
28
|
+
}
|
|
29
|
+
close(code, reason) {
|
|
30
|
+
this.browser.close(code, reason);
|
|
31
|
+
this.dispose();
|
|
32
|
+
}
|
|
33
|
+
async open() {
|
|
34
|
+
let endpoint;
|
|
35
|
+
try {
|
|
36
|
+
endpoint = await this.environments.ensure(this.caller.tenant);
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
this.fail(error.message);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (this.closed) {
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const url = new URL(`${endpoint.url.replace(/^http/, 'ws')}${TA_WEBSOCKET_PATH}`);
|
|
46
|
+
url.searchParams.set('token', endpoint.token);
|
|
47
|
+
const inner = new WebSocket(url);
|
|
48
|
+
this.inner = inner;
|
|
49
|
+
inner.onopen = () => {
|
|
50
|
+
for (const text of this.queued.splice(0)) {
|
|
51
|
+
inner.send(text);
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
inner.onmessage = message => this.browser.open && this.browser.send(String(message.data));
|
|
55
|
+
inner.onclose = event => {
|
|
56
|
+
if (this.closed) {
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
// Stopped, restarted, its port changed: looked for again when the browser connects again.
|
|
60
|
+
this.environments.lost(this.tenantId);
|
|
61
|
+
const reason = `The environment went away (${event.code}).`;
|
|
62
|
+
if (this.answering > 0) {
|
|
63
|
+
this.closeAfterAnswers = reason;
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
this.close(1012, reason);
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
fromBrowser(text) {
|
|
71
|
+
// Most messages are the Ta's, some large (pictures): forwarded without being read.
|
|
72
|
+
if (this.failure === undefined && !GatewayServiceUtil.mayOwn(text)) {
|
|
73
|
+
this.forward(text);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
let message;
|
|
77
|
+
try {
|
|
78
|
+
message = JSON.parse(text);
|
|
79
|
+
}
|
|
80
|
+
catch (_a) {
|
|
81
|
+
this.close(1007, 'Not JSON.');
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
if (GatewayServiceUtil.owns(message.method)) {
|
|
85
|
+
void this.answer(message.id, message.method, Array.isArray(message.params) ? message.params : []);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (this.failure !== undefined) {
|
|
89
|
+
if (message.method !== undefined && message.id !== undefined) {
|
|
90
|
+
this.browser.send(GatewayServiceUtil.error(message.id, `Your environment did not start: ${this.failure}`, TaErrorCode.ENVIRONMENT_FAILED, 'Restart it, or pick another (TaGatewayServer).'));
|
|
91
|
+
}
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
this.forward(text);
|
|
95
|
+
}
|
|
96
|
+
forward(text) {
|
|
97
|
+
var _a;
|
|
98
|
+
if (((_a = this.inner) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN) {
|
|
99
|
+
this.inner.send(text);
|
|
100
|
+
}
|
|
101
|
+
else if (this.queued.length < MAX_QUEUED) {
|
|
102
|
+
this.queued.push(text);
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
this.close(1013, 'The environment is still starting.');
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
async answer(id, method, params) {
|
|
109
|
+
let reply;
|
|
110
|
+
this.answering++;
|
|
111
|
+
try {
|
|
112
|
+
reply = GatewayServiceUtil.result(id, await this.service.call(this.caller, method, params));
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
const known = error instanceof GatewayCallError;
|
|
116
|
+
reply = GatewayServiceUtil.error(id, error.message, known ? error.code : TaErrorCode.COMMAND_FAILED, known ? error.hint : 'The gateway could not do it; try again.');
|
|
117
|
+
}
|
|
118
|
+
this.answering--;
|
|
119
|
+
if (id !== undefined && this.browser.open) {
|
|
120
|
+
this.browser.send(reply);
|
|
121
|
+
}
|
|
122
|
+
if (this.answering === 0 && this.closeAfterAnswers) {
|
|
123
|
+
this.close(1012, this.closeAfterAnswers);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/** The calls that wait, and those to come, fail; those of the gateway still work. */
|
|
127
|
+
fail(reason) {
|
|
128
|
+
this.failure = reason;
|
|
129
|
+
for (const text of this.queued.splice(0)) {
|
|
130
|
+
this.fromBrowser(text);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
dispose() {
|
|
134
|
+
var _a;
|
|
135
|
+
if (this.closed) {
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
this.closed = true;
|
|
139
|
+
this.release();
|
|
140
|
+
(_a = this.inner) === null || _a === void 0 ? void 0 : _a.close();
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
//# sourceMappingURL=gateway-socket.js.map
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export * from './command-sandbox.js';
|
|
2
|
+
export * from './docker-engine.js';
|
|
3
|
+
export * from './docker-sandbox.js';
|
|
4
|
+
export * from './environments.js';
|
|
5
|
+
export * from './gateway-cli.js';
|
|
6
|
+
export * from './gateway-server.js';
|
|
7
|
+
export * from './gateway-service.js';
|
|
8
|
+
export * from './gateway-socket.js';
|
|
9
|
+
export * from './local-sandbox.js';
|
|
10
|
+
export * from './sandbox-provider.js';
|
|
11
|
+
export * from './sign-in-links.js';
|
|
12
|
+
export * from './ta-sandbox.js';
|
|
13
|
+
export * from './tenant-store.js';
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export * from './command-sandbox.js';
|
|
2
|
+
export * from './docker-engine.js';
|
|
3
|
+
export * from './docker-sandbox.js';
|
|
4
|
+
export * from './environments.js';
|
|
5
|
+
export * from './gateway-cli.js';
|
|
6
|
+
export * from './gateway-server.js';
|
|
7
|
+
export * from './gateway-service.js';
|
|
8
|
+
export * from './gateway-socket.js';
|
|
9
|
+
export * from './local-sandbox.js';
|
|
10
|
+
export * from './sandbox-provider.js';
|
|
11
|
+
export * from './sign-in-links.js';
|
|
12
|
+
export * from './ta-sandbox.js';
|
|
13
|
+
export * from './tenant-store.js';
|
|
14
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type ChildProcess } from 'node:child_process';
|
|
2
|
+
import type { SandboxContext, SandboxEndpoint, SandboxProvider, SandboxProviderConfig, SandboxState, SandboxTenant } from './sandbox-provider.js';
|
|
3
|
+
/**
|
|
4
|
+
* `local`: a `ta serve` process per tenant on the machine of the gateway, its agent directory and workspace
|
|
5
|
+
* under `<gateway>/local/<tenant>`. Not a sandbox: every tenant runs as the user of the gateway and can read
|
|
6
|
+
* the others' files. For trying a gateway out, and for tests; `docker` isolates.
|
|
7
|
+
*/
|
|
8
|
+
export declare class LocalSandbox implements SandboxProvider {
|
|
9
|
+
readonly id: string;
|
|
10
|
+
protected readonly context: SandboxContext;
|
|
11
|
+
readonly type = "local";
|
|
12
|
+
readonly name: string;
|
|
13
|
+
protected readonly running: Map<string, {
|
|
14
|
+
child: ChildProcess;
|
|
15
|
+
url: string;
|
|
16
|
+
}>;
|
|
17
|
+
constructor(id: string, config: SandboxProviderConfig, context: SandboxContext);
|
|
18
|
+
start(tenant: SandboxTenant): Promise<SandboxEndpoint>;
|
|
19
|
+
stop(tenant: SandboxTenant): Promise<void>;
|
|
20
|
+
state(tenant: SandboxTenant): Promise<SandboxState>;
|
|
21
|
+
dispose(): Promise<void>;
|
|
22
|
+
static freePort(): Promise<number>;
|
|
23
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { mkdirSync } from 'node:fs';
|
|
3
|
+
import { createServer } from 'node:net';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { SandboxProviders } from './sandbox-provider.js';
|
|
6
|
+
/**
|
|
7
|
+
* `local`: a `ta serve` process per tenant on the machine of the gateway, its agent directory and workspace
|
|
8
|
+
* under `<gateway>/local/<tenant>`. Not a sandbox: every tenant runs as the user of the gateway and can read
|
|
9
|
+
* the others' files. For trying a gateway out, and for tests; `docker` isolates.
|
|
10
|
+
*/
|
|
11
|
+
export class LocalSandbox {
|
|
12
|
+
constructor(id, config, context) {
|
|
13
|
+
this.id = id;
|
|
14
|
+
this.context = context;
|
|
15
|
+
this.type = 'local';
|
|
16
|
+
this.running = new Map();
|
|
17
|
+
this.name = SandboxProviders.string(config, 'name', 'Local');
|
|
18
|
+
}
|
|
19
|
+
async start(tenant) {
|
|
20
|
+
const running = this.running.get(tenant.id);
|
|
21
|
+
if (running && running.child.exitCode === null) {
|
|
22
|
+
return { url: running.url, token: tenant.token };
|
|
23
|
+
}
|
|
24
|
+
const root = join(this.context.dir, 'local', tenant.id);
|
|
25
|
+
const agentDir = join(root, 'agent');
|
|
26
|
+
const cwd = join(root, 'workspace');
|
|
27
|
+
mkdirSync(agentDir, { recursive: true });
|
|
28
|
+
mkdirSync(cwd, { recursive: true });
|
|
29
|
+
const port = await LocalSandbox.freePort();
|
|
30
|
+
const [command, ...args] = this.context.taCommand;
|
|
31
|
+
const child = spawn(command, [...args, 'serve', '--port', String(port)], {
|
|
32
|
+
cwd,
|
|
33
|
+
env: { ...process.env, TA_CODING_AGENT_DIR: agentDir, TA_SERVE_TOKEN: tenant.token, CELL_SERVER__HOST: '127.0.0.1' },
|
|
34
|
+
stdio: 'ignore',
|
|
35
|
+
});
|
|
36
|
+
const url = `http://127.0.0.1:${port}`;
|
|
37
|
+
this.running.set(tenant.id, { child, url });
|
|
38
|
+
child.once('exit', () => {
|
|
39
|
+
var _a;
|
|
40
|
+
if (((_a = this.running.get(tenant.id)) === null || _a === void 0 ? void 0 : _a.child) === child) {
|
|
41
|
+
this.running.delete(tenant.id);
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
return { url, token: tenant.token };
|
|
45
|
+
}
|
|
46
|
+
async stop(tenant) {
|
|
47
|
+
const running = this.running.get(tenant.id);
|
|
48
|
+
this.running.delete(tenant.id);
|
|
49
|
+
if (running && running.child.exitCode === null) {
|
|
50
|
+
await new Promise(done => {
|
|
51
|
+
running.child.once('exit', () => done());
|
|
52
|
+
running.child.kill('SIGTERM');
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
async state(tenant) {
|
|
57
|
+
return this.running.has(tenant.id) ? 'running' : 'stopped';
|
|
58
|
+
}
|
|
59
|
+
async dispose() {
|
|
60
|
+
await Promise.all([...this.running.keys()].map(id => this.stop({ id, account: '', token: '' })));
|
|
61
|
+
}
|
|
62
|
+
static freePort() {
|
|
63
|
+
return new Promise((resolve, reject) => {
|
|
64
|
+
const server = createServer();
|
|
65
|
+
server.once('error', reject);
|
|
66
|
+
server.listen(0, '127.0.0.1', () => {
|
|
67
|
+
const { port } = server.address();
|
|
68
|
+
server.close(() => resolve(port));
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
//# sourceMappingURL=local-sandbox.js.map
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/** A tenant, as a provider of sandboxes sees it: `token` is the one its Ta service must take (TA_SERVE_TOKEN). */
|
|
2
|
+
export interface SandboxTenant {
|
|
3
|
+
id: string;
|
|
4
|
+
account: string;
|
|
5
|
+
token: string;
|
|
6
|
+
}
|
|
7
|
+
/** Where the Ta service of a tenant answers: `url` is its http(s) address, the gateway connects to `/api/ws` there. */
|
|
8
|
+
export interface SandboxEndpoint {
|
|
9
|
+
url: string;
|
|
10
|
+
token: string;
|
|
11
|
+
}
|
|
12
|
+
export type SandboxState = 'running' | 'stopped' | 'missing';
|
|
13
|
+
/**
|
|
14
|
+
* Makes and runs the sandboxes of tenants, one each: a container, a process, a machine of a cloud. As a model
|
|
15
|
+
* provider of pi is to models, built in (`docker`, `command`, `local`, `ta`) or a module of the operator's
|
|
16
|
+
* (`module`).
|
|
17
|
+
*/
|
|
18
|
+
export interface SandboxProvider {
|
|
19
|
+
readonly id: string;
|
|
20
|
+
readonly name: string;
|
|
21
|
+
readonly type: string;
|
|
22
|
+
/** How long its Ta service has to answer once started; default two minutes, for a first pull of an image. */
|
|
23
|
+
readonly readyTimeoutMs?: number;
|
|
24
|
+
/**
|
|
25
|
+
* Creates the sandbox when it is missing, starts it when it is stopped: where its Ta service answers, or
|
|
26
|
+
* will in a moment (the gateway waits for it). Called again when the gateway lost it: it must not make a
|
|
27
|
+
* second one.
|
|
28
|
+
*/
|
|
29
|
+
start(tenant: SandboxTenant): Promise<SandboxEndpoint>;
|
|
30
|
+
/** Stops it, keeping what it holds, to start again later. */
|
|
31
|
+
stop(tenant: SandboxTenant): Promise<void>;
|
|
32
|
+
state(tenant: SandboxTenant): Promise<SandboxState>;
|
|
33
|
+
/** The gateway stops: what runs in this process ends (`local`). */
|
|
34
|
+
dispose?(): Promise<void>;
|
|
35
|
+
}
|
|
36
|
+
export interface SandboxContext {
|
|
37
|
+
/** The directory of the gateway: a module's path is relative to it, `local` keeps its tenants there. */
|
|
38
|
+
dir: string;
|
|
39
|
+
/** How to run `ta`: the Node.js executable and the entry of the command. */
|
|
40
|
+
taCommand: string[];
|
|
41
|
+
}
|
|
42
|
+
/** One of `providers` of sandboxes.json: `type`, a `name`, and the options of its type. */
|
|
43
|
+
export interface SandboxProviderConfig {
|
|
44
|
+
type: string;
|
|
45
|
+
name?: string;
|
|
46
|
+
[option: string]: unknown;
|
|
47
|
+
}
|
|
48
|
+
export type SandboxProviderFactory = (id: string, config: SandboxProviderConfig, context: SandboxContext) => SandboxProvider | Promise<SandboxProvider>;
|
|
49
|
+
/** sandboxes.json in the directory of the gateway. */
|
|
50
|
+
export interface SandboxesConfig {
|
|
51
|
+
/** The provider of a tenant that picked none. */
|
|
52
|
+
default?: string;
|
|
53
|
+
providers?: Record<string, SandboxProviderConfig>;
|
|
54
|
+
/** Whether users may run their Ta in a Ta service of their own (TaEnvironmentChoice of type `ta`). Default: true. */
|
|
55
|
+
ownEnvironments?: boolean;
|
|
56
|
+
/** Stops a sandbox nobody is connected to after this long; 0, the default, keeps it running (scheduled tasks, the double's work). */
|
|
57
|
+
idleMinutes?: number;
|
|
58
|
+
}
|
|
59
|
+
export declare class SandboxConfigError extends Error {
|
|
60
|
+
}
|
|
61
|
+
export declare namespace SandboxProviders {
|
|
62
|
+
const FILE = "sandboxes.json";
|
|
63
|
+
/** Without sandboxes.json: one container per tenant, on the Docker of this machine. */
|
|
64
|
+
const DEFAULT: SandboxesConfig;
|
|
65
|
+
/** TA_PUBLIC_URL without its trailing `/`: where people reach the gateway. */
|
|
66
|
+
function publicBase(env: Record<string, string | undefined>): string | undefined;
|
|
67
|
+
function read(dir: string): SandboxesConfig;
|
|
68
|
+
/** Every provider of the configuration, by the factories of their types; `module` loads the operator's. */
|
|
69
|
+
function create(config: SandboxesConfig, context: SandboxContext, factories: Record<string, SandboxProviderFactory>): Promise<SandboxProvider[]>;
|
|
70
|
+
function string(config: SandboxProviderConfig, key: string, fallback?: string): string | undefined;
|
|
71
|
+
function env(config: SandboxProviderConfig): Record<string, string>;
|
|
72
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { isAbsolute, join } from 'node:path';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
export class SandboxConfigError extends Error {
|
|
5
|
+
}
|
|
6
|
+
export var SandboxProviders;
|
|
7
|
+
(function (SandboxProviders) {
|
|
8
|
+
SandboxProviders.FILE = 'sandboxes.json';
|
|
9
|
+
/** Without sandboxes.json: one container per tenant, on the Docker of this machine. */
|
|
10
|
+
SandboxProviders.DEFAULT = { default: 'docker', providers: { docker: { type: 'docker', name: 'Docker' } } };
|
|
11
|
+
/** TA_PUBLIC_URL without its trailing `/`: where people reach the gateway. */
|
|
12
|
+
function publicBase(env) {
|
|
13
|
+
var _a;
|
|
14
|
+
return ((_a = env.TA_PUBLIC_URL) === null || _a === void 0 ? void 0 : _a.trim().replace(/\/+$/, '')) || undefined;
|
|
15
|
+
}
|
|
16
|
+
SandboxProviders.publicBase = publicBase;
|
|
17
|
+
function read(dir) {
|
|
18
|
+
const file = join(dir, SandboxProviders.FILE);
|
|
19
|
+
if (!existsSync(file)) {
|
|
20
|
+
return SandboxProviders.DEFAULT;
|
|
21
|
+
}
|
|
22
|
+
try {
|
|
23
|
+
return JSON.parse(readFileSync(file, 'utf8'));
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
throw new SandboxConfigError(`${file} is not JSON: ${error.message}`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
SandboxProviders.read = read;
|
|
30
|
+
/** Every provider of the configuration, by the factories of their types; `module` loads the operator's. */
|
|
31
|
+
async function create(config, context, factories) {
|
|
32
|
+
var _a;
|
|
33
|
+
const providers = [];
|
|
34
|
+
for (const [id, entry] of Object.entries((_a = config.providers) !== null && _a !== void 0 ? _a : {})) {
|
|
35
|
+
if (!/^[a-z0-9][a-z0-9-]*$/.test(id) || id === 'own') {
|
|
36
|
+
throw new SandboxConfigError(`"${id}" cannot name a provider of sandboxes: use lower-case letters, digits and -, not "own".`);
|
|
37
|
+
}
|
|
38
|
+
const factory = entry.type === 'module' ? await loadModule(entry, context) : factories[entry.type];
|
|
39
|
+
if (!factory) {
|
|
40
|
+
throw new SandboxConfigError(`The provider "${id}" has the type "${entry.type}", which is none of ${[...Object.keys(factories), 'module'].join(', ')}.`);
|
|
41
|
+
}
|
|
42
|
+
providers.push(await factory(id, entry, context));
|
|
43
|
+
}
|
|
44
|
+
if (config.default && !providers.some(provider => provider.id === config.default)) {
|
|
45
|
+
throw new SandboxConfigError(`The default provider "${config.default}" is not among the providers of ${SandboxProviders.FILE}.`);
|
|
46
|
+
}
|
|
47
|
+
return providers;
|
|
48
|
+
}
|
|
49
|
+
SandboxProviders.create = create;
|
|
50
|
+
/** `{ "type": "module", "path": "./my-sandbox.mjs" }`: its default export is a SandboxProviderFactory. */
|
|
51
|
+
async function loadModule(entry, context) {
|
|
52
|
+
if (typeof entry.path !== 'string' || !entry.path) {
|
|
53
|
+
throw new SandboxConfigError('A provider of the type "module" names its file in "path".');
|
|
54
|
+
}
|
|
55
|
+
const path = isAbsolute(entry.path) ? entry.path : join(context.dir, entry.path);
|
|
56
|
+
const loaded = (await import(pathToFileURL(path).href));
|
|
57
|
+
if (typeof loaded.default !== 'function') {
|
|
58
|
+
throw new SandboxConfigError(`${path} has no default export of a function (id, config, context) => SandboxProvider.`);
|
|
59
|
+
}
|
|
60
|
+
return loaded.default;
|
|
61
|
+
}
|
|
62
|
+
function string(config, key, fallback) {
|
|
63
|
+
const value = config[key];
|
|
64
|
+
if (value === undefined) {
|
|
65
|
+
return fallback;
|
|
66
|
+
}
|
|
67
|
+
if (typeof value !== 'string') {
|
|
68
|
+
throw new SandboxConfigError(`"${key}" of a provider of the type "${config.type}" is a string.`);
|
|
69
|
+
}
|
|
70
|
+
return value;
|
|
71
|
+
}
|
|
72
|
+
SandboxProviders.string = string;
|
|
73
|
+
function env(config) {
|
|
74
|
+
var _a;
|
|
75
|
+
const value = (_a = config.env) !== null && _a !== void 0 ? _a : {};
|
|
76
|
+
if (typeof value !== 'object' || Array.isArray(value) || Object.values(value).some(item => typeof item !== 'string')) {
|
|
77
|
+
throw new SandboxConfigError('"env" of a provider is an object of strings.');
|
|
78
|
+
}
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
SandboxProviders.env = env;
|
|
82
|
+
})(SandboxProviders || (SandboxProviders = {}));
|
|
83
|
+
//# sourceMappingURL=sandbox-provider.js.map
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
interface StoredLink {
|
|
2
|
+
hash: string;
|
|
3
|
+
account: string;
|
|
4
|
+
name?: string;
|
|
5
|
+
expiresAt: number;
|
|
6
|
+
}
|
|
7
|
+
/** Where a link of `ta gateway link` goes: `/sign-in/link/<secret>`. */
|
|
8
|
+
export declare const SIGN_IN_LINK_PATH = "/sign-in/link/";
|
|
9
|
+
/**
|
|
10
|
+
* Links that sign in as an account, once: how an operator lets someone in without a provider of accounts
|
|
11
|
+
* (`user:alice`), or before one is set up. `links.json` of the gateway keeps their hashes; `ta gateway link`
|
|
12
|
+
* writes it from another process, so it is read on every use.
|
|
13
|
+
*/
|
|
14
|
+
export declare class SignInLinks {
|
|
15
|
+
protected readonly file: string;
|
|
16
|
+
constructor(dir: string);
|
|
17
|
+
create(account: string, name?: string, ttlMs?: number, now?: number): string;
|
|
18
|
+
/** The account of a link, which no longer works after. */
|
|
19
|
+
use(secret: string, now?: number): {
|
|
20
|
+
account: string;
|
|
21
|
+
name?: string;
|
|
22
|
+
} | undefined;
|
|
23
|
+
protected read(now: number): StoredLink[];
|
|
24
|
+
}
|
|
25
|
+
export {};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { writePrivate } from './tenant-store.js';
|
|
5
|
+
/** Where a link of `ta gateway link` goes: `/sign-in/link/<secret>`. */
|
|
6
|
+
export const SIGN_IN_LINK_PATH = '/sign-in/link/';
|
|
7
|
+
const hash = (secret) => createHash('sha256').update(secret).digest('base64url');
|
|
8
|
+
/**
|
|
9
|
+
* Links that sign in as an account, once: how an operator lets someone in without a provider of accounts
|
|
10
|
+
* (`user:alice`), or before one is set up. `links.json` of the gateway keeps their hashes; `ta gateway link`
|
|
11
|
+
* writes it from another process, so it is read on every use.
|
|
12
|
+
*/
|
|
13
|
+
export class SignInLinks {
|
|
14
|
+
constructor(dir) {
|
|
15
|
+
this.file = join(dir, 'links.json');
|
|
16
|
+
}
|
|
17
|
+
create(account, name, ttlMs = 24 * 3600 * 1000, now = Date.now()) {
|
|
18
|
+
if (!/^[a-z][a-z0-9-]*:\S+$/.test(account)) {
|
|
19
|
+
throw new Error(`${account} is not an account: write <kind>:<name>, such as github:octocat or user:alice.`);
|
|
20
|
+
}
|
|
21
|
+
const secret = randomBytes(24).toString('base64url');
|
|
22
|
+
const links = this.read(now);
|
|
23
|
+
links.push({ hash: hash(secret), account, name, expiresAt: now + ttlMs });
|
|
24
|
+
writePrivate(this.file, links);
|
|
25
|
+
return `${SIGN_IN_LINK_PATH}${secret}`;
|
|
26
|
+
}
|
|
27
|
+
/** The account of a link, which no longer works after. */
|
|
28
|
+
use(secret, now = Date.now()) {
|
|
29
|
+
const links = this.read(now);
|
|
30
|
+
const link = links.find(one => one.hash === hash(secret));
|
|
31
|
+
writePrivate(this.file, links.filter(one => one !== link));
|
|
32
|
+
return link && { account: link.account, name: link.name };
|
|
33
|
+
}
|
|
34
|
+
read(now) {
|
|
35
|
+
try {
|
|
36
|
+
const links = JSON.parse(readFileSync(this.file, 'utf8'));
|
|
37
|
+
return Array.isArray(links) ? links.filter(link => link.expiresAt > now) : [];
|
|
38
|
+
}
|
|
39
|
+
catch (_a) {
|
|
40
|
+
return [];
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
//# sourceMappingURL=sign-in-links.js.map
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { SandboxEndpoint, SandboxProvider, SandboxProviderConfig, SandboxState } from './sandbox-provider.js';
|
|
2
|
+
export declare namespace TaSandboxUtil {
|
|
3
|
+
/** An http(s) address with no path, query or credentials: `https://ta.example.com`, `http://10.0.0.5:4100`. */
|
|
4
|
+
function url(text: string): string;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* `ta`: a Ta service that runs already, at `url` with its `token`: the gateway neither starts nor stops it.
|
|
8
|
+
* It is how a user brings an environment of their own (TaEnvironmentChoice of type `ta`), and how an operator
|
|
9
|
+
* gives every tenant one shared service, which is not isolation.
|
|
10
|
+
*/
|
|
11
|
+
export declare class TaSandbox implements SandboxProvider {
|
|
12
|
+
readonly id: string;
|
|
13
|
+
readonly type = "ta";
|
|
14
|
+
/** It runs already: what does not answer soon is not there. */
|
|
15
|
+
readonly readyTimeoutMs = 10000;
|
|
16
|
+
readonly name: string;
|
|
17
|
+
readonly url: string;
|
|
18
|
+
protected readonly token: string;
|
|
19
|
+
constructor(id: string, config: SandboxProviderConfig);
|
|
20
|
+
start(): Promise<SandboxEndpoint>;
|
|
21
|
+
stop(): Promise<void>;
|
|
22
|
+
state(): Promise<SandboxState>;
|
|
23
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { SandboxProviders } from './sandbox-provider.js';
|
|
2
|
+
export var TaSandboxUtil;
|
|
3
|
+
(function (TaSandboxUtil) {
|
|
4
|
+
/** An http(s) address with no path, query or credentials: `https://ta.example.com`, `http://10.0.0.5:4100`. */
|
|
5
|
+
function url(text) {
|
|
6
|
+
let url;
|
|
7
|
+
try {
|
|
8
|
+
url = new URL(text.trim());
|
|
9
|
+
}
|
|
10
|
+
catch (_a) {
|
|
11
|
+
throw new Error(`${text} is not an address: write http(s)://<host>[:<port>].`);
|
|
12
|
+
}
|
|
13
|
+
if ((url.protocol !== 'http:' && url.protocol !== 'https:') || url.username || url.password || url.search || url.hash) {
|
|
14
|
+
throw new Error(`${text} is not an address of a Ta service: write http(s)://<host>[:<port>].`);
|
|
15
|
+
}
|
|
16
|
+
return `${url.origin}${url.pathname.replace(/\/+$/, '')}`;
|
|
17
|
+
}
|
|
18
|
+
TaSandboxUtil.url = url;
|
|
19
|
+
})(TaSandboxUtil || (TaSandboxUtil = {}));
|
|
20
|
+
/**
|
|
21
|
+
* `ta`: a Ta service that runs already, at `url` with its `token`: the gateway neither starts nor stops it.
|
|
22
|
+
* It is how a user brings an environment of their own (TaEnvironmentChoice of type `ta`), and how an operator
|
|
23
|
+
* gives every tenant one shared service, which is not isolation.
|
|
24
|
+
*/
|
|
25
|
+
export class TaSandbox {
|
|
26
|
+
constructor(id, config) {
|
|
27
|
+
var _a, _b;
|
|
28
|
+
this.id = id;
|
|
29
|
+
this.type = 'ta';
|
|
30
|
+
/** It runs already: what does not answer soon is not there. */
|
|
31
|
+
this.readyTimeoutMs = 10000;
|
|
32
|
+
this.name = SandboxProviders.string(config, 'name', id);
|
|
33
|
+
this.url = TaSandboxUtil.url((_a = SandboxProviders.string(config, 'url')) !== null && _a !== void 0 ? _a : '');
|
|
34
|
+
this.token = (_b = SandboxProviders.string(config, 'token')) !== null && _b !== void 0 ? _b : '';
|
|
35
|
+
if (!this.token) {
|
|
36
|
+
throw new Error('A Ta service is reached with its access token.');
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
async start() {
|
|
40
|
+
return { url: this.url, token: this.token };
|
|
41
|
+
}
|
|
42
|
+
async stop() { }
|
|
43
|
+
async state() {
|
|
44
|
+
return 'running';
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=ta-sandbox.js.map
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { TaEnvironmentChoice } from '@celljs/ta-protocol';
|
|
2
|
+
/** A tenant: an account and its Ta, wherever it runs. */
|
|
3
|
+
export interface Tenant {
|
|
4
|
+
id: string;
|
|
5
|
+
account: string;
|
|
6
|
+
name?: string;
|
|
7
|
+
avatar?: string;
|
|
8
|
+
/** What its Ta service takes (TA_SERVE_TOKEN): only the gateway and the sandbox know it. */
|
|
9
|
+
token: string;
|
|
10
|
+
/** None: the default provider. A Ta service of the user's holds its token here, which never goes back to a browser. */
|
|
11
|
+
environment?: TaEnvironmentChoice;
|
|
12
|
+
createdAt: number;
|
|
13
|
+
lastActiveAt?: number;
|
|
14
|
+
}
|
|
15
|
+
/** Files written whole or not at all, readable by this user only. */
|
|
16
|
+
export declare function writePrivate(file: string, data: unknown): void;
|
|
17
|
+
export declare namespace TenantUtil {
|
|
18
|
+
/** Stable, and fit for the names of containers and volumes. */
|
|
19
|
+
function id(account: string): string;
|
|
20
|
+
}
|
|
21
|
+
/** `<gateway>/tenants/<id>.json`, one per account, made on its first sign-in. */
|
|
22
|
+
export declare class TenantStore {
|
|
23
|
+
protected readonly dir: string;
|
|
24
|
+
protected readonly cache: Map<string, Tenant>;
|
|
25
|
+
constructor(root: string);
|
|
26
|
+
get(id: string): Tenant | undefined;
|
|
27
|
+
/** The tenant of the account, made when it has none. */
|
|
28
|
+
ensure(account: {
|
|
29
|
+
id: string;
|
|
30
|
+
name?: string;
|
|
31
|
+
avatar?: string;
|
|
32
|
+
}, now?: number): Tenant;
|
|
33
|
+
update(id: string, change: Partial<Omit<Tenant, 'id' | 'account' | 'token'>>): Tenant;
|
|
34
|
+
list(): Tenant[];
|
|
35
|
+
protected save(tenant: Tenant): void;
|
|
36
|
+
}
|