From c2cab40a2e1a770b0fb2ffbc4a800cc6af118f12 Mon Sep 17 00:00:00 2001 From: boufni95 Date: Tue, 16 Jul 2024 22:08:31 +0200 Subject: [PATCH] wire localhost screen --- proto/CODEGEN.md | 1 + proto/wizard/wizard_methods.proto | 65 ++++ proto/wizard/wizard_structs.proto | 32 ++ proto/wizard_service/autogenerated/client.md | 75 +++++ proto/wizard_service/autogenerated/debug.txt | 221 ++++++++++++++ .../autogenerated/ts/express_server.ts | 104 +++++++ .../autogenerated/ts/http_client.ts | 57 ++++ .../autogenerated/ts/nostr_client.ts | 11 + .../autogenerated/ts/nostr_transport.ts | 34 +++ .../wizard_service/autogenerated/ts/types.ts | 163 ++++++++++ src/auth.ts | 3 +- src/services/main/init.ts | 27 +- src/services/main/settings.ts | 6 + src/services/main/unlocker.ts | 64 +++- src/services/wizard/index.ts | 131 ++++++++ static/backup.html | 201 ++++++------ static/index.html | 184 ++++++----- static/liquidity.html | 185 +++++------ static/seed.html | 286 +++++++----------- static/status.html | 145 +++++++++ static/stauts.html | 148 --------- 21 files changed, 1553 insertions(+), 590 deletions(-) create mode 100644 proto/wizard/wizard_methods.proto create mode 100644 proto/wizard/wizard_structs.proto create mode 100644 proto/wizard_service/autogenerated/client.md create mode 100644 proto/wizard_service/autogenerated/debug.txt create mode 100644 proto/wizard_service/autogenerated/ts/express_server.ts create mode 100644 proto/wizard_service/autogenerated/ts/http_client.ts create mode 100644 proto/wizard_service/autogenerated/ts/nostr_client.ts create mode 100644 proto/wizard_service/autogenerated/ts/nostr_transport.ts create mode 100644 proto/wizard_service/autogenerated/ts/types.ts create mode 100644 src/services/wizard/index.ts create mode 100644 static/status.html delete mode 100644 static/stauts.html diff --git a/proto/CODEGEN.md b/proto/CODEGEN.md index 1328b3d7..82e7b302 100644 --- a/proto/CODEGEN.md +++ b/proto/CODEGEN.md @@ -1,4 +1,5 @@ create lnd classes: `npx protoc -I ./others --ts_out=./lnd others/*` create server classes: `npx protoc -I ./service --pub_out=. service/*` +create wizard classes: `npx protoc -I ./wizard --pub_out=./wizard_service wizard/*` export PATH=$PATH:~/Lightning.Pub/proto \ No newline at end of file diff --git a/proto/wizard/wizard_methods.proto b/proto/wizard/wizard_methods.proto new file mode 100644 index 00000000..329f2b5b --- /dev/null +++ b/proto/wizard/wizard_methods.proto @@ -0,0 +1,65 @@ +syntax = "proto3"; + +package wizard_methods; + +import "google/protobuf/descriptor.proto"; +import "wizard_structs.proto"; + +option go_package = "github.com/shocknet/lightning.pub"; +option (file_options) = { + supported_http_methods:["post", "get"]; + supported_auths:{ + id: "guest" + name: "Guest" + context:[] + }; +}; + +message MethodQueryOptions { + repeated string items = 1; +} + +extend google.protobuf.MethodOptions { // TODO: move this stuff to dep repo? + string auth_type = 50003; + string http_method = 50004; + string http_route = 50005; + MethodQueryOptions query = 50006; + bool nostr = 50007; + bool batch = 50008; + +} + +message ProtoFileOptions { + message SupportedAuth { + string id = 1; + string name = 2; + bool encrypted = 3; + map context = 4; + } + repeated SupportedAuth supported_auths = 1; + repeated string supported_http_methods = 2; +} + +extend google.protobuf.FileOptions { + ProtoFileOptions file_options = 50004; +} + +service Wizard { + // + rpc WizardState(wizard_structs.Empty) returns (wizard_structs.StateResponse){ + option (auth_type) = "Guest"; + option (http_method) = "get"; + option (http_route) = "/wizard/state"; + }; + rpc WizardConfig(wizard_structs.ConfigRequest) returns (wizard_structs.ConfigResponse){ + option (auth_type) = "Guest"; + option (http_method) = "post"; + option (http_route) = "/wizard/config"; + }; + rpc WizardConfirm(wizard_structs.ConfirmRequest) returns (wizard_structs.ConfirmResponse){ + option (auth_type) = "Guest"; + option (http_method) = "post"; + option (http_route) = "/wizard/confirm"; + }; + // +} \ No newline at end of file diff --git a/proto/wizard/wizard_structs.proto b/proto/wizard/wizard_structs.proto new file mode 100644 index 00000000..6e4c9a4a --- /dev/null +++ b/proto/wizard/wizard_structs.proto @@ -0,0 +1,32 @@ +syntax = "proto3"; + +package wizard_structs; + +option go_package = "github.com/shocknet/lightning.pub"; + +message Empty {} + +message StateResponse { + bool already_initialized = 1; +} +message ConfigRequest { + string source_name = 1; + string relay_url = 2; + bool automate_liquidity = 3; + bool push_backups_to_nostr = 4; +} + + +message ConfigResponse { + bool already_initialized = 1; + repeated string seed = 2; + string confirmation_id = 3; +} + +message ConfirmRequest { + string confirmation_id = 1; +} + +message ConfirmResponse { + string admin_key = 1; +} diff --git a/proto/wizard_service/autogenerated/client.md b/proto/wizard_service/autogenerated/client.md new file mode 100644 index 00000000..6d805bb0 --- /dev/null +++ b/proto/wizard_service/autogenerated/client.md @@ -0,0 +1,75 @@ +# NOSTR API DEFINITION + + +A nostr request will take the same parameter and give the same response as an http request, but it will use nostr as transport, to do that it will send encrypted events to the server public key, in the event 6 thing are required: +- __rpcName__: string containing the name of the method +- __params__: a map with the all the url params for the method +- __query__: a map with the the url query for the method +- __body__: the body of the method request +- __requestId__: id of the request to be able to get a response + +The nostr server will send back a message response, and inside the body there will also be a __requestId__ to identify the request this response is answering + +## NOSTR Methods +### These are the nostr methods the client implements to communicate with the API via nostr + +# HTTP API DEFINITION + +## Supported HTTP Auths +### These are the supported http auth types, to give different type of access to the API users + +- __Guest__: + - expected context content + +## HTTP Methods +### These are the http methods the client implements to communicate with the API + +- WizardState + - auth type: __Guest__ + - http method: __get__ + - http route: __/wizard/state__ + - This methods has an __empty__ __request__ body + - output: [StateResponse](#StateResponse) + +- WizardConfig + - auth type: __Guest__ + - http method: __post__ + - http route: __/wizard/config__ + - input: [ConfigRequest](#ConfigRequest) + - output: [ConfigResponse](#ConfigResponse) + +- WizardConfirm + - auth type: __Guest__ + - http method: __post__ + - http route: __/wizard/confirm__ + - input: [ConfirmRequest](#ConfirmRequest) + - output: [ConfirmResponse](#ConfirmResponse) + +# INPUTS AND OUTPUTS + +## Messages +### The content of requests and response from the methods + +### ConfirmResponse + - __admin_key__: _string_ + +### Empty + +### StateResponse + - __already_initialized__: _boolean_ + +### ConfigRequest + - __source_name__: _string_ + - __relay_url__: _string_ + - __automate_liquidity__: _boolean_ + - __push_backups_to_nostr__: _boolean_ + +### ConfigResponse + - __already_initialized__: _boolean_ + - __seed__: ARRAY of: _string_ + - __confirmation_id__: _string_ + +### ConfirmRequest + - __confirmation_id__: _string_ +## Enums +### The enumerators used in the messages diff --git a/proto/wizard_service/autogenerated/debug.txt b/proto/wizard_service/autogenerated/debug.txt new file mode 100644 index 00000000..972e6bcd --- /dev/null +++ b/proto/wizard_service/autogenerated/debug.txt @@ -0,0 +1,221 @@ +([]*main.Method) (len=3 cap=4) { + (*main.Method)(0xc0002221e0)({ + in: (main.MethodMessage) { + name: (string) (len=5) "Empty", + hasZeroFields: (bool) true + }, + name: (string) (len=11) "WizardState", + out: (main.MethodMessage) { + name: (string) (len=13) "StateResponse", + hasZeroFields: (bool) false + }, + opts: (*main.methodOptions)(0xc00009e6c0)({ + authType: (*main.supportedAuth)(0xc0003bd290)({ + id: (string) (len=5) "guest", + name: (string) (len=5) "Guest", + context: (map[string]string) { + } + }), + method: (string) (len=3) "get", + route: (main.decodedRoute) { + route: (string) (len=13) "/wizard/state", + params: ([]string) + }, + query: ([]string) , + nostr: (bool) false, + batch: (bool) false + }), + serverStream: (bool) false + }), + (*main.Method)(0xc000222230)({ + in: (main.MethodMessage) { + name: (string) (len=13) "ConfigRequest", + hasZeroFields: (bool) false + }, + name: (string) (len=12) "WizardConfig", + out: (main.MethodMessage) { + name: (string) (len=14) "ConfigResponse", + hasZeroFields: (bool) false + }, + opts: (*main.methodOptions)(0xc00009e840)({ + authType: (*main.supportedAuth)(0xc0003bd350)({ + id: (string) (len=5) "guest", + name: (string) (len=5) "Guest", + context: (map[string]string) { + } + }), + method: (string) (len=4) "post", + route: (main.decodedRoute) { + route: (string) (len=14) "/wizard/config", + params: ([]string) + }, + query: ([]string) , + nostr: (bool) false, + batch: (bool) false + }), + serverStream: (bool) false + }), + (*main.Method)(0xc0002225a0)({ + in: (main.MethodMessage) { + name: (string) (len=14) "ConfirmRequest", + hasZeroFields: (bool) false + }, + name: (string) (len=13) "WizardConfirm", + out: (main.MethodMessage) { + name: (string) (len=15) "ConfirmResponse", + hasZeroFields: (bool) false + }, + opts: (*main.methodOptions)(0xc00009e9c0)({ + authType: (*main.supportedAuth)(0xc0003bd410)({ + id: (string) (len=5) "guest", + name: (string) (len=5) "Guest", + context: (map[string]string) { + } + }), + method: (string) (len=4) "post", + route: (main.decodedRoute) { + route: (string) (len=15) "/wizard/confirm", + params: ([]string) + }, + query: ([]string) , + nostr: (bool) false, + batch: (bool) false + }), + serverStream: (bool) false + }) +} + +([]*main.Enum) + +(map[string]*main.Message) (len=6) { + (string) (len=13) "StateResponse": (*main.Message)(0xc0003ee1c0)({ + fullName: (string) (len=13) "StateResponse", + name: (string) (len=13) "StateResponse", + fields: ([]*main.Field) (len=1 cap=1) { + (*main.Field)(0xc0003bccc0)({ + name: (string) (len=19) "already_initialized", + kind: (string) (len=4) "bool", + isMap: (bool) false, + isArray: (bool) false, + isEnum: (bool) false, + isMessage: (bool) false, + isOptional: (bool) false + }) + } + }), + (string) (len=13) "ConfigRequest": (*main.Message)(0xc0003ee200)({ + fullName: (string) (len=13) "ConfigRequest", + name: (string) (len=13) "ConfigRequest", + fields: ([]*main.Field) (len=4 cap=4) { + (*main.Field)(0xc0003bccf0)({ + name: (string) (len=11) "source_name", + kind: (string) (len=6) "string", + isMap: (bool) false, + isArray: (bool) false, + isEnum: (bool) false, + isMessage: (bool) false, + isOptional: (bool) false + }), + (*main.Field)(0xc0003bcd20)({ + name: (string) (len=9) "relay_url", + kind: (string) (len=6) "string", + isMap: (bool) false, + isArray: (bool) false, + isEnum: (bool) false, + isMessage: (bool) false, + isOptional: (bool) false + }), + (*main.Field)(0xc0003bcd50)({ + name: (string) (len=18) "automate_liquidity", + kind: (string) (len=4) "bool", + isMap: (bool) false, + isArray: (bool) false, + isEnum: (bool) false, + isMessage: (bool) false, + isOptional: (bool) false + }), + (*main.Field)(0xc0003bcd80)({ + name: (string) (len=21) "push_backups_to_nostr", + kind: (string) (len=4) "bool", + isMap: (bool) false, + isArray: (bool) false, + isEnum: (bool) false, + isMessage: (bool) false, + isOptional: (bool) false + }) + } + }), + (string) (len=14) "ConfigResponse": (*main.Message)(0xc0003ee240)({ + fullName: (string) (len=14) "ConfigResponse", + name: (string) (len=14) "ConfigResponse", + fields: ([]*main.Field) (len=3 cap=4) { + (*main.Field)(0xc0003bcdb0)({ + name: (string) (len=19) "already_initialized", + kind: (string) (len=4) "bool", + isMap: (bool) false, + isArray: (bool) false, + isEnum: (bool) false, + isMessage: (bool) false, + isOptional: (bool) false + }), + (*main.Field)(0xc0003bcde0)({ + name: (string) (len=4) "seed", + kind: (string) (len=6) "string", + isMap: (bool) false, + isArray: (bool) true, + isEnum: (bool) false, + isMessage: (bool) false, + isOptional: (bool) false + }), + (*main.Field)(0xc0003bce10)({ + name: (string) (len=15) "confirmation_id", + kind: (string) (len=6) "string", + isMap: (bool) false, + isArray: (bool) false, + isEnum: (bool) false, + isMessage: (bool) false, + isOptional: (bool) false + }) + } + }), + (string) (len=14) "ConfirmRequest": (*main.Message)(0xc0003ee280)({ + fullName: (string) (len=14) "ConfirmRequest", + name: (string) (len=14) "ConfirmRequest", + fields: ([]*main.Field) (len=1 cap=1) { + (*main.Field)(0xc0003bce40)({ + name: (string) (len=15) "confirmation_id", + kind: (string) (len=6) "string", + isMap: (bool) false, + isArray: (bool) false, + isEnum: (bool) false, + isMessage: (bool) false, + isOptional: (bool) false + }) + } + }), + (string) (len=15) "ConfirmResponse": (*main.Message)(0xc0003ee2c0)({ + fullName: (string) (len=15) "ConfirmResponse", + name: (string) (len=15) "ConfirmResponse", + fields: ([]*main.Field) (len=1 cap=1) { + (*main.Field)(0xc0003bce70)({ + name: (string) (len=9) "admin_key", + kind: (string) (len=6) "string", + isMap: (bool) false, + isArray: (bool) false, + isEnum: (bool) false, + isMessage: (bool) false, + isOptional: (bool) false + }) + } + }), + (string) (len=5) "Empty": (*main.Message)(0xc0003ee080)({ + fullName: (string) (len=5) "Empty", + name: (string) (len=5) "Empty", + fields: ([]*main.Field) + }) +} + +parsing file: wizard_structs 6 +parsing file: wizard_methods 2 +-> [{guest Guest map[]}] + diff --git a/proto/wizard_service/autogenerated/ts/express_server.ts b/proto/wizard_service/autogenerated/ts/express_server.ts new file mode 100644 index 00000000..c6f311f5 --- /dev/null +++ b/proto/wizard_service/autogenerated/ts/express_server.ts @@ -0,0 +1,104 @@ +// This file was autogenerated from a .proto file, DO NOT EDIT! + +import express, { Response, json, urlencoded } from 'express' +import cors from 'cors' +import * as Types from './types.js' +export type Logger = { log: (v: any) => void, error: (v: any) => void } +export type ServerOptions = { + allowCors?: true + staticFiles?: string + allowNotImplementedMethods?: true + logger?: Logger + throwErrors?: true + logMethod?: true + logBody?: true + metricsCallback: (metrics: Types.RequestMetric[]) => void + GuestAuthGuard: (authorizationHeader?: string) => Promise +} +declare module 'express-serve-static-core' { interface Request { startTime?: bigint, bodySize?: number, startTimeMs: number } } +const logErrorAndReturnResponse = (error: Error, response: string, res: Response, logger: Logger, metric: Types.RequestMetric, metricsCallback: (metrics: Types.RequestMetric[]) => void) => { + logger.error(error.message || error); metricsCallback([{ ...metric, error: response }]); res.json({ status: 'ERROR', reason: response }) +} +export default (methods: Types.ServerMethods, opts: ServerOptions) => { + const logger = opts.logger || { log: console.log, error: console.error } + const app = express() + if (opts.allowCors) { + app.use(cors()) + } + app.use((req, _, next) => { req.startTime = process.hrtime.bigint(); req.startTimeMs = Date.now(); next() }) + app.use(json()) + app.use(urlencoded({ extended: true })) + if (opts.logMethod) app.use((req, _, next) => { console.log(req.method, req.path); if (opts.logBody) console.log(req.body); next() }) + if (!opts.allowNotImplementedMethods && !methods.WizardState) throw new Error('method: WizardState is not implemented') + app.get('/wizard/state', async (req, res) => { + const info: Types.RequestInfo = { rpcName: 'WizardState', batch: false, nostr: false, batchSize: 0} + const stats: Types.RequestStats = { startMs:req.startTimeMs || 0, start:req.startTime || 0n, parse: process.hrtime.bigint(), guard: 0n, validate: 0n, handle: 0n } + let authCtx: Types.AuthContext = {} + try { + if (!methods.WizardState) throw new Error('method: WizardState is not implemented') + const authContext = await opts.GuestAuthGuard(req.headers['authorization']) + authCtx = authContext + stats.guard = process.hrtime.bigint() + stats.validate = stats.guard + const query = req.query + const params = req.params + const response = await methods.WizardState({rpcName:'WizardState', ctx:authContext }) + stats.handle = process.hrtime.bigint() + res.json({status: 'OK', ...response}) + opts.metricsCallback([{ ...info, ...stats, ...authContext }]) + } catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } + }) + if (!opts.allowNotImplementedMethods && !methods.WizardConfig) throw new Error('method: WizardConfig is not implemented') + app.post('/wizard/config', async (req, res) => { + const info: Types.RequestInfo = { rpcName: 'WizardConfig', batch: false, nostr: false, batchSize: 0} + const stats: Types.RequestStats = { startMs:req.startTimeMs || 0, start:req.startTime || 0n, parse: process.hrtime.bigint(), guard: 0n, validate: 0n, handle: 0n } + let authCtx: Types.AuthContext = {} + try { + if (!methods.WizardConfig) throw new Error('method: WizardConfig is not implemented') + const authContext = await opts.GuestAuthGuard(req.headers['authorization']) + authCtx = authContext + stats.guard = process.hrtime.bigint() + const request = req.body + const error = Types.ConfigRequestValidate(request) + stats.validate = process.hrtime.bigint() + if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback) + const query = req.query + const params = req.params + const response = await methods.WizardConfig({rpcName:'WizardConfig', ctx:authContext , req: request}) + stats.handle = process.hrtime.bigint() + res.json({status: 'OK', ...response}) + opts.metricsCallback([{ ...info, ...stats, ...authContext }]) + } catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } + }) + if (!opts.allowNotImplementedMethods && !methods.WizardConfirm) throw new Error('method: WizardConfirm is not implemented') + app.post('/wizard/confirm', async (req, res) => { + const info: Types.RequestInfo = { rpcName: 'WizardConfirm', batch: false, nostr: false, batchSize: 0} + const stats: Types.RequestStats = { startMs:req.startTimeMs || 0, start:req.startTime || 0n, parse: process.hrtime.bigint(), guard: 0n, validate: 0n, handle: 0n } + let authCtx: Types.AuthContext = {} + try { + if (!methods.WizardConfirm) throw new Error('method: WizardConfirm is not implemented') + const authContext = await opts.GuestAuthGuard(req.headers['authorization']) + authCtx = authContext + stats.guard = process.hrtime.bigint() + const request = req.body + const error = Types.ConfirmRequestValidate(request) + stats.validate = process.hrtime.bigint() + if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback) + const query = req.query + const params = req.params + const response = await methods.WizardConfirm({rpcName:'WizardConfirm', ctx:authContext , req: request}) + stats.handle = process.hrtime.bigint() + res.json({status: 'OK', ...response}) + opts.metricsCallback([{ ...info, ...stats, ...authContext }]) + } catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } + }) + if (opts.staticFiles) { + app.use(express.static(opts.staticFiles)) + app.get('*', function (_, res) { res.sendFile('index.html', { root: opts.staticFiles })}) + } + var server: { close: () => void } | undefined + return { + Close: () => { if (!server) { throw new Error('tried closing server before starting') } else server.close() }, + Listen: (port: number) => { server = app.listen(port, () => logger.log('Example app listening on port ' + port)) } + } +} diff --git a/proto/wizard_service/autogenerated/ts/http_client.ts b/proto/wizard_service/autogenerated/ts/http_client.ts new file mode 100644 index 00000000..e173a8ca --- /dev/null +++ b/proto/wizard_service/autogenerated/ts/http_client.ts @@ -0,0 +1,57 @@ +// This file was autogenerated from a .proto file, DO NOT EDIT! +import axios from 'axios' +import * as Types from './types.js' +export type ResultError = { status: 'ERROR', reason: string } + +export type ClientParams = { + baseUrl: string + retrieveGuestAuth: () => Promise + encryptCallback: (plain: any) => Promise + decryptCallback: (encrypted: any) => Promise + deviceId: string + checkResult?: true +} +export default (params: ClientParams) => ({ + WizardState: async (): Promise => { + const auth = await params.retrieveGuestAuth() + if (auth === null) throw new Error('retrieveGuestAuth() returned null') + let finalRoute = '/wizard/state' + const { data } = await axios.get(params.baseUrl + finalRoute, { headers: { 'authorization': auth } }) + if (data.status === 'ERROR' && typeof data.reason === 'string') return data + if (data.status === 'OK') { + const result = data + if(!params.checkResult) return { status: 'OK', ...result } + const error = Types.StateResponseValidate(result) + if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message } + } + return { status: 'ERROR', reason: 'invalid response' } + }, + WizardConfig: async (request: Types.ConfigRequest): Promise => { + const auth = await params.retrieveGuestAuth() + if (auth === null) throw new Error('retrieveGuestAuth() returned null') + let finalRoute = '/wizard/config' + const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } }) + if (data.status === 'ERROR' && typeof data.reason === 'string') return data + if (data.status === 'OK') { + const result = data + if(!params.checkResult) return { status: 'OK', ...result } + const error = Types.ConfigResponseValidate(result) + if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message } + } + return { status: 'ERROR', reason: 'invalid response' } + }, + WizardConfirm: async (request: Types.ConfirmRequest): Promise => { + const auth = await params.retrieveGuestAuth() + if (auth === null) throw new Error('retrieveGuestAuth() returned null') + let finalRoute = '/wizard/confirm' + const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } }) + if (data.status === 'ERROR' && typeof data.reason === 'string') return data + if (data.status === 'OK') { + const result = data + if(!params.checkResult) return { status: 'OK', ...result } + const error = Types.ConfirmResponseValidate(result) + if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message } + } + return { status: 'ERROR', reason: 'invalid response' } + }, +}) diff --git a/proto/wizard_service/autogenerated/ts/nostr_client.ts b/proto/wizard_service/autogenerated/ts/nostr_client.ts new file mode 100644 index 00000000..2d7e666b --- /dev/null +++ b/proto/wizard_service/autogenerated/ts/nostr_client.ts @@ -0,0 +1,11 @@ +// This file was autogenerated from a .proto file, DO NOT EDIT! +import { NostrRequest } from './nostr_transport.js' +import * as Types from './types.js' +export type ResultError = { status: 'ERROR', reason: string } + +export type NostrClientParams = { + pubDestination: string + checkResult?: true +} +export default (params: NostrClientParams, send: (to:string, message: NostrRequest) => Promise, subscribe: (to:string, message: NostrRequest, cb:(res:any)=> void) => void) => ({ +}) diff --git a/proto/wizard_service/autogenerated/ts/nostr_transport.ts b/proto/wizard_service/autogenerated/ts/nostr_transport.ts new file mode 100644 index 00000000..85249e68 --- /dev/null +++ b/proto/wizard_service/autogenerated/ts/nostr_transport.ts @@ -0,0 +1,34 @@ +// This file was autogenerated from a .proto file, DO NOT EDIT! + +import * as Types from './types.js' +export type Logger = { log: (v: any) => void, error: (v: any) => void } +type NostrResponse = (message: object) => void +export type NostrRequest = { + rpcName?: string + params?: Record + query?: Record + body?: any + authIdentifier?: string + requestId?: string + appId?: string +} +export type NostrOptions = { + logger?: Logger + throwErrors?: true + metricsCallback: (metrics: Types.RequestMetric[]) => void +} +const logErrorAndReturnResponse = (error: Error, response: string, res: NostrResponse, logger: Logger, metric: Types.RequestMetric, metricsCallback: (metrics: Types.RequestMetric[]) => void) => { + logger.error(error.message || error); metricsCallback([{ ...metric, error: response }]); res({ status: 'ERROR', reason: response }) +} +export default (methods: Types.ServerMethods, opts: NostrOptions) => { + const logger = opts.logger || { log: console.log, error: console.error } + return async (req: NostrRequest, res: NostrResponse, startString: string, startMs: number) => { + const startTime = BigInt(startString) + const info: Types.RequestInfo = { rpcName: req.rpcName || 'unkown', batch: false, nostr: true, batchSize: 0 } + const stats: Types.RequestStats = { startMs, start: startTime, parse: process.hrtime.bigint(), guard: 0n, validate: 0n, handle: 0n } + let authCtx: Types.AuthContext = {} + switch (req.rpcName) { + default: logger.error('unknown rpc call name from nostr event:'+req.rpcName) + } + } +} diff --git a/proto/wizard_service/autogenerated/ts/types.ts b/proto/wizard_service/autogenerated/ts/types.ts new file mode 100644 index 00000000..0b7be5ec --- /dev/null +++ b/proto/wizard_service/autogenerated/ts/types.ts @@ -0,0 +1,163 @@ +// This file was autogenerated from a .proto file, DO NOT EDIT! + +export type ResultError = { status: 'ERROR', reason: string } +export type RequestInfo = { rpcName: string, batch: boolean, nostr: boolean, batchSize: number } +export type RequestStats = { startMs:number, start:bigint, parse: bigint, guard: bigint, validate: bigint, handle: bigint } +export type RequestMetric = AuthContext & RequestInfo & RequestStats & { error?: string } +export type GuestContext = { +} +export type GuestMethodInputs = WizardState_Input | WizardConfig_Input | WizardConfirm_Input +export type GuestMethodOutputs = WizardState_Output | WizardConfig_Output | WizardConfirm_Output +export type AuthContext = GuestContext + +export type WizardState_Input = {rpcName:'WizardState'} +export type WizardState_Output = ResultError | ({ status: 'OK' } & StateResponse) + +export type WizardConfig_Input = {rpcName:'WizardConfig', req: ConfigRequest} +export type WizardConfig_Output = ResultError | ({ status: 'OK' } & ConfigResponse) + +export type WizardConfirm_Input = {rpcName:'WizardConfirm', req: ConfirmRequest} +export type WizardConfirm_Output = ResultError | ({ status: 'OK' } & ConfirmResponse) + +export type ServerMethods = { + WizardState?: (req: WizardState_Input & {ctx: GuestContext }) => Promise + WizardConfig?: (req: WizardConfig_Input & {ctx: GuestContext }) => Promise + WizardConfirm?: (req: WizardConfirm_Input & {ctx: GuestContext }) => Promise +} + + +export type OptionsBaseMessage = { + allOptionalsAreSet?: true +} + +export type ConfigResponse = { + already_initialized: boolean + seed: string[] + confirmation_id: string +} +export const ConfigResponseOptionalFields: [] = [] +export type ConfigResponseOptions = OptionsBaseMessage & { + checkOptionalsAreSet?: [] + already_initialized_CustomCheck?: (v: boolean) => boolean + seed_CustomCheck?: (v: string[]) => boolean + confirmation_id_CustomCheck?: (v: string) => boolean +} +export const ConfigResponseValidate = (o?: ConfigResponse, opts: ConfigResponseOptions = {}, path: string = 'ConfigResponse::root.'): Error | null => { + if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message') + if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null') + + if (typeof o.already_initialized !== 'boolean') return new Error(`${path}.already_initialized: is not a boolean`) + if (opts.already_initialized_CustomCheck && !opts.already_initialized_CustomCheck(o.already_initialized)) return new Error(`${path}.already_initialized: custom check failed`) + + if (!Array.isArray(o.seed)) return new Error(`${path}.seed: is not an array`) + for (let index = 0; index < o.seed.length; index++) { + if (typeof o.seed[index] !== 'string') return new Error(`${path}.seed[${index}]: is not a string`) + } + if (opts.seed_CustomCheck && !opts.seed_CustomCheck(o.seed)) return new Error(`${path}.seed: custom check failed`) + + if (typeof o.confirmation_id !== 'string') return new Error(`${path}.confirmation_id: is not a string`) + if (opts.confirmation_id_CustomCheck && !opts.confirmation_id_CustomCheck(o.confirmation_id)) return new Error(`${path}.confirmation_id: custom check failed`) + + return null +} + +export type ConfirmRequest = { + confirmation_id: string +} +export const ConfirmRequestOptionalFields: [] = [] +export type ConfirmRequestOptions = OptionsBaseMessage & { + checkOptionalsAreSet?: [] + confirmation_id_CustomCheck?: (v: string) => boolean +} +export const ConfirmRequestValidate = (o?: ConfirmRequest, opts: ConfirmRequestOptions = {}, path: string = 'ConfirmRequest::root.'): Error | null => { + if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message') + if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null') + + if (typeof o.confirmation_id !== 'string') return new Error(`${path}.confirmation_id: is not a string`) + if (opts.confirmation_id_CustomCheck && !opts.confirmation_id_CustomCheck(o.confirmation_id)) return new Error(`${path}.confirmation_id: custom check failed`) + + return null +} + +export type ConfirmResponse = { + admin_key: string +} +export const ConfirmResponseOptionalFields: [] = [] +export type ConfirmResponseOptions = OptionsBaseMessage & { + checkOptionalsAreSet?: [] + admin_key_CustomCheck?: (v: string) => boolean +} +export const ConfirmResponseValidate = (o?: ConfirmResponse, opts: ConfirmResponseOptions = {}, path: string = 'ConfirmResponse::root.'): Error | null => { + if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message') + if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null') + + if (typeof o.admin_key !== 'string') return new Error(`${path}.admin_key: is not a string`) + if (opts.admin_key_CustomCheck && !opts.admin_key_CustomCheck(o.admin_key)) return new Error(`${path}.admin_key: custom check failed`) + + return null +} + +export type Empty = { +} +export const EmptyOptionalFields: [] = [] +export type EmptyOptions = OptionsBaseMessage & { + checkOptionalsAreSet?: [] +} +export const EmptyValidate = (o?: Empty, opts: EmptyOptions = {}, path: string = 'Empty::root.'): Error | null => { + if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message') + if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null') + + return null +} + +export type StateResponse = { + already_initialized: boolean +} +export const StateResponseOptionalFields: [] = [] +export type StateResponseOptions = OptionsBaseMessage & { + checkOptionalsAreSet?: [] + already_initialized_CustomCheck?: (v: boolean) => boolean +} +export const StateResponseValidate = (o?: StateResponse, opts: StateResponseOptions = {}, path: string = 'StateResponse::root.'): Error | null => { + if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message') + if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null') + + if (typeof o.already_initialized !== 'boolean') return new Error(`${path}.already_initialized: is not a boolean`) + if (opts.already_initialized_CustomCheck && !opts.already_initialized_CustomCheck(o.already_initialized)) return new Error(`${path}.already_initialized: custom check failed`) + + return null +} + +export type ConfigRequest = { + source_name: string + relay_url: string + automate_liquidity: boolean + push_backups_to_nostr: boolean +} +export const ConfigRequestOptionalFields: [] = [] +export type ConfigRequestOptions = OptionsBaseMessage & { + checkOptionalsAreSet?: [] + source_name_CustomCheck?: (v: string) => boolean + relay_url_CustomCheck?: (v: string) => boolean + automate_liquidity_CustomCheck?: (v: boolean) => boolean + push_backups_to_nostr_CustomCheck?: (v: boolean) => boolean +} +export const ConfigRequestValidate = (o?: ConfigRequest, opts: ConfigRequestOptions = {}, path: string = 'ConfigRequest::root.'): Error | null => { + if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message') + if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null') + + if (typeof o.source_name !== 'string') return new Error(`${path}.source_name: is not a string`) + if (opts.source_name_CustomCheck && !opts.source_name_CustomCheck(o.source_name)) return new Error(`${path}.source_name: custom check failed`) + + if (typeof o.relay_url !== 'string') return new Error(`${path}.relay_url: is not a string`) + if (opts.relay_url_CustomCheck && !opts.relay_url_CustomCheck(o.relay_url)) return new Error(`${path}.relay_url: custom check failed`) + + if (typeof o.automate_liquidity !== 'boolean') return new Error(`${path}.automate_liquidity: is not a boolean`) + if (opts.automate_liquidity_CustomCheck && !opts.automate_liquidity_CustomCheck(o.automate_liquidity)) return new Error(`${path}.automate_liquidity: custom check failed`) + + if (typeof o.push_backups_to_nostr !== 'boolean') return new Error(`${path}.push_backups_to_nostr: is not a boolean`) + if (opts.push_backups_to_nostr_CustomCheck && !opts.push_backups_to_nostr_CustomCheck(o.push_backups_to_nostr)) return new Error(`${path}.push_backups_to_nostr: custom check failed`) + + return null +} + diff --git a/src/auth.ts b/src/auth.ts index 492526ab..b5fa93dd 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -1,5 +1,5 @@ import express from 'express'; -import path from 'path'; + import { ServerOptions } from "../proto/autogenerated/ts/express_server"; import { AdminContext, MetricsContext } from "../proto/autogenerated/ts/types"; import Main from './services/main' @@ -8,7 +8,6 @@ const serverOptions = (mainHandler: Main): ServerOptions => { const log = getLogger({}) return { logger: { log, error: err => log(ERROR, err) }, - staticFiles: path.resolve('static'), AdminAuthGuard: adminAuth, MetricsAuthGuard: metricsAuth, AppAuthGuard: async (authHeader) => { return { app_id: mainHandler.applicationManager.DecodeAppToken(stripBearer(authHeader)) } }, diff --git a/src/services/main/init.ts b/src/services/main/init.ts index e1edef42..2e8b7748 100644 --- a/src/services/main/init.ts +++ b/src/services/main/init.ts @@ -5,8 +5,9 @@ import Storage from "../storage/index.js" import { TypeOrmMigrationRunner } from "../storage/migrations/runner.js" import Main from "./index.js" import SanityChecker from "./sanityChecker.js" -import { MainSettings } from "./settings.js" +import { LoadMainSettingsFromEnv, MainSettings } from "./settings.js" import { Utils } from "../helpers/utilsWrapper.js" +import { Wizard } from "../wizard/index.js" export type AppData = { privateKey: string; publicKey: string; @@ -20,20 +21,30 @@ export const initMainHandler = async (log: PubLogger, mainSettings: MainSettings if (manualMigration) { return } - const unlocker = new Unlocker(mainSettings, storageManager) - await unlocker.Unlock() + let reloadedSettings = mainSettings + if (mainSettings.wizard) { + const wizard = new Wizard(mainSettings, storageManager) + const reload = await wizard.WaitUntilConfigured() + if (reload) { + reloadedSettings = LoadMainSettingsFromEnv() + } + } else { + const unlocker = new Unlocker(mainSettings, storageManager) + await unlocker.Unlock() + } - const mainHandler = new Main(mainSettings, storageManager, utils) + const mainHandler = new Main(reloadedSettings, storageManager, utils) await mainHandler.lnd.Warmup() - if (!mainSettings.skipSanityCheck) { + if (!reloadedSettings.skipSanityCheck) { const sanityChecker = new SanityChecker(storageManager, mainHandler.lnd) await sanityChecker.VerifyEventsLog() } const appsData = await mainHandler.storage.applicationStorage.GetApplications() - const existingWalletApp = await appsData.find(app => app.name === 'wallet' || app.name === 'wallet-test') + const defaultNames = ['wallet', 'wallet-test', reloadedSettings.defaultAppName] + const existingWalletApp = await appsData.find(app => defaultNames.includes(app.name)) if (!existingWalletApp) { log("no default wallet app found, creating one...") - const newWalletApp = await mainHandler.storage.applicationStorage.AddApplication('wallet', true) + const newWalletApp = await mainHandler.storage.applicationStorage.AddApplication(reloadedSettings.defaultAppName, true) appsData.push(newWalletApp) } const apps: AppData[] = await Promise.all(appsData.map(app => { @@ -44,7 +55,7 @@ export const initMainHandler = async (log: PubLogger, mainSettings: MainSettings return { privateKey: app.nostr_private_key, publicKey: app.nostr_public_key, appId: app.app_id, name: app.name } } })) - const liquidityProviderApp = apps.find(app => app.name === 'wallet' || app.name === 'wallet-test') + const liquidityProviderApp = apps.find(app => defaultNames.includes(app.name)) if (!liquidityProviderApp) { throw new Error("wallet app not initialized correctly") } diff --git a/src/services/main/settings.ts b/src/services/main/settings.ts index 5cb64d61..503e7d78 100644 --- a/src/services/main/settings.ts +++ b/src/services/main/settings.ts @@ -29,6 +29,9 @@ export type MainSettings = { recordPerformance: boolean skipSanityCheck: boolean disableExternalPayments: boolean + wizard: boolean + defaultAppName: string + pushBackupsToNostr: boolean } export type BitcoinCoreSettings = { @@ -63,6 +66,9 @@ export const LoadMainSettingsFromEnv = (): MainSettings => { recordPerformance: process.env.RECORD_PERFORMANCE === 'true' || false, skipSanityCheck: process.env.SKIP_SANITY_CHECK === 'true' || false, disableExternalPayments: process.env.DISABLE_EXTERNAL_PAYMENTS === 'true' || false, + wizard: process.env.WIZARD === 'true' || false, + defaultAppName: process.env.DEFAULT_APP_NAME || "wallet", + pushBackupsToNostr: process.env.PUSH_BACKUPS_TO_NOSTR === 'true' || false } } diff --git a/src/services/main/unlocker.ts b/src/services/main/unlocker.ts index fffe5f43..3d86dcd5 100644 --- a/src/services/main/unlocker.ts +++ b/src/services/main/unlocker.ts @@ -9,10 +9,13 @@ import { InitWalletReq } from '../lnd/initWalletReq.js'; import Storage from '../storage/index.js' import { LightningClient } from '../../../proto/lnd/lightning.client.js'; const DeadLineMetadata = (deadline = 10 * 1000) => ({ deadline: Date.now() + deadline }) +type EncryptedData = { iv: string, encrypted: string } +type Seed = { plaintextSeed: string[], encryptedSeed: EncryptedData } export class Unlocker { settings: MainSettings storage: Storage abortController = new AbortController() + pendingSeed: Record = {} log = getLogger({ component: "unlocker" }) constructor(settings: MainSettings, storage: Storage) { this.settings = settings @@ -23,7 +26,7 @@ export class Unlocker { this.abortController.abort() } - Unlock = async () => { + getCreds = () => { const macroonPath = this.settings.lndSettings.mainNode.lndMacaroonPath const certPath = this.settings.lndSettings.mainNode.lndCertPath let macaroon = "" @@ -40,6 +43,48 @@ export class Unlocker { throw err } } + return { lndCert, macaroon } + } + + IsInitialized = async () => { + const { macaroon } = await this.getCreds() + return macaroon !== '' + } + + InitInteractive = async (): Promise<{ alreadyInitizialized: true } | { alreadyInitizialized: false, seed: string[], confirmationId: string }> => { + const { lndCert, macaroon } = await this.getCreds() + if (macaroon !== '') { + const { ln, pub } = await this.UnlockFlow(lndCert, macaroon) + this.subscribeToBackups(ln, pub) + return { alreadyInitizialized: true } + } + const unlocker = this.GetUnlockerClient(lndCert) + const seed = await this.genSeed(unlocker) + const confirmationId = crypto.randomBytes(32).toString('hex') + this.pendingSeed[confirmationId] = seed.encryptedSeed + return { alreadyInitizialized: false, seed: seed.plaintextSeed, confirmationId } + } + + ConfirmInitInteractive = async (confirmationId: string) => { + const { lndCert, macaroon } = await this.getCreds() + if (macaroon !== '') { + const { ln, pub } = await this.UnlockFlow(lndCert, macaroon) + this.subscribeToBackups(ln, pub) + return { alreadyInitizialized: true } + } + const seed = this.pendingSeed[confirmationId] + if (!seed) { + throw new Error("seed not found") + } + delete this.pendingSeed[confirmationId] + const plaintextSeed = this.DecryptWalletSeed(seed) + const unlocker = this.GetUnlockerClient(lndCert) + const { ln, pub } = await this.initWallet(lndCert, unlocker, { plaintextSeed, encryptedSeed: seed }) + this.subscribeToBackups(ln, pub) + } + + Unlock = async () => { + const { lndCert, macaroon } = await this.getCreds() const { ln, pub } = macaroon === "" ? await this.InitFlow(lndCert) : await this.UnlockFlow(lndCert, macaroon) this.subscribeToBackups(ln, pub) } @@ -69,15 +114,24 @@ export class Unlocker { InitFlow = async (lndCert: Buffer) => { this.log("macaroon not found, creating wallet...") const unlocker = this.GetUnlockerClient(lndCert) + const { plaintextSeed, encryptedSeed } = await this.genSeed(unlocker) + return this.initWallet(lndCert, unlocker, { plaintextSeed, encryptedSeed }) + } + + genSeed = async (unlocker: WalletUnlockerClient): Promise => { const entropy = crypto.randomBytes(16) const seedRes = await unlocker.genSeed({ aezeedPassphrase: Buffer.alloc(0), seedEntropy: entropy }, DeadLineMetadata()) - this.log("seed created, encrypting and saving...") + this.log("seed created") const { encryptedData } = this.EncryptWalletSeed(seedRes.response.cipherSeedMnemonic) + return { plaintextSeed: seedRes.response.cipherSeedMnemonic, encryptedSeed: encryptedData } + } + + initWallet = async (lndCert: Buffer, unlocker: WalletUnlockerClient, seed: Seed) => { const walletPw = this.GetWalletPassword() - const req = InitWalletReq(walletPw, seedRes.response.cipherSeedMnemonic) + const req = InitWalletReq(walletPw, seed.plaintextSeed) const initRes = await unlocker.initWallet(req, DeadLineMetadata(60 * 1000)) const adminMacaroon = Buffer.from(initRes.response.adminMacaroon).toString('hex') const ln = this.GetLightningClient(lndCert, adminMacaroon) @@ -94,11 +148,13 @@ export class Unlocker { if (!info || !info.ok) { throw new Error("failed to init lnd wallet " + (info ? info.failure : "unknown error")) } - await this.storage.liquidityStorage.SaveNodeSeed(info.pub, JSON.stringify(encryptedData)) + await this.storage.liquidityStorage.SaveNodeSeed(info.pub, JSON.stringify(seed.encryptedSeed)) this.log("created wallet with pub:", info.pub) return { ln, pub: info.pub } } + + GetLndInfo = async (ln: LightningClient): Promise<{ ok: false, failure: 'locked' | 'unknown' } | { ok: true, pub: string }> => { while (true) { try { diff --git a/src/services/wizard/index.ts b/src/services/wizard/index.ts new file mode 100644 index 00000000..a9f280f5 --- /dev/null +++ b/src/services/wizard/index.ts @@ -0,0 +1,131 @@ +import fs from 'fs' +import path from 'path'; +import { config as loadEnvFile } from 'dotenv' +import { getLogger } from "../helpers/logger.js" +import NewWizardServer from "../../../proto/wizard_service/autogenerated/ts/express_server.js" +import * as WizardTypes from "../../../proto/wizard_service/autogenerated/ts/types.js" +import { MainSettings } from "../main/settings.js" +import Storage from '../storage/index.js' +import { Unlocker } from "../main/unlocker.js" +export type WizardSettings = { + sourceName: string + relayUrl: string + automateLiquidity: boolean + pushBackupsToNostr: boolean +} +const defaultProviderPub = "" +export class Wizard { + log = getLogger({ component: "wizard" }) + settings: MainSettings + unlocker: Unlocker + initialized = false + configQueue: { res: (reload: boolean) => void }[] = [] + pendingConfig: WizardSettings | null = null + constructor(mainSettings: MainSettings, storage: Storage) { + this.settings = mainSettings + this.log('Starting wizard...') + this.unlocker = new Unlocker(mainSettings, storage) + const wizardServer = NewWizardServer({ + WizardState: async () => { return { already_initialized: await this.IsInitialized() } }, + WizardConfig: async ({ req }) => { return this.wizardConfig(req) }, + WizardConfirm: async ({ req }) => { return this.wizardConfirm(req) }, + }, { GuestAuthGuard: async () => "", metricsCallback: () => { }, staticFiles: 'static' }) + wizardServer.Listen(mainSettings.servicePort + 1) + } + + IsInitialized = () => { + if (this.initialized) { + return true + } + return this.unlocker.IsInitialized() + } + + WaitUntilConfigured = async (): Promise => { + if (this.initialized) { + return false + } + return new Promise((res) => { + this.configQueue.push({ res }) + }) + } + + wizardConfig = async (req: WizardTypes.ConfigRequest): Promise => { + const err = WizardTypes.ConfigRequestValidate(req, { + source_name_CustomCheck: source => source !== '', + relay_url_CustomCheck: relay => relay !== '', + }) + if (err != null) { throw new Error(err.message) } + + const res = await this.unlocker.InitInteractive() + if (res.alreadyInitizialized) { + this.initialized = true + this.configQueue.forEach(q => q.res(false)) + return { already_initialized: true, confirmation_id: "", seed: [] } + } + this.pendingConfig = { sourceName: req.source_name, relayUrl: req.relay_url, automateLiquidity: req.automate_liquidity, pushBackupsToNostr: req.push_backups_to_nostr } + return { already_initialized: false, confirmation_id: res.confirmationId, seed: res.seed } + + } + + wizardConfirm = async (req: WizardTypes.ConfirmRequest): Promise => { + const err = WizardTypes.ConfirmRequestValidate(req, { + confirmation_id_CustomCheck: conf => conf !== '', + }) + if (err != null) { throw new Error(err.message) } + + const res = await this.unlocker.ConfirmInitInteractive(req.confirmation_id) + if (res?.alreadyInitizialized) { + this.initialized = true + this.configQueue.forEach(q => q.res(false)) + return { admin_key: "" } + } + this.initialized = true + this.updateEnvFile() + this.configQueue.forEach(q => q.res(true)) + return { admin_key: process.env.ADMIN_TOKEN || "" } + } + + updateEnvFile = () => { + if (!this.pendingConfig) { + return + } + let envFileContent: string[] = [] + try { + envFileContent = fs.readFileSync('.env', 'utf-8').split('\n') + } catch (err: any) { + if (err.code !== 'ENOENT') { + } + } + + const toMerge: string[] = [] + const sourceNameIndex = envFileContent.findIndex(line => line.startsWith('DEFAULT_APP_NAME')) + if (sourceNameIndex === -1) { + toMerge.push(`DEFAULT_APP_NAME=${this.pendingConfig.sourceName}`) + } else { + envFileContent[sourceNameIndex] = `DEFAULT_APP_NAME=${this.pendingConfig.sourceName}` + } + const relayUrlIndex = envFileContent.findIndex(line => line.startsWith('RELAY_URL')) + if (relayUrlIndex === -1) { + toMerge.push(`RELAY_URL=${this.pendingConfig.relayUrl}`) + } else { + envFileContent[relayUrlIndex] = `RELAY_URL=${this.pendingConfig.relayUrl}` + } + + const automateLiquidityIndex = envFileContent.findIndex(line => line.startsWith('LIQUIDITY_PROVIDER_PUB')) + if (automateLiquidityIndex === -1) { + toMerge.push(`LIQUIDITY_PROVIDER_PUB=${this.pendingConfig.automateLiquidity ? defaultProviderPub : ""}`) + } else { + envFileContent[automateLiquidityIndex] = `LIQUIDITY_PROVIDER_PUB=` + } + + const pushBackupsToNostrIndex = envFileContent.findIndex(line => line.startsWith('PUSH_BACKUPS_TO_NOSTR')) + if (pushBackupsToNostrIndex === -1) { + toMerge.push(`PUSH_BACKUPS_TO_NOSTR=${this.pendingConfig.pushBackupsToNostr ? 'true' : 'false'}`) + } else { + envFileContent[pushBackupsToNostrIndex] = `PUSH_BACKUPS_TO_NOSTR=${this.pendingConfig.pushBackupsToNostr ? 'true' : 'false'}` + } + const merged = [...envFileContent, ...toMerge].join('\n') + fs.writeFileSync('.env', merged) + loadEnvFile() + } +} \ No newline at end of file diff --git a/static/backup.html b/static/backup.html index 8b7b4bd0..f060dc92 100644 --- a/static/backup.html +++ b/static/backup.html @@ -1,102 +1,117 @@ - - - - - - - - - - Lightning.Pub - - - - -
- Lightning Pub logo - Lightning Pub logo -
-
-
- -

Choose a Recovery Method

-

- New Node! 🎉 It's important - to backup your keys. -

-
+ + + + + + + + + + Lightning.Pub + + + -
+ +
+ Lightning Pub logo + Lightning Pub logo +
-
-
-
- In addition to your seed phrase, you also need channel details to recover funds should your node experience a hardware failure. -
-
-
- It's important always to have the latest version of this file. Fortunately, it's small enough to automatically store on the Nostr relay. -
-
-
- If you did not choose the developers relay, be sure your relay has - adequate storage policies to hold NIP78 events. -
-
-
- -
- -
-
-
-
- -
- -
-
- -
-
+
+
+ +

Choose a Recovery Method

+

+ New Node! 🎉 It's important + to backup your keys. +

+
-
-
+
+ If you did not choose the developers relay, be sure your relay has + adequate storage policies to hold NIP78 events. +
+
+
+ +
+ +
+
+
+
+ +
+ +
+
+
+

+
+ + +
- - - +
+ +
+ Need Help? +
+ + + + + + \ No newline at end of file diff --git a/static/index.html b/static/index.html index 0270e2c4..6c22eea0 100644 --- a/static/index.html +++ b/static/index.html @@ -1,89 +1,111 @@ - - - - - - - - - Lightning.Pub - - - -
- Lightning Pub logo - Lightning Pub logo -
-
-
-

Setup your Pub

-

-

-
+ + + + + + + + + Lightning.Pub + + -
+ +
+ Lightning Pub logo + Lightning Pub logo +
-
-
- Give this node a name that wallet users will see: - -
+
+
+

Setup your Pub

+

+

+
-
- If you want to use a specific Nostr relay, enter it now: - -
+
-
- -
- -
- - -
-
- -
-
- - + +
+ If you want to use a specific Nostr relay, enter it now: + +
+ +
+ +
+ +
+ +
+

+
+ + + + + +
+ +
+ Need Help? +
+ + + + \ No newline at end of file diff --git a/static/liquidity.html b/static/liquidity.html index f281bc9b..3f406e75 100644 --- a/static/liquidity.html +++ b/static/liquidity.html @@ -1,93 +1,108 @@ - - - - - - - - - - Lightning.Pub - - - - -
- Lightning Pub logo - Lightning Pub logo -
-
-
- -

Manage Node Liquidity

-

- How do you want to manage Lightning channels? -

-
+ + + + + + + + + + Lightning.Pub + + + -
+ +
+ Lightning Pub logo + Lightning Pub logo +
-
-
- -
- -
-
- -
- -
- -
-
+
+
+ +

Manage Node Liquidity

+

+ How do you want to manage Lightning channels? +

+
-
-
+
+ +
+ +
+
+

+
+ + +
- - - +
+ +
+ Need Help? +
+ + + + + \ No newline at end of file diff --git a/static/seed.html b/static/seed.html index dc859d92..b17ce4da 100644 --- a/static/seed.html +++ b/static/seed.html @@ -1,180 +1,128 @@ - - - - - - - - - - Lightning.Pub - - - - -
- Lightning Pub logo - Lightning Pub logo -
-
-
- -

Seed Phrase

-

- Store your seed phrase somewhere safe, you will need it if something ever goes wrong with your node hard drive. -

-
+ + + + + + + + + + Lightning.Pub + + + -
+ +
+ Lightning Pub logo + Lightning Pub logo +
-
-
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
- 1 - albert -
-
+
+
+ +

Seed Phrase

+

+ Store your seed phrase somewhere safe, you will need it if something ever goes wrong with your node hard drive. +

+
- +
-
-
- -
- -
-
- -
-
+
+
+
-
-
+ +
+ - - - +
+ +
+ Need Help? +
+ + + + + + \ No newline at end of file diff --git a/static/status.html b/static/status.html new file mode 100644 index 00000000..b8f7ae84 --- /dev/null +++ b/static/status.html @@ -0,0 +1,145 @@ + + + + + + + + + + + + + Lightning.Pub + + + + + +
+ Lightning Pub logo + Lightning Pub logo +
+ +
+
+

Node Status

+

+
+ +
+ +
+
+
+
Public Node Name:
+
+ +
Nodey McNodeFace
+
+ +
+
+
+
+
Nostr Relay:
+
+ +
wss://relay.lightning.pub
+
+ +
+
+
+
+
Administrator:
+
+ npub12334556677889990 +
+
+
+
+
+ Reset +
+ +
+
+
+
+
+ +
+
+
+
Continue
+
+
+
+
+
+
Relay Status:
+
+ Connected +
+
+
+
Lightning Status:
+
+ Syncing +
+
+
+
+ Watchdog Status: +
+ +
+
+
+ No Alarms +
+
+
+ + +
+
+ + + + + + + \ No newline at end of file diff --git a/static/stauts.html b/static/stauts.html deleted file mode 100644 index 0e93a8fb..00000000 --- a/static/stauts.html +++ /dev/null @@ -1,148 +0,0 @@ - - - - - - - - - - - - Lightning.Pub - - - - -
- Lightning Pub logo - Lightning Pub logo -
- -
-
-

Node Status

-

-
- -
- -
-
-
-
Public Node Name:
-
- -
Nodey McNodeFace
-
- -
-
-
-
-
Nostr Relay:
-
- -
wss://relay.lightning.pub
-
- -
-
-
-
-
Administrator:
-
- npub12334556677889990 -
-
-
-
-
Reset -
- -
-
-
-
-
- -
-
-
-
Continue
-
-
-
-
-
-
Relay Status:
-
- Connected -
-
-
-
Lightning Status:
-
- Syncing -
-
-
-
- Watchdog Status: -
- -
-
-
- No Alarms -
-
-
- - -
-
- - - - - -