@celljs/ta-relay 4.18.0 → 4.20.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 (52) hide show
  1. package/esm/common/index.d.ts +3 -0
  2. package/esm/common/index.js +3 -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-hubs-connection.d.ts +2 -0
  10. package/esm/common/relay-hubs-connection.js +3 -0
  11. package/esm/common/relay-hubs-identity.d.ts +24 -2
  12. package/esm/common/relay-hubs-identity.js +81 -0
  13. package/esm/common/relay-identity.d.ts +7 -0
  14. package/esm/common/relay-identity.js +8 -0
  15. package/esm/common/relay-protocol.d.ts +7 -0
  16. package/esm/common/relay-protocol.js +7 -0
  17. package/esm/node/index.d.ts +1 -0
  18. package/esm/node/index.js +1 -0
  19. package/esm/node/relay-server-accounts.d.ts +16 -0
  20. package/esm/node/relay-server-accounts.js +54 -0
  21. package/esm/node/relay-server.d.ts +5 -0
  22. package/esm/node/relay-server.js +7 -0
  23. package/esm/node/relay-store.d.ts +3 -1
  24. package/esm/node/relay-store.js +1 -0
  25. package/lib/common/index.d.ts +3 -0
  26. package/lib/common/index.js +3 -0
  27. package/lib/common/relay-account-client.d.ts +139 -0
  28. package/lib/common/relay-account-client.js +343 -0
  29. package/lib/common/relay-account.d.ts +138 -0
  30. package/lib/common/relay-account.js +125 -0
  31. package/lib/common/relay-accounts.d.ts +108 -0
  32. package/lib/common/relay-accounts.js +401 -0
  33. package/lib/common/relay-hubs-connection.d.ts +2 -0
  34. package/lib/common/relay-hubs-connection.js +3 -0
  35. package/lib/common/relay-hubs-identity.d.ts +24 -2
  36. package/lib/common/relay-hubs-identity.js +81 -0
  37. package/lib/common/relay-identity.d.ts +7 -0
  38. package/lib/common/relay-identity.js +8 -0
  39. package/lib/common/relay-protocol.d.ts +7 -0
  40. package/lib/common/relay-protocol.js +8 -1
  41. package/lib/node/index.d.ts +1 -0
  42. package/lib/node/index.js +1 -0
  43. package/lib/node/relay-server-accounts.d.ts +17 -0
  44. package/lib/node/relay-server-accounts.js +58 -0
  45. package/lib/node/relay-server.d.ts +5 -0
  46. package/lib/node/relay-server.js +7 -0
  47. package/lib/node/relay-store.d.ts +3 -1
  48. package/lib/node/relay-store.js +1 -0
  49. package/package.json +3 -3
  50. package/viewer/join.html +6 -6
  51. package/viewer/page.html +12 -12
  52. package/viewer/room.html +13 -13
@@ -1,4 +1,7 @@
1
1
  export * from './qr-code.js';
2
+ export * from './relay-account.js';
3
+ export * from './relay-account-client.js';
4
+ export * from './relay-accounts.js';
2
5
  export * from './relay-blobs.js';
3
6
  export * from './relay-bytes.js';
4
7
  export * from './relay-card.js';
@@ -1,4 +1,7 @@
1
1
  export * from './qr-code.js';
2
+ export * from './relay-account.js';
3
+ export * from './relay-account-client.js';
4
+ export * from './relay-accounts.js';
2
5
  export * from './relay-blobs.js';
3
6
  export * from './relay-bytes.js';
4
7
  export * from './relay-card.js';
