@celljs/ta-relay 4.11.0 → 4.13.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 (86) hide show
  1. package/README.en.md +26 -1
  2. package/README.md +26 -1
  3. package/esm/common/index.d.ts +5 -0
  4. package/esm/common/index.js +5 -0
  5. package/esm/common/relay-faces.d.ts +32 -0
  6. package/esm/common/relay-faces.js +208 -0
  7. package/esm/common/relay-friends.d.ts +154 -0
  8. package/esm/common/relay-friends.js +482 -0
  9. package/esm/common/relay-hub-util.d.ts +9 -0
  10. package/esm/common/relay-hub-util.js +19 -2
  11. package/esm/common/relay-hubs-connection.d.ts +110 -0
  12. package/esm/common/relay-hubs-connection.js +508 -0
  13. package/esm/common/relay-hubs-protocol.d.ts +174 -0
  14. package/esm/common/relay-hubs-protocol.js +2 -0
  15. package/esm/common/relay-hubs.d.ts +68 -216
  16. package/esm/common/relay-hubs.js +303 -507
  17. package/esm/common/relay-identity.d.ts +2 -0
  18. package/esm/common/relay-info.d.ts +44 -0
  19. package/esm/common/relay-info.js +94 -0
  20. package/esm/common/relay-protocol.d.ts +7 -3
  21. package/esm/common/relay-protocol.js +7 -3
  22. package/esm/common/relay-room-chat.d.ts +36 -2
  23. package/esm/common/relay-room-chat.js +32 -7
  24. package/esm/common/relay-spot.d.ts +122 -0
  25. package/esm/common/relay-spot.js +179 -0
  26. package/esm/guest/guest-i18n.d.ts +5 -0
  27. package/esm/guest/guest-i18n.js +10 -0
  28. package/esm/guest/guest-style.d.ts +1 -1
  29. package/esm/guest/guest-style.js +11 -4
  30. package/esm/guest/guest.js +39 -18
  31. package/esm/node/index.d.ts +2 -0
  32. package/esm/node/index.js +2 -0
  33. package/esm/node/relay-file-storage.d.ts +32 -0
  34. package/esm/node/relay-file-storage.js +101 -0
  35. package/esm/node/relay-host.d.ts +63 -28
  36. package/esm/node/relay-host.js +145 -52
  37. package/esm/node/relay-hub-files.d.ts +1 -1
  38. package/esm/node/relay-server.d.ts +37 -3
  39. package/esm/node/relay-server.js +193 -37
  40. package/esm/node/relay-store.d.ts +34 -6
  41. package/esm/node/relay-store.js +54 -22
  42. package/esm/node/relays-file.d.ts +139 -0
  43. package/esm/node/relays-file.js +373 -0
  44. package/lib/common/index.d.ts +5 -0
  45. package/lib/common/index.js +5 -0
  46. package/lib/common/relay-faces.d.ts +33 -0
  47. package/lib/common/relay-faces.js +211 -0
  48. package/lib/common/relay-friends.d.ts +155 -0
  49. package/lib/common/relay-friends.js +486 -0
  50. package/lib/common/relay-hub-util.d.ts +9 -0
  51. package/lib/common/relay-hub-util.js +19 -2
  52. package/lib/common/relay-hubs-connection.d.ts +111 -0
  53. package/lib/common/relay-hubs-connection.js +513 -0
  54. package/lib/common/relay-hubs-protocol.d.ts +175 -0
  55. package/lib/common/relay-hubs-protocol.js +3 -0
  56. package/lib/common/relay-hubs.d.ts +68 -216
  57. package/lib/common/relay-hubs.js +311 -515
  58. package/lib/common/relay-identity.d.ts +2 -0
  59. package/lib/common/relay-info.d.ts +45 -0
  60. package/lib/common/relay-info.js +97 -0
  61. package/lib/common/relay-protocol.d.ts +7 -3
  62. package/lib/common/relay-protocol.js +8 -4
  63. package/lib/common/relay-room-chat.d.ts +36 -2
  64. package/lib/common/relay-room-chat.js +32 -7
  65. package/lib/common/relay-spot.d.ts +123 -0
  66. package/lib/common/relay-spot.js +183 -0
  67. package/lib/guest/guest-i18n.d.ts +5 -0
  68. package/lib/guest/guest-i18n.js +10 -0
  69. package/lib/guest/guest-style.d.ts +1 -1
  70. package/lib/guest/guest-style.js +11 -4
  71. package/lib/guest/guest.js +39 -18
  72. package/lib/node/index.d.ts +2 -0
  73. package/lib/node/index.js +2 -0
  74. package/lib/node/relay-file-storage.d.ts +33 -0
  75. package/lib/node/relay-file-storage.js +105 -0
  76. package/lib/node/relay-host.d.ts +63 -28
  77. package/lib/node/relay-host.js +146 -53
  78. package/lib/node/relay-hub-files.d.ts +1 -1
  79. package/lib/node/relay-server.d.ts +37 -3
  80. package/lib/node/relay-server.js +193 -37
  81. package/lib/node/relay-store.d.ts +34 -6
  82. package/lib/node/relay-store.js +54 -22
  83. package/lib/node/relays-file.d.ts +140 -0
  84. package/lib/node/relays-file.js +378 -0
  85. package/package.json +2 -2
  86. package/viewer/room.html +21 -14
