What changed, and why it matters
This commit adds a new optional TOTP two-factor authentication feature to LNbits. It is a security-hardening feature, not a vulnerability fix or an introduced flaw. The code shows careful design: secrets are encrypted, recovery codes are hashed, replay attacks are prevented, brute-force attempts are rate-limited, and audit logs exclude credentials. There is no evidence in the commit of a security bug.
No security action required. Treat as a normal feature review; consider verifying test coverage for the new 2FA flows and ensuring the TOTP encryption key file permissions are documented and restricted.
Security signals we found
New defensive feature: TOTP two-factor authentication
AES-GCM encryption of TOTP secrets bound to user ID
SHA-256 hashed recovery codes
Rate-limited verification attempts (5 failures per 15-minute window)
Single-use TOTP code replay protection
HTTP-only challenge cookie with 5-minute expiry
Policy revision invalidation for session security
Audit middleware excludes authentication bodies
CLI-only 2FA reset requiring local access
Evidence from the diff
The patch introduces TOTP-based 2FA across the LNbits core: new settings, database column, encryption key management, enrollment/verification/recovery endpoints, middleware enforcement, and UI. Security-relevant implementation details observed directly in the diff include AES-GCM encryption of TOTP secrets with a per-installation key, SHA-256 hashing of recovery codes, 5-attempt/15-minute brute-force lockout, single-use code replay protection via last_step, short-lived challenge cookies, policy revision invalidation of sessions, exclusion of /api/v1/auth bodies from audit logs, and a CLI-only reset command requiring local server access. No vulnerability is present in the changed code based on the supplied materials.
Changed components
lnbits/core/services/two_factor.pylnbits/core/views/two_factor_api.pylnbits/core/views/auth_api.pylnbits/decorators.pylnbits/middleware.pylnbits/settings.pylnbits/core/models/users.pylnbits/core/crud/users.pylnbits/core/crud/settings.pylnbits/core/migrations.pylnbits/commands.pyInspect captured patch +2437 / −53
diff --git a/.env.example b/.env.example
index dfa5c8c..f49fd70 100644
--- a/.env.example
+++ b/.env.example
@@ -96,6 +96,11 @@ FORWARDED_ALLOW_IPS="*"
# !!!!! It is strongly recommended that you set your own strong random value !!!!
AUTH_SECRET_KEY=""
+# TOTP 2FA encryption key (separate from AUTH_SECRET_KEY).
+# If unset, loaded from or generated in <data_folder>/.lnbits_totp_key.
+# Optional override: uv run lnbits-cli two-factor generate-key
+TOTP_ENCRYPTION_KEY=""
+
# === Funding Source ===# How many times to retry connectiong to the Funding Source before defaulting to the VoidWallet
# FUNDING_SOURCE_MAX_RETRIES=4
diff --git a/docs/guide/two-factor-authentication.md b/docs/guide/two-factor-authentication.md
new file mode 100644
index 0000000..4f3b5f7
--- /dev/null
+++ b/docs/guide/two-factor-authentication.md
@@ -0,0 +1,92 @@
+# Two factor authentication
+
+LNbits supports Google Authenticator, Ente Auth, Aegis and other standard TOTP apps.
+No registration with an authenticator provider is needed. Codes have six digits and
+a 30-second period. Keep the server clock synchronized.
+
+## Operator setup
+
+1. Start LNbits. The TOTP encryption key is initialized automatically, following
+ the same process as `AUTH_SECRET_KEY`: use `TOTP_ENCRYPTION_KEY` when configured,
+ otherwise read `<data_folder>/.lnbits_totp_key`, or generate `uuid4().hex` and
+ save it there if the file is missing.
+2. Under **Settings → Access → Two Factor Auth**, enable 2FA and select **Authenticator app (TOTP)**.
+3. Under **Account → Two Factor Auth (2FA)**, enroll your authenticator and save the
+ ten recovery codes. Confirm that you have saved them.
+4. Optionally enable **Require 2FA for all users**. The acting admin must already have
+ an enrolled authenticator, saved recovery codes and recent verification.
+
+Generated keys have 32 hexadecimal characters. Existing 64-character hexadecimal
+keys remain supported. To provide an explicit environment override, generate one
+with `uv run lnbits-cli two-factor generate-key`, set `TOTP_ENCRYPTION_KEY`, and restart.
+Keep the key file with your data backups, or back up the configured override.
+Restoring enrolled accounts requires their original key. As with `AUTH_SECRET_KEY`,
+a missing file is recreated automatically; the replacement cannot decrypt secrets
+encrypted using the old key.
+
+`TwoFactorSettings` contains `lnbits_two_factor_enabled`,
+`lnbits_two_factor_methods` (currently only `totp`), and
+`lnbits_two_factor_mandatory`. The feature and mandatory policy default to off.
+`totp_encryption_key` is never part of editable or public settings.
+
+## Login and policy
+
+Enrollment activates only after a valid code is entered. Pending setup is not an
+active factor. Setup and login challenges expire after five minutes. Starting and
+confirming enrollment also require a recent first-factor login; log in again if asked.
+
+Password, Nostr, SSO, user-ID login, and password-reset login apply the local 2FA
+policy. The verification page is `/2fa`. User-ID login remains unavailable to admins.
+Direct `?usr=` access cannot bypass verification. Users subject to mandatory enrollment
+can only complete setup until verified; restricted login and account-creation responses
+expose no wallet keys.
+
+Sensitive account changes require recent verification using the existing
+`auth_credetials_update_threshold` (120 seconds by default). Verify a fresh code
+in your account's 2FA section before changing security settings. There is no separate
+remembered-device exception. Existing session expiry settings still apply.
+
+An accepted code cannot be reused, including simultaneous requests. Wait for the next
+code if one was just used for enrollment or login. Five failed attempts block further
+verification for the remainder of a 15-minute window. New challenges and server
+restarts do not reset the attempt counter.
+
+Global **OFF** stops requiring 2FA for everyone, including admins, even when mandatory
+enrollment was selected. Encrypted secrets, recovery codes and replay state remain.
+Global **ON** restores enforcement for existing sessions and new logins.
+
+## Recovery
+
+Use a recovery code instead of an authenticator code after the first login step.
+Each works once. Store them separately from your phone. Regenerating them invalidates
+the old set. Email is not an alternative verification method.
+
+An operator with access to the server and database can run:
+
+```sh
+uv run lnbits-cli two-factor reset USER_ID
+```
+
+The command asks for confirmation, clears that account's factor and recovery codes,
+and changes its security revision. With 2FA enabled, old sessions are rejected.
+The account must log in again; mandatory policy still requires enrollment. The command
+does not change passwords or global policy. No remote admin reset endpoint is provided.
+If the encryption key was lost, restore it before enrolling again.
+
+## Storage and integration boundaries
+
+Private JSON in `accounts.two_factor` is accessed by dedicated CRUD functions and
+excluded from ordinary `Account`, `User` and admin account responses. There is no
+`is_2fa_enabled` column. An authenticated account can obtain safe status from
+`/api/v1/auth/2fa/status`.
+
+Secrets are encrypted using AES-GCM and bound to the account ID. Recovery codes are
+hashed. A per-account service lock serializes code verification and updates within
+a single LNbits process. Login challenges use a separate HTTP-only cookie and cannot
+authenticate ordinary API requests.
+Authentication bodies are excluded from audit details; security logs contain no codes.
+
+Wallet API keys and scoped automation tokens continue to work. **Login 2FA does not
+stop spending with a stolen spending key.** Automation cannot configure 2FA or bypass
+protected security changes. Impersonation requires fresh admin MFA while enabled
+and cannot change the target account's security.
diff --git a/lnbits/app.py b/lnbits/app.py
index 8a910b6..fb20210 100644
--- a/lnbits/app.py
+++ b/lnbits/app.py
@@ -73,6 +73,7 @@ from .core import init_core_routers
from .core.db import core_app_extra
from .core.models.extensions import Extension, ExtensionMeta, InstallableExtension
from .core.services import check_admin_settings, check_webpush_settings
+from .core.services.two_factor import sync_two_factor_policy
from .middleware import (
AuditMiddleware,
ExtensionsRedirectMiddleware,
@@ -94,6 +95,7 @@ async def startup(app: FastAPI):
# setup admin settings
await check_admin_settings()
+ await sync_two_factor_policy()
core_app_extra.register_new_ratelimiter()
await check_webpush_settings()
diff --git a/lnbits/commands.py b/lnbits/commands.py
index 6070a00..fc26f5f 100644
--- a/lnbits/commands.py
+++ b/lnbits/commands.py
@@ -73,6 +73,33 @@ def users():
"""
+@lnbits_cli.group("two-factor")
+def two_factor():
+ """Manage TOTP encryption and recover accounts using local server access."""
+
+
+@two_factor.command("generate-key")
+def generate_totp_key():
+ """Generate an optional TOTP_ENCRYPTION_KEY override."""
+ click.echo(uuid4().hex)
+
+
+@two_factor.command("reset")
+@click.argument("user_id")
+@click.confirmation_option(
+ prompt="Reset this user's authenticator and invalidate their 2FA sessions?"
+)
+@coro
+async def reset_user_two_factor(user_id: str):
+ """Clear one account's enrollment. Mandatory policy still requires re-enrollment."""
+ from lnbits.core.services.two_factor import reset_two_factor
+
+ await reset_two_factor(user_id)
+ click.echo(
+ "Authenticator reset. The user must log in again and re-enroll if required."
+ )
+
+
@lnbits_cli.group()
def extensions():
"""
diff --git a/lnbits/core/__init__.py b/lnbits/core/__init__.py
index a0804cb..125d923 100644
--- a/lnbits/core/__init__.py
+++ b/lnbits/core/__init__.py
@@ -18,6 +18,7 @@ from .views.lnurl_api import lnurl_router
from .views.node_api import node_router, public_node_router, super_node_router
from .views.payment_api import payment_router
from .views.tinyurl_api import tinyurl_router
+from .views.two_factor_api import two_factor_router
from .views.user_api import users_router
from .views.wallet_api import wallet_router
from .views.webpush_api import webpush_router
@@ -30,6 +31,7 @@ core_app = APIRouter(tags=["Core"])
def init_core_routers(app: FastAPI):
app.include_router(core_app)
app.include_router(generic_router)
+ app.include_router(two_factor_router)
app.include_router(auth_router)
app.include_router(admin_router)
app.include_router(node_router)
diff --git a/lnbits/core/crud/settings.py b/lnbits/core/crud/settings.py
index 79eb415..359a88b 100644
--- a/lnbits/core/crud/settings.py
+++ b/lnbits/core/crud/settings.py
@@ -4,7 +4,7 @@ from typing import Any
from loguru import logger
from lnbits.core.db import db
-from lnbits.db import dict_to_model
+from lnbits.db import Connection, dict_to_model
from lnbits.settings import (
AdminSettings,
EditableSettings,
@@ -98,10 +98,10 @@ async def create_admin_settings(super_user: str, new_settings: dict) -> SuperSet
async def get_settings_field(
- id_: str, tag: str | None = "core"
+ id_: str, tag: str | None = "core", conn: Connection | None = None
) -> SettingsField | None:
- row: dict = await db.fetchone(
+ row: dict = await (conn or db).fetchone(
"""
SELECT * FROM system_settings
WHERE id = :id AND tag = :tag
@@ -142,3 +142,8 @@ async def get_settings_by_tag(tag: str) -> dict[str, Any] | None:
)
data.pop("super_user")
return data
+
+
+async def get_two_factor_policy_revision(conn: Connection | None = None) -> str:
+ field = await get_settings_field("two_factor_revision", "security", conn=conn)
+ return field.value if field and field.value else ""
diff --git a/lnbits/core/crud/users.py b/lnbits/core/crud/users.py
index dd6f8d3..b4cfd04 100644
--- a/lnbits/core/crud/users.py
+++ b/lnbits/core/crud/users.py
@@ -12,6 +12,7 @@ from lnbits.core.crud.wallets import (
)
from lnbits.core.db import db
from lnbits.core.models import UserAcls
+from lnbits.core.models.users import TwoFactorConfig
from lnbits.db import Connection, Filters, Page
from lnbits.helpers import sha256s
from lnbits.settings import settings
@@ -299,3 +300,22 @@ def clear_user_cache(user: User):
cache.pop(user_cache_key)
for wallet in user.wallets:
clear_wallet_cache(wallet)
+
+
+async def get_two_factor_config(
+ user_id: str, conn: Connection | None = None
+) -> TwoFactorConfig:
+ row: dict | None = await (conn or db).fetchone(
+ "SELECT two_factor FROM accounts WHERE id = :id", {"id": user_id}
+ )
+ if not row:
+ raise ValueError("Account not found.")
+ raw = row["two_factor"]
+ return TwoFactorConfig.parse_raw(raw) if raw else TwoFactorConfig()
+
+
+async def save_two_factor_config(user_id: str, config: TwoFactorConfig) -> None:
+ await db.execute(
+ "UPDATE accounts SET two_factor = :value WHERE id = :id",
+ {"id": user_id, "value": config.json()},
+ )
diff --git a/lnbits/core/migrations.py b/lnbits/core/migrations.py
index 8796f2e..ea342db 100644
--- a/lnbits/core/migrations.py
+++ b/lnbits/core/migrations.py
@@ -902,3 +902,7 @@ async def m050_add_lightning_address_to_wallets(db: Connection):
CREATE UNIQUE INDEX IF NOT EXISTS idx_wallets_lightning_address
ON wallets (lightning_address);
""")
+
+
+async def m051_add_two_factor_to_accounts(db: Connection):
+ await db.execute("ALTER TABLE accounts ADD COLUMN two_factor TEXT")
diff --git a/lnbits/core/models/users.py b/lnbits/core/models/users.py
index 49bcf71..1419405 100644
--- a/lnbits/core/models/users.py
+++ b/lnbits/core/models/users.py
@@ -381,6 +381,12 @@ class AccessTokenPayload(BaseModel):
email: str | None = None
auth_time: int | None = 0
api_token_id: str | None = None
+ purpose: str = "session"
+ jti: str | None = None
+ mfa_revision: str = ""
+ mfa_policy: str = ""
+ mfa_time: int = 0
+ impersonated_by: str | None = None
class UpdateBalance(BaseModel):
@@ -421,3 +427,32 @@ class DeleteTokenRequest(BaseModel):
id: str
acl_id: str
password: str
+
+
+class TwoFactorConfig(BaseModel):
+ """Private persistence model; never embed in Account or User responses."""
+
+ secret: str | None = None
+ pending_secret: str | None = None
+ pending_until: int = 0
+ revision: str = ""
+ last_step: int = -1
+ recovery_hashes: list[str] = []
+ recovery_saved: bool = False
+ failures: int = 0
+ failure_window: int = 0
+ challenges: dict[str, int] = {}
+
+
+class TwoFactorCode(BaseModel):
+ code: str = Field(min_length=6, max_length=64)
+
+
+class TwoFactorStatus(BaseModel):
+ available: bool
+ enrolled: bool
+ mandatory: bool
+ challenge: bool
+ recovery_remaining: int
+ recovery_saved: bool
+ verification_required: bool
diff --git a/lnbits/core/services/two_factor.py b/lnbits/core/services/two_factor.py
new file mode 100644
index 0000000..d2d0e9e
--- /dev/null
+++ b/lnbits/core/services/two_factor.py
@@ -0,0 +1,415 @@
+import asyncio
+import base64
+import json
+import secrets
+from hashlib import sha256
+from http import HTTPStatus
+from time import time
+
+from cryptography.exceptions import InvalidTag
+from cryptography.hazmat.primitives.ciphers.aead import AESGCM
+from cryptography.hazmat.primitives.hashes import SHA1
+from cryptography.hazmat.primitives.twofactor.totp import TOTP
+from fastapi import HTTPException
+from loguru import logger
+
+from lnbits.core.crud.settings import (
+ get_settings_field,
+ get_two_factor_policy_revision,
+ set_settings_field,
+)
+from lnbits.core.crud.users import (
+ get_two_factor_config,
+ save_two_factor_config,
+)
+from lnbits.core.models.users import AccessTokenPayload, TwoFactorConfig
+from lnbits.db import Connection
+from lnbits.settings import UpdateSettings, settings
+
+CHALLENGE_SECONDS = 300
+FAILURE_WINDOW = 900
+FAILURE_LIMIT = 5
+_two_factor_locks: dict[str, asyncio.Lock] = {}
+
+
+def two_factor_error(message: str = "Two factor verification required."):
+ return HTTPException(
+ HTTPStatus.UNAUTHORIZED, message, headers={"two-factor-required": "true"}
+ )
+
+
+def encryption_key() -> bytes:
+ try:
+ key = bytes.fromhex(settings.totp_encryption_key)
+ if len(key) in (16, 32):
+ return key
+ except ValueError:
+ pass
+ raise HTTPException(
+ HTTPStatus.SERVICE_UNAVAILABLE,
+ "Two factor authentication requires a valid TOTP_ENCRYPTION_KEY.",
+ )
+
+
+def encrypt_totp_secret(user_id: str, secret: bytes) -> str:
+ nonce = secrets.token_bytes(12)
+ encrypted = AESGCM(encryption_key()).encrypt(nonce, secret, user_id.encode())
+ return base64.urlsafe_b64encode(nonce + encrypted).decode()
+
+
+def decrypt_totp_secret(user_id: str, encrypted: str) -> bytes:
+ key = encryption_key()
+ try:
+ data = base64.urlsafe_b64decode(encrypted)
+ return AESGCM(key).decrypt(data[:12], data[12:], user_id.encode())
+ except (InvalidTag, ValueError) as exc:
+ raise HTTPException(
+ HTTPStatus.SERVICE_UNAVAILABLE,
+ "Unable to unlock the authenticator. Contact the operator.",
+ ) from exc
+
+
+def totp(secret: bytes) -> TOTP:
+ # HMAC-SHA1 is the interoperable RFC 6238 default, not a password hash.
+ return TOTP(secret, 6, SHA1(), 30) # noqa: S303
+
+
+def code_step(secret: bytes, code: str, now: int, last_step: int) -> int | None:
+ if len(code) != 6 or not code.isascii() or not code.isdigit():
+ return None
+ current_step = now // 30
+ for step in (current_step, current_step - 1, current_step + 1):
+ if step > last_step and secrets.compare_digest(
+ totp(secret).generate(step * 30), code.encode()
+ ):
+ return step
+ return None
+
+
+def validate_identity(config: TwoFactorConfig, payload: AccessTokenPayload) -> None:
+ if payload.api_token_id or payload.impersonated_by:
+ raise HTTPException(HTTPStatus.FORBIDDEN, "Use your own interactive login.")
+ if payload.mfa_revision != config.revision:
+ raise two_factor_error("Account security changed. Please log in again.")
+ if payload.purpose == "two_factor":
+ if not payload.jti or config.challenges.get(payload.jti, 0) <= time():
+ raise two_factor_error("Verification expired. Please log in again.")
+ elif payload.purpose != "session":
+ raise two_factor_error()
+
+
+def require_recent_login(payload: AccessTokenPayload) -> None:
+ if time() - (payload.auth_time or 0) > settings.auth_credetials_update_threshold:
+ raise HTTPException(
+ HTTPStatus.UNAUTHORIZED,
+ "Please log in again before changing account security.",
+ headers={"token-expired": "true"},
+ )
+
+
+async def issue_challenge(user_id: str) -> AccessTokenPayload:
+ challenge_id = secrets.token_hex(24)
+ now = int(time())
+
+ async with _two_factor_lock(user_id):
+ config = await get_two_factor_config(user_id)
+ config.challenges = {
+ key: expires for key, expires in config.challenges.items() if expires > now
+ }
+ # Bound storage without resetting the persistent account attempt counter.
+ config.challenges = dict(list(config.challenges.items())[-4:])
+ config.challenges[challenge_id] = now + CHALLENGE_SECONDS
+ await save_two_factor_config(user_id, config)
+
+ return AccessTokenPayload(
+ sub="",
+ usr=user_id,
+ auth_time=now,
+ purpose="two_factor",
+ jti=challenge_id,
+ mfa_revision=config.revision,
+ )
+
+
+async def begin_enrollment(user_id: str, payload: AccessTokenPayload) -> bytes:
+ if not settings.lnbits_two_factor_enabled:
+ raise HTTPException(
+ HTTPStatus.FORBIDDEN, "Two factor authentication is disabled."
+ )
+ require_recent_login(payload)
+ secret = secrets.token_bytes(20)
+ encrypted = encrypt_totp_secret(user_id, secret)
+
+ async with _two_factor_lock(user_id):
+ config = await get_two_factor_config(user_id)
+ validate_identity(config, payload)
+ if config.secret:
+ raise HTTPException(
+ HTTPStatus.CONFLICT, "An authenticator is already enrolled."
+ )
+ config.pending_secret = encrypted
+ config.pending_until = int(time()) + CHALLENGE_SECONDS
+ await save_two_factor_config(user_id, config)
+
+ return secret
+
+
+def new_recovery_codes(config: TwoFactorConfig) -> list[str]:
+ codes = [secrets.token_hex(10) for _ in range(10)]
+ config.recovery_hashes = [sha256(code.encode()).hexdigest() for code in codes]
+ config.recovery_saved = False
+ return codes
+
+
+async def verify_factor(
+ user_id: str, payload: AccessTokenPayload, code: str, enrolling: bool = False
+) -> tuple[TwoFactorConfig, list[str]]:
+ now = int(time())
+
+ async with _two_factor_lock(user_id):
+ config = await get_two_factor_config(user_id)
+ validate_identity(config, payload)
+ _record_attempt(config, now)
+ encrypted = config.pending_secret if enrolling else config.secret
+ if not encrypted or (
+ enrolling and (config.secret or config.pending_until < now)
+ ):
+ await save_two_factor_config(user_id, config)
+ raise HTTPException(
+ HTTPStatus.UNAUTHORIZED, "Invalid or already used code."
+ )
+ recovery_hash = sha256(code.strip().lower().encode()).hexdigest()
+ recovery = not enrolling and recovery_hash in config.recovery_hashes
+ if recovery:
+ config.recovery_hashes.remove(recovery_hash)
+ else:
+ step = code_step(
+ decrypt_totp_secret(user_id, encrypted), code, now, config.last_step
+ )
+ if step is None:
+ await save_two_factor_config(user_id, config)
+ raise HTTPException(
+ HTTPStatus.UNAUTHORIZED, "Invalid or already used code."
+ )
+ config.last_step = step
+ codes: list[str] = []
+ if enrolling:
+ config.secret = config.pending_secret
+ config.pending_secret = None
+ config.pending_until = 0
+ config.revision = secrets.token_hex(16)
+ config.challenges = {}
+ codes = new_recovery_codes(config)
+ elif payload.jti:
+ config.challenges.pop(payload.jti, None)
+ config.failures = 0
+ config.failure_window = 0
+ await save_two_factor_config(user_id, config)
+
+ logger.info(
+ "Two factor {} for account {}", "enrolled" if enrolling else "verified", user_id
+ )
+ return config, codes
+
+
+async def acknowledge_recovery_codes(user_id: str, payload: AccessTokenPayload) -> None:
+ async with _two_factor_lock(user_id):
+ config = await get_two_factor_config(user_id)
+ validate_identity(config, payload)
+ config.recovery_saved = True
+ await save_two_factor_config(user_id, config)
+
+
+async def regenerate_recovery_codes(
+ user_id: str, payload: AccessTokenPayload
+) -> list[str]:
+ async with _two_factor_lock(user_id):
+ config = await get_two_factor_config(user_id)
+ validate_identity(config, payload)
+ if not config.secret:
+ raise HTTPException(HTTPStatus.BAD_REQUEST, "No authenticator enrolled.")
+ codes = new_recovery_codes(config)
+ await save_two_factor_config(user_id, config)
+ return codes
+
+
+async def disable_two_factor(
+ user_id: str, payload: AccessTokenPayload
+) -> TwoFactorConfig:
+ if settings.lnbits_two_factor_enabled and settings.lnbits_two_factor_mandatory:
+ raise HTTPException(
+ HTTPStatus.FORBIDDEN, "Two factor authentication is mandatory."
+ )
+ async with _two_factor_lock(user_id):
+ config = await get_two_factor_config(user_id)
+ validate_identity(config, payload)
+ config = TwoFactorConfig(revision=secrets.token_hex(16))
+ await save_two_factor_config(user_id, config)
+ logger.info("Two factor disabled for account {} at {}", user_id, int(time()))
+ return config
+
+
+async def session_payload(
+ user_id: str, config: TwoFactorConfig, verified: bool = False
+) -> AccessTokenPayload:
+ return AccessTokenPayload(
+ sub="",
+ usr=user_id,
+ auth_time=int(time()),
+ mfa_revision=config.revision,
+ mfa_time=int(time()) if verified else 0,
+ mfa_policy=await get_two_factor_policy_revision(),
+ )
+
+
+async def sync_two_factor_policy() -> str:
+ """Invalidate old MFA claims when policy changes, including via environment."""
+ fingerprint = json.dumps(
+ [
+ settings.lnbits_two_factor_enabled,
+ sorted(settings.lnbits_two_factor_methods),
+ settings.lnbits_two_factor_mandatory,
+ ]
+ )
+ previous = await get_settings_field("two_factor_policy", "security")
+ if previous and previous.value == fingerprint:
+ return await get_two_factor_policy_revision()
+ revision = secrets.token_hex(16)
+ await set_settings_field("two_factor_revision", revision, "security")
+ await set_settings_field("two_factor_policy", fingerprint, "security")
+ return revision
+
+
+def security_operation(path: str, method: str) -> bool:
+ if path.rstrip("/") == "/api/v1/auth/impersonate" and method == "DELETE":
+ return False
+ if method == "GET" and (
+ path
+ in {
+ "/api/v1/auth/google",
+ "/api/v1/auth/github",
+ "/api/v1/auth/keycloak",
+ "/api/v1/auth/oidc",
+ }
+ or path.endswith("/reset_password")
+ ):
+ return True
+ if method in {"GET", "HEAD", "OPTIONS"}:
+ return False
+ return path.rstrip("/") == "/api/v1/auth" or path.startswith(
+ (
+ "/api/v1/auth/password",
+ "/api/v1/auth/pubkey",
+ "/api/v1/auth/acl",
+ "/api/v1/auth/impersonate",
+ "/api/v1/auth/2fa",
+ "/admin/api/v1/settings",
+ "/users/api/v1/user",
+ )
+ )
+
+
+async def check_two_factor_session(
+ user_id: str,
+ payload: AccessTokenPayload | None,
+ path: str,
+ method: str,
+ conn: Connection | None = None,
+) -> None:
+ sensitive = security_operation(path, method)
+ if payload and payload.purpose != "session":
+ raise two_factor_error()
+ if payload and payload.api_token_id:
+ if sensitive and (settings.lnbits_two_factor_enabled or "/2fa" in path):
+ raise HTTPException(
+ HTTPStatus.FORBIDDEN, "Interactive authentication required."
+ )
+ return
+ actor = payload.impersonated_by if payload else None
+ if actor and (sensitive or not settings.is_admin_user(actor)):
+ raise HTTPException(
+ HTTPStatus.FORBIDDEN, "Impersonation cannot change account security."
+ )
+ if not settings.lnbits_two_factor_enabled and not (
+ payload and payload.mfa_revision
+ ):
+ return
+ config = await get_two_factor_config(actor or user_id, conn)
+ if payload and config.revision != payload.mfa_revision:
+ raise two_factor_error("Account security changed. Please log in again.")
+ required = (
+ bool(config.secret)
+ or settings.lnbits_two_factor_mandatory
+ or (path.rstrip("/") == "/api/v1/auth/impersonate" and method == "POST")
+ )
+ if not settings.lnbits_two_factor_enabled or not required:
+ return
+ if (
+ not payload
+ or not config.secret
+ or not payload.mfa_time
+ or payload.mfa_policy != await get_two_factor_policy_revision(conn)
+ ):
+ raise two_factor_error()
+ if (
+ sensitive
+ and time() - payload.mfa_time > settings.auth_credetials_update_threshold
+ ):
+ raise two_factor_error("Fresh two factor verification required.")
+
+
+async def reset_two_factor(user_id: str) -> None:
+ async with _two_factor_lock(user_id):
+ await get_two_factor_config(user_id)
+ config = TwoFactorConfig(revision=secrets.token_hex(16))
+ await save_two_factor_config(user_id, config)
+ logger.warning("Two factor reset locally for account {}", user_id)
+
+
+async def validate_two_factor_policy(
+ data: UpdateSettings, account_id: str, payload: AccessTokenPayload
+) -> bool:
+ fields = (
+ "lnbits_two_factor_enabled",
+ "lnbits_two_factor_methods",
+ "lnbits_two_factor_mandatory",
+ )
+ if not any(getattr(data, field) != getattr(settings, field) for field in fields):
+ return False
+ require_recent_login(payload)
+ if payload.api_token_id or payload.impersonated_by:
+ raise HTTPException(HTTPStatus.FORBIDDEN, "Use your own interactive login.")
+ if data.lnbits_two_factor_enabled:
+ encryption_key()
+ if "totp" not in data.lnbits_two_factor_methods:
+ raise HTTPException(
+ HTTPStatus.BAD_REQUEST, "Select at least one two factor method."
+ )
+ if data.lnbits_two_factor_mandatory:
+ config = await get_two_factor_config(account_id)
+ if not config.secret or not config.recovery_saved:
+ raise HTTPException(
+ HTTPStatus.BAD_REQUEST,
+ "Enroll your authenticator and save recovery codes "
+ "before requiring 2FA.",
+ )
+ if time() - payload.mfa_time > settings.auth_credetials_update_threshold:
+ raise two_factor_error(
+ "Verify your authenticator before requiring 2FA."
+ )
+ return True
+
+
+def _record_attempt(config: TwoFactorConfig, now: int) -> None:
+ if now >= config.failure_window + FAILURE_WINDOW:
+ config.failures = 0
+ config.failure_window = now
+ if config.failures >= FAILURE_LIMIT:
+ raise HTTPException(
+ HTTPStatus.TOO_MANY_REQUESTS, "Too many codes. Try again later."
+ )
+ config.failures += 1
+
+
+def _two_factor_lock(user_id: str) -> asyncio.Lock:
+ return _two_factor_locks.setdefault(user_id, asyncio.Lock())
diff --git a/lnbits/core/views/admin_api.py b/lnbits/core/views/admin_api.py
index 2d269f9..07eca22 100644
--- a/lnbits/core/views/admin_api.py
+++ b/lnbits/core/views/admin_api.py
@@ -6,13 +6,13 @@ from shutil import make_archive
from subprocess import Popen
from typing import cast
-from fastapi import APIRouter, Depends, File
+from fastapi import APIRouter, Depends, File, HTTPException
from fastapi.responses import FileResponse
from sqlalchemy.engine import URL, make_url
from sqlalchemy.exc import ArgumentError
from lnbits.core.models.notifications import NotificationType
-from lnbits.core.models.users import Account
+from lnbits.core.models.users import AccessTokenPayload, Account
from lnbits.core.services import (
enqueue_admin_notification,
get_balance_delta,
@@ -20,7 +20,11 @@ from lnbits.core.services import (
)
from lnbits.core.services.notifications import send_email_notification
from lnbits.core.services.settings import dict_to_settings
-from lnbits.decorators import check_admin, check_super_user
+from lnbits.core.services.two_factor import (
+ sync_two_factor_policy,
+ validate_two_factor_policy,
+)
+from lnbits.decorators import access_token_payload, check_admin, check_super_user
from lnbits.server import server_restart
from lnbits.settings import AdminSettings, Settings, UpdateSettings, settings
from lnbits.task_manager import PublicTask, task_manager
@@ -80,8 +84,11 @@ async def api_get_settings(
status_code=HTTPStatus.OK,
)
async def api_update_settings(
- data: UpdateSettings, account: Account = Depends(check_admin)
+ data: UpdateSettings,
+ account: Account = Depends(check_admin),
+ payload: AccessTokenPayload = Depends(access_token_payload),
):
+ policy_changed = await validate_two_factor_policy(data, account.id, payload)
enqueue_admin_notification(
NotificationType.settings_update, {"username": account.username}
)
@@ -91,6 +98,16 @@ async def api_update_settings(
raise ValueError("Updated admin settings not found.")
update_cached_settings(admin_settings.dict())
core_app_extra.register_new_ratelimiter()
+ if policy_changed:
+ from lnbits.core.views.auth_api import _auth_success_response
+
+ policy_revision = await sync_two_factor_policy()
+ # Preserve the acting admin's fresh verification; all other sessions
+ # must satisfy the new policy on their next protected request.
+ response = _auth_success_response(
+ payload=payload.copy(update={"mfa_policy": policy_revision})
+ )
+ return response
return {"status": "Success"}
@@ -99,10 +116,12 @@ async def api_update_settings(
status_code=HTTPStatus.OK,
)
async def api_update_settings_partial(
- data: dict, account: Account = Depends(check_admin)
+ data: dict,
+ account: Account = Depends(check_admin),
+ payload: AccessTokenPayload = Depends(access_token_payload),
):
updatable_settings = dict_to_settings({**settings.dict(), **data})
- return await api_update_settings(updatable_settings, account)
+ return await api_update_settings(updatable_settings, account, payload)
@admin_router.get(
@@ -111,6 +130,10 @@ async def api_update_settings_partial(
dependencies=[Depends(check_admin)],
)
async def api_reset_settings(field_name: str):
+ if field_name not in UpdateSettings.__fields__:
+ raise HTTPException(
+ HTTPStatus.FORBIDDEN, "Only editable settings have public defaults."
+ )
default_settings = Settings()
return {"default_value": getattr(default_settings, field_name)}
diff --git a/lnbits/core/views/api.py b/lnbits/core/views/api.py
index 2975618..8c94b28 100644
--- a/lnbits/core/views/api.py
+++ b/lnbits/core/views/api.py
@@ -79,9 +79,16 @@ async def api_wallets(
return [wallet.copy_with_keys(keep=can_write) for wallet in user.wallets]
-@api_router.post("/api/v1/account")
-async def api_create_account(data: CreateWallet) -> Wallet:
+@api_router.post("/api/v1/account", response_model=None)
+async def api_create_account(data: CreateWallet):
user = await create_user_account(wallet_name=data.name)
+ if settings.lnbits_two_factor_enabled and settings.lnbits_two_factor_mandatory:
+ from lnbits.core.crud.users import get_account
+ from lnbits.core.views.auth_api import _login_response
+
+ account = await get_account(user.id)
+ assert account
+ return await _login_response(account)
return user.wallets[0]
diff --git a/lnbits/core/views/auth_api.py b/lnbits/core/views/auth_api.py
index 8e11453..12e6c29 100644
--- a/lnbits/core/views/auth_api.py
+++ b/lnbits/core/views/auth_api.py
@@ -8,6 +8,7 @@ from time import time
from typing import Annotated
from uuid import uuid4
+import jwt
from fastapi import APIRouter, Cookie, Depends, HTTPException, Request
from fastapi.responses import JSONResponse, RedirectResponse
from fastapi_sso.sso.base import OpenID, SSOBase
@@ -15,6 +16,7 @@ from loguru import logger
from lnbits.core.crud.settings import set_settings_field
from lnbits.core.crud.users import (
+ get_two_factor_config,
get_user_access_control_lists,
update_user_access_control_list,
)
@@ -28,6 +30,7 @@ from lnbits.core.models.users import (
UpdateAccessControlList,
)
from lnbits.core.services import create_user_account
+from lnbits.core.services.two_factor import issue_challenge, session_payload
from lnbits.core.services.users import (
check_register_activation_settings,
update_user_account,
@@ -153,7 +156,7 @@ async def login(data: LoginUsernamePassword) -> JSONResponse:
raise HTTPException(HTTPStatus.UNAUTHORIZED, "Invalid credentials.")
cache.pop(throttle_key)
- return _auth_success_response(account.username, account.id, account.email)
+ return await _login_response(account)
@auth_router.post("/nostr", description="Login via Nostr")
@@ -171,7 +174,7 @@ async def nostr_login(request: Request) -> JSONResponse:
await create_user_account(account)
if not account.activated:
raise HTTPException(HTTPStatus.UNAUTHORIZED, "User is not activated.")
- return _auth_success_response(account.username or "", account.id, account.email)
+ return await _login_response(account)
@auth_router.post("/usr", description="Login via the User ID")
@@ -188,7 +191,7 @@ async def login_usr(data: LoginUsr) -> JSONResponse:
raise HTTPException(
HTTPStatus.FORBIDDEN, "Admin users cannot login with user id only."
)
- return _auth_success_response(account.username, account.id, account.email)
+ return await _login_response(account)
@auth_router.post("/impersonate", description="Login via the User ID of another user")
@@ -213,7 +216,18 @@ async def impersonate_user(
if not account:
raise HTTPException(HTTPStatus.UNAUTHORIZED, "User ID does not exist.")
- response = _auth_success_response(account.username, account.id, account.email)
+ admin_payload = AccessTokenPayload(
+ **jwt.decode(cookie_access_token, settings.auth_secret_key, ["HS256"])
+ )
+ impersonation = admin_payload.copy(
+ update={
+ "sub": "",
+ "usr": account.id,
+ "email": None,
+ "impersonated_by": user.id,
+ }
+ )
+ response = _auth_success_response(payload=impersonation)
max_age = settings.auth_token_expire_minutes * 60
response.set_cookie(
@@ -431,6 +445,7 @@ async def handle_oauth_token(request: Request, provider: str) -> RedirectRespons
async def logout() -> JSONResponse:
response = JSONResponse({"status": "success"}, HTTPStatus.OK)
response.delete_cookie("cookie_access_token")
+ response.delete_cookie("two_factor_challenge")
response.delete_cookie("is_lnbits_user_authorized")
response.delete_cookie("is_access_token_expired")
response.delete_cookie("lnbits_last_active_wallet")
@@ -469,7 +484,7 @@ async def register(data: RegisterUser) -> JSONResponse:
)
account.hash_password(data.password)
await create_user_account(account)
- return _auth_success_response(account.username, account.id, account.email)
+ return await _login_response(account)
@auth_router.put("/pubkey")
@@ -564,7 +579,7 @@ async def reset_password(data: ResetUserPassword) -> JSONResponse:
account.hash_password(data.password)
await update_account(account)
- return _auth_success_response(account.username, user_id, account.email)
+ return await _login_response(account)
@auth_router.patch("")
@@ -636,7 +651,7 @@ async def first_install(data: UpdateSuperuserPassword) -> JSONResponse:
await set_settings_field(
"first_install_token_confirmed", data.first_install_token
)
- return _auth_success_response(account.username, account.id, account.email)
+ return await _login_response(account)
async def _handle_sso_login(userinfo: OpenID, verified_user_id: str | None = None):
@@ -664,20 +679,39 @@ 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)
+ login_response = await _login_response(account)
+ response = RedirectResponse(
+ (
+ "/2fa"
+ if "two_factor_required" in json.loads(bytes(login_response.body))
+ else redirect_path
+ ),
+ headers={"Cache-Control": "no-store"},
+ )
+ response.raw_headers.extend(
+ (key, value)
+ for key, value in login_response.raw_headers
+ if key == b"set-cookie"
+ )
+ return response
def _auth_success_response(
username: str | None = None,
user_id: str | None = None,
email: str | None = None,
+ payload: AccessTokenPayload | None = None,
+ recovery_codes: list[str] | None = None,
) -> JSONResponse:
- payload = AccessTokenPayload(
+ payload = payload or AccessTokenPayload(
sub=username or "", usr=user_id, email=email, auth_time=int(time())
)
access_token = create_access_token(data=payload.dict())
max_age = settings.auth_token_expire_minutes * 60
- response = JSONResponse({"access_token": access_token, "token_type": "bearer"})
+ body: dict = {"access_token": access_token, "token_type": "bearer"}
+ if recovery_codes is not None:
+ body["recovery_codes"] = recovery_codes
+ response = JSONResponse(body, headers={"Cache-Control": "no-store"})
response.set_cookie(
"cookie_access_token",
access_token,
@@ -709,32 +743,6 @@ 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())
- )
- 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,
- )
- response.delete_cookie("is_access_token_expired")
- return response
-
-
def _new_sso(provider: str) -> SSOBase | None:
try:
if not settings.is_auth_method_allowed(AuthMethods(f"{provider}-auth")):
@@ -838,3 +846,36 @@ def _validate_auth_timeout(auth_time: int | None = 0):
f" {settings.auth_credetials_update_threshold} seconds."
" Please login again or ask a new reset key!",
)
+
+
+async def _login_response(account: Account) -> JSONResponse:
+ config = await get_two_factor_config(account.id)
+ if settings.lnbits_two_factor_enabled and (
+ config.secret or settings.lnbits_two_factor_mandatory
+ ):
+ payload = await issue_challenge(account.id)
+ token = create_access_token(payload.dict(), token_expire_minutes=5)
+ response = JSONResponse(
+ {
+ "two_factor_required": True,
+ "enrollment_required": not bool(config.secret),
+ },
+ headers={"Cache-Control": "no-store"},
+ )
+ response.set_cookie(
+ "two_factor_challenge",
+ token,
+ max_age=300,
+ httponly=True,
+ secure=settings.auth_https_only,
+ samesite="lax",
+ )
+ response.delete_cookie("cookie_access_token")
+ response.delete_cookie("is_lnbits_user_authorized")
+ return response
+ payload = await session_payload(account.id, config)
+ payload.sub = account.username or ""
+ payload.email = account.email
+ response = _auth_success_response(payload=payload)
+ response.delete_cookie("two_factor_challenge")
+ return response
diff --git a/lnbits/core/views/generic.py b/lnbits/core/views/generic.py
index 7056f3e..353a494 100644
--- a/lnbits/core/views/generic.py
+++ b/lnbits/core/views/generic.py
@@ -214,6 +214,16 @@ async def index(
)
+@generic_router.get("/2fa")
+async def two_factor_page(request: Request) -> HTMLResponse:
+ return template_renderer().TemplateResponse(
+ request,
+ "two_factor.html",
+ {"public": True},
+ headers={"Cache-Control": "no-store", "Referrer-Policy": "no-referrer"},
+ )
+
+
@generic_router.get("/")
@generic_router.get("/node/public")
@generic_router.get("/first_install", dependencies=[Depends(check_first_install)])
diff --git a/lnbits/core/views/two_factor_api.py b/lnbits/core/views/two_factor_api.py
new file mode 100644
index 0000000..40a2ce6
--- /dev/null
+++ b/lnbits/core/views/two_factor_api.py
@@ -0,0 +1,174 @@
+import base64
+from http import HTTPStatus
+
+from fastapi import APIRouter, Depends, HTTPException, Request
+from fastapi.responses import JSONResponse
+
+from lnbits.core.crud.users import get_account, get_two_factor_config
+from lnbits.core.models.users import (
+ AccessTokenPayload,
+ Account,
+ TwoFactorCode,
+ TwoFactorConfig,
+ TwoFactorStatus,
+)
+from lnbits.core.services.two_factor import (
+ acknowledge_recovery_codes,
+ begin_enrollment,
+ check_two_factor_session,
+ disable_two_factor,
+ regenerate_recovery_codes,
+ require_recent_login,
+ session_payload,
+ totp,
+ two_factor_error,
+ validate_identity,
+ verify_factor,
+)
+from lnbits.decorators import _decode_access_token
+from lnbits.settings import settings
+
+two_factor_router = APIRouter(prefix="/api/v1/auth/2fa", tags=["Two Factor Auth"])
+
+
+async def two_factor_identity(request: Request) -> tuple[Account, AccessTokenPayload]:
+ # Challenge cookies never participate in ordinary account authentication.
+ token: str | None = request.headers.get("Authorization", "").removeprefix("Bearer ")
+ token = token or request.cookies.get("two_factor_challenge")
+ token = token or request.cookies.get("cookie_access_token")
+ if not token:
+ raise HTTPException(HTTPStatus.UNAUTHORIZED, "Please log in first.")
+ payload = _decode_access_token(token)
+ account = await get_account(payload.usr or "")
+ if not account and payload.sub:
+ from lnbits.core.crud.users import get_account_by_username
+
+ account = await get_account_by_username(payload.sub)
+ if not account:
+ raise HTTPException(HTTPStatus.UNAUTHORIZED, "Please log in again.")
+ config = await get_two_factor_config(account.id)
+ validate_identity(config, payload)
+ if not settings.is_user_allowed(account.id):
+ raise HTTPException(HTTPStatus.FORBIDDEN, "Account access is disabled.")
+ return account, payload
+
+
+async def factor_session_response(
+ account: Account,
+ config: TwoFactorConfig,
+ verified: bool,
+ codes: list[str] | None = None,
+) -> JSONResponse:
+ from lnbits.core.views.auth_api import _auth_success_response
+
+ payload = await session_payload(account.id, config, verified)
+ response = _auth_success_response(payload=payload, recovery_codes=codes)
+ response.delete_cookie("two_factor_challenge")
+ response.headers["Cache-Control"] = "no-store"
+ return response
+
+
+@two_factor_router.get("/status")
+async def factor_status(
+ identity: tuple[Account, AccessTokenPayload] = Depends(two_factor_identity),
+) -> TwoFactorStatus:
+ account, payload = identity
+ config = await get_two_factor_config(account.id)
+ verification_required = False
+ try:
+ await recent_factor_identity(identity)
+ except HTTPException as exc:
+ if exc.status_code != HTTPStatus.UNAUTHORIZED:
+ raise
+ verification_required = True
+ return TwoFactorStatus(
+ available=settings.lnbits_two_factor_enabled,
+ mandatory=settings.lnbits_two_factor_mandatory,
+ enrolled=bool(config.secret),
+ challenge=payload.purpose == "two_factor",
+ recovery_remaining=len(config.recovery_hashes),
+ recovery_saved=config.recovery_saved,
+ verification_required=verification_required,
+ )
+
+
+@two_factor_router.post("/setup")
+async def setup_factor(
+ identity: tuple[Account, AccessTokenPayload] = Depends(two_factor_identity),
+) -> JSONResponse:
+ account, payload = identity
+ secret = await begin_enrollment(account.id, payload)
+ uri = totp(secret).get_provisioning_uri(
+ account.username or account.email or account.id, settings.lnbits_site_title
+ )
+ return JSONResponse(
+ {"secret": base64.b32encode(secret).decode(), "uri": uri},
+ headers={"Cache-Control": "no-store"},
+ )
+
+
+@two_factor_router.post("/confirm")
+async def confirm_factor(
+ data: TwoFactorCode,
+ identity: tuple[Account, AccessTokenPayload] = Depends(two_factor_identity),
+) -> JSONResponse:
+ if not settings.lnbits_two_factor_enabled:
+ raise HTTPException(
+ HTTPStatus.FORBIDDEN, "Two factor authentication is disabled."
+ )
+ account, payload = identity
+ require_recent_login(payload)
+ config, codes = await verify_factor(account.id, payload, data.code, enrolling=True)
+ return await factor_session_response(account, config, True, codes)
+
+
+@two_factor_router.post("/verify")
+async def verify_two_factor(
+ data: TwoFactorCode,
+ identity: tuple[Account, AccessTokenPayload] = Depends(two_factor_identity),
+) -> JSONResponse:
+ if not settings.lnbits_two_factor_enabled:
+ raise two_factor_error(
+ "Two factor authentication is disabled. Please log in again."
+ )
+ account, payload = identity
+ config, _ = await verify_factor(account.id, payload, data.code)
+ return await factor_session_response(account, config, True)
+
+
+async def recent_factor_identity(
+ identity: tuple[Account, AccessTokenPayload] = Depends(two_factor_identity),
+) -> tuple[Account, AccessTokenPayload]:
+ account, payload = identity
+ require_recent_login(payload)
+ await check_two_factor_session(account.id, payload, "/api/v1/auth/2fa", "POST")
+ return identity
+
+
+@two_factor_router.post("/recovery/acknowledge")
+async def acknowledge_recovery(
+ identity: tuple[Account, AccessTokenPayload] = Depends(recent_factor_identity),
+):
+ account, payload = identity
+ await acknowledge_recovery_codes(account.id, payload)
+ return {"status": "success"}
+
+
+@two_factor_router.post("/recovery")
+async def regenerate_recovery(
+ identity: tuple[Account, AccessTokenPayload] = Depends(recent_factor_identity),
+) -> JSONResponse:
+ account, payload = identity
+ codes = await regenerate_recovery_codes(account.id, payload)
+ return JSONResponse(
+ {"recovery_codes": codes}, headers={"Cache-Control": "no-store"}
+ )
+
+
+@two_factor_router.delete("")
+async def disable_factor(
+ identity: tuple[Account, AccessTokenPayload] = Depends(recent_factor_identity),
+) -> JSONResponse:
+ account, payload = identity
+ config = await disable_two_factor(account.id, payload)
+ return await factor_session_response(account, config, False)
diff --git a/lnbits/decorators.py b/lnbits/decorators.py
index 2ca70c8..59b770e 100644
--- a/lnbits/decorators.py
+++ b/lnbits/decorators.py
@@ -31,6 +31,7 @@ from lnbits.core.models import (
)
from lnbits.core.models.users import AccountId, EndpointAccess
from lnbits.core.models.wallets import BaseWallet, BaseWalletTypeInfo
+from lnbits.core.services.two_factor import check_two_factor_session
from lnbits.db import Connection, Filter, Filters, TFilterModel
from lnbits.helpers import normalize_path, path_segments, sha256s
from lnbits.settings import AuthMethods, settings
@@ -257,6 +258,9 @@ async def check_account_id_exists(
r["method"],
conn=conn,
)
+ await check_two_factor_session(
+ account_id.id, payload, r["path"], r["method"], conn
+ )
r.scope["user_id"] = account_id.id
await _check_user_access(r, account_id.id, conn=conn)
return account_id
@@ -315,6 +319,11 @@ async def _check_account_exists(
if not account:
raise HTTPException(HTTPStatus.UNAUTHORIZED, "User not found.")
+ if not access_token:
+ await check_two_factor_session(
+ account.id, None, r["path"], r["method"], new_conn
+ )
+
r.scope["user_id"] = account.id
await _check_user_access(r, account.id, conn=new_conn)
@@ -340,11 +349,12 @@ async def optional_user_id(
access_token: Annotated[str | None, Depends(check_access_token)],
usr: UUID4 | None = None,
) -> str | None:
- if usr and settings.is_auth_method_allowed(AuthMethods.user_id_only):
- return usr.hex
if access_token:
account = await _get_account_from_token(access_token, r["path"], r["method"])
return account.id if account else None
+ if usr and settings.is_auth_method_allowed(AuthMethods.user_id_only):
+ account = await _check_account_exists(r, None, usr)
+ return account.id
return None
@@ -543,6 +553,8 @@ async def _get_account_from_jwt_payload(
account.id, payload.api_token_id, path, method, conn=conn
)
+ await check_two_factor_session(account.id, payload, path, method, conn)
+
return account
diff --git a/lnbits/exceptions.py b/lnbits/exceptions.py
index 5701e2d..be859f7 100644
--- a/lnbits/exceptions.py
+++ b/lnbits/exceptions.py
@@ -39,6 +39,18 @@ def render_html_error(request: Request, exc: Exception) -> Response | None:
if not _is_browser_request(request):
return None
+ if isinstance(exc, HTTPException) and (exc.headers or {}).get(
+ "two-factor-required"
+ ):
+ from urllib.parse import urlencode
+
+ query = (
+ urlencode({"usr": request.query_params["usr"]})
+ if "usr" in request.query_params
+ else ""
+ )
+ return RedirectResponse("/2fa" + ("?" + query if query else ""))
+
if (
isinstance(exc, HTTPException)
and exc.headers
@@ -118,6 +130,7 @@ def register_exception_handlers(app: FastAPI): # noqa: C901
return render_html_error(request, exc) or JSONResponse(
status_code=exc.status_code,
content={"detail": exc.detail},
+ headers=exc.headers,
)
@app.exception_handler(PaymentError)
diff --git a/lnbits/middleware.py b/lnbits/middleware.py
index d216786..3c8c2cc 100644
--- a/lnbits/middleware.py
+++ b/lnbits/middleware.py
@@ -179,6 +179,10 @@ class AuditMiddleware(BaseHTTPMiddleware):
http_method = request.scope.get("method", None)
path = request.scope.get("path", None)
+ # Authentication bodies contain passwords, OTPs and recovery credentials.
+ if path and path.startswith("/api/v1/auth"):
+ return "{}"
+
if not settings.audit_http_request(http_method, path):
return None
diff --git a/lnbits/settings.py b/lnbits/settings.py
index 6baa622..76bc74a 100644
--- a/lnbits/settings.py
+++ b/lnbits/settings.py
@@ -986,6 +986,18 @@ class OidcAuthSettings(LNbitsSettings):
oidc_client_custom_icon: str | None = Field(default=None)
+class TwoFactorSettings(LNbitsSettings):
+ lnbits_two_factor_enabled: bool = Field(default=False)
+ lnbits_two_factor_methods: list[str] = Field(default=["totp"])
+ lnbits_two_factor_mandatory: bool = Field(default=False)
+
+ @validator("lnbits_two_factor_methods")
+ def validate_two_factor_methods(cls, methods: list[str]) -> list[str]:
+ if any(method != "totp" for method in methods):
+ raise ValueError("Only TOTP is supported.")
+ return list(dict.fromkeys(methods))
+
+
class AuditSettings(LNbitsSettings):
lnbits_audit_enabled: bool = Field(default=True)
@@ -1090,6 +1102,7 @@ class EditableSettings(
NodeUISettings,
BlockExplorerSettings,
AuditSettings,
+ TwoFactorSettings,
AuthSettings,
NostrAuthSettings,
GoogleAuthSettings,
@@ -1145,6 +1158,8 @@ class EnvSettings(LNbitsSettings):
lnbits_extensions_path: str = Field(default="lnbits")
super_user: str = Field(default="")
auth_secret_key: str = Field(default="")
+ # Generated and persisted as .lnbits_totp_key when unset.
+ totp_encryption_key: str = Field(default="")
version: str = Field(default="0.0.0")
user_agent: str = Field(default="")
enable_log_to_file: bool = Field(default=True)
@@ -1183,6 +1198,20 @@ class EnvSettings(LNbitsSettings):
with open(auth_key_file, "w+") as file:
file.write(self.auth_secret_key)
+ def check_totp_encryption_key(self):
+ if self.totp_encryption_key:
+ return
+ if not os.path.isdir(settings.lnbits_data_folder):
+ os.mkdir(settings.lnbits_data_folder)
+ totp_key_file = Path(settings.lnbits_data_folder, ".lnbits_totp_key")
+ if totp_key_file.is_file():
+ with open(totp_key_file) as file:
+ self.totp_encryption_key = file.readline()
+ return
+ self.totp_encryption_key = uuid4().hex
+ with open(totp_key_file, "w+") as file:
+ file.write(self.totp_encryption_key)
+
class PersistenceSettings(LNbitsSettings):
lnbits_data_folder: str = Field(default="./data")
@@ -1539,6 +1568,7 @@ settings.lnbits_path = str(path.dirname(path.realpath(__file__)))
settings.version = importlib.metadata.version("lnbits")
settings.check_auth_secret_key()
+settings.check_totp_encryption_key()
if not settings.user_agent:
settings.user_agent = f"LNbits/{settings.version}"
@@ -1546,7 +1576,9 @@ if not settings.user_agent:
# printing environment variable for debugging
if not settings.lnbits_admin_ui:
logger.debug("Environment Settings:")
- for key, value in settings.dict(exclude_none=True).items():
+ for key, value in settings.dict(
+ exclude_none=True, exclude={"auth_secret_key", "totp_encryption_key"}
+ ).items():
logger.debug(f"{key}: {value}")
diff --git a/lnbits/static/bundle-components.min.js b/lnbits/static/bundle-components.min.js
index 97dd433..df423fc 100644
--- a/lnbits/static/bundle-components.min.js
+++ b/lnbits/static/bundle-components.min.js
@@ -1 +1 @@
-window.PageError={template:"#page-error"},window.PageHome={template:"#page-home",data:()=>({lnurl:"",authAction:"login",authMethod:"username-password",usr:"",username:"",reset_key:"",email:"",password:"",passwordRepeat:"",invitationCode:"",walletName:"",signup:!1}),computed:{showClaimLnurl(){return""!==this.lnurl&&this.g.settings.allowRegister&&this.g.settings.authMethods.includes("user-id-only")},formatDescription(){return LNbits.utils.convertMarkdown(this.g.settings.siteDescription)},isAccessTokenExpired(){return this.$q.cookies.get("is_access_token_expired")}},methods:{showLogin(e){this.authAction="login",this.authMethod=e},showRegister(e){this.user="",this.username=null,this.password=null,this.passwordRepeat=null,this.invitationCode=null,this.authAction="register",this.authMethod=e},async register(){try{await LNbits.api.register(this.username,this.email,this.password,this.passwordRepeat,this.invitationCode),this.refreshAuthUser()}catch(e){LNbits.utils.notifyApiError(e)}},async reset(){try{await LNbits.api.reset(this.reset_key,this.password,this.passwordRepeat),this.refreshAuthUser()}catch(e){LNbits.utils.notifyApiError(e)}},async login(){try{await LNbits.api.login(this.username,this.password),this.refreshAuthUser()}catch(e){LNbits.utils.notifyApiError(e)}},async loginUsr(){try{await LNbits.api.loginUsr(this.usr),this.refreshAuthUser()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async refreshAuthUser(){try{const e=await LNbits.api.getAuthUser();this.g.user=LNbits.map.user(e.data),this.g.isPublicPage=!1,this.$router.push(`/wallet/${this.g.user.wallets[0].id}`)}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},createWallet(){LNbits.api.createAccount(this.walletName).then(e=>{this.$router.push(`/wallet/${e.data.id}`)})},processing(){Quasar.Notify.create({timeout:0,message:"Processing...",icon:null})}},created(){if(this.g.isUserAuthorized)return this.refreshAuthUser();const e=new URLSearchParams(window.location.search);this.reset_key=e.get("reset_key"),this.reset_key&&(this.authAction="reset"),e.has("lightning")&&(this.lnurl=e.get("lightning"))}},window.PageExtensionBuilder={template:"#page-extension-builder",data:()=>({step:1,previewStepNames:{2:"settings",3:"owner_data",4:"client_data",5:"public_page"},extensionDataCleanString:"",extensionData:{id:"",name:"",stub_version:"",short_description:"",description:"",public_page:{has_public_page:!0,owner_data_fields:{name:"",description:""},client_data_fields:{public_inputs:[]},action_fields:{generate_action:!0,generate_payment_logic:!1,wallet_id:"",currency:"",amount:"",paid_flag:""}},preview_action:{is_preview_mode:!1,is_settings_preview:!1,is_owner_data_preview:!1,is_client_data_preview:!1,is_public_page_preview:!1},settings_data:{name:"Settings",enabled:!0,type:"user",fields:[]},owner_data:{name:"OwnerData",fields:[]},client_data:{enabled:!0,name:"ClientData",fields:[]}},sampleField:{name:"name",type:"str",label:"Name",hint:"",optional:!0,editable:!0,searchable:!0,sortable:!0},settingsTypes:[{label:"User Settings",value:"user"},{label:"Admin Settings",value:"admin"}],amountSource:[{label:"Client Data",value:"client_data"},{label:"Owner Data",value:"owner_data"}],extensionStubVersions:[]}),watch:{"extensionData.public_page.action_fields.amount_source":function(e,t){t&&e!==t&&(this.extensionData.public_page.action_fields.amount="")}},computed:{paymentActionAmountFields(){const e=this.extensionData.public_page.action_fields.amount_source;return e?"owner_data"===e?[""].concat(this.extensionData.owner_data.fields.filter(e=>"int"===e.type||"float"===e.type).map(e=>e.name)):"client_data"===e?[""].concat(this.extensionData.client_data.fields.filter(e=>"int"===e.type||"float"===e.type).map(e=>e.name)):void 0:[""]}},methods:{saveState(){this.$q.localStorage.set("lnbits.extension.builder.data",JSON.stringify(this.extensionData)),this.$q.localStorage.set("lnbits.extension.builder.step",this.step)},nextStep(){this.saveState(),this.$refs.stepper.next(),this.refreshPreview()},previousStep(){this.saveState(),this.$refs.stepper.previous(),this.refreshPreview()},onStepChange(){this.saveState(),this.refreshPreview()},clearAllData(){LNbits.utils.confirmDialog("Are you sure you want to clear all data? This action cannot be undone.").onOk(()=>{this.extensionData=JSON.parse(this.extensionDataCleanString),this.$q.localStorage.remove("lnbits.extension.builder.data"),this.$refs.stepper.set(1)})},exportJsonData(){!0!==Quasar.exportFile(`${this.extensionData.id||"data-export"}.json`,JSON.stringify(this.extensionData,null,2),"text/json")?Quasar.Notify.create({message:"Browser denied file download...",color:"negative",icon:null}):Quasar.Notify.create({message:"File downloaded!",color:"positive",icon:"file_download"})},onJsonDataInput(e){const t=e.target.files[0],s=new FileReader;s.onload=e=>{this.extensionData={...this.extensionData,...JSON.parse(e.target.result)},this.$refs.extensionDataInput.value=null,Quasar.Notify.create({message:"File loaded!",color:"positive",icon:"file_upload"})},s.readAsText(t)},async buildExtension(){try{const e={responseType:"blob"},t=await LNbits.api.request("POST","/api/v1/extension/builder/zip",null,this.extensionData,e),s=window.URL.createObjectURL(new Blob([t.data])),a=document.createElement("a");a.href=s,a.download=`${this.extensionData.id||"lnbits-extension"}.zip`,document.body.appendChild(a),a.click(),a.remove(),window.URL.revokeObjectURL(s)}catch(e){LNbits.utils.notifyApiError(e)}},async buildExtensionAndDeploy(){try{const{data:e}=await LNbits.api.request("POST","/api/v1/extension/builder/deploy",null,this.extensionData);Quasar.Notify.create({message:e.message||"Extension deployed!",color:"positive"})}catch(e){LNbits.utils.notifyApiError(e)}},async cleanCacheData(){LNbits.utils.confirmDialog("Are you sure you want to clean the cache data? This action cannot be undone.","Clean Cache Data").onOk(async()=>{try{const{data:e}=await LNbits.api.request("DELETE","/api/v1/extension/builder",null,{});Quasar.Notify.create({message:e.message||"Cache data cleaned!",color:"positive"})}catch(e){LNbits.utils.notifyApiError(e)}})},async previewExtension(e){this.saveState();try{await LNbits.api.request("POST","/api/v1/extension/builder/preview",null,{...this.extensionData,preview_action:{is_preview_mode:!!e,is_settings_preview:"settings"===e,is_owner_data_preview:"owner_data"===e,is_client_data_preview:"client_data"===e,is_public_page_preview:"public_page"===e}}),this.refreshIframe(e)}catch(e){LNbits.utils.notifyApiError(e)}},async refreshPreview(){setTimeout(()=>{const e=this.previewStepNames[`${this.step}`]||"";e&&this.previewExtension(e)},100)},async getStubExtensionReleases(){try{const e="extension_builder_stub",{data:t}=await LNbits.api.request("GET",`/api/v1/extension/${e}/releases`);this.extensionStubVersions=t;const s=t.filter(e=>e.is_version_compatible);this.extensionData.stub_version=s[0]?s[0].version:""}catch(e){LNbits.utils.notifyApiError(e)}},refreshIframe(e=""){const t=this.$refs[`iframeStep${this.step}`];if(!t)return void console.warn("Extension Builder Preview iframe not loaded yet.");t.onload=()=>{const e=t.contentDocument||t.contentWindow.document;e.body.style.transform="scale(0.8)",e.body.style.transformOrigin="center top"};let s="Page"+this.extensionData.id.toLowerCase().split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("");"public_page"===e&&(s+="Public"),t.src=`/extensions/builder/preview?ext_id=${this.extensionData.id}&page=${e}&component=${s}`},initBasicData(){this.extensionData.owner_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionData.client_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionData.settings_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionDataCleanString=JSON.stringify(this.extensionData)}},created(){this.initBasicData();const e=this.$q.localStorage.getItem("lnbits.extension.builder.data");e&&(this.extensionData={...this.extensionData,...JSON.parse(e)});const t=+this.$q.localStorage.getItem("lnbits.extension.builder.step");t&&(this.step=t),this.g.user.admin&&this.getStubExtensionReleases(),setTimeout(()=>{this.refreshIframe()},1e3)}},window.PageExtensionBuilder={template:"#page-extension-builder",data:()=>({step:1,previewStepNames:{2:"settings",3:"owner_data",4:"client_data",5:"public_page"},extensionDataCleanString:"",extensionData:{id:"",name:"",stub_version:"",short_description:"",description:"",public_page:{has_public_page:!0,owner_data_fields:{name:"",description:""},client_data_fields:{public_inputs:[]},action_fields:{generate_action:!0,generate_payment_logic:!1,wallet_id:"",currency:"",amount:"",paid_flag:""}},preview_action:{is_preview_mode:!1,is_settings_preview:!1,is_owner_data_preview:!1,is_client_data_preview:!1,is_public_page_preview:!1},settings_data:{name:"Settings",enabled:!0,type:"user",fields:[]},owner_data:{name:"OwnerData",fields:[]},client_data:{enabled:!0,name:"ClientData",fields:[]}},sampleField:{name:"name",type:"str",label:"Name",hint:"",optional:!0,editable:!0,searchable:!0,sortable:!0},settingsTypes:[{label:"User Settings",value:"user"},{label:"Admin Settings",value:"admin"}],amountSource:[{label:"Client Data",value:"client_data"},{label:"Owner Data",value:"owner_data"}],extensionStubVersions:[]}),watch:{"extensionData.public_page.action_fields.amount_source":function(e,t){t&&e!==t&&(this.extensionData.public_page.action_fields.amount="")}},computed:{paymentActionAmountFields(){const e=this.extensionData.public_page.action_fields.amount_source;return e?"owner_data"===e?[""].concat(this.extensionData.owner_data.fields.filter(e=>"int"===e.type||"float"===e.type).map(e=>e.name)):"client_data"===e?[""].concat(this.extensionData.client_data.fields.filter(e=>"int"===e.type||"float"===e.type).map(e=>e.name)):void 0:[""]}},methods:{saveState(){this.$q.localStorage.set("lnbits.extension.builder.data",JSON.stringify(this.extensionData)),this.$q.localStorage.set("lnbits.extension.builder.step",this.step)},nextStep(){this.saveState(),this.$refs.stepper.next(),this.refreshPreview()},previousStep(){this.saveState(),this.$refs.stepper.previous(),this.refreshPreview()},onStepChange(){this.saveState(),this.refreshPreview()},clearAllData(){LNbits.utils.confirmDialog("Are you sure you want to clear all data? This action cannot be undone.").onOk(()=>{this.extensionData=JSON.parse(this.extensionDataCleanString),this.$q.localStorage.remove("lnbits.extension.builder.data"),this.$refs.stepper.set(1)})},exportJsonData(){!0!==Quasar.exportFile(`${this.extensionData.id||"data-export"}.json`,JSON.stringify(this.extensionData,null,2),"text/json")?Quasar.Notify.create({message:"Browser denied file download...",color:"negative",icon:null}):Quasar.Notify.create({message:"File downloaded!",color:"positive",icon:"file_download"})},onJsonDataInput(e){const t=e.target.files[0],s=new FileReader;s.onload=e=>{this.extensionData={...this.extensionData,...JSON.parse(e.target.result)},this.$refs.extensionDataInput.value=null,Quasar.Notify.create({message:"File loaded!",color:"positive",icon:"file_upload"})},s.readAsText(t)},async buildExtension(){try{const e={responseType:"blob"},t=await LNbits.api.request("POST","/api/v1/extension/builder/zip",null,this.extensionData,e),s=window.URL.createObjectURL(new Blob([t.data])),a=document.createElement("a");a.href=s,a.download=`${this.extensionData.id||"lnbits-extension"}.zip`,document.body.appendChild(a),a.click(),a.remove(),window.URL.revokeObjectURL(s)}catch(e){LNbits.utils.notifyApiError(e)}},async buildExtensionAndDeploy(){try{const{data:e}=await LNbits.api.request("POST","/api/v1/extension/builder/deploy",null,this.extensionData);Quasar.Notify.create({message:e.message||"Extension deployed!",color:"positive"})}catch(e){LNbits.utils.notifyApiError(e)}},async cleanCacheData(){LNbits.utils.confirmDialog("Are you sure you want to clean the cache data? This action cannot be undone.","Clean Cache Data").onOk(async()=>{try{const{data:e}=await LNbits.api.request("DELETE","/api/v1/extension/builder",null,{});Quasar.Notify.create({message:e.message||"Cache data cleaned!",color:"positive"})}catch(e){LNbits.utils.notifyApiError(e)}})},async previewExtension(e){this.saveState();try{await LNbits.api.request("POST","/api/v1/extension/builder/preview",null,{...this.extensionData,preview_action:{is_preview_mode:!!e,is_settings_preview:"settings"===e,is_owner_data_preview:"owner_data"===e,is_client_data_preview:"client_data"===e,is_public_page_preview:"public_page"===e}}),this.refreshIframe(e)}catch(e){LNbits.utils.notifyApiError(e)}},async refreshPreview(){setTimeout(()=>{const e=this.previewStepNames[`${this.step}`]||"";e&&this.previewExtension(e)},100)},async getStubExtensionReleases(){try{const e="extension_builder_stub",{data:t}=await LNbits.api.request("GET",`/api/v1/extension/${e}/releases`);this.extensionStubVersions=t;const s=t.filter(e=>e.is_version_compatible);this.extensionData.stub_version=s[0]?s[0].version:""}catch(e){LNbits.utils.notifyApiError(e)}},refreshIframe(e=""){const t=this.$refs[`iframeStep${this.step}`];if(!t)return void console.warn("Extension Builder Preview iframe not loaded yet.");t.onload=()=>{const e=t.contentDocument||t.contentWindow.document;e.body.style.transform="scale(0.8)",e.body.style.transformOrigin="center top"};let s="Page"+this.extensionData.id.toLowerCase().split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("");"public_page"===e&&(s+="Public"),t.src=`/extensions/builder/preview?ext_id=${this.extensionData.id}&page=${e}&component=${s}`},initBasicData(){this.extensionData.owner_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionData.client_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionData.settings_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionDataCleanString=JSON.stringify(this.extensionData)}},created(){this.initBasicData();const e=this.$q.localStorage.getItem("lnbits.extension.builder.data");e&&(this.extensionData={...this.extensionData,...JSON.parse(e)});const t=+this.$q.localStorage.getItem("lnbits.extension.builder.step");t&&(this.step=t),this.g.user.admin&&this.getStubExtensionReleases(),setTimeout(()=>{this.refreshIframe()},1e3)}},window.PageExtensionBuilderPreview={template:"#page-extension-builder-preview",mixins:[windowMixin],watch:{name:"reload"},data:()=>({extId:"",pageName:"",componentName:null}),methods:{async reload(){await LNbits.utils.loadTemplate(`/extensions/builder/preview/${this.extId}/template?page_name=${this.pageName}`),await LNbits.utils.loadScript(`/extensions/builder/preview/${this.extId}/component?page_name=${this.pageName}`),this._component=window[this.componentName],console.log("LNbits preview reloaded componentName:",this.componentName,!!this._component),this.$forceUpdate()}},async created(){const e=new URLSearchParams(window.location.search);this.extId=e.get("ext_id")||"",this.pageName=e.get("page")||"",this.componentName=e.get("component")||"",await this.reload()},render(){return this._component?Vue.h(this._component):Vue.h("div","Loading...")}};const EXTENSION_PERMISSION_DEFAULT_MAX_ROWS_PER_SOURCE=1e4,EXTENSION_PERMISSION_MAX_ROWS_PER_SOURCE_LIMIT=1e6,EXTENSION_PERMISSION_MAX_MESSAGES_PER_SECOND_LIMIT=100;window.PageExtensions={template:"#page-extensions",data(){return{extbuilderEnabled:!1,slide:0,fullscreen:!1,autoplay:!0,searchTerm:"",tab:"installed",manageExtensionTab:"releases",filteredExtensions:[],categories:new Set,updatableExtensions:[],showUninstallDialog:!1,showManageExtensionDialog:!1,showExtensionDetailsDialog:!1,showDropDbDialog:!1,showPayToEnableDialog:!1,showUpdateAllDialog:!1,dropDbExtensionId:"",selectedExtension:null,selectedImage:null,selectedExtensionDetails:null,selectedExtensionDetailsDescription:"",selectedExtensionRepos:null,selectedRelease:null,permissionGrant:{show:!1,permissions:[],resolve:null},extensionPermissionMaxRowsPerSourceLimit:1e6,extensionPermissionMaxMessagesPerSecondLimit:100,managedExtensionPermissions:{loading:!1,extensionPermissions:[],userPermissions:{},savingExtensionPermissions:!1,savingKey:"",deletingKey:""},backgroundPaymentDestinationOptions:[{label:"Only transfers to my wallets",value:"own_wallets_only"},{label:"Allow external payments",value:"external_allowed"}],uninstallAndDropDb:!1,maxStars:5,paylinkWebsocket:null,searchToggle:!1,reviewsUrl:null,reviewsDialog:{show:!1,extension:null,loading:!1,submitting:!1,form:{name:"",rating:0,comment:""},error:null},reviews:[],reviewsTable:{loading:!1,columns:[{name:"name",align:"left",label:this.$t("Name"),field:"name",sortable:!0},{name:"comment",align:"left",label:this.$t("Comment"),field:"comment"},{name:"created_at",align:"left",label:this.$t("Date"),field:"created_at"},{name:"rating",align:"right",label:"Rating",field:"rating"}],pagination:{rowsPerPage:5,sortBy:"created_at",descending:!0,page:1}},paymentDialog:{show:!1,invoice:"",hash:""}}},watch:{searchTerm(e){this.filterExtensions(e,this.tab)},tab(e){this.filterExtensions(this.searchTerm,e)}},computed:{managedUserPermissionRows(){const e=[],t=this.managedExtensionPermissions.userPermissions||{};return Object.entries(t).forEach(([t,s])=>{Array.isArray(s)&&s.forEach(s=>{if(!s||"object"!=typeof s)return;const a=String(s.id||""),i=String(s.wallet_id||"");a&&i&&e.push({key:a,permissionId:t,label:this.permissionLabelById(t),grantId:a,walletId:i,walletName:this.walletName(i),grant:s})})}),e}},methods:{filterExtensions(e,t){const s=!["installed","all","featured"].includes(t);var a;this.filteredExtensions=this.extensions.filter(e=>"all"!==t||!e.isInstalled).filter(e=>"installed"!==t||e.isInstalled).filter(e=>"installed"!==t||(!!e.isActive||!!this.g.user.admin)).filter(e=>"featured"!==t||e.isFeatured).filter(e=>!s||(e=>e.categories?.includes(t)??!1)(e)).filter((a=e,function(e){return e.name.toLowerCase().includes(a.toLowerCase())||e.shortDescription?.toLowerCase().includes(a.toLowerCase())})).map(e=>({...e,details_link:e.installedRelease?.details_link||e.latestRelease?.details_link}))},async installExtension(e){this.unsubscribeFromPaylinkWs();const t=await this.resolveExtensionPermissionGrant(e);null!==t&&(this.selectedExtension.inProgress=!0,this.showManageExtensionDialog=!1,e.payment_hash=e.payment_hash||this.getPaylinkHash(e.pay_link),LNbits.api.request("POST","/api/v1/extension",this.g.user.wallets[0].adminkey,{ext_id:this.selectedExtension.id,archive:e.archive,source_repo:e.source_repo,payment_hash:e.payment_hash,version:e.version,permissions:t}).then(t=>{this.selectedExtension.inProgress=!1;const s=this.extensions.find(e=>e.id===this.selectedExtension.id);s.isAvailable=!0,s.isInstalled=!0,s.isWasm=!0===t.data.is_wasm||!0===t.data.isWasm||"wasm"===e.extension_type||!0===s.isWasm,s.icon=t.data.icon||s.icon,s.installedRelease=e,this.toggleExtension(s),s.inProgress=!1,this.selectedExtension=s,this.extensions=this.extensions.concat([]),this.tab="installed"}).catch(e=>{console.warn(e),this.selectedExtension.inProgress=!1,LNbits.utils.notifyApiError(e)}))},async uninstallExtension(){this.showManageExtensionDialog=!1,this.showUninstallDialog=!1,this.selectedExtension.inProgress=!0,LNbits.api.request("DELETE",`/api/v1/extension/${this.selectedExtension.id}`,this.g.user.wallets[0].adminkey).then(e=>{const t=this.extensions.find(e=>e.id===this.selectedExtension.id);t.isAvailable=!1,t.isInstalled=!1,t.inProgress=!1,t.installedRelease=null,this.filteredExtensions=this.filteredExtensions.filter(e=>e.id!==t.id),Quasar.Notify.create({type:"positive",message:"Extension uninstalled!"}),this.uninstallAndDropDb&&this.showDropDb()}).catch(e=>{LNbits.utils.notifyApiError(e),extension.inProgress=!1})},async dropExtensionDb(){const e=this.selectedExtension;this.showManageExtensionDialog=!1,this.showDropDbDialog=!1,this.dropDbExtensionId="",e.inProgress=!0,LNbits.api.request("DELETE",`/api/v1/extension/${e.id}/db`,this.g.user.wallets[0].adminkey).then(t=>{e.installedRelease=null,e.inProgress=!1,e.hasDatabaseTables=!1,Quasar.Notify.create({type:"positive",message:"Extension DB deleted!"})}).catch(t=>{LNbits.utils.notifyApiError(t),e.inProgress=!1})},toggleExtension(e){const t=e.isActive?"activate":"deactivate";LNbits.api.request("PUT",`/api/v1/extension/${e.id}/${t}`,this.g.user.wallets[0].adminkey).then(s=>{Quasar.Notify.create({timeout:2e3,type:"positive",message:`Extension '${e.id}' ${t}d!`})}).catch(t=>{LNbits.utils.notifyApiError(t),e.isActive=!1,e.inProgress=!1})},async enableExtensionForUser(e){e.isPaymentRequired?this.showPayToEnable(e):this.enableExtension(e)},async enableExtension(e){LNbits.api.request("PUT",`/api/v1/extension/${e.id}/enable`,this.g.user.wallets[0].adminkey).then(t=>{this.g.user.extensions=this.g.user.extensions.concat([e.id]),Quasar.Notify.create({type:"positive",message:"Extension enabled!"})}).catch(e=>{console.warn(e),LNbits.utils.notifyApiError(e)})},disableExtension(e){LNbits.api.request("PUT",`/api/v1/extension/${e.id}/disable`,this.g.user.wallets[0].adminkey).then(t=>{this.g.user.extensions=this.g.user.extensions.filter(t=>t!==e.id),Quasar.Notify.create({type:"positive",message:"Extension disabled!"})}).catch(e=>{console.warn(error),LNbits.utils.notifyApiError(e)})},showPayToEnable(e){this.selectedExtension=e,this.selectedExtension.payToEnable.paidAmount=e.payToEnable.amount,this.selectedExtension.payToEnable.showQRCode=!1,this.showPayToEnableDialog=!0},updatePayToInstallData(e){LNbits.api.request("PUT",`/api/v1/extension/${e.id}/sell`,this.g.user.wallets[0].adminkey,{required:e.payToEnable.required,amount:e.payToEnable.amount,wallet:e.payToEnable.wallet}).then(e=>{Quasar.Notify.create({type:"positive",message:"Payment info updated!"}),this.showManageExtensionDialog=!1}).catch(t=>{LNbits.utils.notifyApiError(t),e.inProgress=!1})},showUninstall(){this.showManageExtensionDialog=!1,this.showUninstallDialog=!0,this.uninstallAndDropDb=!1},showDropDb(){this.showDropDbDialog=!0},async showManageExtension(e){if(this.selectedExtension=e,this.selectedRelease=null,this.selectedExtensionRepos=null,this.resetManagedExtensionPermissions(),this.manageExtensionTab=this.g.user.admin?"releases":"extension-permissions",this.showManageExtensionDialog=!0,this.canManageExtensionPermissions(e)&&this.loadManagedExtensionPermissions(e),this.g.user.admin)try{const{data:t}=await LNbits.api.request("GET",`/api/v1/extension/${e.id}/releases`);this.selectedExtensionRepos=t.reduce((e,t)=>(e[t.source_repo]=e[t.source_repo]||{releases:[],isInstalled:!1,repo:t.repo},t.inProgress=!1,t.error=null,t.loaded=!1,t.isInstalled=this.isInstalledVersion(this.selectedExtension,t),t.isInstalled&&(e[t.source_repo].isInstalled=!0),t.pay_link&&(t.requiresPayment=!0,t.paidAmount=t.cost_sats,t.payment_hash=this.getPaylinkHash(t.pay_link)),e[t.source_repo].releases.push(t),e),{})}catch(t){LNbits.utils.notifyApiError(t),e.inProgress=!1}},canShowManageExtensionButton(e){return this.g.user.admin||!0===e?.isWasm&&!0===e?.isInstalled},canManageExtensionPermissions(e=this.selectedExtension){return!0===e?.isWasm&&!0===e?.isInstalled},canShowAdminManageTabs(){return!0===this.g.user.admin},resetManagedExtensionPermissions(){this.managedExtensionPermissions={loading:!1,extensionPermissions:[],userPermissions:{},savingExtensionPermissions:!1,savingKey:"",deletingKey:""}},async loadManagedExtensionPermissions(e=this.selectedExtension){if(this.canManageExtensionPermissions(e)){this.managedExtensionPermissions.loading=!0;try{const{data:t}=await LNbits.api.request("GET",`/api/v1/extension/${e.id}/permissions`);this.managedExtensionPermissions.extensionPermissions=this.cloneEditableExtensionPermissions(t.extension_permissions||[]),this.managedExtensionPermissions.userPermissions=this.cloneUserPermissions(t.user_permissions||{})}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.managedExtensionPermissions.loading=!1}}},cloneEditableExtensionPermissions(e){return(e||[]).filter(e=>e&&"object"==typeof e).map(e=>({...e,policies:Array.isArray(e.policies)?e.policies.map(t=>this.cloneEditablePermissionPolicy(e.id,t)):e.policies}))},cloneEditablePermissionPolicy(e,t){if(!t||"object"!=typeof t||Array.isArray(t))return t;const s=Object.entries(t).reduce((e,[t,s])=>({...e,[t]:Array.isArray(s)?s.slice():s}),{});return"ext.storage.append_public"===e&&(s.max_rows_per_source=this.maxRowsPerSourceValue(s.max_rows_per_source,1e4)),"websocket.publish"===e&&(s.max_messages_per_second=Number(s.max_messages_per_second)),s},maxRowsPerSourceValue(e,t){const s=Number(e);return!Number.isInteger(s)||s<=0?t:Math.min(s,1e6)},extensionPermissionLimitError(e){const t=(e||[]).find(e=>"ext.storage.append_public"===e?.id);if(!t||!Array.isArray(t.policies))return this.websocketPublishLimitError(e);for(const e of t.policies){if(!e||"object"!=typeof e)continue;const t=Number(e.max_rows_per_source);if(!Number.isInteger(t)||t<=0)return"Max rows per source must be a positive integer.";if(t>1e6)return"Max rows per source cannot exceed 1000000."}return this.websocketPublishLimitError(e)},websocketPublishLimitError(e){const t=(e||[]).find(e=>"websocket.publish"===e?.id);if(!t)return"";if(!Array.isArray(t.policies)||1!==t.policies.length)return"Websocket publish requires a max messages per second policy.";const s=t.policies[0];if(!s||"object"!=typeof s)return"Websocket publish requires a max messages per second policy.";const a=Number(s.max_messages_per_second);return!Number.isInteger(a)||a<=0?"Max messages per second must be a positive integer.":a>100?"Max messages per second cannot exceed 100.":""},validateExtensionPermissionLimits(e){const t=this.extensionPermissionLimitError(e);return!t||(Quasar.Notify.create({type:"negative",message:t}),!1)},extensionPermissionsHaveEditableLimits:e=>(e||[]).some(e=>"ext.storage.append_public"===e?.id&&Array.isArray(e.policies)&&e.policies.length>0||"websocket.publish"===e?.id),async saveManagedExtensionPermissions(){const e=this.managedExtensionPermissions.extensionPermissions;if(this.validateExtensionPermissionLimits(e)){this.managedExtensionPermissions.savingExtensionPermissions=!0;try{const{data:t}=await LNbits.api.request("PUT",`/api/v1/extension/${this.selectedExtension.id}/permissions`,this.g.user.wallets[0].adminkey,{permissions:this.cloneEditableExtensionPermissions(e)});this.managedExtensionPermissions.extensionPermissions=this.cloneEditableExtensionPermissions(t.extension_permissions||[]),Quasar.Notify.create({type:"positive",message:"Permission updated."})}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.managedExtensionPermissions.savingExtensionPermissions=!1}}},cloneUserPermissions(e){const t={};return Object.entries(e||{}).forEach(([e,s])=>{Array.isArray(s)&&(t[e]=s.filter(e=>e&&"object"==typeof e).map(e=>({...e,_original:{...e}})))}),t},async showExtensionDetails(e,t){if(t){this.selectedExtension=this.extensions.find(t=>t.id===e)||this.selectedExtension,this.selectedExtensionDetails=null,this.selectedExtensionDetailsDescription="",this.showExtensionDetailsDialog=!0,this.slide=0,this.fullscreen=!1;try{const{data:s}=await LNbits.api.request("GET",`/api/v1/extension/${e}/details?details_link=${t}`);this.selectedExtensionDetails=s,this.selectedExtensionDetailsDescription=this.extensionDescriptionDocument(s.description_md)}catch(e){console.warn(e)}}},extensionDescriptionDocument(e){const t="string"==typeof e?e:"",s=LNbits.utils.convertMarkdown(t),a=(new DOMParser).parseFromString(s,"text/html");a.body.querySelectorAll("applet, base, embed, form, frame, iframe, link, meta, object, portal, script").forEach(e=>e.remove()),a.body.querySelectorAll("*").forEach(e=>{for(const t of[...e.attributes]){const s=t.name.toLowerCase();(s.startsWith("on")||"srcdoc"===s||"xlink:href"===s)&&e.removeAttribute(t.name)}}),a.body.querySelectorAll("a[href], area[href]").forEach(e=>{try{const t=new URL(e.getAttribute("href"),window.location.origin);if(!["http:","https:"].includes(t.protocol)||t.username||t.password)return void e.removeAttribute("href");e.setAttribute("href",t.href),e.setAttribute("target","_blank"),e.setAttribute("rel","noopener noreferrer")}catch(t){e.removeAttribute("href")}});return`<!doctype html>\n <html>\n <head>\n <meta charset="utf-8">\n <meta http-equiv="Content-Security-Policy" content="${["default-src 'none'","img-src https: data:","style-src 'unsafe-inline'","script-src 'none'","script-src-attr 'none'","base-uri 'none'","form-action 'none'","frame-src 'none'","object-src 'none'"].join("; ")}">\n <meta name="referrer" content="no-referrer">\n <meta name="viewport" content="width=device-width, initial-scale=1">\n <style>\n :root { color-scheme: light dark; font-family: Roboto, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }\n body { margin: 0; color: CanvasText; background: Canvas; line-height: 1.5; overflow-wrap: anywhere; }\n img { max-width: 100%; height: auto; }\n pre { overflow: auto; padding: 0.75rem; background: color-mix(in srgb, CanvasText 8%, Canvas); }\n code { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; }\n table { display: block; max-width: 100%; overflow-x: auto; border-collapse: collapse; }\n th, td { padding: 0.35rem 0.6rem; border: 1px solid color-mix(in srgb, CanvasText 20%, Canvas); }\n a[href] { color: LinkText; cursor: pointer; }\n </style>\n </head>\n <body>\n ${a.body.innerHTML}\n </body>\n </html>`},async payAndInstall(e){try{if(null===await this.resolveExtensionPermissionGrant(e))return;this.selectedExtension.inProgress=!0,this.showManageExtensionDialog=!1;const t=await this.requestPaymentForInstall(this.selectedExtension.id,e);this.rememberPaylinkHash(e.pay_link,t.payment_hash);const s=this.g.user.wallets.find(t=>t.id===e.wallet),{data:a}=await LNbits.api.payInvoice(s,t.payment_request);e.payment_hash=a.payment_hash,await this.installExtension(e)}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.selectedExtension.inProgress=!1}},async payAndEnable(e){try{const t=await this.requestPaymentForEnable(e.id,e.payToEnable.paidAmount),s=this.g.user.wallets.find(t=>t.id===e.payToEnable.paymentWallet),{data:a}=await LNbits.api.payInvoice(s,t.payment_request);this.enableExtension(e),this.showPayToEnableDialog=!1}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async showInstallQRCode(e){if(null!==await this.resolveExtensionPermissionGrant(e)){this.selectedRelease=e,this.showManageExtensionDialog=!0;try{const t=await this.requestPaymentForInstall(this.selectedExtension.id,e);this.selectedRelease.paymentRequest=t.payment_request,this.selectedRelease.payment_hash=t.payment_hash,this.selectedRelease=_.clone(this.selectedRelease),this.rememberPaylinkHash(this.selectedRelease.pay_link,this.selectedRelease.payment_hash),this.subscribeToPaylinkWs(this.selectedRelease.pay_link,t.payment_hash)}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}}},async showEnableQRCode(e){try{e.payToEnable.showQRCode=!0,this.selectedExtension=_.clone(e);const t=await this.requestPaymentForEnable(e.id,e.payToEnable.paidAmount);e.payToEnable.paymentRequest=t.payment_request,this.selectedExtension=_.clone(e);const s=new URL(window.location);s.protocol="https:"===s.protocol?"wss":"ws",s.pathname=`/api/v1/ws/${t.payment_hash}`;const a=new WebSocket(s);a.addEventListener("message",async({data:t})=>{!1===JSON.parse(t).pending&&(Quasar.Notify.create({type:"positive",message:"Invoice Paid!"}),this.enableExtension(e),a.close())})}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async requestPaymentForInstall(e,t){const{data:s}=await LNbits.api.request("PUT",`/api/v1/extension/${e}/invoice/install`,null,{ext_id:e,archive:t.archive,source_repo:t.source_repo,cost_sats:t.paidAmount,version:t.version});return s},async requestPaymentForEnable(e,t){const{data:s}=await LNbits.api.request("PUT",`/api/v1/extension/${e}/invoice/enable`,null,{amount:t});return s},clearHangingInvoice(e){this.forgetPaylinkHash(e.pay_link),e.payment_hash=null},rememberPaylinkHash(e,t){this.$q.localStorage.set(`lnbits.extensions.paylink.${e}`,t)},getPaylinkHash(e){return this.$q.localStorage.getItem(`lnbits.extensions.paylink.${e}`)},forgetPaylinkHash(e){this.$q.localStorage.remove(`lnbits.extensions.paylink.${e}`)},subscribeToPaylinkWs(e,t){const s=new URL(`${e}/${t}`);s.protocol="https:"===s.protocol?"wss":"ws",this.paylinkWebsocket=new WebSocket(s),this.paylinkWebsocket.addEventListener("message",async({data:e})=>{JSON.parse(e).paid?(Quasar.Notify.create({type:"positive",message:"Invoice Paid!"}),this.installExtension(this.selectedRelease)):Quasar.Notify.create({type:"warning",message:"Invoice tracking lost!"})})},unsubscribeFromPaylinkWs(){try{this.paylinkWebsocket&&this.paylinkWebsocket.close()}catch(e){console.warn(e)}},hasNewVersion(e){if(e.installedRelease&&e.latestRelease)return e.installedRelease.version!==e.latestRelease.version},isInstalledVersion(e,t){if(e.installedRelease)return e.installedRelease.source_repo===t.source_repo&&e.installedRelease.version===t.version},getReleaseIcon:e=>e.is_version_compatible?e.isInstalled?"download_done":"download":"block",getReleaseIconColor:e=>e.is_version_compatible?e.isInstalled?"text-green":"":"text-red",extensionOpenUrl:e=>e.isWasm?`/ext/${e.id}`:`/${e.id}`,permissionLabelById(e){const t=`extension_permission_${String(e).replace(/[^A-Za-z0-9]/g,"_")}`,s=this.$t(t);return s===t?e:s},walletName(e){const t=(this.g.user.wallets||[]).find(t=>t.id===e);return t?t.name||t.id:e},userPermissionRowCaption:e=>`${e.walletName} (${e.walletId.slice(0,8)}...)`,isBackgroundPaymentPermission:e=>"wallet.pay_invoice_background"===e.permissionId,userPermissionGrantPayload(e){return{wallet_id:e.walletId,max_amount:this.positiveInteger(e.grant.max_amount,0),destination_policy:this.backgroundPaymentDestinationPolicy(e.grant.destination_policy)}},positiveInteger(e,t){const s=Number(e);return!Number.isFinite(s)||s<=0?t:Math.floor(s)},backgroundPaymentDestinationPolicy:e=>"external_allowed"===e?"external_allowed":"own_wallets_only",backgroundPaymentGrantIncreased(e,t){const s=e.grant._original||{},a=this.positiveInteger(s.max_amount,0),i=this.backgroundPaymentDestinationPolicy(s.destination_policy);return t.max_amount>a||"own_wallets_only"===i&&"external_allowed"===t.destination_policy},confirmUserPermissionIncrease:()=>new Promise(e=>{let t=!1;const s=s=>{t||(t=!0,e(s))};LNbits.utils.confirmDialog("This increases what the extension can do with this wallet. Continue?").onOk(()=>s(!0)).onCancel(()=>s(!1)).onDismiss(()=>s(!1))}),async saveUserPermissionGrant(e){if(!this.isBackgroundPaymentPermission(e))return;const t=this.userPermissionGrantPayload(e);if(t.max_amount){if(!this.backgroundPaymentGrantIncreased(e,t)||await this.confirmUserPermissionIncrease()){this.managedExtensionPermissions.savingKey=e.key;try{await LNbits.api.request("POST",`/api/v1/extension/${this.selectedExtension.id}/permissions/background-payment`,null,t),Quasar.Notify.create({type:"positive",message:"Permission updated."}),await this.loadManagedExtensionPermissions()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.managedExtensionPermissions.savingKey=""}}}else Quasar.Notify.create({type:"negative",message:"Max payment amount must be greater than zero."})},deleteUserPermissionGrant(e){LNbits.utils.confirmDialog("Remove this permission grant?").onOk(async()=>{this.managedExtensionPermissions.deletingKey=e.key;try{const t=encodeURIComponent(e.grantId);await LNbits.api.request("DELETE",`/api/v1/extension/${this.selectedExtension.id}/permissions/user/${t}`),Quasar.Notify.create({type:"positive",message:"Permission removed."}),await this.loadManagedExtensionPermissions()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.managedExtensionPermissions.deletingKey=""}})},async getGitHubReleaseDetails(e){if(!e.is_github_release||e.loaded)return;const[t,s]=e.source_repo.split("/");e.inProgress=!0;try{const{data:a}=await LNbits.api.request("GET",`/api/v1/extension/release/${t}/${s}/${e.version}`);e.loaded=!0,e.is_version_compatible=a.is_version_compatible,e.min_lnbits_version=a.min_lnbits_version,e.warning=a.warning,e.extension_type=a.extension_type,e.permissions=a.permissions||[]}catch(t){console.warn(t),e.error=t,LNbits.utils.notifyApiError(t)}finally{e.inProgress=!1}},async resolveExtensionPermissionGrant(e){const t=this.extensionPermissionsForRelease(e);if(!this.releaseRequiresPermissionGrant(e)||!t.length)return[];if(e.grantedPermissions)return e.grantedPermissions;const s=await this.confirmExtensionPermissions(t);return s?(e.grantedPermissions=s,s):null},extensionPermissionsForRelease(e){return e.permissions||this.selectedExtension?.permissions||[]},releaseRequiresPermissionGrant(e){return"wasm"===e.extension_type||!0===this.selectedExtension?.isWasm},confirmExtensionPermissions(e){return new Promise(t=>{this.selectedRelease=null,this.permissionGrant={show:!0,permissions:this.cloneEditableExtensionPermissions(e),resolve:t},this.showManageExtensionDialog=!0})},grantExtensionPermissions(){this.validateExtensionPermissionLimits(this.permissionGrant.permissions)&&this.resolveExtensionPermissionDialog(this.cloneEditableExtensionPermissions(this.permissionGrant.permissions))},cancelExtensionPermissions(){this.resolveExtensionPermissionDialog(null)},onManageExtensionDialogHide(){this.permissionGrant.show&&this.resolveExtensionPermissionDialog(null)},resolveExtensionPermissionDialog(e){const t=this.permissionGrant.resolve;this.permissionGrant={show:!1,permissions:[],resolve:null},this.showManageExtensionDialog=!1,t&&t(e)},permissionGrantHasHighRisk(){return window.LNbitsExtensionPermissions.hasHighRisk({permissions:this.permissionGrant.permissions,extensions:this.extensions,translate:e=>this.$t(e)})},async selectAllUpdatableExtensionss(){this.updatableExtensions.forEach(e=>e.selectedForUpdate=!0)},async updateSelectedExtensions(){let e=0;for(const t of this.updatableExtensions)try{if(!t.selectedForUpdate)continue;if(t.isWasm){Quasar.Notify.create({type:"warning",message:`Skipping ${t.id}; this extension update requires permission approval.`});continue}t.inProgress=!0,await LNbits.api.request("POST","/api/v1/extension",null,{ext_id:t.id,archive:t.latestRelease.archive,source_repo:t.latestRelease.source_repo,payment_hash:t.latestRelease.payment_hash,version:t.latestRelease.version}),e++,t.isAvailable=!0,t.isInstalled=!0,t.isUpgraded=!0,t.inProgress=!1,t.installedRelease=t.latestRelease,t.isActive=!0,this.toggleExtension(t)}catch(e){console.warn(e),Quasar.Notify.create({type:"negative",message:`Failed to update ${t.id}!`})}finally{t.inProgress=!1}Quasar.Notify.create({type:e?"positive":"warning",message:`${e||"No"} extensions updated!`}),this.showUpdateAllDialog=!1},formatAvg(e){const t=Number(e||0);return Math.round(t/2/100*2)/2},async loadReviewStats(){if(this.reviewsUrl)try{const{data:e}=await LNbits.api.request("GET","/api/v1/extension/reviews/tags"),t={};e.forEach(e=>{t[e.tag]=e}),this.extensions.forEach(e=>{e.reviewStats=t[e.id]||null}),this.filterExtensions(this.searchTerm,this.tab)}catch(e){console.warn(e)}else console.info("Extension reviews are not configured")},async openReviews(e){const t=e||(this.selectedExtensionDetails?this.extensions.find(e=>e.id===this.selectedExtensionDetails.id):null);t&&(this.reviewsUrl?(this.reviewsDialog.extension=t,this.selectedExtension=e,this.reviewsDialog.show=!0,await this.getTagReviews()):Quasar.Notify.create({type:"warning",message:this.$t("reviews_url_not_configured")}))},async getTagReviews(e){if(this.reviewsUrl)try{this.reviewsTable.loading=!0;const t=LNbits.utils.prepareFilterQuery(this.reviewsTable,e),{data:s}=await LNbits.api.request("GET",`/api/v1/extension/reviews/${this.selectedExtension.id}?${t}`);this.reviews=s.data,this.reviewsTable.pagination.rowsNumber=s.total}catch(e){LNbits.utils.notifyApiError(e)}finally{this.reviewsTable.loading=!1}else Quasar.Notify.create({type:"warning",message:this.$t("reviews_url_not_configured")})},formatReviewDate(e){if(!e)return"";const t=Number(e);return Number.isNaN(t)?this.utils.formatDate(e):this.utils.formatTimestamp(t)},async submitReview(){if(this.reviewsDialog.extension&&this.reviewsUrl){this.reviewsDialog.submitting=!0;try{const e={tag:this.reviewsDialog.extension.id,name:this.reviewsDialog.form.name,rating:100*this.reviewsDialog.form.rating,comment:this.reviewsDialog.form.comment},{data:t}=await LNbits.api.request("PUT","/api/v1/extension/reviews",null,e);t.payment_request?this.openInvoiceDialog(t.payment_request,t.payment_hash):(Quasar.Notify.create({type:"positive",message:"Review submitted"}),this.resetReviewForm(),await this.getTagReviews(),await this.loadReviewStats())}catch(e){LNbits.utils.notifyApiError(e)}finally{this.reviewsDialog.submitting=!1}}},openInvoiceDialog(e,t){this.paymentDialog.invoice=e,this.paymentDialog.hash=t,this.paymentDialog.show=!0,this.listenForPayment(t)},resetReviewForm(){this.reviewsDialog.form={name:"",rating:0,comment:""},this.paymentDialog={show:!1,invoice:"",hash:""}},listenForPayment(e){try{const t=new URL(this.reviewsUrl);t.protocol="https:"===t.protocol?"wss:":"ws:",t.pathname=`/api/v1/ws/${e}`;const s=new WebSocket(t);s.addEventListener("message",async()=>{Quasar.Notify.create({type:"positive",message:this.$t("reviews_invoice_paid")}),this.paymentDialog.show=!1,this.resetReviewForm(),setTimeout(async()=>{await this.getTagReviews()},1e3),await this.loadReviewStats(),s.close()})}catch(e){console.warn(e)}},async fetchAllExtensions(){try{const{data:e}=await LNbits.api.request("GET","/api/v1/extension/all");return e.forEach(e=>{e.categories?.forEach(e=>this.categories.add(e))}),e}catch(e){return console.warn(e),LNbits.utils.notifyApiError(e),[]}}},async created(){this.extensions=await this.fetchAllExtensions(),this.extbuilderEnabled=this.g.user.admin||this.g.settings.extBuilder,this.reviewsUrl=this.g.settings.extensionsReviewsUrl,0===this.g.user.extensions.length&&(this.tab="all");const e=window.location.hash.replace("#",""),t=this.extensions.find(t=>t.id===e);t&&(this.searchTerm=t.id,t.isInstalled&&(this.tab="installed")),this.updatableExtensions=this.extensions.filter(e=>this.hasNewVersion(e)),await this.loadReviewStats(),this.filterExtensions(this.searchTerm,this.tab)}},window.PageFirstInstall={template:"#page-first-install",data:()=>({loginData:{isPwd:!0,isPwdRepeat:!0,username:"",password:"",passwordRepeat:"",firstInstallToken:""}}),computed:{checkPasswordsMatch(){return this.loginData.password!==this.loginData.passwordRepeat}},methods:{setPassword(){LNbits.api.request("PUT","/api/v1/auth/first_install",null,{username:this.loginData.username,password:this.loginData.password,password_repeat:this.loginData.passwordRepeat,first_install_token:this.loginData.firstInstallToken}).then(async()=>{const e=await LNbits.api.getAuthUser();this.g.user=LNbits.map.user(e.data),this.g.isPublicPage=!1,this.$router.push("/admin")}).catch(this.utils.notifyApiError)}},created(){const e=new URLSearchParams(window.location.search);this.loginData.firstInstallToken=e.get("token")||""}},window.PagePayments={template:"#page-payments",data:()=>({payments:[],dailyChartData:[],searchDate:{from:null,to:null},searchData:{wallet_id:null,payment_hash:null,memo:null,internal_memo:null},statusFilters:{success:!0,pending:!0,failed:!0,incoming:!0,outgoing:!0},chartData:{showPaymentStatus:!0,showPaymentTags:!0,showBalance:!0,showWalletsSize:!1,showBalanceInOut:!1,showPaymentCountInOut:!1},searchOptions:{status:[]},paymentsTable:{columns:[{name:"status",align:"left",label:"Status",field:"status",sortable:!1},{name:"created_at",align:"left",label:"Created At",field:"created_at",sortable:!0},{name:"amount",align:"right",label:"Amount",field:"amount",sortable:!0},{name:"amountFiat",align:"right",label:"Fiat",field:"amountFiat",sortable:!1},{name:"fee_sats",align:"left",label:"Fee",field:"fee_sats",sortable:!0},{name:"tag",align:"left",label:"Tag",field:"tag",sortable:!1},{name:"memo",align:"left",label:"Memo",field:"memo",sortable:!1,max_length:20},{name:"internal_memo",align:"left",label:"Internal Memo",field:"internal_memo",sortable:!1,max_length:20},{name:"wallet_id",align:"left",label:"Wallet (ID)",field:"wallet_id",sortable:!1},{name:"payment_hash",align:"left",label:"Payment Hash",field:"payment_hash",sortable:!1}],pagination:{sortBy:"created_at",rowsPerPage:25,page:1,descending:!0,rowsNumber:10},search:null,hideEmpty:!0,loading:!1},chartsReady:!1,showDetails:!1,paymentDetails:null,lnbitsBalance:0}),async mounted(){this.chartsReady=!0,await this.$nextTick(),this.initCharts(),await this.fetchPayments()},computed:{},methods:{async fetchPayments(e){const t=Object.entries(this.searchData).reduce((e,[t,s])=>s?(e[t]=s,e):e,{});delete t["time[ge]"],delete t["time[le]"],this.searchDate.from&&(t["time[ge]"]=this.searchDate.from+"T00:00:00"),this.searchDate.to&&(t["time[le]"]=this.searchDate.to+"T23:59:59"),this.paymentsTable.filter=t;try{const t=LNbits.utils.prepareFilterQuery(this.paymentsTable,e),{data:s}=await LNbits.api.request("GET",`/api/v1/payments/all/paginated?${t}`);this.paymentsTable.pagination.rowsNumber=s.total,this.payments=s.data.map(e=>(e.extra&&e.extra.tag&&(e.tag=e.extra.tag),e.timeFrom=moment.utc(e.created_at).local().fromNow(),e.outgoing=e.amount<0,e.amount=new Intl.NumberFormat(this.g.locale).format(e.amount/1e3)+" sats",e.extra?.wallet_fiat_amount&&(e.amountFiat=this.formatCurrency(e.extra.wallet_fiat_amount,e.extra.wallet_fiat_currency)),e.extra?.internal_memo&&(e.internal_memo=e.extra.internal_memo),e.fee_sats=new Intl.NumberFormat(this.g.locale).format(e.fee/1e3)+" sats",e))}catch(e){console.error(e),LNbits.utils.notifyApiError(e)}finally{this.updateCharts(e)}},async searchPaymentsBy(e,t){e&&(this.searchData[e]=t),await this.fetchPayments()},clearDateSeach(){this.searchDate={from:null,to:null},delete this.paymentsTable.filter["time[ge]"],delete this.paymentsTable.filter["time[le]"],this.fetchPayments()},searchByDate(){"string"==typeof this.searchDate&&(this.searchDate={from:this.searchDate,to:this.searchDate}),this.searchDate.from&&(this.paymentsTable.filter["time[ge]"]=this.searchDate.from+"T00:00:00"),this.searchDate.to&&(this.paymentsTable.filter["time[le]"]=this.searchDate.to+"T23:59:59"),this.fetchPayments()},handleFilterChanged(){const{success:e,pending:t,failed:s,incoming:a,outgoing:i}=this.statusFilters;delete this.searchData["status[ne]"],delete this.searchData["status[eq]"],e&&t&&s||(e&&t?this.searchData["status[ne]"]="failed":e&&s?this.searchData["status[ne]"]="pending":s&&t?this.searchData["status[ne]"]="success":e?this.searchData["status[eq]"]="success":t?this.searchData["status[eq]"]="pending":s&&(this.searchData["status[eq]"]="failed")),delete this.searchData["amount[ge]"],delete this.searchData["amount[le]"],a&&i||(a?this.searchData["amount[ge]"]="0":i&&(this.searchData["amount[le]"]="0")),this.fetchPayments()},showDetailsToggle(e){return this.paymentDetails=e,this.showDetails=!this.showDetails},formatCurrency(e,t){try{return LNbits.utils.formatCurrency(e,t)}catch(t){return console.error(t),`${e} ???`}},shortify:(e,t=10)=>(valueLength=(e||"").length,valueLength<=t?e:`${e.substring(0,5)}...${e.substring(valueLength-5,valueLength)}`),async updateCharts(e){let t=LNbits.utils.prepareFilterQuery(this.paymentsTable,e);try{const{data:e}=await LNbits.api.request("GET",`/api/v1/payments/stats/count?${t}&count_by=status`);e.sort((e,t)=>e.field-t.field).reverse(),this.searchOptions.status=e.map(e=>e.field),this.paymentsStatusChart.data.datasets[0].data=e.map(e=>e.total),this.paymentsStatusChart.data.labels=[...this.searchOptions.status],this.paymentsStatusChart.update()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}try{const{data:e}=await LNbits.api.request("GET",`/api/v1/payments/stats/wallets?${t}`),s=e.map(e=>e.balance/e.payments_count),a=Math.min(...s),i=Math.max(...s),n=e=>Math.floor(3+22*(e-a)/(i-a)),o=this.randomColors(20),r=e.map((e,t)=>({data:[{x:e.payments_count,y:e.balance,r:n(Math.max(e.balance/e.payments_count,5))}],label:e.wallet_name,wallet_id:e.wallet_id,backgroundColor:o[t%100],hoverOffset:4}));this.paymentsWalletsChart.data.datasets=r,this.paymentsWalletsChart.update()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}try{const{data:e}=await LNbits.api.request("GET",`/api/v1/payments/stats/count?${t}&count_by=tag`);this.searchOptions.tag=e.map(e=>e.field),this.searchOptions.status.sort(),this.paymentsTagsChart.data.datasets[0].data=e.map(e=>e.total),this.paymentsTagsChart.data.labels=e.map(e=>e.field||"core"),this.paymentsTagsChart.update()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}try{const t=Object.entries(this.searchData).reduce((e,[t,s])=>s?(e[t]=s,e):e,{}),s={...this.paymentsTable,filter:t},a=LNbits.utils.prepareFilterQuery(s,e);let{data:i}=await LNbits.api.request("GET",`/api/v1/payments/stats/daily?${a}`);const n=this.searchDate.from+"T00:00:00",o=this.searchDate.to+"T23:59:59";this.lnbitsBalance=i.length?i[i.length-1].balance:0,i=i.filter(e=>this.searchDate.from&&this.searchDate.to?e.date>=n&&e.date<=o:this.searchDate.from?e.date>=n:!this.searchDate.to||e.date<=o),this.paymentsDailyChart.data.datasets=[{label:"Balance",data:i.map(e=>e.balance),pointStyle:!1,borderWidth:2,tension:.7,fill:1},{label:"Fees",data:i.map(e=>e.fee),pointStyle:!1,borderWidth:1,tension:.4,fill:1}],this.paymentsDailyChart.data.labels=i.map(e=>e.date.substring(0,10)),this.paymentsDailyChart.update(),this.paymentsBalanceInOutChart.data.datasets=[{label:"Incoming Payments Balance",data:i.map(e=>e.balance_in)},{label:"Outgoing Payments Balance",data:i.map(e=>e.balance_out)}],this.paymentsBalanceInOutChart.data.labels=i.map(e=>e.date.substring(0,10)),this.paymentsBalanceInOutChart.update(),this.paymentsCountInOutChart.data.datasets=[{label:"Incoming Payments Count",data:i.map(e=>e.count_in)},{label:"Outgoing Payments Count",data:i.map(e=>-e.count_out)}],this.paymentsCountInOutChart.data.labels=i.map(e=>e.date.substring(0,10)),this.paymentsCountInOutChart.update()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async initCharts(){const e=this.$q.localStorage.getItem("lnbits.payments.chartData")||{};this.chartData={...this.chartData,...e},this.chartsReady?(this.paymentsStatusChart=new Chart(this.$refs.paymentsStatusChart.getContext("2d"),{type:"doughnut",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchPaymentsBy("status",s.data.labels[e])}}},data:{datasets:[{label:"",data:[],backgroundColor:["rgb(0, 205, 86)","rgb(64, 72, 78)","rgb(255, 99, 132)"],hoverOffset:4}]}}),this.paymentsWalletsChart=new Chart(this.$refs.paymentsWalletsChart.getContext("2d"),{type:"bubble",options:{responsive:!0,maintainAspectRatio:!1,plugins:{legend:{display:!1},title:{display:!1}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].datasetIndex;this.searchPaymentsBy("wallet_id",s.data.datasets[e].wallet_id)}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(20),hoverOffset:4}]}}),this.paymentsTagsChart=new Chart(this.$refs.paymentsTagsChart.getContext("2d"),{type:"pie",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!1,title:{display:!1,text:"Tags"}}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchPaymentsBy("tag",s.data.labels[e])}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(10),hoverOffset:4}]}}),this.paymentsDailyChart=new Chart(this.$refs.paymentsDailyChart.getContext("2d"),{type:"line",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!0,title:{display:!1,text:"Tags"}}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(10),hoverOffset:4}]}}),this.paymentsBalanceInOutChart=new Chart(this.$refs.paymentsBalanceInOutChart.getContext("2d"),{type:"bar",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!0,title:{display:!1,text:"Tags"}}},scales:{x:{stacked:!0},y:{stacked:!0}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(50),hoverOffset:4}]}}),this.paymentsCountInOutChart=new Chart(this.$refs.paymentsCountInOutChart.getContext("2d"),{type:"bar",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!0,title:{display:!1,text:""}}},scales:{x:{stacked:!0},y:{stacked:!0}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(80),hoverOffset:4}]}})):console.warn("Charts are not ready yet. Initialization delayed.")},saveChartsPreferences(){this.$q.localStorage.set("lnbits.payments.chartData",this.chartData)},randomColors(e=1){const t=[];for(let s=1;s<=10;s++)for(let a=1;a<=10;a++)t.push(`rgb(${a*e*33%200}, ${71*(s+a+e)%255}, ${(s+30*e)%255})`);return t}}},window.PageNode={template:"#page-node",config:{globalProperties:{LNbits:LNbits,msg:"hello"}},data(){return{isSuperUser:!1,wallet:{},tab:"dashboard",payments:1e3,info:{},phoenixd:{capabilities:[]},phoenixdAmount:2e6,phoenixdEstimate:null,phoenixdReceive:"",phoenixdResult:"",phoenixdDialog:{show:!1,operation:"",data:{}},phoenixdBusy:!1,channel_stats:{},channels:{data:[],filter:""},activeBalance:{},ranks:{},peers:{data:[],filter:""},connectPeerDialog:{show:!1,data:{}},setFeeDialog:{show:!1,data:{fee_ppm:0,fee_base_msat:0}},openChannelDialog:{show:!1,data:{}},closeChannelDialog:{show:!1,data:{}},nodeInfoDialog:{show:!1,data:{}},transactionDetailsDialog:{show:!1,data:{}},states:[{label:"Active",value:"active",color:"green"},{label:"Pending",value:"pending",color:"orange"},{label:"Inactive",value:"inactive",color:"grey"},{label:"Closed",value:"closed",color:"red"}],stateFilters:[{label:"Active",value:"active"},{label:"Pending",value:"pending"}],paymentsTable:{data:[],columns:[{name:"pending",label:""},{name:"date",align:"left",label:this.$t("date"),field:"date",sortable:!0},{name:"sat",align:"right",label:this.$t("amount"),field:e=>this.formatMsat(e.amount),sortable:!0},{name:"fee",align:"right",label:this.$t("fee"),field:"fee"},{name:"destination",align:"right",label:"Destination",field:"destination"},{name:"memo",align:"left",label:this.$t("memo"),field:"memo"}],pagination:{rowsPerPage:10,page:1,rowsNumber:10},filter:null},invoiceTable:{data:[],columns:[{name:"pending",label:""},{name:"paid_at",field:"paid_at",align:"left",label:"Paid at",sortable:!0},{name:"expiry",label:this.$t("expiry"),field:"expiry",align:"left",sortable:!0},{name:"amount",label:this.$t("amount"),field:e=>this.formatMsat(e.amount),sortable:!0},{name:"memo",align:"left",label:this.$t("memo"),field:"memo"}],pagination:{rowsPerPage:10,page:1,rowsNumber:10},filter:null}}},created(){this.getInfo()},watch:{tab(e){"transactions"!==e||this.paymentsTable.data.length?"channels"!==e||this.channels.data.length||(this.getChannels(),this.managedChannels||this.getPeers()):(this.getPayments(),this.getInvoices())}},computed:{managedChannels(){return!0===this.info.managed_channels},canManage(){return!0===this.g.user?.super_user},checkChanges(){return!_.isEqual(this.settings,this.formData)},filteredChannels(){return this.stateFilters?this.channels.data.filter(e=>this.stateFilters.find(({value:t})=>t==e.state)):this.channels.data},totalBalance(){return this.filteredChannels.reduce((e,t)=>(e.local_msat+=t.balance.local_msat,e.remote_msat+=t.balance.remote_msat,e.total_msat+=t.balance.total_msat,e),{local_msat:0,remote_msat:0,total_msat:0})}},methods:{hasPhoenixdCapability(e){return this.phoenixd.capabilities.includes(e)},getPhoenixdStatus(){return this.nodeApi("GET","/phoenixd/status").then(e=>{this.phoenixd=e.data}).catch(()=>{})},estimatePhoenixdLiquidity(){return this.phoenixdEstimate=null,this.nodeApi("GET","/phoenixd/liquidity-fees",{query:{amount_sat:this.phoenixdAmount}}).then(e=>{this.phoenixdEstimate=e.data}).catch(()=>{})},getPhoenixdReceive(e){return this.phoenixdReceive="",this.nodeApi("GET",`/phoenixd/receive/${e}`).then(e=>{this.phoenixdReceive=e.data.value}).catch(()=>{})},showPhoenixdDialog(e,t={}){this.phoenixdDialog={show:!0,operation:e,data:{...t}},this.phoenixdResult=""},submitPhoenixd(){const{operation:e,data:t}=this.phoenixdDialog,s={close:`Close channel ${t.channel_id} and send its remaining balance to ${t.address} at ${t.fee_rate} sat/vB?`,send:`Withdraw ${t.amount_sat} sats to ${t.address} at ${t.fee_rate} sat/vB?`,bump:`Spend node funds to bump the funding transaction fee to a target of ${t.fee_rate} sat/vB?`};LNbits.utils.confirmDialog(s[e]+" This spends funds backing LNbits wallets and cannot be undone.").onOk(async()=>{this.phoenixdBusy=!0;try{const s=await this.nodeApi("POST",`/phoenixd/${e}`,{data:t});this.phoenixdResult=s.data.txid,this.phoenixdDialog.show=!1,await this.getInfo(),await this.getChannels()}catch(e){}finally{this.phoenixdBusy=!1}})},exportPhoenixdHistory(){this.nodeApi("POST","/phoenixd/export").then(e=>{Quasar.Notify.create({message:e.data.message})}).catch(()=>{})},formatMsat:e=>LNbits.utils.formatMsat(e),nodeApi(e,t,s){const a=new URLSearchParams(s?.query);return LNbits.api.request(e,`/node/api/v1${t}?${a}`,{},s?.data).catch(e=>{throw LNbits.utils.notifyApiError(e),e})},getChannel(e){return this.nodeApi("GET",`/channels/${e}`).then(e=>{this.setFeeDialog.data.fee_ppm=e.data.fee_ppm,this.setFeeDialog.data.fee_base_msat=e.data.fee_base_msat})},getChannels(){return this.nodeApi("GET","/channels").then(e=>{this.channels.data=e.data})},getInfo(){return this.nodeApi("GET","/info").then(e=>{const t=this.managedChannels;this.info=e.data,this.channel_stats=e.data.channel_stats,this.managedChannels?(this.getPhoenixdStatus(),t||(this.stateFilters=null)):this.get1MLStats()}).catch(()=>{this.info={},this.channel_stats={}})},get1MLStats(){return this.nodeApi("GET","/rank").then(e=>{this.ranks=e.data}).catch(()=>{this.ranks={}})},getPayments(e){e&&(this.paymentsTable.pagination=e.pagination);let t=this.paymentsTable.pagination;const s={limit:t.rowsPerPage,offset:(t.page-1)*t.rowsPerPage??0};return this.nodeApi("GET","/payments",{query:s}).then(e=>{this.paymentsTable.data=e.data.data,this.paymentsTable.pagination.rowsNumber=e.data.total})},getInvoices(e){e&&(this.invoiceTable.pagination=e.pagination);let t=this.invoiceTable.pagination;const s={limit:t.rowsPerPage,offset:(t.page-1)*t.rowsPerPage??0};return this.nodeApi("GET","/invoices",{query:s}).then(e=>{this.invoiceTable.data=e.data.data,this.invoiceTable.pagination.rowsNumber=e.data.total})},getPeers(){return this.nodeApi("GET","/peers").then(e=>{this.peers.data=e.data})},connectPeer(){this.nodeApi("POST","/peers",{data:this.connectPeerDialog.data}).then(()=>{this.connectPeerDialog.show=!1,this.getPeers()})},disconnectPeer(e){LNbits.utils.confirmDialog("Do you really wanna disconnect this peer?").onOk(()=>{this.nodeApi("DELETE",`/peers/${e}`).then(e=>{Quasar.Notify.create({message:"Disconnected",icon:null}),this.needsRestart=!0,this.getPeers()})})},setChannelFee(e){this.nodeApi("PUT",`/channels/${e}`,{data:this.setFeeDialog.data}).then(e=>{this.setFeeDialog.show=!1,this.getChannels()}).catch(LNbits.utils.notifyApiError)},openChannel(){this.nodeApi("POST","/channels",{data:this.openChannelDialog.data}).then(e=>{this.openChannelDialog.show=!1,this.getChannels()}).catch(e=>{console.log(e)})},showCloseChannelDialog(e){this.managedChannels?this.showPhoenixdDialog("close",{channel_id:e.id}):(this.closeChannelDialog.show=!0,this.closeChannelDialog.data={force:!1,short_id:e.short_id,...e.point})},closeChannel(){this.nodeApi("DELETE","/channels",{query:this.closeChannelDialog.data}).then(e=>{this.closeChannelDialog.show=!1,this.getChannels()})},showSetFeeDialog(e){this.setFeeDialog.show=!0,this.setFeeDialog.channel_id=e,this.getChannel(e)},showOpenChannelDialog(e){this.openChannelDialog.show=!0,this.openChannelDialog.data={peer_id:e,funding_amount:0}},showNodeInfoDialog(e){this.nodeInfoDialog.show=!0,this.nodeInfoDialog.data=e},showTransactionDetailsDialog(e){this.transactionDetailsDialog.show=!0,this.transactionDetailsDialog.data=e},shortenNodeId:e=>e?e.substring(0,5)+"..."+e.substring(e.length-5):"..."}},window.PageNodePublic={template:"#page-node-public",data:()=>({enabled:!1,isSuperUser:!1,wallet:{},tab:"dashboard",payments:1e3,info:{},channel_stats:{},channels:[],activeBalance:{},ranks:{},peers:[],connectPeerDialog:{show:!1,data:{}},openChannelDialog:{show:!1,data:{}},closeChannelDialog:{show:!1,data:{}},nodeInfoDialog:{show:!1,data:{}},states:[{label:"Active",value:"active",color:"green"},{label:"Pending",value:"pending",color:"orange"},{label:"Inactive",value:"inactive",color:"grey"},{label:"Closed",value:"closed",color:"red"}]}),created(){this.getInfo()},methods:{formatMsat:e=>LNbits.utils.formatMsat(e),api:(e,t,s)=>LNbits.api.request(e,"/node/public/api/v1"+t,{},s),getInfo(){this.api("GET","/info",{}).then(e=>{this.info=e.data,this.channel_stats=e.data.channel_stats,this.enabled=!0,this.info.managed_channels||this.get1MLStats()}).catch(()=>{this.info={},this.channel_stats={}})},get1MLStats(){this.api("GET","/rank",{}).then(e=>{this.ranks=e.data}).catch(()=>{this.ranks={}})}}},window.PageAudit={template:"#page-audit",data:()=>({chartsReady:!1,auditEntries:[],searchData:{user_id:"",ip_address:"",request_type:"",component:"",request_method:"",response_code:"",path:""},searchOptions:{component:[],request_method:[],response_code:[]},auditTable:{columns:[{name:"created_at",align:"center",label:"Date",field:"created_at",sortable:!0},{name:"duration",align:"left",label:"Duration (sec)",field:"duration",sortable:!0},{name:"component",align:"left",label:"Component",field:"component",sortable:!1},{name:"request_method",align:"left",label:"Method",field:"request_method",sortable:!1},{name:"response_code",align:"left",label:"Code",field:"response_code",sortable:!1},{name:"user_id",align:"left",label:"User Id",field:"user_id",sortable:!1},{name:"ip_address",align:"left",label:"IP Address",field:"ip_address",sortable:!1},{name:"path",align:"left",label:"Path",field:"path",sortable:!1}],pagination:{sortBy:"created_at",rowsPerPage:10,page:1,descending:!0,rowsNumber:10},search:null,hideEmpty:!0,loading:!1},auditDetailsDialog:{data:null,show:!1}}),async created(){},async mounted(){this.chartsReady=!0,await this.$nextTick(),this.initCharts(),await this.fetchAudit()},methods:{async fetchAudit(e){try{const t=LNbits.utils.prepareFilterQuery(this.auditTable,e),{data:s}=await LNbits.api.request("GET",`/audit/api/v1?${t}`);this.auditTable.pagination.rowsNumber=s.total,this.auditEntries=s.data,await this.fetchAuditStats(e)}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.auditTable.loading=!1}},async fetchAuditStats(e){try{const t=LNbits.utils.prepareFilterQuery(this.auditTable,e),{data:s}=await LNbits.api.request("GET",`/audit/api/v1/stats?${t}`),a=s.request_method.map(e=>e.field);this.searchOptions.request_method=[...new Set(this.searchOptions.request_method.concat(a))],this.requestMethodChart.data.labels=a,this.requestMethodChart.data.datasets[0].data=s.request_method.map(e=>e.total),this.requestMethodChart.update();const i=s.response_code.map(e=>e.field);this.searchOptions.response_code=[...new Set(this.searchOptions.response_code.concat(i))],this.responseCodeChart.data.labels=i,this.responseCodeChart.data.datasets[0].data=s.response_code.map(e=>e.total),this.responseCodeChart.update();const n=s.component.map(e=>e.field);this.searchOptions.component=[...new Set(this.searchOptions.component.concat(n))],this.componentUseChart.data.labels=n,this.componentUseChart.data.datasets[0].data=s.component.map(e=>e.total),this.componentUseChart.update(),this.longDurationChart.data.labels=s.long_duration.map(e=>e.field),this.longDurationChart.data.datasets[0].data=s.long_duration.map(e=>e.total),this.longDurationChart.update()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async searchAuditBy(e,t){e&&(this.searchData[e]=t),this.auditTable.filter=Object.entries(this.searchData).reduce((e,[t,s])=>s?(e[t]=s,e):e,{}),await this.fetchAudit()},showDetailsDialog(e){const t=JSON.parse(e?.request_details||"");try{t.body&&(t.body=JSON.parse(t.body))}catch(e){}this.auditDetailsDialog.data=JSON.stringify(t,null,4),this.auditDetailsDialog.show=!0},shortify:e=>(valueLength=(e||"").length,valueLength<=10?e:`${e.substring(0,5)}...${e.substring(valueLength-5,valueLength)}`),async initCharts(){this.chartsReady?(this.responseCodeChart=new Chart(this.$refs.responseCodeChart.getContext("2d"),{type:"doughnut",options:{responsive:!0,plugins:{legend:{position:"bottom"},title:{display:!1,text:"HTTP Response Codes"}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchAuditBy("response_code",s.data.labels[e])}}},data:{datasets:[{label:"",data:[20,10],backgroundColor:["rgb(100, 99, 200)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)"]}],labels:[]}}),this.requestMethodChart=new Chart(this.$refs.requestMethodChart.getContext("2d"),{type:"bar",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchAuditBy("request_method",s.data.labels[e])}}},data:{datasets:[{label:"",data:[],backgroundColor:["rgb(255, 99, 132)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)"],hoverOffset:4}]}}),this.componentUseChart=new Chart(this.$refs.componentUseChart.getContext("2d"),{type:"pie",options:{responsive:!0,plugins:{legend:{position:"xxx"},title:{display:!1,text:"Components"}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchAuditBy("component",s.data.labels[e])}}},data:{datasets:[{data:[],backgroundColor:["rgb(255, 99, 132)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)","rgb(100, 205, 250)","rgb(120, 205, 250)","rgb(140, 205, 250)","rgb(160, 205, 250)"],hoverOffset:4}]}}),this.longDurationChart=new Chart(this.$refs.longDurationChart.getContext("2d"),{type:"bar",options:{responsive:!0,indexAxis:"y",maintainAspectRatio:!1,plugins:{legend:{title:{display:!1,text:"Long Duration"}}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchAuditBy("path",s.data.labels[e])}}},data:{datasets:[{label:"",data:[],backgroundColor:["rgb(255, 99, 132)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)","rgb(100, 205, 250)","rgb(120, 205, 250)","rgb(140, 205, 250)","rgb(160, 205, 250)"],hoverOffset:4}]}})):console.warn("Charts are not ready yet. Initialization delayed.")}}},window.PageWallet={template:"#page-wallet",data:()=>({parse:{show:!1,invoice:null,lnurlpay:null,lnurlauth:null,sending:!1,decoding:!1,decodeId:0,data:{request:"",amount:0,comment:"",memo:"",internalMemo:null,unit:"sat"},paymentChecker:null,copy:{show:!1},camera:{show:!1,camera:"auto"}},receive:{show:!1,status:"pending",paymentReq:null,paymentHash:null,amountMsat:null,minMax:[0,21e14],lnurl:null,units:[],unit:"sat",fiatProvider:"",data:{amount:null,memo:"",internalMemo:null,payment_hash:null}},update:{name:null,currency:null},hasNfc:!1,nfcReaderAbortController:null,formattedFiatAmount:0,totalBreakdown:{show:!1,loading:!1,rows:[],selectedTypes:["bitcoin","fiat"],selectedTags:[]},paymentFilter:{"status[ne]":"failed"},chartConfig:Quasar.LocalStorage.getItem("lnbits.wallets.chartConfig")||{showPaymentInOutChart:!0,showBalanceChart:!0,showBalanceInOutChart:!0}}),computed:{isFiatWallet(){return"fiat"===this.g.wallet.walletType},isCashPayment(){return this.isFiatWallet&&"cash"===this.receive.fiatProvider},bolt12AmountMissing(){return!(!this.parse.invoice||!this.parse.invoice.isBolt12Offer||Number(this.parse.data.amount)>0)},canPay(){return!!this.parse.invoice&&(this.parse.invoice.expired?(Quasar.Notify.create({message:"Invoice has expired",color:"negative"}),!1):this.parse.invoice.isBolt12Offer?!!this.bolt12AmountMissing||Number(this.parse.data.amount)<=this.g.wallet.sat:this.parse.invoice.sat<=this.g.wallet.sat)},lnurlpayInfo(){const e=this.parse.lnurlpay;if(!e)return{};const t={domain:e.callback.split("/")[2],fixed:e.minSendable===e.maxSendable};try{JSON.parse(e.metadata).forEach(([e,s])=>{"text/plain"===e?t.description=s:"image/png;base64"===e||"image/jpeg;base64"===e?t.image=`data:${e},${s}`:"text/identifier"!==e&&"text/email"!==e||(t.targetUser=s)})}catch{}return t},formattedAmount(){return this.isFiatWallet?LNbits.utils.formatCurrency(this.receive.data.amount,this.receive.unit):"sat"==this.receive.unit&&this.g.isSatsDenomination?LNbits.utils.formatMsat(this.receive.amountMsat)+" sat":LNbits.utils.formatCurrency(Number(this.receive.data.amount).toFixed(2),this.g.isSatsDenomination?this.receive.unit:this.g.denomination)},formattedSatAmount(){return LNbits.utils.formatMsat(this.receive.amountMsat)+" sat"},totalBreakdownTags(){const e=this.totalBreakdown.rows.map(e=>e.tag||null);return[...new Set(e)].sort((e,t)=>this.totalBreakdownTagLabel(e).localeCompare(this.totalBreakdownTagLabel(t)))},hasFiatTotalBreakdown(){return this.totalBreakdown.rows.some(e=>e.is_fiat)},selectedTotalBreakdownRows(){return this.totalBreakdown.rows.filter(e=>{const t=e.is_fiat?"fiat":"bitcoin";return this.totalBreakdown.selectedTypes.includes(t)&&this.totalBreakdown.selectedTags.includes(this.totalBreakdownTagKey(e.tag))})},selectedTotalBreakdownMsat(){return this.selectedTotalBreakdownRows.reduce((e,t)=>e+t.total,0)},selectedTotalBreakdownSat(){return Math.round(this.selectedTotalBreakdownMsat/1e3)},selectedTotalBreakdownCount(){return this.selectedTotalBreakdownRows.reduce((e,t)=>e+t.payments_count,0)},formattedTotalBreakdown(){return this.utils.formatBalance(this.selectedTotalBreakdownSat,this.g.denomination)},formattedTotalBreakdownFiat(){if(!this.g.fiatTracking)return null;const e=this.selectedTotalBreakdownSat/1e8*this.g.exchangeRate;return LNbits.utils.formatCurrency(e,this.g.wallet.currency)},primaryTotalBreakdownValue(){return this.g.isFiatPriority&&this.g.fiatTracking&&this.formattedTotalBreakdownFiat||this.formattedTotalBreakdown},secondaryTotalBreakdownValue(){return this.g.fiatTracking?this.g.isFiatPriority?this.formattedTotalBreakdown:this.formattedTotalBreakdownFiat:null}},methods:{showWalletTotalBreakdown(){this.totalBreakdown.show=!0,this.totalBreakdown.rows.length||this.fetchTotalBreakdown()},fetchTotalBreakdown(){this.totalBreakdown.loading=!0,LNbits.api.getPaymentTotalBreakdown(this.g.wallet).then(e=>{this.totalBreakdown.rows=e.data,this.totalBreakdown.selectedTypes=["bitcoin","fiat"],this.totalBreakdown.selectedTags=this.totalBreakdownTags.map(this.totalBreakdownTagKey),this.totalBreakdown.loading=!1}).catch(e=>{this.totalBreakdown.loading=!1,LNbits.utils.notifyApiError(e)})},totalBreakdownTagLabel:e=>e||"No tag",totalBreakdownTagKey:e=>e||"__untagged__",totalBreakdownTagCount(e){return this.totalBreakdown.rows.filter(t=>(t.tag||null)===e).reduce((e,t)=>e+t.payments_count,0)},totalBreakdownTagMsat(e){return this.totalBreakdown.rows.filter(t=>(t.tag||null)===e).reduce((e,t)=>e+t.total,0)},formatTotalBreakdownMsat(e){return this.utils.formatBalance(Math.round(e/1e3),this.g.denomination)},handleSendLnurl(e){this.parse.data.request=e,this.parse.show=!0,this.lnurlScan()},msatoshiFormat:e=>LNbits.utils.formatSat(e/1e3),showReceiveDialog(){this.receive.show=!0,this.receive.status="pending",this.receive.paymentReq=null,this.receive.paymentHash=null,this.receive.fiatPaymentReq=null,this.receive.fiatProvider=this.isFiatWallet?"cash":"",this.receive.data.amount=null,this.receive.data.memo=null,this.receive.data.internalMemo=null,this.receive.data.payment_hash=null,this.receive.units=[...this.isFiatWallet?[]:["sat"],...this.g.allowedCurrencies.length>0?this.g.allowedCurrencies:this.g.currencies],this.receive.unit=this.g.isFiatPriority&&this.g.wallet.currency||"sat",this.isFiatWallet&&(this.receive.unit=this.receive.units.includes(this.g.wallet.currency)?this.g.wallet.currency:this.receive.units[0]),this.receive.minMax=[0,21e14],this.receive.lnurl=null,this.receive.lnurlWithdraw=null},onReceiveDialogHide(){this.hasNfc&&this.nfcReaderAbortController?.abort()},showParseDialog(){this.parse.show=!0,this.parse.invoice=null,this.parse.lnurlpay=null,this.parse.lnurlauth=null,this.parse.copy.show=window.isSecureContext&&void 0!==navigator.clipboard?.readText,this.parse.data.request="",this.parse.data.comment="",this.parse.data.amount=0,this.parse.data.internalMemo=null,this.parse.data.memo="",this.parse.sending=!1,this.parse.data.paymentChecker=null,this.parse.camera.show=!1},closeParseDialog(){this.parse.decodeId++,this.parse.decoding=!1,setTimeout(()=>{clearInterval(this.parse.paymentChecker)},1e4)},handleBalanceUpdate(e){this.g.wallet.sat=this.g.wallet.sat+e},createInvoice(){if("loading"===this.receive.status)return;this.receive.status="loading",this.isFiatWallet||this.g.isSatsDenomination||(this.receive.data.amount=100*this.receive.data.amount);const e=this.isCashPayment;(e?LNbits.api.request("POST","/api/v1/fiat/cash",this.g.wallet.adminkey,{amount:this.receive.data.amount,unit:this.receive.unit,memo:this.receive.data.memo,internal_memo:this.receive.data.internalMemo}):LNbits.api.createInvoice(this.g.wallet,this.receive.data.amount,this.receive.data.memo,this.receive.unit,this.receive.lnurlWithdraw,this.receive.fiatProvider,this.receive.data.internalMemo,this.receive.data.payment_hash)).then(t=>{if(this.g.updatePayments=!this.g.updatePayments,this.receive.status="success",e)return this.receive.show=!1,void Quasar.Notify.create({type:"positive",message:"Cash payment validated."});if(this.receive.paymentReq=t.data.bolt11,this.receive.fiatPaymentReq=t.data.extra?.fiat_payment_request,this.receive.amountMsat=t.data.amount,this.receive.paymentHash=t.data.payment_hash,this.isFiatWallet||this.receive.lnurl||this.readNfcTag(),this.receive.lnurl&&null!==t.data.extra?.lnurl_response){!1===t.data.extra.lnurl_response&&(t.data.extra.lnurl_response="Unable to connect");const e=this.receive.lnurl.callback.split("/")[2];if("string"==typeof t.data.extra.lnurl_response)return void Quasar.Notify.create({timeout:5e3,type:"warning",message:`${e} lnurl-withdraw call failed.`,caption:t.data.extra.lnurl_response});!0===t.data.extra.lnurl_response&&Quasar.Notify.create({timeout:3e3,message:`Invoice sent to ${e}!`,spinner:!0})}}).catch(e=>{LNbits.utils.notifyApiError(e),this.receive.status="pending"})},lnurlScan(){LNbits.api.request("POST","/api/v1/lnurlscan",this.g.wallet.adminkey,{lnurl:this.parse.data.request}).then(e=>{const t=e.data;if("ERROR"!==t.status){if("payRequest"===t.tag)this.parse.lnurlpay=Object.freeze(t),this.parse.data.amount=t.minSendable/1e3,this.receive.units=["sats",...this.g.allowedCurrencies.length>0?this.g.allowedCurrencies:this.g.currencies];else if("login"===t.tag)this.parse.lnurlauth=Object.freeze(t);else if("withdrawRequest"===t.tag){this.parse.show=!1,this.receive.show=!0,this.receive.lnurlWithdraw=Object.freeze(t),this.receive.status="pending",this.receive.paymentReq=null,this.receive.paymentHash=null,this.receive.data.amount=t.maxWithdrawable/1e3,this.receive.data.memo=t.defaultDescription,this.receive.minMax=[t.minWithdrawable/1e3,t.maxWithdrawable/1e3];const e=t.callback.split("/")[2];this.receive.lnurl={domain:e,callback:t.callback,fixed:t.fixed}}}else Quasar.Notify.create({timeout:5e3,type:"warning",message:"lnurl scan failed.",caption:t.reason})}).catch(e=>{LNbits.utils.notifyApiError(e)})},decodeQR(e){this.parse.data.request=e,this.decodeRequest(),this.parse.camera.show=!1},isLnurl:e=>e.toLowerCase().startsWith("lnurl1")||e.startsWith("lnurlp://")||e.startsWith("lnurlw://")||e.startsWith("lnurlauth://")||e.match(/[\w.+-~_]+@[\w.+-~_]/),isBolt12Offer:e=>(e||"").trim().toLowerCase().startsWith("lno1"),async decodeRequest(){if(this.parse.decoding)return;this.parse.show=!0,this.parse.data.request=this.parse.data.request.trim();const e=this.parse.data.request.toLowerCase();if(e.startsWith("lightning:")?(this.parse.data.request=this.parse.data.request.slice(10),this.parse.data.request.startsWith("//")&&(this.parse.data.request=this.parse.data.request.slice(2))):e.startsWith("lnurl:")?this.parse.data.request=this.parse.data.request.slice(6):e.includes("lightning=lnurl1")&&(this.parse.data.request=this.parse.data.request.split("lightning=")[1].split("&")[0]),this.isLnurl(this.parse.data.request))return void this.lnurlScan();if(this.isBolt12Offer(this.parse.data.request)){const e=this.parse.data.request.trim().split("?")[0].split("#")[0];this.parse.data.request=e,this.parse.data.amount=0,this.parse.invoice=null,this.parse.decoding=!0;const t=++this.parse.decodeId;try{const{data:s}=await LNbits.api.request("post","/api/v1/payments/decode",null,{data:e});if(t!==this.parse.decodeId||!this.parse.show)return;const a=null==s.currency&&Number.isSafeInteger(s.amount)&&s.amount>0&&s.amount%1e3==0?s.amount/1e3:0;this.parse.data.request=s.offer,this.parse.data.amount=a,this.parse.invoice=Object.freeze({msat:null==s.currency?s.amount:null,sat:a,fsat:"offer",bolt11:s.offer,description:s.description,hash:null,isBolt12Offer:!0,expired:!1})}catch(e){t===this.parse.decodeId&&this.parse.show&&Quasar.Notify.create({type:"warning",message:e.response?.data?.message||e.message})}finally{t===this.parse.decodeId&&(this.parse.decoding=!1)}return}let t;this.parse.data.request.toLowerCase().includes("lightning")&&(this.parse.data.request=this.parse.data.request.split("lightning=")[1],this.parse.data.request.includes("&")&&(this.parse.data.request=this.parse.data.request.split("&")[0]));try{t=decode(this.parse.data.request)}catch(e){return Quasar.Notify.create({timeout:3e3,type:"warning",message:e+".",caption:"400 BAD REQUEST"}),void(this.parse.show=!1)}let s={msat:t.human_readable_part.amount,sat:t.human_readable_part.amount/1e3,fsat:LNbits.utils.formatSat(t.human_readable_part.amount/1e3),bolt11:this.parse.data.request};_.each(t.data.tags,e=>{if(_.isObject(e)&&_.has(e,"description"))if("payment_hash"===e.description)s.hash=e.value;else if("description"===e.description)s.description=e.value;else if("expiry"===e.description){const a=new Date(1e3*(t.data.time_stamp+e.value)),i=new Date(1e3*t.data.time_stamp);s.expireDate=Quasar.date.formatDate(a,"YYYY-MM-DDTHH:mm:ss.SSSZ"),s.createdDate=Quasar.date.formatDate(i,"YYYY-MM-DDTHH:mm:ss.SSSZ"),s.expireDateFrom=moment.utc(a).local().fromNow(),s.createdDateFrom=moment.utc(i).local().fromNow(),s.expired=!1}}),this.g.wallet.currency&&(s.fiatAmount=LNbits.utils.formatCurrency((s.sat/1e8*this.g.exchangeRate).toFixed(2),this.g.wallet.currency)),this.parse.invoice=Object.freeze(s)},payInvoice(){if(this.parse.sending)return;if(this.parse.invoice?.isBolt12Offer&&!(Number(this.parse.data.amount)>0))return;this.parse.sending=!0;const e=Quasar.Notify.create({timeout:0,message:this.$t("payment_processing")}),t=this.parse.invoice.isBolt12Offer?this.parse.data.amount:null;LNbits.api.payInvoice(this.g.wallet,this.parse.data.request,this.parse.data.internalMemo,t,this.parse.invoice.isBolt12Offer?this.parse.data.memo:null).then(t=>{this.parse.sending=!1,e(),this.g.updatePayments=!this.g.updatePayments,this.parse.show=!1,"success"==t.data.status&&Quasar.Notify.create({type:"positive",message:this.$t("payment_successful")}),"pending"==t.data.status&&Quasar.Notify.create({type:"info",message:this.$t("payment_pending")})}).catch(t=>{this.parse.sending=!1,e(),LNbits.utils.notifyApiError(t),this.g.updatePayments=!this.g.updatePayments})},payLnurl(){this.parse.sending||(this.parse.sending=!0,LNbits.api.request("post","/api/v1/payments/lnurl",this.g.wallet.adminkey,{res:this.parse.lnurlpay,lnurl:this.parse.data.request,unit:this.parse.data.unit,amount:1e3*this.parse.data.amount,comment:this.parse.data.comment,internalMemo:this.parse.data.internalMemo}).then(e=>{if(this.parse.sending=!1,this.parse.show=!1,e.data.extra.success_action){const t=JSON.parse(e.data.extra.success_action);switch(t.tag){case"url":Quasar.Notify.create({message:t.url,caption:t.description,html:!1,type:"positive",timeout:0,closeBtn:!0,actions:[{label:"Open link",color:"white",handler:()=>this.utils.openUrlInNewTab(t.url)}]});break;case"message":Quasar.Notify.create({message:t.message,type:"positive",timeout:0,closeBtn:!0});break;case"aes":this.utils.decryptLnurlPayAES(t,e.data.preimage).then(e=>{Quasar.Notify.create({message:e,caption:t.description,html:!1,type:"positive",timeout:0,closeBtn:!0})}).catch(e=>{Quasar.Notify.create({message:t.description||"Payment successful.",caption:"Could not decrypt success action.",html:!1,type:"warning",timeout:0,closeBtn:!0})})}}}).catch(e=>{this.parse.sending=!1,LNbits.utils.notifyApiError(e)}))},authLnurl(){const e=Quasar.Notify.create({timeout:10,message:"Performing authentication..."});LNbits.api.request("post","/api/v1/lnurlauth",wallet.adminkey,this.parse.lnurlauth).then(t=>{e(),Quasar.Notify.create({message:"Authentication successful.",type:"positive",timeout:3500}),this.parse.show=!1}).catch(e=>{e.response.data.reason?Quasar.Notify.create({message:`Authentication failed. ${this.parse.lnurlauth.callback} says:`,caption:e.response.data.reason,type:"warning",timeout:5e3}):LNbits.utils.notifyApiError(e)})},updateWallet(e){LNbits.api.request("PATCH","/api/v1/wallet",this.g.wallet.adminkey,e).then(e=>{const t={...e.data};t.lightning_address&&(t.lightningAddress=t.lightning_address,t.lightningAddressFull=`${t.lightning_address}@${window.location.host}`),this.g.wallet={...this.g.wallet,...t};const s=this.g.user.wallets.findIndex(t=>t.id===e.data.id);-1!==s&&(this.g.user.wallets[s]={...this.g.user.wallets[s],...t}),Quasar.Notify.create({message:"Wallet updated.",type:"positive",timeout:3500})}).catch(e=>{LNbits.utils.notifyApiError(e)})},pasteToTextArea(){this.$refs.textArea.focus(),navigator.clipboard.readText().then(e=>{this.parse.data.request=e.trim()})},readNfcTag(){try{if("undefined"==typeof NDEFReader)return void console.debug("NFC not supported on this device or browser.");const e=new NDEFReader;this.nfcReaderAbortController=new AbortController,this.nfcReaderAbortController.signal.onabort=e=>{console.debug("All NFC Read operations have been aborted.")},this.hasNfc=!0;const t=Quasar.Notify.create({message:"Tap your NFC tag to pay this invoice with LNURLw."});return e.scan({signal:this.nfcReaderAbortController.signal}).then(()=>{e.onreadingerror=()=>{Quasar.Notify.create({type:"negative",message:"There was an error reading this NFC tag."})},e.onreading=({message:e})=>{const s=new TextDecoder("utf-8"),a=e.records.find(e=>-1!==s.decode(e.data).toUpperCase().indexOf("LNURLW"));if(a){t(),Quasar.Notify.create({type:"positive",message:"NFC tag read successfully."});const e=s.decode(a.data);this.payInvoiceWithNfc(e)}else Quasar.Notify.create({type:"warning",message:"NFC tag does not have LNURLw record."})}})}catch(e){Quasar.Notify.create({type:"negative",message:e?e.toString():"An unexpected error has occurred."})}},payInvoiceWithNfc(e){const t=Quasar.Notify.create({timeout:0,spinner:!0,message:this.$t("payment_processing")});LNbits.api.request("POST",`/api/v1/payments/${this.receive.paymentReq}/pay-with-nfc`,this.g.wallet.adminkey,{lnurl_w:e}).then(e=>{t(),e.data.success?Quasar.Notify.create({type:"positive",message:"Payment successful"}):Quasar.Notify.create({type:"negative",message:e.data.detail||"Payment failed"})}).catch(e=>{t(),LNbits.utils.notifyApiError(e)})}},created(){const e=new URLSearchParams(window.location.search),t=this.g.user.wallets.find(e=>e.id===this.$route.params.id);t?(this.g.wallet=t,this.g.lastActiveWallet=t.id,this.$q.localStorage.setItem("lnbits.lastActiveWallet",t.id),this.$router.replace(`/wallet/${t.id}`).then(()=>{(e.has("lightning")||e.has("lnurl"))&&(this.parse.data.request=e.get("lightning")||e.get("lnurl"),this.decodeRequest(),this.parse.show=!0)})):(this.g.errorCode=404,this.g.errorMessage="Wallet not found.",this.$router.push("/error"))},watch:{"g.updatePaymentsHash"(){this.receive.show=!1},"g.updatePayments"(){this.parse.show=!1,this.g.wallet.currency&&this.$q.localStorage.getItem("lnbits.exchangeRate."+this.g.wallet.currency)&&(this.g.exchangeRate=this.$q.localStorage.getItem("lnbits.exchangeRate."+this.g.wallet.currency),this.g.fiatBalance=this.g.exchangeRate/1e8*this.g.wallet.sat)},"g.wallet"(){this.g.wallet.currency?(this.g.fiatTracking=!0,this.g.fiatBalance=this.g.exchangeRate/1e8*this.g.wallet.sat):(this.g.fiatBalance=0,this.g.fiatTracking=!1)},"g.isFiatPriority"(){this.receive.unit=this.g.isFiatPriority?this.g.wallet.currency:"sat"},"g.fiatBalance"(){this.formattedFiatAmount=LNbits.utils.formatCurrency(this.g.fiatBalance.toFixed(2),this.g.wallet.currency)},"g.exchangeRate"(){this.g.fiatTracking&&this.g.wallet.currency&&(this.g.fiatBalance=this.g.exchangeRate/1e8*this.g.wallet.sat)}}},window.PageWallets={template:"#page-wallets",data:()=>({user:null,tab:"wallets",wallets:[],addWalletDialog:{show:!1},walletsTable:{columns:[{name:"name",align:"left",label:"Name",field:"name",sortable:!0},{name:"currency",align:"center",label:"Currency",field:"currency",sortable:!0},{name:"updated_at",align:"right",label:"Last Updated",field:"updated_at",sortable:!0}],pagination:{sortBy:"updated_at",rowsPerPage:12,page:1,descending:!0,rowsNumber:10},search:"",hideEmpty:!0,loading:!1}}),watch:{"walletsTable.search":{handler(){const e={};this.walletsTable.search&&(e.search=this.walletsTable.search),this.getUserWallets()}}},methods:{async getUserWallets(e){try{this.walletsTable.loading=!0;const t=LNbits.utils.prepareFilterQuery(this.walletsTable,e),{data:s}=await LNbits.api.request("GET",`/api/v1/wallet/paginated?${t}`,null);this.wallets=s.data,this.walletsTable.pagination.rowsNumber=s.total}catch(e){LNbits.utils.notifyApiError(e)}finally{this.walletsTable.loading=!1}},goToWallet(e){this.$router.push({path:"/wallet",query:{wal:e}})},formattedFiatAmount:(e,t)=>LNbits.utils.formatCurrency(Number(e).toFixed(2),t),formattedSatAmount:e=>LNbits.utils.formatMsat(e)+" sat"},async created(){await this.getUserWallets()}},window.PageUsers={template:"#page-users",data(){return{paymentsWallet:{},cancel:{},users:[],wallets:[],searchData:{user:"",username:"",email:"",pubkey:""},paymentPage:{show:!1},activeWallet:{userId:null,show:!1},activeUser:{data:null,showUserId:!1,show:!1},createWalletDialog:{data:{},show:!1},lightningAddressDialog:{wallet:null,lightningAddress:"",show:!1},walletTable:{columns:[{name:"name",align:"left",label:"Name",field:"name"},{name:"id",align:"left",label:"Wallet Id",field:"id"},{name:"currency",align:"left",label:"Currency",field:"currency"},{name:"balance_msat",align:"left",label:"Balance",field:"balance_msat"}],pagination:{sortBy:"name",rowsPerPage:10,page:1,descending:!0,rowsNumber:10},search:null,hideEmpty:!0,loading:!1},usersTable:{columns:[{name:"activated",align:"left",label:this.$t("activated"),field:"activated",sortable:!1},{name:"wallet_id",align:"left",label:"Wallets",field:"wallet_id",sortable:!1},{name:"id",align:"left",label:"User Id",field:"id",sortable:!1},{name:"username",align:"left",label:"Username",field:"username",sortable:!1},{name:"email",align:"left",label:"Email",field:"email",sortable:!1},{name:"pubkey",align:"left",label:"Public Key",field:"pubkey",sortable:!1},{name:"balance_msat",align:"left",label:"Balance",field:"balance_msat",sortable:!1},{name:"transaction_count",align:"left",label:"Payments",field:"transaction_count",sortable:!1},{name:"last_payment",align:"left",label:"Last Payment",field:"last_payment",sortable:!1}],pagination:{sortBy:"created_at",rowsPerPage:10,page:1,descending:!0,rowsNumber:10},sortFields:[{name:"id",label:"User ID"},{name:"username",label:"Username"},{name:"email",label:"Email"},{name:"pubkey",label:"Public Key"},{name:"created_at",label:"Creation Date"},{name:"updated_at",label:"Last Updated"}],search:null,hideEmpty:!0,loading:!1}}},watch:{"usersTable.hideEmpty":function(e,t){this.usersTable.filter=e?{"transaction_count[gt]":0}:{},this.fetchUsers()}},created(){this.fetchUsers()},computed:{lightningAddressSuffix:()=>`@${window.location.host}`},methods:{formatSat:e=>LNbits.utils.formatSat(Math.floor(e/1e3)),backToUsersPage(){this.activeUser.show=!1,this.paymentPage.show=!1,this.activeWallet.show=!1,this.fetchUsers()},handleBalanceUpdate(){this.fetchWallets(this.activeWallet.userId)},resetPassword(e){return LNbits.api.request("PUT",`/users/api/v1/user/${e}/reset_password`).then(e=>{LNbits.utils.confirmDialog(this.$t("reset_key_generated")+" "+this.$t("reset_key_copy")).onOk(()=>{const t=window.location.origin+"?reset_key="+e.data;this.utils.copyText(t)})}).catch(LNbits.utils.notifyApiError)},sortByColumn(e){this.usersTable.pagination.sortBy===e?this.usersTable.pagination.descending=!this.usersTable.pagination.descending:(this.usersTable.pagination.sortBy=e,this.usersTable.pagination.descending=!1),this.fetchUsers()},createUser(){LNbits.api.request("POST","/users/api/v1/user",null,this.activeUser.data).then(e=>{Quasar.Notify.create({type:"positive",message:"User created!",icon:null}),this.activeUser.setPassword=!0,this.activeUser.data=e.data,this.fetchUsers()}).catch(LNbits.utils.notifyApiError)},updateUser(){LNbits.api.request("PUT",`/users/api/v1/user/${this.activeUser.data.id}`,null,this.activeUser.data).then(()=>{Quasar.Notify.create({type:"positive",message:"User updated!",icon:null}),this.activeUser.data=null,this.activeUser.show=!1,this.fetchUsers()}).catch(LNbits.utils.notifyApiError)},createWallet(){const e=this.activeWallet.userId;e?LNbits.api.request("POST",`/users/api/v1/user/${e}/wallet`,null,this.createWalletDialog.data).then(()=>{this.fetchWallets(e),Quasar.Notify.create({type:"positive",message:"Wallet created!"})}).catch(LNbits.utils.notifyApiError):Quasar.Notify.create({type:"warning",message:"No user selected!",icon:null})},deleteUser(e){LNbits.utils.confirmDialog("Are you sure you want to delete this user?").onOk(()=>{LNbits.api.request("DELETE",`/users/api/v1/user/${e}`).then(()=>{this.fetchUsers(),Quasar.Notify.create({type:"positive",message:"User deleted!",icon:null}),this.activeUser.data=null,this.activeUser.show=!1}).catch(LNbits.utils.notifyApiError)})},undeleteUserWallet(e,t){LNbits.api.request("PUT",`/users/api/v1/user/${e}/wallet/${t}/undelete`).then(()=>{this.fetchWallets(e),Quasar.Notify.create({type:"positive",message:"Undeleted user wallet!",icon:null})}).catch(LNbits.utils.notifyApiError)},deleteUserWallet(e,t,s){const a=s?"Wallet is already deleted, are you sure you want to permanently delete this user wallet?":"Are you sure you want to delete this user wallet?";LNbits.utils.confirmDialog(a).onOk(()=>{LNbits.api.request("DELETE",`/users/api/v1/user/${e}/wallet/${t}`).then(()=>{this.fetchWallets(e),Quasar.Notify.create({type:"positive",message:"User wallet deleted!",icon:null})}).catch(LNbits.utils.notifyApiError)})},deleteAllUserWallets(e){LNbits.utils.confirmDialog(this.$t("confirm_delete_all_wallets")).onOk(()=>{LNbits.api.request("DELETE",`/users/api/v1/user/${e}/wallets`).then(t=>{Quasar.Notify.create({type:"positive",message:t.data.message,icon:null}),this.fetchWallets(e)}).catch(LNbits.utils.notifyApiError)})},copyWalletLink(e){const t=`${window.location.origin}/wallet?usr=${this.activeWallet.userId}&wal=${e}`;this.utils.copyText(t)},showLightningAddressDialog(e){this.lightningAddressDialog.wallet=e,this.lightningAddressDialog.lightningAddress=e.lightning_address||"",this.lightningAddressDialog.show=!0},saveLightningAddress(){const e=this.lightningAddressDialog.wallet;e&&LNbits.api.request("PUT",`/users/api/v1/user/${e.user}/wallet/${e.id}/lightning-address`,null,{lightning_address:this.lightningAddressDialog.lightningAddress}).then(t=>{Object.assign(e,t.data),this.lightningAddressDialog.show=!1,Quasar.Notify.create({type:"positive",message:this.$t("lightning_address_updated"),icon:null})}).catch(LNbits.utils.notifyApiError)},fetchUsers(e){this.relaxFilterForFields(["username","email"]);const t=LNbits.utils.prepareFilterQuery(this.usersTable,e);LNbits.api.request("GET",`/users/api/v1/user?${t}`).then(e=>{this.usersTable.loading=!1,this.usersTable.pagination.rowsNumber=e.data.total,this.users=e.data.data}).catch(LNbits.utils.notifyApiError)},fetchWallets(e){return LNbits.api.request("GET",`/users/api/v1/user/${e}/wallet`).then(t=>{this.wallets=t.data,this.activeWallet.userId=e,this.activeWallet.show=!0}).catch(LNbits.utils.notifyApiError)},relaxFilterForFields(e=[]){e.forEach(e=>{const t=this.usersTable?.filter?.[e];t&&this.usersTable.filter[e]&&(this.usersTable.filter[`${e}[like]`]=t,delete this.usersTable.filter[e])})},updateWallet(e){LNbits.api.request("PATCH","/api/v1/wallet",e.adminkey,{name:e.name}).then(()=>{e.editable=!1,Quasar.Notify.create({message:"Wallet name updated.",type:"positive",timeout:3500})}).catch(e=>{LNbits.utils.notifyApiError(e)})},toggleAdmin(e){LNbits.api.request("PUT",`/users/api/v1/user/${e}/admin`).then(()=>{this.fetchUsers(),Quasar.Notify.create({type:"positive",message:"Toggled admin!",icon:null})}).catch(LNbits.utils.notifyApiError)},toggleUserActivated(e){LNbits.api.request("PUT",`/users/api/v1/user/${e}/activate`).then(e=>{this.fetchUsers(),Quasar.Notify.create({type:"positive",message:e.data.message,icon:null})}).catch(LNbits.utils.notifyApiError)},async showAccountPage(e){if(this.activeUser.showPassword=!1,this.activeUser.showUserId=!1,this.activeUser.setPassword=!1,!e)return this.activeUser.data={extra:{}},void(this.activeUser.show=!0);try{const{data:t}=await LNbits.api.request("GET",`/users/api/v1/user/${e}`);this.activeUser.data=t,this.activeUser.show=!0}catch(e){console.warn(e),Quasar.Notify.create({type:"warning",message:"Failed to get user!"}),this.activeUser.show=!1}},async impersonateUser(e){try{await LNbits.api.impersonateUser(e),LNbits.utils.backupLocalStorage("impersonation",!0),this.$q.localStorage.setItem("lnbits.disclaimerShown",!0),window.location="/wallet"}catch(e){console.warn(e),Quasar.Notify.create({type:"warning",message:"Failed to impersonate user!"})}},async showWalletPayments(e){this.activeUser.show=!1,await this.fetchWallets(this.users[0].id),await this.showPayments(e)},showPayments(e){this.paymentsWallet=this.wallets.find(t=>t.id===e),this.paymentPage.show=!0},searchUserBy(e){const t=this.searchData[e];this.usersTable.filter={},t&&(this.usersTable.filter[e]=t),this.fetchUsers()},shortify:e=>(valueLength=(e||"").length,valueLength<=10?e:`${e.substring(0,5)}...${e.substring(valueLength-5,valueLength)}`)}},window.PageAccount={template:"#page-account",data(){return{untouchedUser:null,hasUsername:!1,showUserId:!1,themeOptions:[{name:"bitcoin",color:"deep-orange"},{name:"classic",color:"purple"},{name:"mint",color:"green"},{name:"autumn",color:"brown"},{name:"monochrome",color:"grey"},{name:"salvador",color:"blue-10"},{name:"freedom",color:"pink-13"},{name:"cyber",color:"light-green-9"},{name:"flamingo",color:"pink-3"}],defaultSiteCustomisation:{locale:"en"},reactionOptions:["None","confettiBothSides","confettiFireworks","confettiStars","confettiTop","lightningStrike"],borderOptions:["retro-border","hard-border","neon-border","no-border"],tab:"user",credentialsData:{show:!1,oldPassword:null,newPassword:null,newPasswordRepeat:null,username:null,pubkey:null},apiAcl:{showNewAclDialog:!1,showPasswordDialog:!1,showNewTokenDialog:!1,data:[],passwordGuardedFunction:null,newAclName:"",newTokenName:"",password:"",apiToken:null,selectedTokenId:null,columns:[{name:"Name",align:"left",label:this.$t("Name"),field:"Name",sortable:!1},{name:"path",align:"left",label:this.$t("path"),field:"path",sortable:!1},{name:"read",align:"left",label:this.$t("read"),field:"read",sortable:!1},{name:"write",align:"left",label:this.$t("write"),field:"write",sortable:!1}],pagination:{rowsPerPage:100,page:1}},selectedApiAcl:{id:null,name:null,endpoints:[],token_id_list:[],allRead:!1,allWrite:!1},assets:[],assetsTable:{loading:!1,columns:[{name:"name",align:"left",label:this.$t("Name"),field:"name",sortable:!0},{name:"created_at",align:"left",label:this.$t("created_at"),field:"created_at",sortable:!0}],pagination:{rowsPerPage:6,page:1}},assetsUploadToPublic:!1,notifications:{nostr:{identifier:""}},labels:[],labelsDialog:{show:!1,data:{name:"",description:"",color:"#000000"}},labelsTable:{loading:!1,columns:[{name:"actions",align:"left"},{name:"name",align:"left",label:this.$t("Name"),field:"name",sortable:!0},{name:"description",align:"left",label:this.$t("description"),field:"description"},{name:"color",align:"left",label:this.$t("color"),field:"color"}],pagination:{rowsPerPage:6,page:1}}}},watch:{tab(e){this.$router.push(`/account#${e}`)},$route(e){e.hash.length>1&&(this.tab=e.hash.replace("#",""))},"assetsTable.search":{handler(){const e={};this.assetsTable.search&&(e.search=this.assetsTable.search),this.getUserAssets()}}},computed:{accountNavigationItems(){return[{value:"user",label:this.$t("account_settings"),description:this.$t("account_settings_description"),icon:"person"},{value:"notifications",label:this.$t("notifications"),description:this.$t("account_notifications_description"),icon:"notifications"},{value:"theme",label:this.$t("look_and_feel"),description:this.$t("look_and_feel_description"),icon:"palette"},{value:"api_acls",label:this.$t("access_control_list"),description:this.$t("access_control_list_description"),icon:"lock"},{value:"assets",label:this.$t("assets"),description:this.$t("account_assets_description"),icon:"perm_media"},{value:"labels",label:this.$t("labels"),description:this.$t("account_labels_description"),icon:"local_offer"}]},activeAccountSection(){return this.accountNavigationItems.find(e=>e.value===this.tab)||this.accountNavigationItems[0]},isUserTouched(){return!_.isEqual(this.g.user,this.untouchedUser)},selectedApiToken(){return this.selectedApiAcl.token_id_list.find(e=>e.id===this.apiAcl.selectedTokenId)},expiryAt(){return this.selectedApiToken.expires_at?`${this.$t("expiry")}: ${LNbits.utils.formatTimestamp(this.selectedApiToken.expires_at)}`:""},tokenStatus(){if(this.selectedApiToken.expires_at){const e=new Date;let t="",s="positive";return new Date(1e3*this.selectedApiToken.expires_at)<e?(t=this.$t("acl_token_expired"),s="negative"):t=this.$t("acl_token_active"),{status:t,badgeColor:s}}return""}},methods:{changeLanguage(e){window.i18n.global.locale=e,this.$q.localStorage.set("lnbits.lang",e)},async updateAccount(){try{const{data:e}=await LNbits.api.request("PATCH","/api/v1/auth",null,{user_id:this.g.user.id,username:this.g.user.username,email:this.g.user.email,extra:this.g.user.extra});this.untouchedUser=JSON.parse(JSON.stringify(this.g.user)),this.hasUsername=!!e.username,Quasar.Notify.create({type:"positive",message:"Account updated."})}catch(e){LNbits.utils.notifyApiError(e)}},disableUpdatePassword(){return!this.credentialsData.newPassword||!this.credentialsData.newPasswordRepeat||this.credentialsData.newPassword!==this.credentialsData.newPasswordRepeat},async updatePassword(){if(this.credentialsData.username)try{const{data:e}=await LNbits.api.request("PUT","/api/v1/auth/password",null,{user_id:this.g.user.id,username:this.credentialsData.username,password_old:this.credentialsData.oldPassword,password:this.credentialsData.newPassword,password_repeat:this.credentialsData.newPasswordRepeat});this.untouchedUser=JSON.parse(JSON.stringify(e)),this.hasUsername=!!e.username,this.credentialsData.show=!1,Quasar.Notify.create({type:"positive",message:"Password updated."})}catch(e){LNbits.utils.notifyApiError(e)}else Quasar.Notify.create({type:"warning",message:"Please set a username."})},async updatePubkey(){try{const{data:e}=await LNbits.api.request("PUT","/api/v1/auth/pubkey",null,{user_id:this.g.user.id,pubkey:this.credentialsData.pubkey});this.untouchedUser=JSON.parse(JSON.stringify(e)),this.hasUsername=!!e.username,this.credentialsData.show=!1,this.$q.notify({type:"positive",message:"Public key updated."})}catch(e){LNbits.utils.notifyApiError(e)}},showUpdateCredentials(){this.credentialsData={show:!0,oldPassword:null,username:this.g.user.username,pubkey:this.g.user.pubkey,newPassword:null,newPasswordRepeat:null}},selectAccountSection(e){this.tab=e,"user"===e&&(this.credentialsData.show=!1)},newApiAclDialog(){this.apiAcl.newAclName=null,this.apiAcl.showNewAclDialog=!0},newTokenAclDialog(){this.apiAcl.newTokenName=null,this.apiAcl.newTokenExpiry=null,this.apiAcl.showNewTokenDialog=!0},handleApiACLSelected(e){this.selectedApiAcl={id:null,name:null,endpoints:[],token_id_list:[]},this.apiAcl.selectedTokenId=null,e&&setTimeout(()=>{const t=this.apiAcl.data.find(t=>t.id===e);this.selectedApiAcl&&(this.selectedApiAcl={...t},this.selectedApiAcl.allRead=this.selectedApiAcl.endpoints.every(e=>e.read),this.selectedApiAcl.allWrite=this.selectedApiAcl.endpoints.every(e=>e.write))})},handleAllEndpointsReadAccess(){this.selectedApiAcl.endpoints.forEach(e=>e.read=this.selectedApiAcl.allRead)},handleAllEndpointsWriteAccess(){this.selectedApiAcl.endpoints.forEach(e=>e.write=this.selectedApiAcl.allWrite)},async getApiACLs(){try{const{data:e}=await LNbits.api.request("GET","/api/v1/auth/acl",null);this.apiAcl.data=e.access_control_list}catch(e){LNbits.utils.notifyApiError(e)}},askPasswordAndRunFunction(e){this.apiAcl.passwordGuardedFunction=e,this.apiAcl.showPasswordDialog=!0},runPasswordGuardedFunction(){this.apiAcl.showPasswordDialog=!1;const e=this.apiAcl.passwordGuardedFunction;e&&this[e]()},async addApiACL(){if(this.apiAcl.newAclName){try{const{data:e}=await LNbits.api.request("PUT","/api/v1/auth/acl",null,{id:this.apiAcl.newAclName,name:this.apiAcl.newAclName,password:this.apiAcl.password});this.apiAcl.data=e.access_control_list;const t=this.apiAcl.data.find(e=>e.name===this.apiAcl.newAclName);this.handleApiACLSelected(t.id),this.apiAcl.showNewAclDialog=!1,this.$q.notify({type:"positive",message:"Access Control List created."})}catch(e){LNbits.utils.notifyApiError(e)}finally{this.apiAcl.name="",this.apiAcl.password=""}this.apiAcl.showNewAclDialog=!1}else this.$q.notify({type:"warning",message:"Name is required."})},async updateApiACLs(){try{const{data:e}=await LNbits.api.request("PUT","/api/v1/auth/acl",null,{id:this.g.user.id,password:this.apiAcl.password,...this.selectedApiAcl});this.apiAcl.data=e.access_control_list}catch(e){LNbits.utils.notifyApiError(e)}finally{this.apiAcl.password=""}},async deleteApiACL(){if(this.selectedApiAcl.id){try{await LNbits.api.request("DELETE","/api/v1/auth/acl",null,{id:this.selectedApiAcl.id,password:this.apiAcl.password}),this.$q.notify({type:"positive",message:"Access Control List deleted."})}catch(e){LNbits.utils.notifyApiError(e)}finally{this.apiAcl.password=""}this.apiAcl.data=this.apiAcl.data.filter(e=>e.id!==this.selectedApiAcl.id),this.handleApiACLSelected(this.apiAcl.data[0]?.id)}},async generateApiToken(){if(!this.selectedApiAcl.id)return;const e=new Date(this.apiAcl.newTokenExpiry)-new Date;try{const{data:t}=await LNbits.api.request("POST","/api/v1/auth/acl/token",null,{acl_id:this.selectedApiAcl.id,token_name:this.apiAcl.newTokenName,password:this.apiAcl.password,expiration_time_minutes:Math.trunc(e/6e4)});this.apiAcl.apiToken=t.api_token,this.apiAcl.selectedTokenId=t.id,Quasar.Notify.create({type:"positive",message:"Token Generated."}),await this.getApiACLs(),this.handleApiACLSelected(this.selectedApiAcl.id),this.apiAcl.showNewTokenDialog=!1}catch(e){LNbits.utils.notifyApiError(e)}finally{this.apiAcl.password=""}},async deleteToken(){if(this.apiAcl.selectedTokenId)try{await LNbits.api.request("DELETE","/api/v1/auth/acl/token",null,{id:this.apiAcl.selectedTokenId,acl_id:this.selectedApiAcl.id,password:this.apiAcl.password}),this.$q.notify({type:"positive",message:"Token deleted."}),this.selectedApiAcl.token_id_list=this.selectedApiAcl.token_id_list.filter(e=>e.id!==this.apiAcl.selectedTokenId),this.apiAcl.selectedTokenId=null}catch(e){LNbits.utils.notifyApiError(e)}finally{this.apiAcl.password=""}},async getUserAssets(e){try{this.assetsTable.loading=!0;const t=LNbits.utils.prepareFilterQuery(this.assetsTable,e),{data:s}=await LNbits.api.request("GET",`/api/v1/assets/paginated?${t}`,null);this.assets=s.data,this.assetsTable.pagination.rowsNumber=s.total}catch(e){LNbits.utils.notifyApiError(e)}finally{this.assetsTable.loading=!1}},onImageInput(e){const t=e.target.files[0];t&&this.uploadAsset(t),e.target.value=null},onBackgroundImageInput(e){const t=e.target.files[0];t&&this.uploadBackgroundImage(t),e.target.value=null},async uploadAsset(e,{isPublic:t=this.assetsUploadToPublic,notifySuccess:s=!0}={}){const a=new FormData;a.append("file",e);try{const{data:e}=await LNbits.api.request("POST",`/api/v1/assets?public_asset=${t}`,null,a,{headers:{"Content-Type":"multipart/form-data"}});return s&&this.$q.notify({type:"positive",message:"Upload successful!",icon:null}),await this.getUserAssets(),e}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async uploadBackgroundImage(e){const t=await this.uploadAsset(e,{isPublic:!1,notifySuccess:!1});if(!t)return;const s=`${window.location.origin}/api/v1/assets/${t.id}/thumbnail`;await this.siteCustomisationChanged({bgimageChoice:s})},async deleteAsset(e){LNbits.utils.confirmDialog("Are you sure you want to delete this asset?").onOk(async()=>{try{await LNbits.api.request("DELETE",`/api/v1/assets/${e.id}`,null),this.$q.notify({type:"positive",message:"Asset deleted."}),await this.getUserAssets()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}})},async toggleAssetPublicAccess(e){try{await LNbits.api.request("PUT",`/api/v1/assets/${e.id}`,null,{is_public:!e.is_public}),this.$q.notify({type:"positive",message:"Update successful!",icon:null}),await this.getUserAssets()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},copyAssetLinkToClipboard(e){const t=`${window.location.origin}/api/v1/assets/${e.id}/data`;this.utils.copyText(t)},addUserLabel(){if(!this.labelsDialog.data.name)return void this.$q.notify({type:"warning",message:"Name is required."});if(!this.labelsDialog.data.color)return void this.$q.notify({type:"warning",message:"Color is required."});this.g.user.extra.labels=this.g.user.extra.labels||[];if(!this.g.user.extra.labels.find(e=>e.name===this.labelsDialog.data.name))return this.g.user.extra.labels.unshift({...this.labelsDialog.data}),this.labelsDialog.show=!1,!0;this.$q.notify({type:"warning",message:"A label with this name already exists."})},openAddLabelDialog(){this.labelsDialog.data={name:"",description:"",color:"#000000"},this.labelsDialog.show=!0},openEditLabelDialog(e){this.labelsDialog.data={name:e.name,description:e.description,color:e.color},this.labelsDialog.show=!0},updateUserLabel(){const e=this.labelsDialog.data,t=JSON.parse(JSON.stringify(this.g.user.extra.labels));this.g.user.extra.labels=this.g.user.extra.labels.filter(t=>t.name!==e.name);this.addUserLabel()||(this.g.user.extra.labels=t),this.labelsDialog.show=!1},deleteUserLabel(e){LNbits.utils.confirmDialog("Are you sure you want to delete this label?").onOk(()=>{this.g.user.extra.labels=this.g.user.extra.labels.filter(t=>t.name!==e.name)})},async siteCustomisationChanged(e={}){try{Object.entries(e||{}).forEach(([e,t])=>{e in this.g&&(this.g[e]=t)}),await LNbits.api.updateUiCustomization(e),this.$q.notify({type:"positive",message:"UI Customization updated."})}catch(e){LNbits.utils.notifyApiError(e)}},resetThemeDefaults(){const e={themeChoice:this.g.settings.defaultTheme,borderChoice:this.g.settings.defaultBorder,gradientChoice:this.g.settings.defaultGradient,bgimageChoice:this.g.settings.defaultBgimage||"",reactionChoice:this.g.settings.defaultReaction,darkChoice:this.g.settings.defaultDark,cardRoundedChoice:this.g.settings.defaultCardRounded,cardGradientChoice:this.g.settings.defaultCardGradient,cardShadowChoice:this.g.settings.defaultCardShadow,burgerMenuChoice:this.g.settings.defaultBurgerMenuBackground};this.siteCustomisationChanged(e)}},async created(){this.untouchedUser=JSON.parse(JSON.stringify(this.g.user)),this.hasUsername=!!this.g.user.username,this.$route.hash.length>1&&(this.tab=this.$route.hash.replace("#","")),await this.getApiACLs(),await this.getUserAssets(),this.themeOptions=this.themeOptions.filter(e=>this.g.settings.themeOptions.includes(e.name))}},window.PageAdmin={template:"#page-admin",data:()=>({tab:"funding",settings:{},formData:{lnbits_exchange_rate_providers:[],lnbits_audit_exclude_paths:[],lnbits_audit_include_paths:[],lnbits_audit_http_response_codes:[]},isSuperUser:!1,needsRestart:!1,isSaving:!1,settingsLoaded:!1,settingsSearch:""}),watch:{tab(e){if(["wasm-runtime","wasm-limit-config"].includes(e)&&this.$route.path.startsWith("/admin/extensions/wasm"))return;const t=this.adminRouteForTab(e);this.$route.fullPath!==t&&this.$router.push(t)},$route(e){const t=this.adminTabFromRoute(e);this.tab!==t&&(this.tab=t)}},async created(){this.tab=this.adminTabFromRoute(this.$route),await this.getSettings()},computed:{checkChanges(){return this.settingsLoaded&&!_.isEqual(this.settings,this.formData)},settingsNavigation:()=>[{label:"settings_money",items:[{value:"funding",label:"funding",icon:"account_balance_wallet"},{value:"server",label:"payments",icon:"price_change"},{value:"exchange_providers",label:"exchanges",icon:"show_chart"},{value:"fiat_providers",label:"fiat_providers",icon:"credit_score"}]},{label:"settings_access",items:[{value:"security",label:"security",icon:"security"},{value:"users",label:"users",icon:"group"}]},{label:"settings_system",items:[{value:"extensions",label:"extensions",icon:"extension"},{value:"notifications",label:"notifications",icon:"notifications"},{value:"audit",label:"api_watch",icon:"playlist_add_check_circle"}]},{label:"settings_appearance",items:[{value:"assets-config",label:"assets",icon:"perm_media"},{value:"site_customisation",label:"site_customisation",icon:"palette"},{value:"blockexplorer",label:"block_explorer",icon:"travel_explore"}]}],settingsNavigationItems(){return this.settingsNavigation.flatMap(e=>e.items.map(t=>({...t,label:this.$t(t.label),group:this.$t(e.label)})))},settingsSearchIndex(){const e={funding:[this.$t("wallets_management"),this.$t("funding_sources"),this.$t("routing_fee_reserve_calculations"),this.$t("payment_timeouts"),this.$t("watchdog")],server:[this.$t("currency_settings"),this.$t("payments"),this.$t("lightning_addresses"),this.$t("wallet_limiter"),this.$t("service_fees")],exchange_providers:["LNbits Price Aggregator","Bitcoin Price History",this.$t("exchange_providers")],fiat_providers:[this.$t("fiat_providers"),this.$t("api"),this.$t("webhook"),this.$t("service_fees"),this.$t("amount_limits")],security:[this.$t("server_management"),this.$t("authentication"),"Nostr Auth","Google Auth","GitHub Auth","Keycloak Auth","OIDC Auth",this.$t("security_tools"),this.$t("ip_blocker"),this.$t("rate_limiter"),this.$t("callback"),this.$t("lnurl")],users:[this.$t("user_management"),this.$t("admin_users"),this.$t("allowed_users"),this.$t("allow_creation_user")],extensions:[this.$t("extension_sources"),"Wasm Extension",this.$t("admin_extensions"),this.$t("user_default_extensions"),this.$t("extension_builder_manifest_url"),this.$t("reviews_url")],notifications:[this.$t("notifications_configure"),this.$t("notifications_nostr_config"),this.$t("notifications_telegram_config"),this.$t("notifications_email_config"),this.$t("notifications")],audit:[this.$t("audit"),this.$t("audit_record_req"),this.$t("audit_http_methods_label"),this.$t("audit_paths_label")],"assets-config":["Assets","Thumbnails","Users"],site_customisation:[this.$t("ui_management"),this.$t("ui_custom_badge_title"),this.$t("ui_custom_image"),this.$t("themes"),this.$t("ad_space_section_title")],blockexplorer:[this.$t("block_explorer"),this.$t("electrum_compatible_server")]};return this.settingsNavigationItems.flatMap(t=>(e[t.value]||[t.label]).map(e=>({tab:t.value,category:t.label,section:e,icon:t.icon,searchText:`${t.group} ${t.label} ${e}`.toLowerCase()})))},filteredSettingsSearch(){const e=(this.settingsSearch||"").toLowerCase().split(/\s+/).filter(Boolean);return e.length?this.settingsSearchIndex.filter(t=>e.every(e=>t.searchText.includes(e))).slice(0,12):[]}},methods:{adminTabFromRoute:e=>e.path.startsWith("/admin/extensions/wasm/limits")?"wasm-limit-config":e.path.startsWith("/admin/extensions/wasm")?"wasm-runtime":e.hash.length>1?e.hash.replace("#",""):"funding",adminRouteForTab:e=>"wasm-runtime"===e?"/admin/extensions/wasm":"wasm-limit-config"===e?"/admin/extensions/wasm/limits":`/admin#${e}`,selectSettingsSearchResult(e){this.tab=e.tab,this.settingsSearch="",this.$nextTick(()=>{window.setTimeout(()=>{const t=[...document.querySelectorAll(".q-tab-panel--active h6, .q-tab-panel--active strong, .q-tab-panel--active .text-subtitle1")].find(t=>t.textContent.trim().toLowerCase().includes(e.section.toLowerCase()));t?.scrollIntoView({behavior:"smooth",block:"start"})},350)})},getDefaultSetting(e){LNbits.api.getDefaultSetting(e).then(t=>{this.formData[e]=t.data.default_value})},restartServer(){LNbits.api.request("GET","/admin/api/v1/restart/").then(e=>{this.$q.notify({type:"positive",message:"Success! Restarted Server",icon:null}),this.needsRestart=!1}).catch(LNbits.utils.notifyApiError)},async getSettings(){await LNbits.api.request("GET","/admin/api/v1/settings",this.g.user.wallets[0].adminkey).then(e=>{this.isSuperUser=e.data.is_super_user||!1,this.settings=e.data,this.formData={...this.settings},this.settingsLoaded=!0}).catch(LNbits.utils.notifyApiError)},updateSettings(){const e=_.omit(this.formData,["is_super_user","lnbits_allowed_funding_sources","touch"]);this.isSaving=!0,LNbits.api.request("PUT","/admin/api/v1/settings",this.g.user.wallets[0].adminkey,e).then(e=>{this.needsRestart=this.settings.lnbits_backend_wallet_class!==this.formData.lnbits_backend_wallet_class,this.settings=this.formData,this.formData=_.clone(this.settings),LNbits.api.getAuthUser().then(e=>{this.g.user=LNbits.map.user(e.data)}).catch(LNbits.utils.notifyApiError),Quasar.Notify.create({type:"positive",message:"Success! Settings changed! "+(this.needsRestart?"Restart required!":""),icon:null})}).catch(LNbits.utils.notifyApiError).finally(()=>{this.isSaving=!1})},deleteSettings(){LNbits.utils.confirmDialog("Are you sure you want to restore settings to default?").onOk(()=>{LNbits.api.request("DELETE","/admin/api/v1/settings").then(e=>{Quasar.Notify.create({type:"positive",message:"Success! Restored settings to defaults. Restarting...",icon:null}),this.$q.localStorage.clear()}).catch(LNbits.utils.notifyApiError)})},downloadBackup(){window.open("/admin/api/v1/backup","_blank")}}},window.app.component("lnbits-admin-funding-seed-backup",{props:["active","is-super-user","form-data","settings"],template:"#lnbits-admin-funding-seed-backup",data:()=>({dialog:{show:!1,step:1,seed:"",visible:!1,challenge:[],answers:{},error:"",confirmField:""}}),watch:{active(e){e&&this.openIfRequired()},"formData.lnbits_backend_wallet_class"(e,t){const s=this.seedBackupSource(e);t&&s&&this.formData[s.seedField]&&(this.formData[s.confirmField]=!1),this.openIfRequired()},"formData.boltz_mnemonic"(){this.formData.boltz_mnemonic_backup_confirmed=this.formData.boltz_mnemonic===this.settings.boltz_mnemonic&&this.settings.boltz_mnemonic_backup_confirmed,this.openIfRequired()},"formData.phoenixd_mnemonic"(){this.formData.phoenixd_mnemonic_backup_confirmed=this.formData.phoenixd_mnemonic===this.settings.phoenixd_mnemonic&&this.settings.phoenixd_mnemonic_backup_confirmed,this.openIfRequired()},"formData.spark_l2_mnemonic"(){this.formData.spark_l2_mnemonic_backup_confirmed=this.formData.spark_l2_mnemonic===this.settings.spark_l2_mnemonic&&this.settings.spark_l2_mnemonic_backup_confirmed,this.openIfRequired()}},computed:{seedWords(){return this.dialog.seed.split(/\s+/).filter(Boolean).map((e,t)=>({index:t,word:e}))}},created(){this.openIfRequired()},methods:{seedBackupSource(e=this.formData.lnbits_backend_wallet_class){return"BoltzWallet"===e?{seedField:"boltz_mnemonic",confirmField:"boltz_mnemonic_backup_confirmed"}:"PhoenixdWallet"===e?{seedField:"phoenixd_mnemonic",confirmField:"phoenixd_mnemonic_backup_confirmed"}:"SparkL2Wallet"===e?{seedField:"spark_l2_mnemonic",confirmField:"spark_l2_mnemonic_backup_confirmed"}:void 0},openIfRequired(){if(!this.active||!this.isSuperUser)return;const e=this.seedBackupSource();if(!e)return;const t=(this.formData[e.seedField]||"").trim(),s=this.formData[e.confirmField];!t||s||this.dialog.show||(this.dialog={show:!0,step:1,seed:t,visible:!1,challenge:[],answers:{},error:"",confirmField:e.confirmField})},prepareChallenge(){const e=this.dialog.seed.split(/\s+/).filter(Boolean),t=Math.min(4,e.length),s=_.shuffle([...Array(e.length).keys()]).slice(0,t);this.dialog.challenge=s.sort((e,t)=>e-t).map(t=>({index:t,word:e[t]})),this.dialog.answers={},this.dialog.error="",this.dialog.step=2},submitChallenge(){if(!this.dialog.challenge.every(({index:e,word:t})=>(this.dialog.answers[e]||"").trim().toLowerCase()===t.toLowerCase()))return void(this.dialog.error="One or more words are incorrect. Check your backup and try again.");const e=this.dialog.confirmField;LNbits.api.request("PATCH","/admin/api/v1/settings",this.g.user.wallets[0].adminkey,{[e]:!0}).then(()=>{this.formData[e]=!0,this.settings[e]=!0,this.dialog.show=!1,Quasar.Notify.create({type:"positive",message:"Seed backup confirmed",icon:"check"})}).catch(LNbits.utils.notifyApiError)}}}),window.app.component("lnbits-admin-funding",{props:["active","is-super-user","form-data","settings"],template:"#lnbits-admin-funding",data:()=>({auditData:[]}),created(){this.getAudit()},methods:{getAudit(){LNbits.api.request("GET","/admin/api/v1/audit",this.g.user.wallets[0].adminkey).then(e=>{this.auditData=e.data}).catch(LNbits.utils.notifyApiError)}}}),window.app.component("lnbits-admin-funding-sources",{template:"#lnbits-admin-funding-sources",props:["form-data","allowed-funding-sources"],methods:{getFundingSourceLabel(e){const t=this.rawFundingSources.find(t=>t[0]===e);return t?t[1]:e},showQRValue(e){this.qrValue=e,this.showQRDialog=!0}},computed:{fundingSources(){let e=[];for(const[t,s,a]of this.rawFundingSources){const s={};if(null!==a)for(let[e,t]of Object.entries(a))s[e]="string"==typeof t?{label:t,value:null}:t||{};e.push([t,s])}return new Map(e)},sortedAllowedFundingSources(){return this.allowedFundingSources.sort()}},data:()=>({hideInput:!0,showQRDialog:!1,qrValue:"",rawFundingSources:[["VoidWallet","Void Wallet",null],["FakeWallet","Fake Wallet",{fake_wallet_secret:"Secret",lnbits_denomination:'"sats" or 3 Letter Custom Denomination'}],["CLNRestWallet","Core Lightning Rest (plugin)",{clnrest_url:"Endpoint",clnrest_ca:"ca.pem",clnrest_cert:"server.pem",clnrest_readonly_rune:"Rune used for readonly requests",clnrest_invoice_rune:"Rune used for creating invoices",clnrest_pay_rune:"Rune used for paying invoices using pay",clnrest_renepay_rune:"Rune used for paying invoices using renepay",clnrest_last_pay_index:"Ignores any invoices paid prior to or including this index. 0 is equivalent to not specifying and negative value is invalid.",clnrest_nodeid:"Node id"}],["CoreLightningWallet","Core Lightning",{corelightning_rpc:"Endpoint",corelightning_pay_command:"Custom Pay Command"}],["CoreLightningRestWallet","Core Lightning Rest (legacy)",{corelightning_rest_url:"Endpoint",corelightning_rest_cert:"Certificate",corelightning_rest_macaroon:"Macaroon"}],["LndRestWallet","Lightning Network Daemon (LND Rest)",{lnd_rest_endpoint:"Endpoint",lnd_rest_cert:"Certificate",lnd_rest_macaroon:"Macaroon",lnd_rest_macaroon_encrypted:"Encrypted Macaroon",lnd_rest_route_hints:{advanced:!0,label:"Enable Route Hints"},lnd_rest_allow_self_payment:{advanced:!0,label:"Allow Self Payment"}}],["LndWallet","Lightning Network Daemon (LND)",{lnd_grpc_endpoint:"Endpoint",lnd_grpc_cert:"Certificate",lnd_grpc_port:"Port",lnd_grpc_macaroon:"GRPC Macaroon",lnd_grpc_invoice_macaroon:"GRPC Invoice Macaroon",lnd_grpc_admin_macaroon:"GRPC Admin Macaroon",lnd_grpc_macaroon_encrypted:"Encrypted Macaroon",lnd_grpc_allow_self_payment:{advanced:!0,label:"Allow Self Payment"}}],["LnTipsWallet","LN.Tips",{lntips_api_endpoint:"Endpoint",lntips_api_key:"API Key"}],["LNPayWallet","LN Pay",{lnpay_api_endpoint:"Endpoint",lnpay_api_key:"API Key",lnpay_wallet_key:"Wallet Key"}],["EclairWallet","Eclair (ACINQ)",{eclair_url:"URL",eclair_pass:"Password"}],["LNbitsWallet","LNbits",{lnbits_endpoint:"Endpoint",lnbits_key:"Admin Key"}],["BlinkWallet","Blink",{blink_api_endpoint:"Endpoint",blink_ws_endpoint:"WebSocket",blink_token:"Key",blink_send_without_probe:{advanced:!0,label:"Send payment if fee probe fails",hint:"If enabled (default), payments to destinations that cannot be probed (e.g. fedimints) are still sent. If disabled, such payments fail."}}],["AlbyWallet","Alby",{alby_api_endpoint:"Endpoint",alby_access_token:"Key"}],["BarkWallet","Bark",{bark_api_endpoint:{label:"Endpoint",value:"http://localhost:3000"},bark_api_token:"auth_token"}],["BoltzWallet","Boltz",{boltz_client_endpoint:{label:"Boltz client endpoint",value:"127.0.0.1:9002"},boltz_client_macaroon:{label:"Admin Macaroon path or hex",value:"/home/ubuntu/.boltz/macaroons/admin.macaroon"},boltz_client_cert:{label:"Certificate path or hex",value:"/home/ubuntu/.boltz/tls.cert"},boltz_mnemonic:{label:"Liquid seed phrase",hint:"Boltz will fetch once connected, but you can change later (can be opened in a liquid wallet) ",copy:!0,qrcode:!0},boltz_client_password:{label:"Wallet Password (optional)",advanced:!0}}],["ZBDWallet","ZBD",{zbd_api_endpoint:"Endpoint",zbd_api_key:"Key"}],["PhoenixdWallet","Phoenixd",{phoenixd_api_endpoint:"Endpoint",phoenixd_api_password:"Key",phoenixd_data_dir:{label:"Data Directory",hint:"Directory where phoenixd stores its data, including the seed phrase."},phoenixd_mnemonic:{label:"Phoenixd Seed Phrase",hint:"Only available if phoenixd data-dir is specified",readonly:!0,copy:!0,qrcode:!0}}],["OpenNodeWallet","OpenNode",{opennode_api_endpoint:"Endpoint",opennode_key:"Key"}],["SparkWallet","Spark",{spark_url:"Endpoint",spark_token:"Token"}],["SparkL2Wallet","Spark (L2)",{spark_l2_external_endpoint:{label:"External Sidecar Endpoint",hint:"Make sure to also specify the API key if your sidecar requires authentication.",value:""},spark_l2_mnemonic:{label:"External Sidecar Mnemonic",hint:"Mnemonic for the Spark wallet on the external sidecar. Required if the side car does not have its own mnemonic.",value:""},spark_l2_external_api_key:{label:"External Sidecar API Key",hint:"API key for authenticating with the external sidecar if it requires authentication.",value:""},spark_l2_network:{label:"Network",value:"MAINNET",hint:"The network to use for the Spark wallet.",advanced:!0},spark_l2_pay_wait_ms:{label:"Payment Wait Time (ms)",hint:"The time to wait for a payment to be processed before considering it failed.",advanced:!0},spark_l2_pay_poll_ms:{label:"Payment Poll Time (ms)",hint:"The time to wait between polling for payment status updates.",advanced:!0},spark_l2_stream_keepalive_ms:{label:"Stream Keepalive Time (ms)",hint:"The time to wait between sending keepalive messages to the Spark sidecar to keep the connection open.",advanced:!0}}],["NWCWallet","Nostr Wallet Connect",{nwc_pairing_url:"Pairing URL"}],["BreezSdkWallet","Breez SDK",{breez_api_key:"Breez API Key",breez_greenlight_seed:"Greenlight Seed",breez_greenlight_device_key:"Greenlight Device Key",breez_greenlight_device_cert:"Greenlight Device Cert",breez_greenlight_invite_code:"Greenlight Invite Code"}],["StrikeWallet","Strike (alpha)",{strike_api_endpoint:"API Endpoint",strike_api_key:"API Key"}],["BreezLiquidSdkWallet","Breez Liquid SDK",{breez_liquid_api_key:"Breez API Key (can be empty)",breez_liquid_seed:"Liquid seed phrase",breez_liquid_fee_offset_sat:"Offset amount in sats to increase fee limit"}]]})}),window.app.component("lnbits-admin-fiat-providers",{props:["form-data"],template:"#lnbits-admin-fiat-providers",data:()=>({formAddStripeUser:"",formAddPaypalUser:"",formAddSquareUser:"",formAddRevolutUser:"",creatingRevolutWebhook:!1,hideInputToggle:!0}),computed:{stripeWebhookUrl(){return this.formData?.stripe_payment_webhook_url||this.calculateWebhookUrl("stripe")},paypalWebhookUrl(){return this.formData?.paypal_payment_webhook_url||this.calculateWebhookUrl("paypal")},revolutWebhookUrl(){return this.formData?.revolut_payment_webhook_url||this.calculateWebhookUrl("revolut")}},watch:{formData:{handler(){this.syncWebhookUrls()},immediate:!0}},methods:{basePathFromLocation(){if("undefined"==typeof window)return"";const e=window.location.pathname.replace(/\/+$/,""),t=e.lastIndexOf("/admin");return(t>=0?e.slice(0,t):e||"")||""},calculateWebhookUrl(e){if("undefined"==typeof window)return"";const t=`${this.basePathFromLocation()}/api/v1/callback/${e}`.replace(/\/+/g,"/"),s=t.startsWith("/")?t:`/${t}`;return`${window.location.origin}${s}`},syncWebhookUrls(){this.maybeSetWebhookUrl("stripe_payment_webhook_url","stripe"),this.maybeSetWebhookUrl("paypal_payment_webhook_url","paypal"),this.maybeSetWebhookUrl("square_payment_webhook_url","square"),this.maybeSetWebhookUrl("revolut_payment_webhook_url","revolut")},maybeSetWebhookUrl(e,t){if(!this.formData)return;const s=this.calculateWebhookUrl(t),a=this.formData[e];(!a||a.includes("your-lnbits-domain-here.com"))&&s&&(this.formData[e]=s)},copyWebhookUrl(e){e&&this.copyText(e)},isClearnetWebhookUrl(e){let t;try{t=new URL(e)}catch(e){return!1}const s=t.hostname.toLowerCase();return!!["http:","https:"].includes(t.protocol)&&(!("localhost"===s||s.endsWith(".localhost")||s.endsWith(".local")||s.endsWith(".onion"))&&!(/^127\./.test(s)||/^10\./.test(s)||/^192\.168\./.test(s)||/^169\.254\./.test(s)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(s)||"0.0.0.0"===s||"::1"===s))},notifyRevolutWebhookWarning(e){Quasar.Notify.create({type:"warning",message:e,icon:null,closeBtn:!0})},addStripeAllowedUser(){const e=this.formAddStripeUser||"";e.length&&!this.formData.stripe_limits.allowed_users.includes(e)&&(this.formData.stripe_limits.allowed_users=[...this.formData.stripe_limits.allowed_users,e],this.formAddStripeUser="")},removeStripeAllowedUser(e){this.formData.stripe_limits.allowed_users=this.formData.stripe_limits.allowed_users.filter(t=>t!==e)},addPaypalAllowedUser(){const e=this.formAddPaypalUser||"";e.length&&!this.formData.paypal_limits.allowed_users.includes(e)&&(this.formData.paypal_limits.allowed_users=[...this.formData.paypal_limits.allowed_users,e],this.formAddPaypalUser="")},removePaypalAllowedUser(e){this.formData.paypal_limits.allowed_users=this.formData.paypal_limits.allowed_users.filter(t=>t!==e)},addSquareAllowedUser(){const e=this.formAddSquareUser||"";e.length&&!this.formData.square_limits.allowed_users.includes(e)&&(this.formData.square_limits.allowed_users=[...this.formData.square_limits.allowed_users,e],this.formAddSquareUser="")},removeSquareAllowedUser(e){this.formData.square_limits.allowed_users=this.formData.square_limits.allowed_users.filter(t=>t!==e)},addRevolutAllowedUser(){const e=this.formAddRevolutUser||"";e.length&&!this.formData.revolut_limits.allowed_users.includes(e)&&(this.formData.revolut_limits.allowed_users=[...this.formData.revolut_limits.allowed_users,e],this.formAddRevolutUser="")},removeRevolutAllowedUser(e){this.formData.revolut_limits.allowed_users=this.formData.revolut_limits.allowed_users.filter(t=>t!==e)},checkFiatProvider(e){LNbits.api.request("PUT",`/api/v1/fiat/check/${e}`).then(e=>{const t=e.data;Quasar.Notify.create({type:t.success?"positive":"warning",message:t.message,icon:null})}).catch(LNbits.utils.notifyApiError)},createRevolutWebhook(){const e=this.calculateWebhookUrl("revolut");this.formData.revolut_payment_webhook_url=e,this.formData.revolut_api_secret_key?this.isClearnetWebhookUrl(e)?(this.creatingRevolutWebhook=!0,LNbits.api.request("POST","/api/v1/fiat/revolut/webhook",null,{url:e,endpoint:this.formData.revolut_api_endpoint,api_secret_key:this.formData.revolut_api_secret_key,api_version:this.formData.revolut_api_version}).then(e=>{const t=e.data;this.formData.revolut_payment_webhook_url=t.url,this.formData.revolut_webhook_signing_secret=t.signing_secret,Quasar.Notify.create({type:"positive",message:`Revolut webhook ${t.already_exists?"already exists":"created"}${t.id?`: ${t.id}`:""}.`,icon:null})}).catch(LNbits.utils.notifyApiError).finally(()=>{this.creatingRevolutWebhook=!1})):this.notifyRevolutWebhookWarning("Revolut webhook URL must be a clearnet URL."):this.notifyRevolutWebhookWarning("Add your Revolut API secret key before creating a webhook.")}}}),window.app.component("lnbits-admin-exchange-providers",{props:["form-data"],template:"#lnbits-admin-exchange-providers",data:()=>({exchangeData:{selectedProvider:null,showTickerConversion:!1,convertFromTicker:null,convertToTicker:null},exchangesTable:{columns:[{name:"name",align:"left",label:"Exchange Name",field:"name",sortable:!0},{name:"api_url",align:"left",label:"URL",field:"api_url",sortable:!1},{name:"path",align:"left",label:"JSON Path",field:"path",sortable:!1},{name:"exclude_to",align:"left",label:"Exclude Currencies",field:"exclude_to",sortable:!1},{name:"ticker_conversion",align:"left",label:"Ticker Conversion",field:"ticker_conversion",sortable:!1}],pagination:{sortBy:"name",rowsPerPage:100,page:1,rowsNumber:100},search:null,hideEmpty:!0}}),mounted(){this.getExchangeRateHistory()},methods:{getDefaultSetting(e){LNbits.api.getDefaultSetting(e).then(t=>{this.formData[e]=t.data.default_value})},getExchangeRateHistory(){LNbits.api.request("GET","/api/v1/rate/history",this.g.user.wallets[0].inkey).then(e=>{this.initExchangeChart(e.data)}).catch(function(e){LNbits.utils.notifyApiError(e)})},showExchangeProvidersTab(e){"exchange_providers"===e&&this.getExchangeRateHistory()},addExchangeProvider(){this.formData.lnbits_exchange_rate_providers=[{name:"",api_url:"",path:"",exclude_to:[]},...this.formData.lnbits_exchange_rate_providers]},removeExchangeProvider(e){this.formData.lnbits_exchange_rate_providers=this.formData.lnbits_exchange_rate_providers.filter(t=>t!==e)},removeExchangeTickerConversion(e,t){e.ticker_conversion=e.ticker_conversion.filter(e=>e!==t),this.formData.touch=null},addExchangeTickerConversion(){this.exchangeData.selectedProvider&&(this.exchangeData.selectedProvider.ticker_conversion.push(`${this.exchangeData.convertFromTicker}:${this.exchangeData.convertToTicker}`),this.formData.touch=null,this.exchangeData.showTickerConversion=!1)},showTickerConversionDialog(e){this.exchangeData.convertFromTicker=null,this.exchangeData.convertToTicker=null,this.exchangeData.selectedProvider=e,this.exchangeData.showTickerConversion=!0},initExchangeChart(e){this.exchangeRatesChart&&(this.exchangeRatesChart.destroy(),this.exchangeRatesChart=null);const t=e.map(e=>this.utils.formatTimestamp(e.timestamp,"HH:mm")),s=(this.formData.lnbits_price_aggregator_enabled?[{name:"Aggregator"}]:[...this.formData.lnbits_exchange_rate_providers,{name:"LNbits"}]).map(t=>({label:t.name,data:e.map(e=>e.rates[t.name]),pointStyle:!0,borderWidth:"LNbits"===t.name?4:2,tension:.4}));this.exchangeRatesChart=new Chart(this.$refs.exchangeRatesChart.getContext("2d"),{type:"line",options:{plugins:{legend:{display:!0},title:{display:!0,text:"Bitcoin Price History"}}},data:{labels:t,datasets:s}})}}}),window.app.component("lnbits-admin-security",{props:["form-data"],template:"#lnbits-admin-security",data:()=>({logs:[],formBlockedIPs:"",serverlogEnabled:!1,nostrAcceptedUrl:"",formAllowedIPs:"",formCallbackUrlRule:"",formLnurlRedirectUrlRule:""}),created(){},methods:{addAllowedIPs(){const e=this.formAllowedIPs.trim(),t=this.formData.lnbits_allowed_ips;e&&e.length&&!t.includes(e)&&(this.formData.lnbits_allowed_ips=[...t,e],this.formAllowedIPs="")},removeAllowedIPs(e){const t=this.formData.lnbits_allowed_ips;this.formData.lnbits_allowed_ips=t.filter(t=>t!==e)},addBlockedIPs(){const e=this.formBlockedIPs.trim(),t=this.formData.lnbits_blocked_ips;e&&e.length&&!t.includes(e)&&(this.formData.lnbits_blocked_ips=[...t,e],this.formBlockedIPs="")},removeBlockedIPs(e){const t=this.formData.lnbits_blocked_ips;this.formData.lnbits_blocked_ips=t.filter(t=>t!==e)},addCallbackUrlRule(){const e=this.formCallbackUrlRule.trim(),t=this.formData.lnbits_callback_url_rules;e&&e.length&&!t.includes(e)&&(this.formData.lnbits_callback_url_rules=[...t,e],this.formCallbackUrlRule="")},removeCallbackUrlRule(e){const t=this.formData.lnbits_callback_url_rules;this.formData.lnbits_callback_url_rules=t.filter(t=>t!==e)},addLnurlRedirectUrlRule(){const e=this.formLnurlRedirectUrlRule.trim(),t=this.formData.lnbits_lnurl_redirect_url_rules;e&&e.length&&!t.includes(e)&&(this.formData.lnbits_lnurl_redirect_url_rules=[...t,e],this.formLnurlRedirectUrlRule="")},removeLnurlRedirectUrlRule(e){const t=this.formData.lnbits_lnurl_redirect_url_rules;this.formData.lnbits_lnurl_redirect_url_rules=t.filter(t=>t!==e)},addNostrUrl(){const e=this.nostrAcceptedUrl.trim();this.removeNostrUrl(e),this.formData.nostr_absolute_request_urls.push(e),this.nostrAcceptedUrl=""},removeNostrUrl(e){this.formData.nostr_absolute_request_urls=this.formData.nostr_absolute_request_urls.filter(t=>t!==e)},async toggleServerLog(){if(this.serverlogEnabled=!this.serverlogEnabled,this.serverlogEnabled){const e="http:"!==location.protocol?"wss://":"ws://",t=await LNbits.utils.digestMessage(this.g.user.id),s=e+document.domain+":"+location.port+"/api/v1/ws/"+t;this.ws=new WebSocket(s),this.ws.addEventListener("message",async({data:e})=>{this.logs.push(e.toString());const t=this.$refs.logScroll;if(t){const e=t.getScrollTarget(),s=0;t.setScrollPosition(e.scrollHeight,s)}})}else this.ws.close()}}}),window.app.component("lnbits-admin-users",{props:["form-data"],template:"#lnbits-admin-users",data:()=>({formAddUser:"",formAddAdmin:"",formAddActivationCode:"",showReusableActivationCode:!1}),methods:{addAllowedUser(){let e=this.formAddUser,t=this.formData.lnbits_allowed_users;e&&e.length&&!t.includes(e)&&(this.formData.lnbits_allowed_users=[...t,e],this.formAddUser="")},removeAllowedUser(e){let t=this.formData.lnbits_allowed_users;this.formData.lnbits_allowed_users=t.filter(t=>t!==e)},addAdminUser(){let e=this.formAddAdmin,t=this.formData.lnbits_admin_users;e&&e.length&&!t.includes(e)&&(this.formData.lnbits_admin_users=[...t,e],this.formAddAdmin="")},removeAdminUser(e){let t=this.formData.lnbits_admin_users;this.formData.lnbits_admin_users=t.filter(t=>t!==e)},addOneTimeActivationCode(){const e=this.formAddActivationCode,t=this.formData.lnbits_register_one_time_activation_codes;e?.length&&!t.includes(e)&&(this.formData.lnbits_register_one_time_activation_codes=[...t,e],this.formAddActivationCode="")},removeOneTimeActivationCode(e){const t=this.formData.lnbits_register_one_time_activation_codes;this.formData.lnbits_register_one_time_activation_codes=t.filter(t=>t!==e)}}}),window.app.component("lnbits-admin-server",{props:["form-data"],template:"#lnbits-admin-server",computed:{lightningAddressBlacklistText:{get(){const e=this.formData.lnbits_wallet_lightning_address_blacklist;return Array.isArray(e)?e.join("\n"):e||""},set(e){this.formData.lnbits_wallet_lightning_address_blacklist=e.split(/[\n,]/).map(e=>e.trim().toLowerCase()).filter(e=>e.length)}}}}),window.app.component("lnbits-admin-extensions",{props:["form-data"],template:"#lnbits-admin-extensions",data:()=>({formAddExtensionsManifest:"",formAddWasmManifest:""}),methods:{addExtensionsManifest(){this.addManifest("lnbits_extensions_manifests","formAddExtensionsManifest")},addWasmManifest(){this.addManifest("lnbits_wasm_extensions_manifests","formAddWasmManifest")},addManifest(e,t){const s=this[t].trim(),a=this.formData[e]||[];s&&s.length&&!a.includes(s)&&(this.formData[e]=[...a,s],this[t]="")},removeExtensionsManifest(e){this.removeManifest("lnbits_extensions_manifests",e)},removeWasmManifest(e){this.removeManifest("lnbits_wasm_extensions_manifests",e)},removeManifest(e,t){const s=this.formData[e]||[];this.formData[e]=s.filter(e=>e!==t)}}}),window.app.component("lnbits-admin-wasm-runtime",{props:["form-data"],template:"#lnbits-admin-wasm-runtime",data(){return{wasmRuntimeLoading:!1,wasmHistoryLoading:!1,wasmRuntimeTimer:null,wasmStats:{},wasmCurrentInvocations:[],wasmInvocationHistory:[],wasmStatItems:[{key:"total",label:"Total",icon:"data_usage",color:"primary"},{key:"running",label:"Running",icon:"play_circle",color:"green"},{key:"completed",label:"Completed",icon:"task_alt",color:"teal"},{key:"failed",label:"Failed",icon:"error",color:"red"},{key:"stopped",label:"Stopped",icon:"stop_circle",color:"orange"},{key:"timeout",label:"Timeouts",icon:"timer_off",color:"purple"}],wasmCurrentColumns:[{name:"extension_id",label:"Extension",field:"extension_id",align:"left",sortable:!0},{name:"export_name",label:"Export",field:"export_name",align:"left",sortable:!0},{name:"trigger_type",label:"Trigger",field:"trigger_type",align:"left",sortable:!0},{name:"status",label:"Status",field:"status",align:"left",sortable:!0},{name:"user_id",label:"User",field:"user_id",align:"left",sortable:!0},{name:"started_at",label:"Started",field:"started_at",align:"left",sortable:!0},{name:"duration_ms",label:"Duration",field:e=>e.duration_ms||0,align:"right",sortable:!0},{name:"context",label:"Context",field:e=>this.wasmContextValue(e),align:"left",sortable:!0},{name:"actions",label:"",field:"actions",align:"right"}],wasmHistoryColumns:[{name:"extension_id",label:"Extension",field:"extension_id",align:"left",sortable:!0},{name:"export_name",label:"Export",field:"export_name",align:"left",sortable:!0},{name:"trigger_type",label:"Trigger",field:"trigger_type",align:"left",sortable:!0},{name:"status",label:"Status",field:"status",align:"left",sortable:!0},{name:"user_id",label:"User",field:"user_id",align:"left",sortable:!0},{name:"started_at",label:"Started",field:"started_at",align:"left",sortable:!0},{name:"duration_ms",label:"Duration",field:e=>e.duration_ms||0,align:"right",sortable:!0},{name:"calls",label:"Calls",field:e=>this.wasmCallCount(e),align:"left",sortable:!0},{name:"context",label:"Context",field:e=>this.wasmContextValue(e),align:"left",sortable:!0},{name:"error_message",label:"Error/Stop Reason",field:e=>e.error_message||e.stop_reason||"",align:"left",sortable:!0}]}},computed:{adminKey(){return this.g.user.wallets[0].adminkey},wasmExtensionId(){return this.$route.params.extId||null},wasmExtensionQuery(){return this.wasmExtensionId?`extension_id=${encodeURIComponent(this.wasmExtensionId)}`:""}},watch:{wasmExtensionId(){this.fetchWasmRuntime()}},methods:{async fetchWasmRuntime(){await Promise.all([this.fetchWasmCurrentInvocations(),this.fetchWasmInvocationHistory(),this.fetchWasmInvocationStats()])},async fetchWasmCurrentInvocations(){this.wasmRuntimeLoading=!0;try{const e=this.wasmExtensionQuery?`?${this.wasmExtensionQuery}`:"",{data:t}=await LNbits.api.request("GET",`/api/v1/extension/wasm/invocations/current${e}`,this.adminKey);this.wasmCurrentInvocations=t||[]}catch(e){LNbits.utils.notifyApiError(e)}finally{this.wasmRuntimeLoading=!1}},async fetchWasmInvocationHistory(){this.wasmHistoryLoading=!0;try{const e=["limit=50"];this.wasmExtensionQuery&&e.push(this.wasmExtensionQuery);const{data:t}=await LNbits.api.request("GET",`/api/v1/extension/wasm/invocations?${e.join("&")}`,this.adminKey);this.wasmInvocationHistory=t||[]}catch(e){LNbits.utils.notifyApiError(e)}finally{this.wasmHistoryLoading=!1}},async fetchWasmInvocationStats(){try{const e=["hours=24"];this.wasmExtensionQuery&&e.push(this.wasmExtensionQuery);const{data:t}=await LNbits.api.request("GET",`/api/v1/extension/wasm/invocations/stats?${e.join("&")}`,this.adminKey);this.wasmStats=t||{}}catch(e){LNbits.utils.notifyApiError(e)}},async stopWasmInvocation(e){try{await LNbits.api.request("POST",`/api/v1/extension/wasm/invocations/${encodeURIComponent(e)}/stop`,this.adminKey),Quasar.Notify.create({type:"positive",message:"WASM invocation stop requested."}),await this.fetchWasmRuntime()}catch(e){LNbits.utils.notifyApiError(e)}},deactivateWasmExtension(e){LNbits.utils.confirmDialog(`Deactivate extension '${e}'?`,"Deactivate Extension").onOk(async()=>{try{await LNbits.api.request("PUT",`/api/v1/extension/${encodeURIComponent(e)}/deactivate`,this.adminKey),Quasar.Notify.create({type:"positive",message:`Extension '${e}' deactivated.`}),await this.fetchWasmRuntime()}catch(e){LNbits.utils.notifyApiError(e)}})},formatWasmStat(e){const t=this.wasmStats[e];return null==t?"0":String(t)},formatWasmDate(e){return e?this.utils.formatDate(e):""},wasmStatusColor:e=>({running:"green",stopping:"orange",completed:"teal",failed:"red",stopped:"orange",timeout:"purple",abandoned:"grey"}[e]||"grey"),wasmTriggerColor:e=>({http:"primary",event:"purple"}[e]||"grey"),formatWasmDuration(e){let t=e.duration_ms;return"running"!==e.status&&"stopping"!==e.status||!e.started_at||(t=Date.now()-new Date(e.started_at).getTime()),null==t?"":t>=1e3?`${(t/1e3).toFixed(1)}s`:`${t}ms`},formatWasmCalls:e=>[`host ${e.host_call_count||0}`,`http ${e.http_call_count||0}`,`storage ${e.storage_call_count||0}`,`wallet ${e.wallet_call_count||0}`].join(" / "),wasmCallCount:e=>(e.host_call_count||0)+(e.http_call_count||0)+(e.storage_call_count||0)+(e.wallet_call_count||0),wasmContextValue:e=>[e.method,e.path,e.event_type,e.wallet_id,e.payment_hash].filter(Boolean).join(" "),formatWasmContext:e=>[e.method,e.path,e.event_type,e.wallet_id?`wallet ${e.wallet_id}`:"",e.payment_hash?`payment ${e.payment_hash.slice(0,12)}...`:""].filter(Boolean).join(" | "),formatWasmUserId(e){if(!e)return"-";const t=String(e);return t.length<=12?t:`${t.slice(0,3)}...${t.slice(-3)}`}},created(){this.fetchWasmRuntime(),this.wasmRuntimeTimer=setInterval(()=>{this.fetchWasmCurrentInvocations()},5e3)},unmounted(){this.wasmRuntimeTimer&&clearInterval(this.wasmRuntimeTimer)}}),window.app.component("lnbits-admin-wasm-limit-config",{props:["form-data"],template:"#lnbits-admin-wasm-limit-config",data:()=>({selectedWasmExtensionId:null,wasmExtensionLimitDraft:{},wasmExtensionLimitsSaving:!1,wasmRuntimeLimitExtensions:[],wasmRuntimeLimitExtensionsLoading:!1,wasmLimitInfoDialog:{show:!1,title:"",details:""},wasmRuntimeLimitGroups:[{title:"Execution",fields:[{name:"wasm_runtime_max_execution_ms",label:"Max execution time (ms)",description:"Maximum wall-clock time allowed for one WASM invocation.",details:"This is the elapsed time from starting the invocation until the export returns. When the limit is reached LNbits requests an interrupt and records the invocation as timed out if it cannot finish quickly. Use this to stop long sleeps, slow host calls, and CPU loops that run for too long."},{name:"wasm_runtime_max_fuel",label:"Max fuel",description:"Maximum Wasmtime instruction budget for one invocation.",details:"Fuel is Wasmtime instruction budgeting. It is more deterministic than wall-clock time for CPU-heavy loops because each executed instruction consumes budget. Set this low enough to stop busy loops, but high enough for legitimate extension startup and JSON processing."},{name:"wasm_runtime_max_wasm_stack_bytes",label:"Max WASM stack (bytes)",description:"Maximum stack space for WASM calls and recursion.",details:"This limits stack used by WebAssembly function calls. It protects the server from deep recursion or very large call chains in extension code. If legitimate extensions fail with stack overflow traps, raise this carefully."}]},{title:"Memory and Data Size",fields:[{name:"wasm_runtime_max_memory_bytes",label:"Max memory (bytes)",description:"Maximum WASM linear memory per invocation.",details:"This caps the linear memory visible to the WASM module. It limits memory.grow and can make instantiation fail if the module asks for too much memory up front. This does not include every byte used by the Python process or Wasmtime engine internals."},{name:"wasm_runtime_max_request_bytes",label:"Max request size (bytes)",description:"Maximum serialized input payload accepted before execution.",details:"This caps the serialized payload passed into a WASM export before execution starts. It protects against huge HTTP bodies, oversized event data, and expensive JSON parsing. Requests above this limit should be rejected before invoking the extension."},{name:"wasm_runtime_max_response_bytes",label:"Max response size (bytes)",description:"Maximum serialized response returned by a WASM export.",details:"This caps the JSON or string response returned by the WASM export. It prevents extensions from returning huge responses that consume memory, slow down API calls, or overload the browser. Responses above this limit are treated as invalid."}]},{title:"Wasmtime Objects",fields:[{name:"wasm_runtime_max_table_elements",label:"Max table elements",description:"Maximum total elements allowed in WASM tables.",details:"Tables store references used by WebAssembly, commonly function references. Limiting table elements prevents a module from allocating very large reference tables. Each table element also has host memory overhead."},{name:"wasm_runtime_max_instances",label:"Max instances",description:"Maximum WebAssembly instances allowed inside one store.",details:"This limits how many WebAssembly instances can be created inside one Wasmtime store. LNbits normally needs one instance per invocation, so a low value is expected. Raising it should only be needed if the runtime starts supporting modules that instantiate other modules."},{name:"wasm_runtime_max_tables",label:"Max tables",description:"Maximum WebAssembly tables allowed inside one store.",details:"This limits the number of WebAssembly tables in the store. It is separate from table elements: one setting limits the number of tables, the other limits their total size. Keep this small unless a component model module legitimately needs more tables."},{name:"wasm_runtime_max_memories",label:"Max memories",description:"Maximum WebAssembly linear memories allowed inside one store.",details:"This limits how many separate linear memories a module can create. Most extensions should need only one memory. Keep this small to reduce memory accounting complexity and prevent multi-memory abuse."}]},{title:"Concurrency",fields:[{name:"wasm_runtime_max_concurrent_invocations",label:"Max concurrent invocations",description:"Maximum running WASM invocations across the server.",details:"This is the global cap for running WASM invocations across all extensions and users. It protects the LNbits process from thread exhaustion, CPU pressure, and too many simultaneous stores. New invocations should be rejected or queued once this is reached."},{name:"wasm_runtime_max_concurrent_invocations_per_extension",label:"Max concurrent per extension",description:"Maximum running WASM invocations for one extension.",details:"This caps how many invocations a single extension can run at once. It prevents one malicious or buggy extension from consuming the whole global concurrency budget. Set it lower than the global limit."},{name:"wasm_runtime_max_concurrent_invocations_per_user",label:"Max concurrent per user",description:"Maximum running WASM invocations for one user.",details:"This caps concurrent invocations attributed to one user. It helps protect against a user repeatedly clicking, refreshing, or scripting extension calls. Invocations without a user can still be governed by the global and per-extension limits."}]},{title:"Host Calls",fields:[{name:"wasm_runtime_max_host_calls",label:"Max host calls",description:"Maximum total calls from WASM into LNbits host APIs.",details:"This is the total budget for calls from the WASM module into LNbits host APIs during one invocation. It should count all categories together. It limits chatty extensions and prevents tight loops that repeatedly call back into Python."},{name:"wasm_runtime_max_http_calls",label:"Max HTTP calls",description:"Maximum outbound HTTP host calls per invocation.",details:"This caps outbound HTTP requests made through the host API during one invocation. It reduces SSRF blast radius, protects network resources, and limits slow external dependencies. It should be enforced together with HTTP timeout and response-size limits."},{name:"wasm_runtime_max_storage_calls",label:"Max storage calls",description:"Maximum storage host calls per invocation.",details:"This caps extension storage operations during one invocation. It protects the database from excessive reads and writes triggered by malicious loops. Use it with storage payload-size limits if those are added later."},{name:"wasm_runtime_max_wallet_calls",label:"Max wallet calls",description:"Maximum wallet/payment host calls per invocation.",details:"This caps wallet and payment-related host calls during one invocation. These calls are security-sensitive and may touch balances, invoices, or payments. Keep this conservative and rely on explicit permissions for what the extension is allowed to do."}]},{title:"HTTP",fields:[{name:"wasm_runtime_http_timeout_ms",label:"HTTP timeout (ms)",description:"Maximum time allowed for one WASM HTTP request.",details:"This is the per-request timeout for HTTP calls made through the WASM host API. It prevents a slow remote server from holding an invocation open indefinitely. The total invocation timeout still applies across all work."},{name:"wasm_runtime_max_http_response_bytes",label:"Max HTTP response size (bytes)",description:"Maximum response body size accepted from one WASM HTTP request.",details:"This caps the response body accepted from each HTTP call made by an extension. It protects memory and parsing time when a remote server returns a very large body. Responses above the limit should fail the host call."}]}]}),computed:{adminKey(){return this.g.user.wallets[0].adminkey},isExtensionLimitRoute(){return this.$route.path.startsWith("/admin/extensions/wasm/limits/")},routeWasmExtensionId(){return this.isExtensionLimitRoute?this.$route.params.extId:null},backRoute(){return this.isExtensionLimitRoute?"/admin/extensions/wasm/limits":"/admin#extensions"},backTooltip(){return this.isExtensionLimitRoute?"Wasm Limit Config":"Extensions Settings"},pageDescription(){return this.isExtensionLimitRoute?"Customize limits for one installed WASM extension.":"These values are global defaults. Use 0 to disable a global limit."},wasmRuntimeLimitExtensionOptions(){return this.wasmRuntimeLimitExtensions.map(e=>({label:`${e.name||e.id} (${e.id})`,value:e.id}))},selectedWasmRuntimeLimitExtension(){return this.wasmRuntimeLimitExtensions.find(e=>e.id===this.selectedWasmExtensionId)||null},customWasmLimitCount(){const e=this.selectedWasmRuntimeLimitExtension;return e&&e.wasm_runtime_limits?Object.keys(e.wasm_runtime_limits).length:0}},watch:{selectedWasmExtensionId(){this.loadSelectedWasmRuntimeLimitExtension()},routeWasmExtensionId(){this.syncWasmExtensionLimitRoute()}},created(){this.fetchWasmRuntimeLimitExtensions()},methods:{async fetchWasmRuntimeLimitExtensions(){this.wasmRuntimeLimitExtensionsLoading=!0;try{const{data:e}=await LNbits.api.request("GET","/api/v1/extension/wasm/runtime-limits/extensions",this.adminKey);this.wasmRuntimeLimitExtensions=e||[],this.selectedWasmExtensionId&&!this.wasmRuntimeLimitExtensions.some(e=>e.id===this.selectedWasmExtensionId)&&(this.selectedWasmExtensionId=null),this.syncWasmExtensionLimitRoute()}catch(e){LNbits.utils.notifyApiError(e)}finally{this.wasmRuntimeLimitExtensionsLoading=!1}},syncWasmExtensionLimitRoute(){this.selectedWasmExtensionId=this.routeWasmExtensionId,this.loadSelectedWasmRuntimeLimitExtension()},openWasmExtensionLimit(e){this.$router.push(`/admin/extensions/wasm/limits/${encodeURIComponent(e)}`)},loadSelectedWasmRuntimeLimitExtension(){const e=this.selectedWasmRuntimeLimitExtension;this.wasmExtensionLimitDraft=e?{...e.wasm_runtime_limits||{}}:{}},wasmExtensionLimitHint(e){return`Inherited global value: ${this.formData[e.name]}. ${e.description}`},wasmExtensionLimitPlaceholder(e){const t=this.formData[e.name];return null==t?"":String(t)},normalizedWasmExtensionLimitDraft(){const e={};return this.wasmRuntimeLimitGroups.forEach(t=>{t.fields.forEach(t=>{const s=this.wasmExtensionLimitDraft[t.name],a="string"==typeof s?s.trim():s;if(""===a||null==a)return;const i=Number(a);if(!Number.isFinite(i)||!Number.isInteger(i)||i<0)throw new Error(`${t.label} must be a non-negative integer.`);e[t.name]=i})}),e},async clearWasmExtensionLimits(){this.wasmExtensionLimitDraft={},await this.saveWasmExtensionLimits()},async saveWasmExtensionLimits(){if(this.selectedWasmExtensionId){this.wasmExtensionLimitsSaving=!0;try{const{data:e}=await LNbits.api.request("PUT",`/api/v1/extension/wasm/runtime-limits/${encodeURIComponent(this.selectedWasmExtensionId)}`,this.adminKey,{limits:this.normalizedWasmExtensionLimitDraft()}),t=this.wasmRuntimeLimitExtensions.findIndex(t=>t.id===e.id);t>=0&&this.wasmRuntimeLimitExtensions.splice(t,1,e),this.loadSelectedWasmRuntimeLimitExtension(),Quasar.Notify.create({type:"positive",message:"WASM extension limits saved."})}catch(e){e instanceof Error&&!e.response?Quasar.Notify.create({type:"negative",message:e.message}):LNbits.utils.notifyApiError(e)}finally{this.wasmExtensionLimitsSaving=!1}}},showWasmLimitInfo(e){this.wasmLimitInfoDialog={show:!0,title:e.label,details:e.details}}}}),window.app.component("lnbits-admin-notifications",{props:["form-data"],template:"#lnbits-admin-notifications",data:()=>({nostrNotificationIdentifier:"",emailNotificationAddress:""}),methods:{sendTestEmail(){LNbits.api.request("GET","/admin/api/v1/testemail",this.g.user.wallets[0].adminkey).then(e=>{if("error"===e.data.status)throw new Error(e.data.message);this.$q.notify({message:"Test email sent!",color:"positive"})}).catch(e=>{this.$q.notify({message:e.message,color:"negative"})})},addNostrNotificationIdentifier(){const e=this.nostrNotificationIdentifier.trim(),t=this.formData.lnbits_nostr_notifications_identifiers;e&&e.length&&!t.includes(e)&&(this.formData.lnbits_nostr_notifications_identifiers=[...t,e],this.nostrNotificationIdentifier="")},removeNostrNotificationIdentifier(e){const t=this.formData.lnbits_nostr_notifications_identifiers;this.formData.lnbits_nostr_notifications_identifiers=t.filter(t=>t!==e)},addEmailNotificationAddress(){const e=this.emailNotificationAddress.trim(),t=this.formData.lnbits_email_notifications_to_emails;e&&e.length&&!t.includes(e)&&(this.formData.lnbits_email_notifications_to_emails=[...t,e],this.emailNotificationAddress="")},removeEmailNotificationAddress(e){const t=this.formData.lnbits_email_notifications_to_emails;this.formData.lnbits_email_notifications_to_emails=t.filter(t=>t!==e)}}}),window.app.component("lnbits-admin-site-customisation",{props:["form-data"],template:"#lnbits-admin-site-customisation",data:()=>({lnbits_theme_options:["classic","bitcoin","flamingo","cyber","freedom","mint","autumn","monochrome","salvador"],colors:["primary","secondary","accent","positive","negative","info","warning","red","yellow","orange"],reactionOptions:["none","confettiBothSides","confettiFireworks","confettiStars","confettiTop","lightningStrike"],globalBorderOptions:["retro-border","hard-border","neon-border","no-border"]}),methods:{onBackgroundImageInput(e){const t=e.target.files[0];t&&this.uploadBackgroundImage(t),e.target.value=null},async uploadBackgroundImage(e){const t=new FormData;t.append("file",e);try{const{data:e}=await LNbits.api.request("POST","/api/v1/assets?public_asset=true",null,t,{headers:{"Content-Type":"multipart/form-data"}}),s=`${window.location.origin}/api/v1/assets/${e.id}/thumbnail`;this.formData.lnbits_default_bgimage=s,Quasar.Notify.create({type:"positive",message:"Background image uploaded.",icon:null})}catch(e){LNbits.utils.notifyApiError(e)}}}}),window.app.component("lnbits-admin-assets-config",{props:["form-data"],template:"#lnbits-admin-assets-config",data:()=>({newAllowedAssetMimeType:"",newNoLimitUser:""}),async created(){},methods:{addAllowedAssetMimeType(){this.newAllowedAssetMimeType&&(this.removeAllowedAssetMimeType(this.newAllowedAssetMimeType),this.formData.lnbits_assets_allowed_mime_types.push(this.newAllowedAssetMimeType),this.newAllowedAssetMimeType="",this.formData.touch=null)},removeAllowedAssetMimeType(e){const t=this.formData.lnbits_assets_allowed_mime_types.indexOf(e);-1!==t&&this.formData.lnbits_assets_allowed_mime_types.splice(t,1),this.formData.touch=null},addNewNoLimitUser(){this.newNoLimitUser&&(this.removeNoLimitUser(this.newNoLimitUser),this.formData.lnbits_assets_no_limit_users.push(this.newNoLimitUser),this.newNoLimitUser="",this.formData.touch=null)},removeNoLimitUser(e){e&&(this.formData.lnbits_assets_no_limit_users=this.formData.lnbits_assets_no_limit_users.filter(t=>t!==e),this.formData.touch=null)}}}),window.app.component("lnbits-admin-audit",{props:["form-data"],template:"#lnbits-admin-audit",data:()=>({formAddIncludePath:"",formAddExcludePath:"",formAddIncludeResponseCode:""}),methods:{addIncludePath(){if(""===this.formAddIncludePath)return;const e=this.formData.lnbits_audit_include_paths;e.includes(this.formAddIncludePath)||(this.formData.lnbits_audit_include_paths=[...e,this.formAddIncludePath]),this.formAddIncludePath=""},removeIncludePath(e){this.formData.lnbits_audit_include_paths=this.formData.lnbits_audit_include_paths.filter(t=>t!==e)},addExcludePath(){if(""===this.formAddExcludePath)return;const e=this.formData.lnbits_audit_exclude_paths;e.includes(this.formAddExcludePath)||(this.formData.lnbits_audit_exclude_paths=[...e,this.formAddExcludePath]),this.formAddExcludePath=""},removeExcludePath(e){this.formData.lnbits_audit_exclude_paths=this.formData.lnbits_audit_exclude_paths.filter(t=>t!==e)},addIncludeResponseCode(){if(""===this.formAddIncludeResponseCode)return;const e=this.formData.lnbits_audit_http_response_codes;e.includes(this.formAddIncludeResponseCode)||(this.formData.lnbits_audit_http_response_codes=[...e,this.formAddIncludeResponseCode]),this.formAddIncludeResponseCode=""},removeIncludeResponseCode(e){this.formData.lnbits_audit_http_response_codes=this.formData.lnbits_audit_http_response_codes.filter(t=>t!==e)}}}),window.app.component("lnbits-admin-blockexplorer",{props:["form-data"],template:"#lnbits-admin-blockexplorer",data:()=>({electrumServers:["ssl://fulcrum.lnbits.com:50002","ssl://mainnet.nunchuk.io:52002","ssl://fulcrum.grey.pw:50002","ssl://electrum2.bluewallet.io:443","ssl://electrum.acinq.co:50002","ssl://electrum.blockstream.info:50002","ssl://bitcoin.mullvad.net:5010"]}),computed:{electrumServerOptions(){return[...this.electrumServers,"Custom"]},electrumServerPreset:{get(){return this.electrumServers.includes(this.formData.lnbits_blockexplorer_electrum_url)?this.formData.lnbits_blockexplorer_electrum_url:"Custom"},set(e){"Custom"!==e?this.formData.lnbits_blockexplorer_electrum_url=e:"Custom"!==this.electrumServerPreset&&(this.formData.lnbits_blockexplorer_electrum_url="")}}}}),window.PageBlockExplorer={template:"#page-blockexplorer",data:()=>({query:"",loading:!1,tip:null,fees:null,blocks:[],selectedBlock:null,blockTransactions:[],blockTransactionsLoading:!1,blockTransactionsError:"",blockTransactionsOffset:0,blockTransactionsHasMore:!1,blockTransactionPageSize:12,txResult:null,txStatus:null,addressResult:null,currentAddress:"",addressHistoryPage:1,addressHistoryPageSize:20}),computed:{explorerPath(){return this.g.isPublicPage?"/blockexplorer/public":"/blockexplorer"},feeList(){return this.fees&&this.fees.estimates?Object.entries(this.fees.estimates).map(([e,t])=>({label:this.$t("n_block_fee",{n:e}),rate:(1e5*t).toFixed(1)+" sat/vB"})):[]},recentBlocks(){return this.formattedBlocks.slice(0,10)},blockIntervals(){const e=[...this.blocks].sort((e,t)=>e.height-t.height);return e.slice(1).map((t,s)=>({height:t.height,minutes:Math.max(0,(t.timestamp-e[s].timestamp)/60)}))},averageBlockInterval(){if(!this.blockIntervals.length)return"—";const e=this.blockIntervals.reduce((e,t)=>e+t.minutes,0);return this.$t("minutes_short",{value:(e/this.blockIntervals.length).toFixed(1)})},feeHistogramEntries(){return this.fees&&Array.isArray(this.fees.histogram)?this.fees.histogram.map(e=>({feeRate:Number(e.fee_rate??e[0]),vsize:Number(e.vsize??e[1])})).filter(e=>Number.isFinite(e.feeRate)&&Number.isFinite(e.vsize)):[]},projectedBlocks(){const e=1e6,t=[];let s=null;const a=[...this.feeHistogramEntries].sort((e,t)=>t.feeRate-e.feeRate);for(const i of a){let a=i.vsize;for(;a>0;){if(!s||s.vsize>=e){if(t.length>=5)break;s={vsize:0,weightedFees:0},t.push(s)}const n=Math.min(e-s.vsize,a);s.vsize+=n,s.weightedFees+=n*i.feeRate,a-=n}if(t.length>=5&&s.vsize>=e)break}return t.map((t,s)=>({id:`projected-${s}-${Math.round(t.weightedFees/Math.max(t.vsize,1))}`,label:0===s?this.$t("next_block"):this.$t("projected_block",{number:s+1}),feeRate:t.weightedFees/Math.max(t.vsize,1),vsize:t.vsize/e,fill:Math.min(t.vsize/e,1)}))},projectedBlocksDisplay(){return[...this.projectedBlocks].reverse()},mempoolHistogram(){const e=this.feeHistogramEntries;if(!e.length)return[];const t=Math.max(1,Math.ceil(e.length/24)),s=[];for(let a=0;a<e.length;a+=t){const i=e.slice(a,a+t),n=i.reduce((e,t)=>e+t.vsize,0),o=i.reduce((e,t)=>e+t.feeRate*t.vsize,0);s.push({feeRate:n?o/n:i[0].feeRate,vsize:n})}return s.sort((e,t)=>e.feeRate-t.feeRate)},mempoolSize(){return`${(this.feeHistogramEntries.reduce((e,t)=>e+t.vsize,0)/1e6).toFixed(1)} MvB`},addressHistory(){return this.addressResult?.history||[]},addressHistoryPages(){return Math.ceil(this.addressHistory.length/this.addressHistoryPageSize)},paginatedAddressHistory(){const e=(this.addressHistoryPage-1)*this.addressHistoryPageSize;return this.addressHistory.slice(e,e+this.addressHistoryPageSize)},addressHistoryRange(){if(!this.addressHistory.length)return"";const e=(this.addressHistoryPage-1)*this.addressHistoryPageSize+1,t=Math.min(e+this.addressHistoryPageSize-1,this.addressHistory.length);return this.$t("pagination_range",{start:e,end:t,total:this.addressHistory.length})},formattedBlocks(){const e=Math.floor(Date.now()/1e3);return this.blocks.map((t,s)=>{const a=this.blocks[s+1],i=a?Math.max(0,(t.timestamp-a.timestamp)/60):null;return{...t,shortHash:t.hash.slice(0,8)+"..."+t.hash.slice(-4),timeAgo:this._timeAgo(e-t.timestamp),utcTime:new Date(1e3*t.timestamp).toUTCString(),difficulty:this._difficulty(t.bits),intervalMinutes:i,intervalRatio:null===i?0:Math.min(Math.max(i/20,.04),1)}})}},async created(){await Promise.all([this.loadTip(),this.loadFees(),this.loadBlocks()]),this._blockWsActive=!0,this._connectBlocksWs(),this._loadFromRoute()},beforeUnmount(){this._blockWsActive=!1,this._blockWs&&this._blockWs.close(),this._searchWs&&this._searchWs.close(),this._blockIntervalChart&&this._blockIntervalChart.destroy(),this._mempoolChart&&this._mempoolChart.destroy()},watch:{blocks(){this._scheduleChartRender()},fees(){this._scheduleChartRender()},"$q.dark.isActive"(){this._scheduleChartRender()},$route(e){this._loadFromRoute(e)}},methods:{_loadFromRoute(e){e=e||this.$route;const{type:t,id:s}=e.params;"tx"===t?(this._resetBlockResult(),this.query=s,this._fetchTx(s)):"address"===t?(this._resetBlockResult(),this.query=s,this._fetchAddress(s)):"block"===t?this._openBlockByHeight(s):(this._resetResults(),this._resetBlockResult())},_openBlockByHeight(e){const t=parseInt(e,10),s=this.formattedBlocks.find(e=>e.height===t)||this.blocks.find(e=>e.height===t);s?(this._resetResults(),this.selectedBlock=s,this.loadBlockTransactions(t,0)):this._resetBlockResult()},_resetBlockResult(){this.selectedBlock=null,this.blockTransactions=[],this.blockTransactionsError="",this.blockTransactionsOffset=0,this.blockTransactionsHasMore=!1},_resetResults(){this.txResult=null,this.txStatus=null,this.addressResult=null,this.addressHistoryPage=1,this._searchWs&&(this._searchWs.close(),this._searchWs=null)},_wsUrl:e=>`${"https:"===window.location.protocol?"wss:":"ws:"}//${window.location.host}/blockexplorer/api/v1${e}`,_connectBlocksWs(){const e=new WebSocket(this._wsUrl("/ws/blocks"));e.onmessage=e=>{const t=JSON.parse(e.data),s=this.blocks.filter(e=>e.height!==t.height);this.blocks=[t,...s].slice(0,10),this.loadFees()},e.onerror=()=>e.close(),e.onclose=()=>{this._blockWsActive&&setTimeout(()=>this._connectBlocksWs(),5e3)},this._blockWs=e},_connectSearchWs(e,t){this._searchWs&&(this._searchWs.close(),this._searchWs=null);const s=new WebSocket(this._wsUrl(e));s.onmessage=e=>{try{t(JSON.parse(e.data))}catch(e){}},s.onerror=()=>s.close(),this._searchWs=s},_timeAgo:e=>e<60?e+"s ago":e<3600?Math.floor(e/60)+"m ago":Math.floor(e/3600)+"h ago",_difficulty(e){const t=parseInt(e.slice(0,2),16),s=parseInt(e.slice(2),16),a=65535*Math.pow(2,208)/(s*Math.pow(2,8*(t-3)));return a>=1e12?(a/1e12).toFixed(2)+"T":a>=1e9?(a/1e9).toFixed(2)+"G":a>=1e6?(a/1e6).toFixed(2)+"M":a.toFixed(0)},_scheduleChartRender(){this._chartRenderPending||(this._chartRenderPending=!0,this.$nextTick(()=>{this._chartRenderPending=!1,this._renderCharts()}))},_themeColor:(e,t)=>window.getComputedStyle(document.documentElement).getPropertyValue(`--q-${e}`).trim()||t,_chartOptions(e,t=""){const s=this.$q.dark.isActive?"#eeeeee":"#424242",a=this.$q.dark.isActive?"rgba(255, 255, 255, 0.12)":"rgba(0, 0, 0, 0.12)";return{responsive:!0,maintainAspectRatio:!0,animation:!1,interaction:{intersect:!1,mode:"index"},plugins:{legend:{labels:{color:s}}},scales:{x:{title:{display:Boolean(t),text:t,color:s},ticks:{color:s,maxRotation:0},grid:{display:!1}},y:{beginAtZero:!0,title:{display:!0,text:e,color:s},ticks:{color:s},grid:{color:a}}}}},_renderCharts(){this._renderBlockIntervalChart(),this._renderMempoolChart()},_renderBlockIntervalChart(){const e=this.$refs.blockIntervalChart;if(!e||!this.blockIntervals.length||!window.Chart)return;this._blockIntervalChart&&this._blockIntervalChart.destroy();const t=this._themeColor("primary","#21ba45"),s=this._themeColor("secondary","#26a69a");this._blockIntervalChart=new Chart(e.getContext("2d"),{type:"line",data:{labels:this.blockIntervals.map(e=>e.height.toLocaleString()),datasets:[{label:this.$t("observed_block_time"),data:this.blockIntervals.map(e=>Number(e.minutes.toFixed(2))),borderColor:t,backgroundColor:t,pointRadius:3,tension:.3},{label:this.$t("target_block_time"),data:this.blockIntervals.map(()=>10),borderColor:s,backgroundColor:s,pointRadius:0,borderDash:[6,6]}]},options:this._chartOptions(this.$t("minutes"),this.$t("block_height"))})},_renderMempoolChart(){const e=this.$refs.mempoolChart;if(!e||!this.mempoolHistogram.length||!window.Chart)return;this._mempoolChart&&this._mempoolChart.destroy();const t=this._themeColor("secondary","#26a69a");this._mempoolChart=new Chart(e.getContext("2d"),{type:"bar",data:{labels:this.mempoolHistogram.map(e=>e.feeRate<10?e.feeRate.toFixed(1):e.feeRate.toFixed(0)),datasets:[{label:this.$t("mempool_virtual_size"),data:this.mempoolHistogram.map(e=>Number((e.vsize/1e6).toFixed(3))),backgroundColor:t,borderColor:t,borderWidth:1}]},options:this._chartOptions(this.$t("virtual_size_mb"),this.$t("fee_rate_axis"))})},openBlock(e){this.$router.push(`${this.explorerPath}/block/${e.height}`)},closeBlock(){this.$router.push(this.explorerPath)},async loadBlockTransactions(e,t){this.blockTransactionsLoading=!0,this.blockTransactionsError="";try{const s=await LNbits.api.request("GET",`/blockexplorer/api/v1/block/${e}/transactions?offset=${t}&limit=${this.blockTransactionPageSize}`);this.blockTransactions=s.data.transactions,this.blockTransactionsOffset=s.data.offset,this.blockTransactionsHasMore=s.data.has_more}catch(e){this.blockTransactions=[],this.blockTransactionsError=e.response?.data?.detail||this.$t("block_transactions_unavailable")}finally{this.blockTransactionsLoading=!1}},previousBlockTransactions(){this.loadBlockTransactions(this.selectedBlock.height,Math.max(0,this.blockTransactionsOffset-this.blockTransactionPageSize))},nextBlockTransactions(){this.loadBlockTransactions(this.selectedBlock.height,this.blockTransactionsOffset+this.blockTransactionPageSize)},async loadBlocks(){try{const e=await LNbits.api.request("GET","/blockexplorer/api/v1/blocks");this.blocks=e.data}catch(e){}},async loadTip(){try{const e=await LNbits.api.request("GET","/blockexplorer/api/v1/tip");this.tip=e.data}catch(e){LNbits.utils.notifyApiError(e)}},async loadFees(){try{const e=await LNbits.api.request("GET","/blockexplorer/api/v1/fees");this.fees=e.data}catch(e){}},clearResult(){this.query="",this.$route.path!==this.explorerPath?this.$router.push(this.explorerPath):this._resetResults()},search(){const e=this.query.trim();e&&(/^[0-9a-fA-F]{64}$/.test(e)?this.loadTx(e):this.loadAddress(e))},loadTx(e){this.$router.push(`${this.explorerPath}/tx/${e}`)},loadAddress(e){this.$router.push(`${this.explorerPath}/address/${e}`)},async _fetchTx(e){this.loading=!0;try{const t=await LNbits.api.request("GET","/blockexplorer/api/v1/tx/"+e);this.txResult=t.data,this.txStatus=null,this.addressResult=null,this._connectSearchWs(`/ws/tx/${e}`,e=>{e.error||(this.txStatus=e)})}catch(e){LNbits.utils.notifyApiError(e)}finally{this.loading=!1}},async _fetchAddress(e){this.loading=!0,this.addressHistoryPage=1;try{const t=await LNbits.api.request("GET","/blockexplorer/api/v1/address/"+e);this.addressResult=t.data,this.txResult=null,this.txStatus=null,this.currentAddress=e,this._connectSearchWs(`/ws/address/${e}`,e=>{e.error||(this.addressResult=e,this.addressHistoryPage=Math.min(this.addressHistoryPage,Math.max(1,this.addressHistoryPages)))})}catch(e){LNbits.utils.notifyApiError(e)}finally{this.loading=!1}}}},window.app.component("lnbits-wallet-charts",{template:"#lnbits-wallet-charts",props:["paymentFilter","chartConfig"],data:()=>({debounceTimeoutValue:1337,debounceTimeout:null,chartData:[],chartDataPointCount:0,walletBalanceChart:null,walletBalanceInOut:null,walletPaymentInOut:null,colorPrimary:Quasar.colors.changeAlpha(Quasar.colors.getPaletteColor("primary"),.3),colorSecondary:Quasar.colors.changeAlpha(Quasar.colors.getPaletteColor("secondary"),.3),barOptions:{responsive:!0,maintainAspectRatio:!1,scales:{x:{stacked:!0},y:{stacked:!0}}}}),watch:{paymentFilter:{deep:!0,handler(){this.changeCharts()}},chartConfig:{deep:!0,handler(e){this.$q.localStorage.setItem("lnbits.wallets.chartConfig",e),this.changeCharts()}}},methods:{changeCharts(){this.debounceTimeout&&clearTimeout(this.debounceTimeout),this.debounceTimeout=setTimeout(async()=>{await this.fetchChartData(),this.drawCharts()},this.debounceTimeoutValue)},filterChartData(){const e=this.paymentFilter["time[ge]"]+"T00:00:00",t=this.paymentFilter["time[le]"]+"T23:59:59";let s=0,a=this.chartData.map(e=>void 0!==this.paymentFilter["amount[ge]"]?(s+=e.balance_in,{...e,balance:s,balance_out:0,count_out:0}):void 0!==this.paymentFilter["amount[le]"]?(s-=e.balance_out,{...e,balance:s,balance_in:0,count_in:0}):{...e});a=a.filter(s=>this.paymentFilter["time[ge]"]&&this.paymentFilter["time[le]"]?s.date>=e&&s.date<=t:this.paymentFilter["time[ge]"]?s.date>=e:!this.paymentFilter["time[le]"]||s.date<=t);const i=a.map(e=>new Date(e.date).toLocaleString("default",{month:"short",day:"numeric"}));return this.chartDataPointCount=a.length,{data:a,labels:i}},drawBalanceInOutChart(e,t){this.walletBalanceInOut&&this.walletBalanceInOut.destroy();const s=this.$refs.walletBalanceInOut;s&&(this.walletBalanceInOut=new Chart(s.getContext("2d"),{type:"bar",options:this.barOptions,data:{labels:t,datasets:[{label:"Balance In",borderRadius:5,data:e.map(e=>e.balance_in),backgroundColor:this.colorPrimary},{label:"Balance Out",borderRadius:5,data:e.map(e=>e.balance_out),backgroundColor:this.colorSecondary}]}}))},drawPaymentInOut(e,t){this.walletPaymentInOut&&this.walletPaymentInOut.destroy();const s=this.$refs.walletPaymentInOut;s&&(this.walletPaymentInOut=new Chart(s.getContext("2d"),{type:"bar",options:this.barOptions,data:{labels:t,datasets:[{label:"Payments In",data:e.map(e=>e.count_in),backgroundColor:this.colorPrimary},{label:"Payments Out",data:e.map(e=>-e.count_out),backgroundColor:this.colorSecondary}]}}))},drawBalanceChart(e,t){this.walletBalanceChart&&this.walletBalanceChart.destroy();const s=this.$refs.walletBalanceChart;s&&(this.walletBalanceChart=new Chart(s.getContext("2d"),{type:"line",options:{responsive:!0,maintainAspectRatio:!1},data:{labels:t,datasets:[{label:"Balance",data:e.map(e=>e.balance),pointStyle:!1,backgroundColor:this.colorPrimary,borderColor:this.colorPrimary,borderWidth:2,fill:!0,tension:.7,fill:1},{label:"Fees",data:e.map(e=>e.fee),pointStyle:!1,backgroundColor:this.colorSecondary,borderColor:this.colorSecondary,borderWidth:1,fill:!0,tension:.7,fill:1}]}}))},drawCharts(){const{data:e,labels:t}=this.filterChartData();this.chartConfig.showBalanceChart&&this.drawBalanceChart(e,t),this.chartConfig.showBalanceInOutChart&&this.drawBalanceInOutChart(e,t),this.chartConfig.showPaymentInOutChart&&this.drawPaymentInOut(e,t)},async fetchChartData(){try{const{data:e}=await LNbits.api.request("GET",`/api/v1/payments/stats/daily?wallet_id=${this.g.wallet.id}`);this.chartData=e}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}}},async created(){await this.fetchChartData(),this.drawCharts()}}),window.app.component("lnbits-wallet-api-docs",{template:"#lnbits-wallet-api-docs",methods:{copyAdminKey(){LNbits.utils.confirmDialog(this.$t("admin_key_warning")).onOk(()=>LNbits.utils.copyText(this.g.wallet.adminkey))},resetKeys(){LNbits.utils.confirmDialog("Are you sure you want to reset your API keys?").onOk(()=>{LNbits.api.resetWalletKeys(this.g.wallet).then(e=>{const{id:t,adminkey:s,inkey:a}=e;this.g.wallet={...this.g.wallet,inkey:a,adminkey:s};const i=this.g.user.wallets.findIndex(e=>e.id===t);-1!==i&&(this.g.user.wallets[i]={...this.g.user.wallets[i],inkey:a,adminkey:s}),Quasar.Notify.create({timeout:3500,type:"positive",message:"API keys reset!"})}).catch(e=>{LNbits.utils.notifyApiError(e)})})}},data:()=>({origin:window.location.origin,inkeyHidden:!0,adminkeyHidden:!0,walletIdHidden:!0})}),window.app.component("lnbits-wallet-icon",{template:"#lnbits-wallet-icon",data:()=>({icon:{show:!1,data:{},colorOptions:["primary","purple","orange","green","brown","blue","red","pink"],options:["home","star","bolt","paid","savings","store","videocam","music_note","flight","train","directions_car","school","construction","science","sports_esports","sports_tennis","theaters","water","headset_mic","videogame_asset","person","group","pets","sunny","elderly","verified","snooze","mail","forum","shopping_cart","shopping_bag","attach_money","print_connect","dark_mode","light_mode","android","network_wifi","shield","fitness_center","lunch_dining"]}}),methods:{setSelectedIcon(e){this.icon.data.icon=e},setSelectedColor(e){this.icon.data.color=e},setIcon(){this.$emit("update-wallet",this.icon.data),this.icon.show=!1}}}),window.app.component("lnbits-wallet-new",{template:"#lnbits-wallet-new",data:()=>({wallet:{name:"",sharedWalletId:""},showNewWalletDialog:!1}),watch:{"g.newWalletType"(e){null!==e&&(this.showNewWalletDialog=!0)},showNewWalletDialog(e){!0!==e&&this.reset()}},computed:{walletTypes(){const e=[{label:"Lightning",value:"lightning",description:"Send and receive Lightning payments"}];this.g.user?.canCreateFiatWallet&&e.push({label:"Fiat",value:"fiat",description:"Receive only (for use with fiat)"});const t=this.g.user?.extra?.wallet_invite_requests?.length;return t&&e.push({label:`Lightning Wallet (Share Invite: ${t})`,value:"lightning-shared"}),e},isLightningShared(){return"lightning-shared"===this.g.newWalletType},inviteWalletOptions(){return(this.g.user?.extra?.wallet_invite_requests||[]).map(e=>({label:`${e.to_wallet_name} (from ${e.from_user_name})`,value:e.to_wallet_id}))}},methods:{reset(){this.showNewWalletDialog=!1,this.g.newWalletType=null,this.wallet={name:"",sharedWalletId:""}},async submitRejectWalletInvitation(){try{const e=this.g.user.extra.wallet_invite_requests||[],t=e.find(e=>e.to_wallet_id===this.wallet.sharedWalletId);if(!t)return void Quasar.Notify.create({message:"Cannot find invitation for the selected wallet.",type:"warning"});await LNbits.api.request("DELETE",`/api/v1/wallet/share/invite/${t.request_id}`,this.g.wallet.adminkey),Quasar.Notify.create({message:"Invitation rejected.",type:"positive"}),this.g.user.extra.wallet_invite_requests=e.filter(e=>e.request_id!==t.request_id)}catch(e){LNbits.utils.notifyApiError(e)}},submitAddWallet(){const e=this.wallet;this.isLightningShared||e.name?"lightning-shared"!==this.g.newWalletType||e.sharedWalletId?LNbits.api.createWallet(e.name,this.g.newWalletType,{shared_wallet_id:e.sharedWalletId}).then(e=>{this.$q.notify({message:"Wallet created successfully",color:"positive"}),this.reset(),this.g.user.wallets.push(LNbits.map.wallet(e.data)),this.g.lastWalletId=e.data.id,this.$router.push(`/wallet/${e.data.id}`)}).catch(LNbits.utils.notifyApiError):this.$q.notify({message:"Missing a shared wallet ID",color:"warning"}):this.$q.notify({message:"Please enter a name for the wallet",color:"warning"})}}}),window.app.component("lnbits-wallet-share",{template:"#lnbits-wallet-share",computed:{walletApprovedShares(){return this.g.wallet.extra.shared_with.filter(e=>"approved"===e.status)},walletPendingRequests(){return this.g.wallet.extra.shared_with.filter(e=>"request_access"===e.status)},walletPendingInvites(){return this.g.wallet.extra.shared_with.filter(e=>"invite_sent"===e.status)}},data:()=>({permissionOptions:[{label:"View",value:"view-payments"},{label:"Receive",value:"receive-payments"},{label:"Send",value:"send-payments"}],walletShareInvite:{username:"",permissions:[]}}),methods:{async updateSharePermissions(e){try{const{data:t}=await LNbits.api.request("PUT","/api/v1/wallet/share",this.g.wallet.adminkey,e);Object.assign(e,t),Quasar.Notify.create({message:"Wallet permission updated.",type:"positive"})}catch(e){LNbits.utils.notifyApiError(e)}},async inviteUserToWallet(){try{const{data:e}=await LNbits.api.request("PUT","/api/v1/wallet/share/invite",this.g.wallet.adminkey,{...this.walletShareInvite,status:"invite_sent",wallet_id:this.g.wallet.id});this.g.wallet.extra.shared_with.push(e),this.walletShareInvite={username:"",permissions:[]},Quasar.Notify.create({message:"User invited to wallet.",type:"positive"})}catch(e){LNbits.utils.notifyApiError(e)}},deleteSharePermission(e){LNbits.utils.confirmDialog("Are you sure you want to remove this share permission?").onOk(async()=>{try{await LNbits.api.request("DELETE",`/api/v1/wallet/share/${e.request_id}`,this.g.wallet.adminkey),this.g.wallet.extra.shared_with=this.g.wallet.extra.shared_with.filter(t=>t.wallet_id!==e.wallet_id),Quasar.Notify.create({message:"Wallet permission deleted.",type:"positive"})}catch(e){LNbits.utils.notifyApiError(e)}})}}}),window.app.component("lnbits-wallet-paylinks",{template:"#lnbits-wallet-paylinks",data:()=>({storedPaylinks:[]}),watch:{"g.wallet"(e){this.storedPaylinks=e.storedPaylinks??[]}},created(){this.storedPaylinks=this.g.wallet.storedPaylinks},methods:{updatePaylinks(){LNbits.api.request("PUT",`/api/v1/wallet/stored_paylinks/${this.g.wallet.id}`,this.g.wallet.adminkey,{links:this.storedPaylinks}).then(()=>{this.$q.notify({message:"Paylinks updated.",type:"positive",timeout:3500})}).catch(e=>{LNbits.utils.notifyApiError(e)})},sendToPaylink(e){this.$emit("send-lnurl",e)},editPaylink(){this.$nextTick(()=>{this.updatePaylinks()})},deletePaylink(e){const t=[];this.storedPaylinks.forEach(s=>{s.lnurl!==e&&t.push(s)}),this.storedPaylinks=t,this.updatePaylinks()}}}),window.app.component("lnbits-wallet-extra",{template:"#lnbits-wallet-extra",props:["chartConfig"],data:()=>({lightningAddressInput:""}),computed:{exportUrl(){return`${window.location.origin}/wallet?usr=${this.g.user.id}&wal=${this.g.wallet.id}`},canEditLightningAddress(){return this.g.settings.enableWalletLightningAddresses&&this.g.settings.allowCustomWalletLightningAddresses&&"lightning"===this.g.wallet.walletType},lightningAddressSuffix:()=>`@${window.location.host}`,lightningAddressChanged(){return this.lightningAddressInput!==(this.g.wallet.lightningAddress||"")},lightningAddressFeeHint(){return this.g.settings.chargeWalletLightningAddresses?`Fee: ${this.g.settings.walletLightningAddressPriceSats} sats`:""}},watch:{"g.wallet.id":"resetLightningAddressInput","g.wallet.lightningAddress":"resetLightningAddressInput"},methods:{resetLightningAddressInput(){this.lightningAddressInput=this.g.wallet.lightningAddress||""},saveLightningAddress(){this.updateWallet({lightning_address:this.lightningAddressInput})},handleSendLnurl(e){this.$emit("send-lnurl",e)},updateWallet(e){this.$emit("update-wallet",e)},handleFiatTracking(){this.g.fiatTracking=!this.g.fiatTracking,this.g.fiatTracking?(this.updateWallet({currency:this.g.wallet.currency}),this.updateFiatBalance()):(this.g.isFiatPriority=!1,this.g.wallet.currency="",this.updateWallet({currency:""}))},deleteWallet(){LNbits.utils.confirmDialog("Are you sure you want to delete this wallet?").onOk(()=>{LNbits.api.deleteWallet(this.g.wallet).then(()=>{this.g.user.wallets=this.g.user.wallets.filter(e=>e.id!==this.g.wallet.id),this.g.lastActiveWallet=this.g.user.wallets[0].id,this.$router.push(`/wallet/${this.g.lastActiveWallet}`),Quasar.Notify.create({timeout:3e3,message:"Wallet deleted!",spinner:!0})}).catch(e=>{LNbits.utils.notifyApiError(e)})})},updateFiatBalance(){this.$q.localStorage.getItem("lnbits.exchangeRate."+this.g.wallet.currency)&&(this.g.exchangeRate=this.$q.localStorage.getItem("lnbits.exchangeRate."+this.g.wallet.currency),this.g.fiatBalance=this.g.exchangeRate/1e8*this.g.wallet.sat),LNbits.api.request("GET","/api/v1/rate/"+this.g.wallet.currency,null).then(e=>{this.g.fiatBalance=e.data.price/1e8*this.g.wallet.sat,this.g.exchangeRate=e.data.price.toFixed(2),this.g.fiatTracking=!0,this.$q.localStorage.set("lnbits.exchangeRate."+this.g.wallet.currency,this.g.exchangeRate),this.g.exchangeRate<=0&&(this.g.fiatTracking=!1,this.g.isFiatPriority=!1)}).catch(e=>console.error(e))}},created(){this.resetLightningAddressInput(),""!==this.g.wallet.currency&&this.g.isSatsDenomination?(this.g.fiatTracking=!0,this.updateFiatBalance()):this.g.fiatTracking=!1}}),window.app.component("lnbits-home-logos",{template:"#lnbits-home-logos",data:()=>({logos:[{href:"https://github.com/ElementsProject/lightning",lightSrc:"/static/images/clnl.png",darkSrc:"/static/images/cln.png"},{href:"https://github.com/lightningnetwork/lnd",lightSrc:"/static/images/lnd.png",darkSrc:"/static/images/lnd.png"},{href:"https://opennode.com",lightSrc:"/static/images/opennodel.png",darkSrc:"/static/images/opennode.png"},{href:"https://lnpay.co/",lightSrc:"/static/images/lnpayl.png",darkSrc:"/static/images/lnpay.png"},{href:"https://github.com/rootzoll/raspiblitz",lightSrc:"/static/images/blitzl.png",darkSrc:"/static/images/blitz.png"},{href:"https://start9.com/",lightSrc:"/static/images/start9l.png",darkSrc:"/static/images/start9.png"},{href:"https://getumbrel.com/",lightSrc:"/static/images/umbrell.png",darkSrc:"/static/images/umbrel.png"},{href:"https://mynodebtc.com",lightSrc:"/static/images/mynodel.png",darkSrc:"/static/images/mynode.png"},{href:"https://github.com/shesek/spark-wallet",lightSrc:"/static/images/sparkl.png",darkSrc:"/static/images/spark.png"},{href:"https://voltage.cloud",lightSrc:"/static/images/voltagel.png",darkSrc:"/static/images/voltage.png"},{href:"https://breez.technology/sdk/",lightSrc:"/static/images/breezl.png",darkSrc:"/static/images/breez.png"},{href:"https://blockstream.com/lightning/greenlight/",lightSrc:"/static/images/greenlightl.png",darkSrc:"/static/images/greenlight.png"},{href:"https://getalby.com",lightSrc:"/static/images/albyl.png",darkSrc:"/static/images/alby.png"},{href:"https://zbd.gg",lightSrc:"/static/images/zbdl.png",darkSrc:"/static/images/zbd.png"},{href:"https://phoenix.acinq.co/server",lightSrc:"/static/images/phoenixdl.png",darkSrc:"/static/images/phoenixd.png"},{href:"https://boltz.exchange/",lightSrc:"/static/images/boltzl.svg",darkSrc:"/static/images/boltz.svg"},{href:"https://www.blink.sv/",lightSrc:"/static/images/blink_logol.png",darkSrc:"/static/images/blink_logo.png"}]}),computed:{showLogos(){return this.g.isSatsDenomination&&"LNbits"==this.g.settings.siteTitle&&1==this.g.settings.showHomePageElements}}}),window.app.component("lnbits-error",{template:"#lnbits-error",props:["dynamic","code","message"],computed:{isExtension(){return 403==this.code&&(!!this.message.startsWith("Extension ")||void 0)}},methods:{goBack(){window.history.back()},goHome(){window.location="/"},goToWallet(){this.dynamic?this.$router.push("/wallet"):window.location="/wallet"},goToExtension(){const e=`/extensions#${this.message.match(/'([^']+)'/)[1]}`;this.dynamic?this.$router.push(e):window.location=e},async logOut(){try{await LNbits.api.logout(),window.location="/"}catch(e){LNbits.utils.notifyApiError(e)}}},async created(){if(!this.dynamic&&401==this.code)return console.warn(`Unauthorized: ${this.errorMessage}`),void this.logOut()}}),window.app.component("lnbits-qrcode",{template:"#lnbits-qrcode",components:{QrcodeVue:QrcodeVue.default},props:{value:{type:String,required:!0},nfc:{type:Boolean,default:!1},print:{type:Boolean,default:!1},showButtons:{type:Boolean,default:!0},href:{type:String,default:""},margin:{type:Number,default:3},maxWidth:{type:Number,default:450},logo:{type:String,default:window.g.settings.qrLogo||null}},data:()=>({nfcTagWriting:!1,nfcSupported:"undefined"!=typeof NDEFReader}),methods:{printQrCode(){const e=this.$refs.qrCode.$el.outerHTML,t=window.open("","_blank");t.document.write(`\n <html>\n <head>\n <title>Print QR Code</title>\n <style>\n body {\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100vh;\n margin: 0;\n }\n img {\n position: absolute;\n max-width: 51px;\n width: 14%;\n overflow: hidden;\n background: #fff;\n overflow: hidden;\n padding: -1.2rem;\n border-radius: -1.2rem;\n }\n </style>\n </head>\n <body>${e}<img src="${this.logo}"></body>\n </html>\n `),t.document.close(),t.focus(),t.print(),t.close()},clickQrCode(e){if(""===this.href)return this.utils.copyText(this.value),e.preventDefault(),e.stopPropagation(),!1;this.href&&this.href.startsWith("http")&&(window.open(this.href,"_blank"),e.preventDefault())},async writeNfcTag(){try{if(!this.nfcSupported)throw{toString:function(){return"NFC not supported on this device or browser."}};const e=new NDEFReader;this.nfcTagWriting=!0,this.$q.notify({message:"Tap your NFC tag to write the LNURL-withdraw link to it."}),await e.write({records:[{recordType:"url",data:this.value,lang:"en"}]}),this.nfcTagWriting=!1,this.$q.notify({type:"positive",message:"NFC tag written successfully."})}catch(e){this.nfcTagWriting=!1,this.$q.notify({type:"negative",message:e?e.toString():"An unexpected error has occurred."})}},downloadSVG(){const e=this.$refs.qrCode.$el;if(!e)return void console.error("SVG element not found");let t=(new XMLSerializer).serializeToString(e);t.match(/^<svg[^>]+xmlns="http:\/\/www\.w3\.org\/2000\/svg"/)||(t=t.replace(/^<svg/,'<svg xmlns="http://www.w3.org/2000/svg"')),t='<?xml version="1.0" standalone="no"?>\n'+t;const s=new Blob([t],{type:"image/svg+xml;charset=utf-8"}),a=URL.createObjectURL(s),i=document.createElement("a");i.href=a,i.download="qrcode.svg",document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(a)}},mounted(){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 e=this.value.indexOf(":"),t=-1===e?"":this.value.substring(0,e),s=-1===e?this.value:this.value.substring(e+1);if(this.utils.isValidBech32(s)){const e=s.toUpperCase();return t?`${t.toUpperCase()}:${e}`:e}return this.value}}}),window.app.component("lnbits-qrcode-lnurl",{template:"#lnbits-qrcode-lnurl",props:{url:{required:!0,type:String},prefix:{type:String,default:"lnurlp"},href:{type:String,default:""}},data:()=>({tab:"bech32",lnurl:""}),methods:{setLnurl(){if("bech32"==this.tab){const e=(new TextEncoder).encode(this.url),t=NostrTools.nip19.encodeBytes("lnurl",e);this.lnurl=this.href&&""!==this.href.trim()?`${this.href}?lightning=${t.toUpperCase()}`:`lightning:${t.toUpperCase()}`}else"lud17"==this.tab&&(this.url.startsWith("http://")?this.lnurl=this.url.replace("http://",this.prefix+"://"):this.lnurl=this.url.replace("https://",this.prefix+"://"));this.$emit("update:lnurl",this.lnurl)}},watch:{url(){this.setLnurl()},tab(){this.setLnurl()}},created(){this.setLnurl()}}),window.app.component("lnbits-disclaimer",{template:"#lnbits-disclaimer",computed:{showDisclaimer:()=>!g.disclaimerShown&&g.isUserAuthorized}}),window.app.component("lnbits-footer",{template:"#lnbits-footer",computed:{title(){return`${this.g.settings.siteTitle}, ${this.g.settings.siteTagline}`},version(){return this.$t("lnbits_version")+": "+this.g.settings.version}}}),window.app.component("lnbits-header",{template:"#lnbits-header",computed:{showAdmin(){return this.g.user&&(this.g.user.super_user||this.g.user.admin)},displayName(){return this.g.user?.extra?.display_name||this.g.user.username||this.g.user?.extra?.first_name||"Anon"},displayRole(){return this.g.user?.super_user?"Super User":this.g.user?.admin?"Admin":"User"}},methods:{async stopImpersonation(){try{await LNbits.api.stopImpersonation(),LNbits.utils.restoreLocalStorage("impersonation"),window.location="/users"}catch(e){console.warn(e)}},async handleLanguageChanged(e){try{await LNbits.api.updateUiCustomization({locale:e.locale}),this.$q.notify({type:"positive",message:"Language Updated",caption:e.locale})}catch(e){LNbits.utils.notifyApiError(e)}}}}),window.app.component("lnbits-header-wallets",{template:"#lnbits-header-wallets"}),window.app.component("lnbits-drawer",{template:"#lnbits-drawer"}),window.app.component("lnbits-theme",{watch:{"g.walletFlip"(e){this.$q.localStorage.setItem("lnbits.walletFlip",e),!0===e&&this.$q.screen.lt.md&&(this.g.visibleDrawer=!1)},"g.disclaimerShown"(e){this.$q.localStorage.setItem("lnbits.disclaimerShown",e)},"g.locale"(e){this.$q.localStorage.setItem("lnbits.lang",e),window.i18n.global.locale=e},"g.isFiatPriority"(e){this.$q.localStorage.setItem("lnbits.isFiatPriority",e)},"g.reactionChoice"(e){this.$q.localStorage.set("lnbits.reactions",e)},"g.themeChoice"(e){document.body.setAttribute("data-theme",e),this.$q.localStorage.set("lnbits.theme",e)},"g.darkChoice"(e){this.$q.dark.set(e),this.$q.localStorage.set("lnbits.darkMode",e),Chart.defaults.color=this.$q.dark.isActive?"#fff":"#000"},"g.borderChoice"(e){document.body.classList.forEach(e=>{e.endsWith("-border")&&document.body.classList.remove(e)}),this.$q.localStorage.setItem("lnbits.border",e),document.body.classList.add(e)},"g.gradientChoice"(e){this.$q.localStorage.set("lnbits.gradientBg",e),!0===e?document.body.classList.add("gradient-bg"):document.body.classList.remove("gradient-bg")},"g.cardRoundedChoice"(e){this.$q.localStorage.set("lnbits.cardRounded",e),!0===e?document.body.classList.add("rounded-ui"):document.body.classList.remove("rounded-ui")},"g.cardGradientChoice"(e){this.$q.localStorage.set("lnbits.cardGradient",e),!0===e?document.body.classList.add("card-gradient"):document.body.classList.remove("card-gradient")},"g.cardShadowChoice"(e){this.$q.localStorage.set("lnbits.cardShadow",e),!0===e?document.body.classList.add("card-shadow"):document.body.classList.remove("card-shadow")},"g.burgerMenuChoice"(e){this.$q.localStorage.set("lnbits.burgerMenu",e),!0===e?document.body.classList.remove("no-burger-background"):document.body.classList.add("no-burger-background")},"g.mobileSimple"(e){this.$q.localStorage.set("lnbits.mobileSimple",e),!0===e?document.body.classList.add("mobile-simple"):document.body.classList.remove("mobile-simple")},"g.bgimageChoice"(e){this.$q.localStorage.set("lnbits.backgroundImage",e),""===e?document.body.classList.remove("bg-image"):(document.body.classList.add("bg-image"),document.body.style.setProperty("--background",`url(${e})`))}},methods:{async checkUrlParams(){const e=new URLSearchParams(window.location.search);if(0===e.length)return;if(e.has("theme")){const t=e.get("theme").trim().toLowerCase();this.g.themeChoice=t,e.delete("theme")}if(e.has("border")){const t=e.get("border").trim().toLowerCase();this.g.borderChoice=t,e.delete("border")}if(e.has("gradient")){const t=e.get("gradient").toLowerCase();this.g.gradientChoice="1"===t||"true"===t,e.delete("gradient")}if(e.has("dark")){const t=e.get("dark").trim().toLowerCase();this.g.darkChoice="1"===t||"true"===t,e.delete("dark")}if(e.has("usr")){try{await LNbits.api.loginUsr(e.get("usr")),window.location.href="/wallet"}catch(e){LNbits.utils.notifyApiError(e)}e.delete("usr")}const t=e.size?`?${e.toString()}`:"",s=window.location.pathname+t;window.history.replaceState(null,null,s)}},created(){this.$q.dark.set(this.g.darkChoice),document.body.setAttribute("data-theme",this.g.themeChoice),Chart.defaults.color=this.$q.dark.isActive?"#fff":"#000",document.body.classList.add(this.g.borderChoice),!0===this.g.gradientChoice&&document.body.classList.add("gradient-bg"),!0===this.g.cardRoundedChoice&&document.body.classList.add("rounded-ui"),!0===this.g.cardGradientChoice&&document.body.classList.add("card-gradient"),!0===this.g.cardShadowChoice&&document.body.classList.add("card-shadow"),!0!==this.g.burgerMenuChoice&&document.body.classList.add("no-burger-background"),""!==this.g.bgimageChoice&&(document.body.classList.add("bg-image"),document.body.style.setProperty("--background",`url(${this.g.bgimageChoice})`)),!0===this.g.mobileSimple&&document.body.classList.add("mobile-simple"),Object.entries(this.g.user?.uiWhy this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.