@@ -0,0 +1,138 @@
1
+ import { type AccountCalls, type AccountCircleState, type AccountDevice, type AccountDeviceKind, type AccountName, type AccountRoster, type AccountSignInPoll, type AccountSignInStart } from './relay-account.js';
2
+ import { type RelayIdentity } from './relay-identity.js';
3
+ /** The service said no: `status` 401 is a token no longer good, 403 this device removed. */
4
+ export declare class AccountCallError extends Error {
5
+ readonly status: number;
6
+ constructor(status: number, message: string);
7
+ }
8
+ /** The account service of a relay or a gateway, over fetch: the same in ta serve and a page. */
9
+ export declare namespace AccountService {
10
+ /** How long the service is waited for: one out of reach (a company's network, away from it) answers nothing at all. */
11
+ const TIMEOUT_MS = 8000;
12
+ function base(service: string): string;
13
+ function providers(service: string): Promise<{
14
+ id: string;
15
+ name: string;
16
+ }[]>;
17
+ function start(service: string, provider: string): Promise<AccountSignInStart>;
18
+ function poll(service: string, provider: string, handle: string): Promise<AccountSignInPoll>;
19
+ /**
20
+ * The ways to sign in to an account: those of the relay (GitHub), and those of the gateways of deployments (a
21
+ * company's accounts), whose own sign-in gives the token; a gateway without the account service is left out.
22
+ */
23
+ function ways(relay: string, gateways?: string[]): Promise<AccountWay[]>;
24
+ /** Begins signing in by `way`: the code the user enters on the page of `url`. */
25
+ function begin(way: AccountWay, deviceName: string): Promise<AccountSignInStart>;
26
+ /** One look at a sign-in begun by `way`. */
27
+ function check(way: AccountWay, handle: string): Promise<AccountSignInPoll>;
28
+ /** The calls of an account, with a token of the service (or of the gateway it is part of). */
29
+ function calls(service: string, token: string): AccountCalls;
30
+ }
31
+ /** A way to sign in to an account: a provider of a relay, or of a gateway (`gateway`), whose token is the account's. */
32
+ export interface AccountWay {
33
+ id: string;
34
+ name: string;
35
+ service: string;
36
+ gateway?: true;
37
+ }
38
+ /** What a device keeps of its account (`account.json` of ta serve, localStorage of a page): its keys and whom it trusts. */
39
+ export interface AccountKept {
40
+ /** The relay or the gateway the account is on. */
41
+ service: string;
42
+ token: string;
43
+ account: AccountName;
44
+ kind: AccountDeviceKind;
45
+ /** This device's own keys, made for the account: not the identity others know the user by. */
46
+ self: RelayIdentity;
47
+ circle: AccountCircleState;
48
+ /** The computers that sent this device a way in: their account device id, the pairing link. */
49
+ pairings: Record<string, string>;
50
+ }
51
+ /** A device of the account as a device sees it. */
52
+ export interface AccountDeviceView {
53
+ id: string;
54
+ kind: AccountDeviceKind;
55
+ name: string;
56
+ self: boolean;
57
+ /** Let in, and trusted by this device. */
58
+ trusted: boolean;
59
+ /** Waiting to be let in: `code` is what it shows, for the user to compare. */
60
+ waiting: boolean;
61
+ code?: string;
62
+ online: boolean;
63
+ seenAt: number;
64
+ addedAt: number;
65
+ }
66
+ export interface AccountView {
67
+ account: AccountName;
68
+ service: string;
69
+ self: string;
70
+ /** This device waits to be let in: `code` is what the device that lets it in shows too. */
71
+ waiting: boolean;
72
+ code: string;
73
+ devices: AccountDeviceView[];
74
+ }
75
+ /** What a device of an account does on its side, besides keeping `AccountKept`. */
76
+ export interface AccountHooks {
77
+ save(kept: AccountKept): void | Promise<void>;
78
+ name(): string;
79
+ /** A computer: where it hangs on a relay, so that devices reach it. */
80
+ host?(): {
81
+ relay: string;
82
+ id: string;
83
+ } | undefined;
84
+ /** A computer: a way in for a trusted device of the account (a pairing link), made once. */
85
+ pair?(device: AccountDevice): Promise<string>;
86
+ /** A computer: the devices of the account it made a way in for. */
87
+ paired?(): string[];
88
+ /** A computer: no way in any more for this device of the account. */
89
+ unpair?(device: string): void | Promise<void>;
90
+ /** A way into a computer of the account came: `link` pairs with it. */
91
+ pairing?(from: AccountDevice, link: string): void | Promise<void>;
92
+ /** A computer that sent a way in is no longer trusted, or removed. */
93
+ unpaired?(from: string): void | Promise<void>;
94
+ /** What a package on another device of the account said (AccountAgent.tell), new or changed. */
95
+ told?(from: AccountDevice, topic: string, value: unknown): void | Promise<void>;
96
+ /** This device was removed from the account, or its token no longer works: it is signed out. */
97
+ signedOut?(reason: 'removed' | 'token'): void | Promise<void>;
98
+ }
99
+ /**
100
+ * A device of an account (docs/design/ta-account.md 4): says it is there, keeps whom it trusts, lets others in, makes and
101
+ * takes ways into computers through sealed mail. The same in ta serve and a page; what is particular comes in hooks.
102
+ */
103
+ export declare class AccountAgent {
104
+ protected kept: AccountKept;
105
+ protected readonly hooks: AccountHooks;
106
+ protected roster?: AccountRoster;
107
+ protected readonly calls: AccountCalls;
108
+ /** What was told last, by `<from>|<topic>`: a mail is kept until replaced, told once each time it changes. */
109
+ protected heard: Map<string, string>;
110
+ constructor(kept: AccountKept, hooks: AccountHooks, calls?: AccountCalls);
111
+ /** A new device of `account`: its own keys, trusting itself alone. */
112
+ static create(service: string, token: string, account: AccountName, kind: AccountDeviceKind, name: string): Promise<AccountKept>;
113
+ get state(): AccountKept;
114
+ protected save(next: AccountKept): Promise<void>;
115
+ protected guard<T>(run: () => Promise<T>): Promise<T>;
116
+ /** One round: be in the roster, trust whom to, let the trusted in to this computer, take ways into others. */
117
+ sync(): Promise<AccountView>;
118
+ /** Let in by `me.endorsement.by`: whom it trusts came sealed, signed by it; the device it let in trusts them too. */
119
+ protected joinCircle(roster: AccountRoster, me: AccountDevice): Promise<void>;
120
+ /**
121
+ * The trusted devices in the roster, with the keys this device trusts them by: the service may list other keys under
122
+ * a trusted id, and mail is sealed to and checked against what was trusted, never what the service says now.
123
+ */
124
+ protected trusted(roster: AccountRoster): AccountDevice[];
125
+ /** Ways in: made for the trusted (a computer), dropped for the rest; taken from trusted computers. */
126
+ protected ways(roster: AccountRoster): Promise<void>;
127
+ view(now?: number): Promise<AccountView>;
128
+ /** The devices of the account this one trusts, itself aside, as the service last listed them. */
129
+ devices(): AccountDevice[];
130
+ /** Says `value` to a trusted device of the account, sealed for it: a package on it hears it by `topic`. */
131
+ tell(to: string, topic: string, value: unknown): Promise<void>;
132
+ /** Lets a waiting device in: signs it, and sends it whom this device trusts. */
133
+ approve(id: string): Promise<AccountView>;
134
+ /** Removes a device (one waiting that is not the user's, or one lost): every device drops it. */
135
+ remove(id: string): Promise<AccountView>;
136
+ /** Leaves the account: removed from it, its token dropped. */
137
+ signOut(): Promise<void>;
138
+ }
@@ -0,0 +1,338 @@
1
+ import { ACCOUNT_CALLS, AccountCircle, RELAY_ACCOUNT_PATH, } from './relay-account.js';
2
+ import { RelayIdentityUtil } from './relay-identity.js';
3
+ /** The service said no: `status` 401 is a token no longer good, 403 this device removed. */
4
+ export class AccountCallError extends Error {
5
+ constructor(status, message) {
6
+ super(message);
7
+ this.status = status;
8
+ }
9
+ }
10
+ /** The account service of a relay or a gateway, over fetch: the same in ta serve and a page. */
11
+ export var AccountService;
12
+ (function (AccountService) {
13
+ /** How long the service is waited for: one out of reach (a company's network, away from it) answers nothing at all. */
14
+ AccountService.TIMEOUT_MS = 8000;
15
+ const wait = () => AbortSignal.timeout(AccountService.TIMEOUT_MS);
16
+ async function answer(response) {
17
+ var _a;
18
+ const body = (await response.json().catch(() => ({})));
19
+ if (!response.ok) {
20
+ throw new AccountCallError(response.status, (_a = body.error) !== null && _a !== void 0 ? _a : `The account service answered ${response.status}.`);
21
+ }
22
+ return body;
23
+ }
24
+ function base(service) {
25
+ return service.replace(/\/+$/, '') + RELAY_ACCOUNT_PATH;
26
+ }
27
+ AccountService.base = base;
28
+ async function providers(service) {
29
+ return answer(await fetch(`${base(service)}providers`, { signal: wait() }));
30
+ }
31
+ AccountService.providers = providers;
32
+ async function start(service, provider) {
33
+ return answer(await fetch(`${base(service)}sign-in`, {
34
+ method: 'POST',
35
+ headers: { 'content-type': 'application/json' },
36
+ body: JSON.stringify({ provider }),
37
+ signal: wait(),
38
+ }));
39
+ }
40
+ AccountService.start = start;
41
+ async function poll(service, provider, handle) {
42
+ return answer(await fetch(`${base(service)}sign-in/poll`, {
43
+ method: 'POST',
44
+ headers: { 'content-type': 'application/json' },
45
+ body: JSON.stringify({ provider, handle }),
46
+ signal: wait(),
47
+ }));
48
+ }
49
+ AccountService.poll = poll;
50
+ /**
51
+ * The ways to sign in to an account: those of the relay (GitHub), and those of the gateways of deployments (a
52
+ * company's accounts), whose own sign-in gives the token; a gateway without the account service is left out.
53
+ */
54
+ async function ways(relay, gateways = []) {
55
+ const of = async (gateway) => {
56
+ const base = gateway.replace(/\/+$/, '');
57
+ const [accounts, signIn] = await Promise.all([
58
+ fetch(`${AccountService.base(base)}providers`, { signal: wait() }),
59
+ fetch(`${base}/sign-in`, { signal: wait() }),
60
+ ]);
61
+ if (!accounts.ok || !signIn.ok) {
62
+ return [];
63
+ }
64
+ const { providers } = (await signIn.json());
65
+ return (providers !== null && providers !== void 0 ? providers : []).map(({ id, name }) => ({ id, name, service: base, gateway: true }));
66
+ };
67
+ const found = await Promise.all([
68
+ providers(relay).then(list => list.map(({ id, name }) => ({ id, name, service: relay.replace(/\/+$/, '') }))),
69
+ ...[...new Set(gateways.filter(Boolean))].map(gateway => of(gateway)),
70
+ ].map(one => one.catch(() => [])));
71
+ return found.flat();
72
+ }
73
+ AccountService.ways = ways;
74
+ /** Begins signing in by `way`: the code the user enters on the page of `url`. */
75
+ async function begin(way, deviceName) {
76
+ if (!way.gateway) {
77
+ return start(way.service, way.id);
78
+ }
79
+ const given = await answer(await fetch(`${way.service}/sign-in/device`, { method: 'POST', body: JSON.stringify({ name: deviceName }), signal: wait() }));
80
+ return {
81
+ handle: given.device,
82
+ code: given.code,
83
+ url: `${way.service}/sign-in/${encodeURIComponent(way.id)}?device=${encodeURIComponent(given.code)}`,
84
+ interval: 2,
85
+ expiresIn: Math.max(60, Math.round((given.expiresAt - Date.now()) / 1000)),
86
+ };
87
+ }
88
+ AccountService.begin = begin;
89
+ /** One look at a sign-in begun by `way`. */
90
+ async function check(way, handle) {
91
+ if (!way.gateway) {
92
+ return poll(way.service, way.id, handle);
93
+ }
94
+ const state = await answer(await fetch(`${way.service}/sign-in/device/poll`, { method: 'POST', body: JSON.stringify({ device: handle }), signal: wait() }));
95
+ if (state.status === 'done' && state.token && state.account) {
96
+ return { status: 'done', token: state.token, account: { id: state.account, name: state.account } };
97
+ }
98
+ return state.status === 'expired' ? { status: 'failed', error: 'The sign-in ran out of time: begin it again.' } : { status: 'pending' };
99
+ }
100
+ AccountService.check = check;
101
+ /** The calls of an account, with a token of the service (or of the gateway it is part of). */
102
+ function calls(service, token) {
103
+ const call = async (op, args) => (await answer(await fetch(`${base(service)}call`, {
104
+ method: 'POST',
105
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
106
+ body: JSON.stringify({ op, args }),
107
+ signal: wait(),
108
+ }))).value;
109
+ return Object.fromEntries(ACCOUNT_CALLS.map(op => [op, (...args) => call(op, args)]));
110
+ }
111
+ AccountService.calls = calls;
112
+ })(AccountService || (AccountService = {}));
113
+ /**
114
+ * A device of an account (docs/design/ta-account.md 4): says it is there, keeps whom it trusts, lets others in, makes and
115
+ * takes ways into computers through sealed mail. The same in ta serve and a page; what is particular comes in hooks.
116
+ */
117
+ export class AccountAgent {
118
+ constructor(kept, hooks, calls) {
119
+ this.kept = kept;
120
+ this.hooks = hooks;
121
+ /** What was told last, by `<from>|<topic>`: a mail is kept until replaced, told once each time it changes. */
122
+ this.heard = new Map();
123
+ this.calls = calls !== null && calls !== void 0 ? calls : AccountService.calls(kept.service, kept.token);
124
+ }
125
+ /** A new device of `account`: its own keys, trusting itself alone. */
126
+ static async create(service, token, account, kind, name) {
127
+ const self = await RelayIdentityUtil.create(name);
128
+ return { service: service.replace(/\/+$/, ''), token, account, kind, self, circle: AccountCircle.alone(self), pairings: {} };
129
+ }
130
+ get state() {
131
+ return this.kept;
132
+ }
133
+ async save(next) {
134
+ this.kept = next;
135
+ await this.hooks.save(next);
136
+ }
137
+ async guard(run) {
138
+ var _a, _b;
139
+ try {
140
+ return await run();
141
+ }
142
+ catch (error) {
143
+ if (error instanceof AccountCallError && (error.status === 401 || error.status === 403)) {
144
+ await ((_b = (_a = this.hooks).signedOut) === null || _b === void 0 ? void 0 : _b.call(_a, error.status === 401 ? 'token' : 'removed'));
145
+ }
146
+ throw error;
147
+ }
148
+ }
149
+ /** One round: be in the roster, trust whom to, let the trusted in to this computer, take ways into others. */
150
+ async sync() {
151
+ return this.guard(async () => {
152
+ var _a, _b, _c, _d;
153
+ const { self } = this.kept;
154
+ const name = this.hooks.name();
155
+ const host = (_b = (_a = this.hooks).host) === null || _b === void 0 ? void 0 : _b.call(_a);
156
+ let roster = await this.calls.roster(self.id);
157
+ const mine = roster.devices.find(one => one.id === self.id);
158
+ if (mine === null || mine === void 0 ? void 0 : mine.removed) {
159
+ throw new AccountCallError(403, 'This device was removed from the account.');
160
+ }
161
+ if (!mine || mine.name !== name || ((_c = mine.host) === null || _c === void 0 ? void 0 : _c.relay) !== (host === null || host === void 0 ? void 0 : host.relay) || ((_d = mine.host) === null || _d === void 0 ? void 0 : _d.id) !== (host === null || host === void 0 ? void 0 : host.id)) {
162
+ roster = await this.calls.join({ id: self.id, kind: this.kept.kind, name, sign: self.sign, box: self.box, ...(host ? { host } : {}) });
163
+ }
164
+ this.roster = roster;
165
+ await this.save({ ...this.kept, account: roster.account });
166
+ const me = roster.devices.find(one => one.id === self.id);
167
+ if ((me === null || me === void 0 ? void 0 : me.endorsement) && Object.keys(this.kept.circle.trusted).length === 1) {
168
+ await this.joinCircle(roster, me);
169
+ }
170
+ const circle = await AccountCircle.update(this.kept.circle, roster);
171
+ if (JSON.stringify(circle) !== JSON.stringify(this.kept.circle)) {
172
+ await this.save({ ...this.kept, circle });
173
+ }
174
+ if (me && AccountCircle.admitted(me)) {
175
+ await this.ways(roster);
176
+ }
177
+ return this.view();
178
+ });
179
+ }
180
+ /** Let in by `me.endorsement.by`: whom it trusts came sealed, signed by it; the device it let in trusts them too. */
181
+ async joinCircle(roster, me) {
182
+ const by = roster.devices.find(one => { var _a; return one.id === ((_a = me.endorsement) === null || _a === void 0 ? void 0 : _a.by); });
183
+ if (!by || !me.endorsement || !(await RelayIdentityUtil.verify(by.sign, AccountCircle.text(roster.account.id, me), me.endorsement.signature))) {
184
+ return;
185
+ }
186
+ const mail = (await this.calls.mail(this.kept.self.id)).find(one => one.from === by.id && one.kind === 'circle');
187
+ const sent = mail ? await AccountCircle.open(this.kept.self, by, mail) : undefined;
188
+ if (!(sent === null || sent === void 0 ? void 0 : sent.trusted)) {
189
+ return;
190
+ }
191
+ const trusted = { ...sent.trusted, [by.id]: { sign: by.sign, box: by.box }, ...this.kept.circle.trusted };
192
+ await this.save({ ...this.kept, circle: { trusted, removed: this.kept.circle.removed } });
193
+ }
194
+ /**
195
+ * The trusted devices in the roster, with the keys this device trusts them by: the service may list other keys under
196
+ * a trusted id, and mail is sealed to and checked against what was trusted, never what the service says now.
197
+ */
198
+ trusted(roster) {
199
+ const { circle, self } = this.kept;
200
+ return roster.devices
201
+ .filter(one => one.id !== self.id && AccountCircle.live(one) && circle.trusted[one.id])
202
+ .map(one => ({ ...one, sign: circle.trusted[one.id].sign, box: circle.trusted[one.id].box }));
203
+ }
204
+ /** Ways in: made for the trusted (a computer), dropped for the rest; taken from trusted computers. */
205
+ async ways(roster) {
206
+ var _a, _b, _c, _d, _e, _f, _g, _h;
207
+ const trusted = this.trusted(roster);
208
+ const ids = new Set(trusted.map(one => one.id));
209
+ if (this.hooks.pair && this.hooks.paired) {
210
+ const paired = new Set(this.hooks.paired());
211
+ for (const id of paired) {
212
+ if (!ids.has(id)) {
213
+ await ((_b = (_a = this.hooks).unpair) === null || _b === void 0 ? void 0 : _b.call(_a, id));
214
+ }
215
+ }
216
+ for (const device of trusted) {
217
+ if (!paired.has(device.id)) {
218
+ const link = await this.hooks.pair(device);
219
+ await this.calls.send(await AccountCircle.seal(this.kept.self, device, 'pairing', { link }));
220
+ }
221
+ }
222
+ }
223
+ const mail = await this.calls.mail(this.kept.self.id);
224
+ const pairings = {};
225
+ for (const one of mail) {
226
+ const from = trusted.find(device => device.id === one.from);
227
+ if (!from || (one.kind !== 'pairing' && one.kind !== 'package')) {
228
+ continue;
229
+ }
230
+ if (one.kind === 'package') {
231
+ const key = `${one.from}|${one.topic}`;
232
+ if (this.heard.get(key) !== one.sealed) {
233
+ const opened = await AccountCircle.open(this.kept.self, from, one);
234
+ if (opened && one.topic) {
235
+ this.heard.set(key, one.sealed);
236
+ await ((_d = (_c = this.hooks).told) === null || _d === void 0 ? void 0 : _d.call(_c, from, one.topic, opened.value));
237
+ }
238
+ }
239
+ continue;
240
+ }
241
+ const opened = await AccountCircle.open(this.kept.self, from, one);
242
+ if (typeof (opened === null || opened === void 0 ? void 0 : opened.link) !== 'string') {
243
+ continue;
244
+ }
245
+ pairings[from.id] = opened.link;
246
+ if (this.kept.pairings[from.id] !== opened.link) {
247
+ await ((_f = (_e = this.hooks).pairing) === null || _f === void 0 ? void 0 : _f.call(_e, from, opened.link));
248
+ }
249
+ }
250
+ for (const id of Object.keys(this.kept.pairings)) {
251
+ if (!pairings[id]) {
252
+ await ((_h = (_g = this.hooks).unpaired) === null || _h === void 0 ? void 0 : _h.call(_g, id));
253
+ }
254
+ }
255
+ if (JSON.stringify(pairings) !== JSON.stringify(this.kept.pairings)) {
256
+ await this.save({ ...this.kept, pairings });
257
+ }
258
+ }
259
+ async view(now = Date.now()) {
260
+ var _a;
261
+ const roster = (_a = this.roster) !== null && _a !== void 0 ? _a : (await this.guard(() => this.calls.roster(this.kept.self.id)));
262
+ const { self, circle } = this.kept;
263
+ const me = roster.devices.find(one => one.id === self.id);
264
+ const devices = [];
265
+ for (const device of roster.devices) {
266
+ if (!AccountCircle.live(device)) {
267
+ continue;
268
+ }
269
+ const waiting = AccountCircle.waiting(device);
270
+ const trusted = !!circle.trusted[device.id];
271
+ if (!trusted && !waiting) {
272
+ continue;
273
+ }
274
+ devices.push({
275
+ id: device.id,
276
+ kind: device.kind,
277
+ name: device.name,
278
+ self: device.id === self.id,
279
+ trusted,
280
+ waiting,
281
+ ...(waiting ? { code: await AccountCircle.code(device) } : {}),
282
+ online: device.id === self.id || AccountCircle.online(device, now),
283
+ seenAt: device.seenAt,
284
+ addedAt: device.addedAt,
285
+ });
286
+ }
287
+ return {
288
+ account: roster.account,
289
+ service: this.kept.service,
290
+ self: self.id,
291
+ waiting: !me || AccountCircle.waiting(me) || (!!me.endorsement && Object.keys(circle.trusted).length === 1),
292
+ code: await AccountCircle.code(self),
293
+ devices,
294
+ };
295
+ }
296
+ /** The devices of the account this one trusts, itself aside, as the service last listed them. */
297
+ devices() {
298
+ return this.roster ? this.trusted(this.roster) : [];
299
+ }
300
+ /** Says `value` to a trusted device of the account, sealed for it: a package on it hears it by `topic`. */
301
+ async tell(to, topic, value) {
302
+ const device = this.devices().find(one => one.id === to);
303
+ if (!device) {
304
+ throw new AccountCallError(404, 'No such device trusted in the account.');
305
+ }
306
+ await this.guard(async () => this.calls.send(await AccountCircle.seal(this.kept.self, device, 'package', { value }, topic)));
307
+ }
308
+ /** Lets a waiting device in: signs it, and sends it whom this device trusts. */
309
+ async approve(id) {
310
+ return this.guard(async () => {
311
+ const roster = await this.calls.roster(this.kept.self.id);
312
+ const device = roster.devices.find(one => one.id === id);
313
+ if (!device || !AccountCircle.waiting(device)) {
314
+ throw new AccountCallError(409, 'This device is not waiting to be let in.');
315
+ }
316
+ const signature = await AccountCircle.endorse(this.kept.self, roster.account.id, device);
317
+ await this.calls.endorse(id, this.kept.self.id, signature);
318
+ await this.calls.send(await AccountCircle.seal(this.kept.self, device, 'circle', { trusted: this.kept.circle.trusted }));
319
+ return this.sync();
320
+ });
321
+ }
322
+ /** Removes a device (one waiting that is not the user's, or one lost): every device drops it. */
323
+ async remove(id) {
324
+ return this.guard(async () => {
325
+ await this.calls.remove(id, this.kept.self.id, await AccountCircle.remove(this.kept.self, this.kept.account.id, id));
326
+ return this.sync();
327
+ });
328
+ }
329
+ /** Leaves the account: removed from it, its token dropped. */
330
+ async signOut() {
331
+ const { self, account } = this.kept;
332
+ await AccountCircle.remove(self, account.id, self.id)
333
+ .then(signature => this.calls.remove(self.id, self.id, signature))
334
+ .catch(() => undefined);
335
+ await this.calls.signOut().catch(() => undefined);
336
+ }
337
+ }
338
+ //# sourceMappingURL=relay-account-client.js.map
@@ -0,0 +1,137 @@
1
+ import { type RelayIdentity } from './relay-identity.js';
2
+ /** The account service of a relay or a gateway (docs/design/ta-account.md): the devices of one user, and their mail. */
3
+ export declare const RELAY_ACCOUNT_PATH = "/v1/account/";
4
+ /** Devices of an account at most, removed ones aside: `RELAY_ACCOUNT_MAX_DEVICES` of the service changes it. */
5
+ export declare const RELAY_ACCOUNT_MAX_DEVICES = 20;
6
+ /** A device seen within this is online: computers say they are there every minute. */
7
+ export declare const RELAY_ACCOUNT_ONLINE_MS: number;
8
+ export type AccountDeviceKind = 'computer' | 'phone' | 'browser';
9
+ export interface AccountName {
10
+ /** `github:<id>`, `iam:<user>`: the provider and who the user is there. */
11
+ id: string;
12
+ /** What the user is called there, to show. */
13
+ name: string;
14
+ }
15
+ /** One device of the user, as the service keeps it: public keys only. */
16
+ export interface AccountDevice {
17
+ /** RelayIdentityUtil.id of its keys: its own keys, not the identity others know the user by. */
18
+ id: string;
19
+ kind: AccountDeviceKind;
20
+ name: string;
21
+ /** ECDSA P-256, raw base64url. */
22
+ sign: string;
23
+ /** ECDH P-256, raw base64url. */
24
+ box: string;
25
+ /** A computer: the relay it hangs on and its host id there. */
26
+ host?: {
27
+ relay: string;
28
+ id: string;
29
+ };
30
+ /** The first device of the account: in without anyone letting it in. */
31
+ root?: true;
32
+ /** Let in by a device of the account: its id and signature of AccountCircle.text. */
33
+ endorsement?: {
34
+ by: string;
35
+ signature: string;
36
+ };
37
+ /** Removed: by which device, with its signature of AccountCircle.removal, when. Kept, so that what it signed can still be told apart. */
38
+ removed?: {
39
+ by?: string;
40
+ signature?: string;
41
+ at: number;
42
+ };
43
+ addedAt: number;
44
+ seenAt: number;
45
+ }
46
+ export interface AccountRoster {
47
+ account: AccountName;
48
+ devices: AccountDevice[];
49
+ }
50
+ /**
51
+ * What a device is sent by another, sealed for it alone and signed by the sender: whom it trusts (`circle`), a way into a
52
+ * computer (`pairing`), or what a package of Ta says to the same package on another computer (`package`, by `topic`).
53
+ */
54
+ export type AccountMailKind = 'circle' | 'pairing' | 'package';
55
+ export interface AccountMail {
56
+ from: string;
57
+ to: string;
58
+ kind: AccountMailKind;
59
+ /** Of a `package` mail: the package and what about, one mail kept of each. */
60
+ topic?: string;
61
+ sealed: string;
62
+ signature: string;
63
+ at: number;
64
+ }
65
+ /** What a device asks of its account, with its token (RelayAccounts). */
66
+ export interface AccountCalls {
67
+ roster(device?: string): Promise<AccountRoster>;
68
+ /** Adds the device, or says it is there again (its name, its host). */
69
+ join(device: Pick<AccountDevice, 'id' | 'kind' | 'name' | 'sign' | 'box' | 'host'>): Promise<AccountRoster>;
70
+ endorse(id: string, by: string, signature: string): Promise<AccountRoster>;
71
+ /** Removes `id`, said by `by` (a device let in, or `id` itself) with its signature of AccountCircle.removal. */
72
+ remove(id: string, by: string, signature: string): Promise<AccountRoster>;
73
+ send(mail: Omit<AccountMail, 'at'>): Promise<void>;
74
+ mail(to: string): Promise<AccountMail[]>;
75
+ signOut(): Promise<void>;
76
+ }
77
+ export type AccountCallName = keyof AccountCalls;
78
+ export declare const ACCOUNT_CALLS: readonly AccountCallName[];
79
+ /** A sign-in begun: open `url`, enter `code`; `handle` is what the device polls with. */
80
+ export interface AccountSignInStart {
81
+ handle: string;
82
+ code: string;
83
+ url: string;
84
+ interval: number;
85
+ expiresIn: number;
86
+ }
87
+ export type AccountSignInPoll = {
88
+ status: 'pending';
89
+ } | {
90
+ status: 'done';
91
+ token: string;
92
+ account: AccountName;
93
+ } | {
94
+ status: 'failed';
95
+ error: string;
96
+ };
97
+ /** What a device keeps of the devices it trusts (docs/design/ta-account.md 5). */
98
+ export interface AccountCircleState {
99
+ trusted: Record<string, {
100
+ sign: string;
101
+ box: string;
102
+ }>;
103
+ /** Removed once: never trusted again, whatever the service says later. */
104
+ removed: string[];
105
+ }
106
+ /** The trust of the devices of an account, kept by each device: the service holds keys, never says who to trust. */
107
+ export declare namespace AccountCircle {
108
+ /** What a device signs to let another in. */
109
+ function text(account: string, device: Pick<AccountDevice, 'id' | 'kind' | 'sign' | 'box'>): string;
110
+ /** Six digits both devices show, the user checks they are the same: they come from the keys of the new one. */
111
+ function code(device: Pick<AccountDevice, 'sign' | 'box'>): Promise<string>;
112
+ function live(device: AccountDevice): boolean;
113
+ /** In, by the service: the first one, or let in by someone. Who trusts it is each device's own. */
114
+ function admitted(device: AccountDevice): boolean;
115
+ /** Waiting for a device of the account to let it in. */
116
+ function waiting(device: AccountDevice): boolean;
117
+ /** A device trusting itself alone: the first one, or one not let in yet. */
118
+ function alone(self: Pick<AccountDevice, 'id' | 'sign' | 'box'>): AccountCircleState;
119
+ /**
120
+ * Who to trust now: those trusted before and not removed, and those a trusted device let in with a good signature,
121
+ * until no more. A device the service adds without a signature of one of them is never trusted.
122
+ */
123
+ function update(state: AccountCircleState, roster: AccountRoster): Promise<AccountCircleState>;
124
+ function endorse(self: RelayIdentity, account: string, device: AccountDevice): Promise<string>;
125
+ /** What a device signs to remove one of the account, itself or another. */
126
+ function removal(account: string, id: string): string;
127
+ function remove(self: RelayIdentity, account: string, id: string): Promise<string>;
128
+ /** `value` sealed for `to` and signed by `self`: the service carries it, never reads it. */
129
+ function seal(self: RelayIdentity, to: Pick<AccountDevice, 'id' | 'box'>, kind: AccountMailKind, value: unknown, topic?: string): Promise<Omit<AccountMail, 'at'>>;
130
+ /** What `mail` holds, when it is for `self` and signed by `sender`; undefined otherwise. */
131
+ function open<T>(self: RelayIdentity, sender: {
132
+ sign: string;
133
+ box: string;
134
+ }, mail: AccountMail): Promise<T | undefined>;
135
+ /** Whether a device is online, from when it was last there. */
136
+ function online(device: AccountDevice, now?: number): boolean;
137
+ }