@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,292 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GatewayServer = exports.GatewayServerUtil = exports.SANDBOX_TYPES = void 0;
|
|
4
|
+
const node_fs_1 = require("node:fs");
|
|
5
|
+
const node_http_1 = require("node:http");
|
|
6
|
+
const node_https_1 = require("node:https");
|
|
7
|
+
const node_path_1 = require("node:path");
|
|
8
|
+
const node_stream_1 = require("node:stream");
|
|
9
|
+
const websocket_connection_1 = require("@celljs/rpc/lib/node/websocket/websocket-connection");
|
|
10
|
+
const access_store_1 = require("@celljs/ta-host/lib/node/sign-in/access-store");
|
|
11
|
+
const sign_in_flow_1 = require("@celljs/ta-host/lib/node/sign-in/sign-in-flow");
|
|
12
|
+
const sign_in_pages_1 = require("@celljs/ta-host/lib/node/sign-in/sign-in-pages");
|
|
13
|
+
const sign_in_provider_1 = require("@celljs/ta-host/lib/node/sign-in/sign-in-provider");
|
|
14
|
+
const ta_protocol_1 = require("@celljs/ta-protocol");
|
|
15
|
+
const command_sandbox_1 = require("./command-sandbox");
|
|
16
|
+
const docker_sandbox_1 = require("./docker-sandbox");
|
|
17
|
+
const environments_1 = require("./environments");
|
|
18
|
+
const gateway_service_1 = require("./gateway-service");
|
|
19
|
+
const gateway_socket_1 = require("./gateway-socket");
|
|
20
|
+
const local_sandbox_1 = require("./local-sandbox");
|
|
21
|
+
const sandbox_provider_1 = require("./sandbox-provider");
|
|
22
|
+
const sign_in_links_1 = require("./sign-in-links");
|
|
23
|
+
const ta_sandbox_1 = require("./ta-sandbox");
|
|
24
|
+
const tenant_store_1 = require("./tenant-store");
|
|
25
|
+
/** The browser's token for `/api/files`, which pages load by URL, without the token of the WebSocket. */
|
|
26
|
+
const FILES_COOKIE = 'ta_gateway';
|
|
27
|
+
const TYPES = {
|
|
28
|
+
'.html': 'text/html; charset=utf-8',
|
|
29
|
+
'.js': 'text/javascript',
|
|
30
|
+
'.mjs': 'text/javascript',
|
|
31
|
+
'.css': 'text/css',
|
|
32
|
+
'.json': 'application/json',
|
|
33
|
+
'.webmanifest': 'application/manifest+json',
|
|
34
|
+
'.svg': 'image/svg+xml',
|
|
35
|
+
'.png': 'image/png',
|
|
36
|
+
'.ico': 'image/x-icon',
|
|
37
|
+
'.woff2': 'font/woff2',
|
|
38
|
+
'.wasm': 'application/wasm',
|
|
39
|
+
'.ttf': 'font/ttf',
|
|
40
|
+
};
|
|
41
|
+
/** The built-in types of providers of sandboxes. */
|
|
42
|
+
exports.SANDBOX_TYPES = {
|
|
43
|
+
docker: (id, config) => new docker_sandbox_1.DockerSandbox(id, config),
|
|
44
|
+
command: (id, config) => new command_sandbox_1.CommandSandbox(id, config),
|
|
45
|
+
local: (id, config, context) => new local_sandbox_1.LocalSandbox(id, config, context),
|
|
46
|
+
ta: (id, config) => new ta_sandbox_1.TaSandbox(id, config),
|
|
47
|
+
};
|
|
48
|
+
var GatewayServerUtil;
|
|
49
|
+
(function (GatewayServerUtil) {
|
|
50
|
+
/** A file of `root` for a path of the page, never outside it; the page for what is not a file. */
|
|
51
|
+
function file(root, urlPath) {
|
|
52
|
+
let path;
|
|
53
|
+
try {
|
|
54
|
+
path = decodeURIComponent(urlPath.split('?')[0]);
|
|
55
|
+
}
|
|
56
|
+
catch (_a) {
|
|
57
|
+
path = '/';
|
|
58
|
+
}
|
|
59
|
+
const absolute = (0, node_path_1.normalize)((0, node_path_1.join)(root, path));
|
|
60
|
+
if ((absolute === root || absolute.startsWith(root.endsWith(node_path_1.sep) ? root : root + node_path_1.sep)) && (0, node_fs_1.existsSync)(absolute) && (0, node_fs_1.statSync)(absolute).isFile()) {
|
|
61
|
+
return absolute;
|
|
62
|
+
}
|
|
63
|
+
return (0, node_path_1.join)(root, 'index.html');
|
|
64
|
+
}
|
|
65
|
+
GatewayServerUtil.file = file;
|
|
66
|
+
})(GatewayServerUtil || (exports.GatewayServerUtil = GatewayServerUtil = {}));
|
|
67
|
+
/**
|
|
68
|
+
* `ta gateway`: one sign-in for many people, each with a Ta of their own. An account that signs in is a
|
|
69
|
+
* tenant (GitHub, Google, WeChat, OpenID Connect, or a link of `ta gateway link`); its Ta runs in a sandbox
|
|
70
|
+
* of its own, made by a provider of sandboxes.json, or in a Ta service of the user's. The gateway serves the
|
|
71
|
+
* web client, forwards each browser's WebSocket to the Ta of its tenant, and answers TaGatewayServer and
|
|
72
|
+
* TaAccessServer itself.
|
|
73
|
+
*/
|
|
74
|
+
class GatewayServer {
|
|
75
|
+
static async create(options) {
|
|
76
|
+
(0, node_fs_1.mkdirSync)(options.dir, { recursive: true, mode: 0o700 });
|
|
77
|
+
const config = sandbox_provider_1.SandboxProviders.read(options.dir);
|
|
78
|
+
const context = { dir: options.dir, taCommand: options.taCommand };
|
|
79
|
+
const providers = await sandbox_provider_1.SandboxProviders.create(config, context, exports.SANDBOX_TYPES);
|
|
80
|
+
return new GatewayServer(options, providers, config);
|
|
81
|
+
}
|
|
82
|
+
constructor(options, providers, config) {
|
|
83
|
+
var _a, _b;
|
|
84
|
+
this.options = options;
|
|
85
|
+
this.sockets = new Set();
|
|
86
|
+
const env = (_a = options.env) !== null && _a !== void 0 ? _a : process.env;
|
|
87
|
+
this.admins = access_store_1.AccessUtil.parseList(env.TA_GATEWAY_ADMINS);
|
|
88
|
+
const allowed = [...access_store_1.AccessUtil.parseList(env.TA_ALLOWED_USERS), ...this.admins];
|
|
89
|
+
this.flow = new sign_in_flow_1.SignInFlow(sign_in_provider_1.SignInProviders.fromEnv(env), new access_store_1.AccessStore((0, node_path_1.join)(options.dir, 'access.json'), allowed), sign_in_provider_1.SignInProviders.publicUrl(env));
|
|
90
|
+
this.tenants = new tenant_store_1.TenantStore(options.dir);
|
|
91
|
+
this.links = new sign_in_links_1.SignInLinks(options.dir);
|
|
92
|
+
this.environments = new environments_1.Environments(providers, this.tenants, {
|
|
93
|
+
default: config.default,
|
|
94
|
+
own: config.ownEnvironments !== false,
|
|
95
|
+
idleMinutes: (_b = config.idleMinutes) !== null && _b !== void 0 ? _b : 0,
|
|
96
|
+
});
|
|
97
|
+
this.service = new gateway_service_1.GatewayService(this.flow, this.tenants, this.environments, { cutOff: () => this.cutOff(), reset: id => this.reset(id) });
|
|
98
|
+
}
|
|
99
|
+
isAdmin(account) {
|
|
100
|
+
return this.admins.some(pattern => access_store_1.AccessUtil.matches(pattern, account));
|
|
101
|
+
}
|
|
102
|
+
listen() {
|
|
103
|
+
const server = (0, node_http_1.createServer)((request, response) => void this.handle(request, response));
|
|
104
|
+
server.on('upgrade', (request, socket, head) => this.upgrade(request, socket, head));
|
|
105
|
+
this.server = server;
|
|
106
|
+
return new Promise((resolve, reject) => {
|
|
107
|
+
var _a, _b;
|
|
108
|
+
server.once('error', reject);
|
|
109
|
+
server.listen((_a = this.options.port) !== null && _a !== void 0 ? _a : 4100, (_b = this.options.host) !== null && _b !== void 0 ? _b : '127.0.0.1', () => {
|
|
110
|
+
const { address, port } = server.address();
|
|
111
|
+
resolve(`http://${address.includes(':') ? `[${address}]` : address}:${port}`);
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
async close() {
|
|
116
|
+
for (const socket of this.sockets) {
|
|
117
|
+
socket.close(1001, 'The gateway is stopping.');
|
|
118
|
+
}
|
|
119
|
+
await this.environments.dispose();
|
|
120
|
+
await new Promise(resolve => (this.server ? this.server.close(() => resolve()) : resolve()));
|
|
121
|
+
}
|
|
122
|
+
/** The browsers whose sign-in no longer works are cut off. */
|
|
123
|
+
cutOff() {
|
|
124
|
+
for (const socket of this.sockets) {
|
|
125
|
+
if (!this.caller(socket.caller.token)) {
|
|
126
|
+
socket.close(1008, 'Signed out');
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* The connections of the tenant of now close, and connect again to its environment: in a moment, so that
|
|
132
|
+
* the answer to the call that changed it goes first. Those that open meanwhile stay.
|
|
133
|
+
*/
|
|
134
|
+
reset(tenantId) {
|
|
135
|
+
const sockets = [...this.sockets].filter(socket => socket.tenantId === tenantId);
|
|
136
|
+
setTimeout(() => {
|
|
137
|
+
for (const socket of sockets) {
|
|
138
|
+
socket.close(1012, 'The environment changed.');
|
|
139
|
+
}
|
|
140
|
+
}, 100);
|
|
141
|
+
}
|
|
142
|
+
/** Who a token signs in, while its account is let in. */
|
|
143
|
+
caller(token) {
|
|
144
|
+
const signIn = token ? this.flow.store.check(token) : undefined;
|
|
145
|
+
if (!signIn) {
|
|
146
|
+
return undefined;
|
|
147
|
+
}
|
|
148
|
+
const tenant = this.tenants.ensure({ id: signIn.account, name: signIn.name, avatar: signIn.avatar });
|
|
149
|
+
return { token, account: signIn.account, tenant, admin: this.isAdmin(signIn.account) };
|
|
150
|
+
}
|
|
151
|
+
async handle(request, response) {
|
|
152
|
+
var _a;
|
|
153
|
+
const path = ((_a = request.url) !== null && _a !== void 0 ? _a : '/').split('?')[0];
|
|
154
|
+
try {
|
|
155
|
+
if (path.startsWith(sign_in_links_1.SIGN_IN_LINK_PATH)) {
|
|
156
|
+
this.useLink(request, response, path.slice(sign_in_links_1.SIGN_IN_LINK_PATH.length));
|
|
157
|
+
}
|
|
158
|
+
else if (sign_in_pages_1.SignInPages.matches(request)) {
|
|
159
|
+
await sign_in_pages_1.SignInPages.handle(request, response, this.flow, {
|
|
160
|
+
name: 'ta gateway',
|
|
161
|
+
onSignedIn: (res, token, account, origin) => this.signedIn(res, token, account, origin),
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
else if (path.startsWith(`${ta_protocol_1.TA_FILES_PATH}/`)) {
|
|
165
|
+
await this.files(request, response);
|
|
166
|
+
}
|
|
167
|
+
else if (path === '/api' || path.startsWith('/api/')) {
|
|
168
|
+
sign_in_pages_1.SignInPageUtil.end(response, 404);
|
|
169
|
+
}
|
|
170
|
+
else {
|
|
171
|
+
this.page(request, response, path);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
catch (error) {
|
|
175
|
+
console.warn(`ta gateway: ${request.method} ${path} failed: ${error.message}`);
|
|
176
|
+
if (!response.headersSent) {
|
|
177
|
+
sign_in_pages_1.SignInPageUtil.end(response, 502);
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
response.destroy();
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
/** A link of `ta gateway link`: lets its account in, and signs this browser in as it. */
|
|
185
|
+
useLink(request, response, secret) {
|
|
186
|
+
response.setHeader('Cache-Control', 'no-store');
|
|
187
|
+
response.setHeader('Referrer-Policy', 'no-referrer');
|
|
188
|
+
const link = request.method === 'GET' ? this.links.use(secret) : undefined;
|
|
189
|
+
if (!link) {
|
|
190
|
+
sign_in_pages_1.SignInPageUtil.redirect(response, sign_in_pages_1.SignInPageUtil.back({ outcome: 'failed' }));
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
if (!this.flow.store.allows(link.account)) {
|
|
194
|
+
this.flow.store.allow(link.account, link.name);
|
|
195
|
+
}
|
|
196
|
+
const account = { id: link.account, name: link.name };
|
|
197
|
+
const token = this.flow.store.signIn(account, request.headers['user-agent']);
|
|
198
|
+
console.log(`ta gateway: ${link.account} signed in with a link`);
|
|
199
|
+
this.signedIn(response, token, account, this.origin(request));
|
|
200
|
+
sign_in_pages_1.SignInPageUtil.redirect(response, sign_in_pages_1.SignInPageUtil.back({ token }));
|
|
201
|
+
}
|
|
202
|
+
signedIn(response, token, account, origin) {
|
|
203
|
+
this.tenants.ensure(account);
|
|
204
|
+
const secure = origin.startsWith('https:') ? '; Secure' : '';
|
|
205
|
+
const cookies = response.getHeader('Set-Cookie');
|
|
206
|
+
const list = Array.isArray(cookies) ? cookies : cookies ? [String(cookies)] : [];
|
|
207
|
+
response.setHeader('Set-Cookie', [...list, `${FILES_COOKIE}=${token}; Path=${ta_protocol_1.TA_FILES_PATH}; Max-Age=31536000; HttpOnly; SameSite=Lax${secure}`]);
|
|
208
|
+
}
|
|
209
|
+
origin(request) {
|
|
210
|
+
var _a;
|
|
211
|
+
return (_a = this.flow.publicUrl) !== null && _a !== void 0 ? _a : `http://${request.headers.host}`;
|
|
212
|
+
}
|
|
213
|
+
/** `/api/files` of the Ta of the tenant whose cookie came along. */
|
|
214
|
+
async files(request, response) {
|
|
215
|
+
var _a, _b;
|
|
216
|
+
const caller = this.caller((_a = sign_in_pages_1.SignInPageUtil.cookie(request.headers.cookie, FILES_COOKIE)) !== null && _a !== void 0 ? _a : '');
|
|
217
|
+
if (!caller) {
|
|
218
|
+
sign_in_pages_1.SignInPageUtil.end(response, 404);
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
const endpoint = await this.environments.ensure(caller.tenant);
|
|
222
|
+
const target = new URL((_b = request.url) !== null && _b !== void 0 ? _b : '/', endpoint.url);
|
|
223
|
+
const headers = {};
|
|
224
|
+
for (const name of ['range', 'if-none-match', 'accept', 'accept-encoding', 'user-agent']) {
|
|
225
|
+
const value = request.headers[name];
|
|
226
|
+
if (value !== undefined) {
|
|
227
|
+
headers[name] = value;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
await new Promise((resolve, reject) => {
|
|
231
|
+
const send = target.protocol === 'https:' ? node_https_1.request : node_http_1.request;
|
|
232
|
+
const outgoing = send(target, { method: request.method, headers }, incoming => {
|
|
233
|
+
var _a;
|
|
234
|
+
response.writeHead((_a = incoming.statusCode) !== null && _a !== void 0 ? _a : 502, incoming.headers);
|
|
235
|
+
// A browser that stops reading (a video seeking) closes the request to the Ta of the tenant too.
|
|
236
|
+
(0, node_stream_1.pipeline)(incoming, response, () => resolve());
|
|
237
|
+
});
|
|
238
|
+
outgoing.on('error', reject);
|
|
239
|
+
response.once('close', () => outgoing.destroy());
|
|
240
|
+
outgoing.end();
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
page(request, response, path) {
|
|
244
|
+
var _a;
|
|
245
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
|
246
|
+
response.setHeader('Allow', 'GET, HEAD');
|
|
247
|
+
sign_in_pages_1.SignInPageUtil.end(response, 405);
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
const root = (0, node_path_1.normalize)(this.options.publicDir);
|
|
251
|
+
const file = GatewayServerUtil.file(root, path);
|
|
252
|
+
response.setHeader('Content-Type', (_a = TYPES[(0, node_path_1.extname)(file)]) !== null && _a !== void 0 ? _a : 'application/octet-stream');
|
|
253
|
+
response.setHeader('X-Content-Type-Options', 'nosniff');
|
|
254
|
+
response.setHeader('Cache-Control', path.startsWith('/assets/') ? 'public, max-age=31536000, immutable' : 'no-cache');
|
|
255
|
+
if (request.method === 'HEAD') {
|
|
256
|
+
response.end();
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
// A file gone meanwhile (the web client being replaced) fails this request, not the gateway.
|
|
260
|
+
const stream = (0, node_fs_1.createReadStream)(file);
|
|
261
|
+
stream.once('error', () => (response.headersSent ? response.destroy() : sign_in_pages_1.SignInPageUtil.end(response, 404)));
|
|
262
|
+
response.once('close', () => stream.destroy());
|
|
263
|
+
stream.pipe(response);
|
|
264
|
+
}
|
|
265
|
+
upgrade(request, socket, head) {
|
|
266
|
+
var _a, _b;
|
|
267
|
+
const url = new URL((_a = request.url) !== null && _a !== void 0 ? _a : '/', 'http://gateway');
|
|
268
|
+
if (url.pathname !== ta_protocol_1.TA_WEBSOCKET_PATH) {
|
|
269
|
+
socket.destroy();
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
const checked = websocket_connection_1.WebSocketConnection.check(request);
|
|
273
|
+
if ('status' in checked) {
|
|
274
|
+
websocket_connection_1.WebSocketConnection.refuse(socket, checked.status, checked.message);
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
const header = request.headers.authorization;
|
|
278
|
+
const token = (header === null || header === void 0 ? void 0 : header.startsWith('Bearer ')) ? header.slice('Bearer '.length) : ((_b = url.searchParams.get('token')) !== null && _b !== void 0 ? _b : '');
|
|
279
|
+
const caller = this.caller(token);
|
|
280
|
+
if (!caller) {
|
|
281
|
+
websocket_connection_1.WebSocketConnection.refuse(socket, 401, 'Not authorized.');
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
this.tenants.update(caller.tenant.id, { lastActiveAt: Date.now() });
|
|
285
|
+
const connection = websocket_connection_1.WebSocketConnection.open(socket, checked.key, head, { maxPayload: 32 * 1024 * 1024, heartbeat: 30000 });
|
|
286
|
+
const gatewaySocket = new gateway_socket_1.GatewaySocket(connection, caller, this.environments, this.service);
|
|
287
|
+
this.sockets.add(gatewaySocket);
|
|
288
|
+
connection.onClose(() => this.sockets.delete(gatewaySocket));
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
exports.GatewayServer = GatewayServer;
|
|
292
|
+
//# sourceMappingURL=gateway-server.js.map
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { SignInFlow } from '@celljs/ta-host/lib/node/sign-in/sign-in-flow';
|
|
2
|
+
import { type TaAccessInfo, type TaEnvironmentChoice, TaErrorCode, type TaGatewayInfo, type TaGatewayTenant } from '@celljs/ta-protocol';
|
|
3
|
+
import type { Environments } from './environments';
|
|
4
|
+
import type { Tenant, TenantStore } from './tenant-store';
|
|
5
|
+
/** Who calls: the browser signed in as `account`, with the token `token`. */
|
|
6
|
+
export interface GatewayCaller {
|
|
7
|
+
token: string;
|
|
8
|
+
account: string;
|
|
9
|
+
tenant: Tenant;
|
|
10
|
+
admin: boolean;
|
|
11
|
+
}
|
|
12
|
+
export declare class GatewayCallError extends Error {
|
|
13
|
+
readonly code: TaErrorCode;
|
|
14
|
+
readonly hint: string;
|
|
15
|
+
constructor(message: string, code: TaErrorCode, hint: string);
|
|
16
|
+
}
|
|
17
|
+
export declare namespace GatewayServiceUtil {
|
|
18
|
+
/** The services the gateway answers itself, not the Ta of the tenant. */
|
|
19
|
+
const SERVICES: string[];
|
|
20
|
+
function owns(method: unknown): method is string;
|
|
21
|
+
/** Whether the text of a message may be a call of {@link SERVICES}: those that are not are not parsed. */
|
|
22
|
+
function mayOwn(text: string): boolean;
|
|
23
|
+
/** The error of a JSON-RPC answer, as ta serve sends an ApplicationError: the client reads its code and hint. */
|
|
24
|
+
function error(id: unknown, message: string, code: TaErrorCode, hint: string): string;
|
|
25
|
+
function result(id: unknown, result: unknown): string;
|
|
26
|
+
function choice(value: unknown, own: boolean, providers: string[]): TaEnvironmentChoice | undefined;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The calls the gateway answers on the WebSocket of a browser: TaGatewayServer, and TaAccessServer, whose
|
|
30
|
+
* accounts are those that may have a tenant here; administrators manage them, everyone else sees their own
|
|
31
|
+
* sign-ins.
|
|
32
|
+
*/
|
|
33
|
+
export declare class GatewayService {
|
|
34
|
+
protected readonly flow: SignInFlow;
|
|
35
|
+
protected readonly tenants: TenantStore;
|
|
36
|
+
protected readonly environments: Environments;
|
|
37
|
+
protected readonly hooks: {
|
|
38
|
+
cutOff(): void;
|
|
39
|
+
reset(tenantId: string): void;
|
|
40
|
+
};
|
|
41
|
+
constructor(flow: SignInFlow, tenants: TenantStore, environments: Environments, hooks: {
|
|
42
|
+
cutOff(): void;
|
|
43
|
+
reset(tenantId: string): void;
|
|
44
|
+
});
|
|
45
|
+
call(caller: GatewayCaller, method: string, params: unknown[]): Promise<unknown>;
|
|
46
|
+
info(caller: GatewayCaller): TaGatewayInfo;
|
|
47
|
+
protected ownAllowed(): boolean;
|
|
48
|
+
protected setEnvironment(caller: GatewayCaller, value: unknown): Promise<TaGatewayInfo>;
|
|
49
|
+
protected restart(caller: GatewayCaller): Promise<TaGatewayInfo>;
|
|
50
|
+
protected listTenants(caller: GatewayCaller): Promise<TaGatewayTenant[]>;
|
|
51
|
+
protected stopTenant(caller: GatewayCaller, id: unknown): Promise<void>;
|
|
52
|
+
protected access(caller: GatewayCaller): TaAccessInfo;
|
|
53
|
+
protected allow(account: unknown, name: unknown): void;
|
|
54
|
+
/** The browsers of the account are cut off, and what reaches its Ta otherwise (paired phones) goes with its sandbox. */
|
|
55
|
+
protected disallow(account: string): Promise<void>;
|
|
56
|
+
protected signOut(caller: GatewayCaller, id: string): Promise<void>;
|
|
57
|
+
protected admin<T>(caller: GatewayCaller, action: () => T | Promise<T>): Promise<T>;
|
|
58
|
+
}
|
|
59
|
+
//# sourceMappingURL=gateway-service.d.ts.map
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GatewayService = exports.GatewayServiceUtil = exports.GatewayCallError = void 0;
|
|
4
|
+
const access_store_1 = require("@celljs/ta-host/lib/node/sign-in/access-store");
|
|
5
|
+
const ta_protocol_1 = require("@celljs/ta-protocol");
|
|
6
|
+
const ta_sandbox_1 = require("./ta-sandbox");
|
|
7
|
+
class GatewayCallError extends Error {
|
|
8
|
+
constructor(message, code, hint) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.hint = hint;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
exports.GatewayCallError = GatewayCallError;
|
|
15
|
+
var GatewayServiceUtil;
|
|
16
|
+
(function (GatewayServiceUtil) {
|
|
17
|
+
/** The services the gateway answers itself, not the Ta of the tenant. */
|
|
18
|
+
GatewayServiceUtil.SERVICES = ['TaGatewayServer', 'TaAccessServer'];
|
|
19
|
+
function owns(method) {
|
|
20
|
+
return typeof method === 'string' && GatewayServiceUtil.SERVICES.includes(method.split('/')[0]);
|
|
21
|
+
}
|
|
22
|
+
GatewayServiceUtil.owns = owns;
|
|
23
|
+
/** Whether the text of a message may be a call of {@link SERVICES}: those that are not are not parsed. */
|
|
24
|
+
function mayOwn(text) {
|
|
25
|
+
return GatewayServiceUtil.SERVICES.some(service => text.includes(`"${service}/`));
|
|
26
|
+
}
|
|
27
|
+
GatewayServiceUtil.mayOwn = mayOwn;
|
|
28
|
+
/** The error of a JSON-RPC answer, as ta serve sends an ApplicationError: the client reads its code and hint. */
|
|
29
|
+
function error(id, message, code, hint) {
|
|
30
|
+
return JSON.stringify({ jsonrpc: '2.0', id, error: { code: ta_protocol_1.TA_RPC_ERROR_CODE, message, data: { kind: 'application', data: { code, hint } } } });
|
|
31
|
+
}
|
|
32
|
+
GatewayServiceUtil.error = error;
|
|
33
|
+
function result(id, result) {
|
|
34
|
+
return JSON.stringify({ jsonrpc: '2.0', id, result: result !== null && result !== void 0 ? result : null });
|
|
35
|
+
}
|
|
36
|
+
GatewayServiceUtil.result = result;
|
|
37
|
+
function invalid(message, hint) {
|
|
38
|
+
return new GatewayCallError(message, ta_protocol_1.TaErrorCode.INVALID_ARGUMENT, hint);
|
|
39
|
+
}
|
|
40
|
+
function choice(value, own, providers) {
|
|
41
|
+
var _a;
|
|
42
|
+
const given = (value !== null && value !== void 0 ? value : {});
|
|
43
|
+
if (typeof given.provider === 'string') {
|
|
44
|
+
if (!providers.includes(given.provider)) {
|
|
45
|
+
throw invalid(`The gateway has no provider ${given.provider}.`, 'Pick one of the options of getGateway.');
|
|
46
|
+
}
|
|
47
|
+
return { provider: given.provider };
|
|
48
|
+
}
|
|
49
|
+
if (given.type === 'ta') {
|
|
50
|
+
if (!own) {
|
|
51
|
+
throw invalid('This gateway runs Ta in its own sandboxes only.', 'Pick one of the options of getGateway.');
|
|
52
|
+
}
|
|
53
|
+
let url;
|
|
54
|
+
try {
|
|
55
|
+
url = ta_sandbox_1.TaSandboxUtil.url(String((_a = given.url) !== null && _a !== void 0 ? _a : ''));
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
throw invalid(error.message, 'Write the address its Ta service is reached at, such as https://ta.example.com.');
|
|
59
|
+
}
|
|
60
|
+
if (typeof given.token !== 'string' || !given.token.trim()) {
|
|
61
|
+
throw invalid('A Ta service of your own is reached with its access token.', 'Copy it from ~/.ta/agent/serve.json there, or the link ta serve printed.');
|
|
62
|
+
}
|
|
63
|
+
return { type: 'ta', url, token: given.token.trim(), name: typeof given.name === 'string' && given.name.trim() ? given.name.trim() : undefined };
|
|
64
|
+
}
|
|
65
|
+
throw invalid('No environment was named.', 'Pass { provider } or { type: "ta", url, token }.');
|
|
66
|
+
}
|
|
67
|
+
GatewayServiceUtil.choice = choice;
|
|
68
|
+
})(GatewayServiceUtil || (exports.GatewayServiceUtil = GatewayServiceUtil = {}));
|
|
69
|
+
/**
|
|
70
|
+
* The calls the gateway answers on the WebSocket of a browser: TaGatewayServer, and TaAccessServer, whose
|
|
71
|
+
* accounts are those that may have a tenant here; administrators manage them, everyone else sees their own
|
|
72
|
+
* sign-ins.
|
|
73
|
+
*/
|
|
74
|
+
class GatewayService {
|
|
75
|
+
constructor(flow, tenants, environments, hooks) {
|
|
76
|
+
this.flow = flow;
|
|
77
|
+
this.tenants = tenants;
|
|
78
|
+
this.environments = environments;
|
|
79
|
+
this.hooks = hooks;
|
|
80
|
+
}
|
|
81
|
+
async call(caller, method, params) {
|
|
82
|
+
const [service, name] = method.split('/');
|
|
83
|
+
const handlers = service === 'TaGatewayServer'
|
|
84
|
+
? {
|
|
85
|
+
getGateway: async () => this.info(caller),
|
|
86
|
+
setEnvironment: async (choice) => this.setEnvironment(caller, choice),
|
|
87
|
+
restartEnvironment: async () => this.restart(caller),
|
|
88
|
+
listTenants: async () => this.listTenants(caller),
|
|
89
|
+
stopTenant: async (id) => this.stopTenant(caller, id),
|
|
90
|
+
}
|
|
91
|
+
: {
|
|
92
|
+
getAccess: async () => this.access(caller),
|
|
93
|
+
bindUrl: async (provider) => this.admin(caller, () => this.flow.bindUrl(String(provider))),
|
|
94
|
+
allow: async (account, name) => this.admin(caller, () => this.allow(account, name)),
|
|
95
|
+
dismiss: async (account) => this.admin(caller, () => this.flow.store.dismiss(String(account))),
|
|
96
|
+
disallow: async (account) => this.admin(caller, () => this.disallow(String(account))),
|
|
97
|
+
signOut: async (id) => this.signOut(caller, String(id)),
|
|
98
|
+
};
|
|
99
|
+
const handler = new Map(Object.entries(handlers)).get(name);
|
|
100
|
+
if (!handler) {
|
|
101
|
+
throw new GatewayCallError(`${method} is not a method of the gateway.`, ta_protocol_1.TaErrorCode.INVALID_ARGUMENT, 'Call a method of TaGatewayServer or TaAccessServer.');
|
|
102
|
+
}
|
|
103
|
+
return handler(...params);
|
|
104
|
+
}
|
|
105
|
+
info(caller) {
|
|
106
|
+
var _a;
|
|
107
|
+
const tenant = (_a = this.tenants.get(caller.tenant.id)) !== null && _a !== void 0 ? _a : caller.tenant;
|
|
108
|
+
return {
|
|
109
|
+
account: { id: tenant.account, name: tenant.name, avatar: tenant.avatar },
|
|
110
|
+
tenant: tenant.id,
|
|
111
|
+
environment: this.environments.info(tenant),
|
|
112
|
+
options: this.environments.choices(),
|
|
113
|
+
own: this.ownAllowed(),
|
|
114
|
+
admin: caller.admin,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
ownAllowed() {
|
|
118
|
+
return this.environments.settings.own;
|
|
119
|
+
}
|
|
120
|
+
async setEnvironment(caller, value) {
|
|
121
|
+
var _a;
|
|
122
|
+
const choice = GatewayServiceUtil.choice(value, this.ownAllowed(), this.environments.providers.map(provider => provider.id));
|
|
123
|
+
const tenant = (_a = this.tenants.get(caller.tenant.id)) !== null && _a !== void 0 ? _a : caller.tenant;
|
|
124
|
+
const next = await this.environments.change(tenant, choice);
|
|
125
|
+
caller.tenant = next;
|
|
126
|
+
// Everyone of the tenant connects again, once the browser that asked has its answer.
|
|
127
|
+
this.hooks.reset(next.id);
|
|
128
|
+
return this.info(caller);
|
|
129
|
+
}
|
|
130
|
+
async restart(caller) {
|
|
131
|
+
await this.environments.stop(caller.tenant.id).catch(() => undefined);
|
|
132
|
+
this.hooks.reset(caller.tenant.id);
|
|
133
|
+
return this.info(caller);
|
|
134
|
+
}
|
|
135
|
+
async listTenants(caller) {
|
|
136
|
+
return this.admin(caller, () => this.tenants.list().map(tenant => ({
|
|
137
|
+
id: tenant.id,
|
|
138
|
+
account: tenant.account,
|
|
139
|
+
name: tenant.name,
|
|
140
|
+
environment: this.environments.info(tenant),
|
|
141
|
+
connections: this.environments.connections(tenant.id),
|
|
142
|
+
createdAt: tenant.createdAt,
|
|
143
|
+
lastActiveAt: tenant.lastActiveAt,
|
|
144
|
+
})));
|
|
145
|
+
}
|
|
146
|
+
async stopTenant(caller, id) {
|
|
147
|
+
await this.admin(caller, () => this.environments.stop(String(id)));
|
|
148
|
+
this.hooks.reset(String(id));
|
|
149
|
+
}
|
|
150
|
+
access(caller) {
|
|
151
|
+
const providers = this.flow.providers.map(({ id, name }) => ({ id, name }));
|
|
152
|
+
const info = this.flow.store.info(caller.token);
|
|
153
|
+
if (caller.admin) {
|
|
154
|
+
return { providers, canManage: true, ...info };
|
|
155
|
+
}
|
|
156
|
+
return { providers, canManage: false, accounts: [], requests: [], signIns: info.signIns.filter(signIn => signIn.account === caller.account) };
|
|
157
|
+
}
|
|
158
|
+
allow(account, name) {
|
|
159
|
+
if (typeof account !== 'string' || !/^[a-z][a-z0-9-]*:\S+$/.test(account.trim())) {
|
|
160
|
+
throw new GatewayCallError(`${account} is not an account.`, ta_protocol_1.TaErrorCode.INVALID_ARGUMENT, 'Write it <provider>:<login or address>, such as github:octocat.');
|
|
161
|
+
}
|
|
162
|
+
this.flow.store.allow(account.trim(), typeof name === 'string' ? name : undefined);
|
|
163
|
+
}
|
|
164
|
+
/** The browsers of the account are cut off, and what reaches its Ta otherwise (paired phones) goes with its sandbox. */
|
|
165
|
+
async disallow(account) {
|
|
166
|
+
this.flow.store.disallow(access_store_1.AccessUtil.normalize(account));
|
|
167
|
+
this.hooks.cutOff();
|
|
168
|
+
for (const tenant of this.tenants.list().filter(one => !this.flow.store.allows(one.account))) {
|
|
169
|
+
const unpaired = await this.environments.revoke(tenant).catch((error) => {
|
|
170
|
+
console.warn(`ta gateway: revoking ${tenant.account} failed: ${error.message}`);
|
|
171
|
+
return 0;
|
|
172
|
+
});
|
|
173
|
+
console.log(`ta gateway: ${tenant.account} is no longer let in: its sandbox stopped, ${unpaired} paired devices removed`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
async signOut(caller, id) {
|
|
177
|
+
const own = this.flow.store.info(caller.token).signIns.find(signIn => signIn.id === id);
|
|
178
|
+
if (!caller.admin && (own === null || own === void 0 ? void 0 : own.account) !== caller.account) {
|
|
179
|
+
throw new GatewayCallError('That sign-in is not yours.', ta_protocol_1.TaErrorCode.INVALID_ARGUMENT, 'Sign out of the browsers of your own account.');
|
|
180
|
+
}
|
|
181
|
+
this.flow.store.signOut(id);
|
|
182
|
+
this.hooks.cutOff();
|
|
183
|
+
}
|
|
184
|
+
async admin(caller, action) {
|
|
185
|
+
if (!caller.admin) {
|
|
186
|
+
throw new GatewayCallError('Only administrators of the gateway may do that.', ta_protocol_1.TaErrorCode.INVALID_ARGUMENT, 'Ask one of those of TA_GATEWAY_ADMINS.');
|
|
187
|
+
}
|
|
188
|
+
return action();
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
exports.GatewayService = GatewayService;
|
|
192
|
+
//# sourceMappingURL=gateway-service.js.map
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
|
|
2
|
+
import type { Environments } from './environments';
|
|
3
|
+
import { type GatewayCaller, type GatewayService } from './gateway-service';
|
|
4
|
+
/**
|
|
5
|
+
* One browser's WebSocket: the calls of the gateway's services answered here, everything else forwarded to
|
|
6
|
+
* the Ta of its tenant, whose token only the gateway has, and back. Until that Ta answers, what the browser
|
|
7
|
+
* sends waits; if it does not start, its calls fail with ENVIRONMENT_FAILED, while those of the gateway
|
|
8
|
+
* still work, so that the page can change or restart the environment.
|
|
9
|
+
*/
|
|
10
|
+
export declare class GatewaySocket {
|
|
11
|
+
protected readonly browser: WebSocketConnection;
|
|
12
|
+
readonly caller: GatewayCaller;
|
|
13
|
+
protected readonly environments: Environments;
|
|
14
|
+
protected readonly service: GatewayService;
|
|
15
|
+
protected inner?: WebSocket;
|
|
16
|
+
protected readonly queued: string[];
|
|
17
|
+
protected failure?: string;
|
|
18
|
+
protected closed: boolean;
|
|
19
|
+
/** Calls of the gateway being answered: a change of environment stops the one this socket is on meanwhile. */
|
|
20
|
+
protected answering: number;
|
|
21
|
+
protected closeAfterAnswers?: string;
|
|
22
|
+
protected readonly release: () => void;
|
|
23
|
+
constructor(browser: WebSocketConnection, caller: GatewayCaller, environments: Environments, service: GatewayService);
|
|
24
|
+
get tenantId(): string;
|
|
25
|
+
close(code: number, reason: string): void;
|
|
26
|
+
protected open(): Promise<void>;
|
|
27
|
+
protected fromBrowser(text: string): void;
|
|
28
|
+
protected forward(text: string): void;
|
|
29
|
+
protected answer(id: unknown, method: string, params: unknown[]): Promise<void>;
|
|
30
|
+
/** The calls that wait, and those to come, fail; those of the gateway still work. */
|
|
31
|
+
protected fail(reason: string): void;
|
|
32
|
+
protected dispose(): void;
|
|
33
|
+
}
|
|
34
|
+
//# sourceMappingURL=gateway-socket.d.ts.map
|