@eduwork/dsh-remote-access 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -6447,6 +6447,188 @@ function createHostAdapter(dsh, distIndex) {
6447
6447
  };
6448
6448
  }
6449
6449
 
6450
+ // src/protocol/close-codes.ts
6451
+ var Close = {
6452
+ normal: 1e3,
6453
+ /** Malformed or unexpected message, failed decryption, oversized frame. */
6454
+ protocolError: 4400,
6455
+ /** Relay: unknown access key, invalid ID Token or Host registration signature, or the account's Host limit reached. */
6456
+ unauthorized: 4401,
6457
+ /** Host: the device was rejected or revoked; the reason was sent encrypted first. */
6458
+ forbidden: 4403,
6459
+ /** Relay: no Host is registered under the requested id. */
6460
+ hostOffline: 4404,
6461
+ /** Handshake, accept or heartbeat deadline passed, or the ID Token a Host registered with expired. */
6462
+ timeout: 4408,
6463
+ /** Relay: a newer verified registration took over this Host id. */
6464
+ replaced: 4409,
6465
+ /** Relay: the other end of this connection closed. */
6466
+ peerClosed: 4410,
6467
+ /** Relay: the Host speaks a protocol version this relay does not serve. */
6468
+ upgradeRequired: 4426,
6469
+ /** Rate, size or backlog limit exceeded; a Host retries later. */
6470
+ overLimit: 4429,
6471
+ /** Relay is shutting down or under maintenance. */
6472
+ unavailable: 4503
6473
+ };
6474
+
6475
+ // src/relay-link/link.ts
6476
+ var RelayLink = class {
6477
+ #options;
6478
+ #control;
6479
+ /** The registration being renewed, kept until the new one is in place. */
6480
+ #retiring;
6481
+ /** The next ping or reconnect. */
6482
+ #timer;
6483
+ #pongDeadline;
6484
+ #renewal;
6485
+ /** When the credential of the current registration expires, if it does (Unix seconds). */
6486
+ #expiresAt;
6487
+ #failures = 0;
6488
+ #stopped = true;
6489
+ constructor(options) {
6490
+ this.#options = {
6491
+ pingMs: 25e3,
6492
+ pongMs: 1e4,
6493
+ backoffMs: [1e3, 2e3, 5e3, 1e4, 3e4, 6e4],
6494
+ renewBeforeMs: 5 * 6e4,
6495
+ renewAfterMs: 3e4,
6496
+ ...options
6497
+ };
6498
+ }
6499
+ start() {
6500
+ this.#stopped = false;
6501
+ this.#connect();
6502
+ }
6503
+ stop() {
6504
+ this.#stopped = true;
6505
+ this.#drop();
6506
+ this.#options.onState({ state: "stopped" });
6507
+ }
6508
+ #connect() {
6509
+ if (this.#retiring === void 0) this.#options.onState({ state: "connecting" });
6510
+ const control = new WebSocket(this.#url(RELAY_PATHS.host));
6511
+ this.#control = control;
6512
+ let expiresAt;
6513
+ control.addEventListener("message", ({ data }) => {
6514
+ const message = typeof data === "string" ? parseControl(data) : void 0;
6515
+ if (message?.t === "connect" && typeof message.id === "string") return this.#open(message.id);
6516
+ if (this.#control !== control) return;
6517
+ if (message?.t === "challenge" && typeof message.nonce === "string") {
6518
+ void Promise.all([this.#options.credential(), signRegistration(this.#options.identity.signingKey, this.#options.relay, message.nonce)]).then(([admission, sig]) => {
6519
+ if (this.#control !== control) return;
6520
+ if (admission === void 0) return this.#halt({ state: "lapsed" });
6521
+ expiresAt = admission.expiresAt;
6522
+ control.send(JSON.stringify({ t: "register", protocol: PROTOCOL, hostId: this.#options.identity.hostId, sig, ...admission.credential }));
6523
+ }, (error51) => this.#control === control && this.#failed(`no credential: ${error51.message}`));
6524
+ } else if (message?.t === "registered") {
6525
+ this.#failures = 0;
6526
+ this.#retiring?.close();
6527
+ this.#retiring = void 0;
6528
+ this.#options.onState({ state: "online" });
6529
+ this.#ping(control);
6530
+ if (expiresAt !== void 0 && expiresAt > (this.#expiresAt ?? 0)) {
6531
+ const { renewBeforeMs, renewAfterMs } = this.#options;
6532
+ this.#renewal = setTimeout(() => this.#renew(), Math.max(expiresAt * 1e3 - Date.now() - renewBeforeMs, renewAfterMs));
6533
+ }
6534
+ this.#expiresAt = expiresAt;
6535
+ } else if (message?.t === "pong") {
6536
+ clearTimeout(this.#pongDeadline);
6537
+ this.#ping(control);
6538
+ } else {
6539
+ control.close(Close.protocolError, "unexpected relay message");
6540
+ }
6541
+ });
6542
+ control.addEventListener("close", ({ code, reason }) => {
6543
+ if (this.#control !== control) return;
6544
+ if (code === Close.unauthorized || code === Close.upgradeRequired) this.#halt({ state: "refused", code, reason });
6545
+ else if (code === Close.replaced) this.#halt({ state: "replaced" });
6546
+ else this.#failed(reason || `closed (${code})`);
6547
+ });
6548
+ }
6549
+ /** Ping the relay after a pause; a missing pong means the path is dead even if the socket has not noticed. */
6550
+ #ping(control) {
6551
+ this.#timer = setTimeout(() => {
6552
+ control.send(JSON.stringify({ t: "ping" }));
6553
+ this.#pongDeadline = setTimeout(() => this.#retry("relay stopped answering"), this.#options.pongMs);
6554
+ }, this.#options.pingMs);
6555
+ }
6556
+ /** Register again on a new control socket; the relay closes the current one once the new one is in place. */
6557
+ #renew() {
6558
+ clearTimeout(this.#timer);
6559
+ clearTimeout(this.#pongDeadline);
6560
+ this.#retiring = this.#control;
6561
+ this.#connect();
6562
+ }
6563
+ /** The control socket failed before or after registering; a renewal falls back on the registration it was to replace. */
6564
+ #failed(reason) {
6565
+ const retiring = this.#retiring;
6566
+ if (retiring === void 0 || retiring.readyState !== WebSocket.OPEN) return this.#retry(reason);
6567
+ const control = this.#control;
6568
+ this.#control = retiring;
6569
+ this.#retiring = void 0;
6570
+ control?.close();
6571
+ this.#ping(retiring);
6572
+ const delays = this.#options.backoffMs;
6573
+ this.#renewal = setTimeout(() => this.#renew(), delays[Math.min(this.#failures++, delays.length - 1)]);
6574
+ }
6575
+ #open(id) {
6576
+ const socket = new WebSocket(this.#url(RELAY_PATHS.accept));
6577
+ socket.addEventListener("open", () => {
6578
+ socket.send(JSON.stringify({ t: "accept", id }));
6579
+ this.#options.accept(socket);
6580
+ }, { once: true });
6581
+ }
6582
+ #retry(reason) {
6583
+ this.#drop();
6584
+ if (this.#stopped) return;
6585
+ const delays = this.#options.backoffMs;
6586
+ const delay = delays[Math.min(this.#failures++, delays.length - 1)];
6587
+ this.#options.onState({ state: "offline", reason, retryAt: Date.now() + delay });
6588
+ this.#timer = setTimeout(() => this.#connect(), delay);
6589
+ }
6590
+ #halt(state) {
6591
+ this.#drop();
6592
+ this.#stopped = true;
6593
+ this.#options.onState(state);
6594
+ }
6595
+ /** Abandon the control socket, and one being renewed; their later events are ignored. */
6596
+ #drop() {
6597
+ clearTimeout(this.#timer);
6598
+ clearTimeout(this.#pongDeadline);
6599
+ clearTimeout(this.#renewal);
6600
+ const control = this.#control, retiring = this.#retiring;
6601
+ this.#control = void 0;
6602
+ this.#retiring = void 0;
6603
+ this.#expiresAt = void 0;
6604
+ control?.close();
6605
+ retiring?.close();
6606
+ }
6607
+ #url(path) {
6608
+ const url2 = new URL(path, this.#options.relay);
6609
+ url2.protocol = url2.protocol === "https:" ? "wss:" : "ws:";
6610
+ return url2.href;
6611
+ }
6612
+ };
6613
+ function probe(options, signal, timeoutMs = 1e4) {
6614
+ if (signal.aborted) return Promise.resolve({ state: "stopped" });
6615
+ return new Promise((resolve2) => {
6616
+ const settle = (state) => {
6617
+ clearTimeout(timer);
6618
+ queueMicrotask(() => link.stop());
6619
+ resolve2(state);
6620
+ };
6621
+ const timer = setTimeout(() => settle({ state: "offline", reason: "timed out", retryAt: Date.now() }), timeoutMs);
6622
+ const link = new RelayLink({
6623
+ ...options,
6624
+ accept: (socket) => socket.close(),
6625
+ onState: (state) => state.state !== "connecting" && state.state !== "stopped" && settle(state)
6626
+ });
6627
+ signal.addEventListener("abort", () => settle({ state: "stopped" }), { once: true });
6628
+ link.start();
6629
+ });
6630
+ }
6631
+
6450
6632
  // src/connections/compression.ts
6451
6633
  import { promisify } from "node:util";
6452
6634
  import { gzip } from "node:zlib";
@@ -6482,31 +6664,6 @@ function compressPages(adapter) {
6482
6664
  };
6483
6665
  }
6484
6666
 
6485
- // src/protocol/close-codes.ts
6486
- var Close = {
6487
- normal: 1e3,
6488
- /** Malformed or unexpected message, failed decryption, oversized frame. */
6489
- protocolError: 4400,
6490
- /** Relay: unknown access key, invalid ID Token or Host registration signature, or the account's Host limit reached. */
6491
- unauthorized: 4401,
6492
- /** Host: the device was rejected or revoked; the reason was sent encrypted first. */
6493
- forbidden: 4403,
6494
- /** Relay: no Host is registered under the requested id. */
6495
- hostOffline: 4404,
6496
- /** Handshake, accept or heartbeat deadline passed, or the ID Token a Host registered with expired. */
6497
- timeout: 4408,
6498
- /** Relay: a newer verified registration took over this Host id. */
6499
- replaced: 4409,
6500
- /** Relay: the other end of this connection closed. */
6501
- peerClosed: 4410,
6502
- /** Relay: the Host speaks a protocol version this relay does not serve. */
6503
- upgradeRequired: 4426,
6504
- /** Rate, size or backlog limit exceeded; a Host retries later. */
6505
- overLimit: 4429,
6506
- /** Relay is shutting down or under maintenance. */
6507
- unavailable: 4503
6508
- };
6509
-
6510
6667
  // src/protocol/body.ts
6511
6668
  var WINDOW = 1024 * 1024;
6512
6669
  var CHUNK = 64e3;
@@ -7331,145 +7488,6 @@ function refuse(channel, reason) {
7331
7488
  return void 0;
7332
7489
  }
7333
7490
 
7334
- // src/relay-link/link.ts
7335
- var RelayLink = class {
7336
- #options;
7337
- #control;
7338
- /** The registration being renewed, kept until the new one is in place. */
7339
- #retiring;
7340
- /** The next ping or reconnect. */
7341
- #timer;
7342
- #pongDeadline;
7343
- #renewal;
7344
- /** When the credential of the current registration expires, if it does (Unix seconds). */
7345
- #expiresAt;
7346
- #failures = 0;
7347
- #stopped = true;
7348
- constructor(options) {
7349
- this.#options = {
7350
- pingMs: 25e3,
7351
- pongMs: 1e4,
7352
- backoffMs: [1e3, 2e3, 5e3, 1e4, 3e4, 6e4],
7353
- renewBeforeMs: 5 * 6e4,
7354
- renewAfterMs: 3e4,
7355
- ...options
7356
- };
7357
- }
7358
- start() {
7359
- this.#stopped = false;
7360
- this.#connect();
7361
- }
7362
- stop() {
7363
- this.#stopped = true;
7364
- this.#drop();
7365
- this.#options.onState({ state: "stopped" });
7366
- }
7367
- #connect() {
7368
- if (this.#retiring === void 0) this.#options.onState({ state: "connecting" });
7369
- const control = new WebSocket(this.#url(RELAY_PATHS.host));
7370
- this.#control = control;
7371
- let expiresAt;
7372
- control.addEventListener("message", ({ data }) => {
7373
- const message = typeof data === "string" ? parseControl(data) : void 0;
7374
- if (message?.t === "connect" && typeof message.id === "string") return this.#open(message.id);
7375
- if (this.#control !== control) return;
7376
- if (message?.t === "challenge" && typeof message.nonce === "string") {
7377
- void Promise.all([this.#options.credential(), signRegistration(this.#options.identity.signingKey, this.#options.relay, message.nonce)]).then(([admission, sig]) => {
7378
- if (this.#control !== control) return;
7379
- if (admission === void 0) return this.#halt({ state: "lapsed" });
7380
- expiresAt = admission.expiresAt;
7381
- control.send(JSON.stringify({ t: "register", protocol: PROTOCOL, hostId: this.#options.identity.hostId, sig, ...admission.credential }));
7382
- }, (error51) => this.#control === control && this.#failed(`no credential: ${error51.message}`));
7383
- } else if (message?.t === "registered") {
7384
- this.#failures = 0;
7385
- this.#retiring?.close();
7386
- this.#retiring = void 0;
7387
- this.#options.onState({ state: "online" });
7388
- this.#ping(control);
7389
- if (expiresAt !== void 0 && expiresAt > (this.#expiresAt ?? 0)) {
7390
- const { renewBeforeMs, renewAfterMs } = this.#options;
7391
- this.#renewal = setTimeout(() => this.#renew(), Math.max(expiresAt * 1e3 - Date.now() - renewBeforeMs, renewAfterMs));
7392
- }
7393
- this.#expiresAt = expiresAt;
7394
- } else if (message?.t === "pong") {
7395
- clearTimeout(this.#pongDeadline);
7396
- this.#ping(control);
7397
- } else {
7398
- control.close(Close.protocolError, "unexpected relay message");
7399
- }
7400
- });
7401
- control.addEventListener("close", ({ code, reason }) => {
7402
- if (this.#control !== control) return;
7403
- if (code === Close.unauthorized || code === Close.upgradeRequired) this.#halt({ state: "refused", code, reason });
7404
- else if (code === Close.replaced) this.#halt({ state: "replaced" });
7405
- else this.#failed(reason || `closed (${code})`);
7406
- });
7407
- }
7408
- /** Ping the relay after a pause; a missing pong means the path is dead even if the socket has not noticed. */
7409
- #ping(control) {
7410
- this.#timer = setTimeout(() => {
7411
- control.send(JSON.stringify({ t: "ping" }));
7412
- this.#pongDeadline = setTimeout(() => this.#retry("relay stopped answering"), this.#options.pongMs);
7413
- }, this.#options.pingMs);
7414
- }
7415
- /** Register again on a new control socket; the relay closes the current one once the new one is in place. */
7416
- #renew() {
7417
- clearTimeout(this.#timer);
7418
- clearTimeout(this.#pongDeadline);
7419
- this.#retiring = this.#control;
7420
- this.#connect();
7421
- }
7422
- /** The control socket failed before or after registering; a renewal falls back on the registration it was to replace. */
7423
- #failed(reason) {
7424
- const retiring = this.#retiring;
7425
- if (retiring === void 0 || retiring.readyState !== WebSocket.OPEN) return this.#retry(reason);
7426
- const control = this.#control;
7427
- this.#control = retiring;
7428
- this.#retiring = void 0;
7429
- control?.close();
7430
- this.#ping(retiring);
7431
- const delays = this.#options.backoffMs;
7432
- this.#renewal = setTimeout(() => this.#renew(), delays[Math.min(this.#failures++, delays.length - 1)]);
7433
- }
7434
- #open(id) {
7435
- const socket = new WebSocket(this.#url(RELAY_PATHS.accept));
7436
- socket.addEventListener("open", () => {
7437
- socket.send(JSON.stringify({ t: "accept", id }));
7438
- this.#options.accept(socket);
7439
- }, { once: true });
7440
- }
7441
- #retry(reason) {
7442
- this.#drop();
7443
- if (this.#stopped) return;
7444
- const delays = this.#options.backoffMs;
7445
- const delay = delays[Math.min(this.#failures++, delays.length - 1)];
7446
- this.#options.onState({ state: "offline", reason, retryAt: Date.now() + delay });
7447
- this.#timer = setTimeout(() => this.#connect(), delay);
7448
- }
7449
- #halt(state) {
7450
- this.#drop();
7451
- this.#stopped = true;
7452
- this.#options.onState(state);
7453
- }
7454
- /** Abandon the control socket, and one being renewed; their later events are ignored. */
7455
- #drop() {
7456
- clearTimeout(this.#timer);
7457
- clearTimeout(this.#pongDeadline);
7458
- clearTimeout(this.#renewal);
7459
- const control = this.#control, retiring = this.#retiring;
7460
- this.#control = void 0;
7461
- this.#retiring = void 0;
7462
- this.#expiresAt = void 0;
7463
- control?.close();
7464
- retiring?.close();
7465
- }
7466
- #url(path) {
7467
- const url2 = new URL(path, this.#options.relay);
7468
- url2.protocol = url2.protocol === "https:" ? "wss:" : "ws:";
7469
- return url2.href;
7470
- }
7471
- };
7472
-
7473
7491
  // src/remote-access.ts
7474
7492
  var HANDSHAKE_MS = 1e4;
7475
7493
  var RemoteAccess = class {
@@ -22098,18 +22116,21 @@ var codec2 = (name, schema) => Object.freeze({
22098
22116
  schema
22099
22117
  });
22100
22118
  var parameter = (name, schema) => Object.freeze({ name, wire: name, source: "json", codec: codec2(name, schema) });
22101
- var method = (name, parameters = []) => ({
22119
+ var method = (name, parameters = [], result = "PanelStatus") => ({
22102
22120
  id: `${pkg}#remoteDevices/${name}`,
22103
22121
  service: "remoteDevices",
22104
22122
  namespace: "remoteDevices",
22105
22123
  method: name,
22106
22124
  invocation: { kind: "direct" },
22107
22125
  parameters,
22108
- result: codec2("PanelStatus", external_exports.unknown()),
22126
+ result: codec2(result, external_exports.unknown()),
22109
22127
  sourceLocation: { file: "lib/index.js", line: 1, column: 1 }
22110
22128
  });
22111
22129
  var descriptors = [
22112
22130
  method("status"),
22131
+ method("retry"),
22132
+ method("test", [], "RelayTest"),
22133
+ method("signIn", [], "SignInPage"),
22113
22134
  method("createInvite"),
22114
22135
  method("cancelInvite"),
22115
22136
  method("decide", [parameter("key", external_exports.string()), parameter("approved", external_exports.boolean())]),
@@ -22122,9 +22143,11 @@ var Config = z2.object({
22122
22143
  relay: z2.string().default("").volatile(),
22123
22144
  /** Shown to devices; the computer's name when empty. */
22124
22145
  hostName: z2.string().default("").volatile(),
22146
+ /** With an organization set, use its relay and sign-in rather than the relay and access key above. */
22147
+ useOrganization: z2.boolean().default(true).volatile(),
22125
22148
  /** `index.html` of the published frontend; found the way the official web app finds it when empty. */
22126
22149
  distIndex: z2.string().default(""),
22127
- /** Set by a distribution, not the settings page: when `relay` is set, it replaces the relay and the access key above. */
22150
+ /** Set by a distribution, not the settings page: when `relay` is set, it is offered instead of the relay and the access key above. */
22128
22151
  organization: z2.object({
22129
22152
  relay: z2.string().default(""),
22130
22153
  /** The dsh-oidc profile whose sign-in admits this Host. */
@@ -22133,8 +22156,8 @@ var Config = z2.object({
22133
22156
  });
22134
22157
  var STATE = () => dshHomePath("plugins", "dsh-remote-access", "state.json");
22135
22158
  var loadContext = AsyncLocalStorage.snapshot();
22136
- var _revoke_dec, _decide_dec, _cancelInvite_dec, _createInvite_dec, _status_dec, _a3, _init;
22137
- var RemoteDevices = class extends (_a3 = TypertRemoteService, _status_dec = [Remote], _createInvite_dec = [Remote], _cancelInvite_dec = [Remote], _decide_dec = [Remote], _revoke_dec = [Remote], _a3) {
22159
+ var _revoke_dec, _decide_dec, _cancelInvite_dec, _createInvite_dec, _signIn_dec, _test_dec, _retry_dec, _status_dec, _a3, _init;
22160
+ var RemoteDevices = class extends (_a3 = TypertRemoteService, _status_dec = [Remote], _retry_dec = [Remote], _test_dec = [Remote], _signIn_dec = [Remote], _createInvite_dec = [Remote], _cancelInvite_dec = [Remote], _decide_dec = [Remote], _revoke_dec = [Remote], _a3) {
22138
22161
  constructor(ctx, config2) {
22139
22162
  super(ctx, "remoteDevices");
22140
22163
  __runInitializers(_init, 5, this);
@@ -22144,18 +22167,28 @@ var RemoteDevices = class extends (_a3 = TypertRemoteService, _status_dec = [Rem
22144
22167
  __publicField(this, "logger");
22145
22168
  /** Restarts run one after another; methods wait for the latest. */
22146
22169
  __publicField(this, "settled", Promise.resolve());
22170
+ __publicField(this, "restartLater");
22147
22171
  __publicField(this, "disposed", false);
22148
22172
  __publicField(this, "failed", false);
22149
22173
  __publicField(this, "signedOut", false);
22174
+ /** This Host's identity and devices, opened once for remote access and relay tests alike, so they never create two. */
22175
+ __publicField(this, "store");
22176
+ /** Relay tests in progress. A probe would take over the registration of a link starting meanwhile, so a start stops them. */
22177
+ __publicField(this, "probes", /* @__PURE__ */ new Set());
22150
22178
  __publicField(this, "organization");
22151
22179
  __publicField(this, "access");
22152
22180
  __publicField(this, "accounts");
22153
22181
  this.config = config2;
22154
22182
  this.dsh = ctx;
22155
22183
  this.logger = ctx.logger("eduwork-remote-access");
22156
- const restart = () => {
22157
- this.settled = loadContext(() => this.settled.then(() => this.restart()));
22158
- };
22184
+ const restart = this.restartLater = () => loadContext(() => {
22185
+ const start = () => {
22186
+ this.settled = this.settled.then(() => this.restart());
22187
+ };
22188
+ const hmr = ctx.get("hmr");
22189
+ if (hmr === void 0) start();
22190
+ else hmr.executing.exit(start);
22191
+ });
22159
22192
  ctx.on("loader/volatile-update", restart);
22160
22193
  ctx.on("credentials/reference-updated", (ref) => ref === ACCESS_KEY_REF && restart());
22161
22194
  const { oidcProfileId } = config2.organization;
@@ -22184,6 +22217,44 @@ var RemoteDevices = class extends (_a3 = TypertRemoteService, _status_dec = [Rem
22184
22217
  if (this.signedOut) return { state: "sign-in", ...organization };
22185
22218
  return { state: this.failed ? "failed" : "off", ...organization };
22186
22219
  }
22220
+ async retry() {
22221
+ this.restartLater();
22222
+ return this.status();
22223
+ }
22224
+ async test() {
22225
+ const probing = new AbortController();
22226
+ this.probes.add(probing);
22227
+ try {
22228
+ return await this.testRelay(probing.signal);
22229
+ } finally {
22230
+ this.probes.delete(probing);
22231
+ }
22232
+ }
22233
+ async testRelay(signal) {
22234
+ await this.settled;
22235
+ const route = await this.route(await this.account());
22236
+ if (route === void 0) return { state: "unconfigured" };
22237
+ if (route === "sign-in") return { state: route };
22238
+ const relay = relayBase(route.relay);
22239
+ const answered = relay !== void 0 && await fetch(new URL("healthz", relay), { signal: AbortSignal.timeout(1e4) }).then((response) => response.ok, () => false);
22240
+ if (!answered) return { state: "unreachable" };
22241
+ if (signal.aborted) return { state: "reached", link: this.runningLink() ?? { state: "stopped" } };
22242
+ const { identity } = await this.openStore();
22243
+ const running = this.runningLink();
22244
+ if (running !== void 0) return { state: "reached", link: running };
22245
+ const link = await probe({ relay, credential: route.credential, identity }, signal);
22246
+ if (link.state === "lapsed") this.organization = { ...this.organization, signedIn: false };
22247
+ return { state: "reached", link: this.runningLink() ?? link };
22248
+ }
22249
+ /** The state of remote access's own link, while it runs. */
22250
+ runningLink() {
22251
+ return this.access?.status().link;
22252
+ }
22253
+ async signIn() {
22254
+ const { accounts } = this;
22255
+ if (accounts === void 0) throw new Error(`sign-in "${this.config.organization.oidcProfileId}" is not available`);
22256
+ return (await accounts.begin(this.config.organization.oidcProfileId)).authorizationURL;
22257
+ }
22187
22258
  async createInvite() {
22188
22259
  (await this.running()).createInvite();
22189
22260
  return this.status();
@@ -22206,33 +22277,26 @@ var RemoteDevices = class extends (_a3 = TypertRemoteService, _status_dec = [Rem
22206
22277
  return this.access;
22207
22278
  }
22208
22279
  async restart() {
22280
+ this.stopProbes();
22209
22281
  this.access?.stop();
22210
22282
  this.access = void 0;
22211
22283
  this.failed = false;
22212
22284
  this.signedOut = false;
22213
- const { enabled, hostName, distIndex, organization } = this.config;
22214
- const { accounts } = this, profileID = organization.oidcProfileId;
22215
- const managed = organization.relay !== "";
22216
- const relay = managed ? organization.relay : this.config.relay.get();
22217
- this.organization = managed ? { name: profileID, relay } : void 0;
22218
22285
  try {
22219
- const account = managed ? await accounts?.status(profileID) : void 0;
22220
- if (account !== void 0) this.organization = { name: account.displayName, relay };
22221
- if (this.disposed || !enabled.get() || relay === "") return;
22222
- let credential;
22223
- if (!managed) credential = await this.accessKey();
22224
- else if (accounts === void 0) throw new Error(`sign-in "${profileID}" is not available`);
22225
- else if (account.state === "connected") credential = member(accounts, profileID);
22226
- else this.signedOut = true;
22227
- if (credential === void 0) return;
22286
+ const account = await this.account();
22287
+ if (this.disposed || !this.config.enabled.get()) return;
22288
+ const route = await this.route(account);
22289
+ if (route === "sign-in") this.signedOut = true;
22290
+ if (typeof route !== "object") return;
22228
22291
  const access = new RemoteAccess({
22229
- adapter: createHostAdapter(this.dsh, distIndex || frontendIndex()),
22230
- store: await HostStore.open(STATE()),
22231
- relay,
22232
- credential,
22233
- hostName: hostName.get() || hostname3(),
22292
+ adapter: createHostAdapter(this.dsh, this.config.distIndex || frontendIndex()),
22293
+ store: await this.openStore(),
22294
+ relay: route.relay,
22295
+ credential: route.credential,
22296
+ hostName: this.config.hostName.get() || hostname3(),
22234
22297
  warn: (message) => this.logger.warn(message)
22235
22298
  });
22299
+ this.stopProbes();
22236
22300
  access.start();
22237
22301
  this.access = access;
22238
22302
  } catch (error51) {
@@ -22240,6 +22304,38 @@ var RemoteDevices = class extends (_a3 = TypertRemoteService, _status_dec = [Rem
22240
22304
  this.failed = true;
22241
22305
  }
22242
22306
  }
22307
+ openStore() {
22308
+ return this.store ??= HostStore.open(STATE()).catch((error51) => {
22309
+ this.store = void 0;
22310
+ throw error51;
22311
+ });
22312
+ }
22313
+ stopProbes() {
22314
+ for (const probing of this.probes) probing.abort();
22315
+ }
22316
+ /** The organization's sign-in, when the distribution set an organization and dsh-oidc runs; also what the settings page shows of it. */
22317
+ async account() {
22318
+ const { relay, oidcProfileId } = this.config.organization;
22319
+ if (relay === "") {
22320
+ this.organization = void 0;
22321
+ return void 0;
22322
+ }
22323
+ const account = await this.accounts?.status(oidcProfileId).catch((error51) => void this.logger.warn(error51.message));
22324
+ this.organization = { name: account?.displayName ?? oidcProfileId, relay, signedIn: account?.state === "connected" };
22325
+ return account;
22326
+ }
22327
+ /** Where this Host registers and what admits it there; none until the relay and the access key are set, `sign-in` until the organization's sign-in is. */
22328
+ async route(account) {
22329
+ const { organization, useOrganization } = this.config;
22330
+ if (organization.relay === "" || !useOrganization.get()) {
22331
+ const relay = this.config.relay.get();
22332
+ const credential = relay === "" ? void 0 : await this.accessKey();
22333
+ return credential && { relay, credential };
22334
+ }
22335
+ const { accounts } = this;
22336
+ if (accounts === void 0 || account === void 0) throw new Error(`sign-in "${organization.oidcProfileId}" is not available`);
22337
+ return account.state === "connected" ? { relay: organization.relay, credential: member(accounts, organization.oidcProfileId) } : "sign-in";
22338
+ }
22243
22339
  /** The access key in DSH's credentials; undefined until one is saved. */
22244
22340
  async accessKey() {
22245
22341
  const accessKey = (await this.dsh.credentials.resolve(ACCESS_KEY_REF))?.value;
@@ -22248,6 +22344,9 @@ var RemoteDevices = class extends (_a3 = TypertRemoteService, _status_dec = [Rem
22248
22344
  };
22249
22345
  _init = __decoratorStart(_a3);
22250
22346
  __decorateElement(_init, 1, "status", _status_dec, RemoteDevices);
22347
+ __decorateElement(_init, 1, "retry", _retry_dec, RemoteDevices);
22348
+ __decorateElement(_init, 1, "test", _test_dec, RemoteDevices);
22349
+ __decorateElement(_init, 1, "signIn", _signIn_dec, RemoteDevices);
22251
22350
  __decorateElement(_init, 1, "createInvite", _createInvite_dec, RemoteDevices);
22252
22351
  __decorateElement(_init, 1, "cancelInvite", _cancelInvite_dec, RemoteDevices);
22253
22352
  __decorateElement(_init, 1, "decide", _decide_dec, RemoteDevices);
package/lib/typert.js CHANGED
@@ -11,18 +11,21 @@ var codec = (name, schema) => Object.freeze({
11
11
  schema
12
12
  });
13
13
  var parameter = (name, schema) => Object.freeze({ name, wire: name, source: "json", codec: codec(name, schema) });
14
- var method = (name, parameters = []) => ({
14
+ var method = (name, parameters = [], result = "PanelStatus") => ({
15
15
  id: `${pkg}#remoteDevices/${name}`,
16
16
  service: "remoteDevices",
17
17
  namespace: "remoteDevices",
18
18
  method: name,
19
19
  invocation: { kind: "direct" },
20
20
  parameters,
21
- result: codec("PanelStatus", z.unknown()),
21
+ result: codec(result, z.unknown()),
22
22
  sourceLocation: { file: "lib/index.js", line: 1, column: 1 }
23
23
  });
24
24
  var descriptors = [
25
25
  method("status"),
26
+ method("retry"),
27
+ method("test", [], "RelayTest"),
28
+ method("signIn", [], "SignInPage"),
26
29
  method("createInvite"),
27
30
  method("cancelInvite"),
28
31
  method("decide", [parameter("key", z.string()), parameter("approved", z.boolean())]),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduwork/dsh-remote-access",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "End-to-end encrypted remote access to a DSH host through a self-hosted relay",
5
5
  "type": "module",
6
6
  "license": "MIT",