@celljs/ta-gateway 4.15.0 → 4.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/esm/node/command-sandbox.d.ts +5 -2
  2. package/esm/node/command-sandbox.js +17 -4
  3. package/esm/node/docker-engine.d.ts +45 -0
  4. package/esm/node/docker-engine.js +87 -11
  5. package/esm/node/docker-sandbox.d.ts +3 -1
  6. package/esm/node/docker-sandbox.js +6 -0
  7. package/esm/node/environments.d.ts +34 -2
  8. package/esm/node/environments.js +187 -11
  9. package/esm/node/gateway-audit.d.ts +12 -0
  10. package/esm/node/gateway-audit.js +47 -0
  11. package/esm/node/gateway-cli.d.ts +2 -0
  12. package/esm/node/gateway-cli.js +1 -0
  13. package/esm/node/gateway-policy.d.ts +46 -0
  14. package/esm/node/gateway-policy.js +151 -0
  15. package/esm/node/gateway-quotas.d.ts +32 -0
  16. package/esm/node/gateway-quotas.js +104 -0
  17. package/esm/node/gateway-server.d.ts +16 -1
  18. package/esm/node/gateway-server.js +58 -6
  19. package/esm/node/gateway-service.d.ts +91 -16
  20. package/esm/node/gateway-service.js +366 -45
  21. package/esm/node/gateway-socket.d.ts +7 -1
  22. package/esm/node/gateway-socket.js +40 -1
  23. package/esm/node/gateway-usage.d.ts +37 -0
  24. package/esm/node/gateway-usage.js +137 -0
  25. package/esm/node/local-sandbox.d.ts +12 -0
  26. package/esm/node/local-sandbox.js +36 -1
  27. package/esm/node/sandbox-provider.d.ts +10 -0
  28. package/esm/node/tenant-store.d.ts +12 -1
  29. package/lib/node/command-sandbox.d.ts +5 -2
  30. package/lib/node/command-sandbox.js +17 -4
  31. package/lib/node/docker-engine.d.ts +45 -0
  32. package/lib/node/docker-engine.js +87 -11
  33. package/lib/node/docker-sandbox.d.ts +3 -1
  34. package/lib/node/docker-sandbox.js +6 -0
  35. package/lib/node/environments.d.ts +34 -2
  36. package/lib/node/environments.js +186 -10
  37. package/lib/node/gateway-audit.d.ts +13 -0
  38. package/lib/node/gateway-audit.js +51 -0
  39. package/lib/node/gateway-cli.d.ts +2 -0
  40. package/lib/node/gateway-cli.js +1 -0
  41. package/lib/node/gateway-policy.d.ts +47 -0
  42. package/lib/node/gateway-policy.js +156 -0
  43. package/lib/node/gateway-quotas.d.ts +33 -0
  44. package/lib/node/gateway-quotas.js +108 -0
  45. package/lib/node/gateway-server.d.ts +16 -1
  46. package/lib/node/gateway-server.js +58 -6
  47. package/lib/node/gateway-service.d.ts +91 -16
  48. package/lib/node/gateway-service.js +365 -44
  49. package/lib/node/gateway-socket.d.ts +7 -1
  50. package/lib/node/gateway-socket.js +40 -1
  51. package/lib/node/gateway-usage.d.ts +38 -0
  52. package/lib/node/gateway-usage.js +141 -0
  53. package/lib/node/local-sandbox.d.ts +12 -0
  54. package/lib/node/local-sandbox.js +38 -2
  55. package/lib/node/sandbox-provider.d.ts +10 -0
  56. package/lib/node/tenant-store.d.ts +12 -1
  57. package/package.json +4 -4
