Compare commits

..
Author SHA1 Message Date
dni ⚡ 2329770acd chore: update to version v1.5.2 (#3891) 2026-03-23 17:39:49 +01:00
83 changed files with 3143 additions and 10810 deletions
+1 -45
View File
@@ -94,7 +94,7 @@ AUTH_SECRET_KEY=""
######################################
AUTH_TOKEN_EXPIRE_MINUTES=525600
# Possible authorization methods: user-id-only, username-password, nostr-auth-nip98, google-auth, github-auth, keycloak-auth, oidc-auth
# Possible authorization methods: user-id-only, username-password, nostr-auth-nip98, google-auth, github-auth, keycloak-auth
AUTH_ALLOWED_METHODS="user-id-only, username-password"
# Set this flag if HTTP is used for OAuth
# OAUTHLIB_INSECURE_TRANSPORT="1"
@@ -271,50 +271,6 @@ KEYCLOAK_DISCOVERY_URL=""
KEYCLOAK_CLIENT_CUSTOM_ORG=""
KEYCLOAK_CLIENT_CUSTOM_ICON=""
# OIDC OAuth Config
# Generic OIDC provider configuration
# Make sure that the redirect URI in your OIDC provider is set to: https://{domain}/api/v1/auth/oidc/token
# Required scopes: openid, email, profile
# The discovery URL must be accessible from your LNbits server
# Always use HTTPS in production environments
# The CUSTOM_ORG and CUSTOM_ICON settings allow you to customize the login button
# For example: "Login via Zitadel" with the Zitadel logo
OIDC_DISCOVERY_URL=""
OIDC_CLIENT_ID=""
OIDC_CLIENT_SECRET=""
OIDC_CLIENT_CUSTOM_ORG=""
OIDC_CLIENT_CUSTOM_ICON=""
# Example OIDC configurations for various providers:
#
# ZITADEL:
# OIDC_DISCOVERY_URL=https://login.yourdomain.de/.well-known/openid-configuration
# OIDC_CLIENT_ID=your-zitadel-client-id@project-id
# OIDC_CLIENT_SECRET=your-zitadel-client-secret
# OIDC_CLIENT_CUSTOM_ORG=Zitadel
# OIDC_CLIENT_CUSTOM_ICON=/static/images/zitadel.png
#
# AUTHENTIK:
# OIDC_DISCOVERY_URL=https://authentik.yourdomain.com/application/o/lnbits/.well-known/openid-configuration
# OIDC_CLIENT_ID=your-authentik-client-id
# OIDC_CLIENT_SECRET=your-authentik-client-secret
# OIDC_CLIENT_CUSTOM_ORG=Authentik
# OIDC_CLIENT_CUSTOM_ICON=/static/images/authentik.png
#
# AUTHELIA:
# OIDC_DISCOVERY_URL=https://auth.yourdomain.com/.well-known/openid-configuration
# OIDC_CLIENT_ID=your-authelia-client-id
# OIDC_CLIENT_SECRET=your-authelia-client-secret
# OIDC_CLIENT_CUSTOM_ORG=Authelia
# OIDC_CLIENT_CUSTOM_ICON=/static/images/authelia.png
#
# OKTA:
# OIDC_DISCOVERY_URL=https://your-domain.okta.com/.well-known/openid-configuration
# OIDC_CLIENT_ID=your-okta-client-id
# OIDC_CLIENT_SECRET=your-okta-client-secret
# OIDC_CLIENT_CUSTOM_ORG=Okta
# OIDC_CLIENT_CUSTOM_ICON=/static/images/okta.png
######################################
-29
View File
@@ -1,29 +0,0 @@
name: bundle
on:
workflow_call:
jobs:
bundle:
permissions:
contents: write
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.head_ref }}
- uses: lnbits/lnbits/.github/actions/prepare@dev
with:
python-version: "3.10"
node-version: "24.x"
npm: true
- run: make bundle
- name: Commit and push bundle changes
run: |
git config user.name "alan"
git config user.email "alan@lnbits.com"
git add lnbits/static
if git diff --cached --quiet; then
exit 0
fi
git commit -m "chore: make bundle [skip ci]"
git push
+11 -10
View File
@@ -1,9 +1,14 @@
name: LNbits CI
on:
push:
branches:
- main
- dev
pull_request:
jobs:
lint:
uses: ./.github/workflows/lint.yml
@@ -11,7 +16,7 @@ jobs:
needs: [ lint ]
strategy:
matrix:
python-version: ["3.10", "3.12"]
python-version: ["3.10", "3.11", "3.12"]
db-url: ["", "postgres://lnbits:lnbits@0.0.0.0:5432/lnbits"]
uses: ./.github/workflows/tests.yml
with:
@@ -25,7 +30,7 @@ jobs:
needs: [ lint ]
strategy:
matrix:
python-version: ["3.10", "3.12"]
python-version: ["3.10", "3.11", "3.12"]
db-url: ["", "postgres://lnbits:lnbits@0.0.0.0:5432/lnbits"]
uses: ./.github/workflows/tests.yml
with:
@@ -39,7 +44,7 @@ jobs:
needs: [ lint ]
strategy:
matrix:
python-version: ["3.10", "3.12"]
python-version: ["3.10", "3.11", "3.12"]
db-url: ["", "postgres://lnbits:lnbits@0.0.0.0:5432/lnbits"]
uses: ./.github/workflows/tests.yml
with:
@@ -53,7 +58,7 @@ jobs:
needs: [ lint ]
strategy:
matrix:
python-version: ["3.10", "3.12"]
python-version: ["3.10", "3.11", "3.12"]
uses: ./.github/workflows/migration.yml
with:
python-version: ${{ matrix.python-version }}
@@ -69,7 +74,7 @@ jobs:
uses: ./.github/workflows/regtest.yml
strategy:
matrix:
python-version: ["3.12"]
python-version: ["3.10"]
backend-wallet-class:
- BoltzWallet
- LndRestWallet
@@ -89,11 +94,7 @@ jobs:
needs: [ lint ]
strategy:
matrix:
python-version: ["3.12"]
python-version: ["3.10"]
uses: ./.github/workflows/jmeter.yml
with:
python-version: ${{ matrix.python-version }}
bundle:
needs: [ lint, test-api, test-wallets, test-unit, migration, openapi, regtest, jmeter ]
uses: ./.github/workflows/bundle.yml
-1
View File
@@ -22,7 +22,6 @@ jobs:
- name: run LNbits
env:
LNBITS_ADMIN_UI: true
AUTH_HTTPS_ONLY: false
LNBITS_EXTENSIONS_DEFAULT_INSTALL: "watchonly, satspay, tipjar, tpos, lnurlp, withdraw"
LNBITS_BACKEND_WALLET_CLASS: FakeWallet
run: |
+23
View File
@@ -6,30 +6,53 @@ jobs:
black:
uses: ./.github/workflows/make.yml
strategy:
matrix:
python-version: ["3.10", "3.11", "3.12"]
with:
make: checkblack
python-version: ${{ matrix.python-version }}
ruff:
uses: ./.github/workflows/make.yml
strategy:
matrix:
python-version: ["3.10", "3.11", "3.12"]
with:
make: checkruff
python-version: ${{ matrix.python-version }}
mypy:
uses: ./.github/workflows/make.yml
strategy:
matrix:
python-version: ["3.10", "3.11", "3.12"]
with:
make: mypy
python-version: ${{ matrix.python-version }}
pyright:
uses: ./.github/workflows/make.yml
strategy:
matrix:
python-version: ["3.10", "3.11", "3.12"]
with:
make: pyright
python-version: ${{ matrix.python-version }}
npm: true
prettier:
uses: ./.github/workflows/make.yml
with:
make: checkprettier
npm: true
bundle:
uses: ./.github/workflows/make.yml
with:
make: checkbundle
npm: true
poetry:
uses: ./.github/workflows/poetry.yml
+2 -2
View File
@@ -14,7 +14,7 @@ on:
python-version:
description: "python version"
type: string
default: "3.12"
default: "3.10"
jobs:
make:
@@ -22,7 +22,7 @@ jobs:
strategy:
matrix:
os-version: ["ubuntu-24.04"]
node-version: ["24.x"]
node-version: ["18.x"]
runs-on: ${{ matrix.os-version }}
steps:
- uses: actions/checkout@v4
+1 -1
View File
@@ -8,7 +8,7 @@ on:
required: true
type: string
python-version:
default: "3.12"
default: "3.10"
type: string
os-version:
default: "ubuntu-24.04"
+1 -1
View File
@@ -8,7 +8,7 @@ on:
required: true
type: string
python-version:
default: "3.12"
default: "3.10"
type: string
os-version:
default: "ubuntu-24.04"
+2 -2
View File
@@ -14,11 +14,11 @@ repos:
- id: mixed-line-ending
- id: check-case-conflict
- repo: https://github.com/psf/black
rev: 26.3.1
rev: 25.1.0
hooks:
- id: black
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.14.10
rev: v0.12.10
hooks:
- id: ruff
args: [ --fix, --exit-non-zero-on-fix ]
+1 -1
View File
@@ -43,4 +43,4 @@ ENV LNBITS_HOST="0.0.0.0"
EXPOSE 5000
CMD ["sh", "-c", "uv --offline run lnbits --port $LNBITS_PORT --host $LNBITS_HOST --forwarded-allow-ips='*'"]
CMD ["sh", "-c", "uv run lnbits --port $LNBITS_PORT --host $LNBITS_HOST --forwarded-allow-ips='*'"]
-139
View File
@@ -1,139 +0,0 @@
# Generic OIDC Authentication Configuration
This document explains how to configure generic OIDC authentication for LNbits, which allows integration with various OIDC-compliant authentication providers such as Zitadel, Authentik, and others.
## Overview
The generic OIDC provider (`oidc`) complements the existing Keycloak provider and allows you to integrate any OIDC-compliant authentication service. You can customize the login button with your own organization name and icon.
## Configuration
Add the following environment variables to your `.env` file or system environment:
### Required Settings
```bash
# Enable OIDC authentication
LNBITS_AUTH_ALLOWED_METHODS=oidc-auth
# OIDC Discovery URL (well-known endpoint)
LNBITS_OIDC_DISCOVERY_URL=https://your-oidc-provider-domain/.well-known/openid-configuration
# Client credentials from your OIDC provider
LNBITS_OIDC_CLIENT_ID=your-client-id
LNBITS_OIDC_CLIENT_SECRET=your-client-secret
```
### Optional Settings - Customize the Login Button
You can customize how the OIDC login button appears to your users:
```bash
# Custom organization name (displayed on the login button)
# Example: "Login via Zitadel" or "Login via Authentik"
LNBITS_OIDC_CLIENT_CUSTOM_ORG="Zitadel"
# Custom icon URL (displayed on the login button)
# Can be a full URL or a path to a local image
LNBITS_OIDC_CLIENT_CUSTOM_ICON=https://zitadel.com/favicon.svg
```
If not set, the button will display "Login via OIDC" with a generic lock icon.
## Zitadel Configuration Example
For Zitadel, configure as follows:
1. Create a new application in Zitadel
2. Choose "Web" application type
3. Configure the redirect URI: `https://your-lnbits-domain/api/v1/auth/oidc/token`
4. Save the Client ID and Client Secret
5. Use these environment variables:
```bash
LNBITS_AUTH_ALLOWED_METHODS=oidc-auth
LNBITS_OIDC_DISCOVERY_URL=https://your-oidc-provider-domain/.well-known/openid-configuration
LNBITS_OIDC_CLIENT_ID=your-zitadel-client-id
LNBITS_OIDC_CLIENT_SECRET=your-zitadel-client-secret
# Customize the button to show "Login via Zitadel" with Zitadel's logo
LNBITS_OIDC_CLIENT_CUSTOM_ORG="Zitadel"
LNBITS_OIDC_CLIENT_CUSTOM_ICON="https://zitadel.com/favicon.svg"
```
**Result**: The login page will display a button with the text "Login via Zitadel" and the Zitadel logo.
## Authentik Configuration Example
For Authentik:
1. Create a new OAuth2/OpenID Provider
2. Set the redirect URI: `https://your-lnbits-domain/api/v1/auth/oidc/token`
3. Configure scopes: `openid`, `email`, `profile`
4. Get the Client ID and Client Secret
```bash
LNBITS_AUTH_ALLOWED_METHODS=oidc-auth
LNBITS_OIDC_DISCOVERY_URL=https://authentik.yourdomain.com/application/o/your-app/.well-known/openid-configuration
LNBITS_OIDC_CLIENT_ID=your-authentik-client-id
LNBITS_OIDC_CLIENT_SECRET=your-authentik-client-secret
LNBITS_OIDC_CLIENT_CUSTOM_ORG="Authentik"
```
## Multiple Auth Methods
You can enable multiple authentication methods simultaneously:
```bash
LNBITS_AUTH_ALLOWED_METHODS=username-password,oidc-auth,keycloak-auth
```
## Discovery Endpoint Requirements
Your OIDC provider must expose a standard discovery endpoint (`.well-known/openid-configuration`) that includes:
- `authorization_endpoint`
- `token_endpoint`
- `userinfo_endpoint`
- `jwks_uri` (JSON Web Key Set)
The OIDC implementation will automatically fetch these endpoints from the discovery URL.
## User Mapping
The OIDC provider maps user information from the OIDC userinfo endpoint:
- `sub` → User ID
- `email` → Email address
- `given_name` → First name
- `family_name` → Last name
- `name` or `preferred_username` → Display name
- `picture` → Profile picture URL
## Troubleshooting
### Authentication fails
1. Verify the discovery URL is accessible
2. Check that Client ID and Client Secret are correct
3. Ensure redirect URI in your OIDC provider matches: `https://your-lnbits-domain/api/v1/auth/oidc/token`
4. Check LNbits logs for detailed error messages
### User info not populated
Some OIDC providers may use different claim names. If user information is not correctly populated, check your provider's userinfo endpoint response format and adjust the provider class if needed.
## Security Considerations
- Always use HTTPS in production
- Keep client secrets secure and never commit them to version control
- Use environment variables or secure configuration management
- Regularly rotate client secrets
- Review OIDC provider's security best practices
## Implementation Details
The OIDC provider is implemented in `lnbits/core/models/sso/oidc.py` and extends the `fastapi_sso` library's `SSOBase` class. It uses the standard OpenID Connect flow with:
- Scopes: `openid`, `email`, `profile`
- Response type: `code` (authorization code flow)
- Discovery document for automatic endpoint resolution
+1 -6
View File
@@ -468,12 +468,7 @@ def register_async_tasks() -> None:
create_permanent_task(wait_for_audit_data)
create_permanent_task(wait_notification_messages)
create_permanent_task(
run_interval(
settings.lnbits_funding_source_pending_interval_seconds,
check_pending_payments,
)
)
create_permanent_task(run_interval(30 * 60, check_pending_payments))
create_permanent_task(invoice_listener)
create_permanent_task(internal_invoice_listener)
create_permanent_task(cache.invalidate_forever)
+8 -4
View File
@@ -149,12 +149,14 @@ async def get_payments_paginated( # noqa: C901
f"(status = '{PaymentState.SUCCESS}' OR status = '{PaymentState.PENDING}')"
)
elif complete:
clause.append(f"""
clause.append(
f"""
(
status = '{PaymentState.SUCCESS}'
OR (amount < 0 AND status = '{PaymentState.PENDING}')
)
""")
"""
)
elif pending:
clause.append(f"status = '{PaymentState.PENDING}'")
elif failed:
@@ -344,12 +346,14 @@ async def get_payments_history(
"wallet_id": wallet_id,
}
# count outgoing payments if they are still pending
where = [f"""
where = [
f"""
wallet_id = :wallet_id AND (
status = '{PaymentState.SUCCESS}'
OR (amount < 0 AND status = '{PaymentState.PENDING}')
)
"""]
"""
]
clause = filters.where(where)
transactions: list[dict] = await db.fetchall(
# This query is safe from SQL injection:
+1 -2
View File
@@ -105,8 +105,7 @@ async def get_settings_field(
)
if not row:
return None
value = json.loads(row["value"]) if row["value"] else None
return SettingsField(id=row["id"], value=value, tag=row["tag"])
return SettingsField(id=row["id"], value=json.loads(row["value"]), tag=row["tag"])
async def set_settings_field(id_: str, value: Any | None, tag: str | None = "core"):
+11 -21
View File
@@ -4,12 +4,7 @@ from typing import Any
from uuid import uuid4
from lnbits.core.crud.extensions import get_user_active_extensions_ids
from lnbits.core.crud.wallets import (
clear_wallet_cache,
create_wallet,
get_standalone_wallet,
get_wallets,
)
from lnbits.core.crud.wallets import clear_wallet_cache, create_wallet, get_wallets
from lnbits.core.db import db
from lnbits.core.models import UserAcls
from lnbits.db import Connection, Filters, Page
@@ -57,22 +52,17 @@ async def get_accounts(
) -> Page[AccountOverview]:
where_clauses = []
values: dict[str, Any] = {}
filters = filters or Filters()
wallet_filter = filters.get_filter_by_field("wallet_id")
if wallet_filter and wallet_filter.values:
wallet_id_value = next(iter(wallet_filter.values.values()), None)
wallet = (
await get_standalone_wallet(wallet_id_value, deleted=None, conn=conn)
if wallet_id_value
else None
)
if not wallet:
return Page(data=[], total=0)
where_clauses.append("accounts.id = :account_id")
values = {**values, "account_id": wallet.user}
filters.remove_filter_by_field("wallet_id")
# Make wallet filter explicit
wallet_filter = (
next((f for f in filters.filters if f.field == "wallet_id"), None)
if filters
else None
)
if filters and wallet_filter and wallet_filter.values:
where_clauses.append("wallets.id = :wallet_id")
values = {**values, "wallet_id": next(iter(wallet_filter.values.values()))}
filters.filters = [f for f in filters.filters if f.field != "wallet_id"]
return await (conn or db).fetch_page(
"""
+124 -62
View File
@@ -10,26 +10,31 @@ from lnbits.db import Connection
async def m000_create_migrations_table(db: Connection):
await db.execute("""
await db.execute(
"""
CREATE TABLE IF NOT EXISTS dbversions (
db TEXT PRIMARY KEY,
version INT NOT NULL
)
""")
"""
)
async def m001_initial(db: Connection):
"""
Initial LNbits tables.
"""
await db.execute("""
await db.execute(
"""
CREATE TABLE IF NOT EXISTS accounts (
id TEXT PRIMARY KEY,
email TEXT,
pass TEXT
);
""")
await db.execute("""
"""
)
await db.execute(
"""
CREATE TABLE IF NOT EXISTS extensions (
"user" TEXT NOT NULL,
extension TEXT NOT NULL,
@@ -37,8 +42,10 @@ async def m001_initial(db: Connection):
UNIQUE ("user", extension)
);
""")
await db.execute("""
"""
)
await db.execute(
"""
CREATE TABLE IF NOT EXISTS wallets (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
@@ -46,8 +53,10 @@ async def m001_initial(db: Connection):
adminkey TEXT NOT NULL,
inkey TEXT
);
""")
await db.execute(f"""
"""
)
await db.execute(
f"""
CREATE TABLE IF NOT EXISTS apipayments (
payhash TEXT NOT NULL,
amount {db.big_int} NOT NULL,
@@ -58,9 +67,11 @@ async def m001_initial(db: Connection):
time TIMESTAMP NOT NULL DEFAULT {db.timestamp_now},
UNIQUE (wallet, payhash)
);
""")
"""
)
await db.execute("""
await db.execute(
"""
CREATE VIEW balances AS
SELECT wallet, COALESCE(SUM(s), 0) AS balance FROM (
SELECT wallet, SUM(amount) AS s -- incoming
@@ -74,7 +85,8 @@ async def m001_initial(db: Connection):
GROUP BY wallet
)x
GROUP BY wallet;
""")
"""
)
async def m002_add_fields_to_apipayments(db: Connection):
@@ -137,7 +149,8 @@ async def m004_ensure_fees_are_always_negative(db: Connection):
"""
await db.execute("DROP VIEW balances")
await db.execute("""
await db.execute(
"""
CREATE VIEW balances AS
SELECT wallet, COALESCE(SUM(s), 0) AS balance FROM (
SELECT wallet, SUM(amount) AS s -- incoming
@@ -151,7 +164,8 @@ async def m004_ensure_fees_are_always_negative(db: Connection):
GROUP BY wallet
)x
GROUP BY wallet;
""")
"""
)
async def m005_balance_check_balance_notify(db: Connection):
@@ -160,7 +174,8 @@ async def m005_balance_check_balance_notify(db: Connection):
LNbits wallet and of balanceNotify URLs supplied by users to empty their wallets.
"""
await db.execute("""
await db.execute(
"""
CREATE TABLE IF NOT EXISTS balance_check (
wallet TEXT NOT NULL REFERENCES wallets (id),
service TEXT NOT NULL,
@@ -168,16 +183,19 @@ async def m005_balance_check_balance_notify(db: Connection):
UNIQUE(wallet, service)
);
""")
"""
)
await db.execute("""
await db.execute(
"""
CREATE TABLE IF NOT EXISTS balance_notify (
wallet TEXT NOT NULL REFERENCES wallets (id),
url TEXT NOT NULL,
UNIQUE(wallet, url)
);
""")
"""
)
async def m006_add_invoice_expiry_to_apipayments(db: Connection):
@@ -244,16 +262,19 @@ async def m007_set_invoice_expiries(db: Connection):
async def m008_create_admin_settings_table(db: Connection):
await db.execute("""
await db.execute(
"""
CREATE TABLE IF NOT EXISTS settings (
super_user TEXT,
editable_settings TEXT NOT NULL DEFAULT '{}'
);
""")
"""
)
async def m009_create_tinyurl_table(db: Connection):
await db.execute(f"""
await db.execute(
f"""
CREATE TABLE IF NOT EXISTS tiny_url (
id TEXT PRIMARY KEY,
url TEXT,
@@ -261,11 +282,13 @@ async def m009_create_tinyurl_table(db: Connection):
wallet TEXT,
time TIMESTAMP NOT NULL DEFAULT {db.timestamp_now}
);
""")
"""
)
async def m010_create_installed_extensions_table(db: Connection):
await db.execute("""
await db.execute(
"""
CREATE TABLE IF NOT EXISTS installed_extensions (
id TEXT PRIMARY KEY,
version TEXT NOT NULL,
@@ -276,7 +299,8 @@ async def m010_create_installed_extensions_table(db: Connection):
active BOOLEAN DEFAULT false,
meta TEXT NOT NULL DEFAULT '{}'
);
""")
"""
)
async def m011_optimize_balances_view(db: Connection):
@@ -285,19 +309,23 @@ async def m011_optimize_balances_view(db: Connection):
over the payments table instead of 2.
"""
await db.execute("DROP VIEW balances")
await db.execute("""
await db.execute(
"""
CREATE VIEW balances AS
SELECT wallet, SUM(amount - abs(fee)) AS balance
FROM apipayments
WHERE (pending = false AND amount > 0) OR amount < 0
GROUP BY wallet
""")
"""
)
async def m012_add_currency_to_wallet(db: Connection):
await db.execute("""
await db.execute(
"""
ALTER TABLE wallets ADD COLUMN currency TEXT
""")
"""
)
async def m013_add_deleted_to_wallets(db: Connection):
@@ -317,13 +345,15 @@ async def m014_set_deleted_wallets(db: Connection):
Sets deleted column to wallets.
"""
try:
result = await db.execute("""
result = await db.execute(
"""
SELECT *
FROM wallets
WHERE user LIKE 'del:%'
AND adminkey LIKE 'del:%'
AND inkey LIKE 'del:%'
""")
"""
)
rows = result.mappings().all()
for row in rows:
@@ -356,7 +386,8 @@ async def m014_set_deleted_wallets(db: Connection):
async def m015_create_push_notification_subscriptions_table(db: Connection):
await db.execute(f"""
await db.execute(
f"""
CREATE TABLE IF NOT EXISTS webpush_subscriptions (
endpoint TEXT NOT NULL,
"user" TEXT NOT NULL,
@@ -365,7 +396,8 @@ async def m015_create_push_notification_subscriptions_table(db: Connection):
timestamp TIMESTAMP NOT NULL DEFAULT {db.timestamp_now},
PRIMARY KEY (endpoint, "user")
);
""")
"""
)
async def m016_add_username_column_to_accounts(db: Connection):
@@ -452,7 +484,8 @@ async def m018_balances_view_exclude_deleted(db: Connection):
Make deleted wallets not show up in the balances view.
"""
await db.execute("DROP VIEW balances")
await db.execute("""
await db.execute(
"""
CREATE VIEW balances AS
SELECT apipayments.wallet,
SUM(apipayments.amount - ABS(apipayments.fee)) AS balance
@@ -462,7 +495,8 @@ async def m018_balances_view_exclude_deleted(db: Connection):
AND ((apipayments.pending = false AND apipayments.amount > 0)
OR apipayments.amount < 0)
GROUP BY wallet
""")
"""
)
async def m019_balances_view_based_on_wallets(db: Connection):
@@ -471,7 +505,8 @@ async def m019_balances_view_based_on_wallets(db: Connection):
Important for querying whole lnbits balances.
"""
await db.execute("DROP VIEW balances")
await db.execute("""
await db.execute(
"""
CREATE VIEW balances AS
SELECT apipayments.wallet,
SUM(apipayments.amount - ABS(apipayments.fee)) AS balance
@@ -481,7 +516,8 @@ async def m019_balances_view_based_on_wallets(db: Connection):
AND ((apipayments.pending = false AND apipayments.amount > 0)
OR apipayments.amount < 0)
GROUP BY apipayments.wallet
""")
"""
)
async def m020_add_column_column_to_user_extensions(db: Connection):
@@ -500,7 +536,8 @@ async def m021_add_success_failed_to_apipayments(db: Connection):
await db.execute("UPDATE apipayments SET status = 'success' WHERE NOT pending")
await db.execute("DROP VIEW balances")
await db.execute("""
await db.execute(
"""
CREATE VIEW balances AS
SELECT apipayments.wallet,
SUM(apipayments.amount - ABS(apipayments.fee)) AS balance
@@ -512,7 +549,8 @@ async def m021_add_success_failed_to_apipayments(db: Connection):
OR (apipayments.status IN ('success', 'pending') AND apipayments.amount < 0)
)
GROUP BY apipayments.wallet
""")
"""
)
async def m022_add_pubkey_to_accounts(db: Connection):
@@ -543,7 +581,8 @@ async def m024_drop_pending(db: Connection):
async def m025_refresh_view(db: Connection):
await db.execute("DROP VIEW balances")
await db.execute("""
await db.execute(
"""
CREATE VIEW balances AS
SELECT apipayments.wallet_id,
SUM(apipayments.amount - ABS(apipayments.fee)) AS balance
@@ -555,7 +594,8 @@ async def m025_refresh_view(db: Connection):
OR (apipayments.status IN ('success', 'pending') AND apipayments.amount < 0)
)
GROUP BY apipayments.wallet_id
""")
"""
)
async def m026_update_payment_table(db: Connection):
@@ -618,7 +658,8 @@ async def m027_update_apipayments_data(db: Connection):
async def m028_update_settings(db: Connection):
await db.execute("""
await db.execute(
"""
CREATE TABLE IF NOT EXISTS system_settings (
id TEXT PRIMARY KEY,
value TEXT,
@@ -626,7 +667,8 @@ async def m028_update_settings(db: Connection):
UNIQUE (id, tag)
);
""")
"""
)
async def _insert_key_value(id_: str, value: Any):
await db.execute(
@@ -649,7 +691,8 @@ async def m028_update_settings(db: Connection):
async def m029_create_audit_table(db: Connection):
await db.execute(f"""
await db.execute(
f"""
CREATE TABLE IF NOT EXISTS audit (
component TEXT,
ip_address TEXT,
@@ -663,13 +706,16 @@ async def m029_create_audit_table(db: Connection):
delete_at TIMESTAMP,
created_at TIMESTAMP NOT NULL DEFAULT {db.timestamp_now}
);
""")
"""
)
async def m030_add_user_api_tokens_column(db: Connection):
await db.execute("""
await db.execute(
"""
ALTER TABLE accounts ADD COLUMN access_control_list TEXT
""")
"""
)
async def m031_add_color_and_icon_to_wallets(db: Connection):
@@ -692,25 +738,32 @@ async def m033_update_payment_table(db: Connection):
async def m034_add_stored_paylinks_to_wallet(db: Connection):
await db.execute("""
await db.execute(
"""
ALTER TABLE wallets ADD COLUMN stored_paylinks TEXT
""")
"""
)
async def m035_add_wallet_type_column(db: Connection):
await db.execute("""
await db.execute(
"""
ALTER TABLE wallets ADD COLUMN wallet_type TEXT DEFAULT 'lightning'
""")
"""
)
async def m036_add_shared_wallet_column(db: Connection):
await db.execute("""
await db.execute(
"""
ALTER TABLE wallets ADD COLUMN shared_wallet_id TEXT
""")
"""
)
async def m037_create_assets_table(db: Connection):
await db.execute(f"""
await db.execute(
f"""
CREATE TABLE IF NOT EXISTS assets (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
@@ -723,13 +776,16 @@ async def m037_create_assets_table(db: Connection):
data {db.blob} NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT {db.timestamp_now}
);
""")
"""
)
async def m038_add_labels_for_payments(db: Connection):
await db.execute("""
await db.execute(
"""
ALTER TABLE apipayments ADD COLUMN labels TEXT
""")
"""
)
async def m039_index_payments(db: Connection):
@@ -748,9 +804,11 @@ async def m039_index_payments(db: Connection):
]
for index in indexes:
logger.debug(f"Creating index idx_payments_{index}...")
await db.execute(f"""
await db.execute(
f"""
CREATE INDEX IF NOT EXISTS idx_payments_{index} ON apipayments ({index});
""")
"""
)
async def m040_index_wallets(db: Connection):
@@ -767,9 +825,11 @@ async def m040_index_wallets(db: Connection):
for index in indexes:
logger.debug(f"Creating index idx_wallets_{index}...")
await db.execute(f"""
await db.execute(
f"""
CREATE INDEX IF NOT EXISTS idx_wallets_{index} ON wallets ("{index}");
""")
"""
)
async def m042_index_accounts(db: Connection):
@@ -783,9 +843,11 @@ async def m042_index_accounts(db: Connection):
for index in indexes:
logger.debug(f"Creating index idx_wallets_{index}...")
await db.execute(f"""
await db.execute(
f"""
CREATE INDEX IF NOT EXISTS idx_accounts_{index} ON accounts ("{index}");
""")
"""
)
async def m043_add_ui_customization_to_accounts(db: Connection):
-1
View File
@@ -1 +0,0 @@
"""SSO authentication providers for LNbits"""
-36
View File
@@ -1,36 +0,0 @@
"""Generic OIDC SSO Login Helper"""
from typing import Optional
import httpx
from fastapi_sso.sso.base import DiscoveryDocument, OpenID, SSOBase
class OidcSSO(SSOBase):
"""Class providing login via Generic OIDC OAuth (e.g., Zitadel, Authentik, etc.)"""
provider = "oidc"
scope = ["openid", "email", "profile"]
discovery_url = ""
async def openid_from_response(
self, response: dict, session: Optional["httpx.AsyncClient"] = None
) -> OpenID:
"""Return OpenID from user information provided by OIDC provider"""
return OpenID(
email=response.get("email", ""),
provider=self.provider,
id=response.get("sub"),
first_name=response.get("given_name"),
last_name=response.get("family_name"),
display_name=response.get("name") or response.get("preferred_username"),
picture=response.get("picture"),
)
async def get_discovery_document(self) -> DiscoveryDocument:
"""Get document containing handy urls"""
async with httpx.AsyncClient() as session:
response = await session.get(self.discovery_url)
content = response.json()
return content
-6
View File
@@ -173,12 +173,6 @@ async def check_admin_settings():
if account and account.extra and account.extra.provider == "env":
settings.first_install = True
if settings.has_first_install_token_changed():
logger.warning("First install token is changed. Resetting admin settings.")
new_settings = await init_admin_settings()
settings.super_user = new_settings.super_user
settings.first_install = True
logger.success(
"✔️ Admin UI is enabled. run `uv run lnbits-cli superuser` "
"to get the superuser."
+3
View File
@@ -0,0 +1,3 @@
{% extends "base.html" %} {% from "macros.jinja" import window_vars with context
%} {% block scripts %} {{ window_vars(user) }} {% endblock %} {% block page %}{%
endblock %}
+3
View File
@@ -0,0 +1,3 @@
{% extends "public.html" %} {% from "macros.jinja" import window_vars with
context %} {% block scripts %} {{ window_vars() }} {% endblock %} {% block page
%} {% endblock %}
+11 -62
View File
@@ -12,7 +12,6 @@ from fastapi.responses import JSONResponse, RedirectResponse
from fastapi_sso.sso.base import OpenID, SSOBase
from loguru import logger
from lnbits.core.crud.settings import set_settings_field
from lnbits.core.crud.users import (
get_user_access_control_lists,
update_user_access_control_list,
@@ -155,20 +154,9 @@ async def impersonate_user(
max_age = settings.auth_token_expire_minutes * 60
response.set_cookie(
"admin_access_token",
cookie_access_token,
httponly=True,
secure=settings.auth_https_only,
samesite="lax",
max_age=max_age,
)
response.set_cookie(
"is_lnbits_user_impersonated",
"true",
secure=settings.auth_https_only,
samesite="lax",
max_age=max_age,
"admin_access_token", cookie_access_token, httponly=True, max_age=max_age
)
response.set_cookie("is_lnbits_user_impersonated", "true", max_age=max_age)
return response
@@ -189,12 +177,7 @@ async def stop_impersonate_user(
)
max_age = settings.auth_token_expire_minutes * 60
response.set_cookie(
"cookie_access_token",
admin_access_token,
httponly=True,
secure=settings.auth_https_only,
samesite="lax",
max_age=max_age,
"cookie_access_token", admin_access_token, httponly=True, max_age=max_age
)
response.delete_cookie("admin_access_token")
response.delete_cookie("is_access_token_expired")
@@ -549,13 +532,6 @@ async def first_install(data: UpdateSuperuserPassword) -> JSONResponse:
account.hash_password(data.password)
await update_account(account)
settings.first_install = False
# only confrm it after the super user has been successfully updated
if settings.first_install_token:
settings.first_install_token_confirmed = data.first_install_token
await set_settings_field(
"first_install_token_confirmed", data.first_install_token
)
return _auth_success_response(account.username, account.id, account.email)
@@ -584,7 +560,7 @@ async def _handle_sso_login(userinfo: OpenID, verified_user_id: str | None = Non
id=uuid4().hex, email=email, extra=UserExtra(email_verified=True)
)
await create_user_account(account)
return _auth_redirect_response(redirect_path, account.id, email)
return _auth_redirect_response(redirect_path, email)
def _auth_success_response(
@@ -599,20 +575,9 @@ def _auth_success_response(
max_age = settings.auth_token_expire_minutes * 60
response = JSONResponse({"access_token": access_token, "token_type": "bearer"})
response.set_cookie(
"cookie_access_token",
access_token,
httponly=True,
secure=settings.auth_https_only,
samesite="lax",
max_age=max_age,
)
response.set_cookie(
"is_lnbits_user_authorized",
"true",
secure=settings.auth_https_only,
samesite="lax",
max_age=max_age,
"cookie_access_token", access_token, httponly=True, max_age=max_age
)
response.set_cookie("is_lnbits_user_authorized", "true", max_age=max_age)
response.delete_cookie("is_access_token_expired")
return response
@@ -629,28 +594,15 @@ def _auth_api_token_response(
)
def _auth_redirect_response(path: str, user_id: str, email: str) -> RedirectResponse:
payload = AccessTokenPayload(
usr=user_id, sub="", email=email, auth_time=int(time())
)
def _auth_redirect_response(path: str, email: str) -> RedirectResponse:
payload = AccessTokenPayload(sub="" or "", email=email, auth_time=int(time()))
access_token = create_access_token(data=payload.dict())
max_age = settings.auth_token_expire_minutes * 60
response = RedirectResponse(path)
response.set_cookie(
"cookie_access_token",
access_token,
httponly=True,
secure=settings.auth_https_only,
samesite="lax",
max_age=max_age,
)
response.set_cookie(
"is_lnbits_user_authorized",
"true",
secure=settings.auth_https_only,
samesite="lax",
max_age=max_age,
"cookie_access_token", access_token, httponly=True, max_age=max_age
)
response.set_cookie("is_lnbits_user_authorized", "true", max_age=max_age)
response.delete_cookie("is_access_token_expired")
return response
@@ -670,10 +622,7 @@ def _new_sso(provider: str) -> SSOBase | None:
sso_provider_class = _find_auth_provider_class(provider)
sso_provider = sso_provider_class(
client_id,
client_secret,
None,
allow_insecure_http=not settings.auth_https_only,
client_id, client_secret, None, allow_insecure_http=True
)
if (
discovery_url
+2 -2
View File
@@ -200,7 +200,7 @@ async def index(
) -> HTMLResponse:
return template_renderer().TemplateResponse(
request,
"base.html",
"index.html",
{
"user": user.json(),
},
@@ -211,7 +211,7 @@ async def index(
@generic_router.get("/node/public")
@generic_router.get("/first_install", dependencies=[Depends(check_first_install)])
async def index_public(request: Request) -> HTMLResponse:
return template_renderer().TemplateResponse(request, "base.html", {"public": True})
return template_renderer().TemplateResponse(request, "index.html", {"public": True})
@generic_router.get("/uuidv4/{hex_value}")
-6
View File
@@ -613,12 +613,6 @@ class Filters(BaseModel, Generic[TFilterModel]):
for page_filter in self.filters:
page_filter.table_name = table_name
def get_filter_by_field(self, field: str) -> Filter[TFilterModel] | None:
return next((f for f in self.filters if f.field == field), None)
def remove_filter_by_field(self, field: str) -> None:
self.filters = [f for f in self.filters if f.field != field]
class DbJsonEncoder(json.JSONEncoder):
def default(self, o):
+1
View File
@@ -55,6 +55,7 @@ def static_url_for(static: str, path: str) -> str:
def template_renderer(additional_folders: list | None = None) -> Jinja2Templates:
folders = [
"lnbits/templates",
"lnbits/core/templates",
settings.extension_builder_working_dir_path.as_posix(),
]
-27
View File
@@ -447,7 +447,6 @@ class SecuritySettings(LNbitsSettings):
lnbits_max_outgoing_payment_amount_sats: int = Field(default=10_000_000, ge=0)
lnbits_max_incoming_payment_amount_sats: int = Field(default=10_000_000, ge=0)
first_install_token_confirmed: str | None = Field(default=None)
def is_wallet_max_balance_exceeded(self, amount):
return (
@@ -733,7 +732,6 @@ class FundingSourcesSettings(
# How long to wait for the payment to be confirmed before returning a pending status
# It will not fail the payment, it will make it return pending after the timeout
lnbits_funding_source_pay_invoice_wait_seconds: int = Field(default=5, ge=0)
lnbits_funding_source_pending_interval_seconds: int = Field(default=1800, ge=0)
funding_source_max_retries: int = Field(default=4, ge=0)
@@ -798,7 +796,6 @@ class AuthMethods(Enum):
google_auth = "google-auth"
github_auth = "github-auth"
keycloak_auth = "keycloak-auth"
oidc_auth = "oidc-auth"
@classmethod
def all(cls):
@@ -809,7 +806,6 @@ class AuthMethods(Enum):
AuthMethods.google_auth.value,
AuthMethods.github_auth.value,
AuthMethods.keycloak_auth.value,
AuthMethods.oidc_auth.value,
]
@@ -855,14 +851,6 @@ class KeycloakAuthSettings(LNbitsSettings):
keycloak_client_custom_icon: str | None = Field(default=None)
class OidcAuthSettings(LNbitsSettings):
oidc_discovery_url: str = Field(default="")
oidc_client_id: str = Field(default="")
oidc_client_secret: str = Field(default="")
oidc_client_custom_org: str | None = Field(default=None)
oidc_client_custom_icon: str | None = Field(default=None)
class AuditSettings(LNbitsSettings):
lnbits_audit_enabled: bool = Field(default=True)
@@ -970,7 +958,6 @@ class EditableSettings(
GoogleAuthSettings,
GitHubAuthSettings,
KeycloakAuthSettings,
OidcAuthSettings,
):
@validator(
"lnbits_admin_users",
@@ -1006,9 +993,6 @@ class EnvSettings(LNbitsSettings):
debug: bool = Field(default=False)
debug_database: bool = Field(default=False)
bundle_assets: bool = Field(default=True)
# When enabled, auth cookies require HTTPS and SSO will reject insecure HTTP.
# Set to false for local/dev environments that run without TLS.
auth_https_only: bool = Field(default=True)
host: str = Field(default="127.0.0.1")
port: int = Field(default=5000, gt=0)
forwarded_allow_ips: str = Field(default="*")
@@ -1031,13 +1015,6 @@ class EnvSettings(LNbitsSettings):
def has_default_extension_path(self) -> bool:
return self.lnbits_extensions_path == "lnbits"
def has_first_install_token_changed(self) -> bool:
if not self.first_install_token:
return False
if not settings.first_install_token_confirmed:
return False
return self.first_install_token != settings.first_install_token_confirmed
def check_auth_secret_key(self):
if self.auth_secret_key:
return
@@ -1197,8 +1174,6 @@ class PublicSettings(BaseModel):
auth_methods: list[str] = Field(alias="authMethods")
keycloak_org: str | None = Field(alias="keycloakOrg")
keycloak_icon: str | None = Field(alias="keycloakIcon")
oidc_org: str | None = Field(alias="oidcOrg")
oidc_icon: str | None = Field(alias="oidcIcon")
has_holdinvoice: bool = Field(alias="hasHoldinvoice")
has_nodemanager: bool = Field(alias="hasNodemanager")
show_nodemanager: bool = Field(alias="showNodemanager")
@@ -1263,8 +1238,6 @@ class PublicSettings(BaseModel):
authMethods=settings.auth_allowed_methods,
keycloakOrg=settings.keycloak_client_custom_org,
keycloakIcon=settings.keycloak_client_custom_icon,
oidcOrg=settings.oidc_client_custom_org,
oidcIcon=settings.oidc_client_custom_icon,
hasHoldinvoice=settings.has_holdinvoice,
hasNodemanager=settings.has_nodemanager,
showNodemanager=settings.lnbits_node_ui and settings.has_nodemanager,
File diff suppressed because one or more lines are too long
+11 -11
View File
File diff suppressed because one or more lines are too long
-10
View File
@@ -640,16 +640,6 @@ window.localisation.br = {
auth_keycloak_ci_hint:
'Certifique-se de que a URL de retorno de chamada de autorização esteja definida para https://{domain}/api/v1/auth/keycloak/token',
auth_keycloak_cs_label: 'Segredo do Cliente Keycloak',
auth_keycloak_custom_org_label: 'Organização Personalizada do Keycloak',
auth_keycloak_custom_icon_label: 'Ícone Personalizado do Keycloak (URL)',
auth_oidc_label: 'URL de Descoberta do OIDC',
auth_oidc_ci_label: 'ID do Cliente OIDC',
auth_oidc_ci_hint:
'Certifique-se de que a URL de retorno de chamada de autorização esteja definida para https://{domain}/api/v1/auth/oidc/token',
auth_oidc_cs_label: 'Segredo do Cliente OIDC',
auth_oidc_custom_org_label:
'Nome da Organização Personalizada OIDC (ex. Zitadel, Authentik)',
auth_oidc_custom_icon_label: 'Ícone Personalizado do OIDC (URL)',
auth_keycloak_custom_org_label: 'Keycloak Custom Organization',
auth_keycloak_custom_icon_label: 'Ícone Personalizado do Keycloak (URL)',
currency_settings: 'Configurações de Moeda',
-9
View File
@@ -353,15 +353,6 @@ window.localisation.cn = {
auth_keycloak_ci_hint:
'确保授权回调URL设置为https://{domain}/api/v1/auth/keycloak/token',
auth_keycloak_cs_label: 'Keycloak客户端密钥',
auth_keycloak_custom_org_label: 'Keycloak 自定义组织',
auth_keycloak_custom_icon_label: 'Keycloak 自定义图标 (URL)',
auth_oidc_label: 'OIDC 发现 URL',
auth_oidc_ci_label: 'OIDC 客户端 ID',
auth_oidc_ci_hint:
'确保授权回调URL设置为https://{domain}/api/v1/auth/oidc/token',
auth_oidc_cs_label: 'OIDC客户端密钥',
auth_oidc_custom_org_label: 'OIDC 自定义组织名称(例如 Zitadel、Authentik',
auth_oidc_custom_icon_label: 'OIDC 自定义图标 (URL)',
currency_settings: '货币设置',
allowed_currencies: '允许的货币',
allowed_currencies_hint: '限制可用法定货币的数量',
-10
View File
@@ -367,16 +367,6 @@ window.localisation.cs = {
auth_keycloak_ci_hint:
'Ujistěte se, že je autorizace callback URL nastavena na https://{domain}/api/v1/auth/keycloak/token',
auth_keycloak_cs_label: 'Klíč k aplikaci Keycloak tajemství',
auth_keycloak_custom_org_label: 'Vlastní organizace Keycloak',
auth_keycloak_custom_icon_label: 'Vlastní ikona Keycloak (URL)',
auth_oidc_label: 'URL pro zjištění OIDC',
auth_oidc_ci_label: 'ID klienta OIDC',
auth_oidc_ci_hint:
'Ujistěte se, že je autorizace callback URL nastavena na https://{domain}/api/v1/auth/oidc/token',
auth_oidc_cs_label: 'Klíč k aplikaci OIDC tajemství',
auth_oidc_custom_org_label:
'Název vlastní organizace OIDC (např. Zitadel, Authentik)',
auth_oidc_custom_icon_label: 'Vlastní ikona OIDC (URL)',
currency_settings: 'Nastavení měny',
allowed_currencies: 'Povolené měny',
allowed_currencies_hint: 'Omezte počet dostupných fiat měn',
-10
View File
@@ -377,16 +377,6 @@ window.localisation.de = {
auth_keycloak_ci_hint:
'Stellen Sie sicher, dass die Autorisierungs-Callback-URL auf https://{domain}/api/v1/auth/keycloak/token eingestellt ist.',
auth_keycloak_cs_label: 'Keycloak-Client-Geheimnis',
auth_keycloak_custom_org_label: 'Keycloak Benutzerdefinierte Organisation',
auth_keycloak_custom_icon_label: 'Keycloak Benutzerdefiniertes Symbol (URL)',
auth_oidc_label: 'OIDC Discovery-URL',
auth_oidc_ci_label: 'OIDC-Client-ID',
auth_oidc_ci_hint:
'Stellen Sie sicher, dass die Autorisierungs-Callback-URL auf https://{domain}/api/v1/auth/oidc/token eingestellt ist.',
auth_oidc_cs_label: 'OIDC-Client-Geheimnis',
auth_oidc_custom_org_label:
'OIDC Benutzerdefinierter Organisationsname (z.B. Zitadel, Authentik)',
auth_oidc_custom_icon_label: 'OIDC Benutzerdefiniertes Symbol (URL)',
currency_settings: 'Währungseinstellungen',
allowed_currencies: 'Erlaubte Währungen',
allowed_currencies_hint:
-12
View File
@@ -611,10 +611,6 @@ window.localisation.en = {
payment_timeouts: 'Payment Timeouts',
payment_wait_time: 'Payment Wait Time',
seconds: 'seconds',
payment_pending_interval: 'Check payment interval (sec)',
payment_pending_interval_desc: 'Interval to check pending payments',
payment_pending_interval_tooltip:
'Controls how often LNbits checks for pending payments to update their status. Higher values can reduce the load on the node and speed up the payment process, but it will take longer for pending payments to be updated.',
payment_wait_time_desc:
'Wait time before marking an outgoing payment as pending. Default: 5s; raise for slow-settling invoices.',
payment_wait_time_tooltip:
@@ -646,14 +642,6 @@ window.localisation.en = {
auth_keycloak_cs_label: 'Keycloak Client Secret',
auth_keycloak_custom_org_label: 'Keycloak Custom Organization',
auth_keycloak_custom_icon_label: 'Keycloak Custom Icon (URL)',
auth_oidc_label: 'OIDC Discovery URL',
auth_oidc_ci_label: 'OIDC Client ID',
auth_oidc_ci_hint:
'Make sure that the authorization callback URL is set to https://{domain}/api/v1/auth/oidc/token',
auth_oidc_cs_label: 'OIDC Client Secret',
auth_oidc_custom_org_label:
'OIDC Custom Organization Name (e.g., Zitadel, Authentik)',
auth_oidc_custom_icon_label: 'OIDC Custom Icon (URL)',
currency_settings: 'Currency Settings',
allowed_currencies: 'Allowed Currencies',
allowed_currencies_hint:
-10
View File
@@ -379,16 +379,6 @@ window.localisation.es = {
auth_keycloak_ci_hint:
'Asegúrate de que la URL de devolución de llamada de autorización esté configurada en https://{domain}/api/v1/auth/keycloak/token',
auth_keycloak_cs_label: 'Secreto del Cliente de Keycloak',
auth_keycloak_custom_org_label: 'Organización personalizada de Keycloak',
auth_keycloak_custom_icon_label: 'Icono personalizado de Keycloak (URL)',
auth_oidc_label: 'URL de descubrimiento de OIDC',
auth_oidc_ci_label: 'ID de cliente de OIDC',
auth_oidc_ci_hint:
'Asegúrate de que la URL de devolución de llamada de autorización esté configurada en https://{domain}/api/v1/auth/oidc/token',
auth_oidc_cs_label: 'Secreto del Cliente de OIDC',
auth_oidc_custom_org_label:
'Nombre de organización personalizada OIDC (ej. Zitadel, Authentik)',
auth_oidc_custom_icon_label: 'Icono personalizado de OIDC (URL)',
currency_settings: 'Configuración de moneda',
allowed_currencies: 'Monedas permitidas',
allowed_currencies_hint:
-8
View File
@@ -520,14 +520,6 @@ window.localisation.fi = {
auth_keycloak_cs_label: 'Keycloak-asiakassalasana',
auth_keycloak_custom_org_label: 'Valinnainen Keycloak-organisaatio',
auth_keycloak_custom_icon_label: 'Valinnainen Keycloak-kuvake (URL)',
auth_oidc_label: 'OIDC-discovery-URL',
auth_oidc_ci_label: 'OIDC-asiakastunnus',
auth_oidc_ci_hint:
'Varmista, että valtuutuksen palautus-URL on asetettu muotoon https://{domain}/api/v1/auth/oidc/token',
auth_oidc_cs_label: 'OIDC-asiakassalasana',
auth_oidc_custom_org_label:
'OIDC mukautetun organisaation nimi (esim. Zitadel, Authentik)',
auth_oidc_custom_icon_label: 'Valinnainen OIDC-kuvake (URL)',
currency_settings: 'Valuutta-asetukset',
allowed_currencies: 'Käytettävät valuutat',
allowed_currencies_hint: 'Valitse käytettävissä olevat fiat-valuutat',
-10
View File
@@ -381,16 +381,6 @@ window.localisation.fr = {
auth_keycloak_ci_hint:
"Assurez-vous que l'URL de rappel d'autorisation est définie sur https://{domain}/api/v1/auth/keycloak/token",
auth_keycloak_cs_label: 'Secret client Keycloak',
auth_keycloak_custom_org_label: 'Organisation personnalisée Keycloak',
auth_keycloak_custom_icon_label: 'Icône personnalisée Keycloak (URL)',
auth_oidc_label: 'URL de découverte OIDC',
auth_oidc_ci_label: 'ID Client OIDC',
auth_oidc_ci_hint:
"Assurez-vous que l'URL de rappel d'autorisation est définie sur https://{domain}/api/v1/auth/oidc/token",
auth_oidc_cs_label: 'Secret client OIDC',
auth_oidc_custom_org_label:
"Nom de l'organisation personnalisée OIDC (par ex. Zitadel, Authentik)",
auth_oidc_custom_icon_label: 'Icône personnalisée OIDC (URL)',
currency_settings: 'Paramètres de devise',
allowed_currencies: 'Devises autorisées',
allowed_currencies_hint:
-10
View File
@@ -378,16 +378,6 @@ window.localisation.it = {
auth_keycloak_ci_hint:
"Assicurati che l'URL di callback dell'autorizzazione sia impostato su https://{domain}/api/v1/auth/keycloak/token",
auth_keycloak_cs_label: 'Keycloak Client Secret',
auth_keycloak_custom_org_label: 'Organizzazione personalizzata di Keycloak',
auth_keycloak_custom_icon_label: 'Icona personalizzata di Keycloak (URL)',
auth_oidc_label: 'URL di individuazione di OIDC',
auth_oidc_ci_label: 'ID client di OIDC',
auth_oidc_ci_hint:
"Assicurati che l'URL di callback dell'autorizzazione sia impostato su https://{domain}/api/v1/auth/oidc/token",
auth_oidc_cs_label: 'OIDC Client Secret',
auth_oidc_custom_org_label:
'Nome organizzazione personalizzata OIDC (es. Zitadel, Authentik)',
auth_oidc_custom_icon_label: 'Icona personalizzata di OIDC (URL)',
currency_settings: 'Impostazioni valuta',
allowed_currencies: 'Valute consentite',
allowed_currencies_hint: 'Limita il numero di valute fiat disponibili',
-9
View File
@@ -369,15 +369,6 @@ window.localisation.jp = {
auth_keycloak_ci_hint:
'認証コールバックURLが https://{domain}/api/v1/auth/keycloak/token に設定されていることを確認してください。',
auth_keycloak_cs_label: 'キークローククライアントシークレット',
auth_keycloak_custom_org_label: 'Keycloak カスタム組織',
auth_keycloak_custom_icon_label: 'Keycloak カスタムアイコン (URL)',
auth_oidc_label: 'OIDC ディスカバリー URL',
auth_oidc_ci_label: 'OIDC クライアント ID',
auth_oidc_ci_hint:
'認証コールバックURLが https://{domain}/api/v1/auth/oidc/token に設定されていることを確認してください。',
auth_oidc_cs_label: 'OIDC クライアントシークレット',
auth_oidc_custom_org_label: 'OIDC カスタム組織名(例:Zitadel、Authentik',
auth_oidc_custom_icon_label: 'OIDC カスタムアイコン (URL)',
currency_settings: '通貨設定',
allowed_currencies: '許可されている通貨',
allowed_currencies_hint: '利用可能な法定通貨の数を制限する',
-10
View File
@@ -365,16 +365,6 @@ window.localisation.kr = {
auth_keycloak_ci_hint:
'승인 콜백 URL이 https://{domain}/api/v1/auth/keycloak/token으로 설정되어 있는지 확인하십시오.',
auth_keycloak_cs_label: 'Keycloak 클라이언트 시크릿',
auth_keycloak_custom_org_label: 'Keycloak 사용자 정의 조직',
auth_keycloak_custom_icon_label: 'Keycloak 사용자 정의 아이콘 (URL)',
auth_oidc_label: 'OIDC 디스커버리 URL',
auth_oidc_ci_label: 'OIDC 클라이언트 ID',
auth_oidc_ci_hint:
'승인 콜백 URL이 https://{domain}/api/v1/auth/oidc/token으로 설정되어 있는지 확인하십시오.',
auth_oidc_cs_label: 'OIDC 클라이언트 시크릿',
auth_oidc_custom_org_label:
'OIDC 사용자 정의 조직 이름 (예: Zitadel, Authentik)',
auth_oidc_custom_icon_label: 'OIDC 사용자 정의 아이콘 (URL)',
currency_settings: '통화 설정',
allowed_currencies: '허용되는 통화',
allowed_currencies_hint: '사용 가능한 법정 화폐의 수를 제한하십시오.',
-10
View File
@@ -377,16 +377,6 @@ window.localisation.nl = {
auth_keycloak_ci_hint:
'Zorg ervoor dat de autorisatie callback-URL is ingesteld op https://{domain}/api/v1/auth/keycloak/token',
auth_keycloak_cs_label: 'Keycloak Clientgeheim',
auth_keycloak_custom_org_label: 'Keycloak Aangepaste Organisatie',
auth_keycloak_custom_icon_label: 'Keycloak Aangepast Pictogram (URL)',
auth_oidc_label: 'OIDC Ontdekking URL',
auth_oidc_ci_label: 'OIDC-client-ID',
auth_oidc_ci_hint:
'Zorg ervoor dat de autorisatie callback-URL is ingesteld op https://{domain}/api/v1/auth/oidc/token',
auth_oidc_cs_label: 'OIDC Clientgeheim',
auth_oidc_custom_org_label:
'OIDC Aangepaste Organisatienaam (bijv. Zitadel, Authentik)',
auth_oidc_custom_icon_label: 'OIDC Aangepast Pictogram (URL)',
currency_settings: 'Valuta-instellingen',
allowed_currencies: "Toegestane valuta's",
allowed_currencies_hint: "Beperk het aantal beschikbare fiatvaluta's",
-10
View File
@@ -371,16 +371,6 @@ window.localisation.pi = {
auth_keycloak_ci_hint:
"Make sure thant th' authorization callback URL be set t' https://{domain}/api/v1/auth/keycloak/token",
auth_keycloak_cs_label: 'Keycloak Client Secret',
auth_keycloak_custom_org_label: 'Keycloak Custom Organization',
auth_keycloak_custom_icon_label: 'Keycloak Custom Icon (URL)',
auth_oidc_label: 'OIDC Discovery URL',
auth_oidc_ci_label: 'OIDC Client ID',
auth_oidc_ci_hint:
"Make sure thant th' authorization callback URL be set t' https://{domain}/api/v1/auth/oidc/token",
auth_oidc_cs_label: 'OIDC Client Secret',
auth_oidc_custom_org_label:
'OIDC Custom Organization Name (e.g., Zitadel, Authentik)',
auth_oidc_custom_icon_label: 'OIDC Custom Icon (URL)',
currency_settings: "Doubloon Settin's",
allowed_currencies: "Allo'ed Doubloons",
allowed_currencies_hint: 'Limit the number of available fiat doubloons',
-10
View File
@@ -372,16 +372,6 @@ window.localisation.pl = {
auth_keycloak_ci_hint:
'Upewnij się, że URL zwrotu autoryzacji jest ustawiony na https://{domain}/api/v1/auth/keycloak/token',
auth_keycloak_cs_label: 'Hasło klienta Keycloak',
auth_keycloak_custom_org_label: 'Własna organizacja Keycloak',
auth_keycloak_custom_icon_label: 'Własna ikona Keycloak (URL)',
auth_oidc_label: 'Adres URL Discovery OIDC',
auth_oidc_ci_label: 'Identyfikator klienta OIDC',
auth_oidc_ci_hint:
'Upewnij się, że URL zwrotu autoryzacji jest ustawiony na https://{domain}/api/v1/auth/oidc/token',
auth_oidc_cs_label: 'Hasło klienta OIDC',
auth_oidc_custom_org_label:
'Nazwa własnej organizacji OIDC (np. Zitadel, Authentik)',
auth_oidc_custom_icon_label: 'Własna ikona OIDC (URL)',
currency_settings: 'Ustawienia waluty',
allowed_currencies: 'Dozwolone waluty',
allowed_currencies_hint: 'Ogranicz liczbę dostępnych walut fiducjarnych',
-10
View File
@@ -375,16 +375,6 @@ window.localisation.pt = {
auth_keycloak_ci_hint:
'Certifique-se de que o URL de retorno de chamada de autorização esteja definido como https://{domain}/api/v1/auth/keycloak/token',
auth_keycloak_cs_label: 'Segredo do Cliente do Keycloak',
auth_keycloak_custom_org_label: 'Organização Personalizada do Keycloak',
auth_keycloak_custom_icon_label: 'Ícone Personalizado do Keycloak (URL)',
auth_oidc_label: 'URL de Descoberta do OIDC',
auth_oidc_ci_label: 'ID do Cliente do OIDC',
auth_oidc_ci_hint:
'Certifique-se de que o URL de retorno de chamada de autorização esteja definido como https://{domain}/api/v1/auth/oidc/token',
auth_oidc_cs_label: 'Segredo do Cliente do OIDC',
auth_oidc_custom_org_label:
'Nome da Organização Personalizada OIDC (ex. Zitadel, Authentik)',
auth_oidc_custom_icon_label: 'Ícone Personalizado do OIDC (URL)',
currency_settings: 'Configurações de Moeda',
allowed_currencies: 'Moedas Permitidas',
allowed_currencies_hint: 'Limite o número de moedas fiduciárias disponíveis',
-10
View File
@@ -371,16 +371,6 @@ window.localisation.sk = {
auth_keycloak_ci_hint:
'Uistite sa, že URL spätného volania autorizácie je nastavená na https://{domain}/api/v1/auth/keycloak/token',
auth_keycloak_cs_label: 'Tajný kľúč klienta Keycloak',
auth_keycloak_custom_org_label: 'Vlastná organizácia Keycloak',
auth_keycloak_custom_icon_label: 'Vlastná ikona Keycloak (URL)',
auth_oidc_label: 'URL zistenia OIDC',
auth_oidc_ci_label: 'ID klienta OIDC',
auth_oidc_ci_hint:
'Uistite sa, že URL spätného volania autorizácie je nastavená na https://{domain}/api/v1/auth/oidc/token',
auth_oidc_cs_label: 'Tajný kľúč klienta OIDC',
auth_oidc_custom_org_label:
'Názov vlastnej organizácie OIDC (napr. Zitadel, Authentik)',
auth_oidc_custom_icon_label: 'Vlastná ikona OIDC (URL)',
currency_settings: 'Nastavenia meny',
allowed_currencies: 'Povolené meny',
allowed_currencies_hint: 'Obmedzte počet dostupných fiat mien',
-10
View File
@@ -370,16 +370,6 @@ window.localisation.we = {
auth_keycloak_ci_hint:
"Gwnewch yn siŵr bod URL adalw awdurdodiad wedi'i osod i https://{domain}/api/v1/auth/keycloak/token",
auth_keycloak_cs_label: 'Cyfrinach Cleient Keycloak',
auth_keycloak_custom_org_label: "Sefydliad Wedi'i Addasu Keycloak",
auth_keycloak_custom_icon_label: "Eicon Wedi'i Addasu Keycloak (URL)",
auth_oidc_label: 'URL Darganfod OIDC',
auth_oidc_ci_label: 'ID Cleient OIDC',
auth_oidc_ci_hint:
"Gwnewch yn siŵr bod URL adalw awdurdodiad wedi'i osod i https://{domain}/api/v1/auth/oidc/token",
auth_oidc_cs_label: 'Cyfrinach Cleient OIDC',
auth_oidc_custom_org_label:
"Enw Sefydliad Wedi'i Addasu OIDC (e.e. Zitadel, Authentik)",
auth_oidc_custom_icon_label: "Eicon Wedi'i Addasu OIDC (URL)",
currency_settings: 'Gosodiadau Arian Cyfred',
allowed_currencies: 'Ariannau a Ganiateir',
allowed_currencies_hint: 'Cyfyngu nifer yr arian cyfred fiat sydd ar gael',
Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

@@ -1,19 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<!-- Background circle -->
<circle cx="50" cy="50" r="48" fill="#4A90E2" stroke="#2E5F8E" stroke-width="2"/>
<!-- Lock body -->
<rect x="35" y="45" width="30" height="25" rx="2" fill="#FFFFFF"/>
<!-- Lock shackle -->
<path d="M 40 45 L 40 35 Q 40 25 50 25 Q 60 25 60 35 L 60 45"
fill="none" stroke="#FFFFFF" stroke-width="4" stroke-linecap="round"/>
<!-- Keyhole -->
<circle cx="50" cy="55" r="3" fill="#4A90E2"/>
<rect x="48.5" y="55" width="3" height="8" fill="#4A90E2"/>
<!-- ID letters -->
<text x="50" y="85" font-family="Arial, sans-serif" font-size="12" font-weight="bold"
fill="#FFFFFF" text-anchor="middle">ID</text>
</svg>

Before

Width:  |  Height:  |  Size: 773 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

+6 -5
View File
@@ -442,8 +442,7 @@ window.app.component('username-password', {
'nostr-auth-nip98',
'google-auth',
'github-auth',
'keycloak-auth',
'oidc-auth'
'keycloak-auth'
],
username: this.userName,
password: this.password_1,
@@ -692,10 +691,12 @@ window.app.component('lnbits-node-qrcode', {
<q-card-section>
<div class="text-h6">
<div style="text-align: center">
<lnbits-qrcode
v-if='info.addresses[0]'
<vue-qrcode
:value="info.addresses[0]"
></lnbits-qrcode>
:options="{width: 250}"
v-if='info.addresses[0]'
class="rounded-borders"
></vue-qrcode>
<div v-else class='text-subtitle1'>
No addresses available
</div>
@@ -165,26 +165,5 @@ window.app.component('lnbits-qrcode', {
this.$refs.qrCode.$el.style.maxWidth = this.maxWidth + 'px'
this.$refs.qrCode.$el.setAttribute('width', '100%')
this.$refs.qrCode.$el.removeAttribute('height')
},
computed: {
optimizedValue() {
const separatorIndex = this.value.indexOf(':')
const type =
separatorIndex === -1 ? '' : this.value.substring(0, separatorIndex)
const value =
separatorIndex === -1
? this.value
: this.value.substring(separatorIndex + 1)
if (this.utils.isValidBech32(value)) {
const normalizedValue = value.toUpperCase()
if (type) {
return `${type.toUpperCase()}:${normalizedValue}`
}
return normalizedValue
}
return this.value
}
}
})
-4
View File
@@ -10,10 +10,6 @@ window.PageAccount = {
name: 'bitcoin',
color: 'deep-orange'
},
{
name: 'classic',
color: 'purple'
},
{
name: 'mint',
color: 'green'
-40
View File
@@ -160,46 +160,6 @@ window._lnbitsUtils = {
return null
}
},
isValidBech32(value) {
if (typeof value !== 'string') {
return false
}
const candidate = value.trim()
if (
!candidate ||
(candidate !== candidate.toLowerCase() &&
candidate !== candidate.toUpperCase())
) {
return false
}
const normalized = candidate.toLowerCase()
const splitPosition = normalized.lastIndexOf('1')
if (splitPosition <= 0) {
return false
}
const humanReadablePart = normalized.substring(0, splitPosition)
const data = normalized.substring(splitPosition + 1)
if (data.length < 6) {
return false
}
if (
typeof bech32ToFiveBitArray !== 'function' ||
typeof verify_checksum !== 'function'
) {
return false
}
const words = bech32ToFiveBitArray(data)
if (words.some(word => word < 0)) {
return false
}
return verify_checksum(humanReadablePart, words)
},
async notifyApiError(error) {
if (!error.response) {
return console.error(error)
+2 -7
View File
@@ -82,8 +82,9 @@
<!-- scripts libraries -->
{% for url in INCLUDED_JS %}
<script src="{{ static_url_for('static', url) }}"></script>
{% endfor %} {% if user %}
{% endfor %}
<!-- user init -->
{% if user %}
<script>
window.g.user = LNbits.map.user(JSON.parse({{ user | tojson | safe }}));
{% if not public %}
@@ -91,12 +92,6 @@
{% endif %}
</script>
{% endif %}
<!-- app init -->
<script>
window.app = Vue.createApp({
el: '#vue'
})
</script>
<!-- scripts from extensions -->
{% block scripts %}{% endblock %}
<!-- components js -->
-28
View File
@@ -1050,34 +1050,6 @@ include('components/lnbits-error.vue') %}
></span>
</div>
</q-btn>
<q-btn
v-if="authMethods.includes('oidc-auth')"
href="/api/v1/auth/oidc"
type="a"
outline
no-caps
color="grey"
class="btn-fixed-width"
>
<q-avatar size="32px" class="q-mr-md">
<q-img
:src="
g.settings.oidcIcon
? g.settings.oidcIcon
: utils.url_for('lnbits/static/images/generic-oidc-logo.svg')
"
></q-img>
</q-avatar>
<div>
<span
v-text="
$t('signin_with_custom_org', {
custom_org: g.settings.oidcOrg || 'OIDC'
})
"
></span>
</div>
</q-btn>
</div>
</q-card-section>
</template>
@@ -160,27 +160,6 @@
min="0"
></q-input>
</div>
<div class="col-12 col-md-4">
<p>
<span v-text="$t('payment_pending_interval')"></span>
<sup>
<q-icon name="info" size="16px" class="q-ml-xs"></q-icon>
<q-tooltip max-width="150px">
<span v-text="$t('payment_pending_interval_tooltip')"></span>
</q-tooltip>
</sup>
</p>
<q-input
type="number"
filled
name="lnbits_funding_source_pending_interval_seconds"
v-model="formData.lnbits_funding_source_pending_interval_seconds"
:label="$t('payment_pending_interval')"
:hint="$t('payment_pending_interval_desc')"
step="1"
min="0"
></q-input>
</div>
</div>
<div v-if="isSuperUser">
<lnbits-admin-funding-sources
@@ -192,57 +192,6 @@
</div>
</div>
</q-card-section>
<q-card-section
v-if="formData.auth_allowed_methods?.includes('oidc-auth')"
class="q-pl-xl"
>
<strong class="q-my-none q-mb-sm">OIDC Auth</strong>
<div class="row q-col-gutter-sm q-col-gutter-y-md">
<div class="col-12 col-md-4">
<q-input
filled
v-model="formData.oidc_discovery_url"
:label="$t('auth_oidc_label')"
>
</q-input>
</div>
<div class="col-12 col-md-4">
<q-input
filled
v-model="formData.oidc_client_id"
:label="$t('auth_oidc_ci_label')"
:hint="$t('auth_oidc_ci_hint')"
>
</q-input>
</div>
<div class="col-12 col-md-4">
<q-input
filled
v-model="formData.oidc_client_secret"
type="password"
:label="$t('auth_oidc_cs_label')"
>
</q-input>
</div>
<div class="col-12 col-md-4">
<q-input
filled
v-model="formData.oidc_client_custom_org"
:label="$t('auth_oidc_custom_org_label')"
>
</q-input>
</div>
<div class="col-12 col-md-8">
<q-input
filled
v-model="formData.oidc_client_custom_icon"
:label="$t('auth_oidc_custom_icon_label')"
>
</q-input>
</div>
</div>
</q-card-section>
<q-separator></q-separator>
<q-card-section class="q-pa-none">
<br />
@@ -12,7 +12,7 @@
>
<qrcode-vue
ref="qrCode"
:value="optimizedValue"
:value="value"
:margin="margin"
:size="size"
level="Q"
+3 -1
View File
@@ -1,4 +1,6 @@
{% extends "base.html" %} {% block page_container %}
{% extends "public.html" %} {% from "macros.jinja" import window_vars with
context %} {% block scripts %} {{ window_vars() }} {% endblock %} {% block
page_container %}
<lnbits-error
code="{{ status_code | safe }}"
message="{{ message | safe }}"
+6 -2
View File
@@ -1,5 +1,9 @@
{% macro window_vars(user) -%}
<script>
// deprecated dont use window_vars anymore
<script>
//Needed for Vue to create the app on first load (although called on every page, its only loaded once)
window.app = Vue.createApp({
el: '#vue',
mixins: [window.windowMixin]
})
</script>
{%- endmacro %}
+1 -55
View File
@@ -262,9 +262,7 @@
<div
v-if="
'google-auth' in g.settings.authMethods ||
'github-auth' in g.settings.authMethods ||
'keycloak-auth' in g.settings.authMethods ||
'oidc-auth' in g.settings.authMethods
'github-auth' in g.settings.authMethods
"
class="col q-pa-sm text-h6"
>
@@ -312,58 +310,6 @@
<div>GitHub</div>
</q-btn>
</div>
<div
v-if="'keycloak-auth' in g.settings.authMethods"
class="col q-pa-sm"
>
<q-btn
:href="`/api/v1/auth/keycloak?user_id=${g.user.id}`"
type="a"
outline
no-caps
color="grey"
rounded
class="full-width"
>
<q-avatar size="32px" class="q-mr-md">
<q-img
:src="
g.settings.keycloakIcon
? g.settings.keycloakIcon
: '{{ static_url_for('static', 'images/keycloak-logo.png') }}'
"
></q-img>
</q-avatar>
<div
v-text="g.settings.keycloakOrg || 'Keycloak'"
></div>
</q-btn>
</div>
<div
v-if="'oidc-auth' in g.settings.authMethods"
class="col q-pa-sm"
>
<q-btn
:href="`/api/v1/auth/oidc?user_id=${g.user.id}`"
type="a"
outline
no-caps
color="grey"
rounded
class="full-width"
>
<q-avatar size="32px" class="q-mr-md">
<q-img
:src="
g.settings.oidcIcon
? g.settings.oidcIcon
: '{{ static_url_for('static', 'images/generic-oidc-logo.svg') }}'
"
></q-img>
</q-avatar>
<div v-text="g.settings.oidcOrg || 'OIDC'"></div>
</q-btn>
</div>
</div>
</q-card-section>
+9 -6
View File
@@ -438,7 +438,7 @@
<q-card-section>
<div v-if="selectedRelease.paymentRequest">
<lnbits-qrcode
:value="'LIGHTNING:' + selectedRelease.paymentRequest.toUpperCase()"
:value="'lightning:' + selectedRelease.paymentRequest.toUpperCase()"
:href="'lightning:' + selectedRelease.paymentRequest"
></lnbits-qrcode>
</div>
@@ -836,7 +836,7 @@
<div v-if="selectedExtension.payToEnable.paymentRequest" class="col">
<lnbits-qrcode
:value="
'LIGHTNING:' +
'lightning:' +
selectedExtension.payToEnable.paymentRequest.toUpperCase()
"
:href="
@@ -1247,10 +1247,13 @@
<q-dialog v-model="paymentDialog.show" position="top">
<q-card class="q-pa-md lnbits__dialog-card">
<q-card-section>
<lnbits-qrcode
:value="'LIGHTNING:' + paymentDialog.invoice.toUpperCase()"
:href="'lightning:' + paymentDialog.invoice"
></lnbits-qrcode>
<q-responsive :ratio="1" class="q-mx-xl q-mb-xl">
<lnbits-qrcode
:value="paymentDialog.invoice"
:options="{width: 800}"
class="rounded-borders"
></lnbits-qrcode>
</q-responsive>
</q-card-section>
<q-card-actions align="between">
<q-btn v-close-popup flat color="grey" :label="$t('close')"></q-btn>
+29 -12
View File
@@ -589,16 +589,23 @@
v-if="transactionDetailsDialog.data.bolt11"
class="text-center q-mb-lg"
>
<lnbits-qrcode
<a
:href="
'lightning:' +
transactionDetailsDialog.data.bolt11
"
:value="
'LIGHTNING:' +
transactionDetailsDialog.data.bolt11.toUpperCase()
"
></lnbits-qrcode>
>
<q-responsive :ratio="1" class="q-mx-xl">
<qrcode-vue
:value="
'lightning:' +
transactionDetailsDialog.data.bolt11.toUpperCase()
"
:options="{width: 340}"
class="rounded-borders"
></qrcode-vue>
</q-responsive>
</a>
<q-btn
outline
color="grey"
@@ -691,15 +698,25 @@
v-if="props.row.bolt11"
class="text-center q-mb-lg"
>
<lnbits-qrcode
:value="
'LIGHTNING:' +
props.row.bolt11.toUpperCase()
"
<a
:href="
'lightning:' + props.row.bolt11
"
></lnbits-qrcode>
>
<q-responsive
:ratio="1"
class="q-mx-xl"
>
<qrcode-vue
:value="
'lightning:' +
props.row.bolt11.toUpperCase()
"
:options="{width: 340}"
class="rounded-borders"
></qrcode-vue>
</q-responsive>
</a>
</div>
<div class="row q-mt-lg">
<q-btn
+1 -1
View File
@@ -438,7 +438,7 @@
<lnbits-qrcode
v-else
:href="'lightning:' + receive.paymentReq"
:value="'LIGHTNING:' + receive.paymentReq.toUpperCase()"
:value="'lightning:' + receive.paymentReq"
>
</lnbits-qrcode>
<div class="text-center">
+1 -5
View File
@@ -15,11 +15,7 @@ from lnbits.settings import settings
def log_server_info():
logger.info("LNbits Info")
if settings.first_install:
if settings.has_first_install_token_changed():
logger.success("This is a first install token reset.")
else:
logger.success("This is a fresh install of LNbits.")
logger.success("This is a fresh install of LNbits.")
if settings.first_install_token:
logger.success(
f"FIRST_INSTALL_TOKEN: `{settings.first_install_token}`. "
+1 -1
View File
@@ -69,7 +69,7 @@ def decrypt_content(
1:
]
# extract iv and content
encrypted_content_b64, iv_b64 = content.split("?iv=")
(encrypted_content_b64, iv_b64) = content.split("?iv=")
encrypted_content = base64.b64decode(encrypted_content_b64.encode("ascii"))
iv = base64.b64decode(iv_b64.encode("ascii"))
# Decrypt
+23 -122
View File
@@ -80,40 +80,22 @@ class SparkL2Wallet(Wallet):
async def status(self) -> StatusResponse:
try:
r = await self.client.post("/v1/balance", timeout=30)
r.raise_for_status()
data = r.json()
if not isinstance(data, dict) or len(data) == 0:
return StatusResponse("no data", 0)
error_message = self._extract_error_message(data)
if error_message:
return StatusResponse(self._server_error_message(error_message), 0)
status = data.get("status")
res = await self._request("POST", "/v1/balance")
status = res.get("status")
if status == "missing_mnemonic":
await self._check_sidecar_mnemonic()
return StatusResponse("Spark sidecar mnemonic not set", 0)
balance_msat = data.get("balance_msat")
balance_msat = res.get("balance_msat")
if balance_msat is not None:
return StatusResponse(None, int(balance_msat))
balance_sats = data.get("balance_sats")
balance_sats = res.get("balance_sats")
if balance_sats is None:
return StatusResponse("no data", 0)
return StatusResponse("Spark sidecar: missing balance.", 0)
return StatusResponse(None, int(balance_sats) * 1000)
except json.JSONDecodeError as e:
logger.warning(e)
return StatusResponse("Server error: 'invalid json response'", 0)
except httpx.HTTPStatusError as e:
logger.warning(e)
error_message = self._extract_http_error_message(e.response)
if error_message:
return StatusResponse(self._server_error_message(error_message), 0)
return StatusResponse(self._connect_error_message(), 0)
except Exception as e:
logger.warning(e)
return StatusResponse(self._connect_error_message(), 0)
return StatusResponse(f"Spark sidecar status error: {e}", 0)
async def create_invoice(
self,
@@ -139,28 +121,13 @@ class SparkL2Wallet(Wallet):
"description_hash": description_hash_hex,
"expiry_seconds": expiry_secs,
}
r = await self.client.post("/v1/invoices", json=payload, timeout=30)
r.raise_for_status()
data = r.json()
if not isinstance(data, dict):
return InvoiceResponse(
ok=False, error_message=self._server_error_message(r.text)
)
error_message = self._extract_error_message(data)
if error_message:
return InvoiceResponse(
ok=False,
error_message=self._server_error_message(error_message),
)
bolt11 = data.get("payment_request")
checking_id = data.get("checking_id")
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="Server error: 'missing required fields'",
error_message="Spark sidecar invoice response missing fields.",
)
self.pending_invoices.append(checking_id)
@@ -168,24 +135,10 @@ class SparkL2Wallet(Wallet):
ok=True,
payment_request=bolt11,
checking_id=checking_id,
preimage=data.get("preimage", None),
preimage=res.get("preimage", None),
)
except json.JSONDecodeError:
return InvoiceResponse(
ok=False, error_message="Server error: 'invalid json response'"
)
except httpx.HTTPStatusError as e:
logger.warning(e)
error_message = self._extract_http_error_message(e.response)
if error_message:
return InvoiceResponse(
ok=False,
error_message=self._server_error_message(error_message),
)
return InvoiceResponse(ok=False, error_message=self._connect_error_message())
except Exception as e:
logger.warning(e)
return InvoiceResponse(ok=False, error_message=self._connect_error_message())
return InvoiceResponse(ok=False, error_message=str(e))
async def pay_invoice(self, bolt11: str, fee_limit_msat: int) -> PaymentResponse:
try:
@@ -205,53 +158,27 @@ class SparkL2Wallet(Wallet):
"max_fee_sats": max_fee_sats,
"payment_hash": payment_hash,
}
r = await self.client.post("/v1/payments", json=payload, timeout=30)
r.raise_for_status()
data = r.json()
if not isinstance(data, dict):
return PaymentResponse(error_message=self._server_error_message(r.text))
error_message = self._extract_error_message(data)
if error_message:
return PaymentResponse(error_message=error_message)
if len(data) == 0:
return PaymentResponse(
error_message="Server error: 'missing required fields'"
)
status = data.get("status")
fee_msat = data.get("fee_msat")
preimage = data.get("preimage")
ok = self._map_payment_ok(status) if status else None
if ok is False:
return PaymentResponse(ok=False)
checking_id = payment_hash or data.get("checking_id")
res = await self._request("POST", "/v1/payments", payload)
checking_id = payment_hash or res.get("checking_id")
if not checking_id:
return PaymentResponse(
error_message="Server error: 'missing required fields'"
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=preimage,
preimage=res.get("preimage"),
)
except json.JSONDecodeError:
return PaymentResponse(error_message="Server error: 'invalid json response'")
except httpx.HTTPStatusError as e:
logger.warning(e)
error_message = self._extract_http_error_message(e.response)
if error_message:
return PaymentResponse(error_message=error_message)
return PaymentResponse(error_message=self._connect_error_message())
except Exception as e:
logger.warning(e)
return PaymentResponse(error_message=self._connect_error_message())
return PaymentResponse(ok=False, error_message=str(e))
async def get_invoice_status(self, checking_id: str) -> PaymentStatus:
try:
@@ -403,32 +330,6 @@ class SparkL2Wallet(Wallet):
return False
return None
def _connect_error_message(self) -> str:
return f"Unable to connect to {self.endpoint}."
@staticmethod
def _server_error_message(message: str) -> str:
return f"Server error: '{message}'"
@staticmethod
def _extract_error_message(data: Any) -> str | None:
if not isinstance(data, dict):
return None
for key in ("error", "message", "detail", "reason"):
value = data.get(key)
if value:
return str(value)
return None
def _extract_http_error_message(self, response: httpx.Response | None) -> str | None:
if response is None:
return None
try:
data = response.json()
except Exception:
return None
return self._extract_error_message(data)
async def _check_sidecar_mnemonic(self):
if settings.spark_l2_mnemonic:
valid = mnemonic_is_valid(settings.spark_l2_mnemonic)
+3 -3
View File
@@ -1498,9 +1498,9 @@
"license": "ISC"
},
"node_modules/picomatch": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
"integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
"integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
"dev": true,
"license": "MIT",
"engines": {
Generated
+1824 -2214
View File
File diff suppressed because it is too large Load Diff
+65 -65
View File
@@ -1,56 +1,56 @@
[project]
name = "lnbits"
version = "1.5.3"
version = "1.5.2"
requires-python = ">=3.10,<3.13"
description = "LNbits, free and open-source Lightning wallet and accounts system."
authors = [{ name = "Alan Bits", email = "alan@lnbits.com" }]
urls = { Homepage = "https://lnbits.com", Repository = "https://github.com/lnbits/lnbits" }
readme = "README.md"
dependencies = [
"bech32~=1.2.0",
"click~=8.3.1",
"fastapi~=0.116.1",
"starlette~=0.47.1",
"httpx~=0.27.2",
"jinja2~=3.1.6",
"lnurl~=0.10.0",
"pydantic~=1.10.26",
"pyqrcode~=1.2.1",
"shortuuid~=1.0.13",
"sse-starlette~=2.3.6",
"typing-extensions~=4.15.0",
"uvicorn~=0.40.0",
"sqlalchemy~=1.4.54",
"aiosqlite~=0.22.1",
"asyncpg~=0.31.0",
"uvloop~=0.22.1",
"websockets~=15.0.1",
"loguru~=0.7.3",
"grpcio~=1.76.0",
"protobuf~=6.33.5",
"pyln-client~=25.12.0",
"pywebpush~=2.2.0",
"slowapi~=0.1.9",
"websocket-client~=1.9.0",
"pycryptodomex~=3.23.0",
"packaging~=25.0.0",
"bolt11~=2.1.1",
"pyjwt~=2.12.0",
"itsdangerous~=2.2.0",
"fastapi-sso~=0.19.0",
"bech32==1.2.0",
"click==8.3.1",
"fastapi==0.116.1",
"starlette==0.47.1",
"httpx==0.27.2",
"jinja2==3.1.6",
"lnurl==0.8.3",
"pydantic==1.10.26",
"pyqrcode==1.2.1",
"shortuuid==1.0.13",
"sse-starlette==2.3.6",
"typing-extensions==4.15.0",
"uvicorn==0.40.0",
"sqlalchemy==1.4.54",
"aiosqlite==0.22.1",
"asyncpg==0.31.0",
"uvloop==0.22.1",
"websockets==15.0.1",
"loguru==0.7.3",
"grpcio==1.76.0",
"protobuf==6.33.2",
"pyln-client==25.12",
"pywebpush==2.2.0",
"slowapi==0.1.9",
"websocket-client==1.9.0",
"pycryptodomex==3.23.0",
"packaging==25.0",
"bolt11==2.1.1",
"pyjwt==2.10.1",
"itsdangerous==2.2.0",
"fastapi-sso==0.19.0",
# needed for boltz, lnurldevice, watchonly extensions
"embit~=0.8.0",
"embit==0.8.0",
# needed for scheduler extension
"python-crontab~=3.3.0",
"pynostr~=0.7.0",
"python-multipart~=0.0.22",
"filetype~=1.2.0",
"nostr-sdk~=0.44.0",
"bcrypt~=5.0.0",
"jsonpath-ng~=1.7.0",
"pillow~=12.1.0",
"python-dotenv~=1.2.1",
"greenlet~=3.3.0",
"python-crontab==3.3.0",
"pynostr==0.7.0",
"python-multipart==0.0.21",
"filetype==1.2.0",
"nostr-sdk==0.44.0",
"bcrypt==5.0.0",
"jsonpath-ng==1.7.0",
"pillow>=12.1.0",
"python-dotenv>=1.2.1",
"greenlet (>=3.3.0,<4.0.0)",
]
[project.scripts]
@@ -58,31 +58,31 @@ lnbits = "lnbits.server:main"
lnbits-cli = "lnbits.commands:main"
[project.optional-dependencies]
breez = ["breez-sdk~=0.8.0", "breez-sdk-liquid~=0.11.11"]
liquid = ["wallycore~=1.5.1"]
migration = ["psycopg2-binary~=2.9.11"]
breez = ["breez-sdk==0.8.0", "breez-sdk-liquid==0.11.11"]
liquid = ["wallycore==1.5.1"]
migration = ["psycopg2-binary==2.9.11"]
[dependency-groups]
dev = [
"black~=26.3.1",
"mypy~=1.17.1",
"types-protobuf~=6.32.1.20251210",
"pre-commit~=4.5.1",
"openapi-spec-validator~=0.7.2",
"ruff~=0.14.10",
"types-passlib~=1.7.7.20250602",
"openai~=2.14.0",
"json5~=0.13.0",
"asgi-lifespan~=2.1.0",
"anyio~=4.12.1",
"pytest~=9.0.2",
"pytest-cov~=7.0.0",
"pytest-md~=0.2.0",
"pytest-httpserver~=1.1.3",
"pytest-mock~=3.15.1",
"types-mock~=5.2.0.20250924",
"mock~=5.2.0",
"grpcio-tools~=1.76.0"
"black>=25.12.0,<26.0.0",
"mypy==1.17.1",
"types-protobuf>=6.32.1.20251210,<7.0.0",
"pre-commit>=4.5.1,<5.0.0",
"openapi-spec-validator>=0.7.2,<1.0.0",
"ruff>=0.14.10,<1.0.0",
"types-passlib>=1.7.7.20250602,<2.0.0",
"openai>=2.14.0",
"json5>=0.13.0,<1.0.0",
"asgi-lifespan>=2.1.0,<3.0.0",
"anyio>=4.12.1",
"pytest>=9.0.2",
"pytest-cov>=7.0.0",
"pytest-md>=0.2.0,<0.3.0",
"pytest-httpserver>=1.1.3,<2.0.0",
"pytest-mock>=3.15.1,<4.0.0",
"types-mock>=5.2.0.20250924,<6.0.0",
"mock>=5.2.0,<6.0.0",
"grpcio-tools>=1.76.0,<2.0.0"
]
[tool.poetry]
-2
View File
@@ -43,7 +43,6 @@ def anyio_backend():
@pytest.fixture(scope="session")
def settings():
# override settings for tests
lnbits_settings.auth_https_only = False
lnbits_settings.lnbits_admin_extensions = []
lnbits_settings.lnbits_data_folder = "./tests/data"
lnbits_settings.lnbits_admin_ui = True
@@ -72,7 +71,6 @@ async def app(settings: Settings):
username="superadmin",
password="secret1234",
password_repeat="secret1234",
first_install_token=settings.first_install_token,
)
)
+4 -158
View File
@@ -2,16 +2,10 @@ from uuid import uuid4
import pytest
from lnbits.core.crud.users import (
create_account,
delete_account,
get_accounts,
get_user_from_account,
)
from lnbits.core.crud.wallets import delete_wallet, force_delete_wallet, get_wallets
from lnbits.core.models.users import Account, AccountFilters
from lnbits.core.services.users import create_user_account, create_user_account_no_ckeck
from lnbits.db import Filter, Filters, Operator
from lnbits.core.crud.users import get_user_from_account
from lnbits.core.crud.wallets import delete_wallet, get_wallets
from lnbits.core.models.users import Account
from lnbits.core.services.users import create_user_account
@pytest.mark.anyio
@@ -42,151 +36,3 @@ async def test_get_user_from_account_is_wallet_created():
assert (
len(user.wallets) == 1
), "A new wallet should be created for the user if none exist after deletion"
@pytest.mark.anyio
async def test_get_accounts_success_flow():
# Create a new account
username = f"user_{uuid4().hex[:8]}"
account = Account(
id=uuid4().hex,
username=username,
email=f"{username}@lnbits.com",
)
await create_account(account)
# Should return the created account
filters = Filters[AccountFilters](filters=[], model=AccountFilters)
filters.sortby = "created_at"
filters.direction = "desc"
page = await get_accounts(filters=filters)
assert page.total >= 1
found = any(a.username == username for a in page.data)
assert found
await delete_account(account.id)
@pytest.mark.anyio
async def test_get_accounts_with_wallet_id_filter():
# Create account and wallet
username = f"user_{uuid4().hex[:8]}"
account = Account(
id=uuid4().hex,
username=username,
email=f"{username}@lnbits.com",
)
await create_user_account_no_ckeck(account)
wallets = await get_wallets(account.id, deleted=False)
assert wallets
wallet = wallets[0]
# Filter by wallet_id
filters = Filters[AccountFilters](
filters=[
Filter(
field="wallet_id",
op=Operator.EQ,
model=AccountFilters,
values={"wallet_id__0": wallet.id},
)
],
model=AccountFilters,
)
page = await get_accounts(filters=filters)
assert page.total == 1
assert page.data[0].id == account.id
await delete_account(account.id)
@pytest.mark.anyio
async def test_get_accounts_wallet_id_not_found():
filters = Filters[AccountFilters](
filters=[
Filter(
field="wallet_id",
op=Operator.EQ,
model=AccountFilters,
values={"wallet_id__0": uuid4().hex},
)
],
model=AccountFilters,
)
page = await get_accounts(filters=filters)
assert page.total == 0
assert page.data == []
@pytest.mark.anyio
async def test_get_accounts_empty_filters():
# Should not raise, should return a Page
page = await get_accounts()
assert hasattr(page, "data")
assert hasattr(page, "total")
@pytest.mark.anyio
async def test_get_accounts_with_deleted_wallet():
# Create account and wallet, then delete wallet
username = f"user_{uuid4().hex[:8]}"
account = Account(
id=uuid4().hex,
username=username,
email=f"{username}@lnbits.com",
)
await create_user_account_no_ckeck(account)
wallets = await get_wallets(account.id, deleted=False)
assert wallets
wallet = wallets[0]
await delete_wallet(user_id=account.id, wallet_id=wallet.id)
filters = Filters[AccountFilters](
filters=[
Filter(
field="wallet_id",
op=Operator.EQ,
model=AccountFilters,
values={"wallet_id__0": wallet.id},
)
],
model=AccountFilters,
)
page = await get_accounts(filters=filters)
assert page.total == 1
assert page.data[0].id == account.id
await force_delete_wallet(wallet_id=wallet.id)
filters = Filters[AccountFilters](
filters=[
Filter(
field="wallet_id",
op=Operator.EQ,
model=AccountFilters,
values={"wallet_id__0": wallet.id},
)
],
model=AccountFilters,
)
page = await get_accounts(filters=filters)
assert page.total == 0
assert page.data == []
@pytest.mark.anyio
async def test_get_accounts_group_by_and_pagination():
# Create multiple accounts
accounts = []
for _ in range(3):
username = f"user_{uuid4().hex[:8]}"
account = Account(
id=uuid4().hex,
username=username,
email=f"{username}@lnbits.com",
)
await create_user_account_no_ckeck(account)
accounts.append(account)
filters = Filters[AccountFilters](model=AccountFilters, limit=2, offset=0)
page = await get_accounts(filters=filters)
assert page.total >= 3
assert len(page.data) <= 2
+8 -4
View File
@@ -6,21 +6,25 @@ from tests.helpers import DbTestModel
@pytest.fixture(scope="session")
async def fetch_page(db):
await db.execute("DROP TABLE IF EXISTS test_db_fetch_page")
await db.execute("""
await db.execute(
"""
CREATE TABLE test_db_fetch_page (
id TEXT PRIMARY KEY,
value TEXT NOT NULL,
name TEXT NOT NULL
)
""")
await db.execute("""
"""
)
await db.execute(
"""
INSERT INTO test_db_fetch_page (id, name, value) VALUES
('1', 'Alice', 'foo'),
('2', 'Bob', 'bar'),
('3', 'Carol', 'bar'),
('4', 'Dave', 'bar'),
('5', 'Dave', 'foo')
""")
"""
)
yield
await db.execute("DROP TABLE test_db_fetch_page")
-140
View File
@@ -1,140 +0,0 @@
from pathlib import Path
from uuid import uuid4
import pytest
from lnbits.core.crud import create_account, delete_account, get_account
from lnbits.core.crud.settings import get_settings_field, set_settings_field
from lnbits.core.db import db
from lnbits.core.models import Account, UpdateSuperuserPassword, UserExtra
from lnbits.core.services.users import check_admin_settings
from lnbits.core.views.auth_api import first_install
from lnbits.settings import settings
async def _restore_setting_field(field_name: str, original_row) -> None:
if original_row is None:
await db.execute(
"DELETE FROM system_settings WHERE id = :id AND tag = :tag",
{"id": field_name, "tag": "core"},
)
return
await set_settings_field(field_name, original_row.value, original_row.tag)
def test_has_first_install_token_changed_requires_a_confirmed_mismatch():
original_token = settings.first_install_token
original_confirmed = settings.first_install_token_confirmed
try:
settings.first_install_token = "new-token"
settings.first_install_token_confirmed = "old-token"
assert settings.has_first_install_token_changed() is True
settings.first_install_token_confirmed = "new-token"
assert settings.has_first_install_token_changed() is False
settings.first_install_token_confirmed = None
assert settings.has_first_install_token_changed() is False
settings.first_install_token = None
assert settings.has_first_install_token_changed() is False
finally:
settings.first_install_token = original_token
settings.first_install_token_confirmed = original_confirmed
@pytest.mark.anyio
async def test_first_install_confirms_first_install_token(app):
temp_super_user = uuid4().hex
username = f"super_{temp_super_user[:8]}"
original_super_user = settings.super_user
original_first_install = settings.first_install
original_first_install_token = settings.first_install_token
original_first_install_token_confirmed = settings.first_install_token_confirmed
original_confirmed_row = await get_settings_field("first_install_token_confirmed")
await create_account(Account(id=temp_super_user, extra=UserExtra(provider="env")))
try:
settings.super_user = temp_super_user
settings.first_install = True
settings.first_install_token = "expected-token"
settings.first_install_token_confirmed = None
response = await first_install(
UpdateSuperuserPassword(
username=username,
password="secret1234",
password_repeat="secret1234",
first_install_token="expected-token",
)
)
assert response.status_code == 200
assert settings.first_install is False
assert settings.first_install_token_confirmed == "expected-token"
confirmed_row = await get_settings_field("first_install_token_confirmed")
assert confirmed_row is not None
assert confirmed_row.value == "expected-token"
account = await get_account(temp_super_user)
assert account is not None
assert account.username == username
assert account.extra.provider == "lnbits"
assert account.verify_password("secret1234")
finally:
await _restore_setting_field(
"first_install_token_confirmed", original_confirmed_row
)
settings.super_user = original_super_user
settings.first_install = original_first_install
settings.first_install_token = original_first_install_token
settings.first_install_token_confirmed = original_first_install_token_confirmed
await delete_account(temp_super_user)
@pytest.mark.anyio
async def test_check_admin_settings_clears_persisted_super_user_when_token_changes(app):
temp_super_user = uuid4().hex
original_super_user = settings.super_user
original_first_install = settings.first_install
original_first_install_token = settings.first_install_token
original_first_install_token_confirmed = settings.first_install_token_confirmed
original_super_user_row = await get_settings_field("super_user")
original_confirmed_row = await get_settings_field("first_install_token_confirmed")
super_user_file = Path(settings.lnbits_data_folder) / ".super_user"
await create_account(
Account(id=temp_super_user, extra=UserExtra(provider="lnbits"))
)
try:
await set_settings_field("super_user", temp_super_user)
await set_settings_field("first_install_token_confirmed", "old-token")
settings.lnbits_admin_ui = True
settings.super_user = temp_super_user
settings.first_install = False
settings.first_install_token = "new-token"
settings.first_install_token_confirmed = "old-token"
await check_admin_settings()
super_user_row = await get_settings_field("super_user")
assert super_user_row is not None
assert super_user_row.value
assert settings.first_install is True
finally:
await _restore_setting_field("super_user", original_super_user_row)
await _restore_setting_field(
"first_install_token_confirmed", original_confirmed_row
)
settings.super_user = original_super_user
settings.first_install = original_first_install
settings.first_install_token = original_first_install_token
settings.first_install_token_confirmed = original_first_install_token_confirmed
super_user_file.write_text(original_super_user)
await delete_account(temp_super_user)
+4 -404
View File
@@ -49,14 +49,6 @@
"phoenixd_api_password": "f171ba022a764e679eef950b21fb1c04f171ba022a764e679eef950b21fb1c04",
"user_agent": "LNbits/Tests"
}
},
"sparkl2": {
"wallet_class": "SparkL2Wallet",
"settings": {
"spark_l2_external_endpoint": "http://127.0.0.1:8555",
"spark_l2_external_api_key": "mock-spark-l2-api-key",
"user_agent": "LNbits/Tests"
}
}
},
"functions": {
@@ -123,16 +115,6 @@
},
"method": "GET"
}
},
"sparkl2": {
"status_endpoint": {
"uri": "/v1/balance",
"headers": {
"X-Api-Key": "mock-spark-l2-api-key",
"User-Agent": "LNbits/Tests"
},
"method": "POST"
}
}
},
"tests": [
@@ -208,16 +190,6 @@
}
}
]
},
"sparkl2": {
"status_endpoint": [
{
"response_type": "json",
"response": {
"balance_sats": 55
}
}
]
}
}
},
@@ -283,16 +255,6 @@
"response": "test-error"
}
]
},
"sparkl2": {
"status_endpoint": [
{
"response_type": "json",
"response": {
"error": "\"test-error\""
}
}
]
}
}
},
@@ -351,14 +313,6 @@
"response": {}
}
]
},
"sparkl2": {
"status_endpoint": [
{
"response_type": "json",
"response": {}
}
]
}
}
},
@@ -417,14 +371,6 @@
"response": "data-not-json"
}
]
},
"sparkl2": {
"status_endpoint": [
{
"response_type": "data",
"response": "data-not-json"
}
]
}
}
},
@@ -501,17 +447,6 @@
}
}
]
},
"sparkl2": {
"status_endpoint": [
{
"response_type": "response",
"response": {
"response": "Not Found",
"status": 404
}
}
]
}
}
},
@@ -588,16 +523,6 @@
},
"method": "POST"
}
},
"sparkl2": {
"create_invoice_endpoint": {
"uri": "/v1/invoices",
"headers": {
"X-Api-Key": "mock-spark-l2-api-key",
"User-Agent": "LNbits/Tests"
},
"method": "POST"
}
}
},
"tests": [
@@ -713,24 +638,6 @@
}
}
]
},
"sparkl2": {
"create_invoice_endpoint": [
{
"request_type": "json",
"request_body": {
"amount_sats": 555,
"memo": "Test Invoice",
"description_hash": null,
"expiry_seconds": null
},
"response_type": "json",
"response": {
"checking_id": "e35526a43d04e985594c0dfab848814f524b1c786598ec9a63beddb2d726ac96",
"payment_request": "lnbc5550n1pnq9jg3sp52rvwstvjcypjsaenzdh0h30jazvzsf8aaye0julprtth9kysxtuspp5e5s3z7felv4t9zrcc6wpn7ehvjl5yzewanzl5crljdl3jgeffyhqdq2f38xy6t5wvxqzjccqpjrzjq0yzeq76ney45hmjlnlpvu0nakzy2g35hqh0dujq8ujdpr2e42pf2rrs6vqpgcsqqqqqqqqqqqqqqeqqyg9qxpqysgqwftcx89k5pp28435pgxfl2vx3ksemzxccppw2j9yjn0ngr6ed7wj8ztc0d5kmt2mvzdlcgrludhz7jncd5l5l9w820hc4clpwhtqj3gq62g66n"
}
}
]
}
}
},
@@ -828,23 +735,6 @@
}
}
]
},
"sparkl2": {
"create_invoice_endpoint": [
{
"request_type": "json",
"request_body": {
"amount_sats": 555,
"memo": "Test Invoice",
"description_hash": null,
"expiry_seconds": null
},
"response_type": "json",
"response": {
"error": "Test Error"
}
}
]
}
}
},
@@ -955,21 +845,6 @@
}
}
]
},
"sparkl2": {
"create_invoice_endpoint": [
{
"request_type": "json",
"request_body": {
"amount_sats": 555,
"memo": "Test Invoice",
"description_hash": null,
"expiry_seconds": null
},
"response_type": "json",
"response": {}
}
]
}
}
},
@@ -1067,21 +942,6 @@
"response": "data-not-json"
}
]
},
"sparkl2": {
"create_invoice_endpoint": [
{
"request_type": "json",
"request_body": {
"amount_sats": 555,
"memo": "Test Invoice",
"description_hash": null,
"expiry_seconds": null
},
"response_type": "data",
"response": "data-not-json"
}
]
}
}
},
@@ -1197,24 +1057,6 @@
}
}
]
},
"sparkl2": {
"create_invoice_endpoint": [
{
"request_type": "json",
"request_body": {
"amount_sats": 555,
"memo": "Test Invoice",
"description_hash": null,
"expiry_seconds": null
},
"response_type": "response",
"response": {
"response": "Not Found",
"status": 404
}
}
]
}
}
},
@@ -1313,16 +1155,6 @@
},
"method": "POST"
}
},
"sparkl2": {
"pay_invoice_endpoint": {
"uri": "/v1/payments",
"headers": {
"X-Api-Key": "mock-spark-l2-api-key",
"User-Agent": "LNbits/Tests"
},
"method": "POST"
}
}
},
"tests": [
@@ -1477,24 +1309,6 @@
}
}
]
},
"sparkl2": {
"pay_invoice_endpoint": [
{
"request_type": "json",
"request_body": {
"bolt11": "lnbc210n1pjlgal5sp5xr3uwlfm7ltumdjyukhys0z2rw6grgm8me9k4w9vn05zt9svzzjspp5ud2jdfpaqn5c2k2vphatsjypfafyk8rcvkvwexnrhmwm94ex4jtqdqu24hxjapq23jhxapqf9h8vmmfvdjscqpjrzjqta942048v7qxh5x7pxwplhmtwfl0f25cq23jh87rhx7lgrwwvv86r90guqqnwgqqqqqqqqqqqqqqpsqyg9qxpqysgqylngsyg960lltngzy90e8n22v4j2hvjs4l4ttuy79qqefjv8q87q9ft7uhwdjakvnsgk44qyhalv6ust54x98whl3q635hkwgsyw8xgqjl7jwu",
"max_fee_sats": 25,
"payment_hash": "e35526a43d04e985594c0dfab848814f524b1c786598ec9a63beddb2d726ac96"
},
"response_type": "json",
"response": {
"status": "LIGHTNING_PAYMENT_SUCCEEDED",
"fee_msat": 30000,
"preimage": "0000000000000000000000000000000000000000000000000000000000000000"
}
}
]
}
}
},
@@ -1547,23 +1361,7 @@
"alby": {},
"eclair": [],
"lnbits": [],
"phoenixd": [],
"sparkl2": {
"pay_invoice_endpoint": [
{
"request_type": "json",
"request_body": {
"bolt11": "lnbc210n1pjlgal5sp5xr3uwlfm7ltumdjyukhys0z2rw6grgm8me9k4w9vn05zt9svzzjspp5ud2jdfpaqn5c2k2vphatsjypfafyk8rcvkvwexnrhmwm94ex4jtqdqu24hxjapq23jhxapqf9h8vmmfvdjscqpjrzjqta942048v7qxh5x7pxwplhmtwfl0f25cq23jh87rhx7lgrwwvv86r90guqqnwgqqqqqqqqqqqqqqpsqyg9qxpqysgqylngsyg960lltngzy90e8n22v4j2hvjs4l4ttuy79qqefjv8q87q9ft7uhwdjakvnsgk44qyhalv6ust54x98whl3q635hkwgsyw8xgqjl7jwu",
"max_fee_sats": 25,
"payment_hash": "e35526a43d04e985594c0dfab848814f524b1c786598ec9a63beddb2d726ac96"
},
"response_type": "json",
"response": {
"status": "LIGHTNING_PAYMENT_FAILED"
}
}
]
}
"phoenixd": []
}
},
{
@@ -1707,24 +1505,7 @@
}
],
"lnbits": [],
"phoenixd": [],
"sparkl2": {
"pay_invoice_endpoint": [
{
"request_type": "json",
"request_body": {
"bolt11": "lnbc210n1pjlgal5sp5xr3uwlfm7ltumdjyukhys0z2rw6grgm8me9k4w9vn05zt9svzzjspp5ud2jdfpaqn5c2k2vphatsjypfafyk8rcvkvwexnrhmwm94ex4jtqdqu24hxjapq23jhxapqf9h8vmmfvdjscqpjrzjqta942048v7qxh5x7pxwplhmtwfl0f25cq23jh87rhx7lgrwwvv86r90guqqnwgqqqqqqqqqqqqqqpsqyg9qxpqysgqylngsyg960lltngzy90e8n22v4j2hvjs4l4ttuy79qqefjv8q87q9ft7uhwdjakvnsgk44qyhalv6ust54x98whl3q635hkwgsyw8xgqjl7jwu",
"max_fee_sats": 25,
"payment_hash": "e35526a43d04e985594c0dfab848814f524b1c786598ec9a63beddb2d726ac96"
},
"response_type": "json",
"response": {
"status": "PAYMENT_PENDING",
"preimage": "0000000000000000000000000000000000000000000000000000000000000000"
}
}
]
}
"phoenixd": []
}
},
{
@@ -1817,22 +1598,6 @@
}
}
]
},
"sparkl2": {
"pay_invoice_endpoint": [
{
"request_type": "json",
"request_body": {
"bolt11": "lnbc210n1pjlgal5sp5xr3uwlfm7ltumdjyukhys0z2rw6grgm8me9k4w9vn05zt9svzzjspp5ud2jdfpaqn5c2k2vphatsjypfafyk8rcvkvwexnrhmwm94ex4jtqdqu24hxjapq23jhxapqf9h8vmmfvdjscqpjrzjqta942048v7qxh5x7pxwplhmtwfl0f25cq23jh87rhx7lgrwwvv86r90guqqnwgqqqqqqqqqqqqqqpsqyg9qxpqysgqylngsyg960lltngzy90e8n22v4j2hvjs4l4ttuy79qqefjv8q87q9ft7uhwdjakvnsgk44qyhalv6ust54x98whl3q635hkwgsyw8xgqjl7jwu",
"max_fee_sats": 25,
"payment_hash": "e35526a43d04e985594c0dfab848814f524b1c786598ec9a63beddb2d726ac96"
},
"response_type": "json",
"response": {
"error": "Test Error"
}
}
]
}
}
},
@@ -1930,20 +1695,6 @@
}
}
]
},
"sparkl2": {
"pay_invoice_endpoint": [
{
"request_type": "json",
"request_body": {
"bolt11": "lnbc210n1pjlgal5sp5xr3uwlfm7ltumdjyukhys0z2rw6grgm8me9k4w9vn05zt9svzzjspp5ud2jdfpaqn5c2k2vphatsjypfafyk8rcvkvwexnrhmwm94ex4jtqdqu24hxjapq23jhxapqf9h8vmmfvdjscqpjrzjqta942048v7qxh5x7pxwplhmtwfl0f25cq23jh87rhx7lgrwwvv86r90guqqnwgqqqqqqqqqqqqqqpsqyg9qxpqysgqylngsyg960lltngzy90e8n22v4j2hvjs4l4ttuy79qqefjv8q87q9ft7uhwdjakvnsgk44qyhalv6ust54x98whl3q635hkwgsyw8xgqjl7jwu",
"max_fee_sats": 25,
"payment_hash": "e35526a43d04e985594c0dfab848814f524b1c786598ec9a63beddb2d726ac96"
},
"response_type": "json",
"response": {}
}
]
}
}
},
@@ -2062,20 +1813,6 @@
"response": "data-not-json"
}
]
},
"sparkl2": {
"pay_invoice_endpoint": [
{
"request_type": "json",
"request_body": {
"bolt11": "lnbc210n1pjlgal5sp5xr3uwlfm7ltumdjyukhys0z2rw6grgm8me9k4w9vn05zt9svzzjspp5ud2jdfpaqn5c2k2vphatsjypfafyk8rcvkvwexnrhmwm94ex4jtqdqu24hxjapq23jhxapqf9h8vmmfvdjscqpjrzjqta942048v7qxh5x7pxwplhmtwfl0f25cq23jh87rhx7lgrwwvv86r90guqqnwgqqqqqqqqqqqqqqpsqyg9qxpqysgqylngsyg960lltngzy90e8n22v4j2hvjs4l4ttuy79qqefjv8q87q9ft7uhwdjakvnsgk44qyhalv6ust54x98whl3q635hkwgsyw8xgqjl7jwu",
"max_fee_sats": 25,
"payment_hash": "e35526a43d04e985594c0dfab848814f524b1c786598ec9a63beddb2d726ac96"
},
"response_type": "data",
"response": "data-not-json"
}
]
}
}
},
@@ -2206,23 +1943,6 @@
}
}
]
},
"sparkl2": {
"pay_invoice_endpoint": [
{
"request_type": "json",
"request_body": {
"bolt11": "lnbc210n1pjlgal5sp5xr3uwlfm7ltumdjyukhys0z2rw6grgm8me9k4w9vn05zt9svzzjspp5ud2jdfpaqn5c2k2vphatsjypfafyk8rcvkvwexnrhmwm94ex4jtqdqu24hxjapq23jhxapqf9h8vmmfvdjscqpjrzjqta942048v7qxh5x7pxwplhmtwfl0f25cq23jh87rhx7lgrwwvv86r90guqqnwgqqqqqqqqqqqqqqpsqyg9qxpqysgqylngsyg960lltngzy90e8n22v4j2hvjs4l4ttuy79qqefjv8q87q9ft7uhwdjakvnsgk44qyhalv6ust54x98whl3q635hkwgsyw8xgqjl7jwu",
"max_fee_sats": 25,
"payment_hash": "e35526a43d04e985594c0dfab848814f524b1c786598ec9a63beddb2d726ac96"
},
"response_type": "response",
"response": {
"response": "Not Found",
"status": 404
}
}
]
}
}
},
@@ -2310,16 +2030,6 @@
},
"method": "GET"
}
},
"sparkl2": {
"get_invoice_status_endpoint": {
"uri": "/v1/invoices/e35526a43d04e985594c0dfab848814f524b1c786598ec9a63beddb2d726ac96",
"headers": {
"X-Api-Key": "mock-spark-l2-api-key",
"User-Agent": "LNbits/Tests"
},
"method": "GET"
}
}
},
"tests": [
@@ -2415,24 +2125,6 @@
}
}
]
},
"sparkl2": {
"get_invoice_status_endpoint": [
{
"description": "LIGHTNING_PAYMENT_RECEIVED",
"response_type": "json",
"response": {
"status": "LIGHTNING_PAYMENT_RECEIVED"
}
},
{
"description": "TRANSFER_COMPLETED",
"response_type": "json",
"response": {
"status": "TRANSFER_COMPLETED"
}
}
]
}
}
},
@@ -2501,8 +2193,7 @@
}
}
]
},
"sparkl2": {}
}
}
},
{
@@ -2709,35 +2400,6 @@
"response": "data-not-json"
}
]
},
"sparkl2": {
"get_invoice_status_endpoint": [
{
"description": "no data",
"response_type": "json",
"response": {}
},
{
"description": "pending status",
"response_type": "json",
"response": {
"status": "PAYMENT_PENDING"
}
},
{
"description": "bad json",
"response_type": "data",
"response": "data-not-json"
},
{
"description": "http 404",
"response_type": "response",
"response": {
"response": "Not Found",
"status": 404
}
}
]
}
}
},
@@ -2820,16 +2482,6 @@
},
"method": "GET"
}
},
"sparkl2": {
"get_payment_status_endpoint": {
"uri": "/v1/payments/e35526a43d04e985594c0dfab848814f524b1c786598ec9a63beddb2d726ac96",
"headers": {
"X-Api-Key": "mock-spark-l2-api-key",
"User-Agent": "LNbits/Tests"
},
"method": "GET"
}
}
},
"tests": [
@@ -2935,28 +2587,6 @@
}
}
]
},
"sparkl2": {
"get_payment_status_endpoint": [
{
"description": "LIGHTNING_PAYMENT_SUCCEEDED",
"response_type": "json",
"response": {
"status": "LIGHTNING_PAYMENT_SUCCEEDED",
"fee_msat": 1000,
"preimage": "0000000000000000000000000000000000000000000000000000000000000000"
}
},
{
"description": "TRANSFER_COMPLETED",
"response_type": "json",
"response": {
"status": "TRANSFER_COMPLETED",
"fee_msat": 1000,
"preimage": "0000000000000000000000000000000000000000000000000000000000000000"
}
}
]
}
}
},
@@ -3045,8 +2675,7 @@
}
}
]
},
"sparkl2": {}
}
}
},
{
@@ -3304,35 +2933,6 @@
"response": "data-not-json"
}
]
},
"sparkl2": {
"get_payment_status_endpoint": [
{
"description": "pending status",
"response_type": "json",
"response": {
"status": "PAYMENT_PENDING"
}
},
{
"description": "no data",
"response_type": "json",
"response": {}
},
{
"description": "bad json",
"response_type": "data",
"response": "data-not-json"
},
{
"description": "http 404",
"response_type": "response",
"response": {
"response": "Not Found",
"status": 404
}
}
]
}
}
},
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -40,7 +40,7 @@ def encrypt_content(priv_key, dest_pub_key, content):
def decrypt_content(priv_key, source_pub_key, content):
p = PublicKey(bytes.fromhex("02" + source_pub_key))
shared = p.multiply(bytes.fromhex(priv_key)).format()[1:]
encrypted_content_b64, iv_b64 = content.split("?iv=")
(encrypted_content_b64, iv_b64) = content.split("?iv=")
encrypted_content = base64.b64decode(encrypted_content_b64.encode("ascii"))
iv = base64.b64decode(iv_b64.encode("ascii"))
aes = AES.new(shared, AES.MODE_CBC, iv)
+8 -4
View File
@@ -136,10 +136,12 @@ def migrate_db(file: str, schema: str, exclude_tables: list[str] | None = None):
assert os.path.isfile(file), f"{file} does not exist!"
sqlite_cursor = get_sqlite_cursor(file)
tables = sqlite_cursor.execute("""
tables = sqlite_cursor.execute(
"""
SELECT name FROM sqlite_master
WHERE type='table' AND name not like 'sqlite?_%' escape '?'
""").fetchall()
"""
).fetchall()
for table in tables:
table_name = table[0]
@@ -182,9 +184,11 @@ def build_table_columns(file: str, schema: str, table_name: str):
sqlite_columns = sqlite_cursor.execute(
f"PRAGMA table_info({table_name})"
).fetchall()
pg_cursor.execute(f"""
pg_cursor.execute(
f"""
SELECT table_name, column_name, udt_name FROM information_schema.columns
WHERE table_schema = '{schema}'AND table_name = '{table_name}';""")
WHERE table_schema = '{schema}'AND table_name = '{table_name}';"""
)
pg_columns = pg_cursor.fetchall()
columns = []
Generated
+924 -1002
View File
File diff suppressed because it is too large Load Diff