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