@@ -0,0 +1,47 @@
1
+ import { appendFileSync, chmodSync, existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ /** What is kept of the audit when read: the end of the file, as many bytes at most. */
4
+ const TAIL_BYTES = 2 * 1024 * 1024;
5
+ /**
6
+ * What administrators did, one JSON line each (`audit.jsonl`, readable by the gateway's user only): what changed
7
+ * and what of others was looked at (logs, what an agent did), with who and when.
8
+ */
9
+ export class GatewayAudit {
10
+ constructor(dir) {
11
+ this.file = join(dir, 'audit.jsonl');
12
+ }
13
+ add(entry, now = Date.now()) {
14
+ const fresh = !existsSync(this.file);
15
+ appendFileSync(this.file, `${JSON.stringify({ at: now, ...entry })}\n`, { mode: 0o600 });
16
+ if (fresh) {
17
+ chmodSync(this.file, 0o600);
18
+ }
19
+ }
20
+ /** The latest first. */
21
+ list(limit) {
22
+ let text;
23
+ try {
24
+ text = readFileSync(this.file, 'utf8');
25
+ }
26
+ catch (_a) {
27
+ return [];
28
+ }
29
+ if (text.length > TAIL_BYTES) {
30
+ text = text.slice(text.indexOf('\n', text.length - TAIL_BYTES) + 1);
31
+ }
32
+ const entries = [];
33
+ const lines = text.split('\n');
34
+ for (let index = lines.length - 1; index >= 0 && entries.length < limit; index--) {
35
+ try {
36
+ if (lines[index]) {
37
+ entries.push(JSON.parse(lines[index]));
38
+ }
39
+ }
40
+ catch (_b) {
41
+ // A line cut short when the gateway stopped.
42
+ }
43
+ }
44
+ return entries;
45
+ }
46
+ }
47
+ //# sourceMappingURL=gateway-audit.js.map
@@ -3,6 +3,8 @@ export interface GatewayCliOptions {
3
3
  publicDir: string;
4
4
  /** How to run `ta` (the local sandboxes). */
5
5
  taCommand: string[];
6
+ /** Of Ta, which the console shows. */
7
+ version?: string;
6
8
  }
7
9
  export declare namespace GatewayCli {
8
10
  function run(argv: string[], options: GatewayCliOptions): Promise<void>;
@@ -63,6 +63,7 @@ export var GatewayCli;
63
63
  port: Number((_d = (_c = values.port) !== null && _c !== void 0 ? _c : process.env.PORT) !== null && _d !== void 0 ? _d : 4100),
64
64
  publicDir: options.publicDir,
65
65
  taCommand: options.taCommand,
66
+ version: options.version,
66
67
  });
67
68
  }
