This repository has been archived by the owner on Oct 2, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
citadel.ts
98 lines (87 loc) · 2.44 KB
/
citadel.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import {Manager} from './manager/index.js';
import {Middleware} from './middleware/index.js';
import {joinUrl} from './common/utils.js';
import {RequestFunction} from './common/types.js';
export default class Citadel {
readonly manager;
readonly middleware;
private _jwt = '';
constructor(baseUrl: string) {
const middlewareApi = joinUrl(baseUrl, 'api');
const managerApi = joinUrl(baseUrl, 'manager-api');
this.manager = new Manager(managerApi.toString());
this.middleware = new Middleware(middlewareApi.toString());
}
/**
* Check if the node is online, and what parts are online
*/
public async isOnline(): Promise<{
manager: boolean;
middleware: boolean;
node: boolean;
lightning: {
operational: boolean;
unlocked: boolean;
};
}> {
const manager = await this.manager.isOnline();
const middleware = await this.middleware.isOnline();
let lightning: {
operational: boolean;
unlocked: boolean;
} = {
operational: false,
unlocked: false,
};
try {
lightning = await this.middleware.lightning.info.getStatus();
} catch {}
return {
manager,
middleware,
node: manager && middleware,
lightning,
};
}
/**
* Login to the node.
* @param password The users password
* @param savePw Whether to save the password for later use
*/
public async login(password: string, totpToken: string): Promise<void> {
this.jwt = await this.manager.auth.login(password, totpToken);
}
/**
* Refresh the stored JWT
*/
public async refresh(): Promise<void> {
this.jwt = await this.manager.auth.refresh();
}
public get jwt(): string {
return this._jwt;
}
public set jwt(newJwt: string) {
this._jwt = this.manager.jwt = this.middleware.jwt = newJwt;
}
public set requestFunc(requestFunc: RequestFunction) {
this.manager.requestFunc = this.middleware.requestFunc = requestFunc;
}
public set onAuthFailed(callback: (url: string) => void) {
this.manager.onAuthFailed = this.middleware.onAuthFailed = callback;
}
/**
* Try to discover a node on the network
* @returns The discovered node or false if none found
*/
public static async discover(): Promise<string | false> {
for (const hostname of ['citadel.local', 'citadel']) {
try {
await fetch(`http://${hostname}`);
return hostname;
} catch {
continue;
}
}
return false;
}
}