@@ -13,6 +13,8 @@ export interface RelayIdentity extends RelayPublicIdentity {
13
13
  signKey: JsonWebKey;
14
14
  boxKey: JsonWebKey;
15
15
  createdAt: number;
16
+ /** The user's other computers are this Ta too: who answers in a room is agreed first (docs/design/ta-sync.md 9). */
17
+ shared?: true;
16
18
  }
17
19
  /** Keys, sealing and signatures of rooms and identities, with WebCrypto only: the same in ta serve, a browser and a Worker. */
18
20
  export declare namespace RelayKeys {
@@ -0,0 +1,44 @@
1
+ /** What a relay says of itself (docs/design/ta-relays.md 3.1): GET RELAY_INFO_PATH. */
2
+ export declare const RELAY_INFO_PATH = "/v1/info";
3
+ /** What a relay can do: forward to a host, hold rooms, keep sealed copies, serve the pages of links. */
4
+ export type RelayCapability = 'tunnel' | 'hub' | 'store' | 'pages';
5
+ export interface RelayLimits {
6
+ hubMembers: number;
7
+ /** Characters of a sealed message or value of a room. */
8
+ hubValueBytes: number;
9
+ hubKeys: number;
10
+ hubStateBytes: number;
11
+ hubIdleDays: number;
12
+ /** Bytes of a sealed copy, and its days at most. */
13
+ storeValueBytes: number;
14
+ storeDays: number;
15
+ }
16
+ export interface RelayInfo {
17
+ v: 1;
18
+ capabilities: RelayCapability[];
19
+ limits: RelayLimits;
20
+ /** Whether rooms and copies stay when the relay restarts. */
21
+ persistent: boolean;
22
+ }
23
+ /** A relay that answers no RELAY_INFO_PATH, made before it: all it can do, with the limits of then. */
24
+ export declare const RELAY_LEGACY_INFO: RelayInfo;
25
+ /** What a probe of a relay found. */
26
+ export interface RelayProbe {
27
+ online: boolean;
28
+ info?: RelayInfo;
29
+ /** It answers, but not RELAY_INFO_PATH: one made before it. */
30
+ legacy?: boolean;
31
+ /** Milliseconds to its answer. */
32
+ ms?: number;
33
+ error?: string;
34
+ }
35
+ export declare namespace RelayInfoUtil {
36
+ function of(persistent: boolean): RelayInfo;
37
+ /** The answer of RELAY_INFO_PATH: JSON, readable by any page (it says nothing secret). */
38
+ function response(info: RelayInfo): Response;
39
+ /** The address of a relay as it is kept: http(s), its origin and path, no trailing slash. Throws on what is not one. */
40
+ function normalize(url: string): string;
41
+ /** Asks a relay what it is; never throws. */
42
+ function probe(url: string, timeoutMs?: number): Promise<RelayProbe>;
43
+ function parse(value: unknown): RelayInfo | undefined;
44
+ }
@@ -0,0 +1,94 @@
1
+ import { RELAY_BLOB_MAX_DAYS, RELAY_CONTENT_MAX_BYTES, RELAY_HUB_IDLE_DAYS, RELAY_HUB_MAX_KEYS, RELAY_HUB_MAX_MEMBERS, RELAY_HUB_MAX_STATE, RELAY_HUB_MAX_VALUE, } from './relay-protocol.js';
2
+ /** What a relay says of itself (docs/design/ta-relays.md 3.1): GET RELAY_INFO_PATH. */
3
+ export const RELAY_INFO_PATH = '/v1/info';
4
+ /** A relay that answers no RELAY_INFO_PATH, made before it: all it can do, with the limits of then. */
5
+ export const RELAY_LEGACY_INFO = {
6
+ v: 1,
7
+ capabilities: ['tunnel', 'hub', 'store', 'pages'],
8
+ limits: {
9
+ hubMembers: RELAY_HUB_MAX_MEMBERS,
10
+ hubValueBytes: RELAY_HUB_MAX_VALUE,
11
+ hubKeys: RELAY_HUB_MAX_KEYS,
12
+ hubStateBytes: RELAY_HUB_MAX_STATE,
13
+ hubIdleDays: RELAY_HUB_IDLE_DAYS,
14
+ storeValueBytes: RELAY_CONTENT_MAX_BYTES,
15
+ storeDays: RELAY_BLOB_MAX_DAYS,
16
+ },
17
+ persistent: true,
18
+ };
19
+ export var RelayInfoUtil;
20
+ (function (RelayInfoUtil) {
21
+ function of(persistent) {
22
+ return { ...RELAY_LEGACY_INFO, persistent };
23
+ }
24
+ RelayInfoUtil.of = of;
25
+ /** The answer of RELAY_INFO_PATH: JSON, readable by any page (it says nothing secret). */
26
+ function response(info) {
27
+ return new Response(JSON.stringify(info), {
28
+ headers: { 'content-type': 'application/json', 'access-control-allow-origin': '*', 'cache-control': 'no-store' },
29
+ });
30
+ }
31
+ RelayInfoUtil.response = response;
32
+ /** The address of a relay as it is kept: http(s), its origin and path, no trailing slash. Throws on what is not one. */
33
+ function normalize(url) {
34
+ const text = String(url !== null && url !== void 0 ? url : '').trim();
35
+ const parsed = new URL(text);
36
+ if (!/^https?:$/.test(parsed.protocol) || parsed.search || parsed.hash || parsed.username || parsed.password) {
37
+ throw new Error(`${text} is not the address of a relay.`);
38
+ }
39
+ return `${parsed.origin}${parsed.pathname}`.replace(/\/+$/, '');
40
+ }
41
+ RelayInfoUtil.normalize = normalize;
42
+ /** Asks a relay what it is; never throws. */
43
+ async function probe(url, timeoutMs = 6000) {
44
+ const started = Date.now();
45
+ const controller = new AbortController();
46
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
47
+ try {
48
+ const response = await fetch(`${normalize(url)}${RELAY_INFO_PATH}`, { signal: controller.signal, redirect: 'manual' });
49
+ const ms = Date.now() - started;
50
+ if (response.ok) {
51
+ const info = parse(await response.json().catch(() => undefined));
52
+ return info ? { online: true, info, ms } : { online: true, legacy: true, info: RELAY_LEGACY_INFO, ms };
53
+ }
54
+ if (response.status === 404 || response.status === 426) {
55
+ // A relay of before answers its root and nothing of this path: it is one if its root says so.
56
+ const root = await fetch(`${normalize(url)}/`, { signal: controller.signal }).then(answer => answer.text(), () => '');
57
+ return root.startsWith('Ta relay')
58
+ ? { online: true, legacy: true, info: RELAY_LEGACY_INFO, ms }
59
+ : { online: false, ms, error: `It answers, but is not a relay of Ta (${response.status}).` };
60
+ }
61
+ return { online: false, ms, error: `It answered ${response.status}.` };
62
+ }
63
+ catch (error) {
64
+ const aborted = (error === null || error === void 0 ? void 0 : error.name) === 'AbortError';
65
+ return { online: false, error: aborted ? 'No answer in time.' : (error === null || error === void 0 ? void 0 : error.message) || String(error) };
66
+ }
67
+ finally {
68
+ clearTimeout(timer);
69
+ }
70
+ }
71
+ RelayInfoUtil.probe = probe;
72
+ function parse(value) {
73
+ const info = value;
74
+ if ((info === null || info === void 0 ? void 0 : info.v) !== 1 || !Array.isArray(info.capabilities) || !info.limits || typeof info.limits !== 'object') {
75
+ return undefined;
76
+ }
77
+ const known = ['tunnel', 'hub', 'store', 'pages'];
78
+ const limits = { ...RELAY_LEGACY_INFO.limits };
79
+ for (const key of Object.keys(limits)) {
80
+ const given = info.limits[key];
81
+ if (typeof given === 'number' && given > 0) {
82
+ limits[key] = given;
83
+ }
84
+ }
85
+ return {
86
+ v: 1,
87
+ capabilities: info.capabilities.filter((capability) => known.includes(capability)),
88
+ limits,
89
+ persistent: info.persistent !== false,
90
+ };
91
+ }
92
+ RelayInfoUtil.parse = parse;
93
+ })(RelayInfoUtil || (RelayInfoUtil = {}));
94
+ //# sourceMappingURL=relay-info.js.map
@@ -166,11 +166,15 @@ export declare const RELAY_PROOF = "ta-relay ready";
166
166
  export declare const RELAY_HUB_PATH = "/v1/hub/";
167
167
  /** Links that invite into a room (RelayHubLink): Ta opens them; a browser gets the page of guests (src/guest). */
168
168
  export declare const RELAY_ROOM_PATH = "/r";
169
- /** Members of a room, its owner among them. */
170
- export declare const RELAY_HUB_MAX_MEMBERS = 16;
169
+ /** Members of a hub at most, its owner among them: a room of friends (its owner and RELAY_FRIENDS_MAX friends). */
170
+ export declare const RELAY_HUB_MAX_MEMBERS = 101;
171
+ /** Members of a room the user made, its owner among them: the owner's Ta lets in no more (RelayHubs.answer). */
172
+ export declare const RELAY_ROOM_MAX_MEMBERS = 16;
173
+ /** Friends of a Ta at most: the members of its room of friends (docs/design/ta-link.md 3.1). */
174
+ export declare const RELAY_FRIENDS_MAX = 100;
171
175
  /** Characters of a sealed message or value of the state. */
172
176
  export declare const RELAY_HUB_MAX_VALUE: number;
173
- export declare const RELAY_HUB_MAX_KEYS = 512;
177
+ export declare const RELAY_HUB_MAX_KEYS = 4096;
174
178
  /** Characters of all of the state, sealed. */
175
179
  export declare const RELAY_HUB_MAX_STATE: number;
176
180
  /** Asks to join waiting for the owner, and for how long. */
@@ -91,11 +91,15 @@ export const RELAY_PROOF = 'ta-relay ready';
91
91
  export const RELAY_HUB_PATH = '/v1/hub/';
92
92
  /** Links that invite into a room (RelayHubLink): Ta opens them; a browser gets the page of guests (src/guest). */
93
93
  export const RELAY_ROOM_PATH = '/r';
94
- /** Members of a room, its owner among them. */
95
- export const RELAY_HUB_MAX_MEMBERS = 16;
94
+ /** Members of a hub at most, its owner among them: a room of friends (its owner and RELAY_FRIENDS_MAX friends). */
95
+ export const RELAY_HUB_MAX_MEMBERS = 101;
96
+ /** Members of a room the user made, its owner among them: the owner's Ta lets in no more (RelayHubs.answer). */
97
+ export const RELAY_ROOM_MAX_MEMBERS = 16;
98
+ /** Friends of a Ta at most: the members of its room of friends (docs/design/ta-link.md 3.1). */
99
+ export const RELAY_FRIENDS_MAX = 100;
96
100
  /** Characters of a sealed message or value of the state. */
97
101
  export const RELAY_HUB_MAX_VALUE = 96 * 1024;
98
- export const RELAY_HUB_MAX_KEYS = 512;
102
+ export const RELAY_HUB_MAX_KEYS = 4096;
99
103
  /** Characters of all of the state, sealed. */
100
104
  export const RELAY_HUB_MAX_STATE = 3 * 1024 * 1024;
101
105
  /** Asks to join waiting for the owner, and for how long. */
@@ -21,7 +21,36 @@ export interface RelayChatLine {
21
21
  name: string;
22
22
  text: string;
23
23
  at: number;
24
+ /**
25
+ * Said by the double of the member, its Ta's agent, not by the member (docs/design/ta-link.md 4): as an answer to
26
+ * one who asked it, or for the member who sent it to say something.
27
+ */
28
+ double?: boolean;
29
+ /**
30
+ * Said by an agent of the member's Ta (one of ta-channels) that the member invited to the room: its id there and its
31
+ * name. Not with `double`.
32
+ */
33
+ agent?: RelayChatAgent;
34
+ /**
35
+ * Whom it asks: members' doubles by their member ids, each one's Ta answering if the member lets it; agents in the room
36
+ * by `<member>/<agent id>`, their member's Ta answering.
37
+ */
38
+ to?: string[];
39
+ /** The id of the line it answers. */
40
+ re?: string;
41
+ /**
42
+ * A task handed to the doubles it asks (`to`), not a question (docs/design/ta-link.md 6): each one's Ta works on it on
43
+ * its own, says how it goes under `tasks:<member>` of the state, and answers with `re` when it ends.
44
+ */
45
+ task?: boolean;
24
46
  }
47
+ /** An agent of a member's Ta, in a room (RelayChatLine.agent). */
48
+ export interface RelayChatAgent {
49
+ id: string;
50
+ name: string;
51
+ }
52
+ /** What a line adds to its text: who said it and to whom (RelayRoomChat.say). */
53
+ export type RelayChatLineExtra = Pick<RelayChatLine, 'double' | 'agent' | 'to' | 're' | 'task'>;
25
54
  /** What is kept of a line: `from` is the key's. */
26
55
  type StoredLine = Omit<RelayChatLine, 'from'>;
27
56
  /** The keys of what is said, `chat:<member>:<n>`: each member writes only its own, so none can write as another. */
@@ -39,6 +68,8 @@ export declare namespace RelayRoomChatUtil {
39
68
  } | undefined;
40
69
  /** The lines of a part, if its value is one and was written by the member of its key. */
41
70
  function lines(member: string, value: unknown, by: string): RelayChatLine[] | undefined;
71
+ /** What a stored line adds, as far as it is well formed. */
72
+ function extra(line: Record<string, unknown>): RelayChatLineExtra;
42
73
  function stored(lines: RelayChatLine[]): StoredLine[];
43
74
  function bytes(lines: StoredLine[]): number;
44
75
  function id(): string;
@@ -67,11 +98,14 @@ export declare class RelayRoomChat {
67
98
  load(): Promise<void>;
68
99
  /** A key of the room set, as its event tells: whether it was of the chat. */
69
100
  heard(key: string, value: RelayRoomChatValue): boolean;
70
- /** Says `text` as `self` (its member id and name); set again on what another client of the same Ta wrote first. */
101
+ /**
102
+ * Says `text` as `self` (its member id and name), with what `extra` adds (its double says it, to whose doubles); set
103
+ * again on what another client of the same Ta wrote first. The line said, or undefined when there was nothing to say.
104
+ */
71
105
  say(text: string, self: {
72
106
  member: string;
73
107
  name: string;
74
- }): Promise<void>;
108
+ }, extra?: RelayChatLineExtra): Promise<RelayChatLine | undefined>;
75
109
  protected clear(key: string): Promise<void>;
