@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.
@@ -0,0 +1,122 @@
1
+ import { RelayBytes } from './relay-bytes.js';
2
+ import { RelayIdentityUtil, RelayKeys } from './relay-identity.js';
3
+ /** The account service of a relay or a gateway (docs/design/ta-account.md): the devices of one user, and their mail. */
4
+ export const RELAY_ACCOUNT_PATH = '/v1/account/';
5
+ /** Devices of an account at most, removed ones aside: `RELAY_ACCOUNT_MAX_DEVICES` of the service changes it. */
6
+ export const RELAY_ACCOUNT_MAX_DEVICES = 20;
7
+ /** A device seen within this is online: computers say they are there every minute. */
8
+ export const RELAY_ACCOUNT_ONLINE_MS = 3 * 60000;
9
+ export const ACCOUNT_CALLS = ['roster', 'join', 'endorse', 'remove', 'send', 'mail', 'signOut'];
10
+ /** The trust of the devices of an account, kept by each device: the service holds keys, never says who to trust. */
11
+ export var AccountCircle;
12
+ (function (AccountCircle) {
13
+ /** What a device signs to let another in. */
14
+ function text(account, device) {
15
+ return ['ta-account-device', account, device.id, device.kind, device.sign, device.box].join('\n');
16
+ }
17
+ AccountCircle.text = text;
18
+ /** Six digits both devices show, the user checks they are the same: they come from the keys of the new one. */
19
+ async function code(device) {
20
+ const digest = await RelayKeys.sha256(RelayBytes.concat(RelayBytes.fromBase64(device.sign), RelayBytes.fromBase64(device.box)));
21
+ const number = ((digest[0] << 24) | (digest[1] << 16) | (digest[2] << 8) | digest[3]) >>> 0;
22
+ return String(number % 1000000).padStart(6, '0');
23
+ }
24
+ AccountCircle.code = code;
25
+ function live(device) {
26
+ return !device.removed;
27
+ }
28
+ AccountCircle.live = live;
29
+ /** In, by the service: the first one, or let in by someone. Who trusts it is each device's own. */
30
+ function admitted(device) {
31
+ return live(device) && (!!device.root || !!device.endorsement);
32
+ }
33
+ AccountCircle.admitted = admitted;
34
+ /** Waiting for a device of the account to let it in. */
35
+ function waiting(device) {
36
+ return live(device) && !device.root && !device.endorsement;
37
+ }
38
+ AccountCircle.waiting = waiting;
39
+ /** A device trusting itself alone: the first one, or one not let in yet. */
40
+ function alone(self) {
41
+ return { trusted: { [self.id]: { sign: self.sign, box: self.box } }, removed: [] };
42
+ }
43
+ AccountCircle.alone = alone;
44
+ /**
45
+ * Who to trust now: those trusted before and not removed, and those a trusted device let in with a good signature,
46
+ * until no more. A device the service adds without a signature of one of them is never trusted.
47
+ */
48
+ async function update(state, roster) {
49
+ const removed = new Set(state.removed);
50
+ for (const device of roster.devices) {
51
+ if (device.removed && state.trusted[device.id]) {
52
+ removed.add(device.id);
53
+ }
54
+ }
55
+ const trusted = {};
56
+ for (const [id, keys] of Object.entries(state.trusted)) {
57
+ if (!removed.has(id)) {
58
+ trusted[id] = keys;
59
+ }
60
+ }
61
+ for (let added = true; added;) {
62
+ added = false;
63
+ for (const device of roster.devices) {
64
+ if (trusted[device.id] || removed.has(device.id) || !live(device) || !device.endorsement || !trusted[device.endorsement.by]) {
65
+ continue;
66
+ }
67
+ if (await RelayIdentityUtil.verify(trusted[device.endorsement.by].sign, text(roster.account.id, device), device.endorsement.signature)) {
68
+ trusted[device.id] = { sign: device.sign, box: device.box };
69
+ added = true;
70
+ }
71
+ }
72
+ }
73
+ return { trusted, removed: [...removed] };
74
+ }
75
+ AccountCircle.update = update;
76
+ function endorse(self, account, device) {
77
+ return RelayIdentityUtil.sign(self, text(account, device));
78
+ }
79
+ AccountCircle.endorse = endorse;
80
+ /** What a device signs to remove one of the account, itself or another. */
81
+ function removal(account, id) {
82
+ return ['ta-account-remove', account, id].join('\n');
83
+ }
84
+ AccountCircle.removal = removal;
85
+ function remove(self, account, id) {
86
+ return RelayIdentityUtil.sign(self, removal(account, id));
87
+ }
88
+ AccountCircle.remove = remove;
89
+ function mailText(mail) {
90
+ var _a;
91
+ return ['ta-account-mail', mail.from, mail.to, mail.kind, (_a = mail.topic) !== null && _a !== void 0 ? _a : '', mail.sealed].join('\n');
92
+ }
93
+ async function key(self, otherBox, from, to) {
94
+ return RelayKeys.aesKey(await RelayIdentityUtil.agree(self, otherBox, `${from}>${to}`, 'ta-account-mail'));
95
+ }
96
+ /** `value` sealed for `to` and signed by `self`: the service carries it, never reads it. */
97
+ async function seal(self, to, kind, value, topic) {
98
+ const sealed = await RelayKeys.seal(await key(self, to.box, self.id, to.id), JSON.stringify(value));
99
+ const mail = { from: self.id, to: to.id, kind, ...(topic ? { topic } : {}), sealed };
100
+ return { ...mail, signature: await RelayIdentityUtil.sign(self, mailText(mail)) };
101
+ }
102
+ AccountCircle.seal = seal;
103
+ /** What `mail` holds, when it is for `self` and signed by `sender`; undefined otherwise. */
104
+ async function open(self, sender, mail) {
105
+ if (mail.to !== self.id || !(await RelayIdentityUtil.verify(sender.sign, mailText(mail), mail.signature))) {
106
+ return undefined;
107
+ }
108
+ try {
109
+ return JSON.parse(await RelayKeys.open(await key(self, sender.box, mail.from, mail.to), mail.sealed));
110
+ }
111
+ catch (_a) {
112
+ return undefined;
113
+ }
114
+ }
115
+ AccountCircle.open = open;
116
+ /** Whether a device is online, from when it was last there. */
117
+ function online(device, now = Date.now()) {
118
+ return live(device) && now - device.seenAt < RELAY_ACCOUNT_ONLINE_MS;
119
+ }
120
+ AccountCircle.online = online;
121
+ })(AccountCircle || (AccountCircle = {}));
122
+ //# sourceMappingURL=relay-account.js.map
@@ -0,0 +1,107 @@
1
+ import { type AccountCallName, type AccountDevice, type AccountMail, type AccountName, type AccountRoster, type AccountSignInPoll, type AccountSignInStart } from './relay-account.js';
2
+ import type { RelayHubStorage } from './relay-hub.js';
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
+ }
@@ -0,0 +1,393 @@
1
+ import { ACCOUNT_CALLS, AccountCircle, RELAY_ACCOUNT_MAX_DEVICES, RELAY_ACCOUNT_PATH, } from './relay-account.js';
2
+ import { RelayBytes } from './relay-bytes.js';
3
+ import { RelayIdentityUtil, RelayKeys } from './relay-identity.js';
4
+ import { RELAY_ID } from './relay-protocol.js';
5
+ /** Refused, with the HTTP status it answers with. */
6
+ export class RelayAccountError extends Error {
7
+ constructor(status, message) {
8
+ super(message);
9
+ this.status = status;
10
+ }
11
+ }
12
+ const MAIL_MAX = 16 * 1024;
13
+ const TOKENS_MAX = 50;
14
+ const REMOVED_MAX = 100;
15
+ const SEEN_EVERY_MS = 30000;
16
+ const KINDS = new Set(['computer', 'phone', 'browser']);
17
+ const MAIL_KINDS = new Set(['circle', 'pairing', 'package']);
18
+ const TOPIC = /^[@\w./:-]{1,120}$/;
19
+ /**
20
+ * The devices and mail of one account, in the storage a Durable Object or `ta relay` gives it: public keys, sealed
21
+ * mail and hashes of tokens only (docs/design/ta-account.md 3).
22
+ */
23
+ export class RelayAccountBook {
24
+ constructor(storage) {
25
+ this.storage = storage;
26
+ }
27
+ async handle(request, now = Date.now()) {
28
+ var _a, _b, _c;
29
+ if (request.op === 'issue') {
30
+ return this.issue(request.account, request.hash, now);
31
+ }
32
+ if (request.account) {
33
+ const kept = await this.storage.get('account');
34
+ if (!kept || kept.name !== request.account.name) {
35
+ await this.storage.put('account', request.account);
36
+ }
37
+ }
38
+ else if (!request.hash || !(await this.storage.get(`token:${request.hash}`))) {
39
+ throw new RelayAccountError(401, 'Sign in again: this token is no longer of the account.');
40
+ }
41
+ const args = Array.isArray(request.args) ? request.args : [];
42
+ switch (request.op) {
43
+ case 'roster':
44
+ return this.roster(args[0], now);
45
+ case 'join':
46
+ return this.join(args[0], (_a = request.max) !== null && _a !== void 0 ? _a : RELAY_ACCOUNT_MAX_DEVICES, now);
47
+ case 'endorse':
48
+ return this.endorse(String(args[0]), String(args[1]), String(args[2]), now);
49
+ case 'remove':
50
+ 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);
51
+ case 'send':
52
+ return this.send(args[0], now);
53
+ case 'mail':
54
+ return this.mail(String(args[0]));
55
+ case 'signOut':
56
+ if (request.hash) {
57
+ await this.storage.delete(`token:${request.hash}`);
58
+ }
59
+ return undefined;
60
+ default:
61
+ throw new RelayAccountError(400, 'No such call.');
62
+ }
63
+ }
64
+ async issue(account, hash, now) {
65
+ await this.storage.put('account', account);
66
+ const tokens = [...(await this.storage.list({ prefix: 'token:' }))].sort(([, a], [, b]) => a.at - b.at);
67
+ for (const [key] of tokens.slice(0, Math.max(0, tokens.length - TOKENS_MAX + 1))) {
68
+ await this.storage.delete(key);
69
+ }
70
+ await this.storage.put(`token:${hash}`, { at: now });
71
+ }
72
+ /** Whether anyone signed in to this account: a book of a forged token holds nothing. */
73
+ async signedIn() {
74
+ return !!(await this.storage.get('account'));
75
+ }
76
+ async account() {
77
+ const account = await this.storage.get('account');
78
+ if (!account) {
79
+ throw new RelayAccountError(401, 'Sign in first.');
80
+ }
81
+ return account;
82
+ }
83
+ async devices() {
84
+ return [...(await this.storage.list({ prefix: 'device:' })).values()].sort((a, b) => a.addedAt - b.addedAt);
85
+ }
86
+ async device(id) {
87
+ const device = typeof id === 'string' && RELAY_ID.test(id) ? await this.storage.get(`device:${id}`) : undefined;
88
+ if (!device) {
89
+ throw new RelayAccountError(404, 'No such device in the account.');
90
+ }
91
+ return device;
92
+ }
93
+ async roster(seen, now) {
94
+ if (typeof seen === 'string' && RELAY_ID.test(seen)) {
95
+ const device = await this.storage.get(`device:${seen}`);
96
+ if (device && AccountCircle.live(device) && now - device.seenAt > SEEN_EVERY_MS) {
97
+ await this.storage.put(`device:${seen}`, { ...device, seenAt: now });
98
+ }
99
+ }
100
+ return { account: await this.account(), devices: await this.devices() };
101
+ }
102
+ async join(input, max, now) {
103
+ const name = typeof (input === null || input === void 0 ? void 0 : input.name) === 'string' ? input.name.trim().slice(0, 64) : '';
104
+ if (!input || !KINDS.has(input.kind) || !name || !(await RelayIdentityUtil.check({ id: input.id, name, sign: input.sign, box: input.box }))) {
105
+ throw new RelayAccountError(400, 'Not a device: its id, keys, kind or name.');
106
+ }
107
+ const host = input.host && typeof input.host.relay === 'string' && /^https?:\/\/[^\s]{1,200}$/.test(input.host.relay) && RELAY_ID.test(input.host.id)
108
+ ? { relay: input.host.relay.replace(/\/+$/, ''), id: input.host.id }
109
+ : undefined;
110
+ const kept = await this.storage.get(`device:${input.id}`);
111
+ if (kept === null || kept === void 0 ? void 0 : kept.removed) {
112
+ throw new RelayAccountError(403, 'This device was removed from the account: it joins again with new keys.');
113
+ }
114
+ const devices = await this.devices();
115
+ let device;
116
+ if (kept) {
117
+ const { host: _host, ...rest } = kept;
118
+ device = { ...rest, name, ...(host ? { host } : {}), seenAt: now };
119
+ }
120
+ else {
121
+ if (devices.filter(AccountCircle.live).length >= max) {
122
+ throw new RelayAccountError(409, `An account has ${max} devices at most: remove one first.`);
123
+ }
124
+ const first = !devices.some(AccountCircle.admitted);
125
+ device = {
126
+ id: input.id,
127
+ kind: input.kind,
128
+ name,
129
+ sign: input.sign,
130
+ box: input.box,
131
+ ...(host ? { host } : {}),
132
+ ...(first ? { root: true } : {}),
133
+ addedAt: now,
134
+ seenAt: now,
135
+ };
136
+ }
137
+ await this.storage.put(`device:${device.id}`, device);
138
+ return this.roster(undefined, now);
139
+ }
140
+ async endorse(id, by, signature, now) {
141
+ const [device, endorser, account] = [await this.device(id), await this.device(by), await this.account()];
142
+ if (!AccountCircle.waiting(device)) {
143
+ throw new RelayAccountError(409, 'This device is not waiting to be let in.');
144
+ }
145
+ if (!AccountCircle.admitted(endorser) || !(await RelayIdentityUtil.verify(endorser.sign, AccountCircle.text(account.id, device), signature))) {
146
+ throw new RelayAccountError(403, 'Only a device of the account lets another in, with its signature.');
147
+ }
148
+ await this.storage.put(`device:${id}`, { ...device, endorsement: { by, signature } });
149
+ return this.roster(undefined, now);
150
+ }
151
+ /** By a device let in, or the device itself, with its signature: a token alone removes nothing. */
152
+ async remove(id, by, signature, now) {
153
+ const device = await this.device(id);
154
+ if (device.removed) {
155
+ return this.roster(undefined, now);
156
+ }
157
+ const remover = by && RELAY_ID.test(by) ? await this.storage.get(`device:${by}`) : undefined;
158
+ const may = remover && (by === id ? AccountCircle.live(remover) : AccountCircle.admitted(remover));
159
+ if (!may || !(await RelayIdentityUtil.verify(remover.sign, AccountCircle.removal((await this.account()).id, id), signature))) {
160
+ throw new RelayAccountError(403, 'Only a device of the account removes another, with its signature.');
161
+ }
162
+ await this.storage.put(`device:${id}`, { ...device, removed: { by, signature, at: now } });
163
+ for (const key of (await this.storage.list({ prefix: 'mail:' })).keys()) {
164
+ const [, to, from] = key.split(':');
165
+ if (to === id || from === id) {
166
+ await this.storage.delete(key);
167
+ }
168
+ }
169
+ 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); });
170
+ for (const old of removed.slice(REMOVED_MAX)) {
171
+ await this.storage.delete(`device:${old.id}`);
172
+ }
173
+ return this.roster(undefined, now);
174
+ }
175
+ async send(mail, now) {
176
+ if (!mail ||
177
+ !MAIL_KINDS.has(mail.kind) ||
178
+ typeof mail.sealed !== 'string' ||
179
+ typeof mail.signature !== 'string' ||
180
+ mail.sealed.length > MAIL_MAX ||
181
+ (mail.kind === 'package') !== (typeof mail.topic === 'string' && TOPIC.test(mail.topic))) {
182
+ throw new RelayAccountError(400, 'Not a mail.');
183
+ }
184
+ const [from, to] = [await this.device(mail.from), await this.device(mail.to)];
185
+ if (!AccountCircle.live(from) || !AccountCircle.live(to)) {
186
+ throw new RelayAccountError(409, 'Mail goes between devices of the account.');
187
+ }
188
+ const { from: f, to: t, kind, topic, sealed, signature } = mail;
189
+ await this.storage.put(`mail:${t}:${f}:${kind}${topic ? `:${topic}` : ''}`, {
190
+ from: f,
191
+ to: t,
192
+ kind,
193
+ ...(topic ? { topic } : {}),
194
+ sealed,
195
+ signature,
196
+ at: now,
197
+ });
198
+ }
199
+ async mail(to) {
200
+ await this.device(to);
201
+ return [...(await this.storage.list({ prefix: `mail:${to}:` })).values()];
202
+ }
203
+ }
204
+ /**
205
+ * 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
206
+ * the handle: the device that began the sign-in holds it, as RFC 8628 has it; the relay keeps nothing of it.
207
+ */
208
+ export class RelayGitHubAccounts {
209
+ constructor(clientId = RelayGitHubAccounts.CLIENT_ID, site = 'https://github.com', api = 'https://api.github.com') {
210
+ this.clientId = clientId;
211
+ this.site = site;
212
+ this.api = api;
213
+ this.id = 'github';
214
+ this.name = 'GitHub';
215
+ }
216
+ async post(path, form) {
217
+ const response = await fetch(this.site + path, {
218
+ method: 'POST',
219
+ headers: { accept: 'application/json', 'content-type': 'application/x-www-form-urlencoded', 'user-agent': 'Ta' },
220
+ body: new URLSearchParams(form).toString(),
221
+ });
222
+ return (await response.json());
223
+ }
224
+ async start() {
225
+ var _a, _b, _c;
226
+ const answer = await this.post('/login/device/code', { client_id: this.clientId, scope: 'read:user' });
227
+ if (!answer.device_code || !answer.user_code || !answer.verification_uri) {
228
+ throw new RelayAccountError(502, `GitHub: ${(_a = answer.error_description) !== null && _a !== void 0 ? _a : 'no code'}`);
229
+ }
230
+ return {
231
+ handle: answer.device_code,
232
+ code: answer.user_code,
233
+ url: answer.verification_uri,
234
+ interval: Number((_b = answer.interval) !== null && _b !== void 0 ? _b : 5),
235
+ expiresIn: Number((_c = answer.expires_in) !== null && _c !== void 0 ? _c : 900),
236
+ };
237
+ }
238
+ async poll(handle) {
239
+ var _a, _b, _c, _d;
240
+ const token = await this.post('/login/oauth/access_token', {
241
+ client_id: this.clientId,
242
+ device_code: handle,
243
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
244
+ });
245
+ if (token.error === 'authorization_pending') {
246
+ return 'pending';
247
+ }
248
+ if (token.error === 'slow_down') {
249
+ return 'slowDown';
250
+ }
251
+ if (!token.access_token) {
252
+ 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'}`);
253
+ }
254
+ const user = (await (await fetch(`${this.api}/user`, { headers: { accept: 'application/json', authorization: `Bearer ${token.access_token}`, 'user-agent': 'Ta' } })).json());
255
+ if (!user.id) {
256
+ throw new RelayAccountError(502, 'GitHub did not say who signed in.');
257
+ }
258
+ 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) };
259
+ }
260
+ }
261
+ RelayGitHubAccounts.CLIENT_ID = 'Ov23lip46sRQDlDM1xt7';
262
+ const CORS = {
263
+ 'access-control-allow-origin': '*',
264
+ 'access-control-allow-headers': 'authorization, content-type',
265
+ 'access-control-allow-methods': 'GET, POST, OPTIONS',
266
+ 'access-control-max-age': '86400',
267
+ };
268
+ /**
269
+ * The account service over HTTP, the same in a Worker, `ta relay` and a gateway: `/v1/account/sign-in`,
270
+ * `/v1/account/sign-in/poll`, `/v1/account/providers` and `/v1/account/call`. Tokens go in a header, never a
271
+ * cookie, so any page may call it.
272
+ */
273
+ export class RelayAccounts {
274
+ constructor(options) {
275
+ this.options = options;
276
+ }
277
+ static json(value, status = 200) {
278
+ return new Response(JSON.stringify(value !== null && value !== void 0 ? value : null), { status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store', ...CORS } });
279
+ }
280
+ /** `<account id, base64url>.<secret>`: the account it is of, and what only its holder knows. */
281
+ static token(account) {
282
+ return `${RelayBytes.toBase64(new TextEncoder().encode(account))}.${RelayBytes.toBase64(RelayBytes.random(32))}`;
283
+ }
284
+ static accountOf(token) {
285
+ const [account, secret] = token.split('.');
286
+ try {
287
+ return account && secret ? new TextDecoder().decode(RelayBytes.fromBase64(account)) : undefined;
288
+ }
289
+ catch (_a) {
290
+ return undefined;
291
+ }
292
+ }
293
+ async handle(request) {
294
+ var _a, _b;
295
+ if (request.method === 'OPTIONS') {
296
+ return new Response(null, { status: 204, headers: CORS });
297
+ }
298
+ const path = new URL(request.url).pathname.slice(RELAY_ACCOUNT_PATH.length);
299
+ try {
300
+ if (path === 'providers' && request.method === 'GET') {
301
+ return RelayAccounts.json(this.options.authenticate ? [] : this.options.providers.map(({ id, name }) => ({ id, name })));
302
+ }
303
+ if (request.method !== 'POST') {
304
+ return RelayAccounts.json({ error: 'Not found.' }, 404);
305
+ }
306
+ const body = (await request.json().catch(() => ({})));
307
+ if (path === 'sign-in') {
308
+ return RelayAccounts.json(await this.provider(body.provider).start());
309
+ }
310
+ if (path === 'sign-in/poll') {
311
+ return RelayAccounts.json(await this.poll(body.provider, body.handle));
312
+ }
313
+ if (path === 'call') {
314
+ return RelayAccounts.json({ value: await this.call((_a = request.headers.get('authorization')) !== null && _a !== void 0 ? _a : '', body.op, body.args) });
315
+ }
316
+ return RelayAccounts.json({ error: 'Not found.' }, 404);
317
+ }
318
+ catch (error) {
319
+ const status = error instanceof RelayAccountError ? error.status : ((_b = error.status) !== null && _b !== void 0 ? _b : 500);
320
+ return RelayAccounts.json({ error: error instanceof Error ? error.message : String(error) }, status);
321
+ }
322
+ }
323
+ provider(id) {
324
+ const provider = this.options.authenticate ? undefined : this.options.providers.find(one => one.id === id);
325
+ if (!provider) {
326
+ throw new RelayAccountError(404, 'No such way to sign in here.');
327
+ }
328
+ return provider;
329
+ }
330
+ async poll(id, handle) {
331
+ if (typeof handle !== 'string' || !handle || handle.length > 200) {
332
+ throw new RelayAccountError(400, 'No sign-in to poll.');
333
+ }
334
+ const signedIn = await this.provider(id).poll(handle);
335
+ if (signedIn === 'pending' || signedIn === 'slowDown') {
336
+ return { status: 'pending' };
337
+ }
338
+ const token = RelayAccounts.token(signedIn.id);
339
+ await this.options.book(signedIn.id).handle({ op: 'issue', account: signedIn, hash: await RelayKeys.hash(token) });
340
+ return { status: 'done', token, account: signedIn };
341
+ }
342
+ async call(authorization, op, args) {
343
+ const token = authorization.replace(/^Bearer\s+/i, '');
344
+ if (!ACCOUNT_CALLS.includes(op)) {
345
+ throw new RelayAccountError(400, 'No such call.');
346
+ }
347
+ const request = { op: op, args: Array.isArray(args) ? args : [], max: this.options.maxDevices };
348
+ if (this.options.authenticate) {
349
+ const account = token ? await this.options.authenticate(token) : undefined;
350
+ if (!account) {
351
+ throw new RelayAccountError(401, 'Sign in again.');
352
+ }
353
+ return this.options.book(account.id).handle({ ...request, account });
354
+ }
355
+ const account = RelayAccounts.accountOf(token);
356
+ if (!account) {
357
+ throw new RelayAccountError(401, 'Sign in first.');
358
+ }
359
+ return this.options.book(account).handle({ ...request, hash: await RelayKeys.hash(token) });
360
+ }
361
+ }
362
+ /** The books of a `ta relay` or a gateway, in one process: the requests of one account one after another. */
363
+ export class RelayAccountBooks {
364
+ constructor(storage) {
365
+ this.storage = storage;
366
+ /** Any token names an account: a book that holds none once its requests are done is not kept. */
367
+ this.books = new Map();
368
+ }
369
+ book(account) {
370
+ let kept = this.books.get(account);
371
+ if (!kept) {
372
+ kept = { book: new RelayAccountBook(this.storage(account)), chain: Promise.resolve() };
373
+ this.books.set(account, kept);
374
+ }
375
+ const one = kept;
376
+ return {
377
+ handle: request => {
378
+ const done = one.chain.then(() => one.book.handle(request));
379
+ const next = done
380
+ .catch(() => undefined)
381
+ .then(async () => {
382
+ // Dropped only when nothing came after it, before or while it looked.
383
+ if (one.chain === next && !(await one.book.signedIn()) && one.chain === next && this.books.get(account) === one) {
384
+ this.books.delete(account);
385
+ }
386
+ });
387
+ one.chain = next;
388
+ return done;
389
+ },
390
+ };
391
+ }
392
+ }
393
+ //# sourceMappingURL=relay-accounts.js.map
@@ -5,6 +5,7 @@ export * from './relay-host.js';
5
5
  export * from './relay-hub-files.js';
6
6
  export * from './relay-memory-storage.js';
7
7
  export * from './relay-server.js';
8
+ export * from './relay-server-accounts.js';
8
9
  export * from './relay-store.js';
9
10
  export * from './relay-viewer.js';
10
11
  export * from './relays-file.js';
package/esm/node/index.js CHANGED
@@ -5,6 +5,7 @@ export * from './relay-host.js';
5
5
  export * from './relay-hub-files.js';
6
6
  export * from './relay-memory-storage.js';
7
7
  export * from './relay-server.js';
8
+ export * from './relay-server-accounts.js';
8
9
  export * from './relay-store.js';
9
10
  export * from './relay-viewer.js';
10
11
  export * from './relays-file.js';
@@ -0,0 +1,16 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { type RelayAccountProvider, RelayAccounts, type RelayAccountsOptions } from '../common/relay-accounts.js';
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
+ }