Compare commits
29
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
06f9cf6a57 | ||
|
|
e990901548 | ||
|
|
3b040ee22c | ||
|
|
a738d8002f | ||
|
|
c6790feb14 | ||
|
|
e0d6f3f1c4 | ||
|
|
96fe807c5d | ||
|
|
ea75083663 | ||
|
|
87ae34d4b7 | ||
|
|
da0e7ba427 | ||
|
|
68229be4b4 | ||
|
|
7d9d975312 | ||
|
|
1f948bbe13 | ||
|
|
e8c8ae6537 | ||
|
|
a564627221 | ||
|
|
da57da3656 | ||
|
|
34f503626d | ||
|
|
e84c55f897 | ||
|
|
b688c918c1 | ||
|
|
e261fdd776 | ||
|
|
a59996d5d4 | ||
|
|
64e83e25dc | ||
|
|
d7f9caaaf6 | ||
|
|
3d653a056c | ||
|
|
f54824cc44 | ||
|
|
768d2cbe2a | ||
|
|
efd36d0221 | ||
|
|
4684939e13 | ||
|
|
193ee20da4 |
+3
-1
@@ -59,7 +59,7 @@ LNBITS_EXTENSIONS_DEFAULT_INSTALL="tpos"
|
||||
# LNBITS_EXT_GITHUB_TOKEN=github_pat_xxxxxxxxxxxxxxxxxx
|
||||
|
||||
# which fundingsources are allowed in the admin ui
|
||||
# LNBITS_ALLOWED_FUNDING_SOURCES="VoidWallet, FakeWallet, CoreLightningWallet, CoreLightningRestWallet, LndRestWallet, EclairWallet, LndWallet, LnTipsWallet, LNPayWallet, LNbitsWallet, BlinkWallet, AlbyWallet, ZBDWallet, PhoenixdWallet, OpenNodeWallet, NWCWallet, BreezSdkWallet, BoltzWallet, StrikeWallet, CLNRestWallet"
|
||||
# LNBITS_ALLOWED_FUNDING_SOURCES="VoidWallet, FakeWallet, CoreLightningWallet, CoreLightningRestWallet, LndRestWallet, EclairWallet, LndWallet, LnTipsWallet, LNPayWallet, LNbitsWallet, BlinkWallet, AlbyWallet, ZBDWallet, PhoenixdWallet, OpenNodeWallet, NWCWallet, BreezSdkWallet, BoltzWallet, StrikeWallet, CLNRestWallet, SparkWallet, LightsparkSparkWallet"
|
||||
|
||||
# uvicorn variable, allow https behind a proxy
|
||||
# IMPORTANT: this also needs the webserver to be configured to forward the headers
|
||||
@@ -191,6 +191,8 @@ BOLTZ_CLIENT_MACAROON="/home/bob/.boltz/macaroons/admin.macaroon"
|
||||
# HEXSTRING instead of path also possible
|
||||
BOLTZ_CLIENT_CERT="/home/bob/.boltz/tls.cert"
|
||||
|
||||
# TODO: add Spark
|
||||
|
||||
# StrikeWallet
|
||||
STRIKE_API_ENDPOINT=https://api.strike.me/v1
|
||||
STRIKE_API_KEY=YOUR_STRIKE_API_KEY
|
||||
|
||||
@@ -57,7 +57,7 @@ Below is a side-by-side comparison of Lightning funding sources you can use with
|
||||
| **LN.tips** | Custodial/Self-Custodial | Depends on provider | Medium | ❌ | Low | Provider-managed | Moderate | Low | Transaction fees may apply | Medium | Simple hosted service; use LN.tips API as your backend. |
|
||||
| **Fake Wallet** | Testing (simulated) | ❌ | Low | ❌ | N/A | N/A | Easy | Low | None (test only) | N/A | For testing only; mints accounting units in LNbits (no real sats, unit name configurable). |
|
||||
|
||||
---
|
||||
## TODO: add Spark
|
||||
|
||||
### Notes for readers
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ A backend wallet is selected and configured entirely through LNbits environment
|
||||
|
||||
### CLNRest (using [runes](https://docs.corelightning.org/reference/lightning-createrune))
|
||||
|
||||
[Core Lightning REST API docs](https://docs.corelightning.org/docs/rest)
|
||||
[Core Lightning REST API docs](https://docs.corelightning.org/docs/rest)
|
||||
Should also work with the [Rust version of CLNRest](https://github.com/daywalker90/clnrest-rs)
|
||||
|
||||
**Environment variables**
|
||||
@@ -338,6 +338,8 @@ Configure in the admin UI or via env vars:
|
||||
|
||||
<a id="strike"></a>
|
||||
|
||||
## TODO: add Spark
|
||||
|
||||
## Strike (alpha)
|
||||
|
||||
Custodial provider integrated via **Strike OAuth Connect** (OAuth 2.0 / OIDC). Authenticate a Strike user in your app, then call Strike APIs on the user’s behalf once scopes are granted. Requires a Strike business account, registered OAuth client, minimal scopes, and login/logout redirect URLs.
|
||||
|
||||
@@ -318,6 +318,7 @@ class RegisterUser(BaseModel):
|
||||
username: str = Query(default=..., min_length=2, max_length=20)
|
||||
password: str = Query(default=..., min_length=8, max_length=50)
|
||||
password_repeat: str = Query(default=..., min_length=8, max_length=50)
|
||||
invitation_code: str | None = Query(default=None, max_length=256)
|
||||
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
|
||||
@@ -118,8 +118,8 @@ async def verify_paypal_webhook(headers, payload: bytes):
|
||||
"""
|
||||
webhook_id = settings.paypal_webhook_id
|
||||
if not webhook_id:
|
||||
logger.warning("PayPal webhook ID not set; skipping verification.")
|
||||
return
|
||||
logger.warning("PayPal webhook ID not set.")
|
||||
raise ValueError("PayPal webhook cannot be verified. Missing webhook ID.")
|
||||
|
||||
required_headers = {
|
||||
"PAYPAL-TRANSMISSION-ID": headers.get("PAYPAL-TRANSMISSION-ID"),
|
||||
@@ -129,8 +129,8 @@ async def verify_paypal_webhook(headers, payload: bytes):
|
||||
"PAYPAL-AUTH-ALGO": headers.get("PAYPAL-AUTH-ALGO"),
|
||||
}
|
||||
if not all(required_headers.values()):
|
||||
logger.warning("Missing PayPal webhook headers; skipping verification.")
|
||||
return
|
||||
logger.warning("Missing PayPal webhook headers.")
|
||||
raise ValueError("PayPal webhook cannot be verified. Missing headers.")
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(base_url=settings.paypal_api_endpoint) as client:
|
||||
|
||||
@@ -3,8 +3,10 @@ from uuid import uuid4
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from lnbits.core.crud.settings import set_settings_field
|
||||
from lnbits.core.db import db
|
||||
from lnbits.core.models.extensions import UserExtension
|
||||
from lnbits.core.models.users import RegisterUser
|
||||
from lnbits.db import Connection
|
||||
from lnbits.settings import (
|
||||
EditableSettings,
|
||||
@@ -192,3 +194,25 @@ async def init_admin_settings(super_user: str | None = None) -> SuperSettings:
|
||||
|
||||
editable_settings = EditableSettings.from_dict(settings.dict())
|
||||
return await create_admin_settings(account.id, editable_settings.dict())
|
||||
|
||||
|
||||
async def check_register_activation_settings(data: RegisterUser):
|
||||
if not settings.lnbits_require_user_activation:
|
||||
return None
|
||||
if settings.lnbits_user_activation_by_invitation_code:
|
||||
code = data.invitation_code.strip() if data.invitation_code else ""
|
||||
if len(code) == 0:
|
||||
raise ValueError("Invitation code cannot be empty.")
|
||||
|
||||
if code == settings.lnbits_register_reusable_activation_code:
|
||||
return None
|
||||
if code in settings.lnbits_register_one_time_activation_codes:
|
||||
settings.lnbits_register_one_time_activation_codes.remove(code)
|
||||
await set_settings_field(
|
||||
"lnbits_register_one_time_activation_codes",
|
||||
settings.lnbits_register_one_time_activation_codes,
|
||||
)
|
||||
return None
|
||||
raise ValueError("Invalid invitation code.")
|
||||
|
||||
raise ValueError("No activation method provided.")
|
||||
|
||||
@@ -26,7 +26,10 @@ from lnbits.core.models.users import (
|
||||
UpdateAccessControlList,
|
||||
)
|
||||
from lnbits.core.services import create_user_account
|
||||
from lnbits.core.services.users import update_user_account
|
||||
from lnbits.core.services.users import (
|
||||
check_register_activation_settings,
|
||||
update_user_account,
|
||||
)
|
||||
from lnbits.decorators import (
|
||||
access_token_payload,
|
||||
check_account_exists,
|
||||
@@ -366,6 +369,8 @@ async def register(data: RegisterUser) -> JSONResponse:
|
||||
if data.email and not is_valid_email_address(data.email):
|
||||
raise HTTPException(HTTPStatus.BAD_REQUEST, "Invalid email.")
|
||||
|
||||
await check_register_activation_settings(data)
|
||||
|
||||
account = Account(
|
||||
id=uuid4().hex,
|
||||
email=data.email,
|
||||
@@ -506,15 +511,21 @@ async def update_ui_customization(
|
||||
async def first_install(data: UpdateSuperuserPassword) -> JSONResponse:
|
||||
if not settings.first_install:
|
||||
raise HTTPException(HTTPStatus.FORBIDDEN, "This is not your first install")
|
||||
|
||||
if settings.first_install_token:
|
||||
if not data.first_install_token:
|
||||
raise HTTPException(HTTPStatus.UNAUTHORIZED, "Missing first_install_token.")
|
||||
if settings.first_install_token != data.first_install_token:
|
||||
raise HTTPException(HTTPStatus.UNAUTHORIZED, "Invalid first_install_token.")
|
||||
|
||||
account = await get_account_by_username(data.username, False)
|
||||
if account:
|
||||
raise HTTPException(HTTPStatus.BAD_REQUEST, "Username already exists.")
|
||||
|
||||
account = await get_account(settings.super_user)
|
||||
if not account:
|
||||
raise HTTPException(HTTPStatus.INTERNAL_SERVER_ERROR, "Superuser not found.")
|
||||
|
||||
account.username = data.username
|
||||
account.extra = account.extra or UserExtra()
|
||||
account.extra.provider = "lnbits"
|
||||
|
||||
@@ -41,6 +41,14 @@ class UsersSettings(LNbitsSettings):
|
||||
lnbits_admin_users: list[str] = Field(default=[])
|
||||
lnbits_allowed_users: list[str] = Field(default=[])
|
||||
lnbits_allow_new_accounts: bool = Field(default=True)
|
||||
lnbits_require_user_activation: bool = Field(default=False)
|
||||
|
||||
lnbits_user_activation_by_email: bool = Field(default=False)
|
||||
lnbits_user_activation_by_payment: bool = Field(default=False)
|
||||
lnbits_user_activation_by_invitation_code: bool = Field(default=False)
|
||||
|
||||
lnbits_register_reusable_activation_code: str = Field(default="")
|
||||
lnbits_register_one_time_activation_codes: list[str] = Field(default=[])
|
||||
|
||||
@property
|
||||
def new_accounts_allowed(self) -> bool:
|
||||
@@ -594,6 +602,17 @@ class SparkFundingSource(LNbitsSettings):
|
||||
spark_token: str | None = Field(default=None)
|
||||
|
||||
|
||||
class SparkL2FundingSource(LNbitsSettings):
|
||||
spark_l2_mnemonic: str | None = Field(default=None)
|
||||
spark_l2_network: str = Field(default="MAINNET")
|
||||
spark_l2_internal_sidecar_version: str | None = Field(default="0.1.1")
|
||||
spark_l2_external_endpoint: str | None = Field(default=None)
|
||||
spark_l2_external_api_key: str | None = Field(default=None)
|
||||
spark_l2_pay_wait_ms: int = Field(default=4000, ge=0)
|
||||
spark_l2_pay_poll_ms: int = Field(default=500, ge=0)
|
||||
spark_l2_stream_keepalive_ms: int = Field(default=15000, ge=0)
|
||||
|
||||
|
||||
class LnTipsFundingSource(LNbitsSettings):
|
||||
lntips_api_endpoint: str | None = Field(default=None)
|
||||
lntips_api_key: str | None = Field(default=None)
|
||||
@@ -699,6 +718,7 @@ class FundingSourcesSettings(
|
||||
PhoenixdFundingSource,
|
||||
OpenNodeFundingSource,
|
||||
SparkFundingSource,
|
||||
SparkL2FundingSource,
|
||||
LnTipsFundingSource,
|
||||
NWCFundingSource,
|
||||
BreezSdkFundingSource,
|
||||
@@ -1027,6 +1047,7 @@ class SuperUserSettings(LNbitsSettings):
|
||||
"FakeWallet",
|
||||
"LNPayWallet",
|
||||
"LNbitsWallet",
|
||||
"LightsparkSparkWallet",
|
||||
"LnTipsWallet",
|
||||
"LndRestWallet",
|
||||
"LndWallet",
|
||||
@@ -1188,6 +1209,11 @@ class PublicSettings(BaseModel):
|
||||
wallet_featured_button_label: str | None = Field(alias="walletFeaturedButtonLabel")
|
||||
wallet_featured_button_url: str | None = Field(alias="walletFeaturedButtonUrl")
|
||||
wallet_featured_button_icon: str | None = Field(alias="walletFeaturedButtonIcon")
|
||||
lnbits_user_activation_by_email: bool = Field(alias="userActivationByEmail")
|
||||
lnbits_user_activation_by_payment: bool = Field(alias="userActivationByPayment")
|
||||
lnbits_user_activation_by_invitation_code: bool = Field(
|
||||
alias="userActivationByInvitationCode"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_settings(cls, settings: Settings):
|
||||
@@ -1239,6 +1265,9 @@ class PublicSettings(BaseModel):
|
||||
walletFeaturedButtonLabel=settings.lnbits_wallet_featured_button_label,
|
||||
walletFeaturedButtonUrl=settings.lnbits_wallet_featured_button_url,
|
||||
walletFeaturedButtonIcon=settings.lnbits_wallet_featured_button_icon,
|
||||
userActivationByEmail=settings.lnbits_user_activation_by_email,
|
||||
userActivationByPayment=settings.lnbits_user_activation_by_payment,
|
||||
userActivationByInvitationCode=settings.lnbits_user_activation_by_invitation_code,
|
||||
)
|
||||
|
||||
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+1
-1
File diff suppressed because one or more lines are too long
@@ -171,6 +171,7 @@ window.localisation.en = {
|
||||
drop_db: 'Remove Data',
|
||||
enable: 'Enable',
|
||||
enabled: 'Enabled',
|
||||
disabled: 'Disabled',
|
||||
pay_to_enable: 'Pay To Enable',
|
||||
enable_extension_details: 'Enable extension for current user',
|
||||
disable: 'Disable',
|
||||
@@ -284,7 +285,7 @@ window.localisation.en = {
|
||||
'Nip5 identifier to send notifications to',
|
||||
notifications_nostr_identifiers: 'Nostr Identifiers',
|
||||
notifications_nostr_identifiers_desc:
|
||||
'List of identifiers to send notifications to',
|
||||
'List of identifiers to send notifications to.',
|
||||
|
||||
notifications_telegram_config: 'Telegram Configuration',
|
||||
notifications_enable_telegram: 'Enable Telegram',
|
||||
@@ -708,6 +709,25 @@ window.localisation.en = {
|
||||
allowed_users_label: 'User ID',
|
||||
allow_creation_user: 'Allow creation of new users',
|
||||
allow_creation_user_desc: 'Allow creation of new users on the index page',
|
||||
require_user_activation: 'Require user activation',
|
||||
require_user_activation_desc:
|
||||
'New users will be activated only after they pass one of the confirmation methods. Admins can activate users manually from the admin panel.',
|
||||
reusable_activation_code: 'Reusable activation code',
|
||||
reusable_activation_code_label: 'Reusable activation code',
|
||||
reusable_activation_code_hint:
|
||||
'This activation code can be used multiple times by different users.',
|
||||
one_time_activation_code: 'One-time activation codes',
|
||||
one_time_activation_code_label: 'Add activation code',
|
||||
one_time_activation_code_hint:
|
||||
'List of one-time activation codes. Each code can be used only once, then will be reomved from the list.',
|
||||
invitation_code: 'Invitation Code',
|
||||
invitation_code_hint: 'The invitation code that you have received.',
|
||||
email: 'Email',
|
||||
email_confirmation_hint: 'Email address to send the confirmation code to.',
|
||||
nostr_identifier: 'Nostr Identifier',
|
||||
nostr_identifier_hint:
|
||||
'Nostr nip5 identifier or <npub> to send the confirmation code to.',
|
||||
|
||||
new_user_not_allowed: 'Registration is disabled.',
|
||||
start_user_impersonation: 'Impersonate this user',
|
||||
stop_user_impersonation: 'Stop User Impersonation',
|
||||
|
||||
@@ -66,7 +66,7 @@ window._lnbitsApi = {
|
||||
name: name
|
||||
})
|
||||
},
|
||||
register(username, email, password, password_repeat) {
|
||||
register(username, email, password, password_repeat, invitation_code) {
|
||||
return axios({
|
||||
method: 'POST',
|
||||
url: '/api/v1/auth/register',
|
||||
@@ -74,7 +74,8 @@ window._lnbitsApi = {
|
||||
username,
|
||||
email,
|
||||
password,
|
||||
password_repeat
|
||||
password_repeat,
|
||||
invitation_code
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
@@ -432,8 +432,10 @@ window.app.component('username-password', {
|
||||
username: String,
|
||||
password_1: String,
|
||||
password_2: String,
|
||||
invitationCode: String,
|
||||
resetKey: String
|
||||
},
|
||||
|
||||
data() {
|
||||
return {
|
||||
oauth: [
|
||||
@@ -445,7 +447,11 @@ window.app.component('username-password', {
|
||||
username: this.userName,
|
||||
password: this.password_1,
|
||||
passwordRepeat: this.password_2,
|
||||
reset_key: this.resetKey
|
||||
reset_key: this.resetKey,
|
||||
confirmationMethod: 'code',
|
||||
confirmationEmail: '',
|
||||
confirmationCode: this.invitationCode || '',
|
||||
showConfirmationCode: false
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
@@ -458,6 +464,7 @@ window.app.component('username-password', {
|
||||
this.$emit('update:userName', this.username)
|
||||
this.$emit('update:password_1', this.password)
|
||||
this.$emit('update:password_2', this.passwordRepeat)
|
||||
this.$emit('update:invitationCode', this.confirmationCode)
|
||||
this.$emit('register')
|
||||
},
|
||||
reset() {
|
||||
@@ -549,6 +556,25 @@ window.app.component('username-password', {
|
||||
computed: {
|
||||
showOauth() {
|
||||
return this.oauth.some(m => this.authMethods.includes(m))
|
||||
},
|
||||
disableRegister() {
|
||||
const usernameOK = !!this.username
|
||||
const passwordOK = !!this.password && this.password.length >= 8
|
||||
const passwordsMatch = this.password === this.passwordRepeat
|
||||
const codeOk =
|
||||
this.confirmationMethodsCount === 0 ||
|
||||
this.confirmationMethod !== 'code' ||
|
||||
this.confirmationCode.length > 0
|
||||
|
||||
return !usernameOK || !passwordOK || !passwordsMatch || !codeOk
|
||||
},
|
||||
confirmationMethodsCount() {
|
||||
const methods = [
|
||||
this.g.settings.userActivationByEmail,
|
||||
this.g.settings.userActivationByPayment,
|
||||
this.g.settings.userActivationByInvitationCode
|
||||
]
|
||||
return methods.filter(Boolean).length
|
||||
}
|
||||
},
|
||||
created() {}
|
||||
|
||||
@@ -228,6 +228,51 @@ window.app.component('lnbits-admin-funding-sources', {
|
||||
spark_token: 'Token'
|
||||
}
|
||||
],
|
||||
[
|
||||
'LightsparkSparkWallet',
|
||||
'Spark (L2)',
|
||||
{
|
||||
spark_l2_internal_sidecar_version: {
|
||||
label: 'Internal Sidecar Version (eg: 0.1.1).',
|
||||
hint: 'If specified then the sidecar will be downloaded. Alternatively you can specify an External Sidecar endpoint in the Advanced section.',
|
||||
value: ''
|
||||
},
|
||||
spark_l2_mnemonic: {
|
||||
label: 'Mnemonic',
|
||||
hint: 'Only required if Interna Sidecar version is specified.'
|
||||
},
|
||||
spark_l2_network: {
|
||||
label: 'Network',
|
||||
value: 'MAINNET'
|
||||
},
|
||||
|
||||
spark_l2_external_endpoint: {
|
||||
label: 'External Sidecar Endpoint. ',
|
||||
hint: 'If specified then this endpoint will be used instead of the internal sidecar. Make sure to also specify the API key if your sidecar requires authentication.',
|
||||
value: '',
|
||||
advanced: true
|
||||
},
|
||||
spark_l2_external_api_key: {
|
||||
label: 'External Sidecar API Key. ',
|
||||
hint: 'API Key for authenticating with the external sidecar if it requires authentication.',
|
||||
value: '',
|
||||
advanced: true
|
||||
},
|
||||
|
||||
spark_l2_pay_wait_ms: {
|
||||
label: 'Pay Wait Time (ms)',
|
||||
advanced: true
|
||||
},
|
||||
spark_l2_pay_poll_ms: {
|
||||
label: 'Pay Poll Time (ms)',
|
||||
advanced: true
|
||||
},
|
||||
spark_l2_stream_keepalive_ms: {
|
||||
label: 'Stream Keepalive Time (ms)',
|
||||
advanced: true
|
||||
}
|
||||
}
|
||||
],
|
||||
[
|
||||
'NWCWallet',
|
||||
'Nostr Wallet Connect',
|
||||
|
||||
@@ -4,7 +4,9 @@ window.app.component('lnbits-admin-users', {
|
||||
data() {
|
||||
return {
|
||||
formAddUser: '',
|
||||
formAddAdmin: ''
|
||||
formAddAdmin: '',
|
||||
formAddActivationCode: '',
|
||||
showReusableActivationCode: false
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
@@ -31,6 +33,24 @@ window.app.component('lnbits-admin-users', {
|
||||
removeAdminUser(user) {
|
||||
let admin_users = this.formData.lnbits_admin_users
|
||||
this.formData.lnbits_admin_users = admin_users.filter(u => u !== user)
|
||||
},
|
||||
addOneTimeActivationCode() {
|
||||
const code = this.formAddActivationCode
|
||||
const activationCodes =
|
||||
this.formData.lnbits_register_one_time_activation_codes
|
||||
if (code?.length && !activationCodes.includes(code)) {
|
||||
this.formData.lnbits_register_one_time_activation_codes = [
|
||||
...activationCodes,
|
||||
code
|
||||
]
|
||||
this.formAddActivationCode = ''
|
||||
}
|
||||
},
|
||||
removeOneTimeActivationCode(code) {
|
||||
const codes = this.formData.lnbits_register_one_time_activation_codes
|
||||
this.formData.lnbits_register_one_time_activation_codes = codes.filter(
|
||||
u => u !== code
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -11,6 +11,7 @@ window.PageHome = {
|
||||
email: '',
|
||||
password: '',
|
||||
passwordRepeat: '',
|
||||
invitationCode: '',
|
||||
walletName: '',
|
||||
signup: false
|
||||
}
|
||||
@@ -40,6 +41,7 @@ window.PageHome = {
|
||||
this.username = null
|
||||
this.password = null
|
||||
this.passwordRepeat = null
|
||||
this.invitationCode = null
|
||||
|
||||
this.authAction = 'register'
|
||||
this.authMethod = authMethod
|
||||
@@ -51,7 +53,8 @@ window.PageHome = {
|
||||
this.username,
|
||||
this.email,
|
||||
this.password,
|
||||
this.passwordRepeat
|
||||
this.passwordRepeat,
|
||||
this.invitationCode
|
||||
)
|
||||
this.refreshAuthUser()
|
||||
} catch (e) {
|
||||
|
||||
@@ -814,16 +814,90 @@ include('components/lnbits-error.vue') %}
|
||||
type="password"
|
||||
:rules="[val => !val || val.length >= 8 || $t('invalid_password')]"
|
||||
></q-input>
|
||||
<div
|
||||
v-if="confirmationMethodsCount > 1"
|
||||
class="row justify-center q-mb-md"
|
||||
>
|
||||
<q-tabs
|
||||
v-model="confirmationMethod"
|
||||
dense
|
||||
active-color="primary"
|
||||
indicator-color="primary"
|
||||
>
|
||||
<q-tab
|
||||
v-if="g.settings.userActivationByInvitationCode"
|
||||
name="code"
|
||||
icon="confirmation_number"
|
||||
label="Code"
|
||||
></q-tab>
|
||||
<q-tab
|
||||
v-if="g.settings.userActivationByPayment"
|
||||
name="payment"
|
||||
icon="bolt"
|
||||
label="Payment"
|
||||
></q-tab>
|
||||
<q-tab
|
||||
v-if="g.settings.userActivationByEmail"
|
||||
name="email"
|
||||
icon="email"
|
||||
label="Email"
|
||||
></q-tab>
|
||||
</q-tabs>
|
||||
</div>
|
||||
<div v-if="confirmationMethodsCount > 0" class="q-mb-md">
|
||||
<q-tab-panels v-model="confirmationMethod">
|
||||
<q-tab-panel name="code" class="q-pa-none">
|
||||
<div
|
||||
class="q-my-md q-pa-sm text-body2 text-grey-4 bg-grey-9 rounded-borders"
|
||||
>
|
||||
<q-icon name="info" color="orange-4" class="q-mr-xs"></q-icon>
|
||||
You need an invitation code to register.
|
||||
</div>
|
||||
<div>
|
||||
<q-input
|
||||
dense
|
||||
filled
|
||||
v-model="confirmationCode"
|
||||
:label="$t('invitation_code')"
|
||||
:type="showConfirmationCode ? 'text' : 'password'"
|
||||
:hint="$t('invitation_code_hint')"
|
||||
>
|
||||
<q-btn
|
||||
@click="showConfirmationCode = !showConfirmationCode"
|
||||
dense
|
||||
flat
|
||||
:icon="
|
||||
showConfirmationCode ? 'visibility_off' : 'visibility'
|
||||
"
|
||||
color="grey"
|
||||
></q-btn>
|
||||
</q-input>
|
||||
</div>
|
||||
</q-tab-panel>
|
||||
<q-tab-panel name="payment">
|
||||
<div>payment</div>
|
||||
</q-tab-panel>
|
||||
|
||||
<q-tab-panel name="email" class="q-pa-none">
|
||||
<div>
|
||||
<q-input
|
||||
dense
|
||||
filled
|
||||
v-model="confirmationEmail"
|
||||
:label="$t('email')"
|
||||
:hint="$t('email_confirmation_hint')"
|
||||
>
|
||||
</q-input>
|
||||
</div>
|
||||
</q-tab-panel>
|
||||
</q-tab-panels>
|
||||
</div>
|
||||
|
||||
<div class="row justify-end">
|
||||
<q-btn
|
||||
unelevated
|
||||
color="primary"
|
||||
:disable="
|
||||
!password ||
|
||||
!passwordRepeat ||
|
||||
!username ||
|
||||
password !== passwordRepeat
|
||||
"
|
||||
:disable="disableRegister"
|
||||
type="submit"
|
||||
class="full-width"
|
||||
:label="$t('create_account')"
|
||||
|
||||
@@ -310,7 +310,13 @@
|
||||
<div class="col-12 col-md-6">
|
||||
<q-select
|
||||
filled
|
||||
:options="[$t('second'), $t('minute'), $t('hour')]"
|
||||
:options="[
|
||||
{label: $t('second'), value: 'second'},
|
||||
{label: $t('minute'), value: 'minute'},
|
||||
{label: $t('hour'), value: 'hour'}
|
||||
]"
|
||||
emit-value
|
||||
map-options
|
||||
v-model="formData.lnbits_rate_limit_unit"
|
||||
:label="$t('time_unit')"
|
||||
></q-select>
|
||||
|
||||
@@ -30,7 +30,6 @@
|
||||
>
|
||||
</q-chip>
|
||||
</div>
|
||||
<br />
|
||||
</div>
|
||||
<div class="col-12 col-md-6">
|
||||
<p><span v-text="$t('allowed_users')"></span></p>
|
||||
@@ -57,7 +56,10 @@
|
||||
>
|
||||
</q-chip>
|
||||
</div>
|
||||
<br />
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-12 col-md-6 q-mt-sm">
|
||||
<q-item tag="label" v-ripple>
|
||||
<q-item-section>
|
||||
<q-item-label v-text="$t('allow_creation_user')"></q-item-label>
|
||||
@@ -76,8 +78,237 @@
|
||||
/>
|
||||
</q-item-section>
|
||||
</q-item>
|
||||
<br />
|
||||
</div>
|
||||
<div class="col-12 col-md-6 q-mt-sm">
|
||||
<q-item tag="label" v-ripple>
|
||||
<q-item-section>
|
||||
<q-item-label v-text="$t('require_user_activation')"></q-item-label>
|
||||
<q-item-label
|
||||
caption
|
||||
v-text="$t('require_user_activation_desc')"
|
||||
></q-item-label>
|
||||
</q-item-section>
|
||||
<q-item-section avatar>
|
||||
<q-toggle
|
||||
size="md"
|
||||
v-model="formData.lnbits_require_user_activation"
|
||||
checked-icon="check"
|
||||
color="green"
|
||||
unchecked-icon="clear"
|
||||
/>
|
||||
</q-item-section>
|
||||
</q-item>
|
||||
</div>
|
||||
</div>
|
||||
</q-card-section>
|
||||
<div v-if="formData.lnbits_require_user_activation" class="row">
|
||||
<div class="col">
|
||||
<q-list bordered class="rounded-borders">
|
||||
<q-expansion-item header-class="text-primary text-bold">
|
||||
<template v-slot:header>
|
||||
<q-item-section avatar>
|
||||
<q-icon name="confirmation_number" size="md"></q-icon>
|
||||
</q-item-section>
|
||||
|
||||
<q-item-section> Invitation Code </q-item-section>
|
||||
|
||||
<q-item-section side>
|
||||
<div class="row items-center">
|
||||
<q-toggle
|
||||
size="md"
|
||||
:label="
|
||||
formData.lnbits_user_activation_by_invitation_code
|
||||
? $t('enabled')
|
||||
: $t('disabled')
|
||||
"
|
||||
v-model="formData.lnbits_user_activation_by_invitation_code"
|
||||
color="green"
|
||||
unchecked-icon="clear"
|
||||
/>
|
||||
</div>
|
||||
</q-item-section>
|
||||
</template>
|
||||
|
||||
<q-card class="q-pb-xl">
|
||||
<q-card-section>
|
||||
<div
|
||||
class="q-my-md q-pa-sm text-body2 text-grey-4 bg-grey-9 rounded-borders"
|
||||
>
|
||||
<q-icon
|
||||
name="info"
|
||||
color="orange-4"
|
||||
size="18px"
|
||||
class="q-mr-xs"
|
||||
></q-icon>
|
||||
Users will need to provide a valid invitation code during
|
||||
registration to activate their account.
|
||||
</div>
|
||||
</q-card-section>
|
||||
<q-card-section>
|
||||
<div class="row">
|
||||
<div class="col-12 col-md-6 q-pr-sm">
|
||||
<p><span v-text="$t('reusable_activation_code')"></span></p>
|
||||
<q-input
|
||||
filled
|
||||
v-model="formData.lnbits_register_reusable_activation_code"
|
||||
:type="showReusableActivationCode ? 'text' : 'password'"
|
||||
:label="$t('reusable_activation_code_label')"
|
||||
:hint="$t('reusable_activation_code_hint')"
|
||||
>
|
||||
<q-btn
|
||||
@click="
|
||||
showReusableActivationCode = !showReusableActivationCode
|
||||
"
|
||||
dense
|
||||
flat
|
||||
:icon="
|
||||
showReusableActivationCode
|
||||
? 'visibility_off'
|
||||
: 'visibility'
|
||||
"
|
||||
color="grey"
|
||||
></q-btn>
|
||||
<q-btn
|
||||
@click="
|
||||
utils.copyText(
|
||||
formData.lnbits_register_reusable_activation_code
|
||||
)
|
||||
"
|
||||
dense
|
||||
flat
|
||||
icon="content_copy"
|
||||
color="grey"
|
||||
></q-btn>
|
||||
</q-input>
|
||||
</div>
|
||||
<div class="col-12 col-md-6">
|
||||
<p><span v-text="$t('one_time_activation_code')"></span></p>
|
||||
<q-input
|
||||
filled
|
||||
v-model="formAddActivationCode"
|
||||
@keydown.enter="addOneTimeActivationCode"
|
||||
type="text"
|
||||
:label="$t('one_time_activation_code_label')"
|
||||
:hint="$t('one_time_activation_code_hint')"
|
||||
>
|
||||
<q-btn
|
||||
@click="addOneTimeActivationCode"
|
||||
dense
|
||||
flat
|
||||
icon="add"
|
||||
></q-btn>
|
||||
</q-input>
|
||||
<div>
|
||||
<q-chip
|
||||
v-for="code in formData.lnbits_register_one_time_activation_codes"
|
||||
:key="code"
|
||||
removable
|
||||
@remove="removeOneTimeActivationCode(code)"
|
||||
color="primary"
|
||||
text-color="white"
|
||||
:label="code"
|
||||
class="ellipsis"
|
||||
>
|
||||
</q-chip>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</q-card-section>
|
||||
</q-card>
|
||||
</q-expansion-item>
|
||||
<q-separator></q-separator>
|
||||
|
||||
<q-expansion-item header-class="text-primary text-bold">
|
||||
<template v-slot:header>
|
||||
<q-item-section avatar>
|
||||
<q-avatar>
|
||||
<q-icon name="bolt" size="md"></q-icon>
|
||||
</q-avatar>
|
||||
</q-item-section>
|
||||
|
||||
<q-item-section> Payment </q-item-section>
|
||||
|
||||
<q-item-section side>
|
||||
<div class="row items-center">
|
||||
<q-toggle
|
||||
size="md"
|
||||
disable
|
||||
:label="
|
||||
formData.lnbits_user_activation_by_payment
|
||||
? $t('enabled')
|
||||
: $t('disabled')
|
||||
"
|
||||
v-model="formData.lnbits_user_activation_by_payment"
|
||||
color="green"
|
||||
unchecked-icon="clear"
|
||||
/>
|
||||
</div>
|
||||
</q-item-section>
|
||||
</template>
|
||||
|
||||
<q-card class="q-pb-xl">
|
||||
<q-card-section>
|
||||
<div
|
||||
class="q-my-md q-pa-sm text-body2 text-grey-4 bg-grey-9 rounded-borders"
|
||||
>
|
||||
<q-icon
|
||||
name="info"
|
||||
color="orange-4"
|
||||
size="18px"
|
||||
class="q-mr-xs"
|
||||
></q-icon>
|
||||
Users will need to make a payment during registration to
|
||||
activate their account.
|
||||
</div>
|
||||
</q-card-section>
|
||||
</q-card>
|
||||
</q-expansion-item>
|
||||
<q-separator></q-separator>
|
||||
<q-expansion-item header-class="text-primary text-bold">
|
||||
<template v-slot:header>
|
||||
<q-item-section avatar>
|
||||
<q-avatar>
|
||||
<q-icon name="email"></q-icon>
|
||||
</q-avatar>
|
||||
</q-item-section>
|
||||
|
||||
<q-item-section> Email </q-item-section>
|
||||
|
||||
<q-item-section side>
|
||||
<div class="row items-center">
|
||||
<q-toggle
|
||||
disable
|
||||
size="md"
|
||||
:label="
|
||||
formData.lnbits_user_activation_by_email
|
||||
? $t('enabled')
|
||||
: $t('disabled')
|
||||
"
|
||||
v-model="formData.lnbits_user_activation_by_email"
|
||||
color="green"
|
||||
unchecked-icon="clear"
|
||||
/>
|
||||
</div>
|
||||
</q-item-section>
|
||||
</template>
|
||||
|
||||
<q-card class="q-pb-xl">
|
||||
<q-card-section>
|
||||
<div
|
||||
class="q-my-md q-pa-sm text-body2 text-grey-4 bg-grey-9 rounded-borders"
|
||||
>
|
||||
<q-icon
|
||||
name="info"
|
||||
color="orange-4"
|
||||
size="18px"
|
||||
class="q-mr-xs"
|
||||
></q-icon>
|
||||
Users will receive a confirmation email.
|
||||
</div>
|
||||
</q-card-section>
|
||||
</q-card>
|
||||
</q-expansion-item>
|
||||
</q-list>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -63,6 +63,7 @@
|
||||
v-model:user-name="username"
|
||||
v-model:password_1="password"
|
||||
v-model:password_2="passwordRepeat"
|
||||
v-model:invitation-code="invitationCode"
|
||||
v-model:reset-key="reset_key"
|
||||
@login="login"
|
||||
@register="register"
|
||||
|
||||
@@ -20,6 +20,7 @@ from .corelightning import CoreLightningWallet as CLightningWallet
|
||||
from .corelightningrest import CoreLightningRestWallet
|
||||
from .eclair import EclairWallet
|
||||
from .fake import FakeWallet
|
||||
from .lightspark import LightsparkSparkWallet
|
||||
from .lnbits import LNbitsWallet
|
||||
from .lndgrpc import LndWallet
|
||||
from .lndrest import LndRestWallet
|
||||
@@ -69,6 +70,7 @@ __all__ = [
|
||||
"FakeWallet",
|
||||
"LNPayWallet",
|
||||
"LNbitsWallet",
|
||||
"LightsparkSparkWallet",
|
||||
"LnTipsWallet",
|
||||
"LndRestWallet",
|
||||
"LndWallet",
|
||||
|
||||
@@ -0,0 +1,424 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import uuid
|
||||
from collections.abc import AsyncGenerator
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
|
||||
import httpx
|
||||
from bolt11 import decode as bolt11_decode
|
||||
from loguru import logger
|
||||
|
||||
from lnbits.helpers import download_url, normalize_endpoint
|
||||
from lnbits.settings import settings
|
||||
|
||||
from .base import (
|
||||
InvoiceResponse,
|
||||
PaymentFailedStatus,
|
||||
PaymentPendingStatus,
|
||||
PaymentResponse,
|
||||
PaymentStatus,
|
||||
PaymentSuccessStatus,
|
||||
StatusResponse,
|
||||
Wallet,
|
||||
)
|
||||
|
||||
|
||||
class SparkSidecarError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class LightsparkSparkWallet(Wallet):
|
||||
"""
|
||||
Spark L2 funding source via a local sidecar service.
|
||||
|
||||
Required settings/env:
|
||||
- SPARK_L2_ENDPOINT (default http://127.0.0.1:8765)
|
||||
Optional:
|
||||
- SPARK_L2_API_KEY
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._status = "Initializing"
|
||||
self._sidecar_path = Path(settings.lnbits_data_folder, "light_spark")
|
||||
|
||||
self.pending_invoices: list[str] = []
|
||||
|
||||
self.endpoint = "http://127.0.0.1:8765"
|
||||
self._api_key = uuid.uuid4().hex
|
||||
if settings.spark_l2_internal_sidecar_version:
|
||||
self._sidecar_version = settings.spark_l2_internal_sidecar_version
|
||||
self.sidecar_task = asyncio.create_task(self._start_sidecar())
|
||||
logger.info(f"Internal Spark sidecar ({self._sidecar_version}).")
|
||||
elif settings.spark_l2_external_endpoint:
|
||||
self.endpoint = normalize_endpoint(
|
||||
cast(str, settings.spark_l2_external_endpoint)
|
||||
)
|
||||
self._api_key = settings.spark_l2_external_api_key
|
||||
logger.info(f"Using external Spark sidecar endpoint: {self.endpoint}")
|
||||
else:
|
||||
logger.error(
|
||||
"No Spark sidecar configuration found. Please set either "
|
||||
"spark_l2_internal_sidecar_version or spark_l2_external_endpoint."
|
||||
)
|
||||
|
||||
headers = {"User-Agent": settings.user_agent, "X-Api-Key": self._api_key}
|
||||
|
||||
self.client = httpx.AsyncClient(
|
||||
base_url=self.endpoint,
|
||||
headers=headers,
|
||||
timeout=60,
|
||||
)
|
||||
|
||||
async def cleanup(self):
|
||||
try:
|
||||
await self.client.aclose()
|
||||
self.sidecar_task.cancel()
|
||||
except RuntimeError as e:
|
||||
logger.warning(f"Error closing wallet connection: {e}")
|
||||
|
||||
async def status(self) -> StatusResponse:
|
||||
try:
|
||||
res = await self._request("POST", "/v1/balance")
|
||||
balance_msat = res.get("balance_msat")
|
||||
if balance_msat is not None:
|
||||
return StatusResponse(None, int(balance_msat))
|
||||
balance_sats = res.get("balance_sats")
|
||||
if balance_sats is None:
|
||||
return StatusResponse("Spark sidecar: missing balance.", 0)
|
||||
return StatusResponse(None, int(balance_sats) * 1000)
|
||||
except Exception as e:
|
||||
logger.warning(e)
|
||||
return StatusResponse(f"Spark sidecar status error: {e}", 0)
|
||||
|
||||
async def create_invoice(
|
||||
self,
|
||||
amount: int,
|
||||
memo: str | None = None,
|
||||
description_hash: bytes | None = None,
|
||||
unhashed_description: bytes | None = None,
|
||||
**kwargs,
|
||||
) -> InvoiceResponse:
|
||||
expiry = kwargs.get("expiry")
|
||||
expiry_secs = int(expiry) if expiry else None
|
||||
|
||||
description_hash_hex = None
|
||||
if description_hash:
|
||||
description_hash_hex = description_hash.hex()
|
||||
elif unhashed_description:
|
||||
description_hash_hex = hashlib.sha256(unhashed_description).hexdigest()
|
||||
|
||||
try:
|
||||
payload = {
|
||||
"amount_sats": int(amount),
|
||||
"memo": (memo or "") if not description_hash_hex else None,
|
||||
"description_hash": description_hash_hex,
|
||||
"expiry_seconds": expiry_secs,
|
||||
}
|
||||
res = await self._request("POST", "/v1/invoices", payload)
|
||||
bolt11 = res.get("payment_request")
|
||||
checking_id = res.get("checking_id")
|
||||
if not bolt11 or not checking_id:
|
||||
return InvoiceResponse(
|
||||
ok=False,
|
||||
error_message="Spark sidecar invoice response missing fields.",
|
||||
)
|
||||
self.pending_invoices.append(checking_id)
|
||||
|
||||
return InvoiceResponse(
|
||||
ok=True,
|
||||
payment_request=bolt11,
|
||||
checking_id=checking_id,
|
||||
preimage=res.get("preimage", None),
|
||||
)
|
||||
except Exception as e:
|
||||
return InvoiceResponse(ok=False, error_message=str(e))
|
||||
|
||||
async def pay_invoice(self, bolt11: str, fee_limit_msat: int) -> PaymentResponse:
|
||||
try:
|
||||
max_fee_sats = (int(fee_limit_msat) + 999) // 1000
|
||||
|
||||
payment_hash = None
|
||||
try:
|
||||
payment_hash = bolt11_decode(bolt11).payment_hash
|
||||
except Exception as exc:
|
||||
logger.warning(exc)
|
||||
payment_hash = None
|
||||
payload = {
|
||||
"bolt11": bolt11,
|
||||
"max_fee_sats": max_fee_sats,
|
||||
"payment_hash": payment_hash,
|
||||
}
|
||||
res = await self._request("POST", "/v1/payments", payload)
|
||||
checking_id = payment_hash or res.get("checking_id")
|
||||
if not checking_id:
|
||||
return PaymentResponse(
|
||||
ok=False,
|
||||
error_message="Spark sidecar payment response missing checking_id.",
|
||||
)
|
||||
status = res.get("status")
|
||||
fee_msat = res.get("fee_msat")
|
||||
ok = None
|
||||
if status:
|
||||
ok = self._map_payment_ok(status)
|
||||
return PaymentResponse(
|
||||
ok=ok,
|
||||
checking_id=checking_id,
|
||||
fee_msat=int(fee_msat) if fee_msat is not None else None,
|
||||
preimage=res.get("preimage"),
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
return PaymentResponse(ok=False, error_message=str(e))
|
||||
|
||||
async def get_invoice_status(self, checking_id: str) -> PaymentStatus:
|
||||
try:
|
||||
res = await self._request("GET", f"/v1/invoices/{checking_id}")
|
||||
status = res.get("status")
|
||||
if not status:
|
||||
return PaymentPendingStatus()
|
||||
return self._map_invoice_status(status)
|
||||
except Exception as exc:
|
||||
logger.warning(exc)
|
||||
return PaymentPendingStatus()
|
||||
|
||||
async def get_payment_status(self, checking_id: str) -> PaymentStatus:
|
||||
try:
|
||||
res = await self._request("GET", f"/v1/payments/{checking_id}")
|
||||
status = res.get("status")
|
||||
fee_msat = res.get("fee_msat")
|
||||
preimage = res.get("preimage")
|
||||
if not status:
|
||||
return PaymentPendingStatus()
|
||||
mapped = self._map_payment_status(status)
|
||||
if mapped.success:
|
||||
return PaymentSuccessStatus(
|
||||
fee_msat=int(fee_msat) if fee_msat is not None else None,
|
||||
preimage=preimage,
|
||||
)
|
||||
if mapped.failed:
|
||||
return PaymentFailedStatus()
|
||||
return PaymentPendingStatus()
|
||||
except Exception as exc:
|
||||
logger.warning(exc)
|
||||
return PaymentPendingStatus()
|
||||
|
||||
async def paid_invoices_stream(self) -> AsyncGenerator[str, None]:
|
||||
stream_path = "/v1/invoices/stream"
|
||||
while settings.lnbits_running:
|
||||
try:
|
||||
async with self.client.stream("GET", stream_path, timeout=None) as r:
|
||||
if r.status_code in {404, 405}:
|
||||
logger.warning(
|
||||
"Spark sidecar invoice stream not available, "
|
||||
"falling back to polling."
|
||||
)
|
||||
async for checking_id in self._poll_pending_invoices():
|
||||
yield checking_id
|
||||
return
|
||||
r.raise_for_status()
|
||||
logger.info("connected to Spark sidecar invoice stream.")
|
||||
async for line in r.aiter_lines():
|
||||
if not line or not line.startswith("data:"):
|
||||
continue
|
||||
data = json.loads(line[5:].strip())
|
||||
checking_id = data.get("checking_id")
|
||||
if not checking_id:
|
||||
continue
|
||||
yield checking_id
|
||||
except Exception as exc:
|
||||
logger.error(
|
||||
"lost connection to Spark sidecar invoice stream: "
|
||||
f"'{exc}' retrying in 5 seconds"
|
||||
)
|
||||
await asyncio.sleep(5)
|
||||
|
||||
async def _request(
|
||||
self, method: str, path: str, json_data: dict[str, Any] | None = None
|
||||
) -> dict[str, Any]:
|
||||
error_message = None
|
||||
try:
|
||||
r = await self.client.request(method, path, json=json_data)
|
||||
r.raise_for_status()
|
||||
j = r.json()
|
||||
except (httpx.RequestError, httpx.HTTPStatusError, json.JSONDecodeError) as exc:
|
||||
if isinstance(exc, httpx.HTTPStatusError) and exc.response is not None:
|
||||
try:
|
||||
error_json = exc.response.json()
|
||||
if "error" in error_json:
|
||||
error_message = error_json["error"]
|
||||
except Exception as json_exc:
|
||||
logger.error(
|
||||
f"Failed to parse Spark error response as JSON: {json_exc}"
|
||||
)
|
||||
raise SparkSidecarError(
|
||||
error_message or f"Spark sidecar request error: '{exc}'"
|
||||
) from exc
|
||||
|
||||
if error_message or j.get("error"):
|
||||
raise SparkSidecarError(
|
||||
error_message or f"Spark sidecar error: {j['error']}"
|
||||
)
|
||||
return j
|
||||
|
||||
async def _poll_pending_invoices(self) -> AsyncGenerator[str, None]:
|
||||
while settings.lnbits_running:
|
||||
for invoice in list(self.pending_invoices):
|
||||
try:
|
||||
status = await self.get_invoice_status(invoice)
|
||||
if status.paid:
|
||||
yield invoice
|
||||
self.pending_invoices.remove(invoice)
|
||||
elif status.failed:
|
||||
self.pending_invoices.remove(invoice)
|
||||
except Exception as exc:
|
||||
logger.error(f"could not get status of invoice {invoice}: '{exc}' ")
|
||||
await asyncio.sleep(5)
|
||||
|
||||
async def _start_sidecar(self):
|
||||
logger.info("Starting Spark sidecar")
|
||||
node_path = shutil.which("node")
|
||||
if not node_path:
|
||||
logger.error("Node.js not found in PATH, cannot start Spark sidecar")
|
||||
return
|
||||
logger.info(f"Node.js found: {node_path}")
|
||||
|
||||
repo, version = "spark_sidecar", self._sidecar_version
|
||||
node_modules_path = Path(self._sidecar_path, f"{repo}-{version}")
|
||||
await self._prepare_sidecar(repo, version, node_modules_path)
|
||||
|
||||
await self._start_sidecar_process(node_path, node_modules_path)
|
||||
|
||||
async def _prepare_sidecar(self, repo: str, version: str, node_modules_path: Path):
|
||||
if not Path(node_modules_path, "package.json").is_file():
|
||||
await self._download_sidecar(repo, version)
|
||||
else:
|
||||
logger.info("Spark sidecar already downloaded.")
|
||||
|
||||
if not Path(node_modules_path, "node_modules").is_dir():
|
||||
self._install_sidecar_packages(node_modules_path)
|
||||
else:
|
||||
logger.info("Spark sidecar npm dependencies already installed.")
|
||||
|
||||
def _install_sidecar_packages(self, node_modules_path: Path):
|
||||
logger.info(f"Installing Spark sidecar npm dependencies {node_modules_path}")
|
||||
npm_path = shutil.which("npm")
|
||||
if not npm_path:
|
||||
logger.error("npm not found in PATH, cannot start Spark sidecar")
|
||||
return
|
||||
logger.info(f"npm found: {npm_path}")
|
||||
|
||||
result = subprocess.run( # noqa: S603
|
||||
[npm_path, "install"],
|
||||
cwd=str(node_modules_path),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
shell=False,
|
||||
check=True, # raises an exception if npm fails
|
||||
)
|
||||
logger.info("Spark sidecar npm dependencies installed.")
|
||||
logger.info("npm install output:")
|
||||
logger.info(result.stdout)
|
||||
logger.error(result.stderr)
|
||||
|
||||
async def _start_sidecar_process(self, node_path: str, node_modules_path: Path):
|
||||
logger.info("Starting Spark sidecar node process.")
|
||||
|
||||
env = {
|
||||
"SPARK_NETWORK": settings.spark_l2_network,
|
||||
"SPARK_SIDECAR_API_KEY": self._api_key or "",
|
||||
"SPARK_PAY_WAIT_MS": str(settings.spark_l2_pay_wait_ms),
|
||||
"SPARK_MNEMONIC": str(settings.spark_l2_mnemonic),
|
||||
}
|
||||
|
||||
process = subprocess.Popen( # noqa: S603
|
||||
[node_path, "server.mjs"],
|
||||
env=env,
|
||||
cwd=str(node_modules_path),
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
shell=False,
|
||||
text=True,
|
||||
)
|
||||
|
||||
logger.info("Started Spark sidecar node process.")
|
||||
await asyncio.to_thread(self._log_process_output, process)
|
||||
|
||||
async def _download_sidecar(self, repo: str, version: str):
|
||||
zip_path = Path(self._sidecar_path, f"{repo}.zip")
|
||||
logger.info(f"⏳ Downloading Spark sidecar to {zip_path}")
|
||||
Path(zip_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
if zip_path.is_file():
|
||||
os.remove(zip_path)
|
||||
|
||||
await asyncio.to_thread(
|
||||
download_url,
|
||||
f"https://github.com/lnbits/{repo}/archive/refs/tags/v{version}.zip",
|
||||
zip_path,
|
||||
)
|
||||
logger.info("✅ Downloaded Spark sidecar.")
|
||||
|
||||
logger.info("⏳ Extracting Spark sidecar.")
|
||||
|
||||
shutil.unpack_archive(
|
||||
zip_path,
|
||||
self._sidecar_path,
|
||||
)
|
||||
logger.info("✅ Extracted Spark sidecar.")
|
||||
|
||||
def _log_process_output(self, process: subprocess.Popen):
|
||||
if process.stdout:
|
||||
for line in process.stdout:
|
||||
logger.warning(f"[Lightspark]: {line}", end="")
|
||||
else:
|
||||
logger.error(" No output captured for Spark sidecar.")
|
||||
|
||||
def _map_invoice_status(self, status: str) -> PaymentStatus:
|
||||
success = {
|
||||
"LIGHTNING_PAYMENT_RECEIVED",
|
||||
"TRANSFER_COMPLETED",
|
||||
"PAYMENT_PREIMAGE_RECOVERED",
|
||||
}
|
||||
failed = {
|
||||
"TRANSFER_FAILED",
|
||||
"PAYMENT_PREIMAGE_RECOVERING_FAILED",
|
||||
"REFUND_SIGNING_FAILED",
|
||||
"REFUND_SIGNING_COMMITMENTS_QUERYING_FAILED",
|
||||
"TRANSFER_CREATION_FAILED",
|
||||
}
|
||||
if status in success:
|
||||
return PaymentSuccessStatus()
|
||||
if status in failed:
|
||||
return PaymentFailedStatus()
|
||||
return PaymentPendingStatus()
|
||||
|
||||
def _map_payment_status(self, status: str) -> PaymentStatus:
|
||||
success = {
|
||||
"LIGHTNING_PAYMENT_SUCCEEDED",
|
||||
"TRANSFER_COMPLETED",
|
||||
"PREIMAGE_PROVIDED",
|
||||
}
|
||||
failed = {
|
||||
"LIGHTNING_PAYMENT_FAILED",
|
||||
"TRANSFER_FAILED",
|
||||
"PREIMAGE_PROVIDING_FAILED",
|
||||
"USER_TRANSFER_VALIDATION_FAILED",
|
||||
"USER_SWAP_RETURN_FAILED",
|
||||
}
|
||||
if status in success:
|
||||
return PaymentSuccessStatus()
|
||||
if status in failed:
|
||||
return PaymentFailedStatus()
|
||||
return PaymentPendingStatus()
|
||||
|
||||
def _map_payment_ok(self, status: str) -> bool | None:
|
||||
mapped = self._map_payment_status(status)
|
||||
if mapped.success:
|
||||
return True
|
||||
if mapped.failed:
|
||||
return False
|
||||
return None
|
||||
@@ -297,6 +297,148 @@ async def test_register_ok(http_client: AsyncClient):
|
||||
), f"Expected 1 default wallet, not {len(user.wallets)}."
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_register_no_activation_code(
|
||||
http_client: AsyncClient, settings: Settings
|
||||
):
|
||||
settings.lnbits_require_user_activation = True
|
||||
|
||||
tiny_id = shortuuid.uuid()[:8]
|
||||
response = await http_client.post(
|
||||
"/api/v1/auth/register",
|
||||
json={
|
||||
"username": f"u21.{tiny_id}",
|
||||
"password": "secret1234",
|
||||
"password_repeat": "secret1234",
|
||||
"email": f"u21.{tiny_id}@lnbits.com",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json().get("detail") == "No activation method provided."
|
||||
|
||||
settings.lnbits_user_activation_by_invitation_code = True
|
||||
|
||||
response = await http_client.post(
|
||||
"/api/v1/auth/register",
|
||||
json={
|
||||
"username": f"u21.{tiny_id}",
|
||||
"password": "secret1234",
|
||||
"password_repeat": "secret1234",
|
||||
"email": f"u21.{tiny_id}@lnbits.com",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 400, "User creation blocked without activation code."
|
||||
assert response.json().get("detail") == "Invitation code cannot be empty."
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_register_invalid_activation_code(
|
||||
http_client: AsyncClient, settings: Settings
|
||||
):
|
||||
settings.lnbits_require_user_activation = True
|
||||
settings.lnbits_user_activation_by_invitation_code = True
|
||||
settings.lnbits_register_reusable_activation_code = "foo"
|
||||
settings.lnbits_register_one_time_activation_codes = ["baz", "qux"]
|
||||
|
||||
tiny_id = shortuuid.uuid()[:8]
|
||||
response = await http_client.post(
|
||||
"/api/v1/auth/register",
|
||||
json={
|
||||
"username": f"u21.{tiny_id}",
|
||||
"password": "secret1234",
|
||||
"password_repeat": "secret1234",
|
||||
"email": f"u21.{tiny_id}@lnbits.com",
|
||||
"invitation_code": "bar",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json().get("detail") == "Invalid invitation code."
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_register_reusable_activation_code(
|
||||
http_client: AsyncClient, settings: Settings
|
||||
):
|
||||
settings.lnbits_require_user_activation = True
|
||||
settings.lnbits_user_activation_by_invitation_code = True
|
||||
settings.lnbits_register_reusable_activation_code = "foo"
|
||||
|
||||
tiny_id = shortuuid.uuid()[:8]
|
||||
response = await http_client.post(
|
||||
"/api/v1/auth/register",
|
||||
json={
|
||||
"username": f"u21.{tiny_id}",
|
||||
"password": "secret1234",
|
||||
"password_repeat": "secret1234",
|
||||
"email": f"u21.{tiny_id}@lnbits.com",
|
||||
"invitation_code": "foo",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 200, "User created with reusable code."
|
||||
assert response.json().get("access_token") is not None
|
||||
|
||||
# Register again with the same code
|
||||
tiny_id = shortuuid.uuid()[:8]
|
||||
response = await http_client.post(
|
||||
"/api/v1/auth/register",
|
||||
json={
|
||||
"username": f"u21.{tiny_id}",
|
||||
"password": "secret1234",
|
||||
"password_repeat": "secret1234",
|
||||
"email": f"u21.{tiny_id}@lnbits.com",
|
||||
"invitation_code": "foo",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 200, "User created with reusable code."
|
||||
assert response.json().get("access_token") is not None
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_register_one_time_activation_code(
|
||||
http_client: AsyncClient, settings: Settings
|
||||
):
|
||||
settings.lnbits_require_user_activation = True
|
||||
settings.lnbits_user_activation_by_invitation_code = True
|
||||
settings.lnbits_register_reusable_activation_code = "foo"
|
||||
settings.lnbits_register_one_time_activation_codes = ["baz", "qux"]
|
||||
|
||||
tiny_id = shortuuid.uuid()[:8]
|
||||
response = await http_client.post(
|
||||
"/api/v1/auth/register",
|
||||
json={
|
||||
"username": f"u21.{tiny_id}",
|
||||
"password": "secret1234",
|
||||
"password_repeat": "secret1234",
|
||||
"email": f"u21.{tiny_id}@lnbits.com",
|
||||
"invitation_code": "baz",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 200, "User created with one-time code."
|
||||
assert response.json().get("access_token") is not None
|
||||
|
||||
# Register again with the same code
|
||||
tiny_id = shortuuid.uuid()[:8]
|
||||
response = await http_client.post(
|
||||
"/api/v1/auth/register",
|
||||
json={
|
||||
"username": f"u21.{tiny_id}",
|
||||
"password": "secret1234",
|
||||
"password_repeat": "secret1234",
|
||||
"email": f"u21.{tiny_id}@lnbits.com",
|
||||
"invitation_code": "baz",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 400, "Invalid invitation code."
|
||||
assert response.json().get("detail") == "Invalid invitation code."
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_register_email_twice(http_client: AsyncClient):
|
||||
tiny_id = shortuuid.uuid()[:8]
|
||||
|
||||
@@ -341,3 +341,7 @@ def _settings_cleanup(settings: Settings):
|
||||
settings.lnbits_max_outgoing_payment_amount_sats = 10_000_000_100
|
||||
settings.lnbits_max_incoming_payment_amount_sats = 10_000_000_200
|
||||
settings.stripe_limits = FiatProviderLimits()
|
||||
settings.lnbits_require_user_activation = False
|
||||
settings.lnbits_user_activation_by_invitation_code = False
|
||||
settings.lnbits_register_reusable_activation_code = ""
|
||||
settings.lnbits_register_one_time_activation_codes = []
|
||||
|
||||
Reference in New Issue
Block a user