76
110
  protected latest(member: string): Part | undefined;
77
111
  protected put(key: string, value: RelayRoomChatValue): void;
@@ -25,14 +25,29 @@ export var RelayRoomChatUtil;
25
25
  const lines = [];
26
26
  for (const line of value) {
27
27
  if (line && typeof line.id === 'string' && typeof line.text === 'string' && typeof line.at === 'number') {
28
- lines.push({ id: line.id, from: member, name: typeof line.name === 'string' ? line.name : '', text: line.text, at: line.at });
28
+ lines.push({ id: line.id, from: member, name: typeof line.name === 'string' ? line.name : '', text: line.text, at: line.at, ...extra(line) });
29
29
  }
30
30
  }
31
31
  return lines;
32
32
  }
33
33
  RelayRoomChatUtil.lines = lines;
34
+ /** What a stored line adds, as far as it is well formed. */
35
+ function extra(line) {
36
+ const to = Array.isArray(line.to) ? line.to.filter((each) => typeof each === 'string').slice(0, 16) : [];
37
+ const agent = line.agent;
38
+ return {
39
+ ...(line.double === true ? { double: true } : {}),
40
+ ...(agent && typeof agent.id === 'string' && agent.id && typeof agent.name === 'string' && line.double !== true
41
+ ? { agent: { id: agent.id.slice(0, 64), name: agent.name.slice(0, 64) } }
42
+ : {}),
43
+ ...(to.length ? { to } : {}),
44
+ ...(typeof line.re === 'string' ? { re: line.re } : {}),
45
+ ...(line.task === true && to.length ? { task: true } : {}),
46
+ };
47
+ }
48
+ RelayRoomChatUtil.extra = extra;
34
49
  function stored(lines) {
35
- return lines.map(({ id, name, text, at }) => ({ id, name, text, at }));
50
+ return lines.map(({ from: _from, ...line }) => line);
36
51
  }
