@celljs/ta-relay 4.24.0 → 4.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.en.md +6 -6
  2. package/README.md +6 -6
  3. package/esm/common/index.d.ts +5 -0
  4. package/esm/common/index.js +5 -0
  5. package/esm/common/relay-accounts.d.ts +2 -0
  6. package/esm/common/relay-accounts.js +21 -0
  7. package/esm/common/relay-blobs.d.ts +2 -0
  8. package/esm/common/relay-blobs.js +1 -0
  9. package/esm/common/relay-content-origin.d.ts +44 -0
  10. package/esm/common/relay-content-origin.js +67 -0
  11. package/esm/common/relay-content.d.ts +2 -0
  12. package/esm/common/relay-content.js +12 -2
  13. package/esm/common/relay-friends.js +1 -1
  14. package/esm/common/relay-hub-util.js +1 -1
  15. package/esm/common/relay-hub.js +4 -4
  16. package/esm/common/relay-hubs-admins.js +3 -3
  17. package/esm/common/relay-hubs.js +5 -5
  18. package/esm/common/relay-info.d.ts +11 -1
  19. package/esm/common/relay-info.js +20 -2
  20. package/esm/common/relay-moderation-client.d.ts +32 -0
  21. package/esm/common/relay-moderation-client.js +51 -0
  22. package/esm/common/relay-moderation-door.d.ts +24 -0
  23. package/esm/common/relay-moderation-door.js +48 -0
  24. package/esm/common/relay-moderation-policy.d.ts +78 -0
  25. package/esm/common/relay-moderation-policy.js +59 -0
  26. package/esm/common/relay-moderation.d.ts +165 -0
  27. package/esm/common/relay-moderation.js +464 -0
  28. package/esm/common/relay-protocol.d.ts +5 -1
  29. package/esm/common/relay-protocol.js +4 -0
  30. package/esm/common/relay-room-app.d.ts +5 -0
  31. package/esm/common/relay-room-app.js +8 -0
  32. package/esm/node/relay-chat-files.js +1 -1
  33. package/esm/node/relay-server-accounts.d.ts +2 -0
  34. package/esm/node/relay-server-accounts.js +4 -0
  35. package/esm/node/relay-server-gate.d.ts +39 -0
  36. package/esm/node/relay-server-gate.js +124 -0
  37. package/esm/node/relay-server-web.d.ts +5 -0
  38. package/esm/node/relay-server-web.js +28 -0
  39. package/esm/node/relay-server.d.ts +9 -2
  40. package/esm/node/relay-server.js +40 -47
  41. package/esm/node/relay-store.d.ts +4 -0
  42. package/esm/node/relay-store.js +2 -0
  43. package/esm/viewer/viewer-i18n.d.ts +25 -0
  44. package/esm/viewer/viewer-i18n.js +132 -32
  45. package/esm/viewer/viewer-style.d.ts +1 -1
  46. package/esm/viewer/viewer-style.js +13 -0
  47. package/esm/viewer/viewer.js +127 -6
  48. package/lib/common/index.d.ts +5 -0
  49. package/lib/common/index.js +5 -0
  50. package/lib/common/relay-accounts.d.ts +2 -0
  51. package/lib/common/relay-accounts.js +21 -0
  52. package/lib/common/relay-blobs.d.ts +2 -0
  53. package/lib/common/relay-blobs.js +1 -0
  54. package/lib/common/relay-content-origin.d.ts +45 -0
  55. package/lib/common/relay-content-origin.js +71 -0
  56. package/lib/common/relay-content.d.ts +2 -0
  57. package/lib/common/relay-content.js +12 -2
  58. package/lib/common/relay-friends.js +1 -1
  59. package/lib/common/relay-hub-util.js +1 -1
  60. package/lib/common/relay-hub.js +4 -4
  61. package/lib/common/relay-hubs-admins.js +3 -3
  62. package/lib/common/relay-hubs.js +5 -5
  63. package/lib/common/relay-info.d.ts +11 -1
  64. package/lib/common/relay-info.js +20 -2
  65. package/lib/common/relay-moderation-client.d.ts +33 -0
  66. package/lib/common/relay-moderation-client.js +54 -0
  67. package/lib/common/relay-moderation-door.d.ts +25 -0
  68. package/lib/common/relay-moderation-door.js +51 -0
  69. package/lib/common/relay-moderation-policy.d.ts +79 -0
  70. package/lib/common/relay-moderation-policy.js +62 -0
  71. package/lib/common/relay-moderation.d.ts +166 -0
  72. package/lib/common/relay-moderation.js +468 -0
  73. package/lib/common/relay-protocol.d.ts +5 -1
  74. package/lib/common/relay-protocol.js +4 -0
  75. package/lib/common/relay-room-app.d.ts +5 -0
  76. package/lib/common/relay-room-app.js +8 -0
  77. package/lib/node/relay-chat-files.js +1 -1
  78. package/lib/node/relay-server-accounts.d.ts +2 -0
  79. package/lib/node/relay-server-accounts.js +4 -0
  80. package/lib/node/relay-server-gate.d.ts +40 -0
  81. package/lib/node/relay-server-gate.js +128 -0
  82. package/lib/node/relay-server-web.d.ts +6 -0
  83. package/lib/node/relay-server-web.js +31 -0
  84. package/lib/node/relay-server.d.ts +9 -2
  85. package/lib/node/relay-server.js +39 -46
  86. package/lib/node/relay-store.d.ts +4 -0
  87. package/lib/node/relay-store.js +2 -0
  88. package/lib/viewer/viewer-i18n.d.ts +25 -0
  89. package/lib/viewer/viewer-i18n.js +132 -32
  90. package/lib/viewer/viewer-style.d.ts +1 -1
  91. package/lib/viewer/viewer-style.js +13 -0
  92. package/lib/viewer/viewer.js +127 -6
  93. package/package.json +3 -3
  94. package/viewer/join.html +5 -5
  95. package/viewer/page.html +25 -12
  96. package/viewer/room.html +4 -4
