@celljs/ta-relay 4.17.0 → 4.19.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/esm/common/index.d.ts +4 -0
  2. package/esm/common/index.js +4 -0
  3. package/esm/common/relay-account-client.d.ts +138 -0
  4. package/esm/common/relay-account-client.js +338 -0
  5. package/esm/common/relay-account.d.ts +137 -0
  6. package/esm/common/relay-account.js +122 -0
  7. package/esm/common/relay-accounts.d.ts +107 -0
  8. package/esm/common/relay-accounts.js +393 -0
  9. package/esm/common/relay-faces.d.ts +1 -1
  10. package/esm/common/relay-faces.js +56 -1
  11. package/esm/common/relay-files.d.ts +14 -3
  12. package/esm/common/relay-files.js +41 -16
  13. package/esm/common/relay-friend-sends.d.ts +64 -0
  14. package/esm/common/relay-friend-sends.js +126 -0
  15. package/esm/common/relay-group-invites.d.ts +76 -0
  16. package/esm/common/relay-group-invites.js +163 -0
  17. package/esm/common/relay-hubs-protocol.d.ts +3 -1
  18. package/esm/common/relay-hubs.d.ts +19 -0
  19. package/esm/common/relay-hubs.js +58 -0
  20. package/esm/common/relay-open-in-ta.d.ts +11 -0
  21. package/esm/common/relay-open-in-ta.js +34 -0
  22. package/esm/common/relay-protocol.d.ts +2 -2
  23. package/esm/common/relay-protocol.js +5 -2
  24. package/esm/guest/guest-i18n.d.ts +1 -0
  25. package/esm/guest/guest-i18n.js +45 -41
  26. package/esm/guest/guest-style.d.ts +1 -1
  27. package/esm/guest/guest-style.js +2 -0
  28. package/esm/guest/guest.js +7 -2
  29. package/esm/join/join-i18n.d.ts +1 -0
  30. package/esm/join/join-i18n.js +4 -0
  31. package/esm/join/join.js +4 -1
  32. package/esm/node/index.d.ts +1 -0
  33. package/esm/node/index.js +1 -0
  34. package/esm/node/relay-files-host.d.ts +2 -0
  35. package/esm/node/relay-files-host.js +24 -5
  36. package/esm/node/relay-server-accounts.d.ts +16 -0
  37. package/esm/node/relay-server-accounts.js +54 -0
  38. package/esm/node/relay-server.d.ts +5 -0
  39. package/esm/node/relay-server.js +7 -0
  40. package/esm/node/relay-store.d.ts +3 -1
  41. package/esm/node/relay-store.js +1 -0
  42. package/esm/viewer/viewer-i18n.d.ts +1 -0
  43. package/esm/viewer/viewer-i18n.js +4 -0
  44. package/esm/viewer/viewer-style.d.ts +1 -1
  45. package/esm/viewer/viewer-style.js +2 -0
  46. package/esm/viewer/viewer.js +3 -1
  47. package/lib/common/index.d.ts +4 -0
  48. package/lib/common/index.js +4 -0
  49. package/lib/common/relay-account-client.d.ts +139 -0
  50. package/lib/common/relay-account-client.js +343 -0
  51. package/lib/common/relay-account.d.ts +138 -0
  52. package/lib/common/relay-account.js +125 -0
  53. package/lib/common/relay-accounts.d.ts +108 -0
  54. package/lib/common/relay-accounts.js +401 -0
  55. package/lib/common/relay-faces.d.ts +1 -1
  56. package/lib/common/relay-faces.js +56 -1
  57. package/lib/common/relay-files.d.ts +14 -3
  58. package/lib/common/relay-files.js +42 -17
  59. package/lib/common/relay-friend-sends.d.ts +65 -0
  60. package/lib/common/relay-friend-sends.js +130 -0
  61. package/lib/common/relay-group-invites.d.ts +77 -0
  62. package/lib/common/relay-group-invites.js +167 -0
  63. package/lib/common/relay-hubs-protocol.d.ts +3 -1
  64. package/lib/common/relay-hubs.d.ts +19 -0
  65. package/lib/common/relay-hubs.js +58 -0
  66. package/lib/common/relay-open-in-ta.d.ts +12 -0
  67. package/lib/common/relay-open-in-ta.js +37 -0
  68. package/lib/common/relay-protocol.d.ts +2 -2
  69. package/lib/common/relay-protocol.js +5 -2
  70. package/lib/guest/guest-i18n.d.ts +1 -0
  71. package/lib/guest/guest-i18n.js +45 -41
  72. package/lib/guest/guest-style.d.ts +1 -1
  73. package/lib/guest/guest-style.js +2 -0
  74. package/lib/guest/guest.js +7 -2
  75. package/lib/join/join-i18n.d.ts +1 -0
  76. package/lib/join/join-i18n.js +4 -0
  77. package/lib/join/join.js +4 -1
  78. package/lib/node/index.d.ts +1 -0
  79. package/lib/node/index.js +1 -0
  80. package/lib/node/relay-files-host.d.ts +2 -0
  81. package/lib/node/relay-files-host.js +23 -4
  82. package/lib/node/relay-server-accounts.d.ts +17 -0
  83. package/lib/node/relay-server-accounts.js +58 -0
  84. package/lib/node/relay-server.d.ts +5 -0
  85. package/lib/node/relay-server.js +7 -0
  86. package/lib/node/relay-store.d.ts +3 -1
  87. package/lib/node/relay-store.js +1 -0
  88. package/lib/viewer/viewer-i18n.d.ts +1 -0
  89. package/lib/viewer/viewer-i18n.js +4 -0
  90. package/lib/viewer/viewer-style.d.ts +1 -1
  91. package/lib/viewer/viewer-style.js +2 -0
  92. package/lib/viewer/viewer.js +3 -1
  93. package/package.json +3 -3
  94. package/viewer/join.html +12 -3
  95. package/viewer/page.html +18 -9
  96. package/viewer/room.html +19 -8