37
52
  RelayRoomChatUtil.stored = stored;
38
53
  function bytes(lines) {
@@ -86,20 +101,30 @@ export class RelayRoomChat {
86
101
  this.changed();
87
102
  return true;
88
103
  }
89
- /** Says `text` as `self` (its member id and name); set again on what another client of the same Ta wrote first. */
90
- async say(text, self) {
104
+ /**
105
+ * Says `text` as `self` (its member id and name), with what `extra` adds (its double says it, to whose doubles); set
106
+ * again on what another client of the same Ta wrote first. The line said, or undefined when there was nothing to say.
107
+ */
108
+ async say(text, self, extra = {}) {
91
109
  var _a;
92
110
  var _b, _c;
93
111
  const said = text.trim().slice(0, RELAY_CHAT_TEXT_MAX);
94
112
  if (!said) {
95
- return;
113
+ return undefined;
96
114
  }
97
115
  for (let tries = 0; tries < TRIES; tries++) {
98
116
  const latest = this.latest(self.member);
99
117
  // After what it said last, even within the same millisecond: the lines of a member keep their order.
100
118
  const last = latest === null || latest === void 0 ? void 0 : latest.lines[latest.lines.length - 1];
101
119
  const at = Math.max(Date.now(), ((_b = last === null || last === void 0 ? void 0 : last.at) !== null && _b !== void 0 ? _b : 0) + 1);
102
- const line = { id: RelayRoomChatUtil.id(), from: self.member, name: self.name, text: said, at };
120
+ const line = {
121
+ id: RelayRoomChatUtil.id(),
122
+ from: self.member,
123
+ name: self.name,
124
+ text: said,
125
+ at,
126
+ ...RelayRoomChatUtil.extra(extra),
127
+ };
103
128
  const fits = latest && RelayRoomChatUtil.bytes(RelayRoomChatUtil.stored([...latest.lines, line])) <= RELAY_CHAT_PART_BYTES;
104
129
  const part = !latest ? 0 : fits ? latest.part : latest.part + 1;
105
130
  const lines = fits && latest ? [...latest.lines, line] : [line];
@@ -112,7 +137,7 @@ export class RelayRoomChat {
112
137
  if (part >= RELAY_CHAT_PARTS) {
113
138
  void this.clear(RelayRoomChatUtil.key(self.member, part - RELAY_CHAT_PARTS));
114
139
  }
115
- return;
140
+ return line;
116
141
  }
117
142
  await this.load();
118
143
  }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * A spot (docs/design/ta-nearby.md 2.2): the Ta that typed the same code of six digits, on networks that keep them
3
+ * apart, hear each other's beacons through the relay, and pass sealed messages by their temporary ids. The id of a spot
4
+ * is a hash of its code; the relay keeps nothing of it but who is connected now.
5
+ */
6
+ export declare const RELAY_SPOT_PATH = "/v1/spot/";
7
+ /** Who may come into a spot this long after it was opened; those in stay. */
8
+ export declare const RELAY_SPOT_JOIN_MS: number;
9
+ /** Those in a spot at most. */
10
+ export declare const RELAY_SPOT_MAX = 50;
11
+ /** A message at most. */
12
+ export declare const RELAY_SPOT_MESSAGE = 900000;
13
+ /** Codes nobody opened that one address may try in {@link RELAY_SPOT_TRIES_MS}; then it waits. */
14
+ export declare const RELAY_SPOT_TRIES = 10;
15
+ export declare const RELAY_SPOT_TRIES_MS: number;
16
+ export declare enum RelaySpotCloseCode {
17
+ /** Not understood. */
18
+ BAD = 4400,
19
+ /** No one opened a spot of this code. */
20
+ NONE = 4404,
21
+ /** Opened too long ago to come in. */
22
+ LATE = 4410,
23
+ FULL = 4429,
24
+ /** This address tried too many codes nobody opened: it waits (RelaySpotTries). */
25
+ TRIES = 4428
26
+ }
27
+ /**
28
+ * The codes nobody opened that one address tried lately (docs/design/ta-nearby.md 2.2): six digits are a million
29
+ * codes, so who tries them is held to {@link RELAY_SPOT_TRIES} in {@link RELAY_SPOT_TRIES_MS}. Only those that fail
30
+ * count, so that a whole office behind one address may come into one spot at once.
31
+ */
32
+ export declare namespace RelaySpotTries {
33
+ /** What an address is counted by: an IPv4 address, or the /64 of an IPv6 one, which its owner has all of. */
34
+ function keyOf(address: string | null | undefined): string;
35
+ /** The failures still counted. */
36
+ function recent(fails: readonly number[], now: number): number[];
37
+ function blocked(fails: readonly number[], now: number): boolean;
38
+ /** When it may try again. */
39
+ function until(fails: readonly number[], now: number): number;
40
+ }
41
+ /** What the relay knows of one in a spot: its temporary ids, and when the spot was opened. */
42
+ export interface RelaySpotWho {
43
+ e?: string;
44
+ /** Its id of before, for what was sealed for it just before it changed. */
45
+ was?: string;
46
+ opened: number;
47
+ }
48
+ /** What one sends to its spot. */
49
+ export type RelaySpotIn =
50
+ /** First: opens it, or comes in if it is open. */
51
+ {
52
+ t: 'open';
53
+ }
54
+ /** First: comes in; refused when nobody opened it. */
55
+ | {
56
+ t: 'join';
57
+ }
58
+ /** Its beacon, to every other one. */
59
+ | {
60
+ t: 'here';
61
+ b: {
62
+ e: string;
63
+ } & Record<string, unknown>;
64
+ }
65
+ /** A sealed message to one (`re`: the answer to one of its). */
66
+ | {
67
+ t: 'to';
68
+ to: string;
69
+ id: string;
70
+ f: unknown;
71
+ re?: true;
72
+ } | {
73
+ t: 'bye';
74
+ };
75
+ /** What the relay sends to one in a spot. */
76
+ export type RelaySpotOut = {
77
+ t: 'ready';
78
+ opened: number;
79
+ } | {
80
+ t: 'here';
81
+ b: {
82
+ e: string;
83
+ } & Record<string, unknown>;
84
+ } | {
85
+ t: 'frame';
86
+ from: string;
87
+ id: string;
88
+ f: unknown;
89
+ re?: true;
90
+ }
91
+ /** Nobody of that id is there. */
92
+ | {
93
+ t: 'miss';
94
+ id: string;
95
+ } | {
96
+ t: 'gone';
97
+ e: string;
98
+ };
99
+ export interface RelaySpotSocket {
100
+ /** The same for the same connection. */
101
+ readonly key: unknown;
102
+ who: RelaySpotWho | undefined;
103
+ send(text: string): void;
104
+ close(code: number, reason: string): void;
105
+ }
106
+ /** One spot, on a Durable Object of the Worker or in `ta relay`: the same rules. */
107
+ export declare class RelaySpot {
108
+ protected readonly sockets: () => RelaySpotSocket[];
109
+ protected readonly now: () => number;
110
+ /** One asked to join a code nobody opened: counted against its address (RelaySpotTries). */
111
+ protected readonly missed?: ((socket: RelaySpotSocket) => void) | undefined;
112
+ constructor(sockets: () => RelaySpotSocket[], now?: () => number,
113
+ /** One asked to join a code nobody opened: counted against its address (RelaySpotTries). */
114
+ missed?: ((socket: RelaySpotSocket) => void) | undefined);
115
+ receive(socket: RelaySpotSocket, text: string): void;
116
+ /** One left: the others forget it at once. */
117
+ closed(socket: RelaySpotSocket): void;
118
+ protected enter(socket: RelaySpotSocket, message: RelaySpotIn): void;
119
+ /** The others in the spot. */
120
+ protected others(socket: RelaySpotSocket): RelaySpotSocket[];
121
+ static parse(text: string): RelaySpotIn | undefined;
122
+ }
@@ -0,0 +1,179 @@
1
+ import { RELAY_PING, RELAY_PONG } from './relay-protocol.js';
2
+ /**
3
+ * A spot (docs/design/ta-nearby.md 2.2): the Ta that typed the same code of six digits, on networks that keep them
4
+ * apart, hear each other's beacons through the relay, and pass sealed messages by their temporary ids. The id of a spot
5
+ * is a hash of its code; the relay keeps nothing of it but who is connected now.
6
+ */
7
+ export const RELAY_SPOT_PATH = '/v1/spot/';
8
+ /** Who may come into a spot this long after it was opened; those in stay. */
9
+ export const RELAY_SPOT_JOIN_MS = 10 * 60000;
10
+ /** Those in a spot at most. */
11
+ export const RELAY_SPOT_MAX = 50;
12
+ /** A message at most. */
13
+ export const RELAY_SPOT_MESSAGE = 900000;
14
+ /** Codes nobody opened that one address may try in {@link RELAY_SPOT_TRIES_MS}; then it waits. */
15
+ export const RELAY_SPOT_TRIES = 10;
16
+ export const RELAY_SPOT_TRIES_MS = 10 * 60000;
17
+ export var RelaySpotCloseCode;
18
+ (function (RelaySpotCloseCode) {
19
+ /** Not understood. */
20
+ RelaySpotCloseCode[RelaySpotCloseCode["BAD"] = 4400] = "BAD";
21
+ /** No one opened a spot of this code. */
22
+ RelaySpotCloseCode[RelaySpotCloseCode["NONE"] = 4404] = "NONE";
23
+ /** Opened too long ago to come in. */
24
+ RelaySpotCloseCode[RelaySpotCloseCode["LATE"] = 4410] = "LATE";
25
+ RelaySpotCloseCode[RelaySpotCloseCode["FULL"] = 4429] = "FULL";
26
+ /** This address tried too many codes nobody opened: it waits (RelaySpotTries). */
27
+ RelaySpotCloseCode[RelaySpotCloseCode["TRIES"] = 4428] = "TRIES";
28
+ })(RelaySpotCloseCode || (RelaySpotCloseCode = {}));
29
+ /**
30
+ * The codes nobody opened that one address tried lately (docs/design/ta-nearby.md 2.2): six digits are a million
31
+ * codes, so who tries them is held to {@link RELAY_SPOT_TRIES} in {@link RELAY_SPOT_TRIES_MS}. Only those that fail
32
+ * count, so that a whole office behind one address may come into one spot at once.
33
+ */
34
+ export var RelaySpotTries;
35
+ (function (RelaySpotTries) {
36
+ /** What an address is counted by: an IPv4 address, or the /64 of an IPv6 one, which its owner has all of. */
37
+ function keyOf(address) {
38
+ const ip = (address !== null && address !== void 0 ? address : '').trim().replace(/^::ffff:/i, '');
39
+ if (!ip.includes(':')) {
40
+ return ip || 'unknown';
41
+ }
42
+ const [head, tail = ''] = ip.toLowerCase().split('::');
43
+ const groups = head ? head.split(':') : [];
44
+ const rest = tail ? tail.split(':') : [];
45
+ const full = [...groups, ...Array(Math.max(0, 8 - groups.length - rest.length)).fill('0'), ...rest];
46
+ return `${full
47
+ .slice(0, 4)
48
+ .map(group => group.replace(/^0+(?=.)/, ''))
49
+ .join(':')}::/64`;
50
+ }
51
+ RelaySpotTries.keyOf = keyOf;
52
+ /** The failures still counted. */
53
+ function recent(fails, now) {
54
+ return fails.filter(at => now - at < RELAY_SPOT_TRIES_MS);
55
+ }
56
+ RelaySpotTries.recent = recent;
57
+ function blocked(fails, now) {
58
+ return recent(fails, now).length >= RELAY_SPOT_TRIES;
59
+ }
60
+ RelaySpotTries.blocked = blocked;
61
+ /** When it may try again. */
62
+ function until(fails, now) {
63
+ const kept = recent(fails, now).sort((a, b) => a - b);
64
+ return kept.length >= RELAY_SPOT_TRIES ? kept[kept.length - RELAY_SPOT_TRIES] + RELAY_SPOT_TRIES_MS : now;
65
+ }
66
+ RelaySpotTries.until = until;
67
+ })(RelaySpotTries || (RelaySpotTries = {}));
68
+ /** One spot, on a Durable Object of the Worker or in `ta relay`: the same rules. */
69
+ export class RelaySpot {
70
+ constructor(sockets, now = Date.now,
71
+ /** One asked to join a code nobody opened: counted against its address (RelaySpotTries). */
72
+ missed) {
73
+ this.sockets = sockets;
74
+ this.now = now;
75
+ this.missed = missed;
76
+ }
77
+ receive(socket, text) {
78
+ var _a;
79
+ var _b;
80
+ if (text === RELAY_PING) {
81
+ socket.send(RELAY_PONG);
82
+ return;
83
+ }
84
+ const message = text.length <= RELAY_SPOT_MESSAGE ? RelaySpot.parse(text) : undefined;
85
+ if (!message) {
86
+ socket.close(RelaySpotCloseCode.BAD, 'Not understood.');
87
+ return;
88
+ }
89
+ const who = socket.who;
90
+ if (!who) {
91
+ this.enter(socket, message);
92
+ return;
93
+ }
94
+ if (message.t === 'here') {
95
+ if (who.e !== message.b.e) {
96
+ socket.who = { ...who, ...(who.e ? { was: who.e } : {}), e: message.b.e };
97
+ }
98
+ const text = JSON.stringify({ t: 'here', b: message.b });
99
+ for (const other of this.others(socket)) {
100
+ other.send(text);
101
+ }
102
+ }
103
+ else if (message.t === 'to') {
104
+ const target = this.others(socket).find(other => { var _a, _b; return ((_a = other.who) === null || _a === void 0 ? void 0 : _a.e) === message.to || ((_b = other.who) === null || _b === void 0 ? void 0 : _b.was) === message.to; });
105
+ const out = target
106
+ ? { t: 'frame', from: (_b = (_a = socket.who) === null || _a === void 0 ? void 0 : _a.e) !== null && _b !== void 0 ? _b : '', id: message.id, f: message.f, ...(message.re ? { re: true } : {}) }
107
+ : { t: 'miss', id: message.id };
108
+ (target !== null && target !== void 0 ? target : socket).send(JSON.stringify(out));
109
+ }
110
+ else if (message.t === 'bye') {
111
+ socket.close(1000, 'Bye.');
112
+ }
113
+ }
114
+ /** One left: the others forget it at once. */
115
+ closed(socket) {
116
+ var _a;
117
+ const e = (_a = socket.who) === null || _a === void 0 ? void 0 : _a.e;
118
+ if (e) {
119
+ const text = JSON.stringify({ t: 'gone', e });
120
+ for (const other of this.others(socket)) {
121
+ other.send(text);
122
+ }
123
+ }
124
+ }
125
+ enter(socket, message) {
126
+ var _a;
127
+ if (message.t !== 'open' && message.t !== 'join') {
128
+ socket.close(RelaySpotCloseCode.BAD, 'Open or join first.');
129
+ return;
130
+ }
131
+ const others = this.others(socket);
132
+ const now = this.now();
133
+ const opened = others.length ? Math.min(...others.map(other => { var _a; var _b; return (_b = (_a = other.who) === null || _a === void 0 ? void 0 : _a.opened) !== null && _b !== void 0 ? _b : now; })) : now;
134
+ if (!others.length && message.t === 'join') {
135
+ (_a = this.missed) === null || _a === void 0 ? void 0 : _a.call(this, socket);
136
+ socket.close(RelaySpotCloseCode.NONE, 'No such spot.');
137
+ }
138
+ else if (now - opened > RELAY_SPOT_JOIN_MS) {
139
+ socket.close(RelaySpotCloseCode.LATE, 'Too late to come in.');
140
+ }
141
+ else if (others.length >= RELAY_SPOT_MAX) {
142
+ socket.close(RelaySpotCloseCode.FULL, 'Full.');
143
+ }
144
+ else {
145
+ socket.who = { opened };
146
+ socket.send(JSON.stringify({ t: 'ready', opened }));
147
+ }
148
+ }
149
+ /** The others in the spot. */
150
+ others(socket) {
151
+ return this.sockets().filter(other => other.key !== socket.key && other.who);
152
+ }
153
+ static parse(text) {
154
+ try {
155
+ const data = JSON.parse(text);
156
+ const id = (value) => typeof value === 'string' && value.length > 0 && value.length <= 64;
157
+ switch (data.t) {
158
+ case 'open':
159
+ case 'join':
160
+ case 'bye':
161
+ return { t: data.t };
162
+ case 'here': {
163
+ const b = data.b;
164
+ return b && typeof b === 'object' && id(b.e) ? { t: 'here', b: b } : undefined;
165
+ }
166
+ case 'to':
167
+ return id(data.to) && id(data.id)
168
+ ? { t: 'to', to: data.to, id: data.id, f: data.f, ...(data.re === true ? { re: true } : {}) }
169
+ : undefined;
170
+ default:
171
+ return undefined;
172
+ }
173
+ }
174
+ catch (_a) {
175
+ return undefined;
176
+ }
177
+ }
178
+ }
179
+ //# sourceMappingURL=relay-spot.js.map
@@ -1,6 +1,7 @@
1
1
  declare const zh: {
2
2
  title: string;
3
3
  invalid: string;
4
+ inTa: string;
4
5
  invited: string;
5
6
  joinHint: string;
6
7
  name: string;
@@ -26,6 +27,10 @@ declare const zh: {
26
27
  owner: string;
27
28
  you: string;
28
29
  guest: string;
30
+ doubleOf: string;
31
+ double: string;
32
+ task: string;
33
+ agentOf: string;
29
34
  rename: string;
30
35
  leave: string;
31
36
  leaveAsk: string;