@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,54 @@
1
+ import { join } from 'node:path';
2
+ import { RelayAccountBooks, RelayAccounts, RelayGitHubAccounts } from '../common/relay-accounts.js';
3
+ import { RelayBytes } from '../common/relay-bytes.js';
4
+ import { FileRelayStorage } from './relay-file-storage.js';
5
+ import { MemoryHubStorage } from './relay-memory-storage.js';
6
+ /** What a call of the account service may hold. */
7
+ const MAX_BYTES = 64 * 1024;
8
+ /**
9
+ * The account service of `ta relay` (docs/design/ta-account.md), as the Worker answers it: the book of each account in
10
+ * a directory of its own under `data`, or in memory without one.
11
+ */
12
+ export class RelayServerAccounts {
13
+ /** `authenticate`: a gateway's, whose sign-in gives the tokens (RelayAccountsOptions.authenticate). */
14
+ constructor(data, options = {}) {
15
+ var _a;
16
+ const books = new RelayAccountBooks(account => data ? new FileRelayStorage(join(data, 'accounts', RelayBytes.toBase64(new TextEncoder().encode(account)))) : new MemoryHubStorage());
17
+ const providers = (_a = options.providers) !== null && _a !== void 0 ? _a : (options.authenticate ? [] : [new RelayGitHubAccounts()]);
18
+ this.accounts = new RelayAccounts({ book: account => books.book(account), providers, authenticate: options.authenticate });
19
+ }
20
+ /** Answers a request of RELAY_ACCOUNT_PATH; never throws, an unhandled rejection would end the relay. */
21
+ serve(request, response) {
22
+ this.answer(request, response).catch(() => {
23
+ if (!response.headersSent) {
24
+ response.writeHead(400);
25
+ }
26
+ response.end();
27
+ });
28
+ }
29
+ async answer(request, response) {
30
+ var _a;
31
+ const chunks = [];
32
+ let size = 0;
33
+ for await (const chunk of request) {
34
+ size += chunk.length;
35
+ if (size > MAX_BYTES) {
36
+ response.writeHead(413, { connection: 'close' }).end('Too large.\n');
37
+ return;
38
+ }
39
+ chunks.push(chunk);
40
+ }
41
+ const headers = new Headers();
42
+ for (const [name, value] of Object.entries(request.headers)) {
43
+ if (typeof value === 'string') {
44
+ headers.set(name, value);
45
+ }
46
+ }
47
+ const method = (_a = request.method) !== null && _a !== void 0 ? _a : 'GET';
48
+ const body = chunks.length && method !== 'GET' && method !== 'HEAD' ? Buffer.concat(chunks) : undefined;
49
+ const answer = await this.accounts.handle(new Request(`http://relay${request.url}`, { method, headers, body }));
50
+ response.writeHead(answer.status, Object.fromEntries(answer.headers));
51
+ response.end(Buffer.from(await answer.arrayBuffer()));
52
+ }
53
+ }
54
+ //# 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.js';
5
6
  import { RelayBlobs } from '../common/relay-blobs.js';
6
7
  import { RelayHub, type RelayHubWho } from '../common/relay-hub.js';
7
8
  import { RelayRoom } from '../common/relay-room.js';
8
9
  import { RelaySpot, type RelaySpotSocket, type RelaySpotWho } from '../common/relay-spot.js';
9
10
  import { FileRelayStorage } from './relay-file-storage.js';
10
11
  import { MemoryBlobStorage, MemoryHubStorage } from './relay-memory-storage.js';
12
+ import { RelayServerAccounts } from './relay-server-accounts.js';
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;
@@ -4,6 +4,7 @@ import { createServer } from 'node:http';
4
4
  import { join } from 'node:path';