@@ -0,0 +1,166 @@
1
+ import { type RelayAppeal, type RelayModerationEntry, type RelayModerationPolicy, type RelaySanction, type RelayStanding } from './relay-moderation-policy';
2
+ /** Where anyone reports a link of content (the viewer's "Report"): POST, JSON of RelayReportInput. */
3
+ export declare const RELAY_REPORT_PATH = "/v1/report";
4
+ /** Where the operator of the relay reads the reports and blocks: `authorization: Bearer <TA_ADMIN_TOKEN>`. */
5
+ export declare const RELAY_MODERATION_PATH = "/v1/moderation";
6
+ /** Why a link is reported. */
7
+ export declare const RELAY_REPORT_REASONS: readonly ['phishing', 'malware', 'sexual', 'illegal', 'harassment', 'other'];
8
+ export type RelayReportReason = (typeof RELAY_REPORT_REASONS)[number];
9
+ /** What a report names: the host and the share of the link (never its key, which stays in the fragment). */
10
+ export interface RelayReportInput {
11
+ host: string;
12
+ share: string;
13
+ reason: RelayReportReason;
14
+ note?: string;
15
+ /**
16
+ * The link itself, its key with it, when the one who reports chose to send it: the operator then sees what is
17
+ * reported, as nobody else on the relay can. Only a link of this host and share.
18
+ */
19
+ link?: string;
20
+ }
21
+ export interface RelayReport extends RelayReportInput {
22
+ /** When it was first and last reported, and how many times. */
23
+ at: number;
24
+ last: number;
25
+ count: number;
26
+ /** How many people reported it (by the addresses they came from), and of them for phishing or malware. */
27
+ people?: number;
28
+ severe?: number;
29
+ }
30
+ /** Reasons a few reports are enough for (RelayModerationPolicy.severe). */
31
+ export declare const RELAY_SEVERE_REASONS: readonly RelayReportReason[];
32
+ /** A block the relay made by itself: when, and by which rule. */
33
+ export interface RelayAutoBlock {
34
+ at: number;
35
+ rule: 'people' | 'severe' | 'host';
36
+ /** The people, or the links blocked, that made it. */
37
+ count: number;
38
+ }
39
+ /** What the operator blocked: every link of a host (shown through the domain of content), or one share. */
40
+ export interface RelayBlocks {
41
+ hosts: string[];
42
+ shares: string[];
43
+ /** Those the rules blocked, by `share:<id>` or `host:<id>`. */
44
+ auto?: Record<string, RelayAutoBlock>;
45
+ /** What the operator unblocked after the rules blocked it: never blocked by them again (`share:<id>`, `host:<id>`). */
46
+ pardoned?: string[];
47
+ }
48
+ export type RelayModerationAction = {
49
+ action: 'block' | 'unblock';
50
+ host?: string;
51
+ share?: string;
52
+ } | {
53
+ action: 'dismiss';
54
+ share: string;
55
+ } | {
56
+ action: 'policy';
57
+ policy: Partial<RelayModerationPolicy>;
58
+ } | {
59
+ action: 'limit' | 'ban';
60
+ account: string;
61
+ days?: number;
62
+ reason?: string;
63
+ } | {
64
+ action: 'lift';
65
+ account: string;
66
+ reason?: string;
67
+ } | {
68
+ action: 'answer';
69
+ account: string;
70
+ restore: boolean;
71
+ };
72
+ /** An account, as the relay checked its token. */
73
+ export interface RelayAccountWho {
74
+ id: string;
75
+ name?: string;
76
+ }
77
+ /** Who shares through a computer, once its Ta proved both (RELAY_BIND_PATH). */
78
+ interface Owner {
79
+ account: string;
80
+ name?: string;
81
+ at: number;
82
+ }
83
+ /** Internal paths, reached only from the Worker or `ta relay` once they checked the caller (RelayModerationDoor). */
84
+ export declare const RELAY_MODERATION_INTERNAL: {
85
+ readonly bind: '/bind';
86
+ readonly blocks: '/blocks';
87
+ readonly viewer: '/viewer';
88
+ readonly copy: '/copy';
89
+ readonly policy: '/policy';
90
+ };
91
+ /** Where reports and blocks are kept: the storage of one Durable Object, or of `ta relay`. */
92
+ export interface RelayModerationStorage {
93
+ get<T>(key: string): Promise<T | undefined>;
94
+ put(key: string, value: unknown): Promise<void>;
95
+ }
96
+ /** A report as it is kept: the hashes of the addresses it came from, never shown. */
97
+ interface KeptReport extends RelayReport {
98
+ from?: string[];
99
+ fromSevere?: string[];
100
+ }
101
+ /**
102
+ * Reports of links of content and what the operator blocked (docs/design/ta-link.md 2.10). The relay cannot read what is
103
+ * shared, so it can only take reports, and stop handing on what its operator blocked: the copy of a share on the relay,
104
+ * and every link of a host through the domain of content. Runs the same in a Durable Object and in `ta relay`.
105
+ */
106
+ export declare class RelayModeration {
107
+ protected readonly storage: RelayModerationStorage;
108
+ protected readonly now: () => number;
109
+ constructor(storage: RelayModerationStorage, now?: () => number);
110
+ /**
111
+ * POST RELAY_REPORT_PATH from anyone, `address` counted for its limit; GET and POST RELAY_MODERATION_PATH with
112
+ * `adminToken` (none: the operator set none, and they are not there).
113
+ */
114
+ handle(request: Request, address: string, adminToken?: string, who?: RelayAccountWho): Promise<Response>;
115
+ /** Whether the operator blocked this host or this share. */
116
+ blocked(host?: string, share?: string): Promise<boolean>;
117
+ reports(): Promise<RelayReport[]>;
118
+ protected kept(): Promise<KeptReport[]>;
119
+ blocks(): Promise<RelayBlocks>;
120
+ policy(): Promise<RelayModerationPolicy>;
121
+ sanctions(): Promise<Record<string, RelaySanction>>;
122
+ appeals(): Promise<RelayAppeal[]>;
123
+ log(): Promise<RelayModerationEntry[]>;
124
+ protected record(entry: Omit<RelayModerationEntry, 'at'>): Promise<void>;
125
+ owner(host: string): Promise<Owner | undefined>;
126
+ /** What the operator reads: the reports, blocks, sanctions, appeals, the record, and who shares through each computer reported. */
127
+ state(): Promise<{
128
+ reports: RelayReport[];
129
+ blocks: RelayBlocks;
130
+ policy: RelayModerationPolicy;
131
+ sanctions: Record<string, RelaySanction>;
132
+ appeals: RelayAppeal[];
133
+ log: RelayModerationEntry[];
134
+ owners: Record<string, Owner>;
135
+ }>;
136
+ /** How an account stands, for itself. */
137
+ standing(account: string): Promise<RelayStanding>;
138
+ protected appeal(who: RelayAccountWho, text: string): Promise<RelayStanding>;
139
+ /** The paths only the Worker or `ta relay` reach, the caller checked. */
140
+ protected internal(request: Request, url: URL, who: RelayAccountWho | undefined): Promise<Response | undefined>;
141
+ /** A computer shares through this account from now on: its reports count for it. */
142
+ bind(host: string, who: RelayAccountWho): Promise<void>;
143
+ /**
144
+ * Why a link of this computer does not open: blocked by the operator or the rules; and in a browser (the pages of the
145
+ * relay, `browser`), shared by no account where the policy needs one, or by one limited or banned. `who`: the account
146
+ * a copy is put by, in place of the owner of the computer.
147
+ */
148
+ viewer(host: string, browser: boolean, who?: RelayAccountWho): Promise<number | undefined>;
149
+ apply(action: RelayModerationAction | undefined): Promise<RelayBlocks>;
150
+ /** Limits, bans, or lifts what an account may do; answers its appeal. What the operator lifts of the rules' they leave be. */
151
+ protected sanction(action: Extract<RelayModerationAction, {
152
+ account: string;
153
+ }>): Promise<void>;
154
+ /** What the rules block after a report of this link: the link, then perhaps its computer. */
155
+ protected enforce(report: KeptReport, reports: readonly KeptReport[]): Promise<void>;
156
+ protected report(request: Request, address: string): Promise<Response>;
157
+ static parse(value: unknown): RelayReportInput | undefined;
158
+ /** A link of content of this host and share, as sent with a report; undefined for anything else. */
159
+ static linkOf(value: unknown, host: string, share: string): string | undefined;
160
+ static answer(status: number, body: unknown): Response;
161
+ /** Compares by their SHA-256, so that the time it takes says nothing of the token. */
162
+ static same(given: string, expected: string): Promise<boolean>;
163
+ static digest(text: string): Promise<string>;
164
+ }
165
+ export {};
166
+ //# sourceMappingURL=relay-moderation.d.ts.map
@@ -0,0 +1,468 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RelayModeration = exports.RELAY_MODERATION_INTERNAL = exports.RELAY_SEVERE_REASONS = exports.RELAY_REPORT_REASONS = exports.RELAY_MODERATION_PATH = exports.RELAY_REPORT_PATH = void 0;
4
+ const relay_bytes_1 = require("./relay-bytes");
5
+ const relay_content_1 = require("./relay-content");
6
+ const relay_moderation_policy_1 = require("./relay-moderation-policy");
7
+ const relay_protocol_1 = require("./relay-protocol");
8
+ /** Where anyone reports a link of content (the viewer's "Report"): POST, JSON of RelayReportInput. */
9
+ exports.RELAY_REPORT_PATH = '/v1/report';
10
+ /** Where the operator of the relay reads the reports and blocks: `authorization: Bearer <TA_ADMIN_TOKEN>`. */
11
+ exports.RELAY_MODERATION_PATH = '/v1/moderation';
12
+ /** Why a link is reported. */
13
+ exports.RELAY_REPORT_REASONS = ['phishing', 'malware', 'sexual', 'illegal', 'harassment', 'other'];
14
+ /** Reasons a few reports are enough for (RelayModerationPolicy.severe). */
15
+ exports.RELAY_SEVERE_REASONS = ['phishing', 'malware'];
16
+ /** Internal paths, reached only from the Worker or `ta relay` once they checked the caller (RelayModerationDoor). */
17
+ exports.RELAY_MODERATION_INTERNAL = { bind: '/bind', blocks: '/blocks', viewer: '/viewer', copy: '/copy', policy: '/policy' };
18
+ const HOUR_MS = 60 * 60 * 1000;
19
+ const DAY_MS = 24 * HOUR_MS;
20
+ const MAX_REPORTS = 500;
21
+ const REPORT_DAYS = 90;
22
+ const MAX_TRIES = 10;
23
+ const MAX_NOTE = 500;
24
+ const MAX_BLOCKS = 5000;
25
+ /** The addresses kept of the people who reported a link, hashed: enough to count them for the rules. */
26
+ const MAX_FROM = 32;
27
+ const MAX_LOG = 500;
28
+ const MAX_APPEALS = 200;
29
+ const MAX_HOSTS = 50;
30
+ const JSON_HEADERS = { 'content-type': 'application/json', 'cache-control': 'no-store' };
31
+ /**
32
+ * Reports of links of content and what the operator blocked (docs/design/ta-link.md 2.10). The relay cannot read what is
33
+ * shared, so it can only take reports, and stop handing on what its operator blocked: the copy of a share on the relay,
34
+ * and every link of a host through the domain of content. Runs the same in a Durable Object and in `ta relay`.
35
+ */
36
+ class RelayModeration {
37
+ constructor(storage, now = Date.now) {
38
+ this.storage = storage;
39
+ this.now = now;
40
+ }
41
+ /**
42
+ * POST RELAY_REPORT_PATH from anyone, `address` counted for its limit; GET and POST RELAY_MODERATION_PATH with
43
+ * `adminToken` (none: the operator set none, and they are not there).
44
+ */
45
+ async handle(request, address, adminToken, who) {
46
+ var _a, _b;
47
+ const url = new URL(request.url);
48
+ const { pathname } = url;
49
+ const internal = await this.internal(request, url, who);
50
+ if (internal) {
51
+ return internal;
52
+ }
53
+ if (pathname === relay_moderation_policy_1.RELAY_STANDING_PATH || pathname === relay_moderation_policy_1.RELAY_APPEAL_PATH) {
54
+ if (!who) {
55
+ return RelayModeration.answer(401, { error: 'Sign in first.' });
56
+ }
57
+ if (pathname === relay_moderation_policy_1.RELAY_STANDING_PATH) {
58
+ return RelayModeration.answer(200, await this.standing(who.id));
59
+ }
60
+ const text = String((_a = (await request.json().catch(() => ({}))).text) !== null && _a !== void 0 ? _a : '')
61
+ .trim()
62
+ .slice(0, MAX_NOTE);
63
+ return text ? RelayModeration.answer(200, await this.appeal(who, text)) : RelayModeration.answer(400, { error: 'Say why, in a few words.' });
64
+ }
65
+ if (pathname === exports.RELAY_REPORT_PATH) {
66
+ return request.method === 'POST' ? this.report(request, address) : RelayModeration.answer(405, { error: 'Not allowed.' });
67
+ }
68
+ if (pathname !== exports.RELAY_MODERATION_PATH || !adminToken) {
69
+ return RelayModeration.answer(404, { error: 'Not found.' });
70
+ }
71
+ if (!(await RelayModeration.same((_b = request.headers.get('authorization')) !== null && _b !== void 0 ? _b : '', `Bearer ${adminToken}`))) {
72
+ return RelayModeration.answer(401, { error: 'Not the operator.' });
73
+ }
74
+ if (request.method === 'GET') {
75
+ return RelayModeration.answer(200, await this.state());
76
+ }
77
+ if (request.method !== 'POST') {
78
+ return RelayModeration.answer(405, { error: 'Not allowed.' });
79
+ }
80
+ const action = (await request.json().catch(() => undefined));
81
+ try {
82
+ await this.apply(action);
83
+ return RelayModeration.answer(200, await this.state());
84
+ }
85
+ catch (error) {
86
+ return RelayModeration.answer(400, { error: error.message });
87
+ }
88
+ }
89
+ /** Whether the operator blocked this host or this share. */
90
+ async blocked(host, share) {
91
+ const blocks = await this.blocks();
92
+ return (!!host && blocks.hosts.includes(host)) || (!!share && blocks.shares.includes(share));
93
+ }
94
+ async reports() {
95
+ return (await this.kept()).map(({ from: _from, fromSevere: _severe, ...report }) => report);
96
+ }
97
+ async kept() {
98
+ var _a;
99
+ const since = this.now() - REPORT_DAYS * DAY_MS;
100
+ return ((_a = (await this.storage.get('reports'))) !== null && _a !== void 0 ? _a : []).filter(report => report.last >= since);
101
+ }
102
+ async blocks() {
103
+ var _a, _b, _c, _d;
104
+ const blocks = await this.storage.get('blocks');
105
+ return { hosts: (_a = blocks === null || blocks === void 0 ? void 0 : blocks.hosts) !== null && _a !== void 0 ? _a : [], shares: (_b = blocks === null || blocks === void 0 ? void 0 : blocks.shares) !== null && _b !== void 0 ? _b : [], auto: (_c = blocks === null || blocks === void 0 ? void 0 : blocks.auto) !== null && _c !== void 0 ? _c : {}, pardoned: (_d = blocks === null || blocks === void 0 ? void 0 : blocks.pardoned) !== null && _d !== void 0 ? _d : [] };
106
+ }
107
+ async policy() {
108
+ return relay_moderation_policy_1.RelayModerationPolicyUtil.of(await this.storage.get('policy'));
109
+ }
110
+ async sanctions() {
111
+ var _a;
112
+ const now = this.now();
113
+ const kept = (_a = (await this.storage.get('sanctions'))) !== null && _a !== void 0 ? _a : {};
114
+ return Object.fromEntries(Object.entries(kept).filter(([, sanction]) => relay_moderation_policy_1.RelayModerationPolicyUtil.active(sanction, now)));
115
+ }
116
+ async appeals() {
117
+ var _a;
118
+ return (_a = (await this.storage.get('appeals'))) !== null && _a !== void 0 ? _a : [];
119
+ }
120
+ async log() {
121
+ var _a;
122
+ return (_a = (await this.storage.get('log'))) !== null && _a !== void 0 ? _a : [];
123
+ }
124
+ async record(entry) {
125
+ await this.storage.put('log', [{ ...entry, at: this.now() }, ...(await this.log())].slice(0, MAX_LOG));
126
+ }
127
+ async owner(host) {
128
+ return this.storage.get(`owner:${host}`);
129
+ }
130
+ /** What the operator reads: the reports, blocks, sanctions, appeals, the record, and who shares through each computer reported. */
131
+ async state() {
132
+ const reports = await this.reports();
133
+ const owners = {};
134
+ for (const host of new Set(reports.map(report => report.host))) {
135
+ const owner = await this.owner(host);
136
+ if (owner) {
137
+ owners[host] = owner;
138
+ }
139
+ }
140
+ return {
141
+ reports,
142
+ blocks: await this.blocks(),
143
+ policy: await this.policy(),
144
+ sanctions: await this.sanctions(),
145
+ appeals: await this.appeals(),
146
+ log: (await this.log()).slice(0, 100),
147
+ owners,
148
+ };
149
+ }
150
+ /** How an account stands, for itself. */
151
+ async standing(account) {
152
+ var _a;
153
+ const sanction = (await this.sanctions())[account];
154
+ const hosts = (_a = (await this.storage.get(`hosts:${account}`))) !== null && _a !== void 0 ? _a : [];
155
+ const blocks = await this.blocks();
156
+ const blocked = (await this.kept()).filter(report => hosts.includes(report.host) && blocks.shares.includes(report.share)).map(report => report.share);
157
+ const appeal = (await this.appeals()).find(each => each.account === account);
158
+ return { ...(sanction ? { sanction } : {}), blocked, ...(appeal ? { appeal } : {}) };
159
+ }
160
+ async appeal(who, text) {
161
+ const others = (await this.appeals()).filter(each => each.account !== who.id);
162
+ await this.storage.put('appeals', [{ account: who.id, ...(who.name ? { name: who.name } : {}), at: this.now(), text }, ...others].slice(0, MAX_APPEALS));
163
+ await this.record({ by: 'user', action: 'appeal', target: `account:${who.id}`, reason: text.slice(0, 120) });
164
+ return this.standing(who.id);
165
+ }
166
+ /** The paths only the Worker or `ta relay` reach, the caller checked. */
167
+ async internal(request, url, who) {
168
+ var _a, _b, _c;
169
+ const paths = exports.RELAY_MODERATION_INTERNAL;
170
+ switch (url.pathname) {
171
+ case paths.blocks:
172
+ return RelayModeration.answer(200, await this.blocks());
173
+ case paths.policy:
174
+ return RelayModeration.answer(200, await this.policy());
175
+ case paths.viewer:
176
+ return RelayModeration.answer(200, { code: await this.viewer((_a = url.searchParams.get('host')) !== null && _a !== void 0 ? _a : '', url.searchParams.get('browser') === '1') });
177
+ case paths.bind: {
178
+ const host = String((_b = (await request.json().catch(() => ({}))).host) !== null && _b !== void 0 ? _b : '');
179
+ if (!who || !relay_protocol_1.RELAY_ID.test(host)) {
180
+ return RelayModeration.answer(400, { error: 'Bind a computer to an account.' });
181
+ }
182
+ await this.bind(host, who);
183
+ return RelayModeration.answer(200, await this.standing(who.id));
184
+ }
185
+ case paths.copy: {
186
+ const code = await this.viewer((_c = url.searchParams.get('host')) !== null && _c !== void 0 ? _c : '', true, who);
187
+ return code ? RelayModeration.answer(403, { code }) : RelayModeration.answer(200, {});
188
+ }
189
+ default:
190
+ return undefined;
191
+ }
192
+ }
193
+ /** A computer shares through this account from now on: its reports count for it. */
194
+ async bind(host, who) {
195
+ var _a, _b;
196
+ const before = await this.owner(host);
197
+ if (before && before.account !== who.id) {
198
+ const rest = ((_a = (await this.storage.get(`hosts:${before.account}`))) !== null && _a !== void 0 ? _a : []).filter(each => each !== host);
199
+ await this.storage.put(`hosts:${before.account}`, rest);
200
+ }
201
+ await this.storage.put(`owner:${host}`, { account: who.id, ...(who.name ? { name: who.name } : {}), at: this.now() });
202
+ const hosts = (_b = (await this.storage.get(`hosts:${who.id}`))) !== null && _b !== void 0 ? _b : [];
203
+ if (!hosts.includes(host)) {
204
+ await this.storage.put(`hosts:${who.id}`, [...hosts, host].slice(-MAX_HOSTS));
205
+ }
206
+ }
207
+ /**
208
+ * Why a link of this computer does not open: blocked by the operator or the rules; and in a browser (the pages of the
209
+ * relay, `browser`), shared by no account where the policy needs one, or by one limited or banned. `who`: the account
210
+ * a copy is put by, in place of the owner of the computer.
211
+ */
212
+ async viewer(host, browser, who) {
213
+ var _a;
214
+ var _b;
215
+ if ((await this.blocks()).hosts.includes(host)) {
216
+ return relay_protocol_1.RelayCloseCode.BLOCKED;
217
+ }
218
+ if (!browser) {
219
+ return undefined;
220
+ }
221
+ const policy = await this.policy();
222
+ const account = (_b = who === null || who === void 0 ? void 0 : who.id) !== null && _b !== void 0 ? _b : (_a = (await this.owner(host))) === null || _a === void 0 ? void 0 : _a.account;
223
+ if (!account) {
224
+ return policy.needsAccount.includes('share') ? relay_protocol_1.RelayCloseCode.SIGN_IN : undefined;
225
+ }
226
+ return relay_moderation_policy_1.RelayModerationPolicyUtil.takes((await this.sanctions())[account], 'share', policy, this.now()) ? relay_protocol_1.RelayCloseCode.BLOCKED : undefined;
227
+ }
228
+ async apply(action) {
229
+ var _a, _b;
230
+ const ids = (value) => (typeof value === 'string' && relay_protocol_1.RELAY_ID.test(value) ? value : undefined);
231
+ const host = ids(action === null || action === void 0 ? void 0 : action.host);
232
+ const share = ids(action === null || action === void 0 ? void 0 : action.share);
233
+ if ((action === null || action === void 0 ? void 0 : action.action) === 'policy') {
234
+ await this.storage.put('policy', relay_moderation_policy_1.RelayModerationPolicyUtil.of({ ...(await this.policy()), ...((_a = action.policy) !== null && _a !== void 0 ? _a : {}) }));
235
+ await this.record({ by: 'operator', action: 'policy', target: 'policy' });
236
+ return this.blocks();
237
+ }
238
+ if ((action === null || action === void 0 ? void 0 : action.action) === 'limit' || (action === null || action === void 0 ? void 0 : action.action) === 'ban' || (action === null || action === void 0 ? void 0 : action.action) === 'lift' || (action === null || action === void 0 ? void 0 : action.action) === 'answer') {
239
+ await this.sanction(action);
240
+ return this.blocks();
241
+ }
242
+ if ((action === null || action === void 0 ? void 0 : action.action) === 'dismiss') {
243
+ if (!share) {
244
+ throw new Error('Dismiss the report of a share.');
245
+ }
246
+ await this.storage.put('reports', (await this.kept()).filter(report => report.share !== share));
247
+ await this.record({ by: 'operator', action: 'dismiss', target: `share:${share}` });
248
+ return this.blocks();
249
+ }
250
+ if (((action === null || action === void 0 ? void 0 : action.action) !== 'block' && (action === null || action === void 0 ? void 0 : action.action) !== 'unblock') || (!host && !share)) {
251
+ throw new Error('Block or unblock a host or a share: { "action": "block", "host": "…" }.');
252
+ }
253
+ const blocks = await this.blocks();
254
+ const set = (list, id) => {
255
+ const rest = list.filter(each => each !== id);
256
+ return id && action.action === 'block' ? [...rest, id].slice(-MAX_BLOCKS) : rest;
257
+ };
258
+ const keys = [...(host ? [`host:${host}`] : []), ...(share ? [`share:${share}`] : [])];
259
+ const auto = { ...blocks.auto };
260
+ // What the operator unblocks of what the rules blocked, they leave be from then on; what the operator blocks is theirs.
261
+ const pardon = action.action === 'unblock' ? keys.filter(key => auto[key]) : [];
262
+ for (const key of keys) {
263
+ delete auto[key];
264
+ }
265
+ const pardoned = [...((_b = blocks.pardoned) !== null && _b !== void 0 ? _b : []).filter(key => action.action === 'unblock' || !keys.includes(key)), ...pardon].slice(-MAX_BLOCKS);
266
+ const next = { hosts: set(blocks.hosts, host), shares: set(blocks.shares, share), auto, pardoned: [...new Set(pardoned)] };
267
+ await this.storage.put('blocks', next);
268
+ for (const key of keys) {
269
+ await this.record({ by: 'operator', action: action.action, target: key });
270
+ }
271
+ return next;
272
+ }
273
+ /** Limits, bans, or lifts what an account may do; answers its appeal. What the operator lifts of the rules' they leave be. */
274
+ async sanction(action) {
275
+ var _a;
276
+ var _b, _c, _d, _e;
277
+ const account = typeof action.account === 'string' && action.account && action.account.length <= 200 ? action.account : '';
278
+ if (!account) {
279
+ throw new Error('Name the account.');
280
+ }
281
+ const kept = (_b = (await this.storage.get('sanctions'))) !== null && _b !== void 0 ? _b : {};
282
+ const before = kept[account];
283
+ const appeals = await this.appeals();
284
+ const name = (_c = before === null || before === void 0 ? void 0 : before.name) !== null && _c !== void 0 ? _c : (_a = appeals.find(each => each.account === account)) === null || _a === void 0 ? void 0 : _a.name;
285
+ if (action.action === 'answer') {
286
+ await this.storage.put('appeals', appeals.filter(each => each.account !== account));
287
+ if (action.restore) {
288
+ return this.sanction({ action: 'lift', account, reason: 'appeal' });
289
+ }
290
+ await this.record({ by: 'operator', action: 'keep', target: `account:${account}` });
291
+ return;
292
+ }
293
+ if (action.action === 'lift') {
294
+ delete kept[account];
295
+ await this.storage.put('sanctions', kept);
296
+ if ((before === null || before === void 0 ? void 0 : before.by) === 'rule') {
297
+ const blocks = await this.blocks();
298
+ await this.storage.put('blocks', { ...blocks, pardoned: [...new Set([...((_d = blocks.pardoned) !== null && _d !== void 0 ? _d : []), `account:${account}`])] });
299
+ }
300
+ await this.record({ by: 'operator', action: 'lift', target: `account:${account}`, ...(action.reason ? { reason: action.reason } : {}) });
301
+ return;
302
+ }
303
+ const days = Number(action.days);
304
+ const now = this.now();
305
+ kept[account] = {
306
+ account,
307
+ ...(name ? { name } : {}),
308
+ level: action.action,
309
+ at: now,
310
+ ...(days > 0 ? { until: now + Math.min(days, 3650) * DAY_MS } : {}),
311
+ by: 'operator',
312
+ reason: String((_e = action.reason) !== null && _e !== void 0 ? _e : '').slice(0, 200),
313
+ };
314
+ await this.storage.put('sanctions', kept);
315
+ await this.record({
316
+ by: 'operator',
317
+ action: action.action,
318
+ target: `account:${account}`,
319
+ ...(action.reason ? { reason: String(action.reason).slice(0, 120) } : {}),
320
+ });
321
+ }
322
+ /** What the rules block after a report of this link: the link, then perhaps its computer. */
323
+ async enforce(report, reports) {
324
+ var _a, _b, _c, _d;
325
+ const rules = await this.policy();
326
+ if (!rules.auto) {
327
+ return;
328
+ }
329
+ const blocks = await this.blocks();
330
+ const auto = { ...blocks.auto };
331
+ const pardoned = new Set(blocks.pardoned);
332
+ const now = this.now();
333
+ let changed = false;
334
+ const shareKey = `share:${report.share}`;
335
+ if (!blocks.shares.includes(report.share) && !blocks.hosts.includes(report.host) && !pardoned.has(shareKey)) {
336
+ const severe = (_a = report.severe) !== null && _a !== void 0 ? _a : 0;
337
+ const people = (_b = report.people) !== null && _b !== void 0 ? _b : 0;
338
+ const rule = severe >= rules.severe ? 'severe' : people >= rules.people ? 'people' : undefined;
339
+ if (rule) {
340
+ blocks.shares = [...blocks.shares, report.share].slice(-MAX_BLOCKS);
341
+ auto[shareKey] = { at: now, rule, count: rule === 'severe' ? severe : people };
342
+ changed = true;
343
+ }
344
+ }
345
+ const owner = await this.owner(report.host);
346
+ if (owner) {
347
+ // Of an account: the rules limit the person, for policy.limitDays; the operator alone bans.
348
+ const hosts = (_c = (await this.storage.get(`hosts:${owner.account}`))) !== null && _c !== void 0 ? _c : [report.host];
349
+ const shares = new Set(reports.filter(each => hosts.includes(each.host)).map(each => each.share));
350
+ const stopped = blocks.shares.filter(id => shares.has(id)).length;
351
+ const sanctions = (_d = (await this.storage.get('sanctions'))) !== null && _d !== void 0 ? _d : {};
352
+ if (rules.hostAfter > 0 &&
353
+ stopped >= rules.hostAfter &&
354
+ !pardoned.has(`account:${owner.account}`) &&
355
+ !relay_moderation_policy_1.RelayModerationPolicyUtil.active(sanctions[owner.account], now)) {
356
+ sanctions[owner.account] = {
357
+ account: owner.account,
358
+ ...(owner.name ? { name: owner.name } : {}),
359
+ level: 'limit',
360
+ at: now,
361
+ until: now + rules.limitDays * DAY_MS,
362
+ by: 'rule',
363
+ reason: `${stopped} links stopped`,
364
+ };
365
+ await this.storage.put('sanctions', sanctions);
366
+ await this.record({ by: 'rule', action: 'limit', target: `account:${owner.account}`, reason: `${stopped} links stopped` });
367
+ }
368
+ }
369
+ const hostKey = `host:${report.host}`;
370
+ if (!owner && rules.hostAfter > 0 && !blocks.hosts.includes(report.host) && !pardoned.has(hostKey)) {
371
+ const shares = new Set(reports.filter(each => each.host === report.host).map(each => each.share));
372
+ const blocked = blocks.shares.filter(id => shares.has(id)).length;
373
+ if (blocked >= rules.hostAfter) {
374
+ blocks.hosts = [...blocks.hosts, report.host].slice(-MAX_BLOCKS);
375
+ auto[hostKey] = { at: now, rule: 'host', count: blocked };
376
+ changed = true;
377
+ }
378
+ }
379
+ if (changed) {
380
+ await this.storage.put('blocks', { ...blocks, auto });
381
+ for (const [key, made] of Object.entries(auto)) {
382
+ if (made.at === now) {
383
+ await this.record({ by: 'rule', action: 'block', target: key, reason: made.rule });
384
+ }
385
+ }
386
+ }
387
+ }
388
+ async report(request, address) {
389
+ const input = RelayModeration.parse(await request.json().catch(() => undefined));
390
+ if (!input) {
391
+ return RelayModeration.answer(400, { error: 'Report a link of content: its host, its share and why.' });
392
+ }
393
+ const now = this.now();
394
+ const key = `tries:${address}`;
395
+ const before = await this.storage.get(key);
396
+ const tries = before && now - before.since < HOUR_MS ? before : { count: 0, since: now };
397
+ if (tries.count >= MAX_TRIES) {
398
+ return RelayModeration.answer(429, { error: 'Too many reports: try again later.' });
399
+ }
400
+ await this.storage.put(key, { ...tries, count: tries.count + 1 });
401
+ const reports = await this.kept();
402
+ const who = (await RelayModeration.digest(`ta-report:${address}`)).slice(0, 16);
403
+ const severe = exports.RELAY_SEVERE_REASONS.includes(input.reason);
404
+ const same = reports.find(report => report.share === input.share && report.host === input.host);
405
+ const counted = (list, add) => (add && !(list === null || list === void 0 ? void 0 : list.includes(who)) ? [...(list !== null && list !== void 0 ? list : []), who].slice(-MAX_FROM) : (list !== null && list !== void 0 ? list : []));
406
+ if (same) {
407
+ same.count++;
408
+ same.last = now;
409
+ same.reason = input.reason;
410
+ if (input.note) {
411
+ same.note = input.note;
412
+ }
413
+ if (input.link) {
414
+ same.link = input.link;
415
+ }
416
+ }
417
+ const report = same !== null && same !== void 0 ? same : { ...input, at: now, last: now, count: 1 };
418
+ if (!same) {
419
+ reports.push(report);
420
+ }
421
+ report.from = counted(report.from, true);
422
+ report.fromSevere = counted(report.fromSevere, severe);
423
+ report.people = report.from.length;
424
+ report.severe = report.fromSevere.length;
425
+ await this.storage.put('reports', reports.sort((a, b) => b.last - a.last).slice(0, MAX_REPORTS));
426
+ await this.enforce(report, reports);
427
+ return new Response(null, { status: 204 });
428
+ }
429
+ static parse(value) {
430
+ const given = value;
431
+ if (!given ||
432
+ typeof given.host !== 'string' ||
433
+ typeof given.share !== 'string' ||
434
+ !relay_protocol_1.RELAY_ID.test(given.host) ||
435
+ !relay_protocol_1.RELAY_ID.test(given.share) ||
436
+ !exports.RELAY_REPORT_REASONS.includes(given.reason)) {
437
+ return undefined;
438
+ }
439
+ const note = typeof given.note === 'string' ? given.note.trim().slice(0, MAX_NOTE) : '';
440
+ const link = RelayModeration.linkOf(given.link, given.host, given.share);
441
+ return { host: given.host, share: given.share, reason: given.reason, ...(note ? { note } : {}), ...(link ? { link } : {}) };
442
+ }
443
+ /** A link of content of this host and share, as sent with a report; undefined for anything else. */
444
+ static linkOf(value, host, share) {
445
+ if (typeof value !== 'string' || value.length > 2048) {
446
+ return undefined;
447
+ }
448
+ try {
449
+ const link = relay_content_1.RelayContentUtil.parse(value);
450
+ return link.host === host && link.share === share && link.access !== 'self' && link.access !== 'people' ? value.trim() : undefined;
451
+ }
452
+ catch (_a) {
453
+ return undefined;
454
+ }
455
+ }
456
+ static answer(status, body) {
457
+ return new Response(JSON.stringify(body), { status, headers: JSON_HEADERS });
458
+ }
459
+ /** Compares by their SHA-256, so that the time it takes says nothing of the token. */
460
+ static async same(given, expected) {
461
+ return (await RelayModeration.digest(given)) === (await RelayModeration.digest(expected));
462
+ }
463
+ static async digest(text) {
464
+ return relay_bytes_1.RelayBytes.toBase64(new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))));
465
+ }
466
+ }
467
+ exports.RelayModeration = RelayModeration;
468
+ //# sourceMappingURL=relay-moderation.js.map
@@ -116,7 +116,11 @@ export declare enum RelayCloseCode {
116
116
  /** Too many devices are connected to this host. */
117
117
  FULL = 4429,
118
118
  /** No answer in time: to the hello, or to the pings of the heartbeat; the connection is gone without a word. */
119
- TIMEOUT = 4408
119
+ TIMEOUT = 4408,
120
+ /** The operator of the relay blocked what is shared by this host or link (RelayModeration). */
121
+ BLOCKED = 4451,
122
+ /** Where the operator needs it, links open in a browser only of one who signed in to an account (RelayModerationPolicy.needsAccount). */
123
+ SIGN_IN = 4452
120
124
  }
121
125
  /**
122
126
  * The heartbeat: hosts and devices send `ping` to the relay every so often, outside the channels, and it
@@ -93,6 +93,10 @@ var RelayCloseCode;
93
93
  RelayCloseCode[RelayCloseCode["FULL"] = 4429] = "FULL";
94
94
  /** No answer in time: to the hello, or to the pings of the heartbeat; the connection is gone without a word. */
95
95
  RelayCloseCode[RelayCloseCode["TIMEOUT"] = 4408] = "TIMEOUT";
96
+ /** The operator of the relay blocked what is shared by this host or link (RelayModeration). */
97
+ RelayCloseCode[RelayCloseCode["BLOCKED"] = 4451] = "BLOCKED";
98
+ /** Where the operator needs it, links open in a browser only of one who signed in to an account (RelayModerationPolicy.needsAccount). */
99
+ RelayCloseCode[RelayCloseCode["SIGN_IN"] = 4452] = "SIGN_IN";
96
100
  })(RelayCloseCode || (exports.RelayCloseCode = RelayCloseCode = {}));
97
101
  /**
98
102
  * The heartbeat: hosts and devices send `ping` to the relay every so often, outside the channels, and it