68
69
  catch (error) {
@@ -0,0 +1,46 @@
1
+ import type { TaGatewayLimits, TaGatewayPolicy, TaGatewayRole } from '@celljs/ta-protocol';
2
+ interface StoredPolicy {
3
+ defaults?: TaGatewayLimits;
4
+ /** Accounts made admins in the console. */
5
+ admins?: string[];
6
+ }
7
+ /** The limits of a member once the defaults and their own are taken together: none where a value is missing. */
8
+ export interface ResolvedLimits {
9
+ freeMinutes?: number;
10
+ promptsPerMinute?: number;
11
+ connections?: number;
12
+ providers?: string[];
13
+ own: boolean;
14
+ }
15
+ export declare class PolicyError extends Error {
16
+ }
17
+ export declare namespace GatewayPolicyUtil {
18
+ function rank(role: TaGatewayRole): number;
19
+ /**
20
+ * Limits as a page sent them, checked: whole numbers of 0 and more, a list of providers of those there are, a
21
+ * boolean. `nullable`: those of an account, where null drops a limit; in the defaults null is none, left out.
22
+ */
23
+ function limits(value: unknown, providers: readonly string[], nullable: boolean): TaGatewayLimits;
24
+ /** An account's own over the defaults: a value of its own wins, null in it is none. */
25
+ function resolve(defaults: TaGatewayLimits, own: TaGatewayLimits | undefined, ownAllowed: boolean): ResolvedLimits;
26
+ }
27
+ /**
28
+ * Who manages the gateway and what members may use: owners are those of TA_GATEWAY_ADMINS, where the gateway runs,
29
+ * which the console cannot change; admins and the default limits are those of `policy.json`, which owners change
30
+ * in the console.
31
+ */
32
+ export declare class GatewayPolicy {
33
+ protected readonly owners: readonly string[];
34
+ protected readonly file: string;
35
+ protected stored: StoredPolicy;
36
+ constructor(dir: string, owners: readonly string[]);
37
+ role(account: string): TaGatewayRole;
38
+ /** Whether the account is let in by its role, whatever the list of access says. */
39
+ lets(account: string): boolean;
40
+ get defaults(): TaGatewayLimits;
41
+ setDefaults(limits: TaGatewayLimits): void;
42
+ setRole(account: string, role: 'admin' | 'member'): void;
43
+ view(idleMinutes: number): TaGatewayPolicy;
44
+ protected read(): StoredPolicy;
45
+ }
46
+ export {};
@@ -0,0 +1,151 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { AccessUtil } from '@celljs/ta-host/lib/node/sign-in/access-store';
4
+ import { writePrivate } from './tenant-store.js';
5
+ export class PolicyError extends Error {
6
+ }
7
+ export var GatewayPolicyUtil;
8
+ (function (GatewayPolicyUtil) {
9
+ const NUMBERS = ['freeMinutes', 'promptsPerMinute', 'connections'];
10
+ const RANK = { member: 0, admin: 1, owner: 2 };
11
+ function rank(role) {
12
+ return RANK[role];
13
+ }
14
+ GatewayPolicyUtil.rank = rank;
15
+ /**
16
+ * Limits as a page sent them, checked: whole numbers of 0 and more, a list of providers of those there are, a
17
+ * boolean. `nullable`: those of an account, where null drops a limit; in the defaults null is none, left out.
18
+ */
19
+ function limits(value, providers, nullable) {
20
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
21
+ throw new PolicyError('Limits are an object, such as { "freeMinutes": 600 }.');
22
+ }
23
+ const given = value;
24
+ const out = {};
25
+ for (const key of Object.keys(given)) {
26
+ if (![...NUMBERS, 'providers', 'own'].includes(key)) {
27
+ throw new PolicyError(`"${key}" is no limit: those there are are ${[...NUMBERS, 'providers', 'own'].join(', ')}.`);
28
+ }
29
+ }
30
+ for (const key of NUMBERS) {
31
+ const item = given[key];
32
+ if (item === undefined) {
33
+ continue;
34
+ }
35
+ if (item === null) {
36
+ if (nullable) {
37
+ out[key] = null;
38
+ }
39
+ continue;
40
+ }
41
+ if (typeof item !== 'number' || !Number.isInteger(item) || item < 0 || item > 10000000) {
42
+ throw new PolicyError(`"${key}" is a whole number from 0, or null for none.`);
43
+ }
44
+ out[key] = item;
45
+ }
46
+ if (given.providers !== undefined) {
47
+ if (given.providers === null) {
48
+ if (nullable) {
49
+ out.providers = null;
50
+ }
51
+ }
52
+ else if (!Array.isArray(given.providers) || given.providers.some(id => typeof id !== 'string' || !providers.includes(id))) {
53
+ throw new PolicyError(`"providers" lists providers of the gateway: ${providers.join(', ')}.`);
54
+ }
55
+ else {
56
+ out.providers = [...new Set(given.providers)];
57
+ }
58
+ }
59
+ if (given.own !== undefined) {
60
+ if (given.own === null) {
61
+ if (nullable) {
62
+ out.own = null;
63
+ }
64
+ }
65
+ else if (typeof given.own !== 'boolean') {
66
+ throw new PolicyError('"own" is true or false.');
67
+ }
68
+ else {
69
+ out.own = given.own;
70
+ }
71
+ }
72
+ return out;
73
+ }
74
+ GatewayPolicyUtil.limits = limits;
75
+ /** An account's own over the defaults: a value of its own wins, null in it is none. */
76
+ function resolve(defaults, own, ownAllowed) {
77
+ const pick = (key) => (own && own[key] !== undefined ? own[key] : defaults[key]);
78
+ const number = (key) => {
79
+ const value = pick(key);
80
+ return typeof value === 'number' ? value : undefined;
81
+ };
82
+ const providers = pick('providers');
83
+ const own_ = pick('own');
84
+ return {
85
+ freeMinutes: number('freeMinutes'),
86
+ promptsPerMinute: number('promptsPerMinute'),
87
+ connections: number('connections'),
88
+ providers: Array.isArray(providers) ? providers : undefined,
89
+ own: ownAllowed && own_ !== false,
90
+ };
91
+ }
92
+ GatewayPolicyUtil.resolve = resolve;
93
+ })(GatewayPolicyUtil || (GatewayPolicyUtil = {}));
94
+ /**
95
+ * Who manages the gateway and what members may use: owners are those of TA_GATEWAY_ADMINS, where the gateway runs,
96
+ * which the console cannot change; admins and the default limits are those of `policy.json`, which owners change
97
+ * in the console.
98
+ */
99
+ export class GatewayPolicy {
100
+ constructor(dir, owners) {
101
+ this.owners = owners;
102
+ this.file = join(dir, 'policy.json');
103
+ this.stored = this.read();
104
+ }
105
+ role(account) {
106
+ var _a;
107
+ if (this.owners.some(pattern => AccessUtil.matches(pattern, account))) {
108
+ return 'owner';
109
+ }
110
+ return ((_a = this.stored.admins) === null || _a === void 0 ? void 0 : _a.includes(account)) ? 'admin' : 'member';
111
+ }
112
+ /** Whether the account is let in by its role, whatever the list of access says. */
113
+ lets(account) {
114
+ return this.role(account) !== 'member';
115
+ }
116
+ get defaults() {
117
+ var _a;
118
+ return (_a = this.stored.defaults) !== null && _a !== void 0 ? _a : {};
119
+ }
120
+ setDefaults(limits) {
121
+ this.stored = { ...this.stored, defaults: limits };
122
+ writePrivate(this.file, this.stored);
123
+ }
124
+ setRole(account, role) {
125
+ var _a;
126
+ const admins = ((_a = this.stored.admins) !== null && _a !== void 0 ? _a : []).filter(other => other !== account);
127
+ this.stored = { ...this.stored, admins: role === 'admin' ? [...admins, account] : admins };
128
+ writePrivate(this.file, this.stored);
129
+ }
130
+ view(idleMinutes) {
131
+ var _a;
132
+ return {
133
+ defaults: this.defaults,
134
+ admins: [
135
+ ...this.owners.map(account => ({ account, role: 'owner' })),
136
+ ...((_a = this.stored.admins) !== null && _a !== void 0 ? _a : []).filter(account => this.role(account) === 'admin').map(account => ({ account, role: 'admin' })),
137
+ ],
138
+ idleMinutes,
139
+ };
140
+ }
141
+ read() {
142
+ try {
143
+ const value = JSON.parse(readFileSync(this.file, 'utf8'));
144
+ return value && typeof value === 'object' ? value : {};
145
+ }
146
+ catch (_a) {
147
+ return {};
148
+ }
149
+ }
150
+ }
151
+ //# sourceMappingURL=gateway-policy.js.map
@@ -0,0 +1,32 @@
1
+ import type { TaGatewayRole, TaQuotaBlock, TaQuotaState } from '@celljs/ta-protocol';
2
+ import { type GatewayPolicy, type ResolvedLimits } from './gateway-policy.js';
3
+ import { type GatewayUsage } from './gateway-usage.js';
4
+ import type { Tenant, TenantMeter, TenantStore } from './tenant-store.js';
5
+ /**
6
+ * What members may use and what they used: the minutes their sandboxes ran this month (of UTC), counted by the
7
+ * gateway as it sees them run, and the messages a minute they send their agents. Owners have no limits.
8
+ */
9
+ export declare class GatewayQuotas {
10
+ protected readonly policy: GatewayPolicy;
11
+ protected readonly tenants: TenantStore;
12
+ protected readonly usage: GatewayUsage;
13
+ protected readonly ownAllowed: () => boolean;
14
+ protected lastTick: number;
15
+ /** By tenant: the times of its messages within the last minute. */
16
+ protected readonly prompts: Map<string, number[]>;
17
+ constructor(policy: GatewayPolicy, tenants: TenantStore, usage: GatewayUsage, ownAllowed: () => boolean);
18
+ role(tenant: Tenant): TaGatewayRole;
19
+ limits(tenant: Tenant): ResolvedLimits;
20
+ /** That of this month: a meter of a month before starts again. */
21
+ meter(tenant: Tenant, now?: number): TenantMeter;
22
+ blocked(tenant: Tenant, now?: number): TaQuotaBlock | undefined;
23
+ state(tenant: Tenant, now?: number): TaQuotaState;
24
+ /** What a message of the tenant to its agents needs: false when it sent as many this minute as it may. */
25
+ takePrompt(tenant: Tenant, now?: number): boolean;
26
+ /** When the next message may go: the oldest of the minute leaves it. */
27
+ retryAfter(tenant: Tenant, now?: number): number;
28
+ /** The time since the last tick, to each tenant whose sandbox ran meanwhile; those now blocked. */
29
+ tick(running: readonly string[], now?: number): Tenant[];
30
+ /** Free minutes on top of the limit, this month; never fewer than none. */
31
+ grant(tenant: Tenant, minutes: number, now?: number): Tenant;
32
+ }
@@ -0,0 +1,104 @@
1
+ import { GatewayPolicyUtil } from './gateway-policy.js';
2
+ import { GatewayUsageUtil } from './gateway-usage.js';
3
+ const MINUTE = 60000;
4
+ /** Of the time between two ticks, at most this counts: a gateway asleep or stopped did not see its sandboxes run. */
5
+ const MAX_TICK_MS = 2 * MINUTE;
6
+ /**
7
+ * What members may use and what they used: the minutes their sandboxes ran this month (of UTC), counted by the
8
+ * gateway as it sees them run, and the messages a minute they send their agents. Owners have no limits.
9
+ */
10
+ export class GatewayQuotas {
11
+ constructor(policy, tenants, usage, ownAllowed) {
12
+ this.policy = policy;
13
+ this.tenants = tenants;
14
+ this.usage = usage;
15
+ this.ownAllowed = ownAllowed;
16
+ this.lastTick = Date.now();
17
+ /** By tenant: the times of its messages within the last minute. */
18
+ this.prompts = new Map();
19
+ }
20
+ role(tenant) {
21
+ return this.policy.role(tenant.account);
22
+ }
23
+ limits(tenant) {
24
+ if (this.role(tenant) === 'owner') {
25
+ return { own: this.ownAllowed() };
26
+ }
27
+ return GatewayPolicyUtil.resolve(this.policy.defaults, tenant.limits, this.ownAllowed());
28
+ }
29
+ /** That of this month: a meter of a month before starts again. */
30
+ meter(tenant, now = Date.now()) {
31
+ var _a;
32
+ const { key } = GatewayUsageUtil.month(now);
33
+ return ((_a = tenant.meter) === null || _a === void 0 ? void 0 : _a.month) === key ? tenant.meter : { month: key, runMs: 0, bonusMinutes: 0 };
34
+ }
35
+ blocked(tenant, now = Date.now()) {
36
+ if (tenant.suspended && this.role(tenant) !== 'owner') {
37
+ return 'suspended';
38
+ }
39
+ const { freeMinutes } = this.limits(tenant);
40
+ const meter = this.meter(tenant, now);
41
+ return freeMinutes !== undefined && meter.runMs >= (freeMinutes + meter.bonusMinutes) * MINUTE ? 'minutes' : undefined;
42
+ }
43
+ state(tenant, now = Date.now()) {
44
+ const { key, next } = GatewayUsageUtil.month(now);
45
+ const meter = this.meter(tenant, now);
46
+ const limits = this.limits(tenant);
47
+ const month = this.usage.month(tenant.id, now);
48
+ return {
49
+ month: key,
50
+ resetsAt: next,
51
+ minutes: { used: Math.floor(meter.runMs / MINUTE), limit: limits.freeMinutes, bonus: meter.bonusMinutes },
52
+ tokens: { used: month.tokens, cost: month.cost },
53
+ promptsPerMinute: limits.promptsPerMinute,
54
+ connections: limits.connections,
55
+ blocked: this.blocked(tenant, now),
56
+ };
57
+ }
58
+ /** What a message of the tenant to its agents needs: false when it sent as many this minute as it may. */
59
+ takePrompt(tenant, now = Date.now()) {
60
+ var _a;
61
+ const limit = this.limits(tenant).promptsPerMinute;
62
+ if (limit === undefined) {
63
+ return true;
64
+ }
65
+ const times = ((_a = this.prompts.get(tenant.id)) !== null && _a !== void 0 ? _a : []).filter(time => now - time < MINUTE);
66
+ if (times.length >= limit) {
67
+ this.prompts.set(tenant.id, times);
68
+ return false;
69
+ }
70
+ times.push(now);
71
+ this.prompts.set(tenant.id, times);
72
+ return true;
73
+ }
74
+ /** When the next message may go: the oldest of the minute leaves it. */
75
+ retryAfter(tenant, now = Date.now()) {
76
+ var _a;
77
+ const oldest = (_a = this.prompts.get(tenant.id)) === null || _a === void 0 ? void 0 : _a[0];
78
+ return oldest === undefined ? 0 : Math.max(0, MINUTE - (now - oldest));
79
+ }
80
+ /** The time since the last tick, to each tenant whose sandbox ran meanwhile; those now blocked. */
81
+ tick(running, now = Date.now()) {
82
+ const elapsed = Math.min(Math.max(0, now - this.lastTick), MAX_TICK_MS);
83
+ this.lastTick = now;
84
+ const blocked = [];
85
+ for (const id of running) {
86
+ const tenant = this.tenants.get(id);
87
+ if (!tenant) {
88
+ continue;
89
+ }
90
+ const meter = this.meter(tenant, now);
91
+ const next = this.tenants.update(id, { meter: { ...meter, runMs: meter.runMs + elapsed } });
92
+ if (this.blocked(next, now)) {
93
+ blocked.push(next);
94
+ }
95
+ }
96
+ return blocked;
97
+ }
98
+ /** Free minutes on top of the limit, this month; never fewer than none. */
99
+ grant(tenant, minutes, now = Date.now()) {
100
+ const meter = this.meter(tenant, now);
101
+ return this.tenants.update(tenant.id, { meter: { ...meter, bonusMinutes: Math.max(0, meter.bonusMinutes + minutes) } });
102
+ }
103
+ }
104
+ //# sourceMappingURL=gateway-quotas.js.map
@@ -2,9 +2,14 @@ import { type IncomingMessage, type Server, type ServerResponse } from 'node:htt
2
2
  import { type Duplex } from 'node:stream';