@@ -0,0 +1,108 @@
1
+ import { type AccountCallName, type AccountDevice, type AccountMail, type AccountName, type AccountRoster, type AccountSignInPoll, type AccountSignInStart } from './relay-account';
2
+ import type { RelayHubStorage } from './relay-hub';
3
+ /** Refused, with the HTTP status it answers with. */
4
+ export declare class RelayAccountError extends Error {
5
+ readonly status: number;
6
+ constructor(status: number, message: string);
7
+ }
8
+ /** What the handler asks the book of one account: a call of a device, or a token to issue once a sign-in is done. */
9
+ export type RelayAccountBookRequest = {
10
+ op: 'issue';
11
+ account: AccountName;
12
+ hash: string;
13
+ } | {
14
+ op: AccountCallName;
15
+ args: unknown[];
16
+ hash?: string;
17
+ account?: AccountName;
18
+ max?: number;
19
+ };
20
+ /**
21
+ * The devices and mail of one account, in the storage a Durable Object or `ta relay` gives it: public keys, sealed
22
+ * mail and hashes of tokens only (docs/design/ta-account.md 3).
23
+ */
24
+ export declare class RelayAccountBook {
25
+ protected readonly storage: RelayHubStorage;
26
+ constructor(storage: RelayHubStorage);
27
+ handle(request: RelayAccountBookRequest, now?: number): Promise<unknown>;
28
+ protected issue(account: AccountName, hash: string, now: number): Promise<void>;
29
+ /** Whether anyone signed in to this account: a book of a forged token holds nothing. */
30
+ signedIn(): Promise<boolean>;
31
+ protected account(): Promise<AccountName>;
32
+ protected devices(): Promise<AccountDevice[]>;
33
+ protected device(id: string): Promise<AccountDevice>;
34
+ protected roster(seen: unknown, now: number): Promise<AccountRoster>;
35
+ protected join(input: AccountDevice, max: number, now: number): Promise<AccountRoster>;
36
+ protected endorse(id: string, by: string, signature: string, now: number): Promise<AccountRoster>;
37
+ /** By a device let in, or the device itself, with its signature: a token alone removes nothing. */
38
+ protected remove(id: string, by: string, signature: string, now: number): Promise<AccountRoster>;
39
+ protected send(mail: AccountMail, now: number): Promise<void>;
40
+ protected mail(to: string): Promise<AccountMail[]>;
41
+ }
42
+ /** A way to sign in to accounts of a relay, as the device flow of RFC 8628: the relay asks, the user says yes elsewhere. */
43
+ export interface RelayAccountProvider {
44
+ id: string;
45
+ name: string;
46
+ start(): Promise<AccountSignInStart>;
47
+ poll(handle: string): Promise<AccountName | 'pending' | 'slowDown'>;
48
+ }
49
+ /**
50
+ * GitHub's device flow, for Ta's own OAuth app: a client id is public and the flow needs no secret. The device code is
51
+ * the handle: the device that began the sign-in holds it, as RFC 8628 has it; the relay keeps nothing of it.
52
+ */
53
+ export declare class RelayGitHubAccounts implements RelayAccountProvider {
54
+ protected readonly clientId: string;
55
+ protected readonly site: string;
56
+ protected readonly api: string;
57
+ readonly id = "github";
58
+ readonly name = "GitHub";
59
+ static readonly CLIENT_ID = "Ov23lip46sRQDlDM1xt7";
60
+ constructor(clientId?: string, site?: string, api?: string);
61
+ protected post<T>(path: string, form: Record<string, string>): Promise<T>;
62
+ start(): Promise<AccountSignInStart>;
63
+ poll(handle: string): Promise<AccountName | 'pending' | 'slowDown'>;
64
+ }
65
+ export interface RelayAccountsOptions {
66
+ /** The book of an account, where its requests go one after another. */
67
+ book(account: string): {
68
+ handle(request: RelayAccountBookRequest): Promise<unknown>;
69
+ };
70
+ providers: RelayAccountProvider[];
71
+ /**
72
+ * A gateway: who the bearer is, by a token of its own sign-in. Without it the service issues tokens of its own, once
73
+ * a provider says who signed in.
74
+ */
75
+ authenticate?(token: string): Promise<AccountName | undefined>;
76
+ maxDevices?: number;
77
+ }
78
+ /**
79
+ * The account service over HTTP, the same in a Worker, `ta relay` and a gateway: `/v1/account/sign-in`,
80
+ * `/v1/account/sign-in/poll`, `/v1/account/providers` and `/v1/account/call`. Tokens go in a header, never a
81
+ * cookie, so any page may call it.
82
+ */
83
+ export declare class RelayAccounts {
84
+ protected readonly options: RelayAccountsOptions;
85
+ constructor(options: RelayAccountsOptions);
86
+ static json(value: unknown, status?: number): Response;
87
+ /** `<account id, base64url>.<secret>`: the account it is of, and what only its holder knows. */
88
+ static token(account: string): string;
89
+ static accountOf(token: string): string | undefined;
90
+ handle(request: Request): Promise<Response>;
91
+ protected provider(id: unknown): RelayAccountProvider;
92
+ protected poll(id: unknown, handle: unknown): Promise<AccountSignInPoll>;
93
+ protected call(authorization: string, op: unknown, args: unknown): Promise<unknown>;
94
+ }
95
+ /** The books of a `ta relay` or a gateway, in one process: the requests of one account one after another. */
96
+ export declare class RelayAccountBooks {
97
+ protected readonly storage: (account: string) => RelayHubStorage;
98
+ /** Any token names an account: a book that holds none once its requests are done is not kept. */
99
+ protected readonly books: Map<string, {
100
+ book: RelayAccountBook;
101
+ chain: Promise<unknown>;
102
+ }>;
103
+ constructor(storage: (account: string) => RelayHubStorage);
104
+ book(account: string): {
105
+ handle(request: RelayAccountBookRequest): Promise<unknown>;
106
+ };
107
+ }
108
+ //# sourceMappingURL=relay-accounts.d.ts.map
@@ -0,0 +1,401 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RelayAccountBooks = exports.RelayAccounts = exports.RelayGitHubAccounts = exports.RelayAccountBook = exports.RelayAccountError = void 0;
4
+ const relay_account_1 = require("./relay-account");
5
+ const relay_bytes_1 = require("./relay-bytes");
6
+ const relay_identity_1 = require("./relay-identity");
7
+ const relay_protocol_1 = require("./relay-protocol");
8
+ /** Refused, with the HTTP status it answers with. */
9
+ class RelayAccountError extends Error {
10
+ constructor(status, message) {
11
+ super(message);
12
+ this.status = status;
13
+ }
14
+ }
15
+ exports.RelayAccountError = RelayAccountError;
16
+ const MAIL_MAX = 16 * 1024;
17
+ const TOKENS_MAX = 50;
18
+ const REMOVED_MAX = 100;
19
+ const SEEN_EVERY_MS = 30000;
20
+ const KINDS = new Set(['computer', 'phone', 'browser']);
21
+ const MAIL_KINDS = new Set(['circle', 'pairing', 'package']);
22
+ const TOPIC = /^[@\w./:-]{1,120}$/;
23
+ /**
24
+ * The devices and mail of one account, in the storage a Durable Object or `ta relay` gives it: public keys, sealed
25
+ * mail and hashes of tokens only (docs/design/ta-account.md 3).
26
+ */
27
+ class RelayAccountBook {
28
+ constructor(storage) {
29
+ this.storage = storage;
30
+ }
31
+ async handle(request, now = Date.now()) {
32
+ var _a, _b, _c;
33
+ if (request.op === 'issue') {
34
+ return this.issue(request.account, request.hash, now);
35
+ }
36
+ if (request.account) {
37
+ const kept = await this.storage.get('account');
38
+ if (!kept || kept.name !== request.account.name) {
39
+ await this.storage.put('account', request.account);
40
+ }
41
+ }
42
+ else if (!request.hash || !(await this.storage.get(`token:${request.hash}`))) {
43
+ throw new RelayAccountError(401, 'Sign in again: this token is no longer of the account.');
44
+ }
45
+ const args = Array.isArray(request.args) ? request.args : [];
46
+ switch (request.op) {
47
+ case 'roster':
48
+ return this.roster(args[0], now);
49
+ case 'join':
50
+ return this.join(args[0], (_a = request.max) !== null && _a !== void 0 ? _a : relay_account_1.RELAY_ACCOUNT_MAX_DEVICES, now);
51
+ case 'endorse':
52
+ return this.endorse(String(args[0]), String(args[1]), String(args[2]), now);
53
+ case 'remove':
54
+ return this.remove(String(args[0]), String((_b = args[1]) !== null && _b !== void 0 ? _b : ''), String((_c = args[2]) !== null && _c !== void 0 ? _c : ''), now);
55
+ case 'send':
56
+ return this.send(args[0], now);
57
+ case 'mail':
58
+ return this.mail(String(args[0]));
59
+ case 'signOut':
60
+ if (request.hash) {
61
+ await this.storage.delete(`token:${request.hash}`);
62
+ }
63
+ return undefined;
64
+ default:
65
+ throw new RelayAccountError(400, 'No such call.');
66
+ }
67
+ }
68
+ async issue(account, hash, now) {
69
+ await this.storage.put('account', account);
70
+ const tokens = [...(await this.storage.list({ prefix: 'token:' }))].sort(([, a], [, b]) => a.at - b.at);
71
+ for (const [key] of tokens.slice(0, Math.max(0, tokens.length - TOKENS_MAX + 1))) {
72
+ await this.storage.delete(key);
73
+ }
74
+ await this.storage.put(`token:${hash}`, { at: now });
75
+ }
76
+ /** Whether anyone signed in to this account: a book of a forged token holds nothing. */
77
+ async signedIn() {
78
+ return !!(await this.storage.get('account'));
79
+ }
80
+ async account() {
81
+ const account = await this.storage.get('account');
82
+ if (!account) {
83
+ throw new RelayAccountError(401, 'Sign in first.');
84
+ }
85
+ return account;
86
+ }
87
+ async devices() {
88
+ return [...(await this.storage.list({ prefix: 'device:' })).values()].sort((a, b) => a.addedAt - b.addedAt);
89
+ }
90
+ async device(id) {
91
+ const device = typeof id === 'string' && relay_protocol_1.RELAY_ID.test(id) ? await this.storage.get(`device:${id}`) : undefined;
92
+ if (!device) {
93
+ throw new RelayAccountError(404, 'No such device in the account.');
94
+ }
95
+ return device;
96
+ }
97
+ async roster(seen, now) {
98
+ if (typeof seen === 'string' && relay_protocol_1.RELAY_ID.test(seen)) {
99
+ const device = await this.storage.get(`device:${seen}`);
100
+ if (device && relay_account_1.AccountCircle.live(device) && now - device.seenAt > SEEN_EVERY_MS) {
101
+ await this.storage.put(`device:${seen}`, { ...device, seenAt: now });
102
+ }
103
+ }
104
+ return { account: await this.account(), devices: await this.devices() };
105
+ }
106
+ async join(input, max, now) {
107
+ const name = typeof (input === null || input === void 0 ? void 0 : input.name) === 'string' ? input.name.trim().slice(0, 64) : '';
108
+ if (!input || !KINDS.has(input.kind) || !name || !(await relay_identity_1.RelayIdentityUtil.check({ id: input.id, name, sign: input.sign, box: input.box }))) {
109
+ throw new RelayAccountError(400, 'Not a device: its id, keys, kind or name.');
110
+ }
111
+ const host = input.host && typeof input.host.relay === 'string' && /^https?:\/\/[^\s]{1,200}$/.test(input.host.relay) && relay_protocol_1.RELAY_ID.test(input.host.id)
112
+ ? { relay: input.host.relay.replace(/\/+$/, ''), id: input.host.id }
113
+ : undefined;
114
+ const kept = await this.storage.get(`device:${input.id}`);
115
+ if (kept === null || kept === void 0 ? void 0 : kept.removed) {
116
+ throw new RelayAccountError(403, 'This device was removed from the account: it joins again with new keys.');
117
+ }
118
+ const devices = await this.devices();
119
+ let device;
120
+ if (kept) {
121
+ const { host: _host, ...rest } = kept;
122
+ device = { ...rest, name, ...(host ? { host } : {}), seenAt: now };
123
+ }
124
+ else {
125
+ if (devices.filter(relay_account_1.AccountCircle.live).length >= max) {
126
+ throw new RelayAccountError(409, `An account has ${max} devices at most: remove one first.`);
127
+ }
128
+ const first = !devices.some(relay_account_1.AccountCircle.admitted);
129
+ device = {
130
+ id: input.id,
131
+ kind: input.kind,
132
+ name,
133
+ sign: input.sign,
134
+ box: input.box,
135
+ ...(host ? { host } : {}),
136
+ ...(first ? { root: true } : {}),
137
+ addedAt: now,
138
+ seenAt: now,
139
+ };
140
+ }
141
+ await this.storage.put(`device:${device.id}`, device);
142
+ return this.roster(undefined, now);
143
+ }
144
+ async endorse(id, by, signature, now) {
145
+ const [device, endorser, account] = [await this.device(id), await this.device(by), await this.account()];
146
+ if (!relay_account_1.AccountCircle.waiting(device)) {
147
+ throw new RelayAccountError(409, 'This device is not waiting to be let in.');
148
+ }
149
+ if (!relay_account_1.AccountCircle.admitted(endorser) || !(await relay_identity_1.RelayIdentityUtil.verify(endorser.sign, relay_account_1.AccountCircle.text(account.id, device), signature))) {
150
+ throw new RelayAccountError(403, 'Only a device of the account lets another in, with its signature.');
151
+ }
152
+ await this.storage.put(`device:${id}`, { ...device, endorsement: { by, signature } });
153
+ return this.roster(undefined, now);
154
+ }
155
+ /** By a device let in, or the device itself, with its signature: a token alone removes nothing. */
156
+ async remove(id, by, signature, now) {
157
+ const device = await this.device(id);
158
+ if (device.removed) {
159
+ return this.roster(undefined, now);
160
+ }
161
+ const remover = by && relay_protocol_1.RELAY_ID.test(by) ? await this.storage.get(`device:${by}`) : undefined;
162
+ const may = remover && (by === id ? relay_account_1.AccountCircle.live(remover) : relay_account_1.AccountCircle.admitted(remover));
163
+ if (!may || !(await relay_identity_1.RelayIdentityUtil.verify(remover.sign, relay_account_1.AccountCircle.removal((await this.account()).id, id), signature))) {
164
+ throw new RelayAccountError(403, 'Only a device of the account removes another, with its signature.');
165
+ }
166
+ await this.storage.put(`device:${id}`, { ...device, removed: { by, signature, at: now } });
167
+ for (const key of (await this.storage.list({ prefix: 'mail:' })).keys()) {
168
+ const [, to, from] = key.split(':');
169
+ if (to === id || from === id) {
170
+ await this.storage.delete(key);
171
+ }
172
+ }
173
+ const removed = (await this.devices()).filter(one => one.removed).sort((a, b) => { var _a, _b; var _c, _d; return ((_c = (_a = b.removed) === null || _a === void 0 ? void 0 : _a.at) !== null && _c !== void 0 ? _c : 0) - ((_d = (_b = a.removed) === null || _b === void 0 ? void 0 : _b.at) !== null && _d !== void 0 ? _d : 0); });
174
+ for (const old of removed.slice(REMOVED_MAX)) {
175
+ await this.storage.delete(`device:${old.id}`);
176
+ }
177
+ return this.roster(undefined, now);
178
+ }
179
+ async send(mail, now) {
180
+ if (!mail ||
181
+ !MAIL_KINDS.has(mail.kind) ||
182
+ typeof mail.sealed !== 'string' ||
183
+ typeof mail.signature !== 'string' ||
184
+ mail.sealed.length > MAIL_MAX ||
185
+ (mail.kind === 'package') !== (typeof mail.topic === 'string' && TOPIC.test(mail.topic))) {
186
+ throw new RelayAccountError(400, 'Not a mail.');
187
+ }
188
+ const [from, to] = [await this.device(mail.from), await this.device(mail.to)];
189
+ if (!relay_account_1.AccountCircle.live(from) || !relay_account_1.AccountCircle.live(to)) {
190
+ throw new RelayAccountError(409, 'Mail goes between devices of the account.');
191
+ }
192
+ const { from: f, to: t, kind, topic, sealed, signature } = mail;
193
+ await this.storage.put(`mail:${t}:${f}:${kind}${topic ? `:${topic}` : ''}`, {
194
+ from: f,
195
+ to: t,
196
+ kind,
197
+ ...(topic ? { topic } : {}),
198
+ sealed,
199
+ signature,
200
+ at: now,
201
+ });
202
+ }
203
+ async mail(to) {
204
+ await this.device(to);
205
+ return [...(await this.storage.list({ prefix: `mail:${to}:` })).values()];
206
+ }
207
+ }
208
+ exports.RelayAccountBook = RelayAccountBook;
209
+ /**
210
+ * GitHub's device flow, for Ta's own OAuth app: a client id is public and the flow needs no secret. The device code is
211
+ * the handle: the device that began the sign-in holds it, as RFC 8628 has it; the relay keeps nothing of it.
212
+ */
213
+ class RelayGitHubAccounts {
214
+ constructor(clientId = RelayGitHubAccounts.CLIENT_ID, site = 'https://github.com', api = 'https://api.github.com') {
215
+ this.clientId = clientId;
216
+ this.site = site;
217
+ this.api = api;
218
+ this.id = 'github';
219
+ this.name = 'GitHub';
220
+ }
221
+ async post(path, form) {
222
+ const response = await fetch(this.site + path, {
223
+ method: 'POST',
224
+ headers: { accept: 'application/json', 'content-type': 'application/x-www-form-urlencoded', 'user-agent': 'Ta' },
225
+ body: new URLSearchParams(form).toString(),
226
+ });
227
+ return (await response.json());
228
+ }
229
+ async start() {
230
+ var _a, _b, _c;
231
+ const answer = await this.post('/login/device/code', { client_id: this.clientId, scope: 'read:user' });
232
+ if (!answer.device_code || !answer.user_code || !answer.verification_uri) {
233
+ throw new RelayAccountError(502, `GitHub: ${(_a = answer.error_description) !== null && _a !== void 0 ? _a : 'no code'}`);
234
+ }
235
+ return {
236
+ handle: answer.device_code,
237
+ code: answer.user_code,
238
+ url: answer.verification_uri,
239
+ interval: Number((_b = answer.interval) !== null && _b !== void 0 ? _b : 5),
240
+ expiresIn: Number((_c = answer.expires_in) !== null && _c !== void 0 ? _c : 900),
241
+ };
242
+ }
243
+ async poll(handle) {
244
+ var _a, _b, _c, _d;
245
+ const token = await this.post('/login/oauth/access_token', {
246
+ client_id: this.clientId,
247
+ device_code: handle,
248
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
249
+ });
250
+ if (token.error === 'authorization_pending') {
251
+ return 'pending';
252
+ }
253
+ if (token.error === 'slow_down') {
254
+ return 'slowDown';
255
+ }
256
+ if (!token.access_token) {
257
+ throw new RelayAccountError(400, `GitHub: ${(_b = (_a = token.error_description) !== null && _a !== void 0 ? _a : token.error) !== null && _b !== void 0 ? _b : 'no access token'}`);
258
+ }
259
+ const user = (await (await fetch(`${this.api}/user`, { headers: { accept: 'application/json', authorization: `Bearer ${token.access_token}`, 'user-agent': 'Ta' } })).json());
260
+ if (!user.id) {
261
+ throw new RelayAccountError(502, 'GitHub did not say who signed in.');
262
+ }
263
+ return { id: `github:${user.id}`, name: (_d = (_c = user.login) !== null && _c !== void 0 ? _c : user.name) !== null && _d !== void 0 ? _d : String(user.id) };
264
+ }
265
+ }
266
+ exports.RelayGitHubAccounts = RelayGitHubAccounts;
267
+ RelayGitHubAccounts.CLIENT_ID = 'Ov23lip46sRQDlDM1xt7';
268
+ const CORS = {
269
+ 'access-control-allow-origin': '*',
270
+ 'access-control-allow-headers': 'authorization, content-type',
271
+ 'access-control-allow-methods': 'GET, POST, OPTIONS',
272
+ 'access-control-max-age': '86400',
273
+ };
274
+ /**
275
+ * The account service over HTTP, the same in a Worker, `ta relay` and a gateway: `/v1/account/sign-in`,
276
+ * `/v1/account/sign-in/poll`, `/v1/account/providers` and `/v1/account/call`. Tokens go in a header, never a
277
+ * cookie, so any page may call it.
278
+ */
279
+ class RelayAccounts {
280
+ constructor(options) {
281
+ this.options = options;
282
+ }
283
+ static json(value, status = 200) {
284
+ return new Response(JSON.stringify(value !== null && value !== void 0 ? value : null), { status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store', ...CORS } });
285
+ }
286
+ /** `<account id, base64url>.<secret>`: the account it is of, and what only its holder knows. */
287
+ static token(account) {
288
+ return `${relay_bytes_1.RelayBytes.toBase64(new TextEncoder().encode(account))}.${relay_bytes_1.RelayBytes.toBase64(relay_bytes_1.RelayBytes.random(32))}`;
289
+ }
290
+ static accountOf(token) {
291
+ const [account, secret] = token.split('.');
292
+ try {
293
+ return account && secret ? new TextDecoder().decode(relay_bytes_1.RelayBytes.fromBase64(account)) : undefined;
294
+ }
295
+ catch (_a) {
296
+ return undefined;
297
+ }
298
+ }
299
+ async handle(request) {
300
+ var _a, _b;
301
+ if (request.method === 'OPTIONS') {
302
+ return new Response(null, { status: 204, headers: CORS });
303
+ }
304
+ const path = new URL(request.url).pathname.slice(relay_account_1.RELAY_ACCOUNT_PATH.length);
305
+ try {
306
+ if (path === 'providers' && request.method === 'GET') {
307
+ return RelayAccounts.json(this.options.authenticate ? [] : this.options.providers.map(({ id, name }) => ({ id, name })));
308
+ }
309
+ if (request.method !== 'POST') {
310
+ return RelayAccounts.json({ error: 'Not found.' }, 404);
311
+ }
312
+ const body = (await request.json().catch(() => ({})));
313
+ if (path === 'sign-in') {
314
+ return RelayAccounts.json(await this.provider(body.provider).start());
315
+ }
316
+ if (path === 'sign-in/poll') {
317
+ return RelayAccounts.json(await this.poll(body.provider, body.handle));
318
+ }
319
+ if (path === 'call') {
320
+ return RelayAccounts.json({ value: await this.call((_a = request.headers.get('authorization')) !== null && _a !== void 0 ? _a : '', body.op, body.args) });
321
+ }
322
+ return RelayAccounts.json({ error: 'Not found.' }, 404);
323
+ }
324
+ catch (error) {
325
+ const status = error instanceof RelayAccountError ? error.status : ((_b = error.status) !== null && _b !== void 0 ? _b : 500);
326
+ return RelayAccounts.json({ error: error instanceof Error ? error.message : String(error) }, status);
327
+ }
328
+ }
329
+ provider(id) {
330
+ const provider = this.options.authenticate ? undefined : this.options.providers.find(one => one.id === id);
331
+ if (!provider) {
332
+ throw new RelayAccountError(404, 'No such way to sign in here.');
333
+ }
334
+ return provider;
335
+ }
336
+ async poll(id, handle) {
337
+ if (typeof handle !== 'string' || !handle || handle.length > 200) {
338
+ throw new RelayAccountError(400, 'No sign-in to poll.');
339
+ }
340
+ const signedIn = await this.provider(id).poll(handle);
341
+ if (signedIn === 'pending' || signedIn === 'slowDown') {
342
+ return { status: 'pending' };
343
+ }
344
+ const token = RelayAccounts.token(signedIn.id);
345
+ await this.options.book(signedIn.id).handle({ op: 'issue', account: signedIn, hash: await relay_identity_1.RelayKeys.hash(token) });
346
+ return { status: 'done', token, account: signedIn };
347
+ }
348
+ async call(authorization, op, args) {
349
+ const token = authorization.replace(/^Bearer\s+/i, '');
350
+ if (!relay_account_1.ACCOUNT_CALLS.includes(op)) {
351
+ throw new RelayAccountError(400, 'No such call.');
352
+ }
353
+ const request = { op: op, args: Array.isArray(args) ? args : [], max: this.options.maxDevices };
354
+ if (this.options.authenticate) {
355
+ const account = token ? await this.options.authenticate(token) : undefined;
356
+ if (!account) {
357
+ throw new RelayAccountError(401, 'Sign in again.');
358
+ }
359
+ return this.options.book(account.id).handle({ ...request, account });
360
+ }
361
+ const account = RelayAccounts.accountOf(token);
362
+ if (!account) {
363
+ throw new RelayAccountError(401, 'Sign in first.');
364
+ }
365
+ return this.options.book(account).handle({ ...request, hash: await relay_identity_1.RelayKeys.hash(token) });
366
+ }
367
+ }
368
+ exports.RelayAccounts = RelayAccounts;
369
+ /** The books of a `ta relay` or a gateway, in one process: the requests of one account one after another. */
370
+ class RelayAccountBooks {
371
+ constructor(storage) {
372
+ this.storage = storage;
373
+ /** Any token names an account: a book that holds none once its requests are done is not kept. */
374
+ this.books = new Map();
375
+ }
376
+ book(account) {
377
+ let kept = this.books.get(account);
378
+ if (!kept) {
379
+ kept = { book: new RelayAccountBook(this.storage(account)), chain: Promise.resolve() };
380
+ this.books.set(account, kept);
381
+ }
382
+ const one = kept;
383
+ return {
384
+ handle: request => {
385
+ const done = one.chain.then(() => one.book.handle(request));
386
+ const next = done
387
+ .catch(() => undefined)
388
+ .then(async () => {
389
+ // Dropped only when nothing came after it, before or while it looked.
390
+ if (one.chain === next && !(await one.book.signedIn()) && one.chain === next && this.books.get(account) === one) {
391
+ this.books.delete(account);
392
+ }
393
+ });
394
+ one.chain = next;
395
+ return done;
396
+ },
397
+ };
398
+ }
399
+ }
400
+ exports.RelayAccountBooks = RelayAccountBooks;
401
+ //# sourceMappingURL=relay-accounts.js.map
@@ -1,5 +1,5 @@
1
1
  /** How many faces there are. */
2
- export declare const FACE_COUNT = 16;
2
+ export declare const FACE_COUNT = 25;
3
3
  /** An element of SVG: its tag, its attributes as written in SVG (`stroke-width`, `class`), what is in it. */
4
4
  export interface FaceNode {
5
5
  tag: string;
@@ -8,7 +8,7 @@
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.FaceUtil = exports.FACE_COUNT = void 0;
10
10
  /** How many faces there are. */
11
- exports.FACE_COUNT = 16;
11
+ exports.FACE_COUNT = 25;
12
12
  const BLUE = '#4285F4';
13
13
  const RED = '#EA4335';
14
14
  const YELLOW = '#FBBC05';
@@ -48,6 +48,15 @@ const LOOKS = [
48
48
  { color: PINK, eye: '#4A1428', cheek: 'rgba(160, 20, 70, 0.3)', eyeY: 24, gap: 7.4 }, // drop
49
49
  { color: LILAC, eye: '#2A1A5E', cheek: CHEEK, eyeY: 25, gap: 8 }, // rabbit
50
50
  { color: YELLOW, eye: INK, cheek: CHEEK_WARM, eyeY: 25, gap: 7.4 }, // triangle
51
+ { color: BLUE, eye: WHITE, cheek: CHEEK, eyeY: 19.5, gap: 8 }, // shield
52
+ { color: CREAM, eye: '#4A3420', cheek: 'rgba(240, 120, 120, 0.5)', eyeY: 23.5, gap: 8 }, // house
53
+ { color: GREEN, eye: WHITE, cheek: CHEEK, eyeY: 21, gap: 8 }, // trapezoid
54
+ { color: PINK, eye: '#4A1428', cheek: 'rgba(160, 20, 70, 0.3)', eyeY: 19.5, gap: 8.4 }, // pill
55
+ { color: RED, eye: WHITE, cheek: CHEEK_DEEP, accent: '#B3261E', eyeY: 20, gap: 8.4 }, // lantern
56
+ { color: SKY, eye: WHITE, cheek: CHEEK, eyeY: 23.5, gap: 8 }, // cloud
57
+ { color: VIOLET, eye: WHITE, cheek: CHEEK, accent: '#6B3FD4', eyeY: 22, gap: 8 }, // jar
58
+ { color: TEAL, eye: WHITE, cheek: CHEEK, accent: '#1B8A84', eyeY: 25, gap: 7.6 }, // gourd
59
+ { color: MINT, eye: '#1D3B27', cheek: CHEEK, accent: '#4AAE6C', eyeY: 22.5, gap: 9 }, // frog
51
60
  ];
52
61
  /** The corners of a polygon of `count` sides around (cx, cy), the first straight up; `inner` makes it a star. */
53
62
  function corners(count, radius, cx, cy, inner) {
@@ -141,6 +150,52 @@ function shape(face, look) {
141
150
  ]);
142
151
  case 15:
143
152
  return rounded('20,7 35,33 5,33', color, 6);
153
+ case 16:
154
+ return node('path', {
155
+ d: 'M20 6.5l12 4.2v8.4c0 7.4-4.9 12.6-12 15.9-7.1-3.3-12-8.5-12-15.9v-8.4Z',
156
+ fill: color,
157
+ stroke: color,
158
+ 'stroke-width': 3,
159
+ 'stroke-linejoin': 'round',
160
+ });
161
+ case 17:
162
+ return rounded('20,7 32.5,17.5 32.5,33 7.5,33 7.5,17.5', color, 4.5);
163
+ case 18:
164
+ return rounded('14,9 26,9 32.5,32 7.5,32', color, 6);
165
+ case 19:
166
+ return node('rect', { x: 4.5, y: 10.5, width: 31, height: 19.5, rx: 9.75, fill: color });
167
+ case 20:
168
+ return node('g', {}, [
169
+ node('rect', { x: 14, y: 5.5, width: 12, height: 4.5, rx: 1.6, fill: accent }),
170
+ node('rect', { x: 14, y: 30.5, width: 12, height: 4.5, rx: 1.6, fill: accent }),
171
+ node('ellipse', { cx: 20, cy: 20.25, rx: 15, ry: 12.25, fill: color }),
172
+ ]);
173
+ case 21:
174
+ return node('g', {}, [
175
+ node('circle', { cx: 13.5, cy: 21.5, r: 7, fill: color }),
176
+ node('circle', { cx: 21.5, cy: 16.5, r: 9, fill: color }),
177
+ node('circle', { cx: 28.5, cy: 22.5, r: 6.5, fill: color }),
178
+ node('rect', { x: 5.5, y: 21, width: 29, height: 12, rx: 6, fill: color }),
179
+ ]);
180
+ case 22:
181
+ return node('g', {}, [
182
+ node('rect', { x: 12.5, y: 5.5, width: 15, height: 5.5, rx: 2, fill: accent }),
183
+ node('rect', { x: 7.5, y: 9.5, width: 25, height: 25.5, rx: 6.5, fill: color }),
184
+ ]);
185
+ case 23:
186
+ return node('g', {}, [
187
+ node('rect', { x: 18.8, y: 3.5, width: 2.4, height: 6, rx: 1.2, fill: accent }),
188
+ node('circle', { cx: 20, cy: 13, r: 6.5, fill: color }),
189
+ node('circle', { cx: 20, cy: 25, r: 11.5, fill: color }),
190
+ ]);
191
+ case 24:
192
+ return node('g', {}, [
193
+ node('circle', { cx: 12, cy: 13, r: 5.5, fill: color }),
194
+ node('circle', { cx: 28, cy: 13, r: 5.5, fill: color }),
195
+ node('circle', { cx: 12, cy: 13, r: 2.2, fill: accent }),
196
+ node('circle', { cx: 28, cy: 13, r: 2.2, fill: accent }),
197
+ node('ellipse', { cx: 20, cy: 23.5, rx: 15.5, ry: 11.5, fill: color }),
198
+ ]);
144
199
  default:
145
200
  return node('circle', { cx: 20, cy: 21, r: 14.5, fill: color });
146
201
  }
@@ -47,9 +47,11 @@ export declare const RELAY_FILES_PREFIX = "/api/files/";
47
47
  export declare const RELAY_FILE_CHUNK_BYTES: number;
48
48
  /** The largest file a device reads this way: a video of a workspace is previewed by its first bytes, not all of it. */
49
49
  export declare const RELAY_FILE_MAX_BYTES: number;
50
- /** Files read at once on one channel; a page that loads its pictures asks for several. */
50
+ /** Files read at once on one channel; a page that loads its pictures asks for more, which wait their turn. */
51
51
  export declare const RELAY_FILES_MAX_PARALLEL = 4;
52
- /** For one file, all of it. */
52
+ /** Files waiting their turn on one channel, at most: past them a page asks for more than it can show. */
53
+ export declare const RELAY_FILES_MAX_WAITING = 256;
54
+ /** For one file, all of it, from when it is read, not while it waits its turn. */
53
55
  export declare const RELAY_FILES_TIMEOUT_MS = 30000;
54
56
  /** A file as the page gets it: its type as ta serve answers it, and the bytes. */
55
57
  export interface RelayFileBytes {
@@ -65,6 +67,7 @@ export declare namespace RelayFilesUtil {
65
67
  }
66
68
  /** One file asked for, and what came of it so far. */
67
69
  interface Pending {
70
+ readonly url: string;
68
71
  readonly chunks: Uint8Array[];
69
72
  received: number;
70
73
  head?: {
@@ -73,7 +76,8 @@ interface Pending {
73
76
  };
74
77
  readonly resolve: (bytes: RelayFileBytes) => void;
75
78
  readonly reject: (error: Error) => void;
76
- readonly timer: ReturnType<typeof setTimeout>;
79
+ /** Set once it is asked of the host: before, it waits its turn. */
80
+ timer?: ReturnType<typeof setTimeout>;
77
81
  }
78
82
  export interface RelayFilesOptions {
79
83
  /** For one file. Default RELAY_FILES_TIMEOUT_MS. */
@@ -90,9 +94,14 @@ export declare class RelayFiles {
90
94
  protected opening?: Promise<void>;
91
95
  protected called: number;
92
96
  protected readonly pending: Map<number, Pending>;
97
+ /** Asked for but not yet of the host: no more than {@link RELAY_FILES_MAX_PARALLEL} are read at once. */
98
+ protected readonly waiting: number[];
99
+ protected asked: number;
93
100
  constructor(pairing: RelayPairing, options?: RelayFilesOptions);
94
101
  /** The bytes of a URL of {@link RELAY_FILES_PREFIX}, as ta serve answers them. */
95
102
  get(url: string): Promise<RelayFileBytes>;
103
+ /** Asks the host for the files waiting, as many as it reads at once: more would be turned away. */
104
+ protected ask(): void;
96
105
  /** Whether the channel is open: the page may keep one for as long as it shows files. */
97
106
  get open(): boolean;
98
107
  close(): void;
@@ -102,6 +111,8 @@ export declare class RelayFiles {
102
111
  protected receive(text: string): void;
103
112
  protected settle(id: number, error: Error): void;
104
113
  protected finish(id: number, bytes: RelayFileBytes): void;
114
+ /** A file came or will not: the next one waiting is asked for. */
115
+ protected done(id: number): Pending | undefined;
105
116
  /** The channel went: what was asked for is not coming. */
106
117
  protected fail(error: Error): void;
107
118
  }