5
5
  import { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
6
6
  import { TA_WELL_KNOWN_PATH, TaDeploymentUtil } from '@celljs/ta-protocol/lib/common/deployment-protocol';
7
+ import { RELAY_ACCOUNT_PATH } from '../common/relay-account.js';
7
8
  import { RelayBlobs } from '../common/relay-blobs.js';
8
9
  import { RelayHub } from '../common/relay-hub.js';
9
10
  import { RELAY_INFO_PATH, RelayInfoUtil } from '../common/relay-info.js';
@@ -14,6 +15,7 @@ import { RELAY_JOIN_PATH, RELAY_WEB_PATH } from '../common/relay-team.js';
14
15
  import { RelayWebUtil } from '../common/relay-web.js';
15
16
  import { FileRelayStorage } from './relay-file-storage.js';
16
17
  import { MemoryBlobStorage, MemoryHubStorage } from './relay-memory-storage.js';
18
+ import { RelayServerAccounts } from './relay-server-accounts.js';
17
19
  import { RelayViewer } from './relay-viewer.js';
18
20
  const WEBSOCKET = { maxPayload: 32 * 1024 * 1024, heartbeat: 30000 };
19
21
  const peer = (connection) => ({ send: text => connection.send(text), close: (code, reason) => connection.close(code, reason) });
@@ -35,6 +37,7 @@ export class RelayServer {
35
37
  this.spotTries = new Map();
36
38
  /** The address each connection to a spot came from. */
37
39
  this.spotAddresses = new WeakMap();
40
+ this.accounts = new RelayServerAccounts(options.data, { providers: options.accounts });
38
41
  if (options.data) {
39
42
  mkdirSync(options.data, { recursive: true, mode: 0o700 });
40
43
  try {
@@ -95,6 +98,10 @@ export class RelayServer {
95
98
  response.end(JSON.stringify(info));
96
99
  return;
97
100
  }
101
+ if (path.startsWith(RELAY_ACCOUNT_PATH)) {
102
+ this.accounts.serve(request, response);
103
+ return;
104
+ }
98
105
  if (path.startsWith(RELAY_BLOB_PATH)) {
99
106
  this.blob(path.slice(RELAY_BLOB_PATH.length), request, response).catch(() => {
100
107
  // 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. */
@@ -218,6 +218,7 @@ export class RelayStore {
218
218
  key: randomBytes(32).toString('base64url'),
219
219
  createdAt: now,
220
220
  ...(options.member ? { member: options.member } : {}),
221
+ ...(options.account ? { account: options.account } : {}),
221
222
  ...(options.expiresAt !== undefined ? { expiresAt: options.expiresAt } : {}),
222
223
  };
223
224
  config.devices = [...config.devices.filter(one => one.expiresAt === undefined || one.expiresAt > now), device];
@@ -1,4 +1,7 @@
1
1
  export * from './qr-code';
2
+ export * from './relay-account';
3
+ export * from './relay-account-client';
4
+ export * from './relay-accounts';
2
5
  export * from './relay-blobs';
3
6
  export * from './relay-bytes';
4
7
  export * from './relay-card';
@@ -15,6 +15,9 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./qr-code"), exports);
18
+ __exportStar(require("./relay-account"), exports);
19
+ __exportStar(require("./relay-account-client"), exports);
20
+ __exportStar(require("./relay-accounts"), exports);
18
21
  __exportStar(require("./relay-blobs"), exports);
19
22
  __exportStar(require("./relay-bytes"), exports);
20
23
  __exportStar(require("./relay-card"), exports);
@@ -0,0 +1,139 @@
1
+ import { type AccountCalls, type AccountCircleState, type AccountDevice, type AccountDeviceKind, type AccountName, type AccountRoster, type AccountSignInPoll, type AccountSignInStart } from './relay-account';
2
+ import { type RelayIdentity } from './relay-identity';
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
+ }
139
+ //# sourceMappingURL=relay-account-client.d.ts.map
@@ -0,0 +1,343 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AccountAgent = exports.AccountService = exports.AccountCallError = void 0;
4
+ const relay_account_1 = require("./relay-account");
5
+ const relay_identity_1 = require("./relay-identity");
6
+ /** The service said no: `status` 401 is a token no longer good, 403 this device removed. */
7
+ class AccountCallError extends Error {
8
+ constructor(status, message) {
9
+ super(message);
10
+ this.status = status;
11
+ }
12
+ }
13
+ exports.AccountCallError = AccountCallError;
14
+ /** The account service of a relay or a gateway, over fetch: the same in ta serve and a page. */
15
+ var AccountService;
16
+ (function (AccountService) {
17
+ /** How long the service is waited for: one out of reach (a company's network, away from it) answers nothing at all. */
18
+ AccountService.TIMEOUT_MS = 8000;
19
+ const wait = () => AbortSignal.timeout(AccountService.TIMEOUT_MS);
20
+ async function answer(response) {
21
+ var _a;
22
+ const body = (await response.json().catch(() => ({})));
23
+ if (!response.ok) {
24
+ throw new AccountCallError(response.status, (_a = body.error) !== null && _a !== void 0 ? _a : `The account service answered ${response.status}.`);
25
+ }
26
+ return body;
27
+ }
28
+ function base(service) {
29
+ return service.replace(/\/+$/, '') + relay_account_1.RELAY_ACCOUNT_PATH;
30
+ }
31
+ AccountService.base = base;
32
+ async function providers(service) {
33
+ return answer(await fetch(`${base(service)}providers`, { signal: wait() }));
34
+ }
35
+ AccountService.providers = providers;
36
+ async function start(service, provider) {
37
+ return answer(await fetch(`${base(service)}sign-in`, {
38
+ method: 'POST',
39
+ headers: { 'content-type': 'application/json' },
40
+ body: JSON.stringify({ provider }),
41
+ signal: wait(),
42
+ }));
43
+ }
44
+ AccountService.start = start;
45
+ async function poll(service, provider, handle) {
46
+ return answer(await fetch(`${base(service)}sign-in/poll`, {
47
+ method: 'POST',
48
+ headers: { 'content-type': 'application/json' },
49
+ body: JSON.stringify({ provider, handle }),
50
+ signal: wait(),
51
+ }));
52
+ }
53
+ AccountService.poll = poll;
54
+ /**
55
+ * The ways to sign in to an account: those of the relay (GitHub), and those of the gateways of deployments (a
56
+ * company's accounts), whose own sign-in gives the token; a gateway without the account service is left out.
57
+ */
58
+ async function ways(relay, gateways = []) {
59
+ const of = async (gateway) => {
60
+ const base = gateway.replace(/\/+$/, '');
61
+ const [accounts, signIn] = await Promise.all([
62
+ fetch(`${AccountService.base(base)}providers`, { signal: wait() }),
63
+ fetch(`${base}/sign-in`, { signal: wait() }),
64
+ ]);
65
+ if (!accounts.ok || !signIn.ok) {
66
+ return [];
67
+ }
68
+ const { providers } = (await signIn.json());
69
+ return (providers !== null && providers !== void 0 ? providers : []).map(({ id, name }) => ({ id, name, service: base, gateway: true }));
70
+ };
71
+ const found = await Promise.all([
72
+ providers(relay).then(list => list.map(({ id, name }) => ({ id, name, service: relay.replace(/\/+$/, '') }))),
73
+ ...[...new Set(gateways.filter(Boolean))].map(gateway => of(gateway)),
74
+ ].map(one => one.catch(() => [])));
75
+ return found.flat();
76
+ }
77
+ AccountService.ways = ways;
78
+ /** Begins signing in by `way`: the code the user enters on the page of `url`. */
79
+ async function begin(way, deviceName) {
80
+ if (!way.gateway) {
81
+ return start(way.service, way.id);
82
+ }
83
+ const given = await answer(await fetch(`${way.service}/sign-in/device`, { method: 'POST', body: JSON.stringify({ name: deviceName }), signal: wait() }));
84
+ return {
85
+ handle: given.device,
86
+ code: given.code,
87
+ url: `${way.service}/sign-in/${encodeURIComponent(way.id)}?device=${encodeURIComponent(given.code)}`,
88
+ interval: 2,
89
+ expiresIn: Math.max(60, Math.round((given.expiresAt - Date.now()) / 1000)),
90
+ };
91
+ }
92
+ AccountService.begin = begin;
93
+ /** One look at a sign-in begun by `way`. */
94
+ async function check(way, handle) {
95
+ if (!way.gateway) {
96
+ return poll(way.service, way.id, handle);
97
+ }
98
+ const state = await answer(await fetch(`${way.service}/sign-in/device/poll`, { method: 'POST', body: JSON.stringify({ device: handle }), signal: wait() }));
99
+ if (state.status === 'done' && state.token && state.account) {
100
+ return { status: 'done', token: state.token, account: { id: state.account, name: state.account } };
101
+ }
102
+ return state.status === 'expired' ? { status: 'failed', error: 'The sign-in ran out of time: begin it again.' } : { status: 'pending' };
103
+ }
104
+ AccountService.check = check;
105
+ /** The calls of an account, with a token of the service (or of the gateway it is part of). */
106
+ function calls(service, token) {
107
+ const call = async (op, args) => (await answer(await fetch(`${base(service)}call`, {
108
+ method: 'POST',
109
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
110
+ body: JSON.stringify({ op, args }),
111
+ signal: wait(),
112
+ }))).value;
113
+ return Object.fromEntries(relay_account_1.ACCOUNT_CALLS.map(op => [op, (...args) => call(op, args)]));
114
+ }
115
+ AccountService.calls = calls;
116
+ })(AccountService || (exports.AccountService = AccountService = {}));
117
+ /**
118
+ * A device of an account (docs/design/ta-account.md 4): says it is there, keeps whom it trusts, lets others in, makes and
119
+ * takes ways into computers through sealed mail. The same in ta serve and a page; what is particular comes in hooks.
120
+ */
121
+ class AccountAgent {
122
+ constructor(kept, hooks, calls) {
123
+ this.kept = kept;
124
+ this.hooks = hooks;
125
+ /** What was told last, by `<from>|<topic>`: a mail is kept until replaced, told once each time it changes. */
126
+ this.heard = new Map();
127
+ this.calls = calls !== null && calls !== void 0 ? calls : AccountService.calls(kept.service, kept.token);
128
+ }
129
+ /** A new device of `account`: its own keys, trusting itself alone. */
130
+ static async create(service, token, account, kind, name) {
131
+ const self = await relay_identity_1.RelayIdentityUtil.create(name);
132
+ return { service: service.replace(/\/+$/, ''), token, account, kind, self, circle: relay_account_1.AccountCircle.alone(self), pairings: {} };
133
+ }
134
+ get state() {
135
+ return this.kept;
136
+ }
137
+ async save(next) {
138
+ this.kept = next;
139
+ await this.hooks.save(next);
140
+ }
141
+ async guard(run) {
142
+ var _a, _b;
143
+ try {
144
+ return await run();
145
+ }
146
+ catch (error) {
147
+ if (error instanceof AccountCallError && (error.status === 401 || error.status === 403)) {
148
+ await ((_b = (_a = this.hooks).signedOut) === null || _b === void 0 ? void 0 : _b.call(_a, error.status === 401 ? 'token' : 'removed'));
149
+ }
150
+ throw error;
151
+ }
152
+ }
153
+ /** One round: be in the roster, trust whom to, let the trusted in to this computer, take ways into others. */
154
+ async sync() {
155
+ return this.guard(async () => {
156
+ var _a, _b, _c, _d;
157
+ const { self } = this.kept;
158
+ const name = this.hooks.name();
159
+ const host = (_b = (_a = this.hooks).host) === null || _b === void 0 ? void 0 : _b.call(_a);
160
+ let roster = await this.calls.roster(self.id);
161
+ const mine = roster.devices.find(one => one.id === self.id);
162
+ if (mine === null || mine === void 0 ? void 0 : mine.removed) {
163
+ throw new AccountCallError(403, 'This device was removed from the account.');
164
+ }
165
+ 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)) {
166
+ roster = await this.calls.join({ id: self.id, kind: this.kept.kind, name, sign: self.sign, box: self.box, ...(host ? { host } : {}) });
167
+ }
168
+ this.roster = roster;
169
+ await this.save({ ...this.kept, account: roster.account });
170
+ const me = roster.devices.find(one => one.id === self.id);
171
+ if ((me === null || me === void 0 ? void 0 : me.endorsement) && Object.keys(this.kept.circle.trusted).length === 1) {
172
+ await this.joinCircle(roster, me);
173
+ }
174
+ const circle = await relay_account_1.AccountCircle.update(this.kept.circle, roster);
175
+ if (JSON.stringify(circle) !== JSON.stringify(this.kept.circle)) {
176
+ await this.save({ ...this.kept, circle });
177
+ }
178
+ if (me && relay_account_1.AccountCircle.admitted(me)) {
179
+ await this.ways(roster);
180
+ }
181
+ return this.view();
182
+ });
183
+ }
184
+ /** Let in by `me.endorsement.by`: whom it trusts came sealed, signed by it; the device it let in trusts them too. */
185
+ async joinCircle(roster, me) {
186
+ const by = roster.devices.find(one => { var _a; return one.id === ((_a = me.endorsement) === null || _a === void 0 ? void 0 : _a.by); });
187
+ if (!by || !me.endorsement || !(await relay_identity_1.RelayIdentityUtil.verify(by.sign, relay_account_1.AccountCircle.text(roster.account.id, me), me.endorsement.signature))) {
188
+ return;
189
+ }
190
+ const mail = (await this.calls.mail(this.kept.self.id)).find(one => one.from === by.id && one.kind === 'circle');
191
+ const sent = mail ? await relay_account_1.AccountCircle.open(this.kept.self, by, mail) : undefined;
192
+ if (!(sent === null || sent === void 0 ? void 0 : sent.trusted)) {
193
+ return;
194
+ }
195
+ const trusted = { ...sent.trusted, [by.id]: { sign: by.sign, box: by.box }, ...this.kept.circle.trusted };
196
+ await this.save({ ...this.kept, circle: { trusted, removed: this.kept.circle.removed } });
197
+ }
198
+ /**
199
+ * The trusted devices in the roster, with the keys this device trusts them by: the service may list other keys under
200
+ * a trusted id, and mail is sealed to and checked against what was trusted, never what the service says now.
201
+ */
202
+ trusted(roster) {
203
+ const { circle, self } = this.kept;
204
+ return roster.devices
205
+ .filter(one => one.id !== self.id && relay_account_1.AccountCircle.live(one) && circle.trusted[one.id])
206
+ .map(one => ({ ...one, sign: circle.trusted[one.id].sign, box: circle.trusted[one.id].box }));
207
+ }
208
+ /** Ways in: made for the trusted (a computer), dropped for the rest; taken from trusted computers. */
209
+ async ways(roster) {
210
+ var _a, _b, _c, _d, _e, _f, _g, _h;
211
+ const trusted = this.trusted(roster);
212
+ const ids = new Set(trusted.map(one => one.id));
213
+ if (this.hooks.pair && this.hooks.paired) {
214
+ const paired = new Set(this.hooks.paired());
215
+ for (const id of paired) {
216
+ if (!ids.has(id)) {
217
+ await ((_b = (_a = this.hooks).unpair) === null || _b === void 0 ? void 0 : _b.call(_a, id));
218
+ }
219
+ }
220
+ for (const device of trusted) {
221
+ if (!paired.has(device.id)) {
222
+ const link = await this.hooks.pair(device);
223
+ await this.calls.send(await relay_account_1.AccountCircle.seal(this.kept.self, device, 'pairing', { link }));
224
+ }
225
+ }
226
+ }
227
+ const mail = await this.calls.mail(this.kept.self.id);
228
+ const pairings = {};
229
+ for (const one of mail) {
230
+ const from = trusted.find(device => device.id === one.from);
231
+ if (!from || (one.kind !== 'pairing' && one.kind !== 'package')) {
232
+ continue;
233
+ }
234
+ if (one.kind === 'package') {
235
+ const key = `${one.from}|${one.topic}`;
236
+ if (this.heard.get(key) !== one.sealed) {
237
+ const opened = await relay_account_1.AccountCircle.open(this.kept.self, from, one);
238
+ if (opened && one.topic) {
239
+ this.heard.set(key, one.sealed);
240
+ await ((_d = (_c = this.hooks).told) === null || _d === void 0 ? void 0 : _d.call(_c, from, one.topic, opened.value));
241
+ }
242
+ }
243
+ continue;
244
+ }
245
+ const opened = await relay_account_1.AccountCircle.open(this.kept.self, from, one);
246
+ if (typeof (opened === null || opened === void 0 ? void 0 : opened.link) !== 'string') {
247
+ continue;
248
+ }
249
+ pairings[from.id] = opened.link;
250
+ if (this.kept.pairings[from.id] !== opened.link) {
251
+ await ((_f = (_e = this.hooks).pairing) === null || _f === void 0 ? void 0 : _f.call(_e, from, opened.link));
252
+ }
253
+ }
254
+ for (const id of Object.keys(this.kept.pairings)) {
255
+ if (!pairings[id]) {
256
+ await ((_h = (_g = this.hooks).unpaired) === null || _h === void 0 ? void 0 : _h.call(_g, id));
257
+ }
258
+ }
259
+ if (JSON.stringify(pairings) !== JSON.stringify(this.kept.pairings)) {
260
+ await this.save({ ...this.kept, pairings });
261
+ }
262
+ }
263
+ async view(now = Date.now()) {
264
+ var _a;
265
+ const roster = (_a = this.roster) !== null && _a !== void 0 ? _a : (await this.guard(() => this.calls.roster(this.kept.self.id)));
266
+ const { self, circle } = this.kept;
267
+ const me = roster.devices.find(one => one.id === self.id);
268
+ const devices = [];
269
+ for (const device of roster.devices) {
270
+ if (!relay_account_1.AccountCircle.live(device)) {
271
+ continue;
272
+ }
273
+ const waiting = relay_account_1.AccountCircle.waiting(device);
274
+ const trusted = !!circle.trusted[device.id];
275
+ if (!trusted && !waiting) {
276
+ continue;
277
+ }
278
+ devices.push({
279
+ id: device.id,
280
+ kind: device.kind,
281
+ name: device.name,
282
+ self: device.id === self.id,
283
+ trusted,
284
+ waiting,
285
+ ...(waiting ? { code: await relay_account_1.AccountCircle.code(device) } : {}),
286
+ online: device.id === self.id || relay_account_1.AccountCircle.online(device, now),
287
+ seenAt: device.seenAt,
288
+ addedAt: device.addedAt,
289
+ });
290
+ }
291
+ return {
292
+ account: roster.account,
293
+ service: this.kept.service,
294
+ self: self.id,
295
+ waiting: !me || relay_account_1.AccountCircle.waiting(me) || (!!me.endorsement && Object.keys(circle.trusted).length === 1),
296
+ code: await relay_account_1.AccountCircle.code(self),
297
+ devices,
298
+ };
299
+ }
300
+ /** The devices of the account this one trusts, itself aside, as the service last listed them. */
301
+ devices() {
302
+ return this.roster ? this.trusted(this.roster) : [];
303
+ }
304
+ /** Says `value` to a trusted device of the account, sealed for it: a package on it hears it by `topic`. */
305
+ async tell(to, topic, value) {
306
+ const device = this.devices().find(one => one.id === to);
307
+ if (!device) {
308
+ throw new AccountCallError(404, 'No such device trusted in the account.');
309
+ }
310
+ await this.guard(async () => this.calls.send(await relay_account_1.AccountCircle.seal(this.kept.self, device, 'package', { value }, topic)));
311
+ }
312
+ /** Lets a waiting device in: signs it, and sends it whom this device trusts. */
313
+ async approve(id) {
314
+ return this.guard(async () => {
315
+ const roster = await this.calls.roster(this.kept.self.id);
316
+ const device = roster.devices.find(one => one.id === id);
317
+ if (!device || !relay_account_1.AccountCircle.waiting(device)) {
318
+ throw new AccountCallError(409, 'This device is not waiting to be let in.');
319
+ }
320
+ const signature = await relay_account_1.AccountCircle.endorse(this.kept.self, roster.account.id, device);
321
+ await this.calls.endorse(id, this.kept.self.id, signature);
322
+ await this.calls.send(await relay_account_1.AccountCircle.seal(this.kept.self, device, 'circle', { trusted: this.kept.circle.trusted }));
323
+ return this.sync();
324
+ });
325
+ }
326
+ /** Removes a device (one waiting that is not the user's, or one lost): every device drops it. */
327
+ async remove(id) {
328
+ return this.guard(async () => {
329
+ await this.calls.remove(id, this.kept.self.id, await relay_account_1.AccountCircle.remove(this.kept.self, this.kept.account.id, id));
330
+ return this.sync();
331
+ });
332
+ }
333
+ /** Leaves the account: removed from it, its token dropped. */
334
+ async signOut() {
335
+ const { self, account } = this.kept;
336
+ await relay_account_1.AccountCircle.remove(self, account.id, self.id)
337
+ .then(signature => this.calls.remove(self.id, self.id, signature))
338
+ .catch(() => undefined);
339
+ await this.calls.signOut().catch(() => undefined);
340
+ }
341
+ }
342
+ exports.AccountAgent = AccountAgent;
343
+ //# sourceMappingURL=relay-account-client.js.map