3
3
  import { SignInFlow } from '@celljs/ta-host/lib/node/sign-in/sign-in-flow';
4
4
  import { type SignInAccount } from '@celljs/ta-host/lib/node/sign-in/sign-in-provider';
5
+ import { type TaQuotaBlock } from '@celljs/ta-protocol';
5
6
  import { Environments } from './environments.js';
7
+ import { GatewayAudit } from './gateway-audit.js';
8
+ import { GatewayPolicy } from './gateway-policy.js';
9
+ import { GatewayQuotas } from './gateway-quotas.js';
6
10
  import { type GatewayCaller, GatewayService } from './gateway-service.js';
7
11
  import { GatewaySocket } from './gateway-socket.js';
12
+ import { GatewayUsage } from './gateway-usage.js';
8
13
  import { type SandboxProviderFactory, SandboxProviders } from './sandbox-provider.js';
9
14
  import { SignInLinks } from './sign-in-links.js';
10
15
  import { TenantStore } from './tenant-store.js';
@@ -19,8 +24,12 @@ export interface GatewayServerOptions {
19
24
  publicDir: string;
20
25
  taCommand: string[];
21
26
  env?: Record<string, string | undefined>;
27
+ /** Of Ta, for the console. */
28
+ version?: string;
22
29
  }
