@celljs/ta-relay 4.18.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.
- package/esm/common/index.d.ts +3 -0
- package/esm/common/index.js +3 -0
- package/esm/common/relay-account-client.d.ts +138 -0
- package/esm/common/relay-account-client.js +338 -0
- package/esm/common/relay-account.d.ts +137 -0
- package/esm/common/relay-account.js +122 -0
- package/esm/common/relay-accounts.d.ts +107 -0
- package/esm/common/relay-accounts.js +393 -0
- package/esm/node/index.d.ts +1 -0
- package/esm/node/index.js +1 -0
- package/esm/node/relay-server-accounts.d.ts +16 -0
- package/esm/node/relay-server-accounts.js +54 -0
- package/esm/node/relay-server.d.ts +5 -0
- package/esm/node/relay-server.js +7 -0
- package/esm/node/relay-store.d.ts +3 -1
- package/esm/node/relay-store.js +1 -0
- package/lib/common/index.d.ts +3 -0
- package/lib/common/index.js +3 -0
- package/lib/common/relay-account-client.d.ts +139 -0
- package/lib/common/relay-account-client.js +343 -0
- package/lib/common/relay-account.d.ts +138 -0
- package/lib/common/relay-account.js +125 -0
- package/lib/common/relay-accounts.d.ts +108 -0
- package/lib/common/relay-accounts.js +401 -0
- package/lib/node/index.d.ts +1 -0
- package/lib/node/index.js +1 -0
- package/lib/node/relay-server-accounts.d.ts +17 -0
- package/lib/node/relay-server-accounts.js +58 -0
- package/lib/node/relay-server.d.ts +5 -0
- package/lib/node/relay-server.js +7 -0
- package/lib/node/relay-store.d.ts +3 -1
- package/lib/node/relay-store.js +1 -0
- package/package.json +3 -3
|
@@ -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
|
package/lib/node/index.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ export * from './relay-host';
|
|
|
5
5
|
export * from './relay-hub-files';
|
|
6
6
|
export * from './relay-memory-storage';
|
|
7
7
|
export * from './relay-server';
|
|
8
|
+
export * from './relay-server-accounts';
|
|
8
9
|
export * from './relay-store';
|
|
9
10
|
export * from './relay-viewer';
|
|
10
11
|
export * from './relays-file';
|
package/lib/node/index.js
CHANGED
|
@@ -21,6 +21,7 @@ __exportStar(require("./relay-host"), exports);
|
|
|
21
21
|
__exportStar(require("./relay-hub-files"), exports);
|
|
22
22
|
__exportStar(require("./relay-memory-storage"), exports);
|
|
23
23
|
__exportStar(require("./relay-server"), exports);
|
|
24
|
+
__exportStar(require("./relay-server-accounts"), exports);
|
|
24
25
|
__exportStar(require("./relay-store"), exports);
|
|
25
26
|
__exportStar(require("./relay-viewer"), exports);
|
|
26
27
|
__exportStar(require("./relays-file"), exports);
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import { type RelayAccountProvider, RelayAccounts, type RelayAccountsOptions } from '../common/relay-accounts';
|
|
3
|
+
/**
|
|
4
|
+
* The account service of `ta relay` (docs/design/ta-account.md), as the Worker answers it: the book of each account in
|
|
5
|
+
* a directory of its own under `data`, or in memory without one.
|
|
6
|
+
*/
|
|
7
|
+
export declare class RelayServerAccounts {
|
|
8
|
+
protected readonly accounts: RelayAccounts;
|
|
9
|
+
/** `authenticate`: a gateway's, whose sign-in gives the tokens (RelayAccountsOptions.authenticate). */
|
|
10
|
+
constructor(data: string | undefined, options?: Pick<RelayAccountsOptions, 'authenticate'> & {
|
|
11
|
+
providers?: RelayAccountProvider[];
|
|
12
|
+
});
|
|
13
|
+
/** Answers a request of RELAY_ACCOUNT_PATH; never throws, an unhandled rejection would end the relay. */
|
|
14
|
+
serve(request: IncomingMessage, response: ServerResponse): void;
|
|
15
|
+
protected answer(request: IncomingMessage, response: ServerResponse): Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
//# sourceMappingURL=relay-server-accounts.d.ts.map
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.RelayServerAccounts = void 0;
|
|
4
|
+
const node_path_1 = require("node:path");
|
|
5
|
+
const relay_accounts_1 = require("../common/relay-accounts");
|
|
6
|
+
const relay_bytes_1 = require("../common/relay-bytes");
|
|
7
|
+
const relay_file_storage_1 = require("./relay-file-storage");
|
|
8
|
+
const relay_memory_storage_1 = require("./relay-memory-storage");
|
|
9
|
+
/** What a call of the account service may hold. */
|
|
10
|
+
const MAX_BYTES = 64 * 1024;
|
|
11
|
+
/**
|
|
12
|
+
* The account service of `ta relay` (docs/design/ta-account.md), as the Worker answers it: the book of each account in
|
|
13
|
+
* a directory of its own under `data`, or in memory without one.
|
|
14
|
+
*/
|
|
15
|
+
class RelayServerAccounts {
|
|
16
|
+
/** `authenticate`: a gateway's, whose sign-in gives the tokens (RelayAccountsOptions.authenticate). */
|
|
17
|
+
constructor(data, options = {}) {
|
|
18
|
+
var _a;
|
|
19
|
+
const books = new relay_accounts_1.RelayAccountBooks(account => data ? new relay_file_storage_1.FileRelayStorage((0, node_path_1.join)(data, 'accounts', relay_bytes_1.RelayBytes.toBase64(new TextEncoder().encode(account)))) : new relay_memory_storage_1.MemoryHubStorage());
|
|
20
|
+
const providers = (_a = options.providers) !== null && _a !== void 0 ? _a : (options.authenticate ? [] : [new relay_accounts_1.RelayGitHubAccounts()]);
|
|
21
|
+
this.accounts = new relay_accounts_1.RelayAccounts({ book: account => books.book(account), providers, authenticate: options.authenticate });
|
|
22
|
+
}
|
|
23
|
+
/** Answers a request of RELAY_ACCOUNT_PATH; never throws, an unhandled rejection would end the relay. */
|
|
24
|
+
serve(request, response) {
|
|
25
|
+
this.answer(request, response).catch(() => {
|
|
26
|
+
if (!response.headersSent) {
|
|
27
|
+
response.writeHead(400);
|
|
28
|
+
}
|
|
29
|
+
response.end();
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
async answer(request, response) {
|
|
33
|
+
var _a;
|
|
34
|
+
const chunks = [];
|
|
35
|
+
let size = 0;
|
|
36
|
+
for await (const chunk of request) {
|
|
37
|
+
size += chunk.length;
|
|
38
|
+
if (size > MAX_BYTES) {
|
|
39
|
+
response.writeHead(413, { connection: 'close' }).end('Too large.\n');
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
chunks.push(chunk);
|
|
43
|
+
}
|
|
44
|
+
const headers = new Headers();
|
|
45
|
+
for (const [name, value] of Object.entries(request.headers)) {
|
|
46
|
+
if (typeof value === 'string') {
|
|
47
|
+
headers.set(name, value);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const method = (_a = request.method) !== null && _a !== void 0 ? _a : 'GET';
|
|
51
|
+
const body = chunks.length && method !== 'GET' && method !== 'HEAD' ? Buffer.concat(chunks) : undefined;
|
|
52
|
+
const answer = await this.accounts.handle(new Request(`http://relay${request.url}`, { method, headers, body }));
|
|
53
|
+
response.writeHead(answer.status, Object.fromEntries(answer.headers));
|
|
54
|
+
response.end(Buffer.from(await answer.arrayBuffer()));
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
exports.RelayServerAccounts = RelayServerAccounts;
|
|
58
|
+
//# sourceMappingURL=relay-server-accounts.js.map
|
|
@@ -2,12 +2,14 @@ import { type IncomingMessage, type Server, type ServerResponse } from 'node:htt
|
|
|
2
2
|
import type { Duplex } from 'node:stream';
|
|
3
3
|
import { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
|
|
4
4
|
import { type TaDeploymentEnv } from '@celljs/ta-protocol/lib/common/deployment-protocol';
|
|
5
|
+
import type { RelayAccountProvider } from '../common/relay-accounts';
|
|
5
6
|
import { RelayBlobs } from '../common/relay-blobs';
|
|
6
7
|
import { RelayHub, type RelayHubWho } from '../common/relay-hub';
|
|
7
8
|
import { RelayRoom } from '../common/relay-room';
|
|
8
9
|
import { RelaySpot, type RelaySpotSocket, type RelaySpotWho } from '../common/relay-spot';
|
|
9
10
|
import { FileRelayStorage } from './relay-file-storage';
|
|
10
11
|
import { MemoryBlobStorage, MemoryHubStorage } from './relay-memory-storage';
|
|
12
|
+
import { RelayServerAccounts } from './relay-server-accounts';
|
|
11
13
|
export interface RelayServerOptions {
|
|
12
14
|
host?: string;
|
|
13
15
|
port?: number;
|
|
@@ -29,6 +31,8 @@ export interface RelayServerOptions {
|
|
|
29
31
|
TA_PUBLIC_URL?: string;
|
|
30
32
|
};
|
|
31
33
|
version?: string;
|
|
34
|
+
/** The ways to sign in to accounts (docs/design/ta-account.md): GitHub with Ta's own app, unless given. */
|
|
35
|
+
accounts?: RelayAccountProvider[];
|
|
32
36
|
}
|
|
33
37
|
interface Room {
|
|
34
38
|
secretHash: string;
|
|
@@ -71,6 +75,7 @@ export declare class RelayServer {
|
|
|
71
75
|
/** The address each connection to a spot came from. */
|
|
72
76
|
protected readonly spotAddresses: WeakMap<WebSocketConnection, string>;
|
|
73
77
|
protected server?: Server;
|
|
78
|
+
protected readonly accounts: RelayServerAccounts;
|
|
74
79
|
constructor(options?: RelayServerOptions);
|
|
75
80
|
/** What it is part of, and whether it runs and can keep what it holds: for anyone, and the probes of a platform. */
|
|
76
81
|
protected describe(path: string, request: IncomingMessage, response: ServerResponse): void;
|
package/lib/node/relay-server.js
CHANGED
|
@@ -7,6 +7,7 @@ const node_http_1 = require("node:http");
|
|
|
7
7
|
const node_path_1 = require("node:path");
|
|
8
8
|
const websocket_connection_1 = require("@celljs/rpc/lib/node/websocket/websocket-connection");
|
|
9
9
|
const deployment_protocol_1 = require("@celljs/ta-protocol/lib/common/deployment-protocol");
|
|
10
|
+
const relay_account_1 = require("../common/relay-account");
|
|
10
11
|
const relay_blobs_1 = require("../common/relay-blobs");
|
|
11
12
|
const relay_hub_1 = require("../common/relay-hub");
|
|
12
13
|
const relay_info_1 = require("../common/relay-info");
|
|
@@ -17,6 +18,7 @@ const relay_team_1 = require("../common/relay-team");
|
|
|
17
18
|
const relay_web_1 = require("../common/relay-web");
|
|
18
19
|
const relay_file_storage_1 = require("./relay-file-storage");
|
|
19
20
|
const relay_memory_storage_1 = require("./relay-memory-storage");
|
|
21
|
+
const relay_server_accounts_1 = require("./relay-server-accounts");
|
|
20
22
|
const relay_viewer_1 = require("./relay-viewer");
|
|
21
23
|
const WEBSOCKET = { maxPayload: 32 * 1024 * 1024, heartbeat: 30000 };
|
|
22
24
|
const peer = (connection) => ({ send: text => connection.send(text), close: (code, reason) => connection.close(code, reason) });
|
|
@@ -38,6 +40,7 @@ class RelayServer {
|
|
|
38
40
|
this.spotTries = new Map();
|
|
39
41
|
/** The address each connection to a spot came from. */
|
|
40
42
|
this.spotAddresses = new WeakMap();
|
|
43
|
+
this.accounts = new relay_server_accounts_1.RelayServerAccounts(options.data, { providers: options.accounts });
|
|
41
44
|
if (options.data) {
|
|
42
45
|
(0, node_fs_1.mkdirSync)(options.data, { recursive: true, mode: 0o700 });
|
|
43
46
|
try {
|
|
@@ -98,6 +101,10 @@ class RelayServer {
|
|
|
98
101
|
response.end(JSON.stringify(info));
|
|
99
102
|
return;
|
|
100
103
|
}
|
|
104
|
+
if (path.startsWith(relay_account_1.RELAY_ACCOUNT_PATH)) {
|
|
105
|
+
this.accounts.serve(request, response);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
101
108
|
if (path.startsWith(relay_protocol_1.RELAY_BLOB_PATH)) {
|
|
102
109
|
this.blob(path.slice(relay_protocol_1.RELAY_BLOB_PATH.length), request, response).catch(() => {
|
|
103
110
|
// A request aborted or that failed: an unhandled rejection would end the relay.
|
|
@@ -12,6 +12,8 @@ export interface RelayDevice {
|
|
|
12
12
|
createdAt: number;
|
|
13
13
|
/** One let in by the user, not the user's own device: the principal its calls are made as (docs/design/ta-team.md). */
|
|
14
14
|
member?: string;
|
|
15
|
+
/** A device of the user's account (docs/design/ta-account.md), by its id there: paired by the account, unpaired with it. */
|
|
16
|
+
account?: string;
|
|
15
17
|
/** No longer reaches this ta serve from then on: a link of invitation. */
|
|
16
18
|
expiresAt?: number;
|
|
17
19
|
}
|
|
@@ -152,7 +154,7 @@ export declare class RelayStore {
|
|
|
152
154
|
* each relay that has one (docs/design/ta-relays.md). `member`: a device of one the user let in, not their own;
|
|
153
155
|
* `expiresAt`: it reaches this ta serve until then. Devices expired are dropped as a new one is added.
|
|
154
156
|
*/
|
|
155
|
-
pair(relay: string, deviceName: string, options?: Pick<RelayDevice, 'member' | 'expiresAt'>): RelayPairing;
|
|
157
|
+
pair(relay: string, deviceName: string, options?: Pick<RelayDevice, 'member' | 'expiresAt' | 'account'>): RelayPairing;
|
|
156
158
|
/** Whether ta serve keeps the computer awake for the devices (RelayConfig.keepAwake). */
|
|
157
159
|
setKeepAwake(on: boolean): void;
|
|
158
160
|
/** False when there was no such device. */
|
package/lib/node/relay-store.js
CHANGED
|
@@ -221,6 +221,7 @@ class RelayStore {
|
|
|
221
221
|
key: (0, node_crypto_1.randomBytes)(32).toString('base64url'),
|
|
222
222
|
createdAt: now,
|
|
223
223
|
...(options.member ? { member: options.member } : {}),
|
|
224
|
+
...(options.account ? { account: options.account } : {}),
|
|
224
225
|
...(options.expiresAt !== undefined ? { expiresAt: options.expiresAt } : {}),
|
|
225
226
|
};
|
|
226
227
|
config.devices = [...config.devices.filter(one => one.expiresAt === undefined || one.expiresAt > now), device];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@celljs/ta-relay",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.19.0",
|
|
4
4
|
"description": "Ta from anywhere: a relay that only forwards, and end-to-end encryption between a paired device and ta serve",
|
|
5
5
|
"homepage": "https://github.com/cellbang/ta",
|
|
6
6
|
"bugs": {
|
|
@@ -30,8 +30,8 @@
|
|
|
30
30
|
"watch": "tsc -b -w --preserveWatchOutput"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@celljs/rpc": "4.
|
|
34
|
-
"@celljs/ta-protocol": "4.
|
|
33
|
+
"@celljs/rpc": "4.19.0",
|
|
34
|
+
"@celljs/ta-protocol": "4.19.0"
|
|
35
35
|
},
|
|
36
36
|
"publishConfig": {
|
|
37
37
|
"access": "public"
|