23
30
  export declare namespace GatewayServerUtil {
31
+ /** What a page is told when its Ta does not start for its account's limits; TaGatewayInfo.quota says it in the page's words. */
32
+ function blockedReason(block: TaQuotaBlock | undefined): string | undefined;
24
33
  /** A file of `root` for a path of the page, never outside it; the page for what is not a file. */
25
34
  function file(root: string, urlPath: string): string;
26
35
  /**
@@ -50,11 +59,17 @@ export declare class GatewayServer {
50
59
  readonly links: SignInLinks;
51
60
  protected readonly service: GatewayService;
52
61
  protected readonly sockets: Set<GatewaySocket>;
53
- protected readonly admins: string[];
62
+ readonly policy: GatewayPolicy;
63
+ readonly quotas: GatewayQuotas;
64
+ readonly usage: GatewayUsage;
65
+ readonly audit: GatewayAudit;
54
66
  protected server?: Server;
67
+ protected ticker?: ReturnType<typeof setInterval>;
55
68
  static create(options: GatewayServerOptions): Promise<GatewayServer>;
56
69
  protected constructor(options: GatewayServerOptions, providers: Awaited<ReturnType<typeof SandboxProviders.create>>, config: ReturnType<typeof SandboxProviders.read>);
57
70
  isAdmin(account: string): boolean;
71
+ /** The minutes of the sandboxes that ran since the last time; those out of them, or suspended, stop. */
72
+ tick(now?: number): Promise<void>;
58
73
  listen(): Promise<string>;
59
74
  close(): Promise<void>;
60
75
  /** The browsers whose sign-in no longer works are cut off. */
@@ -12,13 +12,19 @@ import { TA_FILES_PATH, TA_WEBSOCKET_PATH } from '@celljs/ta-protocol';
12
12
  import { CommandSandbox } from './command-sandbox.js';
13
13
  import { DockerSandbox } from './docker-sandbox.js';
14
14
  import { Environments } from './environments.js';
15
+ import { GatewayAudit } from './gateway-audit.js';
16
+ import { GatewayPolicy } from './gateway-policy.js';
17
+ import { GatewayQuotas } from './gateway-quotas.js';
15
18
  import { GatewayService } from './gateway-service.js';
16
19
  import { GatewaySocket } from './gateway-socket.js';
20
+ import { GatewayUsage } from './gateway-usage.js';
17
21
  import { LocalSandbox } from './local-sandbox.js';
18
22
  import { SandboxProviders } from './sandbox-provider.js';
19
23
  import { SIGN_IN_LINK_PATH, SignInLinks } from './sign-in-links.js';
20
24
  import { TaSandbox } from './ta-sandbox.js';
21
25
  import { TenantStore } from './tenant-store.js';
26
+ /** How often the minutes of running sandboxes are counted, and those out of them stopped. */
27
+ const TICK_MS = 30000;
22
28
  /** The browser's token for `/api/files`, which pages load by URL, without the token of the WebSocket. */
23
29
  const FILES_COOKIE = 'ta_gateway';
24
30
  const TYPES = {
@@ -44,6 +50,18 @@ export const SANDBOX_TYPES = {
44
50
  };
45
51
  export var GatewayServerUtil;
46
52
  (function (GatewayServerUtil) {
53
+ /** What a page is told when its Ta does not start for its account's limits; TaGatewayInfo.quota says it in the page's words. */
54
+ function blockedReason(block) {
55
+ switch (block) {
56
+ case 'suspended':
57
+ return 'Your account is suspended by an administrator of the gateway.';
58
+ case 'minutes':
59
+ return 'Your free minutes of this month are used up.';
60
+ default:
61
+ return undefined;
62
+ }
63
+ }
64
+ GatewayServerUtil.blockedReason = blockedReason;
47
65
  /** A file of `root` for a path of the page, never outside it; the page for what is not a file. */
48
66
  function file(root, urlPath) {
49
67
  let path;
@@ -100,8 +118,9 @@ export class GatewayServer {
100
118
  this.options = options;
101
119
  this.sockets = new Set();
102
120
  const env = (_a = options.env) !== null && _a !== void 0 ? _a : process.env;
103
- this.admins = AccessUtil.parseList(env.TA_GATEWAY_ADMINS);
104
- const allowed = [...AccessUtil.parseList(env.TA_ALLOWED_USERS), ...this.admins];
121
+ const owners = AccessUtil.parseList(env.TA_GATEWAY_ADMINS);
122
+ this.policy = new GatewayPolicy(options.dir, owners);
123
+ const allowed = [...AccessUtil.parseList(env.TA_ALLOWED_USERS), ...owners];
105
124
  this.flow = new SignInFlow(SignInProviders.fromEnv(env), new AccessStore(join(options.dir, 'access.json'), allowed), SignInProviders.publicUrl(env));
106
125
  this.tenants = new TenantStore(options.dir);
107
126
  this.links = new SignInLinks(options.dir);
@@ -110,15 +129,40 @@ export class GatewayServer {
110
129
  own: config.ownEnvironments !== false,
111
130
  idleMinutes: (_b = config.idleMinutes) !== null && _b !== void 0 ? _b : 0,
112
131
  });
113
- this.service = new GatewayService(this.flow, this.tenants, this.environments, { cutOff: () => this.cutOff(), reset: id => this.reset(id) });
132
+ this.usage = new GatewayUsage(options.dir);
133
+ this.audit = new GatewayAudit(options.dir);
134
+ this.quotas = new GatewayQuotas(this.policy, this.tenants, this.usage, () => this.environments.settings.own);
135
+ this.environments.guard = tenant => GatewayServerUtil.blockedReason(this.quotas.blocked(tenant));
136
+ this.service = new GatewayService({
137
+ flow: this.flow,
138
+ tenants: this.tenants,
139
+ environments: this.environments,
140
+ policy: this.policy,
141
+ quotas: this.quotas,
142
+ usage: this.usage,
143
+ audit: this.audit,
144
+ hooks: { cutOff: () => this.cutOff(), reset: id => this.reset(id) },
145
+ meta: { links: this.links, startedAt: Date.now(), version: options.version, publicUrl: SandboxProviders.publicBase(env) },
146
+ });
114
147
  }
115
148
  isAdmin(account) {
116
- return this.admins.some(pattern => AccessUtil.matches(pattern, account));
149
+ return this.policy.role(account) !== 'member';
150
+ }
151
+ /** The minutes of the sandboxes that ran since the last time; those out of them, or suspended, stop. */
152
+ async tick(now = Date.now()) {
153
+ for (const tenant of this.quotas.tick(this.environments.runningIds(), now)) {
154
+ console.log(`ta gateway: ${tenant.account} used its free minutes of the month: its sandbox stops`);
155
+ await this.environments.stop(tenant.id).catch(() => undefined);
156
+ this.reset(tenant.id);
157
+ }
117
158
  }
118
159
  listen() {
160
+ var _a, _b;
119
161
  const server = createServer((request, response) => void this.handle(request, response));
120
162
  server.on('upgrade', (request, socket, head) => this.upgrade(request, socket, head));
121
163
  this.server = server;
164
+ this.ticker = setInterval(() => void this.tick().catch(error => console.warn(`ta gateway: counting minutes failed: ${error.message}`)), TICK_MS);
165
+ (_b = (_a = this.ticker).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
122
166
  return new Promise((resolve, reject) => {
123
167
  var _a, _b;
124
168
  server.once('error', reject);
@@ -129,6 +173,8 @@ export class GatewayServer {
129
173
  });
130
174
  }
131
175
  async close() {
176
+ clearInterval(this.ticker);
177
+ await this.tick().catch(() => undefined);
132
178
  for (const socket of this.sockets) {
133
179
  socket.close(1001, 'The gateway is stopping.');
134
180
  }
@@ -162,7 +208,8 @@ export class GatewayServer {
162
208
  return undefined;
163
209
  }
164
210
  const tenant = this.tenants.ensure({ id: signIn.account, name: signIn.name, avatar: signIn.avatar });
165
- return { token, account: signIn.account, tenant, admin: this.isAdmin(signIn.account) };
211
+ const role = this.policy.role(signIn.account);
212
+ return { token, account: signIn.account, tenant, role, admin: role !== 'member' };
166
213
  }
167
214
  async handle(request, response) {
168
215
  var _a;
@@ -306,9 +353,14 @@ export class GatewayServer {
306
353
  WebSocketConnection.refuse(socket, 401, 'Not authorized.');
307
354
  return;
308
355
  }
356
+ const most = this.quotas.limits(caller.tenant).connections;
357
+ if (most !== undefined && this.environments.connections(caller.tenant.id) >= most) {
358
+ WebSocketConnection.refuse(socket, 429, `At most ${most} pages of your account connect at once.`);
359
+ return;
360
+ }
309
361
  this.tenants.update(caller.tenant.id, { lastActiveAt: Date.now() });
310
362
  const connection = WebSocketConnection.open(socket, checked.key, head, { maxPayload: 32 * 1024 * 1024, heartbeat: 30000, deflate: checked.deflate });
311
- const gatewaySocket = new GatewaySocket(connection, caller, this.environments, this.service);
363
+ const gatewaySocket = new GatewaySocket(connection, caller, this.environments, this.service, this.quotas);
312
364
  this.sockets.add(gatewaySocket);
313
365
  connection.onClose(() => this.sockets.delete(gatewaySocket));
314
366
  }